-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_proxy.go
125 lines (109 loc) · 2.35 KB
/
tcp_proxy.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
package do
import (
"io"
"log"
"net"
)
const (
network = "tcp"
)
// TCPProxy listen localAddr and transfer any request to remoteAddr.We can use handlers to specify one custom func to transfer data.
func TCPProxy(localAddr, remoteAddr string, handlers ...func(lconn, rconn net.Conn)) (err error) {
laddr, err := net.ResolveTCPAddr(network, localAddr)
if err != nil {
return
}
l, err := net.ListenTCP(network, laddr)
if err != nil {
return
}
defer l.Close()
log.Printf("listen %v\n", laddr)
raddr, err := net.ResolveTCPAddr(network, remoteAddr)
if err != nil {
return
}
for {
var lconn net.Conn
lconn, err = l.Accept()
if err != nil {
return
}
rconn, err := net.DialTCP(network, nil, raddr)
if err != nil {
return err
}
log.Printf("dial %v\n", raddr)
if len(handlers) == 0 {
TCPProxyDefaultHandler(lconn, rconn)
} else {
go handlers[0](lconn, rconn)
}
}
}
func TCPProxyDefaultHandler(lconn, rconn net.Conn) {
go func() {
defer func() {
rconn.Close()
log.Printf("close remote conn\n")
}()
n, err := io.Copy(lconn, rconn)
if err == io.EOF {
return
}
if err != nil {
log.Printf("copy from remote to local failed: %v\n", err)
return
}
log.Printf("copy %d bytes from remote to local\n", n)
}()
go func() {
defer func() {
lconn.Close()
log.Printf("close local conn\n")
}()
n, err := io.Copy(rconn, lconn)
if err == io.EOF {
return
}
if err != nil {
log.Printf("copy from local to remote failed: %v\n", err)
return
}
log.Printf("copy %d bytes from local to remote\n", n)
}()
}
// TCPSend send to remote addr with handler
func TCPSend(remoteAddr string, handler func(conn net.Conn) error) (err error) {
raddr, err := net.ResolveTCPAddr(network, remoteAddr)
if err != nil {
return
}
rconn, err := net.DialTCP(network, nil, raddr)
if err != nil {
return
}
defer rconn.Close()
return handler(rconn)
}
// TCPRecv recv from local addr with handler, it will block on (*net.TCPListener).Accept
func TCPRecv(localAddr string, handler func(conn net.Conn)) (err error) {
laddr, err := net.ResolveTCPAddr(network, localAddr)
if err != nil {
return
}
l, err := net.ListenTCP(network, laddr)
if err != nil {
return
}
defer l.Close()
for {
var lconn net.Conn
lconn, err = l.Accept()
if err != nil {
return
}
defer lconn.Close()
go handler(lconn)
}
}