/
dial.go
61 lines (50 loc) · 1.47 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
59
60
61
package app
import (
"context"
"crypto/tls"
"fmt"
"net"
"github.com/canonical/go-dqlite/client"
)
// Like client.DialFuncWithTLS but also starts the proxy, since the raft
// connect function only supports Unix and TCP connections.
func makeNodeDialFunc(appCtx context.Context, config *tls.Config) client.DialFunc {
dial := func(ctx context.Context, addr string) (net.Conn, error) {
clonedConfig := config.Clone()
if len(clonedConfig.ServerName) == 0 {
remoteIP, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
clonedConfig.ServerName = remoteIP
}
dialer := &net.Dialer{}
conn, err := dialer.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, err
}
goUnix, cUnix, err := socketpair()
if err != nil {
return nil, fmt.Errorf("create pair of Unix sockets: %w", err)
}
go proxy(appCtx, conn, goUnix, clonedConfig)
return cUnix, nil
}
return dial
}
// extDialFuncWithProxy executes given DialFunc and then copies the data back
// and forth between the remote connection and a local unix socket.
func extDialFuncWithProxy(appCtx context.Context, dialFunc client.DialFunc) client.DialFunc {
return func(ctx context.Context, addr string) (net.Conn, error) {
goUnix, cUnix, err := socketpair()
if err != nil {
return nil, fmt.Errorf("create pair of Unix sockets: %w", err)
}
conn, err := dialFunc(ctx, addr)
if err != nil {
return nil, err
}
go proxy(appCtx, conn, goUnix, nil)
return cUnix, nil
}
}