-
Notifications
You must be signed in to change notification settings - Fork 16
/
dialer.go
63 lines (50 loc) · 1.2 KB
/
dialer.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
package tls
import (
"context"
"crypto/tls"
"net"
"strings"
"github.com/consensys/quorum-key-manager/pkg/tcp"
)
type Dialer struct {
Dialer tcp.Dialer
TLSConfig *tls.Config
}
func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
return d.DialContext(context.Background(), network, addr)
}
func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
netConn, err := d.Dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
colonPos := strings.LastIndex(addr, ":")
if colonPos == -1 {
colonPos = len(addr)
}
hostname := addr[:colonPos]
// If no ServerName is set, infer the ServerName
// from the hostname we're connecting to.
config := d.TLSConfig
if d.TLSConfig.ServerName == "" {
// Make a copy to avoid polluting argument or default.
config = d.TLSConfig.Clone()
config.ServerName = hostname
}
tlsConn := tls.Client(netConn, config)
handshakeErrors := make(chan error, 1)
go func() {
handshakeErrors <- tlsConn.Handshake()
close(handshakeErrors)
}()
select {
case <-ctx.Done():
err = ctx.Err()
case err = <-handshakeErrors:
if err == nil {
return tlsConn, nil
}
}
tlsConn.Close()
return nil, err
}