@jayyuen66/dsh-scrapling 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +113 -0
- package/LICENSE +1 -1
- package/README.md +249 -551
- package/README.zh-CN.md +243 -399
- package/client.js +3 -1409
- package/host.js +28 -22
- package/package.json +41 -40
- package/py/adapters.py +48 -10
- package/py/bridge.py +18 -1
- package/py/crawl.py +39 -5
- package/py/guard.py +40 -7
package/py/adapters.py
CHANGED
|
@@ -226,7 +226,7 @@ def redact_url_secrets(raw: str) -> str:
|
|
|
226
226
|
|
|
227
227
|
|
|
228
228
|
def _network_summary(
|
|
229
|
-
network: Any, #
|
|
229
|
+
network: Any, # 上游的 NetworkRecorder
|
|
230
230
|
*,
|
|
231
231
|
pattern: str | None,
|
|
232
232
|
limit: int,
|
|
@@ -394,7 +394,7 @@ def drop_data_uris(text: str, *, html: bool = False) -> str:
|
|
|
394
394
|
return "\n".join(out)
|
|
395
395
|
|
|
396
396
|
|
|
397
|
-
def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: #
|
|
397
|
+
def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: # 同上
|
|
398
398
|
"""按 ``css_selector`` 把清洗过的树收窄成若干棵子树;没给选择器就是整棵。
|
|
399
399
|
|
|
400
400
|
口径与 Scrapling 自家 ``Convertor._extract_content`` 一致:命中 0 个元素就是空表,
|
|
@@ -663,7 +663,7 @@ _DEPLOYMENT_KNOBS: tuple[tuple[str, str, type], ...] = (
|
|
|
663
663
|
)
|
|
664
664
|
|
|
665
665
|
|
|
666
|
-
def _knob_value(kind: type, value: Any) -> Any: #
|
|
666
|
+
def _knob_value(kind: type, value: Any) -> Any: # 收的是部署载荷里的任意 JSON 值
|
|
667
667
|
"""按声明的类型收下一枚部署旋钮值;类型不符给 None。
|
|
668
668
|
|
|
669
669
|
类型必须真的对得上:这一层承载的是部署表态,把字符串塞进一个整数旋钮(或反过来)时
|
|
@@ -847,6 +847,14 @@ def _capture_once(
|
|
|
847
847
|
from scrapling.fetchers import StealthySession
|
|
848
848
|
|
|
849
849
|
session_params = _session_browser_params(args)
|
|
850
|
+
# 与 _make_session 对齐:浏览器会话的代理只能在构造期给,而 _session_browser_params
|
|
851
|
+
# 按 SESSION_ONLY_KEYS 把它连同 block_webrtc 一起过滤掉了。不在这里补,配了代理的
|
|
852
|
+
# 机器上这条路径的 Chromium 会直连 —— 泄露真实出口 IP,三条浏览器路径行为不一致。
|
|
853
|
+
proxy = guard.split_proxy(guard.default_proxy())
|
|
854
|
+
if proxy is not None:
|
|
855
|
+
session_params["proxy"] = proxy
|
|
856
|
+
# 走代理时强制为真,与 _make_session 同一条理由:WebRTC 泄露的是访客真实出口 IP。
|
|
857
|
+
session_params["block_webrtc"] = bool(args.get("blockWebrtc")) or proxy is not None
|
|
850
858
|
session_params["record_requests"] = True
|
|
851
859
|
fetch_params = _browser_params(args, url, level="fetch")
|
|
852
860
|
# 会话的代理在构造期就定死了,逐次 fetch 再给一次只会被上游丢掉。
|
|
@@ -1161,6 +1169,11 @@ MAX_SESSIONS = 8
|
|
|
1161
1169
|
# 其中最多几个可以是吃内存的浏览器会话。static 只是连接池,便宜得多。
|
|
1162
1170
|
MAX_BROWSER_SESSIONS = 3
|
|
1163
1171
|
|
|
1172
|
+
# 等属主线程回结果的预算。这是**兜底**,不是抓取超时:单次调用的超时由它自己的
|
|
1173
|
+
# timeoutSeconds 管(浏览器导航可能合法地跑上几分钟),这里只负责把「线程已经不在了」
|
|
1174
|
+
# 从「调用很慢」里分出来。取 10 分钟是为了让最长的合法抓取仍先于它触发。
|
|
1175
|
+
_WORKER_RESULT_TIMEOUT_SECONDS = 600.0
|
|
1176
|
+
|
|
1164
1177
|
|
|
1165
1178
|
class _SessionWorker:
|
|
1166
1179
|
"""一个会话的**专属执行线程**:这份会话上的全部远端调用都在它上面排队执行。
|
|
@@ -1177,6 +1190,10 @@ class _SessionWorker:
|
|
|
1177
1190
|
def __init__(self) -> None:
|
|
1178
1191
|
self._jobs: "queue.SimpleQueue[tuple[Callable[[], Any], concurrent.futures.Future[Any]] | None]"
|
|
1179
1192
|
self._jobs = queue.SimpleQueue()
|
|
1193
|
+
# stop() 之后 _loop 已经取走哨兵并返回:此后投进来的任务永远排在一个没人消费的
|
|
1194
|
+
# 队列里,而 run() 的 done.result() 没有超时 —— 调用方会永久阻塞。用这个标记把
|
|
1195
|
+
# 「已停止」变成立刻可见的错误,而不是一次等不到回音的等待。
|
|
1196
|
+
self._closed = threading.Event()
|
|
1180
1197
|
self._thread = threading.Thread(target=self._loop, daemon=True, name="session-worker")
|
|
1181
1198
|
self._thread.start()
|
|
1182
1199
|
|
|
@@ -1195,19 +1212,30 @@ class _SessionWorker:
|
|
|
1195
1212
|
except BaseException as error: # noqa: BLE001 —— 任务异常必须回到调用方线程
|
|
1196
1213
|
done.set_exception(error)
|
|
1197
1214
|
|
|
1198
|
-
def run(self, fn: Callable[[], Any]) -> Any: #
|
|
1215
|
+
def run(self, fn: Callable[[], Any]) -> Any: # 会话调用的返回形态由引擎定
|
|
1199
1216
|
"""把 fn 投递到属主线程执行,并阻塞调用线程直到它结束。
|
|
1200
1217
|
|
|
1201
1218
|
:param fn: 要在属主线程上执行的调用
|
|
1202
1219
|
:returns: fn 的返回值
|
|
1220
|
+
:raises AdapterError: 这条线程已经停止,投进去也没有人会执行
|
|
1203
1221
|
:raises BaseException: fn 抛什么这里就抛什么
|
|
1204
1222
|
"""
|
|
1223
|
+
# 与 stop() 之间没有锁:检查通过之后 stop() 仍可能抢先取走哨兵。那个窗口里
|
|
1224
|
+
# put 进队列的任务确实没人消费,所以下面的 result 必须带超时兜底。
|
|
1225
|
+
if self._closed.is_set():
|
|
1226
|
+
raise AdapterError("NO_SUCH_SESSION", "session has already been closed")
|
|
1205
1227
|
done: concurrent.futures.Future[Any] = concurrent.futures.Future()
|
|
1206
1228
|
self._jobs.put((fn, done))
|
|
1207
|
-
|
|
1229
|
+
try:
|
|
1230
|
+
return done.result(timeout=_WORKER_RESULT_TIMEOUT_SECONDS)
|
|
1231
|
+
except concurrent.futures.TimeoutError:
|
|
1232
|
+
# fn 里真实的长调用(浏览器导航、大页面抓取)不该走到这里:那个预算由它自己的
|
|
1233
|
+
# 超时管。到这里说明这条线程已经不在了,继续等只会把调用方一起挂死。
|
|
1234
|
+
raise AdapterError("SESSION_CLOSED", "session worker did not answer; the session is gone") from None
|
|
1208
1235
|
|
|
1209
1236
|
def stop(self) -> None:
|
|
1210
1237
|
"""发哨兵收线程。队列里的任务会先跑完,所以 close 之后 stop 是安全的。"""
|
|
1238
|
+
self._closed.set()
|
|
1211
1239
|
self._jobs.put(None)
|
|
1212
1240
|
self._thread.join(timeout=5.0)
|
|
1213
1241
|
|
|
@@ -1369,9 +1397,15 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1369
1397
|
if abandoned:
|
|
1370
1398
|
# 构造期间已经被要求关闭(sidecar 关机走的就是 close_all_sessions):这一份刚建好的
|
|
1371
1399
|
# 会话绝不能登记 —— 登记了就没有任何人会再去关它,浏览器进程会活过 sidecar 自己。
|
|
1372
|
-
|
|
1400
|
+
abandoned_entry = {"closer": closer, "type": kind, "lock": entry_lock}
|
|
1373
1401
|
if worker is not None:
|
|
1402
|
+
# 浏览器会话的 close 必须在属主线程上跑:Playwright 的同步 API 与创建它的线程
|
|
1403
|
+
# 绑定,跨线程调用抛 greenlet 错误,而 _release_entry 会 suppress 掉它 ——
|
|
1404
|
+
# 随后 stop() 又把属主线程收掉,这个 Chromium 就再没有任何线程能关。
|
|
1405
|
+
worker.run(lambda: _release_entry(abandoned_entry))
|
|
1374
1406
|
worker.stop()
|
|
1407
|
+
else:
|
|
1408
|
+
_release_entry(abandoned_entry)
|
|
1375
1409
|
return {
|
|
1376
1410
|
"sessionId": session_id,
|
|
1377
1411
|
"sessionType": kind,
|
|
@@ -1460,7 +1494,7 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1460
1494
|
response = worker.run(lambda: session.fetch(url, **params))
|
|
1461
1495
|
except AdapterError:
|
|
1462
1496
|
raise
|
|
1463
|
-
except Exception as error:
|
|
1497
|
+
except Exception as error:
|
|
1464
1498
|
raise AdapterError("FETCH_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1465
1499
|
|
|
1466
1500
|
payload = to_payload(
|
|
@@ -1514,13 +1548,17 @@ def _close_entry(session_id: Any) -> None:
|
|
|
1514
1548
|
"""
|
|
1515
1549
|
with _SESSION_LOCK:
|
|
1516
1550
|
entry = _SESSIONS.pop(session_id, None)
|
|
1551
|
+
if entry is not None and entry.get("pending") is True:
|
|
1552
|
+
# 墓碑必须与 pop 在同一个临界区:session_open 是在 _SESSION_LOCK 里读它的。
|
|
1553
|
+
# 写在锁外会留下这个时序 —— 这里已 pop 并释放锁,构造方接着在锁内读到 False
|
|
1554
|
+
# 并把建好的会话登记回 _SESSIONS,之后才轮到写 True,那条会话就没人关了。
|
|
1555
|
+
entry["closed_while_pending"] = True
|
|
1517
1556
|
if entry is None:
|
|
1518
1557
|
return
|
|
1519
1558
|
if entry.get("pending") is True:
|
|
1520
1559
|
# 还没构造完:构造方自己会在成功时覆盖这一条,或在失败时把它摘掉。这里不能碰
|
|
1521
|
-
# closer ——
|
|
1560
|
+
# closer —— 它还不存在。但墓碑已经留下:构造方一会儿会把建好的会话登记回来,
|
|
1522
1561
|
# 那一步要看见这次关闭,否则刚建好的浏览器没有任何人会再去关它。
|
|
1523
|
-
entry["closed_while_pending"] = True
|
|
1524
1562
|
return
|
|
1525
1563
|
worker: _SessionWorker | None = entry.get("worker")
|
|
1526
1564
|
if worker is not None:
|
|
@@ -1643,7 +1681,7 @@ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
|
|
|
1643
1681
|
worker.run(lambda: session.save_state(target))
|
|
1644
1682
|
else:
|
|
1645
1683
|
worker.run(lambda: session.load_state(target))
|
|
1646
|
-
except Exception as error: #
|
|
1684
|
+
except Exception as error: # 上游的文件/JSON 错误一律翻成可路由的码
|
|
1647
1685
|
raise AdapterError("STATE_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1648
1686
|
return {"sessionId": session_id, "path": target, "saved": saving}
|
|
1649
1687
|
|
package/py/bridge.py
CHANGED
|
@@ -35,12 +35,26 @@
|
|
|
35
35
|
from __future__ import annotations
|
|
36
36
|
|
|
37
37
|
import json
|
|
38
|
+
import os
|
|
38
39
|
import sys
|
|
39
40
|
import threading
|
|
40
41
|
import time
|
|
41
42
|
import traceback
|
|
42
43
|
from typing import Any, Callable
|
|
43
44
|
|
|
45
|
+
# 协议帧与日志一律 UTF-8:宿主按 UTF-8 解码本进程的 stdout/stderr,而两者都是管道。
|
|
46
|
+
# 管道在 Windows 上默认走本地 ANSI 代码页;`LC_ALL=C` 配上 `PYTHONUTF8=0` 这类环境
|
|
47
|
+
# 也会让它们退成 ascii —— 那时 emit 里的非 ASCII 正文会抛 UnicodeEncodeError,而
|
|
48
|
+
# worker 把它当请求异常吞掉,调用方拿不到任何响应,只能等到超时。
|
|
49
|
+
# backslashreplace 兜住另一个方向:json.loads 能把 "\ud800" 解成孤立代理项,严格编码
|
|
50
|
+
# 会让整帧写不出去,替换成转义文本至少留下可读的痕迹。
|
|
51
|
+
# 用 getattr 取 reconfigure:被重定向成 io.StringIO 的流没有这个方法(测试与嵌宿主都可能
|
|
52
|
+
# 这么做),缺了它不该让整个 sidecar 起不来。
|
|
53
|
+
for _stream in (sys.stdout, sys.stderr):
|
|
54
|
+
_reconfigure = getattr(_stream, "reconfigure", None)
|
|
55
|
+
if callable(_reconfigure):
|
|
56
|
+
_reconfigure(encoding="utf-8", errors="backslashreplace")
|
|
57
|
+
|
|
44
58
|
MIN_PYTHON = (3, 14)
|
|
45
59
|
|
|
46
60
|
|
|
@@ -66,7 +80,10 @@ if _gate_message is not None:
|
|
|
66
80
|
|
|
67
81
|
|
|
68
82
|
# 让 py/ 目录里的 guard 能被 adapters 用 `from guard import install` 找到。
|
|
69
|
-
|
|
83
|
+
# 必须走 os.path:宿主传进来的 bridgePath 是 path.join(import.meta.dirname, "py", "bridge.py")
|
|
84
|
+
# 的产物,Windows 上是反斜杠分隔,按 "/" 切会得到整个文件路径,于是 adapters/guard 全都
|
|
85
|
+
# import 不到、ready 握手永远等不到。`-I` 又关掉了脚本目录自动进 sys.path,所以这一步不能省。
|
|
86
|
+
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
70
87
|
if _HERE not in sys.path:
|
|
71
88
|
sys.path.insert(0, _HERE)
|
|
72
89
|
|
package/py/crawl.py
CHANGED
|
@@ -384,12 +384,18 @@ def _is_running(entry: dict[str, Any]) -> bool:
|
|
|
384
384
|
"""这个登记条目算不算「正在跑」。
|
|
385
385
|
|
|
386
386
|
``thread`` 为 ``None`` 表示 spider 还在构造中:它已经占了并发名额,所以算在跑。
|
|
387
|
+
``thread.ident`` 为 ``None`` 是另一段窗口——线程对象已登记但还没 ``start()``。只按
|
|
388
|
+
``is_alive()`` 判会在这段窗口里把条目当成已结束:并发的 :func:`crawl_run` 少算一个名额
|
|
389
|
+
(突破并发上限)、:func:`_evict_finished_crawls` 把它当历史淘汰(之后那次 ``start()``
|
|
390
|
+
就跑在没有登记项的蜘蛛上,叫不停)、:func:`crawl_stop` 判成不在跑。
|
|
387
391
|
|
|
388
392
|
:param entry: 登记条目
|
|
389
393
|
:returns: 是否占用名额
|
|
390
394
|
"""
|
|
391
395
|
thread = entry.get("thread")
|
|
392
|
-
|
|
396
|
+
if thread is None:
|
|
397
|
+
return True
|
|
398
|
+
return thread.ident is None or thread.is_alive()
|
|
393
399
|
|
|
394
400
|
|
|
395
401
|
def _evict_finished_crawls() -> None:
|
|
@@ -461,14 +467,39 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
461
467
|
}
|
|
462
468
|
|
|
463
469
|
|
|
470
|
+
def _shrink_page(page: dict[str, Any], budget: int) -> dict[str, Any]:
|
|
471
|
+
"""把单页压到 ``budget`` 字节以内。
|
|
472
|
+
|
|
473
|
+
``maxContentChars`` 没有上界(部署侧的 ``fetchMaxOutputChars`` 只声明了 ``min(1)``),
|
|
474
|
+
所以「一页就超过回包预算」是可达的:这时 :func:`_take_pages` 若照原样把它交出去,那一帧
|
|
475
|
+
会顶过 Host 的 8 MiB 切帧线,整个 sidecar 连同正在跑的会话一起被判成坏帧拆掉。宁可回
|
|
476
|
+
一页被截断的正文,也不要拆进程。
|
|
477
|
+
|
|
478
|
+
截断量按**序列化之后**的剩余空间算:先量出除 markdown 以外的固定开销,再把 markdown
|
|
479
|
+
砍到剩下的额度。CJK 一个字在 UTF-8 里三字节,所以按字符砍之后还要复查一次字节数,
|
|
480
|
+
复查不过就继续砍,直到装得下或已砍空。
|
|
481
|
+
|
|
482
|
+
:param page: 原始页
|
|
483
|
+
:param budget: 这一页的字节预算
|
|
484
|
+
:returns: 压过的新页(不就地改原对象,state 里留全量)
|
|
485
|
+
"""
|
|
486
|
+
overhead = len(json.dumps({**page, "markdown": ""}, ensure_ascii=False).encode("utf-8"))
|
|
487
|
+
room = max(0, budget - overhead)
|
|
488
|
+
markdown = str(page.get("markdown", ""))
|
|
489
|
+
clipped = markdown[:room] + "\n\n[truncated to fit the status frame budget]"
|
|
490
|
+
while len(clipped.encode("utf-8")) > room and clipped:
|
|
491
|
+
clipped = clipped[: max(0, len(clipped) - max(1, len(clipped) // 4))]
|
|
492
|
+
return {**page, "markdown": clipped, "truncated": True}
|
|
493
|
+
|
|
494
|
+
|
|
464
495
|
def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[str, Any]], bool]:
|
|
465
496
|
"""从 ``since`` 起取一段页,按 :data:`MAX_STATUS_BYTES` 封顶。
|
|
466
497
|
|
|
467
|
-
|
|
468
|
-
|
|
498
|
+
至少回一页:单页就超预算时也回它,否则调用方永远取不到下一页,轮询变成死循环。但这一
|
|
499
|
+
页必须**压到预算之内**再回 —— 原样交出去的那一帧会顶过 Host 的 8 MiB 切帧线。
|
|
469
500
|
|
|
470
|
-
:param all_pages
|
|
471
|
-
:param since
|
|
501
|
+
:param all_pages: 活页表
|
|
502
|
+
:param since: 已经读走多少页
|
|
472
503
|
:returns: (这一段的页, 后面还有没有)
|
|
473
504
|
"""
|
|
474
505
|
if since >= len(all_pages):
|
|
@@ -477,6 +508,9 @@ def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[
|
|
|
477
508
|
spent = 0
|
|
478
509
|
for index in range(since, len(all_pages)):
|
|
479
510
|
size = len(json.dumps(all_pages[index], ensure_ascii=False).encode("utf-8"))
|
|
511
|
+
if size > MAX_STATUS_BYTES:
|
|
512
|
+
# 单页就超预算:压到预算内回它,并置 more 让调用方知道后面还有(或还有别的页)。
|
|
513
|
+
return [_shrink_page(all_pages[index], MAX_STATUS_BYTES)], index + 1 < len(all_pages)
|
|
480
514
|
if taken and spent + size > MAX_STATUS_BYTES:
|
|
481
515
|
return taken, True
|
|
482
516
|
taken.append(all_pages[index])
|
package/py/guard.py
CHANGED
|
@@ -155,7 +155,7 @@ def configure_from_env() -> None:
|
|
|
155
155
|
configure(nat64_prefixes=prefixes)
|
|
156
156
|
|
|
157
157
|
global SYNTHETIC_NETWORKS, PROXY_URL, PROXY_BYPASS, ALLOW_WRITE_METHODS, _BYPASS_ENTRIES # noqa: PLW0603 —— 启动时定一次
|
|
158
|
-
global _ENV_PROXIES, _ENV_BYPASS, _SYSTEM_PROXIES, _PAC_NOTICE #
|
|
158
|
+
global _ENV_PROXIES, _ENV_BYPASS, _SYSTEM_PROXIES, _PAC_NOTICE # 同上
|
|
159
159
|
networks: list[ipaddress.IPv4Network] = []
|
|
160
160
|
for item in os.environ.get(SYNTHETIC_RANGES_ENV, "").split(","):
|
|
161
161
|
text = item.strip()
|
|
@@ -282,7 +282,9 @@ def parse_windows_proxy(entries: dict[str, str]) -> dict[str, str]:
|
|
|
282
282
|
:param entries: 键是 ``ProxyEnable`` / ``ProxyServer`` / ``AutoConfigURL`` 的小写形式
|
|
283
283
|
:returns: 代理表
|
|
284
284
|
"""
|
|
285
|
-
|
|
285
|
+
# `reg query` 对 REG_DWORD 输出的就是十六进制(`0x1`),只有部分工具会写成十进制
|
|
286
|
+
# `1`。只认后者的话这条探测在 Windows 上永远返回空表,整条系统代理路径静默失效。
|
|
287
|
+
if entries.get("proxyenable", "").strip().lower() not in ("1", "0x1"):
|
|
286
288
|
return {}
|
|
287
289
|
raw = entries.get("proxyserver", "").strip()
|
|
288
290
|
if not raw:
|
|
@@ -470,7 +472,15 @@ def split_proxy(raw: str) -> dict[str, str] | None:
|
|
|
470
472
|
:param raw: 代理地址
|
|
471
473
|
:returns: 代理字典;地址不可用时为 None
|
|
472
474
|
"""
|
|
473
|
-
|
|
475
|
+
try:
|
|
476
|
+
parsed = urlparse(raw)
|
|
477
|
+
# 提前取一次端口:越界(`:99999`)或非数字(`:abc`)的端口在这时才抛
|
|
478
|
+
# ValueError,而下面还有几处要读 `parsed.port`。畸形方括号(`http://[::1`)
|
|
479
|
+
# 在 urlparse 里就抛。两处一并按「地址不可用」处理 —— 本函数的契约是返回
|
|
480
|
+
# None 而不是抛,调用方(configure_from_env / proxy_settings)据此如实报未配置。
|
|
481
|
+
port = parsed.port
|
|
482
|
+
except ValueError:
|
|
483
|
+
return None
|
|
474
484
|
scheme = (parsed.scheme or "").lower()
|
|
475
485
|
if scheme not in _BROWSER_PROXY_SCHEMES or not parsed.hostname:
|
|
476
486
|
return None
|
|
@@ -478,8 +488,8 @@ def split_proxy(raw: str) -> dict[str, str] | None:
|
|
|
478
488
|
# server 里得再装回去 —— 否则 `[::1]` 会被解析成端口。
|
|
479
489
|
host = parsed.hostname if ":" not in parsed.hostname else f"[{parsed.hostname}]"
|
|
480
490
|
server = f"{scheme}://{host}"
|
|
481
|
-
if
|
|
482
|
-
server = f"{server}:{
|
|
491
|
+
if port:
|
|
492
|
+
server = f"{server}:{port}"
|
|
483
493
|
return {
|
|
484
494
|
"server": server,
|
|
485
495
|
# 凭据要 percent-decode:urlparse 不解,而 Playwright 是把这对值原样塞进
|
|
@@ -537,13 +547,36 @@ def _nat64_tables() -> tuple[tuple[ipaddress.IPv6Network, int, int], ...]:
|
|
|
537
547
|
return tuple(tables)
|
|
538
548
|
|
|
539
549
|
|
|
550
|
+
def _nat64_inner_bytes(packed: bytes, offset: int) -> bytes:
|
|
551
|
+
"""按 RFC 6052 §2.2 的布局从 16 字节里取出内嵌 IPv4。
|
|
552
|
+
|
|
553
|
+
``/40``、``/48``、``/56`` 这几档的 IPv4 被第 9 个字节(下标 8 的 u 字节)从中间切断:
|
|
554
|
+
前半段在 u 之前,后半段在 u 之后,并不连续。按起点连续切 4 字节会把 u 字节当成 IPv4
|
|
555
|
+
的一位读进来、同时漏掉最后一位 —— ``/48`` 下内嵌 192.0.2.33 的地址会被读成
|
|
556
|
+
192.0.0.2,于是私网地址能被读成公网地址。
|
|
557
|
+
|
|
558
|
+
``/32`` 与 ``/64`` 的 4 字节恰好落在 u 的同一侧,按连续切本来就对;``/96`` 在最后
|
|
559
|
+
4 字节,与 u 无关。统一写法:取 5 字节窗口再剔除 u 字节,六档共用一条路径。
|
|
560
|
+
|
|
561
|
+
:param packed: IPv6 的 16 字节
|
|
562
|
+
:param offset: 内嵌 IPv4 的起始下标
|
|
563
|
+
:returns: 内嵌 IPv4 的 4 字节
|
|
564
|
+
"""
|
|
565
|
+
window = packed[offset : offset + 5]
|
|
566
|
+
return bytes(byte for index, byte in enumerate(window) if offset + index != 8)[:4]
|
|
567
|
+
|
|
568
|
+
|
|
540
569
|
def _embedded_ipv4(address: ipaddress.IPv6Address) -> ipaddress.IPv4Address | None:
|
|
541
|
-
"""若地址落在某个 NAT64 前缀里,抽出内嵌的 IPv4。
|
|
570
|
+
"""若地址落在某个 NAT64 前缀里,抽出内嵌的 IPv4。
|
|
571
|
+
|
|
572
|
+
:param address: IPv6 地址
|
|
573
|
+
:returns: 内嵌的 IPv4 地址;不落在任何前缀里时返回 ``None``
|
|
574
|
+
"""
|
|
542
575
|
packed = address.packed
|
|
543
576
|
for network, _prefixlen, offset in _nat64_tables():
|
|
544
577
|
if address not in network:
|
|
545
578
|
continue
|
|
546
|
-
return ipaddress.IPv4Address(packed
|
|
579
|
+
return ipaddress.IPv4Address(_nat64_inner_bytes(packed, offset))
|
|
547
580
|
return None
|
|
548
581
|
|
|
549
582
|
|