# spill > spill is a modern torrent client built in Rust. Run it as a single-user daemon on Linux and macOS, or embed its engine in your application. Humans and AI agents can use either path. ## Choose a path - One-shot download without a daemon: run `spill download SOURCE -o DIR --json`. - Operate the daemon: install below, start a persistent process (`spill service install` or `spill serve`), and control it through CLI JSON output and `spill wait`. - Integrate into an application: use the Rust library, not a daemon subprocess, when you need in-process torrent functionality. See Rust integration below. - [User guide](https://spill.rs/docs/) (raw Markdown also served at `/docs/.md` and combined at [llms-full.txt](https://spill.rs/llms-full.txt)): follows the latest published release, not development main. Check `spill --version` and use matching API documentation. Source examples describe their own checkout; do not assume an unpublished API exists in the installed crate. ## Install the daemon ```sh curl -fsSL https://spill.rs/install.sh | sh spill --version ``` [Inspect the installer](https://spill.rs/install.sh) first if required by your execution policy. It installs the latest published release to `~/.local/bin`, verifies SHA-256 checksums, smoke-tests the downloaded binary before replacing it atomically, and does not use sudo, edit PATH, or start services. Override defaults with `SPILL_INSTALL_DIR` / `SPILL_VERSION` (or `--install-dir` / `--version`). Follow its PATH instructions or invoke `"$HOME/.local/bin/spill"` directly. Prebuilt platforms: static Linux x64/ARM64 musl binaries (legacy releases use glibc 2.39+), plus Apple Silicon and Intel macOS 11+. Requires curl, tar, and sha256sum or shasum. Cargo installation is also supported: ```sh cargo binstall spill # prebuilt release binary cargo install spill --locked # build from source (current stable Rust and a C compiler) ``` Windows is unsupported. spill is not yet in OS package managers. See [installation, manual downloads, services, and upgrades](https://spill.rs/docs/install/). Stop the daemon before replacing its binary; catalog schema migrations run automatically on startup (schema version 1 is the supported baseline). Keep downloaded payload and back up `catalog.sqlite`. ## Operate and automate One-shot download without a daemon: ```sh spill download /path/to/file.torrent -o ./downloads --json ``` Persistent daemon (background user service or foreground process): ```sh spill service install # creates starter config + user systemd/launchd service and starts it # or manage foreground explicitly: spill health spill serve ``` Check health before starting another daemon. `serve` runs in the foreground indefinitely (downloads default to `~/Downloads`, loopback web UI defaults to `http://127.0.0.1:8080`, pass `--no-web` or `--web ADDR` to change); manage it as a persistent process, not a command expected to finish. Use another terminal or process for client commands: ```sh id=$(spill add /path/to/file.torrent) spill wait "$id" --timeout 3600 spill --json list spill --json get "$id" spill files "$id" spill pause "$id" spill resume "$id" spill pause --all spill set "$id" upload_limit=1MiB seed_ratio=2 seed_time=24h spill set "$id" 'file_priorities={"1":"skip","0":"high"}' spill remove "$id" spill logs spill shutdown ``` Replace the torrent path and `$id` with real values. `add` accepts one or more sources (`.torrent` files, `-` for stdin, quoted magnets, HTTP(S) torrent URLs) and prints each torrent ID; unambiguous prefixes and full v1/v2 aliases work. `--output DIR` overrides the download directory (relative paths are resolved by the CLI); `--remote` stores verified pieces in configured `[remote_storage]`. Lifecycle commands (`pause`, `resume`, `recheck`, `reannounce`, `remove`) accept multiple IDs (`pause`, `resume`, `reannounce` also accept `--all`). `download_limit`/`upload_limit` accept raw bytes/second or human units (`2MiB`, `500K`); `seed_time` accepts seconds or `m`/`h`/`d`; zero means unlimited/off. Prefer `--json` and `spill wait` for automation: response data is one JSON document per line, and errors are printed to stderr as `{"error":"…","code":N}`. Avoid `list --watch` and `logs -f` in noninteractive work because they wait until interrupted. `remove` keeps files (and never deletes remote S3 objects); only add `--delete-payload` when local deletion is intended. `shutdown` stops the daemon cleanly. Exit codes: 0 success, 1 operation failed, 2 invalid input, 3 no matching torrent, 4 daemon unreachable, 130 interrupted. For 4, check the process, control socket, and permissions. Set `SPILL_SOCKET` or pass `--socket PATH` for custom sockets. Standalone/setup tools: `spill download`, `spill config init`, `spill service install|print|uninstall`, `spill create`, `spill inspect`, `spill verify`, `spill restore-catalog`, and `spill extract` (download and verify a completed remote S3 torrent into local files). See [CLI and control protocol](https://spill.rs/docs/cli/). Configuration is read with `spill serve --config PATH` (generate a starter file with `spill config init`, validate edits with `--check`; common overrides also work as `serve` flags). Unknown keys are errors; `state_dir`, `download_dir`, and `control_socket` must be absolute or start with `~/` (environment variables are not expanded). See [configuration](https://spill.rs/docs/configuration/) and [remote S3 storage](https://spill.rs/docs/remote-storage/). ## Rust integration ```sh cargo add spill --no-default-features cargo add tokio --features fs,macros,rt,net,time ``` Use documentation and examples matching your dependency version. - Start with `docs/library.md` in the matching source checkout and the published [user guide](https://spill.rs/docs/). - Consult [docs.rs](https://docs.rs/spill) at the exact dependency version for API signatures. Do not infer Rust APIs from CLI commands. - Run the `download` and `progress` examples from the matching [source](https://github.com/spillrs/spill). The latter demonstrates concurrent transfers and persisted recovery. - Supply a Tokio runtime with I/O and time drivers. No daemon, SQLite catalog, signal handler, or global tracing subscriber is required. - Create the destination directory first (`tokio::fs::create_dir_all`) before passing `Destination::Open`. Construct sources with `TorrentSource::from_metainfo_bytes` or `TorrentSource::from_magnet`. `spill::engine::download` is a one-shot helper with public DHT enabled, no LAN permission or port mapping, and no stored recovery record. - Use `Session` and `TorrentHandle` for concurrent torrents, networking policy, progress, persistence (`RecoveryState` derives `Serialize`/`Deserialize`), and cancellation with joined cleanup (`TorrentOutcome::require_complete()`). Reusable sessions require explicit DHT consent. - `Destination::Remote` with `ObjectStorage` stores verified pieces in S3-compatible buckets; `RemoteDestination::extract` verifies and materializes a completed remote torrent locally. - Retain handles, request stop, and await cleanup before reusing destinations. Dropping a future cannot join cleanup. Partial-file recovery needs the original destination binding and root, not only resume bytes. ## Scope and security BitTorrent v1, v2, and hybrid torrents; TCP and uTP with MSE/PE (`preferred` by default); trackers, DHT, PEX, HTTP web seeds, automatic NAT-PMP/UPnP port mapping, and optional BEP 14 local service discovery (requires `allow_local_network = true`). Private torrents require `.torrent` metadata, not magnets. Outbound LAN addresses are blocked by default; see [v2 and hybrid torrents](https://spill.rs/docs/v2/), [networking](https://spill.rs/docs/networking/), and [private trackers](https://spill.rs/docs/private-trackers/). The [web interface and HTTP API](https://spill.rs/docs/web/) are enabled by default on `127.0.0.1:8080` and accept loopback addresses only (`--no-web` or `web_listen = ""` disables them). Use an SSH tunnel for remote access. API calls require `X-Spill-Token`; dispatched `/api` requests return HTTP 200 with `{"code":N,"data":…,"error":…}` (check `code == 0`). The token is readable by other local users, so it is not multi-user authentication. Prefer the CLI/Unix socket for local automation. See [limits and measured performance](https://spill.rs/docs/limits/) and [troubleshooting](https://spill.rs/docs/troubleshooting/). Do not assume unmeasured capacity or universal peer/tracker compatibility. --- # spill A modern torrent client built in Rust. Run spill as a single-user daemon on Linux and macOS, controlled through the CLI or built-in local web interface. Or embed the same engine in your Rust application without running a separate daemon. ## Run the client [Install spill](install.md), then follow the [quickstart](quickstart.md) to start the daemon (or register it with `spill service install`) and add your first torrent. Use the [CLI and JSON output](cli.md) for interactive control and automation, or open the [local web interface and HTTP API](web.md) at `http://127.0.0.1:8080`. ## Embed the engine The [Rust library guide](library.md) covers dependencies, your Tokio runtime, one-shot downloads, reusable sessions, progress, recovery, and shutdown. The [Rust API reference](https://docs.rs/spill) describes the public interfaces. Applications and agents can use the library directly; no daemon or SQLite catalog is required. ## Capabilities - Download and seed v1, v2-only and hybrid `.torrent` files and magnet links. V2/hybrid metainfo TCP discovery and daemon lifecycles have been checked with libtorrent 2.1.2.0; see [Scope](#scope) for the validation limits. - Connect to peers over TCP and uTP (BEP 29). - Discover peers through HTTP, HTTPS and UDP trackers, the DHT, peer exchange (PEX) and local service discovery (LSD); download from HTTP web seeds. - Use private torrents (BEP 27), with DHT and PEX disabled. - Select files and priorities, limit transfer rates, and configure daemon seeding goals. - Recover verified progress after restarts using checkpoints and file fingerprints. - Optionally store and seed verified pieces directly in an S3-compatible bucket ([Remote S3 storage](remote-storage.md)). - Share one peer port over TCP and UDP, with optional NAT-PMP or UPnP mapping. Read [Torrents](torrents.md), [Remote S3 storage](remote-storage.md), [Networking](networking.md), and [Private trackers](private-trackers.md) for exact behavior. [Limits and performance](limits.md) documents resource bounds and measured workloads. ## Scope spill supports Linux and macOS. Both the daemon and [embeddable engine](library.md) accept v1, v2-only, and hybrid metainfo, magnet links, and HTTP(S) web seeds, with MSE/PE peer encryption ([Networking](networking.md#peer-encryption)) and optional BEP 14 local service discovery ([Networking](networking.md#local-service-discovery)). Interoperability checks cover controlled tests against Transmission 4.1+ and libtorrent 2.1.2.0 (v1/v2/hybrid TCP transfers, magnets, trackers, DHT, hybrid PEX, web seeds, and kill/restart recovery). Recorded baselines live in [`tests/interop/baselines/`](https://github.com/spillrs/spill/tree/main/tests/interop/baselines) and are not evidence of public-swarm capacity, v2 uTP interoperability, or universal client compatibility; see [v2 and hybrid torrents](v2.md) and [Limits and performance](limits.md) for exact coverage and bounds. The daemon is single-user; its optional web interface listens only on loopback and has no multi-user authentication. Remote access requires an SSH tunnel. ## Documentation versions The website's `/docs/` guide follows the latest published release. Documentation in a source checkout describes that checkout. Check `spill --version` and use the corresponding version in the Rust API reference when integrating an older release. --- # Install Install spill with the hosted script, a manual release download, or Cargo. spill is not yet distributed through OS package managers. ## Install with the script (recommended) ```sh curl -fsSL https://spill.rs/install.sh | sh spill --version ``` The script installs the latest published release to `~/.local/bin`, checks its SHA-256 checksum, verifies the binary runs on this host, and replaces it atomically. It does not use sudo, change shell profiles, or start a service. If `spill` is not found, follow the printed shell-specific `PATH` instructions or run `"$HOME/.local/bin/spill"` directly. Requires `curl`, `tar`, and `sha256sum` or `shasum`. Customize the version or directory with flags (or pass `SPILL_INSTALL_DIR` / `SPILL_VERSION` to `sh`): ```sh curl -fsSL https://spill.rs/install.sh | sh -s -- --install-dir "$HOME/bin" ``` Or inspect and pin the script before running it: ```sh curl -fsSL https://spill.rs/install.sh -o install.sh # Read install.sh before running it; replace VERSION with a release (no leading v). sh install.sh --version VERSION --install-dir "$HOME/.local/bin" ``` Stop a running daemon before replacing its binary. Checksums detect corruption, not a compromised release publisher. For upgrades, also read [Upgrading](#upgrading). ## Install a release binary Download an archive and `SHA256SUMS` from the [GitHub Releases](https://github.com/spillrs/spill/releases) page. Archives contain only `spill`; no Rust toolchain or system libraries are needed. | Platform | Archive target | Compatibility | |---|---|---| | Linux x86_64 | `x86_64-unknown-linux-musl` | Static binary (works across glibc and musl distros) | | Linux ARM64 | `aarch64-unknown-linux-musl` | Static binary (works across glibc and musl distros) | | macOS Apple Silicon | `aarch64-apple-darwin` | Built targeting macOS 11 or newer | | macOS Intel | `x86_64-apple-darwin` | Built targeting macOS 11 or newer | SQLite and the web assets are embedded in the single `spill` binary. Choose a released version and the target from the table: ```sh version=VERSION # replace with a release version, without the v prefix target=x86_64-unknown-linux-musl archive="spill-${version}-${target}.tar.gz" base="https://github.com/spillrs/spill/releases/download/v${version}" curl -fLO "$base/$archive" curl -fLO "$base/SHA256SUMS" grep -F " $archive" SHA256SUMS | sha256sum -c - tar -xzf "$archive" sudo install -d /usr/local/bin sudo install -m 0755 spill /usr/local/bin/spill ``` On macOS, use `shasum -a 256 -c -` instead of `sha256sum -c -`. The macOS binary is initially unsigned and unnotarized. If Gatekeeper blocks a browser-downloaded archive, verify the checksum and provenance first, then remove its quarantine attribute with `xattr -d com.apple.quarantine spill` before installing. Do not disable Gatekeeper globally. Checksums detect corruption, not a compromised release account. ## Install from crates.io With [`cargo-binstall`](https://github.com/cargo-bins/cargo-binstall), Cargo fetches the prebuilt release archive directly: ```sh cargo binstall spill ``` To build from source on Linux or macOS, install current stable Rust and a C compiler (SQLite is bundled; no other system libraries are needed): ```sh cargo install spill --locked ``` This installs `spill` into Cargo's binary directory, usually `~/.cargo/bin`. ## Build from source ```sh git clone https://github.com/spillrs/spill cd spill cargo build --release --locked sudo install -d /usr/local/bin sudo install -m 0755 target/release/spill /usr/local/bin/spill ``` The single `spill` binary runs the daemon with `spill serve`; other commands, such as `spill list` or `spill download`, control the daemon or work offline. ## Run it once ```sh spill serve ``` Without `--config`, spill uses built-in defaults (common overrides also work as `serve` flags, such as `--download-dir DIR`, `--web ADDR`, or `--no-web`): | What | Default | |---|---| | State (catalog, lock) | Linux: `~/.local/state/spill`; macOS: `~/Library/Application Support/spill` | | Downloads | `~/Downloads` | | Control socket | Linux: `$XDG_RUNTIME_DIR/spill.sock`, otherwise `~/.local/state/spill/spill.sock`; macOS: `~/Library/Application Support/spill/spill.sock` | | Peer port | `0.0.0.0:6881`, TCP and UDP | | Web interface | `http://127.0.0.1:8080` (loopback only; `--no-web` or `web_listen = ""` disables it) | Stop it with Ctrl-C, `SIGTERM` or `spill shutdown`. Shutdown waits for every torrent to stop cleanly and saves its progress. To create a starter config file, run `spill config init` (or pass `--output PATH`, or `-` for stdout). Validate edits without starting the daemon using `spill serve --config PATH --check`. See [Configuration](configuration.md) for every key. Next: follow the [Quickstart](quickstart.md) to add and manage your first torrent, or continue below to run spill as a background service. ## Run in the background (recommended) Stop any manually running `spill serve`, then register the built-in user service using the current `spill` binary (works for script, Cargo, and manual installs): ```sh spill service install ``` This creates a starter config if one does not exist yet (`~/.config/spill/spill.toml` on Linux, `~/Library/Application Support/spill/spill.toml` on macOS), writes the user service definition referencing your current `spill` binary, and starts it: - **Linux:** writes `~/.config/systemd/user/spill.service` (`Type=notify`) and enables/starts it via `systemctl --user`. To keep it running after logout, run `loginctl enable-linger "$USER"`. - **macOS:** writes `~/Library/LaunchAgents/rs.spill.daemon.plist` and loads it via `launchctl bootstrap`. Allow incoming connections if the macOS firewall prompts for spill. Useful flags and related commands: ```sh spill service print # inspect the generated unit/plist without installing spill service install --config PATH # use a specific config file spill service install --no-start # write the service file without starting it spill service uninstall # stop/remove the service (keeps config, state, and downloads) ``` Check health and recent logs with `spill health` and `spill logs` (or `journalctl --user -u spill -f` on Linux). On shared machines you do not trust, set `web_listen = ""` in the config and restart the service; see [Web security model](web.md#security-model). ## macOS For Cargo/source installs, install Apple's command-line tools (`xcode-select --install`) and current stable Rust. Neither is needed for a release binary. State and the control socket live in `~/Library/Application Support/spill`, and downloads in `~/Downloads`. Use `spill service install` above to install and load the LaunchAgent automatically, or `spill service print` to inspect the plist before installing. Detailed logs append to `~/Library/Application Support/spill/debug.log`, and launchd stderr goes to `~/Library/Application Support/spill/spill.log`. Retention and rotation of both files are managed externally; restart the agent after renaming either file so it reopens the path. See [Troubleshooting](troubleshooting.md) for firewall and file-limit settings. The Linux-only `tests/interop` harnesses are not supported on macOS. ## Run as a Linux user service Use `spill service install` above to write `~/.config/systemd/user/spill.service` and enable it automatically, or `spill service print` to inspect it first. To keep the daemon running after you log out, enable lingering with `loginctl enable-linger "$USER"`. ## Run as a Linux system service For a dedicated `spill` system account with state in `/var/lib/spill` and the control socket at `/run/spill/control.sock`, obtain `deploy/` from the matching [source tag](https://github.com/spillrs/spill/tags): ```sh version="$(spill --version | awk '{print $2}')" curl -fsSL "https://github.com/spillrs/spill/archive/refs/tags/v${version}.tar.gz" \ | tar -xz --strip-components=1 "spill-${version}/deploy" ``` Then install the unit and config: ```sh sudo useradd --system --user-group --home /var/lib/spill --shell /usr/sbin/nologin spill sudo install -d -m 0755 /etc/spill sudo install -m 0644 deploy/spill.toml /etc/spill/spill.toml sudo install -m 0644 deploy/spill.service /etc/systemd/system/spill.service sudo systemctl daemon-reload sudo systemctl enable --now spill sudo -u spill spill --socket /run/spill/control.sock list ``` The system unit expects `/usr/local/bin/spill`. Install the binary there first; a user-local script or Cargo binary is not accessible under its `ProtectHome` sandbox. If you change `download_dir` outside `/var/lib/spill`, list it in `ReadWritePaths`. Set `SPILL_SOCKET=/run/spill/control.sock` to avoid passing `--socket` on every command. Because spill is single-user, `spill serve` enforces umask `0077` in code (downloaded files are created `0600` and directories `0700` owned by `spill`, regardless of systemd `UMask=`). ## Open the port Peers, the DHT and UDP trackers all use the listen port, default `6881`, over both TCP and UDP. Outbound traffic needs no rules. For inbound peers, allow that port through the host firewall. spill tries automatic NAT-PMP and UPnP router mapping by default; check `spill health`. If mapping is disabled (as in the system-service example) or your router refuses, forward the listen port for TCP and UDP yourself. See [Networking](networking.md#automatic-port-mapping). ## Upgrading Stop the daemon before upgrading and back up its state directory. On startup, spill checks the catalog schema version and automatically applies pending migrations before loading torrents. Schema changes and their version updates commit together; a failed migration rolls back and stops startup. Schema version 1 is the supported baseline. Unversioned nonempty catalogs and catalogs newer than the binary supports are rejected. If startup reports `unsupported catalog version`, use a compatible spill binary. Do not reset the version manually. Alternatively, for local torrents you can use a fresh `state_dir` and re-add them: complete local files are verified and seeded without downloading again, but partial downloads, traffic totals and timestamps are not recovered. Remote S3 torrents cannot be recovered from bucket objects alone—use [`restore-catalog`](cli.md#catalog-backup-and-restore) from a snapshot instead. Keep the old state directory as a backup. Incompatible or invalid cached DHT contacts are discarded and rebuilt without affecting saved torrents. Next: follow the [Quickstart](quickstart.md) to add and manage torrents. --- # Quickstart [Install spill](install.md), then start the daemon in the background (creates a default config and registers a user systemd unit on Linux or LaunchAgent on macOS): ```sh spill service install ``` Or run the daemon directly in the foreground (and use a second terminal for the commands below): ```sh spill serve ``` Downloads default to `~/Downloads`, and the loopback web interface is available immediately at . Common overrides work directly as flags—for example `spill serve --download-dir ./downloads --web 127.0.0.1:8081` or `spill serve --no-web`—or pass a TOML config (`spill config init` writes a starter file) with `spill serve --config PATH` (validate first with `--check`). Set `SPILL_SOCKET` or pass `--socket PATH` if you use a different `control_socket`. Automation should manage `serve` as a persistent process; check `spill health` before starting another daemon. ## One-shot download (no daemon) To download a single `.torrent`, magnet link, or HTTP(S) torrent URL and exit without starting a daemon: ```sh spill download ~/Downloads/debian.iso.torrent -o ./incoming ``` ## Add torrents to the daemon ```sh spill add ~/Downloads/debian.iso.torrent spill add 'magnet:?xt=urn:btih:…&tr=udp://tracker.example:1337/announce' spill add movie.torrent --output ./incoming ``` `add` accepts one or more sources and prints each torrent's hex ID (one line each, so `id=$(spill add file.torrent)` works directly). Anywhere an ID is expected you can use any unambiguous prefix (for example `3f2a` below). ## Watch progress ```sh spill list # compact table of torrents, progress, rates, ETA, and errors spill list --watch # refresh every second; Ctrl-C to stop spill wait 3f2a # block until complete (non-zero exit on error or timeout) spill health # daemon web UI, paths, listeners, port mapping, and debug log spill logs -f # follow recent daemon debug.log spill get 3f2a # summary for one torrent spill --json get 3f2a # full torrent JSON, including peers and trackers ``` A torrent moves through `starting`, `metadata` (magnets only), `recovering`, `downloading` and `seeding`. See [Torrents](torrents.md) for every state. ## Control torrents ```sh spill pause 3f2a spill resume 3f2a spill pause --all spill set 3f2a upload_limit=1MiB seed_ratio=2 seed_time=24h spill files 3f2a spill set 3f2a 'file_priorities={"1":"skip","0":"high"}' spill recheck 3f2a spill remove 3f2a # keep downloaded files spill remove 3f2a --delete-payload # also delete files spill created ``` Lifecycle commands (`pause`, `resume`, `recheck`, `reannounce`, `remove`) accept multiple IDs at once (`pause`, `resume`, and `reannounce` also accept `--all`). For automation, prefer `spill --json list`, `spill --json get ID`, and `spill wait ID` over `list --watch`, which runs until interrupted. See [Command line](cli.md) for exit codes and the control protocol. Stop the daemon with `spill shutdown`. ## Use the web interface With the daemon running, open . The page shows progress, rates, ratios, ETA, and errors, adds torrents and magnets (including multiple files or links at once), filters files, and edits settings and file priorities. To pick another loopback port or turn the web interface off, pass `--web 127.0.0.1:8081` or `--no-web` (or set `web_listen` in a TOML config). See [Web interface and HTTP API](web.md). ## Next steps - Customize background service setup or system-wide systemd units: [Install](install.md#run-in-the-background-recommended). - Explore offline tools (`download`, `create`, `inspect`, `verify`, `extract`) and JSON output: [Command line](cli.md). --- # Command line ```text spill [--socket PATH] serve [--config PATH] [--check] [OPTIONS] spill [--json] download SOURCE [-o DIR] [--allow-local-network] [--no-port-mapping] spill [--json] config init [--output PATH] [--force] spill [--json] service install [--config PATH] [--no-start] | print [--config PATH] | uninstall spill [--json] create [OPTIONS] TARGET spill [--json] inspect SOURCE spill [--json] verify FILE.torrent --path DIR spill [--json] extract ID --output DIR [--config PATH] [--catalog PATH] [--region REGION] [--path-style] spill [--socket PATH] [--json] COMMAND spill --version ``` `spill serve` runs the daemon in the foreground, writing operational logs to stderr (respecting `NO_COLOR`) and appending detailed logs to `/debug.log`. Pass `--check` to validate configuration without starting the daemon. Quick flags (`--listen ADDR`, `--web ADDR`, `--no-web`, `--download-dir DIR`, `--state-dir DIR`, `--socket PATH`, `--active-downloads N`, `--active-seeds N`) override values from `--config` or built-in defaults; relative directory and socket flags resolve from the current directory. When started under systemd with `Type=notify`, `spill serve` signals readiness over `NOTIFY_SOCKET`. See [Logging](configuration.md#logging-logging) for filters. `spill download`, `spill config`, `spill service`, `spill create`, `spill inspect`, and `spill verify` work without a running daemon. Client commands talk to a running daemon over its Unix socket. Without `--socket` (or the `SPILL_SOCKET` environment variable), client commands use: - Linux: `$XDG_RUNTIME_DIR/spill.sock`, falling back to `~/.local/state/spill/spill.sock`. - macOS: `~/Library/Application Support/spill/spill.sock`. Pass `--socket` (or export `SPILL_SOCKET`) if your config sets a different `control_socket`. `--socket` is accepted for `spill serve` (overriding `control_socket`) and daemon client commands. `--json` prints raw JSON response data instead of human-readable text, one document per line, and prints errors on stderr as `{"error":"…","code":N}`. Use it for scripts and automation. `--socket` and `--json` can appear before or after the client command. For `create`, `--json` prints the output path, `info_hash` (stable ID), `format` (`v1`, `v2` or `hybrid`), `v1` and `v2` (lowercase hex or null), `total_bytes`, and `piece_count`; progress stays on stderr. ## IDs A metainfo torrent's stable ID is its 40-digit SHA-1 hash for v1 and hybrid torrents, or its full 64-digit SHA-256 hash for v2-only torrents. A magnet keeps its supplied primary ID after resolution. Commands accept the stable ID or any known full-hash alias, case-insensitively, and any prefix matching exactly one torrent. Exact matches take precedence; an ambiguous prefix is an input error that lists matching prefixes. Both hashes of a hybrid address the same torrent, destination and accounting. Adding metainfo or a magnet with an already-known hash is a duplicate, even if the other hash or destination differs. Exception: a magnet with BEP 53 `so` enables its referenced skipped files in the existing torrent and returns that ID, preserving other priorities, settings, destination and pause state. No-op selection updates do not restart the torrent. All supplied hash topics must already identify the same entry. `add`, `get`, and `--json` output print full IDs; `list` text mode displays a 12-character prefix for compact columns. ## Commands ### Torrent control | Command | What it does | |---|---| | `add SOURCE... [--output DIR \| --remote] [--paused] [--set KEY=VALUE]...` | Add one or more local `.torrent` files (or `-` for stdin), `magnet:` links, or HTTP(S) torrent URLs. Relative `--output` paths resolve from the current directory; defaults to `download_dir`. `--remote` stores verified pieces in the configured [`[remote_storage]`](configuration.md#remote-s3-storage-remote_storage) bucket instead of local files (cannot be combined with `--output`). `--paused` prevents startup; repeated `--set` overrides daemon defaults before startup. Prints each torrent ID (one per line in text mode). Existing torrents are errors except for magnet `so` selection updates; see [File selection](torrents.md#file-selection). | | `list [--watch]` | Compact table of torrents: 12-char ID, state, selected progress and `%`, rates, peers, ETA, name, and any `Error:` / `Tracker:` lines. `--watch` refreshes every second until Ctrl-C. | | `wait ID... [--timeout SECS]` | Poll the daemon until every specified torrent reaches completion. Exits non-zero immediately if a torrent records `last_error`, disappears, or exceeds `--timeout`. | | `status` | Daemon health followed by the torrent table (both included in `--json`). | | `get ID` | Concise summary for one torrent in text mode; complete JSON (settings, accounting, peers, trackers, DHT, storage) with `--json`. | | `set ID KEY=VALUE ...` | Change per-torrent settings. Values are JSON (numbers, `true`/`false`, arrays, sparse priority maps) or human rate/duration shorthands (`2MiB`, `500K`, `24h`, `7d`). See [Changing settings with `set`](#changing-settings-with-set). | | `files ID` | Aligned table of files in torrent order: index, size, priority, path (marking `[padding]` entries). Requires metadata. | | `pause ID... \| --all` | Stop one or more torrents (or all torrents) and keep them paused across restarts. | | `resume ID... \| --all` | Allow one or more paused torrents (or all torrents) to run again (they may wait for a free slot). | | `recheck ID...` | Verify every piece against the data on disk, then leave the torrent paused. Use after moving or editing files, or after an unclean power loss. | | `reannounce ID... \| --all` | Announce to the tracker again as soon as the tracker's `min interval` allows. Fails if trackers are disabled or the torrent is not running. A magnet still resolving metadata announces again once resolution finishes. | | `remove ID... [--delete-payload]` | Remove one or more torrents. Files are kept unless `--delete-payload` is given; reports whether created payload was deleted or adopted files were kept. See [Torrents](torrents.md#removing-torrents). | ### Daemon | Command | What it does | |---|---| | `serve [--config PATH] [--check] [OPTIONS]` | Run the daemon in the foreground, or validate effective config and exit with `--check`. Supports `--listen`, `--web`, `--no-web`, `--download-dir`, `--state-dir`, `--socket`, `--active-downloads`, and `--active-seeds`. | | `health` | Plain-text daemon health: version, web UI URL, download/state directories, listeners, inbound peer observations, port mapping, debug log status/path, and admission state. Use `--json` for structured output. See [Health](#health). | | `logs [-f\|--follow]` | Print the recent 64 KiB tail of `/debug.log` (with `-f`, poll for new lines until Ctrl-C). | | `set-bandwidth [--download RATE] [--upload RATE]` | Change one or both daemon-wide caps without restarting torrents. Accepts bytes/s or human units (`2MiB`, `500K`). At least one flag is required; omitted caps stay unchanged; `0` means unlimited. Restart restores configured values. | | `export-catalog PATH` | Export a consistent SQLite catalog snapshot to a new absolute path (local CLI only; not exposed over HTTP). See [Catalog backup and restore](#catalog-backup-and-restore). | | `shutdown` | Stop the daemon cleanly. | ### Standalone & setup tools (no daemon required) | Command | What it does | |---|---| | `download SOURCE [-o DIR] [--allow-local-network] [--no-port-mapping]` | One-shot download of a local `.torrent` (or `-`), magnet link, or HTTP(S) torrent URL into `DIR` (default `.`), then exit cleanly. | | `config init [--output PATH] [--force]` | Write a commented starter config to the platform user config path (or `-` for stdout). | | `service install [--config PATH] [--no-start]` | Create a default config if missing, write the user systemd unit (Linux) or LaunchAgent plist (macOS) pointing to the current `spill` binary, and start it. | | `service print [--config PATH]` | Print the generated user-service definition to stdout without modifying files or service state. | | `service uninstall` | Stop, disable, and remove the user-level background service while keeping config, state, and downloaded files. On Linux, this checks with the user service manager even if the unit file is missing, and reports an error if it cannot verify the service status. | | `create TARGET [OPTIONS]` | Create a v1, v2 or hybrid `.torrent` from a file or directory, without a daemon. See [Creating torrents](#creating-torrents). | | `inspect SOURCE` | Inspect a local `.torrent`, a quoted magnet link, or `-` for metainfo on stdin, without a daemon or network access. Prints a summary in text mode or full JSON with `--json`. See [Inspecting torrents and magnets](#inspecting-torrents-and-magnets). | | `verify FILE.torrent --path DIR` | Read-only, offline check of complete payload (`--output` is accepted as an alias for `--path`). Stops at the first failure. See [Verifying local payload](#verifying-local-payload). | | `extract ID --output DIR [--config PATH] [--catalog PATH] [--region REGION] [--path-style]` | Download every verified piece of a complete remote S3 torrent from the bucket into local files beneath `DIR`, verifying object guards and piece hashes. Reads endpoint, bucket, prefix, and guard mode from the catalog (`--config` is optional; pass `--region` or set `AWS_REGION` when omitting it). Works offline against an exported `--catalog` snapshot or read-only against the live catalog. See [Remote S3 storage](remote-storage.md#extracting-to-local-files). | | `restore-catalog SNAPSHOT --state-dir DIR` | Restore an exported catalog snapshot into an empty state directory with the daemon stopped. See [Catalog backup and restore](#catalog-backup-and-restore). | ## Catalog backup and restore While the daemon is running, export a consistent catalog snapshot to a new file in an existing directory: ```sh spill export-catalog /absolute/backup/catalog.sqlite ``` This command uses the Unix control socket and does not copy payloads. It includes metainfo, tracker completion state, and the latest acknowledged S3 bitmap and piece guards. Do not substitute a copy of the live SQLite main file. Keep the snapshot on independent storage; its age limits how much download progress can be recovered. With the daemon stopped, restore into an empty state directory: ```sh spill restore-catalog /absolute/backup/catalog.sqlite --state-dir /absolute/restore/state ``` Start the daemon with `state_dir` set to that directory. Supply the configuration and credentials separately. S3 torrents must use the original endpoint, bucket, prefix, and guard mode; pinned versions must still exist. Local torrents still need their original payload files and paths. Restore does not overwrite an existing catalog or contact the bucket. Remote recheck and payload deletion are not supported (`spill remove ID` forgets the torrent and leaves bucket objects untouched). ## Changing settings with `set` Keys are the [`[defaults]` keys](configuration.md#torrent-defaults-defaults) (also listed by `spill set --help`): ```sh spill set ID download_limit=2MiB upload_limit=512KiB spill set ID download_limit=1048576 upload_limit=524288 spill set ID seed_ratio=2 seed_time=24h spill set ID trackers=true dht=false pex=false web_seeds=true spill set ID 'file_priorities={"1":"skip","0":"high"}' spill set ID 'file_priorities=["high","skip","normal"]' spill set ID 'file_priorities=[]' # back to all files ``` - Quote values that contain braces, brackets, or spaces so your shell passes them intact. - `download_limit` and `upload_limit` accept raw bytes/second or binary units (`B`, `K`/`KiB`, `M`/`MiB`, `G`/`GiB`, with optional `/s`). `seed_time` accepts raw seconds or duration units (`s`, `m`, `h`, `d`). - Changing only `download_limit` or `upload_limit` applies live without restarting a running torrent and is saved across daemon restarts. Other changes stop and restart a running torrent with the new settings. A paused torrent stays paused. - `file_priorities` accepts either a sparse JSON object mapping zero-based file indices to priorities (`{"3":"skip"}`) or a full array with one entry per file in `spill files` order (including padding files, which must be `"skip"`). Explicit file priorities need metadata, so wait for a magnet to resolve first. For large multi-file torrents, the web UI's Files tab or magnet `so=` is also convenient. - `dht` and `pex` cannot be enabled on private torrents. ## Exit codes | Code | Meaning | |---|---| | 0 | Success | | 1 | The operation failed | | 2 | Invalid input (bad arguments, invalid config, bad values, ambiguous ID, invalid torrent) | | 3 | No torrent matches the ID | | 4 | Cannot reach the daemon (not running, shutting down, wrong socket, permission denied) | | 130 | Interrupted with Ctrl-C (`list --watch`, `wait`, `logs -f`, `download`, `extract`) | In `get` JSON, `transfer.peers[].transport` is `"tcp"`, `"utp"` or `"http"` (for web seeds). `transfer.peers[].encryption` is `"rc4"` or `"plaintext"` for peer streams, or `null` for web seeds and unavailable/unnegotiated observations; it does not describe web-seed TLS. A uTP peer also has `utp_retransmits`, the number of resent outgoing uTP datagrams. `transfer.utp_retransmits` totals these over the current running owner, including peers that have closed; restarting the owner resets it. Counts are sampled while peer I/O is attached; later FIN-linger retransmissions are not included. `transfer.pending_contacts` counts queued and currently dialing or negotiating discovery contacts, not established peers. These diagnostics are not wire traces. ## Health `spill health` prints readable fields, including the running daemon's version, web UI address, and configured directories; `spill health --json` returns the complete health object. The control/HTTP API stays JSON. Existing fields include `version` (the running daemon's version), `pid`, `running`, `listen`, `web_listen`, `download_dir`, `state_dir`, `advertised_port`, `port_mapping` and `admission_closed`. The text output includes local discovery readiness and its last error. LSD failures do not stop the daemon. Interfaces are checked every minute; sockets are rebuilt only on changes or errors, including retrying unavailable interfaces or port 6771. The `network` object adds: | Field | Meaning | |---|---| | `tcp_listen`, `udp_listen` | Local address while the listener/receiver task is running; `null` offline or stopped. Not proof of external reachability. | | `utp_enabled`, `dht_enabled` | Configured session permissions. DHT can be enabled without its lazy node having started. | | `pending_dials`, `pending_dials_limit` | Used and maximum shared dial permits. Finished attempts retain permits until their owner consumes the result. | | `queued_contacts` | Shared contact entries awaiting attempts, including delayed retries. Not a count of immediately eligible peers. | | `pending_handshakes`, `pending_handshakes_limit`, `pending_handshakes_per_ip_limit` | Current shared inbound handshake usage, total cap and per-source-IP cap. | | `utp_connections`, `utp_connections_limit` | Current uTP multiplexer entries and cap, including connecting and closing streams. Both zero offline. | | `inbound_tcp`, `inbound_utp` | Separate passive observations for each peer transport, with the fields below. | | `lsd` | Local discovery: `enabled` permission, `active` multicast socket readiness, `announces` batches sent on at least one interface, `received` valid announcements from other sessions, and `last_error` (or `null`). Counters reset on daemon restart. Any successful interface send clears `last_error`, even if another interface failed in the same batch; those partial failures remain in the logs. | | Inbound field | Meaning | |---|---| | `active` | Successful inbound handshakes whose transports are still alive, including LAN peers. | | `active_public` | Public-address subset of `active`. | | `total` | Successful inbound handshakes since daemon startup, including LAN peers. | | `public_total` | Public-address subset of `total`. | | `last_public_ago_secs` | Seconds since the last successful public inbound handshake; `null` means none observed since startup. | Counts exclude bare TCP accepts, incomplete/invalid handshakes, outbound peers and web seeds. Totals survive disconnections and torrent removal, but reset with the daemon. Public classification excludes loopback, private, link-local and shared-address IPv4 ranges; mapped IPv4 addresses are classified as IPv4. These observations do not contact any external service or send probes. A recent public handshake is evidence of connectivity at that time; a quiet swarm is not evidence of a closed port. See [Troubleshooting](troubleshooting.md#nobody-can-connect-to-me). Health includes `bandwidth.download_limit` and `bandwidth.upload_limit`, the effective daemon-wide caps in payload bytes per second. `0` means unlimited. In `status` JSON these fields are under `health.bandwidth`. Health also includes `logging`: `file_enabled`, `path` (the `debug.log` path), cumulative `events_dropped` since daemon startup, and `write_failed` for the most recent debug-file write. A successful write clears `write_failed`; it does not erase the drop count. These observations do not make health independent of slow control or cleanup work. Resource counts are sampled separately, not one atomic reservation view. ## Inspecting torrents and magnets ```sh spill inspect download.torrent spill inspect download.torrent --json spill inspect 'magnet:?xt=urn:btih:0123456789012345678901234567890123456789' spill inspect - < download.torrent ``` Output is a concise human summary by default; `--json` produces one compact JSON document for scripts containing `kind`, `info_hash`, `format`, `v1`, `v2`, and `name`. Metainfo inspection validates the content structure and reports the private flag, piece length/count, file paths, lengths, offsets and padding flags, plus available tracker tiers, web seeds, comment, creator, creation date and source. `total_bytes` includes virtual padding; `data_bytes` excludes it. File paths follow the metainfo layout (relative to the root for multi-file torrents), not sanitized disk paths. `layers_pending` indicates missing v2 layers in a hybrid. Magnet inspection reports decoded `parameters`, including discovery hints and file selections; it does not resolve metadata. The existing magnet parser skips invalid tracker hints. Inspection never contacts trackers or peers, reads payload, adds a torrent, or connects to the daemon. Metainfo uses the protocol parser's 32 MiB input budget; successful inspection does not guarantee daemon admission under the engine's stricter [limits](limits.md). Non-UTF-8 text is displayed with replacement characters; hashes always use the original info bytes. Control characters are JSON-escaped. Output can contain private tracker passkeys: redact it before sharing. ## Verifying local payload ```sh spill verify download.torrent --path /downloads spill verify download.torrent --path /downloads --json ``` This is a complete-payload pass/fail check using the engine's existing verification. `--path` is the parent directory, as with `add --output`: directory torrents expect `DIR/NAME/`, single-file torrents `DIR/NAME`. Paths use spill's [normalized disk names](torrents.md#adding-torrents). Missing, wrong-size, corrupt or partial (`.part`) files fail; symlinks beneath `DIR` and non-regular files are rejected. The explicitly supplied root may be a symlink. V1, v2 and hybrid torrents are supported; hybrids without v2 layers use SHA-1. Padding files are not read. Metainfo must meet the engine's [limits](limits.md). The command never modifies files, uses networking, or reads/writes daemon or resume state. It does not repair data or provide a per-piece report. Keep payload unchanged throughout the scan: it is not a snapshot. Success prints `Verified HASH`, or `{"info_hash":"HASH","verified":true}` with `--json`, and exits 0. Verification stops at the first failure, writes the error to stderr, and exits 1 without stdout output. Malformed metainfo exits 2. Unlike `recheck ID`, it does not require adding the torrent or update daemon state. ## Creating torrents ```sh spill create ./payload -a https://tracker.example/announce -o payload.torrent spill create ./payload -d -l 20 -t 4 -p -s my-source spill --json create ./payload -w https://seed.example/payload/ ``` The options follow mktorrent's conventions: | Option | Meaning | |---|---| | `-a`, `--announce URL[,URL]` | Tracker tier. Comma-separated URLs are alternatives; repeating the option adds backup tiers. HTTP(S) and UDP are supported. Optional for trackerless torrents. | | `-c`, `--comment TEXT` | Comment outside the info hash. | | `-d`, `--no-date` | Omit the creation date, making unchanged input and options reproducible across worker counts. | | `-F`, `--format v1\|v2\|hybrid` | Torrent format; default v1. | | `-l`, `--piece-length N` | Piece size is **2^N bytes**, not N bytes. Range 15–28 (32 KiB–256 MiB); default 18 (256 KiB). | | `-n`, `--name NAME` | Torrent root name; defaults to the target basename. | | `-o`, `--output PATH` | Output path; default `NAME.torrent` in the current directory. Existing files, directories and symlinks are never replaced. Parent directory must exist. | | `-p`, `--private` | Set `info.private=1`. | | `-s`, `--source TEXT` | Set `info.source`; affects the info hash, like the private flag. | | `-t`, `--threads N` | Nonzero hashing worker count; default is the available CPU count. Each worker uses a 64 KiB read buffer. | | `-v`, `--verbose` | Show piece progress even when stderr is not a terminal. Progress is otherwise automatic on terminals. | | `-w`, `--web-seed URL[,URL]` | HTTP(S) web seeds. May be repeated. For directory torrents, use a directory URL ending in `/`. | V1 sorts whole relative path bytes to match mktorrent. V2 and hybrid use BEP 52 file-tree order (byte-sorted path components) and piece-aligned files; hybrids add BEP 47 padding entries. Hybrid creation refuses a source directory with a top-level `.pad` entry. Hidden and zero-length files are included; empty directories are omitted. Symlinks to files and directories are followed, including links outside the target tree; ancestor cycles, dangling links and special files are errors. Keep the source unchanged until creation finishes. Creation checks for observed file changes but does not take a filesystem snapshot. Unlike mktorrent, spill rejects a directory containing no files, matching its supported metainfo format. [Limits](limits.md) apply; if a payload needs too many pieces, select a larger piece length. Paths are limited to 32 levels including the torrent root. Creation only reads the source; it does not add or start seeding the torrent. Afterward, use `spill add FILE.torrent --output /absolute/parent` to verify and seed files already at the expected destination. A directory torrent expects `PARENT/NAME/`; a single-file torrent, including v2 and hybrid, expects `PARENT/NAME`. A name override or spill's [filesystem name sanitization](torrents.md#adding-torrents) can make those paths differ from the original source paths. Source symlinks are followed during creation, but are not adopted as payload paths when seeding. ## Identity and discovery in JSON `get`, `list` and `status` expose `id`, `format` (`"v1"`, `"v2"` or `"hybrid"`), `v1` (40-digit SHA-1 or `null`), and `v2` (64-digit SHA-256 or `null`). `metadata_ready` means validated metainfo sufficient for payload verification is available; it is independent of payload recovery or completion. `info_validated` means the info dictionary and all supplied magnet topics have passed validation. `hash_bytes` and `hash_total_bytes` report authenticated v2 layer acquisition, excluding proof siblings and repeated roots, not payload progress. These counters are zero when no acquisition is needed at startup. V2-only magnets acquire layers before payload preparation; partial acquisition is discarded on stop. `layers_pending` identifies hybrids using SHA-1 while v2 layers are absent. They rebuild layers from verified payload at full completion; the next start uses both swarms for public torrents. Private hybrids announce only v1. See [v2 and hybrid torrents](v2.md). `completed_announces` is an array of `{ "swarm": "40 hex digits", "delivered": true }` records. `false` means pending; an absent record means no completion event was recorded for that swarm. Delivery is persisted independently for each public hybrid swarm; private hybrids record only v1 delivery. `last_error` reports torrent-level failures, not tracker failures. `tracker_error` exposes a tracker failure while no selected tracker is succeeding for that swarm; recovery or successful fallback clears it. Non-JSON `list` prints it beneath the row, and the web UI includes it in the error filter without changing torrent state. Per-tracker errors remain in `transfer.trackers[].error`, alongside state, counters and reply age. `transfer.trackers[].active` identifies the selected tracker for each swarm. A failed backup can retain its error while the selected tracker succeeds; that does not make the torrent failed or set `tracker_error`. `tracker_message` exposes a selected tracker's warning, also available in `transfer.trackers[].warning`. `transfer.trackers[]` and `transfer.dht[]` identify their swarm with the same `swarm` key: SHA-1 for v1, the 20-byte SHA-256 prefix for v2. DHT observations are an array, empty when disabled. Public hybrids with authenticated layers have independent tracker/DHT state for both keys but shared payload progress and budgets. Pending-layer hybrids use only the v1 swarm. Private hybrids announce only v1, and private torrents disable DHT in every format. Each public hybrid tracker swarm receives the same torrent-wide upload/download counters, not per-swarm traffic; summing their accounting can double-count bytes. DHT entries also report `node_ids` (hexadecimal) and `external_addresses`, each an array in IPv4/IPv6 order. Disabled families have a `null` node ID; an address is `null` until a public bind address or DHT address votes establish it. Before that, the node ID is not yet address-bound. These identities are session-wide, not different for each swarm. See [DHT security](networking.md#dht-security-and-public-addresses). ## Runtime diagnostics in JSON `transfer` is also available during magnet acquisition and payload recovery. During metadata acquisition it reports tracker snapshots, active peer count, `pending_contacts`, and `metadata_error`: the most recent core metadata-peer rejection or request timeout, retained through payload promotion. This is not a torrent failure and is not cleared when another peer succeeds. Per-peer payload records and DHT lookup snapshots are not published during metadata acquisition. Selected-byte counts remain `null` until metadata is ready. | Transfer field | Meaning | |---|---| | `diagnostics_age_ms` | Age of the last diagnostic sample, or `null` before the first sample. Samples normally refresh every two seconds; an old sample is not evidence of current activity. | | `storage` | Latest storage-worker observation, or `null` before storage exists. Fields: `operation`, `operation_age_ms`, `hashes_in_flight`, `reads_in_flight`, `s3` (`null` for local storage). | | `holepunch` | Execution-local cumulative coordination counters described below. | Storage `operation` identifies the worker's current activity or wait: `recovery`, `recovery_wait` (shared recheck capacity), `seed_file_pool`, `idle`, `write`, `hash`, `read`, `put`, `get`, `remote_checkpoint`, `leaves`, `finish_file`, `sync` (completion barrier), `fingerprint`, `checkpoint`, `metadata_checkpoint`, `layers`, `publish` (result delivery), `drain`, `stopped` or `failed`. `operation_age_ms` is how long that label has remained unchanged, not an individual disk-I/O latency. Hash/read counts include submitted payload jobs waiting for blocking execution or collection; they exclude recovery jobs. Jobs can overlap the named worker operation. Check `diagnostics_age_ms` before interpreting storage activity: operation age keeps increasing even if the observation is stale. For an online S3 torrent, `spill --json get ID | jq '.transfer.storage.s3'` shows `put`, `get`, and `proof_get` (a subset of `get`). Each reports `requests`, `retries` (already included in `requests`), `bytes`, `latency_total_us`, and `latency_max_us`. Counters reset when the torrent execution restarts. Attempts are recorded when they finish, fail, or are cancelled. PUT bytes are payload submitted to S3; GET bytes are range body bytes consumed, not virtual padding. These are not provider billing counters. Latency includes body processing but not time waiting for a request slot or retry backoff. Divide `latency_total_us` by `requests` for the mean over attempts. `transfer.peers[].detail.remote_upload_only` reports the peer's BEP 21 hint: `true` means it does not intend to download more pieces. Missing or malformed hints leave the previous value unchanged; the initial value is `false`. This hint does not mean the peer has every piece or that it cannot upload to spill. Holepunch counters reset for each execution: - `rendezvous_started`: introducer requests queued by this torrent. - `remote_errors`: BEP 55 error frames received while holepunching is enabled. - `rendezvous_expired`: pending introducer requests that reached their deadline. - `punches_queued`: punch leases created or ordinary queued contacts upgraded. Duplicates do not increase this count. - `punches_expired`: leases that expired before dial admission, including upgraded contacts restored to their original schedule. These counters are sampled diagnostics, not NAT reachability tests or transfer success counts. All execution diagnostics reset when the torrent restarts. ## Accounting in JSON `get`, `list` and `status` expose the same per-torrent accounting fields: | Field | Meaning | |---|---| | `downloaded_bytes` | Lifetime payload received from peers and web seeds, including corrupt data, duplicates and re-downloads processed by the engine. Excludes existing files and protocol overhead. | | `uploaded_bytes` | Lifetime payload written to peer transports, excluding protocol overhead. Does not prove the remote peer retained it. | | `hash_failed_bytes`, `hash_failed_pieces` | Lifetime bytes and piece-verification attempts rejected after a downloaded piece fails its hash check. Counts the actual piece length, including a short final piece; repeated failures count again. Excludes startup/recheck corruption. | | `verified_bytes` | Currently verified bytes across the full torrent, not cumulative downloads. | | `wanted_bytes`, `wanted_verified_bytes` | Selected data bytes and their verified portion, excluding padding and skipped-file portions of boundary pieces. `null` before metadata is available. | | `completed` | Saved or live completion of the selected target after the completion barrier. Independent of whether the torrent is running. Changing file selection clears it until the new target is checked by a run. | | `seed_seconds` | Seconds running ready and complete, including idle seeding; excludes recovery, pauses and downtime. | | `added_at` | When this catalog entry was created. | | `completed_at` | Most recent recorded transition to complete, including adopted files. Retained if the torrent later becomes incomplete. | | `last_download_at`, `last_upload_at` | Most recent observation of payload received/sent, or `null` if none. | Timestamps are UTC Unix epoch seconds; optional timestamps are `null` until known. Activity timestamps are sampled, not packet timestamps. Live rates update about every two seconds; lifetime accounting is sampled about every second. `transfer.downloaded_bytes` and `transfer.uploaded_bytes` count only the current run and reset when it restarts. `transfer.hash_failed_bytes` and `transfer.hash_failed_pieces` likewise count only the current run. Hash-failure bytes are already included in downloaded traffic, not additional traffic. `transfer` is `null` when no run is present. Stopped progress comes from the saved resume record; file fingerprints are validated when the torrent next runs. Lifetime totals, timestamps and seeding time survive orderly restarts and rechecks. Removing and re-adding a torrent starts its accounting afresh. See [Torrents](torrents.md#accounting) for checkpoint durability. ## Control protocol Client commands send one JSON object per line to the socket and read one JSON response line. Other programs can do the same, for example with `socat`: ```sh # Linux (when XDG_RUNTIME_DIR is set) socket="$XDG_RUNTIME_DIR/spill.sock" # macOS # socket="$HOME/Library/Application Support/spill/spill.sock" echo '{"op":"get","id":"3f2a"}' | socat - "UNIX-CONNECT:$socket" ``` Supported `op` values: `add`, `get`, `set`, `list`, `status`, `files`, `pause`, `resume`, `recheck`, `reannounce`, `remove`, `health`, `set_bandwidth`, and `shutdown`. Requests use `op` plus the same fields as the commands (`id`, `values`, `delete_payload`, `magnet`, `url`, `output_dir`, `paused`, `settings`, `summary` on `list`/`status`, or `download_limit`/`upload_limit` for `set_bandwidth`). Setting `"summary": true` on `list` or `status` omits `settings.file_priorities` and per-peer, tracker, DHT, web-seed, and storage telemetry arrays while keeping progress, rates, active peer counts, and warnings. For `add`, `metainfo` is the `.torrent` file as a standard base64 string (at most 16 MiB decoded); give exactly one of `metainfo`, `magnet`, or `url`. Optional `settings` is an object of per-torrent overrides merged with daemon defaults; `paused` defaults to false. Settings are validated before the torrent is saved or started. Private metainfo always disables DHT and PEX, including initial overrides. An HTTP(S) torrent URL is still fetched when adding paused; payload transfer and discovery wait for `resume`. `remove` returns `{"removed": ID, "delete_payload": bool, "deleted_payload": bool}`. Responses are `{"code":0,"data":…,"error":null}`; `code` uses the exit codes above. Requests are limited to about 22 MiB. --- # Configuration spill reads a TOML 1.1 file only when started with `spill serve --config PATH` (or via the service registered by `spill service install`). Without it, every key below takes its default. Generate a commented starter file with `spill config init`. CLI flags on `spill serve` (`--listen`, `--web`, `--no-web`, `--download-dir`, `--state-dir`, `--socket`, `--active-downloads`, `--active-seeds`) override values from the config file or defaults. The file is limited to 64 KiB. Validate edits without touching a running daemon using `spill serve --config PATH --check`. Rules that apply to the whole file: - `state_dir`, `download_dir`, and `control_socket` must be absolute paths, or start with `~/` (expanded against `HOME`). Environment variables are not expanded. - Unknown keys are errors, so typos are caught at startup. - Invalid values exit with code 2 before starting the runtime. - `[defaults]` is copied into each torrent when it is added. Changing it later does not affect torrents that already exist; use `spill set` for those. ## Daemon keys The table shows Linux path defaults. On macOS, `state_dir` defaults to `~/Library/Application Support/spill` and `control_socket` to `~/Library/Application Support/spill/spill.sock` (ignoring `XDG_RUNTIME_DIR`). Downloads default to `~/Downloads` on both platforms. If you override `state_dir`, set `control_socket` too; its default is independent of that override. | Key | Default | Meaning | |---|---|---| | `state_dir` | `~/.local/state/spill` | Catalog (`catalog.sqlite`), lock file and debug log (`debug.log`). Created with mode `0700`. Two daemons cannot share one state directory. Overriding `state_dir` does not move the default `control_socket`. | | `download_dir` | `~/Downloads` | Where new torrents are saved unless `add` gives an output directory. `spill serve` enforces umask `0077` (`0600` files / `0700` dirs) as part of its single-user design. | | `control_socket` | `$XDG_RUNTIME_DIR/spill.sock`, else `~/.local/state/spill/spill.sock` | Unix socket for `spill`. Created with mode `0600`. Independent of `state_dir`; set explicitly if running a second instance. | | `listen` | `"0.0.0.0:6881"` | Address and port for TCP peers and for uTP peers, the DHT and UDP trackers (UDP, same port). Both must be free. `"[::]:6881"` listens on IPv6 and IPv4 (dual-stack). | | `web_listen` | `"127.0.0.1:8080"` | Address for the web interface. Must be a loopback address. Set `""` (or pass `--no-web`) to disable HTTP. | | `allow_local_network` | `false` | Allow outbound connections to private, loopback and link-local addresses (LAN peers, a tracker on your network), and enable BEP 14 local service discovery for torrents with `dht = true`. LSD uses multicast UDP port 6771; peer destinations still cannot be multicast, unspecified, broadcast or port 0. Inbound connections are not filtered. | | `utp` | `true` | Accept uTP peers and try uTP before TCP when dialing. Set `false` for TCP-only peers; UDP trackers and the DHT remain available. | | `peer_encryption` | `"preferred"` | MSE/PE for TCP and uTP: `"allowed"` tries plaintext first, `"preferred"` tries MSE first, `"required"` permits only RC4 application streams. The first two accept plaintext and allow one alternate-mode retry after a negotiation close/reset. See [Peer encryption](networking.md#peer-encryption). | | `port_mapping` | `true` | Ask the IPv4 gateway to forward the listen port for TCP and UDP, using NAT-PMP then UPnP IGD. Failures never stop torrents. The system-service example disables it. | | `port_mapping_gateway` | unset (auto-discover) | An IPv4 address (port 5351) or `"ip:port"` overrides NAT-PMP discovery. An `"http://host:port/rootDesc.xml"` UPnP description URL skips NAT-PMP and SSDP and uses that IGD directly. Hosts must be unicast, ports nonzero; URL overrides accept HTTP only, without credentials or fragments. | | `peers` | `50` | Maximum connections per torrent, `1`–`4096`. | | `session_peers` | unset | Limit on live TCP/uTP peers across the daemon, `1`–`262144`. When unset, uses `min(active_downloads + active_seeds, 64) × peers`. Idle torrents do not reserve peer slots. | | `session_download_limit` | `0` | Daemon-wide download cap in payload bytes per second. `0` is unlimited. Paces requests, not payload already in flight. | | `session_upload_limit` | `0` | Daemon-wide upload cap in payload bytes per second. `0` is unlimited. | | `write_queue_bytes` | `16777216` (16 MiB) | Received data waiting to be written, per torrent, 16 KiB–1 GiB. Completed seeds cap their queue at 512 KiB. | | `active_downloads` | `8` | How many torrents may download at once, `0`–`64`. | | `active_seeds` | `256` | How many complete torrents may seed at once, `0`–`100000`. | | `dht_bootstrap` | four public routers | `host:port` or `[IPv6]:port` routers used to join the DHT, at most 16. Names resolve separately for each enabled address family. `[]` disables bootstrapping from routers (saved DHT nodes are still used); it does not disable the DHT. | Session caps are shared across torrents and apply in addition to nonzero per-torrent limits. See `spill --json health` for the effective caps. To change them until restart, use `spill set-bandwidth --download BYTES_PER_SECOND` or `--upload BYTES_PER_SECOND`. Live changes do not rewrite the config. `active_downloads` (up to `64`) and `active_seeds` (up to `100000`) are separate slot pools with a nonzero sum. Torrents beyond the limits wait as `queued`. See [Torrents](torrents.md#queueing). ## Remote S3 storage: `[remote_storage]` Add an optional `[remote_storage]` table to store verified torrent pieces as individual objects in an S3-compatible bucket (using spill's built-in HTTPS `reqwest`/`rustls` transport and AWS SigV4 signing; no extra build features are required). ```toml [remote_storage] endpoint = "https://s3.example.com" region = "auto" bucket = "spill-pieces" prefix = "host-a" guard = "StableEtag" # or "Version" path_style = true # default: false # ca_bundle = "/absolute/path/to/ca.pem" # assembly_bytes = 201326592 # read_window = 4 ``` Supply credentials through `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and optional `AWS_SESSION_TOKEN` in the daemon's environment. `endpoint` must be an HTTPS origin; `prefix` must be dedicated to spill. - `guard`: choose `"StableEtag"` only if identical single-part uploads return the same strong ETag; choose `"Version"` only if every object version referenced by a restorable catalog snapshot is retained. - `assembly_bytes`: shared RAM budget for in-flight remote piece downloads and PUT bodies. Defaults to 5% of host/cgroup memory (capped at 512 MiB, or 96 MiB if memory cannot be detected). Each active piece reserves twice its logical size through PUT acknowledgement, so the largest supported remote piece is half this budget. Downloads do not stage pieces on local disk. - `read_window`: maximum outstanding S3 GETs per remote torrent (`1`–`32`, default `4`). Remote torrents share a limit of 64 outstanding S3 GETs per configured destination, and cache piece guards in memory. Permanent S3 errors (HTTP `401`/`403`, `404`, `412`, or binding mismatch) pause the torrent with `last_error` instead of retrying indefinitely. Keep regular backups with [`spill export-catalog`](cli.md#catalog-backup-and-restore). See [Remote S3 storage](remote-storage.md) for provider examples, caching, and operational details. The default DHT routers are `dht.libtorrent.org:25401`, `dht.transmissionbt.com:6881`, `router.bittorrent.com:6881` and `router.utorrent.com:6881`. ### Memory Uploads read verified blocks on request and rely on the OS file cache. Each running torrent reserves `write_queue_bytes` (16 MiB by default) for queued writes. The shared UDP socket requests a 2 MiB kernel receive buffer for uTP bursts; the OS may cap or adjust that size. Each uTP peer has at most 256 KiB of queued/unacknowledged send data and 256 KiB of receive/reassembly data. Of the receive budget, 192 KiB is advertised and 64 KiB is reserved to fill reassembly gaps. Encrypted peer writes stage at most 64 KiB of ciphertext per connection. Transport buffers fill on demand and are additional to the torrent writer reservations. At the default session limit of 3,200 peers (`min(active_downloads + active_seeds, 64) × 50`), uTP buffer allowances alone can reach about 1.6 GiB, before peer queues, bookkeeping and kernel buffers. The roughly 35 MiB measurement for 33 torrents in [Limits](limits.md) is a web-seed workload, not a uTP worst-case estimate. Size any systemd `MemoryMax` for the admitted torrent and peer budgets, not that measured baseline. ## Logging: `[logging]` The daemon writes operational events to stderr and a more detailed history to `/debug.log`. These outputs have independent filters; lowering console verbosity does not discard debug-file events. Changes require a restart. Client commands keep their usual stdout/JSON and stderr behavior. The embeddable engine never installs a subscriber; its application owns tracing configuration. | Key | Default | Meaning | |---|---|---| | `console_filter` | `"info"` | Tracing filter for stderr: lifecycle, torrent failures/recovery and subsystem warnings by default. | | `file_filter` | `"warn,spill=debug"` | Tracing filter for the debug file: spill debug events and dependency warnings. | | `file_enabled` | `true` | Set `false` to create no debug-file output or writer thread. Existing logs are not deleted. | | `peer_endpoints` | `false` | Include peer IP addresses and ports in dial, admission and holepunch trace events in either output. Requires a matching `trace` filter; does not increase verbosity itself. | Filters accept levels (`off`, `error`, `warn`, `info`, `debug`, `trace`) and module directives, for example `warn,spill::engine::storage=trace`. Invalid effective filters stop startup; the file filter is validated even if file output is disabled. `RUST_LOG`, when set, overrides only `console_filter`; it never changes the file filter. Startup failures before logging configuration is installed always go to stderr. `debug.log` is opened in append mode with permissions `0600`, including across restarts. spill does not rotate, truncate or limit the file; retention is the system administrator's responsibility. If an external tool renames the file, restart spill to reopen it at the original path. A background thread writes files without blocking the torrent runtime. Its queue holds at most 1024 events, each capped at 16 KiB; saturation drops new file events rather than blocking transfers. Dropped-event counts are reported to stderr at most once a minute and on clean shutdown. Shutdown drains queued events; logs are not fsynced and a crash can lose recent events. An unusable debug-log destination stops startup. Later write failures are reported once to stderr per failure episode, retried on subsequent events, and do not stop torrents; recovery is also reported. Writer-health messages bypass console filtering. `health --json` also exposes cumulative dropped events and the current file-write failure flag under `logging`; successful writes clear the flag, not the count. Verbosity is event-driven, not a progress feed: - `info`: daemon/torrent lifecycle, recovery and changed port mappings. Successful lease renewals do not repeat the mapping announcement. - `debug`: storage recovery/failure operations, resume rejection, piece retries, stalls, metadata-peer rejections, protocol/request-timeout peer closes, changed tracker failures/recovery and web-seed failures. No periodic progress, successful checkpoints or peer dumps. - `trace`: peer/dial/handshake churn, inbound rejection reasons, transport fallback, successful piece/block activity, piece withdrawals, canonical peer replacements, checkpoint saves and DHT maintenance. Enable only the module you are investigating. `piece_retry` includes `corrupt=true` only for an actual hash mismatch; source loss can restart an isolated attempt without receiving corrupt bytes. `source` identifies a sole contributing connection when known. At trace level, `block_accepted` includes its connection, `peer_replaced` includes both connection IDs and their ranks, and `piece_withdrawn` records a received BEP 54 withdrawal. Continuous listener, UDP, entropy, reconciliation and port-mapping failures report the first failure rather than every retry; recovery is logged. Identical persisted torrent errors are not repeated until cleared or changed. Retry schedules and current errors remain available through the status API. Use `spill --json get ID` and `spill --json health` for current progress and network diagnostics rather than a logging heartbeat. Torrent events carry a torrent ID. Peer endpoints remain off by default; enable `peer_endpoints` to correlate connections with remote addresses during debugging. This associates addresses with torrent IDs in retained logs. It does not change peer addresses in live JSON diagnostics. Inbound rejections before torrent routing omit endpoints even when this setting is enabled; their reasons are logged under `spill::engine::session` at `trace`. Payloads and tracker URLs/credentials are not intentionally logged. Logs can still contain local paths and error text: review them before sharing. See [Troubleshooting](troubleshooting.md#where-are-the-logs) for systemd and macOS. ## Torrent defaults: `[defaults]` These are the per-torrent settings. They are copied into each new torrent and can be changed per torrent later with `spill set ID key=value` or the web interface. Rate-only changes take effect without restarting the torrent and are saved across daemon restarts. | Key | Default | Meaning | |---|---|---| | `download_limit` | `0` | Download rate limit for this torrent in payload bytes per second. `0` is unlimited. | | `upload_limit` | `0` | Upload rate limit, same units. | | `seed_ratio` | `0.0` | Pause after uploading this multiple of the torrent's data size (excluding virtual padding). `0` disables the rule. Must be finite and not negative. | | `seed_time` | `0` | Pause after this many seconds of active seeding. Paused time and downtime do not count. `0` disables the rule. | | `file_priorities` | `[]` | `[]` downloads every file, except that magnet `so` supplies the initial selection when the list is empty. Otherwise one of `"skip"`, `"normal"` or `"high"` per file, in `spill files` order (`spill set` also accepts sparse index objects like `{"1":"skip"}`). Only meaningful per torrent. | | `trackers` | `true` | Announce to the torrent's trackers. | | `dht` | `true` | Use the DHT over the address families supported by `listen`, and local service discovery when `allow_local_network = true`. Always off for private torrents. | | `pex` | `true` | Exchange peers with connected peers. Always off for private torrents. | | `web_seeds` | `true` | Download from the torrent's HTTP web seeds. | When either seed goal is reached, the torrent is paused. Resume it to keep seeding; the goal is checked again and will pause it again unless you change it. ## Examples A desktop user with the web interface: ```toml download_dir = "/home/me/Downloads" web_listen = "127.0.0.1:8080" active_downloads = 3 active_seeds = 10 [defaults] upload_limit = 2097152 # 2 MiB/s seed_ratio = 2.0 ``` A home server on a LAN with IPv6: ```toml state_dir = "/var/lib/spill" download_dir = "/srv/torrents" control_socket = "/run/spill/control.sock" listen = "[::]:6881" port_mapping = false # automatic mapping requires an IPv4 listener allow_local_network = true peers = 100 [defaults] dht = true # separate IPv4 and IPv6 routing tables ``` The annotated files `deploy/spill.toml` and `deploy/spill-user.toml` are annotated starting points for Linux; `deploy/spill-macos.toml` uses the macOS defaults. See the tables above for all supported keys. ## State directory compatibility Schema version **1** is the supported baseline for automatic startup migrations. Pending migrations run in a transaction before torrents are loaded; failure rolls back the changes and stops startup. Catalogs newer than the binary supports and nonempty unversioned catalogs are rejected. See [Upgrading](install.md#upgrading). Keep the state directory: it contains the authority to reopen partial downloads. If you choose a fresh `state_dir`, re-add torrents. Complete payload can be adopted from the original download directory; partial files are not adopted into a fresh catalog. --- # Web interface and HTTP API ## Enabling and configuring it The web interface is enabled by default on `127.0.0.1:8080`. To change the loopback address or disable it, pass `--web ADDR` / `--no-web` to `spill serve`, or set `web_listen` in your config file and restart the daemon: ```toml web_listen = "127.0.0.1:8080" # set "" to disable ``` Only loopback addresses (`127.0.0.1`, `::1`) are accepted. To use it from another machine, tunnel it, for example `ssh -N -L 127.0.0.1:8081:127.0.0.1:8080 server`, then open locally. The local port need not match the remote port. ## The page - **Torrent table:** Search across name, ID, SHA-1/SHA-256 hash, and output path; sort by any metric (including ratio, peers, and ETA); multi-select with checkboxes, `Shift+Click`, or `Ctrl/Cmd+Click`; filter by All torrents, Downloading (including `starting` and `metadata`), Checking (`checking`/`recovering`), Seeding, Paused, Queued, and Needs attention (errors, retrying, tracker/metadata warnings). Press `/` to focus search and `Escape` to clear search or close details. On narrower viewports, the static Discovery column hides automatically to keep transfer metrics visible without horizontal scrolling. - **Adding torrents:** Paste one or more magnet links or HTTP(S) torrent URLs (one per line), or choose / drag-and-drop one or more `.torrent` files (anywhere on the page or onto the upload box). When [`[remote_storage]`](configuration.md#remote-s3-storage-remote_storage) is configured, the Add dialog also offers a **Store pieces in remote S3 bucket** toggle (for magnets, URLs, and uploaded `.torrent` files). Discovery toggles and “Start immediately” apply atomically before startup; private metainfo always disables DHT and PEX. - **Actions:** Pause, resume, recheck (local torrents only; leaves torrent paused), reannounce, and remove. The remove confirmation defaults to keeping files; checking delete only removes local files created by spill (adopted seeds and remote S3 bucket objects are never deleted). - **Inspector tabs:** - **Overview:** Stable ID, full hashes, storage type (`Local disk` or `Remote S3 bucket`), and save path with copy buttons, metadata/layer state, lifetime accounting, active caps/seeding goals, S3 request/retry counters for remote torrents, and per-swarm completion delivery. - **Files:** Shows the local destination directory (with final file paths) or the S3 bucket/prefix/endpoint banner for remote torrents, plus a searchable, paginated file manifest with batch priority editing (`All normal`, `Skip all`, `Save changes`, `Discard`) so multiple edits restart the torrent once instead of per file. Virtual padding entries are marked and locked to `skip`. - **Peers:** Active peers with direction (`inbound`/`outbound`), transport (`tcp`/`utp`/`http`), encryption (`rc4`/`plaintext`), rates, totals, and hover diagnostics. - **Sources:** Editable discovery toggles (`trackers`, `dht`, `pex`, `web_seeds`) plus tracker, DHT, and web-seed tables. - **Remote storage badge & API boundary:** Remote torrents show an **S3** badge in the torrent table. `export_catalog` is rejected with HTTP `403` on `/api` and is available only over the local Unix control socket. - **Session limits & Torrent limits:** Edit daemon-wide caps (**Session limits**, reset on daemon restart) or per-torrent caps (**Torrent limits**, saved across restarts) in MiB/s without restarting transfers. Active non-zero session caps appear as a clickable badge in the overview bar. **Seeding rules** edits upload ratio (against data size) and active seeding hours. - **Daemon status & Logs:** Click the footer indicator for listeners, inbound public peer counts and recency, LSD, port mapping status/errors, session caps, and debug-log health. Click **Logs** for a 64 KiB tail of `debug.log` with follow (auto-pauses if you scroll up), refresh, and copy. If the daemon restarts and rotates its token, the UI pauses polling and prompts (or auto-reloads when no dialog is open). Downloaded totals include corrupt payload and re-downloads, not adopted files. Current-run counters reset when a torrent restarts; lifetime counters survive restarts. Hover over a table total for its exact byte count. See [Accounting in JSON](cli.md#accounting-in-json) for field definitions. ## Security model - The server only accepts loopback addresses (`127.0.0.0/8`, `[::1]`) or `localhost` as the `Host` hostname, including when SSH forwards a different local port. If `Origin` is present it must match the browser-facing HTTP host and port. Disallowed `Host`/`Origin` requests receive HTTP `403`. - Every API request must carry the `X-Spill-Token` header. The page embeds a random token generated when the daemon starts; missing or stale tokens receive HTTP `401` with a JSON error body. - Cross-origin requests are rejected. This protects against other websites in your browser. It is **not** authentication against other users on the same machine: anyone who can reach the loopback port can load the page and its token. Don't enable the web interface on shared machines you don't trust. ## HTTP API All `/api*` endpoints require `POST` (`GET` returns `405 Method Not Allowed`), the `X-Spill-Token` header, and return `Cache-Control: no-store`. For local scripts on the same machine, prefer `spill --json` or the [Unix control socket](cli.md#control-protocol), which need no token extraction. Every JSON response uses the control envelope `{"code":N,"data":…,"error":…}`. Authentication/origin failures return HTTP `401`/`403` and malformed request bodies return HTTP `400`; dispatched control operations return HTTP `200`, so callers must check `"code" == 0` in the JSON body (nonzero codes match CLI exit codes: `1` operation failed, `2` invalid input, `3` not found, `4` unavailable). When calling the HTTP API from a script, read the current token from `` on `GET /` (it rotates on every daemon restart): ```sh TOKEN="$(curl -s http://127.0.0.1:8080/ | sed -n 's/.*name="spill-token" content="\([^"]*\)".*/\1/p')" ``` ### `POST /api` A JSON body with an `op` field, limited to 2 MiB: ```sh curl -s http://127.0.0.1:8080/api \ -H "X-Spill-Token: $TOKEN" -H 'Content-Type: application/json' \ -d '{"op":"set","id":"3f2a","values":{"upload_limit":1048576}}' ``` Operations: `add` (magnets or torrent URLs), `get`, `set`, `list`, `status`, `files`, `pause`, `resume`, `recheck`, `reannounce`, `remove`, `health`, `logs`, `set_bandwidth`, `shutdown`. `list` and `status` accept optional `"summary": true` to omit per-peer, tracker, DHT, web-seed, and storage arrays (the web UI polls `status` with `"summary": true` and fetches `get` for the focused torrent). For `set_bandwidth`, send at least one of `download_limit` or `upload_limit`, for example `{"op":"set_bandwidth","upload_limit":1048576}`. Rates are unsigned integers in payload bytes per second (`0` means unlimited). Omitted caps stay unchanged. The response data contains both effective caps. The change lasts until the daemon restarts and does not restart torrents. The same operation is available on the Unix control socket. For a URL add, send `{"op":"add","url":"https://example.org/file.torrent"}` with optional `output_dir`, `remote` (`true` to store pieces in configured `[remote_storage]`, incompatible with `output_dir`), `paused`, and `settings` fields. For example, `{"op":"add","url":"https://example.org/file.torrent","paused":true,"settings":{"web_seeds":false}}` fetches metainfo but does not start discovery or payload transfer. Settings merge with daemon defaults and are validated before saving. See the [control protocol](cli.md#control-protocol). The `get` response includes `transfer.peers[].transport`: `"tcp"`, `"utp"` or `"http"` (web seed), just like the Unix control API. The same diagnostics include per-peer and owner-total `utp_retransmits`, and `pending_contacts`; see [Command line](cli.md#commands) for their meaning. The same stable-ID and full-hash alias lookup applies over HTTP, including 64-digit v2 hashes. See [Identity and discovery in JSON](cli.md#identity-and-discovery-in-json) for format, metadata readiness, and per-swarm completion/tracker/DHT fields. ### `POST /api/logs` Returns a bounded tail of the configured `/debug.log`. There are no request fields; clients cannot choose a file path. Uses the control response envelope, with `data` containing `enabled`, `text` and `truncated`: ```json {"code":0,"data":{"enabled":true,"text":"…","truncated":false},"error":null} ``` At most 64 KiB are read per request. If older bytes are omitted, `truncated` is true and the first cut line is discarded. Invalid UTF-8 is replaced for text display. When file logging is disabled (or `debug.log` does not exist yet), `text` is empty. Read failures return a nonzero code and an error message, not an empty success. Responses use `Cache-Control: no-store`. Like other API access, this is not authentication against local users; logs may contain sensitive operational details. ### `POST /api/upload` Upload a `.torrent` file as the raw request body (at most 16 MiB). Optional query parameters are `output_dir` (URL-encoded path), `remote=true` (store pieces in configured `[remote_storage]`, incompatible with `output_dir`), `paused=true`, and `settings` (a URL-encoded JSON object of initial overrides): ```sh curl -s "http://127.0.0.1:8080/api/upload?output_dir=%2Fsrv%2Ftorrents" \ -H "X-Spill-Token: $TOKEN" -H 'Content-Type: application/x-bittorrent' \ --data-binary @file.torrent ``` --- # Torrents ## States `spill list` and the web page show one state per torrent: | State | Meaning | |---|---| | `queued` | Waiting for a free download or seed slot. | | `starting` | Admitted; preparing to run. | | `metadata` | A magnet link is fetching the torrent's metadata from peers. | | `recovering` | Opening files and checking which pieces are already valid. | | `checking` | Running an explicit `recheck`. | | `downloading` | Transferring data. | | `seeding` | Complete (for the selected files) and uploading. | | `paused` | Stopped by you, a seed goal or a permanent input error. Stays stopped across restarts. | | `retrying` | Failed; spill retries automatically. `get` shows the error and when the next attempt happens. | ## Queueing `active_downloads` and `active_seeds` limit how many torrents run at once, as two separate pools. A torrent counts as a seed once it is complete. Torrents that don't fit wait as `queued` and start in the order they were added when a slot frees up. A torrent that is already running keeps its slot: resuming or adding another torrent never stops one that is transferring. ## Adding torrents To make a `.torrent` from your own files first, use [`spill create`](cli.md#creating-torrents). Creation works without a daemon and does not automatically add the torrent. Add a local `.torrent` file, an HTTP(S) torrent URL, or a magnet link. Metainfo and magnets may be v1, v2-only or hybrid; see [v2 and hybrid torrents](v2.md). Private torrents require a `.torrent` file. The daemon fetches torrent URLs and checks the file before adding it. A magnet link is added right away and resolves its metadata from peers found via its `tr=` trackers, the DHT and, when enabled, local service discovery. Incoming peers can supply metadata too. Tracker announces have a 30-second completion deadline and skip failed trackers during their per-tracker retry backoff. Magnet trackers are kept for the download, one tier per valid `tr=` in link order, keeping only an exact duplicate URL's first occurrence. See [Trackers](networking.md#trackers) for ordering, timing and remaining differences from libtorrent. Live metadata connections continue into payload transfer with their negotiated extensions and piece availability; peers need not advertise a listening port or reconnect after metadata validates. Magnet parameter names are case-insensitive and numeric suffixes such as `tr.1` are ignored. Invalid tracker hints and malformed percent escapes in `tr`/`ws` values are skipped; input budgets and destination restrictions still apply. The last `dn` display name wins. `so` selects files after metadata resolution (see [File selection](#file-selection)). `ws`, `x.pe` and `xl` do not supply web seeds, explicit peers or size hints. v1/v2 topics can be combined, but conflicting hashes of the same version are rejected. Use `spill add SOURCE --paused` to add without starting discovery or payload transfer. Set initial overrides atomically with repeated `--set KEY=JSON` options, for example `--set dht=false --set pex=false`. Omitted settings inherit daemon defaults. HTTP(S) torrent URLs still fetch metainfo when added paused. Torrents are saved under the output directory: a single-file torrent as one file, a multi-file torrent in a directory named after the torrent. Names are made safe for the filesystem: invalid UTF-8 sequences, `:` and `\` become `_`, components such as `..` are rejected, and replaced or over-long names carry a short hash to distinguish them. Remaining path collisions are rejected. ### Existing files - If **all** of a torrent's files already exist at the destination, spill verifies them and seeds them without downloading. These adopted files are treated as read-only: spill never writes to or deletes them. Keep them unchanged while seeding. When reopening a file for upload, spill checks its device, inode, size, and modification time. If those changed, the torrent stops serving and needs rechecking. Creating a hardlink on its own does not invalidate the seed. - If only **some** of them exist, or a directory sits where a file should go, the torrent enters the catalog and pauses during startup with `last_error` set to `file already exists; choose another output directory`. spill never overwrites files it didn't create. Move the conflicting files away and `resume`, or run `spill remove ID` before re-adding with another `--output`. ### `.part` files While downloading, each non-empty file is named `NAME.part`. When every piece of a file is verified, it is renamed to `NAME`. A file you've set to `skip` stays `.part` (and sparse) unless pieces shared with a selected file fill it. ## File selection Magnet links support BEP 53 `so=0,2,4-8`: select only those zero-based file indices, with inclusive ranges. Indices follow `spill files` order, including padding entries, which remain skipped. Repeated `so` parameters are unioned. Empty, malformed, descending or overflowing selections are input errors. Indices beyond the manifest are ignored, and ranges are clipped to the file list. If no data files remain selected, the target is empty; metadata is still saved so files can be selected later. Selection survives restart. Adding a magnet with `so` for an existing torrent enables referenced skipped files at normal priority without deselecting others or lowering high priorities. It returns the existing ID and preserves the destination, pause state and other settings; other add options do not replace them. A duplicate that adds no files leaves the running torrent and its connections untouched. Before metadata arrives, new indices extend the pending selection. An existing all-files selection stays all files. Without `so`, adding an existing torrent remains an error. All supplied hash topics must already identify the same entry. `spill files ID` lists every file with its priority (and marks virtual BEP 47 padding entries). Set priorities with a full array `set ID 'file_priorities=[...]'` or a sparse index map `set ID 'file_priorities={"1":"skip","2":"high"}'`, using `skip`, `normal`, or `high`: - `high` files are fetched before `normal` ones. - `skip` files are not requested. Pieces that span a selected and a skipped file are still downloaded completely, so part of a skipped file may be written. - A torrent is complete, and starts seeding, when every selected file is. - Padding files (BEP 47) are never written to disk and must be `skip`. Finishing only a subset makes spill a partial seed (BEP 21). It continues uploading and tells peers it is upload-only; tracker announces use `paused` without claiming the whole torrent is complete. This is different from pausing the torrent. See [Networking](networking.md#trackers). ## Seeding goals A torrent pauses itself when it reaches `seed_ratio` (uploaded bytes divided by the torrent's data size, excluding virtual padding) or `seed_time` (seconds spent seeding, not counting pauses or downtime). Seeding duration is measured by the engine at lifecycle transitions, not inferred from supervisor sampling. Uploaded bytes and seeding time are saved and survive restarts. ## Accounting Each torrent keeps lifetime downloaded/uploaded payload totals, seeding time, and added/completed/last-transfer timestamps. Adopted files contribute verified progress but no downloaded traffic. Corrupt payload and re-downloads count as traffic, so downloaded bytes can exceed the torrent's size. Persistent `hash_failed_bytes` and `hash_failed_pieces` count failed downloaded-piece hash checks (including repeated failures), not corruption found during startup or recheck. They indicate wasted traffic, but cannot by themselves distinguish bad sources from local storage problems. Seeding time includes idle time while ready and complete, not just time spent sending bytes. Accounting is saved about every minute, on recorded completion-state changes, and when a run stops. An abrupt crash can lose accounting since the last checkpoint; power loss can also lose recent SQLite commits. There is no stored time series. Removing a torrent deletes its accounting. Completion and selected-file progress remain available while paused or queued. See [Command line](cli.md#accounting-in-json) for field definitions. Seed ratios continue to use lifetime uploaded bytes divided by the full torrent size, not by downloaded bytes or selected-file size. ## Recheck `spill recheck ID` hashes every piece on disk, records the result, then leaves the torrent paused. Resume it to continue: missing or corrupt pieces are downloaded again, and a complete torrent seeds. Recheck after moving files, editing them, or an unclean power loss during a download. A magnet with unresolved metadata may use its enabled trackers or DHT to obtain metadata first. The subsequent scan never downloads missing payload or serves pieces. Library offline rechecks require supplied metainfo. ## Restarts, crashes and durability spill saves each torrent's verified pieces together with a fingerprint (size, modification time and identity) of every file: - every two minutes while a torrent runs, - when it completes, - when it stops. On the next start, files whose fingerprint still matches are trusted; pieces in files that changed are hashed again. A crash therefore costs at most the unsaved progress plus rehashing the files that were being written. Like other clients, spill does not sync data to disk on every write. It syncs a torrent's files once, when the download completes, before marking it complete. After a power loss during a download, data written in the last moments may be lost without changing the files' fingerprint; a `recheck` finds and repairs it. ## Failures and retries If a torrent fails (disk full, permission denied, a file removed underneath it), it shows the error and enters `retrying`. spill retries after 10 seconds, doubling the delay each time up to 30 minutes. Pausing and resuming clears the delay. Problems with a single peer, tracker or web seed never fail a torrent; that source is dropped or retried on its own. Permanent input and destination-conflict errors pause the torrent instead of retrying, preserving `last_error` with `retry_at` set to zero across restarts. This includes private magnets, duplicate hashes learned during metadata resolution, and `file already exists` conflicts at the output path. Use a `.torrent` file for a private torrent, remove a duplicate rather than retrying it, or clear the conflict (or remove and re-add with another `--output`). ## Removing torrents - `remove ID` deletes the torrent from spill and keeps all files. - `remove ID --delete-payload` also deletes the files spill created for it, then any directories that became empty. Files spill did not create (adopted seeds, anything else in those directories) are left alone, and non-empty directories are kept. --- # Remote S3 storage spill can store verified torrent pieces directly as individual objects in an S3-compatible bucket instead of local payload files, using its built-in HTTPS (`reqwest`/`rustls`) and AWS SigV4 client. Remote storage is designed for downloading and seeding large payloads without holding them on local disk. Objects store raw piece bytes—not reconstructed torrent files—so to materialize the actual files onto a local filesystem, use [`spill extract`](#extracting-to-local-files). ## How it works - **No local disk staging:** in-flight blocks are assembled in memory under a shared `assembly_bytes` budget, verified against the torrent's piece hashes, and uploaded with an `x-amz-checksum-sha256` integrity header. - **Guarded reads:** each committed piece is recorded in `catalog.sqlite` together with an immutable object guard (either a strong ETag or an S3 version ID). Every upload read verifies that guard (`If-Match` or `versionId`) and the returned `Content-Range`, so silently replaced objects are never served to peers. - **v1, v2, and hybrid support:** remote storage supports all three formats, including serving BEP 52 Merkle hash proofs from stored pieces. ## Configuration Add a `[remote_storage]` table to your TOML config (see [Configuration](configuration.md#remote-s3-storage-remote_storage) for every key) and supply credentials via environment variables: - `AWS_ACCESS_KEY_ID` (required) - `AWS_SECRET_ACCESS_KEY` (required) - `AWS_SESSION_TOKEN` (optional) `endpoint` must be an HTTPS origin without a path or query string, and `prefix` must be dedicated to spill. ### Example: Cloudflare R2 ```toml [remote_storage] endpoint = "https://.r2.cloudflarestorage.com" region = "auto" bucket = "spill-pieces" prefix = "host-a" guard = "StableEtag" path_style = true ``` For a systemd user service, store credentials in a mode `0600` file (for example `~/.config/spill/r2.env` containing `AWS_ACCESS_KEY_ID=…` and `AWS_SECRET_ACCESS_KEY=…`) and load it from a drop-in unit: ```ini # ~/.config/systemd/user/spill.service.d/40-r2-storage.conf [Service] EnvironmentFile=%h/.config/spill/r2.env ``` ### Example: AWS S3 (versioned bucket) ```toml [remote_storage] endpoint = "https://s3.us-east-1.amazonaws.com" region = "us-east-1" bucket = "my-spill-pieces" prefix = "host-a" guard = "Version" path_style = false ``` ### Choosing `guard` - **`"StableEtag"`:** use only on providers where identical single-part PUTs return the same strong ETag and objects under `prefix` are not overwritten externally (for example Cloudflare R2). - **`"Version"`:** use on buckets with object versioning enabled where every object version referenced by a restorable catalog snapshot is retained. ## Adding and inspecting remote torrents - **CLI:** pass `--remote` to `spill add` (cannot be combined with `--output`): ```sh spill add archive.torrent --remote spill add 'magnet:?xt=urn:btih:…' --remote ``` - **Web UI:** enable **Store pieces in remote S3 bucket** in the Add dialog. Remote torrents display an **S3** badge in the table, the bucket/prefix banner in the **Files** tab, and live S3 request/retry counters in **Overview**. - **Telemetry:** inspect per-torrent S3 counters with: ```sh spill --json get ID | jq '.transfer.storage.s3' ``` See [Runtime diagnostics in JSON](cli.md#runtime-diagnostics-in-json) for the `put`, `get`, and `proof_get` fields. ## Caching, memory, and egress tradeoffs - **Read cache and coalescing:** all remote torrents on a destination share a 64 MiB LRU read cache of 512 KiB chunks with in-flight singleflight coalescing. Sequential and multi-peer seeding serves up to 32 blocks per S3 GET instead of one GET per 16 KiB block. - **Read amplification:** an isolated cold 16 KiB block read fetches up to 512 KiB from the bucket (up to 32× amplification if neighboring blocks are never requested). This cuts request counts on zero-egress stores such as R2, but increases transferred bytes on providers that bill per-GB egress. - **Concurrency:** remote torrents share 64 concurrent S3 GET slots and 64 concurrent S3 PUT slots per configured destination. Each torrent caps its own in-flight GETs at `read_window` (`1`–`32`, default `4`). - **Piece size limit:** each active piece reserves twice its logical length in `assembly_bytes` through PUT acknowledgement, so the largest supported remote piece is `assembly_bytes / 2`. By default `assembly_bytes` is 5% of host/cgroup memory (capped at 512 MiB, or 96 MiB if memory cannot be detected). Increase `assembly_bytes` if you need to add remote torrents with larger piece sizes. ## Extracting to local files To download and reconstruct a complete remote torrent's files onto a local filesystem directly from the bucket (without running a second BitTorrent client): ```sh # Against the default catalog without a config file (reads endpoint/bucket/prefix/guard from SQLite): spill extract ID --output ./downloads --region auto --path-style # Or using your existing daemon config (reuses region, path_style, ca_bundle, and state_dir): spill extract ID --config ~/.config/spill/spill.toml --output ./downloads # Or on another machine from an exported catalog snapshot (no daemon or config needed): spill extract ID --catalog snapshot.sqlite --output ./downloads --region auto --path-style ``` `spill extract` accepts the torrent's full ID, hash alias, or unambiguous prefix, supplies S3 credentials from the same `AWS_*` environment variables, validates the destination binding and piece guards (`If-Match` / `versionId`), verifies every piece's cryptographic hash, and writes files using spill's sanitized local paths without overwriting existing files. When `--config` is omitted, `--region` defaults to `AWS_REGION` / `AWS_DEFAULT_REGION` (pass `--path-style` for path-style providers such as R2, and `--ca-bundle` if using a custom CA). On error or `Ctrl-C`, partial files created by the run are removed. Pass `--json` for structured output (`id`, `name`, `output_dir`, `pieces`, `total_bytes`). ## Backup, restore, and limits - **Catalog backups are required for recovery:** bucket objects alone do not store the verified piece bitmap or pinned object guards. Back up the catalog regularly with [`spill export-catalog`](cli.md#catalog-backup-and-restore) and restore into an empty `state_dir` with `spill restore-catalog` using the same `endpoint`, `bucket`, `prefix`, and `guard` mode. Restoring and starting a complete remote torrent requires zero S3 requests until peers request blocks. - **No `recheck` or remote deletion:** `spill recheck ID` and `spill remove ID --delete-payload` are rejected for remote torrents. Running `spill remove ID` removes the torrent from the catalog and leaves all bucket objects untouched; reclaim storage directly in your bucket when objects are no longer needed. - **Error handling:** transient errors (`429`, `5xx`, or transport resets) retry up to 3 attempts with backoff (honoring `Retry-After`). Permanent errors (`401`/`403`, `404`, `412`, or destination binding mismatches) pause the torrent with `last_error` instead of retrying indefinitely. To use S3 piece storage directly from Rust without the daemon, see [Remote S3 destination](library.md#remote-s3-destination). --- # v2 and hybrid torrents spill downloads and seeds BitTorrent v1, v2-only ([BEP 52](https://www.bittorrent.org/beps/bep_0052.html)) and hybrid torrents through the same daemon commands and library APIs. A hybrid carries both v1 and v2 metadata for the same files; spill treats it as one torrent with one destination and one set of transfer budgets. ## Creating torrents Use `spill create --format v2` or `spill create --format hybrid` to select the format; v1 is the default. See [Creating torrents](cli.md#creating-torrents) for ordering, padding and destination rules. ## Hashes and IDs A v1 torrent has a 40-digit SHA-1 hash and a v2-only torrent a 64-digit SHA-256 hash. A hybrid has both. Its stable ID is the SHA-1 hash, but either full hash addresses the same torrent; see [IDs](cli.md#ids). Adding a torrent or magnet with a hash that is already known is a duplicate, even if the other hash or the destination differs. A magnet with `so` can instead extend an existing entry's file selection when all its hash topics already identify that entry; see [File selection](torrents.md#file-selection). Trackers, the DHT and peer handshakes use a 20-byte key: the SHA-1 hash for v1 and the first 20 bytes of the SHA-256 hash for v2. That shortened key only locates peers; spill always checks metadata against the full hash. ## Where files are placed A v2-only torrent whose file tree has exactly one top-level entry, and that entry is a file, is saved as that file with no enclosing directory. Every other v2-only torrent is saved under a directory named after the torrent's `name`, keeping all directories from the file tree. This matches libtorrent, except that spill does not drop directories below the top level. When files are saved under `name`, a `name` that is not a valid path component makes the torrent invalid; libtorrent substitutes the hash instead. Hybrids are saved like their v1 layout, which spill requires to match the v2 file tree. Files that share a v2 `pieces root` must have the same length. ## Verification V2 pieces are checked against SHA-256 Merkle hashes. Each v2 piece belongs to one file, so the gap after a file is zero padding that is not part of any file. Hybrids with authenticated layers check both SHA-1 and SHA-256. If only one passes, the metadata contradicts itself and the torrent fails permanently. If both fail, the data is fetched again, as for v1. A hybrid missing required piece layers is **layers pending**. It checks pieces with SHA-1 and announces only in the v1 swarm, but accepts peers using either key. After every piece is verified, spill reads the payload once more, rebuilds the SHA-256 layers and checks every file root, including small files. This background read shares the recheck limit, keeps uploads running, and is canceled on stop. Completion is reported after the payload is synced and a pending-mode checkpoint is saved, without waiting for the rebuild. Contradictory roots fail permanently. Matching layers are saved with the metainfo, then a full-mode checkpoint is saved. The next start uses both swarms for public torrents; private hybrids still announce only v1. The current execution keeps SHA-1 verification and rejects hash requests. An interrupted rebuild starts again on the next run. If selected files complete while other pieces remain unverified, layers stay pending. spill refuses hybrids whose v1 and v2 file lists disagree on names, order, sizes or padding. ## Magnets Magnets accept incoming TCP and uTP peers during metadata resolution, as well as dialing discovered peers. Listening addresses learned from metadata peers can be reused for payload transfer after metadata validates. Magnets accept a `btih` topic, a SHA-256 `btmh` topic (`urn:btmh:1220` followed by 64 hex digits), or both. Other `btmh` hash types are refused as unsupported. Resolving a magnet first fetches the info dictionary and checks it against every hash in the magnet. A hybrid can start payload transfer immediately, using its SHA-1 hashes while required layers are pending. V2-only torrents first fetch piece hashes from peers and authenticate them against the file roots. `info_validated`, `hash_bytes`, `hash_total_bytes` and `layers_pending` in [status JSON](cli.md#identity-and-discovery-in-json) distinguish these states. Peers that send rejected, invalid or no hashes cannot stop another peer from supplying a v2-only torrent's layers. A hybrid can be resolved from either hash. Its stable ID stays the hash the magnet supplied, and the other hash is learned when the info dictionary validates. Both hashes remain usable for aliases and duplicate detection, even while the torrent uses only the v1 swarm. If the learned hash already belongs to another torrent, resolution fails instead of merging the two downloads. A btih or dual-topic hybrid magnet can resolve through v1-only peers. A btmh-only magnet still needs to locate its info dictionary using the supplied v2 key. Stopping during resolution discards partial metadata and creates no files. V2-only magnets save fetched piece hashes with the metainfo, so they restart and seed without fetching them again. Hybrids save rebuilt layers in the background after full payload verification. Private torrents must be added from a `.torrent` file. ## Swarms and discovery A v2-only torrent uses its v2 key everywhere. A public hybrid with authenticated layers joins both swarms; a layers-pending hybrid has no upgrade offer or v2 announces. Peers using the v2 key are accepted, and their hash requests are rejected until a restart after the rebuild. Each active swarm has its own tracker announces, intervals, completion delivery and DHT lookups, while payload progress and transfer limits are shared. Both swarms' trackers receive the same torrent-wide upload and download counters, so adding up their tracker statistics double-counts traffic. Private hybrids announce only their v1 identity and persist completion delivery for that identity, avoiding duplicate tracker credit. They do not discover peers through the separate v2 tracker swarm; pure-v2 private torrents still announce v2. Peers found through a tracker or the DHT are dialed with the key of the swarm that returned them. Hybrid peers from PEX are dialed with the v1 key, since PEX does not say which keys a peer supports. An upgrade is offered only when layers are authenticated. Local service discovery (BEP 14) announces a hybrid's v1 hash. For v2-only torrents it uses the first 20 bytes of SHA-256, matching [libtorrent's v2 LSD wire key](https://github.com/arvidn/libtorrent/blob/v2.1.2/include/libtorrent/info_hash.hpp#L108-L112). Both are encoded as 40 hex digits. Received announcements can match either known hybrid key; the announced key is used when dialing. A btmh-only magnet announces its v2 key before metadata is known. Private torrents disable the DHT, PEX and LSD in every format. ## Peer protocol When spill has authenticated hybrid layers and dials with the v1 key it offers to switch to v2, and accepts a reply on either key. Incoming peers may use either key, or offer the switch themselves. On a v2 connection spill follows BEP 52 strictly: - spill answers every block request with a block or a reject, including after a choke. Peers must do the same: a request spill cancelled still needs an answer within the request timeout, or the peer is disconnected. - A block that was never requested disconnects the peer. - A duplicate outstanding block request disconnects the peer. - Hash responses spill did not ask for disconnect the peer. spill answers hash requests for verified data: - Piece-layer hashes need no disk reads and are answered even while the peer is choked. - Hashes below the piece layer require an upload slot, cover at most one piece, and count the bytes read against the upload limit. - Leaf hashes are checked against the piece-layer hash before they are sent. If the file changed on disk after it was verified, spill sends a reject instead. For hybrids, peers in either mode may request the zero padding after a file, because the v1 hashes cover it. Peers of a v2-only torrent cannot request past the end of a file's data; spill rejects those requests. Malformed requests disconnect the peer. Rejected file-tail requests and unsupported hash requests use up the peer's ignored-traffic allowance, and repeating them disconnects the peer. ## Web seeds HTTP(S) web seeds work for all three formats. spill fetches only real file bytes and fills padding with zeros locally. A mirror serving bad data is dropped and another source completes the piece. ## Compatibility Hybrid metainfo may omit piece layers, and hybrid magnets need no v2 hash exchange before downloading. spill rebuilds pending layers from its own verified payload rather than requiring v2 peers. The extra background read costs roughly a recheck. V2 peers can use the rebuilt layers after the torrent restarts. Transmission 4.1.3 reads hybrids as v1 but refuses metainfo with repeated paths. spill and libtorrent name padding `.pad/`, so a hybrid with two equal-sized gaps between files does not load in Transmission. Single-file hybrids have no padding. A v2-only `.torrent` file must contain the `piece layers` entry of every file larger than one piece. libtorrent can fetch missing layers from peers; spill requires them in the file. V2-only magnets fetch and authenticate layers before creating payload files. spill accepts single-hash requests because libtorrent 2.1.2.0 sends them, although BEP 52 requires at least two; spill itself always asks for at least two. See [Scope](index.md#scope) for what has been checked against other clients and what has not, including v2 over uTP. --- # Networking ## One port spill uses a single port number, `listen` (default `6881`), for peer and tracker traffic and the DHT: - **TCP**: incoming peer connections. - **UDP**: uTP peer connections, the DHT and replies from UDP trackers, on the same socket. Both must be free when the daemon starts, even with the DHT disabled. Allow inbound TCP and UDP through the host firewall. Without inbound reachability, spill still downloads and uploads over connections it makes itself. Local service discovery additionally shares multicast UDP port `6771` with other clients when `allow_local_network = true`. Allow that port on the local network if using LSD; it does not need router port forwarding. ## Peer transports spill accepts TCP and uTP (BEP 29) peer connections. Outbound connections try uTP first, then TCP if uTP does not answer within three seconds. A remote uTP timeout or reset is remembered for that cached contact; subsequent ordinary dials use TCP directly. TCP and uTP are not raced. uTP uses LEDBAT delay-based congestion control, intended to yield bandwidth to other traffic. Selective acknowledgements and retransmission recover reordered or lost datagrams. Vectored peer writes are packed together into datagrams. Zero-window probes use exponential backoff, capped at 60 seconds between probes. Both transports use the same peer and pending-handshake limits. Peer diagnostics identify each connection's `transport` as `"tcp"`, `"utp"` or `"http"` (web seed). Set daemon config `utp = false` to dial only TCP and reject incoming uTP. UDP is still required for trackers and the DHT. Forward and allow both TCP and UDP on the listen port to accept both peer transports. IPv6 uTP requires an IPv6 or dual-stack listener; an IPv4-only listener cannot send IPv6 uTP. A dual-stack (`[::]`) listener supports both IPv4 and IPv6 uTP. A full local uTP connection budget causes that dial to use TCP, without marking the remote as uTP-incompatible. Only a uTP connect timeout or reset is remembered as a remote failure. During clean daemon shutdown, uTP gets up to one second to acknowledge FINs before remaining connections are reset. ## UDP holepunching spill supports BEP 55 (`ut_holepunch`) when uTP and PEX are enabled and public metainfo is known. It is disabled for private torrents and during magnet metadata resolution. There is no separate setting. After an ordinary connection attempt fails with a uTP timeout or reset, spill can ask a connected PEX peer to introduce it to a peer advertising holepunch support. The introducer asks both sides to send uTP packets directly to each other. A completed seed can answer these requests too. The introducer never relays payload; holepunching uses the session's existing UDP socket. This does not replace port mapping or guarantee connectivity through every NAT or firewall. Observed UDP mappings are preferred to advertised listening ports, but a NAT may choose a different mapping for each destination. Punches share ordinary dial limits and can be delayed past the other client's connection window. A request received while a dial to the same endpoint is already in flight is ignored rather than cancelled. An ordinary remote uTP failure gives that cached contact one automatic rendezvous opportunity. Later ordinary dials use TCP while that failure cache entry survives, even if the punch succeeded and the peer later disconnected. Idle cache entries can be evicted, and an incoming introduction can force a new uTP attempt. Punch attempts never fall back to TCP or retry with the other encryption setting; an encryption mismatch loses that attempt. Diagnostics label surviving outbound punch connections `source: "holepunch"`. A simultaneous inbound connection can win duplicate-peer resolution and retain its inbound source instead. See [Limits](limits.md#holepunch-coordination) for coordination bounds. ## Automatic port mapping With `port_mapping = true` (the default), spill asks the IPv4 default gateway for TCP and UDP mappings, first using NAT-PMP, then UPnP IGD. PCP is not yet supported. The system-service example disables mapping; user and macOS examples leave it enabled. An IPv6 listener does not use automatic mapping. An IP-valued `port_mapping_gateway` overrides NAT-PMP gateway discovery. An HTTP description URL instead skips NAT-PMP and SSDP, using that UPnP IGD directly. spill requests the listen port as the external port for both protocols. If the gateway grants a different number, trackers, new extension handshakes and DHT announces advertise that external port. A port change does not trigger extra announces: the next regular announce carries it. Different TCP and UDP external ports are rejected, since spill advertises one port. When disabled or after a failed mapping attempt, the advertised port remains the listen port. NAT-PMP requests a two-hour lease and renews at half the granted lifetime. UPnP also requests a two-hour lease and renews halfway through it. If the router returns error 725 (only permanent leases supported), spill retries with lease 0 and reasserts the mapping hourly. Failed attempts retry after 60 seconds, doubling up to 30 minutes. Clean shutdown tries to remove mappings with a two-second timeout. Failures are logged and exposed in `spill health`; they never fail a torrent or stop the daemon. Gateway requests and SSDP multicast deliberately bypass `allow_local_network`: these destinations are our own gateway, not endpoints supplied by torrents. See [Troubleshooting](troubleshooting.md#nobody-can-connect-to-me) if mapping fails. ## Finding peers | Source | What it is | Setting | |---|---|---| | Trackers | HTTP, HTTPS and UDP trackers listed in the torrent or magnet. | `trackers` | | DHT | The distributed hash table (BEP 5/32), over IPv4 and IPv6. | `dht` | | PEX | Peer lists exchanged with connected peers (BEP 11). | `pex` | | LSD | Local service discovery on the LAN (BEP 14). | `allow_local_network` and per-torrent `dht` | | Web seeds | Plain HTTP(S) servers holding the files (BEP 19). | `web_seeds` | Trackers, DHT, PEX and web seeds are on by default, configurable per torrent. LSD is off unless LAN access is enabled and follows the torrent's `dht` setting. Private torrents always have DHT, PEX and LSD off. PEX additions include aligned capability flags indicating uTP connections and peers that advertise BEP 55 holepunch support. IPv4-mapped IPv6 peer endpoints are treated as IPv4 for contact deduplication. Web seeds must support HTTP byte-range requests. Downloaded pieces undergo the same verification as peer transfers. Web seeds follow the same HTTP(S) redirect and address restrictions as trackers: cross-host redirects and HTTPS upgrades are allowed; HTTPS-to-HTTP downgrades are refused. HTTP connections use HTTP/1 without system proxies. HTTPS verifies certificates against bundled Mozilla roots, not the OS trust store; this also applies to [adding a torrent by URL](torrents.md). ### Trackers - UDP announces send the tracker URL's path and query using BEP 41 URLData, preserving escaped bytes and repeated query parameters. This supports trackers that use URL-specific routing or passkeys; the tracker must support URLData. - Trackers are grouped in tiers (BEP 12). Each valid magnet `tr=` gets its own tier in link order; duplicate URLs keep only their first occurrence, and the retained tracker list has no empty duplicate tiers. `.torrent` tiers retain their listed order without shuffling. For public torrents, UDP is preferred over an earlier HTTP(S) tracker on the same hostname, even across tiers. - Public torrents use sequential fallback: try the next in the tier, then the next tier, on failure. Failed trackers move to the back of their tier. When a failed tracker's backoff expires, its retry can run alongside the next eligible working tracker, so the retry's timeout does not delay that tracker. Each tracker has at most one exchange in flight. Selection starts from the beginning again; a working tracker that is not due blocks lower-priority trackers. This is not an announce-to-all-tiers or all-trackers policy. - Private torrents keep one selected URL, switching only after failure and never retrying preferred URLs alongside a working fallback. Switching disconnects all peers, cancels pending dials and discards old contacts before another URL is used. Each switch starts upload, download and corrupt counters at zero, including a return to an earlier URL; `left` still covers the whole torrent. Different URLs are distinct trackers even on one hostname. See [Private trackers](private-trackers.md). - Failed trackers wait before retrying and are skipped while waiting. Consecutive failures use `min(3600, 5 + failures² × 12.5)` seconds, rounded down: 17, 55, 117, 205… seconds. A tracker error reply's retry interval can extend that wait. Success resets consecutive failures; diagnostic failure totals remain cumulative. HTTP 410 disables that tracker for the current announce lifecycle. - Successful announce intervals have a 300-second minimum and no upper clamp. HTTP replies default to a 1800-second interval and 30-second `min interval`; UDP uses a 60-second minimum interval. Explicit HTTP minimum intervals are respected, including zero. `spill reannounce` can shorten the regular interval, but not a failure backoff or minimum interval. A pending completion event may bypass the successful tracker's minimum interval. - Announces have a 30-second completion deadline; UDP connect and announce exchanges each have a 10-second inactivity deadline, without in-exchange retransmissions. UDP trackers share the session's UDP socket. A silent tracker only delays its own torrent. Stopped announces are best-effort within five seconds. Peer transfers stop before final counters are sampled, and stopping during private tracker failover interrupts the switch's tracker cleanup. - Partial seeds (BEP 21) have finished their selected files but not the whole torrent. Every active announce uses `event=paused` (UDP event 4), including the first announce and tracker fallback. `left` still counts all unverified torrent bytes. This event means upload-only participation, not a paused or stopped torrent; shutdown still sends `stopped`, and partial completion never sends `completed`. State changes request a new announce while respecting tracker minimum intervals and failure backoff. - HTTP requests use compact peers, `no_peer_id=1`, `supportcrypto=1`, and `corrupt` (hash-failed payload bytes); `downloaded` excludes hash-failed bytes and is floored at zero. Tracker IDs are returned on later requests. Peer requests use `numwant=200`, or zero for stopped announces. - HTTP trackers resolve DNS on every announce and ignore system proxies. Announces follow up to five HTTP(S) redirects, subject to the same local-network restrictions as the original URL. HTTPS-to-HTTP redirects are refused. Redirects use the supplied `Location` without copying the original query or sending a `Referer` header; stored tracker URLs are unchanged. - Tracker failures appear as `tracker_error` in `get`, `list` and the web UI, clearing after recovery or successful fallback. `last_error` remains reserved for torrent failures. Selected-tracker warnings appear as `tracker_message`. Per-tracker diagnostics retain backup errors and identify the selected entry with `active=true`. - Non-200 HTTP bodies are inspected under the same size limit for bencoded failure messages; malformed or oversized bodies fall back to the HTTP status. HTTP 410 still disables the URL. Transport errors omit request URLs, but remote messages may themselves contain secrets. Public tracker tiers, backoff and request scheduling follow the audited libtorrent 2.1.2 defaults, not full tracker parity. Private tracker switching follows BEP 27. spill does not announce separately per listen address or send private-torrent `ipv4`/`ipv6` overrides. Metadata resolution starts a separate announce lifecycle, so failure history, tracker IDs and keys are not carried into payload download. Keys are random per announcer rather than derived from torrent/session/storage identity. spill does not report `redundant` bytes or subtract them from `downloaded`. Input budgets, URL validation and destination/redirect restrictions remain spill's own policy; HTTP connection pooling, DNS and endpoint failover are not identical to libtorrent's transports. ### DHT The DHT uses the address families supported by `listen`, with separate IPv4 and IPv6 routing tables and address-bound node IDs (BEP 42). Good contacts are saved in the catalog and reverified on the next start; `dht_bootstrap` lists the routers used to join when no saved nodes answer. It starts lazily for public transfers using DHT or magnet metadata resolution, never for private torrents or metainfo-only rechecks. Router outages remain ordinary discovery failures and are retried. Initialization failures fail affected executions and are retained until the session is recreated (restart the daemon to retry). The library's one-shot `download()` permits DHT with `default_routers()`: `dht.libtorrent.org:25401`, `dht.transmissionbt.com:6881`, `router.bittorrent.com:6881` and `router.utorrent.com:6881`. Eligible executions therefore perform router DNS lookups and UDP discovery. Reusable library sessions permit DHT only when their `NetworkOptions::dht` explicitly supplies capability. IPv6-only listeners use IPv6 DHT contacts; dual-stack listeners use both families. On multihomed IPv6 hosts, prefer a specific stable global `listen` address so outgoing DHT queries keep the same source address. Dual-stack bootstrap and refresh queries request both IPv4 and IPv6 referrals; normal peer lookups request their transport's family. Contacts learned across families are verified over their own transport before being used or saved. Router names are resolved separately for each enabled family. Unresponsive bootstrap attempts back off up to 15 minutes, independently for each family. Numeric IPv6 routers use bracketed addresses, for example `"[2001:db8::1]:6881"` (replace this example with a reachable router). Link-local and scoped DHT endpoints are not supported. Outgoing DHT datagrams are limited to 1024 bytes, with at most 40 peers per reply. Query rate limits group IPv6 sources by /64. #### DHT security and public addresses spill includes the requester's observed IP and port in the top-level `ip` field of DHT replies, including errors. Only replies matched to an outstanding query's source endpoint and transaction can contribute public-address observations. A public address explicitly bound by `listen` is used immediately. Otherwise, the node starts with a random ID until at least three independent source subnets agree on an address and form a strict majority of recent reports. Each IPv4 /24 or IPv6 /64 gets one vote in a ten-minute window, retaining at most 32 votes per address family. Local sources, local reported addresses and wrong-family reports are ignored. After the first confirmation, switching addresses requires at least two-thirds of the retained votes and a lead of at least three votes over the current address. Ports are not used to select an identity or change the listening port. Confirmed address changes regenerate the affected family's node ID and rebuild its routing buckets. Retained contacts keep their liveness history; contacts that no longer fit the new buckets are dropped. The rebuild marks buckets stale and schedules a lookup on the new ID regardless of the table's size. Identity changes wake the bootstrap task and end walks aimed at the previous neighbourhood. Outstanding transactions, stored peers and issued announce tokens remain usable. The catalog retains stable random identity material, not trusted public-address observations; confirming the same address after restart reproduces the same ID. IPv4 and IPv6 addresses are confirmed independently. Tracker and peer-handshake address hints are not used. spill continues answering nodes whose IDs fail BEP 42. Their referrals and peer results remain usable, but their tokens are ignored and they do not count toward the closest-eight lookup completion condition. Announce lookups count only compliant nodes that return tokens toward that condition. Private, loopback and link-local addresses are exempt from ID verification. This limits targeted node-ID placement; it does not authenticate DHT nodes or prevent all DHT attacks. ### Local service discovery On Linux and macOS, BEP 14 finds nearby peers without a tracker or DHT bootstrap, including peers that can resolve a trackerless magnet. The daemon enables it with `allow_local_network = true`; library sessions must explicitly set both `NetworkOptions::lsd` and `allow_local_network`. The per-torrent `dht` setting gates LSD independently of whether the session has DHT capability. spill joins `239.192.152.143:6771` and, for IPv6 or dual-stack listeners, `[ff15::efc0:988f]:6771`. A specific listen address selects its interface; an unspecified address selects up, multicast-capable interfaces, excluding loopback and point-to-point links (such as PPP and many VPN tunnels). A specific listen address explicitly selects its interface, including a point-to-point link. Announcements go out on each selected interface with TTL/hop limit 1, advertising the local listen port rather than a router-mapped port. A specific IPv6 listen address is also used as the multicast source, even when that interface has other IPv6 addresses. Interface checks run every minute off the async executor. Sockets and memberships are rebuilt only when the selected interfaces change or after setup or I/O errors. A failed join skips only that interface and is retried at the next check; other interfaces remain usable. A failed sending interface is left out until the rebuild; successful interfaces keep their normal announce cadence. Socket failures are logged; `spill health` under `network.lsd` reports errors unless an announce batch succeeds on at least one interface. These failures do not stop torrents or make session shutdown fail. New registrations announce immediately, bypassing the session-wide minute limit so a magnet's first announce is not delayed past its metadata deadline. Repeat announcements run every five minutes, with at most one repeat batch per minute. Bulk registration can send several initial batches back to back, with up to 20 hashes per packet. Repeat batches are round-robin scheduled. Stopping removes the registration; BEP 14 has no stop message. Peer JSON identifies outbound LSD contacts with `source: "lsd"`. Connections opened during metadata acquisition retain their discovery source when handed to payload transfer. Incoming metadata peers report `source: "metadata"` with `direction: "inbound"`. Magnets accept inbound peers while resolving metadata, so a LAN peer can answer an announcement by connecting immediately. spill advertises its listening port in the metadata-phase extension handshake. Live connections are kept through storage admission, without requiring the peer's listening port or another BitTorrent handshake. Metadata discovery retains its 45-second deadline. A peer that neither connects nor announces within that window may only be found on a later attempt. ## Local addresses By default spill never connects out to private, loopback or link-local addresses, whether it got them from a tracker, the DHT, PEX, a web seed URL or a torrent URL. This keeps a malicious torrent from making spill probe your local network. Peer destinations below port 1024 (including tracker-returned peers on port 443) are also refused unless `allow_local_network = true`; this can exclude seedboxes using low ports. Set `allow_local_network = true` to use LAN peers or trackers. Multicast, broadcast, unspecified peer addresses and port 0 are always refused. LSD is the multicast peer-discovery exception, only when enabled (router mapping also uses SSDP as described above). Scoped link-local IPv6 peers learned by LSD retain their interface scope. Incoming connections are accepted from any address. ## IPv4 and IPv6 - `listen = "0.0.0.0:6881"` (default): IPv4 only. - `listen = "[::]:6881"`: IPv6 and IPv4 for peers, UDP trackers and the DHT. - A specific IPv6 `listen` address: IPv6-only incoming peers, UDP trackers and DHT. - Peers from trackers and PEX can be IPv4 or IPv6; spill connects to whichever your host can reach. - IPv6 UDP trackers need an IPv6 or dual-stack `listen`. ## Peer connections - Up to `peers` connections per torrent (default 50), and at most 8 peers are uploaded to at once per torrent. - Canonical peer priority (BEP 40) ranks eligible outgoing contacts within each torrent, including magnet metadata acquisition. Higher ranks are preferred; holepunch attempts keep precedence, and retry deadlines still apply. spill does not open extra outgoing connections just to displace connected peers. - During payload transfer, a strictly higher-ranked incoming peer can replace the lowest-ranked eligible peer when slots are full. A slot already being freed is reused without evicting another peer. Metadata acquisition keeps its existing sources regardless of incoming rank, preserving their progress. Equal ranks keep the existing connection; web seeds and peers whose rank is unknown are not eviction candidates. One replacement socket may wait for the evicted task to join, without raising the live peer-task limit or changing session-wide reservations. - Ranking uses confirmed DHT external-address votes, router mapping information, or a public bind address. Local peers use the socket's local address when known. Without a trustworthy address for that family, spill retains ordinary admission and contact ordering. An individual peer's address claim is not trusted. Ranks are recomputed from current address information when selecting contacts or admitting a peer; address changes alone do not evict connections. - spill derives its peer ID prefix from its package version: `-sP` followed by base-36 major, minor and patch digits, a reserved `0`, and `-`. Extension handshakes and HTTP requests identify as `spill/VERSION`; this case-sensitive wire identifier is not the prose brand casing. - Full and partial seeds advertise `upload_only=1` in extension handshakes (BEP 21); downloading peers advertise zero. Handshake updates follow selected completion changes, and metadata acquisition never advertises upload-only. Once spill has finished its selection, connections to other upload-only peers or full seeds are retired. An upload-only peer can still supply downloads while spill needs pieces. - spill receives BEP 54 `lt_donthave` piece withdrawals. Once metadata is known, its extension handshake advertises a directional receive ID, independent of the peer's receive mapping. Withdrawn pieces leave that peer's availability; legacy requests are silently cancelled and can be reassigned. Fast and v2 requests remain pending until explicit replies arrive. Malformed withdrawals disconnect the sender. spill does not send piece withdrawals. - If the same peer connects twice (for example, both sides dialed each other), one connection is dropped. - Peers that send bad data are banned for the torrent; unhelpful peers are disconnected to make room for others. - Malformed known peer messages disconnect the peer, including malformed BEP 52 hash messages on v1 torrents. V2 connections follow stricter rules; see [v2 and hybrid torrents](v2.md#peer-protocol). ## Peer encryption spill supports Message Stream Encryption / Protocol Encryption (MSE/PE) on both TCP and uTP. It negotiates before the ordinary BitTorrent handshake and supports RC4 streams and negotiated plaintext application traffic. Set session-wide `peer_encryption` in daemon configuration: - `"allowed"`: initiate plaintext first, accepting MSE from incoming peers. - `"preferred"` (default): initiate MSE first. - `"required"`: reject plaintext and require RC4 for the whole application stream. `allowed` and `preferred` retry once in the alternate mode when the peer closes or resets during negotiation. The retry uses the transport that connected; malformed negotiation and timeouts do not trigger a retry. Once MSE succeeds, a close during the subsequent BitTorrent handshake does not trigger plaintext fallback. This is separate from the initial uTP-to-TCP connection fallback. `required` never downgrades. When responding to MSE, both `allowed` and `preferred` select RC4 if the peer offers it. Peer JSON reports `encryption` as `"rc4"` or `"plaintext"`, independently of `transport`. Negotiated plaintext reports `"plaintext"`. Web seeds report `null`, not their HTTP/TLS security. A peer also reports `null` before its handshake or when its live I/O observation is no longer available. MSE is legacy traffic obfuscation, not modern secure transport: its DH/RC4 parameters are required for interoperability, it has no peer authentication or authenticated encryption, and it does not protect against active interception. It does not encrypt tracker or DHT traffic or hide IP addresses. ## Privacy notes - Trackers, DHT nodes and peers see your IP address and what you download. This is inherent to BitTorrent. - A magnet link announces its info hash (to the DHT, its trackers and, when enabled, local service discovery) before spill knows whether the torrent is private. Use a `.torrent` file for private trackers; private metadata from magnets is rejected. - Peer encryption is obfuscation, not anonymity or authenticated transport; see [Peer encryption](#peer-encryption). - Detailed tracker and web-seed observations expose full URLs, which may contain passkeys or other secrets, even when transport errors redact them. --- # Private trackers spill supports torrents with the `private` flag (BEP 27). Add them from a `.torrent` file; magnets that resolve to private metadata are rejected. ## What changes for private torrents - **DHT, PEX, local discovery and holepunch discovery are off.** spill doesn't advertise DHT or PEX in handshakes, doesn't send DHT port messages, and refuses `set dht=true` or `pex=true`. The daemon disables them when private metainfo is added, regardless of the web add dialog's DHT and PEX selections. - **Outgoing peers come only from the active tracker** (and metainfo web seeds, if enabled). The library rejects caller-supplied direct peers for private torrents. - **One tracker URL is active at a time.** Switching is allowed only after its failure. Before using another URL, spill disconnects existing peers, cancels pending dials and clears old contacts. A recovered preferred URL does not replace a working fallback. Different URLs are treated as different trackers, even if they share a hostname. - **Private metadata is not served** through `ut_metadata`. - Rate limits, file selection and seeding goals work the same as for public torrents. ## Announces Private trackers track your ratio from announces, so spill follows these rules: - `started` is sent when a torrent starts, except that partial seeds announce `paused` (BEP 21). This means selected files are complete, not that the torrent has stopped. `left` still counts missing bytes across the whole torrent. - `stopped` is best-effort within five seconds when paused, removed, stopped by a seeding goal or shut down. Peer transfers stop before final counters are sampled. - Resuming or switching private tracker URLs starts fresh tracker accounting: `uploaded`, `downloaded` and `corrupt` start at zero rather than carrying forward traffic from the previous session. Returning to an earlier URL also starts fresh. `left` still describes the whole torrent; local lifetime totals are unchanged. - `uploaded` counts payload actually written to peer sockets. Tracker `downloaded` subtracts hash-failed bytes from received payload, floored at zero; HTTP reports failed bytes separately as `corrupt`. Redundant payload is not subtracted. Protocol overhead is not counted. Local lifetime download totals include corrupt traffic and can therefore differ from tracker counters. - `completed` is sent once, when a download that had missing data finishes. Delivery is saved per swarm in the catalog (`completed_announces` in `get`: an absent record = not completed here, `delivered: false` = waiting, `delivered: true` = acknowledged), so it survives restarts and is not repeated. If a tracker accepts the event but its reply is lost, it may be sent again. - Private hybrids announce only their v1 identity, avoiding duplicate credit for shared traffic. Their separate v2 tracker swarm is not used for discovery. Pure-v2 private torrents announce their v2 identity. - Torrents whose files were already complete when added (cross-seeding, moved data) announce as seeds and never send `completed`. - A `tracker id` from the tracker is sent back on later announces, and the tracker's `min interval` is respected, including for `reannounce`. - UDP announces include the URL's path and query through BEP 41 URLData, including passkeys. Authentication requires tracker-side URLData support. - Transport errors omit the request URL. Remote failure and warning text is displayed as supplied by the tracker and may itself contain sensitive data. - Bencoded failure messages in bounded non-200 HTTP bodies are also displayed; other error bodies fall back to the HTTP status. HTTP 410 disables the URL. ## Tracker messages - A **failure reason** ("Unregistered torrent", "Passkey not found", …) is shown as `tracker_error` while no selected tracker is succeeding for that swarm. It clears after recovery or successful fallback. Torrent failures remain in `last_error`; tracker rejection does not fail the torrent. - A selected tracker's **warning message** is shown as `tracker_message`. Tracker errors appear in `spill list`, `spill get`, and the web table and inspector. Per-tracker errors remain available in `transfer.trackers[].error`, including failed backups hidden by a successful selected tracker. ## Client whitelists Most private trackers only accept whitelisted clients. spill identifies itself with a version-derived `-sP…-` peer ID prefix and the wire identifier `spill/VERSION`; it never impersonates another client. See [Peer connections](networking.md#peer-connections) for the prefix format. Until a tracker whitelists spill, its announces may be rejected. Check your tracker's rules before using spill there. --- # Limits and performance ## Hard limits Torrents beyond these limits are refused when added. | Limit | Value | |---|---| | `.torrent` / metadata size | 16 MiB | | Pieces per torrent | 1,048,576 | | Piece size | 512 MiB | | Data files per torrent (excluding padding) | 100,000 | V2 expanded piece commitments, cached proof-tree nodes above the piece layer, and expanded paths share a separate 16 MiB admission budget. Proof trees are cached per file root on first use. For one large file this allows approximately 262,000 pieces (256K), fewer when expanded paths consume part of the budget. Magnet size admission includes its trackers and required piece layers and runs before layer acquisition. Only the first 32 web seeds of a torrent are used. Offline [torrent creation](cli.md#creating-torrents) uses the same file, piece count, and metainfo-size ceilings. It accepts power-of-two piece sizes from 32 KiB to 256 MiB (default 256 KiB), follows symlinks, and limits paths to 32 levels including the torrent root. It rejects entirely empty directories; zero-length files are supported. A fixed piece size that would exceed the piece count or metainfo-size limit must be increased explicitly. Daemon-wide limits: | Limit | Value | |---|---| | Online torrent inventory | `active_downloads` (up to 64) plus `active_seeds` (up to 100,000 configurable; not a measured capacity) | | Connections per torrent (`peers`) | 4096 (default 50) | | Running peer-wire connections per session | `session_peers` (defaults to `min(active_downloads + active_seeds, 64) × peers`) | | Peers uploaded to at once, per torrent | 8 | | Config file size | 64 KiB | There is no limit on how many torrents the catalog holds; torrents beyond the active slots wait as `queued`. Library callers have the same per-torrent resource bounds: `Profile.peers` must be 1–4096. `write_queue_bytes` must be 16 KiB–1 GiB. Admission and magnet metadata resolution reject invalid profiles with `InvalidInput` before starting work. `Profile::validate()` checks these bounds without starting an execution. Canonical peer replacement (BEP 40) may retain one waiting socket per torrent while the evicted peer task joins. The waiting socket starts no peer task until capacity is released. Running TCP and uTP peers share a session-wide limit; idle torrents do not reserve connection slots, and no torrent is guaranteed a share. New outbound dials wait when the session is full. Pending listener handshakes and dials have separate limits. ## Holepunch coordination BEP 55 uses the ordinary session dial-token, pending-dial, peer and uTP limits; it has no reserved dial capacity or guaranteed admission latency. | Bound | Value | |---|---| | Pending rendezvous per torrent | 8, at most one per target and introducer | | Rendezvous lifetime, including output queueing | 10 seconds | | Queued holepunch messages per connection | 8 | | Queued punch dial lifetime | 3 seconds | | Incoming rendezvous processed per connection | 4 per 10-second window | | Incoming connect messages processed per connection | 4 per 10-second window | | Retained PEX introductions per connection | 200 | Each incoming-message window starts on its first message. Rejected and duplicate requests consume the allowance too; excess requests are ignored without a reply. The next message after the window expires starts a new one. Relay pairs are queued only if both connections' output queues have room. Expired punch-only dials are dropped. Upgraded ordinary contacts return to their original source and schedule. Duplicate introductions do not extend a queued punch's lifetime. PEX introductions follow the existing one-minute receive gate and disappear when the connection closes or disables PEX. ## Resource use - **Memory**: each running torrent reserves `write_queue_bytes` (16 MiB by default) for queued writes. Local uploads rely on the OS file cache; remote S3 storage adds a shared 64 MiB read cache of 512 KiB chunks with in-flight request coalescing (note: an isolated cold 16 KiB block read fetches up to 512 KiB from the bucket—up to 32× read amplification if neighboring blocks are not requested). In-flight blocks and peer buffers are additional; the reservation is not a process memory limit. - **Open files**: fully verified, completed seeds share a pool of up to 512 open payload files per session, plus one shared directory handle per distinct output root. Initial verification and recovery still open the payload files together, and active downloads keep their files open until complete. These paths can use about 100,000 descriptors for a torrent with 100,000 files. The daemon raises its soft descriptor limit at startup on Linux to the hard limit. On macOS it uses the smaller of the hard limit and `kern.maxfilesperproc`; see [Troubleshooting](troubleshooting.md#macos-file-descriptor-limit). - **Threads**: one async thread runs the daemon; disk I/O and hashing run on a blocking thread pool. ## Measured baselines Measured on a Linux desktop (Intel Core Ultra 7 265, ext4) on a local network, against Transmission 4.1. These are historical workload measurements, not rankings or guarantees for the current release. Raw summaries, source revisions, and workload details are in [the baseline records](https://github.com/spillrs/spill/tree/main/tests/interop/baselines). | Scenario | Result | |---|---| | 1 GiB from one Transmission seed | spill 11.2 s, Transmission 19.5 s | | 8 leechers × 256 MiB from one Transmission seed | spill ~10.6 s (p50 of 10 runs), Transmission 13.7 s | | 33 torrents, 768 MiB, 4 download slots | 35 MiB peak memory, 118 open files, 1.5 ms p95 control latency | | Restart with 33 complete torrents | 0.1 s, nothing downloaded again | | One torrent with 100,000 files | 184 MiB peak memory, 100,018 open files; restart 9.7 s | The peer-wire comparisons include startup and choking delays. Filesystem caches were not dropped, some recorded source trees were dirty, and completion is not defined identically: spill includes its durability barrier; Transmission is observed through RPC progress. The 33-torrent workload uses local web seeds, not a peer-wire swarm. See the [measurement methodology](https://github.com/spillrs/spill/blob/main/tests/interop/README.md) and per-run notes before drawing comparisons. ## Known gaps - Automatic mapping supports NAT-PMP and UPnP IGD, not PCP or IPv6 pinholes. - V2 and hybrid interoperability has been checked only against libtorrent 2.1.2.0 on a controlled network; see [Scope](index.md#scope) and [v2 and hybrid torrents](v2.md#compatibility). Web-seed checks do not cover public-swarm capacity or HTTPS certificate interoperability. - Initial verification and writable storage can still require many open files (see above). --- # Troubleshooting ## Where are the logs? With the [web interface](web.md) enabled, click the footer daemon indicator, then **Logs**, for a bounded recent `debug.log` view with follow, refresh and copy controls. It does not include journald or early startup output. `spill serve` writes timestamped operational events to stderr, with color only on a terminal. Detailed logs append to `/debug.log`; spill does not rotate or limit this file. Retention is managed externally. Client command stdout and JSON are not logs. On Linux under systemd, stderr goes to the journal: ```sh journalctl --user -u spill -f # user service sudo journalctl -u spill -f # system service sudo journalctl -u spill -p warning # warnings and errors sudo tail -f /var/lib/spill/debug.log # system service debug history ``` spill supplies severity prefixes when stderr is connected to the journal, so `journalctl -p` can filter by priority. The journal owns its retention. For a user service, the default debug path is `~/.local/state/spill/debug.log`. For temporary console debugging: ```sh RUST_LOG=spill=debug spill serve --config /absolute/path/to/spill.toml ``` Under systemd, set `Environment=RUST_LOG=spill=debug` in a service override and restart. Remove the override and restart when finished. This changes only the console/journal output, not the independently configured debug file. Normal debug logs omit peer churn, successful piece/block activity and checkpoints; select a module at `trace` when those details are needed, for example `RUST_LOG=warn,spill::engine::peer_io=trace`. There are no periodic progress logs; use `spill --json get ID` for current state. See [Logging configuration](configuration.md#logging-logging) for filters. For peer connection history including IP addresses and ports, set this in the config and restart the daemon: ```toml [logging] file_filter = "warn,spill::engine::torrent=trace,spill::engine::peer_io=trace" peer_endpoints = true ``` Merge these keys into an existing `[logging]` table rather than adding a second one. Endpoint logging applies to both console and file trace events. Keep a bounded retention policy and review logs before sharing: addresses are linked to torrent IDs. Disable it and restart when the investigation is finished. Trace events are not a wire capture or a history of diagnostic samples. For an intermittent stall, also save `spill --json health` and `spill --json get ID` while it is happening; peer details disappear after disconnection. Torrent failures are also kept in the catalog: `spill get ID` shows `last_error` and, when retrying, `retry_at`. Tracker failures appear separately in `transfer.trackers[].error`; tracker warnings appear in `tracker_message` and `transfer.trackers[].warning`. A backup tracker's last error can remain visible while another tracker succeeds. Torrent log events include their ID so you can correlate interleaved transfers. On macOS, the launchd agent captures stderr in `~/Library/Application Support/spill/spill.log`; detailed logs are in `~/Library/Application Support/spill/debug.log`. Neither is macOS unified logging. Check the agent with `launchctl print gui/$(id -u)/rs.spill.daemon`. The separate launchd stderr file needs administrator-managed retention; see [Installation](install.md#macos). `spill health --json` includes `logging.events_dropped` (cumulative since startup) and `logging.write_failed` (cleared after a successful file write). This lets a report identify missing log evidence even without the console log. `debug_log_write_failed` means the debug file could not be written. Check free space and permissions; transfers continue, and `debug_log_recovered` marks successful writing again. `debug_log_events_dropped` reports file events lost to a full writer queue. Capture the journal/console too when reporting these failures. Very verbose filters can generate substantial output. ## macOS file-descriptor limit macOS shells often start with a soft limit of only 256 files. `spill serve` raises its soft limit to the smaller of its hard limit and `kern.maxfilesperproc`, read using `/usr/sbin/sysctl`; failure stops startup with an error rather than silently keeping the low limit. Client commands do not query or change this limit. Check the system cap with `sysctl kern.maxfilesperproc`. The launchd example also requests 10240 files. For unusually large workloads, increase the system cap and the agent's hard limit through your system administration policy before restarting spill. ## `daemon unavailable` (exit code 4) A client command can't reach the control socket. - Is the daemon running? For the Linux user service, run `systemctl --user status spill`; for the macOS launchd agent, run `launchctl print gui/$(id -u)/rs.spill.daemon`. - Is the client using the same socket as the daemon? Set `SPILL_SOCKET` or pass `--socket PATH` if the config sets `control_socket`. - For the Linux system service, run client commands as the `spill` user (the socket is mode `0600`): `sudo -u spill spill --socket /run/spill/control.sock list`. ## The daemon won't start Validate a config file without touching a running daemon using `spill serve --config PATH --check`. | Error | Fix | |---|---| | `cannot start torrent session on …: Address already in use` / `cannot bind web_listen …` | Another program uses the `listen` (TCP/UDP) or `web_listen` port. Pick another port or stop it. | | `control socket already in use` | Another spill is running with the same socket. | | `state directory … is already locked by another spill daemon` | Another spill holds `daemon.lock` in the same `state_dir`. | | `unsupported catalog version` | Use a compatible spill binary: the catalog is newer than this binary supports or is a nonempty unversioned catalog. Do not reset its version manually. See [Upgrading](install.md#upgrading). | | ` must be an absolute path` / `web_listen must be a loopback address` / `active_downloads (0..=64) and active_seeds (0..=100000) require a nonzero active cap` | Fix the named config key. TOML does not expand `~`. | | `unknown field …` | A typo or unsupported key in the config. | ## Adding a torrent fails Synchronous `spill add` failures (exit code 2; nothing added to the catalog): - `torrent already exists`: it's already in the catalog; check `spill list`. - `output_dir must be absolute`: raw control/HTTP API `output_dir` must be absolute (the CLI resolves relative `--output` paths automatically). Post-add startup failures (`spill add` returns an ID, then the torrent pauses with `last_error` in `spill list` / `spill get ID`): - `file already exists; choose another output directory`: some of the torrent's files (or a directory with a file's name) already exist and spill won't overwrite them. If all files are present and complete, spill adopts them instead; otherwise move the conflicting files away and `spill resume ID`, or run `spill remove ID` first before re-adding with another `--output`. - `private torrents require a .torrent file`: the magnet points at a private torrent; run `spill remove ID`, then add the `.torrent` file from the tracker. ## A torrent doesn't download - `queued`: all download slots are busy. Raise `active_downloads` or pause another. - `metadata` for a long time: no peer with the metadata was found. Check the magnet has trackers or that the DHT is enabled. A v2-only magnet with `info_validated` but not `metadata_ready` still needs authenticated piece layers from peers. Hybrids can download with layers pending and rebuild them locally at full completion. - `downloading` with no peers: check `last_error` and the trackers in `get`. If peers are on your LAN, set `allow_local_network = true`. If `peer_encryption = "required"`, plaintext-only peers cannot connect; use `"preferred"` for compatibility (see [Peer encryption](networking.md#peer-encryption)). For uTP-only peers, check that `utp` is enabled (the default). - `retrying`: read `last_error`. Disk full and permission errors are the usual causes. `pause` then `resume` retries immediately. Local filesystem failures retry with backoff; invalid authenticated metadata, private magnets and learned duplicate hashes pause the torrent instead. - On a private tracker, `transfer.trackers[].error` shows the tracker's reason, for example an unregistered torrent or a client that isn't whitelisted. ### Capturing a stall Before restarting, save `spill health --json` and `spill --json get ID`. Check `transfer.diagnostics_age_ms` first: an old sample can describe an earlier state. Compare two samples a few seconds apart. - Contacts but no connections: compare health's shared dial/handshake/uTP usage with its limits. `queued_contacts` includes retries not yet due. - A magnet stuck at metadata: inspect `transfer.trackers` and `metadata_error`. A rejection can remain visible after an honest peer succeeds. - Storage pressure or a long recovery: inspect `transfer.storage.operation`, its age and submitted hash/read counts. `checkpoint` can be waiting on catalog persistence; `sync` is the completion durability barrier. A label's age alone does not prove that a disk operation is hung. - Disappearing peers: debug logs retain protocol/request-timeout close reasons. Trace retains ordinary disconnects; neither reconstructs earlier packet traffic. - Failed web seeds: `transfer.web_seeds[].error` retains the actual failure message rather than only an error category. Sources are still tried once per execution; these observations do not change retry policy. Storage failure logs name the worker operation; payload read/write/finish/sync errors identify the zero-based metainfo file index. Logs and JSON can contain tracker passkeys, URLs and peer addresses: redact those before sharing a report. If control itself does not respond, collect console/debug logs and process state before stopping the daemon; health still shares the control path. ## Torrents stay queued after an internal failure If `spill health` shows `Admission: closed` (or `spill health --json` shows `"admission_closed": true`) while the daemon is running, a torrent stopped without proving that its files were released. spill then starts no further torrents, so it never opens the same files twice. The torrent's `last_error` names the failure. Restart the daemon, and report the error if it repeats. ## Nobody can connect to me Allow the `listen` port for TCP and UDP in your host firewall. `spill health` prints listener readiness, current inbound peers, successful inbound handshake totals and the time since the last public TCP/uTP handshake. No observations means only that none were seen since startup, not that the port is closed. These are passive observations: no external service or probe is used. Local peers do not count as evidence of public reachability. A failed automatic mapping can coexist with successful inbound peers when forwarding is manual. For scripts, use `spill health --json`. Its `network` fields are described in [Health](cli.md#health). `port_mapping` shows `enabled`, `protocol` (`nat-pmp` or `upnp`), `external_ip`, `external_tcp_port`, `external_udp_port`, `last_error` and `next_renewal` (a Unix timestamp in seconds, null when no renewal is scheduled). The top-level `advertised_port` shows the port currently sent to peers and trackers. If the router refuses or never answers, check that NAT-PMP or UPnP is enabled on it. `port_mapping_gateway = "192.168.1.1"` can correct NAT-PMP gateway discovery on multi-interface hosts. On networks that block multicast, use the router's UPnP description URL, for example `port_mapping_gateway = "http://192.168.1.1:5000/rootDesc.xml"`. This skips NAT-PMP and SSDP discovery; use the actual description URL for your router, not its web administration page. Only HTTP and unicast hosts are accepted. Each mapping attempt has an eight-second deadline, including two seconds for SSDP discovery and up to three seconds per description fetch. On busy networks, a slow device can delay discovery of the router until a later backoff retry; a direct description URL avoids that discovery budget. UPnP error 718 means a conflicting mapping: remove the conflicting entry or choose another listen port. Error 725 is handled by retrying with a permanent lease automatically. Otherwise set `port_mapping = false` and forward the listen port manually for TCP and UDP. Downloads and seeding over outbound connections still work when mapping fails. Double NAT and carrier-grade NAT may require changes upstream; a mapping at the local router alone cannot make those reachable. Automatic mapping currently requires an IPv4 listener. On macOS, allow spill's incoming-connections prompt. In System Settings → Network → Firewall → Options, allow the installed `spill` binary. Replacing an unsigned development binary may prompt again. Don't disable the firewall; allow only spill. The firewall permission does not configure your router. ## The DHT doesn't work - The DHT uses the families supported by `listen`. IPv6-only listeners need reachable IPv6 routers or saved IPv6 contacts. Dual-stack listeners can also learn IPv6 contacts from IPv4 nodes, then verify them over IPv6. `listen = "[::]:…"` enables both families. - `dht_bootstrap = []` with no saved nodes leaves the DHT with nobody to talk to. ## Torrents recheck after an upgrade An incompatible resume checkpoint causes the bound torrent's payload to be fully rechecked when it next starts. Existing good data is not downloaded again. Keep the state directory and payload in place; deleting the catalog also discards the recorded authority to reopen partial files. Catalog migrations run automatically at startup; unsupported catalog versions are a separate issue. See [Upgrading](install.md#upgrading). ## Files look wrong after a crash or power loss Run `spill recheck ID`, then `spill resume ID`. Recheck hashes every piece and leaves the torrent paused. Resuming downloads any missing or corrupt pieces. --- # Rust library Embed spill's BitTorrent engine in your application to create torrents, download, seed, inspect magnets, and manage concurrent torrents without a separate daemon, SQLite catalog, CLI, or web server. ## Dependencies and runtime ```sh cargo add spill --no-default-features cargo add tokio --features fs,macros,rt,net,time ``` The default `daemon` feature includes the binary and its CLI, database, and web dependencies. Disable it for engine-only applications. HTTP/TLS and filesystem support remain engine dependencies. Linux and macOS are supported. Supply a Tokio runtime with I/O and time drivers enabled. Current-thread and multithread runtimes are supported; enable Tokio's `rt-multi-thread` feature for the latter. spill creates no runtime, signal handler, or global tracing subscriber. ## Download a torrent Create an output directory first, then use `spill::engine::download`: ```rust use spill::engine::{Destination, TorrentSource, download}; #[tokio::main(flavor = "current_thread")] async fn main() -> std::io::Result<()> { let bytes = tokio::fs::read("example.torrent").await?; let source = TorrentSource::from_metainfo_bytes(&bytes)?; tokio::fs::create_dir_all("downloads").await?; download(source, Destination::Open("downloads".into())).await } ``` For magnets, construct the source with `TorrentSource::from_magnet(uri)?`. `download()` stops after the selected content completes and joins cleanup before returning. It uses an ephemeral IPv4 listener, uTP, public DHT routers, no port mapping, preferred MSE peer encryption, and no permission to contact LAN addresses. It keeps no recovery record. If interrupted, rerunning refuses to overwrite partial files; use persisted recovery for resumable transfers. Dropping the download future requests stop but cannot await cleanup. For timeouts or cancellation that must prove files have been released, use an explicit `Session`. ## Sessions and progress A `Session` shares listeners, discovery, and resource budgets across torrents. Core types (`Session`, `NetworkOptions`, `DhtOptions`, `Limits`, `TorrentOptions`, `TorrentSource`, `Destination`, `RunPolicy`, `Profile`, `FilePriority`, `FileSelection`, `RecoveryState`, `parse_owned`) are re-exported directly from `spill::engine`. ```rust use spill::engine::{ Destination, DhtOptions, Limits, NetworkOptions, RunPolicy, Session, TorrentOptions, TorrentSource, }; #[tokio::main(flavor = "current_thread")] async fn main() -> std::io::Result<()> { let bytes = tokio::fs::read("example.torrent").await?; let source = TorrentSource::from_metainfo_bytes(&bytes)?; tokio::fs::create_dir_all("downloads").await?; let session = Session::bind( NetworkOptions { dht: Some(DhtOptions::default()), ..Default::default() }, Limits::default(), ) .await?; let result = async { let mut options = TorrentOptions::new(source, Destination::Open("downloads".into())); options.run = RunPolicy::UntilComplete; let mut torrent = session.admit(options)?; while torrent.changed().await { let p = torrent.snapshot().progress; println!("{} / {} bytes", p.wanted_verified_bytes, p.wanted_bytes); if p.completed { break; } } torrent.outcome().await.require_complete() } .await; let shutdown = session.shutdown().await; result.and(shutdown) } ``` Session-wide payload rates start unlimited. Use `Session::set_bandwidth_limits` to set download and upload caps in bytes per second (`0` means unlimited), and `Session::bandwidth_limits` to read them in that order. Limits apply to running and future torrents and compose with per-torrent limits. Download limits pace requests rather than bytes already in flight. Use `TorrentHandle::set_bandwidth_limits` to change the per-torrent caps for an existing execution without restarting it. Set rates in `TorrentOptions` for future executions; the library does not persist rate changes. - `NetworkOptions` defaults to an ephemeral IPv4 listener, uTP enabled, `PeerEncryption::Preferred`, no port mapping, no LAN permission, no DHT, and no LSD. Set `dht = Some(DhtOptions::default())` to enable default public DHT routers. Unlike `download()`, reusable sessions do not enable DHT implicitly. Local service discovery requires both `lsd = true` and `allow_local_network = true`; setting `lsd = true` without LAN permission reports an error in `network_status().await.lsd.last_error`. - `TorrentOptions::no_progress_timeout` is `Option` (default `None`). Set `Some(duration)` if you want an incomplete execution to exit with `TorrentExit::NoProgress` after a stall. - `TorrentOptions::initial_peers` supplies direct initial peers (rejected for private metainfo). - `Limits` bounds aggregate resources; each torrent has a `Profile` and `TorrentSettings`. See [Limits](limits.md) and the API reference. - `RunPolicy::Persistent` keeps serving after completion; `UntilComplete` stops after selected-content completion (allowing up to 5 seconds for pending completed tracker announces). `Recheck` runs under `TorrentPhase::Checking` and verifies metainfo against disk without peer or discovery I/O. Offline sessions accept only metainfo rechecks. - `Session::network_status().await` reports local listener-task readiness and passive inbound TCP/uTP handshake counts, public subsets and last-public ages, plus LSD readiness, announce/receive counts and its last error. - `Session::inspect` resolves magnet metadata without creating payload files; await `handle.wait_metadata().await`. - `snapshot()` gives current progress (`downloaded_bytes`, `uploaded_bytes`, `wanted_verified_bytes`, `wanted_bytes`, `phase`); `changed().await` observes latest-value updates, returning `false` after the final report. `handle.file_priorities()` returns the effective priorities once metadata is available (including BEP 53 `so=` selections). - `wait_complete()` waits for wanted-content completion, not termination. `join()` joins termination and returns any execution error (even on a clean incomplete stop). `outcome().await.require_complete()` joins termination and requires both clean exit and wanted-content completion. ## Formats, magnets, and selection Private torrents require metainfo, not magnets. `Session::admit` rejects nonempty `TorrentOptions::initial_peers` for private metainfo; private outgoing peers must come from its active tracker. See [Private trackers](private-trackers.md). Use `FileSelection::from_fn(meta.layout(), |index, file| ...)` to construct custom per-file priorities safely—it automatically keeps virtual BEP 47 padding entries at `FilePriority::Skip`. BEP 53 `so` ranges on magnets apply after metadata resolution unless `TorrentOptions.settings.file_priorities` is non-empty. When restarting from saved metainfo instead of the original magnet, also persist `handle.file_priorities()`. `TorrentIdentity`, `InfoHashV1`, and `InfoHashV2` implement `Display`, `FromStr`, and `Ord`. Parse a 40-char or 64-char hex hash with `str::parse::()` to look up an execution via `Session::torrent(identity)`. `TorrentHandle::info_hash()` returns the admission identity; snapshots contain all hashes learned during resolution. For v2/hybrid details: - `TorrentDiagnostics` identifies tracker and DHT entries by their `swarm` key; `dht` contains one entry per swarm. - `OwnedMetainfo::layers_pending()` identifies hybrids that verify with SHA-1 while required v2 layers are absent. - `Persistence::resolved` acknowledges magnet metainfo before payload preparation and again when a background hybrid layer rebuild completes. Store both publications and use `TorrentHandle::metainfo()` to retain the latest metainfo. - `Layout::is_multi_file()` indicates that file paths are relative to `name`. - `port_map::Gateway::Upnp(url::Url)` accepts a validated `url::Url` (or parse any gateway string with `Gateway::parse`). ## Verify and remove local payload `spill::engine::provisioning::verify` checks complete existing payload against an `OwnedMetainfo`, without a session or Tokio runtime. Supply the parent download directory; paths use spill's normalized disk names. It is read-only, stops at the first failure, and does not use network or resume state. Keep files unchanged during the scan. Asynchronous callers should use `spawn_blocking`. `spill::engine::provisioning::remove(root, &binding)` deletes writable payload files recorded in a `DestinationBinding` while leaving read-only adopted seeds (`binding.is_read_only()`) untouched. ## Create a torrent `spill::engine::create::create` hashes a file or directory without a session, network access, or a Tokio runtime: ```rust use spill::engine::create::{self, Options}; fn main() -> std::io::Result<()> { let options = Options { announce: vec![vec!["https://tracker.example/announce".into()]], creation_date: None, ..Default::default() }; let torrent = create::create(std::path::Path::new("payload"), &options, &mut |done, total| { eprintln!("{done}/{total} pieces"); Ok(()) })?; std::fs::write("payload.torrent", torrent.metainfo) } ``` This is a blocking API; use `spawn_blocking` when calling it from an async application. Call `options.validate()?` to check options before accessing the filesystem. The progress callback runs on the calling thread. Return an error from it to cancel; creation joins its workers before returning. The result includes encoded metainfo, `CreatedTorrent::info_hash` as a `TorrentIdentity`, root name, total bytes (including alignment padding), and piece count. The caller owns output publication; the CLI additionally refuses overwrites and publishes the completed document atomically. `Options::piece_length` is in **bytes**, unlike the CLI's exponent. Defaults are 256 KiB pieces and the available CPU count. `Options::format` selects `Format::V1` (the default), `Format::V2` or `Format::Hybrid`. V1 sorts whole path bytes; v2 and hybrid sort path components and align files to pieces. Symlinks are followed, and the source is never modified. Keep it unchanged until the call returns. See [Creating torrents](cli.md#creating-torrents) for supported fields, source traversal, limits, and the separate add-and-seed workflow; rustdoc owns the exact API contract. ## Destinations and recovery All destinations require an existing root directory: | Destination | Behavior | |---|---| | `Open` | Create new payload, or verify and adopt an already complete seed. | | `Create` | Refuse existing payload. | | `Adopt` | Verify an existing read-only seed. | | `Recover` | Reopen a previous execution using its recorded destination binding and checkpoints. | | `Remote` | Store verified pieces as S3 objects with external checkpoint persistence. | spill never overwrites files it has no recorded authority to write. Resume records bind the format, full torrent identity and pending/full layer mode. A full hybrid cannot trust a pending-mode checkpoint without rechecking. The rebuild saves a full-mode checkpoint, so a normal completed restart needs no extra recheck. Fingerprints cover real files, including empty files, not virtual padding. `Recover` fully rechecks payload when a checkpoint is incompatible, using its existing destination binding. Keep that binding and payload; checkpoint incompatibility alone does not require a fresh state directory. A resume checkpoint alone does not authorize reopening partial payload: `DestinationBinding` does. `RecoveryState` derives `Serialize` and `Deserialize` (along with `dht::SavedState`), so you can persist `(root, RecoveryState)` as one record and update announce delivery via `RecoveryState::record_announce`. Preserve resume bytes unchanged and treat the serialized format as an opaque record tied to the spill version. `Persistence` provides optional acknowledgements for resolved metadata, destination bindings, checkpoints, and completed-announce delivery. The `completion_announce` callback receives `(swarm_key, delivered)`; `RecoveryState::completed_announces` stores `(swarm_key, delivered)` pairs. Preserve every swarm independently: `false` means pending and `true` means acknowledged. Acknowledging one hybrid swarm does not acknowledge the other. They run on blocking threads. Acknowledgement failures fail the execution. Callbacks must not wait synchronously for their own execution or session to stop. Metadata acknowledgement precedes destination preparation; binding acknowledgement precedes file creation. Resume acknowledgement precedes content completion; tracker-delivery acknowledgement precedes advancing delivery state. Stop and shutdown join callbacks already in progress, without a hard deadline. Use `handle.recovery()` to retain the latest acknowledged recovery state for a subsequent execution. For recovery across process restarts, persist it yourself. ### Remote S3 destination [`Destination::Remote`](https://docs.rs/spill/latest/spill/engine/torrent/enum.Destination.html) stores verified pieces directly in an S3-compatible bucket using spill's built-in `reqwest`/`rustls` transport and SigV4 signing (no extra Cargo feature required). Construct an `engine::storage::object::ObjectStorage` with an HTTPS origin endpoint, region, bucket, `Credentials` (updatable live via `ObjectStorage::set_credentials`), optional PEM CA bundle, and `GuardMode` (`StableEtag` or `Version`), and assign a dedicated prefix. Supply all three `RemotePersistence` callbacks (`commit`, `load`, `piece`). Commit the binding, verified bitmap, and changed piece records in one durable transaction. On restart, load the header and resolve guards lazily by piece index; spill caches guards in memory per torrent. Removing a torrent does not delete bucket objects, and `RunPolicy::Recheck` is not supported. The destination supports v1, v2, and hybrid torrents. Hybrid magnets with missing piece layers also require `Persistence::resolved` to durably save the rebuilt metainfo. Clones of one `ObjectStorage` share the assembly byte budget (`with_assembly_bytes`, default 96 MiB), proof-read byte budget, a lazy 64 MiB read cache (512 KiB chunks with in-flight coalescing), and 64-GET concurrency cap; each active piece reserves twice its logical length through PUT acknowledgement. Use `RemoteDestination::extract` to verify and materialize a completed remote torrent into local files. ## Stop and shutdown Call `handle.request_stop()` then await `handle.outcome()`, or use `handle.stop()`. Stop is terminal: resuming means admitting a new execution after joined cleanup. Finished executions retire automatically; old handles cannot control replacements. Call `session.shutdown().await` before releasing the session. Session clones share executions; dropping one clone does not stop them. Dropping the last clone requests stop but cannot await it. A cancelled shutdown wait can be joined again through another retained handle. Joined shutdown releases both TCP and UDP listening ports before returning, even if a clone is kept to read `dht_state()`. `outcome().cleanup_complete` distinguishes a failed transfer with joined cleanup from a failure that cannot prove resources were released. Inspect that outcome before reusing a destination after an error. Session admission closes if cleanup cannot be proven. ## Runnable examples From a source checkout matching your library version: ```sh mkdir -p downloads recovery cargo run --no-default-features --example download -- FILE.torrent downloads cargo run --no-default-features --example download -- --magnet 'magnet:?...' downloads cargo run --no-default-features --example progress -- downloads recovery A.torrent B.torrent ``` The `download` example is minimal; `progress` demonstrates concurrent downloads, progress reporting, persistence callbacks, and recovery after interruption. Examples live in `examples/` in the [source repository](https://github.com/spillrs/spill). Prefer these and the versioned API reference over inferring library methods from daemon commands. --- # Architecture The daemon and embedded applications use the same engine. This page describes stable boundaries; the [source](https://github.com/spillrs/spill/tree/main/src) is the reference for implementation details. For integration, start with the [Rust library guide](library.md) and [API reference](https://docs.rs/spill). ## One package, two uses The `spill` Cargo package contains a library and the `spill` binary. | Layer | Responsibility | |---|---| | `spill::protocol` | Pure wire codecs and validated BitTorrent v1/v2 and hybrid metainfo. No I/O. | | `spill::engine` | Sessions, torrent lifecycles, peers, discovery, storage, and observations. | | Daemon | CLI, configuration, SQLite catalog, supervisor, Unix control socket, and local web interface. | The daemon uses the public engine API, just like an embedding application. Disable default features to use the engine without daemon dependencies. ## Ownership and scheduling A session owns shared networking and resource budgets. Each admitted torrent owns its lifecycle and transfer state. Its deterministic core takes inputs and returns actions; the runtime performs those actions and feeds results back. Protocol and scheduling decisions stay in the core, not in transport or storage. The daemon uses a single-threaded Tokio runtime. Embedded applications supply their own current-thread or multithread runtime. Blocking filesystem operations and hashing run on Tokio's blocking pool. Bounded queues connect peer I/O, transfer state, and the per-torrent writer. Backpressure prevents a slow disk or peer from creating an unbounded payload queue. Admission reserves per-torrent budgets; these are not a total RSS limit. See [Limits and performance](limits.md). ## Verification and durability Only hash-verified pieces are uploaded. Pieces can be verified from buffered data or read back from disk. Resume checkpoints pair verified progress with file fingerprints; changed files are rechecked before transfer resumes. Payload is synced at the completion barrier, not after each write. [Restarts and durability](torrents.md#restarts-crashes-and-durability) describes what checkpoints can and cannot guarantee after a crash or power loss. Stopping joins owned peer, storage, discovery, and blocking work before releasing the destination. Embedded callers explicitly await cleanup; see [Stop and shutdown](library.md#stop-and-shutdown). ## Daemon persistence The SQLite catalog stores torrent intent, settings, accounting, recovery data, and errors. The supervisor reconciles that intent with engine executions and available download/seed slots. CLI, Unix-socket, and HTTP requests use the same control dispatcher. ## Validation Protocol codec tests live in `tests/protocol/`; public-engine and daemon end-to-end scenarios live in `tests/engine/` and `tests/daemon/`. They run without public networking. Transmission interoperability and scale scenarios are opt-in; see the [test harness guide](https://github.com/spillrs/spill/blob/main/tests/interop/README.md).