forked from eycorsican/go-tun2socks
-
Notifications
You must be signed in to change notification settings - Fork 16
/
tcp.go
104 lines (89 loc) · 2.14 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
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
package socks
import (
"errors"
"fmt"
"io"
"log"
"net"
"sync"
"time"
"golang.org/x/net/proxy"
"github.com/eycorsican/go-tun2socks/core"
)
type tcpHandler struct {
sync.Mutex
proxyHost string
proxyPort uint16
conns map[core.Connection]net.Conn
}
func NewTCPHandler(proxyHost string, proxyPort uint16) core.ConnectionHandler {
return &tcpHandler{
proxyHost: proxyHost,
proxyPort: proxyPort,
conns: make(map[core.Connection]net.Conn, 16),
}
}
func (h *tcpHandler) fetchInput(conn core.Connection, input io.Reader) {
defer func() {
h.Close(conn)
conn.Close() // also close tun2socks connection here
}()
_, err := io.Copy(conn, input)
if err != nil {
// log.Printf("fetch input failed: %v", err)
return
}
}
func (h *tcpHandler) getConn(conn core.Connection) (net.Conn, bool) {
h.Lock()
defer h.Unlock()
if c, ok := h.conns[conn]; ok {
return c, true
}
return nil, false
}
func (h *tcpHandler) Connect(conn core.Connection, target net.Addr) error {
dialer, err := proxy.SOCKS5("tcp", core.ParseTCPAddr(h.proxyHost, h.proxyPort).String(), nil, nil)
if err != nil {
return err
}
c, err := dialer.Dial(target.Network(), target.String())
if err != nil {
return err
}
h.Lock()
h.conns[conn] = c
h.Unlock()
c.SetDeadline(time.Time{})
go h.fetchInput(conn, c)
log.Printf("new proxy connection for target: %s:%s", target.Network(), target.String())
return nil
}
func (h *tcpHandler) DidReceive(conn core.Connection, data []byte) error {
if c, found := h.getConn(conn); found {
_, err := c.Write(data)
if err != nil {
h.Close(conn)
return errors.New(fmt.Sprintf("write remote failed: %v", err))
}
return nil
} else {
return errors.New(fmt.Sprintf("proxy connection %v->%v does not exists", conn.LocalAddr(), conn.RemoteAddr()))
}
}
func (h *tcpHandler) DidSend(conn core.Connection, len uint16) {
}
func (h *tcpHandler) DidClose(conn core.Connection) {
h.Close(conn)
}
func (h *tcpHandler) LocalDidClose(conn core.Connection) {
h.Close(conn)
}
func (h *tcpHandler) Close(conn core.Connection) {
if c, found := h.getConn(conn); found {
c.Close()
h.Lock()
delete(h.conns, conn)
h.Unlock()
}
}