-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcfnat.go
More file actions
1957 lines (1714 loc) · 52 KB
/
cfnat.go
File metadata and controls
1957 lines (1714 loc) · 52 KB
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 main
import (
"bufio"
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"math/rand"
"net"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
timeout = 1 * time.Second // 超时时间
maxDuration = 2 * time.Second // 最大持续时间
baiduFakeHost = "sptest.baidu.com"
baiduUserAgent = "okhttp/3.11.0 Dalvik/2.1.0 (Linux; Build/RKQ1.200826.002) baiduboxapp/11.0.5.12 (Baidu; P1 11)"
baiduAuthToken = "482857715"
carrierMobile = "mobile"
carrierTelecom = "telecom"
carrierUnicom = "unicom"
)
var (
activeConnections int32 // 用于跟踪活跃连接的数量
validIPClientCache sync.Map
randomMu sync.Mutex
randomGenerator = rand.New(rand.NewSource(time.Now().UnixNano()))
)
var carrierDisplayNames = map[string]string{
carrierMobile: "中国移动",
carrierTelecom: "中国电信",
carrierUnicom: "中国联通",
}
var defaultCarrierResolvers = map[string][]string{
carrierMobile: {"221.131.143.69:53", "112.4.0.55:53", "211.138.180.2:53"},
carrierTelecom: {"202.96.209.133:53", "202.96.128.86:53", "202.103.24.68:53"},
carrierUnicom: {"202.106.0.20:53", "210.21.196.6:53", "221.5.88.88:53"},
}
var defaultBaiduResolvers = []string{
"223.5.5.5:53",
"223.6.6.6:53",
"119.29.29.29:53",
"180.76.76.76:53",
"114.114.114.114:53",
"1.1.1.1:53",
"8.8.8.8:53",
}
// IPManager 用于安全管理 IP 地址状态
type IPManager struct {
mu sync.RWMutex
currentIP string
ipAddresses []string
currentIndex int
allIPsChecked bool
}
func NewIPManager() *IPManager {
return &IPManager{}
}
func (m *IPManager) SetIPAddresses(ips []string) {
m.mu.Lock()
defer m.mu.Unlock()
m.ipAddresses = ips
m.currentIndex = 0
m.allIPsChecked = false
}
func (m *IPManager) GetCurrentIP() string {
m.mu.RLock()
defer m.mu.RUnlock()
return m.currentIP
}
func (m *IPManager) SetCurrentIP(ip string) {
m.mu.Lock()
defer m.mu.Unlock()
m.currentIP = ip
}
func (m *IPManager) GetIPAddresses() []string {
m.mu.RLock()
defer m.mu.RUnlock()
return m.ipAddresses
}
func (m *IPManager) IsAllIPsChecked() bool {
m.mu.RLock()
defer m.mu.RUnlock()
return m.allIPsChecked
}
func (m *IPManager) Clear() {
m.mu.Lock()
defer m.mu.Unlock()
m.ipAddresses = []string{}
m.currentIP = ""
m.currentIndex = 0
m.allIPsChecked = false
}
func (m *IPManager) switchToNextValidIP(useTLS bool, port int, domain string, code int, proxyPool *BaiduProxyPool) bool {
m.mu.Lock()
defer m.mu.Unlock()
// 尝试从当前索引的下一个 IP 开始检查
for i := m.currentIndex + 1; i < len(m.ipAddresses); i++ {
ip := m.ipAddresses[i]
// 跳过当前 IP
if ip == m.currentIP {
continue
}
if checkValidIP(ip, port, useTLS, domain, code, proxyPool) {
m.currentIP = ip
m.currentIndex = i
m.allIPsChecked = false
log.Printf("切换到新的有效 IP: %s 更新 IP 索引: %d", m.currentIP, m.currentIndex)
return true
}
}
m.allIPsChecked = true
log.Println("所有 IP 都已检查过,程序将退出")
return false
}
type result struct {
ip string // IP地址
dataCenter string // 数据中心
region string // 地区
city string // 城市
latency string // 延迟
tcpDuration time.Duration // TCP请求延迟
}
type location struct {
Iata string `json:"iata"`
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
Cca2 string `json:"cca2"`
Region string `json:"region"`
City string `json:"city"`
}
type carrierListenSpec struct {
carrier string
addr string
}
type proxyEndpoint struct {
addr string
active int32
ewmaNanos int64
failures int32
}
type BaiduProxyPool struct {
name string
endpoints []*proxyEndpoint
}
func NewBaiduProxyPool(name string, addrs []string) *BaiduProxyPool {
pool := &BaiduProxyPool{name: name}
for _, addr := range dedupeStrings(addrs) {
pool.endpoints = append(pool.endpoints, &proxyEndpoint{
addr: addr,
ewmaNanos: int64(timeout),
})
}
return pool
}
func (p *BaiduProxyPool) CacheKey() string {
if p == nil {
return "direct"
}
addrs := make([]string, 0, len(p.endpoints))
for _, endpoint := range p.endpoints {
addrs = append(addrs, endpoint.addr)
}
sort.Strings(addrs)
return p.name + "|" + strings.Join(addrs, ",")
}
func (p *BaiduProxyPool) Len() int {
if p == nil {
return 0
}
return len(p.endpoints)
}
func (p *BaiduProxyPool) Addresses() []string {
if p == nil {
return nil
}
addrs := make([]string, 0, len(p.endpoints))
for _, endpoint := range p.endpoints {
addrs = append(addrs, endpoint.addr)
}
return addrs
}
func (p *BaiduProxyPool) pick() *proxyEndpoint {
if p == nil || len(p.endpoints) == 0 {
return nil
}
if len(p.endpoints) == 1 {
return p.endpoints[0]
}
a := p.endpoints[nextRandomIntn(len(p.endpoints))]
b := p.endpoints[nextRandomIntn(len(p.endpoints))]
for b == a && len(p.endpoints) > 1 {
b = p.endpoints[nextRandomIntn(len(p.endpoints))]
}
if b.scoreNanos() < a.scoreNanos() {
return b
}
return a
}
func (p *BaiduProxyPool) Dial(ctx context.Context, targetAddr string, dialTimeout time.Duration) (net.Conn, error) {
if p == nil || len(p.endpoints) == 0 {
return nil, errors.New("百度代理池为空")
}
attempts := len(p.endpoints)
if attempts > 3 {
attempts = 3
}
var lastErr error
for i := 0; i < attempts; i++ {
endpoint := p.pick()
if endpoint == nil {
return nil, errors.New("百度代理池没有可用节点")
}
atomic.AddInt32(&endpoint.active, 1)
start := time.Now()
conn, err := dialBaiduTunnelViaNode(ctx, endpoint.addr, targetAddr, dialTimeout)
elapsed := time.Since(start)
if err != nil {
atomic.AddInt32(&endpoint.active, -1)
endpoint.recordFailure(elapsed)
lastErr = fmt.Errorf("%s: %w", endpoint.addr, err)
continue
}
endpoint.recordSuccess(elapsed)
return &trackedProxyConn{Conn: conn, endpoint: endpoint}, nil
}
return nil, lastErr
}
func (e *proxyEndpoint) scoreNanos() int64 {
ewma := atomic.LoadInt64(&e.ewmaNanos)
if ewma <= 0 {
ewma = int64(timeout)
}
active := int64(atomic.LoadInt32(&e.active))
failures := int64(atomic.LoadInt32(&e.failures))
return ewma + active*int64(50*time.Millisecond) + failures*int64(300*time.Millisecond)
}
func (e *proxyEndpoint) recordSuccess(elapsed time.Duration) {
updateEWMA(&e.ewmaNanos, elapsed)
if atomic.LoadInt32(&e.failures) > 0 {
atomic.AddInt32(&e.failures, -1)
}
}
func (e *proxyEndpoint) recordFailure(elapsed time.Duration) {
if elapsed > 0 {
updateEWMA(&e.ewmaNanos, elapsed)
}
atomic.AddInt32(&e.failures, 1)
}
type trackedProxyConn struct {
net.Conn
endpoint *proxyEndpoint
once sync.Once
}
func (c *trackedProxyConn) Close() error {
err := c.Conn.Close()
c.once.Do(func() {
atomic.AddInt32(&c.endpoint.active, -1)
})
return err
}
type targetEndpoint struct {
ip string
addr string
active int32
ewmaNanos int64
failures int32
}
type TargetPool struct {
name string
endpoints []*targetEndpoint
}
func NewTargetPool(name string, results []result, port int) *TargetPool {
pool := &TargetPool{name: name}
for _, r := range results {
pool.endpoints = append(pool.endpoints, &targetEndpoint{
ip: r.ip,
addr: net.JoinHostPort(r.ip, strconv.Itoa(port)),
ewmaNanos: int64(r.tcpDuration),
})
}
return pool
}
func (p *TargetPool) Len() int {
if p == nil {
return 0
}
return len(p.endpoints)
}
func (p *TargetPool) pick() *targetEndpoint {
if p == nil || len(p.endpoints) == 0 {
return nil
}
if len(p.endpoints) == 1 {
return p.endpoints[0]
}
a := p.endpoints[nextRandomIntn(len(p.endpoints))]
b := p.endpoints[nextRandomIntn(len(p.endpoints))]
for b == a && len(p.endpoints) > 1 {
b = p.endpoints[nextRandomIntn(len(p.endpoints))]
}
if b.scoreNanos() < a.scoreNanos() {
return b
}
return a
}
func (p *TargetPool) PickTargets(maxAttempts int) []*targetEndpoint {
if p == nil || len(p.endpoints) == 0 {
return nil
}
if maxAttempts <= 0 || maxAttempts > len(p.endpoints) {
maxAttempts = len(p.endpoints)
}
targets := make([]*targetEndpoint, 0, maxAttempts)
seen := make(map[*targetEndpoint]struct{}, maxAttempts)
for len(targets) < maxAttempts {
target := p.pick()
if target == nil {
break
}
if _, ok := seen[target]; ok {
if len(seen) == len(p.endpoints) {
break
}
continue
}
seen[target] = struct{}{}
targets = append(targets, target)
}
return targets
}
func (e *targetEndpoint) scoreNanos() int64 {
ewma := atomic.LoadInt64(&e.ewmaNanos)
if ewma <= 0 {
ewma = int64(timeout)
}
active := int64(atomic.LoadInt32(&e.active))
failures := int64(atomic.LoadInt32(&e.failures))
return ewma + active*int64(50*time.Millisecond) + failures*int64(300*time.Millisecond)
}
func (e *targetEndpoint) recordSuccess(elapsed time.Duration) {
updateEWMA(&e.ewmaNanos, elapsed)
if atomic.LoadInt32(&e.failures) > 0 {
atomic.AddInt32(&e.failures, -1)
}
}
func (e *targetEndpoint) recordFailure(elapsed time.Duration) {
if elapsed > 0 {
updateEWMA(&e.ewmaNanos, elapsed)
}
atomic.AddInt32(&e.failures, 1)
}
func updateEWMA(dst *int64, sample time.Duration) {
if sample <= 0 {
return
}
sampleNanos := int64(sample)
for {
old := atomic.LoadInt64(dst)
next := sampleNanos
if old > 0 {
next = (old*7 + sampleNanos) / 8
}
if atomic.CompareAndSwapInt64(dst, old, next) {
return
}
}
}
func main() {
localAddr := flag.String("addr", "0.0.0.0:1234", "本地监听的 IP 和端口")
code := flag.Int("code", 200, "HTTP/HTTPS 响应状态码")
coloFilter := flag.String("colo", "", "筛选数据中心例如 HKG,SJC,LAX (多个数据中心用逗号隔开,留空则忽略匹配)")
Delay := flag.Int("delay", 300, "有效延迟(毫秒),超过此延迟将断开连接")
domain := flag.String("domain", "cloudflaremirrors.com/debian", "响应状态码检查的域名地址")
ipCount := flag.Int("ipnum", 20, "提取的有效IP数量")
ipsType := flag.String("ips", "4", "指定生成IPv4还是IPv6地址 (4或6)")
num := flag.Int("num", 5, "目标负载 IP 数量")
port := flag.Int("port", 443, "转发的目标端口")
random := flag.Bool("random", true, "是否随机生成IP,如果为false,则从CIDR中拆分出所有IP")
maxThreads := flag.Int("task", 100, "并发请求最大协程数")
useTLS := flag.Bool("tls", true, "是否为 TLS 端口")
useBaiduProxy := flag.Bool("baidu-proxy", true, "是否启用固定百度前置代理")
baiduDomain := flag.String("baidu-domain", "cloudnproxy.baidu.com", "百度前置代理域名")
baiduPort := flag.Int("baidu-port", 443, "百度前置代理端口")
baiduScanTarget := flag.String("baidu-scan-target", "myip.ipip.net:80", "扫描百度代理IP池时用于 CONNECT 的目标")
baiduIPCount := flag.Int("baidu-ipnum", 12, "每个运营商保留的百度代理IP数量")
carrierListens := flag.String("carrier-listens", "", "按运营商启动多个监听端口,例如 mobile=0.0.0.0:1234,telecom=0.0.0.0:1235,unicom=0.0.0.0:1236")
carrierResolvers := flag.String("carrier-resolvers", "", "额外用于聚合解析百度代理域名的DNS,例如 mobile=1.1.1.1:53|2.2.2.2:53,telecom=...,unicom=...")
flag.Parse()
if *carrierListens != "" {
specs, err := parseCarrierListens(*carrierListens)
if err != nil {
log.Fatalf("解析 -carrier-listens 失败: %v", err)
}
resolvers, err := parseCarrierResolvers(*carrierResolvers)
if err != nil {
log.Fatalf("解析 -carrier-resolvers 失败: %v", err)
}
if err := runCarrierMode(specs, resolvers, *baiduDomain, *baiduPort, *baiduScanTarget, *baiduIPCount, *code, *coloFilter, *Delay, *domain, *ipCount, *ipsType, *num, *port, *random, *maxThreads, *useTLS, *useBaiduProxy); err != nil {
log.Fatalf("运营商分池模式失败: %v", err)
}
return
}
// 创建 IP 管理器
ipManager := NewIPManager()
var defaultProxyPool *BaiduProxyPool
if *useBaiduProxy {
defaultProxyPool = NewBaiduProxyPool("default", []string{ensureHostPort(*baiduDomain, *baiduPort)})
}
// 启动 TCP 监听
listener, err := net.Listen("tcp", *localAddr)
if err != nil {
log.Fatalf("无法监听 %s: %v", *localAddr, err)
}
defer listener.Close()
if defaultProxyPool != nil {
log.Printf("百度前置代理已启用: %s", strings.Join(defaultProxyPool.Addresses(), ","))
} else {
log.Printf("百度前置代理已关闭,使用直连拨号")
}
log.Printf("正在监听 %s 并转发到 %d 个目标地址,有效延迟:%d ms", *localAddr, *num, *Delay)
for {
startTime := time.Now()
// 使用函数处理 locations.json,确保 defer 正确执行
locations, err := loadLocations()
if err != nil {
log.Printf("加载位置信息失败: %v", err)
time.Sleep(3 * time.Second)
continue
}
locationMap := make(map[string]location)
for _, loc := range locations {
locationMap[loc.Iata] = loc
}
var url string
var filename string
// 使用 switch 替代 if-else
switch *ipsType {
case "6":
filename = "ips-v6.txt"
url = "https://www.baipiao.eu.org/cloudflare/ips-v6"
case "4":
filename = "ips-v4.txt"
url = "https://www.baipiao.eu.org/cloudflare/ips-v4"
default:
fmt.Println("无效的IP类型。请使用 '4' 或 '6'")
return
}
var content string
// 检查本地是否有文件
if _, err = os.Stat(filename); os.IsNotExist(err) {
fmt.Printf("文件 %s 不存在,正在从 URL %s 下载数据\n", filename, url)
content, err = getURLContent(url)
if err != nil {
fmt.Println("获取URL内容出错:", err)
return
}
err = saveToFile(filename, content)
if err != nil {
fmt.Println("保存文件出错:", err)
return
}
} else {
content, err = getFileContent(filename)
if err != nil {
fmt.Println("读取本地文件出错:", err)
return
}
}
var ipList []string
if *random {
ipList = parseIPList(content)
switch *ipsType {
case "6":
ipList = getRandomIPv6s(ipList)
case "4":
ipList = getRandomIPv4s(ipList)
}
} else {
ipList, err = readIPs(filename)
if err != nil {
fmt.Println("读取IP出错:", err)
return
}
}
// 从生成的 IP 列表进行处理
results := scanIPs(ipList, locationMap, *maxThreads, defaultProxyPool)
if len(results) == 0 {
fmt.Println("未发现有效IP")
time.Sleep(3 * time.Second)
continue
}
// 应用数据中心筛选
if *coloFilter != "" {
filters := strings.Split(*coloFilter, ",")
var filteredResults []result
for _, r := range results {
for _, filter := range filters {
if strings.EqualFold(r.dataCenter, filter) {
filteredResults = append(filteredResults, r)
break
}
}
}
results = filteredResults
}
// 按 TCP 延迟排序
sort.Slice(results, func(i, j int) bool {
return results[i].tcpDuration < results[j].tcpDuration
})
// 只显示指定数量的 IP
if len(results) > *ipCount {
results = results[:*ipCount]
}
fmt.Println("IP 地址 | 数据中心 | 地区 | 城市 | 延迟")
for _, r := range results {
fmt.Printf("%s | %s | %s | %s | %s\n", r.ip, r.dataCenter, r.region, r.city, r.latency)
}
fmt.Printf("成功提取 %d 个有效IP,耗时 %d秒\n", len(results), time.Since(startTime)/time.Second)
// 设置 IP 地址列表
var ips []string
for _, r := range results {
ips = append(ips, r.ip)
}
ipManager.SetIPAddresses(ips)
// 选择一个有效 IP
currentIP := selectValidIP(ipManager, *useTLS, *port, *domain, *code, defaultProxyPool)
if currentIP == "" {
log.Printf("没有有效的 IP 可用")
continue
}
ipManager.SetCurrentIP(currentIP)
// 创建用于控制 goroutine 退出的 context
ctx, cancel := context.WithCancel(context.Background())
// 用于状态检查完成的信号
done := make(chan bool)
var loopWG sync.WaitGroup
loopWG.Add(2)
// 启动状态检查线程
go func() {
defer loopWG.Done()
statusCheck(ctx, *localAddr, *useTLS, *port, done, *domain, *code, time.Duration(*Delay)*time.Millisecond, ipManager, defaultProxyPool)
}()
// 主循环,接收连接
go func() {
defer loopWG.Done()
for {
select {
case <-ctx.Done():
log.Println("连接接受 goroutine 收到退出信号")
return
default:
// 设置接受连接的超时,以便能够检查 context
if tcpListener, ok := listener.(*net.TCPListener); ok {
tcpListener.SetDeadline(time.Now().Add(1 * time.Second))
}
conn, err := listener.Accept()
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
continue
}
if opErr, ok := err.(*net.OpError); ok && opErr.Err.Error() == "use of closed network connection" {
return
}
log.Printf("接受连接时发生错误: %v", err)
continue
}
clientAddr := conn.RemoteAddr().String()
atomic.AddInt32(&activeConnections, 1)
log.Printf("客户端来源: %s 连接建立,当前活跃连接数: %d", clientAddr, atomic.LoadInt32(&activeConnections))
currIP := ipManager.GetCurrentIP()
go handleConnection(conn, generateTargets(currIP, *port, *num), time.Duration(*Delay)*time.Millisecond, defaultProxyPool)
}
}
}()
<-done
cancel() // 取消 context,通知所有 goroutine 退出
loopWG.Wait()
// 清空 IP 地址
ipManager.Clear()
validIPClientCache = sync.Map{}
log.Println("主函数将退出当前循环,因为所有 IP 都已用尽")
}
}
func runCarrierMode(specs []carrierListenSpec, resolvers map[string][]string, baiduDomain string, baiduPort int, baiduScanTarget string, baiduIPCount int, code int, coloFilter string, delayMS int, domain string, ipCount int, ipsType string, num int, port int, random bool, maxThreads int, useTLS bool, useBaiduProxy bool) error {
locations, err := loadLocations()
if err != nil {
return fmt.Errorf("加载位置信息失败: %w", err)
}
locationMap := make(map[string]location)
for _, loc := range locations {
locationMap[loc.Iata] = loc
}
ipList, err := loadCandidateIPs(ipsType, random)
if err != nil {
return err
}
log.Printf("运营商分池模式启动,候选转发 IP 数量: %d", len(ipList))
proxyPools := make(map[string]*BaiduProxyPool)
if useBaiduProxy {
proxyPools = buildBaiduPoolsByCarrier(resolvers, baiduDomain, baiduPort, baiduScanTarget, baiduIPCount, maxThreads)
for _, spec := range specs {
if _, ok := proxyPools[spec.carrier]; !ok {
proxyPools[spec.carrier] = NewBaiduProxyPool(spec.carrier, nil)
}
}
} else {
log.Printf("百度前置代理已关闭,运营商端口将使用直连拨号")
}
var listeners []net.Listener
for _, spec := range specs {
proxyPool := proxyPools[spec.carrier]
results := scanCarrierTargets(spec.carrier, ipList, locationMap, maxThreads, proxyPool, coloFilter, ipCount)
targetPool := NewTargetPool(spec.carrier, results, port)
listener, err := net.Listen("tcp", spec.addr)
if err != nil {
for _, l := range listeners {
l.Close()
}
return fmt.Errorf("无法监听 %s(%s): %w", carrierName(spec.carrier), spec.addr, err)
}
listeners = append(listeners, listener)
log.Printf("%s 监听 %s,百度代理节点 %d 个,转发目标 %d 个", carrierName(spec.carrier), spec.addr, proxyPool.Len(), targetPool.Len())
go acceptCarrierConnections(listener, spec, targetPool, proxyPool, time.Duration(delayMS)*time.Millisecond, num)
}
select {}
}
func loadCandidateIPs(ipsType string, random bool) ([]string, error) {
var url string
var filename string
switch ipsType {
case "6":
filename = "ips-v6.txt"
url = "https://www.baipiao.eu.org/cloudflare/ips-v6"
case "4":
filename = "ips-v4.txt"
url = "https://www.baipiao.eu.org/cloudflare/ips-v4"
default:
return nil, fmt.Errorf("无效的IP类型。请使用 '4' 或 '6'")
}
var content string
var err error
if _, err = os.Stat(filename); os.IsNotExist(err) {
fmt.Printf("文件 %s 不存在,正在从 URL %s 下载数据\n", filename, url)
content, err = getURLContent(url)
if err != nil {
return nil, fmt.Errorf("获取URL内容出错: %w", err)
}
if err = saveToFile(filename, content); err != nil {
return nil, fmt.Errorf("保存文件出错: %w", err)
}
} else {
content, err = getFileContent(filename)
if err != nil {
return nil, fmt.Errorf("读取本地文件出错: %w", err)
}
}
if random {
ipList := parseIPList(content)
switch ipsType {
case "6":
return getRandomIPv6s(ipList), nil
case "4":
return getRandomIPv4s(ipList), nil
}
}
ipList, err := readIPs(filename)
if err != nil {
return nil, fmt.Errorf("读取IP出错: %w", err)
}
return ipList, nil
}
func scanCarrierTargets(carrier string, ipList []string, locationMap map[string]location, maxThreads int, proxyPool *BaiduProxyPool, coloFilter string, ipCount int) []result {
log.Printf("%s 开始扫描转发 IP,百度代理池: %s", carrierName(carrier), strings.Join(proxyPool.Addresses(), ","))
results := scanIPs(ipList, locationMap, maxThreads, proxyPool)
if len(results) == 0 {
log.Printf("%s 未发现有效转发 IP", carrierName(carrier))
return nil
}
if coloFilter != "" {
filters := strings.Split(coloFilter, ",")
var filteredResults []result
for _, r := range results {
for _, filter := range filters {
if strings.EqualFold(r.dataCenter, strings.TrimSpace(filter)) {
filteredResults = append(filteredResults, r)
break
}
}
}
results = filteredResults
}
sort.Slice(results, func(i, j int) bool {
return results[i].tcpDuration < results[j].tcpDuration
})
if ipCount > 0 && len(results) > ipCount {
results = results[:ipCount]
}
fmt.Printf("%s IP 地址 | 数据中心 | 地区 | 城市 | 延迟\n", carrierName(carrier))
for _, r := range results {
fmt.Printf("%s | %s | %s | %s | %s | %s\n", carrierName(carrier), r.ip, r.dataCenter, r.region, r.city, r.latency)
}
return results
}
func acceptCarrierConnections(listener net.Listener, spec carrierListenSpec, targetPool *TargetPool, proxyPool *BaiduProxyPool, delay time.Duration, maxAttempts int) {
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("%s 接受连接失败: %v", carrierName(spec.carrier), err)
continue
}
clientAddr := conn.RemoteAddr().String()
atomic.AddInt32(&activeConnections, 1)
log.Printf("%s 客户端来源: %s 连接建立,当前活跃连接数: %d", carrierName(spec.carrier), clientAddr, atomic.LoadInt32(&activeConnections))
go handlePoolConnection(conn, spec.carrier, targetPool, proxyPool, delay, maxAttempts)
}
}
func handlePoolConnection(conn net.Conn, carrier string, targetPool *TargetPool, proxyPool *BaiduProxyPool, delay time.Duration, maxAttempts int) {
defer func() {
clientAddr := conn.RemoteAddr().String()
atomic.AddInt32(&activeConnections, -1)
log.Printf("%s 客户端来源: %s 连接关闭,当前活跃连接数: %d", carrierName(carrier), clientAddr, atomic.LoadInt32(&activeConnections))
conn.Close()
}()
targets := targetPool.PickTargets(maxAttempts)
if len(targets) == 0 {
log.Printf("%s 没有可用转发目标,关闭客户端连接", carrierName(carrier))
return
}
var bestConn net.Conn
var bestTarget *targetEndpoint
var bestDelay time.Duration
for _, target := range targets {
atomic.AddInt32(&target.active, 1)
start := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), delay)
forwardConn, err := dialTarget(ctx, "tcp", target.addr, delay, proxyPool)
cancel()
elapsed := time.Since(start)
if err != nil {
atomic.AddInt32(&target.active, -1)
target.recordFailure(elapsed)
log.Printf("%s 连接目标 %s 失败或超时 %d ms: %v", carrierName(carrier), target.addr, delay.Milliseconds(), err)
continue
}
target.recordSuccess(elapsed)
if bestConn == nil || elapsed < bestDelay {
if bestConn != nil {
bestConn.Close()
atomic.AddInt32(&bestTarget.active, -1)
}
bestConn = forwardConn
bestTarget = target
bestDelay = elapsed
} else {
forwardConn.Close()
atomic.AddInt32(&target.active, -1)
}
}
if bestConn == nil {
log.Printf("%s 未找到符合延迟要求的连接,关闭客户端连接", carrierName(carrier))
return
}
defer atomic.AddInt32(&bestTarget.active, -1)
log.Printf("%s 选择目标: %s 延迟: %d ms", carrierName(carrier), bestTarget.addr, bestDelay.Milliseconds())
pipeConnections(conn, bestConn)
}
func buildBaiduPoolsByCarrier(extraResolvers map[string][]string, domain string, port int, scanTarget string, maxNodes int, maxThreads int) map[string]*BaiduProxyPool {
candidates := resolveBaiduProxyCandidates(domain, port, extraResolvers)
if len(candidates) == 0 {
log.Printf("没有解析到任何百度代理 IP")
return nil
}
grouped := make(map[string][]string)
for _, addr := range candidates {
host, _, err := net.SplitHostPort(addr)
if err != nil {
log.Printf("跳过无效百度代理地址 %s: %v", addr, err)
continue
}
carrier, asn, asName, err := classifyCarrierByIP(host)
if err != nil {
log.Printf("百度代理候选归属未知: %s: %v", addr, err)
continue
}
if carrier == "" {
log.Printf("百度代理候选未归入三大运营商: %s -> AS%s %s", addr, asn, asName)
continue
}
log.Printf("百度代理候选归属: %s -> AS%s %s -> %s", addr, asn, asName, carrierName(carrier))
grouped[carrier] = append(grouped[carrier], addr)
}
pools := make(map[string]*BaiduProxyPool)
for carrier, addrs := range grouped {
addrs = dedupeStrings(addrs)
log.Printf("%s 百度代理候选池: %s", carrierName(carrier), strings.Join(addrs, ","))
scanned := scanBaiduProxyAddrs(carrier, addrs, scanTarget, timeout, maxThreads)
if maxNodes > 0 && len(scanned) > maxNodes {
scanned = scanned[:maxNodes]
}
if len(scanned) == 0 {
log.Printf("%s 没有扫描到可用百度代理 IP", carrierName(carrier))
continue
}
log.Printf("%s 百度代理可用池: %s", carrierName(carrier), strings.Join(scanned, ","))
pools[carrier] = NewBaiduProxyPool(carrier, scanned)
}
return pools
}
func resolveBaiduProxyCandidates(domain string, port int, extraResolvers map[string][]string) []string {
resolvers := collectBaiduResolvers(extraResolvers)
type lookupResult struct {
source string
ips []string
err error
}
results := make(chan lookupResult, len(resolvers)+1)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
ips, err := net.LookupHost(domain)
results <- lookupResult{source: "system", ips: ips, err: err}
}()
for _, resolverAddr := range resolvers {
wg.Add(1)
go func(addr string) {
defer wg.Done()
ips, err := lookupHostWithResolver(domain, addr)
results <- lookupResult{source: addr, ips: ips, err: err}
}(resolverAddr)
}
go func() {
wg.Wait()
close(results)
}()
var addrs []string
for result := range results {
if result.err != nil {
log.Printf("解析百度代理域名失败 resolver=%s: %v", result.source, result.err)
continue
}
var parsed []string
for _, ip := range result.ips {
if net.ParseIP(ip) == nil {
continue
}
addr := ensureHostPort(ip, port)
addrs = append(addrs, addr)
parsed = append(parsed, addr)
}
if len(parsed) > 0 {
log.Printf("解析百度代理域名成功 resolver=%s: %s", result.source, strings.Join(parsed, ","))
}
}
addrs = dedupeStrings(addrs)
sort.Strings(addrs)
log.Printf("百度代理聚合候选 IP 数量: %d", len(addrs))
return addrs
}