-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdial.go
58 lines (49 loc) · 1.31 KB
/
dial.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
package sshclient
import (
"context"
"net"
"golang.org/x/crypto/ssh"
)
// DialContextFunc creates SSH connection to host with a given address.
type DialContextFunc func(ctx context.Context, network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
// ContextDialer returns DialContextFunc based on dialer to make net connections.
func ContextDialer(dialer *net.Dialer) DialContextFunc {
return contextDialer{dialer}.DialContext
}
type contextDialer struct {
dialer *net.Dialer
}
func (d contextDialer) DialContext(ctx context.Context, network, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {
conn, err := d.dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
type dialRes struct {
client *ssh.Client
err error
}
dialc := make(chan dialRes, 1)
go func() {
sshConn, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
dialc <- dialRes{err: err}
} else {
dialc <- dialRes{client: ssh.NewClient(sshConn, chans, reqs)}
}
}()
select {
case v := <-dialc:
// Our dial finished
if v.client != nil {
return v.client, nil
}
// Our dial failed
conn.Close()
// It wasn't an error due to cancellation, so
// return the original error message:
return nil, v.err
case <-ctx.Done():
conn.Close()
return nil, ctx.Err()
}
}