libtorrent Documentation

repository·RC_2_1·Indexed 27 days ago

https://github.com/arvidn/libtorrent

A high-performance C++ library implementing the BitTorrent protocol and its extensions for server-side and embedded use cases. Version 2.1.0. Includes guides for building with boost-build (b2) and cmake across Linux, macOS, and Windows, configuration of SSL/Crypto support (OpenSSL, wolfSSL), and details on Python bindings and CLI client options.

Tokens
32.5K
Snippets
37
Records
205
Agent score
88%

What's inside libtorrent

  1. Overview of libtorrent

    RC_2_1
    libtorrent is an open source C++ library that implements the BitTorrent protocol and its most popular extensions. It is designed for efficiency and ease of use, making it suitable for real-world deployment in environments ranging from high-performance servers to resource-constrained embedded devices.
  2. Overview of libtorrent features

    RC_2_1

    libtorrent is a feature-complete C++ BitTorrent implementation designed for efficiency and scalability, suitable for both embedded devices and desktops.

    Key capabilities include:

    • BitTorrent v2 Support: Full support for BEP 52, featuring SHA-256, Merkle hash trees for per-file validation, and a more efficient directory-based file structure.
    • Extensibility: A plugin interface for custom extensions and support for various protocols (DHT, Magnet links/BEP 9, PEX, etc.).
    • Advanced Disk Management: Asynchronous multi-threaded disk I/O, fast resume support, and multi-threaded SHA-1 verification.
    • Optimized Networking: High-quality uTP implementation (BEP 29), block-level piece picking, and automatic upload slot management.
    • Specialized Modes: Includes a 'share mode' for optimizing upload ratios rather than downloading.
  3. Overview of the BitTorrent DHT Arbitrary Store Extension

    RC_2_1

    This extension allows the BitTorrent DHT to store and retrieve arbitrary data. It supports two types of items:

    1. Immutable Items: Stored under the SHA-1 hash of the data itself. Since they cannot be modified, no authentication is required. A requesting node should verify that the received data's hash matches the requested target.
    2. Mutable Items: Stored under the SHA-1 hash of the publisher's public key (optionally concatenated with a salt). These items can be updated by the original publisher using a private key. Updates are secured via a monotonically increasing sequence number (seq) and an ed25519 signature (sig).
  4. Access libtorrent language bindings

    RC_2_1

    While libtorrent is a C++ library, bindings are available for several other languages:

    • Python: Use the Python bindings.
    • Java: Available via frostwire-jlibtorrent.
    • Golang: Available via libtorrent-go.
    • Node.js: Available via node-libtorrent.
  5. Understand SSRF mitigations in libtorrent

    RC_2_1

    libtorrent implements several mitigations against Server-Side Request Forgery (SSRF) attacks involving tracker URLs and web seeds. These mitigations are designed to prevent attackers from using libtorrent to probe local networks, cloud metadata services (like AWS http://169.254.169.254/), or internal REST interfaces.

    Key mitigations include:

    • Tracker URL Restrictions: For tracker URLs pointing to localhost, libtorrent requires the request path to be /announce. This follows the standard BitTorrent convention and helps prevent hitting arbitrary local REST APIs.
    • Web Seed Restrictions:
      • Web seeds resolving to a local network address are not allowed to have query string parameters.
      • Web seeds resolving to a global address (non-loopback, non-local network, non-multicast) are prohibited from redirecting to a non-global IP address.
    • Protocol Scheme Enforcement: libtorrent only supports http, https, and udp schemes. It explicitly rejects other schemes, such as file://, to prevent unauthorized local file access.
    • Query String Validation: libtorrent implements checks for tracker URLs that include query string arguments that are intended to be added by the client, preventing certain types of parameter injection.
  6. Understand libtorrent high-level structure

    RC_2_1

    Libtorrent uses a Pimpl (pointer to implementation) pattern to separate the public interface from internal state.

    • session: The public interface to the session. It hides the session_impl object to maintain binary compatibility.
    • session_impl: The internal state object containing global information such as m_torrent (list of torrents), m_connections (peer connections), m_settings (global rate limits), m_dht (DHT state), and port mapping state (m_upnp and m_natpmp).
    • torrent_handle: The public interface to a torrent. It holds a weak reference to the internal torrent object and communicates with the network thread via messages.
  7. Understand streaming vs sequential_download

    RC_2_1

    Libtorrent provides two ways to manage peer request queues for ordered data:

    1. sequential_download: A simple mode that waits for a queue slot to open and requests the next piece in sequence. While it saturates bandwidth and keeps pieces roughly in-order, it is sub-optimal for streaming because a slow peer holding up an early piece can prevent fast peers from receiving requests for later, more critical pieces.

    2. Streaming (Time-critical logic): An advanced version of sequential download that actively manages peer request queues. It ensures the most time-critical pieces occupy the "best" queue slots across all available peers, making it more suitable for real-time media playback.

  8. Understand libtorrent terminology

    RC_2_1

    To work with the libtorrent internals, you must understand the following core concepts:

    • piece: A part of the torrent data identified by a SHA-1 hash in the .torrent file. Pieces are typically powers of two in size.
    • block: A 16 kiB unit that a piece is split into. A block never spans two pieces. 16 kiB is the standard largest transfer unit in the BitTorrent protocol.
    • piece picker: The logic responsible for determining which blocks (from pieces) to request from peers.
    • file storage: Objects that represent the file layout, containing the list of files, piece sizes, and the mapping from pieces to files. Designed to be compact for large torrents.
    • torrent: An object representing the complete state of a swarm download, including the piece picker, peer connections, and file storage.
    • peer_connection: A peer that is currently connected to the client.
    • torrent_peer: A peer that the client knows about (via tracker, DHT, or peer exchange) but is not currently connected to.
    • peer_list: A collection of known peers for a swarm, which may include both connected and unconnected peers.
  9. Understanding uTP (uTorrent Transport Protocol) in libtorrent

    RC_2_1

    uTP is a transport protocol designed to prevent BitTorrent traffic from saturating a user's internet connection and causing high latency for interactive applications (like web browsing or Skype).

    Unlike TCP, which primarily reacts to packet loss, uTP uses a congestion controller called LEDBAT that reacts to changes in one-way delays. This allows uTP to detect when a modem's send buffer is filling up and proactively reduce its send rate before packet loss occurs, leaving headroom for other traffic. Once interactive traffic ceases, uTP automatically scales back up to utilize the available bandwidth.

  10. Understand the DHT RSS Feed Extension

    RC_2_1

    This proposal (superseded by dht_put) describes a BitTorrent DHT extension for decentralized RSS-like functionality. It allows creating repositories of torrents where a single identity (a private key) has the authority to add content.

    Key Concepts:

    • Target ID: The SHA-1 hash of a feed name and a 512-bit public key. This is where the repository is stored in the DHT.
    • Storage Node: A DHT node to which an item is being announced.
    • Subscribing Node: A node that performs lookups in the DHT to find storage nodes and request items.
    • Security: Every item must be signed with the private key corresponding to the public key used in the Target ID. Recipients must verify both the public key against the Target ID and the signature of each individual item.
  11. Understand libtorrent threading model

    RC_2_1

    Libtorrent utilizes multiple threads to manage network, disk, and name resolution tasks. The number of threads depends on the settings_pack::aio_threads setting.

    • Main Network Thread: Manages all sockets, sends/receives messages, and maintains session, torrent, and peer state. It typically blocks on system calls like epoll() when idle.
    • Disk I/O Threads: Handles all disk read/write operations and performs SHA-1/SHA-256 piece verification. Messages are passed back to the main thread upon completion. Multiple threads may be used to prevent disk starvation.
    • Asynchronous Host Name Resolution Thread: Spawned by boost.asio on systems lacking native asynchronous host name resolution to simulate non-blocking getaddrinfo().
  12. Path MTU discovery in uTP

    RC_2_1

    libtorrent's uTP implementation performs Path MTU (Maximum Transfer Unit) discovery to find the largest packet size that can be sent without fragmentation. This avoids the overhead, bandwidth waste, and packet loss associated with fragmented datagrams.

    Key mechanisms include:

    • Binary Search: The implementation uses a binary search between a minimum internet MTU (576) and a maximum (1500 for Ethernet) to find the optimal packet size.
    • DF (Don't Fragment) Bit: It sets the DF bit in datagrams to trigger ICMP 'packet-too-big' messages from routers, allowing for discovery. Because some firewalls block ICMP, it also uses probes to detect drops caused by size limits.
    • Interface Optimization: libtorrent automatically detects the MTU of the network interface used by a uTP connection. This allows it to immediately use appropriate sizes for VPN tunnels or jumbo frames without needing a full search.