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

home

Core

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;
   std::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
{
   explicit torrent_info (bdecode_node const& torrent_file);
   explicit torrent_info (span<char const> buffer, from_span_t);
   torrent_info (char const* buffer, int size, error_code& ec);
   torrent_info (span<char const> buffer, error_code& ec, from_span_t);
   torrent_info (std::string const& filename, error_code& ec);
   torrent_info (bdecode_node const& torrent_file, error_code& ec);
   torrent_info (char const* buffer, int size);
   explicit torrent_info (sha1_hash const& info_hash);
   explicit torrent_info (std::string const& filename);
   torrent_info (torrent_info const& t);
   ~torrent_info ();
   file_storage const& files () const;
   file_storage const& orig_files () const;
   void rename_file (file_index_t 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());
   std::int64_t total_size () const;
   int num_pieces () const;
   int piece_length () const;
   piece_index_t last_piece () const;
   index_range<piece_index_t> piece_range () const;
   piece_index_t end_piece () const;
   const sha1_hash& info_hash () const;
   int num_files () const;
   std::vector<file_slice> map_block (piece_index_t const piece
      , std::int64_t offset, int size) const;
   peer_request map_file (file_index_t const file, std::int64_t offset, int size) const;
   string_view ssl_cert () const;
   bool is_valid () const;
   bool priv () const;
   bool is_i2p () const;
   int piece_size (piece_index_t index) const;
   char const* hash_for_piece_ptr (piece_index_t const index) const;
   sha1_hash hash_for_piece (piece_index_t index) const;
   bool is_loaded () const;
   std::vector<sha1_hash> const& merkle_tree () const;
   void set_merkle_tree (std::vector<sha1_hash>& h);
   const std::string& name () const;
   std::time_t creation_date () const;
   const std::string& creator () const;
   const std::string& comment () const;
   std::vector<std::pair<std::string, int>> const& nodes () const;
   void add_node (std::pair<std::string, int> const& node);
   bool parse_info_section (bdecode_node const& e, error_code& ec);
   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);
};

torrent_info()

explicit torrent_info (bdecode_node const& torrent_file);
explicit torrent_info (span<char const> buffer, from_span_t);
torrent_info (char const* buffer, int size, error_code& ec);
torrent_info (span<char const> buffer, error_code& ec, from_span_t);
torrent_info (std::string const& filename, error_code& ec);
torrent_info (bdecode_node const& torrent_file, error_code& ec);
torrent_info (char const* buffer, int size);
explicit torrent_info (sha1_hash const& info_hash);
explicit torrent_info (std::string const& filename);
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 overload that takes a span also needs an extra parameter of type from_span_t to disambiguate the std::string overload for string literals. There is an object in the libtorrent namespace of this type called from_span.

~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 (file_index_t 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 multi file 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 BEP 38 (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()

std::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.

piece_range() last_piece() end_piece()

piece_index_t last_piece () const;
index_range<piece_index_t> piece_range () const;
piece_index_t end_piece () const;

last_piece() returns the index to the last piece in the torrent and end_piece() returns the index to the one-past-end piece in the torrent piece_range() returns an implementation-defined type that can be used as the container in a range-for loop. Where the values are the indices of all pieces in the file_storage.

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() along with the file_path(), file_size()-family of functions to access files using indices.

map_block()

std::vector<file_slice> map_block (piece_index_t const piece
      , std::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 (file_index_t const file, std::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().

ssl_cert()

string_view 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 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., the client should not advertise itself on the trackerless network (the Kademlia DHT) for this torrent.

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.

piece_size()

int piece_size (piece_index_t index) const;

returns the piece size of file with index. This will be the same as piece_length(), except for the last piece, which may be shorter.

hash_for_piece_ptr() hash_for_piece()

char const* hash_for_piece_ptr (piece_index_t const index) const;
sha1_hash hash_for_piece (piece_index_t 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 0-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.

name()

const std::string& name () const;

name() returns the name of the torrent. name contains UTF-8 encoded string.

creation_date()

std::time_t creation_date () const;

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. .. posix time: http://www.opengroup.org/onlinepubs/009695399/functions/time.html

creator()

const std::string& creator () const;

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

comment()

const std::string& comment () const;

comment() returns the comment associated with the torrent. If there's no comment, it will return an empty string. comment contains UTF-8 encoded string.

nodes()

std::vector<std::pair<std::string, int>> 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);

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).

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 nullptr.

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 BEP 30.

peer_class_info

Declared in "libtorrent/peer_class.hpp"

holds settings for a peer class. Used in set_peer_class() and get_peer_class() calls.

struct peer_class_info
{
   bool ignore_unchoke_slots;
   int connection_limit_factor;
   std::string label;
   int upload_limit;
   int download_limit;
   int upload_priority;
   int download_priority;
};
ignore_unchoke_slots
ignore_unchoke_slots determines whether peers should always unchoke a peer, regardless of the choking algorithm, or if it should honor the unchoke slot limits. It's used for local peers by default. If any of the peer classes a peer belongs to has this set to true, that peer will be unchoked at all times.
connection_limit_factor
adjusts the connection limit (global and per torrent) that applies to this peer class. By default, local peers are allowed to exceed the normal connection limit for instance. This is specified as a percent factor. 100 makes the peer class apply normally to the limit. 200 means as long as there are fewer connections than twice the limit, we accept this peer. This factor applies both to the global connection limit and the per-torrent limit. Note that if not used carefully one peer class can potentially completely starve out all other over time.
label
not used by libtorrent. It's intended as a potentially user-facing identifier of this peer class.
upload_limit download_limit
transfer rates limits for the whole peer class. They are specified in bytes per second and apply to the sum of all peers that are members of this class.
upload_priority download_priority
relative priorities used by the bandwidth allocator in the rate limiter. If no rate limits are in use, the priority is not used either. Priorities start at 1 (0 is not a valid priority) and may not exceed 255.

peer_connection_handle

Declared in "libtorrent/peer_connection_handle.hpp"

struct peer_connection_handle
{
   explicit peer_connection_handle (std::weak_ptr<peer_connection> impl);
   connection_type type () const;
   void add_extension (std::shared_ptr<peer_plugin>);
   peer_plugin const* find_plugin (string_view type) const;
   bool is_seed () const;
   bool upload_only () const;
   bool has_piece (piece_index_t i) const;
   peer_id const& pid () const;
   bool is_interesting () const;
   bool is_choked () const;
   bool is_peer_interested () const;
   bool has_peer_choked () const;
   void maybe_unchoke_this_peer ();
   void choke_this_peer ();
   void get_peer_info (peer_info& p) const;
   torrent_handle associated_torrent () const;
   tcp::endpoint local_endpoint () const;
   tcp::endpoint const& remote () const;
   bool is_disconnecting () const;
   bool is_outgoing () const;
   bool is_connecting () const;
   void disconnect (error_code const& ec, operation_t op
      , disconnect_severity_t = peer_connection_interface::normal);
   bool on_local_network () const;
   bool ignore_unchoke_slots () const;
   bool failed () const;
   bool should_log (peer_log_alert::direction_t direction) const;
   void peer_log (peer_log_alert::direction_t direction
      , char const* event, char const* fmt = "", ...) const TORRENT_FORMAT(4,5);
   bool can_disconnect (error_code const& ec) const;
   bool has_metadata () const;
   bool in_handshake () const;
   void send_buffer (char const* begin, int size);
   std::time_t last_seen_complete () const;
   time_point time_of_last_unchoke () const;
   bool operator!= (peer_connection_handle const& o) const;
   bool operator< (peer_connection_handle const& o) const;
   bool operator== (peer_connection_handle const& o) const;
   std::shared_ptr<peer_connection> native_handle () const;
};

bt_peer_connection_handle

Declared in "libtorrent/peer_connection_handle.hpp"

struct bt_peer_connection_handle : 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 (std::shared_ptr<crypto_plugin> crypto);
   void switch_send_crypto (std::shared_ptr<crypto_plugin> crypto);
   std::shared_ptr<bt_peer_connection> native_handle () const;
};

session_params

Declared in "libtorrent/session.hpp"

The session_params is a parameters pack for configuring the session before it's started.

struct session_params
{
   explicit session_params (settings_pack&& sp);
   explicit session_params (settings_pack const& sp);
   session_params ();
   session_params (settings_pack&& sp
      , std::vector<std::shared_ptr<plugin>> exts);
   session_params (settings_pack const& sp
      , std::vector<std::shared_ptr<plugin>> exts);
   session_params (session_params const&) = default;
   session_params (session_params&&) = default;
   session_params& operator= (session_params const&) = default;
   session_params& operator= (session_params&&) = default;

   settings_pack settings;
   std::vector<std::shared_ptr<plugin>> extensions;
   dht::dht_settings dht_settings;
   dht::dht_state dht_state;
   dht::dht_storage_constructor_type dht_storage_constructor;
};

session_params()

explicit session_params (settings_pack&& sp);
explicit session_params (settings_pack const& sp);
session_params ();

This constructor can be used to start with the default plugins (ut_metadata, ut_pex and smart_ban). The default values in the settings is to start the default features like upnp, NAT-PMP, and dht for example.

session_params()

session_params (settings_pack&& sp
      , std::vector<std::shared_ptr<plugin>> exts);
session_params (settings_pack const& sp
      , std::vector<std::shared_ptr<plugin>> exts);

This constructor helps to configure the set of initial plugins to be added to the session before it's started.

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_handle::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 session_handle
{
   explicit session (session_params&& params);
   session ();
   explicit session (session_params const& params);
   session (session_params&& params, io_service& ios);
   session (session_params const& params, io_service& ios);
   session (settings_pack const& pack
      , session_flags_t const flags = add_default_plugins);
   session (settings_pack&& pack
      , session_flags_t const flags = add_default_plugins);
   session (session&&) = default;
   session& operator= (session&&) = default;
   session& operator= (session const&) = delete;
   session (session const&) = delete;
   session (settings_pack&& pack
      , io_service& ios
      , session_flags_t const flags = add_default_plugins);
   session (settings_pack const& pack
      , io_service& ios
      , session_flags_t const flags = add_default_plugins);
   ~session ();
   session_proxy abort ();
};

session()

explicit session (session_params&& params);
session ();
explicit session (session_params const& params);

Constructs the session objects which acts as the container of torrents. In order to avoid a race condition between starting the session and configuring it, you can pass in a session_params object. Its settings will take effect before the session starts up.

session()

session (session_params&& params, io_service& ios);
session (session_params const& params, io_service& ios);

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 (settings_pack const& pack
      , session_flags_t const flags = add_default_plugins);
session (settings_pack&& pack
      , session_flags_t const flags = add_default_plugins);

Constructs the session objects 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() operator=()

session (session&&) = default;
session& operator= (session&&) = default;

movable

session() operator=()

session& operator= (session const&) = delete;
session (session const&) = delete;

non-copyable

session()

session (settings_pack&& pack
      , io_service& ios
      , session_flags_t const flags = add_default_plugins);
session (settings_pack const& pack
      , io_service& ios
      , session_flags_t const flags = 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()
};

announce_endpoint

Declared in "libtorrent/announce_entry.hpp"

announces are sent to each tracker using every listen socket this class holds information about one listen socket for one tracker

struct announce_endpoint
{
   void reset ();
   void failed (int backoff_ratio, seconds32 retry_interval = seconds32(0));
   bool can_announce (time_point now, bool is_seed, std::uint8_t fail_limit) const;
   bool is_working () const;

   std::string message;
   error_code last_error;
   tcp::endpoint local_endpoint;
   int scrape_incomplete = -1;
   int scrape_complete = -1;
   int scrape_downloaded = -1;
   std::uint8_t fails : 7;
   bool updating : 1;
   bool start_sent : 1;
   bool complete_sent : 1;
};

reset()

void reset ();

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

failed()

void failed (int backoff_ratio, seconds32 retry_interval = seconds32(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, std::uint8_t fail_limit) 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.

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
local_endpoint
the local endpoint of the listen interface associated with this endpoint
scrape_incomplete scrape_complete
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
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.
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.

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 ();
   announce_entry (announce_entry const&);
   ~announce_entry ();
   announce_entry& operator= (announce_entry const&);
   explicit announce_entry (string_view u);
   void reset ();
   void trim ();

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

   std::string url;
   std::string trackerid;
   std::vector<announce_endpoint> endpoints;
   std::uint8_t tier = 0;
   std::uint8_t fail_limit = 0;
   std::uint8_t source:4;
   bool verified:1;
};

announce_entry() ~announce_entry() operator=()

announce_entry ();
announce_entry (announce_entry const&);
~announce_entry ();
announce_entry& operator= (announce_entry const&);
explicit announce_entry (string_view u);

constructs a tracker announce entry with u as the URL.

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.

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 programmatically via the add_tracker() 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).
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
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.

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;

   piece_index_t 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.

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
{
   piece_index_t piece_index;
   int blocks_in_piece;
   int finished;
   int writing;
   int requested;
   block_info* blocks;
};
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.

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 system_error 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 () noexcept = default;
   torrent_handle (torrent_handle const& t) = default;
   torrent_handle& operator= (torrent_handle const&) = default;
   torrent_handle (torrent_handle&& t) noexcept = default;
   torrent_handle& operator= (torrent_handle&&) noexcept = default;
   void add_piece (piece_index_t piece, char const* data, add_piece_flags_t flags = {}) const;
   void read_piece (piece_index_t piece) const;
   bool have_piece (piece_index_t piece) const;
   void get_peer_info (std::vector<peer_info>& v) const;
   torrent_status status (status_flags_t flags = status_flags_t::all()) const;
   void get_download_queue (std::vector<partial_piece_info>& queue) const;
   void clear_piece_deadlines () const;
   void reset_piece_deadline (piece_index_t index) const;
   void set_piece_deadline (piece_index_t index, int deadline, deadline_flags_t flags = {}) const;
   void file_progress (std::vector<std::int64_t>& progress, int flags = 0) const;
   std::vector<open_file_state> file_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 (
      std::function<std::shared_ptr<torrent_plugin>(torrent_handle const&, void*)> const& ext
      , void* userdata = nullptr);
   bool set_metadata (span<char const> metadata) const;
   bool is_valid () const;
   void pause (pause_flags_t flags = {}) const;
   void resume () const;
   void set_flags (torrent_flags_t flags) const;
   void set_flags (torrent_flags_t flags, torrent_flags_t mask) const;
   void unset_flags (torrent_flags_t flags) const;
   torrent_flags_t flags () const;
   void flush_cache () const;
   void force_recheck () const;
   void save_resume_data (resume_data_flags_t flags = {}) const;
   bool need_save_resume_data () const;
   queue_position_t queue_position () const;
   void queue_position_top () const;
   void queue_position_down () const;
   void queue_position_bottom () const;
   void queue_position_up () const;
   void queue_position_set (queue_position_t 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;
   std::shared_ptr<const torrent_info> torrent_file () const;
   void piece_availability (std::vector<int>& avail) const;
   download_priority_t piece_priority (piece_index_t index) const;
   void piece_priority (piece_index_t index, download_priority_t priority) const;
   void prioritize_pieces (std::vector<std::pair<piece_index_t, download_priority_t>> const& pieces) const;
   void prioritize_pieces (std::vector<download_priority_t> const& pieces) const;
   std::vector<download_priority_t> get_piece_priorities () const;
   std::vector<download_priority_t> get_file_priorities () const;
   download_priority_t file_priority (file_index_t index) const;
   void file_priority (file_index_t index, download_priority_t priority) const;
   void prioritize_files (std::vector<download_priority_t> const& files) const;
   void force_dht_announce () const;
   void force_reannounce (int seconds = 0, int tracker_index = -1, reannounce_flags_t = {}) 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 connect_peer (tcp::endpoint const& adr, peer_source_flags_t source = {}
      , pex_flags_t flags = pex_encryption | pex_utp | pex_holepunch) 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
      , move_flags_t flags = move_flags_t::always_replace_files
      ) const;
   void rename_file (file_index_t index, std::string const& new_name) 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;
   std::uint32_t id () const;
   std::shared_ptr<torrent> native_handle () const;

   enum file_progress_flags_t
   {
      piece_granularity,
   };

   static constexpr add_piece_flags_t overwrite_existing = 0_bit;
   static constexpr status_flags_t query_distributed_copies = 0_bit;
   static constexpr status_flags_t query_accurate_download_counters = 1_bit;
   static constexpr status_flags_t query_last_seen_complete = 2_bit;
   static constexpr status_flags_t query_pieces = 3_bit;
   static constexpr status_flags_t query_verified_pieces = 4_bit;
   static constexpr status_flags_t query_torrent_file = 5_bit;
   static constexpr status_flags_t query_name = 6_bit;
   static constexpr status_flags_t query_save_path = 7_bit;
   static constexpr deadline_flags_t alert_when_available = 0_bit;
   static constexpr pause_flags_t graceful_pause = 0_bit;
   static constexpr pause_flags_t clear_disk_cache = 1_bit;
   static constexpr resume_data_flags_t flush_disk_cache = 0_bit;
   static constexpr resume_data_flags_t save_info_dict = 1_bit;
   static constexpr resume_data_flags_t only_if_modified = 2_bit;
   static constexpr reannounce_flags_t ignore_min_interval = 0_bit;
};

torrent_handle()

torrent_handle () noexcept = default;

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

add_piece()

void add_piece (piece_index_t piece, char const* data, add_piece_flags_t flags = {}) 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 (piece_index_t 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 (piece_index_t 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 system_error exception. Each entry in the vector contains information about that particular peer. See peer_info.

status()

torrent_status status (status_flags_t flags = status_flags_t::all()) const;

status() will return a structure with information about the status of this torrent. If the torrent_handle is invalid, it will throw system_error 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 clear_piece_deadlines () const;
void reset_piece_deadline (piece_index_t index) const;
void set_piece_deadline (piece_index_t index, int deadline, deadline_flags_t flags = {}) 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.

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 have the same effect 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.

file_progress()

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

This function fills in the supplied vector with 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()

std::vector<open_file_state> file_status () const;

This function returns a vector with status about files that are open for this torrent. Any file that is not open 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 open_file_state

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 (
      std::function<std::shared_ptr<torrent_plugin>(torrent_handle const&, void*)> const& ext
      , void* userdata = nullptr);

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 (span<char const> metadata) 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 (pause_flags_t flags = {}) 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.

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 auto-managed first. Torrents are auto-managed by default when added to the session. For more information, see queuing.

unset_flags() set_flags() flags()

void set_flags (torrent_flags_t flags) const;
void set_flags (torrent_flags_t flags, torrent_flags_t mask) const;
void unset_flags (torrent_flags_t flags) const;
torrent_flags_t flags () const;

sets and gets the torrent state flags. See torrent_flags_t. The set_flags overload that take a mask will affect all flags part of the mask, and set their values to what the flags argument is set to. This allows clearing and setting flags in a single function call. The set_flags overload that just takes flags, sets all the specified flags and leave any other flags unchanged. unset_flags clears the specified flags, while leaving any other flags unchanged.

The seed_mode flag is special, it can only be cleared by the set_flags() function, not set.

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.

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 (resume_data_flags_t flags = {}) const;

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

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 const& h : handles)
{
        if (!h.is_valid()) continue;
        torrent_status s = h.status();
        if (!s.has_metadata || !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 == nullptr) 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 == nullptr)
                {
                        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 save_resume_data_alert is posted. It is important to make sure this alert is received and handled in order for this function to be meaningful.

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

queue_position_t queue_position () const;
void queue_position_top () const;
void queue_position_down () 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 (queue_position_t 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.

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()

std::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 nullptr). 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() get_piece_priorities()

download_priority_t piece_priority (piece_index_t index) const;
void piece_priority (piece_index_t index, download_priority_t priority) const;
void prioritize_pieces (std::vector<std::pair<piece_index_t, download_priority_t>> const& pieces) const;
void prioritize_pieces (std::vector<download_priority_t> const& pieces) const;
std::vector<download_priority_t> get_piece_priorities () 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. Magnet links 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.

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

It's possible to cancel the effect of file priorities by setting the priorities for the affected pieces. Care has to be taken when mixing usage of file- and piece priorities.

get_file_priorities() prioritize_files() file_priority()

std::vector<download_priority_t> get_file_priorities () const;
download_priority_t file_priority (file_index_t index) const;
void file_priority (file_index_t index, download_priority_t priority) const;
void prioritize_files (std::vector<download_priority_t> const& files) 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.

get_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.

Since changing file priorities may involve disk operations (of moving files in- and out of the part file), the internal accounting of file priorities happen asynchronously. i.e. setting file priorities and then immediately querying them may not yield the same priorities just set. However, the piece priorities are updated immediately.

when combining file- and piece priorities, the resume file will record both. When loading the resume data, the file priorities will be applied first, then the piece priorities.

force_reannounce() force_dht_announce()

void force_dht_announce () const;
void force_reannounce (int seconds = 0, int tracker_index = -1, reannounce_flags_t = {}) 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.

The flags argument can be used to affect the re-announce. See ignore_min_interval.

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.

Local peers are not rate limited by default. see peer classes.

connect_peer()

void connect_peer (tcp::endpoint const& adr, peer_source_flags_t source = {}
      , pex_flags_t flags = pex_encryption | pex_utp | pex_holepunch) 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 system_error. The second (optional) argument will be bitwise 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 hole punching 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
      , move_flags_t flags = move_flags_t::always_replace_files
      ) 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 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 keeps the existing file in the target directory, if there is one. The source files will still be removed in that case. Note that it won't automatically re-check files. If an incomplete torrent is moved into a directory with the complete files, pause, move, force-recheck and resume. Without the re-checking, the torrent will keep downloading and files in the new download directory will be overwritten.

Files that have been renamed to have absolute paths 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 (file_index_t 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.

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()

std::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 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.
overwrite_existing
instruct libtorrent to overwrite any data that may already have been downloaded with the data of the new piece being added.
query_distributed_copies
calculates distributed_copies, distributed_full_copies and distributed_fraction.
query_accurate_download_counters
includes partial downloaded blocks in total_done and total_wanted_done.
query_last_seen_complete
includes last_seen_complete.
query_pieces
populate the pieces field in torrent_status.
query_verified_pieces
includes verified_pieces (only applies to torrents in seed mode).
query_torrent_file
includes torrent_file, which is all the static information from the .torrent file.
query_name
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
includes save_path, the path to the directory the files of the torrent are saved to.
alert_when_available
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.
graceful_pause clear_disk_cache
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.
flush_disk_cache
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
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
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.
ignore_min_interval
by default, force-reannounce will still honor the min-interval published by the tracker. If this flag is set, it will be ignored and the tracker is announced immediately.

open_file_state

Declared in "libtorrent/disk_interface.hpp"

this contains information about a file that's currently open by the libtorrent disk I/O subsystem. It's associated with a single torrent.

struct open_file_state
{
   file_index_t file_index;
   file_open_mode_t open_mode;
   time_point last_use;
};
file_index
the index of the file this entry refers to into the file_storage file list of this torrent. This starts indexing at 0.
open_mode

open_mode is a bitmask of the file flags this file is currently opened with. These are the flags used in the file::open() function. The flags used in this bitfield are defined by the file_open_mode enum.

Note that the read/write mode is not a bitmask. The two least significant bits are used to represent the read/write mode. Those bits can be masked out using the rw_mask constant.

last_use
a (high precision) timestamp of when the file was last used.

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

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;
   time_duration next_announce = seconds (0);

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

   torrent_handle handle;
   error_code errc;
   file_index_t error_file = torrent_status::error_file_none;
   static constexpr file_index_t error_file_none{-1};
   static constexpr file_index_t error_file_ssl_ctx{-3};
   static constexpr file_index_t error_file_exception{-5};
   static constexpr file_index_t error_file_partfile{-6};
   std::string save_path;
   std::string name;
   std::weak_ptr<const torrent_info> torrent_file;
   std::string current_tracker;
   std::int64_t total_download = 0;
   std::int64_t total_upload = 0;
   std::int64_t total_payload_download = 0;
   std::int64_t total_payload_upload = 0;
   std::int64_t total_failed_bytes = 0;
   std::int64_t total_redundant_bytes = 0;
   typed_bitfield<piece_index_t> pieces;
   typed_bitfield<piece_index_t> verified_pieces;
   std::int64_t total_done = 0;
   std::int64_t total = 0;
   std::int64_t total_wanted_done = 0;
   std::int64_t total_wanted = 0;
   std::int64_t all_time_upload = 0;
   std::int64_t all_time_download = 0;
   std::time_t added_time = 0;
   std::time_t completed_time = 0;
   std::time_t last_seen_complete = 0;
   storage_mode_t storage_mode = storage_mode_sparse;
   float progress = 0.f;
   int progress_ppm = 0;
   queue_position_t queue_position{};
   int download_rate = 0;
   int upload_rate = 0;
   int download_payload_rate = 0;
   int upload_payload_rate = 0;
   int num_seeds = 0;
   int num_peers = 0;
   int num_complete = -1;
   int num_incomplete = -1;
   int list_seeds = 0;
   int list_peers = 0;
   int connect_candidates = 0;
   int num_pieces = 0;
   int distributed_full_copies = 0;
   int distributed_fraction = 0;
   float distributed_copies = 0.f;
   int block_size = 0;
   int num_uploads = 0;
   int num_connections = 0;
   int uploads_limit = 0;
   int connections_limit = 0;
   int up_bandwidth_queue = 0;
   int down_bandwidth_queue = 0;
   int seed_rank = 0;
   state_t state = checking_resume_data;
   bool need_save_resume = false;
   bool is_seeding = false;
   bool is_finished = false;
   bool has_metadata = false;
   bool has_incoming = false;
   bool moving_storage = false;
   bool announcing_to_trackers = false;
   bool announcing_to_lsd = false;
   bool announcing_to_dht = false;
   sha1_hash info_hash;
   time_point last_upload;
   time_point last_download;
   seconds active_duration;
   seconds finished_duration;
   seconds seeding_duration;
   torrent_flags_t flags{};
};

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.

seconds()

time_duration next_announce = seconds (0);

the time until the torrent will announce itself to the tracker.

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 implies the ut_metadata 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.
errc
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.
error_file_none
special values for error_file to describe which file or component encountered the error (errc). the error did not occur on a file
error_file_ssl_ctx
the error occurred setting up the SSL context
error_file_exception
there was a serious error reported in this torrent. The error code or a torrent log alert may provide more information.
error_file_partfile
the error occurred with the partfile
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.
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
the total number of bytes to download for this torrent. This may be less than the size of the torrent in case there are pad files. This number only counts bytes that will actually be requested from peers.
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(nullptr) 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 distributed_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 smaller, if the pieces are smaller.
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.
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
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.
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.
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.
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.
info_hash
the info-hash for this torrent
flags
reflects several of the torrent's flags. For more information, see torrent_handle::flags().

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
{
   char const* name;
   int value_index;
   metric_type_t type;
};

peer_info

Declared in "libtorrent/peer_info.hpp"

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

struct peer_info
{
   enum connection_type_t
   {
      standard_bittorrent,
      web_seed,
      http_seed,
   };

   std::string client;
   typed_bitfield<piece_index_t> pieces;
   std::int64_t total_download;
   std::int64_t total_upload;
   time_duration last_request;
   time_duration last_active;
   time_duration download_queue_time;
   static constexpr peer_flags_t interesting = 0_bit;
   static constexpr peer_flags_t choked = 1_bit;
   static constexpr peer_flags_t remote_interested = 2_bit;
   static constexpr peer_flags_t remote_choked = 3_bit;
   static constexpr peer_flags_t supports_extensions = 4_bit;
   static constexpr peer_flags_t local_connection = 5_bit;
   static constexpr peer_flags_t handshake = 6_bit;
   static constexpr peer_flags_t connecting = 7_bit;
   static constexpr peer_flags_t on_parole = 9_bit;
   static constexpr peer_flags_t seed = 10_bit;
   static constexpr peer_flags_t optimistic_unchoke = 11_bit;
   static constexpr peer_flags_t snubbed = 12_bit;
   static constexpr peer_flags_t upload_only = 13_bit;
   static constexpr peer_flags_t endgame_mode = 14_bit;
   static constexpr peer_flags_t holepunched = 15_bit;
   static constexpr peer_flags_t i2p_socket = 16_bit;
   static constexpr peer_flags_t utp_socket = 17_bit;
   static constexpr peer_flags_t ssl_socket = 18_bit;
   static constexpr peer_flags_t rc4_encrypted = 19_bit;
   static constexpr peer_flags_t plaintext_encrypted = 20_bit;
   peer_flags_t flags;
   static constexpr peer_source_flags_t tracker = 0_bit;
   static constexpr peer_source_flags_t dht = 1_bit;
   static constexpr peer_source_flags_t pex = 2_bit;
   static constexpr peer_source_flags_t lsd = 3_bit;
   static constexpr peer_source_flags_t resume_data = 4_bit;
   static constexpr peer_source_flags_t incoming = 5_bit;
   peer_source_flags_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 receive_buffer_watermark;
   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;
   piece_index_t downloading_piece_index;
   int downloading_block_index;
   int downloading_progress;
   int downloading_total;
   int connection_type;
   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;
   static constexpr bandwidth_state_flags_t bw_idle = 0_bit;
   static constexpr bandwidth_state_flags_t bw_limit = 1_bit;
   static constexpr bandwidth_state_flags_t bw_network = 2_bit;
   static constexpr bandwidth_state_flags_t bw_disk = 4_bit;
   bandwidth_state_flags_t read_state;
   bandwidth_state_flags_t write_state;
};

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
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
interesting
we are interested in pieces from this peer.
choked
we have choked this peer.
remote_interested
the peer is interested in us
remote_choked
the peer has choked us.
supports_extensions
means that this peer supports the extension protocol.
local_connection
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
The connection is opened, and waiting for the handshake. Until the handshake is done, the peer cannot be identified.
connecting
The connection is in a half-open state (i.e. it is being connected).
on_parole
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
This peer is a seed (it has all the pieces).
optimistic_unchoke
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
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
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
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
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
indicates that this socket is running on top of the I2P transport.
utp_socket
indicates that this socket is a uTP socket
ssl_socket
indicates that this socket is running on top of an SSL (TLS) channel
rc4_encrypted
this connection is obfuscated with RC4
plaintext_encrypted
the handshake of this connection was obfuscated with a Diffie-Hellman exchange
flags
tells you in which state the peer is in. It is set to any combination of the peer_flags_t flags above.
tracker
The peer was received from the tracker.
dht
The peer was received from the kademlia DHT.
pex
The peer was received from the peer exchange extension.
lsd
The peer was received from the local service discovery (The peer is on the local network).
resume_data
The peer was added from the fast resume data.
incoming
we received an incoming connection from this peer
source
a combination of flags describing from which sources this peer was received. A combination of the peer_source_flags_t above.
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 receive_buffer_watermark
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 busy 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.
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 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.
bw_idle
The peer is not waiting for any external events to send or receive data.
bw_limit
The peer is waiting for the rate limiter.
bw_network
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
The peer is waiting for the disk I/O thread to catch up writing buffers to disk before downloading more.
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.

session_handle

Declared in "libtorrent/session_handle.hpp"

struct session_handle
{
   session_handle ();
   session_handle (session_handle&& t) noexcept = default;
   session_handle& operator= (session_handle const&) = default;
   session_handle& operator= (session_handle&&) noexcept = default;
   session_handle (session_handle const& t) = default;
   bool is_valid () const;
   void load_state (bdecode_node const& e, save_state_flags_t flags = save_state_flags_t::all());
   void save_state (entry& e, save_state_flags_t flags = save_state_flags_t::all()) const;
   void refresh_torrent_status (std::vector<torrent_status>* ret
      , status_flags_t flags = {}) const;
   std::vector<torrent_status> get_torrent_status (
      std::function<bool(torrent_status const&)> const& pred
      , status_flags_t flags = {}) const;
   void post_torrent_updates (status_flags_t flags = status_flags_t::all());
   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&& params);
   torrent_handle add_torrent (add_torrent_params const& params);
   torrent_handle add_torrent (add_torrent_params&& params);
   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&& params, error_code& ec);
   void resume ();
   void pause ();
   bool is_paused () const;
   void get_cache_info (cache_status* ret, torrent_handle h = torrent_handle(), int flags = 0) const;
   bool is_dht_running () const;
   void set_dht_settings (dht::dht_settings const& settings);
   dht::dht_settings get_dht_settings () const;
   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 (std::array<char, 32> key
      , std::string salt = std::string());
   sha1_hash dht_put_item (entry data);
   void dht_put_item (std::array<char, 32> key
      , std::function<void(entry&, std::array<char, 64>&
      , std::int64_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, dht::announce_flags_t flags = {});
   void dht_live_nodes (sha1_hash const& nid);
   void dht_sample_infohashes (udp::endpoint const& ep, sha1_hash const& target);
   void dht_direct_request (udp::endpoint const& ep, entry const& e, void* userdata = nullptr);
   void add_extension (std::function<std::shared_ptr<torrent_plugin>(
      torrent_handle const&, void*)> ext);
   void add_extension (std::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);
   bool is_listening () const;
   unsigned short listen_port () const;
   unsigned short ssl_listen_port () const;
   ip_filter get_peer_class_filter () const;
   void set_peer_class_filter (ip_filter const& f);
   void set_peer_class_type_filter (peer_class_type_filter const& f);
   peer_class_type_filter get_peer_class_type_filter () const;
   peer_class_t create_peer_class (char const* name);
   void delete_peer_class (peer_class_t cid);
   peer_class_info get_peer_class (peer_class_t cid) const;
   void set_peer_class (peer_class_t cid, peer_class_info const& pci);
   void remove_torrent (const torrent_handle& h, remove_flags_t options = {});
   void apply_settings (settings_pack&& s);
   settings_pack get_settings () const;
   void apply_settings (settings_pack const& s);
   void pop_alerts (std::vector<alert*>* alerts);
   void set_alert_notify (std::function<void()> const& fun);
   alert* wait_for_alert (time_duration max_wait);
   void delete_port_mapping (port_mapping_t handle);
   std::vector<port_mapping_t> add_port_mapping (portmap_protocol t, int external_port, int local_port);
   void reopen_network_sockets (reopen_network_flags_t options = reopen_map_ports);
   std::shared_ptr<aux::session_impl> native_handle () const;

   static constexpr save_state_flags_t save_settings = 0_bit;
   static constexpr save_state_flags_t save_dht_settings = 1_bit;
   static constexpr save_state_flags_t save_dht_state = 2_bit;
   static constexpr peer_class_t global_peer_class_id{0};
   static constexpr peer_class_t tcp_peer_class_id{1};
   static constexpr peer_class_t local_peer_class_id{2};
   static constexpr remove_flags_t delete_files = 0_bit;
   static constexpr remove_flags_t delete_partfile = 1_bit;
   static constexpr session_flags_t add_default_plugins = 0_bit;
   constexpr static portmap_protocol udp = portmap_protocol::udp;
   constexpr static portmap_protocol tcp = portmap_protocol::tcp;
   static constexpr reopen_network_flags_t reopen_map_ports = 0_bit;
};

load_state() save_state()

void load_state (bdecode_node const& e, save_state_flags_t flags = save_state_flags_t::all());
void save_state (entry& e, save_state_flags_t flags = save_state_flags_t::all()) const;

TODO: 2 the ip filter should probably be saved here too 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).

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
      , status_flags_t flags = {}) const;
std::vector<torrent_status> get_torrent_status (
      std::function<bool(torrent_status const&)> const& pred
      , status_flags_t flags = {}) 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.

The intended use of these functions is to start off by calling get_torrent_status() to get a list of all torrents that match your criteria. Then call refresh_torrent_status() on that list. This will only refresh the status for the torrents in your list, and thus ignore all other torrents you might be running. This may save a significant amount of time, especially if the number of torrents you're interested in is small. In order to keep your list of interested torrents up to date, you can either call get_torrent_status() from time to time, to include torrents you might have become interested in since the last time. In order to stop refreshing a certain torrent, simply remove it from the list.

post_torrent_updates()

void post_torrent_updates (status_flags_t flags = status_flags_t::all());

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&& params);
torrent_handle add_torrent (add_torrent_params const& params);
torrent_handle add_torrent (add_torrent_params&& params);
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&& params, error_code& ec);

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 system_error 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.

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;
void set_dht_settings (dht::dht_settings const& settings);
dht::dht_settings get_dht_settings () const;

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 (std::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 (std::array<char, 32> key
      , std::function<void(entry&, std::array<char, 64>&
      , std::int64_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.
std::array<char,64>& signature
the signature authenticating the current value. This may be zeros 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.
std::int64_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 blob's value is 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_live_nodes()

void dht_live_nodes (sha1_hash const& nid);

Retrieve all the live DHT (identified by nid) nodes. All the nodes id and endpoint will be returned in the list of nodes in the alert dht_live_nodes_alert. Since this alert is a response to an explicit call, it will always be posted, regardless of the alert mask.

dht_sample_infohashes()

void dht_sample_infohashes (udp::endpoint const& ep, sha1_hash const& target);

Query the DHT node specified by ep to retrieve a sample of the info-hashes that the node currently have in their storage. The target is included for iterative lookups so that indexing nodes can perform a key space traversal with a single RPC per node by adjusting the target value for each RPC. It has no effect on the returned sample value. The result is posted as a dht_sample_infohashes_alert.

dht_direct_request()

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

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 (std::function<std::shared_ptr<torrent_plugin>(
      torrent_handle const&, void*)> ext);
void add_extension (std::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 std::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:

uTorrent metadata
Allows peers to download the metadata (.torrent files) from the swarm directly. Makes it possible to join a swarm with just a tracker and info-hash.
#include <libtorrent/extensions/ut_metadata.hpp>
ses.add_extension(&lt::create_ut_metadata_plugin);
uTorrent peer exchange
Exchanges peers between clients.
#include <libtorrent/extensions/ut_pex.hpp>
ses.add_extension(&lt::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(&lt::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.

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.

get_peer_class_filter() set_peer_class_filter()

ip_filter get_peer_class_filter () const;
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 = ses.get_peer_class_filter();
peer_class_t my_class = ses.create_peer_class("200.1.x.x IP range");
f.add_rule(make_address("200.1.1.0"), make_address("200.1.255.255")
        , 1 << static_cast<std::uint32_t>(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.

The get_peer_class_filter() function returns the current filter.

For more information, see peer classes.

set_peer_class_type_filter() get_peer_class_type_filter()

void set_peer_class_type_filter (peer_class_type_filter const& f);
peer_class_type_filter get_peer_class_type_filter () const;

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.

create_peer_class()

peer_class_t 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 (peer_class_t 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 (peer_class_t cid) const;
void set_peer_class (peer_class_t 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, remove_flags_t options = {});

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_handle::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 system_error exception. Once the torrent is deleted, a torrent_deleted_alert is posted.

Note that when a queued or downloading torrent is removed, its position in the download queue is vacated and every subsequent torrent in the queue has their queue positions updated. This can potentially cause a large state_update to be posted. When removing all torrents, it is advised to remove them from the back of the queue, to minimize the shifting.

get_settings() apply_settings()

void apply_settings (settings_pack&& s);
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 (std::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 nullptr.

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.

The type of an alert is returned by the polymorphic function alert::type() but can also be queries from a concrete type via T::alert_type, as a static constant.

add_port_mapping() delete_port_mapping()

void delete_port_mapping (port_mapping_t handle);
std::vector<port_mapping_t> add_port_mapping (portmap_protocol 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.

reopen_network_sockets()

void reopen_network_sockets (reopen_network_flags_t options = reopen_map_ports);

Instructs the session to reopen all listen and outgoing sockets.

It's useful in the case your platform doesn't support the built in IP notifier mechanism, or if you have a better more reliable way to detect changes in the IP routing table.

native_handle()

std::shared_ptr<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.

save_settings
saves settings (i.e. the settings_pack)
save_dht_settings
saves dht_settings
save_dht_state
saves dht state such as nodes and node-id, possibly accelerating joining the DHT if provided at next session startup.
global_peer_class_id tcp_peer_class_id local_peer_class_id
built-in peer classes
delete_files
delete the files belonging to the torrent from disk. including the part-file, if there is one
delete_partfile
delete just the part-file associated with this torrent
add_default_plugins
this will add common extensions like ut_pex, ut_metadata, lt_tex smart_ban and possibly others.
udp tcp
protocols used by add_port_mapping()
reopen_map_ports
This option indicates if the ports are mapped using natpmp and upnp. If mapping was already made, they are deleted and added again. This only works if natpmp and/or upnp are configured to be enable.

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 loaded a .torrent file into a torrent_info object
  • info_hash - when you don't have the metadata (.torrent file) but. This is set when adding a magnet link.

one of those fields must 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.

The add_torrent_params is also used when requesting resume data for a torrent. It can be saved to and restored from a file and added back to a new session. For serialization and deserialization of add_torrent_params objects, see read_resume_data() and write_resume_data().

struct add_torrent_params
{
   add_torrent_params (add_torrent_params&&) noexcept;
   add_torrent_params& operator= (add_torrent_params const&);
   explicit add_torrent_params (storage_constructor_type sc = default_storage_constructor);
   add_torrent_params& operator= (add_torrent_params&&) = default;
   add_torrent_params (add_torrent_params const&);

   int version = LIBTORRENT_VERSION_NUM;
   std::shared_ptr<torrent_info> ti;
   aux::noexcept_movable<std::vector<std::string>> trackers;
   aux::noexcept_movable<std::vector<int>> tracker_tiers;
   aux::noexcept_movable<std::vector<std::pair<std::string, int>>> dht_nodes;
   std::string name;
   std::string save_path;
   storage_mode_t storage_mode = storage_mode_sparse;
   aux::noexcept_movable<storage_constructor_type> storage;
   void* userdata = nullptr;
   aux::noexcept_movable<std::vector<download_priority_t>> file_priorities;
   std::string trackerid;
   torrent_flags_t flags = torrent_flags::default_flags;
   sha1_hash info_hash;
   int max_uploads = -1;
   int max_connections = -1;
   int upload_limit = -1;
   int download_limit = -1;
   std::int64_t total_uploaded = 0;
   std::int64_t total_downloaded = 0;
   int active_time = 0;
   int finished_time = 0;
   int seeding_time = 0;
   std::time_t added_time = 0;
   std::time_t completed_time = 0;
   std::time_t last_seen_complete = 0;
   int num_complete = -1;
   int num_incomplete = -1;
   int num_downloaded = -1;
   aux::noexcept_movable<std::vector<std::string>> http_seeds;
   aux::noexcept_movable<std::vector<std::string>> url_seeds;
   aux::noexcept_movable<std::vector<tcp::endpoint>> peers;
   aux::noexcept_movable<std::vector<tcp::endpoint>> banned_peers;
   aux::noexcept_movable<std::map<piece_index_t, bitfield>> unfinished_pieces;
   typed_bitfield<piece_index_t> have_pieces;
   typed_bitfield<piece_index_t> verified_pieces;
   aux::noexcept_movable<std::vector<download_priority_t>> piece_priorities;
   aux::noexcept_movable<std::vector<sha1_hash>> merkle_tree;
   aux::noexcept_movable<std::map<file_index_t, std::string>> renamed_files;
   std::time_t last_download = 0;
   std::time_t last_upload = 0;
};

add_torrent_params() operator=()

add_torrent_params (add_torrent_params&&) noexcept;
add_torrent_params& operator= (add_torrent_params const&);
explicit add_torrent_params (storage_constructor_type sc = default_storage_constructor);
add_torrent_params& operator= (add_torrent_params&&) = default;
add_torrent_params (add_torrent_params const&);

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.

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 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.
tracker_tiers
the tiers the URLs in trackers belong to. Trackers belonging to different tiers may be treated differently, as defined by the multi tracker extension. This is optional, if not specified trackers are assumed to be part of tier 0, or whichever the last tier was as iterating over the trackers.
dht_nodes
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

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 performs slightly better than a relative path.

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(). The file priorities specified in here take precedence over those specified in the resume data, if any.
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.
flags

flags controlling aspects of this torrent and how it's added. See torrent_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. To add a magnet link, use parse_magnet_uri() to populate fields in the add_torrent_params object.
max_uploads max_connections

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

For fine grained control over rate limits, including making them apply to local peers, see peer classes.

total_uploaded total_downloaded
the total number of bytes uploaded and downloaded by this torrent so far.
active_time finished_time seeding_time
the number of seconds this torrent has spent in started, finished and seeding state so far, respectively.
added_time completed_time
if set to a non-zero value, this is the posix time of when this torrent was first added, including previous runs/sessions. If set to zero, the internal added_time will be set to the time of when add_torrent() is called.
last_seen_complete
if set to non-zero, initializes the time (expressed in posix time) when we last saw a seed or peers that together formed a complete copy of the torrent. If left set to zero, the internal counterpart to this field will be updated when we see a seed or a distributed copies >= 1.0.
num_complete num_incomplete

these field can be used to initialize the torrent's cached scrape data. The scrape data is high level metadata about the current state of the swarm, as returned by the tracker (either when announcing to it or by sending a specific scrape request). num_complete is the number of peers in the swarm that are seeds, or have every piece in the torrent. num_incomplete is the number of peers in the swarm that do not have every piece. num_downloaded is the number of times the torrent has been downloaded (not initiated, but the number of times a download has completed).

Leaving any of these values set to -1 indicates we don't know, or we have not received any scrape data.

http_seeds url_seeds

URLs can be added to these two lists to specify additional web seeds to be used by the torrent. If the flag_override_web_seeds is set, these will be the _only_ ones to be used. i.e. any web seeds found in the .torrent file will be overridden.

http_seeds expects URLs to web servers implementing the original HTTP seed specification BEP 17.

url_seeds expects URLs to regular web servers, aka "get right" style, specified in BEP 19.

peers
peers to add to the torrent, to be tried to be connected to as bittorrent peers.
banned_peers
peers banned from this torrent. The will not be connected to
unfinished_pieces
this is a map of partially downloaded piece. The key is the piece index and the value is a bitfield where each bit represents a 16 kiB block. A set bit means we have that block.
have_pieces
this is a bitfield indicating which pieces we already have of this torrent.
verified_pieces
when in seed_mode, pieces with a set bit in this bitfield have been verified to be valid. Other pieces will be verified the first time a peer requests it.
piece_priorities
this sets the priorities for each individual piece in the torrent. Each element in the vector represent the piece with the same index. If you set both file- and piece priorities, file priorities will take precedence.
merkle_tree
if this is a merkle tree torrent, and you're seeding, this field must be set. It is all the hashes in the binary tree, with the root as the first entry. See torrent_info::set_merkle_tree() for more info.
renamed_files
this is a map of file indices in the torrent and new filenames to be applied before the torrent is added.

peer_class_type_filter

Declared in "libtorrent/peer_class_type_filter.hpp"

peer_class_type_filter is a simple container for rules for adding and subtracting peer-classes from peers. It is applied after the peer class filter is applied (which is based on the peer's IP address).

struct peer_class_type_filter
{
   peer_class_type_filter ();
   void add (socket_type_t const st, peer_class_t const peer_class);
   void remove (socket_type_t const st, peer_class_t const peer_class);
   void allow (socket_type_t const st, peer_class_t const peer_class);
   void disallow (socket_type_t const st, peer_class_t const peer_class);
   std::uint32_t apply (socket_type_t const st, std::uint32_t peer_class_mask);

   enum socket_type_t : std::uint8_t
   {
      tcp_socket,
      utp_socket,
      ssl_tcp_socket,
      ssl_utp_socket,
      i2p_socket,
      num_socket_types,
   };
};

remove() add()

void add (socket_type_t const st, peer_class_t const peer_class);
void remove (socket_type_t const st, peer_class_t const peer_class);

add() and remove() adds and removes a peer class to be added to new peers based on socket type.

disallow() allow()

void allow (socket_type_t const st, peer_class_t const peer_class);
void disallow (socket_type_t const st, peer_class_t const peer_class);

disallow() and allow() adds and removes a peer class to be removed from new peers based on socket type.

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

apply()

std::uint32_t apply (socket_type_t const st, std::uint32_t peer_class_mask);

takes a bitmask of peer classes and returns a new bitmask of peer classes after the rules have been applied, based on the socket type argument (st).

enum socket_type_t : std::uint8_t

Declared in "libtorrent/peer_class_type_filter.hpp"

name value description
tcp_socket 0 these match the socket types from socket_type.hpp shifted one down
utp_socket 1  
ssl_tcp_socket 2  
ssl_utp_socket 3  
i2p_socket 4  
num_socket_types 5  

dht_state

Declared in "libtorrent/kademlia/dht_state.hpp"

This structure helps to store and load the state of the dht_tracker. At this moment the library is only a dual stack implementation of the DHT. See BEP 32

struct dht_state
{
   void clear ();

   node_ids_t nids;
   std::vector<udp::endpoint> nodes;
   std::vector<udp::endpoint> nodes6;
};
nodes
the bootstrap nodes saved from the buckets node
nodes6
the bootstrap nodes saved from the IPv6 buckets node

dht_storage_counters

Declared in "libtorrent/kademlia/dht_storage.hpp"

This structure hold the relevant counters for the storage

struct dht_storage_counters
{
   void reset ();

   std::int32_t torrents = 0;
   std::int32_t peers = 0;
   std::int32_t immutable_data = 0;
   std::int32_t mutable_data = 0;
};

reset()

void reset ();

This member function set the counters to zero.

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(). You should know that if this storage becomes full of DHT items, the current implementation could degrade in performance.

struct dht_storage_interface
{
   virtual void update_node_ids (std::vector<node_id> const& ids) = 0;
   virtual bool get_peers (sha1_hash const& info_hash
      , bool noseed, bool scrape, address const& requester
      , entry& peers) const = 0;
   virtual void announce_peer (sha1_hash const& info_hash
      , tcp::endpoint const& endp
      , string_view 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
      , span<char const> buf
      , address const& addr) = 0;
   virtual bool get_mutable_item_seq (sha1_hash const& target
      , sequence_number& seq) const = 0;
   virtual bool get_mutable_item (sha1_hash const& target
      , sequence_number seq, bool force_fill
      , entry& item) const = 0;
   virtual void put_mutable_item (sha1_hash const& target
      , span<char const> buf
      , signature const& sig
      , sequence_number seq
      , public_key const& pk
      , span<char const> salt
      , address const& addr) = 0;
   virtual int get_infohashes_sample (entry& item) = 0;
   virtual void tick () = 0;
   virtual dht_storage_counters counters () const = 0;
   virtual ~dht_storage_interface ();
};

update_node_ids()

virtual void update_node_ids (std::vector<node_id> const& ids) = 0;

This member function notifies the list of all node's ids of each DHT running inside libtorrent. It's advisable that the concrete implementation keeps a copy of this list for an eventual prioritization when deleting an element to make room for a new one.

get_peers()

virtual bool get_peers (sha1_hash const& info_hash
      , bool noseed, bool scrape, address const& requester
      , 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 the maximum number of peers are stored for this info_hash.

announce_peer()

virtual void announce_peer (sha1_hash const& info_hash
      , tcp::endpoint const& endp
      , string_view 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
      , span<char const> buf
      , 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
      , sequence_number& 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
      , sequence_number 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
      , span<char const> buf
      , signature const& sig
      , sequence_number seq
      , public_key const& pk
      , span<char const> salt
      , 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.

get_infohashes_sample()

virtual int get_infohashes_sample (entry& item) = 0;

This function retrieves a sample info-hashes

For implementers: The info-hashes should be stored in ["samples"] (N × 20 bytes). the following keys should be filled item["interval"] - the subset refresh interval in seconds. item["num"] - number of info-hashes in storage.

Internally, this function is allowed to lazily evaluate, cache and modify the actual sample to put in item

returns the number of info-hashes in the sample.

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.

dht_settings

Declared in "libtorrent/kademlia/dht_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
{
   int max_peers_reply = 100;
   int search_branching = 5;
   int max_fail_count = 20;
   int max_torrents = 2000;
   int max_dht_items = 700;
   int max_peers = 500;
   int max_torrent_search_reply = 20;
   bool restrict_routing_ips = true;
   bool restrict_search_ips = true;
   bool extended_routing_table = true;
   bool aggressive_lookups = true;
   bool privacy_lookups = false;
   bool enforce_node_id = false;
   bool ignore_dark_internet = true;
   int block_timeout = 5 * 60;
   int block_ratelimit = 5;
   bool read_only = false;
   int item_lifetime = 0;
   int upload_rate_limit = 8000;
   int sample_infohashes_interval = 21600;
   int max_infohashes_sample_count = 20;
};
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.
upload_rate_limit
the number of bytes per second (on average) the DHT is allowed to send. If the incoming requests causes to many bytes to be sent in responses, incoming requests will be dropped until the quota has been replenished.
sample_infohashes_interval
the info-hashes sample recomputation interval (in seconds). The node will precompute a subset of the tracked info-hashes and return that instead of calculating it upon each request. The permissible range is between 0 and 21600 seconds (inclusive).
max_infohashes_sample_count
the maximum number of elements in the sampled subset of info-hashes. If this number is too big, expect the DHT storage implementations to clamp it in order to allow UDP packets go through

crypt_acquire_provider()

Declared in "libtorrent/win_crypto_provider.hpp"

inline HCRYPTPROV crypt_acquire_provider (DWORD provider_type);

crypt_gen_random()

Declared in "libtorrent/win_crypto_provider.hpp"

inline void crypt_gen_random (span<char> buffer);

write_string()

Declared in "libtorrent/io.hpp"

inline int write_string (std::string const& str, char*& start);

read_session_params()

Declared in "libtorrent/session.hpp"

session_params read_session_params (bdecode_node const& e
   , save_state_flags_t flags = save_state_flags_t::all());

This function helps to construct a session_params from a bencoded data generated by session_handle::save_state

hash_value()

Declared in "libtorrent/torrent_handle.hpp"

std::size_t hash_value (torrent_handle const& h);

for std::hash (and to support using this type in unordered_map etc.)

host_to_network()

Declared in "libtorrent/byteswap.hpp"

inline std::uint32_t host_to_network (std::uint32_t x);

these need to be within the disabled warnings because on OSX the htonl and ntohl macros cause lots of old-style case warnings

network_to_host()

Declared in "libtorrent/byteswap.hpp"

inline std::uint32_t network_to_host (std::uint32_t x);

host_to_network()

Declared in "libtorrent/byteswap.hpp"

inline std::uint16_t host_to_network (std::uint16_t x);

network_to_host()

Declared in "libtorrent/byteswap.hpp"

inline std::uint16_t network_to_host (std::uint16_t x);

version()

Declared in "libtorrent/version.hpp"

char const* version ();

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

read_resume_data()

Declared in "libtorrent/read_resume_data.hpp"

add_torrent_params read_resume_data (span<char const> buffer);
add_torrent_params read_resume_data (bdecode_node const& rd
   , error_code& ec);
add_torrent_params read_resume_data (bdecode_node const& rd);
add_torrent_params read_resume_data (span<char const> buffer
   , error_code& ec);

these functions are used to parse resume data and populate the appropriate fields in an add_torrent_params object. This object can then be used to add the actual torrent_info object to and pass to session::add_torrent() or session::async_add_torrent().

If the client wants to override any field that was loaded from the resume data, e.g. save_path, those fields must be changed after loading resume data but before adding the torrent.

write_resume_data_buf() write_resume_data()

Declared in "libtorrent/write_resume_data.hpp"

entry write_resume_data (add_torrent_params const& atp);
std::vector<char> write_resume_data_buf (add_torrent_params const& atp);

this function turns the resume data in an add_torrent_params object into a bencoded structure

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.

openssl_set_tlsext_hostname()

Declared in "libtorrent/openssl.hpp"

inline void openssl_set_tlsext_hostname (SSL* s, char const* name);

openssl_set_tlsext_servername_callback()

Declared in "libtorrent/openssl.hpp"

inline void openssl_set_tlsext_servername_callback (SSL_CTX* ctx
   , int (*servername_callback)(SSL*, int*, void*));

openssl_set_tlsext_servername_arg()

Declared in "libtorrent/openssl.hpp"

inline void openssl_set_tlsext_servername_arg (SSL_CTX* ctx, void* userdata);

openssl_num_general_names()

Declared in "libtorrent/openssl.hpp"

inline int openssl_num_general_names (GENERAL_NAMES* gens);

openssl_general_name_value()

Declared in "libtorrent/openssl.hpp"

inline GENERAL_NAME* openssl_general_name_value (GENERAL_NAMES* gens, int i);

alignof()

Declared in "libtorrent/aligned_storage.hpp"

template <std::size_t Len, std::size_t Align = alignof (void*)>;

this is for backwards compatibility with not-quite C++11 compilers

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 (string_view 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.

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 (string_view uri, add_torrent_params& p, error_code& ec);
add_torrent_params parse_magnet_uri (string_view uri);
add_torrent_params parse_magnet_uri (string_view uri, error_code& ec);

This function parses out information from the magnet link and populates the add_torrent_params object. The overload that does not take an error_code reference will throw a system_error on error The overload taking an add_torrent_params reference will fill in the fields specified in the magnet URI.

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.

calculate_pad_bytes()

Declared in "libtorrent/heterogeneous_queue.hpp"

inline std::size_t calculate_pad_bytes (char const* inptr, std::size_t alignment);

create_packet()

Declared in "libtorrent/packet_pool.hpp"

inline packet_ptr create_packet (int const size);

dht_default_storage_constructor()

Declared in "libtorrent/kademlia/dht_storage.hpp"

std::unique_ptr<dht_storage_interface> dht_default_storage_constructor (
   dht_settings const& settings);

sign_mutable_item()

Declared in "libtorrent/kademlia/item.hpp"

signature sign_mutable_item (
   span<char const> v
   , span<char const> salt
   , sequence_number seq
   , public_key const& pk
   , secret_key const& sk);

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.

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.

enum artificial_jobs

Declared in "libtorrent/block_cache.hpp"

name value description
flushing    
flush_expired 1  
try_flush_write_blocks 2  
try_flush_write_blocks2 3  
flush_range 4  
clear_outstanding_jobs 5  
set_outstanding_jobs 6  
last_job 7  

enum kind_t

Declared in "libtorrent/disk_io_thread.hpp"

name value description
read_cache 0  
write_cache 1  
volatile_read_cache 2  

enum pcp_errors

Declared in "libtorrent/natpmp.hpp"

name value description
pcp_success 0  
pcp_unsupp_version 1  
pcp_not_authorized 2  
pcp_malformed_request 3  
pcp_unsupp_opcode 4  
pcp_unsupp_option 5  
pcp_malformed_option 6  
pcp_network_failure 7  
pcp_no_resources 8  
pcp_unsupp_protocol 9  
pcp_user_ex_quota 10  
pcp_cannot_provide_external 11  
pcp_address_mismatch 12  
pcp_excessive_remote_peers 13  

enum class transport : std::uint8_t

Declared in "libtorrent/session_udp_sockets.hpp"

name value description
plaintext 0  
ssl 1