forked from txthinking/brook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
455 lines (427 loc) · 9.8 KB
/
client.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
454
455
package brook
import (
"bytes"
"errors"
"io"
"log"
"net"
"time"
cache "github.com/patrickmn/go-cache"
"github.com/txthinking/brook/plugin"
"github.com/txthinking/socks5"
xx "github.com/txthinking/x"
)
// Client
type Client struct {
Server *socks5.Server
RemoteAddr string
Password []byte
TCPTimeout int
TCPDeadline int
UDPDeadline int
TCPListen *net.TCPListener
Socks5Middleman plugin.Socks5Middleman
HTTPMiddleman plugin.HTTPMiddleman
}
// NewClient returns a new Client
func NewClient(addr, ip, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) (*Client, error) {
s5, err := socks5.NewClassicServer(addr, ip, "", "", tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
if err != nil {
return nil, err
}
x := &Client{
RemoteAddr: server,
Server: s5,
Password: []byte(password),
TCPTimeout: tcpTimeout,
TCPDeadline: tcpDeadline,
UDPDeadline: udpDeadline,
}
return x, nil
}
// SetSocks5Middleman sets socks5middleman plugin
func (x *Client) SetSocks5Middleman(m plugin.Socks5Middleman) {
x.Socks5Middleman = m
}
// SetHTTPMiddleman sets httpmiddleman plugin
func (x *Client) SetHTTPMiddleman(m plugin.HTTPMiddleman) {
x.HTTPMiddleman = m
}
// ListenAndServe will let client start a socks5 proxy
// sm can be nil
func (x *Client) ListenAndServe() error {
return x.Server.Run(x)
}
// TCPHandle handles tcp request
func (x *Client) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error {
if x.Socks5Middleman != nil {
done, err := x.Socks5Middleman.TCPHandle(s, c, r)
if err != nil {
if done {
return err
}
return ErrorReply(r, c, err)
}
if done {
return nil
}
}
if r.Cmd == socks5.CmdConnect {
tmp, err := Dial.Dial("tcp", x.RemoteAddr)
if err != nil {
return ErrorReply(r, c, err)
}
rc := tmp.(*net.TCPConn)
defer rc.Close()
if x.TCPTimeout != 0 {
if err := rc.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
return ErrorReply(r, c, err)
}
}
if x.TCPDeadline != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
return ErrorReply(r, c, err)
}
}
k, n, err := PrepareKey(x.Password)
if err != nil {
return ErrorReply(r, c, err)
}
if _, err := rc.Write(n); err != nil {
return ErrorReply(r, c, err)
}
rawaddr := make([]byte, 0, 7)
rawaddr = append(rawaddr, r.Atyp)
rawaddr = append(rawaddr, r.DstAddr...)
rawaddr = append(rawaddr, r.DstPort...)
n, err = WriteTo(rc, rawaddr, k, n, true)
if err != nil {
return ErrorReply(r, c, err)
}
a, address, port, err := socks5.ParseAddress(rc.LocalAddr().String())
if err != nil {
return ErrorReply(r, c, err)
}
rp := socks5.NewReply(socks5.RepSuccess, a, address, port)
if err := rp.WriteTo(c); err != nil {
return err
}
go func() {
n := make([]byte, 12)
if _, err := io.ReadFull(rc, n); err != nil {
return
}
k, err := GetKey(x.Password, n)
if err != nil {
log.Println(err)
return
}
var b []byte
for {
if x.TCPDeadline != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
return
}
}
b, n, err = ReadFrom(rc, k, n, false)
if err != nil {
return
}
if _, err := c.Write(b); err != nil {
return
}
}
}()
var b [1024 * 2]byte
for {
if x.TCPDeadline != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
return nil
}
}
i, err := c.Read(b[:])
if err != nil {
return nil
}
n, err = WriteTo(rc, b[0:i], k, n, false)
if err != nil {
return nil
}
}
return nil
}
if r.Cmd == socks5.CmdUDP {
caddr, err := r.UDP(c, x.Server.ServerAddr)
if err != nil {
return err
}
_, p, err := net.SplitHostPort(caddr.String())
if err != nil {
return err
}
if p == "0" {
time.Sleep(time.Duration(x.Server.UDPSessionTime) * time.Second)
return nil
}
ch := make(chan byte)
x.Server.TCPUDPAssociate.Set(caddr.String(), ch, cache.DefaultExpiration)
<-ch
return nil
}
return socks5.ErrUnsupportCmd
}
// UDPHandle handles udp request
func (x *Client) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error {
if x.Socks5Middleman != nil {
if done, err := x.Socks5Middleman.UDPHandle(s, addr, d); err != nil || done {
return err
}
}
send := func(ue *socks5.UDPExchange, data []byte) error {
cd, err := Encrypt(x.Password, data)
if err != nil {
return err
}
_, err = ue.RemoteConn.Write(cd)
if err != nil {
return err
}
return nil
}
var ue *socks5.UDPExchange
iue, ok := s.UDPExchanges.Get(addr.String())
if ok {
ue = iue.(*socks5.UDPExchange)
return send(ue, d.Bytes()[3:])
}
c, err := Dial.Dial("udp", x.RemoteAddr)
if err != nil {
v, ok := s.TCPUDPAssociate.Get(addr.String())
if ok {
ch := v.(chan byte)
ch <- 0x00
s.TCPUDPAssociate.Delete(addr.String())
}
return err
}
rc := c.(*net.UDPConn)
ue = &socks5.UDPExchange{
ClientAddr: addr,
RemoteConn: rc,
}
if err := send(ue, d.Bytes()[3:]); err != nil {
v, ok := s.TCPUDPAssociate.Get(ue.ClientAddr.String())
if ok {
ch := v.(chan byte)
ch <- 0x00
s.TCPUDPAssociate.Delete(ue.ClientAddr.String())
}
ue.RemoteConn.Close()
return err
}
s.UDPExchanges.Set(ue.ClientAddr.String(), ue, cache.DefaultExpiration)
go func(ue *socks5.UDPExchange) {
defer func() {
v, ok := s.TCPUDPAssociate.Get(ue.ClientAddr.String())
if ok {
ch := v.(chan byte)
ch <- 0x00
}
s.UDPExchanges.Delete(ue.ClientAddr.String())
ue.RemoteConn.Close()
}()
var b [65536]byte
for {
if s.UDPDeadline != 0 {
if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
break
}
}
n, err := ue.RemoteConn.Read(b[:])
if err != nil {
break
}
_, _, _, data, err := Decrypt(x.Password, b[0:n])
if err != nil {
log.Println(err)
break
}
a, addr, port, err := socks5.ParseAddress(ue.ClientAddr.String())
if err != nil {
log.Println(err)
break
}
d1 := socks5.NewDatagram(a, addr, port, data)
if _, err := s.UDPConn.WriteToUDP(d1.Bytes(), ue.ClientAddr); err != nil {
break
}
}
}(ue)
return nil
}
// ListenAndServeHTTP will let client start a http proxy
func (x *Client) ListenAndServeHTTP() error {
var err error
x.TCPListen, err = net.ListenTCP("tcp", x.Server.TCPAddr)
if err != nil {
return nil
}
for {
c, err := x.TCPListen.AcceptTCP()
if err != nil {
return err
}
go func(c *net.TCPConn) {
defer c.Close()
if x.TCPTimeout != 0 {
if err := c.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
log.Println(err)
return
}
}
if x.TCPDeadline != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
log.Println(err)
return
}
}
if err := x.HTTPHandle(c); err != nil {
log.Println(err)
return
}
}(c)
}
}
// HTTPHandle handle http request
func (x *Client) HTTPHandle(c *net.TCPConn) error {
b := make([]byte, 0, 1024)
for {
var b1 [1024]byte
n, err := c.Read(b1[:])
if err != nil {
return err
}
b = append(b, b1[:n]...)
if bytes.Contains(b, []byte{0x0d, 0x0a, 0x0d, 0x0a}) {
break
}
if len(b) >= 2083+18 {
return errors.New("HTTP header too long")
}
}
bb := bytes.SplitN(b, []byte(" "), 3)
if len(bb) != 3 {
return errors.New("Invalid Request")
}
method, aoru := string(bb[0]), string(bb[1])
var addr string
if method == "CONNECT" {
addr = aoru
}
if method != "CONNECT" {
var err error
addr, err = xx.GetAddressFromURL(aoru)
if err != nil {
return err
}
}
if x.HTTPMiddleman != nil {
if done, err := x.HTTPMiddleman.Handle(method, addr, b, c); err != nil || done {
return err
}
}
tmp, err := Dial.Dial("tcp", x.RemoteAddr)
if err != nil {
return err
}
rc := tmp.(*net.TCPConn)
defer rc.Close()
if x.TCPTimeout != 0 {
if err := rc.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
return err
}
}
if x.TCPDeadline != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
return err
}
}
k, n, err := PrepareKey(x.Password)
if err != nil {
return err
}
if _, err := rc.Write(n); err != nil {
return err
}
a, h, p, err := socks5.ParseAddress(addr)
if err != nil {
return err
}
rawaddr := make([]byte, 0, 7)
rawaddr = append(rawaddr, a)
rawaddr = append(rawaddr, h...)
rawaddr = append(rawaddr, p...)
n, err = WriteTo(rc, rawaddr, k, n, true)
if err != nil {
return err
}
if method == "CONNECT" {
_, err := c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
if err != nil {
return err
}
}
if method != "CONNECT" {
n, err = WriteTo(rc, b, k, n, false)
if err != nil {
return err
}
}
go func() {
n := make([]byte, 12)
if _, err := io.ReadFull(rc, n); err != nil {
return
}
k, err := GetKey(x.Password, n)
if err != nil {
log.Println(err)
return
}
var b []byte
for {
if x.TCPDeadline != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
return
}
}
b, n, err = ReadFrom(rc, k, n, false)
if err != nil {
return
}
if _, err := c.Write(b); err != nil {
return
}
}
}()
var bf [1024 * 2]byte
for {
if x.TCPDeadline != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
return nil
}
}
i, err := c.Read(bf[:])
if err != nil {
return nil
}
n, err = WriteTo(rc, bf[0:i], k, n, false)
if err != nil {
return nil
}
}
return nil
}
// Shutdown used to stop the client
func (x *Client) Shutdown() error {
return x.Server.Stop()
}