Repository navigation
Expand file tree
/
Copy pathhttp_api.py
More file actions
617 lines (526 loc) · 21 KB
/
Copy pathhttp_api.py
File metadata and controls
617 lines (526 loc) · 21 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
# -*- coding: utf-8 -*-
"""HTTP API:aiohttp 路由、速率限制、响应编码 helper。"""
import asyncio
import logging
import socket
import struct
import time
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any
import bencodepy
from aiohttp import web
from config import (
ALLOW_IP_PARAM,
ALLOW_PRIVATE_IP,
API_KEY,
BEHIND_PROXY,
COMPACT4_STRUCT,
COMPACT6_STRUCT,
INTERVAL,
MAX_HTTP_BODY_SIZE,
MAX_NUMWANT,
MAX_SCRAPE_HASHES,
MIN_INTERVAL,
PROTECT_ANNOUNCE,
PROTECT_SCRAPE,
UDP_PORT,
VALID_EVENTS,
)
from metrics import MetricsCollector
from models import Peer
from utils import (
bytes_to_hex,
constant_time_compare,
get_all,
get_first,
get_int,
hex_to_bytes,
is_private_ip,
is_truthy,
is_valid_ip,
maybe_hex_to_bytes,
normalize_ip,
parse_query_string_raw,
)
logger = logging.getLogger("tracker")
# ---------------------------------------------------------------------------
# HTTP 辅助函数
# ---------------------------------------------------------------------------
def _bencode_response(data: dict[Any, Any], status: int = 200) -> web.Response:
try:
payload = bencodepy.encode(data)
except Exception:
# 注意 bencode 长度前缀必须与字符串实际字节数一致("encode error" = 12 字节)
payload = b"d14:failure reason12:encode errore"
return web.Response(body=payload, status=status, content_type="text/plain")
def _bencode_error(message: str) -> web.Response:
"""BEP 3: tracker 错误响应始终返回 HTTP 200 + failure reason。"""
try:
payload = bencodepy.encode({b"failure reason": message.encode("utf-8")})
except Exception:
msg = message.encode("utf-8")
payload = b"d14:failure reason" + str(len(msg)).encode() + b":" + msg + b"e"
return web.Response(body=payload, status=200, content_type="text/plain")
def _json_response(data: Any, status: int = 200, indent: int | None = None) -> web.Response:
from utils import json_dumps
body = json_dumps(data, indent=indent) if indent is not None else json_dumps(data)
return web.Response(body=body, status=status, content_type="application/json")
def _json_error(message: str, status: int = 400) -> web.Response:
return _json_response({"error": message}, status=status)
def _get_client_ip(request: web.Request) -> str:
if BEHIND_PROXY:
# 从右向左取第一个合法 IP:右侧条目由可信代理追加,最左侧最易被客户端伪造
xff = request.headers.get("X-Forwarded-For", "")
if xff:
for part in reversed(xff.split(",")):
cand = part.strip()
if cand and is_valid_ip(cand):
return normalize_ip(cand)
real_ip = request.headers.get("X-Real-IP", "").strip()
if real_ip and is_valid_ip(real_ip):
return normalize_ip(real_ip)
transport = request.transport
if transport is not None:
peername = transport.get_extra_info("peername")
if peername:
return normalize_ip(peername[0])
return "127.0.0.1"
def _validate_hash(h: bytes | None, name: str) -> web.Response | None:
if h is None:
return _bencode_error(f"Missing {name}")
if len(h) != 20:
return _bencode_error(
f"Invalid {name} length ({len(h)} bytes, expected 20). "
f"Pass raw 20-byte binary or 40-char hex string."
)
return None
def _encode_compact_peers(peers: list[Peer]) -> tuple[bytes, bytes]:
"""编码 compact peer 列表,返回 (IPv4_blob, IPv6_blob)。"""
parts4: list[bytes] = []
parts6: list[bytes] = []
for p in peers:
if p.port <= 0 or p.port > 65535:
continue
ip = normalize_ip(p.ip)
if ":" in ip:
try:
packed = socket.inet_pton(socket.AF_INET6, ip)
except OSError:
logger.debug("跳过无效 IPv6 peer: %s", ip)
continue
parts6.append(COMPACT6_STRUCT.pack(packed, p.port))
else:
try:
packed = socket.inet_pton(socket.AF_INET, ip)
except OSError:
logger.debug("跳过无效 IPv4 peer: %s", ip)
continue
parts4.append(COMPACT4_STRUCT.pack(packed, p.port))
return b"".join(parts4), b"".join(parts6)
def _check_api_key(request: web.Request) -> web.Response | None:
if not API_KEY:
# 未配置 API_KEY 时管理端点一律禁用,避免 /shutdown 等被匿名调用
return _json_error("Admin API disabled (server has no API key)", status=403)
provided = request.headers.get("X-API-Key", "")
if not constant_time_compare(provided, API_KEY):
return _json_error("Unauthorized", status=401)
return None
def _check_announce_key(parsed_qs: dict[bytes, list[bytes]]) -> web.Response | None:
if not API_KEY or not PROTECT_ANNOUNCE:
return None
key_bytes = get_first(parsed_qs, "key")
if key_bytes is None:
return _bencode_error("Missing key (private tracker)")
if not constant_time_compare(key_bytes, API_KEY.encode("utf-8")):
return _bencode_error("Invalid key (private tracker)")
return None
def _check_scrape_key(parsed_qs: dict[bytes, list[bytes]]) -> web.Response | None:
if not API_KEY or not PROTECT_SCRAPE:
return None
key_bytes = get_first(parsed_qs, "key")
if key_bytes is None:
return _bencode_error("Missing key (private tracker)")
if not constant_time_compare(key_bytes, API_KEY.encode("utf-8")):
return _bencode_error("Invalid key (private tracker)")
return None
# ---------------------------------------------------------------------------
# HTTP 速率限制
# ---------------------------------------------------------------------------
@dataclass(slots=True)
class _HttpRateEntry:
tokens: float
last_update: float
class HttpRateLimiter:
"""per-IP Token Bucket,用于 HTTP /announce 与 /scrape。
内部使用 OrderedDict 实现 LRU 淘汰,避免 O(n) 扫描。"""
def __init__(self) -> None:
from config import (
HTTP_RATE_LIMIT_BURST,
HTTP_RATE_LIMIT_ENABLED,
HTTP_RATE_LIMIT_MAX_ENTRIES,
HTTP_RATE_LIMIT_RPS,
)
self._enabled = HTTP_RATE_LIMIT_ENABLED
self._rps = HTTP_RATE_LIMIT_RPS
self._burst = HTTP_RATE_LIMIT_BURST
self._table: OrderedDict[str, _HttpRateEntry] = OrderedDict()
self._max_entries = HTTP_RATE_LIMIT_MAX_ENTRIES
def check(self, ip: str) -> bool:
if not self._enabled:
return True
now = time.monotonic()
while len(self._table) >= self._max_entries:
self._table.popitem(last=False)
entry = self._table.get(ip)
if entry is None:
entry = _HttpRateEntry(tokens=float(self._burst), last_update=now)
self._table[ip] = entry
else:
self._table.move_to_end(ip)
elapsed = now - entry.last_update
entry.tokens = min(float(self._burst), entry.tokens + elapsed * self._rps)
entry.last_update = now
if entry.tokens < 1.0:
return False
entry.tokens -= 1.0
return True
# ---------------------------------------------------------------------------
# aiohttp 路由(通过 app 上下文注入 tracker / metrics)
# ---------------------------------------------------------------------------
routes = web.RouteTableDef()
_start_time = time.monotonic() # uptime 使用单调时钟,避免校时跳变
# 惰性初始化:避免模块导入时的副作用
_shutdown_event: asyncio.Event | None = None
_http_rate_limiter: HttpRateLimiter | None = None
def get_shutdown_event() -> asyncio.Event:
global _shutdown_event
if _shutdown_event is None:
_shutdown_event = asyncio.Event()
return _shutdown_event
def get_http_rate_limiter() -> HttpRateLimiter:
global _http_rate_limiter
if _http_rate_limiter is None:
_http_rate_limiter = HttpRateLimiter()
return _http_rate_limiter
def _get_tracker(request: web.Request):
"""从 aiohttp app 上下文获取 Tracker 实例。"""
return request.app["tracker"]
def _get_metrics(request: web.Request) -> MetricsCollector:
"""从 aiohttp app 上下文获取 MetricsCollector 实例。"""
return request.app["metrics"]
@routes.get("/")
async def index(request: web.Request) -> web.Response:
return _json_response(
{
"status": "ok",
"service": "BitTorrent Tracker",
"uptime": time.monotonic() - _start_time,
"endpoints": {
"announce": "/announce",
"scrape": "/scrape",
"health": "/health",
"stats": "/stats (requires API key)",
"metrics": "/metrics",
},
}
)
@routes.get("/announce")
async def announce(request: web.Request) -> web.Response:
client_ip = _get_client_ip(request)
if not get_http_rate_limiter().check(client_ip):
_get_metrics(request).inc_rate_limit()
return _bencode_error("Rate limit exceeded")
start = time.monotonic()
try:
qs = request.rel_url.raw_query_string.encode("ascii")
parsed_qs = parse_query_string_raw(qs)
auth_err = _check_announce_key(parsed_qs)
if auth_err:
_get_metrics(request).inc_announce("http", failed=True)
return auth_err
info_hash = maybe_hex_to_bytes(get_first(parsed_qs, "info_hash"))
peer_id = maybe_hex_to_bytes(get_first(parsed_qs, "peer_id"))
port_bytes = get_first(parsed_qs, "port")
err = _validate_hash(info_hash, "info_hash") or _validate_hash(peer_id, "peer_id")
if err:
_get_metrics(request).inc_announce("http", failed=True)
return err
if not port_bytes:
_get_metrics(request).inc_announce("http", failed=True)
return _bencode_error("Missing port")
try:
port = int(port_bytes)
if port < 1 or port > 65535:
_get_metrics(request).inc_announce("http", failed=True)
return _bencode_error("Invalid port")
except (ValueError, TypeError):
_get_metrics(request).inc_announce("http", failed=True)
return _bencode_error("Invalid port")
uploaded = get_int(parsed_qs, "uploaded", 0)
downloaded = get_int(parsed_qs, "downloaded", 0)
left = get_int(parsed_qs, "left", 0, negative_as_huge=True)
numwant_bytes = get_first(parsed_qs, "numwant")
if numwant_bytes is None:
numwant = 50
else:
try:
numwant = int(numwant_bytes)
except (ValueError, TypeError):
_get_metrics(request).inc_announce("http", failed=True)
return _bencode_error("Invalid numwant parameter")
if numwant == -1:
numwant = MAX_NUMWANT
elif numwant < 0:
numwant = 0
numwant = min(numwant, MAX_NUMWANT)
event_bytes = get_first(parsed_qs, "event")
event = event_bytes.decode("ascii", errors="replace") if event_bytes else None
if event is not None and event not in VALID_EVENTS:
event = None
compact = is_truthy(get_first(parsed_qs, "compact"))
# ip 查询参数默认不信任(可被伪造用于污染 swarm),仅在显式配置时启用
ip_param: str | None = None
if ALLOW_IP_PARAM:
ip_param_bytes = get_first(parsed_qs, "ip")
if ip_param_bytes:
cand = ip_param_bytes.decode("ascii", errors="replace")
if is_valid_ip(cand):
ip_param = cand
if ip_param is not None and (ALLOW_PRIVATE_IP or not is_private_ip(ip_param)):
ip = normalize_ip(ip_param)
else:
ip = client_ip
if not is_valid_ip(ip):
ip = "127.0.0.1"
stats, peers, failure = await _get_tracker(request).announce(
info_hash=info_hash,
peer_id=peer_id,
ip=ip,
port=port,
uploaded=uploaded,
downloaded=downloaded,
left=left,
event=event,
numwant=numwant,
)
if failure is not None:
_get_metrics(request).inc_announce("http", failed=True)
return _bencode_error(failure)
response_data: dict[bytes, Any] = {
b"interval": INTERVAL,
b"min interval": MIN_INTERVAL,
b"complete": stats["complete"],
b"incomplete": stats["incomplete"],
b"downloaded": stats["downloaded"],
}
if compact:
v4_blob, v6_blob = _encode_compact_peers(peers)
response_data[b"peers"] = v4_blob
if v6_blob:
response_data[b"peers6"] = v6_blob
else:
response_data[b"peers"] = [
{
b"peer id": p.peer_id,
b"ip": normalize_ip(p.ip).encode("ascii"),
b"port": p.port,
}
for p in peers
]
_get_metrics(request).inc_announce("http")
return _bencode_response(response_data)
except Exception:
logger.exception("Announce 处理错误")
_get_metrics(request).inc_announce("http", failed=True)
return _bencode_error("Internal tracker error")
finally:
_get_metrics(request).observe_duration("http_announce", time.monotonic() - start)
@routes.get("/scrape")
async def scrape(request: web.Request) -> web.Response:
client_ip = _get_client_ip(request)
if not get_http_rate_limiter().check(client_ip):
_get_metrics(request).inc_rate_limit()
return _bencode_error("Rate limit exceeded")
start = time.monotonic()
try:
qs = request.rel_url.raw_query_string.encode("ascii")
parsed_qs = parse_query_string_raw(qs)
auth_err = _check_scrape_key(parsed_qs)
if auth_err:
_get_metrics(request).inc_scrape("http", failed=True)
return auth_err
info_hashes = list(get_all(parsed_qs, "info_hash"))
extra = request.match_info.get("extra", "")
if extra:
from utils import HEX_RE
for chunk in extra.strip("/").split("/"):
chunk = chunk.strip()
chunk_bytes = chunk.encode("ascii")
if len(chunk_bytes) == 40 and HEX_RE.match(chunk_bytes):
info_hashes.append(chunk_bytes)
if not info_hashes:
_get_metrics(request).inc_scrape("http", failed=True)
return _bencode_error("Missing info_hash")
seen: set[bytes] = set()
unique: list[bytes] = []
for ih in info_hashes:
norm = maybe_hex_to_bytes(ih)
if not norm or len(norm) != 20:
continue
if norm in seen:
continue
seen.add(norm)
unique.append(norm)
if not unique:
_get_metrics(request).inc_scrape("http", failed=True)
return _bencode_error("No valid info_hash")
if len(unique) > MAX_SCRAPE_HASHES:
unique = unique[:MAX_SCRAPE_HASHES]
files = await _get_tracker(request).scrape(unique)
http_files: dict[bytes, dict[bytes, int]] = {}
for ih, s in files.items():
http_files[ih] = {
b"complete": s[b"seeders"],
b"downloaded": s[b"completed"],
b"incomplete": s[b"leechers"],
}
_get_metrics(request).inc_scrape("http")
return _bencode_response({b"files": http_files})
except Exception:
logger.exception("Scrape 处理错误")
_get_metrics(request).inc_scrape("http", failed=True)
return _bencode_error("Internal tracker error")
finally:
_get_metrics(request).observe_duration("http_scrape", time.monotonic() - start)
@routes.get("/metrics")
async def metrics_endpoint(request: web.Request) -> web.Response:
return web.Response(
body=_get_metrics(request).render(),
content_type="text/plain; version=0.0.4",
charset="utf-8",
)
@routes.post("/add_torrent_info")
async def add_torrent_info(request: web.Request) -> web.Response:
auth = _check_api_key(request)
if auth:
return auth
try:
if request.content_length and request.content_length > MAX_HTTP_BODY_SIZE:
return _json_error("Request body too large", status=413)
try:
data = await request.json()
except web.HTTPException:
# aiohttp 对非法 Content-Type 抛 HTTPBadRequest,交还给框架处理
raise
except (ValueError, UnicodeDecodeError):
return _json_error("Invalid JSON body", status=400)
if not isinstance(data, dict):
return _json_error("Request body must be a JSON object", status=400)
if "info_hash" not in data:
return _json_error("Missing info_hash")
try:
info_hash = hex_to_bytes(str(data["info_hash"]))
if len(info_hash) != 20:
return _json_error("info_hash must be 20 bytes")
except Exception:
return _json_error("Invalid info_hash hex")
allowed_fields = {
"name",
"size",
"piece_length",
"comment",
"created_by",
"creation_date",
}
update_data: dict[str, Any] = {}
for field in allowed_fields:
if field in data:
val = data[field]
if field in ("name", "comment", "created_by"):
update_data[field] = (
str(val) if val is not None else ("" if field == "name" else None)
)
else:
try:
v = int(val) if val is not None else 0
if v < 0:
return _json_error(
f"Field {field} must be non-negative"
)
update_data[field] = v
except (ValueError, TypeError):
return _json_error(f"Invalid value for field {field}")
await _get_tracker(request).upsert_torrent_info(info_hash, update_data)
return _json_response({"status": "ok"})
except web.HTTPException:
raise
except Exception:
logger.exception("add_torrent_info 错误")
return _json_error("Internal error", status=500)
@routes.get("/stats")
async def get_all_stats(request: web.Request) -> web.Response:
auth = _check_api_key(request)
if auth:
return auth
try:
return _json_response(await _get_tracker(request).get_all_stats(), indent=2)
except Exception:
logger.exception("stats 错误")
return _json_error("Internal error", status=500)
@routes.post("/save_state")
async def save_state(request: web.Request) -> web.Response:
auth = _check_api_key(request)
if auth:
return auth
await _get_tracker(request).save_state(_get_metrics(request))
return _json_response({"status": "ok", "message": "Tracker 状态已保存"})
@routes.get("/export_state")
async def export_state(request: web.Request) -> web.Response:
"""导出与旧版 JSON 状态格式兼容的全量快照(备份/迁移用)。"""
auth = _check_api_key(request)
if auth:
return auth
try:
snapshot = await _get_tracker(request).build_json_snapshot()
return _json_response(snapshot)
except Exception:
logger.exception("export_state 错误")
return _json_error("Internal error", status=500)
@routes.get("/health")
async def health(request: web.Request) -> web.Response:
return _json_response(
{
"status": "ok",
"uptime": time.monotonic() - _start_time,
"torrents": len(_get_tracker(request).torrents),
"udp_port": UDP_PORT,
"http_port": request.app["http_port"],
}
)
@routes.post("/shutdown")
async def shutdown(request: web.Request) -> web.Response:
auth = _check_api_key(request)
if auth:
return auth
evt = get_shutdown_event()
if not evt.is_set():
evt.set()
return _json_response({"status": "shutting down"})
# ---------------------------------------------------------------------------
# 应用工厂(便于测试)
# ---------------------------------------------------------------------------
def create_app(tracker=None, metrics: MetricsCollector | None = None) -> web.Application:
from config import PORT
app = web.Application(client_max_size=MAX_HTTP_BODY_SIZE)
app.add_routes(routes)
# 统一路由:/scrape 与 /scrape/<hash>
app.router.add_get("/scrape/{extra:.*}", scrape)
# 注入 tracker / metrics 实例到 app 上下文
if tracker is None:
from core import Tracker
tracker = Tracker()
app["tracker"] = tracker
app["metrics"] = metrics if metrics is not None else MetricsCollector()
app["http_port"] = PORT
return app