-
Notifications
You must be signed in to change notification settings - Fork 17
/
server.go
453 lines (408 loc) · 11.5 KB
/
server.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
package socks5
import (
"bytes"
"context"
"fmt"
"io"
"net"
)
// Server is accepting connections and handling the details of the SOCKS5 protocol
type Server struct {
// Authentication is proxy authentication
Authentication Authentication
// ProxyDial specifies the optional proxyDial function for
// establishing the transport connection.
ProxyDial func(ctx context.Context, network string, address string) (net.Conn, error)
// ProxyListen specifies the optional proxyListen function for
// establishing the transport connection.
ProxyListen func(context.Context, string, string) (net.Listener, error)
// ProxyListenPacket specifies the optional proxyListenPacket function for
// establishing the transport connection.
ProxyListenPacket func(ctx context.Context, network string, address string) (net.PacketConn, error)
// PacketForwardAddress specifies the packet forwarding address
PacketForwardAddress func(ctx context.Context, destinationAddr string, packet net.PacketConn, conn net.Conn) (net.IP, int, error)
// Logger error log
Logger Logger
// Context is default context
Context context.Context
// BytesPool getting and returning temporary bytes for use by io.CopyBuffer
BytesPool BytesPool
}
type Logger interface {
Println(v ...interface{})
}
// NewServer creates a new Server
func NewServer() *Server {
return &Server{}
}
// ListenAndServe is used to create a listener and serve on it
func (s *Server) ListenAndServe(network, addr string) error {
l, err := s.proxyListen(s.context(), network, addr)
if err != nil {
return err
}
return s.Serve(l)
}
func (s *Server) proxyListen(ctx context.Context, network, address string) (net.Listener, error) {
proxyListen := s.ProxyListen
if proxyListen == nil {
var listenConfig net.ListenConfig
proxyListen = listenConfig.Listen
}
return proxyListen(ctx, network, address)
}
// Serve is used to serve connections from a listener
func (s *Server) Serve(l net.Listener) error {
for {
conn, err := l.Accept()
if err != nil {
return err
}
go s.ServeConn(conn)
}
}
// ServeConn is used to serve a single connection.
func (s *Server) ServeConn(conn net.Conn) {
defer conn.Close()
err := s.serveConn(conn)
if err != nil && s.Logger != nil && !isClosedConnError(err) {
s.Logger.Println(err)
}
}
func (s *Server) serveConn(conn net.Conn) error {
version, err := readByte(conn)
if err != nil {
return err
}
if version != socks5Version {
return fmt.Errorf("unsupported SOCKS version: %d", version)
}
req := &request{
Version: socks5Version,
Conn: conn,
}
methods, err := readBytes(conn)
if err != nil {
return err
}
if s.Authentication != nil && bytes.IndexByte(methods, byte(userAuth)) != -1 {
_, err := conn.Write([]byte{socks5Version, byte(userAuth)})
if err != nil {
return err
}
header, err := readByte(conn)
if err != nil {
return err
}
if header != userAuthVersion {
return fmt.Errorf("unsupported auth version: %d", header)
}
username, err := readBytes(conn)
if err != nil {
return err
}
req.Username = string(username)
password, err := readBytes(conn)
if err != nil {
return err
}
req.Password = string(password)
if !s.Authentication.Auth(req.Command, req.Username, req.Password) {
_, err := conn.Write([]byte{userAuthVersion, authFailure})
if err != nil {
return err
}
return errUserAuthFailed
}
_, err = conn.Write([]byte{userAuthVersion, authSuccess})
if err != nil {
return err
}
} else if s.Authentication == nil && bytes.IndexByte(methods, byte(noAuth)) != -1 {
_, err := conn.Write([]byte{socks5Version, byte(noAuth)})
if err != nil {
return err
}
} else {
_, err := conn.Write([]byte{socks5Version, byte(noAcceptable)})
if err != nil {
return err
}
return errNoSupportedAuth
}
var header [3]byte
_, err = io.ReadFull(conn, header[:])
if err != nil {
return err
}
if header[0] != socks5Version {
return fmt.Errorf("unsupported Command version: %d", header[0])
}
req.Command = Command(header[1])
dest, err := readAddr(conn)
if err != nil {
if err == errUnrecognizedAddrType {
err := sendReply(conn, addrTypeNotSupported, nil)
if err != nil {
return err
}
}
return err
}
req.DestinationAddr = dest
err = s.handle(req)
if err != nil {
return err
}
return nil
}
func (s *Server) handle(req *request) error {
switch req.Command {
case ConnectCommand:
return s.handleConnect(req)
case BindCommand:
return s.handleBind(req)
case AssociateCommand:
return s.handleAssociate(req)
default:
if err := sendReply(req.Conn, commandNotSupported, nil); err != nil {
return err
}
return fmt.Errorf("unsupported Command: %v", req.Command)
}
}
func (s *Server) handleConnect(req *request) error {
ctx := s.context()
target, err := s.proxyDial(ctx, "tcp", req.DestinationAddr.Address())
if err != nil {
if err := sendReply(req.Conn, errToReply(err), nil); err != nil {
return fmt.Errorf("failed to send reply: %v", err)
}
return fmt.Errorf("connect to %v failed: %w", req.DestinationAddr, err)
}
defer target.Close()
localAddr := target.LocalAddr()
local, ok := localAddr.(*net.TCPAddr)
if !ok {
return fmt.Errorf("connect to %v failed: local address is %s://%s", req.DestinationAddr, localAddr.Network(), localAddr.String())
}
bind := address{IP: local.IP, Port: local.Port}
if err := sendReply(req.Conn, successReply, &bind); err != nil {
return fmt.Errorf("failed to send reply: %v", err)
}
var buf1, buf2 []byte
if s.BytesPool != nil {
buf1 = s.BytesPool.Get()
buf2 = s.BytesPool.Get()
defer func() {
s.BytesPool.Put(buf1)
s.BytesPool.Put(buf2)
}()
} else {
buf1 = make([]byte, 32*1024)
buf2 = make([]byte, 32*1024)
}
return tunnel(ctx, target, req.Conn, buf1, buf2)
}
func (s *Server) handleBind(req *request) error {
ctx := s.context()
var lc net.ListenConfig
listener, err := lc.Listen(ctx, "tcp", req.DestinationAddr.String())
if err != nil {
if err := sendReply(req.Conn, errToReply(err), nil); err != nil {
return fmt.Errorf("failed to send reply: %v", err)
}
return fmt.Errorf("connect to %v failed: %w", req.DestinationAddr, err)
}
localAddr := listener.Addr()
local, ok := localAddr.(*net.TCPAddr)
if !ok {
listener.Close()
return fmt.Errorf("connect to %v failed: local address is %s://%s", req.DestinationAddr, localAddr.Network(), localAddr.String())
}
bind := address{IP: local.IP, Port: local.Port}
if err := sendReply(req.Conn, successReply, &bind); err != nil {
listener.Close()
return fmt.Errorf("failed to send reply: %v", err)
}
conn, err := listener.Accept()
if err != nil {
listener.Close()
if err := sendReply(req.Conn, errToReply(err), nil); err != nil {
return fmt.Errorf("failed to send reply: %v", err)
}
return fmt.Errorf("connect to %v failed: %w", req.DestinationAddr, err)
}
listener.Close()
remoteAddr := conn.RemoteAddr()
local, ok = remoteAddr.(*net.TCPAddr)
if !ok {
return fmt.Errorf("connect to %v failed: remote address is %s://%s", req.DestinationAddr, localAddr.Network(), localAddr.String())
}
bind = address{IP: local.IP, Port: local.Port}
if err := sendReply(req.Conn, successReply, &bind); err != nil {
return fmt.Errorf("failed to send reply: %v", err)
}
var buf1, buf2 []byte
if s.BytesPool != nil {
buf1 = s.BytesPool.Get()
buf2 = s.BytesPool.Get()
defer func() {
s.BytesPool.Put(buf1)
s.BytesPool.Put(buf2)
}()
} else {
buf1 = make([]byte, 32*1024)
buf2 = make([]byte, 32*1024)
}
return tunnel(ctx, conn, req.Conn, buf1, buf2)
}
func (s *Server) handleAssociate(req *request) error {
ctx := s.context()
destinationAddr := req.DestinationAddr.String()
udpConn, err := s.proxyListenPacket(ctx, "udp", destinationAddr)
if err != nil {
if err := sendReply(req.Conn, errToReply(err), nil); err != nil {
return fmt.Errorf("failed to send reply: %v", err)
}
return fmt.Errorf("connect to %v failed: %w", req.DestinationAddr, err)
}
defer udpConn.Close()
replyPacketForwardAddress := defaultReplyPacketForwardAddress
if s.PacketForwardAddress != nil {
replyPacketForwardAddress = s.PacketForwardAddress
}
ip, port, err := replyPacketForwardAddress(ctx, destinationAddr, udpConn, req.Conn)
if err != nil {
return err
}
bind := address{IP: ip, Port: port}
if err := sendReply(req.Conn, successReply, &bind); err != nil {
return fmt.Errorf("failed to send reply: %v", err)
}
go func() {
var buf [1]byte
for {
_, err := req.Conn.Read(buf[:])
if err != nil {
udpConn.Close()
break
}
}
}()
var (
sourceAddr net.Addr
wantSource string
targetAddr net.Addr
wantTarget string
replyPrefix []byte
buf [maxUdpPacket]byte
)
for {
n, addr, err := udpConn.ReadFrom(buf[:])
if err != nil {
return err
}
if sourceAddr == nil {
sourceAddr = addr
wantSource = sourceAddr.String()
}
gotAddr := addr.String()
if wantSource == gotAddr {
if n < 3 {
continue
}
reader := bytes.NewBuffer(buf[3:n])
addr, err := readAddr(reader)
if err != nil {
if s.Logger != nil {
s.Logger.Println(err)
}
continue
}
if targetAddr == nil {
targetAddr = &net.UDPAddr{
IP: addr.IP,
Port: addr.Port,
}
wantTarget = targetAddr.String()
}
if addr.String() != wantTarget {
if s.Logger != nil {
s.Logger.Println(fmt.Errorf("ignore non-target addresses %s", addr))
}
continue
}
_, err = udpConn.WriteTo(reader.Bytes(), targetAddr)
if err != nil {
return err
}
} else if targetAddr != nil && wantTarget == gotAddr {
if replyPrefix == nil {
b := bytes.NewBuffer(make([]byte, 3, 16))
err = writeAddrWithStr(b, wantTarget)
if err != nil {
return err
}
replyPrefix = b.Bytes()
}
copy(buf[len(replyPrefix):len(replyPrefix)+n], buf[:n])
copy(buf[:len(replyPrefix)], replyPrefix)
_, err = udpConn.WriteTo(buf[:len(replyPrefix)+n], sourceAddr)
if err != nil {
return err
}
}
}
}
func (s *Server) proxyDial(ctx context.Context, network, address string) (net.Conn, error) {
proxyDial := s.ProxyDial
if proxyDial == nil {
var dialer net.Dialer
proxyDial = dialer.DialContext
}
return proxyDial(ctx, network, address)
}
func (s *Server) proxyListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
proxyListenPacket := s.ProxyListenPacket
if proxyListenPacket == nil {
var listener net.ListenConfig
proxyListenPacket = listener.ListenPacket
}
return proxyListenPacket(ctx, network, address)
}
func (s *Server) context() context.Context {
if s.Context == nil {
return context.Background()
}
return s.Context
}
func sendReply(w io.Writer, resp reply, addr *address) error {
_, err := w.Write([]byte{socks5Version, byte(resp), 0})
if err != nil {
return err
}
err = writeAddr(w, addr)
return err
}
type request struct {
Version uint8
Command Command
DestinationAddr *address
Username string
Password string
Conn net.Conn
}
func defaultReplyPacketForwardAddress(ctx context.Context, destinationAddr string, packet net.PacketConn, conn net.Conn) (net.IP, int, error) {
udpLocal := packet.LocalAddr()
udpLocalAddr, ok := udpLocal.(*net.UDPAddr)
if !ok {
return nil, 0, fmt.Errorf("connect to %v failed: local address is %s://%s", destinationAddr, udpLocal.Network(), udpLocal.String())
}
tcpLocal := conn.LocalAddr()
tcpLocalAddr, ok := tcpLocal.(*net.TCPAddr)
if !ok {
return nil, 0, fmt.Errorf("connect to %v failed: local address is %s://%s", destinationAddr, tcpLocal.Network(), tcpLocal.String())
}
return tcpLocalAddr.IP, udpLocalAddr.Port, nil
}