Torrents over a fail-closed VPN (#1026)

Torrents reach the Internet only through a fail-closed VPN (WireGuard or
OpenVPN, any provider), so peers never see a WROLPi's own address.

- A network namespace (Pi/Debian) or the vpn container (Docker) with an
  nftables kill switch; NAT-PMP or fixed port forwarding.
- qBittorrent inside it, sandboxed; torrents kept in config/torrents/.
- Torrent download form, Torrents page, Share as torrent, nav warning, and
  VPN settings in both Controller UIs.
- Help docs: Torrents, and The VPN for Torrents.

QA'd on a Raspberry Pi with a real provider over WireGuard and OpenVPN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-11-28 14:25:24 -07:00 • committed by Roland
parent 633b125dc6
commit 2c3300b8b0
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
80 changed files with 7516 additions and 45 deletions

View file

@ -0,0 +1,6 @@
from .api import torrents_bp
from .downloader import torrent_downloader
from .lib import get_torrents_config, torrents_worker
from .share import share_torrent
__all__ = ['share_torrent', 'torrents_bp', 'get_torrents_config', 'torrent_downloader', 'torrents_worker']

135
modules/torrents/api.py Normal file
View file

@ -0,0 +1,135 @@
from dataclasses import dataclass
from typing import Optional
from sanic import Blueprint, response
from sanic.request import Request
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from modules.torrents import lib, share
from wrolpi.api_utils import json_response
from wrolpi.common import get_wrolpi_config, wrol_mode_check
from wrolpi.downloader import download_manager
from wrolpi.errors import ValidationError
torrents_bp = Blueprint('Torrents', '/api/torrents')
@dataclass
class ShareLimitsRequest:
seed_ratio_limit: Optional[float] = None
seed_time_limit: Optional[int] = None
@dataclass
class ShareRequest:
path: str
trackers: Optional[list] = None
web_seeds: Optional[list] = None
# Make these trackers the ones offered next time.
remember_trackers: bool = False
@dataclass
class LimitsRequest:
upload: int = 0
download: int = 0
@torrents_bp.get('/')
@openapi.description("Every torrent, qBittorrent's state, and the VPN's (torrents reach the Internet only through it)")
async def get_torrents(_: Request):
return json_response(await lib.get_torrents_status())
@torrents_bp.post('/upload')
@openapi.description('Download a .torrent file (multipart field `torrent`) into `destination` (form field, relative '
'to the media directory). Its progress is shown on the Downloads page.')
@wrol_mode_check
async def upload_torrent(request: Request):
file = request.files.get('torrent') if request.files else None
if not file:
raise ValidationError('Choose a .torrent file')
torrent = file.body
hash_, name = lib.torrent_identity(torrent)
save_path = lib.check_save_path(request.form.get('destination') or lib.DEFAULT_SAVE_PATH)
torrent_file = lib.get_torrents_config().get_torrent_file(hash_)
torrent_file.parent.mkdir(parents=True, exist_ok=True)
torrent_file.write_bytes(torrent)
# Its magnet link names it on the Downloads page; the downloader uses the saved file. A write block, as
# post_download explains.
with request.ctx.db.write() as session:
download_manager.create_downloads(session, [lib.torrent_magnet(torrent)], lib.TORRENT_DOWNLOADER,
reset_attempts=True, destination=lib.get_media_directory() / save_path)
return json_response(dict(hash=hash_, name=name))
@torrents_bp.post('/<hash_:str>/pause')
@wrol_mode_check
async def pause_torrent(_: Request, hash_: str):
await lib.set_paused(hash_, True)
return response.empty()
@torrents_bp.post('/<hash_:str>/resume')
@wrol_mode_check
async def resume_torrent(_: Request, hash_: str):
await lib.set_paused(hash_, False)
return response.empty()
@torrents_bp.put('/<hash_:str>/limits')
@openapi.definition(body=ShareLimitsRequest, summary='Stop seeding at a ratio / after minutes seeding (null: never)')
@validate(ShareLimitsRequest)
@wrol_mode_check
async def put_share_limits(_: Request, hash_: str, body: ShareLimitsRequest):
lib.set_share_limits(hash_, body.seed_ratio_limit, body.seed_time_limit)
return response.empty()
@torrents_bp.delete('/<hash_:str>')
@openapi.description('Remove a torrent. Its files are kept unless `delete_files=true`.')
@wrol_mode_check
async def delete_torrent(request: Request, hash_: str):
await lib.remove_torrent(hash_, delete_files=request.args.get('delete_files') == 'true')
return response.empty()
@torrents_bp.get('/<hash_:str>/torrent')
@openapi.description("A torrent's .torrent file, to share it")
async def get_torrent_file(_: Request, hash_: str):
config = lib.get_torrents_config()
entity = config.get(hash_)
torrent_file = config.get_torrent_file(hash_)
if not entity or not torrent_file.is_file():
raise ValidationError('That torrent has no .torrent file yet')
return await response.file(torrent_file, mime_type='application/x-bittorrent',
filename=f'{entity["name"]}.torrent')
@torrents_bp.put('/limits')
@openapi.definition(body=LimitsRequest, summary="Torrents' total upload and download limits, in KiB/s (0: none)")
@validate(LimitsRequest)
@wrol_mode_check
async def put_limits(_: Request, body: LimitsRequest):
if body.upload < 0 or body.download < 0:
raise ValidationError('A speed limit cannot be negative')
wrolpi_config = get_wrolpi_config()
wrolpi_config.torrent_upload_limit = body.upload
wrolpi_config.torrent_download_limit = body.download
return response.empty()
@torrents_bp.post('/share')
@openapi.definition(body=ShareRequest,
summary='Make a torrent of a file or directory in the library (`path`, relative to the media '
'directory), and seed it. Returns the Job making it.')
@validate(ShareRequest)
@wrol_mode_check
async def share_torrent(_: Request, body: ShareRequest):
trackers = share.check_trackers(body.trackers)
job_id = share.share(body.path, trackers, body.web_seeds or [])
# Only once the request was accepted.
if body.remember_trackers:
get_wrolpi_config().torrent_trackers = trackers
return json_response(dict(job_id=job_id), status=201)

View file

@ -0,0 +1,128 @@
import copy
import pytest
from modules.torrents import lib
@pytest.fixture
def test_torrents_config(test_directory):
"""An isolated torrents config in the test directory."""
from wrolpi.api_utils import api_app
from wrolpi.contexts import attach_shared_contexts
if not hasattr(api_app.shared_ctx, 'switches_lock'):
attach_shared_contexts(api_app)
(test_directory / 'config' / 'torrents').mkdir(parents=True, exist_ok=True)
lib.set_test_torrents_config(True)
config = lib.get_torrents_config()
config.initialize()
try:
yield config
finally:
lib.set_test_torrents_config(False)
class FakeQBittorrent:
"""qBittorrent's WebUI API, in memory."""
def __init__(self, torrents=None, tags=None, preferences=None, metadata=True, created=None,
creator_statuses=None):
self._torrents = {t['hash']: dict(t) for t in torrents or []}
self._tags = list(tags or [])
self._preferences = dict(preferences or {'upnp': True, 'lsd': True, 'listen_port': 57968,
'current_network_interface': 'vpn0'})
self.metadata = metadata
self.calls = []
# The torrent creator: the .torrent it makes, and the statuses it reports in turn.
self.created = created
self.creator_statuses = list(creator_statuses or [{'status': 'Finished', 'progress': None}])
async def version(self):
return 'v5.1.0'
async def preferences(self):
return dict(self._preferences)
async def set_preferences(self, preferences):
self.calls.append(('set_preferences', preferences))
self._preferences.update(preferences)
async def transfer_info(self):
return {'connection_status': 'connected', 'up_info_speed': 100, 'dl_info_speed': 0}
async def torrents(self):
return [copy.deepcopy(t) for t in self._torrents.values()]
async def tags(self):
return list(self._tags)
async def create_tags(self, *tags):
self._tags.extend(t for t in tags if t not in self._tags)
def _tag_set(self, hash_):
return {t for t in self._torrents[hash_].get('tags', '').split(',') if t}
async def add_tags(self, hashes, *tags):
for h in hashes:
self._torrents[h]['tags'] = ','.join(sorted(self._tag_set(h) | set(tags)))
async def remove_tags(self, hashes, *tags):
for h in hashes:
self._torrents[h]['tags'] = ','.join(sorted(self._tag_set(h) - set(tags)))
async def add(self, save_path, torrent=None, url=None, tags=None, stopped=False, skip_checking=False):
self.calls.append(('add', save_path, torrent, url, tags, stopped))
if skip_checking:
self.calls.append(('skip_checking', save_path))
if torrent and torrent.startswith(b'd'):
hash_, name = lib.torrent_identity(torrent)
elif torrent:
# A stand-in .torrent written by a test: b'torrent <hash>'.
hash_ = name = torrent.decode()[-40:]
else:
hash_, name = lib.magnet_identity(url)
self._torrents[hash_] = dict(hash=hash_, name=name, save_path=save_path,
tags=','.join(tags or []), state='stoppedDL' if stopped else 'downloading',
progress=0)
async def delete(self, hashes, delete_files=False):
self.calls.append(('delete', hashes, delete_files))
for h in hashes:
self._torrents.pop(h, None)
async def export(self, hash_):
return f'torrent {hash_}'.encode() if self.metadata else None
async def set_share_limits(self, hashes, ratio_limit, seeding_time_limit):
self.calls.append(('set_share_limits', hashes, ratio_limit, seeding_time_limit))
for h in hashes:
self._torrents[h].update(ratio_limit=ratio_limit, seeding_time_limit=seeding_time_limit)
async def create_torrent(self, source_path, trackers, url_seeds):
self.calls.append(('create_torrent', source_path, trackers, url_seeds))
return 'task-1'
async def torrent_creator_status(self, task_id):
return self.creator_statuses.pop(0) if len(self.creator_statuses) > 1 else self.creator_statuses[0]
async def torrent_creator_file(self, task_id):
return self.created
async def delete_torrent_creator_task(self, task_id):
self.calls.append(('delete_torrent_creator_task', task_id))
async def start(self, hashes):
self.calls.append(('start', hashes))
for h in hashes:
self._torrents[h]['state'] = 'downloading'
async def stop(self, hashes):
self.calls.append(('stop', hashes))
for h in hashes:
self._torrents[h]['state'] = 'stoppedDL'
@pytest.fixture
def fake_qbittorrent():
return FakeQBittorrent

View file

@ -0,0 +1,85 @@
"""
Torrents from the Download menu: a magnet link, or the URL of a .torrent file.
The Download finishes once the torrent is added (to config/torrents/, then qBittorrent); a torrent can take days, and
no download worker waits for it. The torrents worker shows its progress on the Download, and marks it completed
when the torrent is.
"""
import pathlib
from dataclasses import dataclass
from sqlalchemy.orm import Session
from modules.torrents import lib
from wrolpi.common import aiohttp_get, get_relative_to_media_directory
from wrolpi.downloader import Download, DownloadContext, DownloadResult, Downloader
from wrolpi.errors import ValidationError
@dataclass
class PreparedTorrent:
url: str
save_path: str
@dataclass
class ExecutedTorrent:
hash: str
name: str
class TorrentDownloader(Downloader):
name = lib.TORRENT_DOWNLOADER
pretty_name = 'Torrent'
listable = False
def normalize_domain(self, url: str) -> str:
# Magnet links have no domain; torrents are limited by qBittorrent, not the daily download limits.
return 'torrents'
def prepare_download(self, session: Session, download: Download) -> PreparedTorrent:
save_path = lib.DEFAULT_SAVE_PATH
if download.destination:
save_path = str(get_relative_to_media_directory(download.destination))
return PreparedTorrent(url=download.url, save_path=save_path)
async def execute_download(self, prepared: PreparedTorrent, ctx: DownloadContext,
download: Download = None) -> ExecutedTorrent | DownloadResult:
url = prepared.url.strip()
try:
if url.lower().startswith('magnet:'):
hash_, _ = lib.magnet_identity(url)
torrent_file = lib.get_torrents_config().get_torrent_file(hash_)
# An uploaded .torrent is saved before its Download is made; use it rather than the magnet link.
torrent = torrent_file.read_bytes() if torrent_file.is_file() else None
entity = await lib.add_torrent(prepared.save_path, torrent=torrent, magnet=None if torrent else url)
elif url.lower().startswith(('http://', 'https://')):
entity = await lib.add_torrent(prepared.save_path, torrent=await fetch_torrent_file(url))
else:
return DownloadResult(success=False, error='A torrent must be a magnet link or a .torrent URL')
except (ValidationError, lib.QBittorrentError, lib.QBittorrentUnavailable) as e:
return DownloadResult(success=False, error=str(e))
return ExecutedTorrent(hash=entity['slug'], name=entity['name'])
def finalize_download(self, session: Session, download: Download, executed: ExecutedTorrent) -> DownloadResult:
# The torrents worker finds this Download's torrent by its hash.
download.info_json = dict(torrent_hash=executed.hash, name=executed.name)
return DownloadResult(success=True, location='/admin/torrents')
async def fetch_torrent_file(url: str) -> bytes:
"""A .torrent file from a website. (Only this small file comes from the website; the torrent itself is
downloaded through the VPN.)"""
torrent = bytearray()
async with aiohttp_get(url, timeout=60) as response:
if response.status != 200:
raise ValidationError(f'Could not download the .torrent file ({response.status})')
# `read(n)` returns whatever has arrived (up to n), not the whole file; read every chunk.
async for chunk in response.content.iter_chunked(64 * 1024):
torrent.extend(chunk)
if len(torrent) > lib.MAX_TORRENT_FILE_BYTES:
raise ValidationError('That file is too large to be a .torrent file')
return bytes(torrent)
torrent_downloader = TorrentDownloader()

604
modules/torrents/lib.py Normal file
View file

@ -0,0 +1,604 @@
"""
Torrents: qBittorrent, inside the VPN's network namespace, kept as config/torrents/ says.
Each torrent is `config/torrents/<hash>.yaml`, with its `.torrent` file beside it, so a restored WROLPi re-adds
(and re-checks, never re-downloads) every torrent. There is no database. The torrents can also be managed in
qBittorrent's own WebUI (port 8091), so WROLPi follows it too:
- A torrent WROLPi knows carries the `wrolpi` tag in qBittorrent. An untagged torrent (added in the WebUI) is
adopted into the config once its metadata has arrived.
- qBittorrent keeps its tags in its profile. Without the `wrolpi` tag, the profile is new (first start, or a
restore), and every torrent in the config is added. With it, a torrent missing from qBittorrent was removed in the
WebUI, and leaves the config; a tagged torrent missing from the config was removed from the config, and leaves
qBittorrent (its files are kept).
- `paused` in the config is what the user wants. WROL Mode stops torrents with the `wrolpi-wrol-mode` tag, so they
are started again when it ends; any other stop or start of a torrent is the user's, and is saved.
"""
import asyncio
import base64
import hashlib
import pathlib
import re
import time
import urllib.parse
from dataclasses import dataclass, field
from typing import List, Optional
import aiohttp
from wrolpi import flags
from wrolpi.api_utils import perpetual_signal
from wrolpi.common import MultiFileConfig, get_media_directory, logger, wrol_mode_enabled, \
get_relative_to_media_directory, get_wrolpi_config
from wrolpi.errors import ValidationError
from wrolpi.vars import DOCKERIZED, PYTEST
from modules.torrents.qbittorrent import QBittorrent, QBittorrentError, QBittorrentUnavailable
logger = logger.getChild(__name__)
TAG = 'wrolpi'
WROL_MODE_TAG = 'wrolpi-wrol-mode'
TUNNEL_INTERFACE = 'vpn0'
# Where torrents are saved unless asked otherwise, relative to the media directory.
DEFAULT_SAVE_PATH = 'torrents'
STOPPED_STATES = {'stoppedUP', 'stoppedDL'}
# Downloaded, and being (or ready to be) seeded.
COMPLETE_STATES = {'uploading', 'stalledUP', 'forcedUP', 'queuedUP', 'stoppedUP', 'checkingUP'}
SYNC_SECONDS = 10
CONTROLLER_URL = 'http://controller' if DOCKERIZED else 'http://127.0.0.1'
@dataclass
class TorrentConfigValidator:
version: int
slug: str
name: str
save_path: str
paused: bool = False
magnet: str = None
complete: bool = False
# Stop seeding at this ratio / after this many minutes seeding. None: never.
seed_ratio_limit: float = None
seed_time_limit: int = None
class TorrentsConfig(MultiFileConfig):
subdirectory = 'torrents'
name = 'torrents'
validator = TorrentConfigValidator
default_entity = dict(version=0, slug=None, name=None, save_path=DEFAULT_SAVE_PATH, paused=False, magnet=None,
complete=False, seed_ratio_limit=None, seed_time_limit=None)
def get_torrent_file(self, slug: str) -> pathlib.Path:
return self.get_directory() / f'{slug}.torrent'
def update(self, slug: str, **values):
entity = self.get(slug)
if entity is None:
return
entity.update(values)
self.replace(slug, entity)
def delete(self, slug: str):
with self.save_lock():
self._configs.pop(slug, None)
self.get_file(slug).unlink(missing_ok=True)
self.get_torrent_file(slug).unlink(missing_ok=True)
TORRENTS_CONFIG = TorrentsConfig()
TEST_TORRENTS_CONFIG: Optional[TorrentsConfig] = None
def get_torrents_config() -> TorrentsConfig:
if isinstance(TEST_TORRENTS_CONFIG, TorrentsConfig):
return TEST_TORRENTS_CONFIG
return TORRENTS_CONFIG
def set_test_torrents_config(enabled: bool):
global TEST_TORRENTS_CONFIG
TEST_TORRENTS_CONFIG = TorrentsConfig() if enabled else None
def save_path_of(entity: dict) -> str:
"""The absolute directory qBittorrent saves a torrent in."""
save_path = pathlib.Path(entity.get('save_path') or DEFAULT_SAVE_PATH)
return str(save_path if save_path.is_absolute() else get_media_directory() / save_path)
def config_save_path(save_path: str) -> str:
"""How the config records qBittorrent's save path: relative to the media directory when it is in it."""
try:
return str(get_relative_to_media_directory(save_path))
except ValueError:
return save_path
MAX_TORRENT_FILE_BYTES = 20 * 1024 * 1024
HASH_RE = re.compile(r'^[0-9a-f]{40}$')
def bdecode(data: bytes, start: int = 0):
"""Decode the bencoded value (a .torrent file's) which starts at `start`. Returns (value, where it ends)."""
def decode(i: int):
c = data[i:i + 1]
if c == b'i':
end = data.index(b'e', i)
return int(data[i + 1:end]), end + 1
if c in (b'l', b'd'):
i += 1
items = []
while data[i:i + 1] != b'e':
item, i = decode(i)
items.append(item)
if c == b'l':
return items, i + 1
return dict(zip(items[::2], items[1::2])), i + 1
if c.isdigit():
colon = data.index(b':', i)
length = int(data[i:colon])
return data[colon + 1:colon + 1 + length], colon + 1 + length
raise ValueError(f'Not bencoded data at {i}')
return decode(start)
def torrent_identity(torrent: bytes) -> tuple[str, str]:
"""(hash, name) of a .torrent file, the hash as qBittorrent names it (see `torrent_id`)."""
v1, v2, name = torrent_info_hashes(torrent)
return torrent_id(v1, v2), name
def torrent_id(v1: Optional[str], v2: Optional[str]) -> str:
"""qBittorrent names a torrent by libtorrent's "best" info hash: the v2 (SHA-256) hash truncated to 40 characters
when it has one (a v2 or hybrid torrent), otherwise the v1 (SHA-1) hash."""
return v2[:40] if v2 else v1
def torrent_magnet(torrent: bytes) -> str:
"""A magnet link for a .torrent file, with both info hashes of a hybrid torrent."""
v1, v2, name = torrent_info_hashes(torrent)
return magnet_link(v1, v2, name)
def torrent_info_hashes(torrent: bytes) -> tuple[Optional[str], Optional[str], str]:
"""(v1 SHA-1 info hash or None, v2 SHA-256 info hash or None, name) of a .torrent file."""
if len(torrent) > MAX_TORRENT_FILE_BYTES:
raise ValidationError('That file is too large to be a .torrent file')
try:
if torrent[:1] != b'd':
raise ValueError('Not a dictionary')
# Walk the top-level dictionary to find the info dictionary exactly as it is written; that is what is hashed.
info = raw_info = None
i = 1
while torrent[i:i + 1] != b'e':
key, i = bdecode(torrent, i)
value_start = i
value, i = bdecode(torrent, i)
if key == b'info':
info, raw_info = value, torrent[value_start:i]
if not isinstance(info, dict):
raise ValueError('No info dictionary')
except (ValueError, KeyError, TypeError, IndexError) as e:
raise ValidationError('That is not a .torrent file') from e
# v1 torrents have `pieces`; v2 torrents have `meta version` 2 (a hybrid torrent has both).
v1 = hashlib.sha1(raw_info).hexdigest() if b'pieces' in info else None
v2 = hashlib.sha256(raw_info).hexdigest() if info.get(b'meta version') == 2 else None
if not v1 and not v2:
raise ValidationError('That is not a .torrent file')
name = info.get(b'name.utf-8') or info.get(b'name') or torrent_id(v1, v2).encode()
return v1, v2, name.decode('utf-8', errors='replace')
def magnet_identity(magnet: str) -> tuple[str, str]:
"""(hash, name) of a magnet link, the hash as qBittorrent names it (see `torrent_id`)."""
query = urllib.parse.parse_qs(urllib.parse.urlparse(magnet).query)
v1 = v2 = None
for xt in query.get('xt', []):
lower = xt.lower()
if lower.startswith('urn:btih:'):
value = xt[len('urn:btih:'):]
if len(value) == 32:
# Base32, as some magnet links write it.
value = base64.b32decode(value.upper()).hex()
if HASH_RE.match(value.lower()):
v1 = value.lower()
elif lower.startswith('urn:btmh:1220') and re.fullmatch(r'[0-9a-f]{64}', lower[len('urn:btmh:1220'):]):
# A v2 info hash: a SHA-256 multihash.
v2 = lower[len('urn:btmh:1220'):]
if not v1 and not v2:
raise ValidationError('That magnet link has no BitTorrent info hash (xt=urn:btih:... or xt=urn:btmh:...)')
hash_ = torrent_id(v1, v2)
return hash_, (query.get('dn') or [hash_])[0]
def magnet_link(v1: Optional[str], v2: Optional[str], name: str) -> str:
xts = ([f'xt=urn:btih:{v1}'] if v1 else []) + ([f'xt=urn:btmh:1220{v2}'] if v2 else [])
return f'magnet:?{"&".join(xts)}&dn={urllib.parse.quote(name)}'
def check_save_path(save_path: str) -> str:
"""A save path relative to the media directory, which must stay in it (torrents are only saved in the library)."""
save_path = save_path or DEFAULT_SAVE_PATH
media_directory = get_media_directory()
path = pathlib.Path(save_path)
absolute = (path if path.is_absolute() else media_directory / path).resolve()
if absolute != media_directory and media_directory not in absolute.parents:
raise ValidationError('Torrents can only be saved in the media directory')
if absolute == media_directory / 'config' or media_directory / 'config' in absolute.parents:
raise ValidationError("Torrents cannot be saved in WROLPi's config directory")
return str(absolute.relative_to(media_directory)) or '.'
async def add_torrent(save_path: str = None, torrent: bytes = None, magnet: str = None,
client: QBittorrent = None, skip_checking: bool = False) -> dict:
"""Add a torrent from a .torrent file's bytes, or a magnet link: to the config (the source of truth), then to
qBittorrent. Returns its config."""
client = client or QBittorrent()
config = get_torrents_config()
save_path = check_save_path(save_path)
if torrent:
hash_, name = torrent_identity(torrent)
magnet = torrent_magnet(torrent)
elif magnet:
hash_, name = magnet_identity(magnet)
else:
raise ValidationError('A .torrent file or a magnet link is required')
if config.get(hash_) is None:
config.create(hash_, dict(slug=hash_, name=name, save_path=save_path, magnet=magnet))
if torrent:
config.get_torrent_file(hash_).write_bytes(torrent)
if hash_ not in {t['hash'] for t in await client.torrents()}:
await add_from_config(client, config.get(hash_), stopped=wrol_mode_enabled(), skip_checking=skip_checking)
return config.get(hash_)
async def remove_torrent(hash_: str, delete_files: bool = False, client: QBittorrent = None):
client = client or QBittorrent()
await client.delete([hash_], delete_files=delete_files)
get_torrents_config().delete(hash_)
async def set_paused(hash_: str, paused: bool, client: QBittorrent = None):
client = client or QBittorrent()
config = get_torrents_config()
if config.get(hash_) is None:
raise ValidationError('Unknown torrent')
config.update(hash_, paused=paused)
if paused:
await client.stop([hash_])
elif not wrol_mode_enabled():
await client.start([hash_])
def set_share_limits(hash_: str, seed_ratio_limit: float = None, seed_time_limit: int = None):
"""None is no limit. The torrents worker applies them."""
if seed_ratio_limit is not None and seed_ratio_limit < 0:
raise ValidationError('The ratio limit cannot be negative')
if seed_time_limit is not None and seed_time_limit < 0:
raise ValidationError('The seeding time limit cannot be negative')
config = get_torrents_config()
if config.get(hash_) is None:
raise ValidationError('Unknown torrent')
config.update(hash_, seed_ratio_limit=seed_ratio_limit, seed_time_limit=seed_time_limit)
async def get_vpn_status() -> dict:
"""The Controller's report of the VPN torrents use; {} when the Controller cannot be reached."""
try:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
async with session.get(f'{CONTROLLER_URL}/api/vpn/status') as response:
return await response.json() if response.status == 200 else {}
except (aiohttp.ClientError, TimeoutError, ValueError):
return {}
def desired_preferences(vpn_status: dict) -> dict:
preferences = {
# Torrents use only the tunnel. (The kill switch already blocks everything else.)
'current_network_interface': TUNNEL_INTERFACE,
'current_interface_address': '',
# The router UPnP or NAT-PMP would ask is the VPN's; the tunnel asks for the port itself.
'upnp': False,
# Nothing to discover on the tunnel's "local" network.
'lsd': False,
# A file still downloading is never mistaken for a finished one.
'incomplete_files_ext': True,
'save_path': str(get_media_directory() / DEFAULT_SAVE_PATH),
'random_port': False,
# Peers are not told which client (and version) this is, so a known flaw in one cannot be aimed at it.
'anonymous_mode': True,
# Running a program would be code execution for anyone who can reach the WebUI.
'autorun_enabled': False,
'autorun_on_torrent_added_enabled': False,
}
wrolpi_config = get_wrolpi_config()
# qBittorrent's limits are bytes per second; 0 is unlimited.
preferences['up_limit'] = (wrolpi_config.torrent_upload_limit or 0) * 1024
preferences['dl_limit'] = (wrolpi_config.torrent_download_limit or 0) * 1024
if port := vpn_status.get('forwarded_port'):
# Peers connect to the port the VPN forwards.
preferences['listen_port'] = port
return preferences
async def enforce_preferences(client: QBittorrent, vpn_status: dict) -> dict:
"""Set the preferences which differ from what WROLPi needs; returns those changed."""
current = await client.preferences()
changed = {k: v for k, v in desired_preferences(vpn_status).items() if current.get(k) != v}
if changed:
logger.info(f'Setting qBittorrent preferences: {changed}')
await client.set_preferences(changed)
return changed
async def add_from_config(client: QBittorrent, entity: dict, stopped: bool, skip_checking: bool = False):
config = get_torrents_config()
torrent_file = config.get_torrent_file(entity['slug'])
torrent = torrent_file.read_bytes() if torrent_file.is_file() else None
if not torrent and not entity.get('magnet'):
logger.error(f'Cannot add torrent {entity["name"]}: it has no .torrent file and no magnet link')
return
pathlib.Path(save_path_of(entity)).mkdir(parents=True, exist_ok=True)
tags = [TAG, WROL_MODE_TAG] if stopped and not entity.get('paused') else [TAG]
await client.add(save_path_of(entity), torrent=torrent, url=None if torrent else entity['magnet'], tags=tags,
stopped=stopped, skip_checking=skip_checking)
logger.info(f'Added torrent {entity["name"]} to qBittorrent')
async def adopt(client: QBittorrent, torrent: dict) -> bool:
"""Add a torrent added in qBittorrent's WebUI to the config, once its metadata has arrived."""
exported = await client.export(torrent['hash'])
if not exported:
return False
config = get_torrents_config()
slug = torrent['hash']
config.get_torrent_file(slug).parent.mkdir(parents=True, exist_ok=True)
config.get_torrent_file(slug).write_bytes(exported)
if config.get(slug) is None:
# (WROLPi may have recorded it already, e.g. while it was still adding the torrent.)
config.create(slug, dict(slug=slug, name=torrent['name'], save_path=config_save_path(torrent['save_path']),
paused=torrent['state'] in STOPPED_STATES, magnet=torrent.get('magnet_uri')))
await client.add_tags([slug], TAG)
logger.info(f'Adopted torrent {torrent["name"]} added in qBittorrent')
return True
# How long a torrent may be in the config, but not yet in qBittorrent, before it is added from the config (another
# process may be adding it).
ADD_GRACE_SECONDS = 30
@dataclass
class ReconcileState:
"""What reconcile has seen, across its passes. A torrent is forgotten (removed in the WebUI) only once it has been
seen in qBittorrent; one never seen is being added, or must be added."""
seen: set = field(default_factory=set)
missing_since: dict = field(default_factory=dict)
RECONCILE_STATE = ReconcileState()
async def reconcile(client: QBittorrent, wrol_mode: bool, state: ReconcileState = None) -> dict:
"""Make qBittorrent and the config agree; returns what was done (for tests and logs)."""
state = state or ReconcileState()
config = get_torrents_config()
done = dict(added=[], adopted=[], forgotten=[], removed=[], stopped=[], started=[], completed=[])
torrents = {t['hash']: t for t in await client.torrents()}
entities = {e['slug']: e for e in config.all()}
if TAG not in await client.tags():
# A new qBittorrent profile: add every torrent the config has.
await client.create_tags(TAG, WROL_MODE_TAG)
for slug, entity in entities.items():
if slug not in torrents:
await add_from_config(client, entity, stopped=wrol_mode or bool(entity.get('paused')))
done['added'].append(slug)
return done
for slug, torrent in torrents.items():
tags = {t.strip() for t in (torrent.get('tags') or '').split(',') if t.strip()}
if TAG not in tags:
if await adopt(client, torrent):
done['adopted'].append(slug)
continue
entity = entities.get(slug)
if entity is None:
# Removed from the config: removed from qBittorrent, its files kept.
await client.delete([slug], delete_files=False)
done['removed'].append(slug)
state.seen.discard(slug)
continue
state.seen.add(slug)
stopped = torrent['state'] in STOPPED_STATES
if wrol_mode:
if not stopped:
await client.add_tags([slug], WROL_MODE_TAG)
await client.stop([slug])
done['stopped'].append(slug)
elif WROL_MODE_TAG in tags:
# Stopped by WROL Mode, which has ended.
await client.remove_tags([slug], WROL_MODE_TAG)
if not entity.get('paused'):
await client.start([slug])
done['started'].append(slug)
elif stopped != bool(entity.get('paused')):
# Stopped or started in the WebUI: that is what the user wants now.
config.update(slug, paused=stopped)
ratio_limit = -1 if entity.get('seed_ratio_limit') is None else entity['seed_ratio_limit']
time_limit = -1 if entity.get('seed_time_limit') is None else entity['seed_time_limit']
if torrent.get('ratio_limit') != ratio_limit or torrent.get('seeding_time_limit') != time_limit:
await client.set_share_limits([slug], ratio_limit, time_limit)
if not entity.get('complete') and torrent['state'] in COMPLETE_STATES and torrent.get('progress', 0) >= 1:
config.update(slug, complete=True)
done['completed'].append(slug)
index_downloaded(torrent)
if not config.get_torrent_file(slug).is_file() and (exported := await client.export(slug)):
config.get_torrent_file(slug).write_bytes(exported)
now = time.monotonic()
missing = entities.keys() - torrents.keys()
state.missing_since = {slug: since for slug, since in state.missing_since.items() if slug in missing}
for slug in missing:
if slug in state.seen:
# Removed in the WebUI.
config.delete(slug)
state.seen.discard(slug)
done['forgotten'].append(slug)
elif now - state.missing_since.setdefault(slug, now) >= ADD_GRACE_SECONDS:
# Never shown by qBittorrent: its add failed, or the config was restored.
entity = entities[slug]
await add_from_config(client, entity, stopped=wrol_mode or bool(entity.get('paused')))
del state.missing_since[slug]
done['added'].append(slug)
return done
def index_downloaded(torrent: dict):
"""Index a finished torrent's files, as any other download's."""
from wrolpi.files.worker import file_worker
content_path = pathlib.Path(torrent.get('content_path') or torrent['save_path'])
try:
content_path.relative_to(get_media_directory())
except ValueError:
logger.warning(f'Not indexing torrent {torrent["name"]}: it is outside the media directory')
return
file_worker.queue_refresh([content_path], expand_stems=True)
TORRENT_DOWNLOADER = 'torrent'
# qBittorrent's ETA for "never".
ETA_UNKNOWN = 8640000
def format_eta(seconds: int) -> Optional[str]:
if seconds is None or seconds < 0 or seconds >= ETA_UNKNOWN:
return None
hours, rest = divmod(int(seconds), 3600)
minutes, seconds = divmod(rest, 60)
return f'{hours}:{minutes:02}:{seconds:02}' if hours else f'{minutes}:{seconds:02}'
def sync_download_rows(torrents: dict):
"""Show each torrent's progress on its Download (the Downloads page), which finished when it was added: no
download worker waits days for a torrent. It is shown as completed once the torrent is."""
from wrolpi.db import get_db_session
from wrolpi.downloader import Download, set_download_progress, clear_download_progress
from wrolpi.dates import now
with get_db_session(commit=True) as session:
for download in session.query(Download).filter(Download.downloader == TORRENT_DOWNLOADER):
torrent = torrents.get((download.info_json or {}).get('torrent_hash'))
if not torrent:
clear_download_progress(download.id)
elif torrent.get('progress', 0) < 1:
set_download_progress(download.id, dict(
percent=round(torrent.get('progress', 0) * 100, 1),
speed=torrent.get('dlspeed'),
eta=format_eta(torrent.get('eta')),
bytes_downloaded=torrent.get('completed'),
total_bytes=torrent.get('size'),
))
download.last_successful_download = None
else:
clear_download_progress(download.id)
if download.last_successful_download is None:
download.last_successful_download = now()
async def sync_torrents(client: QBittorrent = None) -> Optional[dict]:
"""One pass: qBittorrent's preferences, and the config; None when qBittorrent cannot be reached."""
client = client or QBittorrent()
vpn_status = await get_vpn_status()
try:
await client.version()
except QBittorrentUnavailable:
publish_summary(len(get_torrents_config().slugs), vpn_status.get('state'), running=False)
return None
await enforce_preferences(client, vpn_status)
done = await reconcile(client, wrol_mode_enabled(), RECONCILE_STATE)
torrents = await client.torrents()
await asyncio.to_thread(sync_download_rows, {t['hash']: t for t in torrents})
publish_summary(len(torrents), vpn_status.get('state'), running=True)
return done
def publish_summary(count: int, vpn_state: Optional[str], running: bool):
"""What /api/status tells the navigation: torrents exist, and whether the VPN they need is connected."""
from wrolpi.api_utils import api_app
try:
api_app.shared_ctx.torrents_summary.update(count=count, vpn_state=vpn_state, running=running)
except AttributeError:
# The shared context is not attached (some unit tests).
pass
@perpetual_signal(sleep=SYNC_SECONDS)
async def torrents_worker():
if PYTEST or not flags.media_mounted.is_set() or not get_torrents_config().successful_import:
return
try:
done = await sync_torrents()
except (QBittorrentError, QBittorrentUnavailable, OSError) as e:
logger.warning(f'Could not sync torrents with qBittorrent: {e}')
return
if done and any(done.values()):
logger.info(f'Synced torrents with qBittorrent: { {k: v for k, v in done.items() if v} }')
async def get_torrents_status(client: QBittorrent = None) -> dict:
"""qBittorrent's state, the VPN's, and every torrent, for the API."""
client = client or QBittorrent()
config = get_torrents_config()
vpn_status = await get_vpn_status()
try:
transfer, torrents = await asyncio.gather(client.transfer_info(), client.torrents())
except (QBittorrentUnavailable, QBittorrentError) as e:
return dict(running=False, error=str(e), vpn=vpn_status, torrents=[],
limits=dict(upload=get_wrolpi_config().torrent_upload_limit,
download=get_wrolpi_config().torrent_download_limit),
trackers=get_wrolpi_config().torrent_trackers)
return dict(
running=True,
error=None,
vpn=vpn_status,
# connected (peers can reach this WROLPi), firewalled, or disconnected.
connection_status=transfer.get('connection_status'),
upload_speed=transfer.get('up_info_speed'),
download_speed=transfer.get('dl_info_speed'),
limits=dict(upload=get_wrolpi_config().torrent_upload_limit,
download=get_wrolpi_config().torrent_download_limit),
trackers=get_wrolpi_config().torrent_trackers,
torrents=[torrent_status(t, config.get(t['hash'])) for t in torrents],
)
def torrent_status(torrent: dict, entity: Optional[dict]) -> dict:
entity = entity or {}
return dict(
hash=torrent['hash'],
name=torrent['name'],
size=torrent.get('size'),
progress=torrent.get('progress'),
state=torrent.get('state'),
ratio=torrent.get('ratio'),
uploaded=torrent.get('uploaded'),
upload_speed=torrent.get('upspeed'),
download_speed=torrent.get('dlspeed'),
eta=format_eta(torrent.get('eta')),
peers=torrent.get('num_leechs'),
seeds=torrent.get('num_seeds'),
save_path=config_save_path(torrent.get('save_path') or ''),
# Managed by WROLPi (in config/torrents/); otherwise not yet adopted (e.g. waiting for a magnet's metadata).
managed=bool(entity),
paused=entity.get('paused', torrent.get('state') in STOPPED_STATES),
seed_ratio_limit=entity.get('seed_ratio_limit'),
seed_time_limit=entity.get('seed_time_limit'),
magnet=entity.get('magnet') or torrent.get('magnet_uri'),
)

View file

@ -0,0 +1,138 @@
"""
A small client of qBittorrent's WebUI API (v2, qBittorrent 5).
qBittorrent runs inside the VPN's network namespace. WROLPi reaches its WebUI through the namespace's uplink, from
which it needs no password (see qbittorrent_prepare.py).
"""
import json
from typing import List, Optional
import aiohttp
from wrolpi.vars import DOCKERIZED
WEBUI_PORT = 8091
# Docker: qBittorrent runs in the `vpn` container, beside the tunnel. Raspberry Pi / Debian: the `wrolpi-vpn`
# namespace's end of its veth pair (etc/raspberrypios/wrolpi-vpn-netns.sh).
QBITTORRENT_URL = f'http://vpn:{WEBUI_PORT}' if DOCKERIZED else f'http://10.211.0.2:{WEBUI_PORT}'
TIMEOUT = aiohttp.ClientTimeout(total=10)
class QBittorrentUnavailable(Exception):
"""qBittorrent is not running, or cannot be reached."""
class QBittorrentError(Exception):
"""qBittorrent refused a request."""
class QBittorrent:
def __init__(self, url: str = QBITTORRENT_URL):
self.url = url.rstrip('/')
async def _request(self, method: str, path: str, params: dict = None, data=None) -> bytes:
try:
async with aiohttp.ClientSession(timeout=TIMEOUT) as session:
async with session.request(method, f'{self.url}/api/v2/{path}', params=params, data=data) as response:
body = await response.read()
if response.status >= 400:
raise QBittorrentError(f'qBittorrent refused {path} ({response.status}): {body[:200]!r}')
return body
except (aiohttp.ClientConnectionError, TimeoutError) as e:
raise QBittorrentUnavailable(f'Cannot reach qBittorrent at {self.url}: {e}') from e
async def _get_json(self, path: str, **params):
return json.loads(await self._request('GET', path, params=params or None))
async def version(self) -> str:
return (await self._request('GET', 'app/version')).decode()
async def preferences(self) -> dict:
return await self._get_json('app/preferences')
async def set_preferences(self, preferences: dict):
await self._request('POST', 'app/setPreferences', data={'json': json.dumps(preferences)})
async def transfer_info(self) -> dict:
return await self._get_json('transfer/info')
async def torrents(self) -> List[dict]:
return await self._get_json('torrents/info')
async def tags(self) -> List[str]:
return await self._get_json('torrents/tags')
async def create_tags(self, *tags: str):
await self._request('POST', 'torrents/createTags', data={'tags': ','.join(tags)})
async def add_tags(self, hashes: List[str], *tags: str):
await self._request('POST', 'torrents/addTags', data={'hashes': '|'.join(hashes), 'tags': ','.join(tags)})
async def remove_tags(self, hashes: List[str], *tags: str):
await self._request('POST', 'torrents/removeTags', data={'hashes': '|'.join(hashes), 'tags': ','.join(tags)})
async def add(self, save_path: str, torrent: bytes = None, url: str = None, tags: List[str] = None,
stopped: bool = False, skip_checking: bool = False):
"""Add a torrent from a .torrent file's bytes, or a magnet link / URL."""
form = aiohttp.FormData()
if torrent:
form.add_field('torrents', torrent, filename='file.torrent', content_type='application/x-bittorrent')
elif url:
form.add_field('urls', url)
else:
raise ValueError('A torrent or a URL is required')
form.add_field('savepath', save_path)
form.add_field('stopped', 'true' if stopped else 'false')
if skip_checking:
# Its files were just hashed to make it; do not hash them again.
form.add_field('skip_checking', 'true')
if tags:
form.add_field('tags', ','.join(tags))
body = await self._request('POST', 'torrents/add', data=form)
if body.strip() == b'Fails.':
raise QBittorrentError('qBittorrent could not add the torrent')
async def delete(self, hashes: List[str], delete_files: bool = False):
await self._request('POST', 'torrents/delete',
data={'hashes': '|'.join(hashes), 'deleteFiles': 'true' if delete_files else 'false'})
async def export(self, hash_: str) -> Optional[bytes]:
"""The .torrent file of a torrent, or None while a magnet link's metadata has not arrived."""
try:
return await self._request('GET', 'torrents/export', params={'hash': hash_})
except QBittorrentError:
return None
async def start(self, hashes: List[str]):
await self._request('POST', 'torrents/start', data={'hashes': '|'.join(hashes)})
async def stop(self, hashes: List[str]):
await self._request('POST', 'torrents/stop', data={'hashes': '|'.join(hashes)})
async def set_share_limits(self, hashes: List[str], ratio_limit: float, seeding_time_limit: int):
"""Stop seeding at a ratio / after minutes seeding; -2 is qBittorrent's global setting, -1 is no limit."""
await self._request('POST', 'torrents/setShareLimits', data={
'hashes': '|'.join(hashes), 'ratioLimit': str(ratio_limit), 'seedingTimeLimit': str(seeding_time_limit),
'inactiveSeedingTimeLimit': '-2'})
async def create_torrent(self, source_path: str, trackers: List[str], url_seeds: List[str]) -> str:
"""Start making a hybrid (v1 and v2) torrent of a file or directory; returns the task's ID. qBittorrent does
not add it; WROLPi does."""
body = await self._request('POST', 'torrentcreator/addTask', data={
'sourcePath': source_path, 'format': 'hybrid', 'startSeeding': 'false',
'trackers': '|'.join(trackers), 'urlSeeds': '|'.join(url_seeds)})
return json.loads(body)['taskID']
async def torrent_creator_status(self, task_id: str) -> dict:
"""{'status': 'Queued' | 'Running' | 'Finished' | 'Failed', 'progress': 0-100, 'errorMessage': ...}"""
tasks = await self._get_json('torrentcreator/status', taskID=task_id)
if not tasks:
raise QBittorrentError(f'qBittorrent has no torrent creator task {task_id}')
return tasks[0]
async def torrent_creator_file(self, task_id: str) -> bytes:
return await self._request('GET', 'torrentcreator/torrentFile', params={'taskID': task_id})
async def delete_torrent_creator_task(self, task_id: str):
await self._request('POST', 'torrentcreator/deleteTask', data={'taskID': task_id})

View file

@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""
Prepare qBittorrent's config before it starts, inside the VPN's network namespace.
qBittorrent runs in the namespace the VPN's kill switch guards (controller/vpn/tunnel.py): the `wrolpi-vpn` namespace
on a Raspberry Pi or Debian, or the `vpn` container's on Docker. Its WebUI must be reachable by WROLPi (the API, and
Caddy, which serves it to the LAN on port 8091) through the namespace's uplink, and never through the tunnel. So the
WebUI listens only on the uplink's address, and needs no password from the addresses allowed (`--allow`: the host's
end of the veth pair on a Raspberry Pi, the compose network on Docker). WROLPi has no logins; the LAN reaches the
WebUI only through Caddy, over TLS, and Caddy refuses qBittorrent's settings (they can run programs). Torrents use
only the tunnel's interface from the first moment; WROLPi enforces the rest of the preferences once qBittorrent is
up.
This runs standalone (in the `vpn` container, or before wrolpi-torrent.service), so it imports only the standard
library.
"""
import argparse
import configparser
import ipaddress
import json
import pathlib
import subprocess
WEBUI_PORT = 8091
TUNNEL_INTERFACE = 'vpn0'
def find_uplink() -> tuple[str, str]:
"""The namespace's uplink: (its address, its network). The tunnel never replaces the default route, so the
default route's interface is the uplink."""
routes = json.loads(subprocess.check_output(['ip', '-j', '-4', 'route', 'show', 'default']) or b'[]')
interfaces = [r['dev'] for r in routes if r.get('dev') and r['dev'] != TUNNEL_INTERFACE]
if not interfaces:
raise RuntimeError('The VPN namespace has no uplink; is the VPN service running?')
addresses = json.loads(subprocess.check_output(['ip', '-j', '-4', 'addr', 'show', 'dev', interfaces[0]]) or b'[]')
for entry in addresses:
for address in entry.get('addr_info', []):
if address.get('scope') == 'global':
interface = ipaddress.ip_interface(f"{address['local']}/{address['prefixlen']}")
return str(interface.ip), str(interface.network)
raise RuntimeError(f'The VPN namespace uplink {interfaces[0]} has no address')
def prepare(profile: pathlib.Path, address: str, allowed: list[str]) -> pathlib.Path:
"""Write the WebUI and interface settings into qBittorrent's config, keeping everything else in it."""
path = profile / 'qBittorrent' / 'config' / 'qBittorrent.conf'
# qBittorrent's config is Qt's INI: case-sensitive keys, `\` in key names, no interpolation.
config = configparser.RawConfigParser(strict=False)
config.optionxform = str
if path.is_file():
config.read(path, encoding='utf-8')
settings = {
'Preferences': {
'WebUI\\Enabled': 'true',
'WebUI\\Address': address,
'WebUI\\Port': str(WEBUI_PORT),
'WebUI\\LocalHostAuth': 'false',
'WebUI\\AuthSubnetWhitelistEnabled': 'true',
'WebUI\\AuthSubnetWhitelist': ', '.join(allowed),
# Reached by the LAN through Caddy, so the Host is this WROLPi's LAN address, not the uplink's. Plain HTTP
# on this port is only reachable from the host or the compose network, so no browser visiting another
# site can reach it under that site's name (DNS rebinding); the LAN gets Caddy's TLS.
'WebUI\\HostHeaderValidation': 'false',
},
'BitTorrent': {
'Session\\Interface': TUNNEL_INTERFACE,
'Session\\InterfaceName': TUNNEL_INTERFACE,
},
# Never run a program (WROLPi also forces these off, and Caddy refuses the WebUI's settings).
'AutoRun': {
'enabled': 'false',
'OnTorrentAdded\\Enabled': 'false',
},
'LegalNotice': {
'Accepted': 'true',
},
}
for section, values in settings.items():
if not config.has_section(section):
config.add_section(section)
for key, value in values.items():
config.set(section, key, value)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, 'w', encoding='utf-8') as f:
config.write(f, space_around_delimiters=False)
return path
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0])
parser.add_argument('--profile', type=pathlib.Path, required=True, help="qBittorrent's --profile directory")
parser.add_argument('--allow', action='append',
help="A network which needs no WebUI password; repeatable. Default: the uplink's network")
parser.add_argument('--uplink', type=ipaddress.ip_interface,
help="The uplink's address and prefix (e.g. 10.211.0.2/30). Default: found with `ip`; a unit "
"whose seccomp filter forbids capset must give it, as `ip` drops capabilities with capset")
args = parser.parse_args(argv)
if args.uplink:
address, network = str(args.uplink.ip), str(args.uplink.network)
else:
address, network = find_uplink()
allowed = [str(ipaddress.ip_network(i)) for i in args.allow] if args.allow else [network]
path = prepare(args.profile, address, allowed)
print(f'qBittorrent WebUI on {address}:{WEBUI_PORT}, without a password from {", ".join(allowed)}; config {path}')
if __name__ == '__main__':
main()

126
modules/torrents/share.py Normal file
View file

@ -0,0 +1,126 @@
"""
"Share as torrent": make a torrent of a file or directory already in the library, and seed it.
qBittorrent hashes the files (a 659 GB file takes an hour or more on a Raspberry Pi), so this runs as a Job, which
shows its progress and can be cancelled. The new torrent is a hybrid (v1 and v2) torrent, with the trackers and web
seeds given; WROLPi adds it to config/torrents/ and qBittorrent without hashing the files again.
"""
import asyncio
import pathlib
import urllib.parse
from typing import List
from modules.torrents import lib
from modules.torrents.qbittorrent import QBittorrent, QBittorrentError
from wrolpi.common import get_media_directory, logger
from wrolpi.errors import ValidationError
from wrolpi.jobs import enqueue_job, get_current_job, register_job
logger = logger.getChild(__name__)
SHARE_JOB = 'share_torrent'
POLL_SECONDS = 2
def publishes_config(path: pathlib.Path, media_directory: pathlib.Path) -> bool:
"""True when a torrent of `path` would include WROLPi's config directory (the VPN's key and login, and more): it
is config/, is inside it, or holds it (the library itself)."""
config_directory = media_directory / 'config'
return path == config_directory or config_directory in path.parents or path in config_directory.parents
def check_share_path(path: str) -> pathlib.Path:
"""The absolute path of a file or directory in the library (not WROLPi's config) to make a torrent of."""
path = (path or '').rstrip('/')
if not path:
raise ValidationError('Choose a file or directory to share')
lib.check_save_path(path)
media_directory = get_media_directory().resolve()
absolute = (media_directory / path).resolve()
if not absolute.exists():
raise ValidationError(f'{path} does not exist')
if publishes_config(absolute, media_directory):
raise ValidationError("A torrent cannot include WROLPi's config directory")
if absolute.is_dir():
files = False
for item in absolute.rglob('*'):
if item.is_symlink():
# A link would publish what it points at. A link to a folder could lead anywhere (and its own links
# are not walked here), so only links to files in the library are allowed.
target = item.resolve()
if target.is_dir():
raise ValidationError(f'{item.relative_to(media_directory)} links to a folder; a torrent cannot '
f'include links to folders')
if publishes_config(target, media_directory) or media_directory not in target.parents:
raise ValidationError(f'{item.relative_to(media_directory)} links outside the library or into '
f"WROLPi's config directory")
files = files or item.is_file()
if not files:
raise ValidationError(f'{path} has no files to share')
return absolute
def check_urls(urls: List[str], schemes: tuple, what: str) -> List[str]:
checked = []
for url in urls or []:
url = url.strip()
if not url:
continue
parsed = urllib.parse.urlparse(url)
if parsed.scheme not in schemes or not parsed.hostname or any(c in url for c in '|\r\n '):
raise ValidationError(f'{url!r} is not a {what} ({" or ".join(schemes)})')
if url not in checked:
checked.append(url)
return checked
def check_trackers(trackers: List[str]) -> List[str]:
return check_urls(trackers, ('udp', 'http', 'https'), 'tracker URL')
def check_web_seeds(web_seeds: List[str]) -> List[str]:
return check_urls(web_seeds, ('http', 'https'), 'web seed URL')
def share(path: str, trackers: List[str], web_seeds: List[str]) -> str:
"""Check the request and start the Job; returns its ID."""
source = check_share_path(path)
trackers, web_seeds = check_trackers(trackers), check_web_seeds(web_seeds)
relative = source.relative_to(get_media_directory())
return enqueue_job(SHARE_JOB, description=f'Make a torrent of {relative}', path=str(relative), trackers=trackers,
web_seeds=web_seeds)
@register_job(SHARE_JOB)
async def share_torrent(path: str, trackers: List[str], web_seeds: List[str], client: QBittorrent = None) -> dict:
job = get_current_job()
client = client or QBittorrent()
source = check_share_path(path)
logger.info(f'Making a torrent of {path}')
task_id = await client.create_torrent(str(source), trackers, web_seeds)
try:
while True:
status = await client.torrent_creator_status(task_id)
if status['status'] == 'Finished':
break
if status['status'] == 'Failed':
raise QBittorrentError(f'qBittorrent could not make the torrent: {status.get("errorMessage")}')
if job:
job.set_progress(status.get('progress'))
if job.cancel_requested():
raise asyncio.CancelledError('The torrent was cancelled while it was being made')
await asyncio.sleep(POLL_SECONDS)
torrent = await client.torrent_creator_file(task_id)
finally:
# A cancelled task stops hashing; a finished one is no longer needed.
try:
await client.delete_torrent_creator_task(task_id)
except QBittorrentError as e:
logger.warning(f'Could not delete the torrent creator task {task_id}: {e}')
# Seed from where the files already are: the torrent is named after them, in their directory.
save_path = str(source.parent.relative_to(get_media_directory())) or '.'
entity = await lib.add_torrent(save_path, torrent=torrent, client=client, skip_checking=True)
lib.get_torrents_config().update(entity['slug'], complete=True)
logger.info(f'Made the torrent {entity["name"]} ({entity["slug"]}), and seeding it')
return dict(hash=entity['slug'], name=entity['name'], magnet=entity['magnet'])

View file

View file

@ -0,0 +1,297 @@
"""Adding torrents (magnet links, .torrent files and URLs), managing them, and their progress on the Downloads page."""
import hashlib
from http import HTTPStatus
from unittest import mock
import pytest
from modules.torrents import lib
from modules.torrents.downloader import TorrentDownloader, PreparedTorrent, ExecutedTorrent
from wrolpi.downloader import Download
from wrolpi.errors import ValidationError
def bencode(value) -> bytes:
if isinstance(value, int):
return f'i{value}e'.encode()
if isinstance(value, str):
value = value.encode()
if isinstance(value, bytes):
return f'{len(value)}:'.encode() + value
if isinstance(value, list):
return b'l' + b''.join(bencode(i) for i in value) + b'e'
if isinstance(value, dict):
return b'd' + b''.join(bencode(k) + bencode(value[k]) for k in sorted(value)) + b'e'
raise TypeError(value)
INFO = {'name': 'planet.pmtiles', 'piece length': 16384, 'pieces': b'\x00' * 20, 'length': 1000}
# The announce URL holds the bytes which start the info dictionary; it must not be mistaken for it.
TORRENT = bencode({'announce': 'http://tracker.example/4:infod', 'info': INFO})
HASH = hashlib.sha1(bencode(INFO)).hexdigest()
class TestIdentity:
def test_torrent_file(self):
assert lib.torrent_identity(TORRENT) == (HASH, 'planet.pmtiles')
def test_v2_only(self):
info = {'name': 'v2', 'piece length': 16384, 'meta version': 2, 'file tree': {}}
torrent = bencode({'info': info})
v2 = hashlib.sha256(bencode(info)).hexdigest()
assert lib.torrent_identity(torrent)[0] == v2[:40]
assert lib.torrent_magnet(torrent) == f'magnet:?xt=urn:btmh:1220{v2}&dn=v2'
def test_hybrid(self):
"""A hybrid torrent (what "Share as torrent" makes) is named by its truncated v2 hash, as qBittorrent names it
(libtorrent's "best" hash); its magnet link carries both hashes."""
info = {**INFO, 'meta version': 2, 'file tree': {}}
torrent = bencode({'info': info})
v1, v2 = hashlib.sha1(bencode(info)).hexdigest(), hashlib.sha256(bencode(info)).hexdigest()
assert lib.torrent_identity(torrent) == (v2[:40], 'planet.pmtiles')
magnet = lib.torrent_magnet(torrent)
assert magnet == f'magnet:?xt=urn:btih:{v1}&xt=urn:btmh:1220{v2}&dn=planet.pmtiles'
assert lib.magnet_identity(magnet) == (v2[:40], 'planet.pmtiles')
@pytest.mark.parametrize('torrent', [b'', b'not a torrent', bencode({'announce': 'x'}), bencode([1, 2]),
b'd4:infoi1ee', b'x' * (lib.MAX_TORRENT_FILE_BYTES + 1)])
def test_not_a_torrent(self, torrent):
with pytest.raises(ValidationError):
lib.torrent_identity(torrent)
def test_magnet(self):
assert lib.magnet_identity(f'magnet:?xt=urn:btih:{HASH.upper()}&dn=planet') == (HASH, 'planet')
base32 = __import__('base64').b32encode(bytes.fromhex(HASH)).decode()
assert lib.magnet_identity(f'magnet:?xt=urn:btih:{base32}')[0] == HASH
with pytest.raises(ValidationError):
lib.magnet_identity('magnet:?dn=no-hash')
# A v1 magnet link of a hybrid torrent still names it by v1 (qBittorrent knows nothing else of it).
v2 = 'c' * 64
assert lib.magnet_identity(f'magnet:?xt=urn:btmh:1220{v2}')[0] == v2[:40]
def test_magnet_link_round_trips(self):
assert lib.magnet_identity(lib.magnet_link(HASH, None, 'a planet & more')) == (HASH, 'a planet & more')
class TestSavePath:
def test_in_the_library(self, test_directory):
assert lib.check_save_path('maps') == 'maps'
assert lib.check_save_path(str(test_directory / 'maps' / 'big')) == 'maps/big'
assert lib.check_save_path(None) == lib.DEFAULT_SAVE_PATH
@pytest.mark.parametrize('save_path', ['../outside', '/etc', 'config', 'config/torrents', 'maps/../../x'])
def test_refused(self, test_directory, save_path):
with pytest.raises(ValidationError):
lib.check_save_path(save_path)
async def test_add_torrent_file(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
entity = await lib.add_torrent('maps', torrent=TORRENT, client=client)
assert entity['slug'] == HASH
assert entity['name'] == 'planet.pmtiles'
assert entity['save_path'] == 'maps'
assert lib.magnet_identity(entity['magnet'])[0] == HASH
assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT
_, save_path, torrent, url, tags, stopped = next(c for c in client.calls if c[0] == 'add')
assert save_path == str(lib.get_media_directory() / 'maps')
assert (torrent, url, tags, stopped) == (TORRENT, None, [lib.TAG], False)
async def test_add_magnet_once(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
magnet = f'magnet:?xt=urn:btih:{HASH}&dn=planet'
await lib.add_torrent(None, magnet=magnet, client=client)
await lib.add_torrent(None, magnet=magnet, client=client)
adds = [c for c in client.calls if c[0] == 'add']
assert len(adds) == 1
assert adds[0][3] == magnet
assert test_torrents_config.get(HASH)['save_path'] == lib.DEFAULT_SAVE_PATH
async def test_pause_resume_remove(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
await lib.add_torrent(None, torrent=TORRENT, client=client)
await lib.set_paused(HASH, True, client=client)
assert test_torrents_config.get(HASH)['paused'] is True
assert ('stop', [HASH]) in client.calls
await lib.set_paused(HASH, False, client=client)
assert ('start', [HASH]) in client.calls
await lib.remove_torrent(HASH, delete_files=True, client=client)
assert ('delete', [HASH], True) in client.calls
assert test_torrents_config.get(HASH) is None
assert not test_torrents_config.get_torrent_file(HASH).exists()
async def test_share_limits_are_applied(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
await lib.add_torrent(None, torrent=TORRENT, client=client)
await lib.reconcile(client, wrol_mode=False)
# No limits: none in qBittorrent either.
assert ('set_share_limits', [HASH], -1, -1) in client.calls
lib.set_share_limits(HASH, 2.0, 1440)
await lib.reconcile(client, wrol_mode=False)
assert ('set_share_limits', [HASH], 2.0, 1440) in client.calls
calls = len(client.calls)
await lib.reconcile(client, wrol_mode=False)
assert not [c for c in client.calls[calls:] if c[0] == 'set_share_limits']
with pytest.raises(ValidationError):
lib.set_share_limits(HASH, -1)
def test_speed_limits(test_wrolpi_config):
config = lib.get_wrolpi_config()
config.torrent_upload_limit = 500
config.torrent_download_limit = 0
preferences = lib.desired_preferences({})
assert preferences['up_limit'] == 500 * 1024
assert preferences['dl_limit'] == 0
def test_download_rows_show_torrent_progress(test_session, test_directory):
download = Download(url=f'magnet:?xt=urn:btih:{HASH}', downloader=lib.TORRENT_DOWNLOADER, status='complete',
info_json=dict(torrent_hash=HASH), last_successful_download=lib.get_media_directory() and None)
other = Download(url='https://example.com/file', downloader='file', status='complete')
test_session.add_all([download, other])
test_session.commit()
progress = {}
with mock.patch('wrolpi.downloader.set_download_progress', lambda i, p: progress.__setitem__(i, p)), \
mock.patch('wrolpi.downloader.clear_download_progress', lambda i: progress.pop(i, None)):
lib.sync_download_rows({HASH: dict(hash=HASH, progress=0.25, dlspeed=1000, eta=125, completed=250,
size=1000)})
assert progress[download.id] == dict(percent=25.0, speed=1000, eta='2:05', bytes_downloaded=250,
total_bytes=1000)
test_session.expire_all()
# Downloading: not shown as completed.
assert test_session.get(Download, download.id).last_successful_download is None
lib.sync_download_rows({HASH: dict(hash=HASH, progress=1.0, size=1000)})
assert download.id not in progress
test_session.expire_all()
assert test_session.get(Download, download.id).last_successful_download is not None
assert other.id not in progress
class TestDownloader:
async def test_magnet(self, test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
downloader = TorrentDownloader()
with mock.patch.object(lib, 'QBittorrent', lambda: client):
executed = await downloader.execute_download(
PreparedTorrent(url=f'magnet:?xt=urn:btih:{HASH}&dn=planet', save_path='maps'), ctx=mock.Mock())
assert executed == ExecutedTorrent(hash=HASH, name='planet')
download = Download(url='x')
result = downloader.finalize_download(mock.Mock(), download, executed)
assert result.success and result.location == '/admin/torrents'
assert download.info_json['torrent_hash'] == HASH
async def test_uploaded_file_is_used_over_its_magnet_link(self, test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
test_torrents_config.get_torrent_file(HASH).write_bytes(TORRENT)
with mock.patch.object(lib, 'QBittorrent', lambda: client):
await TorrentDownloader().execute_download(
PreparedTorrent(url=lib.torrent_magnet(TORRENT), save_path='maps'), ctx=mock.Mock())
assert next(c for c in client.calls if c[0] == 'add')[2] == TORRENT
async def test_torrent_url(self, test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
with mock.patch.object(lib, 'QBittorrent', lambda: client), \
mock.patch('modules.torrents.downloader.fetch_torrent_file', mock.AsyncMock(return_value=TORRENT)):
executed = await TorrentDownloader().execute_download(
PreparedTorrent(url='https://example.com/planet.torrent', save_path='maps'), ctx=mock.Mock())
assert executed.hash == HASH
async def test_refused(self, test_torrents_config):
result = await TorrentDownloader().execute_download(
PreparedTorrent(url='ftp://example.com/x.torrent', save_path='maps'), ctx=mock.Mock())
assert result.success is False
result = await TorrentDownloader().execute_download(
PreparedTorrent(url='magnet:?xt=urn:btih:nothex', save_path='maps'), ctx=mock.Mock())
assert 'info hash' in result.error
async def test_fetch_torrent_file_reads_every_chunk(test_directory):
"""A .torrent file which arrives in many pieces is read whole."""
from aiohttp import web
from aiohttp.test_utils import TestServer
from modules.torrents.downloader import fetch_torrent_file
big = bencode({'announce': 'http://tracker.example/', 'comment': 'x' * 300_000, 'info': INFO})
async def handler(request):
response = web.StreamResponse()
await response.prepare(request)
for i in range(0, len(big), 1000):
await response.write(big[i:i + 1000])
return response
app = web.Application()
app.router.add_get('/planet.torrent', handler)
app.router.add_get('/missing.torrent', lambda request: web.Response(status=404))
async with TestServer(app) as server:
torrent = await fetch_torrent_file(str(server.make_url('/planet.torrent')))
with pytest.raises(ValidationError, match='404'):
await fetch_torrent_file(str(server.make_url('/missing.torrent')))
assert torrent == big
assert lib.torrent_identity(torrent) == (HASH, 'planet.pmtiles')
class TestAPI:
async def test_upload(self, test_torrents_config, async_client, test_session):
request, response = await async_client.post('/api/torrents/upload', data={'destination': 'maps'},
files={'torrent': ('planet.torrent', TORRENT)})
assert response.status_code == HTTPStatus.OK, response.json
assert response.json == dict(hash=HASH, name='planet.pmtiles')
assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT
download = test_session.query(Download).one()
assert download.downloader == lib.TORRENT_DOWNLOADER
assert lib.magnet_identity(download.url)[0] == HASH
assert str(download.destination).endswith('/maps')
async def test_upload_refused(self, test_torrents_config, async_client):
request, response = await async_client.post('/api/torrents/upload', data={'destination': 'config'},
files={'torrent': ('planet.torrent', TORRENT)})
assert response.status_code == HTTPStatus.BAD_REQUEST
request, response = await async_client.post('/api/torrents/upload',
files={'torrent': ('bad.torrent', b'nope')})
assert response.status_code == HTTPStatus.BAD_REQUEST
async def test_manage(self, test_torrents_config, async_client, fake_qbittorrent, test_wrolpi_config):
client = fake_qbittorrent(tags=[lib.TAG])
with mock.patch.object(lib, 'QBittorrent', lambda: client):
await lib.add_torrent(None, torrent=TORRENT, client=client)
request, response = await async_client.post(f'/api/torrents/{HASH}/pause')
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_torrents_config.get(HASH)['paused'] is True
request, response = await async_client.put(f'/api/torrents/{HASH}/limits',
json={'seed_ratio_limit': 3.0, 'seed_time_limit': None})
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_torrents_config.get(HASH)['seed_ratio_limit'] == 3.0
request, response = await async_client.get(f'/api/torrents/{HASH}/torrent')
assert response.status_code == HTTPStatus.OK
assert response.body == TORRENT
request, response = await async_client.put('/api/torrents/limits', json={'upload': 100, 'download': 0})
assert response.status_code == HTTPStatus.NO_CONTENT
assert lib.get_wrolpi_config().torrent_upload_limit == 100
with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={'state': 'connected'})):
request, response = await async_client.get('/api/torrents')
torrent = response.json['torrents'][0]
assert (torrent['managed'], torrent['paused'], torrent['seed_ratio_limit']) == (True, True, 3.0)
assert response.json['limits'] == {'upload': 100, 'download': 0}
request, response = await async_client.delete(f'/api/torrents/{HASH}?delete_files=true')
assert response.status_code == HTTPStatus.NO_CONTENT
assert ('delete', [HASH], True) in client.calls
async def test_status_tells_the_navigation(test_torrents_config, async_client, fake_qbittorrent):
"""/api/status carries the torrents summary the worker publishes, so the navigation can warn without asking
qBittorrent or the Controller itself."""
client = fake_qbittorrent(tags=[lib.TAG])
await lib.add_torrent(None, torrent=TORRENT, client=client)
with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={'state': 'connecting'})):
await lib.sync_torrents(client)
request, response = await async_client.get('/api/status')
assert response.json['torrents'] == {'count': 1, 'vpn_state': 'connecting', 'running': True}

View file

@ -0,0 +1,148 @@
"""Share as torrent: make a torrent of a file or directory in the library, and seed it."""
import asyncio
from http import HTTPStatus
from unittest import mock
import pytest
from modules.torrents import lib, share
from modules.torrents.test.test_adding import TORRENT, HASH
from wrolpi.errors import ValidationError
@pytest.fixture
def planet(test_directory):
path = test_directory / 'maps' / 'planet.pmtiles'
path.parent.mkdir(parents=True)
path.write_bytes(b'tiles')
return path
class TestCheck:
def test_share_path(self, test_directory, planet):
assert share.check_share_path('maps/planet.pmtiles') == planet
assert share.check_share_path('maps/') == planet.parent
@pytest.mark.parametrize('path,message', [
('', 'Choose'), ('missing.bin', 'does not exist'), ('../outside', 'media directory'),
('config/torrents', 'config'), ('empty', 'no files'),
])
def test_refused(self, test_directory, planet, path, message):
(test_directory / 'empty').mkdir()
(test_directory / 'config' / 'torrents').mkdir(parents=True, exist_ok=True)
with pytest.raises(ValidationError, match=message):
share.check_share_path(path)
@pytest.mark.parametrize('path', ['.', './', '/', 'maps/..', 'config', 'config/vpn'])
def test_never_the_config(self, test_directory, planet, path):
(test_directory / 'config' / 'vpn').mkdir(parents=True, exist_ok=True)
(test_directory / 'config' / 'vpn' / 'wireguard.conf').write_text('PrivateKey = secret')
with pytest.raises(ValidationError):
share.check_share_path(path)
def test_links_out_are_refused(self, test_directory, planet):
(test_directory / 'config' / 'vpn').mkdir(parents=True, exist_ok=True)
(test_directory / 'config' / 'vpn' / 'wireguard.conf').write_text('PrivateKey = secret')
(test_directory / 'maps' / 'keys').symlink_to(test_directory / 'config' / 'vpn')
with pytest.raises(ValidationError, match='links to a folder'):
share.check_share_path('maps')
(test_directory / 'maps' / 'keys').unlink()
(test_directory / 'maps' / 'hosts').symlink_to('/etc/hosts')
with pytest.raises(ValidationError, match='outside the library'):
share.check_share_path('maps')
(test_directory / 'maps' / 'hosts').unlink()
# A link to the library itself would publish everything.
(test_directory / 'maps' / 'all').symlink_to(test_directory)
with pytest.raises(ValidationError, match='links to a folder'):
share.check_share_path('maps')
(test_directory / 'maps' / 'all').unlink()
# A link to a folder could lead anywhere (its own links are not walked).
(test_directory / 'videos').mkdir()
(test_directory / 'maps' / 'videos').symlink_to(test_directory / 'videos')
with pytest.raises(ValidationError, match='links to a folder'):
share.check_share_path('maps')
(test_directory / 'maps' / 'videos').unlink()
# A link to a file elsewhere in the library is fine; one to a file in config/ is not.
(test_directory / 'videos' / 'a.mp4').write_bytes(b'video')
(test_directory / 'maps' / 'a.mp4').symlink_to(test_directory / 'videos' / 'a.mp4')
assert share.check_share_path('maps') == planet.parent
(test_directory / 'maps' / 'key').symlink_to(test_directory / 'config' / 'vpn' / 'wireguard.conf')
with pytest.raises(ValidationError, match='config directory'):
share.check_share_path('maps')
def test_urls(self):
assert share.check_trackers(['udp://t.example:1337/announce', ' https://t.example/announce ', '',
'udp://t.example:1337/announce']) == \
['udp://t.example:1337/announce', 'https://t.example/announce']
assert share.check_web_seeds(['https://cdn.example/planet.pmtiles']) == ['https://cdn.example/planet.pmtiles']
for bad in ('ftp://t.example/', 'udp://', 'https://a.example/x|https://b.example/y', 'not a url'):
with pytest.raises(ValidationError):
share.check_trackers([bad])
with pytest.raises(ValidationError):
share.check_web_seeds(['udp://t.example:1337/announce'])
async def test_share(test_torrents_config, planet, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG], created=TORRENT, creator_statuses=[
{'status': 'Running', 'progress': 40}, {'status': 'Finished', 'progress': None}])
job = mock.Mock()
job.cancel_requested.return_value = False
with mock.patch.object(share, 'get_current_job', lambda: job), mock.patch.object(share, 'POLL_SECONDS', 0):
result = await share.share_torrent('maps/planet.pmtiles', ['udp://t.example:1337/announce'],
['https://cdn.example/planet.pmtiles'], client=client)
assert result['hash'] == HASH
assert lib.magnet_identity(result['magnet'])[0] == HASH
assert ('create_torrent', str(planet), ['udp://t.example:1337/announce'],
['https://cdn.example/planet.pmtiles']) in client.calls
job.set_progress.assert_called_with(40)
# Seeded from where the files are, without hashing them again; the creator's task is cleaned up.
assert ('skip_checking', str(planet.parent)) in client.calls
assert ('delete_torrent_creator_task', 'task-1') in client.calls
entity = test_torrents_config.get(HASH)
assert (entity['save_path'], entity['complete']) == ('maps', True)
assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT
async def test_share_failed(test_torrents_config, planet, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG], creator_statuses=[{'status': 'Failed', 'errorMessage': 'disk error'}])
with pytest.raises(lib.QBittorrentError, match='disk error'):
await share.share_torrent('maps/planet.pmtiles', [], [], client=client)
assert ('delete_torrent_creator_task', 'task-1') in client.calls
assert test_torrents_config.get(HASH) is None
async def test_share_cancelled(test_torrents_config, planet, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG], creator_statuses=[{'status': 'Running', 'progress': 10}])
job = mock.Mock()
job.cancel_requested.return_value = True
with mock.patch.object(share, 'get_current_job', lambda: job), pytest.raises(asyncio.CancelledError):
await share.share_torrent('maps/planet.pmtiles', [], [], client=client)
# Stops qBittorrent hashing.
assert ('delete_torrent_creator_task', 'task-1') in client.calls
assert not [c for c in client.calls if c[0] == 'add']
async def test_share_api(test_torrents_config, async_client, planet, test_wrolpi_config):
with mock.patch.object(share, 'enqueue_job', return_value='job-1') as enqueue_job:
request, response = await async_client.post('/api/torrents/share', json={
'path': 'maps/planet.pmtiles', 'trackers': ['udp://t.example:1337/announce'],
'web_seeds': ['https://cdn.example/planet.pmtiles'], 'remember_trackers': True})
assert response.status_code == HTTPStatus.CREATED, response.json
assert response.json == {'job_id': 'job-1'}
assert enqueue_job.call_args.kwargs == dict(
description='Make a torrent of maps/planet.pmtiles', path='maps/planet.pmtiles',
trackers=['udp://t.example:1337/announce'], web_seeds=['https://cdn.example/planet.pmtiles'])
# Offered next time.
assert lib.get_wrolpi_config().torrent_trackers == ['udp://t.example:1337/announce']
request, response = await async_client.post('/api/torrents/share', json={
'path': 'config', 'trackers': ['udp://other.example:1/announce'], 'remember_trackers': True})
assert response.status_code == HTTPStatus.BAD_REQUEST
# A refused request changes nothing.
assert lib.get_wrolpi_config().torrent_trackers == ['udp://t.example:1337/announce']
def test_default_trackers(test_wrolpi_config):
assert lib.get_wrolpi_config().torrent_trackers == [
'udp://tracker.opentrackr.org:1337/announce', 'udp://tracker.torrent.eu.org:451/announce']

View file

@ -0,0 +1,360 @@
"""Torrents: qBittorrent kept as config/torrents/ says, and the config following qBittorrent's WebUI."""
import configparser
import json
import subprocess
from pathlib import Path
from unittest import mock
import pytest
import yaml
from modules.torrents import lib, qbittorrent_prepare
REPOSITORY = Path(__file__).parent.parent.parent.parent
A, B, C = 'a' * 40, 'b' * 40, 'c' * 40
def make_entity(config, slug, torrent_file=True, **values):
entity = dict(slug=slug, name=f'torrent {slug[:4]}', save_path='torrents', **values)
config.create(slug, entity)
if torrent_file:
config.get_torrent_file(slug).write_bytes(f'torrent {slug}'.encode())
def qbt_torrent(hash_, tags='wrolpi', state='uploading', progress=1.0, save_path=None, **values):
return dict(hash=hash_, name=f'torrent {hash_[:4]}', tags=tags, state=state, progress=progress,
save_path=save_path or str(lib.get_media_directory() / 'torrents'),
magnet_uri=f'magnet:?xt=urn:btih:{hash_}', **values)
async def test_preferences(test_directory, fake_qbittorrent):
client = fake_qbittorrent()
changed = await lib.enforce_preferences(client, {'state': 'connected', 'forwarded_port': 36523})
assert changed['upnp'] is False
assert changed['lsd'] is False
assert changed['listen_port'] == 36523
assert changed['autorun_enabled'] is False and changed['autorun_on_torrent_added_enabled'] is False
assert changed['anonymous_mode'] is True
assert changed['save_path'] == str(test_directory / 'torrents')
# Already right: not set again.
assert 'current_network_interface' not in changed
assert await lib.enforce_preferences(client, {'state': 'connected', 'forwarded_port': 36523}) == {}
# Without a forwarded port, the listening port is left alone.
assert 'listen_port' not in lib.desired_preferences({'state': 'connected', 'forwarded_port': None})
async def test_new_profile_gets_every_torrent(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
make_entity(test_torrents_config, B, torrent_file=False, magnet=f'magnet:?xt=urn:btih:{B}', paused=True)
client = fake_qbittorrent()
done = await lib.reconcile(client, wrol_mode=False)
assert sorted(done['added']) == [A, B]
assert set(await client.tags()) == {lib.TAG, lib.WROL_MODE_TAG}
adds = {c[2] or c[3]: c for c in client.calls if c[0] == 'add'}
# From its .torrent file (re-checked, never re-downloaded), into its directory.
_, save_path, torrent, url, tags, stopped = adds[f'torrent {A}'.encode()]
assert save_path == str(lib.get_media_directory() / 'torrents')
assert (tags, stopped) == ([lib.TAG], False)
# Only a magnet link: added from that. Paused stays paused.
_, _, _, url, tags, stopped = adds[f'magnet:?xt=urn:btih:{B}']
assert (tags, stopped) == ([lib.TAG], True)
async def test_new_profile_in_wrol_mode(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
client = fake_qbittorrent()
await lib.reconcile(client, wrol_mode=True)
_, _, _, _, tags, stopped = next(c for c in client.calls if c[0] == 'add')
# Started again when WROL Mode ends.
assert stopped and lib.WROL_MODE_TAG in tags
async def test_adopts_torrents_added_in_the_webui(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A, tags='', state='downloading', progress=0.2,
save_path=str(lib.get_media_directory() / 'maps'))],
tags=[lib.TAG])
done = await lib.reconcile(client, wrol_mode=False)
assert done['adopted'] == [A]
entity = test_torrents_config.get(A)
assert entity['save_path'] == 'maps'
assert entity['paused'] is False
assert entity['magnet'] == f'magnet:?xt=urn:btih:{A}'
assert test_torrents_config.get_torrent_file(A).read_bytes() == f'torrent {A}'.encode()
assert (await client.torrents())[0]['tags'] == lib.TAG
async def test_waits_for_metadata_before_adopting(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A, tags='', state='metaDL', progress=0)], tags=[lib.TAG], metadata=False)
done = await lib.reconcile(client, wrol_mode=False)
assert done['adopted'] == []
assert test_torrents_config.get(A) is None
async def test_removed_in_the_webui_leaves_the_config(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
client = fake_qbittorrent([qbt_torrent(A)], tags=[lib.TAG])
state = lib.ReconcileState()
await lib.reconcile(client, wrol_mode=False, state=state)
await client.delete([A])
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert done['forgotten'] == [A]
assert test_torrents_config.get(A) is None
assert not test_torrents_config.get_file(A).exists()
assert not test_torrents_config.get_torrent_file(A).exists()
async def test_being_added_is_not_forgotten(test_torrents_config, fake_qbittorrent):
"""A torrent in the config, which qBittorrent has not shown yet, is being added (by another process); it is not
"removed in the WebUI"."""
make_entity(test_torrents_config, A)
client = fake_qbittorrent([], tags=[lib.TAG])
state = lib.ReconcileState()
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert done['forgotten'] == [] and done['added'] == []
assert test_torrents_config.get(A) and test_torrents_config.get_torrent_file(A).is_file()
# The add lands.
await lib.add_from_config(client, test_torrents_config.get(A), stopped=False)
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert not any(done.values())
assert test_torrents_config.get(A)
async def test_never_shown_is_added_again(test_torrents_config, fake_qbittorrent):
"""One still missing after the grace period (its add failed, or a restored config) is added, not forgotten."""
make_entity(test_torrents_config, A)
client = fake_qbittorrent([], tags=[lib.TAG])
state = lib.ReconcileState()
with mock.patch.object(lib.time, 'monotonic', return_value=1000.0):
assert (await lib.reconcile(client, wrol_mode=False, state=state))['added'] == []
with mock.patch.object(lib.time, 'monotonic', return_value=1000.0 + lib.ADD_GRACE_SECONDS):
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert done['added'] == [A] and done['forgotten'] == []
assert A in {t['hash'] for t in await client.torrents()}
async def test_removed_from_the_config_leaves_qbittorrent_keeping_files(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A)], tags=[lib.TAG])
done = await lib.reconcile(client, wrol_mode=False)
assert done['removed'] == [A]
assert ('delete', [A], False) in client.calls
async def test_pausing_in_the_webui_is_saved(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
client = fake_qbittorrent([qbt_torrent(A, state='stoppedUP')], tags=[lib.TAG])
await lib.reconcile(client, wrol_mode=False)
assert test_torrents_config.get(A)['paused'] is True
await client.start([A])
await lib.reconcile(client, wrol_mode=False)
assert test_torrents_config.get(A)['paused'] is False
async def test_wrol_mode_stops_torrents_and_starts_them_again(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A, complete=True)
make_entity(test_torrents_config, B, paused=True, complete=True)
client = fake_qbittorrent([qbt_torrent(A), qbt_torrent(B, state='stoppedUP')], tags=[lib.TAG])
done = await lib.reconcile(client, wrol_mode=True)
assert done['stopped'] == [A]
# The user's wishes are unchanged.
assert test_torrents_config.get(A)['paused'] is False
done = await lib.reconcile(client, wrol_mode=False)
assert done['started'] == [A]
torrents = {t['hash']: t for t in await client.torrents()}
assert lib.WROL_MODE_TAG not in torrents[A]['tags']
# Paused by the user: not started.
assert torrents[B]['state'] == 'stoppedUP'
async def test_finished_torrent_is_indexed_once(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
content = lib.get_media_directory() / 'torrents' / 'planet.pmtiles'
client = fake_qbittorrent([qbt_torrent(A, content_path=str(content))], tags=[lib.TAG])
with mock.patch('wrolpi.files.worker.file_worker') as file_worker:
done = await lib.reconcile(client, wrol_mode=False)
assert done['completed'] == [A]
file_worker.queue_refresh.assert_called_once_with([content], expand_stems=True)
await lib.reconcile(client, wrol_mode=False)
assert file_worker.queue_refresh.call_count == 1
assert test_torrents_config.get(A)['complete'] is True
async def test_sync_is_skipped_without_qbittorrent(test_torrents_config):
client = mock.Mock()
client.version = mock.AsyncMock(side_effect=lib.QBittorrentUnavailable('down'))
with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={})):
assert await lib.sync_torrents(client) is None
async def test_status(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A, size=10, ratio=2.5, upspeed=5, dlspeed=0, num_leechs=1, num_seeds=3)],
tags=[lib.TAG])
with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={'state': 'connected'})):
status = await lib.get_torrents_status(client)
assert status['running'] is True
assert status['connection_status'] == 'connected'
assert status['vpn'] == {'state': 'connected'}
assert status['torrents'][0]['save_path'] == 'torrents'
assert status['torrents'][0]['ratio'] == 2.5
class TestPrepare:
def test_writes_webui_and_interface_keeping_the_rest(self, tmp_path):
path = tmp_path / 'qBittorrent' / 'config' / 'qBittorrent.conf'
path.parent.mkdir(parents=True)
path.write_text('[Preferences]\nWebUI\\Port=8080\nDownloads\\SavePath=/media/wrolpi/x/\n'
'[Network]\nCookies=@Invalid()\n')
qbittorrent_prepare.prepare(tmp_path, '10.211.0.2', ['10.211.0.1/32'])
config = configparser.RawConfigParser(strict=False)
config.optionxform = str
config.read(path)
preferences = config['Preferences']
assert preferences['WebUI\\Address'] == '10.211.0.2'
assert preferences['WebUI\\Port'] == '8091'
assert preferences['WebUI\\AuthSubnetWhitelist'] == '10.211.0.1/32'
assert preferences['WebUI\\AuthSubnetWhitelistEnabled'] == 'true'
assert config['BitTorrent']['Session\\Interface'] == 'vpn0'
assert config['AutoRun']['enabled'] == 'false'
assert config['AutoRun']['OnTorrentAdded\\Enabled'] == 'false'
# qBittorrent's own settings are kept, case and all.
assert preferences['Downloads\\SavePath'] == '/media/wrolpi/x/'
assert config['Network']['Cookies'] == '@Invalid()'
assert 'WebUI\\Port=8091' in path.read_text()
def test_uplink(self):
outputs = {
('ip', '-j', '-4', 'route', 'show', 'default'):
json.dumps([{'dev': 'vpn-uplink', 'gateway': '10.211.0.1'}]).encode(),
('ip', '-j', '-4', 'addr', 'show', 'dev', 'vpn-uplink'):
json.dumps([{'addr_info': [{'local': '10.211.0.2', 'prefixlen': 30, 'scope': 'global'}]}]).encode(),
}
with mock.patch.object(qbittorrent_prepare.subprocess, 'check_output', lambda cmd: outputs[tuple(cmd)]):
assert qbittorrent_prepare.find_uplink() == ('10.211.0.2', '10.211.0.0/30')
def test_standalone(self):
source = (REPOSITORY / 'modules/torrents/qbittorrent_prepare.py').read_text()
imports = {line.split()[1].split('.')[0] for line in source.splitlines() if line.startswith(('import ', 'from '))}
assert imports <= set(__import__('sys').stdlib_module_names)
class TestInstalled:
def test_uplink_given_runs_no_ip(self, tmp_path):
"""The Pi unit's seccomp filter forbids capset, which `ip` calls to drop its capabilities (it is killed with
SIGSYS); so the unit gives the uplink rather than having it looked up."""
with mock.patch.object(qbittorrent_prepare.subprocess, 'check_output',
side_effect=AssertionError('ran ip')):
qbittorrent_prepare.main(['--profile', str(tmp_path), '--uplink', '10.211.0.2/30'])
config = configparser.RawConfigParser()
config.optionxform = str
config.read(tmp_path / 'qBittorrent/config/qBittorrent.conf')
assert config['Preferences']['WebUI\\Address'] == '10.211.0.2'
assert config['Preferences']['WebUI\\AuthSubnetWhitelist'] == '10.211.0.0/30'
def test_unit_gives_the_namespace_address(self):
unit = (REPOSITORY / 'etc/raspberrypios/wrolpi-torrent.service').read_text()
script = (REPOSITORY / 'etc/raspberrypios/wrolpi-vpn-netns.sh').read_text()
assert 'NAMESPACE_ADDRESS=10.211.0.2\n' in script and 'NETWORK=10.211.0.0/30\n' in script
assert '--uplink 10.211.0.2/30' in unit
def test_unit(self):
unit = (REPOSITORY / 'etc/raspberrypios/wrolpi-torrent.service').read_text()
assert 'NetworkNamespacePath=/run/netns/wrolpi-vpn' in unit
assert 'BindsTo=wrolpi-vpn.service' in unit
# systemd does not bind the namespace's resolv.conf the way `ip netns exec` does.
assert 'BindReadOnlyPaths=/etc/netns/wrolpi-vpn/resolv.conf:/etc/resolv.conf' in unit
assert '--allow 10.211.0.1/32' in unit
assert 'ProtectSystem=strict' in unit and 'ReadWritePaths=/media/wrolpi' in unit
# Never WROLPi's config; qBittorrent's own state is outside the library.
assert 'ReadOnlyPaths=/media/wrolpi/config' in unit
assert '--profile=/var/lib/wrolpi-torrent' in unit and 'StateDirectory=wrolpi-torrent' in unit
assert 'User=wrolpi' in unit
for hardening in ('CapabilityBoundingSet=\n', 'PrivateDevices=yes', 'SystemCallFilter=@system-service',
'RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK', 'RestrictNamespaces=yes'):
assert hardening in unit, hardening
for script in ('repair.sh', 'pi-gen/stage2/04-wrolpi/03-run-chroot.sh',
'debian-live-config/config/includes.chroot/usr/local/sbin/wrolpi-bootstrap.sh',
'etc/raspberrypios/wrolpi.target'):
assert 'wrolpi-torrent.service' in (REPOSITORY / script).read_text(), script
for packages in ('pi-gen/stage2/04-wrolpi/01-packages-nr',
'debian-live-config/config/package-lists/wrolpi.list.chroot'):
assert 'qbittorrent-nox' in (REPOSITORY / packages).read_text().splitlines()
def test_upgrades_keep_qbittorrent_patched(self):
upgrade = (REPOSITORY / 'scripts/upgrade.sh').read_text()
assert '--only-upgrade' in upgrade and "'libtorrent-rasterbar*'" in upgrade
assert 'docker compose build --pull --no-cache vpn' in (REPOSITORY / 'UPGRADE.md').read_text()
@staticmethod
def run_upgrade_blocks(tmp_path, installed: bool, online: bool = False) -> subprocess.CompletedProcess:
"""Run upgrade.sh's torrent install and patch blocks under set -e, offline (apt-get update fails) unless
`online`."""
upgrade = (REPOSITORY / 'scripts/upgrade.sh').read_text()
start = upgrade.index('# Install torrents (qBittorrent)')
patch = upgrade.index('if command -v qbittorrent-nox')
block = upgrade[start:upgrade.index('\nfi\n', patch) + 4]
bin_ = tmp_path / 'bin'
bin_.mkdir()
update = 'exit 0' if online else '[ "$1" != update ]'
stubs = [('dpkg-query', 'exit 0'), ('apt-get', f'echo "$@" >> {tmp_path}/apt; {update}')]
if installed:
stubs += [(name, 'exit 0') for name in ('nft', 'openvpn', 'wg', 'qbittorrent-nox')]
for name, body in stubs:
(bin_ / name).write_text(f'#!/bin/sh\n{body}\n')
(bin_ / name).chmod(0o755)
script = tmp_path / 'block.sh'
script.write_text(f'set -e\n{block}\necho reached repair\n')
# Only the stubs and a shell: the machine running the tests may have the real tools.
(bin_ / 'echo').symlink_to('/bin/echo')
return subprocess.run(['/bin/bash', str(script)], capture_output=True, text=True, env={'PATH': str(bin_)})
@pytest.mark.parametrize('installed', [True, False], ids=['patch', 'install'])
def test_offline_upgrade_continues(self, tmp_path, installed):
"""WROLPi is often offline: a failed apt-get update must not end upgrade.sh (set -e) before repair.sh, whether
the torrent tools are installed (patch them) or not yet (install them)."""
result = self.run_upgrade_blocks(tmp_path, installed)
assert result.returncode == 0, result.stderr
assert 'reached repair' in result.stdout
# Nothing is installed or upgraded from stale lists.
assert 'install' not in (tmp_path / 'apt').read_text()
def test_install_skips_recommended_packages(self, tmp_path):
"""Recommends pulled in pcscd, opensc, easy-rsa and an enabled openvpn.service, none of which WROLPi uses."""
result = self.run_upgrade_blocks(tmp_path, installed=False, online=True)
assert result.returncode == 0, result.stderr
installs = [line for line in (tmp_path / 'apt').read_text().splitlines()
if line.startswith('install') and '--only-upgrade' not in line]
assert installs and all('--no-install-recommends' in line for line in installs), installs
def test_docker(self):
"""qBittorrent shares the tunnel's container: a container joined to another's network keeps the old, dead
one when that container is recreated, so torrents would silently stop."""
compose = yaml.safe_load((REPOSITORY / 'docker-compose.yml').read_text())
assert 'torrent' not in compose['services']
vpn = compose['services']['vpn']
assert './test/config:/media/wrolpi/config:ro' in vpn['volumes']
assert 'torrent-profile:/profile' in vpn['volumes']
assert vpn['cap_drop'] == ['ALL'] and set(vpn['cap_add']) == {'NET_ADMIN', 'SETUID', 'SETGID', 'SETPCAP', 'KILL'}
assert 'no-new-privileges:true' in vpn['security_opt']
assert '8091:8091' in compose['services']['web']['ports']
dockerfile = (REPOSITORY / 'docker/vpn/Dockerfile').read_text()
assert 'qbittorrent-nox' in dockerfile and 'qbittorrent_prepare.py' in dockerfile
entrypoint = (REPOSITORY / 'docker/vpn/entrypoint.sh').read_text()
# qBittorrent starts only after the kill switch, unprivileged, and the container stops if either stops.
assert entrypoint.index('while [ ! -f "${STATUS}" ]') < entrypoint.index('setpriv')
assert '--bounding-set=-all' in entrypoint and '--no-new-privs' in entrypoint
@pytest.mark.parametrize('caddyfile,upstream', [('etc/raspberrypios/Caddyfile', '10.211.0.2:8091'),
('docker/web/Caddyfile', 'vpn:8091')])
def test_caddy_serves_the_webui_but_not_its_settings(self, caddyfile, upstream):
text = (REPOSITORY / caddyfile).read_text()
block = text[text.index(':8091 {'):]
block = block[:block.index('\n}\n')]
assert f'reverse_proxy {upstream}' in block
for refused in ('/api/v2/app/setPreferences', '/api/v2/app/shutdown', '/api/v2/search/*'):
assert refused in block, refused
assert 'respond @qbittorrent_settings' in block
assert 'tls ' in block