-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_dialer.go
73 lines (62 loc) · 1.42 KB
/
client_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
64
65
66
67
68
69
70
71
72
73
package remotedialer
import (
"context"
"io"
"net"
"time"
)
type Hijacker func(ctx context.Context, conn net.Conn, proto, address string) (next bool)
var DialHijack Hijacker = func(ctx context.Context, conn net.Conn, proto, address string) (next bool) {
return true
}
func clientDial(ctx context.Context, dialer Dialer, conn *connection, proto, address string) {
defer func(conn *connection) {
_ = conn.Close()
}(conn)
// Do client hijacker
if !DialHijack(ctx, conn, proto, address) {
conn.doTunnelClose(io.EOF)
return
}
var (
netConn net.Conn
err error
)
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Minute))
if dialer == nil {
d := net.Dialer{}
netConn, err = d.DialContext(ctx, proto, address)
} else {
netConn, err = dialer(ctx, proto, address)
}
cancel()
if err != nil {
conn.doTunnelClose(err)
return
}
defer func(netConn net.Conn) {
_ = netConn.Close()
}(netConn)
pipe(conn, netConn)
}
func pipe(client *connection, server net.Conn) {
ch := make(chan struct{}, 1)
deFun := func(err error) error {
if err == nil {
err = io.EOF
}
client.doTunnelClose(err)
_ = server.Close()
return err
}
go func() {
defer close(ch)
_, err := io.Copy(server, client)
_ = deFun(err)
}()
_, err := io.Copy(client, server)
err = deFun(err)
<-ch
// Write tunnel error after no more I/O is happening, just incase messages get out of order
client.writeErr(err)
}