-
Notifications
You must be signed in to change notification settings - Fork 4
/
daze.go
1293 lines (1207 loc) · 33.8 KB
/
daze.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package daze
import (
"bufio"
"bytes"
"context"
"crypto/cipher"
"crypto/rc4"
"crypto/sha256"
"crypto/tls"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"math"
"math/bits"
"math/rand/v2"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/mohanson/daze/lib/doa"
"github.com/mohanson/daze/lib/lru"
)
// ============================================================================
// ___ ___ ___ ___
// /\ \ /\ \ /\ \ /\ \
// /::\ \ /::\ \ \:\ \ /::\ \
// /:/\:\ \ /:/\:\ \ \:\ \ /:/\:\ \
// /:/ \:\__\ /::\~\:\ \ \:\ \ /::\~\:\ \
// /:/__/ \:|__| /:/\:\ \:\__\ _______\:\__\ /:/\:\ \:\__\
// \:\ \ /:/ / \/__\:\/:/ / \::::::::/__/ \:\~\:\ \/__/
// \:\ /:/ / \::/ / \:\~~\~~ \:\ \:\__\
// \:\/:/ / /:/ / \:\ \ \:\ \/__/
// \::/__/ /:/ / \:\__\ \:\__\
// ~~ \/__/ \/__/ \/__/
// ============================================================================
// Conf is acting as package level configuration.
var Conf = struct {
DialerTimeout time.Duration
RouterLruSize int
}{
DialerTimeout: time.Second * 8,
// A single cache entry represents a single host or DNS name lookup. Make the cache as large as the maximum number
// of clients that access your web site concurrently. Note that setting the cache size too high is a waste of
// memory and degrades performance.
RouterLruSize: 64,
}
// ResolverDns returns a DNS resolver.
func ResolverDns(addr string) *net.Resolver {
return &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: Conf.DialerTimeout,
}
return d.DialContext(ctx, "udp", addr)
},
}
}
// ResolverDot returns a DoT resolver. For further information, see https://datatracker.ietf.org/doc/html/rfc7858.
func ResolverDot(addr string) *net.Resolver {
host, _, _ := net.SplitHostPort(addr)
conf := &tls.Config{
ServerName: host,
ClientSessionCache: tls.NewLRUClientSessionCache(0),
}
return &net.Resolver{
PreferGo: true,
Dial: func(context context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: Conf.DialerTimeout,
}
c, err := d.DialContext(context, "tcp", addr)
if err != nil {
return nil, err
}
return tls.Client(c, conf), nil
},
}
}
// Cdoh structure can be used for DoH protocol processing.
type Cdoh struct {
Server string
Buffer *bytes.Buffer
}
func (c Cdoh) Read(b []byte) (n int, err error) { return c.Buffer.Read(b) }
func (c Cdoh) Close() error { return nil }
func (c Cdoh) LocalAddr() net.Addr { return nil }
func (c Cdoh) RemoteAddr() net.Addr { return nil }
func (c Cdoh) SetDeadline(t time.Time) error { return nil }
func (c Cdoh) SetReadDeadline(t time.Time) error { return nil }
func (c Cdoh) SetWriteDeadline(t time.Time) error { return nil }
func (c Cdoh) Write(b []byte) (n int, err error) {
size := int(binary.BigEndian.Uint16(b[:2]))
doa.Doa(size == len(b)-2)
resp, err := http.Post(c.Server, "application/dns-message", bytes.NewReader(b[2:]))
if err != nil {
log.Println("cdoh:", err)
return len(b), nil
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("cdoh:", err)
return len(b), nil
}
data := make([]byte, 2+len(body))
binary.BigEndian.PutUint16(data[:2], uint16(len(body)))
copy(data[2:], body)
c.Buffer.Write(data)
return len(b), nil
}
// ResolverDoh returns a DoH resolver. For further information, see https://datatracker.ietf.org/doc/html/rfc8484.
func ResolverDoh(addr string) *net.Resolver {
urls := doa.Try(url.Parse(addr))
urls.Host = doa.Try(net.LookupHost(urls.Hostname()))[0]
return &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
conn := &Cdoh{
Server: urls.String(),
Buffer: bytes.NewBuffer([]byte{}),
}
return conn, nil
},
}
}
// Link copies from src to dst and dst to src until either EOF is reached.
func Link(a, b io.ReadWriteCloser) {
w := sync.WaitGroup{}
w.Add(2)
go func() {
io.Copy(b, a)
b.Close()
w.Done()
}()
go func() {
io.Copy(a, b)
a.Close()
w.Done()
}()
w.Wait()
}
// ReadWriteCloser is the interface that groups the basic Read, Write and Close methods.
type ReadWriteCloser struct {
io.Reader
io.Writer
io.Closer
}
// Context carries infomations for a tcp connection.
type Context struct {
Cid uint32
}
// Dialer abstracts the way to establish network connections.
type Dialer interface {
Dial(ctx *Context, network string, address string) (io.ReadWriteCloser, error)
}
// Direct is the default dialer for connecting to an address.
type Direct struct{}
// Dial implements daze.Dialer.
func (d *Direct) Dial(ctx *Context, network string, address string) (io.ReadWriteCloser, error) {
return Dial(network, address)
}
// Locale is the main process of daze. In most cases, it is usually deployed as a daemon on a local machine.
type Locale struct {
Listen string
Dialer Dialer
Closer io.Closer
}
// ServeProxy serves traffic in HTTP Proxy/Tunnel format.
//
// Introduction:
// See https://en.wikipedia.org/wiki/Proxy_server
// See https://en.wikipedia.org/wiki/HTTP_tunnel
// See https://www.infoq.com/articles/Web-Sockets-Proxy-Servers/
func (l *Locale) ServeProxy(ctx *Context, cli io.ReadWriteCloser) error {
cliReader := bufio.NewReader(cli)
cli = ReadWriteCloser{
Reader: cliReader,
Writer: cli,
Closer: cli,
}
var err error
for {
err = func() error {
r, err := http.ReadRequest(cliReader)
if err != nil {
return err
}
var port string
if r.URL.Port() == "" {
port = "80"
} else {
port = r.URL.Port()
}
if r.Method == "CONNECT" {
log.Printf("conn: %08x proto format=tunnel", ctx.Cid)
} else {
log.Printf("conn: %08x proto format=hproxy", ctx.Cid)
}
srv, err := l.Dialer.Dial(ctx, "tcp", r.URL.Hostname()+":"+port)
if err != nil {
return err
}
defer srv.Close()
if r.Method == "CONNECT" {
_, err := cli.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
if err != nil {
return err
}
Link(cli, srv)
return io.EOF
}
if r.Method == "GET" && r.Header.Get("Upgrade") == "websocket" {
if err := r.Write(srv); err != nil {
return err
}
Link(cli, srv)
return io.EOF
}
srvReader := bufio.NewReader(srv)
if err := r.Write(srv); err != nil {
return err
}
s, err := http.ReadResponse(srvReader, r)
if err != nil {
return err
}
return s.Write(cli)
}()
if err != nil {
break
}
}
// It makes no sense to report a EOF error.
if err == io.EOF {
return nil
}
return err
}
// ServeSocks4 serves traffic in SOCKS4/SOCKS4a format.
//
// Introduction:
// See https://en.wikipedia.org/wiki/SOCKS
// See http://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol
func (l *Locale) ServeSocks4(ctx *Context, cli io.ReadWriteCloser) error {
cliReader := bufio.NewReader(cli)
cli = ReadWriteCloser{
Reader: cliReader,
Writer: cli,
Closer: cli,
}
var (
fCode uint8
fDstPort = make([]byte, 2)
fDstIP = make([]byte, 4)
fHostName []byte
dstHost string
dstPort uint16
dst string
srv io.ReadWriteCloser
err error
)
cliReader.Discard(1)
fCode, _ = cliReader.ReadByte()
io.ReadFull(cliReader, fDstPort)
dstPort = binary.BigEndian.Uint16(fDstPort)
io.ReadFull(cliReader, fDstIP)
_, err = cliReader.ReadBytes(0x00)
if err != nil {
return err
}
if bytes.Equal(fDstIP[:3], []byte{0x00, 0x00, 0x00}) && fDstIP[3] != 0x00 {
fHostName, err = cliReader.ReadBytes(0x00)
if err != nil {
return err
}
fHostName = fHostName[:len(fHostName)-1]
dstHost = string(fHostName)
} else {
dstHost = net.IP(fDstIP).String()
}
dst = dstHost + ":" + strconv.Itoa(int(dstPort))
log.Printf("conn: %08x proto format=socks4", ctx.Cid)
switch fCode {
case 0x01:
srv, err = l.Dialer.Dial(ctx, "tcp", dst)
if err != nil {
cli.Write([]byte{0x00, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
} else {
defer srv.Close()
cli.Write([]byte{0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
Link(cli, srv)
}
return err
case 0x02:
panic("unreachable")
}
return nil
}
// ServeSocks5 serves traffic in SOCKS5 format.
//
// Introduction:
// See https://en.wikipedia.org/wiki/SOCKS
// See https://tools.ietf.org/html/rfc1928
func (l *Locale) ServeSocks5(ctx *Context, cli io.ReadWriteCloser) error {
cliReader := bufio.NewReader(cli)
cli = ReadWriteCloser{
Reader: cliReader,
Writer: cli,
Closer: cli,
}
var (
fN uint8
fCmd uint8
fAT uint8
fDstAddr []byte
fDstPort = make([]byte, 2)
dstHost string
dstPort uint16
dst string
err error
)
cliReader.Discard(1)
fN, _ = cliReader.ReadByte()
cliReader.Discard(int(fN))
cli.Write([]byte{0x05, 0x00})
cliReader.Discard(1)
fCmd, _ = cliReader.ReadByte()
cliReader.Discard(1)
fAT, _ = cliReader.ReadByte()
switch fAT {
case 0x01:
fDstAddr = make([]byte, 4)
io.ReadFull(cliReader, fDstAddr)
dstHost = net.IP(fDstAddr).String()
case 0x03:
fN, _ = cliReader.ReadByte()
fDstAddr = make([]byte, int(fN))
io.ReadFull(cliReader, fDstAddr)
dstHost = string(fDstAddr)
case 0x04:
fDstAddr = make([]byte, 16)
io.ReadFull(cliReader, fDstAddr)
dstHost = net.IP(fDstAddr).String()
}
_, err = io.ReadFull(cli, fDstPort)
if err != nil {
return err
}
dstPort = binary.BigEndian.Uint16(fDstPort)
dst = net.JoinHostPort(dstHost, strconv.Itoa(int(dstPort)))
switch fCmd {
case 0x01:
return l.ServeSocks5TCP(ctx, cli, dst)
case 0x02:
panic("unreachable")
case 0x03:
return l.ServeSocks5UDP(ctx, cli)
}
return nil
}
// ServeSocks5TCP serves socks5 TCP protocol.
func (l *Locale) ServeSocks5TCP(ctx *Context, cli io.ReadWriteCloser, dst string) error {
log.Printf("conn: %08x proto format=socks5", ctx.Cid)
srv, err := l.Dialer.Dial(ctx, "tcp", dst)
if err != nil {
cli.Write([]byte{0x05, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
} else {
cli.Write([]byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
// Since the Link function will close the srv, there is no need to close it manually.
Link(cli, srv)
}
return err
}
// ServeSocks5UDP serves socks5 UDP protocol.
func (l *Locale) ServeSocks5UDP(ctx *Context, cli io.ReadWriteCloser) error {
var (
bndAddr *net.UDPAddr
bndPort uint16
bnd *net.UDPConn
appAddr *net.UDPAddr
appSize int
appHeadSize int
appHead []byte
dstHost string
dstPort uint16
dst string
srv io.ReadWriteCloser
b bool
cpl = map[string]io.ReadWriteCloser{}
buf = make([]byte, 2048)
err error
)
bndAddr = doa.Try(net.ResolveUDPAddr("udp", "127.0.0.1:0"))
bnd = doa.Try(net.ListenUDP("udp", bndAddr))
defer bnd.Close()
bndPort = uint16(bnd.LocalAddr().(*net.UDPAddr).Port)
copy(buf, []byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
binary.BigEndian.PutUint16(buf[8:10], bndPort)
_, err = cli.Write(buf[:10])
if err != nil {
return err
}
// https://datatracker.ietf.org/doc/html/rfc1928, Page 7, UDP ASSOCIATE:
// A UDP association terminates when the TCP connection that the UDP ASSOCIATE request arrived on terminates.
go func() {
io.Copy(io.Discard, cli)
bnd.Close()
}()
for {
appSize, appAddr, err = bnd.ReadFromUDP(buf)
if err != nil {
break
}
// +----+------+------+----------+----------+----------+
// |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
// +----+------+------+----------+----------+----------+
// | 2 | 1 | 1 | Variable | 2 | Variable |
// +----+------+------+----------+----------+----------+
// The fields in the UDP request header are:
// * RSV Reserved X'0000'
// * FRAG Current fragment number
// * ATYP address type of following addresses:
// * IP V4 address: X'01'
// * DOMAINNAME: X'03'
// * IP V6 address: X'04'
// * DST.ADDR desired destination address
// * DST.PORT desired destination port
// * DATA user data
doa.Doa(buf[0] == 0x00)
doa.Doa(buf[1] == 0x00)
// Implementation of fragmentation is optional; an implementation that does not support fragmentation MUST drop
// any datagram whose FRAG field is other than X'00'.
doa.Doa(buf[2] == 0x00)
switch buf[3] {
case 0x01:
appHeadSize = 10
case 0x03:
appHeadSize = int(buf[4]) + 7
case 0x04:
appHeadSize = 22
}
appHead = make([]byte, appHeadSize)
copy(appHead, buf[0:appHeadSize])
switch appHead[3] {
case 0x01:
dstHost = net.IP(appHead[4:8]).String()
dstPort = binary.BigEndian.Uint16(appHead[8:10])
case 0x03:
l := appHead[4]
dstHost = string(appHead[5 : 5+l])
dstPort = binary.BigEndian.Uint16(appHead[5+l : 7+l])
case 0x04:
dstHost = net.IP(appHead[4:20]).String()
dstPort = binary.BigEndian.Uint16(appHead[20:22])
}
dst = dstHost + ":" + strconv.Itoa(int(dstPort))
srv, b = cpl[dst]
if b {
goto send
} else {
goto init
}
init:
log.Printf("conn: %08x proto format=socks5", ctx.Cid)
srv, err = l.Dialer.Dial(ctx, "udp", dst)
if err != nil {
log.Printf("conn: %08x error %s", ctx.Cid, err)
continue
}
cpl[dst] = srv
go func(srv io.ReadWriteCloser, appHead []byte, appAddr *net.UDPAddr) error {
var (
buf = make([]byte, 2048)
l = len(appHead)
n int
err error
)
copy(buf, appHead)
for {
n, err = srv.Read(buf[l:])
if err != nil {
break
}
_, err = bnd.WriteToUDP(buf[:l+n], appAddr)
if err != nil {
break
}
}
return err
}(srv, appHead, appAddr)
send:
_, err = srv.Write(buf[appHeadSize:appSize])
if err != nil {
log.Printf("conn: %08x error %s", ctx.Cid, err)
continue
}
}
for _, e := range cpl {
e.Close()
}
return nil
}
// Serve serves incoming connections and handle it with a different handler(ServeProxy/ServeSocks4/ServeSocks5).
func (l *Locale) Serve(ctx *Context, cli io.ReadWriteCloser) error {
var (
buf = make([]byte, 1)
err error
)
_, err = io.ReadFull(cli, buf)
if err != nil {
// There are some clients that will establish a link in advance without sending any messages so that they can
// immediately get the connected conn when they really need it. When they leave, it makes no sense to report a
// EOF error.
if err == io.EOF {
return nil
}
return err
}
cli = ReadWriteCloser{
Reader: io.MultiReader(bytes.NewReader(buf), cli),
Writer: cli,
Closer: cli,
}
if buf[0] == 0x05 {
return l.ServeSocks5(ctx, cli)
}
if buf[0] == 0x04 {
return l.ServeSocks4(ctx, cli)
}
return l.ServeProxy(ctx, cli)
}
// Close listener.
func (l *Locale) Close() error {
if l.Closer != nil {
return l.Closer.Close()
}
return nil
}
// Run it.
func (l *Locale) Run() error {
s, err := net.Listen("tcp", l.Listen)
if err != nil {
return err
}
l.Closer = s
log.Println("main: listen and serve on", l.Listen)
go func() {
idx := uint32(math.MaxUint32)
for {
cli, err := s.Accept()
if err != nil {
if !errors.Is(err, net.ErrClosed) {
log.Println("main:", err)
}
break
}
idx++
ctx := &Context{idx}
log.Printf("conn: %08x accept remote=%s", ctx.Cid, cli.RemoteAddr())
go func() {
defer cli.Close()
if err := l.Serve(ctx, cli); err != nil {
log.Printf("conn: %08x error %s", ctx.Cid, err)
}
log.Printf("conn: %08x closed", ctx.Cid)
}()
}
}()
return nil
}
// NewLocale returns a Locale.
func NewLocale(listen string, dialer Dialer) *Locale {
return &Locale{
Listen: listen,
Dialer: dialer,
}
}
// ============================================================================
// ___ ___ ___ ___
// /\ \ /\ \ /\ \ /\ \
// /::\ \ /::\ \ /::\ \ /::\ \
// /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \
// /::\~\:\ \ /:/ \:\ \ /::\~\:\ \ /:/ \:\__\
// /:/\:\ \:\__\ /:/__/ \:\__\ /:/\:\ \:\__\ /:/__/ \:|__|
// \/_|::\/:/ / \:\ \ /:/ / \/__\:\/:/ / \:\ \ /:/ /
// |:|::/ / \:\ /:/ / \::/ / \:\ /:/ /
// |:|\/__/ \:\/:/ / /:/ / \:\/:/ /
// |:| | \::/ / /:/ / \::/__/
// \|__| \/__/ \/__/ ~~
// ============================================================================
// A Road represents a host's road mode.
type Road uint32
const (
// RoadLocale means it don't need a proxy
RoadLocale Road = iota
// RoadRemote means it should accessed through proxy
RoadRemote
// RoadFucked means it is pure rubbish
RoadFucked
// RoadPuzzle means ?
RoadPuzzle
)
func (r Road) String() string {
switch r {
case RoadLocale:
return "direct"
case RoadRemote:
return "remote"
case RoadFucked:
return "fucked"
case RoadPuzzle:
return "puzzle"
}
panic("unreachable")
}
// Router is a selector that will judge the host address.
type Router interface {
// The host must be a literal IP address, or a host name that can be resolved to IP addresses.
// Examples:
// Road("golang.org")
// Road("192.0.2.1")
Road(ctx *Context, host string) Road
}
// RouterIPNet is a router by IPNets. It judges whether an IP or domain name is within its range.
type RouterIPNet struct {
L []*net.IPNet
R []*net.IPNet
B []*net.IPNet
}
// FromFile loads a CIDR file.
func (r *RouterIPNet) FromFile(name string) {
f := doa.Try(OpenFile(name))
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
line := s.Text()
seps := strings.Fields(line)
if len(seps) < 2 {
continue
}
_, cidr, err := net.ParseCIDR(seps[1])
doa.Nil(err)
switch seps[0] {
case "#":
case "L":
r.L = append(r.L, cidr)
case "R":
r.R = append(r.R, cidr)
case "B":
r.B = append(r.B, cidr)
}
}
doa.Nil(s.Err())
}
// Road implements daze.Router.
func (r *RouterIPNet) Road(ctx *Context, host string) Road {
l, err := net.DefaultResolver.LookupIPAddr(context.Background(), host)
if err != nil {
log.Printf("conn: %08x error %s", ctx.Cid, err)
return RoadPuzzle
}
a := l[0]
for _, e := range r.L {
if e.Contains(a.IP) {
return RoadLocale
}
}
for _, e := range r.R {
if e.Contains(a.IP) {
return RoadRemote
}
}
for _, e := range r.B {
if e.Contains(a.IP) {
return RoadFucked
}
}
return RoadPuzzle
}
// NewRouterIPNet returns a new RouterIPNet object.
func NewRouterIPNet() *RouterIPNet {
return &RouterIPNet{
L: LoadReservedIP(),
R: []*net.IPNet{},
B: []*net.IPNet{},
}
}
// RouterRight always returns the same road.
type RouterRight struct {
R Road
}
// Road implements daze.Router.
func (r *RouterRight) Road(ctx *Context, host string) Road {
return r.R
}
// NewRouterRight returns a new RouterRight.
func NewRouterRight(road Road) *RouterRight {
return &RouterRight{R: road}
}
// RouterCache cache routing results for next use.
type RouterCache struct {
Lru *lru.Lru[string, Road]
Raw Router
}
// Road implements daze.Router.
func (r *RouterCache) Road(ctx *Context, host string) Road {
a, b := r.Lru.GetExists(host)
if b {
return a
}
c := r.Raw.Road(ctx, host)
r.Lru.Set(host, c)
return c
}
// NewRouterCache returns a new Cache object.
func NewRouterCache(r Router) *RouterCache {
return &RouterCache{
Lru: lru.New[string, Road](Conf.RouterLruSize),
Raw: r,
}
}
// RouterChain concat multiple routers in series.
type RouterChain struct {
L []Router
}
// Road implements daze.Router.
func (r *RouterChain) Road(ctx *Context, host string) Road {
for _, e := range r.L {
a := e.Road(ctx, host)
if a != RoadPuzzle {
return a
}
}
return RoadPuzzle
}
// NewRouterChain returns a new RouterChain.
func NewRouterChain(router ...Router) *RouterChain {
return &RouterChain{
L: router,
}
}
// RouterRules aims to be a minimal configuration file format that's easy to read due to obvious semantics.
// There are two parts per line on the RULE file: mode and glob. mode is on the left of the space sign and glob is on
// the right. mode is a character that describes whether the host should be accessed through a proxy, and the glob is a
// glob-style string.
//
// Glob patterns:
// * h?llo matches hello, hallo and hxllo
// * h*llo matches hllo and heeeello
// * h[ae]llo matches hello and hallo, but not hillo
// * h[^e]llo matches hallo, hbllo, ... but not hello
// * h[a-b]llo matches hallo and hbllo
//
// This is a normal RULE document:
// L a.com a.a.com
// R b.com *.b.com
// B c.com
//
// L(ocale) means using locale network
// R(emote) means using remote network
// B(anned) means to block it
type RouterRules struct {
L []string
R []string
B []string
}
// Road implements daze.Router.
func (r *RouterRules) Road(ctx *Context, host string) Road {
for _, e := range r.L {
if doa.Try(filepath.Match(e, host)) {
return RoadLocale
}
}
for _, e := range r.R {
if doa.Try(filepath.Match(e, host)) {
return RoadRemote
}
}
for _, e := range r.B {
if doa.Try(filepath.Match(e, host)) {
return RoadFucked
}
}
return RoadPuzzle
}
// FromFile loads a RULE file.
func (r *RouterRules) FromFile(name string) {
f := doa.Try(OpenFile(name))
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
line := s.Text()
seps := strings.Fields(line)
if len(seps) < 2 {
continue
}
switch seps[0] {
case "#":
case "L":
r.L = append(r.L, seps[1:]...)
case "R":
r.R = append(r.R, seps[1:]...)
case "B":
r.B = append(r.B, seps[1:]...)
}
}
doa.Nil(s.Err())
}
// NewRouterRules returns a new RoaderRules.
func NewRouterRules() *RouterRules {
return &RouterRules{
L: []string{},
R: []string{},
B: []string{},
}
}
// Aimbot automatically distinguish whether to use a proxy or a local network.
type Aimbot struct {
Remote Dialer
Locale Dialer
Router Router
}
// Dial connects to the address on the named network.
func (s *Aimbot) Dial(ctx *Context, network string, address string) (io.ReadWriteCloser, error) {
var (
dst string
err error
rwc io.ReadWriteCloser
tag Road
)
log.Printf("conn: %08x dial network=%s address=%s", ctx.Cid, network, address)
dst, _, err = net.SplitHostPort(address)
if err != nil {
return nil, err
}
tag = s.Router.Road(ctx, dst)
log.Printf("conn: %08x route road=%s", ctx.Cid, tag)
switch tag {
case RoadLocale:
rwc, err = s.Locale.Dial(ctx, network, address)
case RoadRemote:
rwc, err = s.Remote.Dial(ctx, network, address)
case RoadFucked:
err = fmt.Errorf("conn: %s has been blocked", dst)
case RoadPuzzle:
rwc, err = s.Remote.Dial(ctx, network, address)
}
if err == nil {
log.Printf("conn: %08x estab", ctx.Cid)
}
return rwc, err
}
// AimbotOption provides configuration for quick initialization of Aimbot.
type AimbotOption struct {
Type string
Rule string
Cidr string
}
// NewAimbot returns a new Aimbot.
func NewAimbot(client Dialer, option *AimbotOption) *Aimbot {
router := func() Router {
if option.Type == "locale" {
routerRight := NewRouterRight(RoadLocale)
return routerRight
}
if option.Type == "remote" {
routerLocal := NewRouterIPNet()
routerRight := NewRouterRight(RoadRemote)
routerChain := NewRouterChain(routerLocal, routerRight)
routerCache := NewRouterCache(routerChain)
return routerCache
}
if option.Type == "rule" {
log.Println("main: load rule", option.Rule)
routerRules := NewRouterRules()
routerRules.FromFile(option.Rule)
log.Println("main: size is", len(routerRules.L)+len(routerRules.R)+len(routerRules.B))
log.Println("main: load rule", option.Cidr)
routerLocal := NewRouterIPNet()
routerLocal.FromFile(option.Cidr)
log.Println("main: size is", len(routerLocal.L)+len(routerLocal.R)+len(routerLocal.B))
routerRight := NewRouterRight(RoadRemote)
routerChain := NewRouterChain(routerRules, routerLocal, routerRight)
routerCache := NewRouterCache(routerChain)
return routerCache
}
panic("unreachable")
}()
return &Aimbot{
Remote: client,
Locale: &Direct{},
Router: router,
}
}
// ============================================================================
// ___ ___ ___ ___
// /\ \ /\ \ /\ \ /\__\
// \:\ \ /::\ \ /::\ \ /:/ /
// \:\ \ /:/\:\ \ /:/\:\ \ /:/ /
// /::\ \ /:/ \:\ \ /:/ \:\ \ /:/ /
// /:/\:\__\ /:/__/ \:\__\ /:/__/ \:\__\ /:/__/
// /:/ \/__/ \:\ \ /:/ / \:\ \ /:/ / \:\ \
// /:/ / \:\ /:/ / \:\ /:/ / \:\ \
// /:/ / \:\/:/ / \:\/:/ / \:\ \
// /:/ / \::/ / \::/ / \:\__\
// \/__/ \/__/ \/__/ \/__/
// ============================================================================
// Check interface implementation.
var (
_ Dialer = (*Aimbot)(nil)
_ Dialer = (*Direct)(nil)
_ Router = (*RouterCache)(nil)
_ Router = (*RouterChain)(nil)
_ Router = (*RouterIPNet)(nil)
_ Router = (*RouterRight)(nil)
_ Router = (*RouterRules)(nil)
)
// Dial connects to the address on the named network.
func Dial(network string, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: Conf.DialerTimeout,
}
return d.Dial(network, address)
}