forked from eycorsican/go-tun2socks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udp.go
192 lines (161 loc) · 4.03 KB
/
udp.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package socks
import (
"errors"
"fmt"
"io"
"net"
"sync"
"time"
"github.com/eycorsican/go-tun2socks/common/log"
"github.com/eycorsican/go-tun2socks/core"
)
type udpHandler struct {
sync.Mutex
proxyHost string
proxyPort uint16
udpConns map[core.UDPConn]net.PacketConn
tcpConns map[core.UDPConn]net.Conn
remoteAddrs map[core.UDPConn]*net.UDPAddr // UDP relay server addresses
timeout time.Duration
}
func NewUDPHandler(proxyHost string, proxyPort uint16, timeout time.Duration) core.UDPConnHandler {
return &udpHandler{
proxyHost: proxyHost,
proxyPort: proxyPort,
udpConns: make(map[core.UDPConn]net.PacketConn, 8),
tcpConns: make(map[core.UDPConn]net.Conn, 8),
remoteAddrs: make(map[core.UDPConn]*net.UDPAddr, 8),
timeout: timeout,
}
}
func (h *udpHandler) handleTCP(conn core.UDPConn, c net.Conn) {
buf := core.NewBytes(core.BufSize)
defer func() {
h.Close(conn)
core.FreeBytes(buf)
}()
for {
c.SetDeadline(time.Time{})
if _, err := c.Read(buf); err != nil {
return
}
}
}
func (h *udpHandler) fetchUDPInput(conn core.UDPConn, input net.PacketConn) {
buf := core.NewBytes(core.BufSize)
defer func() {
h.Close(conn)
core.FreeBytes(buf)
}()
for {
input.SetDeadline(time.Now().Add(h.timeout))
n, _, err := input.ReadFrom(buf)
if err != nil {
return
}
if len(buf) < 3 {
return
}
addr := SplitAddr(buf[3:])
if addr == nil {
return
}
resolvedAddr, err := net.ResolveUDPAddr("udp", addr.String())
if err != nil {
return
}
_, err = conn.WriteFrom(buf[int(3+len(addr)):n], resolvedAddr)
if err != nil {
log.Warnf("write local failed: %v", err)
return
}
}
}
func (h *udpHandler) Connect(conn core.UDPConn, target *net.UDPAddr) error {
if target == nil {
return h.connectInternal(conn, "")
}
return h.connectInternal(conn, target.String())
}
func (h *udpHandler) connectInternal(conn core.UDPConn, dest string) error {
c, err := net.DialTimeout("tcp", core.ParseTCPAddr(h.proxyHost, h.proxyPort).String(), 4*time.Second)
if err != nil {
return err
}
// send VER, NMETHODS, METHODS
c.Write([]byte{5, 1, 0})
buf := make([]byte, MaxAddrLen)
// read VER METHOD
if _, err := io.ReadFull(c, buf[:2]); err != nil {
return err
}
if len(dest) != 0 {
targetAddr := ParseAddr(dest)
// write VER CMD RSV ATYP DST.ADDR DST.PORT
c.Write(append([]byte{5, socks5UDPAssociate, 0}, targetAddr...))
} else {
c.Write(append([]byte{5, socks5UDPAssociate, 0}, []byte{1, 0, 0, 0, 0, 0, 0}...))
}
// read VER REP RSV ATYP BND.ADDR BND.PORT
if _, err := io.ReadFull(c, buf[:3]); err != nil {
return err
}
rep := buf[1]
if rep != 0 {
return errors.New("SOCKS handshake failed")
}
remoteAddr, err := readAddr(c, buf)
if err != nil {
return err
}
resolvedRemoteAddr, err := net.ResolveUDPAddr("udp", remoteAddr.String())
if err != nil {
return errors.New("failed to resolve remote address")
}
go h.handleTCP(conn, c)
pc, err := net.ListenPacket("udp", "")
if err != nil {
return err
}
h.Lock()
h.tcpConns[conn] = c
h.udpConns[conn] = pc
h.remoteAddrs[conn] = resolvedRemoteAddr
h.Unlock()
go h.fetchUDPInput(conn, pc)
log.Infof("new proxy connection to %v", dest)
return nil
}
func (h *udpHandler) ReceiveTo(conn core.UDPConn, data []byte, addr *net.UDPAddr) error {
h.Lock()
pc, ok1 := h.udpConns[conn]
remoteAddr, ok2 := h.remoteAddrs[conn]
h.Unlock()
if ok1 && ok2 {
buf := append([]byte{0, 0, 0}, ParseAddr(addr.String())...)
buf = append(buf, data[:]...)
_, err := pc.WriteTo(buf, remoteAddr)
if err != nil {
h.Close(conn)
return errors.New(fmt.Sprintf("write remote failed: %v", err))
}
return nil
} else {
h.Close(conn)
return errors.New(fmt.Sprintf("proxy connection %v->%v does not exists", conn.LocalAddr(), addr))
}
}
func (h *udpHandler) Close(conn core.UDPConn) {
conn.Close()
h.Lock()
defer h.Unlock()
if c, ok := h.tcpConns[conn]; ok {
c.Close()
delete(h.tcpConns, conn)
}
if pc, ok := h.udpConns[conn]; ok {
pc.Close()
delete(h.udpConns, conn)
}
delete(h.remoteAddrs, conn)
}