Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
247 lines (201 loc) · 6.81 KB
/
Copy pathutils.py
File metadata and controls
247 lines (201 loc) · 6.81 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
# -*- coding: utf-8 -*-
"""通用工具函数:JSON 编解码、hex 转换、IP 处理、查询串解析、日志节流等。"""
import functools
import hashlib
import hmac
import ipaddress
import logging
import random
import re
import time
from typing import Any
import orjson
from config import COMPACT_TRUTHY, SENTINEL_HUGE
logger = logging.getLogger("tracker")
# ---------------------------------------------------------------------------
# JSON 辅助函数
# ---------------------------------------------------------------------------
def json_loads(data: bytes) -> Any:
return orjson.loads(data)
def json_dumps(obj: Any, **kwargs: Any) -> bytes:
option = orjson.OPT_INDENT_2 if kwargs.get("indent") else 0
return orjson.dumps(obj, option=option)
# ---------------------------------------------------------------------------
# 工具函数
# ---------------------------------------------------------------------------
HEX_RE = re.compile(rb"^[0-9a-fA-F]+$")
_HEX_NIBBLE: list[int] = [-1] * 256
for _c in range(256):
if 48 <= _c <= 57:
_HEX_NIBBLE[_c] = _c - 48
elif 65 <= _c <= 70:
_HEX_NIBBLE[_c] = _c - 55
elif 97 <= _c <= 102:
_HEX_NIBBLE[_c] = _c - 87
rand = random.Random()
# 日志节流:同一 key 的告警最多每 interval 秒输出一次,避免被高频事件刷屏
_LOG_THROTTLE_TS: dict[str, float] = {}
def warn_throttled(key: str, msg: str, *args: Any, interval: float = 60.0) -> None:
now = time.monotonic()
last = _LOG_THROTTLE_TS.get(key)
if last is not None and now - last < interval:
return
if len(_LOG_THROTTLE_TS) > 10_000:
_LOG_THROTTLE_TS.clear()
_LOG_THROTTLE_TS[key] = now
logger.warning(msg, *args)
def bytes_to_hex(b: bytes) -> str:
return b.hex()
def hex_to_bytes(s: str | bytes) -> bytes:
if isinstance(s, bytes):
s = s.decode("ascii", errors="replace")
if len(s) % 2:
raise ValueError("hex string length must be even")
return bytes.fromhex(s)
def constant_time_compare(a: str | bytes, b: str | bytes) -> bool:
if isinstance(a, str):
a = a.encode("utf-8")
if isinstance(b, str):
b = b.encode("utf-8")
if len(a) != len(b):
return False
return hmac.compare_digest(a, b)
def constant_time_compare_int(a: int, b: int) -> bool:
"""恒时比较两个整数(64 位无符号掩码,支持负数/大整数)。"""
return hmac.compare_digest(
(a & 0xFFFFFFFFFFFFFFFF).to_bytes(8, "big"),
(b & 0xFFFFFFFFFFFFFFFF).to_bytes(8, "big"),
)
def percent_decode_bytes(b: bytes) -> bytes:
if not b or (b"%" not in b and b"+" not in b):
return b
n = len(b)
result = bytearray(n)
i = j = 0
while i < n:
c = b[i]
if c == ord("+"):
result[j] = 0x20
i += 1
j += 1
elif c == ord("%") and i + 2 < n:
high = _HEX_NIBBLE[b[i + 1]]
low = _HEX_NIBBLE[b[i + 2]]
if high >= 0 and low >= 0:
result[j] = (high << 4) | low
i += 3
j += 1
continue
result[j] = c
i += 1
j += 1
else:
result[j] = c
i += 1
j += 1
return bytes(result[:j])
def parse_query_string_raw(qs: bytes) -> dict[bytes, list[bytes]]:
result: dict[bytes, list[bytes]] = {}
if not qs:
return result
for item in qs.split(b"&"):
if not item:
continue
if b"=" in item:
key, val = item.split(b"=", 1)
else:
key, val = item, b""
key = percent_decode_bytes(key)
val = percent_decode_bytes(val)
lst = result.get(key)
if lst is None:
result[key] = [val]
else:
lst.append(val)
return result
def get_first(parsed_qs: dict[bytes, list[bytes]], key: str) -> bytes | None:
vals = parsed_qs.get(key.encode("ascii"))
return vals[0] if vals else None
def get_all(parsed_qs: dict[bytes, list[bytes]], key: str) -> list[bytes]:
return parsed_qs.get(key.encode("ascii"), [])
def get_int(
parsed_qs: dict[bytes, list[bytes]],
key: str,
default: int = 0,
*,
negative_as_huge: bool = False,
) -> int:
val = get_first(parsed_qs, key)
if val is None:
return default
try:
v = int(val)
except (ValueError, TypeError):
return default
if negative_as_huge:
return v if v >= 0 else SENTINEL_HUGE
return max(0, v)
def is_truthy(val: bytes | None) -> bool:
"""判断 bencoded/query 参数是否为真值(1/true/True)。"""
if val is None:
return False
return val.lower() in COMPACT_TRUTHY
@functools.lru_cache(maxsize=65536)
def is_private_ip(ip: str) -> bool:
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return True
return addr.is_private or addr.is_loopback or addr.is_multicast or addr.is_unspecified
@functools.lru_cache(maxsize=65536)
def normalize_ip(ip_str: str) -> str:
try:
addr = ipaddress.ip_address(ip_str)
except ValueError:
return ip_str
if isinstance(addr, ipaddress.IPv6Address):
if addr.ipv4_mapped is not None:
return str(addr.ipv4_mapped)
if addr.sixtofour is not None:
return str(addr.sixtofour)
if addr.teredo is not None:
_, client = addr.teredo
return str(client)
return addr.compressed
return ip_str
@functools.lru_cache(maxsize=65536)
def is_valid_ip(ip_str: str) -> bool:
try:
ipaddress.ip_address(ip_str)
return True
except ValueError:
return False
def maybe_hex_to_bytes(s: bytes | None) -> bytes | None:
if s is None:
return None
if len(s) == 40 and HEX_RE.match(s):
try:
return bytes.fromhex(s.decode("ascii"))
except ValueError:
return s
return s
def udp_key_from_api_key(api_key: str) -> int | None:
"""将 API_KEY 派生为 UDP 32 位 signed 整数 key。
派生规则:若 API_KEY 是十进制数字字符串,取其低 32 位;
否则始终通过 SHA-256 哈希派生,确保与 HTTP API_KEY 语义一致。
派生结果为 0 时视为无效(客户端未携带 key 时默认值即 0),强制改用哈希派生或置 1。
"""
if not api_key:
return None
raw: int | None = None
try:
# 纯数字字符串:直接取低 32 位
raw = int(api_key) & 0xFFFFFFFF
except ValueError:
raw = None
if raw is None or raw == 0:
digest = hashlib.sha256(api_key.encode("utf-8")).digest()
raw = int.from_bytes(digest[:4], "big", signed=False)
if raw == 0:
raw = 1 # 极端情况下哈希前 4 字节全零,避免与"未携带 key"混淆
return raw - 0x100000000 if raw >= 0x80000000 else raw