-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.go
More file actions
1417 lines (1347 loc) · 41.4 KB
/
Copy pathcommands.go
File metadata and controls
1417 lines (1347 loc) · 41.4 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 ipcheck
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
mrand "math/rand"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
)
var ErrUsage = errors.New("usage")
func RunIPCheck(ctx context.Context, args []string) error {
paths := newAppPaths()
sigCtrl := newSignalController()
stopSignals := installSignalHandler(sigCtrl)
defer stopSignals()
fs := flag.NewFlagSet("ip-check", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Fprintln(os.Stdout, "usage: ip-check [options] source [source ...]")
fmt.Fprintln(os.Stdout)
fmt.Fprintln(os.Stdout, "ip-check 参数")
fmt.Fprintln(os.Stdout)
fs.PrintDefaults()
}
var (
whiteList stringList
blockList stringList
preferLocs stringList
preferOrgs stringList
blockOrgs stringList
preferPorts intList
preferColo stringList
blockColo stringList
maxVT int
maxRT int
maxST int
maxBT int
port int
host string
disableRT bool
disableVT bool
disableST bool
output string
fastCheck bool
speed int
avgSpeed int
rtt int
loss int
configPath string
testURL string
verbose bool
noSave bool
dryRun bool
onlyV4 bool
onlyV6 bool
crSize int
resolveThreadNum int
disableFileCheck bool
pureMode bool
showVersion bool
)
fs.Var(&whiteList, "w", "偏好ip参数, 可重复传入, 如 -w 8 -w 9")
fs.Var(&whiteList, "white_list", "偏好ip参数, 可重复传入, 如 -white_list 8 -white_list 9")
fs.Var(&blockList, "b", "屏蔽ip参数, 可重复传入")
fs.Var(&blockList, "block_list", "屏蔽ip参数, 可重复传入")
fs.Var(&preferLocs, "pl", "偏好国家地区, 可重复传入, 如 -pl hongkong -pl japan")
fs.Var(&preferLocs, "prefer_locs", "偏好国家地区, 可重复传入")
fs.Var(&preferOrgs, "po", "偏好org, 可重复传入")
fs.Var(&preferOrgs, "prefer_orgs", "偏好org, 可重复传入")
fs.Var(&blockOrgs, "bo", "屏蔽org, 可重复传入")
fs.Var(&blockOrgs, "block_orgs", "屏蔽org, 可重复传入")
fs.Var(&preferPorts, "pp", "针对 ip:port 测试源筛选端口, 可重复传入")
fs.Var(&preferPorts, "prefer_ports", "针对 ip:port 测试源筛选端口, 可重复传入")
fs.Var(&preferColo, "pc", "偏好colo选择, 可重复传入, 如 -pc HKG -pc SJC")
fs.Var(&preferColo, "prefer_colo", "偏好colo选择, 可重复传入")
fs.Var(&blockColo, "bc", "屏蔽colo选择, 可重复传入, 如 -bc HKG -bc SJC")
fs.Var(&blockColo, "block_colo", "屏蔽colo选择, 可重复传入")
fs.IntVar(&maxVT, "lv", 0, "最大用来检测有效(valid) ip数量限制")
fs.IntVar(&maxVT, "max_vt_ip_count", 0, "最大用来检测有效(valid) ip数量限制")
fs.IntVar(&maxRT, "lr", 0, "最大用来检测rtt ip数量限制")
fs.IntVar(&maxRT, "max_rt_ip_count", 0, "最大用来检测rtt ip数量限制")
fs.IntVar(&maxST, "ls", 0, "最大用来检测下载(speed)速度的ip数量限制")
fs.IntVar(&maxST, "max_st_ip_count", 0, "最大用来检测下载(speed)速度的ip数量限制")
fs.IntVar(&maxBT, "lb", 0, "最大better ip的ip数量限制")
fs.IntVar(&maxBT, "max_bt_ip_count", 0, "最大better ip的ip数量限制")
fs.IntVar(&port, "p", 443, "用来检测的端口")
fs.IntVar(&port, "port", 443, "用来检测的端口")
fs.StringVar(&host, "H", "", "可用性域名")
fs.StringVar(&host, "host", "", "可用性域名")
fs.BoolVar(&disableRT, "dr", false, "是否禁用RTT测试")
fs.BoolVar(&disableRT, "disable_rt", false, "是否禁用RTT测试")
fs.BoolVar(&disableVT, "dv", false, "是否禁用可用性测试")
fs.BoolVar(&disableVT, "disable_vt", false, "是否禁用可用性测试")
fs.BoolVar(&disableST, "ds", false, "是否禁用速度测试")
fs.BoolVar(&disableST, "disable_st", false, "是否禁用速度测试")
fs.StringVar(&output, "o", "", "输出文件")
fs.StringVar(&output, "output", "", "输出文件")
fs.BoolVar(&fastCheck, "f", false, "是否执行快速测试")
fs.BoolVar(&fastCheck, "fast_check", false, "是否执行快速测试")
fs.IntVar(&speed, "s", 0, "期望ip的最低网速(kB/s)")
fs.IntVar(&speed, "speed", 0, "期望ip的最低网速(kB/s)")
fs.IntVar(&avgSpeed, "as", 0, "期望ip的最低平均网速(kB/s)")
fs.IntVar(&avgSpeed, "avg_speed", 0, "期望ip的最低平均网速(kB/s)")
fs.IntVar(&rtt, "r", 0, "期望的最大rtt(ms)")
fs.IntVar(&rtt, "rtt", 0, "期望的最大rtt(ms)")
fs.IntVar(&loss, "l", -1, "期望的最大丢包率")
fs.IntVar(&loss, "loss", -1, "期望的最大丢包率")
fs.StringVar(&configPath, "c", "", "配置文件")
fs.StringVar(&configPath, "config", "", "配置文件")
fs.StringVar(&testURL, "u", "", "测速地址")
fs.StringVar(&testURL, "url", "", "测速地址")
fs.BoolVar(&verbose, "v", false, "显示调试信息")
fs.BoolVar(&verbose, "verbose", false, "显示调试信息")
fs.BoolVar(&noSave, "ns", false, "是否忽略保存测速结果文件")
fs.BoolVar(&noSave, "no_save", false, "是否忽略保存测速结果文件")
fs.BoolVar(&dryRun, "dry_run", false, "是否跳过所有测试")
fs.BoolVar(&onlyV4, "4", false, "仅测试ipv4")
fs.BoolVar(&onlyV4, "only_v4", false, "仅测试ipv4")
fs.BoolVar(&onlyV6, "6", false, "仅测试ipv6")
fs.BoolVar(&onlyV6, "only_v6", false, "仅测试ipv6")
fs.IntVar(&crSize, "cs", 0, "cidr 随机抽样ip数量限制")
fs.IntVar(&crSize, "cr_size", 0, "cidr 随机抽样ip数量限制")
fs.BoolVar(&disableFileCheck, "df", false, "是否禁用可用性检测文件可用性")
fs.BoolVar(&disableFileCheck, "disable_file_check", false, "是否禁用可用性检测文件可用性")
fs.BoolVar(&pureMode, "pure_mode", false, "纯净模式, 不使用geo数据库进行ip信息补全")
fs.IntVar(&resolveThreadNum, "rs", 0, "域名解析线程数")
fs.IntVar(&resolveThreadNum, "resolve_thread_num", 0, "域名解析线程数")
fs.BoolVar(&showVersion, "version", false, "显示版本信息")
normalizedArgs := normalizeArgs(args, ipCheckArgSpec())
if err := fs.Parse(normalizedArgs); err != nil {
printIPCheckUsage()
return ErrUsage
}
if showVersion {
consolePrint(fmt.Sprintf("ip-check version %s installed in %s", version, paths.baseDir))
return nil
}
if fs.NArg() == 0 {
printIPCheckUsage()
return ErrUsage
}
configPath, err := ensureIPCheckConfig(paths, configPath)
if err != nil {
return err
}
cfg, err := loadConfig(configPath)
if err != nil {
return err
}
cfg.PureMode = pureMode
cfg.Mode = ModeIPCheck
cfg.Runtime.Verbose = verbose
if cfg.Runtime.Verbose {
cfg.Valid.PrintErr = true
cfg.RTT.PrintErr = true
cfg.Speed.PrintErr = true
}
cfg.Runtime.IPSources = uniqueStrings(fs.Args())
cfg.Runtime.WhiteList = uniqueStrings([]string(whiteList))
if len(cfg.Runtime.WhiteList) == 0 {
cfg.Runtime.BlockList = uniqueStrings([]string(blockList))
}
pcList := []string(preferColo)
bcList := []string(blockColo)
if len(pcList) > 0 && len(bcList) > 0 {
bcList = nil
}
if len(pcList) > 0 {
cfg.Valid.PreferColo = toUpperSlice(uniqueStrings(pcList))
cfg.Valid.BlockColo = nil
}
if len(bcList) > 0 {
cfg.Valid.BlockColo = toUpperSlice(uniqueStrings(bcList))
cfg.Valid.PreferColo = nil
}
if len(cfg.Valid.PreferColo) > 0 && len(cfg.Valid.BlockColo) > 0 {
cfg.Valid.BlockColo = nil
}
cfg.Runtime.PreferLocs = uniqueStrings([]string(preferLocs))
cfg.Runtime.PreferOrgs = uniqueStrings([]string(preferOrgs))
if len(cfg.Runtime.PreferOrgs) == 0 {
cfg.Runtime.BlockOrgs = uniqueStrings([]string(blockOrgs))
}
cfg.Runtime.PreferPorts = []int(preferPorts)
cfg.Valid.Enabled = !disableVT
cfg.RTT.Enabled = !disableRT
cfg.Speed.Enabled = !disableST
cfg.Runtime.DryRun = dryRun
cfg.Runtime.OnlyV4 = onlyV4
cfg.Runtime.OnlyV6 = onlyV6
cfg.IPPort = port
cfg.Valid.FileCheck = !disableFileCheck
cfg.NoSave = noSave
if host != "" {
cfg.Valid.HostName = host
}
if rtt > 0 {
cfg.RTT.MaxRTT = float64(rtt)
}
if speed > 0 {
cfg.Speed.DownloadSpeed = speed
}
if avgSpeed > 0 {
cfg.Speed.AvgDownloadSpeed = avgSpeed
}
if cfg.Speed.AvgDownloadSpeed > cfg.Speed.DownloadSpeed {
cfg.Speed.AvgDownloadSpeed = cfg.Speed.DownloadSpeed
}
if fastCheck {
cfg.Speed.FastCheck = true
}
if loss >= 0 {
cfg.RTT.MaxLoss = float64(loss)
}
if maxVT > 0 {
cfg.Valid.IPLimitCount = maxVT
}
if maxRT > 0 {
cfg.RTT.IPLimitCount = maxRT
}
if maxST > 0 {
cfg.Speed.IPLimitCount = maxST
}
if maxBT > 0 {
cfg.Speed.BetterIPLimit = maxBT
}
if crSize > 0 {
cfg.CIDRSampleIPNum = crSize
}
if resolveThreadNum > 0 {
cfg.Runtime.ResolveThreadNum = resolveThreadNum
}
if testURL != "" {
hostName, path, err := parseURLParts(testURL)
if err != nil {
return err
}
cfg.Valid.HostName = hostName
cfg.Valid.Path = path
cfg.Valid.FileURL = testURL
cfg.Speed.URL = testURL
}
if output != "" {
cfg.Runtime.OutputFile = output
} else {
cfg.Runtime.OutputFile = defaultOutputPath(cfg.Runtime.IPSources[0], cfg.IPPort)
}
if cfg.Runtime.DryRun {
consolePrint("跳过所有测试!!!")
cfg.Valid.Enabled = false
cfg.RTT.Enabled = false
cfg.Speed.Enabled = false
}
if !cfg.Valid.Enabled {
consolePrint("可用性检测已关闭")
}
if !cfg.RTT.Enabled {
consolePrint("rtt 测试已关闭")
}
if !cfg.Speed.Enabled {
consolePrint("速度测试已关闭")
}
consolePrint(fmt.Sprintf("当前配置文件为: %s", configPath))
consolePrint(fmt.Sprintf("纯净模式: %s", pyBool(cfg.PureMode)))
consolePrint(fmt.Sprintf("是否开启调试信息: %s", pyBool(cfg.Runtime.Verbose)))
consolePrint(fmt.Sprintf("测试源文件为: %s", pyStringList(cfg.Runtime.IPSources)))
if len(blockList) > 0 && len(cfg.Runtime.WhiteList) > 0 {
consolePrint("偏好参数与黑名单参数同时存在, 自动忽略黑名单参数!")
}
if len(cfg.Runtime.WhiteList) > 0 {
consolePrint("白名单参数为:", pyStringList(cfg.Runtime.WhiteList))
}
if len(cfg.Runtime.BlockList) > 0 {
consolePrint("黑名单参数为:", pyStringList(cfg.Runtime.BlockList))
}
if len(cfg.Valid.PreferColo) > 0 {
consolePrint("可用性测试优选colo 参数为:", pyStringList(cfg.Valid.PreferColo))
}
if len(cfg.Valid.BlockColo) > 0 {
consolePrint("可用性测试屏蔽colo 参数为:", pyStringList(cfg.Valid.BlockColo))
}
if len(cfg.Runtime.PreferLocs) > 0 {
consolePrint("优选地区参数为:", pyStringList(cfg.Runtime.PreferLocs))
}
if len(blockOrgs) > 0 && len(cfg.Runtime.PreferOrgs) > 0 {
consolePrint("偏好org参数与屏蔽org参数同时存在, 自动忽略屏蔽org参数!")
}
if len(cfg.Runtime.PreferOrgs) > 0 {
consolePrint("优选org 参数为:", pyStringList(cfg.Runtime.PreferOrgs))
}
if len(cfg.Runtime.BlockOrgs) > 0 {
consolePrint("屏蔽org 参数为:", pyStringList(cfg.Runtime.BlockOrgs))
}
if len(cfg.Runtime.PreferPorts) > 0 {
consolePrint("ip:port 测试源端口为:", pyIntList(cfg.Runtime.PreferPorts))
}
consolePrint(fmt.Sprintf("测试端口为: %d", cfg.IPPort))
consolePrint(fmt.Sprintf("可用性测试文件检测开关为: %s", pyBool(cfg.Valid.FileCheck)))
consolePrint(fmt.Sprintf("期望最大rtt 为: %s ms", pyFloat(cfg.RTT.MaxRTT)))
consolePrint(fmt.Sprintf("期望网速为: %d kB/s", cfg.Speed.DownloadSpeed))
consolePrint(fmt.Sprintf("期望平均网速为: %d kB/s", cfg.Speed.AvgDownloadSpeed))
if cfg.Speed.FastCheck {
consolePrint("快速测速已开启")
}
consolePrint(fmt.Sprintf("优选ip 文件为: %s", cfg.Runtime.OutputFile))
consolePrint(fmt.Sprintf("是否忽略保存测速结果到文件: %s", pyBool(cfg.NoSave || cfg.Runtime.DryRun)))
consolePrint(fmt.Sprintf("cidr 抽样ip 个数为: %d", cfg.CIDRSampleIPNum))
consolePrint(fmt.Sprintf("域名解析线程数为: %d", cfg.Runtime.ResolveThreadNum))
geoSvc, err := openGeoService(paths)
if err != nil {
return err
}
if geoSvc != nil {
defer geoSvc.Close()
}
infos, metrics, err := parseSources(ctx, cfg, geoSvc, true)
if err != nil {
return err
}
if len(infos) == 0 {
return fmt.Errorf("没有从参数中生产待测试ip 列表, 请检查参数")
}
consolePrint(fmt.Sprintf("解析ip 耗时: %s秒", pyFloat(metrics.ResolveSeconds)))
consolePrint(fmt.Sprintf("获取geo 信息耗时: %s秒", pyFloat(metrics.GeoSeconds)))
consolePrint(fmt.Sprintf("预处理ip 总计耗时: %s秒", pyFloat(metrics.TotalSeconds)))
consolePrint(fmt.Sprintf("从参数中生成了%d 个待测试ip", len(infos)))
infos = filterByPreferOrgsWithGeo(infos, cfg.Runtime.PreferOrgs, geoSvc)
infos = filterByBlockOrgsWithGeo(infos, cfg.Runtime.BlockOrgs, geoSvc)
infos = filterByLocsWithGeo(infos, cfg.Runtime.PreferLocs, geoSvc)
shuffleIPInfos(infos)
if cfg.Runtime.DryRun {
consolePrint("跳过可用性测试")
consolePrint("跳过RTT测试")
consolePrint("跳过速度测试")
printBetterIPs(infos)
return nil
}
geoCfg, _ := loadGeoConfig(paths.geoConfig)
updateChan := make(chan string, 1)
go checkGeoUpdate(ctx, paths, geoCfg, updateChan)
defer func() {
select {
case msg := <-updateChan:
consolePrint(msg)
default:
}
}()
validCtx, validCancel := context.WithCancel(ctx)
sigCtrl.setStage(stageValid, validCtx, validCancel)
passed := runValidTest(validCtx, infos, cfg, sigCtrl)
if validCtx.Err() != nil {
sigCtrl.printCache()
}
sigCtrl.clearStage()
validCancel()
if len(passed) == 0 {
consolePrint("可用性测试没有获取到可用ip, 测试停止!")
return nil
}
rttCtx, rttCancel := context.WithCancel(ctx)
sigCtrl.setStage(stageRTT, rttCtx, rttCancel)
passed = runRTTTest(rttCtx, passed, cfg, sigCtrl)
if rttCtx.Err() != nil {
sigCtrl.printCache()
}
sigCtrl.clearStage()
rttCancel()
if len(passed) == 0 {
consolePrint("rtt 测试没有获取到可用ip, 测试停止!")
return nil
}
speedCtx, speedCancel := context.WithCancel(ctx)
sigCtrl.setStage(stageSpeed, speedCtx, speedCancel)
passed = runSpeedTest(speedCtx, passed, cfg, sigCtrl)
if speedCtx.Err() != nil {
sigCtrl.printCache()
}
sigCtrl.clearStage()
speedCancel()
sigCtrl.finish()
if len(passed) == 0 {
consolePrint("下载测试没有获取到可用ip, 测试停止!")
return nil
}
sort.Slice(passed, func(i, j int) bool { return passed[i].MaxSpeed > passed[j].MaxSpeed })
printBetterIPs(passed)
if !(cfg.NoSave || cfg.Runtime.DryRun) {
if cfg.PureMode {
return writePureIPs(passed, cfg.Runtime.OutputFile)
}
return writeBetterIPs(passed, cfg.Runtime.OutputFile)
}
return nil
}
func RunIPCheckCfg(args []string) error {
paths := newAppPaths()
fs := flag.NewFlagSet("ip-check-cfg", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Fprintln(os.Stdout, "usage: ip-check-cfg [options]")
fmt.Fprintln(os.Stdout)
fmt.Fprintln(os.Stdout, "ip-check 参数配置向导")
fmt.Fprintln(os.Stdout)
fs.PrintDefaults()
}
output := fs.String("o", paths.ipCheckConfig, "")
fs.StringVar(output, "output", paths.ipCheckConfig, "参数配置文件路径")
example := fs.Bool("e", false, "")
fs.BoolVar(example, "example", false, "显示配置文件示例")
if err := fs.Parse(normalizeArgs(args, cfgArgSpec())); err != nil {
return ErrUsage
}
if *example {
fmt.Print(defaultIPCheckConfig)
return nil
}
path, err := ensureIPCheckConfig(paths, *output)
if err != nil {
return err
}
consolePrint(fmt.Sprintf("编辑配置文件 %s", path))
return openEditor(path)
}
func RunGeoInfo(ctx context.Context, args []string) error {
paths := newAppPaths()
fs := flag.NewFlagSet("igeo-info", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Fprintln(os.Stdout, "usage: igeo-info [options] ip [ip ...]")
fmt.Fprintln(os.Stdout)
fmt.Fprintln(os.Stdout, "geo-info 获取ip(s) 的归属地信息")
}
if err := fs.Parse(normalizeArgs(args, geoInfoArgSpec())); err != nil {
return ErrUsage
}
if fs.NArg() == 0 {
fs.Usage()
return ErrUsage
}
cfg := defaultConfig()
cfg.Mode = ModeGeoInfo
cfg.Runtime.IPSources = uniqueStrings(fs.Args())
svc, err := openGeoService(paths)
if err != nil {
return err
}
defer svc.Close()
infos, _, err := parseSources(ctx, cfg, svc, true)
if err != nil {
return err
}
if len(infos) == 0 {
consolePrint("请检查是否输入了有效ip(s)")
return nil
}
for _, info := range infos {
consolePrint(info.geoInfoString())
}
return nil
}
func RunGeoDownload(ctx context.Context, args []string) error {
paths := newAppPaths()
fs := flag.NewFlagSet("igeo-dl", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Fprintln(os.Stdout, "usage: igeo-dl [options]")
fmt.Fprintln(os.Stdout)
fmt.Fprintln(os.Stdout, "igeo-dl 升级/下载geo 数据库")
fmt.Fprintln(os.Stdout)
fs.PrintDefaults()
}
urlArg := fs.String("u", "", "")
fs.StringVar(urlArg, "url", "", "geo数据库下载地址, 要求结尾包含 GeoLite2-City.mmdb 或 GeoLite2-ASN.mmdb")
proxyArg := fs.String("p", "", "")
fs.StringVar(proxyArg, "proxy", "", "下载时使用的代理")
autoYes := fs.Bool("y", false, "")
fs.BoolVar(autoYes, "yes", false, "自动确认更新并下载 GEO 数据库")
if err := fs.Parse(normalizeArgs(args, geoDownloadArgSpec())); err != nil {
return ErrUsage
}
cfgPath, err := ensureGeoConfig(paths)
if err != nil {
return err
}
geoCfg, err := loadGeoConfig(cfgPath)
if err != nil {
return err
}
if *proxyArg != "" {
geoCfg.Proxy = *proxyArg
}
if *urlArg != "" {
switch {
case hasSuffixAny(*urlArg, geoCityDBName):
consolePrint("CITY 数据库下载地址:", *urlArg)
return downloadFile(ctx, *urlArg, paths.geoCityDB, geoCfg.Proxy)
case hasSuffixAny(*urlArg, geoASNDBName):
consolePrint("ASN 数据库下载地址:", *urlArg)
return downloadFile(ctx, *urlArg, paths.geoASNDB, geoCfg.Proxy)
default:
return fmt.Errorf("请输入包含%s 或 %s 的url", geoCityDBName, geoASNDBName)
}
}
return selfUpdateGeo(ctx, paths, geoCfg, *autoYes)
}
func RunGeoCfg(args []string) error {
paths := newAppPaths()
fs := flag.NewFlagSet("igeo-cfg", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Fprintln(os.Stdout, "usage: igeo-cfg [options]")
fmt.Fprintln(os.Stdout)
fmt.Fprintln(os.Stdout, "geo-cfg 编辑geo config")
fmt.Fprintln(os.Stdout)
fs.PrintDefaults()
}
example := fs.Bool("e", false, "")
fs.BoolVar(example, "example", false, "显示配置文件示例")
if err := fs.Parse(normalizeArgs(args, geoCfgArgSpec())); err != nil {
return ErrUsage
}
if *example {
fmt.Print(defaultGeoConfig)
return nil
}
path, err := ensureGeoConfig(paths)
if err != nil {
return err
}
consolePrint(fmt.Sprintf("编辑配置文件 %s", path))
return openEditor(path)
}
func RunIPFilter(ctx context.Context, args []string) error {
paths := newAppPaths()
fs := flag.NewFlagSet("ip-filter", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Fprintln(os.Stdout, "usage: ip-filter [options] source [source ...]")
fmt.Fprintln(os.Stdout)
fmt.Fprintln(os.Stdout, "ip-filter: ip 筛选工具")
fmt.Fprintln(os.Stdout)
fs.PrintDefaults()
}
var whiteList, blockList, preferLocs, preferOrgs, blockOrgs stringList
var output string
var onlyV4, onlyV6 bool
var crSize int
var resolveThreadNum int
fs.Var(&whiteList, "w", "偏好ip参数, 可重复传入")
fs.Var(&whiteList, "white_list", "偏好ip参数, 可重复传入")
fs.Var(&blockList, "b", "屏蔽ip参数, 可重复传入")
fs.Var(&blockList, "block_list", "屏蔽ip参数, 可重复传入")
fs.Var(&preferLocs, "pl", "偏好国家地区, 可重复传入")
fs.Var(&preferLocs, "prefer_locs", "偏好国家地区, 可重复传入")
fs.Var(&preferOrgs, "po", "偏好org, 可重复传入")
fs.Var(&preferOrgs, "prefer_orgs", "偏好org, 可重复传入")
fs.Var(&blockOrgs, "bo", "屏蔽org, 可重复传入")
fs.Var(&blockOrgs, "block_orgs", "屏蔽org, 可重复传入")
fs.BoolVar(&onlyV4, "4", false, "仅筛选ipv4")
fs.BoolVar(&onlyV4, "only_v4", false, "仅筛选ipv4")
fs.BoolVar(&onlyV6, "6", false, "仅筛选ipv6")
fs.BoolVar(&onlyV6, "only_v6", false, "仅筛选ipv6")
fs.IntVar(&crSize, "cs", 0, "cidr 随机抽样ip数量限制")
fs.IntVar(&crSize, "cr_size", 0, "cidr 随机抽样ip数量限制")
fs.IntVar(&resolveThreadNum, "rs", 0, "域名解析线程数")
fs.IntVar(&resolveThreadNum, "resolve_thread_num", 0, "域名解析线程数")
fs.StringVar(&output, "o", "", "输出文件")
fs.StringVar(&output, "output", "", "输出文件")
if err := fs.Parse(normalizeArgs(args, ipFilterArgSpec())); err != nil {
return ErrUsage
}
if fs.NArg() == 0 {
return ErrUsage
}
cfg := defaultConfig()
cfg.Mode = ModeIPFilter
cfg.Runtime.IPSources = uniqueStrings(fs.Args())
cfg.Runtime.WhiteList = uniqueStrings([]string(whiteList))
if len(blockList) > 0 && len(cfg.Runtime.WhiteList) > 0 {
consolePrint("偏好参数与黑名单参数同时存在, 自动忽略黑名单参数!")
}
if len(cfg.Runtime.WhiteList) == 0 {
cfg.Runtime.BlockList = uniqueStrings([]string(blockList))
}
cfg.Runtime.PreferLocs = uniqueStrings([]string(preferLocs))
if len(cfg.Runtime.WhiteList) > 0 {
consolePrint("白名单参数为:", pyStringList(cfg.Runtime.WhiteList))
}
if len(cfg.Runtime.BlockList) > 0 {
consolePrint("黑名单参数为:", pyStringList(cfg.Runtime.BlockList))
}
if len(cfg.Runtime.PreferLocs) > 0 {
consolePrint("优选地区参数为:", pyStringList(cfg.Runtime.PreferLocs))
}
cfg.Runtime.PreferOrgs = uniqueStrings([]string(preferOrgs))
if len(blockOrgs) > 0 && len(cfg.Runtime.PreferOrgs) > 0 {
consolePrint("偏好org参数与屏蔽org参数同时存在, 自动忽略屏蔽org参数!")
}
if len(cfg.Runtime.PreferOrgs) == 0 {
cfg.Runtime.BlockOrgs = uniqueStrings([]string(blockOrgs))
}
if len(cfg.Runtime.PreferOrgs) > 0 {
consolePrint("优选org 参数为:", pyStringList(cfg.Runtime.PreferOrgs))
}
if len(cfg.Runtime.BlockOrgs) > 0 {
consolePrint("屏蔽org 参数为:", pyStringList(cfg.Runtime.BlockOrgs))
}
cfg.Runtime.OnlyV4 = onlyV4
cfg.Runtime.OnlyV6 = onlyV6
if crSize > 0 {
cfg.CIDRSampleIPNum = crSize
}
if resolveThreadNum > 0 {
cfg.Runtime.ResolveThreadNum = resolveThreadNum
}
consolePrint("cidr 抽样ip 个数为:", cfg.CIDRSampleIPNum)
consolePrint("域名解析线程数为:", cfg.Runtime.ResolveThreadNum)
geoSvc, err := openGeoService(paths)
if err != nil {
return err
}
if geoSvc != nil {
defer geoSvc.Close()
}
infos, metrics, err := parseSources(ctx, cfg, geoSvc, true)
if err != nil {
return err
}
consolePrint(fmt.Sprintf("解析ip 耗时: %s秒", pyFloat(metrics.ResolveSeconds)))
consolePrint(fmt.Sprintf("获取geo 信息耗时: %s秒", pyFloat(metrics.GeoSeconds)))
consolePrint(fmt.Sprintf("预处理ip 总计耗时: %s秒", pyFloat(metrics.TotalSeconds)))
infos = filterByPreferOrgsWithGeo(infos, cfg.Runtime.PreferOrgs, geoSvc)
infos = filterByBlockOrgsWithGeo(infos, cfg.Runtime.BlockOrgs, geoSvc)
infos = filterByLocsWithGeo(infos, cfg.Runtime.PreferLocs, geoSvc)
if len(infos) == 0 {
consolePrint("未筛选出指定IP, 请检查参数!")
return nil
}
seen := map[string]struct{}{}
var ips []string
for _, info := range infos {
if _, ok := seen[info.IP]; ok {
continue
}
seen[info.IP] = struct{}{}
ips = append(ips, info.IP)
}
consolePrint(fmt.Sprintf("从筛选条件中生成了%d个ip:", len(ips)))
for _, ip := range ips {
consolePrint(ip)
}
if output != "" {
if err := os.WriteFile(output, []byte(joinLines(ips)+"\n"), 0o644); err != nil {
return err
}
consolePrint(fmt.Sprintf("筛选通过%d个ip 已导入到%s", len(ips), output))
}
return nil
}
func printBetterIPs(infos []IPInfo) {
consolePrint("优选ip 如下: ")
for _, info := range infos {
consolePrint(info.infoString())
}
}
func writeBetterIPs(infos []IPInfo, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
for _, info := range infos {
if _, err := fmt.Fprintln(file, info.fileInfoString()); err != nil {
return err
}
}
if _, err := fmt.Fprintln(file); err != nil {
return err
}
if _, err := fmt.Fprintln(file, generatedTimeDescription()); err != nil {
return err
}
consolePrint(fmt.Sprintf("测试通过%d个优选ip 已导出到 %s", len(infos), path))
return nil
}
func writePureIPs(infos []IPInfo, path string) error {
lines := make([]string, 0, len(infos))
for _, info := range infos {
lines = append(lines, info.IP)
}
if err := os.WriteFile(path, []byte(joinLines(lines)+"\n"), 0o644); err != nil {
return err
}
consolePrint(fmt.Sprintf("测试通过%d个优选ip 已导出到 %s", len(infos), path))
return nil
}
func downloadFile(ctx context.Context, rawURL, path, proxy string) error {
consolePrint("正在下载geo database ... ...")
consolePrint(fmt.Sprintf("下载代理为: %s", proxy))
client, err := newTimeoutHTTPClient(proxy, 30*time.Second)
if err != nil {
return err
}
tmpPath := path + ".part"
progress := newDownloadProgress()
var (
total int64 = -1
lastUpdate = time.Now()
)
buf := make([]byte, 64*1024)
// Retry with resume to handle flaky connections and unexpected EOFs.
const maxAttempts = 6
for attempt := 1; attempt <= maxAttempts; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
partSize, statErr := fileSize(tmpPath)
if statErr != nil {
return statErr
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return err
}
// Disable transparent gzip/deflate so Content-Length/Range math stays correct.
req.Header.Set("Accept-Encoding", "identity")
if partSize > 0 {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-", partSize))
}
resp, err := client.Do(req)
if err != nil {
if attempt == maxAttempts {
return err
}
sleepWithBackoff(ctx, attempt, 500*time.Millisecond)
continue
}
func() {
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK, http.StatusPartialContent:
case http.StatusRequestedRangeNotSatisfiable:
// Common when partSize already equals total.
_, _, totalFromCR, ok := parseContentRange(resp.Header.Get("Content-Range"))
if ok && totalFromCR > 0 && partSize >= totalFromCR {
total = totalFromCR
return
}
err = fmt.Errorf("download failed: http %d", resp.StatusCode)
return
default:
err = fmt.Errorf("download failed: http %d", resp.StatusCode)
return
}
// Determine total size if possible.
switch resp.StatusCode {
case http.StatusOK:
if partSize > 0 {
// Server ignored our Range request; restart from scratch to avoid corruption.
if truncateErr := os.Truncate(tmpPath, 0); truncateErr != nil {
err = truncateErr
return
}
partSize = 0
}
if resp.ContentLength > 0 {
total = resp.ContentLength
}
case http.StatusPartialContent:
start, _, totalFromCR, ok := parseContentRange(resp.Header.Get("Content-Range"))
if ok && start >= 0 && start != partSize {
// Mismatched resume point; restart from scratch.
if truncateErr := os.Truncate(tmpPath, 0); truncateErr != nil {
err = truncateErr
return
}
partSize = 0
total = -1
err = errors.New("resume point mismatch")
return
} else if ok && totalFromCR > 0 {
total = totalFromCR
} else if resp.ContentLength > 0 {
total = partSize + resp.ContentLength
}
}
file, openErr := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY, 0o644)
if openErr != nil {
err = openErr
return
}
defer file.Close()
if _, seekErr := file.Seek(partSize, io.SeekStart); seekErr != nil {
err = seekErr
return
}
progress.Reset(partSize)
var (
written atomic.Int64
readErrChan = make(chan error, 1)
)
written.Store(partSize)
go func() {
for {
n, readErr := resp.Body.Read(buf)
if n > 0 {
if _, writeErr := file.Write(buf[:n]); writeErr != nil {
readErrChan <- writeErr
return
}
written.Add(int64(n))
}
if readErr == nil {
continue
}
readErrChan <- readErr
return
}
}()
ticker := time.NewTicker(300 * time.Millisecond)
defer ticker.Stop()
for {
select {
case readErr := <-readErrChan:
current := written.Load()
var speed int64
if errors.Is(readErr, io.EOF) {
speed = progress.Final(current)
} else {
speed = progress.Update(current)
}
printDownloadProgress(path, current, total, speed)
lastUpdate = time.Now()
if errors.Is(readErr, io.EOF) {
goto readDone
}
// Retry on transient read errors (e.g. unexpected EOF / connection reset).
err = readErr
return
case <-ticker.C:
current := written.Load()
if time.Since(lastUpdate) < 300*time.Millisecond {
continue
}
speed := progress.Update(current)
printDownloadProgress(path, current, total, speed)
lastUpdate = time.Now()
}
}
readDone:
finalWritten := written.Load()
// If server advertised a fixed total, ensure we got everything; otherwise resume next attempt.
if total > 0 && finalWritten < total {
err = io.ErrUnexpectedEOF
return
}
// Successful completion.
speed := progress.Final(finalWritten)
printDownloadProgress(path, finalWritten, total, speed)
err = nil
}()
if err == nil {
break
}
if attempt == maxAttempts {
return err
}
sleepWithBackoff(ctx, attempt, 500*time.Millisecond)
}
// Finalize: atomic rename part file to target path.
finalSize, err := fileSize(tmpPath)
if err != nil {
return err
}
if total > 0 && finalSize != total {
return fmt.Errorf("download incomplete: got %d bytes, want %d bytes", finalSize, total)
}
_ = os.Remove(path)
if err := os.Rename(tmpPath, path); err != nil {
return err
}
consoleKeepRefreshLine()
consolePrint(fmt.Sprintf("下载geo database到%s 成功.", path))
return nil
}
func selfUpdateGeo(ctx context.Context, paths appPaths, cfg *GeoConfig, autoYes bool) error {
if cfg.DBAPIURL == "" {
return fmt.Errorf("geo config missing db_api_url")
}
consolePrint(fmt.Sprintf("请求代理为: %s", cfg.Proxy))
client, err := newTimeoutHTTPClient(cfg.Proxy, 15*time.Second)
if err != nil {
return err
}
resp, err := retryRequest(ctx, 2, 0.5, func() (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, cfg.DBAPIURL, nil)
if err != nil {
return nil, err
}
return client.Do(req)
})
if err != nil {
return err
}
defer resp.Body.Close()
var remote map[string]any
if err := json.NewDecoder(resp.Body).Decode(&remote); err != nil {
return err
}
local := loadVersionFile(paths.geoVersion)
localTag, _ := local["tag_name"].(string)
remoteTag, _ := remote["tag_name"].(string)
allowUpdate := autoYes
switch {
case len(remote) == 0:
allowUpdate = autoYes || askConfirm("检测GEO数据库更新失败, 是否强制下载GEO数据库: Y(es)/N(o)")
case localTag != remoteTag:
if localTag == "" {
localTag = "unknown"
}
if remoteTag == "" {
remoteTag = "unknown"
}
if autoYes {
consolePrint(fmt.Sprintf("检测到GEO数据库有更新: %s -> %s, 自动更新下载中... ...", localTag, remoteTag))
allowUpdate = true
} else {
allowUpdate = askConfirm(fmt.Sprintf("检测到GEO数据库有更新: %s -> %s, 是否更新: Y(es)/N(o)", localTag, remoteTag))
}
default:
if remoteTag == "" {
remoteTag = "unknown"
}
if autoYes {
consolePrint(fmt.Sprintf("检测到GEO数据库为最新: %s, 无需更新!", remoteTag))
return nil
}
allowUpdate = askConfirm(fmt.Sprintf("GEO数据库已最新: %s, 是否强制重新下载GEO数据库: Y(es)/N(o)", remoteTag))
}
if !allowUpdate {
return nil
}
consolePrint("ASN 数据库下载地址:", cfg.DBASNURL)
if err := downloadFile(ctx, cfg.DBASNURL, paths.geoASNDB, cfg.Proxy); err != nil {
return err
}
consolePrint("CITY 数据库下载地址:", cfg.DBCityURL)
if err := downloadFile(ctx, cfg.DBCityURL, paths.geoCityDB, cfg.Proxy); err != nil {
return err
}
if len(remote) == 0 {
remote = local
}
return saveVersionFile(paths.geoVersion, remote)