libtorrent API Documentation
| Author: | Arvid Norberg, arvid@rasterbar.com |
|---|---|
| Version: | 0.14.4 |
Table of contents
- overview
- network primitives
- session
- session()
- ~session()
- pause() resume() is_paused()
- abort()
- add_torrent()
- remove_torrent()
- find_torrent() get_torrents()
- set_upload_rate_limit() set_download_rate_limit() upload_rate_limit() download_rate_limit()
- set_max_uploads() set_max_connections()
- num_uploads() num_connections()
- set_max_half_open_connections() max_half_open_connections()
- load_asnum_db() load_country_db() int as_for_ip()
- load_state() state()
- set_ip_filter()
- status()
- get_cache_status()
- get_cache_info()
- is_listening() listen_port() listen_on()
- pop_alert() set_alert_mask() wait_for_alert() set_alert_queue_size_limit()
- add_extension()
- set_settings() set_pe_settings()
- set_peer_proxy() set_web_seed_proxy() set_tracker_proxy() set_dht_proxy()
- peer_proxy() web_seed_proxy() tracker_proxy() dht_proxy()
- start_dht() stop_dht() set_dht_settings() dht_state()
- add_dht_node() add_dht_router()
- start_lsd() stop_lsd()
- start_upnp() stop_upnp()
- start_natpmp() stop_natpmp()
- entry
- torrent_info
- torrent_info()
- add_tracker()
- files() orig_files()
- rename_file()
- begin_files() end_files() rbegin_files() rend_files()
- num_files() file_at()
- map_block()
- map_file()
- url_seeds() add_url_seed()
- trackers()
- total_size() piece_length() piece_size() num_pieces()
- hash_for_piece() hash_for_piece_ptr() info_hash()
- name() comment() creation_date() creator()
- priv()
- nodes()
- add_node()
- metadata() metadata_size()
- torrent_handle
- piece_priority() prioritize_pieces() piece_priorities()
- file_priority() prioritize_files() file_priorities()
- file_progress()
- save_path()
- move_storage()
- rename_file()
- get_storage_impl()
- force_reannounce()
- scrape_tracker()
- connect_peer()
- name()
- set_ratio()
- set_upload_limit() set_download_limit() upload_limit() download_limit()
- set_sequential_download() is_sequential_download()
- set_peer_upload_limit() set_peer_download_limit()
- pause() resume() is_paused()
- force_recheck()
- clear_error()
- resolve_countries()
- is_seed()
- is_auto_managed() auto_managed()
- has_metadata()
- set_tracker_login()
- trackers() replace_trackers()
- add_url_seed() remove_url_seed() url_seeds()
- queue_position() queue_position_up() queue_position_down() queue_position_top() queue_position_bottom()
- use_interface()
- info_hash()
- set_max_uploads() set_max_connections()
- save_resume_data()
- status()
- get_download_queue()
- get_peer_info()
- get_torrent_info()
- is_valid()
- torrent_status
- peer_info
- session_settings
- pe_settings
- proxy_settings
- ip_filter
- big_number
- bitfield
- hasher
- fingerprint
- UPnP and NAT-PMP
- free functions
- alerts
- external_ip_alert
- listen_failed_alert
- portmap_error_alert
- portmap_alert
- file_error_alert
- file_renamed_alert
- file_rename_failed_alert
- tracker_announce_alert
- tracker_error_alert
- tracker_reply_alert
- dht_reply_alert
- tracker_warning_alert
- scrape_reply_alert
- scrape_failed_alert
- url_seed_alert
- hash_failed_alert
- peer_ban_alert
- peer_error_alert
- invalid_request_alert
- torrent_finished_alert
- performance_alert
- metadata_failed_alert
- metadata_received_alert
- fastresume_rejected_alert
- peer_blocked_alert
- storage_moved_alert
- storage_moved_failed_alert
- torrent_paused_alert
- torrent_resumed_alert
- save_resume_data_alert
- save_resume_data_failed_alert
- dispatcher
- exceptions
- storage_interface
- magnet links
- queuing
- fast resume
- threads
- storage allocation
- extensions
- filename checks
- acknowledgments
overview
The interface of libtorrent consists of a few classes. The main class is the session, it contains the main loop that serves all torrents.
The basic usage is as follows:
construct a session
start extensions (see add_extension()).
start DHT, LSD, UPnP, NAT-PMP etc (see start_dht() stop_dht() set_dht_settings() dht_state() start_lsd() stop_lsd(), start_upnp() stop_upnp() and start_natpmp() stop_natpmp())
parse .torrent-files and add them to the session (see bdecode() bencode() and add_torrent())
main loop (see session)
- query the torrent_handles for progress (see torrent_handle)
- query the session for information
- add and remove torrents from the session at run-time
save resume data for all torrent_handles (optional, see save_resume_data())
destruct session object
Each class and function is described in this manual.
For a description on how to create torrent files, see make_torrent.
network primitives
There are a few typedefs in the libtorrent namespace which pulls in network types from the asio namespace. These are:
typedef asio::ip::address address; typedef asio::ip::address_v4 address_v4; typedef asio::ip::address_v6 address_v6; using asio::ip::tcp; using asio::ip::udp;
These are declared in the <libtorrent/socket.hpp> header.
The using statements will give easy access to:
tcp::endpoint udp::endpoint
Which are the endpoint types used in libtorrent. An endpoint is an address with an associated port.
For documentation on these types, please refer to the asio documentation.
session
The session class has the following synopsis:
class session: public boost::noncopyable
{
session(fingerprint const& print
= libtorrent::fingerprint(
"LT", 0, 1, 0, 0)
, int flags = start_default_features | add_default_plugins);
session(
fingerprint const& print
, std::pair<int, int> listen_port_range
, char const* listen_interface = 0
, int flags = start_default_features | add_default_plugins);
torrent_handle add_torrent(add_torrent_params const& params);
void pause();
void resume();
bool is_paused() const;
session_proxy abort();
enum options_t
{
none = 0,
delete_files = 1
};
enum session_flags_t
{
add_default_plugins = 1,
start_default_features = 2
};
void remove_torrent(torrent_handle const& h, int options = none);
torrent_handle find_torrent(sha_hash const& ih);
std::vector<torrent_handle> get_torrents() const;
void set_settings(session_settings const& settings);
void set_pe_settings(pe_settings const& settings);
void set_upload_rate_limit(int bytes_per_second);
int upload_rate_limit() const;
void set_download_rate_limit(int bytes_per_second);
int download_rate_limit() const;
void set_max_uploads(int limit);
void set_max_connections(int limit);
void set_max_half_open_connections(int limit);
int max_half_open_connections() const;
void set_peer_proxy(proxy_settings const& s);
void set_web_seed_proxy(proxy_settings const& s);
void set_tracker_proxy(proxy_settings const& s);
proxy_settings const& peer_proxy() const;
proxy_settings const& web_seed_proxy() const;
proxy_settings const& tracker_proxy() const;
int num_uploads() const;
int num_connections() const;
bool load_asnum_db(char const* file);
bool load_country_db(char const* file);
int as_for_ip(address const& adr);
void load_state(entry const& ses_state);
entry state() const;
void set_ip_filter(ip_filter const& f);
session_status status() const;
cache_status get_cache_status() const;
bool is_listening() const;
unsigned short listen_port() const;
bool listen_on(
std::pair<int, int> const& port_range
, char const* interface = 0);
std::auto_ptr<alert> pop_alert();
alert const* wait_for_alert(time_duration max_wait);
void set_alert_mask(int m);
size_t set_alert_queue_size_limit(size_t queue_size_limit_);
void add_extension(boost::function<
boost::shared_ptr<torrent_plugin>(torrent*)> ext);
void start_dht();
void stop_dht();
void set_dht_settings(
dht_settings const& settings);
entry dht_state() const;
void add_dht_node(std::pair<std::string
, int> const& node);
void add_dht_router(std::pair<std::string
, int> const& node);
void start_lsd();
void stop_lsd();
upnp* start_upnp();
void stop_upnp();
natpmp* start_natpmp();
void stop_natpmp();
};
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.
session()
session(fingerprint const& print
= libtorrent::fingerprint("LT", 0, 1, 0, 0)
, int flags = start_default_features | add_default_plugins);
session(fingerprint const& print
, std::pair<int, int> listen_port_range
, char const* listen_interface = 0
, int flags = start_default_features | add_default_plugins);
If the fingerprint in the first overload is omited, the client will get a default fingerprint stating the version of libtorrent. The fingerprint is a short string that will be used in the peer-id to identify the client and the client's version. For more details see the fingerprint class. The constructor that only takes a fingerprint will not open a listen port for the session, to get it running you'll have to call session::listen_on(). The other constructor, that takes a port range and an interface as well as the fingerprint will automatically try to listen on a port on the given interface. For more information about the parameters, see listen_on() function.
The flags paramater 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 things. If you do not want them to start, pass 0 as the flags parameter.
~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 set_settings().
pause() resume() is_paused()
void pause(); void resume(); 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.
abort()
session_proxy abort();
In case you want to destruct the session asynchrounously, 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()
};
add_torrent()
typedef storage_interface* (&storage_constructor_type)(
file_storage const&, file_storage const*, fs::path const&, file_pool&);
struct add_torrent_params
{
add_torrent_params(storage_constructor_type s);
boost::intrusive_ptr<torrent_info> ti;
char const* tracker_url;
sha1_hash info_hash;
char const* name;
fs::path save_path;
std::vector<char>* resume_data;
storage_mode_t storage_mode;
bool paused;
bool auto_managed;
bool duplicate_is_error;
storage_constructor_type storage;
void* userdata;
};
torrent_handle add_torrent(add_torrent_params const& params);
You add torrents through the add_torrent() function where you give an object with all the parameters.
The only mandatory parameter is save_path which is the directory where you want the files to be saved. You also need to specify either the ti (the torrent file) or info_hash (the info hash of the torrent). If you 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 0 in case no name should be assigned to the torrent. In case it's not 0, the name is used for the torrent as long as it doesn't have metadata. See torrent_handle::name.
If the torrent doesn't have a tracker, but relies on the DHT to find peers, the tracker_url can be 0, otherwise you might specify a tracker url that tracks this 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 duplicate_torrent 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.
The optional parameter, resume_data can be given if up to date fast-resume data is available. The fast-resume data can be acquired from a running torrent by calling save_resume_data() on torrent_handle. See fast resume. The vector that is passed in will be swapped into the running torrent instance with std::vector::swap().
The storage_mode parameter refers to the layout of the storage for this torrent. There are 3 different modes:
- storage_mode_sparse
- All pieces will be written to the place where they belong and sparse files will be used. This is the recommended, and default mode.
- storage_mode_allocate
- Same as storage_mode_sparse except that files will be ftruncated on startup (SetEndOfFile() on windows). For filesystem that supports sparse files, this is in all practical aspects identical to sparse mode. For filesystems that don't, it will allocate the data for the files. The mac filesystem HFS+ doesn't support sparse files, it will allocate the files with zeroes.
- storage_mode_compact
- The storage will grow as more pieces are downloaded, and pieces are rearranged to finally be in their correct places once the entire torrent has been downloaded.
For more information, see storage allocation.
paused is a boolean that specifies whether or not the torrent is to be started in a paused state. I.e. it won't connect to the tracker or any of the peers until it's resumed. This is typically a good way of avoiding race conditions when setting configuration options on torrents before starting them.
If you pass in resume data, the paused state of the torrent when the resume data was saved will override the paused state you pass in here.
If auto_managed is true, this torrent will be queued, started and seeded automatically by libtorrent. When this is set, the torrent should also be started as paused. The default queue order is the order the torrents were added. They are all downloaded in that order. For more details, see queuing.
If you pass in resume data, the auto_managed state of the torrent when the resume data was saved will override the auto_managed state you pass in here.
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.
The userdata parameter is optional and will be passed on to the extension constructor functions, if any (see add_extension()).
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.
remove_torrent()
void remove_torrent(torrent_handle const& h, int options = none);
remove_torrent() will close all peer connections associated with the torrent and tell the tracker that we've stopped participating in the swarm. The optional second argument options can be used to delete all the files downloaded by this torrent. To do this, pass in the value session::delete_files. The removal of the torrent is asyncronous, there is no guarantee that adding the same torrent immediately after it was removed will not throw a duplicate_torrent exception.
find_torrent() get_torrents()
torrent_handle find_torrent(sha_hash const& ih); 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.
set_upload_rate_limit() set_download_rate_limit() upload_rate_limit() download_rate_limit()
void set_upload_rate_limit(int bytes_per_second); void set_download_rate_limit(int bytes_per_second); int upload_rate_limit() const; int download_rate_limit() const;
set_upload_rate_limit() set the maximum number of bytes allowed to be sent to peers per second. This bandwidth is distributed among all the peers. If you don't want to limit upload rate, you can set this to -1 (the default). set_download_rate_limit() works the same way but for download rate instead of upload rate. download_rate_limit() and upload_rate_limit() returns the previously set limits.
Upload and download rate limits are not applied to peers on the local network by default. To change that, see session_settings::ignore_limits_on_local_network.
set_max_uploads() set_max_connections()
void set_max_uploads(int limit); void set_max_connections(int limit);
These functions will set a global limit on the number of unchoked peers (uploads) and the number of connections opened. The number of connections is set to a hard minimum of at least two connections per torrent, so if you set a too low connections limit, and open too many torrents, the limit will not be met. The number of uploads is at least one per torrent.
num_uploads() num_connections()
int num_uploads() const; int num_connections() const;
Returns the number of currently unchoked peers and the number of connections (including half-open ones) respectively.
set_max_half_open_connections() max_half_open_connections()
void set_max_half_open_connections(int limit); int max_half_open_connections() const;
Sets the maximum number of half-open connections libtorrent will have when connecting to peers. A half-open connection is one where connect() has been called, but the connection still hasn't been established (nor failed). Windows XP Service Pack 2 sets a default, system wide, limit of the number of half-open connections to 10. So, this limit can be used to work nicer together with other network applications on that system. The default is to have no limit, and passing -1 as the limit, means to have no limit. When limiting the number of simultaneous connection attempts, peers will be put in a queue waiting for their turn to get connected.
max_half_open_connections() returns the set limit. This limit defaults to 8 on windows.
load_asnum_db() load_country_db() int as_for_ip()
bool load_asnum_db(char const* file); bool load_country_db(char const* file); int as_for_ip(address const& adr);
These functions are not available if TORRENT_DISABLE_GEO_IP is defined. They expects a path to the MaxMind ASN database and MaxMind GeoIP database respectively. This will be used to look up which AS and country peers belong to.
as_for_ip returns the AS number for the IP address specified. If the IP is not in the database or the ASN database is not loaded, 0 is returned.
load_state() state()
void load_state(entry const& ses_state); entry state() const;
These functions loads and save session state. Currently, the only state that's stored is peak download rates for ASes. This map is used to determine which order to connect to peers.
set_ip_filter()
void set_ip_filter(ip_filter const& filter);
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.
status()
session_status status() const;
status() returns session wide-statistics and status. The session_status struct has the following members:
struct session_status
{
bool has_incoming_connections;
float upload_rate;
float download_rate;
float payload_upload_rate;
float payload_download_rate;
size_type total_download;
size_type total_upload;
size_type total_redundant_bytes;
size_type total_failed_bytes;
size_type total_payload_download;
size_type total_payload_upload;
int num_peers;
int num_unchoked;
int allowed_upload_slots;
int dht_nodes;
int dht_cache_nodes;
int dht_torrents;
int dht_global_nodes;
};
has_incoming_connections is false as long as no incoming connections have been established on the listening socket. Every time you change the listen port, this will be reset to false.
upload_rate, download_rate, payload_download_rate and payload_upload_rate are the total download and upload rates accumulated from all torrents. The payload versions is the payload download only.
total_download and total_upload are the total number of bytes downloaded and uploaded to and from all torrents. total_payload_download and total_payload_upload are the same thing but where only the payload is considered.
total_redundant_bytes is the number of bytes that has been received more than once. This can happen if a request from a peer times out and is requested from a different peer, and then received again from the first one. To make this lower, increase the request_timeout and the piece_timeout in the session settings.
total_failed_bytes is the number of bytes that was downloaded which later failed the hash-check.
num_peers is the total number of peer connections this session has. This includes incoming connections that still hasn't sent their handshake or outgoing connections that still hasn't completed the TCP connection. This number may be slightly higher than the sum of all peers of all torrents because the incoming connections may not be assigned a torrent yet.
num_unchoked is the current number of unchoked peers. allowed_upload_slots is the current allowed number of unchoked peers.
dht_nodes, dht_cache_nodes and dht_torrents are only available when built with DHT support. They are all set to 0 if the DHT isn't running. When the DHT is running, dht_nodes is set to the number of nodes in the routing table. This number only includes active nodes, not cache nodes. The dht_cache_nodes is set to the number of nodes in the node cache. These nodes are used to replace the regular nodes in the routing table in case any of them becomes unresponsive.
dht_torrents are the number of torrents tracked by the DHT at the moment.
dht_global_nodes is an estimation of the total number of nodes in the DHT network.
get_cache_status()
cache_status get_cache_status() const;
Returns status of the disk cache for this session.
struct cache_status
{
size_type blocks_written;
size_type writes;
size_type blocks_read;
size_type blocks_read_hit;
size_type reads;
int cache_size;
int read_cache_size;
};
blocks_written is the total number of 16 KiB blocks written to disk since this session was started.
writes is the total number of write operations performed since this session was started.
The ratio (blocks_written - writes) / blocks_written represents the number of saved write operations per total write operations. i.e. a kind of cache hit ratio for the write cahe.
blocks_read is the number of blocks that were requested from the bittorrent engine (from peers), that were served from disk or cache.
blocks_read_hit is the number of blocks that were served from cache.
The ratio blocks_read_hit / blocks_read is the cache hit ratio for the read cache.
cache_size is the number of 16 KiB blocks currently in the disk cache. This includes both read and write cache.
read_cache_size is the number of 16KiB blocks in the read cache.
get_cache_info()
void get_cache_info(sha1_hash const& ih
, std::vector<cached_piece_info>& ret) const;
get_cache_info() fills out the supplied vector with information for each piece that is currently in the disk cache for the torrent with the specified info-hash (ih).
struct cached_piece_info
{
int piece;
std::vector<bool> blocks;
ptime last_use;
enum kind_t { read_cache = 0, write_cache = 1 };
kind_t kind;
};
piece is the piece index for this cache entry.
blocks has one entry for each block in this piece. true represents the data for that block being in the disk cache and false means it's not.
last_use is the time when a block was last written to this piece. The older a piece is, the more likely it is to be flushed to disk.
kind specifies if this piece is part of the read cache or the write cache.
is_listening() listen_port() listen_on()
bool is_listening() const;
unsigned short listen_port() const;
bool listen_on(
std::pair<int, int> const& port_range
, char const* interface = 0);
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 use listen_on() to make another try.
listen_port() returns the port we ended up listening on. Since you just pass a port-range to the constructor and to listen_on(), to know which port it ended up using, you have to ask the session using this function.
listen_on() will change the listen port and/or the listen interface. If the session is already listening on a port, this socket will be closed and a new socket will be opened with these new settings. The port range is the ports it will try to listen on, if the first port fails, it will continue trying the next port within the range and so on. The interface parameter can be left as 0, in that case the os will decide which interface to listen on, otherwise it should be the ip-address of the interface you want the listener socket bound to. listen_on() returns true if it managed to open the socket, and false if it failed. If it fails, it will also generate an appropriate alert (listen_failed_alert).
The interface parameter can also be a hostname that will resolve to the device you want to listen on.
If you're also starting the DHT, it is a good idea to do that after you've called listen_on(), since the default listen port for the DHT is the same as the tcp listen socket. If you start the DHT first, it will assume the tcp port is free and open the udp socket on that port, then later, when listen_on() is called, it may turn out that the tcp port is in use. That results in the DHT and the bittorrent socket listening on different ports. If the DHT is active when listen_on is called, the udp port will be rebound to the new port, if it was configured to use the same port as the tcp socket, and if the listen_on call failed to bind to the same port that the udp uses.
The reason why it's a good idea to run the DHT and the bittorrent socket on the same port is because that is an assumption that may be used to increase performance. One way to accelerate the connecting of peers on windows may be to first ping all peers with a DHT ping packet, and connect to those that responds first. On windows one can only connect to a few peers at a time because of a built in limitation (in XP Service pack 2).
pop_alert() set_alert_mask() wait_for_alert() set_alert_queue_size_limit()
std::auto_ptr<alert> pop_alert(); alert const* wait_for_alert(time_duration max_wait); void set_alert_mask(int m); size_t set_alert_queue_size_limit(size_t queue_size_limit_);
pop_alert() is used to ask the session if any errors or events has occurred. With set_alert_mask() you can filter which alerts to receive through pop_alert(). For information about the alert categories, see alerts.
wait_for_alert blocks until an alert is available, or for no more than max_wait time. If wait_for_alert returns because of the time-out, and no alerts are available, it returns 0. If at least one alert was generated, a pointer to that alert is returned. The alert is not popped, any subsequent calls to wait_for_alert will return the same pointer until the alert is popped by calling pop_alert. This is useful for leaving any alert dispatching mechanism independent of this blocking call, the dispatcher can be called and it can pop the alert independently.
set_alert_queue_size_limit() you can specify how many alerts can be awaiting for dispatching. If this limit is reached, new incoming alerts can not be received until alerts are popped by calling pop_alert. Default value is 1000.
add_extension()
void add_extension(boost::function<
boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext);
This function adds an extension to this session. The argument is a function object that is called with a torrent* and which should return a boost::shared_ptr<torrent_plugin>. To write custom plugins, see libtorrent plugins. For the typical bittorrent client all of these extensions should be added. The main plugins implemented in libtorrent are:
- metadata extension
- Allows peers to download the metadata (.torren files) from the swarm directly. Makes it possible to join a swarm with just a tracker and info-hash.
#include <libtorrent/extensions/metadata_transfer.hpp> ses.add_extension(&libtorrent::create_metadata_plugin);
- uTorrent metadata
- Same as metadata extension but compatible with uTorrent.
#include <libtorrent/extensions/ut_metadata.hpp> ses.add_extension(&libtorrent::create_ut_metadata_plugin);
- uTorrent peer exchange
- Exchanges peers between clients.
#include <libtorrent/extensions/ut_pex.hpp> ses.add_extension(&libtorrent::create_ut_pex_plugin);
- smart ban plugin
- A plugin that, with a small overhead, can ban peers that sends bad data with very high accuracy. Should eliminate most problems on poisoned torrents.
#include <libtorrent/extensions/smart_ban.hpp> ses.add_extension(&libtorrent::create_smart_ban_plugin);
set_settings() set_pe_settings()
void set_settings(session_settings const& settings); void set_pe_settings(pe_settings const& settings);
Sets the session settings and the packet encryption settings respectively. See session_settings and pe_settings for more information on available options.
set_peer_proxy() set_web_seed_proxy() set_tracker_proxy() set_dht_proxy()
void set_peer_proxy(proxy_settings const& s); void set_web_seed_proxy(proxy_settings const& s); void set_tracker_proxy(proxy_settings const& s); void set_dht_proxy(proxy_settings const& s);
The set_dht_proxy is not available when DHT is disabled. These functions sets the proxy settings for different kinds of connections, bittorrent peers, web seeds, trackers and the DHT traffic.
set_peer_proxy affects regular bittorrent peers. set_web_seed_proxy affects only web seeds. see HTTP seeding.
set_tracker_proxy only affects HTTP tracker connections (UDP tracker connections are affected if the given proxy supports UDP, e.g. SOCKS5).
set_dht_proxy affects the DHT messages. Since they are sent over UDP, it only has any effect if the proxy supports UDP.
For more information on what settings are available for proxies, see proxy_settings.
peer_proxy() web_seed_proxy() tracker_proxy() dht_proxy()
proxy_settings const& peer_proxy() const; proxy_settings const& web_seed_proxy() const; proxy_settings const& tracker_proxy() const; proxy_settings const& dht_proxy() const;
These functions returns references to their respective current settings.
The dht_proxy is not available when DHT is disabled.
start_dht() stop_dht() set_dht_settings() dht_state()
void start_dht(entry const& startup_state); void stop_dht(); void set_dht_settings(dht_settings const& settings); entry dht_state() const;
These functions are not available in case TORRENT_DISABLE_DHT is defined. start_dht starts the dht node and makes the trackerless service available to torrents. The startup state is optional and can contain nodes and the node id from the previous session. The dht node state is a bencoded dictionary with the following entries:
- nodes
- A list of strings, where each string is a node endpoint encoded in binary. If the string is 6 bytes long, it is an IPv4 address of 4 bytes, encoded in network byte order (big endian), followed by a 2 byte port number (also network byte order). If the string is 18 bytes long, it is 16 bytes of IPv6 address followed by a 2 bytes port number (also network byte order).
- node-id
- The node id written as a readable string as a hexadecimal number.
dht_state will return the current state of the dht node, this can be used to start up the node again, passing this entry to start_dht. It is a good idea to save this to disk when the session is closed, and read it up again when starting.
If the port the DHT is supposed to listen on is already in use, and exception is thrown, asio::error.
stop_dht stops the dht node.
add_dht_node adds a node to the routing table. This can be used if your client has its own source of bootstrapping nodes.
set_dht_settings sets some parameters availavle to the dht node. The struct has the following members:
struct dht_settings
{
int max_peers_reply;
int search_branching;
int service_port;
int max_fail_count;
};
max_peers_reply is the maximum number of peers the node will send in response to a get_peers message from another node.
search_branching is 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.
service_port is the udp port the node will listen to. This will default to 0, which means the udp listen port will be the same as the tcp listen port. This is in general a good idea, since some NAT implementations reserves the udp port for any mapped tcp port, and vice versa. NAT-PMP guarantees this for example.
max_fail_count is 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.
add_dht_node() add_dht_router()
void add_dht_node(std::pair<std::string, int> const& node); void add_dht_router(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.
add_dht_router adds the given endpoint to a list of DHT router nodes. If a search is ever made while the routing table is empty, those nodes will be used as backups. Nodes in the router node list will also never be added to the regular routing table, which effectively means they are only used for bootstrapping, to keep the load off them.
An example routing node that you could typically add is router.bittorrent.com.
start_lsd() stop_lsd()
void start_lsd(); void stop_lsd();
Starts and stops Local Service Discovery. This service will broadcast the infohashes of all the non-private torrents on the local network to look for peers on the same swarm within multicast reach.
It is turned off by default.
start_upnp() stop_upnp()
upnp* start_upnp(); void stop_upnp();
Starts and stops the UPnP service. When started, the listen port and the DHT port are attempted to be forwarded on local UPnP router devices.
The upnp object returned by start_upnp() can be used to add and remove arbitrary port mappings. Mapping status is returned through the portmap_alert and the portmap_error_alert. The object will be valid until stop_upnp() is called. See UPnP and NAT-PMP.
It is off by default.
start_natpmp() stop_natpmp()
natpmp* start_natpmp(); void stop_natpmp();
Starts and stops the NAT-PMP service. When started, the listen port and the DHT port are attempted to be forwarded on the router through NAT-PMP.
The natpmp object returned by start_natpmp() can be used to add and remove arbitrary port mappings. Mapping status is returned through the portmap_alert and the portmap_error_alert. The object will be valid until stop_natpmp() is called. See UPnP and NAT-PMP.
It is off by default.
entry
The entry class represents one node in a bencoded hierarchy. It works as a variant type, it can be either a list, a dictionary (std::map), an integer or a string. This is its synopsis:
class entry
{
public:
typedef std::map<std::string, entry> dictionary_type;
typedef std::string string_type;
typedef std::list<entry> list_type;
typedef size_type integer_type;
enum data_type
{
int_t,
string_t,
list_t,
dictionary_t,
undefined_t
};
data_type type() const;
entry(dictionary_type const&);
entry(string_type const&);
entry(list_type const&);
entry(integer_type const&);
entry();
entry(data_type t);
entry(entry const& e);
~entry();
void operator=(entry const& e);
void operator=(dictionary_type const&);
void operator=(string_type const&);
void operator=(list_type const&);
void operator=(integer_type const&);
integer_type& integer();
integer_type const& integer() const;
string_type& string();
string_type const& string() const;
list_type& list();
list_type const& list() const;
dictionary_type& dict();
dictionary_type const& dict() const;
// these functions requires that the entry
// is a dictionary, otherwise they will throw
entry& operator[](char const* key);
entry& operator[](std::string const& key);
entry const& operator[](char const* key) const;
entry const& operator[](std::string const& key) const;
entry* find_key(char const* key);
entry const* find_key(char const* key) const;
void print(std::ostream& os, int indent = 0) const;
};
TODO: finish documentation of entry.
integer() string() list() dict() type()
integer_type& integer(); integer_type const& integer() const; string_type& string(); string_type const& string() const; list_type& list(); list_type const& list() const; dictionary_type& dict(); dictionary_type const& dict() const;
The integer(), string(), list() and dict() functions are accessors that return the respective type. If the entry object isn't of the type you request, the accessor will throw type_error (which derives from std::runtime_error). You can ask an entry for its type through the type() function.
The print() function is there for debug purposes only.
If you want to create an entry you give it the type you want it to have in its constructor, and then use one of the non-const accessors to get a reference which you then can assign the value you want it to have.
The typical code to get info from a torrent file will then look like this:
entry torrent_file;
// ...
// throws if this is not a dictionary
entry::dictionary_type const& dict = torrent_file.dict();
entry::dictionary_type::const_iterator i;
i = dict.find("announce");
if (i != dict.end())
{
std::string tracker_url = i->second.string();
std::cout << tracker_url << "\n";
}
The following code is equivalent, but a little bit shorter:
entry torrent_file;
// ...
// throws if this is not a dictionary
if (entry* i = torrent_file.find_key("announce"))
{
std::string tracker_url = i->string();
std::cout << tracker_url << "\n";
}
To make it easier to extract information from a torrent file, the class torrent_info exists.
operator[]
entry& operator[](char const* key); entry& operator[](std::string const& key); entry const& operator[](char const* key) const; entry const& operator[](std::string const& key) const;
All of these functions requires the entry to be a dictionary, if it isn't they will throw libtorrent::type_error.
The non-const versions of the operator[] will return a reference to either the existing element at the given key or, if there is no element with the given key, a reference to a newly inserted element at that key.
The const version of operator[] will only return a reference to an existing element at the given key. If the key is not found, it will throw libtorrent::type_error.
find_key()
entry* find_key(char const* key); entry const* find_key(char const* key) const;
These functions requires the entry to be a dictionary, if it isn't they will throw libtorrent::type_error.
They will look for an element at the given key in the dictionary, if the element cannot be found, they will return 0. If an element with the given key is found, the return a pointer to it.
torrent_info
In previous versions of libtorrent, this class was also used for creating torrent files. This functionality has been moved to create_torrent, see make_torrent.
The torrent_info has the following synopsis:
class torrent_info
{
public:
torrent_info(sha1_hash const& info_hash);
torrent_info(lazy_entry const& torrent_file);
torrent_info(char const* buffer, int size);
torrent_info(boost::filesystem::path const& filename);
void add_tracker(std::string const& url, int tier = 0);
std::vector<announce_entry> const& trackers() const;
file_storage const& files() const;
file_storage const& orig_files() const;
void rename_file(int index, std::string const& new_filename);
void rename_file(int index, std::wstring const& new_filename);
typedef file_storage::iterator file_iterator;
typedef file_storage::reverse_iterator reverse_file_iterator;
file_iterator begin_files() const;
file_iterator end_files() const;
reverse_file_iterator rbegin_files() const;
reverse_file_iterator rend_files() const;
int num_files() const;
file_entry const& file_at(int index) const;
std::vector<file_slice> map_block(int piece, size_type offset
, int size) const;
peer_request map_file(int file_index, size_type file_offset
, int size) const;
bool priv() const;
std::vector<std::string> const& url_seeds() const;
size_type total_size() const;
int piece_length() const;
int num_pieces() const;
sha1_hash const& info_hash() const;
std::string const& name() const;
std::string const& comment() const;
std::string const& creator() const;
std::vector<std::pair<std::string, int> > const& nodes() const;
void add_node(std::pair<std::string, int> const& node);
boost::optional<boost::posix_time::ptime>
creation_date() const;
int piece_size(unsigned int index) const;
sha1_hash const& hash_for_piece(unsigned int index) const;
char const* hash_for_piece_ptr(unsigned int index) const;
boost::shared_array<char> metadata() const;
int metadata_size() const;
};
torrent_info()
torrent_info(sha1_hash const& info_hash); torrent_info(lazy_entry const& torrent_file); torrent_info(char const* buffer, int size); torrent_info(boost::filesystem::path const& filename);
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 lazy_entry will create a torrent_info object from the information found in the given torrent_file. The lazy_entry represents a tree node in an bencoded file. To load an ordinary .torrent file into a lazy_entry, use lazy_bdecode(), see bdecode() bencode().
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.
add_tracker()
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. For more information see trackers().
files() orig_files()
file_storage const& file() 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 chaged using torrent_info::rename_file().
For more information on the file_storage object, see the separate document on how to create torrents.
rename_file()
void rename_file(int index, std::string const& new_filename); void rename_file(int index, std::wstring 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().
begin_files() end_files() rbegin_files() rend_files()
file_iterator begin_files() const; file_iterator end_files() const; reverse_file_iterator rbegin_files() const; reverse_file_iterator rend_files() const;
This class will need some explanation. First of all, to get a list of all files in the torrent, you can use begin_files(), end_files(), rbegin_files() and rend_files(). These will give you standard vector iterators with the type file_entry.
struct file_entry
{
boost::filesystem::path path;
size_type offset;
size_type size;
size_type file_base;
boost::shared_ptr<const boost::filesystem::path> orig_path;
};
The path is the full (relative) path of each file. i.e. if it is a multi-file torrent, all the files starts with a directory with the same name as torrent_info::name(). The filenames are encoded with UTF-8.
size is the size of the file (in bytes) and offset is the byte offset of the file within the torrent. i.e. the sum of all the sizes of the files before it in the list.
file_base is the offset in the file where the storage should start. The normal case is to have this set to 0, so that the storage starts saving data at the start if the file. In cases where multiple files are mapped into the same file though, the file_base should be set to an offset so that the different regions do not overlap. This is used when mapping "unselected" files into a so-called part file.
orig_path is set to 0 in case the path element is an exact copy of that found in the metadata. In case the path in the original metadata was incorrectly encoded, and had to be fixed in order to be acceptable utf-8, the original string is preserved in orig_path. The reason to keep it is to be able to reproduce the info-section exactly, with the correct info-hash.
num_files() file_at()
int num_files() const; file_entry const& file_at(int index) const;
If you need index-access to files you can use the num_files() and file_at() to access files using indices.
map_block()
std::vector<file_slice> map_block(int piece, size_type 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.
The file slice struct looks like this:
struct file_slice
{
int file_index;
size_type offset;
size_type size;
};
The file_index refers to the index of the file (in the torrent_info). To get the path and filename, use file_at() and give the file_index as argument. The offset is the byte offset in the file where the range starts, and size is the number of bytes this range is. The size + offset will never be greater than the file size.
map_file()
peer_request map_file(int file_index, size_type file_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. The peer_request structure looks like this:
struct peer_request
{
int piece;
int start;
int length;
bool operator==(peer_request const& r) const;
};
piece is the index of the piece in which the range starts. start is the offset within that piece where the range starts. length is the size of the range, in bytes.
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().
url_seeds() add_url_seed()
std::vector<std::string> const& url_seeds() const; void add_url_seed(std::string const& url);
If there are any url-seeds in this torrent, url_seeds() will return a vector of those urls. If you're creating a torrent file, add_url_seed() adds one url to the list of url-seeds. Currently, the only transport protocol supported for the url is http.
See HTTP seeding for more information.
trackers()
std::vector<announce_entry> const& trackers() const;
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.
struct announce_entry
{
announce_entry(std::string const& url);
std::string url;
int tier;
};
total_size() piece_length() piece_size() num_pieces()
size_type total_size() const; int piece_length() const; int piece_size(unsigned int index) const; int num_pieces() 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.
hash_for_piece() hash_for_piece_ptr() info_hash()
size_type piece_size(unsigned int index) const; sha1_hash const& hash_for_piece(unsigned int index) const; char const* hash_for_piece_ptr(unsigned int index) const;
hash_for_piece() takes a piece-index and returns the 20-bytes sha1-hash for that piece and info_hash() returns the 20-bytes sha1-hash for the info-section of the torrent file. For more information on the sha1_hash, see the big_number class. hash_for_piece_ptr() returns a pointer to the 20 byte sha1 digest for the piece. Note that the string is not null-terminated.
name() comment() creation_date() creator()
std::string const& name() const; std::string const& comment() const; boost::optional<boost::posix_time::ptime> creation_date() const;
name() returns the name of the torrent.
comment() returns the comment associated with the torrent. If there's no comment, it will return an empty string. creation_date() returns a boost::posix_time::ptime object, representing the time when this torrent file was created. If there's no time stamp in the torrent file, this will return a date of January 1:st 1970.
Both the name and the comment is UTF-8 encoded strings.
creator() returns the creator string in the torrent. If there is no creator string it will return an empty string.
priv()
bool priv() const;
priv() returns true if this torrent is private. i.e., it should not be distributed on the trackerless network (the kademlia DHT).
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.
metadata() metadata_size()
boost::shared_array<char> metadata() const; int metadata_size() const;
metadata() returns a the raw info section of the torrent file. The size of the metadata is returned by metadata_size().
torrent_handle
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. Its declaration looks like this:
struct torrent_handle
{
torrent_handle();
torrent_status status();
void file_progress(std::vector<size_type>& fp);
void get_download_queue(std::vector<partial_piece_info>& queue) const;
void get_peer_info(std::vector<peer_info>& v) const;
torrent_info const& get_torrent_info() const;
bool is_valid() const;
std::string name() const;
void save_resume_data() const;
void force_reannounce() const;
void force_reannounce(boost::posix_time::time_duration) const;
void scrape_tracker() const;
void connect_peer(asio::ip::tcp::endpoint const& adr, int source = 0) const;
void set_tracker_login(std::string const& username
, std::string const& password) const;
std::vector<announce_entry> const& trackers() const;
void replace_trackers(std::vector<announce_entry> const&);
void add_url_seed(std::string const& url);
void remove_url_seed(std::string const& url);
std::set<std::string> url_seeds() const;
void set_ratio(float ratio) const;
void set_max_uploads(int max_uploads) const;
void set_max_connections(int max_connections) const;
void set_upload_limit(int limit) const;
int upload_limit() const;
void set_download_limit(int limit) const;
int download_limit() const;
void set_sequential_download(bool sd) const;
bool is_sequential_download() const;
void set_peer_upload_limit(asio::ip::tcp::endpoint ip, int limit) const;
void set_peer_download_limit(asio::ip::tcp::endpoint ip, int limit) const;
int queue_position() const;
void queue_position_up() const;
void queue_position_down() const;
void queue_position_top() const;
void queue_position_bottom() const;
void use_interface(char const* net_interface) const;
void pause() const;
void resume() const;
bool is_paused() const;
bool is_seed() const;
void force_recheck() const;
void clear_error() const;
void resolve_countries(bool r);
bool resolve_countries() const;
void piece_priority(int index, int priority) const;
int piece_priority(int index) const;
void prioritize_pieces(std::vector<int> const& pieces) const;
std::vector<int> piece_priorities() const;
void file_priority(int index, int priority) const;
int file_priority(int index) const;
void prioritize_files(std::vector<int> const& files) const;
std::vector<int> file_priorities() const;
bool is_auto_managed() const;
void auto_managed(bool m) const;
bool has_metadata() const;
boost::filesystem::path save_path() const;
void move_storage(boost::filesystem::path const& save_path) const;
void rename_file(int index, boost::filesystem::path) const;
storage_interface* get_storage_impl() const;
sha1_hash info_hash() const;
bool operator==(torrent_handle const&) const;
bool operator!=(torrent_handle const&) const;
bool operator<(torrent_handle const&) const;
};
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 invalid_handle exception, in case the handle is no longer refering 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.
piece_priority() prioritize_pieces() piece_priorities()
void piece_priority(int index, int priority) const; int piece_priority(int index) const; void prioritize_pieces(std::vector<int> const& pieces) const; std::vector<int> piece_priorities() const;
These functions are used to set and get the prioritiy of individual pieces. By default all pieces have priority 1. 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 different priority levels:
- piece is not downloaded at all
- normal priority. Download order is dependent on availability
- higher than normal priority. Pieces are preferred over pieces with the same availability, but not over pieces with lower availability
- pieces are as likely to be picked as partial pieces.
- pieces are preferred over partial pieces, but not over pieces with lower availability
- currently the same as 4
- piece is as likely to be picked as any piece with availability 1
- maximum priority, availability is disregarded, the piece is preferred over any other piece with lower priority
The exact definitions of these priorities are implementation details, and subject to change. The interface guarantees that higher number means higher priority, and that 0 means do not download.
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.
piece_priorities returns a vector with one element for each piece in the torrent. Each element is the current priority of that piece.
file_priority() prioritize_files() file_priorities()
void file_priority(int index, int priority) const; int file_priority(int index) const; void prioritize_files(std::vector<int> const& files) const; std::vector<int> file_priorities() const;
index must be in the range [0, number_of_files).
file_priority queries or sets the priority of file index.
prioritize_files takes a vector that has at as many elements as there are files in the torrent. Each entry is the priority of that file. The function sets the priorities of all the pieces in the torrent based on the vector.
file_priorities returns a vector with the priorities of all files.
The priority values are the same as for piece_priority.
Whenever a file priority is changed, all other piece priorities are reset to match the file priorities. In order to maintain sepcial priorities for particular pieces, piece_priority has to be called again for those pieces.
file_progress()
void file_progress(std::vector<size_type>& fp);
This function fills in the supplied vector with the the number of bytes downloaded of each file in this torrent. The progress values are ordered the same as the files in the torrent_info. This operation is not very cheap. Its complexity is O(n + mj). Where n is the number of files, m is the number of downloading pieces and j is the number of blocks in a piece.
save_path()
boost::filesystem::path save_path() const;
save_path() returns the path that was given to add_torrent() when this torrent was started.
move_storage()
void move_storage(boost::filesystem::path const& save_path) 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.
rename_file()
void rename_file(int index, boost::filesystem::path) 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.
get_storage_impl()
storage_interface* get_storage_impl() const;
Returns the storage implementation for this torrent. This depends on the storage contructor function that was passed to session::add_torrent.
force_reannounce()
void force_reannounce() const; void force_reannounce(boost::posix_time::time_duration) const;
force_reannounce() will force this torrent to do another tracker request, to receive new peers. The second overload of force_reannounce that takes a time_duration as argument will schedule a reannounce in that amount of time from now.
scrape_tracker()
void scrape_tracker() const;
scrape_tracker() will send a scrape request to the tracker. 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.
connect_peer()
void connect_peer(asio::ip::tcp::endpoint const& adr, int source = 0) 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 invalid_handle. The second (optional) argument will be bitwised ORed into the source mask of this peer. Typically this is one of the source flags in peer_info. i.e. tracker, pex, dht etc.
name()
std::string name() const;
Returns the name of the torrent. i.e. the name from the metadata associated with it. 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.
set_ratio()
void set_ratio(float ratio) const;
set_ratio() sets the desired download / upload ratio. If set to 0, it is considered being infinite. i.e. the client will always upload as much as it can, no matter how much it gets back in return. With this setting it will work much like the standard clients.
Besides 0, the ratio can be set to any number greater than or equal to 1. It means how much to attempt to upload in return for each download. e.g. if set to 2, the client will try to upload 2 bytes for every byte received. The default setting for this is 0, which will make it work as a standard client.
set_upload_limit() set_download_limit() upload_limit() download_limit()
void set_upload_limit(int limit) const; void set_download_limit(int limit) const; int upload_limit() const; int download_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 (session::set_upload_rate_limit) will not override the global rate limit. The torrent can never upload more than the global rate limit.
upload_limit and download_limit will return the current limit setting, for upload and download, respectively.
set_sequential_download() is_sequential_download()
void set_sequential_download(bool sd); bool is_sequential_download() const;
set_sequential_download() enables or disables sequential download. When enabled, the piece picker will pick pieces in sequence instead of rarest first.
Enabling sequential download will affect the piece distribution negatively in the swarm. It should be used sparingly.
is_sequential_download() returns true if this torrent is downloading in sequence, and false otherwise.
set_peer_upload_limit() set_peer_download_limit()
void set_peer_upload_limit(asio::ip::tcp::endpoint ip, int limit) const; void set_peer_download_limit(asio::ip::tcp::endpoint ip, int limit) const;
Works like set_upload_limit and set_download_limit respectively, but controls individual peer instead of the whole torrent.
pause() resume() is_paused()
void pause() const; void resume() const; bool is_paused() 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. You can use is_paused() to determine if a torrent is currently paused. Torrents may be paused automatically if there is a file error (e.g. disk full) or something similar. See file_error_alert.
torrents that are auto-managed may be automatically resumed again. It does not make sense to pause an auto-managed torrent without making it not automanaged first. Torrents are auto-managed by default when added to the session. For more information, see queuing.
is_paused() only returns true if the torrent itself is paused. If the torrent is not running because the session is paused, this still returns false. To know if a torrent is active or not, you need to inspect both torrent_handle::is_paused() and session::is_paused().
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.
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.
resolve_countries()
void resolve_countries(bool r); bool resolve_countries() const;
Sets or gets the flag that derermines if countries should be resolved for the peers of this torrent. It defaults to false. If it is set to true, the peer_info structure for the peers in this torrent will have their country member set. See peer_info for more information on how to interpret this field.
is_seed()
bool is_seed() const;
Returns true if the torrent is in seed mode (i.e. if it has finished downloading).
is_auto_managed() auto_managed()
bool is_auto_managed() const; void auto_managed(bool m) const;
is_auto_managed() returns true if this torrent is currently auto managed. auto_managed() changes whether the torrent is auto managed or not. For more info, see queuing.
has_metadata()
bool has_metadata() const;
Returns 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 return false is when the torrent was started torrent-less (i.e. with just an info-hash and tracker ip). Note that if the torrent doesn't have metadata, the member get_torrent_info() will throw.
set_tracker_login()
void set_tracker_login(std::string const& username
, std::string const& password) const;
set_tracker_login() sets a username and password that will be sent along in the HTTP-request of the tracker announce. Set this if the tracker requires authorization.
trackers() replace_trackers()
std::vector<announce_entry> const& trackers() const; void replace_trackers(std::vector<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().
add_url_seed() remove_url_seed() url_seeds()
void add_url_seed(std::string const& url); void remove_url_seed(std::string const& url); 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.
queue_position() queue_position_up() queue_position_down() queue_position_top() queue_position_bottom()
int queue_position() const; void queue_position_up() const; void queue_position_down() const; void queue_position_top() const; void queue_position_bottom() 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_*() 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.
use_interface()
void use_interface(char const* net_interface) const;
use_interface() sets the network interface this torrent will use when it opens outgoing connections. By default, it uses the same interface as the session uses to listen on. The parameter must be a string containing an ip-address (either an IPv4 or IPv6 address). If the string does not conform to this format and exception is thrown.
info_hash()
sha1_hash info_hash() const;
info_hash() returns the info-hash for the torrent.
set_max_uploads() set_max_connections()
void set_max_uploads(int max_uploads) const; void set_max_connections(int max_connections) 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.
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.
save_resume_data()
void save_resume_data() const;
save_resume_data() generates fast-resume data and returns it as an entry. This entry is suitable for being bencoded. For more information about how fast-resume works, see fast resume.
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:
- The torrent handle is invalid.
- The torrent is checking (or is queued for checking) its storage, it will obviously not be ready to write resume data.
- 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!
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 reume 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:
int num_resume_data = 0;
std::vector<torrent_handle> handles = ses.get_torrents();
ses.pause();
for (std::vector<torrent_handle>::iterator i = handles.begin();
i != handles.end(); ++i)
{
torrent_handle& h = *i;
if (!h.has_metadata()) continue;
if (!h.is_valid()) continue;
h.save_resume_data();
++num_resume_data;
}
while (num_resume_data > 0)
{
alert const* a = ses.wait_for_alert(seconds(10));
// if we don't get an alert within 10 seconds, abort
if (a == 0) break;
std::auto_ptr<alert> holder = ses.pop_alert();
if (dynamic_cast<save_resume_data_failed_alert const*>(a))
{
process_alert(a);
--num_resume_data;
continue;
}
save_resume_data_alert const* rd = dynamic_cast<save_resume_data_alert const*>(a);
i