-
Notifications
You must be signed in to change notification settings - Fork 12
/
tunnel.go
222 lines (197 loc) · 5.02 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
// Copyright 2017, The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE.md file.
package main
import (
"context"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"golang.org/x/crypto/ssh"
)
type logger interface {
Printf(string, ...interface{})
}
type tunnel struct {
auth []ssh.AuthMethod
hostKeys ssh.HostKeyCallback
mode byte // '>' for forward, '<' for reverse
user string
hostAddr string
bindAddr string
dialAddr string
retryInterval time.Duration
keepAlive KeepAliveConfig
log logger
}
func (t tunnel) String() string {
var left, right string
mode := "<?>"
switch t.mode {
case '>':
left, mode, right = t.bindAddr, "->", t.dialAddr
case '<':
left, mode, right = t.dialAddr, "<-", t.bindAddr
}
return fmt.Sprintf("%s@%s | %s %s %s", t.user, t.hostAddr, left, mode, right)
}
func (t tunnel) bindTunnel(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
for {
var once sync.Once // Only print errors once per session
func() {
// Connect to the server host via SSH.
cl, err := ssh.Dial("tcp", t.hostAddr, &ssh.ClientConfig{
User: t.user,
Auth: t.auth,
HostKeyCallback: t.hostKeys,
Timeout: 5 * time.Second,
})
if err != nil {
once.Do(func() { t.log.Printf("(%v) SSH dial error: %v", t, err) })
return
}
wg.Add(1)
go t.keepAliveMonitor(&once, wg, cl)
defer cl.Close()
// Attempt to bind to the inbound socket.
var ln net.Listener
switch t.mode {
case '>':
ln, err = net.Listen("tcp", t.bindAddr)
case '<':
ln, err = cl.Listen("tcp", t.bindAddr)
}
if err != nil {
once.Do(func() { t.log.Printf("(%v) bind error: %v", t, err) })
return
}
// The socket is binded. Make sure we close it eventually.
bindCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
cl.Wait()
cancel()
}()
go func() {
<-bindCtx.Done()
once.Do(func() {}) // Suppress future errors
ln.Close()
}()
t.log.Printf("(%v) binded tunnel", t)
defer t.log.Printf("(%v) collapsed tunnel", t)
// Accept all incoming connections.
for {
cn1, err := ln.Accept()
if err != nil {
once.Do(func() { t.log.Printf("(%v) accept error: %v", t, err) })
return
}
wg.Add(1)
go t.dialTunnel(bindCtx, wg, cl, cn1)
}
}()
select {
case <-ctx.Done():
return
case <-time.After(t.retryInterval):
t.log.Printf("(%v) retrying...", t)
}
}
}
func (t tunnel) dialTunnel(ctx context.Context, wg *sync.WaitGroup, client *ssh.Client, cn1 net.Conn) {
defer wg.Done()
// The inbound connection is established. Make sure we close it eventually.
connCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
<-connCtx.Done()
cn1.Close()
}()
// Establish the outbound connection.
var cn2 net.Conn
var err error
switch t.mode {
case '>':
cn2, err = client.Dial("tcp", t.dialAddr)
case '<':
cn2, err = net.Dial("tcp", t.dialAddr)
}
if err != nil {
t.log.Printf("(%v) dial error: %v", t, err)
return
}
go func() {
<-connCtx.Done()
cn2.Close()
}()
t.log.Printf("(%v) connection established", t)
defer t.log.Printf("(%v) connection closed", t)
// Copy bytes from one connection to the other until one side closes.
var once sync.Once
var wg2 sync.WaitGroup
wg2.Add(2)
go func() {
defer wg2.Done()
defer cancel()
if _, err := io.Copy(cn1, cn2); err != nil {
once.Do(func() { t.log.Printf("(%v) connection error: %v", t, err) })
}
once.Do(func() {}) // Suppress future errors
}()
go func() {
defer wg2.Done()
defer cancel()
if _, err := io.Copy(cn2, cn1); err != nil {
once.Do(func() { t.log.Printf("(%v) connection error: %v", t, err) })
}
once.Do(func() {}) // Suppress future errors
}()
wg2.Wait()
}
// keepAliveMonitor periodically sends messages to invoke a response.
// If the server does not respond after some period of time,
// assume that the underlying net.Conn abruptly died.
func (t tunnel) keepAliveMonitor(once *sync.Once, wg *sync.WaitGroup, client *ssh.Client) {
defer wg.Done()
if t.keepAlive.Interval == 0 || t.keepAlive.CountMax == 0 {
return
}
// Detect when the SSH connection is closed.
wait := make(chan error, 1)
wg.Add(1)
go func() {
defer wg.Done()
wait <- client.Wait()
}()
// Repeatedly check if the remote server is still alive.
var aliveCount int32
ticker := time.NewTicker(time.Duration(t.keepAlive.Interval) * time.Second)
defer ticker.Stop()
for {
select {
case err := <-wait:
if err != nil && err != io.EOF {
once.Do(func() { t.log.Printf("(%v) SSH error: %v", t, err) })
}
return
case <-ticker.C:
if n := atomic.AddInt32(&aliveCount, 1); n > int32(t.keepAlive.CountMax) {
once.Do(func() { t.log.Printf("(%v) SSH keep-alive termination", t) })
client.Close()
return
}
}
wg.Add(1)
go func() {
defer wg.Done()
_, _, err := client.SendRequest("[email protected]", true, nil)
if err == nil {
atomic.StoreInt32(&aliveCount, 0)
}
}()
}
}