-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathconfig.go
682 lines (590 loc) · 20.1 KB
/
config.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
package main
import (
"crypto/tls"
"encoding/json"
"flag"
"log"
"net/http"
"net/http/cookiejar"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"time"
"github.com/dlclark/regexp2"
"github.com/pelletier/go-toml/v2"
"github.com/tidwall/jsonc"
)
type ConfigStruct struct {
CheckUpdate bool
Debug bool
Debug_CheckTorrent bool
Debug_CheckPeer bool
Interval uint32
CleanInterval uint32
UpdateInterval uint32
RestartInterval uint32
TorrentMapCleanInterval uint32
BanTime uint32
BanAllPort bool
BanIPCIDR string
BanIP6CIDR string
IgnoreEmptyPeer bool
IgnoreNoLeechersTorrent bool
IgnorePTTorrent bool
IgnoreFailureExit bool
SleepTime uint32
Timeout uint32
Proxy string
LongConnection bool
LogPath string
LogToFile bool
LogDebug bool
Listen string
ClientType string
ClientURL string
ClientUsername string
ClientPassword string
UseBasicAuth bool
UseShadowBan bool
SkipCertVerification bool
FetchFailedThreshold int
ExecCommand_FetchFailed string
ExecCommand_Run string
ExecCommand_Ban string
ExecCommand_Unban string
SyncServerURL string
SyncServerToken string
BlockList []string
BlockListURL []string
BlockListFile []string
PortBlockList []uint32
IPBlockList []string
IPBlockListURL []string
IPBlockListFile []string
IgnoreByDownloaded uint32
GenIPDat uint32
IPUploadedCheck bool
IPUpCheckInterval uint32
IPUpCheckIncrementMB uint32
IPUpCheckPerTorrentRatio float64
MaxIPPortCount uint32
BanByProgressUploaded bool
BanByPUStartMB uint32
BanByPUStartPrecent float64
BanByPUAntiErrorRatio float64
BanByRelativeProgressUploaded bool
BanByRelativePUStartMB uint32
BanByRelativePUStartPrecent float64
BanByRelativePUAntiErrorRatio float64
}
var programName = "qBittorrent-ClientBlocker"
var programVersion = "Unknown"
var programUserAgent = programName + "/" + programVersion
var shortFlag_ShowVersion bool
var longFlag_ShowVersion bool
var startDelay uint
var noChdir bool
var needRegHotKey bool
var needHideWindow bool
var needHideSystray bool
var randomStrRegexp = regexp2.MustCompile("[a-zA-Z0-9]{32}", 0)
var blockListCompiled sync.Map
var ipBlockListCompiled sync.Map
var blockListURLLastFetch int64 = 0
var ipBlockListURLLastFetch int64 = 0
var blockListFileLastMod = make(map[string]int64)
var ipBlockListFileLastMod = make(map[string]int64)
var cookieJar, _ = cookiejar.New(nil)
var lastURL = ""
var configLastMod = make(map[string]int64)
var configFilename string = "config.json"
var shortFlag_configFilename string
var longFlag_configFilename string
var additionConfigFilename string = "config_additional.json"
var shortFlag_additionConfigFilename string
var longFlag_additionConfigFilename string
var httpTransport = &http.Transport{
DisableKeepAlives: true,
ForceAttemptHTTP2: false,
MaxConnsPerHost: 32,
MaxIdleConns: 32,
MaxIdleConnsPerHost: 32,
IdleConnTimeout: 60 * time.Second,
TLSHandshakeTimeout: 12 * time.Second,
ResponseHeaderTimeout: 60 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
Proxy: GetProxy,
}
var httpClient http.Client
var httpClientExternal http.Client // 没有 Cookie.
var httpServer = http.Server{
ReadTimeout: 30,
WriteTimeout: 30,
Handler: &httpServerHandler{},
}
var config = ConfigStruct{
CheckUpdate: true,
Debug: false,
Debug_CheckTorrent: false,
Debug_CheckPeer: false,
Interval: 6,
CleanInterval: 3600,
UpdateInterval: 86400,
RestartInterval: 6,
TorrentMapCleanInterval: 60,
BanTime: 86400,
BanAllPort: false,
BanIPCIDR: "/32",
BanIP6CIDR: "/128",
IgnoreEmptyPeer: true,
IgnoreNoLeechersTorrent: false,
IgnorePTTorrent: true,
IgnoreFailureExit: false,
SleepTime: 20,
Timeout: 6,
Proxy: "Auto",
LongConnection: true,
LogPath: "logs",
LogToFile: true,
LogDebug: false,
Listen: "127.0.0.1:26262",
ClientType: "",
ClientURL: "",
ClientUsername: "",
ClientPassword: "",
UseBasicAuth: false,
UseShadowBan: true,
SkipCertVerification: false,
FetchFailedThreshold: 0,
ExecCommand_FetchFailed: "",
ExecCommand_Run: "",
ExecCommand_Ban: "",
ExecCommand_Unban: "",
SyncServerURL: "",
SyncServerToken: "",
BlockList: []string{},
BlockListURL: []string{},
BlockListFile: []string{},
PortBlockList: []uint32{},
IPBlockList: []string{},
IPBlockListURL: nil,
IPBlockListFile: nil,
IgnoreByDownloaded: 100,
GenIPDat: 0,
IPUploadedCheck: false,
IPUpCheckInterval: 300,
IPUpCheckIncrementMB: 38000,
IPUpCheckPerTorrentRatio: 3,
MaxIPPortCount: 0,
BanByProgressUploaded: false,
BanByPUStartMB: 20,
BanByPUStartPrecent: 2,
BanByPUAntiErrorRatio: 3,
BanByRelativeProgressUploaded: false,
BanByRelativePUStartMB: 20,
BanByRelativePUStartPrecent: 2,
BanByRelativePUAntiErrorRatio: 3,
}
func SetBlockListFromContent(blockListContent []string, blockListSource string) int {
setCount := 0
for index, content := range blockListContent {
content = StrTrim(ProcessRemark(content))
if content == "" {
Log("Debug-SetBlockListFromContent_Compile", GetLangText("Error-Debug-EmptyLineWithSource"), false, index, blockListSource)
continue
}
if _, exists := blockListCompiled.Load(content); exists {
continue
}
Log("Debug-SetBlockListFromContent_Compile", ":%d %s (Source: %s)", false, index, content, blockListSource)
reg, err := regexp2.Compile("(?i)"+content, 0)
if err != nil {
Log("SetBlockListFromContent_Compile", GetLangText("Error-SetBlockListFromContent_Compile"), true, index, content, blockListSource)
continue
}
reg.MatchTimeout = 50 * time.Millisecond
blockListCompiled.Store(content, reg)
setCount++
}
return setCount
}
func SetBlockListFromFile() bool {
if config.BlockListFile == nil || len(config.BlockListFile) == 0 {
return true
}
setCount := 0
for _, filePath := range config.BlockListFile {
blockListFileStat, err := os.Stat(filePath)
if err != nil {
Log("SetBlockListFromFile", GetLangText("Error-LoadFile"), false, filePath, err.Error())
return false
}
// Max 8MB.
if blockListFileStat.Size() > 8388608 {
Log("SetBlockListFromFile", GetLangText("Error-LargeFile"), true)
continue
}
fileLastMod := blockListFileStat.ModTime().Unix()
if fileLastMod == blockListFileLastMod[filePath] {
return false
}
if blockListFileLastMod[filePath] != 0 {
Log("Debug-SetBlockListFromFile", GetLangText("Debug-SetBlockListFromFile_HotReload"), false, filePath)
}
blockListContent, err := os.ReadFile(filePath)
if err != nil {
Log("SetBlockListFromFile", GetLangText("Error-LoadFile"), true, filePath, err.Error())
return false
}
blockListFileLastMod[filePath] = fileLastMod
var content []string
if filepath.Ext(filePath) == ".json" {
err = json.Unmarshal(jsonc.ToJSON(blockListContent), &content)
if err != nil {
Log("SetBlockListFromFile", GetLangText("Error-GenJSONWithID"), true, filePath, err.Error())
continue
}
} else {
content = strings.Split(string(blockListContent), "\n")
}
setCount += SetBlockListFromContent(content, filePath)
}
Log("SetBlockListFromFile", GetLangText("Success-SetBlockListFromFile"), true, setCount)
return true
}
func SetBlockListFromURL() bool {
if config.BlockListURL == nil || len(config.BlockListURL) == 0 || (blockListURLLastFetch+int64(config.UpdateInterval)) > currentTimestamp {
return true
}
blockListURLLastFetch = currentTimestamp
setCount := 0
for _, blockListURL := range config.BlockListURL {
httpStatusCode, httpHeader, blockListContent := Fetch(blockListURL, false, false, true, nil)
if httpStatusCode == 304 {
continue
}
if blockListContent == nil {
//blockListURLLastFetch -= (int64(config.UpdateInterval) + 900)
Log("SetBlockListFromURL", GetLangText("Error-FetchResponse2"), true)
continue
}
// Max 8MB.
if len(blockListContent) > 8388608 {
Log("SetBlockListFromURL", GetLangText("Error-LargeFile"), true)
continue
}
var content []string
if strings.HasSuffix(strings.ToLower(strings.Split(httpHeader.Get("Content-Type"), ";")[0]), "json") {
err := json.Unmarshal(jsonc.ToJSON(blockListContent), &content)
if err != nil {
Log("SetBlockListFromFile", GetLangText("Error-GenJSONWithID"), true, blockListURL, err.Error())
continue
}
} else {
content = strings.Split(string(blockListContent), "\n")
}
setCount += SetBlockListFromContent(content, blockListURL)
}
Log("SetBlockListFromURL", GetLangText("Success-SetBlockListFromURL"), true, setCount)
return true
}
func SetIPBlockListFromContent(ipBlockListContent []string, ipBlockListSource string) int {
setCount := 0
for index, content := range ipBlockListContent {
content = StrTrim(ProcessRemark(content))
if content == "" {
Log("Debug-SetIPBlockListFromContent_Compile", GetLangText("Error-Debug-EmptyLineWithSource"), false, index, ipBlockListSource)
continue
}
if _, exists := ipBlockListCompiled.Load(content); exists {
continue
}
Log("Debug-SetIPBlockListFromContent_Compile", ":%d %s (Source: %s)", false, index, content, ipBlockListSource)
cidr := ParseIPCIDR(content)
if cidr == nil {
Log("SetIPBlockListFromContent_Compile", GetLangText("Error-SetIPBlockListFromContent_Compile"), true, index, content, ipBlockListSource)
continue
}
ipBlockListCompiled.Store(content, cidr)
setCount++
}
return setCount
}
func SetIPBlockListFromFile() bool {
if config.IPBlockListFile == nil || len(config.IPBlockListFile) == 0 {
return true
}
setCount := 0
for _, filePath := range config.IPBlockListFile {
ipBlockListFileStat, err := os.Stat(filePath)
if err != nil {
Log("SetIPBlockListFromFile", GetLangText("Error-LoadFile"), false, filePath, err.Error())
return false
}
fileLastMod := ipBlockListFileStat.ModTime().Unix()
if fileLastMod <= ipBlockListFileLastMod[filePath] {
return true
}
if ipBlockListFileLastMod[filePath] != 0 {
Log("Debug-SetIPBlockListFromFile", GetLangText("Debug-SetIPBlockListFromFile_HotReload"), false, filePath)
}
ipBlockListFile, err := os.ReadFile(filePath)
if err != nil {
Log("SetIPBlockListFromFile", GetLangText("Error-LoadFile"), true, filePath, err.Error())
return false
}
ipBlockListFileLastMod[filePath] = fileLastMod
var content []string
if filepath.Ext(filePath) == ".json" {
err := json.Unmarshal(jsonc.ToJSON(ipBlockListFile), &content)
if err != nil {
Log("SetIPBlockListFromFile", GetLangText("Error-GenJSONWithID"), true, filePath, err.Error())
}
} else {
content = strings.Split(string(ipBlockListFile), "\n")
}
setCount += SetIPBlockListFromContent(content, filePath)
}
Log("SetIPBlockListFromFile", GetLangText("Success-SetIPBlockListFromFile"), true, setCount)
return true
}
func SetIPBlockListFromURL() bool {
if config.IPBlockListURL == nil || len(config.IPBlockListURL) == 0 || (ipBlockListURLLastFetch+int64(config.UpdateInterval)) > currentTimestamp {
return true
}
ipBlockListURLLastFetch = currentTimestamp
setCount := 0
for _, ipBlockListURL := range config.IPBlockListURL {
httpStatusCode, httpHeader, ipBlockListContent := Fetch(ipBlockListURL, false, false, true, nil)
if httpStatusCode == 304 {
continue
}
if ipBlockListContent == nil {
//ipBlockListURLLastFetch -= (int64(config.UpdateInterval) + 900)
Log("SetIPBlockListFromURL", GetLangText("Error-FetchResponse2"), true)
continue
}
if len(ipBlockListContent) > 8388608 {
Log("SetIPBlockListFromURL", GetLangText("Error-LargeFile"), true)
continue
}
var content []string
if strings.HasSuffix(httpHeader.Get("Content-Type"), "json") {
err := json.Unmarshal(jsonc.ToJSON(ipBlockListContent), &content)
if err != nil {
Log("SetIPBlockListFromURL", GetLangText("Error-GenJSONWithID"), true, ipBlockListURL, err.Error())
continue
}
} else {
content = strings.Split(string(ipBlockListContent), "\n")
}
setCount += SetIPBlockListFromContent(content, ipBlockListURL)
}
Log("SetIPBlockListFromURL", GetLangText("Success-SetIPBlockListFromURL"), true, setCount)
return true
}
func LoadConfig(filename string, notExistErr bool) int {
configFileStat, err := os.Stat(filename)
if err != nil {
notExist := os.IsNotExist(err)
if notExistErr || !notExist {
Log("Debug-LoadConfig", GetLangText("Error-LoadConfigMeta"), false, filename, err.Error())
}
if notExist {
return -5
}
return -2
}
tmpConfigLastMod := configFileStat.ModTime().Unix()
if tmpConfigLastMod <= configLastMod[filename] {
return -1
}
if configLastMod[filename] != 0 {
Log("Debug-LoadConfig", GetLangText("Debug-LoadConfig_HotReload"), false, filename)
}
configFile, err := os.ReadFile(filename)
if err != nil {
Log("LoadConfig", GetLangText("Error-LoadConfig"), true, filename, err.Error())
return -3
}
configLastMod[filename] = tmpConfigLastMod
switch filepath.Ext(strings.ToLower(filename)) {
case ".json":
if err := json.Unmarshal(jsonc.ToJSON(configFile), &config); err != nil {
Log("LoadConfig", GetLangText("Error-ParseConfig"), true, filename, err.Error())
return -4
}
case ".toml":
if err := toml.Unmarshal(configFile, &config); err != nil {
Log("LoadConfig", GetLangText("Error-ParseConfig"), true, filename, err.Error())
return -4
}
}
Log("LoadConfig", GetLangText("Success-LoadConfig"), true, filename)
return 0
}
func InitConfig() {
if config.Interval < 1 {
config.Interval = 1
}
if config.Timeout < 1 {
config.Timeout = 1
}
if config.ClientURL != "" {
config.ClientURL = strings.TrimRight(config.ClientURL, "/")
}
if config.SkipCertVerification {
httpTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
} else {
httpTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: false}
}
httpTransportExternal := httpTransport.Clone()
if config.Proxy == "Auto" {
// Aka default. 仅对外部资源使用代理.
httpTransport.Proxy = nil
httpTransportExternal.Proxy = GetProxy
} else if config.Proxy == "All" {
httpTransport.Proxy = GetProxy
httpTransportExternal.Proxy = GetProxy
} else {
httpTransport.Proxy = nil
httpTransportExternal.Proxy = nil
}
if config.LongConnection {
httpTransport.DisableKeepAlives = false
}
currentTimeout := time.Duration(config.Timeout) * time.Second
httpClient = http.Client{
Timeout: currentTimeout,
Jar: cookieJar,
Transport: httpTransport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
httpClientExternal = http.Client{
Timeout: currentTimeout,
Transport: httpTransportExternal,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
httpServer.ReadTimeout = currentTimeout
httpServer.WriteTimeout = currentTimeout
t := reflect.TypeOf(config)
v := reflect.ValueOf(config)
for k := 0; k < t.NumField(); k++ {
Log("LoadConfig_Current", "%v: %v", false, t.Field(k).Name, v.Field(k).Interface())
}
EraseSyncMap(&blockListCompiled)
blockListURLLastFetch = 0
SetBlockListFromContent(config.BlockList, "BlockList")
EraseSyncMap(&ipBlockListCompiled)
ipBlockListURLLastFetch = 0
SetIPBlockListFromContent(config.IPBlockList, "IPBlockList")
}
func LoadInitConfig(firstLoad bool) bool {
loadConfigStatus := LoadConfig(configFilename, true)
if loadConfigStatus < -1 {
Log("LoadInitConfig", GetLangText("Failed-LoadInitConfig"), true)
} else {
loadAdditionalConfigStatus := LoadConfig(additionConfigFilename, false)
if loadAdditionalConfigStatus == -5 && additionConfigFilename == "config_additional.json" {
loadAdditionalConfigStatus = LoadConfig("config/"+additionConfigFilename, false)
}
if loadConfigStatus == 0 || loadAdditionalConfigStatus == 0 {
InitConfig()
}
}
if !LoadLog() && logFile != nil {
logFile.Close()
logFile = nil
}
if firstLoad {
GetProxy(nil)
SetURLFromClient()
}
if config.ClientURL != "" {
if lastURL != config.ClientURL {
if !DetectClient() {
Log("LoadInitConfig", GetLangText("LoadInitConfig_DetectClientFailed"), true)
return false
}
if !Login() {
Log("LoadInitConfig", GetLangText("LoadInitConfig_AuthFailed"), true)
return false
}
InitClient()
SubmitBlockPeer(nil)
lastURL = config.ClientURL
}
} else {
// 重置为上次使用的 URL, 主要目的是防止热重载配置文件可能破坏首次启动后从 qBittorrent 配置文件读取的 URL.
config.ClientURL = lastURL
}
if config.UseShadowBan && TestShadowBanAPI() <= 0 {
config.UseShadowBan = false
}
if !firstLoad {
SetBlockListFromFile()
SetIPBlockListFromFile()
go SetBlockListFromURL()
go SetIPBlockListFromURL()
}
return true
}
func RegFlag() {
flag.BoolVar(&shortFlag_ShowVersion, "v", false, GetLangText("ProgramVersion"))
flag.BoolVar(&longFlag_ShowVersion, "version", false, GetLangText("ProgramVersion"))
flag.StringVar(&shortFlag_configFilename, "c", "", GetLangText("ConfigPath"))
flag.StringVar(&longFlag_configFilename, "config", "", GetLangText("ConfigPath"))
flag.StringVar(&shortFlag_additionConfigFilename, "ca", "", GetLangText("AdditionalConfigPath"))
flag.StringVar(&longFlag_additionConfigFilename, "config_additional", "", GetLangText("AdditionalConfigPath"))
flag.BoolVar(&config.Debug, "debug", false, GetLangText("DebugMode"))
flag.UintVar(&startDelay, "startdelay", 0, GetLangText("StartDelay"))
flag.BoolVar(&noChdir, "nochdir", false, GetLangText("NoChdir"))
flag.BoolVar(&needRegHotKey, "reghotkey", true, GetLangText("RegHotKey"))
flag.BoolVar(&needHideWindow, "hidewindow", false, GetLangText("HideWindow"))
flag.BoolVar(&needHideSystray, "hidesystray", false, GetLangText("HideSystray"))
flag.Parse()
}
func ShowVersion() {
Log("ShowVersion", "%s %s", false, programName, programVersion)
}
func PrepareEnv() bool {
LoadLang(GetLangCode())
RegFlag()
ShowVersion()
log.SetFlags(0)
log.SetOutput(logwriter)
if shortFlag_ShowVersion || longFlag_ShowVersion {
return false
}
if longFlag_configFilename != "" {
configFilename = longFlag_configFilename
} else if shortFlag_configFilename != "" {
configFilename = shortFlag_configFilename
}
if longFlag_additionConfigFilename != "" {
additionConfigFilename = longFlag_additionConfigFilename
} else if shortFlag_additionConfigFilename != "" {
additionConfigFilename = shortFlag_additionConfigFilename
}
path, err := os.Executable()
if err != nil {
Log("PrepareEnv", GetLangText("Error-DetectProgramPath"), false, err.Error())
return false
}
if !noChdir {
programDir := filepath.Dir(path)
if os.Chdir(programDir) == nil {
Log("PrepareEnv", GetLangText("Success-ChangeWorkingDir"), false, programDir)
LoadLang(GetLangCode())
} else {
Log("PrepareEnv", GetLangText("Failed-ChangeWorkingDir"), false, programDir)
}
}
return true
}