fix(types): validate rTorrent XML-RPC response shapes

This commit is contained in:
jxxghp
2026-10-17 15:44:59 +08:00
parent b685d725a7
commit 4593fae19b
2 changed files with 204 additions and 53 deletions

View File

@@ -1,20 +1,82 @@
import http.client
import io
import socket
import traceback
import xmlrpc.client
from collections.abc import Buffer
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
from typing import Any, Dict, List, Optional, Tuple, TypedDict, Union, cast
from urllib.parse import urlparse
from app.runtime.log import logger
class _Torrent(TypedDict):
"""rTorrent 多调用结果映射,保留现有下载器字典字段。"""
hash: str
name: str
total_size: Union[int, float]
completed: Union[int, float]
dlspeed: Union[int, float]
upspeed: Union[int, float]
state: Union[int, float]
complete: Union[int, float]
save_path: str
tags: str
is_active: Union[int, float]
is_open: Union[int, float]
ratio: float
content_path: str
progress: float
def _rpc_rows(value: object) -> list[list[object]]:
"""校验 XML-RPC 多调用的二维数组,异常仍由调用方原有错误分支处理。"""
if not isinstance(value, (list, tuple)):
raise TypeError("rTorrent multicall response must be an array")
rows: list[list[object]] = []
for row in value:
if not isinstance(row, (list, tuple)):
raise TypeError("rTorrent multicall row must be an array")
rows.append(list(row))
return rows
def _rpc_text(value: object) -> str:
"""校验外部返回的文本,不将意外对象强转为路径或标签。"""
if not isinstance(value, str):
raise TypeError("rTorrent response field must be text")
return value
def _rpc_number(value: object) -> Union[int, float]:
"""保留 XML-RPC 数值原值,拒绝不能执行原有算术的字段。"""
if not isinstance(value, (int, float)):
raise TypeError("rTorrent response field must be numeric")
return value
def _rpc_integer(value: object) -> int:
"""保留比率和分块字段原有的 int 转换,兼容数字字符串。"""
if not isinstance(value, (str, bytes, bytearray, int, float)):
raise TypeError("rTorrent response field must be convertible to int")
return int(value)
class SCGITransport(xmlrpc.client.Transport):
"""
通过SCGI协议与rTorrent通信的Transport
"""
def single_request(self, host, handler, request_body, verbose=False):
def single_request(
self, host: Union[str, tuple[str, dict[str, str]]], handler: str,
request_body: Buffer, verbose: bool = False,
) -> tuple[Any, ...]:
"""用 SCGI netstring 交换 XML-RPC 报文,并在解析前释放连接。"""
request_body = bytes(request_body)
if isinstance(host, tuple):
host = host[0]
# 建立socket连接
parsed = urlparse(f"scgi://{host}")
sock = socket.create_connection(
@@ -52,22 +114,20 @@ class SCGITransport(xmlrpc.client.Transport):
return self.parse_response(self._build_response(response))
@staticmethod
def _build_response(data: bytes):
def _build_response(data: bytes) -> http.client.HTTPResponse:
"""
构造类文件对象用于parse_response
"""
import http.client
import io
class _FakeSocket(io.BytesIO):
"""为 HTTPResponse 提供内存 socket 接口,复用标准库 XML-RPC 解码。"""
def makefile(self, *args, **kwargs):
def makefile(self, *args: object, **kwargs: object) -> io.BytesIO:
"""返回当前字节流供 HTTPResponse 读取。"""
return self
raw = b"HTTP/1.0 200 OK\r\nContent-Type: text/xml\r\n\r\n" + data
response = http.client.HTTPResponse(_FakeSocket(raw)) # noqa
# HTTPResponse 只调用 makefile;内存适配器由上方实现该接口。
response = http.client.HTTPResponse(cast(socket.socket, _FakeSocket(raw)))
response.begin()
return response
@@ -83,8 +143,8 @@ class Rtorrent:
port: Optional[int] = None,
username: Optional[str] = None,
password: Optional[str] = None,
**kwargs,
):
**kwargs: object,
) -> None:
"""读取下载器连接配置并建立代理,连接失败时保留待重连状态。"""
self._proxy = None
self._host = ""
@@ -147,7 +207,7 @@ class Rtorrent:
return False
return True if not self._proxy else False
def reconnect(self):
def reconnect(self) -> None:
"""
重连
"""
@@ -155,10 +215,10 @@ class Rtorrent:
def get_torrents(
self,
ids: Optional[Union[str, list]] = None,
ids: Optional[Union[str, list[str]]] = None,
status: Optional[str] = None,
tags: Optional[Union[str, list]] = None,
) -> Tuple[List[Dict], bool]:
tags: Optional[Union[str, list[str]]] = None,
) -> Tuple[List[_Torrent], bool]:
"""
获取种子列表
:return: 种子列表, 是否发生异常
@@ -185,23 +245,24 @@ class Rtorrent:
]
# 获取所有种子
results = self._proxy.d.multicall2("", "main", *fields)
torrents = []
for r in results:
torrent = {
"hash": r[0],
"name": r[1],
"total_size": r[2],
"completed": r[3],
"dlspeed": r[4],
"upspeed": r[5],
"state": r[6], # 0=stopped, 1=started
"complete": r[7], # 0=incomplete, 1=complete
"save_path": r[8],
"tags": r[9], # d.custom1 用于标签
"is_active": r[10],
"is_open": r[11],
"ratio": int(r[12]) / 1000.0 if r[12] else 0,
"content_path": r[13], # base_path 即完整内容路径
torrents: list[_Torrent] = []
for r in _rpc_rows(results):
torrent: _Torrent = {
"hash": _rpc_text(r[0]),
"name": _rpc_text(r[1]),
"total_size": _rpc_number(r[2]),
"completed": _rpc_number(r[3]),
"dlspeed": _rpc_number(r[4]),
"upspeed": _rpc_number(r[5]),
"state": _rpc_number(r[6]), # 0=stopped, 1=started
"complete": _rpc_number(r[7]), # 0=incomplete, 1=complete
"save_path": _rpc_text(r[8]),
"tags": _rpc_text(r[9]), # d.custom1 用于标签
"is_active": _rpc_number(r[10]),
"is_open": _rpc_number(r[11]),
"ratio": _rpc_integer(r[12]) / 1000.0 if r[12] else 0,
"progress": 0,
"content_path": _rpc_text(r[13]), # base_path 即完整内容路径
}
# 计算进度
if torrent["total_size"] > 0:
@@ -239,8 +300,8 @@ class Rtorrent:
return [], True
def get_completed_torrents(
self, ids: Union[str, list] = None, tags: Union[str, list] = None
) -> Optional[List[Dict]]:
self, ids: Optional[Union[str, list[str]]] = None, tags: Optional[Union[str, list[str]]] = None
) -> Optional[List[_Torrent]]:
"""
获取已完成的种子
"""
@@ -252,8 +313,8 @@ class Rtorrent:
return [t for t in torrents if t.get("complete") == 1]
def get_downloading_torrents(
self, ids: Union[str, list] = None, tags: Union[str, list] = None
) -> Optional[List[Dict]]:
self, ids: Optional[Union[str, list[str]]] = None, tags: Optional[Union[str, list[str]]] = None
) -> Optional[List[_Torrent]]:
"""
获取正在下载的种子
"""
@@ -271,7 +332,7 @@ class Rtorrent:
download_dir: Optional[str] = None,
tags: Optional[List[str]] = None,
cookie: Optional[str] = None,
**kwargs,
**kwargs: object,
) -> bool:
"""
添加种子
@@ -316,7 +377,7 @@ class Rtorrent:
logger.error(f"添加种子出错:{str(err)}")
return False
def start_torrents(self, ids: Union[str, list]) -> bool:
def start_torrents(self, ids: Union[str, list[str]]) -> bool:
"""
启动种子
"""
@@ -332,7 +393,7 @@ class Rtorrent:
logger.error(f"启动种子出错:{str(err)}")
return False
def stop_torrents(self, ids: Union[str, list]) -> bool:
def stop_torrents(self, ids: Union[str, list[str]]) -> bool:
"""
停止种子
"""
@@ -348,7 +409,7 @@ class Rtorrent:
logger.error(f"停止种子出错:{str(err)}")
return False
def delete_torrents(self, delete_file: bool, ids: Union[str, list]) -> bool:
def delete_torrents(self, delete_file: bool, ids: Union[str, list[str]]) -> bool:
"""
删除种子
"""
@@ -368,7 +429,7 @@ class Rtorrent:
if base_path:
import shutil
path = Path(base_path)
path = Path(_rpc_text(base_path))
if path.is_dir():
shutil.rmtree(str(path), ignore_errors=True)
elif path.is_file():
@@ -383,7 +444,7 @@ class Rtorrent:
logger.error(f"删除种子出错:{str(err)}")
return False
def get_files(self, tid: str) -> Optional[List[Dict]]:
def get_files(self, tid: str) -> Optional[List[Dict[str, object]]]:
"""
获取种子文件列表
"""
@@ -401,15 +462,15 @@ class Rtorrent:
"f.completed_chunks=",
"f.size_chunks=",
)
result = []
for idx, f in enumerate(files):
result: list[dict[str, object]] = []
for idx, f in enumerate(_rpc_rows(files)):
result.append(
{
"id": idx,
"name": f[0],
"size": f[1],
"priority": f[2],
"progress": int(f[3]) / int(f[4]) * 100 if int(f[4]) > 0 else 0,
"progress": _rpc_integer(f[3]) / _rpc_integer(f[4]) * 100 if _rpc_integer(f[4]) > 0 else 0,
}
)
return result
@@ -418,7 +479,7 @@ class Rtorrent:
return None
def set_files(
self, torrent_hash: str = None, file_ids: list = None, priority: int = 0
self, torrent_hash: Optional[str] = None, file_ids: Optional[list[Union[int, str]]] = None, priority: int = 0
) -> bool:
"""
设置下载文件的优先级,priority为0为不下载,priority为1为普通
@@ -438,7 +499,7 @@ class Rtorrent:
return False
def set_torrents_tag(
self, ids: Union[str, list], tags: List[str], overwrite: bool = False
self, ids: Union[str, list[str]], tags: List[str], overwrite: bool = False
) -> bool:
"""
设置种子标签(使用d.custom1)
@@ -461,7 +522,7 @@ class Rtorrent:
# 获取现有标签
existing = self._proxy.d.custom1(tid)
existing_tags = (
[t.strip() for t in existing.split(",") if t.strip()]
[t.strip() for t in _rpc_text(existing).split(",") if t.strip()]
if existing
else []
)
@@ -473,7 +534,7 @@ class Rtorrent:
logger.error(f"设置种子Tag出错:{str(err)}")
return False
def remove_torrents_tag(self, ids: Union[str, list], tag: Union[str, list]) -> bool:
def remove_torrents_tag(self, ids: Union[str, list[str]], tag: Union[str, list[str]]) -> bool:
"""
移除种子标签
"""
@@ -489,7 +550,7 @@ class Rtorrent:
for tid in ids:
existing = self._proxy.d.custom1(tid)
existing_tags = (
[t.strip() for t in existing.split(",") if t.strip()]
[t.strip() for t in _rpc_text(existing).split(",") if t.strip()]
if existing
else []
)
@@ -509,7 +570,7 @@ class Rtorrent:
try:
existing = self._proxy.d.custom1(ids)
return (
[t.strip() for t in existing.split(",") if t.strip()]
[t.strip() for t in _rpc_text(existing).split(",") if t.strip()]
if existing
else []
)
@@ -518,7 +579,7 @@ class Rtorrent:
return []
def get_torrent_id_by_tag(
self, tags: Union[str, list], status: Optional[str] = None
self, tags: Union[str, list[str]], status: Optional[str] = None
) -> Optional[str]:
"""
通过标签多次尝试获取刚添加的种子ID,并移除标签
@@ -532,7 +593,7 @@ class Rtorrent:
time.sleep(3)
torrents, error = self.get_torrents(tags=tags)
if not error and torrents:
torrent_id = torrents[0].get("hash")
torrent_id = torrents[0]["hash"]
# 移除查找标签
for tag in tags:
self.remove_torrents_tag(ids=torrent_id, tag=[tag])
@@ -595,7 +656,7 @@ class Rtorrent:
logger.error(f"设置种子保存目录出错:{str(err)}")
return False
def transfer_info(self) -> Optional[Dict]:
def transfer_info(self) -> Optional[Dict[str, object]]:
"""
获取传输信息
"""

View File

@@ -0,0 +1,90 @@
"""验证 rTorrent XML-RPC 返回值映射及异常响应的隔离。"""
from unittest.mock import Mock
import pytest
from app.modules.rtorrent.rtorrent import Rtorrent
@pytest.fixture
def client():
"""构造无网络客户端,所有远端调用均由 Mock 接管。"""
result = Rtorrent.__new__(Rtorrent)
result._proxy = Mock()
return result
@pytest.fixture
def torrent_row():
"""提供与 d.multicall2 字段顺序一致的种子记录。"""
return ["ABC", "movie", 1000, 250, 10, 20, 1, 0,
"/downloads", "movie, keep", 1, 1, "1500", "/downloads/movie"]
def test_torrent_mapping_keeps_progress_ratio_and_filters(client, torrent_row):
"""有效响应保留字段原值、百分比和千分比,过滤不改变记录。"""
client._proxy.d.multicall2.return_value = [torrent_row]
torrents, error = client.get_torrents(ids="abc", tags=["keep"])
assert error is False
assert torrents[0]["progress"] == 25.0
assert torrents[0]["ratio"] == 1.5
assert torrents[0]["total_size"] == 1000
assert torrents[0]["content_path"] == "/downloads/movie"
assert client.get_torrents(ids=["other"]) == ([], False)
assert client.get_torrents(tags="other") == ([], False)
assert client.get_downloading_torrents() == torrents
assert client.get_completed_torrents() == []
def test_zero_size_and_tuple_rows_remain_supported(client, torrent_row):
"""XML-RPC 数组支持列表和元组,零大小任务保持零进度。"""
torrent_row[2] = 0
torrent_row[12] = 0
client._proxy.d.multicall2.return_value = (tuple(torrent_row),)
torrents, error = client.get_torrents()
assert error is False
assert torrents[0]["progress"] == torrents[0]["ratio"] == 0
@pytest.mark.parametrize("payload", [None, 123, "wrong", [123], [["short"]]])
def test_malformed_multicall_keeps_error_contract(client, payload):
"""错误的远端数组仍返回原有失败标记,不泄漏部分结果。"""
client._proxy.d.multicall2.return_value = payload
assert client.get_torrents() == ([], True)
@pytest.mark.parametrize("index,value", [(0, 12), (2, "1000"), (9, ["tag"]), (12, {})])
def test_invalid_torrent_fields_keep_error_contract(client, torrent_row, index, value):
"""身份、算术和标签字段不接受不符合 XML-RPC 合同的类型。"""
torrent_row[index] = value
client._proxy.d.multicall2.return_value = [torrent_row]
assert client.get_torrents() == ([], True)
def test_file_chunk_progress_accepts_numeric_strings(client):
"""文件分块计数继续兼容字符串,并避免零分母。"""
client._proxy.f.multicall.return_value = [
["one", 100, 1, "2", "4"], ["two", 0, 0, 0, 0],
]
assert client.get_files("ABC") == [
{"id": 0, "name": "one", "size": 100, "priority": 1, "progress": 50.0},
{"id": 1, "name": "two", "size": 0, "priority": 0, "progress": 0},
]
client._proxy.f.multicall.return_value = [["bad", 100, 1, {}, 4]]
assert client.get_files("ABC") is None
def test_tag_operations_preserve_merge_remove_and_empty_response(client):
"""标签的合并、删除和空返回兼容原行为。"""
client._proxy.d.custom1.return_value = " old, keep "
assert client.set_torrents_tag("ABC", ["new"])
assert set(client._proxy.d.custom1.set.call_args.args[1].split(",")) == {"old", "keep", "new"}
assert client.remove_torrents_tag("ABC", "old")
client._proxy.d.custom1.set.assert_called_with("ABC", "keep")
assert client.get_torrent_tags("ABC") == ["old", "keep"]
client._proxy.d.custom1.return_value = None
assert client.get_torrent_tags("ABC") == []
client._proxy.d.custom1.return_value = ["invalid"]
assert client.set_torrents_tag("ABC", ["new"]) is False
assert client.get_torrent_tags("ABC") == []