-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest.go
1400 lines (1137 loc) · 39.2 KB
/
request.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 fbproxy
import (
"bytes"
"context"
"crypto/md5"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
config "fb-proxy/pkg/config"
"github.com/miekg/dns"
"go.uber.org/zap"
utls "github.com/refraction-networking/utls"
publicsuffix "golang.org/x/net/publicsuffix"
)
const (
ErrUnknownError = "UNKNOWN_ERROR"
ErrContextCanceled = "CONTEXT_CANCELED"
ErrEof = "EOF_ERROR"
ErrResolveIP = "RESOLVE_IP_ERROR"
ErrRetrieveNode = "RETRIEVE_NODE_ERROR"
ErrTcpConnectionReset = "TCP_CONNECTION_RESET_BY_PEER"
ErrTcpConnectionRefused = "TCP_CONNECTION_REFUSED"
ErrTcpNoRouteToHost = "TCP_NO_ROUTE_TO_HOST"
ErrTcpIoTimeout = "TCP_IO_TIMEOUT"
ErrTcpNoConnTargetRegused = "TCP_NO_CONNECTION_TARGET_REFUSED"
ErrTcpEstablishedConnectionAborted = "TCP_ESTABLISHED_CONNECTION_ABORTED"
ErrTcpSocketAccessForbidden = "TCP_SOCKET_ACCESS_FORBIDDEN"
ErrTcpSocketUnreachableHost = "TCP_SOCKET_UNREACHABLE_HOST"
ErrTlsCertMismatch = "TLS_CERTIFICATE_MISMATCH"
ErrTlsInternal = "TLS_INTERNAL_ERROR"
ErrTlsCertVerify = "TLS_VERIFY_CERTIFICATE_ERROR"
ErrTlsDoesNotLookLikeHandshake = "TLS_DOES_NOT_LOOK_LIKE_HANDSHAKE"
ErrTlsHandshakeFailure = "TLS_HANDSHAKE_FAILURE"
ErrHttpTimeoutResponseHeaders = "HTTP_TIMEOUT_RESPONSE_HEADERS"
)
var trustedCertDomains = make(map[string]string)
func ShortenDomain(domain string) string {
parts := strings.Split(domain, ".")
short := ""
for _, part := range parts {
short += string(part[0])
}
short += strconv.Itoa(len(domain))
return short
}
type DOHServer struct {
ID string
URL string
Reachability int
Attempts int
Successes int
}
type DOHServers struct {
dohMap map[string]DOHServer
mutex sync.RWMutex
}
type requestIDKeyType struct{}
var requestIDKey requestIDKeyType
type contextServerNameKeyType struct{}
var contextServerNameKey contextServerNameKeyType
type contextHostKeyType struct{}
var contextHostKey contextHostKeyType
type dnsResponse struct {
Status int `json:"Status"`
Answer []struct {
Type int `json:"type"`
TTL int `json:"TTL"`
Data string `json:"data"`
} `json:"Answer"`
}
type methodResult struct {
methodIndex int
orderIndex int
response *partialResponse
url string
}
type partialResponse struct {
data []byte
body io.ReadCloser
response *http.Response
}
type ReadCloserWrapper struct {
io.Reader
io.Closer
}
type dnsCacheEntry struct {
ip string
expiry time.Time
}
type Node struct {
ID string
Host string
IP string
Times []time.Duration
TotalTime time.Duration
AvgTime time.Duration
Errors []string
}
type Nodes struct {
NodesMap map[string]Node
mutex sync.RWMutex
}
var loadOnce sync.Once
var methodData = make(map[string]int)
var methodDataMutex sync.RWMutex
var nodeData = make(map[string]string)
var nodeDataMutex sync.RWMutex
var methodDataFilePath string
var snisLock = &sync.RWMutex{}
var nodes = &Nodes{
NodesMap: make(map[string]Node),
}
var dohServers *DOHServers
var exeDir string
func init() {
exePath, err := os.Executable()
if err != nil {
zap.S().Fatal(err)
}
exeDir = filepath.Dir(exePath)
}
func initProxy() {
zap.S().Debugln("Running initProxy()...")
methodData = readMethodData()
dohServers = initializeDOHServers(config.DohURLlist)
zap.S().Debugf("dohServers initialized: %v", dohServers)
loadFbConfig(config.FbConfigFile)
}
func (n *Nodes) AddNode(host, ip string) {
n.mutex.Lock()
defer n.mutex.Unlock()
nodeID := fmt.Sprintf("%s-%s", ShortenDomain(host), ip)
newNode := Node{
ID: nodeID,
Host: host,
IP: ip,
Times: []time.Duration{},
Errors: []string{},
}
n.NodesMap[nodeID] = newNode
}
func (n *DOHServers) AddDOHServer(dohURL string) {
n.mutex.Lock()
defer n.mutex.Unlock()
var ID string
if strings.HasPrefix(dohURL, "https://") {
ID = "https://" + strings.Split(dohURL, "/")[2]
} else {
ID = dohURL
}
newDOHServer := DOHServer{
ID: ID,
URL: dohURL,
Reachability: 1,
Attempts: 0,
Successes: 0,
}
n.dohMap[ID] = newDOHServer
zap.S().Debugf("Added DOH server: %s to dohMap", ID)
}
func incrementIP(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
func loadFbConfig(FbConfigFile string) {
defer func() {
if r := recover(); r != nil {
zap.S().Errorf("Panic recovered in loadFbConfig. Error: %v", r)
}
}()
var fbConfigFilePath string
if runtime.GOOS == "android" {
fbConfigFilePath = config.FbConfigFilePathAndroid
} else {
fbConfigFilePath = filepath.Join(exeDir, config.FbConfigFile)
}
fbConfigBytes, err := os.ReadFile(fbConfigFilePath)
if err != nil {
zap.S().Errorf("Error reading config data from external file: %v", err)
fbConfigBytes, err = config.EmbeddedFiles.ReadFile(FbConfigFile)
if err != nil {
zap.S().Errorf("Error reading config data from embedded file: %v", err)
return
} else {
zap.S().Infoln("Config data loaded from embedded file")
}
} else {
zap.S().Infoln("Config data loaded from external file")
}
fbConfigStr := string(fbConfigBytes)
fbConfigLines := strings.Split(fbConfigStr, "\n")
for _, line := range fbConfigLines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.Split(line, "\t")
switch parts[0] {
case "CDN-CIDRS":
zap.S().Debugf("fb.config CDN-CIDRS %s: %d IPs", parts[3], len(strings.Split(parts[4], ",")))
for _, cidr := range strings.Split(parts[4], ",") {
if strings.Contains(cidr, "/") {
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
zap.S().Errorf("Error parsing CIDR %s: %v", cidr, err)
continue
}
for ip := ipnet.IP.Mask(ipnet.Mask); ipnet.Contains(ip); incrementIP(ip) {
nodes.AddNode(parts[3], ip.String())
}
} else {
nodes.AddNode(parts[3], cidr)
}
}
case "CDN-CERTS":
zap.S().Debugf("fb.config CDN-CERTS %s: %d domains", parts[1], len(strings.Split(parts[2], ",")))
for _, cdnHostname := range strings.Split(parts[1], ",") {
trustedCertDomains[cdnHostname] = parts[2]
}
}
}
}
func initializeDOHServers(dohURLlist []string) *DOHServers {
dohServers = &DOHServers{
dohMap: make(map[string]DOHServer),
}
for _, dohURL := range dohURLlist {
dohServers.AddDOHServer(dohURL)
}
return dohServers
}
func (n *Nodes) RetrieveNode(eTldPlusOne string, orderIndex int, requestID string) Node {
n.mutex.RLock()
defer n.mutex.RUnlock()
if len(n.NodesMap) == 0 {
return Node{}
}
if orderIndex == 0 {
nodeDataMutex.Lock()
nodeID, nodeDataExists := nodeData[eTldPlusOne]
nodeDataMutex.Unlock()
if nodeDataExists && rand.Float64() > config.SwitchNodeChance {
zap.S().With("requestID", requestID).Debugf("Using node %s for %s from nodeData", nodeID, eTldPlusOne)
return n.NodesMap[nodeID]
}
}
testedNodes := make([]Node, 0)
untestedNodes := make([]Node, 0)
for _, node := range n.NodesMap {
if node.AvgTime == 0 {
untestedNodes = append(untestedNodes, node)
} else {
testedNodes = append(testedNodes, node)
}
}
zap.S().With("requestID", requestID).Debugf("Number of tested Nodes: %d", len(testedNodes))
zap.S().With("requestID", requestID).Debugf("Number of untested Nodes: %d", len(untestedNodes))
if len(testedNodes) == 0 {
zap.S().With("requestID", requestID).Debug("Using untested node because all nodes are untested")
return untestedNodes[rand.Intn(len(untestedNodes))]
}
if len(untestedNodes) > 0 && rand.Float64() < config.UntestedNodeChance {
zap.S().With("requestID", requestID).Debug("Using untested node by chance")
return untestedNodes[rand.Intn(len(untestedNodes))]
}
sort.Slice(testedNodes, func(i, j int) bool {
return testedNodes[i].AvgTime > testedNodes[j].AvgTime
})
totalInverse := 0.0
for _, node := range testedNodes {
inverseTime := 1.0 / float64(node.AvgTime)
totalInverse += math.Pow(inverseTime, config.NodePowerCoeff)
}
randomInverse := rand.Float64() * totalInverse
zap.S().With("requestID", requestID).Debugf("Calculated totalInverse: %v, randomInverse: %v", totalInverse, randomInverse)
cumulativeInverse := 0.0
for _, node := range testedNodes {
inverseTime := 1.0 / float64(node.AvgTime)
cumulativeInverse += math.Pow(inverseTime, config.NodePowerCoeff)
zap.S().With("requestID", requestID).Debugf("Checking node: %v, node.AvgTime: %v, inverseTime: %v, cumulativeInverse: %v, count of node.Errors: %d",
node, node.AvgTime, inverseTime, cumulativeInverse, len(node.Errors))
if cumulativeInverse > randomInverse && len(node.Errors) <= config.LimitNodeErrors {
return node
}
}
return Node{}
}
func (d *DOHServers) RetrieveDOHServer() DOHServer {
d.mutex.RLock()
defer d.mutex.RUnlock()
if len(d.dohMap) == 0 {
return DOHServer{}
}
reachableDOHServers := make([]DOHServer, 0)
unreachableDOHServers := make([]DOHServer, 0)
for _, dohServer := range d.dohMap {
if dohServer.Reachability == 0 {
unreachableDOHServers = append(unreachableDOHServers, dohServer)
} else {
reachableDOHServers = append(reachableDOHServers, dohServer)
}
}
if len(reachableDOHServers) == 0 {
zap.S().Debug("All DOH servers are unreachable")
if rand.Float64() < config.UnreachableDOHServerChance {
zap.S().Debug("Attempting unreachable DOH server by chance")
return unreachableDOHServers[rand.Intn(len(unreachableDOHServers))]
} else {
zap.S().Debug("Not attempting any DOH server")
return DOHServer{}
}
}
if len(unreachableDOHServers) > 0 && rand.Float64() < config.UnreachableDOHServerChance {
zap.S().Debug("Attempting unreachable DOH server by chance")
return unreachableDOHServers[rand.Intn(len(unreachableDOHServers))]
}
zap.S().Debug("Using reachable DOH server")
return reachableDOHServers[rand.Intn(len(reachableDOHServers))]
}
func (n *Nodes) RecordNodeTime(node Node, elapsedTime time.Duration, debug bool) {
n.mutex.Lock()
defer n.mutex.Unlock()
nodeMap, ok := n.NodesMap[node.ID]
if !ok {
zap.S().Infoln("Node with ID %s not found", node.ID)
return
}
if len(nodeMap.Times) >= config.MaxNodeTimeRecords {
nodeMap.TotalTime -= nodeMap.Times[0]
nodeMap.Times = nodeMap.Times[1:]
}
nodeMap.Times = append(nodeMap.Times, elapsedTime)
nodeMap.TotalTime += elapsedTime
nodeMap.AvgTime = nodeMap.TotalTime / time.Duration(len(nodeMap.Times))
n.NodesMap[node.ID] = nodeMap
if debug {
jsonBytes, err := json.MarshalIndent(n.NodesMap, "", " ")
if err != nil {
zap.S().Infof("Error marshalling nodeMap to JSON: %v", err)
return
}
err = os.WriteFile("nodeMap.json", jsonBytes, 0644)
if err != nil {
zap.S().Infof("Error writing nodeMap to file: %v", err)
}
}
}
func getErrorCode(err error) string {
if err == nil {
return ErrUnknownError
}
errStr := err.Error()
switch {
case strings.Contains(errStr, "does not match expected domains"):
return ErrTlsCertMismatch
case strings.Contains(errStr, "connection reset by peer"):
return ErrTcpConnectionReset
case strings.Contains(errStr, "connection refused"):
return ErrTcpConnectionRefused
case strings.Contains(errStr, "no route to host"):
return ErrTcpNoRouteToHost
case strings.Contains(errStr, "i/o timeout"):
return ErrTcpIoTimeout
case strings.Contains(errStr, "No connection could be made because the target machine actively refused it"):
return ErrTcpNoConnTargetRegused
case strings.Contains(errStr, "tls: internal error"):
return ErrTlsInternal
case strings.Contains(errStr, "tls: failed to verify certificate"):
return ErrTlsCertVerify
case strings.Contains(errStr, "tls: first record does not look like a TLS handshake"):
return ErrTlsDoesNotLookLikeHandshake
case strings.Contains(errStr, "tls: handshake failure"):
return ErrTlsHandshakeFailure
case strings.Contains(errStr, "context canceled"):
return ErrContextCanceled
case strings.Contains(errStr, "EOF"):
return ErrEof
case strings.Contains(errStr, "Error resolving IP"):
return ErrResolveIP
case strings.Contains(errStr, "Error retrieving node"):
return ErrRetrieveNode
case strings.Contains(errStr, "wsarecv: An established connection was aborted by the software in your host machine"):
return ErrTcpEstablishedConnectionAborted
case strings.Contains(errStr, "connectex: An attempt was made to access a socket in a way forbidden by its access permissions"):
return ErrTcpSocketAccessForbidden
case strings.Contains(errStr, "connectex: A socket operation was attempted to an unreachable host"):
return ErrTcpSocketUnreachableHost
case strings.Contains(errStr, "timeout awaiting response headers"):
return ErrHttpTimeoutResponseHeaders
case strings.Contains(errStr, "Node returned HTTP status code"):
return "HTTP_CODE_" + strings.Split(errStr, ":")[1]
default:
return ErrUnknownError
}
}
func (n *Nodes) RecordError(node Node, err error) {
n.mutex.Lock()
defer n.mutex.Unlock()
nodeMap, ok := n.NodesMap[node.ID]
if !ok {
zap.S().Infof("Node with ID %s not found", node.ID)
return
}
errorCode := getErrorCode(err)
if errorCode != ErrContextCanceled {
nodeMap.Errors = append(nodeMap.Errors, errorCode)
n.NodesMap[node.ID] = nodeMap
}
}
func (d *DOHServers) UpdateDOHServers(dohServer DOHServer, reachability int, debug bool) {
d.mutex.Lock()
defer d.mutex.Unlock()
dohMap, ok := d.dohMap[dohServer.ID]
if !ok {
zap.S().Debugf("DOH server with ID %s not found", dohServer.ID)
return
}
dohMap.Reachability = reachability
dohMap.Attempts++
if reachability == 1 {
dohMap.Successes++
}
d.dohMap[dohServer.ID] = dohMap
if debug {
jsonBytes, err := json.MarshalIndent(d.dohMap, "", " ")
if err != nil {
zap.S().Infof("Error marshalling dohMap to JSON: %v", err)
return
}
err = os.WriteFile("dohMap.json", jsonBytes, 0644)
if err != nil {
zap.S().Infof("Error writing dohMap to file: %v", err)
}
}
}
var dnsCache = map[string]dnsCacheEntry{}
var dnsCacheLock = &sync.RWMutex{}
func resolveIPFromCache(host string) (string, error) {
dnsCacheLock.RLock()
if val, ok := dnsCache[host]; ok {
if time.Now().Before(val.expiry) {
dnsCacheLock.RUnlock()
return val.ip, nil
}
}
dnsCacheLock.RUnlock()
return "", fmt.Errorf("No entry in cache")
}
var resolveIPsem = make(chan struct{}, config.ConcurrentDOHRequests)
var httpClientDNS = http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
Dial: (&net.Dialer{
Timeout: config.TimeoutNetDialer / 2,
}).Dial,
TLSHandshakeTimeout: config.TimeoutTLSHandshake / 2,
ResponseHeaderTimeout: config.TimeoutResponseHeader / 2,
},
Timeout: config.TimeoutHTTPClient / 2,
}
func resolveIPWithAPI(httpClientDNS http.Client, dohServer DOHServer, host string, debug bool, requestID string) (string, error) {
if dohServer.URL == "" {
return "", fmt.Errorf("No DOH server is available")
}
resolveIPsem <- struct{}{}
defer func() { <-resolveIPsem }()
zap.S().With("requestID", requestID).Infof("Resolve IP for host %s using DOH server %s", host, dohServer.ID)
url := fmt.Sprintf(dohServer.URL, host)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Header.Set("accept", "application/dns-json")
resp, err := httpClientDNS.Do(req)
if err != nil {
return "", fmt.Errorf("Error reaching DOH server: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
dnsResp := dnsResponse{}
err = json.Unmarshal(body, &dnsResp)
if err != nil {
return "", err
}
if debug {
dnsRespJSON, err := json.MarshalIndent(dnsResp, "", " ")
if err != nil {
zap.S().With("requestID", requestID).Debugln("Error marshalling DNS response for saving:", err)
} else {
err = os.WriteFile("dns_response.json", dnsRespJSON, 0644)
if err != nil {
zap.S().With("requestID", requestID).Debugln("Error writing DNS response to file:", err)
} else {
zap.S().With("requestID", requestID).Debugln("DNS response saved to dns_response.json")
}
}
}
if dnsResp.Status != 0 {
return "", fmt.Errorf("DNS response status is not 0: %d", dnsResp.Status)
}
for _, answer := range dnsResp.Answer {
if answer.Type == 1 {
ttl := answer.TTL
dnsCacheLock.Lock()
dnsCache[host] = dnsCacheEntry{
ip: answer.Data,
expiry: time.Now().Add(time.Duration(ttl) * time.Second),
}
dnsCacheLock.Unlock()
return answer.Data, nil
}
}
return "", fmt.Errorf("no A record found for %s", host)
}
func resolveIPWithCDN(httpClientDNS http.Client, dohServer DOHServer, host string, debug bool, requestID string) (string, error) {
proxyURL, _ := url.Parse(fmt.Sprintf("http://localhost:%s", config.ProxyPort))
var httpClientDNSWithProxy = http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Proxy: http.ProxyURL(proxyURL),
Dial: (&net.Dialer{
Timeout: config.TimeoutNetDialer,
}).Dial,
TLSHandshakeTimeout: config.TimeoutTLSHandshake,
ResponseHeaderTimeout: config.TimeoutResponseHeader,
},
Timeout: config.TimeoutHTTPClient,
}
return resolveIPWithDOH(httpClientDNSWithProxy, dohServer, host, debug, requestID)
}
func resolveIPWithDOH(httpClientDNS http.Client, dohServer DOHServer, host string, debug bool, requestID string) (string, error) {
if dohServer.URL == "" {
return "", fmt.Errorf("No DOH server URL provided")
}
resolveIPsem <- struct{}{}
defer func() { <-resolveIPsem }()
zap.S().With("requestID", requestID).Infof("Resolve IP for host %s using DOH server %s", host, dohServer.ID)
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(host), dns.TypeA)
m.RecursionDesired = true
wireMsg, err := m.Pack()
if err != nil {
return "", err
}
encodedMsg := base64.RawURLEncoding.EncodeToString(wireMsg)
var dohDomain string
if strings.HasPrefix(dohServer.URL, "doh://") {
dohDomain = strings.TrimPrefix(dohServer.URL, "doh://")
} else if strings.HasPrefix(dohServer.URL, "dohocdn://") {
dohDomain = strings.TrimPrefix(dohServer.URL, "dohocdn://")
config.UpdateDomainFrontingOnlyDomains(dohDomain)
zap.S().Debugf("Updated config.DomainFrontingOnlyDomains: %v", config.DomainFrontingOnlyDomains)
}
url := "https://" + dohDomain + "/dns-query?dns=" + encodedMsg
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Header.Set("accept", "application/dns-message")
req.Header.Set("User-Agent", config.SystemUserAgent)
resp, err := httpClientDNS.Do(req)
if err != nil {
return "", fmt.Errorf("Error reaching DOH server: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
in := new(dns.Msg)
if err := in.Unpack(body); err != nil {
return "", err
}
if debug {
debugOutput, _ := json.MarshalIndent(in, "", " ")
_ = os.WriteFile("dns_response.json", debugOutput, 0644)
zap.S().With("requestID", requestID).Debugln("DNS response saved to dns_response.json")
}
if in.Rcode != dns.RcodeSuccess {
return "", fmt.Errorf("DNS response status is not successful: %d", in.Rcode)
}
for _, ans := range in.Answer {
if aRecord, ok := ans.(*dns.A); ok {
ttl := ans.Header().Ttl
dnsCacheLock.Lock()
dnsCache[host] = dnsCacheEntry{
ip: aRecord.A.String(),
expiry: time.Now().Add(time.Duration(ttl) * time.Second),
}
dnsCacheLock.Unlock()
return aRecord.A.String(), nil
}
}
return "", fmt.Errorf("no A record found for %s", host)
}
func readPartialResponse(resp *http.Response) (*partialResponse, error) {
p := make([]byte, 512)
n, err := resp.Body.Read(p)
if err != nil && err != io.EOF {
return nil, err
}
return &partialResponse{
data: p[:n],
body: resp.Body,
response: resp,
}, nil
}
func getMD5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
func addSNI(sni string) {
snisLock.Lock()
defer snisLock.Unlock()
if !config.ValidSNIs[sni] {
config.ValidSNIs[sni] = true
}
}
func getSNI() string {
snisLock.RLock()
defer snisLock.RUnlock()
keys := make([]string, 0, len(config.ValidSNIs))
for k := range config.ValidSNIs {
keys = append(keys, k)
}
return keys[rand.Intn(len(keys))]
}
func sliceContains[T comparable](slice []T, element T) bool {
for _, v := range slice {
if v == element {
return true
}
}
return false
}
func copyHeader(h http.Header) http.Header {
copy := make(http.Header, len(h))
for k, vv := range h {
copy[k] = copyStringSlice(vv)
}
return copy
}
func copyStringSlice(slice []string) []string {
newSlice := make([]string, len(slice))
copy(newSlice, slice)
return newSlice
}
var ProcessRequestsem = make(chan struct{}, config.ConcurrentProcessRequests)
func ProcessRequest(req *http.Request, debug bool) (processRequestResp *http.Response, processRequestErr error) {
ProcessRequestsem <- struct{}{}
defer func() { <-ProcessRequestsem }()
startProcessRequest := time.Now()
requestID := fmt.Sprintf("%p", req)
defer func() {
if r := recover(); r != nil {
zap.S().With("requestID", requestID).Errorf("Panic recovered in ProcessRequest. Error: %v", r)
processRequestResp = nil
processRequestErr = fmt.Errorf("Panic recovered in ProcessRequest: %v", r)
}
}()
url_ := req.URL
method := req.Method
header := req.Header
body := req.Body
bodyBytes, err := io.ReadAll(body)
if err != nil {
return nil, err
}
methodResults := make(chan methodResult)
errors := make(chan error)
methods := []func(context.Context, *url.URL, string, string, string, http.Header, io.ReadCloser, bool) (*partialResponse, error){
func(ctx context.Context, parsedURL *url.URL, host string, ip string, httpMethod string, header http.Header, body io.ReadCloser, debug bool) (*partialResponse, error) {
zap.S().With("requestID", requestID).Infoln("Attempt with SNI")
if ip == "" {
return nil, fmt.Errorf("Error resolving IP")
}
sni := host
resp, err := makeRequest(ctx, parsedURL, httpMethod, header, body, host, ip, sni, debug)
if err != nil {
return nil, err
}
pr, err := readPartialResponse(resp)
addSNI(sni)
return pr, err
},
func(ctx context.Context, parsedURL *url.URL, host string, ip string, httpMethod string, header http.Header, body io.ReadCloser, debug bool) (*partialResponse, error) {
zap.S().With("requestID", requestID).Infoln("Attempt without SNI")
if ip == "" {
return nil, fmt.Errorf("Error resolving IP")
}
resp, err := makeRequest(ctx, parsedURL, httpMethod, header, body, host, ip, "", debug)
if err != nil {
return nil, err
}
return readPartialResponse(resp)
},
func(ctx context.Context, parsedURL *url.URL, host string, ip string, httpMethod string, header http.Header, body io.ReadCloser, debug bool) (*partialResponse, error) {
zap.S().With("requestID", requestID).Infoln("Attempt with fake SNI")
if ip == "" {
return nil, fmt.Errorf("Error resolving IP")
}
sni := getSNI()
resp, err := makeRequest(ctx, parsedURL, httpMethod, header, body, host, ip, sni, debug)
if err != nil {
return nil, err
}
return readPartialResponse(resp)
},
func(ctx context.Context, parsedURL *url.URL, host string, ip string, httpMethod string, header http.Header, body io.ReadCloser, debug bool) (*partialResponse, error) {
zap.S().With("requestID", requestID).Infoln("Attempt with CDN account:", host)
if ip == "" || host == "" {
return nil, fmt.Errorf("Error retrieving node")
}
originalURL := parsedURL.Scheme + "://" + parsedURL.Hostname() + parsedURL.RequestURI()
zap.S().With("requestID", requestID).Debugf("[method3] originalURL: %s", originalURL)
md5Hash := getMD5Hash(originalURL + config.DomainFrontingHashSuffix)
dfURL := &url.URL{
Scheme: "",
Host: "",
Path: config.DomainFrontingPathPrefix + md5Hash,
}
headerCopy := copyHeader(header)
headerCopy.Add(config.DomainFrontingOriginalURLHeader, originalURL)
sni := getSNI()
zap.S().With("requestID", requestID).Debugf("[method3] updated header: %v", headerCopy)
resp, err := makeRequest(ctx, dfURL, httpMethod, headerCopy, body, host, ip, sni, debug)
if err != nil {
return nil, err
}
return readPartialResponse(resp)
},
}
methodOrder := []int{0, 1, 2, 3, 3, 3, 3, 3}
zap.S().With("requestID", requestID).Debugf("url_.Hostname(): %s", url_.Hostname())
zap.S().With("requestID", requestID).Debugf("url_.Host(): %s", url_.Host)
host := url_.Hostname()
zap.S().With("requestID", requestID).Debugf("url_: %s", url_.String())
zap.S().With("requestID", requestID).Debugf("host: %s", host)
hostIsIP := net.ParseIP(host) != nil
zap.S().With("requestID", requestID).Debugf("hostIsIP: %v", hostIsIP)
eTldPlusOne, err := publicsuffix.EffectiveTLDPlusOne(host)
if err != nil || hostIsIP {
zap.S().With("requestID", requestID).Errorf("Error getting eTldPlusOne for host %s", host)
eTldPlusOne = host
}
zap.S().With("requestID", requestID).Debugf("eTldPlusOne: %s", eTldPlusOne)
if sliceContains(config.BlockedDomains, "*."+eTldPlusOne) || sliceContains(config.BlockedDomains, host) {
zap.S().With("requestID", requestID).Debugln("SNI is in BlockedDomains, so we avoid methods that expose it")
methodOrder = []int{1, 2, 3, 3, 3, 3, 3}
}
if sliceContains(config.DomainFrontingOnlyDomains, "*."+eTldPlusOne) || sliceContains(config.DomainFrontingOnlyDomains, host) {
zap.S().With("requestID", requestID).Debugln("SNI is in DomainFrontingOnlyDomains, so we only try method 3")
methodOrder = []int{3, 3, 3, 3, 3}
}
methodDataMutex.RLock()
method_, methodDataExists := methodData[eTldPlusOne]
methodDataMutex.RUnlock()
if methodDataExists {
if rand.Float64() < config.UseExistingMethodDataChance {
zap.S().With("requestID", requestID).Debugln("methodData exists, moving matching elements to the front of methodOrder")
methodOrder = moveMatchingElementsToFront(methodOrder, method_)
} else {
zap.S().With("requestID", requestID).Debugln("methodData exists, but using default methodOrder by chance")
}
}
zap.S().With("requestID", requestID).Infoln("Method order:", methodOrder)
errCount := 0
cancels := make([]context.CancelFunc, len(methodOrder))
for orderIndex, methodIndex := range methodOrder {
go func(orderIndex int, methodIndex int) {
defer func() {
if r := recover(); r != nil {
zap.S().With("requestID", requestID).Errorf("Panic recovered in method goroutine. Error: %v", r)
errCount++
zap.S().With("requestID", requestID).Debugln("errCount:", errCount)
if errCount == len(methodOrder) {
errors <- fmt.Errorf("Panic recovered in method goroutine")
}
}
}()
ctx, cancel := context.WithCancel(context.Background())
ctx = context.WithValue(ctx, requestIDKey, requestID)
cancels[orderIndex] = cancel
time.Sleep(time.Duration(orderIndex) * config.MethodDelay)
if ctx.Err() != nil {
return
}
zap.S().With("requestID", requestID).Infof("Attempt (%d) method %d for URL %s", orderIndex, methodIndex, url_.String())
var host_ string