forked from jetstack/tarmak
/
tunnel.go
269 lines (215 loc) · 4.76 KB
/
tunnel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// Copyright Jetstack Ltd. See LICENSE for details.
package ssh
import (
"bufio"
"fmt"
"io"
"net"
"os"
"os/exec"
"sync"
"syscall"
"time"
"github.com/kardianos/osext"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"github.com/jetstack/tarmak/pkg/tarmak/interfaces"
)
const (
timeout = time.Minute * 10
)
type Tunnel struct {
ssh *SSH
log *logrus.Entry
dest string
destPort string
localPort string
daemonize bool
bastionConn *ssh.Client
listener net.Listener
daemon *os.Process
// have both a stopCh and doneCh so we have a chance to clean up connections
// properly before we exit the program during daemon mode
stopCh chan struct{}
doneCh chan struct{}
openConns []<-chan struct{}
connsLock sync.Mutex // prevent closing the same connection multiple times at once
remoteConns []net.Conn
}
var _ interfaces.Tunnel = &Tunnel{}
// This opens a local tunnel through a SSH connection
func (s *SSH) Tunnel(dest, destPort, localPort string, daemonize bool) interfaces.Tunnel {
tunnel := &Tunnel{
log: s.log.WithField("destination", dest),
ssh: s,
dest: dest,
destPort: destPort,
daemonize: daemonize,
localPort: localPort,
doneCh: make(chan struct{}),
}
s.tunnels = append(s.tunnels, tunnel)
return tunnel
}
// Start tunnel and wait till a tcp socket is reachable
func (t *Tunnel) Start() error {
t.stopCh = make(chan struct{})
t.doneCh = make(chan struct{})
// ensure there is connectivity to the bastion
bastionClient, err := t.ssh.bastionClient()
if err != nil {
return err
}
t.bastionConn = bastionClient
if t.daemonize {
err := t.startDaemon()
if err != nil {
return err
}
// allow for some warm up time
time.Sleep(time.Second * 3)
return nil
}
listener, err := net.Listen("tcp", net.JoinHostPort(t.BindAddress(), t.Port()))
if err != nil {
return err
}
t.listener = listener
go t.handle()
return nil
}
func (t *Tunnel) handle() {
go t.handleTimeout()
var errCount int
for {
remoteConn, err := t.bastionConn.Dial("tcp",
net.JoinHostPort(t.dest, t.destPort))
if err != nil {
select {
case <-t.stopCh:
return
default:
}
errCount++
if errCount == 10 {
return
}
time.Sleep(time.Second * 3)
continue
}
t.remoteConns = append(t.remoteConns, remoteConn)
conn, err := t.listener.Accept()
if err != nil {
select {
case <-t.stopCh:
return
default:
}
t.log.Warnf("error accepting ssh tunnel connection: %s", err)
continue
}
t.remoteConns = append(t.remoteConns, conn)
t.connsLock.Lock()
ch := make(chan struct{})
t.openConns = append(t.openConns, ch)
t.connsLock.Unlock()
go func() {
io.Copy(remoteConn, conn)
conn.Close()
// reset timer to another 10 mins since this connection is now closed
time.Sleep(timeout)
close(ch)
}()
go func() {
io.Copy(conn, remoteConn)
remoteConn.Close()
}()
}
}
// prevent tarmak clean up from killing used daemons
func (t *Tunnel) Stop() {
t.cleanup()
if t.daemon != nil {
t.daemon.Kill()
}
}
func (t *Tunnel) cleanup() {
// prevent closing the same connection multiple times at once as well as
// accepting any new ones
t.connsLock.Lock()
defer t.connsLock.Unlock()
select {
case <-t.stopCh:
default:
close(t.stopCh)
}
for _, conn := range t.remoteConns {
if conn != nil {
conn.Close()
}
}
if t.listener != nil {
t.listener.Close()
}
}
func (t *Tunnel) Port() string {
return t.localPort
}
func (t *Tunnel) BindAddress() string {
return "127.0.0.1"
}
func (t *Tunnel) handleTimeout() {
// initial timeout whilst waiting for first connection
time.Sleep(timeout)
// need to use C style for-loop so we catch new openConns channels in the
// slice to wait on
t.connsLock.Lock()
for i := 0; i < len(t.openConns); i++ {
t.connsLock.Unlock()
<-t.openConns[i]
t.connsLock.Lock()
}
t.connsLock.Unlock()
t.cleanup()
select {
case <-t.doneCh:
default:
close(t.doneCh)
}
}
func (t *Tunnel) Done() <-chan struct{} {
return t.doneCh
}
func (t *Tunnel) startDaemon() error {
binaryPath, err := osext.Executable()
if err != nil {
return fmt.Errorf("error finding tarmak executable: %s", err)
}
cmd := exec.Command(binaryPath, "tunnel", t.dest, t.destPort, t.localPort)
outR, outW := io.Pipe()
errR, errW := io.Pipe()
outS := bufio.NewScanner(outR)
errS := bufio.NewScanner(errR)
cmd.Stdin = nil
cmd.Stdout = outW
cmd.Stderr = errW
go func() {
for outS.Scan() {
t.log.WithField("tunnel", t.dest).Debug(outS.Text())
}
}()
go func() {
for errS.Scan() {
t.log.WithField("tunnel", t.dest).Debug(errS.Text())
}
}()
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Foreground: false,
}
if err := cmd.Start(); err != nil {
return err
}
t.daemon = cmd.Process
return nil
}