libtorrent API Documentation

Author: Arvid Norberg, arvid@libtorrent.org
Version: 1.1.2

overview

The interface of libtorrent consists of a few classes. The main class is the session, it contains the main loop that serves all torrents.

The basic usage is as follows:

Each class and function is described in this manual, you may want to have a look at the tutorial as well.

For a description on how to create torrent files, see create_torrent.

things to keep in mind

A common problem developers are facing is torrents stopping without explanation. Here is a description on which conditions libtorrent will stop your torrents, how to find out about it and what to do about it.

Make sure to keep track of the paused state, the error state and the upload mode of your torrents. By default, torrents are auto-managed, which means libtorrent will pause them, unpause them, scrape them and take them out of upload-mode automatically.

Whenever a torrent encounters a fatal error, it will be stopped, and the torrent_status::error will describe the error that caused it. If a torrent is auto managed, it is scraped periodically and paused or resumed based on the number of downloaders per seed. This will effectively seed torrents that are in the greatest need of seeds.

If a torrent hits a disk write error, it will be put into upload mode. This means it will not download anything, but only upload. The assumption is that the write error is caused by a full disk or write permission errors. If the torrent is auto-managed, it will periodically be taken out of the upload mode, trying to write things to the disk again. This means torrent will recover from certain disk errors if the problem is resolved. If the torrent is not auto managed, you have to call set_upload_mode() to turn downloading back on again.

network primitives

There are a few typedefs in the libtorrent namespace which pulls in network types from the boost::asio namespace. These are:

typedef boost::asio::ip::address address;
typedef boost::asio::ip::address_v4 address_v4;
typedef boost::asio::ip::address_v6 address_v6;
using boost::asio::ip::tcp;
using boost::asio::ip::udp;

These are declared in the <libtorrent/socket.hpp> header.

The using statements will give easy access to:

tcp::endpoint
udp::endpoint

Which are the endpoint types used in libtorrent. An endpoint is an address with an associated port.

For documentation on these types, please refer to the asio documentation.

exceptions

Many functions in libtorrent have two versions, one that throws exceptions on errors and one that takes an error_code reference which is filled with the error code on errors.

There is one exception class that is used for errors in libtorrent, it is based on boost.system's error_code class to carry the error code.

For more information, see libtorrent_exception and error_code_enum.

translating error codes

The error_code::message() function will typically return a localized error string, for system errors. That is, errors that belong to the generic or system category.

Errors that belong to the libtorrent error category are not localized however, they are only available in english. In order to translate libtorrent errors, compare the error category of the error_code object against libtorrent::libtorrent_category(), and if matches, you know the error code refers to the list above. You can provide your own mapping from error code to string, which is localized. In this case, you cannot rely on error_code::message() to generate your strings.

The numeric values of the errors are part of the API and will stay the same, although new error codes may be appended at the end.

Here's a simple example of how to translate error codes:

std::string error_code_to_string(boost::system::error_code const& ec)
{
        if (ec.category() != libtorrent::libtorrent_category())
        {
                return ec.message();
        }
        // the error is a libtorrent error

        int code = ec.value();
        static const char const* swedish[] =
        {
                "inget fel",
                "en fil i torrenten kolliderar med en fil fran en annan torrent",
                "hash check misslyckades",
                "torrentfilen ar inte en dictionary",
                "'info'-nyckeln saknas eller ar korrupt i torrentfilen",
                "'info'-faltet ar inte en dictionary",
                "'piece length' faltet saknas eller ar korrupt i torrentfilen",
                "torrentfilen saknar namnfaltet",
                "ogiltigt namn i torrentfilen (kan vara en attack)",
                // ... more strings here
        };

        // use the default error string in case we don't have it
        // in our translated list
        if (code < 0 || code >= sizeof(swedish)/sizeof(swedish[0]))
                return ec.message();

        return swedish[code];
}

queuing

libtorrent supports queuing. Queuing is a mechanism to automatically pause and resume torrents based on certain criteria. The criteria depends on the overall state the torrent is in (checking, downloading or seeding).

To opt-out of the queuing logic, make sure your torrents are added with the add_torrent_params::flag_auto_managed bit cleared. Or call torrent_handle::auto_managed(false) on the torrent handle.

The overall purpose of the queuing logic is to improve performance under arbitrary torrent downloading and seeding load. For example, if you want to download 100 torrents on a limited home connection, you improve performance by downloading them one at a time (or maybe two at a time), over downloading them all in parallel. The benefits are:

  • the average completion time of a torrent is half of what it would be if all downloaded in parallel.
  • The amount of upload capacity is more likely to reach the reciprocation rate of your peers, and is likely to improve your return on investment (download to upload ratio)
  • your disk I/O load is likely to be more local which may improve I/O performance and decrease fragmentation.

There are fundamentally 3 seaparate queues:

  • checking torrents
  • downloading torrents
  • seeding torrents

Every torrent that is not seeding has a queue number associated with it, this is its place in line to be started. See torrent_status::queue_position.

On top of the limits of each queue, there is an over arching limit, set in settings_pack::active_limit. The auto manager will never start more than this number of torrents (with one exception described below). Non-auto-managed torrents are exempt from this logic, and not counted.

At a regular interval, torrents are checked if there needs to be any re-ordering of which torrents are active and which are queued. This interval can be controlled via settings_pack::auto_manage_interval.

For queuing to work, resume data needs to be saved and restored for all torrents. See torrent_handle::save_resume_data().

queue position

The torrents in the front of the queue are started and the rest are ordered by their queue position. Any newly added torrent is placed at the end of the queue. Once a torrent is removed or turns into a seed, its queue position is -1 and all torrents that used to be after it in the queue, decreases their position in order to fill the gap.

The queue positions are always contiguous, in a sequence without any gaps.

Lower queue position means closer to the front of the queue, and will be started sooner than torrents with higher queue positions.

To query a torrent for its position in the queue, or change its position, see: torrent_handle::queue_position(), torrent_handle::queue_position_up(), torrent_handle::queue_position_down(), torrent_handle::queue_position_top() and torrent_handle::queue_position_bottom().

checking queue

The checking queue affects torrents in the torrent_status::checking or torrent_status::allocating state that are auto-managed.

The checking queue will make sure that (of the torrents in its queue) no more than settings_pack::active_checking_limit torrents are started at any given time. Once a torrent completes checking and moves into a diffferent state, the next in line will be started for checking.

Any torrent added force-started or force-stopped (i.e. the auto managed flag is _not_ set), will not be subject to this limit and they will all check independently and in parallel.

downloading queue

Similarly to the checking queue, the downloading queue will make sure that no more than settings_pack::active_downloads torrents are in the downloading state at any given time.

The torrent_status::queue_position is used again here to determine who is next in line to be started once a downloading torrent completes or is stopped/removed.

seeding queue

The seeding queue does not use torrent_status::queue_position to determine which torrent to seed. Instead, it estimates the demand for the torrent to be seeded. A torrent with few other seeds and many downloaders is assumed to have a higher demand of more seeds than one with many seeds and few downloaders.

It limits the number of started seeds to settings_pack::active_seeds.

On top of this basic bias, seed priority can be controller by specifying a seed ratio (the upload to download ratio), a seed-time ratio (the download time to seeding time ratio) and a seed-time (the abosulte time to be seeding a torrent). Until all those targets are hit, the torrent will be prioritized for seeding.

Among torrents that have met their seed target, torrents where we don't know of any other seed take strict priority.

In order to avoid flapping, torrents that were started less than 30 minutes ago also have priority to keep seeding.

Finally, for torrents where none of the above apply, they are prioritized based on the download to seed ratio.

The relevant settings to control these limits are settings_pack::share_ratio_limit, settings_pack::seed_time_ratio_limit and settings_pack::seed_time_limit.

queuing options

In addition to simply starting and stopping torrents, the queuing mechanism can have more fine grained control of the resources used by torrents.

half-started torrents

In addition to the downloading and seeding limits, there are limits on actions torrents perform. The downloading and seeding limits control whether peers are allowed at all, and if peers are not allowed, torrents are stopped and don't do anything. If peers are allowed, torrents may:

  1. announce to trackers
  2. announce to the DHT
  3. announce to local peer discovery (local service discovery)

Each of those actions are associated with a cost and hence may need a seprarate limit. These limits are controlled by settings_pack::active_tracker_limit, settings_pack::active_dht_limit and settings_pack::active_lsd_limit respectively.

Specifically, announcing to a tracker is typically cheaper than announcing to the DHT. active_dht_limit will limit the number of torrents that are allowed to announce to the DHT. The highest priority ones will, and the lower priority ones won't. The will still be considered started though, and any incoming peers will still be accepted.

If you do not wish to impose such limits (basically, if you do not wish to have half-started torrents) make sure to set these limits to -1 (infinite).

prefer seeds

In the case where active_downloads + active_seeds > active_limit, there's an ambiguity whether the downloads should be satisfied first or the seeds. To disambiguate this case, the settings_pack::auto_manage_prefer_seeds determines whether seeds are preferred or not.

inactive torrents

Torrents that are not transferring any bytes (downloading or uploading) have a relatively low cost to be started. It's possible to exempt such torrents from the download and seed queues by setting settings_pack::dont_count_slow_torrents to true.

Since it sometimes may take a few minutes for a newly started torrent to find peers and be unchoked, or find peers that are interested in requesting data, torrents are not considered inactive immadiately. There must be an extended period of no transfers before it is considered inactive and exempt from the queuing limits.

fast resume

The fast resume mechanism is a way to remember which pieces are downloaded and where they are put between sessions. You can generate fast resume data by calling save_resume_data() on torrent_handle. You can then save this data to disk and use it when resuming the torrent. libtorrent will not check the piece hashes then, and rely on the information given in the fast-resume data. The fast-resume data also contains information about which blocks, in the unfinished pieces, were downloaded, so it will not have to start from scratch on the partially downloaded pieces.

To use the fast-resume data you simply give it to async_add_torrent() and add_torrent(), and it will skip the time consuming checks. It may have to do the checking anyway, if the fast-resume data is corrupt or doesn't fit the storage for that torrent, then it will not trust the fast-resume data and just do the checking.

file format

The file format is a bencoded dictionary containing the following fields:

file-format string: "libtorrent resume file"
file-version integer: 1
info-hash string, the info hash of the torrent this data is saved for.
blocks per piece integer, the number of blocks per piece. Must be: piece_size / (16 * 1024). Clamped to be within the range [1, 256]. It is the number of blocks per (normal sized) piece. Usually each block is 16 * 1024 bytes in size. But if piece size is greater than 4 megabytes, the block size will increase.
pieces A string with piece flags, one character per piece. Bit 1 means we have that piece. Bit 2 means we have verified that this piece is correct. This only applies when the torrent is in seed_mode.
slots list of integers. The list maps slots to piece indices. It tells which piece is on which slot. If piece index is -2 it means it is free, that there's no piece there. If it is -1, means the slot isn't allocated on disk yet. The pieces have to meet the following requirement:
total_uploaded integer. The number of bytes that have been uploaded in total for this torrent.
total_downloaded integer. The number of bytes that have been downloaded in total for this torrent.
active_time integer. The number of seconds this torrent has been active. i.e. not paused.
seeding_time integer. The number of seconds this torrent has been active and seeding.
num_seeds integer. An estimate of the number of seeds on this torrent when the resume data was saved. This is scrape data or based on the peer list if scrape data is unavailable.
num_downloaders integer. An estimate of the number of downloaders on this torrent when the resume data was last saved. This is used as an initial estimate until we acquire up-to-date scrape info.
upload_rate_limit integer. In case this torrent has a per-torrent upload rate limit, this is that limit. In bytes per second.
download_rate_limit integer. The download rate limit for this torrent in case one is set, in bytes per second.
max_connections integer. The max number of peer connections this torrent may have, if a limit is set.
max_uploads integer. The max number of unchoked peers this torrent may have, if a limit is set.
seed_mode integer. 1 if the torrent is in seed mode, 0 otherwise.
file_priority list of integers. One entry per file in the torrent. Each entry is the priority of the file with the same index.
piece_priority string of bytes. Each byte is interpreted as an integer and is the priority of that piece.
auto_managed integer. 1 if the torrent is auto managed, otherwise 0.
sequential_download integer. 1 if the torrent is in sequential download mode, 0 otherwise.
paused integer. 1 if the torrent is paused, 0 otherwise.
trackers list of lists of strings. The top level list lists all tracker tiers. Each second level list is one tier of trackers.
mapped_files list of strings. If any file in the torrent has been renamed, this entry contains a list of all the filenames. In the same order as in the torrent file.
url-list list of strings. List of url-seed URLs used by this torrent. The urls are expected to be properly encoded and not contain any illegal url characters.
httpseeds list of strings. List of httpseed URLs used by this torrent. The urls are expected to be properly encoded and not contain any illegal url characters.
merkle tree string. In case this torrent is a merkle torrent, this is a string containing the entire merkle tree, all nodes, including the root and all leaves. The tree is not necessarily complete, but complete enough to be able to send any piece that we have, indicated by the have bitmask.
save_path string. The save path where this torrent was saved. This is especially useful when moving torrents with move_storage() since this will be updated.
peers string. This string contains IPv4 and port pairs of peers we were connected to last session. The endpoints are in compact representation. 4 bytes IPv4 address followed by 2 bytes port. Hence, the length of this string should be divisible by 6.
banned_peers string. This string has the same format as peers but instead represent IPv4 peers that we have banned.
peers6 string. This string contains IPv6 and port pairs of peers we were connected to last session. The endpoints are in compact representation. 16 bytes IPv6 address followed by 2 bytes port. The length of this string should be divisible by 18.
banned_peers6 string. This string has the same format as peers6 but instead represent IPv6 peers that we have banned.
info If this field is present, it should be the info-dictionary of the torrent this resume data is for. Its SHA-1 hash must match the one in the info-hash field. When present, the torrent is loaded from here, meaning the torrent can be added purely from resume data (no need to load the .torrent file separately). This may have performance advantages.
unfinished

list of dictionaries. Each dictionary represents an piece, and has the following layout:

piece integer, the index of the piece this entry refers to.
bitmask string, a binary bitmask representing the blocks that have been downloaded in this piece.
adler32 The adler32 checksum of the data in the blocks specified by bitmask.
file sizes list where each entry corresponds to a file in the file list in the metadata. Each entry has a list of two values, the first value is the size of the file in bytes, the second is the time stamp when the last time someone wrote to it. This information is used to compare with the files on disk. All the files must match exactly this information in order to consider the resume data as current. Otherwise a full re-check is issued.
allocation The allocation mode for the storage. Can be either full or sparse. If this is full, the file sizes and timestamps are disregarded. Pieces are assumed not to have moved around even if the files have been modified after the last resume data checkpoint.

storage allocation

There are two modes in which storage (files on disk) are allocated in libtorrent.

  1. The traditional full allocation mode, where the entire files are filled up with zeros before anything is downloaded. Files are allocated on demand, the first time anything is written to them. The main benefit of this mode is that it avoids creating heavily fragmented files.
  2. The sparse allocation, sparse files are used, and pieces are downloaded directly to where they belong. This is the recommended (and default) mode.

sparse allocation

On filesystems that supports sparse files, this allocation mode will only use as much space as has been downloaded.

The main drawback of this mode is that it may create heavily fragmented files.

  • It does not require an allocation pass on startup.

full allocation

When a torrent is started in full allocation mode, the disk-io thread will make sure that the entire storage is allocated, and fill any gaps with zeros. It will of course still check for existing pieces and fast resume data. The main drawbacks of this mode are:

  • It may take longer to start the torrent, since it will need to fill the files with zeroes. This delay is linear to the size of the download.
  • The download may occupy unnecessary disk space between download sessions.
  • Disk caches usually perform poorly with random access to large files and may slow down the download some.

The benefits of this mode are:

  • Downloaded pieces are written directly to their final place in the files and the total number of disk operations will be fewer and may also play nicer to filesystems' file allocation, and reduce fragmentation.
  • No risk of a download failing because of a full disk during download, once all files have been created.

HTTP seeding

There are two kinds of HTTP seeding. One with that assumes a smart (and polite) client and one that assumes a smart server. These are specified in BEP 19 and BEP 17 respectively.

libtorrent supports both. In the libtorrent source code and API, BEP 19 urls are typically referred to as url seeds and BEP 17 urls are typically referred to as HTTP seeds.

The libtorrent implementation of BEP 19 assumes that, if the URL ends with a slash ('/'), the filename should be appended to it in order to request pieces from that file. The way this works is that if the torrent is a single-file torrent, only that filename is appended. If the torrent is a multi-file torrent, the torrent's name '/' the file name is appended. This is the same directory structure that libtorrent will download torrents into.

dynamic loading of torrent files

libtorrent has a feature that can unload idle torrents from memory. The purpose of this is to support being active on many more torrents than the RAM permits. This is useful for both embedded devices that have limited RAM and servers seeding tens of thousands of torrents.

The most significant parts of loaded torrents that use RAM are the piece hashes (20 bytes per piece) and the file list. The entire info-dictionary of the .torrent file is kept in RAM.

In order to activate the dynamic loading of torrent files, set the load function on the session. See set_load_function().

When a load function is set on the session, the dynamic load/unload feature is enabled. Torrents are kept in an LRU. Every time an operation is performed, on a torrent or from a peer, that requires the metadata of the torrent to be loaded, the torrent is bumped up in the LRU. When a torrent is paused or queued, it is demoted to the least recently used torrent in the LRU, since it's a good candidate for eviction.

To configure how many torrents are allowed to be loaded at the same time, set settings_pack::active_loaded_limit on the session.

Torrents can be exempt from being unloaded by being pinned. Pinned torrents still count against the limit, but are never considered for eviction. You can either pin a torrent when adding it, in add_torrent_params (see async_add_torrent() and add_torrent()), or after ading it with the set_pinned() function on torrent_handle.

Torrents that start out without metadata (e.g. magnet links or http downloads) are automatically pinned. This is important in order to give the client a chance to save the metadata to disk once it's received (see metadata_received_alert).

Once the metadata is saved to disk, it might make sense to unpin the torrent.

piece picker

The piece picker in libtorrent has the following features:

  • rarest first
  • sequential download
  • random pick
  • reverse order picking
  • parole mode
  • prioritize partial pieces
  • prefer whole pieces
  • piece affinity by speed category
  • piece priorities

internal representation

It is optimized by, at all times, keeping a list of pieces ordered by rarity, randomly shuffled within each rarity class. This list is organized as a single vector of contigous memory in RAM, for optimal memory locality and to eliminate heap allocations and frees when updating rarity of pieces.

Expensive events, like a peer joining or leaving, are evaluated lazily, since it's cheaper to rebuild the whole list rather than updating every single piece in it. This means as long as no blocks are picked, peers joining and leaving is no more costly than a single peer joining or leaving. Of course the special cases of peers that have all or no pieces are optimized to not require rebuilding the list.

picker strategy

The normal mode of the picker is of course rarest first, meaning pieces that few peers have are preferred to be downloaded over pieces that more peers have. This is a fundamental algorithm that is the basis of the performance of bittorrent. However, the user may set the piece picker into sequential download mode. This mode simply picks pieces sequentially, always preferring lower piece indices.

When a torrent starts out, picking the rarest pieces means increased risk that pieces won't be completed early (since there are only a few peers they can be downloaded from), leading to a delay of having any piece to offer to other peers. This lack of pieces to trade, delays the client from getting started into the normal tit-for-tat mode of bittorrent, and will result in a long ramp-up time. The heuristic to mitigate this problem is to, for the first few pieces, pick random pieces rather than rare pieces. The threshold for when to leave this initial picker mode is determined by settings_pack::initial_picker_threshold.

reverse order

An orthogonal setting is reverse order, which is used for snubbed peers. Snubbed peers are peers that appear very slow, and might have timed out a piece request. The idea behind this is to make all snubbed peers more likely to be able to do download blocks from the same piece, concentrating slow peers on as few pieces as possible. The reverse order means that the most common pieces are picked, instead of the rarest pieces (or in the case of sequential download, the last pieces, intead of the first).

parole mode

Peers that have participated in a piece that failed the hash check, may be put in parole mode. This means we prefer downloading a full piece from this peer, in order to distinguish which peer is sending corrupt data. Whether to do this is or not is controlled by settings_pack::use_parole_mode.

In parole mode, the piece picker prefers picking one whole piece at a time for a given peer, avoiding picking any blocks from a piece any other peer has contributed to (since that would defeat the purpose of parole mode).

prioritize partial pieces

This setting determines if partially downloaded or requested pieces should always be preferred over other pieces. The benefit of doing this is that the number of partial pieces is minimized (and hence the turn-around time for downloading a block until it can be uploaded to others is minimized). It also puts less stress on the disk cache, since fewer partial pieces need to be kept in the cache. Whether or not to enable this is controlled by setting_pack::prioritize_partial_pieces.

The main benefit of not prioritizing partial pieces is that the rarest first algorithm gets to have more influence on which pieces are picked. The picker is more likely to truly pick the rarest piece, and hence improving the performance of the swarm.

This setting is turned on automatically whenever the number of partial pieces in the piece picker exceeds the number of peers we're connected to times 1.5. This is in order to keep the waste of partial pieces to a minimum, but still prefer rarest pieces.

prefer whole pieces

The prefer whole pieces setting makes the piece picker prefer picking entire pieces at a time. This is used by web connections (both http seeding standards), in order to be able to coalesce the small bittorrent requests to larger HTTP requests. This significantly improves performance when downloading over HTTP.

It is also used by peers that are downloading faster than a certain threshold. The main advantage is that these peers will better utilize the other peer's disk cache, by requesting all blocks in a single piece, from the same peer.

This threshold is controlled by the settings_pack::whole_pieces_threshold setting.

TODO: piece priorities

predictive piece announce

In order to improve performance, libtorrent supports a feature called predictive piece announce. When enabled, it will make libtorrent announce that we have pieces to peers, before we truly have them. The most important case is to announce a piece as soon as it has been downloaded and passed the hash check, but not yet been written to disk. In this case, there is a risk the piece will fail to be written to disk, in which case we won't have the piece anymore, even though we announced it to peers.

The other case is when we're very close to completing the download of a piece and assume it will pass the hash check, we can announce it to peers to make it available one round-trip sooner than otherwise. This lets libtorrent start uploading the piece to interested peers immediately when the piece complete, instead of waiting one round-trip for the peers to request it.

This makes for the implementation slightly more complicated, since piece will have more states and more complicated transitions. For instance, a piece could be:

  1. hashed but not fully written to disk
  2. fully written to disk but not hashed
  3. not fully downloaded
  4. downloaded and hash checked

Once a piece is fully downloaded, the hash check could complete before any of the write operations or it could complete after all write operations are complete.

peer classes

The peer classes feature in libtorrent allows a client to define custom groups of peers and rate limit them individually. Each such group is called a peer class. There are a few default peer classes that are always created:

  • global - all peers belong to this class, except peers on the local network
  • local peers - all peers on the local network belongs to this class TCP peers
  • tcp class - all peers connected over TCP belong to this class

The TCP peers class is used by the uTP/TCP balancing logic, if it's enabled, to throttle TCP peers. The global and local classes are used to adjust the global rate limits.

When the rate limits are adjusted for a specific torrent, a class is created implicitly for that torrent.

The default peer class IDs are defined as enums in the session class:

enum {
        global_peer_class_id,
        tcp_peer_class_id,
        local_peer_class_id
};

A peer class can be considered a more general form of lables that some clients have. Peer classes however are not just applied to torrents, but ultimately the peers.

Peer classes can be created with the create_peer_class() call (on the session object), and deleted with the delete_peer_class() call.

Peer classes are configured with the set_peer_class() get_peer_class() calls.

Custom peer classes can be assigned to torrents, with the ??? call, in which case all its peers will belong to the class. They can also be assigned based on the peer's IP address. See set_peer_class_filter() for more information.

SSL torrents

Torrents may have an SSL root (CA) certificate embedded in them. Such torrents are called SSL torrents. An SSL torrent talks to all bittorrent peers over SSL. The protocols are layered like this:

utp_stack.png

During the SSL handshake, both peers need to authenticate by providing a certificate that is signed by the CA certificate found in the .torrent file. These peer certificates are expected to be privided to peers through some other means than bittorrent. Typically by a peer generating a certificate request which is sent to the publisher of the torrent, and the publisher returning a signed certificate.

In libtorrent, set_ssl_certificate() in torrent_handle is used to tell libtorrent where to find the peer certificate and the private key for it. When an SSL torrent is loaded, the torrent_need_cert_alert is posted to remind the user to provide a certificate.

A peer connecting to an SSL torrent MUST provide the SNI TLS extension (server name indication). The server name is the hex encoded info-hash of the torrent to connect to. This is required for the client accepting the connection to know which certificate to present.

SSL connections are accepted on a separate socket from normal bittorrent connections. To pick which port the SSL socket should bind to, set settings_pack::ssl_listen to a different port. It defaults to port 4433. This setting is only taken into account when the normal listen socket is opened (i.e. just changing this setting won't necessarily close and re-open the SSL socket). To not listen on an SSL socket at all, set ssl_listen to 0.

This feature is only available if libtorrent is build with openssl support (TORRENT_USE_OPENSSL) and requires at least openSSL version 1.0, since it needs SNI support.

Peer certificates must have at least one SubjectAltName field of type dNSName. At least one of the fields must exactly match the name of the torrent. This is a byte-by-byte comparison, the UTF-8 encoding must be identical (i.e. there's no unicode normalization going on). This is the recommended way of verifying certificates for HTTPS servers according to RFC 2818. Note the difference that for torrents only dNSName fields are taken into account (not IP address fields). The most specific (i.e. last) Common Name field is also taken into account if no SubjectAltName did not match.

If any of these fields contain a single asterisk ("*"), the certificate is considered covering any torrent, allowing it to be reused for any torrent.

The purpose of matching the torrent name with the fields in the peer certificate is to allow a publisher to have a single root certificate for all torrents it distributes, and issue separate peer certificates for each torrent. A peer receiving a certificate will not necessarily be able to access all torrents published by this root certificate (only if it has a "star cert").

testing

To test incoming SSL connections to an SSL torrent, one can use the following openssl command:

openssl s_client -cert <peer-certificate>.pem -key <peer-private-key>.pem -CAfile \
   <torrent-cert>.pem -debug -connect 127.0.0.1:4433 -tls1 -servername <info-hash>

To create a root certificate, the Distinguished Name (DN) is not taken into account by bittorrent peers. You still need to specify something, but from libtorrent's point of view, it doesn't matter what it is. libtorrent only makes sure the peer certificates are signed by the correct root certificate.

One way to create the certificates is to use the CA.sh script that comes with openssl, like thisi (don't forget to enter a common Name for the certificate):

CA.sh -newca
CA.sh -newreq
CA.sh -sign

The torrent certificate is located in ./demoCA/private/demoCA/cacert.pem, this is the pem file to include in the .torrent file.

The peer's certificate is located in ./newcert.pem and the certificate's private key in ./newkey.pem.

session statistics

libtorrent provides a mechanism to query performance and statistics counters from its internals. This is primarily useful for troubleshooting of production systems and performance tuning.

The statistics consists of two fundamental types. counters and gauges. A counter is a monotonically increasing value, incremented every time some event occurs. For example, every time the network thread wakes up because a socket became readable will increment a counter. Another example is every time a socket receives n bytes, a counter is incremented by n.

Counters are the most flexible of metrics. It allows the program to sample the counter at any interval, and calculate average rates of increments to the counter. Some events may be rare and need to be sampled over a longer period in order to get userful rates, where other events may be more frequent and evenly distributed that sampling it frequently yields useful values. Counters also provides accurate overall counts. For example, converting samples of a download rate into a total transfer count is not accurate and takes more samples. Converting an increasing counter into a rate is easy and flexible.

Gauges measure the instantaneous state of some kind. This is used for metrics that are not counting events or flows, but states that can fluctuate. For example, the number of torrents that are currenly being downloaded.

It's important to know whether a value is a counter or a gauge in order to interpret it correctly. In order to query libtorrent for which counters and gauges are available, call session_stats_metrics(). This will return metadata about the values available for inspection in libtorrent. It will include whether a value is a counter or a gauge. The key information it includes is the index used to extract the actual measurements for a specific counter or gauge.

In order to take a sample, call post_session_stats() in the session object. This will result in a session_stats_alert being posted. In this alert object, there is an array of values, these values make up the sample. The value index in the stats metric indicates which index the metric's value is stored in.

The mapping between metric and value is not stable across versions of libtorrent. Always query the metrics first, to find out the index at which the value is stored, before interpreting the values array in the session_stats_alert. The mapping will not change during the runtime of your process though, it's tied to a specific libtorrent version. You only have to query the mapping once on startup (or every time libtorrent.so is loaded, if it's done dynamically).

The available stats metrics are:

name type
peer.error_peers counter
peer.disconnected_peers counter

error_peers is the total number of peer disconnects caused by an error (not initiated by this client) and disconnected initiated by this client (disconnected_peers).

name type
peer.eof_peers counter
peer.connreset_peers counter
peer.connrefused_peers counter
peer.connaborted_peers counter
peer.notconnected_peers counter
peer.perm_peers counter
peer.buffer_peers counter
peer.unreachable_peers counter
peer.broken_pipe_peers counter
peer.addrinuse_peers counter
peer.no_access_peers counter
peer.invalid_arg_peers counter
peer.aborted_peers counter

these counters break down the peer errors into more specific categories. These errors are what the underlying transport reported (i.e. TCP or uTP)

name type
peer.piece_requests counter
peer.max_piece_requests counter
peer.invalid_piece_requests counter
peer.choked_piece_requests counter
peer.cancelled_piece_requests counter
peer.piece_rejects counter

the total number of incoming piece requests we've received followed by the number of rejected piece requests for various reasons. max_piece_requests mean we already had too many outstanding requests from this peer, so we rejected it. cancelled_piece_requests are ones where the other end explicitly asked for the piece to be rejected.

name type
peer.error_incoming_peers counter
peer.error_outgoing_peers counter

these counters break down the peer errors into whether they happen on incoming or outgoing peers.

name type
peer.error_rc4_peers counter
peer.error_encrypted_peers counter

these counters break down the peer errors into whether they happen on encrypted peers (just encrypted handshake) and rc4 peers (full stream encryption). These can indicate whether encrypted peers are more or less likely to fail

name type
peer.error_tcp_peers counter
peer.error_utp_peers counter

these counters break down the peer errors into whether they happen on uTP peers or TCP peers. these may indicate whether one protocol is more error prone

name type
peer.connect_timeouts counter
peer.uninteresting_peers counter
peer.timeout_peers counter
peer.no_memory_peers counter
peer.too_many_peers counter
peer.transport_timeout_peers counter
peer.num_banned_peers counter
peer.banned_for_hash_failure counter
peer.connection_attempts counter
peer.connection_attempt_loops counter
peer.incoming_connections counter

these counters break down the reasons to disconnect peers.

name type
peer.num_tcp_peers gauge
peer.num_socks5_peers gauge
peer.num_http_proxy_peers gauge
peer.num_utp_peers gauge
peer.num_i2p_peers gauge
peer.num_ssl_peers gauge
peer.num_ssl_socks5_peers gauge
peer.num_ssl_http_proxy_peers gauge
peer.num_ssl_utp_peers gauge
peer.num_peers_half_open gauge
peer.num_peers_connected gauge
peer.num_peers_up_interested gauge
peer.num_peers_down_interested gauge
peer.num_peers_up_unchoked_all gauge
peer.num_peers_up_unchoked_optimistic gauge
peer.num_peers_up_unchoked gauge
peer.num_peers_down_unchoked gauge
peer.num_peers_up_requests gauge
peer.num_peers_down_requests gauge
peer.num_peers_end_game gauge
peer.num_peers_up_disk gauge
peer.num_peers_down_disk gauge

the number of peer connections for each kind of socket. these counts include half-open (connecting) peers. num_peers_up_unchoked_all is the total number of unchoked peers, whereas num_peers_up_unchoked only are unchoked peers that count against the limit (i.e. excluding peers that are unchoked because the limit doesn't apply to them). num_peers_up_unchoked_optimistic is the number of optimistically unchoked peers.

name type
net.on_read_counter counter
net.on_write_counter counter
net.on_tick_counter counter
net.on_lsd_counter counter
net.on_lsd_peer_counter counter
net.on_udp_counter counter
net.on_accept_counter counter
net.on_disk_queue_counter counter
net.on_disk_counter counter

These counters count the number of times the network thread wakes up for each respective reason. If these counters are very large, it may indicate a performance issue, causing the network thread to wake up too ofte, wasting CPU. mitigate it by increasing buffers and limits for the specific trigger that wakes up the thread.

name type
net.sent_payload_bytes counter
net.sent_bytes counter
net.sent_ip_overhead_bytes counter
net.sent_tracker_bytes counter
net.recv_payload_bytes counter
net.recv_bytes counter
net.recv_ip_overhead_bytes counter
net.recv_tracker_bytes counter

total number of bytes sent and received by the session

name type
net.limiter_up_queue gauge
net.limiter_down_queue gauge

the number of sockets currently waiting for upload and download bandwidht from the rate limiter.

name type
net.limiter_up_bytes gauge
net.limiter_down_bytes gauge

the number of upload and download bytes waiting to be handed out from the rate limiter.

name type
net.recv_failed_bytes counter

the number of bytes downloaded that had to be discarded because they failed the hash check

name type
net.recv_redundant_bytes counter

the number of downloaded bytes that were discarded because they were downloaded multiple times (from different peers)

name type
net.has_incoming_connections gauge

is false by default and set to true when the first incoming connection is established this is used to know if the client is behind NAT or not.

name type
ses.num_checking_torrents gauge
ses.num_stopped_torrents gauge
ses.num_upload_only_torrents gauge
ses.num_downloading_torrents gauge
ses.num_seeding_torrents gauge
ses.num_queued_seeding_torrents gauge
ses.num_queued_download_torrents gauge
ses.num_error_torrents gauge

these gauges count the number of torrents in different states. Each torrent only belongs to one of these states. For torrents that could belong to multiple of these, the most prominent in picked. For instance, a torrent with an error counts as an error-torrent, regardless of its other state.

name type
ses.non_filter_torrents gauge

the number of torrents that don't have the IP filter applied to them.

name type
ses.num_loaded_torrents gauge
ses.num_pinned_torrents gauge

the number of torrents that are currently loaded

name type
ses.num_piece_passed counter
ses.num_piece_failed counter
ses.num_have_pieces counter
ses.num_total_pieces_added counter

these count the number of times a piece has passed the hash check, the number of times a piece was successfully written to disk and the number of total possible pieces added by adding torrents. e.g. when adding a torrent with 1000 piece, num_total_pieces_added is incremented by 1000.

name type
ses.torrent_evicted_counter counter

this counts the number of times a torrent has been evicted (only applies when dynamic loading of torrent files is enabled).

name type
ses.num_unchoke_slots gauge

the number of allowed unchoked peers

name type
ses.num_incoming_choke counter
ses.num_incoming_unchoke counter
ses.num_incoming_interested counter
ses.num_incoming_not_interested counter
ses.num_incoming_have counter
ses.num_incoming_bitfield counter
ses.num_incoming_request counter
ses.num_incoming_piece counter
ses.num_incoming_cancel counter
ses.num_incoming_dht_port counter
ses.num_incoming_suggest counter
ses.num_incoming_have_all counter
ses.num_incoming_have_none counter
ses.num_incoming_reject counter
ses.num_incoming_allowed_fast counter
ses.num_incoming_ext_handshake counter
ses.num_incoming_pex counter
ses.num_incoming_metadata counter
ses.num_incoming_extended counter
ses.num_outgoing_choke counter
ses.num_outgoing_unchoke counter
ses.num_outgoing_interested counter
ses.num_outgoing_not_interested counter
ses.num_outgoing_have counter
ses.num_outgoing_bitfield counter
ses.num_outgoing_request counter
ses.num_outgoing_piece counter
ses.num_outgoing_cancel counter
ses.num_outgoing_dht_port counter
ses.num_outgoing_suggest counter
ses.num_outgoing_have_all counter
ses.num_outgoing_have_none counter
ses.num_outgoing_reject counter
ses.num_outgoing_allowed_fast counter
ses.num_outgoing_ext_handshake counter
ses.num_outgoing_pex counter
ses.num_outgoing_metadata counter
ses.num_outgoing_extended counter

bittorrent message counters. These counters are incremented every time a message of the corresponding type is received from or sent to a bittorrent peer.

name type
ses.waste_piece_timed_out counter
ses.waste_piece_cancelled counter
ses.waste_piece_unknown counter
ses.waste_piece_seed counter
ses.waste_piece_end_game counter
ses.waste_piece_closing counter

the number of wasted downloaded bytes by reason of the bytes being wasted.

name type
picker.piece_picker_partial_loops counter
picker.piece_picker_suggest_loops counter
picker.piece_picker_sequential_loops counter
picker.piece_picker_reverse_rare_loops counter
picker.piece_picker_rare_loops counter
picker.piece_picker_rand_start_loops counter
picker.piece_picker_rand_loops counter
picker.piece_picker_busy_loops counter

the number of pieces considered while picking pieces

name type
picker.reject_piece_picks counter
picker.unchoke_piece_picks counter
picker.incoming_redundant_piece_picks counter
picker.incoming_piece_picks counter
picker.end_game_piece_picks counter
picker.snubbed_piece_picks counter
picker.interesting_piece_picks counter
picker.hash_fail_piece_picks counter

This breaks down the piece picks into the event that triggered it

name type
disk.write_cache_blocks gauge
disk.read_cache_blocks gauge

These gauges indicate how many blocks are currently in use as dirty disk blocks (write_cache_blocks) and read cache blocks, respectively. deprecates cache_status::read_cache_size. The sum of these gauges deprecates cache_status::cache_size.

name type
disk.request_latency gauge

the number of microseconds it takes from receiving a request from a peer until we're sending the response back on the socket.

name type
disk.pinned_blocks gauge
disk.disk_blocks_in_use gauge

disk_blocks_in_use indicates how many disk blocks are currently in use, either as dirty blocks waiting to be written or blocks kept around in the hope that a peer will request it or in a peer send buffer. This gauge deprecates cache_status::total_used_buffers.

name type
disk.queued_disk_jobs gauge
disk.num_running_disk_jobs gauge
disk.num_read_jobs gauge
disk.num_write_jobs gauge
disk.num_jobs gauge
disk.blocked_disk_jobs gauge
disk.num_writing_threads gauge
disk.num_running_threads gauge

queued_disk_jobs is the number of disk jobs currently queued, waiting to be executed by a disk thread. Deprecates cache_status::job_queue_length.

name type
disk.queued_write_bytes gauge
disk.arc_mru_size gauge
disk.arc_mru_ghost_size gauge
disk.arc_mfu_size gauge
disk.arc_mfu_ghost_size gauge
disk.arc_write_size gauge
disk.arc_volatile_size gauge

the number of bytes we have sent to the disk I/O thread for writing. Every time we hear back from the disk I/O thread with a completed write job, this is updated to the number of bytes the disk I/O thread is actually waiting for to be written (as opposed to bytes just hanging out in the cache)

name type
disk.num_blocks_written counter
disk.num_blocks_read counter

the number of blocks written and read from disk in total. A block is 16 kiB. num_blocks_written and num_blocks_read deprecates cache_status::blocks_written and cache_status::blocks_read respectively.

name type
disk.num_blocks_hashed counter

the total number of blocks run through SHA-1 hashing

name type
disk.num_blocks_cache_hits counter

the number of blocks read from the disk cache Deprecates cache_info::blocks_read_hit.

name type
disk.num_write_ops counter
disk.num_read_ops counter

the number of disk I/O operation for reads and writes. One disk operation may transfer more then one block. These counters deprecates cache_status::writes and cache_status::reads.

name type
disk.num_read_back counter

the number of blocks that had to be read back from disk in order to hash a piece (when verifying against the piece hash)

name type
disk.disk_read_time counter
disk.disk_write_time counter
disk.disk_hash_time counter
disk.disk_job_time counter

cumulative time spent in various disk jobs, as well as total for all disk jobs. Measured in microseconds

name type
disk.num_fenced_read gauge
disk.num_fenced_write gauge
disk.num_fenced_hash gauge
disk.num_fenced_move_storage gauge
disk.num_fenced_release_files gauge
disk.num_fenced_delete_files gauge
disk.num_fenced_check_fastresume gauge
disk.num_fenced_save_resume_data gauge
disk.num_fenced_rename_file gauge
disk.num_fenced_stop_torrent gauge
disk.num_fenced_cache_piece gauge
disk.num_fenced_flush_piece gauge
disk.num_fenced_flush_hashed gauge
disk.num_fenced_flush_storage gauge
disk.num_fenced_trim_cache gauge
disk.num_fenced_file_priority gauge
disk.num_fenced_load_torrent gauge
disk.num_fenced_clear_piece gauge
disk.num_fenced_tick_storage gauge

for each kind of disk job, a counter of how many jobs of that kind are currently blocked by a disk fence

name type
dht.dht_nodes gauge

The number of nodes in the DHT routing table

name type
dht.dht_node_cache gauge

The number of replacement nodes in the DHT routing table

name type
dht.dht_torrents gauge

the number of torrents currently tracked by our DHT node

name type
dht.dht_peers gauge

the number of peers currently tracked by our DHT node

name type
dht.dht_immutable_data gauge

the number of immutable data items tracked by our DHT node

name type
dht.dht_mutable_data gauge

the number of mutable data items tracked by our DHT node

name type
dht.dht_allocated_observers gauge

the number of RPC observers currently allocated

name type
dht.dht_messages_in counter
dht.dht_messages_out counter

the total number of DHT messages sent and received

name type
dht.dht_messages_out_dropped counter

the number of outgoing messages that failed to be sent

name type
dht.dht_bytes_in counter
dht.dht_bytes_out counter

the total number of bytes sent and received by the DHT

name type
dht.dht_ping_in counter
dht.dht_ping_out counter
dht.dht_find_node_in counter
dht.dht_find_node_out counter
dht.dht_get_peers_in counter
dht.dht_get_peers_out counter
dht.dht_announce_peer_in counter
dht.dht_announce_peer_out counter
dht.dht_get_in counter
dht.dht_get_out counter
dht.dht_put_in counter
dht.dht_put_out counter

the number of DHT messages we've sent and received by kind.

name type
dht.dht_invalid_announce counter
dht.dht_invalid_get_peers counter
dht.dht_invalid_put counter
dht.dht_invalid_get counter

the number of failed incoming DHT requests by kind of request

name type
utp.utp_packet_loss counter
utp.utp_timeout counter
utp.utp_packets_in counter
utp.utp_packets_out counter
utp.utp_fast_retransmit counter
utp.utp_packet_resend counter
utp.utp_samples_above_target counter
utp.utp_samples_below_target counter
utp.utp_payload_pkts_in counter
utp.utp_payload_pkts_out counter
utp.utp_invalid_pkts_in counter
utp.utp_redundant_pkts_in counter

uTP counters. Each counter represents the number of time each event has occurred.

name type
utp.num_utp_idle gauge
utp.num_utp_syn_sent gauge
utp.num_utp_connected gauge
utp.num_utp_fin_sent gauge
utp.num_utp_close_wait gauge
utp.num_utp_deleted gauge

the number of uTP sockets in each respective state

name type
sock_bufs.socket_send_size3 counter
sock_bufs.socket_send_size4 counter
sock_bufs.socket_send_size5 counter
sock_bufs.socket_send_size6 counter
sock_bufs.socket_send_size7 counter
sock_bufs.socket_send_size8 counter
sock_bufs.socket_send_size9 counter
sock_bufs.socket_send_size10 counter
sock_bufs.socket_send_size11 counter
sock_bufs.socket_send_size12 counter
sock_bufs.socket_send_size13 counter
sock_bufs.socket_send_size14 counter
sock_bufs.socket_send_size15 counter
sock_bufs.socket_send_size16 counter
sock_bufs.socket_send_size17 counter
sock_bufs.socket_send_size18 counter
sock_bufs.socket_send_size19 counter
sock_bufs.socket_send_size20 counter
sock_bufs.socket_recv_size3 counter
sock_bufs.socket_recv_size4 counter
sock_bufs.socket_recv_size5 counter
sock_bufs.socket_recv_size6 counter
sock_bufs.socket_recv_size7 counter
sock_bufs.socket_recv_size8 counter
sock_bufs.socket_recv_size9 counter
sock_bufs.socket_recv_size10 counter
sock_bufs.socket_recv_size11 counter
sock_bufs.socket_recv_size12 counter
sock_bufs.socket_recv_size13 counter
sock_bufs.socket_recv_size14 counter
sock_bufs.socket_recv_size15 counter
sock_bufs.socket_recv_size16 counter
sock_bufs.socket_recv_size17 counter
sock_bufs.socket_recv_size18 counter
sock_bufs.socket_recv_size19 counter
sock_bufs.socket_recv_size20 counter

the buffer sizes accepted by socket send and receive calls respectively. The larger the buffers are, the more efficient, because it reqire fewer system calls per byte. The size is 1 << n, where n is the number at the end of the counter name. i.e. 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576 bytes

home

Core

add_torrent_params

Declared in "libtorrent/add_torrent_params.hpp"

The add_torrent_params is a parameter pack for adding torrents to a session. The key fields when adding a torrent are:

  • ti - when you have a .torrent file
  • url - when you have a magnet link
  • info_hash - when all you have is an info-hash (this is similar to a magnet link)

one of those fields need to be set. Another mandatory field is save_path. The add_torrent_params object is passed into one of the session::add_torrent() overloads or session::async_add_torrent().

If you only specify the info-hash, the torrent file will be downloaded from peers, which requires them to support the metadata extension. For the metadata extension to work, libtorrent must be built with extensions enabled (TORRENT_DISABLE_EXTENSIONS must not be defined). It also takes an optional name argument. This may be left empty in case no name should be assigned to the torrent. In case it's not, the name is used for the torrent as long as it doesn't have metadata. See torrent_handle::name.

struct add_torrent_params
{
   add_torrent_params (storage_constructor_type sc = default_storage_constructor);

   enum flags_t
   {
      flag_seed_mode,
      flag_override_resume_data,
      flag_upload_mode,
      flag_share_mode,
      flag_apply_ip_filter,
      flag_paused,
      flag_auto_managed,
      flag_duplicate_is_error,
      flag_merge_resume_trackers,
      flag_update_subscribe,
      flag_super_seeding,
      flag_sequential_download,
      flag_use_resume_save_path,
      flag_pinned,
      flag_merge_resume_http_seeds,
      flag_stop_when_ready,
   };

   int version;
   boost::shared_ptr<torrent_info> ti;
   std::vector<std::string> trackers;
   std::vector<std::string> url_seeds;
   std::vector<std::pair<std::string, int> > dht_nodes;
   std::string name;
   std::string save_path;
   std::vector<char> resume_data;
   storage_mode_t storage_mode;
   storage_constructor_type storage;
   void* userdata;
   std::vector<boost::uint8_t> file_priorities;
   std::string trackerid;
   std::string url;
   std::string uuid;
   std::string source_feed_url;
   boost::uint64_t flags;
   sha1_hash info_hash;
   int max_uploads;
   int max_connections;
   int upload_limit;
   int download_limit;
};

add_torrent_params()

add_torrent_params (storage_constructor_type sc = default_storage_constructor);

The constructor can be used to initialize the storage constructor, which determines the storage mechanism for the downloaded or seeding data for the torrent. For more information, see the storage field.

enum flags_t

Declared in "libtorrent/add_torrent_params.hpp"

name value description
flag_seed_mode 1

If flag_seed_mode is set, libtorrent will assume that all files are present for this torrent and that they all match the hashes in the torrent file. Each time a peer requests to download a block, the piece is verified against the hash, unless it has been verified already. If a hash fails, the torrent will automatically leave the seed mode and recheck all the files. The use case for this mode is if a torrent is created and seeded, or if the user already know that the files are complete, this is a way to avoid the initial file checks, and significantly reduce the startup time.

Setting flag_seed_mode on a torrent without metadata (a .torrent file) is a no-op and will be ignored.

If resume data is passed in with this torrent, the seed mode saved in there will override the seed mode you set here.

flag_override_resume_data 2 If flag_override_resume_data is set, flags set for this torrent in this add_torrent_params object will take precedence over whatever states are saved in the resume data. For instance, the paused, auto_managed, sequential_download, seed_mode, super_seeding, max_uploads, max_connections, upload_limit and download_limit are all affected by this flag. The intention of this flag is to have any field in add_torrent_params configuring the torrent override the corresponding configuration from the resume file, with the one exception of save resume data, which has its own flag (for historic reasons). If this flag is set, but file_priorities is empty, file priorities are still loaded from the resume data, if present.
flag_upload_mode 4

If flag_upload_mode is set, the torrent will be initialized in upload-mode, which means it will not make any piece requests. This state is typically entered on disk I/O errors, and if the torrent is also auto managed, it will be taken out of this state periodically. This mode can be used to avoid race conditions when adjusting priorities of pieces before allowing the torrent to start downloading.

If the torrent is auto-managed (flag_auto_managed), the torrent will eventually be taken out of upload-mode, regardless of how it got there. If it's important to manually control when the torrent leaves upload mode, don't make it auto managed.

flag_share_mode 8

determines if the torrent should be added in share mode or not. Share mode indicates that we are not interested in downloading the torrent, but merely want to improve our share ratio (i.e. increase it). A torrent started in share mode will do its best to never download more than it uploads to the swarm. If the swarm does not have enough demand for upload capacity, the torrent will not download anything. This mode is intended to be safe to add any number of torrents to, without manual screening, without the risk of downloading more than is uploaded.

A torrent in share mode sets the priority to all pieces to 0, except for the pieces that are downloaded, when pieces are decided to be downloaded. This affects the progress bar, which might be set to "100% finished" most of the time. Do not change file or piece priorities for torrents in share mode, it will make it not work.

The share mode has one setting, the share ratio target, see settings_pack::share_mode_target for more info.

flag_apply_ip_filter 16 determines if the IP filter should apply to this torrent or not. By default all torrents are subject to filtering by the IP filter (i.e. this flag is set by default). This is useful if certain torrents needs to be exempt for some reason, being an auto-update torrent for instance.
flag_paused 32 specifies whether or not the torrent is to be started in a paused state. I.e. it won't connect to the tracker or any of the peers until it's resumed. This is typically a good way of avoiding race conditions when setting configuration options on torrents before starting them.
flag_auto_managed 64

If the torrent is auto-managed (flag_auto_managed), the torrent may be resumed at any point, regardless of how it paused. If it's important to manually control when the torrent is paused and resumed, don't make it auto managed.

If flag_auto_managed is set, the torrent will be queued, started and seeded automatically by libtorrent. When this is set, the torrent should also be started as paused. The default queue order is the order the torrents were added. They are all downloaded in that order. For more details, see queuing.

If you pass in resume data, the auto_managed state of the torrent when the resume data was saved will override the auto_managed state you pass in here. You can override this by setting override_resume_data.

flag_duplicate_is_error 128  
flag_merge_resume_trackers 256 defaults to off and specifies whether tracker URLs loaded from resume data should be added to the trackers in the torrent or replace the trackers. When replacing trackers (i.e. this flag is not set), any trackers passed in via add_torrent_params are also replaced by any trackers in the resume data. The default behavior is to have the resume data override the .torrent file _and_ the trackers added in add_torrent_params.
flag_update_subscribe 512 on by default and means that this torrent will be part of state updates when calling post_torrent_updates().
flag_super_seeding 1024 sets the torrent into super seeding mode. If the torrent is not a seed, this flag has no effect. It has the same effect as calling torrent_handle::super_seeding(true) on the torrent handle immediately after adding it.
flag_sequential_download 2048 sets the sequential download state for the torrent. It has the same effect as calling torrent_handle::sequential_download(true) on the torrent handle immediately after adding it.
flag_use_resume_save_path 4096 if this flag is set, the save path from the resume data file, if present, is honored. This defaults to not being set, in which case the save_path specified in add_torrent_params is always used.
flag_pinned 8192 indicates that this torrent should never be unloaded from RAM, even if unloading torrents are allowed in general. Setting this makes the torrent exempt from loading/unloading management.
flag_merge_resume_http_seeds 32768 defaults to off and specifies whether web seed URLs loaded from resume data should be added to the ones in the torrent file or replace them. No distinction is made between the two different kinds of web seeds (BEP 17 and BEP 19). When replacing web seeds (i.e. when this flag is not set), any web seeds passed in via add_torrent_params are also replaced. The default behavior is to have any web seeds in the resume data take precedence over whatever is passed in here as well as the .torrent file.
flag_stop_when_ready 16384 the stop when ready flag. Setting this flag is equivalent to calling torrent_handle::stop_when_ready() immediately after the torrent is added.
version
filled in by the constructor and should be left untouched. It is used for forward binary compatibility.
ti
torrent_info object with the torrent to add. Unless the url or info_hash is set, this is required to be initialized.
trackers
If the torrent doesn't have a tracker, but relies on the DHT to find peers, the trackers can specify tracker URLs for the torrent.
url_seeds
url seeds to be added to the torrent (BEP 17).
dht_nodes name
a list of hostname and port pairs, representing DHT nodes to be added to the session (if DHT is enabled). The hostname may be an IP address.
save_path

the path where the torrent is or will be stored. Note that this may also be stored in resume data. If you want the save path saved in the resume data to be used, you need to set the flag_use_resume_save_path flag.

Note

On windows this path (and other paths) are interpreted as UNC paths. This means they must use backslashes as directory separators and may not contain the special directories "." or "..".

Setting this to an absolute path is slightly more performant than a relative path.

resume_data
The optional parameter, resume_data can be given if up to date fast-resume data is available. The fast-resume data can be acquired from a running torrent by calling save_resume_data() on torrent_handle. See fast resume. The vector that is passed in will be swapped into the running torrent instance with std::vector::swap().
storage_mode
One of the values from storage_mode_t. For more information, see storage allocation.
storage
can be used to customize how the data is stored. The default storage will simply write the data to the files it belongs to, but it could be overridden to save everything to a single file at a specific location or encrypt the content on disk for instance. For more information about the storage_interface that needs to be implemented for a custom storage, see storage_interface.
userdata
The userdata parameter is optional and will be passed on to the extension constructor functions, if any (see torrent_handle::add_extension()).
file_priorities
can be set to control the initial file priorities when adding a torrent. The semantics are the same as for torrent_handle::prioritize_files().
trackerid
the default tracker id to be used when announcing to trackers. By default this is empty, and no tracker ID is used, since this is an optional argument. If a tracker returns a tracker ID, that ID is used instead of this.
url
If you specify a url, the torrent will be set in downloading_metadata state until the .torrent file has been downloaded. If there's any error while downloading, the torrent will be stopped and the torrent error state (torrent_status::error) will indicate what went wrong. The url may be set to a magnet link.
uuid
if uuid is specified, it is used to find duplicates. If another torrent is already running with the same UUID as the one being added, it will be considered a duplicate. This is mainly useful for RSS feed items which has UUIDs specified.
source_feed_url
should point to the URL of the RSS feed this torrent comes from, if it comes from an RSS feed.
flags

flags controlling aspects of this torrent and how it's added. See flags_t for details.

Note

The flags field is initialized with default flags by the constructor. In order to preserve default behavior when clearing or setting other flags, make sure to bitwise OR or in a flag or bitwise AND the inverse of a flag to clear it.

info_hash
set this to the info hash of the torrent to add in case the info-hash is the only known property of the torrent. i.e. you don't have a .torrent file nor a magnet link.
max_uploads max_connections upload_limit download_limit

max_uploads, max_connections, upload_limit, download_limit correspond to the set_max_uploads(), set_max_connections(), set_upload_limit() and set_download_limit() functions on torrent_handle. These values let you initialize these settings when the torrent is added, instead of calling these functions immediately following adding it.

-1 means unlimited on these settings just like their counterpart functions on torrent_handle

announce_entry

Declared in "libtorrent/announce_entry.hpp"

this class holds information about one bittorrent tracker, as it relates to a specific torrent.

struct announce_entry
{
   announce_entry (std::string const& u);
   announce_entry (announce_entry const&) = default;
   ~announce_entry ();
   announce_entry& operator= (announce_entry const&) = default;
   announce_entry ();
   int next_announce_in () const;
   int min_announce_in () const;
   void reset ();
   void failed (aux::session_settings const& sett, int retry_interval = 0);
   bool can_announce (time_point now, bool is_seed) const;
   bool is_working () const;
   void trim ();

   enum tracker_source
   {
      source_torrent,
      source_client,
      source_magnet_link,
      source_tex,
   };

   std::string url;
   std::string trackerid;
   std::string message;
   error_code last_error;
   time_point next_announce;
   time_point min_announce;
   int scrape_incomplete;
   int scrape_complete;
   int scrape_downloaded;
   boost::uint8_t tier;
   boost::uint8_t fail_limit;
   boost::uint8_t fails:7;
   bool updating:1;
   boost::uint8_t source:4;
   bool verified:1;
   bool start_sent:1;
   bool complete_sent:1;
   bool send_stats:1;
};

announce_entry() ~announce_entry() operator=()

announce_entry (std::string const& u);
announce_entry (announce_entry const&) = default;
~announce_entry ();
announce_entry& operator= (announce_entry const&) = default;
announce_entry ();

constructs a tracker announce entry with u as the URL.

min_announce_in() next_announce_in()

int next_announce_in () const;
int min_announce_in () const;

returns the number of seconds to the next announce on this tracker. min_announce_in() returns the number of seconds until we are allowed to force another tracker update with this tracker.

If the last time this tracker was contacted failed, last_error is the error code describing what error occurred.

reset()

void reset ();

reset announce counters and clears the started sent flag. The announce_entry will look like we've never talked to the tracker.

failed()

void failed (aux::session_settings const& sett, int retry_interval = 0);

updates the failure counter and time-outs for re-trying. This is called when the tracker announce fails.

can_announce()

bool can_announce (time_point now, bool is_seed) const;

returns true if we can announce to this tracker now. The current time is passed in as now. The is_seed argument is necessary because once we become a seed, we need to announce right away, even if the re-announce timer hasn't expired yet.

is_working()

bool is_working () const;

returns true if the last time we tried to announce to this tracker succeeded, or if we haven't tried yet.

trim()

void trim ();

trims whitespace characters from the beginning of the URL.

enum tracker_source

Declared in "libtorrent/announce_entry.hpp"

name value description
source_torrent 1 the tracker was part of the .torrent file
source_client 2 the tracker was added programatically via the add_troacker()_ function
source_magnet_link 4 the tracker was part of a magnet link
source_tex 8 the tracker was received from the swarm via tracker exchange
url
tracker URL as it appeared in the torrent file
trackerid
the current &trackerid= argument passed to the tracker. this is optional and is normally empty (in which case no trackerid is sent).
message
if this tracker has returned an error or warning message that message is stored here
last_error
if this tracker failed the last time it was contacted this error code specifies what error occurred
next_announce
the time of next tracker announce
min_announce
no announces before this time
scrape_incomplete scrape_complete scrape_downloaded
if this tracker has returned scrape data, these fields are filled in with valid numbers. Otherwise they are set to -1. the number of current downloaders
tier
the tier this tracker belongs to
fail_limit
the max number of failures to announce to this tracker in a row, before this tracker is not used anymore. 0 means unlimited
fails
the number of times in a row we have failed to announce to this tracker.
updating
true while we're waiting for a response from the tracker.
source
a bitmask specifying which sources we got this tracker from.
verified
set to true the first time we receive a valid response from this tracker.
start_sent
set to true when we get a valid response from an announce with event=started. If it is set, we won't send start in the subsequent announces.
complete_sent
set to true when we send a event=completed.
send_stats
this is false the stats sent to this tracker will be 0

cache_status

Declared in "libtorrent/disk_io_thread.hpp"

this struct holds a number of statistics counters relevant for the disk io thread and disk cache.

struct cache_status
{
   cache_status ();

   std::vector<cached_piece_info> pieces;
};

cache_status()

cache_status ();

initializes all counters to 0

bt_peer_connection_handle

Declared in "libtorrent/peer_connection_handle.hpp"

struct bt_peer_connection_handle : public peer_connection_handle
{
   explicit bt_peer_connection_handle (peer_connection_handle pc);
   bool support_extensions () const;
   bool packet_finished () const;
   bool supports_encryption () const;
   void switch_recv_crypto (boost::shared_ptr<crypto_plugin> crypto);
   void switch_send_crypto (boost::shared_ptr<crypto_plugin> crypto);
   boost::shared_ptr<bt_peer_connection> native_handle () const;
};

peer_info

Declared in "libtorrent/peer_info.hpp"

holds information and statistics about one peer that libtorrent is connected to

struct peer_info
{
   enum peer_flags_t
   {
      interesting,
      choked,
      remote_interested,
      remote_choked,
      supports_extensions,
      local_connection,
      handshake,
      connecting,
      on_parole,
      seed,
      optimistic_unchoke,
      snubbed,
      upload_only,
      endgame_mode,
      holepunched,
      i2p_socket,
      utp_socket,
      ssl_socket,
      rc4_encrypted,
      plaintext_encrypted,
   };

   enum peer_source_flags
   {
      tracker,
      dht,
      pex,
      lsd,
      resume_data,
      incoming,
   };

   enum connection_type_t
   {
      standard_bittorrent,
      web_seed,
      http_seed,
   };

   enum bw_state
   {
      bw_idle,
      bw_limit,
      bw_network,
      bw_disk,
   };

   std::string client;
   bitfield pieces;
   boost::int64_t total_download;
   boost::int64_t total_upload;
   time_duration last_request;
   time_duration last_active;
   time_duration download_queue_time;
   boost::uint32_t flags;
   boost::uint32_t source;
   int up_speed;
   int down_speed;
   int payload_up_speed;
   int payload_down_speed;
   peer_id pid;
   int queue_bytes;
   int request_timeout;
   int send_buffer_size;
   int used_send_buffer;
   int receive_buffer_size;
   int used_receive_buffer;
   int num_hashfails;
   int download_queue_length;
   int timed_out_requests;
   int busy_requests;
   int requests_in_buffer;
   int target_dl_queue_length;
   int upload_queue_length;
   int failcount;
   int downloading_piece_index;
   int downloading_block_index;
   int downloading_progress;
   int downloading_total;
   int connection_type;
   int remote_dl_rate;
   int pending_disk_bytes;
   int pending_disk_read_bytes;
   int send_quota;
   int receive_quota;
   int rtt;
   int num_pieces;
   int download_rate_peak;
   int upload_rate_peak;
   float progress;
   int progress_ppm;
   int estimated_reciprocation_rate;
   tcp::endpoint ip;
   tcp::endpoint local_endpoint;
   char read_state;
   char write_state;
};

enum peer_flags_t

Declared in "libtorrent/peer_info.hpp"

name value description
interesting 1 we are interested in pieces from this peer.
choked 2 we have choked this peer.
remote_interested 4 the peer is interested in us
remote_choked 8 the peer has choked us.
supports_extensions 16 means that this peer supports the extension protocol.
local_connection 32 The connection was initiated by us, the peer has a listen port open, and that port is the same as in the address of this peer. If this flag is not set, this peer connection was opened by this peer connecting to us.
handshake 64 The connection is opened, and waiting for the handshake. Until the handshake is done, the peer cannot be identified.
connecting 128 The connection is in a half-open state (i.e. it is being connected).
on_parole 512 The peer has participated in a piece that failed the hash check, and is now "on parole", which means we're only requesting whole pieces from this peer until it either fails that piece or proves that it doesn't send bad data.
seed 1024 This peer is a seed (it has all the pieces).
optimistic_unchoke 2048 This peer is subject to an optimistic unchoke. It has been unchoked for a while to see if it might unchoke us in return an earn an upload/unchoke slot. If it doesn't within some period of time, it will be choked and another peer will be optimistically unchoked.
snubbed 4096 This peer has recently failed to send a block within the request timeout from when the request was sent. We're currently picking one block at a time from this peer.
upload_only 8192 This peer has either explicitly (with an extension) or implicitly (by becoming a seed) told us that it will not downloading anything more, regardless of which pieces we have.
endgame_mode 16384 This means the last time this peer picket a piece, it could not pick as many as it wanted because there were not enough free ones. i.e. all pieces this peer has were already requested from other peers.
holepunched 32768 This flag is set if the peer was in holepunch mode when the connection succeeded. This typically only happens if both peers are behind a NAT and the peers connect via the NAT holepunch mechanism.
i2p_socket 65536 indicates that this socket is runnin on top of the I2P transport.
utp_socket 131072 indicates that this socket is a uTP socket
ssl_socket 262144 indicates that this socket is running on top of an SSL (TLS) channel
rc4_encrypted 1048576 this connection is obfuscated with RC4
plaintext_encrypted 2097152 the handshake of this connection was obfuscated with a diffie-hellman exchange

enum peer_source_flags

Declared in "libtorrent/peer_info.hpp"

name value description
tracker 1 The peer was received from the tracker.
dht 2 The peer was received from the kademlia DHT.
pex 4 The peer was received from the peer exchange extension.
lsd 8 The peer was received from the local service discovery (The peer is on the local network).
resume_data 16 The peer was added from the fast resume data.
incoming 32 we received an incoming connection from this peer

enum connection_type_t

Declared in "libtorrent/peer_info.hpp"

name value description
standard_bittorrent 0 Regular bittorrent connection
web_seed 1 HTTP connection using the BEP 19 protocol
http_seed 2 HTTP connection using the BEP 17 protocol

enum bw_state

Declared in "libtorrent/peer_info.hpp"

name value description
bw_idle 0 The peer is not waiting for any external events to send or receive data.
bw_limit 1 The peer is waiting for the rate limiter.
bw_network 2 The peer has quota and is currently waiting for a network read or write operation to complete. This is the state all peers are in if there are no bandwidth limits.
bw_disk 4 The peer is waiting for the disk I/O thread to catch up writing buffers to disk before downloading more.
client
a string describing the software at the other end of the connection. In some cases this information is not available, then it will contain a string that may give away something about which software is running in the other end. In the case of a web seed, the server type and version will be a part of this string.
pieces
a bitfield, with one bit per piece in the torrent. Each bit tells you if the peer has that piece (if it's set to 1) or if the peer miss that piece (set to 0).
total_download total_upload
the total number of bytes downloaded from and uploaded to this peer. These numbers do not include the protocol chatter, but only the payload data.
last_request last_active
the time since we last sent a request to this peer and since any transfer occurred with this peer
download_queue_time
the time until all blocks in the request queue will be downloaded
flags
tells you in which state the peer is in. It is set to any combination of the peer_flags_t enum.
source
a combination of flags describing from which sources this peer was received. See peer_source_flags.
up_speed down_speed
the current upload and download speed we have to and from this peer (including any protocol messages). updated about once per second
payload_up_speed payload_down_speed
The transfer rates of payload data only updated about once per second
pid
the peer's id as used in the bit torrent protocol. This id can be used to extract 'fingerprints' from the peer. Sometimes it can tell you which client the peer is using. See identify_client()_
request_timeout
the number of seconds until the current front piece request will time out. This timeout can be adjusted through settings_pack::request_timeout. -1 means that there is not outstanding request.
send_buffer_size used_send_buffer
the number of bytes allocated and used for the peer's send buffer, respectively.
receive_buffer_size used_receive_buffer
the number of bytes allocated and used as receive buffer, respectively.
num_hashfails
the number of pieces this peer has participated in sending us that turned out to fail the hash check.
download_queue_length
this is the number of requests we have sent to this peer that we haven't got a response for yet
timed_out_requests
the number of block requests that have timed out, and are still in the download queue
busy_requests
the number of busy requests in the download queue. A budy request is a request for a block we've also requested from a different peer
requests_in_buffer
the number of requests messages that are currently in the send buffer waiting to be sent.
target_dl_queue_length
the number of requests that is tried to be maintained (this is typically a function of download speed)
upload_queue_length
the number of piece-requests we have received from this peer that we haven't answered with a piece yet.
failcount
the number of times this peer has "failed". i.e. failed to connect or disconnected us. The failcount is decremented when we see this peer in a tracker response or peer exchange message.
downloading_piece_index downloading_block_index downloading_progress downloading_total
You can know which piece, and which part of that piece, that is currently being downloaded from a specific peer by looking at these four members. downloading_piece_index is the index of the piece that is currently being downloaded. This may be set to -1 if there's currently no piece downloading from this peer. If it is >= 0, the other three members are valid. downloading_block_index is the index of the block (or sub-piece) that is being downloaded. downloading_progress is the number of bytes of this block we have received from the peer, and downloading_total is the total number of bytes in this block.
connection_type
the kind of connection this peer uses. See connection_type_t.
remote_dl_rate
an estimate of the rate this peer is downloading at, in bytes per second.
pending_disk_bytes
the number of bytes this peer has pending in the disk-io thread. Downloaded and waiting to be written to disk. This is what is capped by settings_pack::max_queued_disk_bytes.
pending_disk_read_bytes
number of outstanding bytes to read from disk
send_quota receive_quota
the number of bytes this peer has been assigned to be allowed to send and receive until it has to request more quota from the bandwidth manager.
rtt
an estimated round trip time to this peer, in milliseconds. It is estimated by timing the the tcp connect(). It may be 0 for incoming connections.
num_pieces
the number of pieces this peer has.
download_rate_peak upload_rate_peak
the highest download and upload rates seen on this connection. They are given in bytes per second. This number is reset to 0 on reconnect.
progress
the progress of the peer in the range [0, 1]. This is always 0 when floating point operations are disabled, instead use progress_ppm.
progress_ppm
indicates the download progress of the peer in the range [0, 1000000] (parts per million).
estimated_reciprocation_rate
this is an estimation of the upload rate, to this peer, where it will unchoke us. This is a coarse estimation based on the rate at which we sent right before we were choked. This is primarily used for the bittyrant choking algorithm.
ip
the IP-address to this peer. The type is an asio endpoint. For more info, see the asio documentation.
local_endpoint
the IP and port pair the socket is bound to locally. i.e. the IP address of the interface it's going out over. This may be useful for multi-homed clients with multiple interfaces to the internet.
read_state write_state
bitmasks indicating what state this peer is in with regards to sending and receiving data. The states are declared in the bw_state enum.

peer_request

Declared in "libtorrent/peer_request.hpp"

represents a byte range within a piece. Internally this is is used for incoming piece requests.

struct peer_request
{
   bool operator== (peer_request const& r) const;

   int piece;
   int start;
   int length;
};

operator==()

bool operator== (peer_request const& r) const;

returns true if the right hand side peer_request refers to the same range as this does.

piece
the index of the piece in which the range starts.
start
the offset within that piece where the range starts.
length
the size of the range, in bytes.

session_proxy

Declared in "libtorrent/session.hpp"

this is a holder for the internal session implementation object. Once the session destruction is explicitly initiated, this holder is used to synchronize the completion of the shutdown. The lifetime of this object may outlive session, causing the session destructor to not block. The session_proxy destructor will block however, until the underlying session is done shutting down.

class session_proxy
{
   ~session_proxy ();
   session_proxy (session_proxy const&) = default;
   session_proxy& operator= (session_proxy const&) = default;
   session_proxy ();
};

session_proxy() ~session_proxy() operator=()

~session_proxy ();
session_proxy (session_proxy const&) = default;
session_proxy& operator= (session_proxy const&) = default;
session_proxy ();

default constructor, does not refer to any session implementation object.

session

Declared in "libtorrent/session.hpp"

The session holds all state that spans multiple torrents. Among other things it runs the network loop and manages all torrents. Once it's created, the session object will spawn the main thread that will do all the work. The main thread will be idle as long it doesn't have any torrents to participate in.

You have some control over session configuration through the session::apply_settings() member function. To change one or more configuration options, create a settings_pack. object and fill it with the settings to be set and pass it in to session::apply_settings().

see apply_settings().

class session: public boost::noncopyable, public session_handle
{
   session (settings_pack const& pack = settings_pack()
      , int flags = start_default_features | add_default_plugins);
   session (settings_pack const& pack
      , io_service& ios
      , int flags = start_default_features | add_default_plugins);
   ~session ();
   session_proxy abort ();
};

session()

session (settings_pack const& pack = settings_pack()
      , int flags = start_default_features | add_default_plugins);

Constructs the session obects which acts as the container of torrents. It provides configuration options across torrents (such as rate limits, disk cache, ip filter etc.). In order to avoid a race condition between starting the session and configuring it, you can pass in a settings_pack object. Its settings will take effect before the session starts up.

The flags parameter can be used to start default features (upnp & nat-pmp) and default plugins (ut_metadata, ut_pex and smart_ban). The default is to start those features. If you do not want them to start, pass 0 as the flags parameter.

session()

session (settings_pack const& pack
      , io_service& ios
      , int flags = start_default_features | add_default_plugins);

overload of the constructor that takes an external io_service to run the session object on. This is primarily useful for tests that may want to run multiple sessions on a single io_service, or low resource systems where additional threads are expensive and sharing an io_service with other events is fine.

Warning

The session object does not cleanly terminate with an external io_service. The io_service::run() call _must_ have returned before it's safe to destruct the session. Which means you MUST call session::abort() and save the session_proxy first, then destruct the session object, then sync with the io_service, then destruct the session_proxy object.

~session()

~session ();

The destructor of session will notify all trackers that our torrents have been shut down. If some trackers are down, they will time out. All this before the destructor of session returns. So, it's advised that any kind of interface (such as windows) are closed before destructing the session object. Because it can take a few second for it to finish. The timeout can be set with apply_settings().

abort()

session_proxy abort ();

In case you want to destruct the session asynchronously, you can request a session destruction proxy. If you don't do this, the destructor of the session object will block while the trackers are contacted. If you keep one session_proxy to the session when destructing it, the destructor will not block, but start to close down the session, the destructor of the proxy will then synchronize the threads. So, the destruction of the session is performed from the session destructor call until the session_proxy destructor call. The session_proxy does not have any operations on it (since the session is being closed down, no operations are allowed on it). The only valid operation is calling the destructor:

class session_proxy
{
public:
        session_proxy();
        ~session_proxy()
};

session_handle

Declared in "libtorrent/session_handle.hpp"

struct session_handle
{
   session_handle ();
   session_handle (aux::session_impl* impl);
   bool is_valid () const;
   void load_state (bdecode_node const& e, boost::uint32_t flags = 0xffffffff);
   void save_state (entry& e, boost::uint32_t flags = 0xffffffff) const;
   void refresh_torrent_status (std::vector<torrent_status>* ret
      , boost::uint32_t flags = 0) const;
   void get_torrent_status (std::vector<torrent_status>* ret
      , boost::function<bool(torrent_status const&)> const& pred
      , boost::uint32_t flags = 0) const;
   void post_torrent_updates (boost::uint32_t flags = 0xffffffff);
   void post_session_stats ();
   void post_dht_stats ();
   torrent_handle find_torrent (sha1_hash const& info_hash) const;
   std::vector<torrent_handle> get_torrents () const;
   void async_add_torrent (add_torrent_params const& params);
   torrent_handle add_torrent (add_torrent_params const& params, error_code& ec);
   torrent_handle add_torrent (add_torrent_params const& params);
   void resume ();
   void pause ();
   bool is_paused () const;
   void set_load_function (user_load_function_t fun);
   void get_cache_info (cache_status* ret, torrent_handle h = torrent_handle(), int flags = 0) const;
   bool is_dht_running () const;
   dht_settings get_dht_settings () const;
   void set_dht_settings (dht_settings const& settings);
   void set_dht_storage (dht::dht_storage_constructor_type sc);
   void add_dht_node (std::pair<std::string, int> const& node);
   void dht_get_item (sha1_hash const& target);
   void dht_get_item (boost::array<char, 32> key
      , std::string salt = std::string());
   sha1_hash dht_put_item (entry data);
   void dht_put_item (boost::array<char, 32> key
      , boost::function<void(entry&, boost::array<char,64>&
      , boost::uint64_t&, std::string const&)> cb
      , std::string salt = std::string());
   void dht_get_peers (sha1_hash const& info_hash);
   void dht_announce (sha1_hash const& info_hash, int port = 0, int flags = 0);
   void dht_direct_request (udp::endpoint ep, entry const& e, void* userdata = 0);
   void add_extension (boost::function<boost::shared_ptr<torrent_plugin>(
      torrent_handle const&, void*)> ext);
   void add_extension (boost::shared_ptr<plugin> ext);
   ip_filter get_ip_filter () const;
   void set_ip_filter (ip_filter const& f);
   void set_port_filter (port_filter const& f);
   peer_id id () const;
   void set_key (int key);
   bool is_listening () const;
   unsigned short listen_port () const;
   unsigned short ssl_listen_port () const;
   void set_peer_class_filter (ip_filter const& f);
   void set_peer_class_type_filter (peer_class_type_filter const& f);
   int create_peer_class (char const* name);
   void delete_peer_class (int cid);
   peer_class_info get_peer_class (int cid);
   void set_peer_class (int cid, peer_class_info const& pci);
   void remove_torrent (const torrent_handle& h, int options = 0);
   settings_pack get_settings () const;
   void apply_settings (settings_pack const& s);
   void pop_alerts (std::vector<alert*>* alerts);
   void set_alert_notify (boost::function<void()> const& fun);
   alert* wait_for_alert (time_duration max_wait);
   void delete_port_mapping (int handle);
   int add_port_mapping (protocol_type t, int external_port, int local_port);
   aux::session_impl* native_handle () const;

   enum save_state_flags_t
   {
      save_settings,
      save_dht_settings,
      save_dht_state,
      save_encryption_settings,
   };

   enum options_t
   {
      delete_files,
      delete_partfile,
   };

   enum session_flags_t
   {
      add_default_plugins,
      start_default_features,
   };

   enum protocol_type
   {
      udp,
      tcp,
   };
};

load_state() save_state()

void load_state (bdecode_node const& e, boost::uint32_t flags = 0xffffffff);
void save_state (entry& e, boost::uint32_t flags = 0xffffffff) const;

loads and saves all session settings, including dht_settings, encryption settings and proxy settings. save_state writes all keys to the entry that's passed in, which needs to either not be initialized, or initialized as a dictionary.

load_state expects a bdecode_node which can be built from a bencoded buffer with bdecode().

The flags argument is used to filter which parts of the session state to save or load. By default, all state is saved/restored (except for the individual torrents). see save_state_flags_t

When saving settings, there are two fields that are not loaded. peer_fingerprint and user_agent. Those are left as configured by the session_settings passed to the session constructor or subsequently set via apply_settings().

get_torrent_status() refresh_torrent_status()

void refresh_torrent_status (std::vector<torrent_status>* ret
      , boost::uint32_t flags = 0) const;
void get_torrent_status (std::vector<torrent_status>* ret
      , boost::function<bool(torrent_status const&)> const& pred
      , boost::uint32_t flags = 0) const;

Note

these calls are potentially expensive and won't scale well with lots of torrents. If you're concerned about performance, consider using post_torrent_updates() instead.

get_torrent_status returns a vector of the torrent_status for every torrent which satisfies pred, which is a predicate function which determines if a torrent should be included in the returned set or not. Returning true means it should be included and false means excluded. The flags argument is the same as to torrent_handle::status(). Since pred is guaranteed to be called for every torrent, it may be used to count the number of torrents of different categories as well.

refresh_torrent_status takes a vector of torrent_status structs (for instance the same vector that was returned by get_torrent_status() ) and refreshes the status based on the handle member. It is possible to use this function by first setting up a vector of default constructed torrent_status objects, only initializing the handle member, in order to request the torrent status for multiple torrents in a single call. This can save a significant amount of time if you have a lot of torrents.

Any torrent_status object whose handle member is not referring to a valid torrent are ignored.

post_torrent_updates()

void post_torrent_updates (boost::uint32_t flags = 0xffffffff);

This functions instructs the session to post the state_update_alert, containing the status of all torrents whose state changed since the last time this function was called.

Only torrents who has the state subscription flag set will be included. This flag is on by default. See add_torrent_params. the flags argument is the same as for torrent_handle::status(). see torrent_handle::status_flags_t.

post_session_stats()

void post_session_stats ();

This function will post a session_stats_alert object, containing a snapshot of the performance counters from the internals of libtorrent. To interpret these counters, query the session via session_stats_metrics().

For more information, see the session statistics section.

post_dht_stats()

void post_dht_stats ();

This will cause a dht_stats_alert to be posted.

find_torrent() get_torrents()

torrent_handle find_torrent (sha1_hash const& info_hash) const;
std::vector<torrent_handle> get_torrents () const;

find_torrent() looks for a torrent with the given info-hash. In case there is such a torrent in the session, a torrent_handle to that torrent is returned. In case the torrent cannot be found, an invalid torrent_handle is returned.

See torrent_handle::is_valid() to know if the torrent was found or not.

get_torrents() returns a vector of torrent_handles to all the torrents currently in the session.

add_torrent() async_add_torrent()

void async_add_torrent (add_torrent_params const& params);
torrent_handle add_torrent (add_torrent_params const& params, error_code& ec);
torrent_handle add_torrent (add_torrent_params const& params);

You add torrents through the add_torrent() function where you give an object with all the parameters. The add_torrent() overloads will block until the torrent has been added (or failed to be added) and returns an error code and a torrent_handle. In order to add torrents more efficiently, consider using async_add_torrent() which returns immediately, without waiting for the torrent to add. Notification of the torrent being added is sent as add_torrent_alert.

The overload that does not take an error_code throws an exception on error and is not available when building without exception support. The torrent_handle returned by add_torrent() can be used to retrieve information about the torrent's progress, its peers etc. It is also used to abort a torrent.

If the torrent you are trying to add already exists in the session (is either queued for checking, being checked or downloading) add_torrent() will throw libtorrent_exception which derives from std::exception unless duplicate_is_error is set to false. In that case, add_torrent() will return the handle to the existing torrent.

all torrent_handles must be destructed before the session is destructed!

pause() resume() is_paused()

void resume ();
void pause ();
bool is_paused () const;

Pausing the session has the same effect as pausing every torrent in it, except that torrents will not be resumed by the auto-manage mechanism. Resuming will restore the torrents to their previous paused state. i.e. the session pause state is separate from the torrent pause state. A torrent is inactive if it is paused or if the session is paused.

set_load_function()

void set_load_function (user_load_function_t fun);

This function enables dynamic loading of torrent files. When a torrent is unloaded but needs to be availabe in memory, this function is called from within the libtorrent network thread. From within this thread, you can not use any of the public APIs of libtorrent itself. The the info-hash of the torrent is passed in to the function and it is expected to fill in the passed in vector<char> with the .torrent file corresponding to it.

If there is an error loading the torrent file, the error_code (ec) should be set to reflect the error. In such case, the torrent itself is stopped and set to an error state with the corresponding error code.

Given that the function is called from the internal network thread of libtorrent, it's important to not stall. libtorrent will not be able to send nor receive any data until the function call returns.

The signature of the function to pass in is:

void fun(sha1_hash const& info_hash, std::vector<char>& buf, error_code& ec);

get_cache_info()

void get_cache_info (cache_status* ret, torrent_handle h = torrent_handle(), int flags = 0) const;

Fills in the cache_status struct with information about the given torrent. If flags is session::disk_cache_no_pieces the cache_status::pieces field will not be set. This may significantly reduce the cost of this call.

get_dht_settings() is_dht_running() set_dht_settings()

bool is_dht_running () const;
dht_settings get_dht_settings () const;
void set_dht_settings (dht_settings const& settings);

set_dht_settings sets some parameters available to the dht node. See dht_settings for more information.

is_dht_running() returns true if the DHT support has been started and false otherwise.

get_dht_settings() returns the current settings

set_dht_storage()

void set_dht_storage (dht::dht_storage_constructor_type sc);

set_dht_storage set a dht custom storage constructor function to be used internally when the dht is created.

Since the dht storage is a critical component for the dht behavior, this function will only be effective the next time the dht is started. If you never touch this feature, a default map-memory based storage is used.

If you want to make sure the dht is initially created with your custom storage, create a session with the setting settings_pack::enable_dht to false, set your constructor function and call apply_settings with settings_pack::enable_dht to true.

add_dht_node()

void add_dht_node (std::pair<std::string, int> const& node);

add_dht_node takes a host name and port pair. That endpoint will be pinged, and if a valid DHT reply is received, the node will be added to the routing table.

dht_get_item()

void dht_get_item (sha1_hash const& target);

query the DHT for an immutable item at the target hash. the result is posted as a dht_immutable_item_alert.

dht_get_item()

void dht_get_item (boost::array<char, 32> key
      , std::string salt = std::string());

query the DHT for a mutable item under the public key key. this is an ed25519 key. salt is optional and may be left as an empty string if no salt is to be used. if the item is found in the DHT, a dht_mutable_item_alert is posted.

dht_put_item()

sha1_hash dht_put_item (entry data);

store the given bencoded data as an immutable item in the DHT. the returned hash is the key that is to be used to look the item up again. It's just the sha-1 hash of the bencoded form of the structure.

dht_put_item()

void dht_put_item (boost::array<char, 32> key
      , boost::function<void(entry&, boost::array<char,64>&
      , boost::uint64_t&, std::string const&)> cb
      , std::string salt = std::string());

store a mutable item. The key is the public key the blob is to be stored under. The optional salt argument is a string that is to be mixed in with the key when determining where in the DHT the value is to be stored. The callback function is called from within the libtorrent network thread once we've found where to store the blob, possibly with the current value stored under the key. The values passed to the callback functions are:

entry& value
the current value stored under the key (may be empty). Also expected to be set to the value to be stored by the function.
boost::array<char,64>& signature
the signature authenticating the current value. This may be zeroes if there is currently no value stored. The function is expected to fill in this buffer with the signature of the new value to store. To generate the signature, you may want to use the sign_mutable_item function.
boost::uint64_t& seq
current sequence number. May be zero if there is no current value. The function is expected to set this to the new sequence number of the value that is to be stored. Sequence numbers must be monotonically increasing. Attempting to overwrite a value with a lower or equal sequence number will fail, even if the signature is correct.
std::string const& salt
this is the salt that was used for this put call.

Since the callback function cb is called from within libtorrent, it is critical to not perform any blocking operations. Ideally not even locking a mutex. Pass any data required for this function along with the function object's context and make the function entirely self-contained. The only reason data blobs' values are computed via a function instead of just passing in the new value is to avoid race conditions. If you want to update the value in the DHT, you must first retrieve it, then modify it, then write it back. The way the DHT works, it is natural to always do a lookup before storing and calling the callback in between is convenient.

dht_direct_request()

void dht_direct_request (udp::endpoint ep, entry const& e, void* userdata = 0);

Send an arbitrary DHT request directly to the specified endpoint. This function is intended for use by plugins. When a response is received or the request times out, a dht_direct_response_alert will be posted with the response (if any) and the userdata pointer passed in here. Since this alert is a response to an explicit call, it will always be posted, regardless of the alert mask.

add_extension()

void add_extension (boost::function<boost::shared_ptr<torrent_plugin>(
      torrent_handle const&, void*)> ext);
void add_extension (boost::shared_ptr<plugin> ext);

This function adds an extension to this session. The argument is a function object that is called with a torrent_handle and which should return a boost::shared_ptr<torrent_plugin>. To write custom plugins, see libtorrent plugins. For the typical bittorrent client all of these extensions should be added. The main plugins implemented in libtorrent are:

metadata extension
Allows peers to download the metadata (.torren files) from the swarm directly. Makes it possible to join a swarm with just a tracker and info-hash.
#include <libtorrent/extensions/metadata_transfer.hpp>
ses.add_extension(&libtorrent::create_metadata_plugin);
uTorrent metadata
Same as metadata extension but compatible with uTorrent.
#include <libtorrent/extensions/ut_metadata.hpp>
ses.add_extension(&libtorrent::create_ut_metadata_plugin);
uTorrent peer exchange
Exchanges peers between clients.
#include <libtorrent/extensions/ut_pex.hpp>
ses.add_extension(&libtorrent::create_ut_pex_plugin);
smart ban plugin
A plugin that, with a small overhead, can ban peers that sends bad data with very high accuracy. Should eliminate most problems on poisoned torrents.
#include <libtorrent/extensions/smart_ban.hpp>
ses.add_extension(&libtorrent::create_smart_ban_plugin);

get_ip_filter() set_ip_filter()

ip_filter get_ip_filter () const;
void set_ip_filter (ip_filter const& f);

Sets a filter that will be used to reject and accept incoming as well as outgoing connections based on their originating ip address. The default filter will allow connections to any ip address. To build a set of rules for which addresses are accepted and not, see ip_filter.

Each time a peer is blocked because of the IP filter, a peer_blocked_alert is generated. get_ip_filter() Returns the ip_filter currently in the session. See ip_filter.

set_port_filter()

void set_port_filter (port_filter const& f);

apply port_filter f to incoming and outgoing peers. a port filter will reject making outgoing peer connections to certain remote ports. The main intention is to be able to avoid triggering certain anti-virus software by connecting to SMTP, FTP ports.

id()

peer_id id () const;

returns the raw peer ID used by libtorrent. When anonymous mode is set the peer ID is randomized per peer.

set_key()

void set_key (int key);

sets the key sent to trackers. If it's not set, it is initialized by libtorrent. The key may be used by the tracker to identify the peer potentially across you changing your IP.

listen_port() ssl_listen_port() is_listening()

bool is_listening () const;
unsigned short listen_port () const;
unsigned short ssl_listen_port () const;

is_listening() will tell you whether or not the session has successfully opened a listening port. If it hasn't, this function will return false, and then you can set a new settings_pack::listen_interfaces to try another interface and port to bind to.

listen_port() returns the port we ended up listening on.

set_peer_class_filter()

void set_peer_class_filter (ip_filter const& f);

Sets the peer class filter for this session. All new peer connections will take this into account and be added to the peer classes specified by this filter, based on the peer's IP address.

The ip-filter essentially maps an IP -> uint32. Each bit in that 32 bit integer represents a peer class. The least significant bit represents class 0, the next bit class 1 and so on.

For more info, see ip_filter.

For example, to make all peers in the range 200.1.1.0 - 200.1.255.255 belong to their own peer class, apply the following filter:

ip_filter f;
int my_class = ses.create_peer_class("200.1.x.x IP range");
f.add_rule(address_v4::from_string("200.1.1.0")
        , address_v4::from_string("200.1.255.255")
        , 1 << my_class);
ses.set_peer_class_filter(f);

This setting only applies to new connections, it won't affect existing peer connections.

This function is limited to only peer class 0-31, since there are only 32 bits in the IP range mapping. Only the set bits matter; no peer class will be removed from a peer as a result of this call, peer classes are only added.

The peer_class argument cannot be greater than 31. The bitmasks representing peer classes in the peer_class_filter are 32 bits.

For more information, see peer classes.

set_peer_class_type_filter()

void set_peer_class_type_filter (peer_class_type_filter const& f);

Sets and gets the peer class type filter. This is controls automatic peer class assignments to peers based on what kind of socket it is.

It does not only support assigning peer classes, it also supports removing peer classes based on socket type.

The order of these rules being applied are:

  1. peer-class IP filter
  2. peer-class type filter, removing classes
  3. peer-class type filter, adding classes

For more information, see peer classes. TODO: add get_peer_class_type_filter() as well

create_peer_class()

int create_peer_class (char const* name);

Creates a new peer class (see peer classes) with the given name. The returned integer is the new peer class' identifier. Peer classes may have the same name, so each invocation of this function creates a new class and returns a unique identifier.

Identifiers are assigned from low numbers to higher. So if you plan on using certain peer classes in a call to set_peer_class_filter(), make sure to create those early on, to get low identifiers.

For more information on peer classes, see peer classes.

delete_peer_class()

void delete_peer_class (int cid);

This call dereferences the reference count of the specified peer class. When creating a peer class it's automatically referenced by 1. If you want to recycle a peer class, you may call this function. You may only call this function once per peer class you create. Calling it more than once for the same class will lead to memory corruption.

Since peer classes are reference counted, this function will not remove the peer class if it's still assigned to torrents or peers. It will however remove it once the last peer and torrent drops their references to it.

There is no need to call this function for custom peer classes. All peer classes will be properly destructed when the session object destructs.

For more information on peer classes, see peer classes.

get_peer_class() set_peer_class()

peer_class_info get_peer_class (int cid);
void set_peer_class (int cid, peer_class_info const& pci);

These functions queries information from a peer class and updates the configuration of a peer class, respectively.

cid must refer to an existing peer class. If it does not, the return value of get_peer_class() is undefined.

set_peer_class() sets all the information in the peer_class_info object in the specified peer class. There is no option to only update a single property.

A peer or torrent belonging to more than one class, the highest priority among any of its classes is the one that is taken into account.

For more information, see peer classes.

remove_torrent()

void remove_torrent (const torrent_handle& h, int options = 0);

remove_torrent() will close all peer connections associated with the torrent and tell the tracker that we've stopped participating in the swarm. This operation cannot fail. When it completes, you will receive a torrent_removed_alert.

The optional second argument options can be used to delete all the files downloaded by this torrent. To do so, pass in the value session::delete_files. The removal of the torrent is asynchronous, there is no guarantee that adding the same torrent immediately after it was removed will not throw a libtorrent_exception exception. Once the torrent is deleted, a torrent_deleted_alert is posted.

get_settings() apply_settings()

settings_pack get_settings () const;
void apply_settings (settings_pack const& s);

Applies the settings specified by the settings_pack s. This is an asynchronous operation that will return immediately and actually apply the settings to the main thread of libtorrent some time later.

pop_alerts() wait_for_alert() set_alert_notify()

void pop_alerts (std::vector<alert*>* alerts);
void set_alert_notify (boost::function<void()> const& fun);
alert* wait_for_alert (time_duration max_wait);

Alerts is the main mechanism for libtorrent to report errors and events. pop_alerts fills in the vector passed to it with pointers to new alerts. The session still owns these alerts and they will stay valid until the next time pop_alerts is called. You may not delete the alert objects.

It is safe to call pop_alerts from multiple different threads, as long as the alerts themselves are not accessed once another thread calls pop_alerts. Doing this requires manual synchronization between the popping threads.

wait_for_alert will block the current thread for max_wait time duration, or until another alert is posted. If an alert is available at the time of the call, it returns immediately. The returned alert pointer is the head of the alert queue. wait_for_alert does not pop alerts from the queue, it merely peeks at it. The returned alert will stay valid until pop_alerts is called twice. The first time will pop it and the second will free it.

If there is no alert in the queue and no alert arrives within the specified timeout, wait_for_alert returns NULL.

In the python binding, wait_for_alert takes the number of milliseconds to wait as an integer.

The alert queue in the session will not grow indefinitely. Make sure to pop periodically to not miss notifications. To control the max number of alerts that's queued by the session, see settings_pack::alert_queue_size.

Some alerts are considered so important that they are posted even when the alert queue is full. Some alerts are considered mandatory and cannot be disabled by the alert_mask. For instance, save_resume_data_alert and save_resume_data_failed_alert are always posted, regardless of the alert mask.

To control which alerts are posted, set the alert_mask (settings_pack::alert_mask).

the set_alert_notify function lets the client set a function object to be invoked every time the alert queue goes from having 0 alerts to 1 alert. This function is called from within libtorrent, it may be the main thread, or it may be from within a user call. The intention of of the function is that the client wakes up its main thread, to poll for more alerts using pop_alerts(). If the notify function fails to do so, it won't be called again, until pop_alerts is called for some other reason. For instance, it could signal an eventfd, post a message to an HWND or some other main message pump. The actual retrieval of alerts should not be done in the callback. In fact, the callback should not block. It should not perform any expensive work. It really should just notify the main application thread.

add_port_mapping() delete_port_mapping()

void delete_port_mapping (int handle);
int add_port_mapping (protocol_type t, int external_port, int local_port);

add_port_mapping adds a port forwarding on UPnP and/or NAT-PMP, whichever is enabled. The return value is a handle referring to the port mapping that was just created. Pass it to delete_port_mapping() to remove it.

native_handle()

aux::session_impl* native_handle () const;

This function is intended only for use by plugins. This type does not have a stable API and should be relied on as little as possible.

enum save_state_flags_t

Declared in "libtorrent/session_handle.hpp"

name value description
save_settings 1 saves settings (i.e. the settings_pack)
save_dht_settings 2 saves dht_settings
save_dht_state 4 saves dht state such as nodes and node-id, possibly accelerating joining the DHT if provided at next session startup.
save_encryption_settings 32 save pe_settings

enum options_t

Declared in "libtorrent/session_handle.hpp"

name value description
delete_files 1 delete the files belonging to the torrent from disk. including the part-file, if there is one
delete_partfile 2 delete just the part-file associated with this torrent

enum session_flags_t

Declared in "libtorrent/session_handle.hpp"

name value description
add_default_plugins 1 this will add common extensions like ut_pex, ut_metadata, lt_tex smart_ban and possibly others.
start_default_features 2 this will start features like DHT, local service discovery, UPnP and NAT-PMP.

enum protocol_type

Declared in "libtorrent/session_handle.hpp"

name value description
udp 1  
tcp 2  

stats_metric

Declared in "libtorrent/session_stats.hpp"

describes one statistics metric from the session. For more information, see the session statistics section.

struct stats_metric
{
   enum metric_type_t
   {
      type_counter,
      type_gauge,
   };

   char const* name;
   int value_index;
   metric_type_t type;
};

enum metric_type_t

Declared in "libtorrent/session_stats.hpp"

name value description
type_counter 0  
type_gauge 1  

block_info

Declared in "libtorrent/torrent_handle.hpp"

holds the state of a block in a piece. Who we requested it from and how far along we are at downloading it.

struct block_info
{
   void set_peer (tcp::endpoint const& ep);
   tcp::endpoint peer () const;

   enum block_state_t
   {
      none,
      requested,
      writing,
      finished,
   };

   unsigned bytes_progress:15;
   unsigned block_size:15;
   unsigned state:2;
   unsigned num_peers:14;
};

set_peer() peer()

void set_peer (tcp::endpoint const& ep);
tcp::endpoint peer () const;

The peer is the ip address of the peer this block was downloaded from.

enum block_state_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
none 0 This block has not been downloaded or requested form any peer.
requested 1 The block has been requested, but not completely downloaded yet.
writing 2 The block has been downloaded and is currently queued for being written to disk.
finished 3 The block has been written to disk.
bytes_progress
the number of bytes that have been received for this block
block_size
the total number of bytes in this block.
state
the state this block is in (see block_state_t)
num_peers
the number of peers that is currently requesting this block. Typically this is 0 or 1, but at the end of the torrent blocks may be requested by more peers in parallel to speed things up.

partial_piece_info

Declared in "libtorrent/torrent_handle.hpp"

This class holds information about pieces that have outstanding requests or outstanding writes

struct partial_piece_info
{
   enum state_t
   {
      none,
      slow,
      medium,
      fast,
   };

   int piece_index;
   int blocks_in_piece;
   int finished;
   int writing;
   int requested;
   block_info* blocks;
   state_t piece_state;
};

enum state_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
none 0  
slow 1  
medium 2  
fast 3  
piece_index
the index of the piece in question. blocks_in_piece is the number of blocks in this particular piece. This number will be the same for most pieces, but the last piece may have fewer blocks than the standard pieces.
blocks_in_piece
the number of blocks in this piece
finished
the number of blocks that are in the finished state
writing
the number of blocks that are in the writing state
requested
the number of blocks that are in the requested state
blocks

this is an array of blocks_in_piece number of items. One for each block in the piece.

Warning

This is a pointer that points to an array that's owned by the session object. The next time get_download_queue() is called, it will be invalidated.

piece_state

the download speed class this piece falls into. this is used internally to cluster peers of the same speed class together when requesting blocks.

set to either fast, medium, slow or none. It tells which download rate category the peers downloading this piece falls into. none means that no peer is currently downloading any part of the piece. Peers prefer picking pieces from the same category as themselves. The reason for this is to keep the number of partially downloaded pieces down. Pieces set to none can be converted into any of fast, medium or slow as soon as a peer want to download from it.

torrent_handle

Declared in "libtorrent/torrent_handle.hpp"

You will usually have to store your torrent handles somewhere, since it's the object through which you retrieve information about the torrent and aborts the torrent.

Warning

Any member function that returns a value or fills in a value has to be made synchronously. This means it has to wait for the main thread to complete the query before it can return. This might potentially be expensive if done from within a GUI thread that needs to stay responsive. Try to avoid querying for information you don't need, and try to do it in as few calls as possible. You can get most of the interesting information about a torrent from the torrent_handle::status() call.

The default constructor will initialize the handle to an invalid state. Which means you cannot perform any operation on it, unless you first assign it a valid handle. If you try to perform any operation on an uninitialized handle, it will throw invalid_handle.

Warning

All operations on a torrent_handle may throw libtorrent_exception exception, in case the handle is no longer referring to a torrent. There is one exception is_valid() will never throw. Since the torrents are processed by a background thread, there is no guarantee that a handle will remain valid between two calls.

struct torrent_handle
{
   torrent_handle ();
   torrent_handle (torrent_handle const& t);
   torrent_handle& operator= (torrent_handle const&) = default;
   void add_piece (int piece, char const* data, int flags = 0) const;
   void read_piece (int piece) const;
   bool have_piece (int piece) const;
   void get_peer_info (std::vector<peer_info>& v) const;
   torrent_status status (boost::uint32_t flags = 0xffffffff) const;
   void get_download_queue (std::vector<partial_piece_info>& queue) const;
   void reset_piece_deadline (int index) const;
   void clear_piece_deadlines () const;
   void set_piece_deadline (int index, int deadline, int flags = 0) const;
   void set_priority (int prio) const;
   void file_progress (std::vector<boost::int64_t>& progress, int flags = 0) const;
   void file_status (std::vector<pool_file_status>& status) const;
   void clear_error () const;
   std::vector<announce_entry> trackers () const;
   void replace_trackers (std::vector<announce_entry> const&) const;
   void add_tracker (announce_entry const&) const;
   void add_url_seed (std::string const& url) const;
   void remove_url_seed (std::string const& url) const;
   std::set<std::string> url_seeds () const;
   void add_http_seed (std::string const& url) const;
   void remove_http_seed (std::string const& url) const;
   std::set<std::string> http_seeds () const;
   void add_extension (
      boost::function<boost::shared_ptr<torrent_plugin>(torrent_handle const&, void*)> const& ext
      , void* userdata = 0);
   bool set_metadata (char const* metadata, int size) const;
   bool is_valid () const;
   void pause (int flags = 0) const;
   void resume () const;
   void stop_when_ready (bool b) const;
   void set_upload_mode (bool b) const;
   void set_share_mode (bool b) const;
   void flush_cache () const;
   void apply_ip_filter (bool b) const;
   void force_recheck () const;
   void save_resume_data (int flags = 0) const;
   bool need_save_resume_data () const;
   void auto_managed (bool m) const;
   void queue_position_down () const;
   void queue_position_top () const;
   int queue_position () const;
   void queue_position_bottom () const;
   void queue_position_up () const;
   void queue_position_set (int p) const;
   void set_ssl_certificate (std::string const& certificate
      , std::string const& private_key
      , std::string const& dh_params
      , std::string const& passphrase = "");
   void set_ssl_certificate_buffer (std::string const& certificate
      , std::string const& private_key
      , std::string const& dh_params);
   storage_interface* get_storage_impl () const;
   shared_ptr<const torrent_info> torrent_file () const;
   void piece_availability (std::vector<int>& avail) const;
   int piece_priority (int index) const;
   std::vector<int> piece_priorities () const;
   void piece_priority (int index, int priority) const;
   void prioritize_pieces (std::vector<int> const& pieces) const;
   void prioritize_pieces (std::vector<std::pair<int, int> > const& pieces) const;
   int file_priority (int index) const;
   void prioritize_files (std::vector<int> const& files) const;
   void file_priority (int index, int priority) const;
   std::vector<int> file_priorities () const;
   void force_reannounce (int seconds = 0, int tracker_index = -1) const;
   void force_dht_announce () const;
   void scrape_tracker (int idx = -1) const;
   int upload_limit () const;
   int download_limit () const;
   void set_upload_limit (int limit) const;
   void set_download_limit (int limit) const;
   void set_pinned (bool p) const;
   void set_sequential_download (bool sd) const;
   void connect_peer (tcp::endpoint const& adr, int source = 0
      , int flags = 0x1 + 0x4 + 0x8) const;
   int max_uploads () const;
   void set_max_uploads (int max_uploads) const;
   int max_connections () const;
   void set_max_connections (int max_connections) const;
   void move_storage (std::string const& save_path, int flags = 0) const;
   void rename_file (int index, std::string const& new_name) const;
   void super_seeding (bool on) const;
   sha1_hash info_hash () const;
   bool operator!= (const torrent_handle& h) const;
   bool operator< (const torrent_handle& h) const;
   bool operator== (const torrent_handle& h) const;
   boost::uint32_t id () const;
   boost::shared_ptr<torrent> native_handle () const;

   enum flags_t
   {
      overwrite_existing,
   };

   enum status_flags_t
   {
      query_distributed_copies,
      query_accurate_download_counters,
      query_last_seen_complete,
      query_pieces,
      query_verified_pieces,
      query_torrent_file,
      query_name,
      query_save_path,
   };

   enum deadline_flags
   {
      alert_when_available,
   };

   enum file_progress_flags_t
   {
      piece_granularity,
   };

   enum pause_flags_t
   {
      graceful_pause,
   };

   enum save_resume_flags_t
   {
      flush_disk_cache,
      save_info_dict,
      only_if_modified,
   };
};

torrent_handle()

torrent_handle ();

constructs a torrent handle that does not refer to a torrent. i.e. is_valid() will return false.

add_piece()

void add_piece (int piece, char const* data, int flags = 0) const;

This function will write data to the storage as piece piece, as if it had been downloaded from a peer. data is expected to point to a buffer of as many bytes as the size of the specified piece. The data in the buffer is copied and passed on to the disk IO thread to be written at a later point.

By default, data that's already been downloaded is not overwritten by this buffer. If you trust this data to be correct (and pass the piece hash check) you may pass the overwrite_existing flag. This will instruct libtorrent to overwrite any data that may already have been downloaded with this data.

Since the data is written asynchronously, you may know that is passed or failed the hash check by waiting for piece_finished_alert or hash_failed_alert.

read_piece()

void read_piece (int piece) const;

This function starts an asynchronous read operation of the specified piece from this torrent. You must have completed the download of the specified piece before calling this function.

When the read operation is completed, it is passed back through an alert, read_piece_alert. Since this alert is a response to an explicit call, it will always be posted, regardless of the alert mask.

Note that if you read multiple pieces, the read operations are not guaranteed to finish in the same order as you initiated them.

have_piece()

bool have_piece (int piece) const;

Returns true if this piece has been completely downloaded, and false otherwise.

get_peer_info()

void get_peer_info (std::vector<peer_info>& v) const;

takes a reference to a vector that will be cleared and filled with one entry for each peer connected to this torrent, given the handle is valid. If the torrent_handle is invalid, it will throw libtorrent_exception exception. Each entry in the vector contains information about that particular peer. See peer_info.

status()

torrent_status status (boost::uint32_t flags = 0xffffffff) const;

status() will return a structure with information about the status of this torrent. If the torrent_handle is invalid, it will throw libtorrent_exception exception. See torrent_status. The flags argument filters what information is returned in the torrent_status. Some information in there is relatively expensive to calculate, and if you're not interested in it (and see performance issues), you can filter them out.

By default everything is included. The flags you can use to decide what to include are defined in the status_flags_t enum.

get_download_queue()

void get_download_queue (std::vector<partial_piece_info>& queue) const;

get_download_queue() takes a non-const reference to a vector which it will fill with information about pieces that are partially downloaded or not downloaded at all but partially requested. See partial_piece_info for the fields in the returned vector.

clear_piece_deadlines() reset_piece_deadline() set_piece_deadline()

void reset_piece_deadline (int index) const;
void clear_piece_deadlines () const;
void set_piece_deadline (int index, int deadline, int flags = 0) const;

This function sets or resets the deadline associated with a specific piece index (index). libtorrent will attempt to download this entire piece before the deadline expires. This is not necessarily possible, but pieces with a more recent deadline will always be prioritized over pieces with a deadline further ahead in time. The deadline (and flags) of a piece can be changed by calling this function again.

The flags parameter can be used to ask libtorrent to send an alert once the piece has been downloaded, by passing alert_when_available. When set, the read_piece_alert alert will be delivered, with the piece data, when it's downloaded.

If the piece is already downloaded when this call is made, nothing happens, unless the alert_when_available flag is set, in which case it will do the same thing as calling read_piece() for index.

deadline is the number of milliseconds until this piece should be completed.

reset_piece_deadline removes the deadline from the piece. If it hasn't already been downloaded, it will no longer be considered a priority.

clear_piece_deadlines() removes deadlines on all pieces in the torrent. As if reset_piece_deadline() was called on all pieces.

set_priority()

void set_priority (int prio) const;

This sets the bandwidth priority of this torrent. The priority of a torrent determines how much bandwidth its peers are assigned when distributing upload and download rate quotas. A high number gives more bandwidth. The priority must be within the range [0, 255].

The default priority is 0, which is the lowest priority.

To query the priority of a torrent, use the torrent_handle::status() call.

Torrents with higher priority will not necessarily get as much bandwidth as they can consume, even if there's is more quota. Other peers will still be weighed in when bandwidth is being distributed. With other words, bandwidth is not distributed strictly in order of priority, but the priority is used as a weight.

Peers whose Torrent has a higher priority will take precedence when distributing unchoke slots. This is a strict prioritization where every interested peer on a high priority torrent will be unchoked before any other, lower priority, torrents have any peers unchoked.

file_progress()

void file_progress (std::vector<boost::int64_t>& progress, int flags = 0) const;

This function fills in the supplied vector with the the number of bytes downloaded of each file in this torrent. The progress values are ordered the same as the files in the torrent_info. This operation is not very cheap. Its complexity is O(n + mj). Where n is the number of files, m is the number of downloading pieces and j is the number of blocks in a piece.

The flags parameter can be used to specify the granularity of the file progress. If left at the default value of 0, the progress will be as accurate as possible, but also more expensive to calculate. If torrent_handle::piece_granularity is specified, the progress will be specified in piece granularity. i.e. only pieces that have been fully downloaded and passed the hash check count. When specifying piece granularity, the operation is a lot cheaper, since libtorrent already keeps track of this internally and no calculation is required.

file_status()

void file_status (std::vector<pool_file_status>& status) const;

This function fills in the passed in vector with status about files that are open for this torrent. Any file that is not open in this torrent, will not be reported in the vector, i.e. it's possible that the vector is empty when returning, if none of the files in the torrent are currently open.

see pool_file_status.

clear_error()

void clear_error () const;

If the torrent is in an error state (i.e. torrent_status::error is non-empty), this will clear the error and start the torrent again.

add_tracker() replace_trackers() trackers()

std::vector<announce_entry> trackers () const;
void replace_trackers (std::vector<announce_entry> const&) const;
void add_tracker (announce_entry const&) const;

trackers() will return the list of trackers for this torrent. The announce entry contains both a string url which specify the announce url for the tracker as well as an int tier, which is specifies the order in which this tracker is tried. If you want libtorrent to use another list of trackers for this torrent, you can use replace_trackers() which takes a list of the same form as the one returned from trackers() and will replace it. If you want an immediate effect, you have to call force_reannounce(). See announce_entry.

add_tracker() will look if the specified tracker is already in the set. If it is, it doesn't do anything. If it's not in the current set of trackers, it will insert it in the tier specified in the announce_entry.

The updated set of trackers will be saved in the resume data, and when a torrent is started with resume data, the trackers from the resume data will replace the original ones.

url_seeds() add_url_seed() remove_url_seed()

void add_url_seed (std::string const& url) const;
void remove_url_seed (std::string const& url) const;
std::set<std::string> url_seeds () const;

add_url_seed() adds another url to the torrent's list of url seeds. If the given url already exists in that list, the call has no effect. The torrent will connect to the server and try to download pieces from it, unless it's paused, queued, checking or seeding. remove_url_seed() removes the given url if it exists already. url_seeds() return a set of the url seeds currently in this torrent. Note that urls that fails may be removed automatically from the list.

See http seeding for more information.

http_seeds() remove_http_seed() add_http_seed()

void add_http_seed (std::string const& url) const;
void remove_http_seed (std::string const& url) const;
std::set<std::string> http_seeds () const;

These functions are identical as the *_url_seed() variants, but they operate on BEP 17 web seeds instead of BEP 19.

See http seeding for more information.

add_extension()

void add_extension (
      boost::function<boost::shared_ptr<torrent_plugin>(torrent_handle const&, void*)> const& ext
      , void* userdata = 0);

add the specified extension to this torrent. The ext argument is a function that will be called from within libtorrent's context passing in the internal torrent object and the specified userdata pointer. The function is expected to return a shared pointer to a torrent_plugin instance.

set_metadata()

bool set_metadata (char const* metadata, int size) const;

set_metadata expects the info section of metadata. i.e. The buffer passed in will be hashed and verified against the info-hash. If it fails, a metadata_failed_alert will be generated. If it passes, a metadata_received_alert is generated. The function returns true if the metadata is successfully set on the torrent, and false otherwise. If the torrent already has metadata, this function will not affect the torrent, and false will be returned.

is_valid()

bool is_valid () const;

Returns true if this handle refers to a valid torrent and false if it hasn't been initialized or if the torrent it refers to has been aborted. Note that a handle may become invalid after it has been added to the session. Usually this is because the storage for the torrent is somehow invalid or if the filenames are not allowed (and hence cannot be opened/created) on your filesystem. If such an error occurs, a file_error_alert is generated and all handles that refers to that torrent will become invalid.

pause() resume()

void pause (int flags = 0) const;
void resume () const;

pause(), and resume() will disconnect all peers and reconnect all peers respectively. When a torrent is paused, it will however remember all share ratios to all peers and remember all potential (not connected) peers. Torrents may be paused automatically if there is a file error (e.g. disk full) or something similar. See file_error_alert.

To know if a torrent is paused or not, call torrent_handle::status() and inspect torrent_status::paused.

The flags argument to pause can be set to torrent_handle::graceful_pause which will delay the disconnect of peers that we're still downloading outstanding requests from. The torrent will not accept any more requests and will disconnect all idle peers. As soon as a peer is done transferring the blocks that were requested from it, it is disconnected. This is a graceful shut down of the torrent in the sense that no downloaded bytes are wasted.

Note

Torrents that are auto-managed may be automatically resumed again. It does not make sense to pause an auto-managed torrent without making it not automanaged first. Torrents are auto-managed by default when added to the session. For more information, see queuing.

stop_when_ready()

void stop_when_ready (bool b) const;

set or clear the stop-when-ready flag. When this flag is set, the torrent will force stop whenever it transitions from a non-data-transferring state into a data-transferring state (referred to as being ready to download or seed). This is useful for torrents that should not start downloading or seeding yet, but want to be made ready to do so. A torrent may need to have its files checked for instance, so it needs to be started and possibly queued for checking (auto-managed and started) but as soon as it's done, it should be stopped.

Force stopped means auto-managed is set to false and it's paused. As if auto_manage(false) and pause() were called on the torrent.

Note that the torrent may transition into a downloading state while calling this function, and since the logic is edge triggered you may miss the edge. To avoid this race, if the torrent already is in a downloading state when this call is made, it will trigger the stop-when-ready immediately.

When the stop-when-ready logic fires, the flag is cleared. Any subsequent transitions between downloading and non-downloading states will not be affected, until this function is used to set it again.

The behavior is more robust when setting this flag as part of adding the torrent. See add_torrent_params.

The stop-when-ready flag fixes the inherent race condition of waiting for the state_changed_alert and then call pause(). The download/seeding will most likely start in between posting the alert and receiving the call to pause.

set_upload_mode()

void set_upload_mode (bool b) const;

Explicitly sets the upload mode of the torrent. In upload mode, the torrent will not request any pieces. If the torrent is auto managed, it will automatically be taken out of upload mode periodically (see settings_pack::optimistic_disk_retry). Torrents are automatically put in upload mode whenever they encounter a disk write error.

m should be true to enter upload mode, and false to leave it.

To test if a torrent is in upload mode, call torrent_handle::status() and inspect torrent_status::upload_mode.

set_share_mode()

void set_share_mode (bool b) const;

Enable or disable share mode for this torrent. When in share mode, the torrent will not necessarily be downloaded, especially not the whole of it. Only parts that are likely to be distributed to more than 2 other peers are downloaded, and only if the previous prediction was correct.

flush_cache()

void flush_cache () const;

Instructs libtorrent to flush all the disk caches for this torrent and close all file handles. This is done asynchronously and you will be notified that it's complete through cache_flushed_alert.

Note that by the time you get the alert, libtorrent may have cached more data for the torrent, but you are guaranteed that whatever cached data libtorrent had by the time you called torrent_handle::flush_cache() has been written to disk.

apply_ip_filter()

void apply_ip_filter (bool b) const;

Set to true to apply the session global IP filter to this torrent (which is the default). Set to false to make this torrent ignore the IP filter.

force_recheck()

void force_recheck () const;

force_recheck puts the torrent back in a state where it assumes to have no resume data. All peers will be disconnected and the torrent will stop announcing to the tracker. The torrent will be added to the checking queue, and will be checked (all the files will be read and compared to the piece hashes). Once the check is complete, the torrent will start connecting to peers again, as normal.

save_resume_data()

void save_resume_data (int flags = 0) const;

save_resume_data() asks libtorrent to generate fast-resume data for this torrent.

The flags argument is a bitmask of flags ORed together. see save_resume_flags_t

This operation is asynchronous, save_resume_data will return immediately. The resume data is delivered when it's done through an save_resume_data_alert.

The fast resume data will be empty in the following cases:

  1. The torrent handle is invalid.
  2. The torrent hasn't received valid metadata and was started without metadata (see libtorrent's metadata from peers extension)

Note that by the time you receive the fast resume data, it may already be invalid if the torrent is still downloading! The recommended practice is to first pause the session, then generate the fast resume data, and then close it down. Make sure to not remove_torrent() before you receive the save_resume_data_alert though. There's no need to pause when saving intermittent resume data.

Warning

If you pause every torrent individually instead of pausing the session, every torrent will have its paused state saved in the resume data!

Warning

The resume data contains the modification timestamps for all files. If one file has been modified when the torrent is added again, the will be rechecked. When shutting down, make sure to flush the disk cache before saving the resume data. This will make sure that the file timestamps are up to date and won't be modified after saving the resume data. The recommended way to do this is to pause the torrent, which will flush the cache and disconnect all peers.

Note

It is typically a good idea to save resume data whenever a torrent is completed or paused. In those cases you don't need to pause the torrent or the session, since the torrent will do no more writing to its files. If you save resume data for torrents when they are paused, you can accelerate the shutdown process by not saving resume data again for paused torrents. Completed torrents should have their resume data saved when they complete and on exit, since their statistics might be updated.

In full allocation mode the resume data is never invalidated by subsequent writes to the files, since pieces won't move around. This means that you don't need to pause before writing resume data in full or sparse mode. If you don't, however, any data written to disk after you saved resume data and before the session closed is lost.

It also means that if the resume data is out dated, libtorrent will not re-check the files, but assume that it is fairly recent. The assumption is that it's better to loose a little bit than to re-check the entire file.

It is still a good idea to save resume data periodically during download as well as when closing down.

Example code to pause and save resume data for all torrents and wait for the alerts:

extern int outstanding_resume_data; // global counter of outstanding resume data
std::vector<torrent_handle> handles = ses.get_torrents();
ses.pause();
for (torrent_handle i : handles)
{
        torrent_handle& h = *i;
        if (!h.is_valid()) continue;
        torrent_status s = h.status();
        if (!s.has_metadata) continue;
        if (!s.need_save_resume_data()) continue;

        h.save_resume_data();
        ++outstanding_resume_data;
}

while (outstanding_resume_data > 0)
{
        alert const* a = ses.wait_for_alert(seconds(10));

        // if we don't get an alert within 10 seconds, abort
        if (a == 0) break;

        std::vector<alert*> alerts;
        ses.pop_alerts(&alerts);

        for (alert* i : alerts)
        {
                if (alert_cast<save_resume_data_failed_alert>(a))
                {
                        process_alert(a);
                        --outstanding_resume_data;
                        continue;
                }

                save_resume_data_alert const* rd = alert_cast<save_resume_data_alert>(a);
                if (rd == 0)
                {
                        process_alert(a);
                        continue;
                }

                torrent_handle h = rd->handle;
                torrent_status st = h.status(torrent_handle::query_save_path
                        | torrent_handle::query_name);
                std::ofstream out((st.save_path
                        + "/" + st.name + ".fastresume").c_str()
                        , std::ios_base::binary);
                out.unsetf(std::ios_base::skipws);
                bencode(std::ostream_iterator<char>(out), *rd->resume_data);
                --outstanding_resume_data;
        }
}

Note

Note how outstanding_resume_data is a global counter in this example. This is deliberate, otherwise there is a race condition for torrents that was just asked to save their resume data, they posted the alert, but it has not been received yet. Those torrents would report that they don't need to save resume data again, and skipped by the initial loop, and thwart the counter otherwise.

need_save_resume_data()

bool need_save_resume_data () const;

This function returns true if any whole chunk has been downloaded since the torrent was first loaded or since the last time the resume data was saved. When saving resume data periodically, it makes sense to skip any torrent which hasn't downloaded anything since the last time.

Note

A torrent's resume data is considered saved as soon as the alert is posted. It is important to make sure this alert is received and handled in order for this function to be meaningful.

auto_managed()

void auto_managed (bool m) const;

changes whether the torrent is auto managed or not. For more info, see queuing.

queue_position() queue_position_up() queue_position_bottom() queue_position_down() queue_position_top()

void queue_position_down () const;
void queue_position_top () const;
int queue_position () const;
void queue_position_bottom () const;
void queue_position_up () const;

Every torrent that is added is assigned a queue position exactly one greater than the greatest queue position of all existing torrents. Torrents that are being seeded have -1 as their queue position, since they're no longer in line to be downloaded.

When a torrent is removed or turns into a seed, all torrents with greater queue positions have their positions decreased to fill in the space in the sequence.

queue_position() returns the torrent's position in the download queue. The torrents with the smallest numbers are the ones that are being downloaded. The smaller number, the closer the torrent is to the front of the line to be started.

The queue position is also available in the torrent_status.

The queue_position_*() functions adjust the torrents position in the queue. Up means closer to the front and down means closer to the back of the queue. Top and bottom refers to the front and the back of the queue respectively.

queue_position_set()

void queue_position_set (int p) const;

updates the position in the queue for this torrent. The relative order of all other torrents remain intact but their numerical queue position shifts to make space for this torrent's new position

set_ssl_certificate_buffer() set_ssl_certificate()

void set_ssl_certificate (std::string const& certificate
      , std::string const& private_key
      , std::string const& dh_params
      , std::string const& passphrase = "");
void set_ssl_certificate_buffer (std::string const& certificate
      , std::string const& private_key
      , std::string const& dh_params);

For SSL torrents, use this to specify a path to a .pem file to use as this client's certificate. The certificate must be signed by the certificate in the .torrent file to be valid.

The set_ssl_certificate_buffer() overload takes the actual certificate, private key and DH params as strings, rather than paths to files. This overload is only available when libtorrent is built against boost 1.54 or later.

cert is a path to the (signed) certificate in .pem format corresponding to this torrent.

private_key is a path to the private key for the specified certificate. This must be in .pem format.

dh_params is a path to the Diffie-Hellman parameter file, which needs to be in .pem format. You can generate this file using the openssl command like this: openssl dhparam -outform PEM -out dhparams.pem 512.

passphrase may be specified if the private key is encrypted and requires a passphrase to be decrypted.

Note that when a torrent first starts up, and it needs a certificate, it will suspend connecting to any peers until it has one. It's typically desirable to resume the torrent after setting the ssl certificate.

If you receive a torrent_need_cert_alert, you need to call this to provide a valid cert. If you don't have a cert you won't be allowed to connect to any peers.

get_storage_impl()

storage_interface* get_storage_impl () const;

Returns the storage implementation for this torrent. This depends on the storage constructor function that was passed to add_torrent.

torrent_file()

shared_ptr<const torrent_info> torrent_file () const;

Returns a pointer to the torrent_info object associated with this torrent. The torrent_info object may be a copy of the internal object. If the torrent doesn't have metadata, the pointer will not be initialized (i.e. a NULL pointer). The torrent may be in a state without metadata only if it was started without a .torrent file, e.g. by using the libtorrent extension of just supplying a tracker and info-hash.

piece_availability()

void piece_availability (std::vector<int>& avail) const;

Fills the specified std::vector<int> with the availability for each piece in this torrent. libtorrent does not keep track of availability for seeds, so if the torrent is seeding the availability for all pieces is reported as 0.

The piece availability is the number of peers that we are connected that has advertised having a particular piece. This is the information that libtorrent uses in order to prefer picking rare pieces.

piece_priority() prioritize_pieces() piece_priorities()

int piece_priority (int index) const;
std::vector<int> piece_priorities () const;
void piece_priority (int index, int priority) const;
void prioritize_pieces (std::vector<int> const& pieces) const;
void prioritize_pieces (std::vector<std::pair<int, int> > const& pieces) const;

These functions are used to set and get the priority of individual pieces. By default all pieces have priority 4. That means that the random rarest first algorithm is effectively active for all pieces. You may however change the priority of individual pieces. There are 8 priority levels. 0 means not to download the piece at all. Otherwise, lower priority values means less likely to be picked. Piece priority takes precedence over piece availability. Every piece with priority 7 will be attempted to be picked before a priority 6 piece and so on.

The default priority of pieces is 4.

Piece priorities can not be changed for torrents that have not downloaded the metadata yet. For instance, magnet links and torrents added by URL won't have metadata immediately. see the metadata_received_alert.

piece_priority sets or gets the priority for an individual piece, specified by index.

prioritize_pieces takes a vector of integers, one integer per piece in the torrent. All the piece priorities will be updated with the priorities in the vector. The second overload of prioritize_pieces that takes a vector of pairs will update the priorities of only select pieces, and leave all other unaffected. Each pair is (piece, priority). That is, the first item is the piece index and the second item is the priority of that piece. Invalid entries, where the piece index or priority is out of range, are not allowed.

piece_priorities returns a vector with one element for each piece in the torrent. Each element is the current priority of that piece.

file_priorities() prioritize_files() file_priority()

int file_priority (int index) const;
void prioritize_files (std::vector<int> const& files) const;
void file_priority (int index, int priority) const;
std::vector<int> file_priorities () const;

index must be in the range [0, number_of_files).

file_priority() queries or sets the priority of file index.

prioritize_files() takes a vector that has at as many elements as there are files in the torrent. Each entry is the priority of that file. The function sets the priorities of all the pieces in the torrent based on the vector.

file_priorities() returns a vector with the priorities of all files.

The priority values are the same as for piece_priority().

Whenever a file priority is changed, all other piece priorities are reset to match the file priorities. In order to maintain special priorities for particular pieces, piece_priority() has to be called again for those pieces.

You cannot set the file priorities on a torrent that does not yet have metadata or a torrent that is a seed. file_priority(int, int) and prioritize_files() are both no-ops for such torrents.

force_reannounce() force_dht_announce()

void force_reannounce (int seconds = 0, int tracker_index = -1) const;
void force_dht_announce () const;

force_reannounce() will force this torrent to do another tracker request, to receive new peers. The seconds argument specifies how many seconds from now to issue the tracker announces.

If the tracker's min_interval has not passed since the last announce, the forced announce will be scheduled to happen immediately as the min_interval expires. This is to honor trackers minimum re-announce interval settings.

The tracker_index argument specifies which tracker to re-announce. If set to -1 (which is the default), all trackers are re-announce.

force_dht_announce will announce the torrent to the DHT immediately.

scrape_tracker()

void scrape_tracker (int idx = -1) const;

scrape_tracker() will send a scrape request to a tracker. By default (idx = -1) it will scrape the last working tracker. If idx is >= 0, the tracker with the specified index will scraped.

A scrape request queries the tracker for statistics such as total number of incomplete peers, complete peers, number of downloads etc.

This request will specifically update the num_complete and num_incomplete fields in the torrent_status struct once it completes. When it completes, it will generate a scrape_reply_alert. If it fails, it will generate a scrape_failed_alert.

set_upload_limit() upload_limit() download_limit() set_download_limit()

int upload_limit () const;
int download_limit () const;
void set_upload_limit (int limit) const;
void set_download_limit (int limit) const;

set_upload_limit will limit the upload bandwidth used by this particular torrent to the limit you set. It is given as the number of bytes per second the torrent is allowed to upload. set_download_limit works the same way but for download bandwidth instead of upload bandwidth. Note that setting a higher limit on a torrent then the global limit (settings_pack::upload_rate_limit) will not override the global rate limit. The torrent can never upload more than the global rate limit.

upload_limit and download_limit will return the current limit setting, for upload and download, respectively.

set_pinned()

void set_pinned (bool p) const;

A pinned torrent may not be unloaded by libtorrent. When the dynamic loading and unloading of torrents is enabled (by setting a load function on the session), this can be used to exempt certain torrents from the unloading logic.

Magnet links, and other torrents that start out without having metadata are pinned automatically. This is to give the client a chance to get the metadata and save it before it's unloaded. In this case, it may be useful to un-pin the torrent once its metadata has been saved to disk.

For more information about dynamically loading and unloading torrents, see dynamic loading of torrent files.

set_sequential_download()

void set_sequential_download (bool sd) const;

set_sequential_download() enables or disables sequential download. When enabled, the piece picker will pick pieces in sequence instead of rarest first. In this mode, piece priorities are ignored, with the exception of priority 7, which are still preferred over the sequential piece order.

Enabling sequential download will affect the piece distribution negatively in the swarm. It should be used sparingly.

connect_peer()

void connect_peer (tcp::endpoint const& adr, int source = 0
      , int flags = 0x1 + 0x4 + 0x8) const;

connect_peer() is a way to manually connect to peers that one believe is a part of the torrent. If the peer does not respond, or is not a member of this torrent, it will simply be disconnected. No harm can be done by using this other than an unnecessary connection attempt is made. If the torrent is uninitialized or in queued or checking mode, this will throw libtorrent_exception. The second (optional) argument will be bitwised ORed into the source mask of this peer. Typically this is one of the source flags in peer_info. i.e. tracker, pex, dht etc.

flags are the same flags that are passed along with the ut_pex extension.

0x01 peer supports encryption.
0x02 peer is a seed
0x04 supports uTP. If this is not set, the peer will only be contacted over TCP.
0x08 supports holepunching protocol. If this flag is received from a peer, it can be used as a rendezvous point in case direct connections to the peer fail

max_uploads() set_max_uploads()

int max_uploads () const;
void set_max_uploads (int max_uploads) const;

set_max_uploads() sets the maximum number of peers that's unchoked at the same time on this torrent. If you set this to -1, there will be no limit. This defaults to infinite. The primary setting controlling this is the global unchoke slots limit, set by unchoke_slots_limit in settings_pack.

max_uploads() returns the current settings.

max_connections() set_max_connections()

int max_connections () const;
void set_max_connections (int max_connections) const;

set_max_connections() sets the maximum number of connection this torrent will open. If all connections are used up, incoming connections may be refused or poor connections may be closed. This must be at least 2. The default is unlimited number of connections. If -1 is given to the function, it means unlimited. There is also a global limit of the number of connections, set by connections_limit in settings_pack.

max_connections() returns the current settings.

move_storage()

void move_storage (std::string const& save_path, int flags = 0) const;

Moves the file(s) that this torrent are currently seeding from or downloading to. If the given save_path is not located on the same drive as the original save path, the files will be copied to the new drive and removed from their original location. This will block all other disk IO, and other torrents download and upload rates may drop while copying the file.

Since disk IO is performed in a separate thread, this operation is also asynchronous. Once the operation completes, the storage_moved_alert is generated, with the new path as the message. If the move fails for some reason, storage_moved_failed_alert is generated instead, containing the error message.

The flags argument determines the behavior of the copying/moving of the files in the torrent. see move_flags_t.

  • always_replace_files = 0
  • fail_if_exist = 1
  • dont_replace = 2

always_replace_files is the default and replaces any file that exist in both the source directory and the target directory.

fail_if_exist first check to see that none of the copy operations would cause an overwrite. If it would, it will fail. Otherwise it will proceed as if it was in always_replace_files mode. Note that there is an inherent race condition here. If the files in the target directory appear after the check but before the copy or move completes, they will be overwritten. When failing because of files already existing in the target path, the error of move_storage_failed_alert is set to boost::system::errc::file_exists.

The intention is that a client may use this as a probe, and if it fails, ask the user which mode to use. The client may then re-issue the move_storage call with one of the other modes.

dont_replace always takes the existing file in the target directory, if there is one. The source files will still be removed in that case.

Files that have been renamed to have absolute pahts are not moved by this function. Keep in mind that files that don't belong to the torrent but are stored in the torrent's directory may be moved as well. This goes for files that have been renamed to absolute paths that still end up inside the save path.

rename_file()

void rename_file (int index, std::string const& new_name) const;

Renames the file with the given index asynchronously. The rename operation is complete when either a file_renamed_alert or file_rename_failed_alert is posted.

super_seeding()

void super_seeding (bool on) const;

Enables or disabled super seeding/initial seeding for this torrent. The torrent needs to be a seed for this to take effect.

info_hash()

sha1_hash info_hash () const;

info_hash() returns the info-hash of the torrent. If this handle is to a torrent that hasn't loaded yet (for instance by being added) by a URL, the returned value is undefined.

operator!=() operator<() operator==()

bool operator!= (const torrent_handle& h) const;
bool operator< (const torrent_handle& h) const;
bool operator== (const torrent_handle& h) const;

comparison operators. The order of the torrents is unspecified but stable.

native_handle()

boost::shared_ptr<torrent> native_handle () const;

This function is intended only for use by plugins and the alert dispatch function. This type does not have a stable API and should be relied on as little as possible.

enum flags_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
overwrite_existing 1  

enum status_flags_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
query_distributed_copies 1 calculates distributed_copies, distributed_full_copies and distributed_fraction.
query_accurate_download_counters 2 includes partial downloaded blocks in total_done and total_wanted_done.
query_last_seen_complete 4 includes last_seen_complete.
query_pieces 8 includes pieces.
query_verified_pieces 16 includes verified_pieces (only applies to torrents in seed mode).
query_torrent_file 32 includes torrent_file, which is all the static information from the .torrent file.
query_name 64 includes name, the name of the torrent. This is either derived from the .torrent file, or from the &dn= magnet link argument or possibly some other source. If the name of the torrent is not known, this is an empty string.
query_save_path 128 includes save_path, the path to the directory the files of the torrent are saved to.

enum deadline_flags

Declared in "libtorrent/torrent_handle.hpp"

name value description
alert_when_available 1  

enum file_progress_flags_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
piece_granularity 1 only calculate file progress at piece granularity. This makes the file_progress() call cheaper and also only takes bytes that have passed the hash check into account, so progress cannot regress in this mode.

enum pause_flags_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
graceful_pause 1  

enum save_resume_flags_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
flush_disk_cache 1 the disk cache will be flushed before creating the resume data. This avoids a problem with file timestamps in the resume data in case the cache hasn't been flushed yet.
save_info_dict 2 the resume data will contain the metadata from the torrent file as well. This is default for any torrent that's added without a torrent file (such as a magnet link or a URL).
only_if_modified 4 if nothing significant has changed in the torrent since the last time resume data was saved, fail this attempt. Significant changes primarily include more data having been downloaded, file or piece priorities having changed etc. If the resume data doesn't need saving, a save_resume_data_failed_alert is posted with the error resume_data_not_modified.

web_seed_entry

Declared in "libtorrent/torrent_info.hpp"

the web_seed_entry holds information about a web seed (also known as URL seed or HTTP seed). It is essentially a URL with some state associated with it. For more information, see BEP 17 and BEP 19.

struct web_seed_entry
{
   web_seed_entry (std::string const& url_, type_t type_
      , std::string const& auth_ = std::string()
      , headers_t const& extra_headers_ = headers_t());
   bool operator== (web_seed_entry const& e) const;
   bool operator< (web_seed_entry const& e) const;

   enum type_t
   {
      url_seed,
      http_seed,
   };

   std::string url;
   std::string auth;
   headers_t extra_headers;
   boost::uint8_t type;
};

operator==()

bool operator== (web_seed_entry const& e) const;

URL and type comparison

operator<()

bool operator< (web_seed_entry const& e) const;

URL and type less-than comparison

enum type_t

Declared in "libtorrent/torrent_info.hpp"

name value description
url_seed 0  
http_seed 1  
url
The URL of the web seed
auth
Optional authentication. If this is set, it's passed in as HTTP basic auth to the web seed. The format is: username:password.
extra_headers
Any extra HTTP headers that need to be passed to the web seed
type
The type of web seed (see type_t)

torrent_info

Declared in "libtorrent/torrent_info.hpp"

TODO: there may be some opportunities to optimize the size if torrent_info. specifically to turn some std::string and std::vector into pointers

class torrent_info
{
   torrent_info (std::string const& filename, int flags = 0);
   torrent_info (std::string const& filename, error_code& ec, int flags = 0);
   torrent_info (char const* buffer, int size, error_code& ec, int flags = 0);
   torrent_info (sha1_hash const& info_hash, int flags = 0);
   torrent_info (bdecode_node const& torrent_file, error_code& ec, int flags = 0);
   torrent_info (char const* buffer, int size, int flags = 0);
   torrent_info (bdecode_node const& torrent_file, int flags = 0);
   torrent_info (torrent_info const& t);
   ~torrent_info ();
   file_storage const& files () const;
   file_storage const& orig_files () const;
   void rename_file (int index, std::string const& new_filename);
   void remap_files (file_storage const& f);
   std::vector<announce_entry> const& trackers () const;
   void add_tracker (std::string const& url, int tier = 0);
   std::vector<sha1_hash> similar_torrents () const;
   std::vector<std::string> collections () const;
   void add_url_seed (std::string const& url
      , std::string const& extern_auth = std::string()
      , web_seed_entry::headers_t const& extra_headers = web_seed_entry::headers_t());
   std::vector<web_seed_entry> const& web_seeds () const;
   void set_web_seeds (std::vector<web_seed_entry> seeds);
   void add_http_seed (std::string const& url
      , std::string const& extern_auth = std::string()
      , web_seed_entry::headers_t const& extra_headers = web_seed_entry::headers_t());
   boost::int64_t total_size () const;
   int num_pieces () const;
   int piece_length () const;
   const sha1_hash& info_hash () const;
   int num_files () const;
   std::vector<file_slice> map_block (int piece, boost::int64_t offset, int size) const;
   peer_request map_file (int file, boost::int64_t offset, int size) const;
   void unload ();
   void load (char const* buffer, int size, error_code& ec);
   std::string ssl_cert () const;
   bool is_valid () const;
   bool priv () const;
   bool is_i2p () const;
   sha1_hash hash_for_piece (int index) const;
   char const* hash_for_piece_ptr (int index) const;
   int piece_size (int index) const;
   bool is_loaded () const;
   std::vector<sha1_hash> const& merkle_tree () const;
   void set_merkle_tree (std::vector<sha1_hash>& h);
   boost::optional<time_t> creation_date () const;
   const std::string& name () const;
   const std::string& comment () const;
   const std::string& creator () const;
   nodes_t const& nodes () const;
   void add_node (std::pair<std::string, int> const& node);
   bool parse_info_section (bdecode_node const& e, error_code& ec, int flags);
   bdecode_node info (char const* key) const;
   void swap (torrent_info& ti);
   int metadata_size () const;
   boost::shared_array<char> metadata () const;
   bool is_merkle_torrent () const;
   bool parse_torrent_file (bdecode_node const& libtorrent, error_code& ec, int flags);
};

torrent_info()

torrent_info (std::string const& filename, int flags = 0);
torrent_info (std::string const& filename, error_code& ec, int flags = 0);
torrent_info (char const* buffer, int size, error_code& ec, int flags = 0);
torrent_info (sha1_hash const& info_hash, int flags = 0);
torrent_info (bdecode_node const& torrent_file, error_code& ec, int flags = 0);
torrent_info (char const* buffer, int size, int flags = 0);
torrent_info (bdecode_node const& torrent_file, int flags = 0);
torrent_info (torrent_info const& t);

The constructor that takes an info-hash will initialize the info-hash to the given value, but leave all other fields empty. This is used internally when downloading torrents without the metadata. The metadata will be created by libtorrent as soon as it has been downloaded from the swarm.

The constructor that takes a bdecode_node will create a torrent_info object from the information found in the given torrent_file. The bdecode_node represents a tree node in an bencoded file. To load an ordinary .torrent file into a bdecode_node, use bdecode().

The version that takes a buffer pointer and a size will decode it as a .torrent file and initialize the torrent_info object for you.

The version that takes a filename will simply load the torrent file and decode it inside the constructor, for convenience. This might not be the most suitable for applications that want to be able to report detailed errors on what might go wrong.

There is an upper limit on the size of the torrent file that will be loaded by the overload taking a filename. If it's important that even very large torrent files are loaded, use one of the other overloads.

The overloads that takes an error_code const& never throws if an error occur, they will simply set the error code to describe what went wrong and not fully initialize the torrent_info object. The overloads that do not take the extra error_code parameter will always throw if an error occurs. These overloads are not available when building without exception support.

The flags argument is currently unused.

~torrent_info()

~torrent_info ();

frees all storage associated with this torrent_info object

orig_files() files()

file_storage const& files () const;
file_storage const& orig_files () const;

The file_storage object contains the information on how to map the pieces to files. It is separated from the torrent_info object because when creating torrents a storage object needs to be created without having a torrent file. When renaming files in a storage, the storage needs to make its own copy of the file_storage in order to make its mapping differ from the one in the torrent file.

orig_files() returns the original (unmodified) file storage for this torrent. This is used by the web server connection, which needs to request files with the original names. Filename may be changed using torrent_info::rename_file().

For more information on the file_storage object, see the separate document on how to create torrents.

rename_file()

void rename_file (int index, std::string const& new_filename);

Renames a the file with the specified index to the new name. The new filename is reflected by the file_storage returned by files() but not by the one returned by orig_files().

If you want to rename the base name of the torrent (for a multifile torrent), you can copy the file_storage (see files() and orig_files() ), change the name, and then use remap_files().

The new_filename can both be a relative path, in which case the file name is relative to the save_path of the torrent. If the new_filename is an absolute path (i.e. is_complete(new_filename) == true), then the file is detached from the save_path of the torrent. In this case the file is not moved when move_storage() is invoked.

remap_files()

void remap_files (file_storage const& f);

Remaps the file storage to a new file layout. This can be used to, for instance, download all data in a torrent to a single file, or to a number of fixed size sector aligned files, regardless of the number and sizes of the files in the torrent.

The new specified file_storage must have the exact same size as the current one.

trackers() add_tracker()

std::vector<announce_entry> const& trackers () const;
void add_tracker (std::string const& url, int tier = 0);

add_tracker() adds a tracker to the announce-list. The tier determines the order in which the trackers are to be tried.

The trackers() function will return a sorted vector of announce_entry. Each announce entry contains a string, which is the tracker url, and a tier index. The tier index is the high-level priority. No matter which trackers that works or not, the ones with lower tier will always be tried before the one with higher tier number. For more information, see announce_entry.

collections() similar_torrents()

std::vector<sha1_hash> similar_torrents () const;
std::vector<std::string> collections () const;

These two functions are related to BEP38 (mutable torrents). The vectors returned from these correspond to the "similar" and "collections" keys in the .torrent file. Both info-hashes and collections from within the info-dict and from outside of it are included.

add_url_seed() set_web_seeds() add_http_seed() web_seeds()

void add_url_seed (std::string const& url
      , std::string const& extern_auth = std::string()
      , web_seed_entry::headers_t const& extra_headers = web_seed_entry::headers_t());
std::vector<web_seed_entry> const& web_seeds () const;
void set_web_seeds (std::vector<web_seed_entry> seeds);
void add_http_seed (std::string const& url
      , std::string const& extern_auth = std::string()
      , web_seed_entry::headers_t const& extra_headers = web_seed_entry::headers_t());

web_seeds() returns all url seeds and http seeds in the torrent. Each entry is a web_seed_entry and may refer to either a url seed or http seed.

add_url_seed() and add_http_seed() adds one url to the list of url/http seeds. Currently, the only transport protocol supported for the url is http.

set_web_seeds() replaces all web seeds with the ones specified in the seeds vector.

The extern_auth argument can be used for other authorization schemes than basic HTTP authorization. If set, it will override any username and password found in the URL itself. The string will be sent as the HTTP authorization header's value (without specifying "Basic").

The extra_headers argument defaults to an empty list, but can be used to insert custom HTTP headers in the requests to a specific web seed.

See http seeding for more information.

piece_length() num_pieces() total_size()

boost::int64_t total_size () const;
int num_pieces () const;
int piece_length () const;

total_size(), piece_length() and num_pieces() returns the total number of bytes the torrent-file represents (all the files in it), the number of byte for each piece and the total number of pieces, respectively. The difference between piece_size() and piece_length() is that piece_size() takes the piece index as argument and gives you the exact size of that piece. It will always be the same as piece_length() except in the case of the last piece, which may be smaller.

info_hash()

const sha1_hash& info_hash () const;

returns the info-hash of the torrent

num_files()

int num_files () const;

If you need index-access to files you can use the num_files() and file_path() et.al. to access files using indices.

map_block()

std::vector<file_slice> map_block (int piece, boost::int64_t offset, int size) const;

This function will map a piece index, a byte offset within that piece and a size (in bytes) into the corresponding files with offsets where that data for that piece is supposed to be stored. See file_slice.

map_file()

peer_request map_file (int file, boost::int64_t offset, int size) const;

This function will map a range in a specific file into a range in the torrent. The file_offset parameter is the offset in the file, given in bytes, where 0 is the start of the file. See peer_request.

The input range is assumed to be valid within the torrent. file_offset + size is not allowed to be greater than the file size. file_index must refer to a valid file, i.e. it cannot be >= num_files().

unload() load()

void unload ();
void load (char const* buffer, int size, error_code& ec);

load and unload this torrent info

ssl_cert()

std::string ssl_cert () const;

Returns the SSL root certificate for the torrent, if it is an SSL torrent. Otherwise returns an empty string. The certificate is the the public certificate in x509 format.

is_valid()

bool is_valid () const;

returns true if this torrent_info object has a torrent loaded. This is primarily used to determine if a magnet link has had its metadata resolved yet or not.

priv()

bool priv () const;

returns true if this torrent is private. i.e., it should not be distributed on the trackerless network (the kademlia DHT).

is_i2p()

bool is_i2p () const;

returns true if this is an i2p torrent. This is determined by whether or not it has a tracker whose URL domain name ends with ".i2p". i2p torrents disable the DHT and local peer discovery as well as talking to peers over anything other than the i2p network.

hash_for_piece_ptr() hash_for_piece() piece_size()

sha1_hash hash_for_piece (int index) const;
char const* hash_for_piece_ptr (int index) const;
int piece_size (int index) const;

hash_for_piece() takes a piece-index and returns the 20-bytes sha1-hash for that piece and info_hash() returns the 20-bytes sha1-hash for the info-section of the torrent file. hash_for_piece_ptr() returns a pointer to the 20 byte sha1 digest for the piece. Note that the string is not null-terminated.

set_merkle_tree() merkle_tree()

std::vector<sha1_hash> const& merkle_tree () const;
void set_merkle_tree (std::vector<sha1_hash>& h);

merkle_tree() returns a reference to the merkle tree for this torrent, if any.

set_merkle_tree() moves the passed in merkle tree into the torrent_info object. i.e. h will not be identical after the call. You need to set the merkle tree for a torrent that you've just created (as a merkle torrent). The merkle tree is retrieved from the create_torrent::merkle_tree() function, and need to be saved separately from the torrent file itself. Once it's added to libtorrent, the merkle tree will be persisted in the resume data.

creator() creation_date() name() comment()

boost::optional<time_t> creation_date () const;
const std::string& name () const;
const std::string& comment () const;
const std::string& creator () const;

name() returns the name of the torrent.

comment() returns the comment associated with the torrent. If there's no comment, it will return an empty string. creation_date() returns the creation date of the torrent as time_t (posix time). If there's no time stamp in the torrent file, the optional object will be uninitialized.

Both the name and the comment is UTF-8 encoded strings.

creator() returns the creator string in the torrent. If there is no creator string it will return an empty string.

nodes()

nodes_t const& nodes () const;

If this torrent contains any DHT nodes, they are put in this vector in their original form (host name and port number).

add_node()

void add_node (std::pair<std::string, int> const& node);

This is used when creating torrent. Use this to add a known DHT node. It may be used, by the client, to bootstrap into the DHT network.

parse_info_section()

bool parse_info_section (bdecode_node const& e, error_code& ec, int flags);

populates the torrent_info by providing just the info-dict buffer. This is used when loading a torrent from a magnet link for instance, where we only have the info-dict. The bdecode_node e points to a parsed info-dictionary. ec returns an error code if something fails (typically if the info dictionary is malformed). flags are currently unused.

info()

bdecode_node info (char const* key) const;

This function looks up keys from the info-dictionary of the loaded torrent file. It can be used to access extension values put in the .torrent file. If the specified key cannot be found, it returns NULL.

swap()

void swap (torrent_info& ti);

swap the content of this and ti`.

metadata_size() metadata()

int metadata_size () const;
boost::shared_array<char> metadata () const;

metadata() returns a the raw info section of the torrent file. The size of the metadata is returned by metadata_size().

is_merkle_torrent()

bool is_merkle_torrent () const;

returns whether or not this is a merkle torrent. see BEP30.

torrent_status

Declared in "libtorrent/torrent_status.hpp"

holds a snapshot of the status of a torrent, as queried by torrent_handle::status().

struct torrent_status
{
   bool operator== (torrent_status const& st) const;

   enum state_t
   {
      checking_files,
      downloading_metadata,
      downloading,
      finished,
      seeding,
      allocating,
      checking_resume_data,
   };

   torrent_handle handle;
   std::string _dummy_string_;
   error_code errc;
   int error_file;
   std::string save_path;
   std::string name;
   boost::weak_ptr<const torrent_info> torrent_file;
   time_duration next_announce;
   std::string current_tracker;
   boost::int64_t total_download;
   boost::int64_t total_upload;
   boost::int64_t total_payload_download;
   boost::int64_t total_payload_upload;
   boost::int64_t total_failed_bytes;
   boost::int64_t total_redundant_bytes;
   bitfield pieces;
   bitfield verified_pieces;
   boost::int64_t total_done;
   boost::int64_t total_wanted_done;
   boost::int64_t total_wanted;
   boost::int64_t all_time_upload;
   boost::int64_t all_time_download;
   time_t added_time;
   time_t completed_time;
   time_t last_seen_complete;
   storage_mode_t storage_mode;
   float progress;
   int progress_ppm;
   int queue_position;
   int download_rate;
   int upload_rate;
   int download_payload_rate;
   int upload_payload_rate;
   int num_seeds;
   int num_peers;
   int num_complete;
   int num_incomplete;
   int list_seeds;
   int list_peers;
   int connect_candidates;
   int num_pieces;
   int distributed_full_copies;
   int distributed_fraction;
   float distributed_copies;
   int block_size;
   int num_uploads;
   int num_connections;
   int uploads_limit;
   int connections_limit;
   int up_bandwidth_queue;
   int down_bandwidth_queue;
   int time_since_upload;
   int time_since_download;
   int active_time;
   int finished_time;
   int seeding_time;
   int seed_rank;
   int last_scrape;
   int priority;
   state_t state;
   bool need_save_resume;
   bool ip_filter_applies;
   bool upload_mode;
   bool share_mode;
   bool super_seeding;
   bool paused;
   bool auto_managed;
   bool sequential_download;
   bool is_seeding;
   bool is_finished;
   bool has_metadata;
   bool has_incoming;
   bool seed_mode;
   bool moving_storage;
   bool is_loaded;
   bool announcing_to_trackers;
   bool announcing_to_lsd;
   bool announcing_to_dht;
   bool stop_when_ready;
   sha1_hash info_hash;
};

operator==()

bool operator== (torrent_status const& st) const;

compares if the torrent status objects come from the same torrent. i.e. only the torrent_handle field is compared.

enum state_t

Declared in "libtorrent/torrent_status.hpp"

name value description
checking_files 1 The torrent has not started its download yet, and is currently checking existing files.
downloading_metadata 2 The torrent is trying to download metadata from peers. This assumes the metadata_transfer extension is in use.
downloading 3 The torrent is being downloaded. This is the state most torrents will be in most of the time. The progress meter will tell how much of the files that has been downloaded.
finished 4 In this state the torrent has finished downloading but still doesn't have the entire torrent. i.e. some pieces are filtered and won't get downloaded.
seeding 5 In this state the torrent has finished downloading and is a pure seeder.
allocating 6 If the torrent was started in full allocation mode, this indicates that the (disk) storage for the torrent is allocated.
checking_resume_data 7 The torrent is currently checking the fastresume data and comparing it to the files on disk. This is typically completed in a fraction of a second, but if you add a large number of torrents at once, they will queue up.
handle
a handle to the torrent whose status the object represents.
_dummy_string_ errc error_file
may be set to an error code describing why the torrent was paused, in case it was paused by an error. If the torrent is not paused or if it's paused but not because of an error, this error_code is not set. if the error is attributed specifically to a file, error_file is set to the index of that file in the .torrent file. internal
save_path
the path to the directory where this torrent's files are stored. It's typically the path as was given to async_add_torrent() or add_torrent() when this torrent was started. This field is only included if the torrent status is queried with torrent_handle::query_save_path.
name
the name of the torrent. Typically this is derived from the .torrent file. In case the torrent was started without metadata, and hasn't completely received it yet, it returns the name given to it when added to the session. See session::add_torrent. This field is only included if the torrent status is queried with torrent_handle::query_name.
torrent_file
set to point to the torrent_info object for this torrent. It's only included if the torrent status is queried with torrent_handle::query_torrent_file.
next_announce
the time until the torrent will announce itself to the tracker.
current_tracker
the URL of the last working tracker. If no tracker request has been successful yet, it's set to an empty string.
total_download total_upload
the number of bytes downloaded and uploaded to all peers, accumulated, this session only. The session is considered to restart when a torrent is paused and restarted again. When a torrent is paused, these counters are reset to 0. If you want complete, persistent, stats, see all_time_upload and all_time_download.
total_payload_download total_payload_upload
counts the amount of bytes send and received this session, but only the actual payload data (i.e the interesting data), these counters ignore any protocol overhead. The session is considered to restart when a torrent is paused and restarted again. When a torrent is paused, these counters are reset to 0.
total_failed_bytes
the number of bytes that has been downloaded and that has failed the piece hash test. In other words, this is just how much crap that has been downloaded since the torrent was last started. If a torrent is paused and then restarted again, this counter will be reset.
total_redundant_bytes
the number of bytes that has been downloaded even though that data already was downloaded. The reason for this is that in some situations the same data can be downloaded by mistake. When libtorrent sends requests to a peer, and the peer doesn't send a response within a certain timeout, libtorrent will re-request that block. Another situation when libtorrent may re-request blocks is when the requests it sends out are not replied in FIFO-order (it will re-request blocks that are skipped by an out of order block). This is supposed to be as low as possible. This only counts bytes since the torrent was last started. If a torrent is paused and then restarted again, this counter will be reset.
pieces
a bitmask that represents which pieces we have (set to true) and the pieces we don't have. It's a pointer and may be set to 0 if the torrent isn't downloading or seeding.
verified_pieces
a bitmask representing which pieces has had their hash checked. This only applies to torrents in seed mode. If the torrent is not in seed mode, this bitmask may be empty.
total_done
the total number of bytes of the file(s) that we have. All this does not necessarily has to be downloaded during this session (that's total_payload_download).
total_wanted_done
the number of bytes we have downloaded, only counting the pieces that we actually want to download. i.e. excluding any pieces that we have but have priority 0 (i.e. not wanted).
total_wanted
The total number of bytes we want to download. This may be smaller than the total torrent size in case any pieces are prioritized to 0, i.e. not wanted
all_time_upload all_time_download
are accumulated upload and download payload byte counters. They are saved in and restored from resume data to keep totals across sessions.
added_time
the posix-time when this torrent was added. i.e. what time(NULL) returned at the time.
completed_time
the posix-time when this torrent was finished. If the torrent is not yet finished, this is 0.
last_seen_complete
the time when we, or one of our peers, last saw a complete copy of this torrent.
storage_mode
The allocation mode for the torrent. See storage_mode_t for the options. For more information, see storage allocation.
progress
a value in the range [0, 1], that represents the progress of the torrent's current task. It may be checking files or downloading.
progress_ppm

progress parts per million (progress * 1000000) when disabling floating point operations, this is the only option to query progress

reflects the same value as progress, but instead in a range [0, 1000000] (ppm = parts per million). When floating point operations are disabled, this is the only alternative to the floating point value in progress.

queue_position
the position this torrent has in the download queue. If the torrent is a seed or finished, this is -1.
download_rate upload_rate
the total rates for all peers for this torrent. These will usually have better precision than summing the rates from all peers. The rates are given as the number of bytes per second.
download_payload_rate upload_payload_rate
the total transfer rate of payload only, not counting protocol chatter. This might be slightly smaller than the other rates, but if projected over a long time (e.g. when calculating ETA:s) the difference may be noticeable.
num_seeds
the number of peers that are seeding that this client is currently connected to.
num_peers
the number of peers this torrent currently is connected to. Peer connections that are in the half-open state (is attempting to connect) or are queued for later connection attempt do not count. Although they are visible in the peer list when you call get_peer_info().
num_complete num_incomplete
if the tracker sends scrape info in its announce reply, these fields will be set to the total number of peers that have the whole file and the total number of peers that are still downloading. set to -1 if the tracker did not send any scrape data in its announce reply.
list_seeds list_peers
the number of seeds in our peer list and the total number of peers (including seeds). We are not necessarily connected to all the peers in our peer list. This is the number of peers we know of in total, including banned peers and peers that we have failed to connect to.
connect_candidates
the number of peers in this torrent's peer list that is a candidate to be connected to. i.e. It has fewer connect attempts than the max fail count, it is not a seed if we are a seed, it is not banned etc. If this is 0, it means we don't know of any more peers that we can try.
num_pieces
the number of pieces that has been downloaded. It is equivalent to: std::accumulate(pieces->begin(), pieces->end()). So you don't have to count yourself. This can be used to see if anything has updated since last time if you want to keep a graph of the pieces up to date.
distributed_full_copies
the number of distributed copies of the torrent. Note that one copy may be spread out among many peers. It tells how many copies there are currently of the rarest piece(s) among the peers this client is connected to.
distributed_fraction

tells the share of pieces that have more copies than the rarest piece(s). Divide this number by 1000 to get the fraction.

For example, if distributed_full_copies is 2 and distrbuted_fraction is 500, it means that the rarest pieces have only 2 copies among the peers this torrent is connected to, and that 50% of all the pieces have more than two copies.

If we are a seed, the piece picker is deallocated as an optimization, and piece availability is no longer tracked. In this case the distributed copies members are set to -1.

distributed_copies

the number of distributed copies of the file. note that one copy may be spread out among many peers. This is a floating point representation of the distributed copies.

the integer part tells how many copies
there are of the rarest piece(s)
the fractional part tells the fraction of pieces that
have more copies than the rarest piece(s).
block_size
the size of a block, in bytes. A block is a sub piece, it is the number of bytes that each piece request asks for and the number of bytes that each bit in the partial_piece_info's bitset represents, see get_download_queue(). This is typically 16 kB, but it may be larger if the pieces are larger.
num_uploads
the number of unchoked peers in this torrent.
num_connections
the number of peer connections this torrent has, including half-open connections that hasn't completed the bittorrent handshake yet. This is always >= num_peers.
uploads_limit
the set limit of upload slots (unchoked peers) for this torrent.
connections_limit
the set limit of number of connections for this torrent.
up_bandwidth_queue down_bandwidth_queue
the number of peers in this torrent that are waiting for more bandwidth quota from the torrent rate limiter. This can determine if the rate you get from this torrent is bound by the torrents limit or not. If there is no limit set on this torrent, the peers might still be waiting for bandwidth quota from the global limiter, but then they are counted in the session_status object.
time_since_upload time_since_download
the number of seconds since any peer last uploaded from this torrent and the last time a downloaded piece passed the hash check, respectively. Note, when starting up a torrent that needs its files checked, piece may pass and that will be considered downloading for the purpose of this counter. -1 means there either hasn't been any uploading/downloading, or it was too long ago for libtorrent to remember (currently forgetting happens after about 18 hours)
active_time finished_time seeding_time
These keep track of the number of seconds this torrent has been active (not paused) and the number of seconds it has been active while being finished and active while being a seed. seeding_time should be <= finished_time which should be <= active_time. They are all saved in and restored from resume data, to keep totals across sessions.
seed_rank
A rank of how important it is to seed the torrent, it is used to determine which torrents to seed and which to queue. It is based on the peer to seed ratio from the tracker scrape. For more information, see queuing. Higher value means more important to seed
last_scrape
the number of seconds since this torrent acquired scrape data. If it has never done that, this value is -1.
priority
the priority of this torrent
state
the main state the torrent is in. See torrent_status::state_t.
need_save_resume
true if this torrent has unsaved changes to its download state and statistics since the last resume data was saved.
ip_filter_applies
true if the session global IP filter applies to this torrent. This defaults to true.
upload_mode
true if the torrent is blocked from downloading. This typically happens when a disk write operation fails. If the torrent is auto-managed, it will periodically be taken out of this state, in the hope that the disk condition (be it disk full or permission errors) has been resolved. If the torrent is not auto-managed, you have to explicitly take it out of the upload mode by calling set_upload_mode() on the torrent_handle.
share_mode
true if the torrent is currently in share-mode, i.e. not downloading the torrent, but just helping the swarm out.
super_seeding
true if the torrent is in super seeding mode
paused
set to true if the torrent is paused and false otherwise. It's only true if the torrent itself is paused. If the torrent is not running because the session is paused, this is still false. To know if a torrent is active or not, you need to inspect both torrent_status::paused and session::is_paused().
auto_managed
set to true if the torrent is auto managed, i.e. libtorrent is responsible for determining whether it should be started or queued. For more info see queuing
sequential_download
true when the torrent is in sequential download mode. In this mode pieces are downloaded in order rather than rarest first.
is_seeding
true if all pieces have been downloaded.
is_finished
true if all pieces that have a priority > 0 are downloaded. There is only a distinction between finished and seeding if some pieces or files have been set to priority 0, i.e. are not downloaded.
has_metadata
true if this torrent has metadata (either it was started from a .torrent file or the metadata has been downloaded). The only scenario where this can be false is when the torrent was started torrent-less (i.e. with just an info-hash and tracker ip, a magnet link for instance).
has_incoming
true if there has ever been an incoming connection attempt to this torrent.
seed_mode
true if the torrent is in seed_mode. If the torrent was started in seed mode, it will leave seed mode once all pieces have been checked or as soon as one piece fails the hash check.
moving_storage
this is true if this torrent's storage is currently being moved from one location to another. This may potentially be a long operation if a large file ends up being copied from one drive to another.
is_loaded
true if this torrent is loaded into RAM. A torrent can be started and still not loaded into RAM, in case it has not had any peers interested in it yet. Torrents are loaded on demand.
announcing_to_trackers announcing_to_lsd announcing_to_dht
these are set to true if this torrent is allowed to announce to the respective peer source. Whether they are true or false is determined by the queue logic/auto manager. Torrents that are not auto managed will always be allowed to announce to all peer sources.
stop_when_ready
this reflects whether the stop_when_ready flag is currently enabled on this torrent. For more information, see torrent_handle::stop_when_ready().
info_hash
the info-hash for this torrent

dht_storage_counters

Declared in "libtorrent/kademlia/dht_storage.hpp"

This structure hold the relevant counters for the storage

struct dht_storage_counters
{
   boost::int32_t torrents;
   boost::int32_t peers;
   boost::int32_t immutable_data;
   boost::int32_t mutable_data;
};

dht_storage_interface

Declared in "libtorrent/kademlia/dht_storage.hpp"

The DHT storage interface is a pure virtual class that can be implemented to customize how the data for the DHT is stored.

The default storage implementation uses three maps in RAM to save the peers, mutable and immutable items and it's designed to provide a fast and fully compliant behavior of the BEPs.

libtorrent comes with one built-in storage implementation: dht_default_storage (private non-accessible class). Its constructor function is called dht_default_storage_constructor().

struct dht_storage_interface
{
   virtual bool get_peers (sha1_hash const& info_hash
      , bool noseed, bool scrape
      , entry& peers) const = 0;
   virtual void announce_peer (sha1_hash const& info_hash
      , tcp::endpoint const& endp
      , std::string const& name, bool seed) = 0;
   virtual bool get_immutable_item (sha1_hash const& target
      , entry& item) const = 0;
   virtual void put_immutable_item (sha1_hash const& target
      , char const* buf, int size
      , address const& addr) = 0;
   virtual bool get_mutable_item_seq (sha1_hash const& target
      , boost::int64_t& seq) const = 0;
   virtual bool get_mutable_item (sha1_hash const& target
      , boost::int64_t seq, bool force_fill
      , entry& item) const = 0;
   virtual void put_mutable_item (sha1_hash const& target
      , char const* buf, int size
      , char const* sig
      , boost::int64_t seq
      , char const* pk
      , char const* salt, int salt_size
      , address const& addr) = 0;
   virtual void tick () = 0;
   virtual dht_storage_counters counters () const = 0;
   virtual ~dht_storage_interface ();
};

get_peers()

virtual bool get_peers (sha1_hash const& info_hash
      , bool noseed, bool scrape
      , entry& peers) const = 0;

This function retrieve the peers tracked by the DHT corresponding to the given info_hash. You can specify if you want only seeds and/or you are scraping the data.

For future implementers: If the torrent tracked contains a name, such a name must be stored as a string in peers["n"]

If the scrape parameter is true, you should fill these keys:

peers["BFpe"] - with the standard bit representation of a
                256 bloom filter containing the downloaders
peers["BFsd"] - with the standard bit representation of a
                256 bloom filter containing the seeders

If the scrape parameter is false, you should fill the key peers["values"] with a list containing a subset of peers tracked by the given info_hash. Such a list should consider the value of dht_settings::max_peers_reply. If noseed is true only peers marked as no seed should be included.

returns true if an entry with the info_hash is found and the data is returned inside the (entry) out parameter peers.

announce_peer()

virtual void announce_peer (sha1_hash const& info_hash
      , tcp::endpoint const& endp
      , std::string const& name, bool seed) = 0;

This function is named announce_peer for consistency with the upper layers, but has nothing to do with networking. Its only responsibility is store the peer in such a way that it's returned in the entry with the lookup_peers.

The name parameter is the name of the torrent if provided in the announce_peer DHT message. The length of this value should have a maximum length in the final storage. The default implementation truncate the value for a maximum of 50 characters.

get_immutable_item()

virtual bool get_immutable_item (sha1_hash const& target
      , entry& item) const = 0;

This function retrieves the immutable item given its target hash.

For future implementers: The value should be returned as an entry in the key item["v"].

returns true if the item is found and the data is returned inside the (entry) out parameter item.

put_immutable_item()

virtual void put_immutable_item (sha1_hash const& target
      , char const* buf, int size
      , address const& addr) = 0;

Store the item's data. This layer is only for storage. The authentication of the item is performed by the upper layer.

For implementers: This data can be stored only if the target is not already present. The implementation should consider the value of dht_settings::max_dht_items.

get_mutable_item_seq()

virtual bool get_mutable_item_seq (sha1_hash const& target
      , boost::int64_t& seq) const = 0;

This function retrieves the sequence number of a mutable item.

returns true if the item is found and the data is returned inside the out parameter seq.

get_mutable_item()

virtual bool get_mutable_item (sha1_hash const& target
      , boost::int64_t seq, bool force_fill
      , entry& item) const = 0;

This function retrieves the mutable stored in the DHT.

For implementers: The item sequence should be stored in the key item["seq"]. if force_fill is true or (0 <= seq and seq < item["seq"]) the following keys should be filled item["v"] - with the value no encoded. item["sig"] - with a string representation of the signature. item["k"] - with a string representation of the public key.

returns true if the item is found and the data is returned inside the (entry) out parameter item.

put_mutable_item()

virtual void put_mutable_item (sha1_hash const& target
      , char const* buf, int size
      , char const* sig
      , boost::int64_t seq
      , char const* pk
      , char const* salt, int salt_size
      , address const& addr) = 0;

Store the item's data. This layer is only for storage. The authentication of the item is performed by the upper layer.

For implementers: The sequence number should be checked if the item is already present. The implementation should consider the value of dht_settings::max_dht_items.

tick()

virtual void tick () = 0;

This function is called periodically (non-constant frequency).

For implementers: Use this functions for expire peers or items or any other storage cleanup.

generate_fingerprint()

Declared in "libtorrent/fingerprint.hpp"

std::string generate_fingerprint (std::string name
   , int major, int minor = 0, int revision = 0, int tag = 0);

This is a utility function to produce a client ID fingerprint formatted to the most common convention.

The name string should contain exactly two characters. These are the characters unique to your client, used to identify it. Make sure not to clash with anybody else. Here are some taken id's:

id chars client
'AZ' Azureus
'LT' libtorrent (default)
'BX' BittorrentX
'MT' Moonlight Torrent
'TS' Torrent Storm
'SS' Swarm Scope
'XT' Xan Torrent

There's an informal directory of client id's here.

The major, minor, revision and tag parameters are used to identify the version of your client.

to_hex()

Declared in "libtorrent/hex.hpp"

void to_hex (char const *in, int len, char* out);
std::string to_hex (std::string const& s);

The overload taking a std::string converts (binary) the string s to hexadecimal representation and returns it. The overload taking a char const* and a length converts the binary buffer [in, in + len) to hexadecimal and prints it to the buffer out. The caller is responsible for making sure the buffer pointed to by out is large enough, i.e. has at least len * 2 bytes of space.

from_hex()

Declared in "libtorrent/hex.hpp"

bool from_hex (char const *in, int len, char* out);

converts the buffer [in, in + len) from hexadecimal to binary. The binary output is written to the buffer pointed to by out. The caller is responsible for making sure the buffer at out has enough space for the result to be written to, i.e. (len + 1) / 2 bytes.

make_magnet_uri()

Declared in "libtorrent/magnet_uri.hpp"

std::string make_magnet_uri (torrent_handle const& handle);
std::string make_magnet_uri (torrent_info const& info);

Generates a magnet URI from the specified torrent. If the torrent handle is invalid, an empty string is returned.

For more information about magnet links, see magnet links.

parse_magnet_uri()

Declared in "libtorrent/magnet_uri.hpp"

void parse_magnet_uri (std::string const& uri, add_torrent_params& p, error_code& ec);

This function parses out information from the magnet link and populates the add_torrent_params object.

session_stats_metrics()

Declared in "libtorrent/session_stats.hpp"

std::vector<stats_metric> session_stats_metrics ();

This free function returns the list of available metrics exposed by libtorrent's statistics API. Each metric has a name and a value index. The value index is the index into the array in session_stats_alert where this metric's value can be found when the session stats is sampled (by calling post_session_stats()).

find_metric_idx()

Declared in "libtorrent/session_stats.hpp"

int find_metric_idx (char const* name);

given a name of a metric, this function returns the counter index of it, or -1 if it could not be found. The counter index is the index into the values array returned by session_stats_alert.

hash_value()

Declared in "libtorrent/torrent_handle.hpp"

std::size_t hash_value (torrent_status const& ts);

allows torrent_handle to be used in unordered_map and unordered_set.

is_utp_stream_logging()

Declared in "libtorrent/utp_stream.hpp"

bool is_utp_stream_logging ();

set_utp_stream_logging()

Declared in "libtorrent/utp_stream.hpp"

void set_utp_stream_logging (bool enable);

This function should be used at the very beginning and very end of your program.

version()

Declared in "libtorrent/version.hpp"

char const* version ();

returns the libtorrent version as string form in this format: "<major>.<minor>.<tiny>.<tag>"

dht_default_storage_constructor()

Declared in "libtorrent/kademlia/dht_storage.hpp"

dht_storage_interface* dht_default_storage_constructor (sha1_hash const& id
   , dht_settings const& settings);

sign_mutable_item()

Declared in "libtorrent/kademlia/item.hpp"

void sign_mutable_item (
   std::pair<char const*, int> v
   , std::pair<char const*, int> salt
   , boost::uint64_t seq
   , char const* pk
   , char const* sk
   , char* sig);

given a byte range v and an optional byte range salt, a sequence number, public key pk (must be 32 bytes) and a secret key sk (must be 64 bytes), this function produces a signature which is written into a 64 byte buffer pointed to by sig. The caller is responsible for allocating the destination buffer that's passed in as the sig argument. Typically it would be allocated on the stack.

verify_message()

Declared in "libtorrent/kademlia/msg.hpp"

bool verify_message (bdecode_node const& msg, key_desc_t const desc[]
   , bdecode_node ret[], int size, char* error, int error_size);

home

Plugins

libtorrent has a plugin interface for implementing extensions to the protocol. These can be general extensions for transferring metadata or peer exchange extensions, or it could be used to provide a way to customize the protocol to fit a particular (closed) network.

In short, the plugin interface makes it possible to:

  • register extension messages (sent in the extension handshake), see extensions.
  • add data and parse data from the extension handshake.
  • send extension messages and standard bittorrent messages.
  • override or block the handling of standard bittorrent messages.
  • save and restore state via the session state
  • see all alerts that are posted

a word of caution

Writing your own plugin is a very easy way to introduce serious bugs such as dead locks and race conditions. Since a plugin has access to internal structures it is also quite easy to sabotage libtorrent's operation.

All the callbacks in this interface are called with the main libtorrent thread mutex locked. And they are always called from the libtorrent network thread. In case portions of your plugin are called from other threads, typically the main thread, you cannot use any of the member functions on the internal structures in libtorrent, since those require the mutex to be locked. Furthermore, you would also need to have a mutex on your own shared data within the plugin, to make sure it is not accessed at the same time from the libtorrent thread (through a callback). See boost thread's mutex. If you need to send out a message from another thread, it is advised to use an internal queue, and do the actual sending in tick().

Since the plugin interface gives you easy access to internal structures, it is not supported as a stable API. Plugins should be considered specific to a specific version of libtorrent. Although, in practice the internals mostly don't change that dramatically.

plugin-interface

The plugin interface consists of three base classes that the plugin may implement. These are called plugin, torrent_plugin and peer_plugin. They are found in the <libtorrent/extensions.hpp> header.

These plugins are instantiated for each session, torrent and possibly each peer, respectively.

For plugins that only need per torrent state, it is enough to only implement torrent_plugin and pass a constructor function or function object to session::add_extension() or torrent_handle::add_extension() (if the torrent has already been started and you want to hook in the extension at run-time).

The signature of the function is:

boost::shared_ptr<torrent_plugin> (*)(torrent_handle const&, void*);

The second argument is the userdata passed to session::add_torrent() or torrent_handle::add_extension().

The function should return a boost::shared_ptr<torrent_plugin> which may or may not be 0. If it is a null pointer, the extension is simply ignored for this torrent. If it is a valid pointer (to a class inheriting torrent_plugin), it will be associated with this torrent and callbacks will be made on torrent events.

For more elaborate plugins which require session wide state, you would implement plugin, construct an object (in a boost::shared_ptr) and pass it in to session::add_extension().

custom alerts

Since plugins are running within internal libtorrent threads, one convenient way to communicate with the client is to post custom alerts.

The expected interface of any alert, apart from deriving from the alert base class, looks like this:

static const int alert_type = <unique alert ID>;
virtual int type() const { return alert_type; }

virtual std::string message() const;

virtual std::auto_ptr<alert> clone() const
{ return std::auto_ptr<alert>(new name(*this)); }

static const int static_category = <bitmask of alert::category_t flags>;
virtual int category() const { return static_category; }

virtual char const* what() const { return <string literal of the name of this alert>; }

The alert_type is used for the type-checking in alert_cast. It must not collide with any other alert. The built-in alerts in libtorrent will not use alert type IDs greater than user_alert_id. When defining your own alert, make sure it's greater than this constant.

type() is the run-time equivalence of the alert_type.

The message() virtual function is expected to construct a useful string representation of the alert and the event or data it represents. Something convenient to put in a log file for instance.

clone() is used internally to copy alerts. The suggested implementation of simply allocating a new instance as a copy of *this is all that's expected.

The static category is required for checking whether or not the category for a specific alert is enabled or not, without instantiating the alert. The category virtual function is the run-time equivalence.

The what() virtual function may simply be a string literal of the class name of your alert.

For more information, see the alert section.

plugin

Declared in "libtorrent/extensions.hpp"

this is the base class for a session plugin. One primary feature is that it is notified of all torrents that are added to the session, and can add its own torrent_plugins.

struct plugin
{
   virtual boost::uint32_t implemented_features ();
   virtual boost::shared_ptr<torrent_plugin> new_torrent (torrent_handle const&, void*);
   virtual void added (session_handle);
   virtual void register_dht_extensions (dht_extensions_t&);
   virtual void on_alert (alert const*);
   virtual bool on_unknown_torrent (sha1_hash const& /* info_hash */
      , peer_connection_handle const& /* pc */, add_torrent_params& /* p */);
   virtual void on_tick ();
   virtual bool on_optimistic_unchoke (std::vector<peer_connection_handle>& /* peers */);
   virtual void save_state (entry&) const;
   virtual void load_state (bdecode_node const&);

   enum feature_flags_t
   {
      optimistic_unchoke_feature,
      tick_feature,
   };
};

implemented_features()

virtual boost::uint32_t implemented_features ();

This function is expected to return a bitmask indicating which features this plugin implements. Some callbacks on this object may not be called unless the corresponding feature flag is returned here. Note that callbacks may still be called even if the corresponding feature is not specified in the return value here. See feature_flags_t for possible flags to return.

new_torrent()

virtual boost::shared_ptr<torrent_plugin> new_torrent (torrent_handle const&, void*);

this is called by the session every time a new torrent is added. The torrent* points to the internal torrent object created for the new torrent. The void* is the userdata pointer as passed in via add_torrent_params.

If the plugin returns a torrent_plugin instance, it will be added to the new torrent. Otherwise, return an empty shared_ptr to a torrent_plugin (the default).

added()

virtual void added (session_handle);

called when plugin is added to a session

register_dht_extensions()

virtual void register_dht_extensions (dht_extensions_t&);

called after a plugin is added allows the plugin to register DHT requests it would like to handle

on_alert()

virtual void on_alert (alert const*);

called when an alert is posted alerts that are filtered are not posted

on_unknown_torrent()

virtual bool on_unknown_torrent (sha1_hash const& /* info_hash */
      , peer_connection_handle const& /* pc */, add_torrent_params& /* p */);

return true if the add_torrent_params should be added

on_tick()

virtual void on_tick ();

called once per second

on_optimistic_unchoke()

virtual bool on_optimistic_unchoke (std::vector<peer_connection_handle>& /* peers */);

called when choosing peers to optimistically unchoke. peer's will be unchoked in the order they appear in the given vector. if the plugin returns true then the ordering provided will be used and no other plugin will be allowed to change it. If your plugin expects this to be called, make sure to include the flag optimistic_unchoke_feature in the return value from implemented_features().

save_state()

virtual void save_state (entry&) const;

called when saving settings state

load_state()

virtual void load_state (bdecode_node const&);

called when loading settings state

enum feature_flags_t

Declared in "libtorrent/extensions.hpp"

name value description
optimistic_unchoke_feature 1 include this bit if your plugin needs to alter the order of the optimistic unchoke of peers. i.e. have the on_optimistic_unchoke() callback be called.
tick_feature 2 include this bit if your plugin needs to have on_tick() called

torrent_plugin

Declared in "libtorrent/extensions.hpp"

Torrent plugins are associated with a single torrent and have a number of functions called at certain events. Many of its functions have the ability to change or override the default libtorrent behavior.

struct torrent_plugin
{
   virtual boost::shared_ptr<peer_plugin> new_connection (peer_connection_handle const&);
   virtual void on_piece_pass (int /*index*/);
   virtual void on_piece_failed (int /*index*/);
   virtual void tick ();
   virtual bool on_resume ();
   virtual bool on_pause ();
   virtual void on_files_checked ();
   virtual void on_state (int /*s*/);
   virtual void on_unload ();
   virtual void on_load ();
   virtual void on_add_peer (tcp::endpoint const&,
      int /*src*/, int /*flags*/);
};

new_connection()

virtual boost::shared_ptr<peer_plugin> new_connection (peer_connection_handle const&);

This function is called each time a new peer is connected to the torrent. You may choose to ignore this by just returning a default constructed shared_ptr (in which case you don't need to override this member function).

If you need an extension to the peer connection (which most plugins do) you are supposed to return an instance of your peer_plugin class. Which in turn will have its hook functions called on event specific to that peer.

The peer_connection_handle will be valid as long as the shared_ptr is being held by the torrent object. So, it is generally a good idea to not keep a shared_ptr to your own peer_plugin. If you want to keep references to it, use weak_ptr.

If this function throws an exception, the connection will be closed.

on_piece_failed() on_piece_pass()

virtual void on_piece_pass (int /*index*/);
virtual void on_piece_failed (int /*index*/);

These hooks are called when a piece passes the hash check or fails the hash check, respectively. The index is the piece index that was downloaded. It is possible to access the list of peers that participated in sending the piece through the torrent and the piece_picker.

tick()

virtual void tick ();

This hook is called approximately once per second. It is a way of making it easy for plugins to do timed events, for sending messages or whatever.

on_resume() on_pause()

virtual bool on_resume ();
virtual bool on_pause ();

These hooks are called when the torrent is paused and unpaused respectively. The return value indicates if the event was handled. A return value of true indicates that it was handled, and no other plugin after this one will have this hook function called, and the standard handler will also not be invoked. So, returning true effectively overrides the standard behavior of pause or unpause.

Note that if you call pause() or resume() on the torrent from your handler it will recurse back into your handler, so in order to invoke the standard handler, you have to keep your own state on whether you want standard behavior or overridden behavior.

on_files_checked()

virtual void on_files_checked ();

This function is called when the initial files of the torrent have been checked. If there are no files to check, this function is called immediately.

i.e. This function is always called when the torrent is in a state where it can start downloading.

on_state()

virtual void on_state (int /*s*/);

called when the torrent changes state the state is one of torrent_status::state_t enum members

on_unload() on_load()

virtual void on_unload ();
virtual void on_load ();

called when the torrent is unloaded from RAM and loaded again, respectively unload is called right before the torrent is unloaded and load is called right after it's loaded. i.e. the full torrent state is available when these callbacks are called.

on_add_peer()

virtual void on_add_peer (tcp::endpoint const&,
      int /*src*/, int /*flags*/);

called every time a new peer is added to the peer list. This is before the peer is connected to. For flags, see torrent_plugin::flags_t. The source argument refers to the source where we learned about this peer from. It's a bitmask, because many sources may have told us about the same peer. For peer source flags, see peer_info::peer_source_flags.

peer_plugin

Declared in "libtorrent/extensions.hpp"

peer plugins are associated with a specific peer. A peer could be both a regular bittorrent peer (bt_peer_connection) or one of the web seed connections (web_peer_connection or http_seed_connection). In order to only attach to certain peers, make your torrent_plugin::new_connection only return a plugin for certain peer connection types

struct peer_plugin
{
   virtual char const* type () const;
   virtual void add_handshake (entry&);
   virtual void on_disconnect (error_code const& /*ec*/);
   virtual void on_connected ();
   virtual bool on_handshake (char const* /*reserved_bits*/);
   virtual bool on_extension_handshake (bdecode_node const&);
   virtual bool on_have (int /*index*/);
   virtual bool on_bitfield (bitfield const& /*bitfield*/);
   virtual bool on_have_all ();
   virtual bool on_reject (peer_request const&);
   virtual bool on_request (peer_request const&);
   virtual bool on_unchoke ();
   virtual bool on_interested ();
   virtual bool on_allowed_fast (int /*index*/);
   virtual bool on_have_none ();
   virtual bool on_choke ();
   virtual bool on_not_interested ();
   virtual bool on_piece (peer_request const& /*piece*/
      , disk_buffer_holder& /*data*/);
   virtual bool on_suggest (int /*index*/);
   virtual bool on_cancel (peer_request const&);
   virtual bool on_dont_have (int /*index*/);
   virtual void sent_unchoke ();
   virtual void sent_payload (int /* bytes */);
   virtual bool can_disconnect (error_code const& /*ec*/);
   virtual bool on_extended (int /*length*/, int /*msg*/,
      buffer::const_interval /*body*/);
   virtual bool on_unknown_message (int /*length*/, int /*msg*/,
      buffer::const_interval /*body*/);
   virtual void on_piece_pass (int /*index*/);
   virtual void on_piece_failed (int /*index*/);
   virtual void tick ();
   virtual bool write_request (peer_request const&);
};

type()

virtual char const* type () const;

This function is expected to return the name of the plugin.

add_handshake()

virtual void add_handshake (entry&);

can add entries to the extension handshake this is not called for web seeds

on_disconnect()

virtual void on_disconnect (error_code const& /*ec*/);

called when the peer is being disconnected.

on_connected()

virtual void on_connected ();

called when the peer is successfully connected. Note that incoming connections will have been connected by the time the peer plugin is attached to it, and won't have this hook called.

on_handshake()

virtual bool on_handshake (char const* /*reserved_bits*/);

this is called when the initial BT handshake is received. Returning false means that the other end doesn't support this extension and will remove it from the list of plugins. this is not called for web seeds

on_extension_handshake()

virtual bool on_extension_handshake (bdecode_node const&);

called when the extension handshake from the other end is received if this returns false, it means that this extension isn't supported by this peer. It will result in this peer_plugin being removed from the peer_connection and destructed. this is not called for web seeds

on_bitfield() on_have_none() on_suggest() on_unchoke() on_cancel() on_have() on_choke() on_piece() on_request() on_reject() on_not_interested() on_interested() on_allowed_fast() on_have_all() on_dont_have()

virtual bool on_have (int /*index*/);
virtual bool on_bitfield (bitfield const& /*bitfield*/);
virtual bool on_have_all ();
virtual bool on_reject (peer_request const&);
virtual bool on_request (peer_request const&);
virtual bool on_unchoke ();
virtual bool on_interested ();
virtual bool on_allowed_fast (int /*index*/);
virtual bool on_have_none ();
virtual bool on_choke ();
virtual bool on_not_interested ();
virtual bool on_piece (peer_request const& /*piece*/
      , disk_buffer_holder& /*data*/);
virtual bool on_suggest (int /*index*/);
virtual bool on_cancel (peer_request const&);
virtual bool on_dont_have (int /*index*/);

returning true from any of the message handlers indicates that the plugin has handled the message. it will break the plugin chain traversing and not let anyone else handle the message, including the default handler.

sent_unchoke()

virtual void sent_unchoke ();

called after a choke message has been sent to the peer

sent_payload()

virtual void sent_payload (int /* bytes */);

called after piece data has been sent to the peer this can be used for stats book keeping

can_disconnect()

virtual bool can_disconnect (error_code const& /*ec*/);

called when libtorrent think this peer should be disconnected. if the plugin returns false, the peer will not be disconnected.

on_extended()

virtual bool on_extended (int /*length*/, int /*msg*/,
      buffer::const_interval /*body*/);

called when an extended message is received. If returning true, the message is not processed by any other plugin and if false is returned the next plugin in the chain will receive it to be able to handle it. This is not called for web seeds. thus function may be called more than once per incoming message, but only the last of the calls will the body size equal the length. i.e. Every time another fragment of the message is received, this function will be called, until finally the whole message has been received. The purpose of this is to allow early disconnects for invalid messages and for reporting progress of receiving large messages.

on_unknown_message()

virtual bool on_unknown_message (int /*length*/, int /*msg*/,
      buffer::const_interval /*body*/);

this is not called for web seeds

on_piece_failed() on_piece_pass()

virtual void on_piece_pass (int /*index*/);
virtual void on_piece_failed (int /*index*/);

called when a piece that this peer participated in either fails or passes the hash_check

tick()

virtual void tick ();

called approximately once every second

write_request()

virtual bool write_request (peer_request const&);

called each time a request message is to be sent. If true is returned, the original request message won't be sent and no other plugin will have this function called.

crypto_plugin

Declared in "libtorrent/extensions.hpp"

struct crypto_plugin
{
   virtual void set_incoming_key (unsigned char const* key, int len) = 0;
   virtual void set_outgoing_key (unsigned char const* key, int len) = 0;
   virtual int encrypt (std::vector<boost::asio::mutable_buffer>& /*send_vec*/) = 0;
   virtual void decrypt (std::vector<boost::asio::mutable_buffer>& /*receive_vec*/
      , int& /* consume */, int& /*produce*/, int& /*packet_size*/) = 0;
};

encrypt()

virtual int encrypt (std::vector<boost::asio::mutable_buffer>& /*send_vec*/) = 0;

encrypted the provided buffers and returns the number of bytes which are now ready to be sent to the lower layer. This must be at least as large as the number of bytes passed in and may be larger if there is additional data to be inserted at the head of the send buffer. The additional data is retrieved from the passed in vector. The vector must be cleared if no additional data is to be inserted.

decrypt()

virtual void decrypt (std::vector<boost::asio::mutable_buffer>& /*receive_vec*/
      , int& /* consume */, int& /*produce*/, int& /*packet_size*/) = 0;

decrypt the provided buffers. consume is set to the number of bytes which should be trimmed from the head of the buffers, default is 0

produce is set to the number of bytes of payload which are now ready to be sent to the upper layer. default is the number of bytes passed in receive_vec

packet_size is set to the minimum number of bytes which must be read to advance the next step of decryption. default is 0

create_smart_ban_plugin()

Declared in "libtorrent/extensions/smart_ban.hpp"

boost::shared_ptr<torrent_plugin> create_smart_ban_plugin (torrent_handle const&, void*);

constructor function for the smart ban extension. The extension keeps track of the data peers have sent us for failing pieces and once the piece completes and passes the hash check bans the peers that turned out to have sent corrupt data. This function can either be passed in the add_torrent_params::extensions field, or via torrent_handle::add_extension().

create_ut_metadata_plugin()

Declared in "libtorrent/extensions/ut_metadata.hpp"

boost::shared_ptr<torrent_plugin> create_ut_metadata_plugin (torrent_handle const&, void*);

constructor function for the ut_metadata extension. The ut_metadata extension allows peers to request the .torrent file (or more specifically the 'info'-dictionary of the .torrent file) from each other. This is the main building block in making magnet links work. This extension is enabled by default unless explicitly disabled in the session constructor.

This can either be passed in the add_torrent_params::extensions field, or via torrent_handle::add_extension().

create_ut_pex_plugin()

Declared in "libtorrent/extensions/ut_pex.hpp"

boost::shared_ptr<torrent_plugin> create_ut_pex_plugin (torrent_handle const&, void*);

constructor function for the ut_pex extension. The ut_pex extension allows peers to gossip about their connections, allowing the swarm stay well connected and peers aware of more peers in the swarm. This extension is enabled by default unless explicitly disabled in the session constructor.

This can either be passed in the add_torrent_params::extensions field, or via torrent_handle::add_extension().

home

Create Torrents

This section describes the functions and classes that are used to create torrent files. It is a layered API with low level classes and higher level convenience functions. A torrent is created in 4 steps:

  1. first the files that will be part of the torrent are determined.
  2. the torrent properties are set, such as tracker url, web seeds, DHT nodes etc.
  3. Read through all the files in the torrent, SHA-1 all the data and set the piece hashes.
  4. The torrent is bencoded into a file or buffer.

If there are a lot of files and or deep directory hierarchies to traverse, step one can be time consuming.

Typically step 3 is by far the most time consuming step, since it requires to read all the bytes from all the files in the torrent.

All of these classes and functions are declared by including libtorrent/create_torrent.hpp.

example:

file_storage fs;

// recursively adds files in directories
add_files(fs, "./my_torrent");

create_torrent t(fs);
t.add_tracker("http://my.tracker.com/announce");
t.set_creator("libtorrent example");

// reads the files and calculates the hashes
set_piece_hashes(t, ".");

ofstream out("my_torrent.torrent", std::ios_base::binary);
bencode(std::ostream_iterator<char>(out), t.generate());

create_torrent

Declared in "libtorrent/create_torrent.hpp"

This class holds state for creating a torrent. After having added all information to it, call create_torrent::generate() to generate the torrent. The entry that's returned can then be bencoded into a .torrent file using bencode().

struct create_torrent
{
   create_torrent (torrent_info const& ti);
   create_torrent (torrent_info const& ti, bool use_preformatted);
   create_torrent (file_storage& fs, int piece_size = 0
      , int pad_file_limit = -1, int flags = optimize_alignment
      , int alignment = -1);
   entry generate () const;
   file_storage const& files () const;
   void set_comment (char const* str);
   void set_creator (char const* str);
   void set_hash (int index, sha1_hash const& h);
   void set_file_hash (int index, sha1_hash const& h);
   void add_url_seed (std::string const& url);
   void add_http_seed (std::string const& url);
   void add_node (std::pair<std::string, int> const& node);
   void add_tracker (std::string const& url, int tier = 0);
   void set_root_cert (std::string const& pem);
   bool priv () const;
   void set_priv (bool p);
   int num_pieces () const;
   int piece_length () const;
   int piece_size (int i) const;
   std::vector<sha1_hash> const& merkle_tree () const;
   void add_similar_torrent (sha1_hash ih);
   void add_collection (std::string c);

   enum flags_t
   {
      optimize_alignment,
      merkle,
      modification_time,
      symlinks,
      mutable_torrent_support,
   };
};

create_torrent()

create_torrent (torrent_info const& ti);
create_torrent (torrent_info const& ti, bool use_preformatted);
create_torrent (file_storage& fs, int piece_size = 0
      , int pad_file_limit = -1, int flags = optimize_alignment
      , int alignment = -1);

The piece_size is the size of each piece in bytes. It must be a multiple of 16 kiB. If a piece size of 0 is specified, a piece_size will be calculated such that the torrent file is roughly 40 kB.

If a pad_size_limit is specified (other than -1), any file larger than the specified number of bytes will be preceded by a pad file to align it with the start of a piece. The pad_file_limit is ignored unless the optimize_alignment flag is passed. Typically it doesn't make sense to set this any lower than 4kiB.

The overload that takes a torrent_info object will make a verbatim copy of its info dictionary (to preserve the info-hash). The copy of the info dictionary will be used by create_torrent::generate(). This means that none of the member functions of create_torrent that affects the content of the info dictionary (such as set_hash()), will have any affect.

The flags arguments specifies options for the torrent creation. It can be any combination of the flags defined by create_torrent::flags_t.

alignment is used when pad files are enabled. This is the size eligible files are aligned to. The default is -1, which means the piece size of the torrent. The use_preformatted parameter can be set to true to preserve invalid encoding of the .torrent file.

generate()

entry generate () const;

This function will generate the .torrent file as a bencode tree. In order to generate the flat file, use the bencode() function.

It may be useful to add custom entries to the torrent file before bencoding it and saving it to disk.

If anything goes wrong during torrent generation, this function will return an empty entry structure. You can test for this condition by querying the type of the entry:

file_storage fs;
// add file ...
create_torrent t(fs);
// add trackers and piece hashes ...
e = t.generate();

if (e.type() == entry::undefined_t)
{
        // something went wrong
}

For instance, you cannot generate a torrent with 0 files in it. If you don't add any files to the file_storage, torrent generation will fail.

files()

file_storage const& files () const;

returns an immutable reference to the file_storage used to create the torrent from.

set_comment()

void set_comment (char const* str);

Sets the comment for the torrent. The string str should be utf-8 encoded. The comment in a torrent file is optional.

set_creator()

void set_creator (char const* str);

Sets the creator of the torrent. The string str should be utf-8 encoded. This is optional.

set_hash()

void set_hash (int index, sha1_hash const& h);

This sets the SHA-1 hash for the specified piece (index). You are required to set the hash for every piece in the torrent before generating it. If you have the files on disk, you can use the high level convenience function to do this. See set_piece_hashes().

set_file_hash()

void set_file_hash (int index, sha1_hash const& h);

This sets the sha1 hash for this file. This hash will end up under the key sha1 associated with this file (for multi-file torrents) or in the root info dictionary for single-file torrents.

add_url_seed() add_http_seed()

void add_url_seed (std::string const& url);
void add_http_seed (std::string const& url);

This adds a url seed to the torrent. You can have any number of url seeds. For a single file torrent, this should be an HTTP url, pointing to a file with identical content as the file of the torrent. For a multi-file torrent, it should point to a directory containing a directory with the same name as this torrent, and all the files of the torrent in it.

The second function, add_http_seed() adds an HTTP seed instead.

add_node()

void add_node (std::pair<std::string, int> const& node);

This adds a DHT node to the torrent. This especially useful if you're creating a tracker less torrent. It can be used by clients to bootstrap their DHT node from. The node is a hostname and a port number where there is a DHT node running. You can have any number of DHT nodes in a torrent.

add_tracker()

void add_tracker (std::string const& url, int tier = 0);

Adds a tracker to the torrent. This is not strictly required, but most torrents use a tracker as their main source of peers. The url should be an http:// or udp:// url to a machine running a bittorrent tracker that accepts announces for this torrent's info-hash. The tier is the fallback priority of the tracker. All trackers with tier 0 are tried first (in any order). If all fail, trackers with tier 1 are tried. If all of those fail, trackers with tier 2 are tried, and so on.

set_root_cert()

void set_root_cert (std::string const& pem);

This function sets an X.509 certificate in PEM format to the torrent. This makes the torrent an SSL torrent. An SSL torrent requires that each peer has a valid certificate signed by this root certificate. For SSL torrents, all peers are connecting over SSL connections. For more information, see the section on ssl torrents.

The string is not the path to the cert, it's the actual content of the certificate, loaded into a std::string.

priv() set_priv()

bool priv () const;
void set_priv (bool p);

Sets and queries the private flag of the torrent. Torrents with the private flag set ask clients to not use any other sources than the tracker for peers, and to not advertise itself publicly, apart from the tracker.

num_pieces()

int num_pieces () const;

returns the number of pieces in the associated file_storage object.

piece_length() piece_size()

int piece_length () const;
int piece_size (int i) const;

piece_length() returns the piece size of all pieces but the last one. piece_size() returns the size of the specified piece. these functions are just forwarding to the associated file_storage.

merkle_tree()

std::vector<sha1_hash> const& merkle_tree () const;

This function returns the merkle hash tree, if the torrent was created as a merkle torrent. The tree is created by generate() and won't be valid until that function has been called. When creating a merkle tree torrent, the actual tree itself has to be saved off separately and fed into libtorrent the first time you start seeding it, through the torrent_info::set_merkle_tree() function. From that point onwards, the tree will be saved in the resume data.

add_collection() add_similar_torrent()

void add_similar_torrent (sha1_hash ih);
void add_collection (std::string c);

Add similar torrents (by info-hash) or collections of similar torrents. Similar torrents are expected to share some files with this torrent. Torrents sharing a collection name with this torrent are also expected to share files with this torrent. A torrent may have more than one collection and more than one similar torrents. For more information, see BEP 38.

enum flags_t

Declared in "libtorrent/create_torrent.hpp"

name value description
optimize_alignment 1 This will insert pad files to align the files to piece boundaries, for optimized disk-I/O. This will minimize the number of bytes of pad- files, to keep the impact down for clients that don't support them.
merkle 2 This will create a merkle hash tree torrent. A merkle torrent cannot be opened in clients that don't specifically support merkle torrents. The benefit is that the resulting torrent file will be much smaller and not grow with more pieces. When this option is specified, it is recommended to have a fairly small piece size, say 64 kiB. When creating merkle torrents, the full hash tree is also generated and should be saved off separately. It is accessed through the create_torrent::merkle_tree() function.
modification_time 4 This will include the file modification time as part of the torrent. This is not enabled by default, as it might cause problems when you create a torrent from separate files with the same content, hoping to yield the same info-hash. If the files have different modification times, with this option enabled, you would get different info-hashes for the files.
symlinks 8 If this flag is set, files that are symlinks get a symlink attribute set on them and their data will not be included in the torrent. This is useful if you need to reconstruct a file hierarchy which contains symlinks.
mutable_torrent_support 16 to create a torrent that can be updated via a mutable torrent (see BEP38). This also needs to be enabled for torrents that update another torrent.

add_files()

Declared in "libtorrent/create_torrent.hpp"

void add_files (file_storage& fs, std::string const& file
   , boost::function<bool(std::string)> p, boost::uint32_t flags = 0);
void add_files (file_storage& fs, std::string const& file
   , boost::uint32_t flags = 0);

Adds the file specified by path to the file_storage object. In case path refers to a directory, files will be added recursively from the directory.

If specified, the predicate p is called once for every file and directory that is encountered. Files for which p returns true are added, and directories for which p returns true are traversed. p must have the following signature:

bool Pred(std::string const& p);

The path that is passed in to the predicate is the full path of the file or directory. If no predicate is specified, all files are added, and all directories are traversed.

The ".." directory is never traversed.

The flags argument should be the same as the flags passed to the create_torrent constructor.

set_piece_hashes()

Declared in "libtorrent/create_torrent.hpp"

void set_piece_hashes (create_torrent& t, std::string const& p
   , boost::function<void(int)> const& f, error_code& ec);
inline void set_piece_hashes (create_torrent& t, std::string const& p);
inline void set_piece_hashes (create_torrent& t, std::string const& p, error_code& ec);

This function will assume that the files added to the torrent file exists at path p, read those files and hash the content and set the hashes in the create_torrent object. The optional function f is called in between every hash that is set. f must have the following signature:

void Fun(int);

The overloads that don't take an error_code& may throw an exception in case of a file error, the other overloads sets the error code to reflect the error, if any.

home

Error Codes

libtorrent_exception

Declared in "libtorrent/error_code.hpp"

struct libtorrent_exception: std::exception
{
   libtorrent_exception (libtorrent_exception const&) = default;
   virtual const char* what () const TORRENT_EXCEPTION_THROW_SPECIFIER;
   virtual ~libtorrent_exception () TORRENT_EXCEPTION_THROW_SPECIFIER;
   libtorrent_exception& operator= (libtorrent_exception const&) = default;
   libtorrent_exception (error_code const& s);
   error_code error () const;
};

storage_error

Declared in "libtorrent/error_code.hpp"

used by storage to return errors also includes which underlying file the error happened on

struct storage_error
{
   storage_error (error_code e);
   storage_error ();
   operator bool () const;
   char const* operation_str () const;

   error_code ec;
   boost::int32_t file:24;
   boost::uint32_t operation:8;
};

operation_str()

char const* operation_str () const;

Returns a string literal representing the file operation that failed. If there were no failure, it returns an empty string.

ec
the error that occurred
file
the file the error occurred on
operation
A code from file_operation_t enum, indicating what kind of operation failed.

bdecode_category()

Declared in "libtorrent/bdecode.hpp"

boost::system::error_category& bdecode_category ();

libtorrent_category()

Declared in "libtorrent/error_code.hpp"

boost::system::error_category& libtorrent_category ();

return the instance of the libtorrent_error_category which maps libtorrent error codes to human readable error messages.

http_category()

Declared in "libtorrent/error_code.hpp"

boost::system::error_category& http_category ();

returns the error_category for HTTP errors

gzip_category()

Declared in "libtorrent/gzip.hpp"

boost::system::error_category& gzip_category ();

get the error_category for zip errors

i2p_category()

Declared in "libtorrent/i2p_stream.hpp"

boost::system::error_category& i2p_category ();

returns the error category for I2P errors

socks_category()

Declared in "libtorrent/socks5_stream.hpp"

boost::system::error_category& socks_category ();

returns the error_category for SOCKS5 errors

upnp_category()

Declared in "libtorrent/upnp.hpp"

boost::system::error_category& upnp_category ();

the boost.system error category for UPnP errors

enum error_code_enum

Declared in "libtorrent/bdecode.hpp"

name value description
no_error 0 Not an error
expected_digit 1 expected digit in bencoded string
expected_colon 2 expected colon in bencoded string
unexpected_eof 3 unexpected end of file in bencoded string
expected_value 4 expected value (list, dict, int or string) in bencoded string
depth_exceeded 5 bencoded recursion depth limit exceeded
limit_exceeded 6 bencoded item count limit exceeded
overflow 7 integer overflow
error_code_max 8 the number of error codes

enum error_code_enum

Declared in "libtorrent/error_code.hpp"

name value description
no_error 0 Not an error
file_collision 1 Two torrents has files which end up overwriting each other
failed_hash_check 2 A piece did not match its piece hash
torrent_is_no_dict 3 The .torrent file does not contain a bencoded dictionary at its top level
torrent_missing_info 4 The .torrent file does not have an info dictionary
torrent_info_no_dict 5 The .torrent file's info entry is not a dictionary
torrent_missing_piece_length 6 The .torrent file does not have a piece length entry
torrent_missing_name 7 The .torrent file does not have a name entry
torrent_invalid_name 8 The .torrent file's name entry is invalid
torrent_invalid_length 9 The length of a file, or of the whole .torrent file is invalid. Either negative or not an integer
torrent_file_parse_failed 10 Failed to parse a file entry in the .torrent
torrent_missing_pieces 11 The pieces field is missing or invalid in the .torrent file
torrent_invalid_hashes 12 The pieces string has incorrect length
too_many_pieces_in_torrent 13 The .torrent file has more pieces than is supported by libtorrent
invalid_swarm_metadata 14 The metadata (.torrent file) that was received from the swarm matched the info-hash, but failed to be parsed
invalid_bencoding 15 The file or buffer is not correctly bencoded
no_files_in_torrent 16 The .torrent file does not contain any files
invalid_escaped_string 17 The string was not properly url-encoded as expected
session_is_closing 18 Operation is not permitted since the session is shutting down
duplicate_torrent 19 There's already a torrent with that info-hash added to the session
invalid_torrent_handle 20 The supplied torrent_handle is not referring to a valid torrent
invalid_entry_type 21 The type requested from the entry did not match its type
missing_info_hash_in_uri 22 The specified URI does not contain a valid info-hash
file_too_short 23 One of the files in the torrent was unexpectedly small. This might be caused by files being changed by an external process
unsupported_url_protocol 24 The URL used an unknown protocol. Currently http and https (if built with openssl support) are recognized. For trackers udp is recognized as well.
url_parse_error 25 The URL did not conform to URL syntax and failed to be parsed
peer_sent_empty_piece 26 The peer sent a 'piece' message of length 0
parse_failed 27 A bencoded structure was corrupt and failed to be parsed
invalid_file_tag 28 The fast resume file was missing or had an invalid file version tag
missing_info_hash 29 The fast resume file was missing or had an invalid info-hash
mismatching_info_hash 30 The info-hash did not match the torrent
invalid_hostname 31 The URL contained an invalid hostname
invalid_port 32 The URL had an invalid port
port_blocked 33 The port is blocked by the port-filter, and prevented the connection
expected_close_bracket_in_address 34 The IPv6 address was expected to end with ']'
destructing_torrent 35 The torrent is being destructed, preventing the operation to succeed
timed_out 36 The connection timed out
upload_upload_connection 37 The peer is upload only, and we are upload only. There's no point in keeping the connection
uninteresting_upload_peer 38 The peer is upload only, and we're not interested in it. There's no point in keeping the connection
invalid_info_hash 39 The peer sent an unknown info-hash
torrent_paused 40 The torrent is paused, preventing the operation from succeeding
invalid_have 41 The peer sent an invalid have message, either wrong size or referring to a piece that doesn't exist in the torrent
invalid_bitfield_size 42 The bitfield message had the incorrect size
too_many_requests_when_choked 43 The peer kept requesting pieces after it was choked, possible abuse attempt.
invalid_piece 44 The peer sent a piece message that does not correspond to a piece request sent by the client
no_memory 45 memory allocation failed
torrent_aborted 46 The torrent is aborted, preventing the operation to succeed
self_connection 47 The peer is a connection to ourself, no point in keeping it
invalid_piece_size 48 The peer sent a piece message with invalid size, either negative or greater than one block
timed_out_no_interest 49 The peer has not been interesting or interested in us for too long, no point in keeping it around
timed_out_inactivity 50 The peer has not said anything in a long time, possibly dead
timed_out_no_handshake 51 The peer did not send a handshake within a reasonable amount of time, it might not be a bittorrent peer
timed_out_no_request 52 The peer has been unchoked for too long without requesting any data. It might be lying about its interest in us
invalid_choke 53 The peer sent an invalid choke message
invalid_unchoke 54 The peer send an invalid unchoke message
invalid_interested 55 The peer sent an invalid interested message
invalid_not_interested 56 The peer sent an invalid not-interested message
invalid_request 57 The peer sent an invalid piece request message
invalid_hash_list 58 The peer sent an invalid hash-list message (this is part of the merkle-torrent extension)
invalid_hash_piece 59 The peer sent an invalid hash-piece message (this is part of the merkle-torrent extension)
invalid_cancel 60 The peer sent an invalid cancel message
invalid_dht_port 61 The peer sent an invalid DHT port-message
invalid_suggest 62 The peer sent an invalid suggest piece-message
invalid_have_all 63 The peer sent an invalid have all-message
invalid_have_none 64 The peer sent an invalid have none-message
invalid_reject 65 The peer sent an invalid reject message
invalid_allow_fast 66 The peer sent an invalid allow fast-message
invalid_extended 67 The peer sent an invalid extension message ID
invalid_message 68 The peer sent an invalid message ID
sync_hash_not_found 69 The synchronization hash was not found in the encrypted handshake
invalid_encryption_constant 70 The encryption constant in the handshake is invalid
no_plaintext_mode 71 The peer does not support plaintext, which is the selected mode
no_rc4_mode 72 The peer does not support rc4, which is the selected mode
unsupported_encryption_mode 73 The peer does not support any of the encryption modes that the client supports
unsupported_encryption_mode_selected 74 The peer selected an encryption mode that the client did not advertise and does not support
invalid_pad_size 75 The pad size used in the encryption handshake is of invalid size
invalid_encrypt_handshake 76 The encryption handshake is invalid
no_incoming_encrypted 77 The client is set to not support incoming encrypted connections and this is an encrypted connection
no_incoming_regular 78 The client is set to not support incoming regular bittorrent connections, and this is a regular connection
duplicate_peer_id 79 The client is already connected to this peer-ID
torrent_removed 80 Torrent was removed
packet_too_large 81 The packet size exceeded the upper sanity check-limit
reserved 82  
http_error 83 The web server responded with an error
missing_location 84 The web server response is missing a location header
invalid_redirection 85 The web seed redirected to a path that no longer matches the .torrent directory structure
redirecting 86 The connection was closed because it redirected to a different URL
invalid_range 87 The HTTP range header is invalid
no_content_length 88 The HTTP response did not have a content length
banned_by_ip_filter 89 The IP is blocked by the IP filter
too_many_connections 90 At the connection limit
peer_banned 91 The peer is marked as banned
stopping_torrent 92 The torrent is stopping, causing the operation to fail
too_many_corrupt_pieces 93 The peer has sent too many corrupt pieces and is banned
torrent_not_ready 94 The torrent is not ready to receive peers
peer_not_constructed 95 The peer is not completely constructed yet
session_closing 96 The session is closing, causing the operation to fail
optimistic_disconnect 97 The peer was disconnected in order to leave room for a potentially better peer
torrent_finished 98 The torrent is finished
no_router 99 No UPnP router found
metadata_too_large 100 The metadata message says the metadata exceeds the limit
invalid_metadata_request 101 The peer sent an invalid metadata request message
invalid_metadata_size 102 The peer advertised an invalid metadata size
invalid_metadata_offset 103 The peer sent a message with an invalid metadata offset
invalid_metadata_message 104 The peer sent an invalid metadata message
pex_message_too_large 105 The peer sent a peer exchange message that was too large
invalid_pex_message 106 The peer sent an invalid peer exchange message
invalid_lt_tracker_message 107 The peer sent an invalid tracker exchange message
too_frequent_pex 108 The peer sent an pex messages too often. This is a possible attempt of and attack
no_metadata 109 The operation failed because it requires the torrent to have the metadata (.torrent file) and it doesn't have it yet. This happens for magnet links before they have downloaded the metadata, and also torrents added by URL.
invalid_dont_have 110 The peer sent an invalid dont_have message. The don't have message is an extension to allow peers to advertise that the no longer has a piece they previously had.
requires_ssl_connection 111 The peer tried to connect to an SSL torrent without connecting over SSL.
invalid_ssl_cert 112 The peer tried to connect to a torrent with a certificate for a different torrent.
not_an_ssl_torrent 113 the torrent is not an SSL torrent, and the operation requires an SSL torrent
banned_by_port_filter 114 peer was banned because its listen port is within a banned port range, as specified by the port_filter.
unsupported_protocol_version 120 The NAT-PMP router responded with an unsupported protocol version
natpmp_not_authorized 121 You are not authorized to map ports on this NAT-PMP router
network_failure 122 The NAT-PMP router failed because of a network failure
no_resources 123 The NAT-PMP router failed because of lack of resources
unsupported_opcode 124 The NAT-PMP router failed because an unsupported opcode was sent
missing_file_sizes 130 The resume data file is missing the 'file sizes' entry
no_files_in_resume_data 131 The resume data file 'file sizes' entry is empty
missing_pieces 132 The resume data file is missing the 'pieces' and 'slots' entry
mismatching_number_of_files 133 The number of files in the resume data does not match the number of files in the torrent
mismatching_file_size 134 One of the files on disk has a different size than in the fast resume file
mismatching_file_timestamp 135 One of the files on disk has a different timestamp than in the fast resume file
not_a_dictionary 136 The resume data file is not a dictionary
invalid_blocks_per_piece 137 The 'blocks per piece' entry is invalid in the resume data file
missing_slots 138 The resume file is missing the 'slots' entry, which is required for torrents with compact allocation. DEPRECATED
too_many_slots 139 The resume file contains more slots than the torrent
invalid_slot_list 140 The 'slot' entry is invalid in the resume data
invalid_piece_index 141 One index in the 'slot' list is invalid
pieces_need_reorder 142 The pieces on disk needs to be re-ordered for the specified allocation mode. This happens if you specify sparse allocation and the files on disk are using compact storage. The pieces needs to be moved to their right position. DEPRECATED
resume_data_not_modified 143 this error is returned when asking to save resume data and specifying the flag to only save when there's anything new to save (torrent_handle::only_if_modified) and there wasn't anything changed.
http_parse_error 150 The HTTP header was not correctly formatted
http_missing_location 151 The HTTP response was in the 300-399 range but lacked a location header
http_failed_decompress 152 The HTTP response was encoded with gzip or deflate but decompressing it failed
no_i2p_router 160 The URL specified an i2p address, but no i2p router is configured
no_i2p_endpoint 161 i2p acceptor is not available yet, can't announce without endpoint
scrape_not_available 170 The tracker URL doesn't support transforming it into a scrape URL. i.e. it doesn't contain "announce.
invalid_tracker_response 171 invalid tracker response
invalid_peer_dict 172 invalid peer dictionary entry. Not a dictionary
tracker_failure 173 tracker sent a failure message
invalid_files_entry 174 missing or invalid 'files' entry
invalid_hash_entry 175 missing or invalid 'hash' entry
invalid_peers_entry 176 missing or invalid 'peers' and 'peers6' entry
invalid_tracker_response_length 177 udp tracker response packet has invalid size
invalid_tracker_transaction_id 178 invalid transaction id in udp tracker response
invalid_tracker_action 179 invalid action field in udp tracker response
error_code_max 180 the number of error codes

enum http_errors

Declared in "libtorrent/error_code.hpp"

name value description
cont 100  
ok 200  
created 201  
accepted 202  
no_content 204  
multiple_choices 300  
moved_permanently 301  
moved_temporarily 302  
not_modified 304  
bad_request 400  
unauthorized 401  
forbidden 403  
not_found 404  
internal_server_error 500  
not_implemented 501  
bad_gateway 502  
service_unavailable 503  

enum error_code_enum

Declared in "libtorrent/gzip.hpp"

name value description
no_error 0 Not an error
invalid_gzip_header 1 the supplied gzip buffer has invalid header
inflated_data_too_large 2 the gzip buffer would inflate to more bytes than the specified maximum size, and was rejected.
data_did_not_terminate 3 available inflate data did not terminate
space_exhausted 4 output space exhausted before completing inflate
invalid_block_type 5 invalid block type (type == 3)
invalid_stored_block_length 6 stored block length did not match one's complement
too_many_length_or_distance_codes 7 dynamic block code description: too many length or distance codes
code_lengths_codes_incomplete 8 dynamic block code description: code lengths codes incomplete
repeat_lengths_with_no_first_length 9 dynamic block code description: repeat lengths with no first length
repeat_more_than_specified_lengths 10 dynamic block code description: repeat more than specified lengths
invalid_literal_length_code_lengths 11 dynamic block code description: invalid literal/length code lengths
invalid_distance_code_lengths 12 dynamic block code description: invalid distance code lengths
invalid_literal_code_in_block 13 invalid literal/length or distance code in fixed or dynamic block
distance_too_far_back_in_block 14 distance is too far back in fixed or dynamic block
unknown_gzip_error 15 an unknown error occurred during gzip inflation
error_code_max 16 the number of error codes

enum i2p_error_code

Declared in "libtorrent/i2p_stream.hpp"

name value description
no_error 0  
parse_failed 1  
cant_reach_peer 2  
i2p_error 3  
invalid_key 4  
invalid_id 5  
timeout 6  
key_not_found 7  
duplicated_id 8  
num_errors 9  

enum socks_error_code

Declared in "libtorrent/socks5_stream.hpp"

name value description
no_error 0  
unsupported_version 1  
unsupported_authentication_method 2  
unsupported_authentication_version 3  
authentication_error 4  
username_required 5  
general_failure 6  
command_not_supported 7  
no_identd 8  
identd_error 9  
num_errors 10  

enum error_code_enum

Declared in "libtorrent/upnp.hpp"

name value description
no_error 0 No error
invalid_argument 402 One of the arguments in the request is invalid
action_failed 501 The request failed
value_not_in_array 714 The specified value does not exist in the array
source_ip_cannot_be_wildcarded 715 The source IP address cannot be wild-carded, but must be fully specified
external_port_cannot_be_wildcarded 716 The external port cannot be wildcarded, but must be specified
port_mapping_conflict 718 The port mapping entry specified conflicts with a mapping assigned previously to another client
internal_port_must_match_external 724 Internal and external port value must be the same
only_permanent_leases_supported 725 The NAT implementation only supports permanent lease times on port mappings
remote_host_must_be_wildcard 726 RemoteHost must be a wildcard and cannot be a specific IP addres or DNS name
external_port_must_be_wildcard 727 ExternalPort must be a wildcard and cannot be a specific port

home

Storage

file_slice

Declared in "libtorrent/file_storage.hpp"

represents a window of a file in a torrent.

The file_index refers to the index of the file (in the torrent_info). To get the path and filename, use file_path() and give the file_index as argument. The offset is the byte offset in the file where the range starts, and size is the number of bytes this range is. The size + offset will never be greater than the file size.

struct file_slice
{
   int file_index;
   boost::int64_t offset;
   boost::int64_t size;
};
file_index
the index of the file
offset
the offset from the start of the file, in bytes
size
the size of the window, in bytes

file_storage

Declared in "libtorrent/file_storage.hpp"

The file_storage class represents a file list and the piece size. Everything necessary to interpret a regular bittorrent storage file structure.

class file_storage
{
   bool is_valid () const;
   void reserve (int num_files);
   void add_file (std::string const& path, boost::int64_t file_size, int file_flags = 0
      , std::time_t mtime = 0, std::string const& symlink_path = "");
   void add_file_borrow (char const* filename, int filename_len
      , std::string const& path, boost::int64_t file_size
      , boost::uint32_t file_flags = 0, char const* filehash = 0
      , boost::int64_t mtime = 0, std::string const& symlink_path = "");
   void rename_file (int index, std::string const& new_filename);
   std::vector<file_slice> map_block (int piece, boost::int64_t offset
      , int size) const;
   peer_request map_file (int file, boost::int64_t offset, int size) const;
   int num_files () const;
   boost::int64_t total_size () const;
   void set_num_pieces (int n);
   int num_pieces () const;
   void set_piece_length (int l);
   int piece_length () const;
   int piece_size (int index) const;
   std::string const& name () const;
   void set_name (std::string const& n);
   void swap (file_storage& ti);
   void unload ();
   bool is_loaded () const;
   void optimize (int pad_file_limit = -1, int alignment = -1
      , bool tail_padding = false);
   sha1_hash hash (int index) const;
   std::string file_name (int index) const;
   boost::int64_t file_offset (int index) const;
   time_t mtime (int index) const;
   bool pad_file_at (int index) const;
   std::string const& symlink (int index) const;
   std::string file_path (int index, std::string const& save_path = "") const;
   boost::int64_t file_size (int index) const;
   boost::uint32_t file_path_hash (int index, std::string const& save_path) const;
   void all_path_hashes (boost::unordered_set<boost::uint32_t>& table) const;
   std::vector<std::string> const& paths () const;
   int file_flags (int index) const;
   bool file_absolute_path (int index) const;
   int file_index_at_offset (boost::int64_t offset) const;
   char const* file_name_ptr (int index) const;
   int file_name_len (int index) const;
   void apply_pointer_offset (ptrdiff_t off);

   enum flags_t
   {
      pad_file,
      attribute_hidden,
      attribute_executable,
      attribute_symlink,
   };

   enum file_flags_t
   {
      flag_pad_file,
      flag_hidden,
      flag_executable,
      flag_symlink,
   };
};

is_valid()

bool is_valid () const;

returns true if the piece length has been initialized on the file_storage. This is typically taken as a proxy of whether the file_storage as a whole is initialized or not.

reserve()

void reserve (int num_files);

allocates space for num_files in the internal file list. This can be used to avoid reallocating the internal file list when the number of files to be added is known up-front.

add_file() add_file_borrow()

void add_file (std::string const& path, boost::int64_t file_size, int file_flags = 0
      , std::time_t mtime = 0, std::string const& symlink_path = "");
void add_file_borrow (char const* filename, int filename_len
      , std::string const& path, boost::int64_t file_size
      , boost::uint32_t file_flags = 0, char const* filehash = 0
      , boost::int64_t mtime = 0, std::string const& symlink_path = "");

Adds a file to the file storage. The add_file_borrow version expects that filename points to a string of filename_len bytes that is the file name (without a path) of the file that's being added. This memory is borrowed, i.e. it is the caller's responsibility to make sure it stays valid throughout the lifetime of this file_storage object or any copy of it. The same thing applies to filehash, which is an optional pointer to a 20 byte binary SHA-1 hash of the file.

if filename is NULL, the filename from path is used and not borrowed. In this case filename_len is ignored.

The path argument is the full path (in the torrent file) to the file to add. Note that this is not supposed to be an absolute path, but it is expected to include the name of the torrent as the first path element.

file_size is the size of the file in bytes.

The file_flags argument sets attributes on the file. The file attributes is an extension and may not work in all bittorrent clients.

For possible file attributes, see file_storage::flags_t.

The mtime argument is optional and can be set to 0. If non-zero, it is the posix time of the last modification time of this file.

symlink_path is the path the file is a symlink to. To make this a symlink you also need to set the file_storage::flag_symlink file flag.

If more files than one are added, certain restrictions to their paths apply. In a multi-file file storage (torrent), all files must share the same root directory.

That is, the first path element of all files must be the same. This shared path element is also set to the name of the torrent. It can be changed by calling set_name.

rename_file()

void rename_file (int index, std::string const& new_filename);

renames the file at index to new_filename. Keep in mind that filenames are expected to be UTF-8 encoded.

map_block()

std::vector<file_slice> map_block (int piece, boost::int64_t offset
      , int size) const;

returns a list of file_slice objects representing the portions of files the specified piece index, byte offset and size range overlaps. this is the inverse mapping of map_file().

Preconditions of this function is that the input range is within the torrents address space. piece may not be negative and

piece * piece_size + offset + size

may not exceed the total size of the torrent.

map_file()

peer_request map_file (int file, boost::int64_t offset, int size) const;

returns a peer_request representing the piece index, byte offset and size the specified file range overlaps. This is the inverse mapping ove map_block(). Note that the peer_request return type is meant to hold bittorrent block requests, which may not be larger than 16 kiB. Mapping a range larger than that may return an overflown integer.

num_files()

int num_files () const;

returns the number of files in the file_storage

total_size()

boost::int64_t total_size () const;

returns the total number of bytes all the files in this torrent spans

num_pieces() set_num_pieces()

void set_num_pieces (int n);
int num_pieces () const;

set and get the number of pieces in the torrent

piece_length() set_piece_length()

void set_piece_length (int l);
int piece_length () const;

set and get the size of each piece in this torrent. This size is typically an even power of 2. It doesn't have to be though. It should be divisible by 16kiB however.

piece_size()

int piece_size (int index) const;

returns the piece size of index. This will be the same as piece_length(), except for the last piece, which may be shorter.

set_name() name()

std::string const& name () const;
void set_name (std::string const& n);

set and get the name of this torrent. For multi-file torrents, this is also the name of the root directory all the files are stored in.

swap()

void swap (file_storage& ti);

swap all content of this with ti.

unload()

void unload ();

deallocates most of the memory used by this instance, leaving it only partially usable

is_loaded()

bool is_loaded () const;

returns true when populated with at least one file

optimize()

void optimize (int pad_file_limit = -1, int alignment = -1
      , bool tail_padding = false);

if pad_file_limit >= 0, files larger than that limit will be padded, default is to not add any padding (-1). The alignment specifies the alignment files should be padded to. This defaults to the piece size (-1) but it may also make sense to set it to 16 kiB, or something divisible by 16 kiB. If pad_file_limit is 0, every file will be padded (except empty ones). tail_padding indicates whether aligned files also are padded at the end to make them end aligned. This is required for mutable torrents, since piece hashes are compared

file_path_hash()

boost::uint32_t file_path_hash (int index, std::string const& save_path) const;

returns the crc32 hash of file_path(index)

all_path_hashes()

void all_path_hashes (boost::unordered_set<boost::uint32_t>& table) const;

this will add the CRC32 hash of all directory entries to the table. No filename will be included, just directories. Every depth of directories are added separately to allow test for collisions with files at all levels. i.e. if one path in the torrent is foo/bar/baz, the CRC32 hashes for foo, foo/bar and foo/bar/baz will be added to the set.

file_flags()

int file_flags (int index) const;

returns a bitmask of flags from file_flags_t that apply to file at index.

file_absolute_path()

bool file_absolute_path (int index) const;

returns true if the file at the specified index has been renamed to have an absolute path, i.e. is not anchored in the save path of the torrent.

file_index_at_offset()

int file_index_at_offset (boost::int64_t offset) const;

returns the index of the file at the given offset in the torrent

file_name_len() file_name_ptr()

char const* file_name_ptr (int index) const;
int file_name_len (int index) const;

low-level function. returns a pointer to the internal storage for the filename. This string may not be null terminated! the file_name_len() function returns the length of the filename.

apply_pointer_offset()

void apply_pointer_offset (ptrdiff_t off);

if the backing buffer changed for this storage, this is the pointer offset to add to any pointers to make them point into the new buffer

enum flags_t

Declared in "libtorrent/file_storage.hpp"

name value description
pad_file 1 the file is a pad file. It's required to contain zeroes at it will not be saved to disk. Its purpose is to make the following file start on a piece boundary.
attribute_hidden 2 this file has the hidden attribute set. This is primarily a windows attribute
attribute_executable 4 this file has the executable attribute set.
attribute_symlink 8 this file is a symbolic link. It should have a link target string associated with it.

enum file_flags_t

Declared in "libtorrent/file_storage.hpp"

name value description
flag_pad_file 1 this file is a pad file. The creator of the torrent promises the file is entirely filled with zeroes and does not need to be downloaded. The purpose is just to align the next file to either a block or piece boundary.
flag_hidden 2 this file is hidden (sets the hidden attribute on windows)
flag_executable 4 this file is executable (sets the executable bit on posix like systems)
flag_symlink 8 this file is a symlink. The symlink target is specified in a separate field

storage_params

Declared in "libtorrent/storage_defs.hpp"

see default_storage::default_storage()

struct storage_params
{
   storage_params ();

   file_storage const* files;
   file_storage const* mapped_files;
   std::string path;
   file_pool* pool;
   storage_mode_t mode;
   std::vector<boost::uint8_t> const* priorities;
   torrent_info const* info;
};

default_storage_constructor()

Declared in "libtorrent/storage_defs.hpp"

storage_interface* default_storage_constructor (storage_params const&);

the constructor function for the regular file storage. This is the default value for add_torrent_params::storage.

disabled_storage_constructor()

Declared in "libtorrent/storage_defs.hpp"

storage_interface* disabled_storage_constructor (storage_params const&);

the constructor function for the disabled storage. This can be used for testing and benchmarking. It will throw away any data written to it and return garbage for anything read from it.

zero_storage_constructor()

Declared in "libtorrent/storage_defs.hpp"

storage_interface* zero_storage_constructor (storage_params const&);

enum storage_mode_t

Declared in "libtorrent/storage_defs.hpp"

name value description
storage_mode_allocate 0 All pieces will be written to their final position, all files will be allocated in full when the torrent is first started. This is done with fallocate() and similar calls. This mode minimizes fragmentation.
storage_mode_sparse 1 All pieces will be written to the place where they belong and sparse files will be used. This is the recommended, and default mode.

home

Custom Storage

libtorrent provides a customization point for storage of data. By default, (default_storage) downloaded files are saved to disk according with the general conventions of bittorrent clients, mimicing the original file layout when the torrent was created. The libtorrent user may define a custom storage to store piece data in a different way.

A custom storage implementation must derive from and implement the storage_interface. You must also provide a function that constructs the custom storage object and provide this function to the add_torrent() call via add_torrent_params. Either passed in to the constructor or by setting the add_torrent_params::storage field.

This is an example storage implementation that stores all pieces in a std::map, i.e. in RAM. It's not necessarily very useful in practice, but illustrates the basics of implementing a custom storage.

struct temp_storage : storage_interface
{
        temp_storage(file_storage const& fs) : m_files(fs) {}
        virtual bool initialize(storage_error& se) { return false; }
        virtual bool has_any_file() { return false; }
        virtual int read(char* buf, int piece, int offset, int size)
        {
                std::map<int, std::vector<char> >::const_iterator i = m_file_data.find(piece);
                if (i == m_file_data.end()) return 0;
                int available = i->second.size() - offset;
                if (available <= 0) return 0;
                if (available > size) available = size;
                memcpy(buf, &i->second[offset], available);
                return available;
        }
        virtual int write(const char* buf, int piece, int offset, int size)
        {
                std::vector<char>& data = m_file_data[piece];
                if (data.size() < offset + size) data.resize(offset + size);
                std::memcpy(&data[offset], buf, size);
                return size;
        }
        virtual bool rename_file(int file, std::string const& new_name)
        { assert(false); return false; }
        virtual bool move_storage(std::string const& save_path) { return false; }
        virtual bool verify_resume_data(bdecode_node const& rd
                , std::vector<std::string> const* links
                , storage_error& error) { return false; }
        virtual bool write_resume_data(entry& rd) const { return false; }
        virtual boost::int64_t physical_offset(int piece, int offset)
        { return piece * m_files.piece_length() + offset; };
        virtual sha1_hash hash_for_slot(int piece, partial_hash& ph, int piece_size)
        {
                int left = piece_size - ph.offset;
                assert(left >= 0);
                if (left > 0)
                {
                        std::vector<char>& data = m_file_data[piece];
                        // if there are padding files, those blocks will be considered
                        // completed even though they haven't been written to the storage.
                        // in this case, just extend the piece buffer to its full size
                        // and fill it with zeroes.
                        if (data.size() < piece_size) data.resize(piece_size, 0);
                        ph.h.update(&data[ph.offset], left);
                }
                return ph.h.final();
        }
        virtual bool release_files() { return false; }
        virtual bool delete_files() { return false; }

        std::map<int, std::vector<char> > m_file_data;
        file_storage m_files;
};

storage_interface* temp_storage_constructor(storage_params const& params)
{
        return new temp_storage(*params.files);
}

disk_buffer_holder

Declared in "libtorrent/disk_buffer_holder.hpp"

The disk buffer holder acts like a scoped_ptr that frees a disk buffer when it's destructed, unless it's released. release returns the disk buffer and transfers ownership and responsibility to free it to the caller.

A disk buffer is freed by passing it to session_impl::free_disk_buffer().

get() returns the pointer without transferring responsibility. If this buffer has been released, buffer() will return 0.

struct disk_buffer_holder
{
   disk_buffer_holder (buffer_allocator_interface& alloc, disk_io_job const& j);
   ~disk_buffer_holder ();
   char* release ();
   char* get () const;
   void reset (char* buf = 0);
   void reset (disk_io_job const& j);
   void swap (disk_buffer_holder& h);
   block_cache_reference ref () const;
};

disk_buffer_holder()

disk_buffer_holder (buffer_allocator_interface& alloc, disk_io_job const& j);

construct a buffer holder that will free the held buffer using a disk buffer pool directly (there's only one disk_buffer_pool per session)

~disk_buffer_holder()

~disk_buffer_holder ();

frees any unreleased disk buffer held by this object

release()

char* release ();

return the held disk buffer and clear it from the holder. The responsibility to free it is passed on to the caller

get()

char* get () const;

return a pointer to the held buffer

reset()

void reset (char* buf = 0);
void reset (disk_io_job const& j);

set the holder object to hold the specified buffer (or NULL by default). If it's already holding a disk buffer, it will first be freed.

swap()

void swap (disk_buffer_holder& h);

swap pointers of two disk buffer holders.

file_pool

Declared in "libtorrent/file_pool.hpp"

this is an internal cache of open file handles. It's primarily used by storage_interface implementations. It provides semi weak guarantees of not opening more file handles than specified. Given multiple threads, each with the ability to lock a file handle (via smart pointer), there may be windows where more file handles are open.

struct file_pool : boost::noncopyable
{
   ~file_pool ();
   file_pool (int size = 40);
   file_handle open_file (void* st, std::string const& p
      , int file_index, file_storage const& fs, int m, error_code& ec);
   void release (void* st = NULL);
   void release (void* st, int file_index);
   void resize (int size);
   int size_limit () const;
};

~file_pool() file_pool()

~file_pool ();
file_pool (int size = 40);

size specifies the number of allowed files handles to hold open at any given time.

open_file()

file_handle open_file (void* st, std::string const& p
      , int file_index, file_storage const& fs, int m, error_code& ec);

return an open file handle to file at file_index in the file_storage fs opened at save path p. m is the file open mode (see file::open_mode_t).

release()

void release (void* st = NULL);
void release (void* st, int file_index);

release all files belonging to the specified storage_interface (st) the overload that takes file_index releases only the file with that index in storage st.

resize()

void resize (int size);

update the allowed number of open file handles to size.

size_limit()

int size_limit () const;

returns the current limit of number of allowed open file handles held by the file_pool.

storage_interface

Declared in "libtorrent/storage.hpp"

The storage interface is a pure virtual class that can be implemented to customize how and where data for a torrent is stored. The default storage implementation uses regular files in the filesystem, mapping the files in the torrent in the way one would assume a torrent is saved to disk. Implementing your own storage interface makes it possible to store all data in RAM, or in some optimized order on disk (the order the pieces are received for instance), or saving multifile torrents in a single file in order to be able to take advantage of optimized disk-I/O.

It is also possible to write a thin class that uses the default storage but modifies some particular behavior, for instance encrypting the data before it's written to disk, and decrypting it when it's read again.

The storage interface is based on pieces. Avery read and write operation happens in the piece-space. Each piece fits 'piece_size' number of bytes. All access is done by writing and reading whole or partial pieces.

libtorrent comes with two built-in storage implementations; default_storage and disabled_storage. Their constructor functions are called default_storage_constructor() and disabled_storage_constructor respectively. The disabled storage does just what it sounds like. It throws away data that's written, and it reads garbage. It's useful mostly for benchmarking and profiling purpose.

struct storage_interface
{
   virtual void initialize (storage_error& ec) = 0;
   virtual int writev (file::iovec_t const* bufs, int num_bufs
      , int piece, int offset, int flags, storage_error& ec) = 0;
   virtual int readv (file::iovec_t const* bufs, int num_bufs
      , int piece, int offset, int flags, storage_error& ec) = 0;
   virtual bool has_any_file (storage_error& ec) = 0;
   virtual void set_file_priority (std::vector<boost::uint8_t> const& prio
      , storage_error& ec) = 0;
   virtual int move_storage (std::string const& save_path, int flags
      , storage_error& ec) = 0;
   virtual bool verify_resume_data (bdecode_node const& rd
      , std::vector<std::string> const* links
      , storage_error& ec) = 0;
   virtual void write_resume_data (entry& rd, storage_error& ec) const = 0;
   virtual void release_files (storage_error& ec) = 0;
   virtual void rename_file (int index, std::string const& new_filename
      , storage_error& ec) = 0;
   virtual void delete_files (int options, storage_error& ec) = 0;
   virtual bool tick ();
   aux::session_settings const& settings () const;

   aux::session_settings* m_settings;
};

initialize()

virtual void initialize (storage_error& ec) = 0;

This function is called when the storage is to be initialized. The default storage will create directories and empty files at this point. If allocate_files is true, it will also ftruncate all files to their target size.

If an error occurs, storage_error should be set to reflect it.

writev() readv()

virtual int writev (file::iovec_t const* bufs, int num_bufs
      , int piece, int offset, int flags, storage_error& ec) = 0;
virtual int readv (file::iovec_t const* bufs, int num_bufs
      , int piece, int offset, int flags, storage_error& ec) = 0;

These functions should read and write the data in or to the given piece at the given offset. It should read or write num_bufs buffers sequentially, where the size of each buffer is specified in the buffer array bufs. The file::iovec_t type has the following members:

struct iovec_t { void* iov_base; size_t iov_len; };

These functions may be called simultaneously from multiple threads. Make sure they are thread safe. The file in libtorrent is thread safe when it can fall back to pread, preadv or the windows equivalents. On targets where read operations cannot be thread safe (i.e one has to seek first and then read), only one disk thread is used.

Every buffer in bufs can be assumed to be page aligned and be of a page aligned size, except for the last buffer of the torrent. The allocated buffer can be assumed to fit a fully page aligned number of bytes though. This is useful when reading and writing the last piece of a file in unbuffered mode.

The offset is aligned to 16 kiB boundaries most of the time, but there are rare exceptions when it's not. Specifically if the read cache is disabled/or full and a peer requests unaligned data. Most clients request aligned data.

The number of bytes read or written should be returned, or -1 on error. If there's an error, the storage_error must be filled out to represent the error that occurred.

has_any_file()

virtual bool has_any_file (storage_error& ec) = 0;

This function is called when first checking (or re-checking) the storage for a torrent. It should return true if any of the files that is used in this storage exists on disk. If so, the storage will be checked for existing pieces before starting the download.

If an error occurs, storage_error should be set to reflect it.

set_file_priority()

virtual void set_file_priority (std::vector<boost::uint8_t> const& prio
      , storage_error& ec) = 0;

change the priorities of files. This is a fenced job and is guaranteed to be the only running function on this storage when called

move_storage()

virtual int move_storage (std::string const& save_path, int flags
      , storage_error& ec) = 0;

This function should move all the files belonging to the storage to the new save_path. The default storage moves the single file or the directory of the torrent.

Before moving the files, any open file handles may have to be closed, like release_files().

If an error occurs, storage_error should be set to reflect it.

returns one of: | no_error = 0 | fatal_disk_error = -1 | need_full_check = -2 | file_exist = -4

verify_resume_data()

virtual bool verify_resume_data (bdecode_node const& rd
      , std::vector<std::string> const* links
      , storage_error& ec) = 0;

This function should verify the resume data rd with the files on disk. If the resume data seems to be up-to-date, return true. If not, set error to a description of what mismatched and return false.

The default storage may compare file sizes and time stamps of the files.

If an error occurs, storage_error should be set to reflect it.

This function should verify the resume data rd with the files on disk. If the resume data seems to be up-to-date, return true. If not, set error to a description of what mismatched and return false.

If the links pointer is non-null, it has the same number of elements as there are files. Each element is either empty or contains the absolute path to a file identical to the corresponding file in this torrent. The storage must create hard links (or copy) those files. If any file does not exist or is inaccessible, the disk job must fail.

write_resume_data()

virtual void write_resume_data (entry& rd, storage_error& ec) const = 0;

This function should fill in resume data, the current state of the storage, in rd. The default storage adds file timestamps and sizes.

Returning true indicates an error occurred.

If an error occurs, storage_error should be set to reflect it.

release_files()

virtual void release_files (storage_error& ec) = 0;

This function should release all the file handles that it keeps open to files belonging to this storage. The default implementation just calls file_pool::release_files().

If an error occurs, storage_error should be set to reflect it.

rename_file()

virtual void rename_file (int index, std::string const& new_filename
      , storage_error& ec) = 0;

Rename file with index file to the thame new_name.

If an error occurs, storage_error should be set to reflect it.

delete_files()

virtual void delete_files (int options, storage_error& ec) = 0;

This function should delete some or all of the storage for this torrent. The options parameter specifies whether to delete all files or just the partfile. options are set to the same value as the options passed to session::remove_torrent().

If an error occurs, storage_error should be set to reflect it.

The disk_buffer_pool is used to allocate and free disk buffers. It has the following members:

struct disk_buffer_pool : boost::noncopyable
{
        char* allocate_buffer(char const* category);
        void free_buffer(char* buf);

        char* allocate_buffers(int blocks, char const* category);
        void free_buffers(char* buf, int blocks);

        int block_size() const { return m_block_size; }

        void release_memory();
};

tick()

virtual bool tick ();

called periodically (useful for deferred flushing). When returning false, it means no more ticks are necessary. Any disk job submitted will re-enable ticking. The default will always turn ticking back off again.

settings()

aux::session_settings const& settings () const;

access global session_settings

m_settings
initialized in disk_io_thread::perform_async_job

default_storage

Declared in "libtorrent/storage.hpp"

The default implementation of storage_interface. Behaves as a normal bittorrent client. It is possible to derive from this class in order to override some of its behavior, when implementing a custom storage.

class default_storage : public storage_interface, boost::noncopyable
{
   default_storage (storage_params const& params);
   virtual int move_storage (std::string const& save_path, int flags
      , storage_error& ec) override;
   virtual bool verify_resume_data (bdecode_node const& rd
      , std::vector<std::string> const* links
      , storage_error& error) override;
   virtual void initialize (storage_error& ec) override;
   virtual bool tick () override;
   virtual void delete_files (int options, storage_error& ec) override;
   virtual void rename_file (int index, std::string const& new_filename
      , storage_error& ec) override;
   virtual void set_file_priority (std::vector<boost::uint8_t> const& prio
      , storage_error& ec) override;
   virtual void write_resume_data (entry& rd, storage_error& ec) const override;
   virtual void release_files (storage_error& ec) override;
   virtual bool has_any_file (storage_error& ec) override;
   int readv (file::iovec_t const* bufs, int num_bufs
      , int piece, int offset, int flags, storage_error& ec) override;
   int writev (file::iovec_t const* bufs, int num_bufs
      , int piece, int offset, int flags, storage_error& ec) override;
   file_storage const& files () const;
   static void disk_write_access_log (bool enable);
   static bool disk_write_access_log ();
};

default_storage()

default_storage (storage_params const& params);

constructs the default_storage based on the give file_storage (fs). mapped is an optional argument (it may be NULL). If non-NULL it represents the file mapping that have been made to the torrent before adding it. That's where files are supposed to be saved and looked for on disk. save_path is the root save folder for this torrent. file_pool is the cache of file handles that the storage will use. All files it opens will ask the file_pool to open them. file_prio is a vector indicating the priority of files on startup. It may be an empty vector. Any file whose index is not represented by the vector (because the vector is too short) are assumed to have priority 1. this is used to treat files with priority 0 slightly differently.

files()

file_storage const& files () const;

if the files in this storage are mapped, returns the mapped file_storage, otherwise returns the original file_storage object.

enum move_flags_t

Declared in "libtorrent/storage.hpp"

name value description
always_replace_files 0 replace any files in the destination when copying or moving the storage
fail_if_exist 1 if any files that we want to copy exist in the destination exist, fail the whole operation and don't perform any copy or move. There is an inherent race condition in this mode. The files are checked for existence before the operation starts. In between the check and performing the copy, the destination files may be created, in which case they are replaced.
dont_replace 2 if any file exist in the target, take those files instead of the ones we may have in the source.

home

Utility

bitfield

Declared in "libtorrent/bitfield.hpp"

The bitfield type stores any number of bits as a bitfield in a heap allocated array.

struct bitfield
{
   bitfield (int bits);
   bitfield (bitfield const& rhs);
   bitfield (bitfield&& rhs);
   bitfield (int bits, bool val);
   bitfield ();
   bitfield (char const* b, int bits);
   void assign (char const* b, int bits);
   bool operator[] (int index) const;
   bool get_bit (int index) const;
   void clear_bit (int index);
   void set_bit (int index);
   bool all_set () const;
   bool none_set () const;
   int size () const;
   int num_words () const;
   bool empty () const;
   char const* data () const;
   bitfield& operator= (bitfield const& rhs);
   int count () const;
};

bitfield()

bitfield (int bits);
bitfield (bitfield const& rhs);
bitfield (bitfield&& rhs);
bitfield (int bits, bool val);
bitfield ();
bitfield (char const* b, int bits);

constructs a new bitfield. The default constructor creates an empty bitfield. bits is the size of the bitfield (specified in bits). val is the value to initialize the bits to. If not specified all bits are initialized to 0.

The constructor taking a pointer b and bits copies a bitfield from the specified buffer, and bits number of bits (rounded up to the nearest byte boundary).

assign()

void assign (char const* b, int bits);

copy bitfield from buffer b of bits number of bits, rounded up to the nearest byte boundary.

operator[]()

bool operator[] (int index) const;

query bit at index. Returns true if bit is 1, otherwise false.

set_bit() clear_bit()

void clear_bit (int index);
void set_bit (int index);

set bit at index to 0 (clear_bit) or 1 (set_bit).

all_set()

bool all_set () const;

returns true if all bits in the bitfield are set

size()

int size () const;

returns the size of the bitfield in bits.

empty()

bool empty () const;

returns true if the bitfield has zero size.

data()

char const* data () const;

returns a pointer to the internal buffer of the bitfield.

operator=()

bitfield& operator= (bitfield const& rhs);

copy operator

count()

int count () const;

count the number of bits in the bitfield that are set to 1.

hasher

Declared in "libtorrent/hasher.hpp"

this is a SHA-1 hash class.

You use it by first instantiating it, then call update() to feed it with data. i.e. you don't have to keep the entire buffer of which you want to create the hash in memory. You can feed the hasher parts of it at a time. When You have fed the hasher with all the data, you call final() and it will return the sha1-hash of the data.

The constructor that takes a char const* and an integer will construct the sha1 context and feed it the data passed in.

If you want to reuse the hasher object once you have created a hash, you have to call reset() to reinitialize it.

The sha1-algorithm used was implemented by Steve Reid and released as public domain. For more info, see src/sha1.cpp.

class hasher
{
   hasher ();
   hasher (const char* data, int len);
   hasher& operator= (hasher const& h);
   hasher (hasher const& h);
   hasher& update (std::string const& data);
   hasher& update (const char* data, int len);
   sha1_hash final ();
   void reset ();
   ~hasher ();
};

hasher()

hasher (const char* data, int len);

this is the same as default constructing followed by a call to update(data, len).

update()

hasher& update (std::string const& data);
hasher& update (const char* data, int len);

append the following bytes to what is being hashed

final()

sha1_hash final ();

returns the SHA-1 digest of the buffers previously passed to update() and the hasher constructor.

reset()

void reset ();

restore the hasher state to be as if the hasher has just been default constructed.

sha1_hash

Declared in "libtorrent/sha1_hash.hpp"

This type holds a SHA-1 digest or any other kind of 20 byte sequence. It implements a number of convenience functions, such as bit operations, comparison operators etc.

In libtorrent it is primarily used to hold info-hashes, piece-hashes, peer IDs, node IDs etc.

class sha1_hash
{
   sha1_hash ();
   static sha1_hash max ();
   static sha1_hash min ();
   explicit sha1_hash (char const* s);
   void assign (char const* str);
   explicit sha1_hash (std::string const& s);
   void assign (std::string const& s);
   char* data ();
   char const* data () const;
   void clear ();
   bool is_all_zeros () const;
   sha1_hash& operator<<= (int n);
   sha1_hash& operator>>= (int n);
   bool operator!= (sha1_hash const& n) const;
   bool operator< (sha1_hash const& n) const;
   bool operator== (sha1_hash const& n) const;
   sha1_hash operator~ () const;
   sha1_hash operator^ (sha1_hash const& n) const;
   sha1_hash& operator^= (sha1_hash const& n);
   sha1_hash operator& (sha1_hash const& n) const;
   sha1_hash& operator&= (sha1_hash const& n);
   sha1_hash& operator|= (sha1_hash const& n);
   boost::uint8_t& operator[] (int i);
   boost::uint8_t const& operator[] (int i) const;
   const_iterator begin () const;
   iterator begin ();
   iterator end ();
   const_iterator end () const;
   std::string to_string () const;
};

sha1_hash()

sha1_hash ();

constructs an all-zero sha1-hash

max()

static sha1_hash max ();

returns an all-F sha1-hash. i.e. the maximum value representable by a 160 bit number (20 bytes). This is a static member function.

min()

static sha1_hash min ();

returns an all-zero sha1-hash. i.e. the minimum value representable by a 160 bit number (20 bytes). This is a static member function.

assign() sha1_hash()

explicit sha1_hash (char const* s);
void assign (char const* str);
explicit sha1_hash (std::string const& s);
void assign (std::string const& s);

copies 20 bytes from the pointer provided, into the sha1-hash. The passed in string MUST be at least 20 bytes. NULL terminators are ignored, s is treated like a raw memory buffer.

clear()

void clear ();

set the sha1-hash to all zeroes.

is_all_zeros()

bool is_all_zeros () const;

return true if the sha1-hash is all zero.

operator<<=()

sha1_hash& operator<<= (int n);

shift left n bits.

operator>>=()

sha1_hash& operator>>= (int n);

shift r n bits.

operator!=() operator<() operator==()

bool operator!= (sha1_hash const& n) const;
bool operator< (sha1_hash const& n) const;
bool operator== (sha1_hash const& n) const;

standard comparison operators

operator~()

sha1_hash operator~ () const;

returns a bit-wise negated copy of the sha1-hash

operator^()

sha1_hash operator^ (sha1_hash const& n) const;

returns the bit-wise XOR of the two sha1-hashes.

operator^=()

sha1_hash& operator^= (sha1_hash const& n);

in-place bit-wise XOR with the passed in sha1_hash.

operator&()

sha1_hash operator& (sha1_hash const& n) const;

returns the bit-wise AND of the two sha1-hashes.

operator&=()

sha1_hash& operator&= (sha1_hash const& n);

in-place bit-wise AND of the passed in sha1_hash

operator|=()

sha1_hash& operator|= (sha1_hash const& n);

in-place bit-wise OR of the two sha1-hash.

operator[]()

boost::uint8_t& operator[] (int i);
boost::uint8_t const& operator[] (int i) const;

accessors for specific bytes

begin() end()

const_iterator begin () const;
iterator begin ();
iterator end ();
const_iterator end () const;

start and end iterators for the hash. The value type of these iterators is boost::uint8_t.

to_string()

std::string to_string () const;

return a copy of the 20 bytes representing the sha1-hash as a std::string. It's still a binary string with 20 binary characters.

hash_value()

Declared in "libtorrent/sha1_hash.hpp"

inline std::size_t hash_value (sha1_hash const& b);

operator<<()

Declared in "libtorrent/sha1_hash.hpp"

inline std::ostream& operator<< (std::ostream& os, sha1_hash const& peer);

print a sha1_hash object to an ostream as 40 hexadecimal digits

operator>>()

Declared in "libtorrent/sha1_hash.hpp"

inline std::istream& operator>> (std::istream& is, sha1_hash& peer);

read 40 hexadecimal digits from an istream into a sha1_hash

home

Bencoding

Bencoding is a common representation in bittorrent used for for dictionary, list, int and string hierarchies. It's used to encode .torrent files and some messages in the network protocol. libtorrent also uses it to store settings, resume data and other state between sessions.

Strings in bencoded structures are not necessarily representing text. Strings are raw byte buffers of a certain length. If a string is meant to be interpreted as text, it is required to be UTF-8 encoded. See BEP 3.

There are two mechanims to decode bencoded buffers in libtorrent.

The most flexible one is bdecode() bencode(), which returns a structure represented by entry. Oncea buffer has been decoded with this function, it can be discarded. The entry does not contain any references back to it. This means that bdecode() copies all the data out of the buffer and into its own hierarchy. This makes this function expensive, which might matter if you're parsing large amounts of data.

Another consideration is that bdecode() bencode() is a recursive parser. For this reason, in order to avoid DoS attacks by triggering a stack overflow, there is a recursion limit. This limit is a sanity check to make sure it doesn't run the risk of busting the stack.

The second mechanism is the decode function for bdecode_node. This function builds a tree that points back into the original buffer. The returned bdecode_node will not be valid once the buffer it was parsed out of is discarded.

Not only is this function more efficient because of less memory allocation and data copy, the parser is also not recursive, which means it probably performs a little bit better and can have a higher recursion limit on the structures it's parsing.

entry

Declared in "libtorrent/entry.hpp"

The entry class represents one node in a bencoded hierarchy. It works as a variant type, it can be either a list, a dictionary (std::map), an integer or a string.

class entry
{
   data_type type () const;
   entry (list_type const&);
   entry (integer_type const&);
   entry (dictionary_type const&);
   entry (string_type const&);
   entry (preformatted_type const&);
   entry (data_type t);
   void operator= (string_type const&);
   void operator= (integer_type const&);
   void operator= (entry const&);
   void operator= (dictionary_type const&);
   void operator= (list_type const&);
   void operator= (preformatted_type const&);
   void operator= (bdecode_node const&);
   preformatted_type& preformatted ();
   const integer_type& integer () const;
   const string_type& string () const;
   const preformatted_type& preformatted () const;
   const dictionary_type& dict () const;
   string_type& string ();
   list_type& list ();
   dictionary_type& dict ();
   integer_type& integer ();
   const list_type& list () const;
   void swap (entry& e);
   entry& operator[] (std::string const& key);
   const entry& operator[] (std::string const& key) const;
   entry& operator[] (char const* key);
   const entry& operator[] (char const* key) const;
   entry const* find_key (char const* key) const;
   entry* find_key (char const* key);
   entry* find_key (std::string const& key);
   entry const* find_key (std::string const& key) const;
   std::string to_string () const;

   enum data_type
   {
      int_t,
      string_t,
      list_t,
      dictionary_t,
      undefined_t,
      preformatted_t,
   };

   mutable boost::uint8_t m_type_queried:1;
};

type()

data_type type () const;

returns the concrete type of the entry

entry()

entry (list_type const&);
entry (integer_type const&);
entry (dictionary_type const&);
entry (string_type const&);
entry (preformatted_type const&);

constructors directly from a specific type. The content of the argument is copied into the newly constructed entry

entry()

entry (data_type t);

construct an empty entry of the specified type. see data_type enum.

operator=()

void operator= (string_type const&);
void operator= (integer_type const&);
void operator= (entry const&);
void operator= (dictionary_type const&);
void operator= (list_type const&);
void operator= (preformatted_type const&);
void operator= (bdecode_node const&);

copies the structure of the right hand side into this entry.

string() integer() dict() preformatted() list()

preformatted_type& preformatted ();
const integer_type& integer () const;
const string_type& string () const;
const preformatted_type& preformatted () const;
const dictionary_type& dict () const;
string_type& string ();
list_type& list ();
dictionary_type& dict ();
integer_type& integer ();
const list_type& list () const;

The integer(), string(), list() and dict() functions are accessors that return the respective type. If the entry object isn't of the type you request, the accessor will throw libtorrent_exception (which derives from std::runtime_error). You can ask an entry for its type through the type() function.

If you want to create an entry you give it the type you want it to have in its constructor, and then use one of the non-const accessors to get a reference which you then can assign the value you want it to have.

The typical code to get info from a torrent file will then look like this:

entry torrent_file;
// ...

// throws if this is not a dictionary
entry::dictionary_type const& dict = torrent_file.dict();
entry::dictionary_type::const_iterator i;
i = dict.find("announce");
if (i != dict.end())
{
        std::string tracker_url = i->second.string();
        std::cout << tracker_url << "\n";
}

The following code is equivalent, but a little bit shorter:

entry torrent_file;
// ...

// throws if this is not a dictionary
if (entry* i = torrent_file.find_key("announce"))
{
        std::string tracker_url = i->string();
        std::cout << tracker_url << "\n";
}

To make it easier to extract information from a torrent file, the class torrent_info exists.

swap()

void swap (entry& e);

swaps the content of this with e.

operator[]()

entry& operator[] (std::string const& key);
const entry& operator[] (std::string const& key) const;
entry& operator[] (char const* key);
const entry& operator[] (char const* key) const;

All of these functions requires the entry to be a dictionary, if it isn't they will throw libtorrent::type_error.

The non-const versions of the operator[] will return a reference to either the existing element at the given key or, if there is no element with the given key, a reference to a newly inserted element at that key.

The const version of operator[] will only return a reference to an existing element at the given key. If the key is not found, it will throw libtorrent::type_error.

find_key()

entry const* find_key (char const* key) const;
entry* find_key (char const* key);
entry* find_key (std::string const& key);
entry const* find_key (std::string const& key) const;

These functions requires the entry to be a dictionary, if it isn't they will throw libtorrent::type_error.

They will look for an element at the given key in the dictionary, if the element cannot be found, they will return 0. If an element with the given key is found, the return a pointer to it.

to_string()

std::string to_string () const;

returns a pretty-printed string representation of the bencoded structure, with JSON-style syntax

enum data_type

Declared in "libtorrent/entry.hpp"

name value description
int_t 0  
string_t 1  
list_t 2  
dictionary_t 3  
undefined_t 4  
preformatted_t 5  
m_type_queried
in debug mode this is set to false by bdecode to indicate that the program has not yet queried the type of this entry, and should not assume that it has a certain type. This is asserted in the accessor functions. This does not apply if exceptions are used.

bdecode() bencode()

Declared in "libtorrent/bencode.hpp"

template<class InIt> entry bdecode (InIt start, InIt end);
template<class OutIt> int bencode (OutIt out, const entry& e);
template<class InIt> entry bdecode (InIt start, InIt end, int& len);

These functions will encode data to bencoded or decode bencoded data.

If possible, bdecode() producing a bdecode_node should be preferred over this function.

The entry class is the internal representation of the bencoded data and it can be used to retrieve information, an entry can also be build by the program and given to bencode() to encode it into the OutIt iterator.

The OutIt and InIt are iterators (InputIterator and OutputIterator respectively). They are templates and are usually instantiated as ostream_iterator, back_insert_iterator or istream_iterator. These functions will assume that the iterator refers to a character (char). So, if you want to encode entry e into a buffer in memory, you can do it like this:

std::vector<char> buffer;
bencode(std::back_inserter(buf), e);

If you want to decode a torrent file from a buffer in memory, you can do it like this:

std::vector<char> buffer;
// ...
entry e = bdecode(buf.begin(), buf.end());

Or, if you have a raw char buffer:

const char* buf;
// ...
entry e = bdecode(buf, buf + data_size);

Now we just need to know how to retrieve information from the entry.

If bdecode() encounters invalid encoded data in the range given to it it will return a default constructed entry object.

operator<<()

Declared in "libtorrent/entry.hpp"

inline std::ostream& operator<< (std::ostream& os, const entry& e);

prints the bencoded structure to the ostream as a JSON-style structure.

home

Alerts

The pop_alerts() function on session is the main interface for retrieving alerts (warnings, messages and errors from libtorrent). If no alerts have been posted by libtorrent pop_alerts() will return an empty list.

By default, only errors are reported. settings_pack::alert_mask can be used to specify which kinds of events should be reported. The alert mask is comprised by bits from the category_t enum.

Every alert belongs to one or more category. There is a cost associated with posting alerts. Only alerts that belong to an enabled category are posted. Setting the alert bitmask to 0 will disable all alerts (except those that are non-discardable). Alerts that are responses to API calls such as save_resume_data() and post_session_stats() are non-discardable and will be posted even if their category is disabled.

There are other alert base classes that some alerts derive from, all the alerts that are generated for a specific torrent are derived from torrent_alert, and tracker events derive from tracker_alert.

Alerts returned by pop_alerts() are only valid until the next call to pop_alerts(). You may not copy an alert object to access it after the next call to pop_alerts(). Internal members of alerts also become invalid once pop_alerts() is called again.

alert

Declared in "libtorrent/alert.hpp"

The alert class is the base class that specific messages are derived from. alert types are not copyable, and cannot be constructed by the client. The pointers returned by libtorrent are short lived (the details are described under session_handle::pop_alerts())

class alert
{
   time_point timestamp () const;
   virtual int type () const = 0;
   virtual char const* what () const = 0;
   virtual std::string message () const = 0;
   virtual int category () const = 0;

   enum category_t
   {
      error_notification,
      peer_notification,
      port_mapping_notification,
      storage_notification,
      tracker_notification,
      debug_notification,
      status_notification,
      progress_notification,
      ip_block_notification,
      performance_warning,
      dht_notification,
      stats_notification,
      session_log_notification,
      torrent_log_notification,
      peer_log_notification,
      incoming_request_notification,
      dht_log_notification,
      dht_operation_notification,
      port_mapping_log_notification,
      picker_log_notification,
      all_categories,
   };
};

timestamp()

time_point timestamp () const;

a timestamp is automatically created in the constructor

type()

virtual int type () const = 0;

returns an integer that is unique to this alert type. It can be compared against a specific alert by querying a static constant called alert_type in the alert. It can be used to determine the run-time type of an alert* in order to cast to that alert type and access specific members.

e.g:

std::vector<alert*> alerts;
ses.pop_alerts(&alerts);
for (alert* i : alerts) {
        switch (a->type()) {

                case read_piece_alert::alert_type:
                {
                        read_piece_alert* p = (read_piece_alert*)a;
                        if (p->ec) {
                                // read_piece failed
                                break;
                        }
                        // use p
                        break;
                }
                case file_renamed_alert::alert_type:
                {
                        // etc...
                }
        }
}

what()

virtual char const* what () const = 0;

returns a string literal describing the type of the alert. It does not include any information that might be bundled with the alert.

message()

virtual std::string message () const = 0;

generate a string describing the alert and the information bundled with it. This is mainly intended for debug and development use. It is not suitable to use this for applications that may be localized. Instead, handle each alert type individually and extract and render the information from the alert depending on the locale.

category()

virtual int category () const = 0;

returns a bitmask specifying which categories this alert belong to.

enum category_t

Declared in "libtorrent/alert.hpp"

name value description
error_notification 1

Enables alerts that report an error. This includes:

  • tracker errors
  • tracker warnings
  • file errors
  • resume data failures
  • web seed errors
  • .torrent files errors
  • listen socket errors
  • port mapping errors
peer_notification 2 Enables alerts when peers send invalid requests, get banned or snubbed.
port_mapping_notification 4 Enables alerts for port mapping events. For NAT-PMP and UPnP.
storage_notification 8 Enables alerts for events related to the storage. File errors and synchronization events for moving the storage, renaming files etc.
tracker_notification 16 Enables all tracker events. Includes announcing to trackers, receiving responses, warnings and errors.
debug_notification 32 Low level alerts for when peers are connected and disconnected.
status_notification 64 Enables alerts for when a torrent or the session changes state.
progress_notification 128 Alerts for when blocks are requested and completed. Also when pieces are completed.
ip_block_notification 256 Alerts when a peer is blocked by the ip blocker or port blocker.
performance_warning 512 Alerts when some limit is reached that might limit the download or upload rate.
dht_notification 1024 Alerts on events in the DHT node. For incoming searches or bootstrapping being done etc.
stats_notification 2048 If you enable these alerts, you will receive a stats_alert approximately once every second, for every active torrent. These alerts contain all statistics counters for the interval since the lasts stats alert.
session_log_notification 8192 Enables debug logging alerts. These are available unless libtorrent was built with logging disabled (TORRENT_DISABLE_LOGGING). The alerts being posted are log_alert and are session wide.
torrent_log_notification 16384 Enables debug logging alerts for torrents. These are available unless libtorrent was built with logging disabled (TORRENT_DISABLE_LOGGING). The alerts being posted are torrent_log_alert and are torrent wide debug events.
peer_log_notification 32768 Enables debug logging alerts for peers. These are available unless libtorrent was built with logging disabled (TORRENT_DISABLE_LOGGING). The alerts being posted are peer_log_alert and low-level peer events and messages.
incoming_request_notification 65536 enables the incoming_request_alert.
dht_log_notification 131072 enables dht_log_alert, debug logging for the DHT
dht_operation_notification 262144 enable events from pure dht operations not related to torrents
port_mapping_log_notification 524288 enables port mapping log events. This log is useful for debugging the UPnP or NAT-PMP implementation
picker_log_notification 1048576 enables verbose logging from the piece picker.
all_categories 2147483647

The full bitmask, representing all available categories.

since the enum is signed, make sure this isn't interpreted as -1. For instance, boost.python does that and fails when assigning it to an unsigned parameter.

torrent_alert

Declared in "libtorrent/alert_types.hpp"

This is a base class for alerts that are associated with a specific torrent. It contains a handle to the torrent.

struct torrent_alert : alert
{
   virtual std::string message () const override;
   char const* torrent_name () const;

   torrent_handle handle;
};

message()

virtual std::string message () const override;

returns the message associated with this alert

handle
The torrent_handle pointing to the torrent this alert is associated with.

peer_alert

Declared in "libtorrent/alert_types.hpp"

The peer alert is a base class for alerts that refer to a specific peer. It includes all the information to identify the peer. i.e. ip and peer-id.

struct peer_alert : torrent_alert
{
   virtual int category () const override;
   virtual std::string message () const override;

   static const int alert_type = 1;
   static const int static_category = alert::peer_notification;
   tcp::endpoint ip;
   peer_id pid;
};
ip
The peer's IP address and port.
pid
the peer ID, if known.

tracker_alert

Declared in "libtorrent/alert_types.hpp"

This is a base class used for alerts that are associated with a specific tracker. It derives from torrent_alert since a tracker is also associated with a specific torrent.

struct tracker_alert : torrent_alert
{
   virtual int category () const override;
   virtual std::string message () const override;
   char const* tracker_url () const;

   static const int alert_type = 2;
   static const int static_category = alert::tracker_notification;
};

tracker_url()

char const* tracker_url () const;

returns a null-terminated string of the tracker's URL

torrent_added_alert

Declared in "libtorrent/alert_types.hpp"

The torrent_added_alert is posted once every time a torrent is successfully added. It doesn't contain any members of its own, but inherits the torrent handle from its base class. It's posted when the status_notification bit is set in the alert_mask.

struct torrent_added_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
};

torrent_removed_alert

Declared in "libtorrent/alert_types.hpp"

The torrent_removed_alert is posted whenever a torrent is removed. Since the torrent handle in its base class will always be invalid (since the torrent is already removed) it has the info hash as a member, to identify it. It's posted when the status_notification bit is set in the alert_mask.

Even though the handle member doesn't point to an existing torrent anymore, it is still useful for comparing to other handles, which may also no longer point to existing torrents, but to the same non-existing torrents.

The torrent_handle acts as a weak_ptr, even though its object no longer exists, it can still compare equal to another weak pointer which points to the same non-existent object.

struct torrent_removed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
   sha1_hash info_hash;
};

read_piece_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted when the asynchronous read operation initiated by a call to torrent_handle::read_piece() is completed. If the read failed, the torrent is paused and an error state is set and the buffer member of the alert is 0. If successful, buffer points to a buffer containing all the data of the piece. piece is the piece index that was read. size is the number of bytes that was read.

If the operation fails, ec will indicate what went wrong.

struct read_piece_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::storage_notification;
   error_code ec;
   boost::shared_array<char> buffer;
   int piece;
   int size;
};

file_completed_alert

Declared in "libtorrent/alert_types.hpp"

This is posted whenever an individual file completes its download. i.e. All pieces overlapping this file have passed their hash check.

struct file_completed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::progress_notification;
   int index;
};
index
refers to the index of the file that completed.

file_renamed_alert

Declared in "libtorrent/alert_types.hpp"

This is posted as a response to a torrent_handle::rename_file() call, if the rename operation succeeds.

struct file_renamed_alert final : torrent_alert
{
   virtual std::string message () const override;
   char const* new_name () const;

   static const int static_category = alert::storage_notification;
   int index;
};
index
refers to the index of the file that was renamed,

file_rename_failed_alert

Declared in "libtorrent/alert_types.hpp"

This is posted as a response to a torrent_handle::rename_file() call, if the rename operation failed.

struct file_rename_failed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::storage_notification;
   int index;
   error_code error;
};
index error
refers to the index of the file that was supposed to be renamed, error is the error code returned from the filesystem.

performance_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a limit is reached that might have a negative impact on upload or download rate performance.

struct performance_alert final : torrent_alert
{
   virtual std::string message () const override;

   enum performance_warning_t
   {
      outstanding_disk_buffer_limit_reached,
      outstanding_request_limit_reached,
      upload_limit_too_low,
      download_limit_too_low,
      send_buffer_watermark_too_low,
      too_many_optimistic_unchoke_slots,
      too_high_disk_queue_limit,
      aio_limit_reached,
      bittyrant_with_no_uplimit,
      too_few_outgoing_ports,
      too_few_file_descriptors,
      num_warnings,
   };

   static const int static_category = alert::performance_warning;
   performance_warning_t warning_code;
};

enum performance_warning_t

Declared in "libtorrent/alert_types.hpp"

name value description
outstanding_disk_buffer_limit_reached 0 This warning means that the number of bytes queued to be written to disk exceeds the max disk byte queue setting (settings_pack::max_queued_disk_bytes). This might restrict the download rate, by not queuing up enough write jobs to the disk I/O thread. When this alert is posted, peer connections are temporarily stopped from downloading, until the queued disk bytes have fallen below the limit again. Unless your max_queued_disk_bytes setting is already high, you might want to increase it to get better performance.
outstanding_request_limit_reached 1 This is posted when libtorrent would like to send more requests to a peer, but it's limited by settings_pack::max_out_request_queue. The queue length libtorrent is trying to achieve is determined by the download rate and the assumed round-trip-time (settings_pack::request_queue_time). The assumed round-trip-time is not limited to just the network RTT, but also the remote disk access time and message handling time. It defaults to 3 seconds. The target number of outstanding requests is set to fill the bandwidth-delay product (assumed RTT times download rate divided by number of bytes per request). When this alert is posted, there is a risk that the number of outstanding requests is too low and limits the download rate. You might want to increase the max_out_request_queue setting.
upload_limit_too_low 2 This warning is posted when the amount of TCP/IP overhead is greater than the upload rate limit. When this happens, the TCP/IP overhead is caused by a much faster download rate, triggering TCP ACK packets. These packets eat into the rate limit specified to libtorrent. When the overhead traffic is greater than the rate limit, libtorrent will not be able to send any actual payload, such as piece requests. This means the download rate will suffer, and new requests can be sent again. There will be an equilibrium where the download rate, on average, is about 20 times the upload rate limit. If you want to maximize the download rate, increase the upload rate limit above 5% of your download capacity.
download_limit_too_low 3 This is the same warning as upload_limit_too_low but referring to the download limit instead of upload. This suggests that your download rate limit is much lower than your upload capacity. Your upload rate will suffer. To maximize upload rate, make sure your download rate limit is above 5% of your upload capacity.
send_buffer_watermark_too_low 4

We're stalled on the disk. We want to write to the socket, and we can write but our send buffer is empty, waiting to be refilled from the disk. This either means the disk is slower than the network connection or that our send buffer watermark is too small, because we can send it all before the disk gets back to us. The number of bytes that we keep outstanding, requested from the disk, is calculated as follows:

min(512, max(upload_rate * send_buffer_watermark_factor / 100, send_buffer_watermark))

If you receive this alert, you might want to either increase your send_buffer_watermark or send_buffer_watermark_factor.

too_many_optimistic_unchoke_slots 5 If the half (or more) of all upload slots are set as optimistic unchoke slots, this warning is issued. You probably want more regular (rate based) unchoke slots.
too_high_disk_queue_limit 6 If the disk write queue ever grows larger than half of the cache size, this warning is posted. The disk write queue eats into the total disk cache and leaves very little left for the actual cache. This causes the disk cache to oscillate in evicting large portions of the cache before allowing peers to download any more, onto the disk write queue. Either lower max_queued_disk_bytes or increase cache_size.
aio_limit_reached 7  
bittyrant_with_no_uplimit 8  
too_few_outgoing_ports 9 This is generated if outgoing peer connections are failing because of address in use errors, indicating that settings_pack::outgoing_ports is set and is too small of a range. Consider not using the outgoing_ports setting at all, or widen the range to include more ports.
too_few_file_descriptors 10  
num_warnings 11  

state_changed_alert

Declared in "libtorrent/alert_types.hpp"

Generated whenever a torrent changes its state.

struct state_changed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
   torrent_status::state_t state;
   torrent_status::state_t prev_state;
};
state
the new state of the torrent.
prev_state
the previous state.

tracker_error_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated on tracker time outs, premature disconnects, invalid response or a HTTP response other than "200 OK". From the alert you can get the handle to the torrent the tracker belongs to.

The times_in_row member says how many times in a row this tracker has failed. status_code is the code returned from the HTTP server. 401 means the tracker needs authentication, 404 means not found etc. If the tracker timed out, the code will be set to 0.

struct tracker_error_alert final : tracker_alert
{
   virtual std::string message () const override;
   char const* error_message () const;

   static const int static_category = alert::tracker_notification | alert::error_notification;
   int times_in_row;
   int status_code;
   error_code error;
};

error_message()

char const* error_message () const;

the message associated with this error

tracker_warning_alert

Declared in "libtorrent/alert_types.hpp"

This alert is triggered if the tracker reply contains a warning field. Usually this means that the tracker announce was successful, but the tracker has a message to the client.

struct tracker_warning_alert final : tracker_alert
{
   virtual std::string message () const override;
   char const* warning_message () const;

   static const int static_category = alert::tracker_notification | alert::error_notification;
};

warning_message()

char const* warning_message () const;

the message associated with this warning

scrape_reply_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a scrape request succeeds.

struct scrape_reply_alert final : tracker_alert
{
   virtual std::string message () const override;

   int incomplete;
   int complete;
};
incomplete complete
the data returned in the scrape response. These numbers may be -1 if the response was malformed.

scrape_failed_alert

Declared in "libtorrent/alert_types.hpp"

If a scrape request fails, this alert is generated. This might be due to the tracker timing out, refusing connection or returning an http response code indicating an error.

struct scrape_failed_alert final : tracker_alert
{
   virtual std::string message () const override;
   char const* error_message () const;

   static const int static_category = alert::tracker_notification | alert::error_notification;
   error_code error;
};

error_message()

char const* error_message () const;

if the error indicates there is an associated message, this returns that message. Otherwise and empty string.

error
the error itself. This may indicate that the tracker sent an error message (error::tracker_failure), in which case it can be retrieved by calling error_message().

tracker_reply_alert

Declared in "libtorrent/alert_types.hpp"

This alert is only for informational purpose. It is generated when a tracker announce succeeds. It is generated regardless what kind of tracker was used, be it UDP, HTTP or the DHT.

struct tracker_reply_alert final : tracker_alert
{
   virtual std::string message () const override;

   int num_peers;
};
num_peers
tells how many peers the tracker returned in this response. This is not expected to be more thant the num_want settings. These are not necessarily all new peers, some of them may already be connected.

dht_reply_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated each time the DHT receives peers from a node. num_peers is the number of peers we received in this packet. Typically these packets are received from multiple DHT nodes, and so the alerts are typically generated a few at a time.

struct dht_reply_alert final : tracker_alert
{
   virtual std::string message () const override;

   int num_peers;
};

tracker_announce_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated each time a tracker announce is sent (or attempted to be sent). There are no extra data members in this alert. The url can be found in the base class however.

struct tracker_announce_alert final : tracker_alert
{
   virtual std::string message () const override;

   int event;
};
event

specifies what event was sent to the tracker. It is defined as:

  1. None
  2. Completed
  3. Started
  4. Stopped

hash_failed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a finished piece fails its hash check. You can get the handle to the torrent which got the failed piece and the index of the piece itself from the alert.

struct hash_failed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
   int piece_index;
};

peer_ban_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a peer is banned because it has sent too many corrupt pieces to us. ip is the endpoint to the peer that was banned.

struct peer_ban_alert final : peer_alert
{
   virtual std::string message () const override;
};

peer_unsnubbed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a peer is unsnubbed. Essentially when it was snubbed for stalling sending data, and now it started sending data again.

struct peer_unsnubbed_alert final : peer_alert
{
   virtual std::string message () const override;
};

peer_snubbed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a peer is snubbed, when it stops sending data when we request it.

struct peer_snubbed_alert final : peer_alert
{
   virtual std::string message () const override;
};

peer_error_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a peer sends invalid data over the peer-peer protocol. The peer will be disconnected, but you get its ip address from the alert, to identify it.

struct peer_error_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::peer_notification;
   int operation;
   error_code error;
};
operation
a NULL-terminated string of the low-level operation that failed, or NULL if there was no low level disk operation.
error
tells you what error caused this alert.

peer_connect_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted every time an outgoing peer connect attempts succeeds.

struct peer_connect_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::debug_notification;
   int socket_type;
};

peer_disconnected_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a peer is disconnected for any reason (other than the ones covered by peer_error_alert ).

struct peer_disconnected_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::debug_notification;
   int socket_type;
   operation_t operation;
   error_code error;
   close_reason_t reason;
};
socket_type
the kind of socket this peer was connected over
operation
the operation or level where the error occurred. Specified as an value from the operation_t enum. Defined in operations.hpp.
error
tells you what error caused peer to disconnect.
reason
the reason the peer disconnected (if specified)

invalid_request_alert

Declared in "libtorrent/alert_types.hpp"

This is a debug alert that is generated by an incoming invalid piece request. ip is the address of the peer and the request is the actual incoming request from the peer. See peer_request for more info.

struct invalid_request_alert final : peer_alert
{
   virtual std::string message () const override;

   peer_request request;
   bool we_have;
   bool peer_interested;
   bool withheld;
};
request
the request we received from the peer
we_have
true if we have this piece
peer_interested
true if the peer indicated that it was interested to download before sending the request
withheld
if this is true, the peer is not allowed to download this piece because of superseeding rules.

torrent_finished_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a torrent switches from being a downloader to a seed. It will only be generated once per torrent. It contains a torrent_handle to the torrent in question.

struct torrent_finished_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
};

piece_finished_alert

Declared in "libtorrent/alert_types.hpp"

this alert is posted every time a piece completes downloading and passes the hash check. This alert derives from torrent_alert which contains the torrent_handle to the torrent the piece belongs to.

struct piece_finished_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::progress_notification;
   int piece_index;
};
piece_index
the index of the piece that finished

request_dropped_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a peer rejects or ignores a piece request.

struct request_dropped_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::progress_notification
   | alert::peer_notification;
   int block_index;
   int piece_index;
};

block_timeout_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a block request times out.

struct block_timeout_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::progress_notification
   | alert::peer_notification;
   int block_index;
   int piece_index;
};

block_finished_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a block request receives a response.

struct block_finished_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::progress_notification;
   int block_index;
   int piece_index;
};

block_downloading_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a block request is sent to a peer.

struct block_downloading_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::progress_notification;
   int block_index;
   int piece_index;
};

unwanted_block_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a block is received that was not requested or whose request timed out.

struct unwanted_block_alert final : peer_alert
{
   virtual std::string message () const override;

   int block_index;
   int piece_index;
};

storage_moved_alert

Declared in "libtorrent/alert_types.hpp"

The storage_moved_alert is generated when all the disk IO has completed and the files have been moved, as an effect of a call to torrent_handle::move_storage. This is useful to synchronize with the actual disk. The path member is the new path of the storage.

struct storage_moved_alert final : torrent_alert
{
   virtual std::string message () const override;
   char const* storage_path () const;

   static const int static_category = alert::storage_notification;
};

storage_path()

char const* storage_path () const;

the path the torrent was moved to

storage_moved_failed_alert

Declared in "libtorrent/alert_types.hpp"

The storage_moved_failed_alert is generated when an attempt to move the storage, via torrent_handle::move_storage(), fails.

struct storage_moved_failed_alert final : torrent_alert
{
   virtual std::string message () const override;
   char const* file_path () const;

   static const int static_category = alert::storage_notification;
   error_code error;
   char const* operation;
};

file_path()

char const* file_path () const;

If the error happened for a specific file, this returns its path.

operation
If the error happened in a specific disk operation this is a NULL terminated string naming which one, otherwise it's NULL.

torrent_deleted_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a request to delete the files of a torrent complete.

The info_hash is the info-hash of the torrent that was just deleted. Most of the time the torrent_handle in the torrent_alert will be invalid by the time this alert arrives, since the torrent is being deleted. The info_hash member is hence the main way of identifying which torrent just completed the delete.

This alert is posted in the storage_notification category, and that bit needs to be set in the alert_mask.

struct torrent_deleted_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::storage_notification;
   sha1_hash info_hash;
};

torrent_delete_failed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a request to delete the files of a torrent fails. Just removing a torrent from the session cannot fail

struct torrent_delete_failed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::storage_notification
   | alert::error_notification;
   error_code error;
   sha1_hash info_hash;
};
error
tells you why it failed.
info_hash
the info hash of the torrent whose files failed to be deleted

save_resume_data_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated as a response to a torrent_handle::save_resume_data request. It is generated once the disk IO thread is done writing the state for this torrent.

struct save_resume_data_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::storage_notification;
   boost::shared_ptr<entry> resume_data;
};
resume_data
points to the resume data.

save_resume_data_failed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated instead of save_resume_data_alert if there was an error generating the resume data. error describes what went wrong.

struct save_resume_data_failed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::storage_notification
   | alert::error_notification;
   error_code error;
};
error
the error code from the resume_data failure

torrent_paused_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated as a response to a torrent_handle::pause request. It is generated once all disk IO is complete and the files in the torrent have been closed. This is useful for synchronizing with the disk.

struct torrent_paused_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
};

torrent_resumed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated as a response to a torrent_handle::resume() request. It is generated when a torrent goes from a paused state to an active state.

struct torrent_resumed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
};

torrent_checked_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted when a torrent completes checking. i.e. when it transitions out of the checking files state into a state where it is ready to start downloading

struct torrent_checked_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
};

url_seed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a HTTP seed name lookup fails.

struct url_seed_alert final : torrent_alert
{
   virtual std::string message () const override;
   char const* server_url () const;
   char const* error_message () const;

   static const int static_category = alert::peer_notification | alert::error_notification;
   error_code error;
};

server_url()

char const* server_url () const;

the URL the error is associated with

error_message()

char const* error_message () const;

in case the web server sent an error message, this function returns it.

error
the error the web seed encountered. If this is not set, the server sent an error message, call error_message().

file_error_alert

Declared in "libtorrent/alert_types.hpp"

If the storage fails to read or write files that it needs access to, this alert is generated and the torrent is paused.

struct file_error_alert final : torrent_alert
{
   virtual std::string message () const override;
   char const* filename () const;

   static const int static_category = alert::status_notification
   | alert::storage_notification;
   error_code error;
   char const* operation;
};

filename()

char const* filename () const;

the file that experienced the error

error operation
the error code describing the error.

metadata_failed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when the metadata has been completely received and the info-hash failed to match it. i.e. the metadata that was received was corrupt. libtorrent will automatically retry to fetch it in this case. This is only relevant when running a torrent-less download, with the metadata extension provided by libtorrent.

struct metadata_failed_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::error_notification;
   error_code error;
};
error
indicates what failed when parsing the metadata. This error is what's returned from lazy_bdecode().

metadata_received_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when the metadata has been completely received and the torrent can start downloading. It is not generated on torrents that are started with metadata, but only those that needs to download it from peers (when utilizing the libtorrent extension).

There are no additional data members in this alert.

Typically, when receiving this alert, you would want to save the torrent file in order to load it back up again when the session is restarted. Here's an example snippet of code to do that:

torrent_handle h = alert->handle();
if (h.is_valid()) {
        boost::shared_ptr<torrent_info const> ti = h.torrent_file();
        create_torrent ct(*ti);
        entry te = ct.generate();
        std::vector<char> buffer;
        bencode(std::back_inserter(buffer), te);
        FILE* f = fopen((to_hex(ti->info_hash().to_string()) + ".torrent").c_str(), "wb+");
        if (f) {
                fwrite(&buffer[0], 1, buffer.size(), f);
                fclose(f);
        }
}
struct metadata_received_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
};

udp_error_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted when there is an error on the UDP socket. The UDP socket is used for all uTP, DHT and UDP tracker traffic. It's global to the session.

struct udp_error_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::error_notification;
   udp::endpoint endpoint;
   error_code error;
};
endpoint
the source address associated with the error (if any)
error
the error code describing the error

external_ip_alert

Declared in "libtorrent/alert_types.hpp"

Whenever libtorrent learns about the machines external IP, this alert is generated. The external IP address can be acquired from the tracker (if it supports that) or from peers that supports the extension protocol. The address can be accessed through the external_address member.

struct external_ip_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
   address external_address;
};
external_address
the IP address that is believed to be our external IP

listen_failed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when none of the ports, given in the port range, to session can be opened for listening. The endpoint member is the interface and port that failed, error is the error code describing the failure.

libtorrent may sometimes try to listen on port 0, if all other ports failed. Port 0 asks the operating system to pick a port that's free). If that fails you may see a listen_failed_alert with port 0 even if you didn't ask to listen on it.

struct listen_failed_alert final : alert
{
   virtual std::string message () const override;
   char const* listen_interface () const;

   enum socket_type_t
   {
      tcp,
      tcp_ssl,
      udp,
      i2p,
      socks5,
      utp_ssl,
   };

   enum op_t
   {
      parse_addr,
      open,
      bind,
      listen,
      get_peer_name,
      accept,
   };

   static const int static_category = alert::status_notification | alert::error_notification;
   error_code error;
   int operation;
   socket_type_t sock_type;
   tcp::endpoint endpoint;
};

listen_interface()

char const* listen_interface () const;

the interface libtorrent attempted to listen on that failed.

enum socket_type_t

Declared in "libtorrent/alert_types.hpp"

name value description
tcp 0  
tcp_ssl 1  
udp 2  
i2p 3  
socks5 4  
utp_ssl 5  

enum op_t

Declared in "libtorrent/alert_types.hpp"

name value description
parse_addr 0  
open 1  
bind 2  
listen 3  
get_peer_name 4  
accept 5  
error
the error the system returned
operation
the specific low level operation that failed. See op_t.
sock_type
the type of listen socket this alert refers to.
endpoint
the address and port libtorrent attempted to listen on

listen_succeeded_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted when the listen port succeeds to be opened on a particular interface. endpoint is the endpoint that successfully was opened for listening.

struct listen_succeeded_alert final : alert
{
   virtual std::string message () const override;

   enum socket_type_t
   {
      tcp,
      tcp_ssl,
      udp,
      i2p,
      socks5,
      utp_ssl,
   };

   static const int static_category = alert::status_notification;
   tcp::endpoint endpoint;
   socket_type_t sock_type;
};

enum socket_type_t

Declared in "libtorrent/alert_types.hpp"

name value description
tcp 0  
tcp_ssl 1  
udp 2  
i2p 3  
socks5 4  
utp_ssl 5  
endpoint
the endpoint libtorrent ended up listening on. The address refers to the local interface and the port is the listen port.
sock_type
the type of listen socket this alert refers to.

portmap_error_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a NAT router was successfully found but some part of the port mapping request failed. It contains a text message that may help the user figure out what is wrong. This alert is not generated in case it appears the client is not running on a NAT:ed network or if it appears there is no NAT router that can be remote controlled to add port mappings.

struct portmap_error_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::port_mapping_notification
   | alert::error_notification;
   int mapping;
   int map_type;
   error_code error;
};
mapping
refers to the mapping index of the port map that failed, i.e. the index returned from add_mapping().
map_type
is 0 for NAT-PMP and 1 for UPnP.
error
tells you what failed.

portmap_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a NAT router was successfully found and a port was successfully mapped on it. On a NAT:ed network with a NAT-PMP capable router, this is typically generated once when mapping the TCP port and, if DHT is enabled, when the UDP port is mapped.

struct portmap_alert final : alert
{
   virtual std::string message () const override;

   enum protocol_t
   {
      tcp,
      udp,
   };

   static const int static_category = alert::port_mapping_notification;
   int mapping;
   int external_port;
   int map_type;
   int protocol;
};

enum protocol_t

Declared in "libtorrent/alert_types.hpp"

name value description
tcp 0  
udp 1  
mapping
refers to the mapping index of the port map that failed, i.e. the index returned from add_mapping().
external_port
the external port allocated for the mapping.
map_type
0 for NAT-PMP and 1 for UPnP.
protocol
the protocol this mapping was for. one of protocol_t enums

portmap_log_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated to log informational events related to either UPnP or NAT-PMP. They contain a log line and the type (0 = NAT-PMP and 1 = UPnP). Displaying these messages to an end user is only useful for debugging the UPnP or NAT-PMP implementation. This alert is only posted if the alert::port_mapping_log_notification flag is enabled in the alert mask.

struct portmap_log_alert final : alert
{
   virtual std::string message () const override;
   char const* log_message () const;

   static const int static_category = alert::port_mapping_log_notification;
   int map_type;
};

log_message()

char const* log_message () const;

the message associated with this log line

fastresume_rejected_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a fastresume file has been passed to add_torrent() but the files on disk did not match the fastresume file. The error_code explains the reason why the resume file was rejected.

struct fastresume_rejected_alert final : torrent_alert
{
   virtual std::string message () const override;
   char const* file_path () const;

   static const int static_category = alert::status_notification
   | alert::error_notification;
   error_code error;
   char const* operation;
};

file_path()

char const* file_path () const;

If the error happened to a specific file, this returns the path to it.

operation
If the error happened in a disk operation. a NULL-terminated string of the name of that operation. operation is NULL otherwise.

peer_blocked_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted when an incoming peer connection, or a peer that's about to be added to our peer list, is blocked for some reason. This could be any of:

  • the IP filter
  • i2p mixed mode restrictions (a normal peer is not allowed on an i2p swarm)
  • the port filter
  • the peer has a low port and no_connect_privileged_ports is enabled
  • the protocol of the peer is blocked (uTP/TCP blocking)
struct peer_blocked_alert final : torrent_alert
{
   virtual std::string message () const override;

   enum reason_t
   {
      ip_filter,
      port_filter,
      i2p_mixed,
      privileged_ports,
      utp_disabled,
      tcp_disabled,
      invalid_local_interface,
   };

   static const int static_category = alert::ip_block_notification;
   address ip;
   int reason;
};

enum reason_t

Declared in "libtorrent/alert_types.hpp"

name value description
ip_filter 0  
port_filter 1  
i2p_mixed 2  
privileged_ports 3  
utp_disabled 4  
tcp_disabled 5  
invalid_local_interface 6  
ip
the address that was blocked.

dht_announce_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a DHT node announces to an info-hash on our DHT node. It belongs to the dht_notification category.

struct dht_announce_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::dht_notification;
   address ip;
   int port;
   sha1_hash info_hash;
};

dht_get_peers_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when a DHT node sends a get_peers message to our DHT node. It belongs to the dht_notification category.

struct dht_get_peers_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::dht_notification;
   sha1_hash info_hash;
};

stats_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted approximately once every second, and it contains byte counters of most statistics that's tracked for torrents. Each active torrent posts these alerts regularly. This alert has been superceded by calling post_torrent_updates() regularly on the session object. This alert will be removed

struct stats_alert final : torrent_alert
{
   virtual std::string message () const override;

   enum stats_channel
   {
      upload_payload,
      upload_protocol,
      download_payload,
      download_protocol,
      upload_ip_protocol,
      deprecated1,
      deprecated2,
      download_ip_protocol,
      deprecated3,
      deprecated4,
      num_channels,
   };

   static const int static_category = alert::stats_notification;
   int transferred[num_channels];
   int interval;
};

enum stats_channel

Declared in "libtorrent/alert_types.hpp"

name value description
upload_payload 0  
upload_protocol 1  
download_payload 2  
download_protocol 3  
upload_ip_protocol 4  
deprecated1 5  
deprecated2 6  
download_ip_protocol 7  
deprecated3 8  
deprecated4 9  
num_channels 10  
transferred[num_channels]
an array of samples. The enum describes what each sample is a measurement of. All of these are raw, and not smoothing is performed.
interval
the number of milliseconds during which these stats were collected. This is typically just above 1000, but if CPU is limited, it may be higher than that.

cache_flushed_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted when the disk cache has been flushed for a specific torrent as a result of a call to torrent_handle::flush_cache(). This alert belongs to the storage_notification category, which must be enabled to let this alert through. The alert is also posted when removing a torrent from the session, once the outstanding cache flush is complete and the torrent does no longer have any files open.

struct cache_flushed_alert final : torrent_alert
{
   static const int static_category = alert::storage_notification;
};

anonymous_mode_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted when a bittorrent feature is blocked because of the anonymous mode. For instance, if the tracker proxy is not set up, no trackers will be used, because trackers can only be used through proxies when in anonymous mode.

struct anonymous_mode_alert final : torrent_alert
{
   virtual std::string message () const override;

   enum kind_t
   {
      tracker_not_anonymous,
   };

   static const int static_category = alert::error_notification;
   int kind;
   std::string str;
};

enum kind_t

Declared in "libtorrent/alert_types.hpp"

name value description
tracker_not_anonymous 0 means that there's no proxy set up for tracker communication and the tracker will not be contacted. The tracker which this failed for is specified in the str member.
kind str
specifies what error this is, see kind_t.

lsd_peer_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when we receive a local service discovery message from a peer for a torrent we're currently participating in.

struct lsd_peer_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::peer_notification;
};

trackerid_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted whenever a tracker responds with a trackerid. The tracker ID is like a cookie. The libtorrent will store the tracker ID for this tracker and repeat it in subsequent announces.

struct trackerid_alert final : tracker_alert
{
   virtual std::string message () const override;
   char const* tracker_id () const;

   static const int static_category = alert::status_notification;
};

tracker_id()

char const* tracker_id () const;

The tracker ID returned by the tracker

dht_bootstrap_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted when the initial DHT bootstrap is done.

struct dht_bootstrap_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::dht_notification;
};

torrent_error_alert

Declared in "libtorrent/alert_types.hpp"

This is posted whenever a torrent is transitioned into the error state.

struct torrent_error_alert final : torrent_alert
{
   virtual std::string message () const override;
   char const* filename () const;

   static const int static_category = alert::error_notification | alert::status_notification;
   error_code error;
};

filename()

char const* filename () const;

the filename (or object) the error occurred on.

error
specifies which error the torrent encountered.

torrent_need_cert_alert

Declared in "libtorrent/alert_types.hpp"

This is always posted for SSL torrents. This is a reminder to the client that the torrent won't work unless torrent_handle::set_ssl_certificate() is called with a valid certificate. Valid certificates MUST be signed by the SSL certificate in the .torrent file.

struct torrent_need_cert_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
   error_code error;
};

incoming_connection_alert

Declared in "libtorrent/alert_types.hpp"

The incoming connection alert is posted every time we successfully accept an incoming connection, through any mean. The most straight-forward ways of accepting incoming connections are through the TCP listen socket and the UDP listen socket for uTP sockets. However, connections may also be accepted through a Socks5 or i2p listen socket, or via an SSL listen socket.

struct incoming_connection_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::peer_notification;
   int socket_type;
   tcp::endpoint ip;
};
socket_type

tells you what kind of socket the connection was accepted as:

  1. none (no socket instantiated)
  2. TCP
  3. Socks5
  4. HTTP
  5. uTP
  6. i2p
  7. SSL/TCP
  8. SSL/Socks5
  9. HTTPS (SSL/HTTP)
  10. SSL/uTP
ip
is the IP address and port the connection came from.

add_torrent_alert

Declared in "libtorrent/alert_types.hpp"

This alert is always posted when a torrent was attempted to be added and contains the return status of the add operation. The torrent handle of the new torrent can be found in the base class' handle member. If adding the torrent failed, error contains the error code.

struct add_torrent_alert final : torrent_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
   add_torrent_params params;
   error_code error;
};
params
a copy of the parameters used when adding the torrent, it can be used to identify which invocation to async_add_torrent() caused this alert.
error
set to the error, if one occurred while adding the torrent.

state_update_alert

Declared in "libtorrent/alert_types.hpp"

This alert is only posted when requested by the user, by calling session::post_torrent_updates() on the session. It contains the torrent status of all torrents that changed since last time this message was posted. Its category is status_notification, but it's not subject to filtering, since it's only manually posted anyway.

struct state_update_alert final : alert
{
   state_update_alert (aux::stack_allocator& alloc
      , std::vector<torrent_status> st);
   virtual std::string message () const override;

   static const int static_category = alert::status_notification;
   std::vector<torrent_status> status;
};
status
contains the torrent status of all torrents that changed since last time this message was posted. Note that you can map a torrent status to a specific torrent via its handle member. The receiving end is suggested to have all torrents sorted by the torrent_handle or hashed by it, for efficient updates.

session_stats_alert

Declared in "libtorrent/alert_types.hpp"

The session_stats_alert is posted when the user requests session statistics by calling post_session_stats() on the session object. Its category is status_notification, but it is not subject to filtering, since it's only manually posted anyway.

struct session_stats_alert final : alert
{
   session_stats_alert (aux::stack_allocator& alloc, counters const& cnt);
   virtual std::string message () const override;

   static const int static_category = alert::stats_notification;
   boost::uint64_t values[counters::num_counters];
};
values[counters

An array are a mix of counters and gauges, which meanings can be queries via the session_stats_metrics() function on the session. The mapping from a specific metric to an index into this array is constant for a specific version of libtorrent, but may differ for other versions. The intended usage is to request the mapping, i.e. call session_stats_metrics(), once on startup, and then use that mapping to interpret these values throughout the process' runtime.

For more information, see the session statistics section.

dht_error_alert

Declared in "libtorrent/alert_types.hpp"

posted when something fails in the DHT. This is not necessarily a fatal error, but it could prevent proper operation

struct dht_error_alert final : alert
{
   virtual std::string message () const override;

   enum op_t
   {
      unknown,
      hostname_lookup,
   };

   static const int static_category = alert::error_notification | alert::dht_notification;
   error_code error;
   op_t operation;
};

enum op_t

Declared in "libtorrent/alert_types.hpp"

name value description
unknown 0  
hostname_lookup 1  
error
the error code
operation
the operation that failed

dht_immutable_item_alert

Declared in "libtorrent/alert_types.hpp"

this alert is posted as a response to a call to session::get_item(), specifically the overload for looking up immutable items in the DHT.

struct dht_immutable_item_alert final : alert
{
   dht_immutable_item_alert (aux::stack_allocator& alloc, sha1_hash const& t
      , entry const& i);
   virtual std::string message () const override;

   static const int static_category = alert::dht_notification;
   sha1_hash target;
   entry item;
};
target
the target hash of the immutable item. This must match the sha-1 hash of the bencoded form of item.
item
the data for this item

dht_mutable_item_alert

Declared in "libtorrent/alert_types.hpp"

this alert is posted as a response to a call to session::get_item(), specifically the overload for looking up mutable items in the DHT.

struct dht_mutable_item_alert final : alert
{
   dht_mutable_item_alert (aux::stack_allocator& alloc
      , boost::array<char, 32> k
      , boost::array<char, 64> sig
      , boost::uint64_t sequence
      , std::string const& s
      , entry const& i
      , bool a);
   virtual std::string message () const override;

   static const int static_category = alert::dht_notification;
   boost::array<char, 32> key;
   boost::array<char, 64> signature;
   boost::uint64_t seq;
   std::string salt;
   entry item;
   bool authoritative;
};
key
the public key that was looked up
signature
the signature of the data. This is not the signature of the plain encoded form of the item, but it includes the sequence number and possibly the hash as well. See the dht_store document for more information. This is primarily useful for echoing back in a store request.
seq
the sequence number of this item
salt
the salt, if any, used to lookup and store this item. If no salt was used, this is an empty string
item
the data for this item
authoritative
the last response for mutable data is authoritative.

dht_put_alert

Declared in "libtorrent/alert_types.hpp"

this is posted when a DHT put operation completes. This is useful if the client is waiting for a put to complete before shutting down for instance.

struct dht_put_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::dht_notification;
   sha1_hash target;
   boost::array<char, 32> public_key;
   boost::array<char, 64> signature;
   std::string salt;
   boost::uint64_t seq;
   int num_success;
};
target
the target hash the item was stored under if this was an immutable item.
public_key signature salt seq
if a mutable item was stored, these are the public key, signature, salt and sequence number the item was stored under.
num_success
DHT put operation usually writes item to k nodes, maybe the node is stale so no response, or the node doesn't support 'put', or the token for write is out of date, etc. num_success is the number of successful responses we got from the puts.

i2p_alert

Declared in "libtorrent/alert_types.hpp"

this alert is used to report errors in the i2p SAM connection

struct i2p_alert final : alert
{
   i2p_alert (aux::stack_allocator& alloc, error_code const& ec);
   virtual std::string message () const override;

   static const int static_category = alert::error_notification;
   error_code error;
};
error
the error that occurred in the i2p SAM connection

dht_outgoing_get_peers_alert

Declared in "libtorrent/alert_types.hpp"

This alert is generated when we send a get_peers request It belongs to the dht_notification category.

struct dht_outgoing_get_peers_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::dht_notification;
   sha1_hash info_hash;
   sha1_hash obfuscated_info_hash;
   udp::endpoint ip;
};
info_hash
the info_hash of the torrent we're looking for peers for.
obfuscated_info_hash
if this was an obfuscated lookup, this is the info-hash target actually sent to the node.
ip
the endpoint we're sending this query to

log_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted by some session wide event. Its main purpose is trouble shooting and debugging. It's not enabled by the default alert mask and is enabled by the alert::session_log_notification bit. Furthermore, it's by default disabled as a build configuration.

struct log_alert final : alert
{
   virtual std::string message () const override;
   char const* msg () const;

   static const int static_category = alert::session_log_notification;
};

msg()

char const* msg () const;

returns the log message

torrent_log_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted by torrent wide events. It's meant to be used for trouble shooting and debugging. It's not enabled by the default alert mask and is enabled by the alert::torrent_log_notification bit. By default it is disabled as a build configuration.

struct torrent_log_alert final : torrent_alert
{
   virtual std::string message () const override;
   char const* msg () const;

   static const int static_category = alert::torrent_log_notification;
};

msg()

char const* msg () const;

returns the log message

peer_log_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted by events specific to a peer. It's meant to be used for trouble shooting and debugging. It's not enabled by the default alert mask and is enabled by the alert::peer_log_notification bit. By default it is disabled as a build configuration.

struct peer_log_alert final : peer_alert
{
   virtual std::string message () const override;
   char const* msg () const;

   enum direction_t
   {
      incoming_message,
      outgoing_message,
      incoming,
      outgoing,
      info,
   };

   static const int static_category = alert::peer_log_notification;
   char const* event_type;
   direction_t direction;
};

msg()

char const* msg () const;

returns the log message

enum direction_t

Declared in "libtorrent/alert_types.hpp"

name value description
incoming_message 0  
outgoing_message 1  
incoming 2  
outgoing 3  
info 4  
event_type
string literal indicating the kind of event. For messages, this is the message name.

lsd_error_alert

Declared in "libtorrent/alert_types.hpp"

posted if the local service discovery socket fails to start properly. it's categorized as error_notification.

struct lsd_error_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::error_notification;
   error_code error;
};
error
The error code

dht_lookup

Declared in "libtorrent/alert_types.hpp"

holds statistics about a current dht_lookup operation. a DHT lookup is the traversal of nodes, looking up a set of target nodes in the DHT for retrieving and possibly storing information in the DHT

struct dht_lookup
{
   char const* type;
   int outstanding_requests;
   int timeouts;
   int responses;
   int branch_factor;
   int nodes_left;
   int last_sent;
   int first_timeout;
};
type
string literal indicating which kind of lookup this is
outstanding_requests
the number of outstanding request to individual nodes this lookup has right now
timeouts
the total number of requests that have timed out so far for this lookup
responses
the total number of responses we have received for this lookup so far for this lookup
branch_factor
the branch factor for this lookup. This is the number of nodes we keep outstanding requests to in parallel by default. when nodes time out we may increase this.
nodes_left
the number of nodes left that could be queries for this lookup. Many of these are likely to be part of the trail while performing the lookup and would never end up actually being queried.
last_sent
the number of seconds ago the last message was sent that's still outstanding
first_timeout
the number of outstanding requests that have exceeded the short timeout and are considered timed out in the sense that they increased the branch factor

dht_routing_bucket

Declared in "libtorrent/alert_types.hpp"

struct to hold information about a single DHT routing table bucket

struct dht_routing_bucket
{
   int num_nodes;
   int num_replacements;
   int last_active;
};
num_nodes num_replacements
the total number of nodes and replacement nodes in the routing table
last_active
number of seconds since last activity

dht_stats_alert

Declared in "libtorrent/alert_types.hpp"

contains current DHT state. Posted in response to session::post_dht_stats().

struct dht_stats_alert final : alert
{
   virtual std::string message () const override;

   static const int static_category = alert::stats_notification;
   std::vector<dht_lookup> active_requests;
   std::vector<dht_routing_bucket> routing_table;
};
active_requests
a vector of the currently running DHT lookups.
routing_table
contains information about every bucket in the DHT routing table.

incoming_request_alert

Declared in "libtorrent/alert_types.hpp"

posted every time an incoming request from a peer is accepted and queued up for being serviced. This alert is only posted if the alert::incoming_request_notification flag is enabled in the alert mask.

struct incoming_request_alert final : peer_alert
{
   virtual std::string message () const override;

   static const int static_category = alert::incoming_request_notification;
   peer_request req;
};
req
the request this peer sent to us

dht_log_alert

Declared in "libtorrent/alert_types.hpp"

struct dht_log_alert final : alert
{
   dht_log_alert (aux::stack_allocator& alloc
      , dht_module_t m, char const* msg);
   virtual std::string message () const override;
   char const* log_message () const;

   enum dht_module_t
   {
      tracker,
      node,
      routing_table,
      rpc_manager,
      traversal,
   };

   static const int static_category = alert::dht_log_notification;
   dht_module_t module;
};

log_message()

char const* log_message () const;

the log message

enum dht_module_t

Declared in "libtorrent/alert_types.hpp"

name value description
tracker 0  
node 1  
routing_table 2  
rpc_manager 3  
traversal 4  
module
the module, or part, of the DHT that produced this log message.

dht_pkt_alert

Declared in "libtorrent/alert_types.hpp"

This alert is posted every time a DHT message is sent or received. It is only posted if the alert::dht_log_notification alert category is enabled. It contains a verbatim copy of the message.

struct dht_pkt_alert final : alert
{
   dht_pkt_alert (aux::stack_allocator& alloc, char const* buf, int size
      , dht_pkt_alert::direction_t d, udp::endpoint ep);
   virtual std::string message () const override;
   int pkt_size () const;
   char const* pkt_buf () const;

   enum direction_t
   {
      incoming,
      outgoing,
   };

   static const int static_category = alert::dht_log_notification;
   direction_t dir;
   udp::endpoint node;
};

pkt_size() pkt_buf()

int pkt_size () const;
char const* pkt_buf () const;

returns a pointer to the packet buffer and size of the packet, respectively. This buffer is only valid for as long as the alert itself is valid, which is owned by libtorrent and reclaimed whenever pop_alerts() is called on the session.

enum direction_t

Declared in "libtorrent/alert_types.hpp"

name value description
incoming 0  
outgoing 1  
dir
whether this is an incoming or outgoing packet.
node
the DHT node we received this packet from, or sent this packet to (depending on dir).

dht_get_peers_reply_alert

Declared in "libtorrent/alert_types.hpp"

struct dht_get_peers_reply_alert final : alert
{
   dht_get_peers_reply_alert (aux::stack_allocator& alloc
      , sha1_hash const& ih
      , std::vector<tcp::endpoint> const& v);
   virtual std::string message () const override;
   int num_peers () const;
   std::vector<tcp::endpoint> peers () const;

   static const int static_category = alert::dht_operation_notification;
   sha1_hash info_hash;
};

dht_direct_response_alert

Declared in "libtorrent/alert_types.hpp"

This is posted exactly once for every call to session_handle::dht_direct_request. If the request failed, response() will return a default constructed bdecode_node.

struct dht_direct_response_alert final : alert
{
   dht_direct_response_alert (aux::stack_allocator& alloc, void* userdata
      , udp::endpoint const& addr, bdecode_node const& response);
   virtual std::string message () const override;
   dht_direct_response_alert (aux::stack_allocator& alloc, void* userdata
      , udp::endpoint const& addr);
   bdecode_node response () const;

   static const int static_category = alert::dht_notification;
   void* userdata;
   udp::endpoint addr;
};

dht_direct_response_alert() message()

virtual std::string message () const override;
dht_direct_response_alert (aux::stack_allocator& alloc, void* userdata
      , udp::endpoint const& addr);

for when there was a timeout so we don't have a response

picker_log_alert

Declared in "libtorrent/alert_types.hpp"

this is posted when one or more blocks are picked by the piece picker, assuming the verbose piece picker logging is enabled (see picker_log_notification).

struct picker_log_alert final : peer_alert
{
   virtual std::string message () const override;
   std::vector<piece_block> blocks () const;

   enum picker_flags_t
   {
      partial_ratio,
      prioritize_partials,
      rarest_first_partials,
      rarest_first,
      reverse_rarest_first,
      suggested_pieces,
      prio_sequential_pieces,
      sequential_pieces,
      reverse_pieces,
      time_critical,
      random_pieces,
      prefer_contiguous,
      reverse_sequential,
      backup1,
      backup2,
      end_game,
   };

   static const int static_category = alert::picker_log_notification;
   boost::uint32_t picker_flags;
};

enum picker_flags_t

Declared in "libtorrent/alert_types.hpp"

name value description
partial_ratio 1 the ratio of partial pieces is too high. This forces a preference for picking blocks from partial pieces.
prioritize_partials 2  
rarest_first_partials 4  
rarest_first 8  
reverse_rarest_first 16  
suggested_pieces 32  
prio_sequential_pieces 64  
sequential_pieces 128  
reverse_pieces 256  
time_critical 512  
random_pieces 1024  
prefer_contiguous 2048  
reverse_sequential 4096  
backup1 8192  
backup2 16384  
end_game 32768  
picker_flags
this is a bitmask of which features were enabled for this particular pick. The bits are defined in the picker_flags_t enum.

alert_cast()

Declared in "libtorrent/alert.hpp"

template <class T> T* alert_cast (alert* a);
template <class T> T const* alert_cast (alert const* a);

When you get an alert, you can use alert_cast<> to attempt to cast the pointer to a specific alert type, in order to query it for more information.

Note

alert_cast<> can only cast to an exact alert type, not a base class

operation_name()

Declared in "libtorrent/alert_types.hpp"

char const* operation_name (int op);

maps an operation id (from peer_error_alert and peer_disconnected_alert) to its name. See peer_connection for the constants

enum operation_t

Declared in "libtorrent/operations.hpp"

name value description
op_bittorrent 0 this is used when the bittorrent logic determines to disconnect
op_iocontrol 1 a call to iocontrol failed
op_getpeername 2 a call to getpeername failed (querying the remote IP of a connection)
op_getname 3 a call to getname failed (querying the local IP of a connection)
op_alloc_recvbuf 4 an attempt to allocate a receive buffer failed
op_alloc_sndbuf 5 an attempt to allocate a send buffer failed
op_file_write 6 writing to a file failed
op_file_read 7 reading from a file failed
op_file 8 a non-read and non-write file operation failed
op_sock_write 9 a socket write operation failed
op_sock_read 10 a socket read operation failed
op_sock_open 11 a call to open(), to create a socket socket failed
op_sock_bind 12 a call to bind() on a socket failed
op_available 13 an attempt to query the number of bytes available to read from a socket failed
op_encryption 14 a call related to bittorrent protocol encryption failed
op_connect 15 an attempt to connect a socket failed
op_ssl_handshake 16 establishing an SSL connection failed
op_get_interface 17 a connection failed to satisfy the bind interface setting

home

Filter

ip_filter

Declared in "libtorrent/ip_filter.hpp"

The ip_filter class is a set of rules that uniquely categorizes all ip addresses as allowed or disallowed. The default constructor creates a single rule that allows all addresses (0.0.0.0 - 255.255.255.255 for the IPv4 range, and the equivalent range covering all addresses for the IPv6 range).

A default constructed ip_filter does not filter any address.

struct ip_filter
{
   void add_rule (address first, address last, boost::uint32_t flags);
   int access (address const& addr) const;
   filter_tuple_t export_filter () const;

   enum access_flags
   {
      blocked,
   };
};

add_rule()

void add_rule (address first, address last, boost::uint32_t flags);

Adds a rule to the filter. first and last defines a range of ip addresses that will be marked with the given flags. The flags can currently be 0, which means allowed, or ip_filter::blocked, which means disallowed.

precondition: first.is_v4() == last.is_v4() && first.is_v6() == last.is_v6()

postcondition: access(x) == flags for every x in the range [first, last]

This means that in a case of overlapping ranges, the last one applied takes precedence.

access()

int access (address const& addr) const;

Returns the access permissions for the given address (addr). The permission can currently be 0 or ip_filter::blocked. The complexity of this operation is O(log n), where n is the minimum number of non-overlapping ranges to describe the current filter.

export_filter()

filter_tuple_t export_filter () const;

This function will return the current state of the filter in the minimum number of ranges possible. They are sorted from ranges in low addresses to high addresses. Each entry in the returned vector is a range with the access control specified in its flags field.

The return value is a tuple containing two range-lists. One for IPv4 addresses and one for IPv6 addresses.

enum access_flags

Declared in "libtorrent/ip_filter.hpp"

name value description
blocked 1 indicates that IPs in this range should not be connected to nor accepted as incoming connections

port_filter

Declared in "libtorrent/ip_filter.hpp"

the port filter maps non-overlapping port ranges to flags. This is primarily used to indicate whether a range of ports should be connected to or not. The default is to have the full port range (0-65535) set to flag 0.

class port_filter
{
   void add_rule (boost::uint16_t first, boost::uint16_t last, boost::uint32_t flags);
   int access (boost::uint16_t port) const;

   enum access_flags
   {
      blocked,
   };
};

add_rule()

void add_rule (boost::uint16_t first, boost::uint16_t last, boost::uint32_t flags);

set the flags for the specified port range (first, last) to flags overwriting any existing rule for those ports. The range is inclusive, i.e. the port last also has the flag set on it.

access()

int access (boost::uint16_t port) const;

test the specified port (port) for whether it is blocked or not. The returned value is the flags set for this port. see acces_flags.

enum access_flags

Declared in "libtorrent/ip_filter.hpp"

name value description
blocked 1 this flag indicates that destination ports in the range should not be connected to

home

Settings

You have some control over session configuration through the session::apply_settings() member function. To change one or more configuration options, create a settings_pack object and fill it with the settings to be set and pass it in to session::apply_settings().

The settings_pack object is a collection of settings updates that are applied to the session when passed to session::apply_settings(). It's empty when constructed.

You have control over proxy and authorization settings and also the user-agent that will be sent to the tracker. The user-agent will also be used to identify the client with other peers.

dht_settings

Declared in "libtorrent/session_settings.hpp"

structure used to hold configuration options for the DHT

The dht_settings struct used to contain a service_port member to control which port the DHT would listen on and send messages from. This field is deprecated and ignored. libtorrent always tries to open the UDP socket on the same port as the TCP socket.

struct dht_settings
{
   dht_settings ();

   int max_peers_reply;
   int search_branching;
   int max_fail_count;
   int max_torrents;
   int max_dht_items;
   int max_peers;
   int max_torrent_search_reply;
   bool restrict_routing_ips;
   bool restrict_search_ips;
   bool extended_routing_table;
   bool aggressive_lookups;
   bool privacy_lookups;
   bool enforce_node_id;
   bool ignore_dark_internet;
   int block_timeout;
   int block_ratelimit;
   bool read_only;
   int item_lifetime;
};

dht_settings()

dht_settings ();

initialized dht_settings to the default values

max_peers_reply
the maximum number of peers to send in a reply to get_peers
search_branching
the number of concurrent search request the node will send when announcing and refreshing the routing table. This parameter is called alpha in the kademlia paper
max_fail_count
the maximum number of failed tries to contact a node before it is removed from the routing table. If there are known working nodes that are ready to replace a failing node, it will be replaced immediately, this limit is only used to clear out nodes that don't have any node that can replace them.
max_torrents
the total number of torrents to track from the DHT. This is simply an upper limit to make sure malicious DHT nodes cannot make us allocate an unbounded amount of memory.
max_dht_items
max number of items the DHT will store
max_peers
the max number of peers to store per torrent (for the DHT)
max_torrent_search_reply
the max number of torrents to return in a torrent search query to the DHT
restrict_routing_ips

determines if the routing table entries should restrict entries to one per IP. This defaults to true, which helps mitigate some attacks on the DHT. It prevents adding multiple nodes with IPs with a very close CIDR distance.

when set, nodes whose IP address that's in the same /24 (or /64 for IPv6) range in the same routing table bucket. This is an attempt to mitigate node ID spoofing attacks also restrict any IP to only have a single entry in the whole routing table

restrict_search_ips
determines if DHT searches should prevent adding nodes with IPs with very close CIDR distance. This also defaults to true and helps mitigate certain attacks on the DHT.
extended_routing_table
makes the first buckets in the DHT routing table fit 128, 64, 32 and 16 nodes respectively, as opposed to the standard size of 8. All other buckets have size 8 still.
aggressive_lookups
slightly changes the lookup behavior in terms of how many outstanding requests we keep. Instead of having branch factor be a hard limit, we always keep branch factor outstanding requests to the closest nodes. i.e. every time we get results back with closer nodes, we query them right away. It lowers the lookup times at the cost of more outstanding queries.
privacy_lookups
when set, perform lookups in a way that is slightly more expensive, but which minimizes the amount of information leaked about you.
enforce_node_id
when set, node's whose IDs that are not correctly generated based on its external IP are ignored. When a query arrives from such node, an error message is returned with a message saying "invalid node ID".
ignore_dark_internet
ignore DHT messages from parts of the internet we wouldn't expect to see any traffic from
block_timeout
the number of seconds a DHT node is banned if it exceeds the rate limit. The rate limit is averaged over 10 seconds to allow for bursts above the limit.
block_ratelimit
the max number of packets per second a DHT node is allowed to send without getting banned.
read_only
when set, the other nodes won't keep this node in their routing tables, it's meant for low-power and/or ephemeral devices that cannot support the DHT, it is also useful for mobile devices which are sensitive to network traffic and battery life. this node no longer responds to 'query' messages, and will place a 'ro' key (value = 1) in the top-level message dictionary of outgoing query messages.
item_lifetime
the number of seconds a immutable/mutable item will be expired. default is 0, means never expires.

settings_pack

Declared in "libtorrent/settings_pack.hpp"

The settings_pack struct, contains the names of all settings as enum values. These values are passed in to the set_str(), set_int(), set_bool() functions, to specify the setting to change.

These are the available settings:

name type default
user_agent string "libtorrent/" LIBTORRENT_VERSION

this is the client identification to the tracker. The recommended format of this string is: "ClientName/ClientVersion libtorrent/libtorrentVersion". This name will not only be used when making HTTP requests, but also when sending extended headers to peers that support that extension. It may not contain r or n

name type default
announce_ip string 0

announce_ip is the ip address passed along to trackers as the &ip= parameter. If left as the default, that parameter is omitted.

name type default
handshake_client_version string 0

this is the client name and version identifier sent to peers in the handshake message. If this is an empty string, the user_agent is used instead

name type default
outgoing_interfaces string ""

sets the network interface this session will use when it opens outgoing connections. By default, it binds outgoing connections to INADDR_ANY and port 0 (i.e. let the OS decide). Ths parameter must be a string containing one or more, comma separated, adapter names. Adapter names on unix systems are of the form "eth0", "eth1", "tun0", etc. When specifying multiple interfaces, they will be assigned in round-robin order. This may be useful for clients that are multi-homed. Binding an outgoing connection to a local IP does not necessarily make the connection via the associated NIC/Adapter. Setting this to an empty string will disable binding of outgoing connections.

name type default
listen_interfaces string "0.0.0.0:6881"

a comma-separated list of IP port-pairs. These are the listen ports that will be opened for accepting incoming uTP and TCP connections. It is possible to listen on multiple IPs and multiple ports. Binding to port 0 will make the operating system pick the port. The default is "0.0.0.0:6881", which binds to all interfaces on port 6881.

If binding fails because the port is busy, the port number will be incremented by one, settings_pack::max_retry_port_bind times.

if all retry attempts fail, the socket will be bound to port 0, meaning the operating system will pick a port. This behavior can be disabled by disabling settings_pack::listen_system_port_fallback.

if binding fails, the listen_failed_alert is posted, potentially more than once. Once/if binding the listen socket(s) succeed, listen_succeeded_alert is posted.

Each port will attempt to open both a UDP and a TCP listen socket, to allow accepting uTP connections as well as TCP. If using the DHT, this will also make the DHT use the same UDP ports.

Note

The current support for opening arbitrary UDP sockets is limited. In this version of libtorrent, there will only ever be two UDP sockets, one for IPv4 and one for IPv6.

name type default
proxy_hostname string ""

when using a poxy, this is the hostname where the proxy is running see proxy_type.

name type default
proxy_username string ""
proxy_password string ""

when using a proxy, these are the credentials (if any) to use whne connecting to it. see proxy_type

name type default
i2p_hostname string ""

sets the i2p SAM bridge to connect to. set the port with the i2p_port setting.

name type default
peer_fingerprint string "-LT1120-"

this is the fingerprint for the client. It will be used as the prefix to the peer_id. If this is 20 bytes (or longer) it will be truncated at 20 bytes and used as the entire peer-id

There is a utility function, generate_fingerprint() that can be used to generate a standard client peer ID fingerprint prefix.

name type default
dht_bootstrap_nodes string "dht.libtorrent.org:25401"

This is a comma-separated list of IP port-pairs. They will be added to the DHT node (if it's enabled) as back-up nodes in case we don't know of any. This setting will contain one or more bootstrap nodes by default.

Changing these after the DHT has been started may not have any effect until the DHT is restarted.

name type default
allow_multiple_connections_per_ip bool false

determines if connections from the same IP address as existing connections should be rejected or not. Multiple connections from the same IP address is not allowed by default, to prevent abusive behavior by peers. It may be useful to allow such connections in cases where simulations are run on the same machine, and all peers in a swarm has the same IP address.

name type default
send_redundant_have bool true

send_redundant_have controls if have messages will be sent to peers that already have the piece. This is typically not necessary, but it might be necessary for collecting statistics in some cases. Default is false.

name type default
lazy_bitfields bool false

if this is true, outgoing bitfields will never be fuil. If the client is seed, a few bits will be set to 0, and later filled in with have messages. This is to prevent certain ISPs from stopping people from seeding.

name type default
use_dht_as_fallback bool false

use_dht_as_fallback determines how the DHT is used. If this is true, the DHT will only be used for torrents where all trackers in its tracker list has failed. Either by an explicit error message or a time out. This is false by default, which means the DHT is used by default regardless of if the trackers fail or not.

name type default
upnp_ignore_nonrouters bool false

upnp_ignore_nonrouters indicates whether or not the UPnP implementation should ignore any broadcast response from a device whose address is not the configured router for this machine. i.e. it's a way to not talk to other people's routers by mistake.

name type default
use_parole_mode bool true

use_parole_mode specifies if parole mode should be used. Parole mode means that peers that participate in pieces that fail the hash check are put in a mode where they are only allowed to download whole pieces. If the whole piece a peer in parole mode fails the hash check, it is banned. If a peer participates in a piece that passes the hash check, it is taken out of parole mode.

name type default
use_read_cache bool true

enable and disable caching of blocks read from disk. the purpose of the read cache is partly read-ahead of requests but also to avoid reading blocks back from the disk multiple times for popular pieces.

name type default
coalesce_reads bool false
coalesce_writes bool false

allocate separate, contiguous, buffers for read and write calls. Only used where writev/readv cannot be used will use more RAM but may improve performance

name type default
auto_manage_prefer_seeds bool false

prefer seeding torrents when determining which torrents to give active slots to, the default is false which gives preference to downloading torrents

name type default
dont_count_slow_torrents bool true

if dont_count_slow_torrents is true, torrents without any payload transfers are not subject to the active_seeds and active_downloads limits. This is intended to make it more likely to utilize all available bandwidth, and avoid having torrents that don't transfer anything block the active slots.

name type default
close_redundant_connections bool true

close_redundant_connections specifies whether libtorrent should close connections where both ends have no utility in keeping the connection open. For instance if both ends have completed their downloads, there's no point in keeping it open.

name type default
prioritize_partial_pieces bool false

If prioritize_partial_pieces is true, partial pieces are picked before pieces that are more rare. If false, rare pieces are always prioritized, unless the number of partial pieces is growing out of proportion.

name type default
rate_limit_ip_overhead bool true

if set to true, the estimated TCP/IP overhead is drained from the rate limiters, to avoid exceeding the limits with the total traffic

name type default
announce_to_all_tiers bool false
announce_to_all_trackers bool false

announce_to_all_trackers controls how multi tracker torrents are treated. If this is set to true, all trackers in the same tier are announced to in parallel. If all trackers in tier 0 fails, all trackers in tier 1 are announced as well. If it's set to false, the behavior is as defined by the multi tracker specification. It defaults to false, which is the same behavior previous versions of libtorrent has had as well.

announce_to_all_tiers also controls how multi tracker torrents are treated. When this is set to true, one tracker from each tier is announced to. This is the uTorrent behavior. This is false by default in order to comply with the multi-tracker specification.

name type default
prefer_udp_trackers bool true

prefer_udp_trackers is true by default. It means that trackers may be rearranged in a way that udp trackers are always tried before http trackers for the same hostname. Setting this to false means that the trackers' tier is respected and there's no preference of one protocol over another.

name type default
strict_super_seeding bool false

strict_super_seeding when this is set to true, a piece has to have been forwarded to a third peer before another one is handed out. This is the traditional definition of super seeding.

name type default
disable_hash_checks bool false

when set to true, all data downloaded from peers will be assumed to be correct, and not tested to match the hashes in the torrent this is only useful for simulation and testing purposes (typically combined with disabled_storage)

name type default
allow_i2p_mixed bool false

if this is true, i2p torrents are allowed to also get peers from other sources than the tracker, and connect to regular IPs, not providing any anonymization. This may be useful if the user is not interested in the anonymization of i2p, but still wants to be able to connect to i2p peers.

name type default
low_prio_disk bool true

low_prio_disk determines if the disk I/O should use a normal or low priority policy. This defaults to true, which means that it's low priority by default. Other processes doing disk I/O will normally take priority in this mode. This is meant to improve the overall responsiveness of the system while downloading in the background. For high-performance server setups, this might not be desirable.

name type default
volatile_read_cache bool false

volatile_read_cache, if this is set to true, read cache blocks that are hit by peer read requests are removed from the disk cache to free up more space. This is useful if you don't expect the disk cache to create any cache hits from other peers than the one who triggered the cache line to be read into the cache in the first place.

name type default
guided_read_cache bool false

guided_read_cache enables the disk cache to adjust the size of a cache line generated by peers to depend on the upload rate you are sending to that peer. The intention is to optimize the RAM usage of the cache, to read ahead further for peers that you're sending faster to.

name type default
no_atime_storage bool true

no_atime_storage this is a linux-only option and passes in the O_NOATIME to open() when opening files. This may lead to some disk performance improvements.

name type default
incoming_starts_queued_torrents bool false

incoming_starts_queued_torrents defaults to false. If a torrent has been paused by the auto managed feature in libtorrent, i.e. the torrent is paused and auto managed, this feature affects whether or not it is automatically started on an incoming connection. The main reason to queue torrents, is not to make them unavailable, but to save on the overhead of announcing to the trackers, the DHT and to avoid spreading one's unchoke slots too thin. If a peer managed to find us, even though we're no in the torrent anymore, this setting can make us start the torrent and serve it.

name type default
report_true_downloaded bool false

when set to true, the downloaded counter sent to trackers will include the actual number of payload bytes downloaded including redundant bytes. If set to false, it will not include any redundancy bytes

name type default
strict_end_game_mode bool true

strict_end_game_mode defaults to true, and controls when a block may be requested twice. If this is true, a block may only be requested twice when there's ay least one request to every piece that's left to download in the torrent. This may slow down progress on some pieces sometimes, but it may also avoid downloading a lot of redundant bytes. If this is false, libtorrent attempts to use each peer connection to its max, by always requesting something, even if it means requesting something that has been requested from another peer already.

name type default
broadcast_lsd bool true

if broadcast_lsd is set to true, the local peer discovery (or Local Service Discovery) will not only use IP multicast, but also broadcast its messages. This can be useful when running on networks that don't support multicast. Since broadcast messages might be expensive and disruptive on networks, only every 8th announce uses broadcast.

name type default
enable_outgoing_utp bool true
enable_incoming_utp bool true
enable_outgoing_tcp bool true
enable_incoming_tcp bool true

when set to true, libtorrent will try to make outgoing utp connections controls whether libtorrent will accept incoming connections or make outgoing connections of specific type.

name type default
ignore_resume_timestamps bool false

ignore_resume_timestamps determines if the storage, when loading resume data files, should verify that the file modification time with the timestamps in the resume data. This defaults to false, which means timestamps are taken into account, and resume data is less likely to accepted (torrents are more likely to be fully checked when loaded). It might be useful to set this to true if your network is faster than your disk, and it would be faster to redownload potentially missed pieces than to go through the whole storage to look for them.

name type default
no_recheck_incomplete_resume bool false

no_recheck_incomplete_resume determines if the storage should check the whole files when resume data is incomplete or missing or whether it should simply assume we don't have any of the data. By default, this is determined by the existence of any of the files. By setting this setting to true, the files won't be checked, but will go straight to download mode.

name type default
anonymous_mode bool false

anonymous_mode defaults to false. When set to true, the client tries to hide its identity to a certain degree. The peer-ID will no longer include the client's fingerprint. The user-agent will be reset to an empty string. Trackers will only be used if they are using a proxy server. The listen sockets are closed, and incoming connections will only be accepted through a SOCKS5 or I2P proxy (if a peer proxy is set up and is run on the same machine as the tracker proxy). Since no incoming connections are accepted, NAT-PMP, UPnP, DHT and local peer discovery are all turned off when this setting is enabled.

If you're using I2P, it might make sense to enable anonymous mode as well.

name type default
report_web_seed_downloads bool true

specifies whether downloads from web seeds is reported to the tracker or not. Defaults to on. Turning it off also excludes web seed traffic from other stats and download rate reporting via the libtorrent API.

name type default
announce_double_nat bool false

set to true if uTP connections should be rate limited This option is DEPRECATED, please use set_peer_class_filter() instead. if this is true, the &ip= argument in tracker requests (unless otherwise specified) will be set to the intermediate IP address if the user is double NATed. If the user is not double NATed, this option does not have an affect

name type default
seeding_outgoing_connections bool true

seeding_outgoing_connections determines if seeding (and finished) torrents should attempt to make outgoing connections or not. By default this is true. It may be set to false in very specific applications where the cost of making outgoing connections is high, and there are no or small benefits of doing so. For instance, if no nodes are behind a firewall or a NAT, seeds don't need to make outgoing connections.

name type default
no_connect_privileged_ports bool false

when this is true, libtorrent will not attempt to make outgoing connections to peers whose port is < 1024. This is a safety precaution to avoid being part of a DDoS attack

name type default
smooth_connects bool true

smooth_connects is true by default, which means the number of connection attempts per second may be limited to below the connection_speed, in case we're close to bump up against the limit of number of connections. The intention of this setting is to more evenly distribute our connection attempts over time, instead of attempting to connect in batches, and timing them out in batches.

name type default
always_send_user_agent bool false

always send user-agent in every web seed request. If false, only the first request per http connection will include the user agent

name type default
apply_ip_filter_to_trackers bool true

apply_ip_filter_to_trackers defaults to true. It determines whether the IP filter applies to trackers as well as peers. If this is set to false, trackers are exempt from the IP filter (if there is one). If no IP filter is set, this setting is irrelevant.

name type default
use_disk_read_ahead bool true

use_disk_read_ahead defaults to true and will attempt to optimize disk reads by giving the operating system heads up of disk read requests as they are queued in the disk job queue.

name type default
lock_files bool false

lock_files determines whether or not to lock files which libtorrent is downloading to or seeding from. This is implemented using fcntl(F_SETLK) on unix systems and by not passing in SHARE_READ and SHARE_WRITE on windows. This might prevent 3rd party processes from corrupting the files under libtorrent's feet.

name type default
contiguous_recv_buffer bool true

contiguous_recv_buffer determines whether or not libtorrent should receive data from peers into a contiguous intermediate buffer, to then copy blocks into disk buffers from, or to make many smaller calls to read(), each time passing in the specific buffer the data belongs in. When downloading at high rates, the latter may save some time copying data. When seeding at high rates, all incoming traffic consists of a very large number of tiny packets, and enabling contiguous_recv_buffer will provide higher performance. When this is enabled, it will only be used when seeding to peers, since that's when it provides performance improvements.

name type default
ban_web_seeds bool true

when true, web seeds sending bad data will be banned

name type default
allow_partial_disk_writes bool true

when set to false, the write_cache_line_size will apply across piece boundaries. this is a bad idea unless the piece picker also is configured to have an affinity to pick pieces belonging to the same write cache line as is configured in the disk cache.

name type default
force_proxy bool false

If true, disables any communication that's not going over a proxy. Enabling this requires a proxy to be configured as well, see proxy_type and proxy_hostname settings. The listen sockets are closed, and incoming connections will only be accepted through a SOCKS5 or I2P proxy (if a peer proxy is set up and is run on the same machine as the tracker proxy). This setting also disabled peer country lookups, since those are done via DNS lookups that aren't supported by proxies.

name type default
support_share_mode bool true

if false, prevents libtorrent to advertise share-mode support

name type default
support_merkle_torrents bool true

if this is false, don't advertise support for the Tribler merkle tree piece message

name type default
report_redundant_bytes bool true

if this is true, the number of redundant bytes is sent to the tracker

name type default
listen_system_port_fallback bool true

if this is true, libtorrent will fall back to listening on a port chosen by the operating system (i.e. binding to port 0). If a failure is preferred, set this to false.

name type default
use_disk_cache_pool bool true

use_disk_cache_pool enables using a pool allocator for disk cache blocks. Enabling it makes the cache perform better at high throughput. It also makes the cache less likely and slower at returning memory back to the system, once allocated.

name type default
announce_crypto_support bool true

when this is true, and incoming encrypted connections are enabled, &supportcrypt=1 is included in http tracker announces

name type default
enable_upnp bool true

Starts and stops the UPnP service. When started, the listen port and the DHT port are attempted to be forwarded on local UPnP router devices.

The upnp object returned by start_upnp() can be used to add and remove arbitrary port mappings. Mapping status is returned through the portmap_alert and the portmap_error_alert. The object will be valid until stop_upnp() is called. See upnp and nat pmp.

name type default
enable_natpmp bool true

Starts and stops the NAT-PMP service. When started, the listen port and the DHT port are attempted to be forwarded on the router through NAT-PMP.

The natpmp object returned by start_natpmp() can be used to add and remove arbitrary port mappings. Mapping status is returned through the portmap_alert and the portmap_error_alert. The object will be valid until stop_natpmp() is called. See upnp and nat pmp.

name type default
enable_lsd bool true

Starts and stops Local Service Discovery. This service will broadcast the infohashes of all the non-private torrents on the local network to look for peers on the same swarm within multicast reach.

name type default
enable_dht bool true

starts the dht node and makes the trackerless service available to torrents.

name type default
prefer_rc4 bool false

if the allowed encryption level is both, setting this to true will prefer rc4 if both methods are offered, plaintext otherwise

name type default
proxy_hostnames bool true

if true, hostname lookups are done via the configured proxy (if any). This is only supported by SOCKS5 and HTTP.

name type default
proxy_peer_connections bool true

if true, peer connections are made (and accepted) over the configured proxy, if any. Web seeds as well as regular bittorrent peer connections are considered "peer connections". Anything transporting actual torrent payload (trackers and DHT traffic are not considered peer connections).

name type default
auto_sequential bool true

if this setting is true, torrents with a very high availability of pieces (and seeds) are downloaded sequentially. This is more efficient for the disk I/O. With many seeds, the download order is unlikely to matter anyway

name type default
proxy_tracker_connections bool true

if true, tracker connections are made over the configured proxy, if any.

name type default
tracker_completion_timeout int 30

tracker_completion_timeout is the number of seconds the tracker connection will wait from when it sent the request until it considers the tracker to have timed-out. Default value is 60 seconds.

name type default
tracker_receive_timeout int 10

tracker_receive_timeout is the number of seconds to wait to receive any data from the tracker. If no data is received for this number of seconds, the tracker will be considered as having timed out. If a tracker is down, this is the kind of timeout that will occur.

name type default
stop_tracker_timeout int 5

the time to wait when sending a stopped message before considering a tracker to have timed out. this is usually shorter, to make the client quit faster

name type default
tracker_maximum_response_length int 1024*1024

this is the maximum number of bytes in a tracker response. If a response size passes this number of bytes it will be rejected and the connection will be closed. On gzipped responses this size is measured on the uncompressed data. So, if you get 20 bytes of gzip response that'll expand to 2 megabytes, it will be interrupted before the entire response has been uncompressed (assuming the limit is lower than 2 megs).

name type default
piece_timeout int 20

the number of seconds from a request is sent until it times out if no piece response is returned.

name type default
request_timeout int 60

the number of seconds one block (16kB) is expected to be received within. If it's not, the block is requested from a different peer

name type default
request_queue_time int 3

the length of the request queue given in the number of seconds it should take for the other end to send all the pieces. i.e. the actual number of requests depends on the download rate and this number.

name type default
max_allowed_in_request_queue int 500

the number of outstanding block requests a peer is allowed to queue up in the client. If a peer sends more requests than this (before the first one has been sent) the last request will be dropped. the higher this is, the faster upload speeds the client can get to a single peer.

name type default
max_out_request_queue int 500

max_out_request_queue is the maximum number of outstanding requests to send to a peer. This limit takes precedence over request_queue_time. i.e. no matter the download speed, the number of outstanding requests will never exceed this limit.

name type default
whole_pieces_threshold int 20

if a whole piece can be downloaded in this number of seconds, or less, the peer_connection will prefer to request whole pieces at a time from this peer. The benefit of this is to better utilize disk caches by doing localized accesses and also to make it easier to identify bad peers if a piece fails the hash check.

name type default
peer_timeout int 120

peer_timeout is the number of seconds the peer connection should wait (for any activity on the peer connection) before closing it due to time out. This defaults to 120 seconds, since that's what's specified in the protocol specification. After half the time out, a keep alive message is sent.

name type default
urlseed_timeout int 20

same as peer_timeout, but only applies to url-seeds. this is usually set lower, because web servers are expected to be more reliable.

name type default
urlseed_pipeline_size int 5

controls the pipelining size of url-seeds. i.e. the number of HTTP request to keep outstanding before waiting for the first one to complete. It's common for web servers to limit this to a relatively low number, like 5

name type default
urlseed_wait_retry int 30

time to wait until a new retry of a web seed takes place

name type default
file_pool_size int 40

sets the upper limit on the total number of files this session will keep open. The reason why files are left open at all is that some anti virus software hooks on every file close, and scans the file for viruses. deferring the closing of the files will be the difference between a usable system and a completely hogged down system. Most operating systems also has a limit on the total number of file descriptors a process may have open. It is usually a good idea to find this limit and set the number of connections and the number of files limits so their sum is slightly below it.

name type default
max_failcount int 3

max_failcount is the maximum times we try to connect to a peer before stop connecting again. If a peer succeeds, the failcounter is reset. If a peer is retrieved from a peer source (other than DHT) the failcount is decremented by one, allowing another try.

name type default
min_reconnect_time int 60

the number of seconds to wait to reconnect to a peer. this time is multiplied with the failcount.

name type default
peer_connect_timeout int 15

peer_connect_timeout the number of seconds to wait after a connection attempt is initiated to a peer until it is considered as having timed out. This setting is especially important in case the number of half-open connections are limited, since stale half-open connection may delay the connection of other peers considerably.

name type default
connection_speed int 10

connection_speed is the number of connection attempts that are made per second. If a number < 0 is specified, it will default to 200 connections per second. If 0 is specified, it means don't make outgoing connections at all.

name type default
inactivity_timeout int 600

if a peer is uninteresting and uninterested for longer than this number of seconds, it will be disconnected. default is 10 minutes

name type default
unchoke_interval int 15

unchoke_interval is the number of seconds between chokes/unchokes. On this interval, peers are re-evaluated for being choked/unchoked. This is defined as 30 seconds in the protocol, and it should be significantly longer than what it takes for TCP to ramp up to it's max rate.

name type default
optimistic_unchoke_interval int 30

optimistic_unchoke_interval is the number of seconds between each optimistic unchoke. On this timer, the currently optimistically unchoked peer will change.

name type default
num_want int 200

num_want is the number of peers we want from each tracker request. It defines what is sent as the &num_want= parameter to the tracker.

name type default
initial_picker_threshold int 4

initial_picker_threshold specifies the number of pieces we need before we switch to rarest first picking. This defaults to 4, which means the 4 first pieces in any torrent are picked at random, the following pieces are picked in rarest first order.

name type default
allowed_fast_set_size int 10

the number of allowed pieces to send to peers that supports the fast extensions

name type default
suggest_mode int settings_pack::no_piece_suggestions

suggest_mode controls whether or not libtorrent will send out suggest messages to create a bias of its peers to request certain pieces. The modes are:

  • no_piece_suggestsions which is the default and will not send out suggest messages.
  • suggest_read_cache which will send out suggest messages for the most recent pieces that are in the read cache.
name type default
max_queued_disk_bytes int 1024 * 1024

max_queued_disk_bytes is the number maximum number of bytes, to be written to disk, that can wait in the disk I/O thread queue. This queue is only for waiting for the disk I/O thread to receive the job and either write it to disk or insert it in the write cache. When this limit is reached, the peer connections will stop reading data from their sockets, until the disk thread catches up. Setting this too low will severely limit your download rate.

name type default
handshake_timeout int 10

the number of seconds to wait for a handshake response from a peer. If no response is received within this time, the peer is disconnected.

name type default
send_buffer_low_watermark int 10 * 1024
send_buffer_watermark int 500 * 1024
send_buffer_watermark_factor int 50

send_buffer_low_watermark the minimum send buffer target size (send buffer includes bytes pending being read from disk). For good and snappy seeding performance, set this fairly high, to at least fit a few blocks. This is essentially the initial window size which will determine how fast we can ramp up the send rate

if the send buffer has fewer bytes than send_buffer_watermark, we'll read another 16kB block onto it. If set too small, upload rate capacity will suffer. If set too high, memory will be wasted. The actual watermark may be lower than this in case the upload rate is low, this is the upper limit.

the current upload rate to a peer is multiplied by this factor to get the send buffer watermark. The factor is specified as a percentage. i.e. 50 -> 0.5 This product is clamped to the send_buffer_watermark setting to not exceed the max. For high speed upload, this should be set to a greater value than 100. For high capacity connections, setting this higher can improve upload performance and disk throughput. Setting it too high may waste RAM and create a bias towards read jobs over write jobs.

name type default
choking_algorithm int settings_pack::fixed_slots_choker
seed_choking_algorithm int settings_pack::round_robin

choking_algorithm specifies which algorithm to use to determine which peers to unchoke.

The options for choking algorithms are:

  • fixed_slots_choker is the traditional choker with a fixed number of unchoke slots (as specified by session::set_max_uploads()).
  • rate_based_choker opens up unchoke slots based on the upload rate achieved to peers. The more slots that are opened, the marginal upload rate required to open up another slot increases.
  • bittyrant_choker attempts to optimize download rate by finding the reciprocation rate of each peer individually and prefers peers that gives the highest return on investment. It still allocates all upload capacity, but shuffles it around to the best peers first. For this choker to be efficient, you need to set a global upload rate limit (settings_pack::upload_rate_limit). For more information about this choker, see the paper. This choker is not fully implemented nor tested.

seed_choking_algorithm controls the seeding unchoke behavior. The available options are:

  • round_robin which round-robins the peers that are unchoked when seeding. This distributes the upload bandwidht uniformly and fairly. It minimizes the ability for a peer to download everything without redistributing it.
  • fastest_upload unchokes the peers we can send to the fastest. This might be a bit more reliable in utilizing all available capacity.
  • anti_leech prioritizes peers who have just started or are just about to finish the download. The intention is to force peers in the middle of the download to trade with each other.
name type default
cache_size int 1024
cache_buffer_chunk_size int 0
cache_expiry int 300

cache_size is the disk write and read cache. It is specified in units of 16 KiB blocks. Buffers that are part of a peer's send or receive buffer also count against this limit. Send and receive buffers will never be denied to be allocated, but they will cause the actual cached blocks to be flushed or evicted. If this is set to -1, the cache size is automatically set to the amount of physical RAM available in the machine divided by 8. If the amount of physical RAM cannot be determined, it's set to 1024 (= 16 MiB).

Disk buffers are allocated using a pool allocator, the number of blocks that are allocated at a time when the pool needs to grow can be specified in cache_buffer_chunk_size. Lower numbers saves memory at the expense of more heap allocations. If it is set to 0, the effective chunk size is proportional to the total cache size, attempting to strike a good balance between performance and memory usage. It defaults to 0. cache_expiry is the number of seconds from the last cached write to a piece in the write cache, to when it's forcefully flushed to disk. Default is 60 second.

On 32 bit builds, the effective cache size will be limited to 3/4 of 2 GiB to avoid exceeding the virtual address space limit.

name type default
disk_io_write_mode int settings_pack::enable_os_cache
disk_io_read_mode int settings_pack::enable_os_cache

determines how files are opened when they're in read only mode versus read and write mode. The options are:

enable_os_cache
This is the default and files are opened normally, with the OS caching reads and writes.
disable_os_cache
This opens all files in no-cache mode. This corresponds to the OS not letting blocks for the files linger in the cache. This makes sense in order to avoid the bittorrent client to potentially evict all other processes' cache by simply handling high throughput and large files. If libtorrent's read cache is disabled, enabling this may reduce performance.

One reason to disable caching is that it may help the operating system from growing its file cache indefinitely.

name type default
outgoing_port int 0
num_outgoing_ports int 0

this is the first port to use for binding outgoing connections to. This is useful for users that have routers that allow QoS settings based on local port. when binding outgoing connections to specific ports, num_outgoing_ports is the size of the range. It should be more than a few

Warning

setting outgoing ports will limit the ability to keep multiple connections to the same client, even for different torrents. It is not recommended to change this setting. Its main purpose is to use as an escape hatch for cheap routers with QoS capability but can only classify flows based on port numbers.

It is a range instead of a single port because of the problems with failing to reconnect to peers if a previous socket to that peer and port is in TIME_WAIT state.

name type default
peer_tos int 0x20

peer_tos determines the TOS byte set in the IP header of every packet sent to peers (including web seeds). The default value for this is 0x0 (no marking). One potentially useful TOS mark is 0x20, this represents the QBone scavenger service. For more details, see QBSS.

name type default
active_downloads int 3
active_seeds int 5
active_checking int 1
active_dht_limit int 88
active_tracker_limit int 1600
active_lsd_limit int 60
active_limit int 15
active_loaded_limit int 100

for auto managed torrents, these are the limits they are subject to. If there are too many torrents some of the auto managed ones will be paused until some slots free up. active_downloads and active_seeds controls how many active seeding and downloading torrents the queuing mechanism allows. The target number of active torrents is min(active_downloads + active_seeds, active_limit). active_downloads and active_seeds are upper limits on the number of downloading torrents and seeding torrents respectively. Setting the value to -1 means unlimited. For example if there are 10 seeding torrents and 10 downloading torrents, and active_downloads is 4 and active_seeds is 4, there will be 4 seeds active and 4 downloading torrents. If the settings are active_downloads = 2 and active_seeds = 4, then there will be 2 downloading torrents and 4 seeding torrents active. Torrents that are not auto managed are not counted against these limits.

active_checking is the limit of number of simultaneous checking torrents.

active_limit is a hard limit on the number of active (auto managed) torrents. This limit also applies to slow torrents.

active_dht_limit is the max number of torrents to announce to the DHT. By default this is set to 88, which is no more than one DHT announce every 10 seconds.

active_tracker_limit is the max number of torrents to announce to their trackers. By default this is 360, which is no more than one announce every 5 seconds.

active_lsd_limit is the max number of torrents to announce to the local network over the local service discovery protocol. By default this is 80, which is no more than one announce every 5 seconds (assuming the default announce interval of 5 minutes).

You can have more torrents active, even though they are not announced to the DHT, lsd or their tracker. If some peer knows about you for any reason and tries to connect, it will still be accepted, unless the torrent is paused, which means it won't accept any connections.

active_loaded_limit is the number of torrents that are allowed to be loaded at any given time. Note that a torrent can be active even though it's not loaded. If an unloaded torrents finds a peer that wants to access it, the torrent will be loaded on demand, using a user-supplied callback function. If the feature of unloading torrents is not enabled, this setting have no effect. If this limit is set to 0, it means unlimited. For more information, see dynamic loading of torrent files.

name type default
auto_manage_interval int 30

auto_manage_interval is the number of seconds between the torrent queue is updated, and rotated.

name type default
seed_time_limit int 24 * 60 * 60

this is the limit on the time a torrent has been an active seed (specified in seconds) before it is considered having met the seed limit criteria. See queuing.

name type default
auto_scrape_interval int 1800
auto_scrape_min_interval int 300

auto_scrape_interval is the number of seconds between scrapes of queued torrents (auto managed and paused torrents). Auto managed torrents that are paused, are scraped regularly in order to keep track of their downloader/seed ratio. This ratio is used to determine which torrents to seed and which to pause.

auto_scrape_min_interval is the minimum number of seconds between any automatic scrape (regardless of torrent). In case there are a large number of paused auto managed torrents, this puts a limit on how often a scrape request is sent.

name type default
max_peerlist_size int 3000
max_paused_peerlist_size int 1000

max_peerlist_size is the maximum number of peers in the list of known peers. These peers are not necessarily connected, so this number should be much greater than the maximum number of connected peers. Peers are evicted from the cache when the list grows passed 90% of this limit, and once the size hits the limit, peers are no longer added to the list. If this limit is set to 0, there is no limit on how many peers we'll keep in the peer list.

max_paused_peerlist_size is the max peer list size used for torrents that are paused. This default to the same as max_peerlist_size, but can be used to save memory for paused torrents, since it's not as important for them to keep a large peer list.

name type default
min_announce_interval int 5 * 60

this is the minimum allowed announce interval for a tracker. This is specified in seconds and is used as a sanity check on what is returned from a tracker. It mitigates hammering misconfigured trackers.

name type default
auto_manage_startup int 60

this is the number of seconds a torrent is considered active after it was started, regardless of upload and download speed. This is so that newly started torrents are not considered inactive until they have a fair chance to start downloading.

name type default
seeding_piece_quota int 20

seeding_piece_quota is the number of pieces to send to a peer, when seeding, before rotating in another peer to the unchoke set. It defaults to 3 pieces, which means that when seeding, any peer we've sent more than this number of pieces to will be unchoked in favour of a choked peer.

name type default
max_rejects int 50

TODO: deprecate this max_rejects is the number of piece requests we will reject in a row while a peer is choked before the peer is considered abusive and is disconnected.

name type default
recv_socket_buffer_size int 0
send_socket_buffer_size int 0

recv_socket_buffer_size and send_socket_buffer_size specifies the buffer sizes set on peer sockets. 0 (which is the default) means the OS default (i.e. don't change the buffer sizes). The socket buffer sizes are changed using setsockopt() with SOL_SOCKET/SO_RCVBUF and SO_SNDBUFFER.

name type default
read_cache_line_size int 32
write_cache_line_size int 16

read_cache_line_size is the number of blocks to read into the read cache when a read cache miss occurs. Setting this to 0 is essentially the same thing as disabling read cache. The number of blocks read into the read cache is always capped by the piece boundary.

When a piece in the write cache has write_cache_line_size contiguous blocks in it, they will be flushed. Setting this to 1 effectively disables the write cache.

name type default
optimistic_disk_retry int 10 * 60

optimistic_disk_retry is the number of seconds from a disk write errors occur on a torrent until libtorrent will take it out of the upload mode, to test if the error condition has been fixed.

libtorrent will only do this automatically for auto managed torrents.

You can explicitly take a torrent out of upload only mode using set_upload_mode().

name type default
max_suggest_pieces int 10

max_suggest_pieces is the max number of suggested piece indices received from a peer that's remembered. If a peer floods suggest messages, this limit prevents libtorrent from using too much RAM. It defaults to 10.

name type default
local_service_announce_interval int 5 * 60

local_service_announce_interval is the time between local network announces for a torrent. By default, when local service discovery is enabled a torrent announces itself every 5 minutes. This interval is specified in seconds.

name type default
dht_announce_interval int 15 * 60

dht_announce_interval is the number of seconds between announcing torrents to the distributed hash table (DHT).

name type default
udp_tracker_token_expiry int 60

udp_tracker_token_expiry is the number of seconds libtorrent will keep UDP tracker connection tokens around for. This is specified to be 60 seconds, and defaults to that. The higher this value is, the fewer packets have to be sent to the UDP tracker. In order for higher values to work, the tracker needs to be configured to match the expiration time for tokens.

name type default
default_cache_min_age int 1

default_cache_min_age is the minimum number of seconds any read cache line is kept in the cache. This defaults to one second but may be greater if guided_read_cache is enabled. Having a lower bound on the time a cache line stays in the cache is an attempt to avoid swapping the same pieces in and out of the cache in case there is a shortage of spare cache space.

name type default
num_optimistic_unchoke_slots int 0

num_optimistic_unchoke_slots is the number of optimistic unchoke slots to use. It defaults to 0, which means automatic. Having a higher number of optimistic unchoke slots mean you will find the good peers faster but with the trade-off to use up more bandwidth. When this is set to 0, libtorrent opens up 20% of your allowed upload slots as optimistic unchoke slots.

name type default
default_est_reciprocation_rate int 16000
increase_est_reciprocation_rate int 20
decrease_est_reciprocation_rate int 3

default_est_reciprocation_rate is the assumed reciprocation rate from peers when using the BitTyrant choker. This defaults to 14 kiB/s. If set too high, you will over-estimate your peers and be more altruistic while finding the true reciprocation rate, if it's set too low, you'll be too stingy and waste finding the true reciprocation rate.

increase_est_reciprocation_rate specifies how many percent the estimated reciprocation rate should be increased by each unchoke interval a peer is still choking us back. This defaults to 20%. This only applies to the BitTyrant choker.

decrease_est_reciprocation_rate specifies how many percent the estimated reciprocation rate should be decreased by each unchoke interval a peer unchokes us. This default to 3%. This only applies to the BitTyrant choker.

name type default
max_pex_peers int 50

the max number of peers we accept from pex messages from a single peer. this limits the number of concurrent peers any of our peers claims to be connected to. If they claim to be connected to more than this, we'll ignore any peer that exceeds this limit

name type default
tick_interval int 500

tick_interval specifies the number of milliseconds between internal ticks. This is the frequency with which bandwidth quota is distributed to peers. It should not be more than one second (i.e. 1000 ms). Setting this to a low value (around 100) means higher resolution bandwidth quota distribution, setting it to a higher value saves CPU cycles.

name type default
share_mode_target int 3

share_mode_target specifies the target share ratio for share mode torrents. This defaults to 3, meaning we'll try to upload 3 times as much as we download. Setting this very high, will make it very conservative and you might end up not downloading anything ever (and not affecting your share ratio). It does not make any sense to set this any lower than 2. For instance, if only 3 peers need to download the rarest piece, it's impossible to download a single piece and upload it more than 3 times. If the share_mode_target is set to more than 3, nothing is downloaded.

name type default
upload_rate_limit int 0
download_rate_limit int 0

upload_rate_limit and download_rate_limit sets the session-global limits of upload and download rate limits, in bytes per second. By default peers on the local network are not rate limited.

A value of 0 means unlimited.

name type default
dht_upload_rate_limit int 4000

dht_upload_rate_limit sets the rate limit on the DHT. This is specified in bytes per second and defaults to 4000. For busy boxes with lots of torrents that requires more DHT traffic, this should be raised.

name type default
unchoke_slots_limit int 8

unchoke_slots_limit is the max number of unchoked peers in the session. The number of unchoke slots may be ignored depending on what choking_algorithm is set to.

name type default
connections_limit int 200

connections_limit sets a global limit on the number of connections opened. The number of connections is set to a hard minimum of at least two per torrent, so if you set a too low connections limit, and open too many torrents, the limit will not be met.

name type default
connections_slack int 10

connections_slack is the the number of incoming connections exceeding the connection limit to accept in order to potentially replace existing ones.

name type default
utp_target_delay int 100
utp_gain_factor int 3000
utp_min_timeout int 500
utp_syn_resends int 2
utp_fin_resends int 2
utp_num_resends int 3
utp_connect_timeout int 3000
utp_loss_multiplier int 50

utp_target_delay is the target delay for uTP sockets in milliseconds. A high value will make uTP connections more aggressive and cause longer queues in the upload bottleneck. It cannot be too low, since the noise in the measurements would cause it to send too slow. The default is 50 milliseconds. utp_gain_factor is the number of bytes the uTP congestion window can increase at the most in one RTT. This defaults to 300 bytes. If this is set too high, the congestion controller reacts too hard to noise and will not be stable, if it's set too low, it will react slow to congestion and not back off as fast. utp_min_timeout is the shortest allowed uTP socket timeout, specified in milliseconds. This defaults to 500 milliseconds. The timeout depends on the RTT of the connection, but is never smaller than this value. A connection times out when every packet in a window is lost, or when a packet is lost twice in a row (i.e. the resent packet is lost as well).

The shorter the timeout is, the faster the connection will recover from this situation, assuming the RTT is low enough. utp_syn_resends is the number of SYN packets that are sent (and timed out) before giving up and closing the socket. utp_num_resends is the number of times a packet is sent (and lossed or timed out) before giving up and closing the connection. utp_connect_timeout is the number of milliseconds of timeout for the initial SYN packet for uTP connections. For each timed out packet (in a row), the timeout is doubled. utp_loss_multiplier controls how the congestion window is changed when a packet loss is experienced. It's specified as a percentage multiplier for cwnd. By default it's set to 50 (i.e. cut in half). Do not change this value unless you know what you're doing. Never set it higher than 100.

name type default
mixed_mode_algorithm int settings_pack::peer_proportional

The mixed_mode_algorithm determines how to treat TCP connections when there are uTP connections. Since uTP is designed to yield to TCP, there's an inherent problem when using swarms that have both TCP and uTP connections. If nothing is done, uTP connections would often be starved out for bandwidth by the TCP connections. This mode is prefer_tcp. The peer_proportional mode simply looks at the current throughput and rate limits all TCP connections to their proportional share based on how many of the connections are TCP. This works best if uTP connections are not rate limited by the global rate limiter (which they aren't by default).

name type default
listen_queue_size int 5

listen_queue_size is the value passed in to listen() for the listen socket. It is the number of outstanding incoming connections to queue up while we're not actively waiting for a connection to be accepted. The default is 5 which should be sufficient for any normal client. If this is a high performance server which expects to receive a lot of connections, or used in a simulator or test, it might make sense to raise this number. It will not take affect until the listen_interfaces settings is updated.

name type default
torrent_connect_boost int 10

torrent_connect_boost is the number of peers to try to connect to immediately when the first tracker response is received for a torrent. This is a boost to given to new torrents to accelerate them starting up. The normal connect scheduler is run once every second, this allows peers to be connected immediately instead of waiting for the session tick to trigger connections.

name type default
alert_queue_size int 1000

alert_queue_size is the maximum number of alerts queued up internally. If alerts are not popped, the queue will eventually fill up to this level.

name type default
max_metadata_size int 3 * 1024 * 10240

max_metadata_size is the maximum allowed size (in bytes) to be received by the metadata extension, i.e. magnet links.

name type default
checking_mem_usage int 256

the number of blocks to keep outstanding at any given time when checking torrents. Higher numbers give faster re-checks but uses more memory. Specified in number of 16 kiB blocks

name type default
predictive_piece_announce int 0

if set to > 0, pieces will be announced to other peers before they are fully downloaded (and before they are hash checked). The intention is to gain 1.5 potential round trip times per downloaded piece. When non-zero, this indicates how many milliseconds in advance pieces should be announced, before they are expected to be completed.

name type default
aio_threads int 4
aio_max int 300

for some aio back-ends, aio_threads specifies the number of io-threads to use, and aio_max the max number of outstanding jobs.

name type default
network_threads int 0

network_threads is the number of threads to use to call async_write_some (i.e. send) on peer connection sockets. When seeding at extremely high rates, this may become a bottleneck, and setting this to 2 or more may parallelize that cost. When using SSL torrents, all encryption for outgoing traffic is done within the socket send functions, and this will help parallelizing the cost of SSL encryption as well.

name type default
ssl_listen int 0

ssl_listen sets the listen port for SSL connections. If this is set to 0, no SSL listen port is opened. Otherwise a socket is opened on this port. This setting is only taken into account when opening the regular listen port, and won't re-open the listen socket simply by changing this setting.

name type default
tracker_backoff int 250

tracker_backoff determines how aggressively to back off from retrying failing trackers. This value determines x in the following formula, determining the number of seconds to wait until the next retry:

delay = 5 + 5 * x / 100 * fails^2

This setting may be useful to make libtorrent more or less aggressive in hitting trackers.

name type default
share_ratio_limit int 200
seed_time_ratio_limit int 700

when a seeding torrent reaches either the share ratio (bytes up / bytes down) or the seed time ratio (seconds as seed / seconds as downloader) or the seed time limit (seconds as seed) it is considered done, and it will leave room for other torrents these are specified as percentages

name type default
peer_turnover int 4
peer_turnover_cutoff int 90
peer_turnover_interval int 300

peer_turnover is the percentage of peers to disconnect every turnover peer_turnover_interval (if we're at the peer limit), this is specified in percent when we are connected to more than limit * peer_turnover_cutoff peers disconnect peer_turnover fraction of the peers. It is specified in percent peer_turnover_interval is the interval (in seconds) between optimistic disconnects if the disconnects happen and how many peers are disconnected is controlled by peer_turnover and peer_turnover_cutoff

name type default
connect_seed_every_n_download int 10

this setting controls the priority of downloading torrents over seeding or finished torrents when it comes to making peer connections. Peer connections are throttled by the connection_speed and the half-open connection limit. This makes peer connections a limited resource. Torrents that still have pieces to download are prioritized by default, to avoid having many seeding torrents use most of the connection attempts and only give one peer every now and then to the downloading torrent. libtorrent will loop over the downloading torrents to connect a peer each, and every n:th connection attempt, a finished torrent is picked to be allowed to connect to a peer. This setting controls n.

name type default
max_http_recv_buffer_size int 4*1024*204

the max number of bytes to allow an HTTP response to be when announcing to trackers or downloading .torrent files via the url provided in add_torrent_params.

name type default
max_retry_port_bind int 10

if binding to a specific port fails, should the port be incremented by one and tried again? This setting specifies how many times to retry a failed port bind

name type default
alert_mask int alert::error_notification

a bitmask combining flags from alert::category_t defining which kinds of alerts to receive

name type default
out_enc_policy int settings_pack::pe_enabled
in_enc_policy int settings_pack::pe_enabled

control the settings for incoming and outgoing connections respectively. see enc_policy enum for the available options. Keep in mind that protocol encryption degrades performance in several respects:

  1. It prevents "zero copy" disk buffers being sent to peers, since each peer needs to mutate the data (i.e. encrypt it) the data must be copied per peer connection rather than sending the same buffer to multiple peers.
  2. The encryption itself requires more CPU than plain bittorrent protocol. The highest cost is the Diffie Hellman exchange on connection setup.
  3. The encryption handshake adds several round-trips to the connection setup, and delays transferring data.
name type default
allowed_enc_level int settings_pack::pe_both

determines the encryption level of the connections. This setting will adjust which encryption scheme is offered to the other peer, as well as which encryption scheme is selected by the client. See enc_level enum for options.

name type default
inactive_down_rate int 2048
inactive_up_rate int 2048

the download and upload rate limits for a torrent to be considered active by the queuing mechanism. A torrent whose download rate is less than inactive_down_rate and whose upload rate is less than inactive_up_rate for auto_manage_startup seconds, is considered inactive, and another queued torrent may be started. This logic is disabled if dont_count_slow_torrents is false.

name type default
proxy_type int settings_pack::none

proxy to use, defaults to none. see proxy_type_t.

name type default
proxy_port int 0

the port of the proxy server

name type default
i2p_port int 0

sets the i2p SAM bridge port to connect to. set the hostname with the i2p_hostname setting.

name type default
cache_size_volatile int 256

this determines the max number of volatile disk cache blocks. If the number of volatile blocks exceed this limit, other volatile blocks will start to be evicted. A disk cache block is volatile if it has low priority, and should be one of the first blocks to be evicted under pressure. For instance, blocks pulled into the cache as the result of calculating a piece hash are volatile. These blocks don't represent potential interest among peers, so the value of keeping them in the cache is limited.

name type default
urlseed_max_request_bytes int 16 * 1024 * 1024

The maximum request range of an url seed in bytes. This value defines the largest possible sequential web seed request. Default is 16 * 1024 * 1024. Lower values are possible but will be ignored if they are lower then piece size. This value should be related to your download speed to prevent libtorrent from creating too many expensive http requests per second. You can select a value as high as you want but keep in mind that libtorrent can't create parallel requests if the first request did already select the whole file. If you combine bittorrent seeds with web seeds and pick strategies like rarest first you may find your web seed requests split into smaller parts because we don't download already picked pieces twice.

name type default
web_seed_name_lookup_retry int 1800

time to wait until a new retry of a web seed name lookup

struct settings_pack
{
   void set_int (int name, int val);
   void set_str (int name, std::string val);
   void set_bool (int name, bool val);
   bool has_val (int name) const;
   void clear ();
   void clear (int name);
   bool get_bool (int name) const;
   int get_int (int name) const;
   std::string get_str (int name) const;

   enum type_bases
   {
      string_type_base,
      int_type_base,
      bool_type_base,
      type_mask,
      index_mask,
   };

   enum string_types
   {
      user_agent,
      announce_ip,
      deprecated12,
      handshake_client_version,
      outgoing_interfaces,
      listen_interfaces,
      proxy_hostname,
      proxy_username,
      proxy_password,
      i2p_hostname,
      peer_fingerprint,
      dht_bootstrap_nodes,
      max_string_setting_internal,
   };

   enum bool_types
   {
      allow_multiple_connections_per_ip,
      deprecated1,
      send_redundant_have,
      lazy_bitfields,
      use_dht_as_fallback,
      upnp_ignore_nonrouters,
      use_parole_mode,
      use_read_cache,
      deprecated7,
      deprecated10,
      deprecated13,
      coalesce_reads,
      coalesce_writes,
      auto_manage_prefer_seeds,
      dont_count_slow_torrents,
      close_redundant_connections,
      prioritize_partial_pieces,
      rate_limit_ip_overhead,
      announce_to_all_tiers,
      announce_to_all_trackers,
      prefer_udp_trackers,
      strict_super_seeding,
      deprecated8,
      disable_hash_checks,
      allow_i2p_mixed,
      low_prio_disk,
      volatile_read_cache,
      guided_read_cache,
      no_atime_storage,
      incoming_starts_queued_torrents,
      report_true_downloaded,
      strict_end_game_mode,
      broadcast_lsd,
      enable_outgoing_utp,
      enable_incoming_utp,
      enable_outgoing_tcp,
      enable_incoming_tcp,
      ignore_resume_timestamps,
      no_recheck_incomplete_resume,
      anonymous_mode,
      report_web_seed_downloads,
      deprecated2,
      announce_double_nat,
      seeding_outgoing_connections,
      no_connect_privileged_ports,
      smooth_connects,
      always_send_user_agent,
      apply_ip_filter_to_trackers,
      use_disk_read_ahead,
      lock_files,
      contiguous_recv_buffer,
      ban_web_seeds,
      allow_partial_disk_writes,
      force_proxy,
      support_share_mode,
      support_merkle_torrents,
      report_redundant_bytes,
      listen_system_port_fallback,
      use_disk_cache_pool,
      announce_crypto_support,
      enable_upnp,
      enable_natpmp,
      enable_lsd,
      enable_dht,
      prefer_rc4,
      proxy_hostnames,
      proxy_peer_connections,
      auto_sequential,
      proxy_tracker_connections,
      max_bool_setting_internal,
   };

   enum int_types
   {
      tracker_completion_timeout,
      tracker_receive_timeout,
      stop_tracker_timeout,
      tracker_maximum_response_length,
      piece_timeout,
      request_timeout,
      request_queue_time,
      max_allowed_in_request_queue,
      max_out_request_queue,
      whole_pieces_threshold,
      peer_timeout,
      urlseed_timeout,
      urlseed_pipeline_size,
      urlseed_wait_retry,
      file_pool_size,
      max_failcount,
      min_reconnect_time,
      peer_connect_timeout,
      connection_speed,
      inactivity_timeout,
      unchoke_interval,
      optimistic_unchoke_interval,
      num_want,
      initial_picker_threshold,
      allowed_fast_set_size,
      suggest_mode,
      max_queued_disk_bytes,
      handshake_timeout,
      send_buffer_low_watermark,
      send_buffer_watermark,
      send_buffer_watermark_factor,
      choking_algorithm,
      seed_choking_algorithm,
      cache_size,
      cache_buffer_chunk_size,
      cache_expiry,
      deprecated11,
      disk_io_write_mode,
      disk_io_read_mode,
      outgoing_port,
      num_outgoing_ports,
      peer_tos,
      active_downloads,
      active_seeds,
      active_checking,
      active_dht_limit,
      active_tracker_limit,
      active_lsd_limit,
      active_limit,
      active_loaded_limit,
      auto_manage_interval,
      seed_time_limit,
      auto_scrape_interval,
      auto_scrape_min_interval,
      max_peerlist_size,
      max_paused_peerlist_size,
      min_announce_interval,
      auto_manage_startup,
      seeding_piece_quota,
      max_rejects,
      recv_socket_buffer_size,
      send_socket_buffer_size,
      deprecated14,
      read_cache_line_size,
      write_cache_line_size,
      optimistic_disk_retry,
      max_suggest_pieces,
      local_service_announce_interval,
      dht_announce_interval,
      udp_tracker_token_expiry,
      default_cache_min_age,
      num_optimistic_unchoke_slots,
      default_est_reciprocation_rate,
      increase_est_reciprocation_rate,
      decrease_est_reciprocation_rate,
      max_pex_peers,
      tick_interval,
      share_mode_target,
      upload_rate_limit,
      download_rate_limit,
      deprecated3,
      deprecated4,
      dht_upload_rate_limit,
      unchoke_slots_limit,
      deprecated5,
      connections_limit,
      connections_slack,
      utp_target_delay,
      utp_gain_factor,
      utp_min_timeout,
      utp_syn_resends,
      utp_fin_resends,
      utp_num_resends,
      utp_connect_timeout,
      deprecated6,
      utp_loss_multiplier,
      mixed_mode_algorithm,
      listen_queue_size,
      torrent_connect_boost,
      alert_queue_size,
      max_metadata_size,
      deprecated9,
      checking_mem_usage,
      predictive_piece_announce,
      aio_threads,
      aio_max,
      network_threads,
      ssl_listen,
      tracker_backoff,
      share_ratio_limit,
      seed_time_ratio_limit,
      peer_turnover,
      peer_turnover_cutoff,
      peer_turnover_interval,
      connect_seed_every_n_download,
      max_http_recv_buffer_size,
      max_retry_port_bind,
      alert_mask,
      out_enc_policy,
      in_enc_policy,
      allowed_enc_level,
      inactive_down_rate,
      inactive_up_rate,
      proxy_type,
      proxy_port,
      i2p_port,
      cache_size_volatile,
      urlseed_max_request_bytes,
      web_seed_name_lookup_retry,
      max_int_setting_internal,
   };

   enum settings_counts_t
   {
      num_string_settings,
      num_bool_settings,
      num_int_settings,
   };

   enum suggest_mode_t
   {
      no_piece_suggestions,
      suggest_read_cache,
   };

   enum choking_algorithm_t
   {
      fixed_slots_choker,
      rate_based_choker,
      bittyrant_choker,
   };

   enum seed_choking_algorithm_t
   {
      round_robin,
      fastest_upload,
      anti_leech,
   };

   enum io_buffer_mode_t
   {
      enable_os_cache,
      deprecated,
      disable_os_cache,
   };

   enum bandwidth_mixed_algo_t
   {
      prefer_tcp,
      peer_proportional,
   };

   enum enc_policy
   {
      pe_forced,
      pe_enabled,
      pe_disabled,
   };

   enum enc_level
   {
      pe_plaintext,
      pe_rc4,
      pe_both,
   };

   enum proxy_type_t
   {
      none,
      socks4,
      socks5,
      socks5_pw,
      http,
      http_pw,
      i2p_proxy,
   };
};

clear()

void clear ();

clear the settings pack from all settings

clear()

void clear (int name);

clear a specific setting from the pack

enum type_bases

Declared in "libtorrent/settings_pack.hpp"

name value description
string_type_base 0  
int_type_base 16384  
bool_type_base 32768  
type_mask 49152  
index_mask 16383  

enum string_types

Declared in "libtorrent/settings_pack.hpp"

name value description
user_agent   this is the client identification to the tracker. The recommended format of this string is: "ClientName/ClientVersion libtorrent/libtorrentVersion". This name will not only be used when making HTTP requests, but also when sending extended headers to peers that support that extension. It may not contain r or n
announce_ip 1 announce_ip is the ip address passed along to trackers as the &ip= parameter. If left as the default, that parameter is omitted.
deprecated12 2  
handshake_client_version 3 this is the client name and version identifier sent to peers in the handshake message. If this is an empty string, the user_agent is used instead
outgoing_interfaces 4 sets the network interface this session will use when it opens outgoing connections. By default, it binds outgoing connections to INADDR_ANY and port 0 (i.e. let the OS decide). Ths parameter must be a string containing one or more, comma separated, adapter names. Adapter names on unix systems are of the form "eth0", "eth1", "tun0", etc. When specifying multiple interfaces, they will be assigned in round-robin order. This may be useful for clients that are multi-homed. Binding an outgoing connection to a local IP does not necessarily make the connection via the associated NIC/Adapter. Setting this to an empty string will disable binding of outgoing connections.
listen_interfaces 5

a comma-separated list of IP port-pairs. These are the listen ports that will be opened for accepting incoming uTP and TCP connections. It is possible to listen on multiple IPs and multiple ports. Binding to port 0 will make the operating system pick the port. The default is "0.0.0.0:6881", which binds to all interfaces on port 6881.

If binding fails because the port is busy, the port number will be incremented by one, settings_pack::max_retry_port_bind times.

if all retry attempts fail, the socket will be bound to port 0, meaning the operating system will pick a port. This behavior can be disabled by disabling settings_pack::listen_system_port_fallback.

if binding fails, the listen_failed_alert is posted, potentially more than once. Once/if binding the listen socket(s) succeed, listen_succeeded_alert is posted.

Each port will attempt to open both a UDP and a TCP listen socket, to allow accepting uTP connections as well as TCP. If using the DHT, this will also make the DHT use the same UDP ports.

Note

The current support for opening arbitrary UDP sockets is limited. In this version of libtorrent, there will only ever be two UDP sockets, one for IPv4 and one for IPv6.

proxy_hostname 6 when using a poxy, this is the hostname where the proxy is running see proxy_type.
proxy_username 7 when using a proxy, these are the credentials (if any) to use whne connecting to it. see proxy_type
proxy_password 8  
i2p_hostname 9 sets the i2p SAM bridge to connect to. set the port with the i2p_port setting.
peer_fingerprint 10

this is the fingerprint for the client. It will be used as the prefix to the peer_id. If this is 20 bytes (or longer) it will be truncated at 20 bytes and used as the entire peer-id

There is a utility function, generate_fingerprint() that can be used to generate a standard client peer ID fingerprint prefix.

dht_bootstrap_nodes 11

This is a comma-separated list of IP port-pairs. They will be added to the DHT node (if it's enabled) as back-up nodes in case we don't know of any. This setting will contain one or more bootstrap nodes by default.

Changing these after the DHT has been started may not have any effect until the DHT is restarted.

max_string_setting_internal 12  

enum bool_types

Declared in "libtorrent/settings_pack.hpp"

name value description
allow_multiple_connections_per_ip   determines if connections from the same IP address as existing connections should be rejected or not. Multiple connections from the same IP address is not allowed by default, to prevent abusive behavior by peers. It may be useful to allow such connections in cases where simulations are run on the same machine, and all peers in a swarm has the same IP address.
deprecated1 1  
send_redundant_have 2 send_redundant_have controls if have messages will be sent to peers that already have the piece. This is typically not necessary, but it might be necessary for collecting statistics in some cases. Default is false.
lazy_bitfields 3 if this is true, outgoing bitfields will never be fuil. If the client is seed, a few bits will be set to 0, and later filled in with have messages. This is to prevent certain ISPs from stopping people from seeding.
use_dht_as_fallback 4 use_dht_as_fallback determines how the DHT is used. If this is true, the DHT will only be used for torrents where all trackers in its tracker list has failed. Either by an explicit error message or a time out. This is false by default, which means the DHT is used by default regardless of if the trackers fail or not.
upnp_ignore_nonrouters 5 upnp_ignore_nonrouters indicates whether or not the UPnP implementation should ignore any broadcast response from a device whose address is not the configured router for this machine. i.e. it's a way to not talk to other people's routers by mistake.
use_parole_mode 6 use_parole_mode specifies if parole mode should be used. Parole mode means that peers that participate in pieces that fail the hash check are put in a mode where they are only allowed to download whole pieces. If the whole piece a peer in parole mode fails the hash check, it is banned. If a peer participates in a piece that passes the hash check, it is taken out of parole mode.
use_read_cache 7 enable and disable caching of blocks read from disk. the purpose of the read cache is partly read-ahead of requests but also to avoid reading blocks back from the disk multiple times for popular pieces.
deprecated7 8  
deprecated10 9  
deprecated13 10  
coalesce_reads 11 allocate separate, contiguous, buffers for read and write calls. Only used where writev/readv cannot be used will use more RAM but may improve performance
coalesce_writes 12  
auto_manage_prefer_seeds 13 prefer seeding torrents when determining which torrents to give active slots to, the default is false which gives preference to downloading torrents
dont_count_slow_torrents 14 if dont_count_slow_torrents is true, torrents without any payload transfers are not subject to the active_seeds and active_downloads limits. This is intended to make it more likely to utilize all available bandwidth, and avoid having torrents that don't transfer anything block the active slots.
close_redundant_connections 15 close_redundant_connections specifies whether libtorrent should close connections where both ends have no utility in keeping the connection open. For instance if both ends have completed their downloads, there's no point in keeping it open.
prioritize_partial_pieces 16 If prioritize_partial_pieces is true, partial pieces are picked before pieces that are more rare. If false, rare pieces are always prioritized, unless the number of partial pieces is growing out of proportion.
rate_limit_ip_overhead 17 if set to true, the estimated TCP/IP overhead is drained from the rate limiters, to avoid exceeding the limits with the total traffic
announce_to_all_tiers 18

announce_to_all_trackers controls how multi tracker torrents are treated. If this is set to true, all trackers in the same tier are announced to in parallel. If all trackers in tier 0 fails, all trackers in tier 1 are announced as well. If it's set to false, the behavior is as defined by the multi tracker specification. It defaults to false, which is the same behavior previous versions of libtorrent has had as well.

announce_to_all_tiers also controls how multi tracker torrents are treated. When this is set to true, one tracker from each tier is announced to. This is the uTorrent behavior. This is false by default in order to comply with the multi-tracker specification.

announce_to_all_trackers 19  
prefer_udp_trackers 20 prefer_udp_trackers is true by default. It means that trackers may be rearranged in a way that udp trackers are always tried before http trackers for the same hostname. Setting this to false means that the trackers' tier is respected and there's no preference of one protocol over another.
strict_super_seeding 21 strict_super_seeding when this is set to true, a piece has to have been forwarded to a third peer before another one is handed out. This is the traditional definition of super seeding.
deprecated8 22  
disable_hash_checks 23 when set to true, all data downloaded from peers will be assumed to be correct, and not tested to match the hashes in the torrent this is only useful for simulation and testing purposes (typically combined with disabled_storage)
allow_i2p_mixed 24 if this is true, i2p torrents are allowed to also get peers from other sources than the tracker, and connect to regular IPs, not providing any anonymization. This may be useful if the user is not interested in the anonymization of i2p, but still wants to be able to connect to i2p peers.
low_prio_disk 25 low_prio_disk determines if the disk I/O should use a normal or low priority policy. This defaults to true, which means that it's low priority by default. Other processes doing disk I/O will normally take priority in this mode. This is meant to improve the overall responsiveness of the system while downloading in the background. For high-performance server setups, this might not be desirable.
volatile_read_cache 26 volatile_read_cache, if this is set to true, read cache blocks that are hit by peer read requests are removed from the disk cache to free up more space. This is useful if you don't expect the disk cache to create any cache hits from other peers than the one who triggered the cache line to be read into the cache in the first place.
guided_read_cache 27 guided_read_cache enables the disk cache to adjust the size of a cache line generated by peers to depend on the upload rate you are sending to that peer. The intention is to optimize the RAM usage of the cache, to read ahead further for peers that you're sending faster to.
no_atime_storage 28 no_atime_storage this is a linux-only option and passes in the O_NOATIME to open() when opening files. This may lead to some disk performance improvements.
incoming_starts_queued_torrents 29 incoming_starts_queued_torrents defaults to false. If a torrent has been paused by the auto managed feature in libtorrent, i.e. the torrent is paused and auto managed, this feature affects whether or not it is automatically started on an incoming connection. The main reason to queue torrents, is not to make them unavailable, but to save on the overhead of announcing to the trackers, the DHT and to avoid spreading one's unchoke slots too thin. If a peer managed to find us, even though we're no in the torrent anymore, this setting can make us start the torrent and serve it.
report_true_downloaded 30 when set to true, the downloaded counter sent to trackers will include the actual number of payload bytes downloaded including redundant bytes. If set to false, it will not include any redundancy bytes
strict_end_game_mode 31 strict_end_game_mode defaults to true, and controls when a block may be requested twice. If this is true, a block may only be requested twice when there's ay least one request to every piece that's left to download in the torrent. This may slow down progress on some pieces sometimes, but it may also avoid downloading a lot of redundant bytes. If this is false, libtorrent attempts to use each peer connection to its max, by always requesting something, even if it means requesting something that has been requested from another peer already.
broadcast_lsd 32 if broadcast_lsd is set to true, the local peer discovery (or Local Service Discovery) will not only use IP multicast, but also broadcast its messages. This can be useful when running on networks that don't support multicast. Since broadcast messages might be expensive and disruptive on networks, only every 8th announce uses broadcast.
enable_outgoing_utp 33 when set to true, libtorrent will try to make outgoing utp connections controls whether libtorrent will accept incoming connections or make outgoing connections of specific type.
enable_incoming_utp 34  
enable_outgoing_tcp 35  
enable_incoming_tcp 36  
ignore_resume_timestamps 37 ignore_resume_timestamps determines if the storage, when loading resume data files, should verify that the file modification time with the timestamps in the resume data. This defaults to false, which means timestamps are taken into account, and resume data is less likely to accepted (torrents are more likely to be fully checked when loaded). It might be useful to set this to true if your network is faster than your disk, and it would be faster to redownload potentially missed pieces than to go through the whole storage to look for them.
no_recheck_incomplete_resume 38 no_recheck_incomplete_resume determines if the storage should check the whole files when resume data is incomplete or missing or whether it should simply assume we don't have any of the data. By default, this is determined by the existence of any of the files. By setting this setting to true, the files won't be checked, but will go straight to download mode.
anonymous_mode 39

anonymous_mode defaults to false. When set to true, the client tries to hide its identity to a certain degree. The peer-ID will no longer include the client's fingerprint. The user-agent will be reset to an empty string. Trackers will only be used if they are using a proxy server. The listen sockets are closed, and incoming connections will only be accepted through a SOCKS5 or I2P proxy (if a peer proxy is set up and is run on the same machine as the tracker proxy). Since no incoming connections are accepted, NAT-PMP, UPnP, DHT and local peer discovery are all turned off when this setting is enabled.

If you're using I2P, it might make sense to enable anonymous mode as well.

report_web_seed_downloads 40 specifies whether downloads from web seeds is reported to the tracker or not. Defaults to on. Turning it off also excludes web seed traffic from other stats and download rate reporting via the libtorrent API.
deprecated2 41 set to true if uTP connections should be rate limited This option is DEPRECATED, please use set_peer_class_filter() instead.
announce_double_nat 42 if this is true, the &ip= argument in tracker requests (unless otherwise specified) will be set to the intermediate IP address if the user is double NATed. If the user is not double NATed, this option does not have an affect
seeding_outgoing_connections 43 seeding_outgoing_connections determines if seeding (and finished) torrents should attempt to make outgoing connections or not. By default this is true. It may be set to false in very specific applications where the cost of making outgoing connections is high, and there are no or small benefits of doing so. For instance, if no nodes are behind a firewall or a NAT, seeds don't need to make outgoing connections.
no_connect_privileged_ports 44 when this is true, libtorrent will not attempt to make outgoing connections to peers whose port is < 1024. This is a safety precaution to avoid being part of a DDoS attack
smooth_connects 45 smooth_connects is true by default, which means the number of connection attempts per second may be limited to below the connection_speed, in case we're close to bump up against the limit of number of connections. The intention of this setting is to more evenly distribute our connection attempts over time, instead of attempting to connect in batches, and timing them out in batches.
always_send_user_agent 46 always send user-agent in every web seed request. If false, only the first request per http connection will include the user agent
apply_ip_filter_to_trackers 47 apply_ip_filter_to_trackers defaults to true. It determines whether the IP filter applies to trackers as well as peers. If this is set to false, trackers are exempt from the IP filter (if there is one). If no IP filter is set, this setting is irrelevant.
use_disk_read_ahead 48 use_disk_read_ahead defaults to true and will attempt to optimize disk reads by giving the operating system heads up of disk read requests as they are queued in the disk job queue.
lock_files 49 lock_files determines whether or not to lock files which libtorrent is downloading to or seeding from. This is implemented using fcntl(F_SETLK) on unix systems and by not passing in SHARE_READ and SHARE_WRITE on windows. This might prevent 3rd party processes from corrupting the files under libtorrent's feet.
contiguous_recv_buffer 50 contiguous_recv_buffer determines whether or not libtorrent should receive data from peers into a contiguous intermediate buffer, to then copy blocks into disk buffers from, or to make many smaller calls to read(), each time passing in the specific buffer the data belongs in. When downloading at high rates, the latter may save some time copying data. When seeding at high rates, all incoming traffic consists of a very large number of tiny packets, and enabling contiguous_recv_buffer will provide higher performance. When this is enabled, it will only be used when seeding to peers, since that's when it provides performance improvements.
ban_web_seeds 51 when true, web seeds sending bad data will be banned
allow_partial_disk_writes 52 when set to false, the write_cache_line_size will apply across piece boundaries. this is a bad idea unless the piece picker also is configured to have an affinity to pick pieces belonging to the same write cache line as is configured in the disk cache.
force_proxy 53 If true, disables any communication that's not going over a proxy. Enabling this requires a proxy to be configured as well, see proxy_type and proxy_hostname settings. The listen sockets are closed, and incoming connections will only be accepted through a SOCKS5 or I2P proxy (if a peer proxy is set up and is run on the same machine as the tracker proxy). This setting also disabled peer country lookups, since those are done via DNS lookups that aren't supported by proxies.
support_share_mode 54 if false, prevents libtorrent to advertise share-mode support
support_merkle_torrents 55 if this is false, don't advertise support for the Tribler merkle tree piece message
report_redundant_bytes 56 if this is true, the number of redundant bytes is sent to the tracker
listen_system_port_fallback 57 if this is true, libtorrent will fall back to listening on a port chosen by the operating system (i.e. binding to port 0). If a failure is preferred, set this to false.
use_disk_cache_pool 58 use_disk_cache_pool enables using a pool allocator for disk cache blocks. Enabling it makes the cache perform better at high throughput. It also makes the cache less likely and slower at returning memory back to the system, once allocated.
announce_crypto_support 59 when this is true, and incoming encrypted connections are enabled, &supportcrypt=1 is included in http tracker announces
enable_upnp 60

Starts and stops the UPnP service. When started, the listen port and the DHT port are attempted to be forwarded on local UPnP router devices.

The upnp object returned by start_upnp() can be used to add and remove arbitrary port mappings. Mapping status is returned through the portmap_alert and the portmap_error_alert. The object will be valid until stop_upnp() is called. See upnp and nat pmp.

enable_natpmp 61

Starts and stops the NAT-PMP service. When started, the listen port and the DHT port are attempted to be forwarded on the router through NAT-PMP.

The natpmp object returned by start_natpmp() can be used to add and remove arbitrary port mappings. Mapping status is returned through the portmap_alert and the portmap_error_alert. The object will be valid until stop_natpmp() is called. See upnp and nat pmp.

enable_lsd 62 Starts and stops Local Service Discovery. This service will broadcast the infohashes of all the non-private torrents on the local network to look for peers on the same swarm within multicast reach.
enable_dht 63 starts the dht node and makes the trackerless service available to torrents.
prefer_rc4 64 if the allowed encryption level is both, setting this to true will prefer rc4 if both methods are offered, plaintext otherwise
proxy_hostnames 65 if true, hostname lookups are done via the configured proxy (if any). This is only supported by SOCKS5 and HTTP.
proxy_peer_connections 66 if true, peer connections are made (and accepted) over the configured proxy, if any. Web seeds as well as regular bittorrent peer connections are considered "peer connections". Anything transporting actual torrent payload (trackers and DHT traffic are not considered peer connections).
auto_sequential 67 if this setting is true, torrents with a very high availability of pieces (and seeds) are downloaded sequentially. This is more efficient for the disk I/O. With many seeds, the download order is unlikely to matter anyway
proxy_tracker_connections 68 if true, tracker connections are made over the configured proxy, if any.
max_bool_setting_internal 69  

enum int_types

Declared in "libtorrent/settings_pack.hpp"

name value description
tracker_completion_timeout   tracker_completion_timeout is the number of seconds the tracker connection will wait from when it sent the request until it considers the tracker to have timed-out. Default value is 60 seconds.
tracker_receive_timeout 1 tracker_receive_timeout is the number of seconds to wait to receive any data from the tracker. If no data is received for this number of seconds, the tracker will be considered as having timed out. If a tracker is down, this is the kind of timeout that will occur.
stop_tracker_timeout 2 the time to wait when sending a stopped message before considering a tracker to have timed out. this is usually shorter, to make the client quit faster
tracker_maximum_response_length 3 this is the maximum number of bytes in a tracker response. If a response size passes this number of bytes it will be rejected and the connection will be closed. On gzipped responses this size is measured on the uncompressed data. So, if you get 20 bytes of gzip response that'll expand to 2 megabytes, it will be interrupted before the entire response has been uncompressed (assuming the limit is lower than 2 megs).
piece_timeout 4 the number of seconds from a request is sent until it times out if no piece response is returned.
request_timeout 5 the number of seconds one block (16kB) is expected to be received within. If it's not, the block is requested from a different peer
request_queue_time 6 the length of the request queue given in the number of seconds it should take for the other end to send all the pieces. i.e. the actual number of requests depends on the download rate and this number.
max_allowed_in_request_queue 7 the number of outstanding block requests a peer is allowed to queue up in the client. If a peer sends more requests than this (before the first one has been sent) the last request will be dropped. the higher this is, the faster upload speeds the client can get to a single peer.
max_out_request_queue 8 max_out_request_queue is the maximum number of outstanding requests to send to a peer. This limit takes precedence over request_queue_time. i.e. no matter the download speed, the number of outstanding requests will never exceed this limit.
whole_pieces_threshold 9 if a whole piece can be downloaded in this number of seconds, or less, the peer_connection will prefer to request whole pieces at a time from this peer. The benefit of this is to better utilize disk caches by doing localized accesses and also to make it easier to identify bad peers if a piece fails the hash check.
peer_timeout 10 peer_timeout is the number of seconds the peer connection should wait (for any activity on the peer connection) before closing it due to time out. This defaults to 120 seconds, since that's what's specified in the protocol specification. After half the time out, a keep alive message is sent.
urlseed_timeout 11 same as peer_timeout, but only applies to url-seeds. this is usually set lower, because web servers are expected to be more reliable.
urlseed_pipeline_size 12 controls the pipelining size of url-seeds. i.e. the number of HTTP request to keep outstanding before waiting for the first one to complete. It's common for web servers to limit this to a relatively low number, like 5
urlseed_wait_retry 13 time to wait until a new retry of a web seed takes place
file_pool_size 14 sets the upper limit on the total number of files this session will keep open. The reason why files are left open at all is that some anti virus software hooks on every file close, and scans the file for viruses. deferring the closing of the files will be the difference between a usable system and a completely hogged down system. Most operating systems also has a limit on the total number of file descriptors a process may have open. It is usually a good idea to find this limit and set the number of connections and the number of files limits so their sum is slightly below it.
max_failcount 15 max_failcount is the maximum times we try to connect to a peer before stop connecting again. If a peer succeeds, the failcounter is reset. If a peer is retrieved from a peer source (other than DHT) the failcount is decremented by one, allowing another try.
min_reconnect_time 16 the number of seconds to wait to reconnect to a peer. this time is multiplied with the failcount.
peer_connect_timeout 17 peer_connect_timeout the number of seconds to wait after a connection attempt is initiated to a peer until it is considered as having timed out. This setting is especially important in case the number of half-open connections are limited, since stale half-open connection may delay the connection of other peers considerably.
connection_speed 18 connection_speed is the number of connection attempts that are made per second. If a number < 0 is specified, it will default to 200 connections per second. If 0 is specified, it means don't make outgoing connections at all.
inactivity_timeout 19 if a peer is uninteresting and uninterested for longer than this number of seconds, it will be disconnected. default is 10 minutes
unchoke_interval 20 unchoke_interval is the number of seconds between chokes/unchokes. On this interval, peers are re-evaluated for being choked/unchoked. This is defined as 30 seconds in the protocol, and it should be significantly longer than what it takes for TCP to ramp up to it's max rate.
optimistic_unchoke_interval 21 optimistic_unchoke_interval is the number of seconds between each optimistic unchoke. On this timer, the currently optimistically unchoked peer will change.
num_want 22 num_want is the number of peers we want from each tracker request. It defines what is sent as the &num_want= parameter to the tracker.
initial_picker_threshold 23 initial_picker_threshold specifies the number of pieces we need before we switch to rarest first picking. This defaults to 4, which means the 4 first pieces in any torrent are picked at random, the following pieces are picked in rarest first order.
allowed_fast_set_size 24 the number of allowed pieces to send to peers that supports the fast extensions
suggest_mode 25

suggest_mode controls whether or not libtorrent will send out suggest messages to create a bias of its peers to request certain pieces. The modes are:

  • no_piece_suggestsions which is the default and will not send out suggest messages.
  • suggest_read_cache which will send out suggest messages for the most recent pieces that are in the read cache.
max_queued_disk_bytes 26 max_queued_disk_bytes is the number maximum number of bytes, to be written to disk, that can wait in the disk I/O thread queue. This queue is only for waiting for the disk I/O thread to receive the job and either write it to disk or insert it in the write cache. When this limit is reached, the peer connections will stop reading data from their sockets, until the disk thread catches up. Setting this too low will severely limit your download rate.
handshake_timeout 27 the number of seconds to wait for a handshake response from a peer. If no response is received within this time, the peer is disconnected.
send_buffer_low_watermark 28

send_buffer_low_watermark the minimum send buffer target size (send buffer includes bytes pending being read from disk). For good and snappy seeding performance, set this fairly high, to at least fit a few blocks. This is essentially the initial window size which will determine how fast we can ramp up the send rate

if the send buffer has fewer bytes than send_buffer_watermark, we'll read another 16kB block onto it. If set too small, upload rate capacity will suffer. If set too high, memory will be wasted. The actual watermark may be lower than this in case the upload rate is low, this is the upper limit.

the current upload rate to a peer is multiplied by this factor to get the send buffer watermark. The factor is specified as a percentage. i.e. 50 -> 0.5 This product is clamped to the send_buffer_watermark setting to not exceed the max. For high speed upload, this should be set to a greater value than 100. For high capacity connections, setting this higher can improve upload performance and disk throughput. Setting it too high may waste RAM and create a bias towards read jobs over write jobs.

send_buffer_watermark 29  
send_buffer_watermark_factor 30  
choking_algorithm 31

choking_algorithm specifies which algorithm to use to determine which peers to unchoke.

The options for choking algorithms are:

  • fixed_slots_choker is the traditional choker with a fixed number of unchoke slots (as specified by session::set_max_uploads()).
  • rate_based_choker opens up unchoke slots based on the upload rate achieved to peers. The more slots that are opened, the marginal upload rate required to open up another slot increases.
  • bittyrant_choker attempts to optimize download rate by finding the reciprocation rate of each peer individually and prefers peers that gives the highest return on investment. It still allocates all upload capacity, but shuffles it around to the best peers first. For this choker to be efficient, you need to set a global upload rate limit (settings_pack::upload_rate_limit). For more information about this choker, see the paper. This choker is not fully implemented nor tested.

seed_choking_algorithm controls the seeding unchoke behavior. The available options are:

  • round_robin which round-robins the peers that are unchoked when seeding. This distributes the upload bandwidht uniformly and fairly. It minimizes the ability for a peer to download everything without redistributing it.
  • fastest_upload unchokes the peers we can send to the fastest. This might be a bit more reliable in utilizing all available capacity.
  • anti_leech prioritizes peers who have just started or are just about to finish the download. The intention is to force peers in the middle of the download to trade with each other.
seed_choking_algorithm 32  
cache_size 33

cache_size is the disk write and read cache. It is specified in units of 16 KiB blocks. Buffers that are part of a peer's send or receive buffer also count against this limit. Send and receive buffers will never be denied to be allocated, but they will cause the actual cached blocks to be flushed or evicted. If this is set to -1, the cache size is automatically set to the amount of physical RAM available in the machine divided by 8. If the amount of physical RAM cannot be determined, it's set to 1024 (= 16 MiB).

Disk buffers are allocated using a pool allocator, the number of blocks that are allocated at a time when the pool needs to grow can be specified in cache_buffer_chunk_size. Lower numbers saves memory at the expense of more heap allocations. If it is set to 0, the effective chunk size is proportional to the total cache size, attempting to strike a good balance between performance and memory usage. It defaults to 0. cache_expiry is the number of seconds from the last cached write to a piece in the write cache, to when it's forcefully flushed to disk. Default is 60 second.

On 32 bit builds, the effective cache size will be limited to 3/4 of 2 GiB to avoid exceeding the virtual address space limit.

cache_buffer_chunk_size 34  
cache_expiry 35  
deprecated11 36  
disk_io_write_mode 37

determines how files are opened when they're in read only mode versus read and write mode. The options are:

enable_os_cache
This is the default and files are opened normally, with the OS caching reads and writes.
disable_os_cache
This opens all files in no-cache mode. This corresponds to the OS not letting blocks for the files linger in the cache. This makes sense in order to avoid the bittorrent client to potentially evict all other processes' cache by simply handling high throughput and large files. If libtorrent's read cache is disabled, enabling this may reduce performance.

One reason to disable caching is that it may help the operating system from growing its file cache indefinitely.

disk_io_read_mode 38  
outgoing_port 39

this is the first port to use for binding outgoing connections to. This is useful for users that have routers that allow QoS settings based on local port. when binding outgoing connections to specific ports, num_outgoing_ports is the size of the range. It should be more than a few

Warning

setting outgoing ports will limit the ability to keep multiple connections to the same client, even for different torrents. It is not recommended to change this setting. Its main purpose is to use as an escape hatch for cheap routers with QoS capability but can only classify flows based on port numbers.

It is a range instead of a single port because of the problems with failing to reconnect to peers if a previous socket to that peer and port is in TIME_WAIT state.

num_outgoing_ports 40  
peer_tos 41 peer_tos determines the TOS byte set in the IP header of every packet sent to peers (including web seeds). The default value for this is 0x0 (no marking). One potentially useful TOS mark is 0x20, this represents the QBone scavenger service. For more details, see QBSS.
active_downloads 42

for auto managed torrents, these are the limits they are subject to. If there are too many torrents some of the auto managed ones will be paused until some slots free up. active_downloads and active_seeds controls how many active seeding and downloading torrents the queuing mechanism allows. The target number of active torrents is min(active_downloads + active_seeds, active_limit). active_downloads and active_seeds are upper limits on the number of downloading torrents and seeding torrents respectively. Setting the value to -1 means unlimited.

For example if there are 10 seeding torrents and 10 downloading torrents, and active_downloads is 4 and active_seeds is 4, there will be 4 seeds active and 4 downloading torrents. If the settings are active_downloads = 2 and active_seeds = 4, then there will be 2 downloading torrents and 4 seeding torrents active. Torrents that are not auto managed are not counted against these limits.

active_checking is the limit of number of simultaneous checking torrents.

active_limit is a hard limit on the number of active (auto managed) torrents. This limit also applies to slow torrents.

active_dht_limit is the max number of torrents to announce to the DHT. By default this is set to 88, which is no more than one DHT announce every 10 seconds.

active_tracker_limit is the max number of torrents to announce to their trackers. By default this is 360, which is no more than one announce every 5 seconds.

active_lsd_limit is the max number of torrents to announce to the local network over the local service discovery protocol. By default this is 80, which is no more than one announce every 5 seconds (assuming the default announce interval of 5 minutes).

You can have more torrents active, even though they are not announced to the DHT, lsd or their tracker. If some peer knows about you for any reason and tries to connect, it will still be accepted, unless the torrent is paused, which means it won't accept any connections.

active_loaded_limit is the number of torrents that are allowed to be loaded at any given time. Note that a torrent can be active even though it's not loaded. If an unloaded torrents finds a peer that wants to access it, the torrent will be loaded on demand, using a user-supplied callback function. If the feature of unloading torrents is not enabled, this setting have no effect. If this limit is set to 0, it means unlimited. For more information, see dynamic loading of torrent files.

active_seeds 43  
active_checking 44  
active_dht_limit 45  
active_tracker_limit 46  
active_lsd_limit 47  
active_limit 48  
active_loaded_limit 49  
auto_manage_interval 50 auto_manage_interval is the number of seconds between the torrent queue is updated, and rotated.
seed_time_limit 51 this is the limit on the time a torrent has been an active seed (specified in seconds) before it is considered having met the seed limit criteria. See queuing.
auto_scrape_interval 52

auto_scrape_interval is the number of seconds between scrapes of queued torrents (auto managed and paused torrents). Auto managed torrents that are paused, are scraped regularly in order to keep track of their downloader/seed ratio. This ratio is used to determine which torrents to seed and which to pause.

auto_scrape_min_interval is the minimum number of seconds between any automatic scrape (regardless of torrent). In case there are a large number of paused auto managed torrents, this puts a limit on how often a scrape request is sent.

auto_scrape_min_interval 53  
max_peerlist_size 54

max_peerlist_size is the maximum number of peers in the list of known peers. These peers are not necessarily connected, so this number should be much greater than the maximum number of connected peers. Peers are evicted from the cache when the list grows passed 90% of this limit, and once the size hits the limit, peers are no longer added to the list. If this limit is set to 0, there is no limit on how many peers we'll keep in the peer list.

max_paused_peerlist_size is the max peer list size used for torrents that are paused. This default to the same as max_peerlist_size, but can be used to save memory for paused torrents, since it's not as important for them to keep a large peer list.

max_paused_peerlist_size 55  
min_announce_interval 56 this is the minimum allowed announce interval for a tracker. This is specified in seconds and is used as a sanity check on what is returned from a tracker. It mitigates hammering misconfigured trackers.
auto_manage_startup 57 this is the number of seconds a torrent is considered active after it was started, regardless of upload and download speed. This is so that newly started torrents are not considered inactive until they have a fair chance to start downloading.
seeding_piece_quota 58 seeding_piece_quota is the number of pieces to send to a peer, when seeding, before rotating in another peer to the unchoke set. It defaults to 3 pieces, which means that when seeding, any peer we've sent more than this number of pieces to will be unchoked in favour of a choked peer.
max_rejects 59 TODO: deprecate this max_rejects is the number of piece requests we will reject in a row while a peer is choked before the peer is considered abusive and is disconnected.
recv_socket_buffer_size 60 recv_socket_buffer_size and send_socket_buffer_size specifies the buffer sizes set on peer sockets. 0 (which is the default) means the OS default (i.e. don't change the buffer sizes). The socket buffer sizes are changed using setsockopt() with SOL_SOCKET/SO_RCVBUF and SO_SNDBUFFER.
send_socket_buffer_size 61  
deprecated14 62  
read_cache_line_size 63

read_cache_line_size is the number of blocks to read into the read cache when a read cache miss occurs. Setting this to 0 is essentially the same thing as disabling read cache. The number of blocks read into the read cache is always capped by the piece boundary.

When a piece in the write cache has write_cache_line_size contiguous blocks in it, they will be flushed. Setting this to 1 effectively disables the write cache.

write_cache_line_size 64  
optimistic_disk_retry 65

optimistic_disk_retry is the number of seconds from a disk write errors occur on a torrent until libtorrent will take it out of the upload mode, to test if the error condition has been fixed.

libtorrent will only do this automatically for auto managed torrents.

You can explicitly take a torrent out of upload only mode using set_upload_mode().

max_suggest_pieces 66 max_suggest_pieces is the max number of suggested piece indices received from a peer that's remembered. If a peer floods suggest messages, this limit prevents libtorrent from using too much RAM. It defaults to 10.
local_service_announce_interval 67 local_service_announce_interval is the time between local network announces for a torrent. By default, when local service discovery is enabled a torrent announces itself every 5 minutes. This interval is specified in seconds.
dht_announce_interval 68 dht_announce_interval is the number of seconds between announcing torrents to the distributed hash table (DHT).
udp_tracker_token_expiry 69 udp_tracker_token_expiry is the number of seconds libtorrent will keep UDP tracker connection tokens around for. This is specified to be 60 seconds, and defaults to that. The higher this value is, the fewer packets have to be sent to the UDP tracker. In order for higher values to work, the tracker needs to be configured to match the expiration time for tokens.
default_cache_min_age 70 default_cache_min_age is the minimum number of seconds any read cache line is kept in the cache. This defaults to one second but may be greater if guided_read_cache is enabled. Having a lower bound on the time a cache line stays in the cache is an attempt to avoid swapping the same pieces in and out of the cache in case there is a shortage of spare cache space.
num_optimistic_unchoke_slots 71 num_optimistic_unchoke_slots is the number of optimistic unchoke slots to use. It defaults to 0, which means automatic. Having a higher number of optimistic unchoke slots mean you will find the good peers faster but with the trade-off to use up more bandwidth. When this is set to 0, libtorrent opens up 20% of your allowed upload slots as optimistic unchoke slots.
default_est_reciprocation_rate 72

default_est_reciprocation_rate is the assumed reciprocation rate from peers when using the BitTyrant choker. This defaults to 14 kiB/s. If set too high, you will over-estimate your peers and be more altruistic while finding the true reciprocation rate, if it's set too low, you'll be too stingy and waste finding the true reciprocation rate.

increase_est_reciprocation_rate specifies how many percent the estimated reciprocation rate should be increased by each unchoke interval a peer is still choking us back. This defaults to 20%. This only applies to the BitTyrant choker.

decrease_est_reciprocation_rate specifies how many percent the estimated reciprocation rate should be decreased by each unchoke interval a peer unchokes us. This default to 3%. This only applies to the BitTyrant choker.

increase_est_reciprocation_rate 73  
decrease_est_reciprocation_rate 74  
max_pex_peers 75 the max number of peers we accept from pex messages from a single peer. this limits the number of concurrent peers any of our peers claims to be connected to. If they claim to be connected to more than this, we'll ignore any peer that exceeds this limit
tick_interval 76 tick_interval specifies the number of milliseconds between internal ticks. This is the frequency with which bandwidth quota is distributed to peers. It should not be more than one second (i.e. 1000 ms). Setting this to a low value (around 100) means higher resolution bandwidth quota distribution, setting it to a higher value saves CPU cycles.
share_mode_target 77 share_mode_target specifies the target share ratio for share mode torrents. This defaults to 3, meaning we'll try to upload 3 times as much as we download. Setting this very high, will make it very conservative and you might end up not downloading anything ever (and not affecting your share ratio). It does not make any sense to set this any lower than 2. For instance, if only 3 peers need to download the rarest piece, it's impossible to download a single piece and upload it more than 3 times. If the share_mode_target is set to more than 3, nothing is downloaded.
upload_rate_limit 78

upload_rate_limit and download_rate_limit sets the session-global limits of upload and download rate limits, in bytes per second. By default peers on the local network are not rate limited.

A value of 0 means unlimited.

download_rate_limit 79  
deprecated3 80  
deprecated4 81  
dht_upload_rate_limit 82 dht_upload_rate_limit sets the rate limit on the DHT. This is specified in bytes per second and defaults to 4000. For busy boxes with lots of torrents that requires more DHT traffic, this should be raised.
unchoke_slots_limit 83 unchoke_slots_limit is the max number of unchoked peers in the session. The number of unchoke slots may be ignored depending on what choking_algorithm is set to.
deprecated5 84  
connections_limit 85 connections_limit sets a global limit on the number of connections opened. The number of connections is set to a hard minimum of at least two per torrent, so if you set a too low connections limit, and open too many torrents, the limit will not be met.
connections_slack 86 connections_slack is the the number of incoming connections exceeding the connection limit to accept in order to potentially replace existing ones.
utp_target_delay 87

utp_target_delay is the target delay for uTP sockets in milliseconds. A high value will make uTP connections more aggressive and cause longer queues in the upload bottleneck. It cannot be too low, since the noise in the measurements would cause it to send too slow. The default is 50 milliseconds. utp_gain_factor is the number of bytes the uTP congestion window can increase at the most in one RTT. This defaults to 300 bytes. If this is set too high, the congestion controller reacts too hard to noise and will not be stable, if it's set too low, it will react slow to congestion and not back off as fast.

utp_min_timeout is the shortest allowed uTP socket timeout, specified in milliseconds. This defaults to 500 milliseconds. The timeout depends on the RTT of the connection, but is never smaller than this value. A connection times out when every packet in a window is lost, or when a packet is lost twice in a row (i.e. the resent packet is lost as well).

The shorter the timeout is, the faster the connection will recover from this situation, assuming the RTT is low enough. utp_syn_resends is the number of SYN packets that are sent (and timed out) before giving up and closing the socket. utp_num_resends is the number of times a packet is sent (and lossed or timed out) before giving up and closing the connection. utp_connect_timeout is the number of milliseconds of timeout for the initial SYN packet for uTP connections. For each timed out packet (in a row), the timeout is doubled. utp_loss_multiplier controls how the congestion window is changed when a packet loss is experienced. It's specified as a percentage multiplier for cwnd. By default it's set to 50 (i.e. cut in half). Do not change this value unless you know what you're doing. Never set it higher than 100.

utp_gain_factor 88  
utp_min_timeout 89  
utp_syn_resends 90  
utp_fin_resends 91  
utp_num_resends 92  
utp_connect_timeout 93  
deprecated6 94  
utp_loss_multiplier 95  
mixed_mode_algorithm 96 The mixed_mode_algorithm determines how to treat TCP connections when there are uTP connections. Since uTP is designed to yield to TCP, there's an inherent problem when using swarms that have both TCP and uTP connections. If nothing is done, uTP connections would often be starved out for bandwidth by the TCP connections. This mode is prefer_tcp. The peer_proportional mode simply looks at the current throughput and rate limits all TCP connections to their proportional share based on how many of the connections are TCP. This works best if uTP connections are not rate limited by the global rate limiter (which they aren't by default).
listen_queue_size 97 listen_queue_size is the value passed in to listen() for the listen socket. It is the number of outstanding incoming connections to queue up while we're not actively waiting for a connection to be accepted. The default is 5 which should be sufficient for any normal client. If this is a high performance server which expects to receive a lot of connections, or used in a simulator or test, it might make sense to raise this number. It will not take affect until the listen_interfaces settings is updated.
torrent_connect_boost 98 torrent_connect_boost is the number of peers to try to connect to immediately when the first tracker response is received for a torrent. This is a boost to given to new torrents to accelerate them starting up. The normal connect scheduler is run once every second, this allows peers to be connected immediately instead of waiting for the session tick to trigger connections.
alert_queue_size 99 alert_queue_size is the maximum number of alerts queued up internally. If alerts are not popped, the queue will eventually fill up to this level.
max_metadata_size 100 max_metadata_size is the maximum allowed size (in bytes) to be received by the metadata extension, i.e. magnet links.
deprecated9 101  
checking_mem_usage 102 the number of blocks to keep outstanding at any given time when checking torrents. Higher numbers give faster re-checks but uses more memory. Specified in number of 16 kiB blocks
predictive_piece_announce 103 if set to > 0, pieces will be announced to other peers before they are fully downloaded (and before they are hash checked). The intention is to gain 1.5 potential round trip times per downloaded piece. When non-zero, this indicates how many milliseconds in advance pieces should be announced, before they are expected to be completed.
aio_threads 104 for some aio back-ends, aio_threads specifies the number of io-threads to use, and aio_max the max number of outstanding jobs.
aio_max 105  
network_threads 106 network_threads is the number of threads to use to call async_write_some (i.e. send) on peer connection sockets. When seeding at extremely high rates, this may become a bottleneck, and setting this to 2 or more may parallelize that cost. When using SSL torrents, all encryption for outgoing traffic is done within the socket send functions, and this will help parallelizing the cost of SSL encryption as well.
ssl_listen 107 ssl_listen sets the listen port for SSL connections. If this is set to 0, no SSL listen port is opened. Otherwise a socket is opened on this port. This setting is only taken into account when opening the regular listen port, and won't re-open the listen socket simply by changing this setting.
tracker_backoff 108

tracker_backoff determines how aggressively to back off from retrying failing trackers. This value determines x in the following formula, determining the number of seconds to wait until the next retry:

delay = 5 + 5 * x / 100 * fails^2

This setting may be useful to make libtorrent more or less aggressive in hitting trackers.

share_ratio_limit 109 when a seeding torrent reaches either the share ratio (bytes up / bytes down) or the seed time ratio (seconds as seed / seconds as downloader) or the seed time limit (seconds as seed) it is considered done, and it will leave room for other torrents these are specified as percentages
seed_time_ratio_limit 110  
peer_turnover 111 peer_turnover is the percentage of peers to disconnect every turnover peer_turnover_interval (if we're at the peer limit), this is specified in percent when we are connected to more than limit * peer_turnover_cutoff peers disconnect peer_turnover fraction of the peers. It is specified in percent peer_turnover_interval is the interval (in seconds) between optimistic disconnects if the disconnects happen and how many peers are disconnected is controlled by peer_turnover and peer_turnover_cutoff
peer_turnover_cutoff 112  
peer_turnover_interval 113  
connect_seed_every_n_download 114 this setting controls the priority of downloading torrents over seeding or finished torrents when it comes to making peer connections. Peer connections are throttled by the connection_speed and the half-open connection limit. This makes peer connections a limited resource. Torrents that still have pieces to download are prioritized by default, to avoid having many seeding torrents use most of the connection attempts and only give one peer every now and then to the downloading torrent. libtorrent will loop over the downloading torrents to connect a peer each, and every n:th connection attempt, a finished torrent is picked to be allowed to connect to a peer. This setting controls n.
max_http_recv_buffer_size 115 the max number of bytes to allow an HTTP response to be when announcing to trackers or downloading .torrent files via the url provided in add_torrent_params.
max_retry_port_bind 116 if binding to a specific port fails, should the port be incremented by one and tried again? This setting specifies how many times to retry a failed port bind
alert_mask 117 a bitmask combining flags from alert::category_t defining which kinds of alerts to receive
out_enc_policy 118

control the settings for incoming and outgoing connections respectively. see enc_policy enum for the available options. Keep in mind that protocol encryption degrades performance in several respects:

  1. It prevents "zero copy" disk buffers being sent to peers, since each peer needs to mutate the data (i.e. encrypt it) the data must be copied per peer connection rather than sending the same buffer to multiple peers.
  2. The encryption itself requires more CPU than plain bittorrent protocol. The highest cost is the Diffie Hellman exchange on connection setup.
  3. The encryption handshake adds several round-trips to the connection setup, and delays transferring data.
in_enc_policy 119  
allowed_enc_level 120 determines the encryption level of the connections. This setting will adjust which encryption scheme is offered to the other peer, as well as which encryption scheme is selected by the client. See enc_level enum for options.
inactive_down_rate 121 the download and upload rate limits for a torrent to be considered active by the queuing mechanism. A torrent whose download rate is less than inactive_down_rate and whose upload rate is less than inactive_up_rate for auto_manage_startup seconds, is considered inactive, and another queued torrent may be started. This logic is disabled if dont_count_slow_torrents is false.
inactive_up_rate 122  
proxy_type 123 proxy to use, defaults to none. see proxy_type_t.
proxy_port 124 the port of the proxy server
i2p_port 125 sets the i2p SAM bridge port to connect to. set the hostname with the i2p_hostname setting.
cache_size_volatile 126 this determines the max number of volatile disk cache blocks. If the number of volatile blocks exceed this limit, other volatile blocks will start to be evicted. A disk cache block is volatile if it has low priority, and should be one of the first blocks to be evicted under pressure. For instance, blocks pulled into the cache as the result of calculating a piece hash are volatile. These blocks don't represent potential interest among peers, so the value of keeping them in the cache is limited.
urlseed_max_request_bytes 127 The maximum request range of an url seed in bytes. This value defines the largest possible sequential web seed request. Default is 16 * 1024 * 1024. Lower values are possible but will be ignored if they are lower then piece size. This value should be related to your download speed to prevent libtorrent from creating too many expensive http requests per second. You can select a value as high as you want but keep in mind that libtorrent can't create parallel requests if the first request did already select the whole file. If you combine bittorrent seeds with web seeds and pick strategies like rarest first you may find your web seed requests split into smaller parts because we don't download already picked pieces twice.
web_seed_name_lookup_retry 128 time to wait until a new retry of a web seed name lookup
max_int_setting_internal 129  

enum settings_counts_t

Declared in "libtorrent/settings_pack.hpp"

name value description
num_string_settings    
num_bool_settings    
num_int_settings    

enum suggest_mode_t

Declared in "libtorrent/settings_pack.hpp"

name value description
no_piece_suggestions 0  
suggest_read_cache 1  

enum choking_algorithm_t

Declared in "libtorrent/settings_pack.hpp"

name value description
fixed_slots_choker 0  
rate_based_choker 2  
bittyrant_choker 3  

enum seed_choking_algorithm_t

Declared in "libtorrent/settings_pack.hpp"

name value description
round_robin 0  
fastest_upload 1  
anti_leech 2  

enum io_buffer_mode_t

Declared in "libtorrent/settings_pack.hpp"

name value description
enable_os_cache 0  
deprecated 1  
disable_os_cache 2  

enum bandwidth_mixed_algo_t

Declared in "libtorrent/settings_pack.hpp"

name value description
prefer_tcp 0 disables the mixed mode bandwidth balancing
peer_proportional 1 does not throttle uTP, throttles TCP to the same proportion of throughput as there are TCP connections

enum enc_policy

Declared in "libtorrent/settings_pack.hpp"

name value description
pe_forced 0 Only encrypted connections are allowed. Incoming connections that are not encrypted are closed and if the encrypted outgoing connection fails, a non-encrypted retry will not be made.
pe_enabled 1 encrypted connections are enabled, but non-encrypted connections are allowed. An incoming non-encrypted connection will be accepted, and if an outgoing encrypted connection fails, a non- encrypted connection will be tried.
pe_disabled 2 only non-encrypted connections are allowed.

enum enc_level

Declared in "libtorrent/settings_pack.hpp"

name value description
pe_plaintext 1 use only plaintext encryption
pe_rc4 2 use only rc4 encryption
pe_both 3 allow both

enum proxy_type_t

Declared in "libtorrent/settings_pack.hpp"

name value description
none 0 This is the default, no proxy server is used, all other fields are ignored.
socks4 1 The server is assumed to be a SOCKS4 server that requires a username.
socks5 2 The server is assumed to be a SOCKS5 server (RFC 1928) that does not require any authentication. The username and password are ignored.
socks5_pw 3 The server is assumed to be a SOCKS5 server that supports plain text username and password authentication (RFC 1929). The username and password specified may be sent to the proxy if it requires.
http 4 The server is assumed to be an HTTP proxy. If the transport used for the connection is non-HTTP, the server is assumed to support the CONNECT method. i.e. for web seeds and HTTP trackers, a plain proxy will suffice. The proxy is assumed to not require authorization. The username and password will not be used.
http_pw 5 The server is assumed to be an HTTP proxy that requires user authorization. The username and password will be sent to the proxy.
i2p_proxy 6 route through a i2p SAM proxy

min_memory_usage() high_performance_seed()

Declared in "libtorrent/session.hpp"

void min_memory_usage (settings_pack& set);
void high_performance_seed (settings_pack& set);

The default values of the session settings are set for a regular bittorrent client running on a desktop system. There are functions that can set the session settings to pre set settings for other environments. These can be used for the basis, and should be tweaked to fit your needs better.

min_memory_usage returns settings that will use the minimal amount of RAM, at the potential expense of upload and download performance. It adjusts the socket buffer sizes, disables the disk cache, lowers the send buffer watermarks so that each connection only has at most one block in use at any one time. It lowers the outstanding blocks send to the disk I/O thread so that connections only have one block waiting to be flushed to disk at any given time. It lowers the max number of peers in the peer list for torrents. It performs multiple smaller reads when it hashes pieces, instead of reading it all into memory before hashing.

This configuration is inteded to be the starting point for embedded devices. It will significantly reduce memory usage.

high_performance_seed returns settings optimized for a seed box, serving many peers and that doesn't do any downloading. It has a 128 MB disk cache and has a limit of 400 files in its file pool. It support fast upload rates by allowing large send buffers.

setting_by_name() name_for_setting()

Declared in "libtorrent/settings_pack.hpp"

char const* name_for_setting (int s);
int setting_by_name (std::string const& name);

default_settings()

Declared in "libtorrent/settings_pack.hpp"

settings_pack default_settings ();

returns a settings_pack with every setting set to its default value

home

Bdecoding

bdecode_node

Declared in "libtorrent/bdecode.hpp"

Sometimes it's important to get a non-owning reference to the root node ( to be able to copy it as a reference for instance). For that, use the non_owning() member function.

There are 5 different types of nodes, see type_t.

struct bdecode_node
{
   friend int bdecode (char const* start, char const* end, bdecode_node& ret
      , error_code& ec, int* error_pos, int depth_limit
      , int token_limit);
   bdecode_node ();
   bdecode_node (bdecode_node const&);
   bdecode_node& operator= (bdecode_node const&);
   type_t type () const;
   operator bool () const;
   bdecode_node non_owning () const;
   std::pair<char const*, int> data_section () const;
   bdecode_node list_at (int i) const;
   std::string list_string_value_at (int i
      , char const* default_val = "");
   boost::int64_t list_int_value_at (int i
      , boost::int64_t default_val = 0);
   int list_size () const;
   std::string dict_find_string_value (char const* key
      , char const* default_value = "") const;
   bdecode_node dict_find_string (char const* key) const;
   int dict_size () const;
   boost::int64_t dict_find_int_value (char const* key
      , boost::int64_t default_val = 0) const;
   bdecode_node dict_find (std::string key) const;
   bdecode_node dict_find_list (char const* key) const;
   bdecode_node dict_find (char const* key) const;
   bdecode_node dict_find_dict (std::string key) const;
   bdecode_node dict_find_dict (char const* key) const;
   std::pair<std::string, bdecode_node> dict_at (int i) const;
   bdecode_node dict_find_int (char const* key) const;
   boost::int64_t int_value () const;
   int string_length () const;
   std::string string_value () const;
   char const* string_ptr () const;
   void clear ();
   void swap (bdecode_node& n);
   void reserve (int tokens);
   void switch_underlying_buffer (char const* buf);

   enum type_t
   {
      none_t,
      dict_t,
      list_t,
      string_t,
      int_t,
   };
};

bdecode_node()

bdecode_node ();

creates a default constructed node, it will have the type none_t.

bdecode_node() operator=()

bdecode_node (bdecode_node const&);
bdecode_node& operator= (bdecode_node const&);

For owning nodes, the copy will create a copy of the tree, but the underlying buffer remains the same.

type()

type_t type () const;

the type of this node. See type_t.

bool()

operator bool () const;

returns true if type() != none_t.

non_owning()

bdecode_node non_owning () const;

return a non-owning reference to this node. This is useful to refer to the root node without copying it in assignments.

data_section()

std::pair<char const*, int> data_section () const;

returns the buffer and length of the section in the original bencoded buffer where this node is defined. For a dictionary for instance, this starts with d and ends with e, and has all the content of the dictionary in between.

list_at() list_string_value_at() list_int_value_at() list_size()

bdecode_node list_at (int i) const;
std::string list_string_value_at (int i
      , char const* default_val = "");
boost::int64_t list_int_value_at (int i
      , boost::int64_t default_val = 0);
int list_size () const;

functions with the list_ prefix operate on lists. These functions are only valid if type() == list_t. list_at() returns the item in the list at index i. i may not be greater than or equal to the size of the list. size() returns the size of the list.

dict_size() dict_find_dict() dict_find_string() dict_find_int() dict_at() dict_find_list() dict_find_int_value() dict_find() dict_find_string_value()

std::string dict_find_string_value (char const* key
      , char const* default_value = "") const;
bdecode_node dict_find_string (char const* key) const;
int dict_size () const;
boost::int64_t dict_find_int_value (char const* key
      , boost::int64_t default_val = 0) const;
bdecode_node dict_find (std::string key) const;
bdecode_node dict_find_list (char const* key) const;
bdecode_node dict_find (char const* key) const;
bdecode_node dict_find_dict (std::string key) const;
bdecode_node dict_find_dict (char const* key) const;
std::pair<std::string, bdecode_node> dict_at (int i) const;
bdecode_node dict_find_int (char const* key) const;

Functions with the dict_ prefix operates on dictionaries. They are only valid if type() == dict_t. In case a key you're looking up contains a 0 byte, you cannot use the null-terminated string overloads, but have to use std::string instead. dict_find_list will return a valid bdecode_node if the key is found _and_ it is a list. Otherwise it will return a default-constructed bdecode_node.

Functions with the _value suffix return the value of the node directly, rather than the nodes. In case the node is not found, or it has a different type, a default value is returned (which can be specified).

int_value()

boost::int64_t int_value () const;

this function is only valid if type() == int_t. It returns the value of the integer.

string_ptr() string_length() string_value()

int string_length () const;
std::string string_value () const;
char const* string_ptr () const;

these functions are only valid if type() == string_t. They return the string values. Note that string_ptr() is not null-terminated. string_length() returns the number of bytes in the string.

clear()

void clear ();

resets the bdecoded_node to a default constructed state. If this is an owning node, the tree is freed and all child nodes are invalidated.

swap()

void swap (bdecode_node& n);

Swap contents.

reserve()

void reserve (int tokens);

pre-allocate memory for the specified numbers of tokens. This is useful if you know approximately how many tokens are in the file you are about to parse. Doing so will save realloc operations while parsing. You should only call this on the root node, before passing it in to bdecode().

switch_underlying_buffer()

void switch_underlying_buffer (char const* buf);

this buffer MUST be identical to the one originally parsed. This operation is only defined on owning root nodes, i.e. the one passed in to decode().

enum type_t

Declared in "libtorrent/bdecode.hpp"

name value description
none_t 0 uninitialized or default constructed. This is also used to indicate that a node was not found in some cases.
dict_t 1 a dictionary node. The dict_find_ functions are valid.
list_t 2 a list node. The list_ functions are valid.
string_t 3 a string node, the string_ functions are valid.
int_t 4 an integer node. The int_ functions are valid.

print_entry()

Declared in "libtorrent/bdecode.hpp"

std::string print_entry (bdecode_node const& e
   , bool single_line = false, int indent = 0);

print the bencoded structure in a human-readable format to a string that's returned.

bdecode()

Declared in "libtorrent/bdecode.hpp"

int bdecode (char const* start, char const* end, bdecode_node& ret
   , error_code& ec, int* error_pos = 0, int depth_limit = 100
   , int token_limit = 1000000);

This function decodes/parses bdecoded data (for example a .torrent file). The data structure is returned in the ret argument. the buffer to parse is specified by the start of the buffer as well as the end, i.e. one byte past the end. If the buffer fails to parse, the function returns a non-zero value and fills in ec with the error code. The optional argument error_pos, if set to non-null, will be set to the byte offset into the buffer where the parse failure occurred.

depth_limit specifies the max number of nested lists or dictionaries are allowed in the data structure. (This affects the stack usage of the function, be careful not to set it too high).

token_limit is the max number of tokens allowed to be parsed from the buffer. This is simply a sanity check to not have unbounded memory usage.

The resulting bdecode_node is an owning node. That means it will be holding the whole parsed tree. When iterating lists and dictionaries, those bdecode_node objects will simply have references to the root or owning bdecode_node. If the root node is destructed, all other nodes that refer to anything in that tree become invalid.

However, the underlying buffer passed in to this function (start, end) must also remain valid while the bdecoded tree is used. The parsed tree produced by this function does not copy any data out of the buffer, but simply produces references back into it.

home

ed25519

ed25519_create_seed()

Declared in "libtorrent/ed25519.hpp"

void ed25519_create_seed (unsigned char *seed);

ed25519_key_exchange() ed25519_create_keypair() ed25519_verify() ed25519_sign() ed25519_add_scalar()

Declared in "libtorrent/ed25519.hpp"

void ed25519_add_scalar (unsigned char *public_key, unsigned char *private_key, const unsigned char *scalar);
void ed25519_key_exchange (unsigned char *shared_secret, const unsigned char *public_key, const unsigned char *private_key);
void ed25519_create_keypair (unsigned char *public_key, unsigned char *private_key, const unsigned char *seed);
int ed25519_verify (const unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *private_key);
void ed25519_sign (unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *public_key, const unsigned char *private_key);