forked from wadahiro/go-transproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
74 lines (58 loc) · 1.41 KB
/
tcp.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
package transproxy
import (
"log"
"net"
"net/url"
"strings"
"time"
"golang.org/x/net/proxy"
)
type TCPProxy struct {
TCPProxyConfig
}
type TCPProxyConfig struct {
ListenAddress string
NoProxy NoProxy
}
func NewTCPProxy(c TCPProxyConfig) *TCPProxy {
return &TCPProxy{
TCPProxyConfig: c,
}
}
func (s TCPProxy) Start() error {
//pdialer := proxy.FromEnvironment()
dialer := &net.Dialer{
KeepAlive: 3 * time.Minute,
DualStack: true,
}
u, err := url.Parse(GetProxyEnv("http_proxy"))
if err != nil {
return err
}
pdialer, err := proxy.FromURL(u, dialer)
if err != nil {
return err
}
npdialer := proxy.Direct
log.Printf("info: Start listener on %s category='TCP-Proxy'", s.ListenAddress)
go func() {
ListenTCP(s.ListenAddress, func(tc *TCPConn) {
// access logging
host, _, _ := net.SplitHostPort(tc.RemoteAddr().String())
log.Printf("info: category='TCP-Proxy' remoteAddr='%s' method=CONNECT host='%s'", host, tc.OrigAddr)
var destConn net.Conn
// TODO Convert OrigAddr to domain and check useProxy with domain too?
if useProxy(s.NoProxy, strings.Split(tc.OrigAddr, ":")[0]) {
destConn, err = pdialer.Dial("tcp", tc.OrigAddr)
} else {
destConn, err = npdialer.Dial("tcp", tc.OrigAddr)
}
if err != nil {
log.Printf("error: Failed to connect to destination - %s category='TCP-Proxy'", err.Error())
return
}
Pipe(tc, destConn)
})
}()
return nil
}