/
client.go
229 lines (182 loc) · 3.88 KB
/
client.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
package myssh
import (
"errors"
"io"
"log"
"net"
"net/url"
"os"
"runtime/debug"
"sync"
"time"
"golang.org/x/crypto/ssh"
)
const DEFAULT_TIMEOUT = 3 * time.Minute
var (
ErrNotValid = errors.New("SSHClient not valid")
)
type SSHConn struct {
net.Conn
IsLocal bool
}
func (c *SSHConn) Read(b []byte) (n int, err error) {
c.SetReadDeadline(time.Now().Add(DEFAULT_TIMEOUT))
return c.Conn.Read(b)
}
func (c *SSHConn) Write(b []byte) (n int, err error) {
c.SetWriteDeadline(time.Now().Add(DEFAULT_TIMEOUT))
return c.Conn.Write(b)
}
func (c *SSHConn) Close() error {
c.SetDeadline(time.Now().Add(DEFAULT_TIMEOUT))
return c.Conn.Close()
}
type SSHClient struct {
Addr string
User string
KeyFile string
c *ssh.Client
closeOnce *sync.Once
chDial chan int
chShutdown chan int
wg sync.WaitGroup
locker sync.RWMutex
}
func (cli *SSHClient) Dial(n string, addr string) (c net.Conn, err error) {
if !cli.IsValid() {
err = ErrNotValid
return
}
c, err = cli.c.Dial(n, addr)
if err == io.EOF {
log.Println("[ERROR] ssh: connect failed")
cli.chDial <- 0
}
c = &SSHConn{
Conn: c,
}
return
}
func (cli *SSHClient) Close() {
if !cli.IsValid() {
return
}
cli.closeOnce.Do(func() {
defer func() {
if e := recover(); e != nil {
log.Printf("SSHClient::Close crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
}
}()
cli.locker.Lock()
defer cli.locker.Unlock()
cli.c.Close()
cli.c = nil
cli.chDial = nil
})
}
func (cli *SSHClient) Shutdown() {
cli.chShutdown <- 0
cli.wg.Wait()
cli.Close()
}
func (cli *SSHClient) Ping() (err error) {
defer func() {
if e := recover(); e != nil {
log.Printf("SSHClient::Ping crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
}
}()
if cli.c == nil {
err = ErrNotValid
return
}
_, _, err = cli.c.SendRequest("keepalive@ssh-tunnel", true, nil)
return
}
func (cli *SSHClient) IsValid() bool {
cli.locker.RLock()
defer cli.locker.RUnlock()
return cli.c != nil
}
func (cli *SSHClient) dial() (err error) {
pemFile, err := os.ReadFile(cli.KeyFile)
if err != nil {
return
}
signer, err := ssh.ParsePrivateKey(pemFile)
if err != nil {
log.Printf("ssh: %v", err)
return
}
conf := &ssh.ClientConfig{
User: cli.User,
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
Timeout: 3 * time.Minute,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
BannerCallback: func(message string) error {
log.Println("[ERROR] ssh:", message)
return nil
},
}
if cli.c, err = ssh.Dial("tcp", cli.Addr, conf); err != nil {
return
}
cli.closeOnce = new(sync.Once)
return
}
func (cli *SSHClient) keeplive() {
defer func() {
if e := recover(); e != nil {
log.Printf("SSHClient::keeplive crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
}
}()
cli.wg.Add(1)
defer cli.wg.Done()
ticker := time.NewTicker(time.Minute * 1)
log.Println("ssh: keeplive start")
fn := func() (err error) {
defer func() {
if e := recover(); e != nil {
log.Printf("SSHClient::ping crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
}
}()
if err = cli.Ping(); err != nil {
cli.Close()
if err = cli.dial(); err != nil {
log.Println("ssh: reconnect failed.")
} else {
log.Println("ssh: reconnect success.")
}
}
return
}
running := true
for running {
select {
case <-cli.chDial:
fn()
case <-ticker.C:
fn()
case <-cli.chShutdown:
running = false
}
}
log.Println("ssh: keeplive exit.")
}
func NewSSHClient(remoteURL string, remoteKey string) (cli *SSHClient, err error) {
u, err := url.Parse(remoteURL)
if err != nil {
return
}
cli = new(SSHClient)
cli.Addr = u.Hostname() + ":" + u.Port()
cli.User = u.User.Username()
cli.KeyFile = remoteKey
cli.chDial = make(chan int)
cli.chShutdown = make(chan int)
if err = cli.dial(); err != nil {
cli = nil
return
}
go cli.keeplive()
return
}