-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter_engine.py
More file actions
1521 lines (1343 loc) · 63 KB
/
Copy pathfilter_engine.py
File metadata and controls
1521 lines (1343 loc) · 63 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
"""
域名过滤引擎 - 支持 AdGuard Home 规则语法
拦截匹配规则的域名 DNS 请求
支持的规则语法:
||domain.com^ - 拦截 domain.com 及其所有子域名
@@||domain.com^ - 例外规则(白名单)
domain.com - 简单域名拦截
|domain.com^ - 从根开始匹配
||domain.com^$important - 重要规则(覆盖例外)
|http://domain/path - URL 前缀规则(提取域名)
/regex/ - 正则匹配域名
0.0.0.0 domain.com - hosts 格式
! / # - 注释行
"""
import os
import re
import time
import zlib
import asyncio
import logging
from typing import List, Tuple, Optional, Set, Callable, BinaryIO, TextIO
from io import BytesIO, StringIO
from pathlib import Path
from urllib.parse import urlparse
import aiohttp
logger = logging.getLogger("dns-proxy.filter")
# 规则下载最大大小(50MB)
DEFAULT_MAX_SIZE = 50 * 1024 * 1024
# 默认规则缓冲区大小(类似 Go 的 DefaultRuleBufSize)
DEFAULT_RULE_BUF_SIZE = 65536
class ParseResult:
"""规则解析结果,类似 Go 的 ParseResult"""
__slots__ = ("title", "rules_count", "checksum", "bytes_written")
def __init__(self, title: str = "", rules_count: int = 0,
checksum: int = 0, bytes_written: int = 0):
self.title = title
self.rules_count = rules_count
self.checksum = checksum
self.bytes_written = bytes_written
class AdGuardRuleParser:
"""
AdGuard 规则解析器
对标 Go: github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist.Parser
"""
ERR_HTML = "looks like the rules text contains an html, not plain text"
@staticmethod
def _looks_like_html(text: str) -> bool:
"""检测内容是否为 HTML(检查前 100 行)"""
lines = text.splitlines()[:100]
for line in lines:
stripped = line.strip()
if not stripped:
continue
if (stripped.startswith("<!") or
stripped.startswith("<html") or
stripped.startswith("<HTML") or
stripped.startswith("<head") or
stripped.startswith("<HEAD") or
stripped.startswith("<body") or
stripped.startswith("<BODY")):
return True
# 只要遇到非空规则行就停止检查
if not stripped.startswith("!") and not stripped.startswith("#"):
break
return False
@staticmethod
def _has_binary_chars(text: str) -> Tuple[bool, int, str]:
"""
检测二进制字符(仅检测真正的控制字符,不误伤中文等 Unicode)
返回: (是否检测到, 行号, 描述)
"""
for i, line in enumerate(text.splitlines(), 1):
for j, ch in enumerate(line):
code = ord(ch)
# 只检测真正的控制字节:0x00-0x08, 0x0B-0x0C, 0x0E-0x1F, 0x7F
# 不检测 > 0x7E(中文、日文等 Unicode 字符不是二进制垃圾)
if (0x00 <= code <= 0x08) or (0x0B <= code <= 0x0C) or \
(0x0E <= code <= 0x1F) or code == 0x7F:
char_desc = f"'\\x{code:02x}'"
return True, i, f"line {i}: character {j}: likely binary character {char_desc}"
return False, 0, ""
@staticmethod
def _extract_title(text: str) -> str:
"""从注释中提取标题 ! Title: xxx"""
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("! "):
# 检查 "! Title:"
# Go 代码中: ! Title: 后面跟上标题
# 也处理中文 "! 标题:"
lower = stripped.lower()
for prefix in ("! title:", "! 标题:"):
if lower.startswith(prefix):
title = stripped[len(prefix):].strip()
if title:
return title
return ""
@staticmethod
def _clean_rule_line(line: str) -> Optional[str]:
"""
清理单行规则文本
返回清理后的规则行,或 None 表示跳过
- 去除首尾空白
- 跳过空行和注释
- 跳过 cosmetic 规则
"""
line = line.strip()
if not line:
return None
# 注释: ! 或 #
if line.startswith("!") or line.startswith("#"):
return None
# cosmetic 规则: ## #@# $$
if "##" in line or "#@#" in line or "$$" in line:
return None
# etc/hosts 格式: 0.0.0.0 domain.com 或 127.0.0.1 domain.com
# 官方定义:精确匹配域名,不匹配子域名
hosts_match = re.match(
r'^(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|0\.0\.0\.0)\s+(\S+)$',
line
)
if hosts_match:
domain = hosts_match.group(1)
# 跳过带路径的 hosts 条目
if "/" not in domain:
return domain # 裸域名 → FilterRule 会做精确匹配
return line
def parse(self, text: str, buf: Optional[bytearray] = None) -> ParseResult:
"""
解析规则文本
类似 Go: parser.Parse(w, r, buf) → ParseResult
Args:
text: 原始规则文本
buf: 可选缓冲区
Returns:
ParseResult
"""
# 1. HTML 检测
if self._looks_like_html(text):
raise ValueError(self.ERR_HTML)
# 2. 二进制字符检测
has_binary, line_no, desc = self._has_binary_chars(text)
if has_binary:
raise ValueError(desc)
# 3. 提取标题
title = self._extract_title(text)
# 4. 解析并写入输出
output = StringIO()
rules_count = 0
for raw_line in text.splitlines():
cleaned = self._clean_rule_line(raw_line)
if cleaned is None:
continue
output.write(cleaned)
output.write("\n")
rules_count += 1
output_str = output.getvalue()
# 5. 计算 CRC32 checksum
checksum = zlib.crc32(output_str.encode("utf-8")) & 0xFFFFFFFF
return ParseResult(
title=title,
rules_count=rules_count,
checksum=checksum,
bytes_written=len(output_str),
)
def parse_to_text(self, text: str) -> Tuple[str, ParseResult]:
"""
解析并返回清理后的规则文本
返回: (cleaned_text, parse_result)
"""
result = self.parse(text)
# 重新生成清理后的文本
lines = []
for raw_line in text.splitlines():
cleaned = self._clean_rule_line(raw_line)
if cleaned is not None:
lines.append(cleaned)
cleaned_text = "\n".join(lines)
return cleaned_text, result
class FilterRule:
"""单条过滤规则(编译后的匹配规则)"""
__slots__ = ("pattern", "is_exception", "is_important", "is_regex", "raw", "_skip")
def __init__(self, rule_text: str):
self.raw = rule_text
self.is_exception = False
self.is_important = False
self.is_regex = False
self.pattern = rule_text
self._skip = False
self._parse()
# AdGuard 官方已知的全部 modifier 集合
# 参见: https://adguard.com/kb/general/ad-filtering/create-own-filters/
# 不在列表中的 modifier → 整条规则跳过(官方规范)
_KNOWN_MODIFIERS = {
# DNS-specific(完全支持)
'important', 'badfilter', 'client', 'denyallow', 'dnstype',
'dnsrewrite', 'ctag',
# Content-type(浏览器级别,DNS 列表中常见,安全忽略)
'third-party', 'strict-third-party', 'strict-first-party',
'script', 'image', 'stylesheet', 'object',
'xmlhttprequest', 'subdocument', 'font', 'media', 'popup',
'document', 'websocket', 'other', 'all',
'ping', 'webrtc', 'popup', 'frame', 'xhr',
'inline-font', 'inline-script',
# 条件修饰符(需要请求上下文,DNS 无法评估)
'domain', 'match-case', 'method', 'to', 'header', 'app',
# URL/内容修改
'redirect', 'redirect-rule', 'replace', 'removeparam',
'queryprune', 'removeheader', 'csp', 'permissions',
'referrerpolicy', 'urltransform', 'xmlprune', 'empty',
# 例外相关
'elemhide', 'generichide', 'specifichide', 'jsinject',
'urlblock', 'content', 'extension', 'genericblock',
# 杂项
'popunder', 'network', 'hls', 'jsonprune', 'cookie',
# 其他
'noop', 'reason',
}
# 例外规则上 DNS 级别无法评估的修饰符集合
# 这些修饰符限制了例外规则的适用范围(如仅限特定页面/请求类型),
# 但 DNS 代理无法区分请求来源和类型,所以带这些修饰符的例外规则应跳过。
_EXCEPTION_RESTRICTIVE_MODIFIERS = frozenset({
# 条件修饰符(需要页面域名/请求来源上下文)
'domain', 'third-party', 'strict-third-party', 'strict-first-party',
'denyallow', 'app', 'method', 'to', 'header', 'client', 'ctag',
# Content-type(需要请求类型信息)
'script', 'image', 'stylesheet', 'object', 'xmlhttprequest',
'subdocument', 'font', 'media', 'popup', 'document',
'websocket', 'other', 'all', 'ping', 'webrtc', 'popup',
'frame', 'xhr', 'inline-font', 'inline-script',
# match-case(DNS 大小写不敏感)
'match-case',
# URL/内容修改(DNS 级别无法修改请求/响应)
'redirect', 'redirect-rule', 'replace', 'removeparam',
'queryprune', 'removeheader', 'csp', 'permissions',
'referrerpolicy', 'urltransform', 'xmlprune', 'empty',
# 伪装/例外相关(DNS 级别无意义)
'elemhide', 'generichide', 'specifichide', 'jsinject',
'urlblock', 'content', 'extension', 'genericblock',
# 杂项限制修饰符
'popunder', 'network', 'hls', 'jsonprune', 'cookie',
})
# 拦截规则上 DNS 级别无法评估的范围限制修饰符集合
# 这些修饰符将拦截规则的适用范围限制在特定页面/应用/请求上下文中,
# 如 $domain=xxx(仅特定页面)、$app=xxx(仅特定应用)。
# DNS 代理无法评估这些条件,若不跳过会导致全局拦截 → 误拦合法域名。
# 注意:content-type 修饰符($script、$image 等)不在其中——
# 对广告域名进行全类型拦截是可接受的。
#
# 此外还包括 HTTP 级别操作修饰符(如 $cookie、$redirect 等),
# 这些修饰符表示规则的意图是修改 HTTP 请求/响应,而非 DNS 拦截。
# DNS 代理无法执行这些操作(如修改 Cookie、重定向到本地资源),
# 若在 DNS 级别应用会导致整个域名被误拦截。
_BLOCK_RESTRICTIVE_MODIFIERS = frozenset({
# 范围限制修饰符(需要请求上下文,DNS 无法评估)
'domain', # 限制到特定来源页面
'app', # 限制到特定应用
'method', # 限制到特定 HTTP 方法
'to', # 限制到特定请求目标
'header', # 限制到特定 HTTP 头
'client', # 限制到特定 DHCP 客户端
'ctag', # 限制到特定客户端标签
# ========== HTTP 级别操作修饰符 ==========
# 以下修饰符表示规则意图是修改 HTTP 请求/响应而非 DNS 拦截。
# DNS 代理无法执行这些操作,跳过以避免误拦截整个域名。
'cookie', # 修改/移除 Cookie(HTTP 响应头/请求头)
'removeparam', # 移除 URL 查询参数(HTTP 请求)
'queryprune', # $removeparam 的别名
'removeheader', # 移除 HTTP 请求/响应头
'redirect', # 重定向到本地资源(HTTP 响应)
'redirect-rule', # 条件重定向(HTTP 响应)
'replace', # 替换响应内容(HTTP 响应)
'csp', # 修改 Content-Security-Policy(HTTP 响应头)
'permissions', # 修改 Permissions-Policy(HTTP 响应头)
'referrerpolicy', # 修改 Referrer-Policy(HTTP 响应头)
'urltransform', # 修改请求 URL(HTTP 请求)
'xmlprune', # 修剪 XML 响应内容(HTTP 响应)
'empty', # 返回空响应(HTTP 响应,已弃用)
'hls', # 修改 HLS 流(HTTP 响应)
'jsonprune', # 修剪 JSON 响应内容(HTTP 响应)
'network', # 防火墙规则(IP/端口级别,非 DNS)
'mp4', # 替换为视频占位符(HTTP 响应,已弃用)
})
@staticmethod
def _validate_modifiers(modifiers_str: str) -> bool:
"""验证 modifier 是否已知,未知则跳过整条规则"""
for mod in modifiers_str.split(','):
mod = mod.strip()
# 提取 modifier 名(去掉 =value 部分)
if '=' in mod:
name = mod.split('=', 1)[0].strip()
else:
name = mod
# ~ 前缀表示排除
if name.startswith('~'):
name = name[1:]
# 允许 s@...@...@ 格式(内容替换,DNS 级别不适用,跳过规则本身)
if name == 's':
return False
if name not in FilterRule._KNOWN_MODIFIERS:
return False
return True
@staticmethod
def _pattern_to_regex(pattern: str, match_subdomains: bool = False,
exact_start: bool = False, exact_end: bool = False) -> Optional[re.Pattern]:
"""
将 AdGuard 模式转换为正则表达式
Args:
pattern: 域名模式(不含 ||、|、@@ 等前缀)
match_subdomains: 是否匹配子域名(|| 前缀)
exact_start: 是否限定开头(| 前缀)
exact_end: 是否限定结尾(后缀 |)
Returns:
编译后的 regex 或 None(pattern 无效时)
"""
if not pattern:
return None
# 处理 * 通配符:escape 其他特殊字符,* 转成 [^.]*
parts = []
i = 0
while i < len(pattern):
ch = pattern[i]
if ch == '*':
# 匹配除点号外的任意字符(不跨域名段)
parts.append('[^.]*')
elif ch in '.^$+{}[]\\()|':
parts.append('\\' + ch)
else:
parts.append(ch)
i += 1
regex_str = ''.join(parts)
# 构建完整正则
if match_subdomains:
# ||domain.com → 匹配 domain.com 和 sub.domain.com,但不匹配 notdomain.com
full = r'(^|\.)' + regex_str + r'$'
elif exact_start and exact_end:
full = r'^' + regex_str + r'$'
elif exact_start:
full = r'^' + regex_str
elif exact_end:
full = regex_str + r'$'
else:
full = regex_str + r'$'
try:
return re.compile(full, re.IGNORECASE)
except re.error:
return None
def _parse(self):
"""
解析 AdGuard 规则语法(官方规范实现)
参见: https://adguard.com/kb/general/ad-filtering/create-own-filters/
"""
text = self.raw.strip()
if not text:
self._skip = True
return
# 1. 例外规则标记
while text.startswith("@@"):
self.is_exception = True
text = text[2:]
# 2. 跳过 cosmetic 规则
if "##" in text or "#@#" in text or "$$" in text:
self._skip = True
return
# 3. 分离 $modifiers 并验证
modifiers_str = None
if "$" in text:
parts = text.rsplit("$", 1)
text = parts[0]
modifiers_str = parts[1]
if modifiers_str:
# 未知 modifier → 跳过整条规则(官方规范)
if not self._validate_modifiers(modifiers_str):
self._skip = True
return
# 检测 important 修饰符(可能在 modifier 列表任意位置)
for mod in modifiers_str.split(','):
if mod.strip() == 'important':
self.is_important = True
break
# 例外规则带有限制性修饰符(如 $domain=xxx、$third-party、$script 等)
# 则跳过该规则。DNS 代理无法评估这些修饰符的条件,
# 如果无条件应用,会导致本应有限制的例外被无限放行。
if self.is_exception:
for mod in modifiers_str.split(','):
mod = mod.strip()
if '=' in mod:
name = mod.split('=', 1)[0].strip()
else:
name = mod
if name.startswith('~'):
name = name[1:]
# 除了 $important 之外的其他修饰符都是限制性的
if name in self._EXCEPTION_RESTRICTIVE_MODIFIERS:
self._skip = True
return
# 拦截规则带范围限制修饰符(如 $domain=xxx、$app=xxx 等)
# 则跳过该规则。这些修饰符将拦截范围限制在特定页面/应用中,
# DNS 无法评估这些条件,若不跳过会导致全局拦截 → 误拦合法域名。
if not self.is_exception and not self.is_important:
for mod in modifiers_str.split(','):
mod = mod.strip()
if '=' in mod:
name = mod.split('=', 1)[0].strip()
else:
name = mod
if name.startswith('~'):
name = name[1:]
# 跳过非重要拦截规则中携带的限制性修饰符
if name in self._BLOCK_RESTRICTIVE_MODIFIERS:
logger.debug("跳过 DNS 不适用的规则: %s (修饰符: $%s)",
self.raw[:80], name)
self._skip = True
return
if not text:
self._skip = True
return
# 4. URL 前缀规则: |http(s)://domain.com/path
if text.startswith("|http://") or text.startswith("|https://"):
url_text = text[1:].rstrip("^")
if "://*" in url_text:
self._skip = True
return
try:
parsed = urlparse(url_text)
domain = parsed.hostname
if domain:
# 含路径的 URL 规则(如 |https://github.com/path^)需要 HTTP 级别匹配,
# DNS 级别无法评估路径条件,跳过以避免误拦整个域名。
if parsed.path and parsed.path not in ("/", ""):
self._skip = True
return
self.pattern = self._pattern_to_regex(domain, match_subdomains=False)
if self.pattern:
self.is_regex = True
return
except Exception as e:
logger.debug("过滤器规则解析异常(域名): %s", e)
pass
self._skip = True
return
# 5. http(s):// 开头(无 | 前缀)→ 提取域名,精确匹配
if text.startswith("http://") or text.startswith("https://"):
try:
parsed = urlparse(text)
domain = parsed.hostname
if domain:
# 含路径的 URL 规则同上,DNS 级别无法评估路径
if parsed.path and parsed.path not in ("/", ""):
self._skip = True
return
self.pattern = self._pattern_to_regex(domain, match_subdomains=False)
if self.pattern:
self.is_regex = True
return
except Exception as e:
logger.debug("过滤器规则解析异常(URL): %s", e)
pass
self._skip = True
return
# 6. ||domain.com — 匹配域名及所有子域名
if text.startswith("||"):
domain_part = text[2:]
# 含路径的 || 规则(如 ||api.bilibili.com/path^)需要 HTTP 路径匹配,
# DNS 级别无法评估路径条件,跳过以避免误拦整个域名。
if "/" in domain_part:
self._skip = True
return
domain = domain_part.rstrip("^")
# 去掉前置 *.(||*.example.com → ||example.com)
if domain.startswith("*."):
domain = domain[2:]
if domain and "." in domain:
self.pattern = self._pattern_to_regex(domain, match_subdomains=True)
if self.pattern:
self.is_regex = True
return
self._skip = True
return
# 7. | 指针语法
has_start_pipe = text.startswith("|")
has_end_pipe = text.endswith("|")
has_end_caret = text.endswith("^")
if has_start_pipe or has_end_pipe:
if has_start_pipe and has_end_pipe:
# |exact.domain.com| — 精确匹配
domain = text[1:-1].rstrip("^")
self.pattern = self._pattern_to_regex(domain, exact_start=True, exact_end=True)
elif has_start_pipe and has_end_caret:
# |domain.com^ — 精确匹配(^ 标记域名结束)
domain = text[1:-1].rstrip("^")
self.pattern = self._pattern_to_regex(domain, exact_start=True, exact_end=True)
elif has_start_pipe:
# |example — 匹配以 example 开头的域名
domain = text[1:].rstrip("^")
self.pattern = self._pattern_to_regex(domain, exact_start=True)
else:
# example.com| — 匹配以 example.com 结尾的域名
domain = text[:-1].rstrip("^")
self.pattern = self._pattern_to_regex(domain, exact_end=True)
if self.pattern:
self.is_regex = True
else:
self._skip = True
return
# 8. /regex/ 规则
if text.startswith("/") and text.endswith("/"):
regex_text = text[1:-1]
try:
self.pattern = re.compile(regex_text, re.IGNORECASE)
self.is_regex = True
except re.error:
self._skip = True
return
# 9. hosts 格式: 0.0.0.0 domain / 127.0.0.1 domain / ::1 domain
hosts_match = re.match(
r'^(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|0\.0\.0\.0)\s+(\S+)$',
text
)
if hosts_match:
domain = hosts_match.group(1)
if "/" not in domain and "." in domain:
text = domain # 去掉 IP 前缀,用裸域名做精确匹配
# 继续执行下面的普通域名规则
# 10. 普通域名规则 — 官方定义:精确匹配,不匹配子域名
clean = text.rstrip("^")
if clean:
# 纯通配符 * 会匹配所有域名,DNS 级别不应使用
if clean == '*':
self._skip = True
return
# 包含 * 通配符的普通域名
if "*" in clean:
self.pattern = self._pattern_to_regex(clean)
else:
self.pattern = self._pattern_to_regex(clean, exact_start=True, exact_end=True)
if self.pattern:
self.is_regex = True
else:
self._skip = True
else:
self._skip = True
def matches(self, domain: str) -> bool:
"""检查域名是否匹配此规则"""
try:
return bool(self.pattern.search(domain))
except Exception:
return False
def __repr__(self) -> str:
return f"FilterRule({'例外' if self.is_exception else '拦截'}: {self.raw})"
class DomainIndex:
"""
域名索引 — 按域名索引规则,支持父域名链查找。
类似 Go urlfilter 的 domain-based matching:
匹配 sub.example.com 时,按 sub.example.com → example.com → com 顺序查找。
"""
def __init__(self):
# 域名 -> 规则列表(精确域名索引)
self._by_domain: Dict[str, List[FilterRule]] = {}
# 通配/无特定域名的规则(正则、前缀后缀等)
self._pattern_rules: List[FilterRule] = []
# 已索引的域名集合(类似于 Go 的快速过滤)
self._domain_set: Set[str] = set()
self._count = 0
def add_rule(self, rule: FilterRule, index_domain: Optional[str]):
"""向索引添加一条规则"""
if index_domain:
self._by_domain.setdefault(index_domain, []).append(rule)
self._domain_set.add(index_domain)
else:
self._pattern_rules.append(rule)
self._count += 1
def match(self, domain: str) -> Optional[Tuple[FilterRule, str]]:
"""
匹配域名,返回 (匹配的规则, 匹配方式)。
按父域名链从精确到宽泛查找。
"""
# 1. 精确域名
if domain in self._by_domain:
for rule in self._by_domain[domain]:
if rule.matches(domain):
return rule, "精确域名匹配"
# 2. 父域名链 (sub.example.com → example.com → com)
parts = domain.split(".")
for i in range(1, len(parts)):
parent = ".".join(parts[i:])
if parent in self._by_domain:
for rule in self._by_domain[parent]:
if rule.matches(domain):
return rule, f"父域名匹配 ({parent})"
# 3. 通配/正则规则
for rule in self._pattern_rules:
if rule.matches(domain):
return rule, "模式匹配"
return None
def has_domain(self, domain: str) -> bool:
"""域名是否在索引中(快速检查)"""
if domain in self._domain_set:
return True
parts = domain.split(".")
for i in range(1, len(parts)):
if ".".join(parts[i:]) in self._domain_set:
return True
return False
def clear(self):
self._by_domain.clear()
self._pattern_rules.clear()
self._domain_set.clear()
self._count = 0
@property
def count(self) -> int:
return self._count
@property
def domain_count(self) -> int:
return len(self._domain_set)
class FilterEngine:
"""
域名过滤引擎(支持定时从远程更新规则)
架构类似 Go 的 DNSFilter:
- 黑名单引擎 (block_index) — 拦截匹配规则的域名
- 白名单引擎 (allow_index) — 先于黑名单检查,匹配则放行
- 重要规则 (important_rules) — 不受白名单影响
- 自定义 hosts 映射 — 类似 Windows hosts 文件,可自定义域名指向 IP
"""
def __init__(self, cache_dir: Optional[str] = None):
# 黑名单索引(Go: filteringEngine)
self._block_index = DomainIndex()
# 白名单索引(Go: filteringEngineAllow)
self._allow_index = DomainIndex()
# 重要规则不再单独保存列表,直接查索引即可
# 冗余规则列表已移除:_block_rules / _exception_rules / _important_rules
# 改为实时从索引计算 stats(见 stats 属性)
self._loaded_files: List[str] = []
self._loaded_urls: List[str] = []
self._rule_count = 0
self._title = ""
# 统一过滤结果缓存(合并原 _filter_cache + _custom_hosts_cache)
# 格式: {domain: (blocked, reason, timestamp, priority)}
# priority=True 的条目(自定义 hosts)永不淘汰
self._filter_cache: Dict[str, Tuple[bool, str, float, bool]] = {}
self._filter_cache_timeout: float = 5.0
self._filter_cache_maxsize: int = 100000 # 过滤缓存最大条目数,防止无界增长
self._update_callback: Optional[Callable] = None
# 校验和缓存(类似 Go 的 checksum)
self._file_checksums: dict = {}
self._url_checksums: dict = {}
# 缓存目录
self._cache_dir = cache_dir
# 解析器
self._parser = AdGuardRuleParser()
# 定时更新相关
self._update_task: Optional[asyncio.Task] = None
self._running = False
self._update_interval_hours = 0
self._update_files: List[str] = []
self._update_urls: List[str] = []
# ========== 自定义 hosts 映射 ==========
# 格式: {domain: [(ip, rdtype), ...]}
# 例如: {"my.dns": [("127.0.0.1", dns.rdatatype.A), ("192.168.1.1", dns.rdatatype.A)]}
self._custom_hosts: Dict[str, List[Tuple[str, int]]] = {}
self._custom_hosts_enabled = True
# 内存压力下暂停过滤缓存写入(由优化器控制)
self._cache_suspended = False
# 纯域名快速查找集合(无通配符/正则的规则)
self._plain_domains: Set[str] = set()
@property
def title(self) -> str:
return self._title
# 过滤结果缓存 TTL(秒)
FILTER_CACHE_TTL = 5.0
@staticmethod
def _extract_index_domain(rule_text: str) -> Optional[str]:
"""
从规则文本中提取域名索引键。
返回域名用于索引,或 None 表示此规则无法通过域名索引查找。
||doubleclick.net^ -> doubleclick.net
example.org -> example.org
0.0.0.0 tracker.com -> tracker.com
|http://domain/path -> domain
|domain.com^ -> domain.com
|exact.com| -> exact.com
||example.* -> None (通配符 TLD)
|prefix -> None (前缀匹配)
suffix| -> None (后缀匹配)
/regex/ -> None (正则)
"""
line = rule_text.strip()
if not line:
return None
if line.startswith("!") or line.startswith("#"):
return None
if "##" in line or "#@#" in line or "$$" in line:
return None
while line.startswith("@@"):
line = line[2:]
if "$" in line:
line = line.rsplit("$", 1)[0]
if not line:
return None
# hosts 格式
hosts_match = re.match(
r'^(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|0\.0\.0\.0)\s+(\S+)$',
line
)
if hosts_match:
domain = hosts_match.group(1)
if "." in domain and "*" not in domain and "/" not in domain:
return domain.lower()
return None
# ||domain 格式
if line.startswith("||"):
domain = line[2:]
# 含路径的 ||domain/path 规则在 _parse 中跳过,这里也不应索引
if "/" in domain:
return None
domain = domain.rstrip("^")
if domain.startswith("*."):
domain = domain[2:]
if domain and "." in domain and "*" not in domain:
return domain.lower()
return None
# |http://domain/path
if line.startswith("|http://") or line.startswith("|https://"):
url_text = line[1:].rstrip("^")
try:
parsed = urlparse(url_text)
# 含路径的 URL 规则在 _parse 中跳过,这里也不应索引
if parsed.path and parsed.path not in ("/", ""):
return None
if parsed.hostname and "." in parsed.hostname:
return parsed.hostname.lower()
except Exception as e:
logger.debug("过滤器域名提取异常(URL): %s", e)
pass
return None
# |domain^ 或 |domain| 精确匹配
if line.startswith("|") and (line.endswith("^") or line.endswith("|")):
domain = line[1:].rstrip("^|")
return domain.lower() if domain else None
# | 前缀 / 后缀 | → 不能索引
if line.startswith("|") or line.endswith("|"):
return None
# /regex/ → 不能索引
if line.startswith("/") and line.endswith("/"):
return None
# http(s)://domain
if line.startswith("http://") or line.startswith("https://"):
try:
parsed = urlparse(line)
# 含路径的 URL 规则在 _parse 中跳过,这里也不应索引
if parsed.path and parsed.path not in ("/", ""):
return None
if parsed.hostname and "." in parsed.hostname:
return parsed.hostname.lower()
except Exception as e:
logger.debug("过滤器域名提取异常(HTTP): %s", e)
pass
return None
# 普通域名
domain = line.rstrip("^").lower()
if domain and "." in domain and "*" not in domain:
return domain
return None
def _index_rule(self, rule: FilterRule, rule_text: str):
"""将单条规则加入对应的索引(不再维护冗余列表)"""
if rule.is_exception:
index_domain = self._extract_index_domain(rule_text)
self._allow_index.add_rule(rule, index_domain)
elif rule.is_important:
# 重要规则也加入黑名单索引
index_domain = self._extract_index_domain(rule_text)
self._block_index.add_rule(rule, index_domain)
else:
index_domain = self._extract_index_domain(rule_text)
self._block_index.add_rule(rule, index_domain)
# 为纯域名规则(无通配符/正则)添加快速 set-lookup
if not rule.is_regex and not rule._skip:
domain = rule_text.strip().lower().rstrip('^')
# 仅当规则是普通域名(不含 * ? 等特殊字符)
if domain and '.' in domain and '*' not in domain and '/' not in domain:
self._plain_domains.add(domain)
def _compile_rules(self, cleaned_text: str, source: str = "memory"):
"""
编译清理后的规则文本为 FilterRule 对象并建立索引
"""
count = 0
for line in cleaned_text.splitlines():
line = line.strip()
if not line:
continue
rule = FilterRule(line)
if rule._skip:
continue
self._index_rule(rule, line)
count += 1
self._rule_count += count
logger.info(
"从 %s 索引了 %d 条规则 (总: %d, 拦截索引: %d 域名, 白名单: %d 域名)",
source, count,
self._rule_count,
self._block_index.domain_count,
self._allow_index.domain_count,
)
def load_rules_from_text(self, text: str, source: str = "memory"):
"""
从文本加载规则(完整流程:解析 → 编译)
"""
try:
cleaned_text, parse_res = self._parser.parse_to_text(text)
if parse_res.rules_count > 0:
self._compile_rules(cleaned_text, source=source)
if parse_res.title and not self._title:
self._title = parse_res.title
return parse_res
except ValueError as e:
logger.error("解析 %s 失败: %s", source, e)
return ParseResult()
def load_rules_from_file(self, filepath: str) -> bool:
"""从文件加载规则"""
path = Path(filepath)
if not path.exists():
logger.warning("规则文件不存在: %s", filepath)
return False
try:
text = path.read_text(encoding="utf-8", errors="replace")
parse_res = self.load_rules_from_text(text, source=filepath)
self._loaded_files.append(filepath)
return parse_res.rules_count > 0
except Exception as e:
logger.error("读取规则文件 %s 失败: %s", filepath, e)
return False
async def _fetch_url_async(self, url: str, max_size: int = DEFAULT_MAX_SIZE,
timeout: int = 30) -> Optional[str]:
"""获取远程 URL 内容(全量模式,向下兼容)"""
try:
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=timeout),
headers={"User-Agent": "SecureDNS-Proxy/1.0"},
) as session:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=timeout)) as resp:
if resp.status != 200:
logger.error("获取 URL %s 失败: HTTP %d", url, resp.status)
return None
content_length = resp.headers.get("Content-Length")
if content_length and int(content_length) > max_size:
logger.error("URL %s 文件过大: %s bytes (限制 %d)",
url, content_length, max_size)
return None
raw = await resp.read()
if len(raw) > max_size:
logger.error("URL %s 实际大小 %d 超过限制 %d",
url, len(raw), max_size)
return None
return raw.decode("utf-8", errors="replace")
except asyncio.TimeoutError:
logger.error("获取 URL %s 超时 (%ds)", url, timeout)
return None
except Exception as e:
logger.error("从 URL %s 加载规则失败: %s", url, e)
return None
async def load_rules_from_url_async(self, url: str) -> bool:
"""
异步从远程 URL 加载规则(带流式处理,避免全量文本驻留内存)。
逐行读取并解析,不将整个文件同时加载到内存。
"""
try:
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=80),
headers={"User-Agent": "SecureDNS-Proxy/1.0"},
) as session:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=80)) as resp:
if resp.status != 200:
logger.error("获取 URL %s 失败: HTTP %d", url, resp.status)
return False
content_length = resp.headers.get("Content-Length")
if content_length and int(content_length) > DEFAULT_MAX_SIZE:
logger.error("URL %s 文件过大: %s bytes (限制 %d)",
url, content_length, DEFAULT_MAX_SIZE)
return False
# 流式逐块读取,逐行处理
total = 0
line_buffer = ""
rule_count = 0
lines_processed = 0
first_chunk = True
raw_preview = bytearray()