Core

Author: Arvid Norberg, arvid@rasterbar.com
Version: 1.0.0

disk_buffer_holder

Declared in "libtorrent/disk_buffer_holder.hpp"

The disk buffer holder acts like a scoped_ptr that frees a disk buffer when it's destructed, unless it's released. release returns the disk buffer and transferres ownership and responsibility to free it to the caller.

A disk buffer is freed by passing it to session_impl::free_disk_buffer().

buffer() returns the pointer without transferring responsibility. If this buffer has been released, buffer() will return 0.

struct disk_buffer_holder
{
   disk_buffer_holder (disk_buffer_pool& disk_pool, char* buf);
   ~disk_buffer_holder ();
   char* release ();
   char* get () const;
   void reset (char* buf = 0);
   void swap (disk_buffer_holder& h);
};

disk_buffer_holder()

disk_buffer_holder (disk_buffer_pool& disk_pool, char* buf);

construct a buffer holder that will free the held buffer using a disk buffer pool directly (there's only one disk_buffer_pool per session)

~disk_buffer_holder()

~disk_buffer_holder ();

frees any unreleased disk buffer held by this object

release()

char* release ();

return the held disk buffer and clear it from the holder. The responsibility to free it is passed on to the caller

get()

char* get () const;

return a pointer to the held buffer

reset()

void reset (char* buf = 0);

set the holder object to hold the specified buffer (or NULL by default). If it's already holding a disk buffer, it will first be freed.

swap()

void swap (disk_buffer_holder& h);

swap pointers of two disk buffer holders.

hasher

Declared in "libtorrent/hasher.hpp"

this is a SHA-1 hash class.

You use it by first instantiating it, then call update() to feed it with data. i.e. you don't have to keep the entire buffer of which you want to create the hash in memory. You can feed the hasher parts of it at a time. When You have fed the hasher with all the data, you call final() and it will return the sha1-hash of the data.

The constructor that takes a char const* and an integer will construct the sha1 context and feed it the data passed in.

If you want to reuse the hasher object once you have created a hash, you have to call reset() to reinitialize it.

The sha1-algorithm used was implemented by Steve Reid and released as public domain. For more info, see src/sha1.cpp.

class hasher
{
   hasher ();
   hasher (const char* data, int len);
   hasher& operator= (hasher const& h);
   hasher (hasher const& h);
   hasher& update (std::string const& data);
   hasher& update (const char* data, int len);
   sha1_hash final ();
   void reset ();
   ~hasher ();
};

hasher()

hasher (const char* data, int len);

this is the same as default constructing followed by a call to update(data, len).

update()

hasher& update (std::string const& data);
hasher& update (const char* data, int len);

append the following bytes to what is being hashed

final()

sha1_hash final ();

returns the SHA-1 digest of the buffers previously passed to update() and the hasher constructor.

reset()

void reset ();

restore the hasher state to be as if the hasher has just been default constructed.

peer_info

Declared in "libtorrent/peer_info.hpp"

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

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

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

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

   enum connection_type_t
   {
      standard_bittorrent,
      web_seed,
      http_seed,
   };

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

enum peer_flags_t

Declared in "libtorrent/peer_info.hpp"

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

enum peer_source_flags

Declared in "libtorrent/peer_info.hpp"

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

enum bw_state

Declared in "libtorrent/peer_info.hpp"

name value description
bw_idle 0 The peer is not waiting for any external events to send or receive data.
bw_limit 1 The peer is waiting for the rate limiter.
bw_network 2 The peer has quota and is currently waiting for a network read or write operation to complete. This is the state all peers are in if there are no bandwidth limits.
bw_disk 4 The peer is waiting for the disk I/O thread to catch up writing buffers to disk before downloading more.

enum connection_type_t

Declared in "libtorrent/peer_info.hpp"

name value description
standard_bittorrent 0 Regular bittorrent connection over TCP
web_seed 1 HTTP connection using the BEP 19 protocol
http_seed 2 HTTP connection using the BEP 17 protocol
flags
tells you in which state the peer is in. It is set to any combination of the peer_flags_t enum.
source
a combination of flags describing from which sources this peer was received.
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.
ip
the IP-address to this peer. The type is an asio endpoint. For more info, see the asio documentation.
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
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.
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()_
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).
upload_limit download_limit
the number of bytes per second we are allowed to send to or receive from this peer. It may be -1 if there's no local limit on the peer. The global limit and the torrent limit may also be enforced.
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 queue_bytes
the time until all blocks in the request queue will be d
request_timeout
the number of seconds until the current front piece request will time out. This timeout can be adjusted through session_settings::request_timeout. -1 means that there is not outstanding request.
send_buffer_size used_send_buffer
the number of bytes allocated and used for the peer's send buffer, respectively.
receive_buffer_size used_receive_buffer
the number of bytes allocated and used as receive buffer, respectively.
num_hashfails
the number of pieces this peer has participated in sending us that turned out to fail the hash check.
country[2]
the two letter ISO 3166 country code for the country the peer is connected from. If the country hasn't been resolved yet, both chars are set to 0. If the resolution failed for some reason, the field is set to "--". If the resolution service returns an invalid country code, it is set to "!!". The countries.nerd.dk service is used to look up countries. This field will remain set to 0 unless the torrent is set to resolve countries, see resolve_countries().
inet_as_name
the name of the AS this peer is located in. This might be an empty string if there is no name in the geo ip database.
inet_as
the AS number the peer is located in.
download_queue_length
this is the number of requests we have sent to this peer that we haven't got a response for yet
timed_out_requests
the number of block requests that have timed out, and are still in the download queue
busy_requests
the number of busy requests in the download queue. A budy request is a request for a block we've also requested from a different peer
requests_in_buffer
the number of requests messages that are currently in the send buffer waiting to be sent.
target_dl_queue_length
the number of requests that is tried to be maintained (this is typically a function of download speed)
upload_queue_length
the number of piece-requests we have received from this peer that we haven't answered with a piece yet.
failcount
the number of times this peer has "failed". i.e. failed to connect or disconnected us. The failcount is decremented when we see this peer in a tracker response or peer exchange message.
downloading_piece_index downloading_block_index downloading_progress downloading_total
You can know which piece, and which part of that piece, that is currently being downloaded from a specific peer by looking at these four members. downloading_piece_index is the index of the piece that is currently being downloaded. This may be set to -1 if there's currently no piece downloading from this peer. If it is >= 0, the other three members are valid. downloading_block_index is the index of the block (or sub-piece) that is being downloaded. downloading_progress is the number of bytes of this block we have received from the peer, and downloading_total is the total number of bytes in this block.
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.
connection_type
the kind of connection this peer uses. See connection_type_t.
remote_dl_rate
an estimate of the rate this peer is downloading at, in bytes per second.
pending_disk_bytes
the number of bytes this peer has pending in the disk-io thread. Downloaded and waiting to be written to disk. This is what is capped by session_settings::max_queued_disk_bytes.
send_quota receive_quota
the number of bytes this peer has been assigned to be allowed to send and receive until it has to request more quota from the bandwidth manager.
rtt
an estimated round trip time to this peer, in milliseconds. It is estimated by timing the the tcp connect(). It may be 0 for incoming connections.
num_pieces
the number of pieces this peer has.
download_rate_peak upload_rate_peak
the highest download and upload rates seen on this connection. They are given in bytes per second. This number is reset to 0 on reconnect.
progress_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.
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.

peer_request

Declared in "libtorrent/peer_request.hpp"

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

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

   int piece;
   int start;
   int length;
};

operator==()

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

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

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

block_info

Declared in "libtorrent/torrent_handle.hpp"

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

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

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

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

set_peer() peer()

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

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

enum block_state_t

Declared in "libtorrent/torrent_handle.hpp"

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

partial_piece_info

Declared in "libtorrent/torrent_handle.hpp"

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

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

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

enum state_t

Declared in "libtorrent/torrent_handle.hpp"

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

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

Warning

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

piece_state

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

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

torrent_handle

Declared in "libtorrent/torrent_handle.hpp"

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

Warning

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

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

Warning

All operations on a torrent_handle may throw libtorrent_exception exception, in case the handle is no longer 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.

struct torrent_handle
{
   torrent_handle ();
   void add_piece (int piece, char const* data, int flags = 0) const;
   void read_piece (int piece) const;
   bool have_piece (int piece) const;
   void get_peer_info (std::vector<peer_info>& v) const;
   torrent_status status (boost::uint32_t flags = 0xffffffff) const;
   void get_download_queue (std::vector<partial_piece_info>& queue) const;
   void reset_piece_deadline (int index) const;
   void set_piece_deadline (int index, int deadline, int flags = 0) const;
   void set_priority (int prio) const;
   void file_progress (std::vector<size_type>& progress, int flags = 0) const;
   void clear_error () const;
   std::vector<announce_entry> trackers () const;
   void replace_trackers (std::vector<announce_entry> const&) const;
   void add_tracker (announce_entry const&) const;
   void add_url_seed (std::string const& url) const;
   void remove_url_seed (std::string const& url) const;
   std::set<std::string> url_seeds () const;
   void add_http_seed (std::string const& url) const;
   void remove_http_seed (std::string const& url) const;
   std::set<std::string> http_seeds () const;
   void add_extension (
      boost::function<boost::shared_ptr<torrent_plugin>(torrent*, void*)> const& ext
      , void* userdata = 0);
   bool set_metadata (char const* metadata, int size) const;
   bool is_valid () const;
   void pause (int flags = 0) const;
   void resume () const;
   void set_upload_mode (bool b) const;
   void set_share_mode (bool b) const;
   void flush_cache () const;
   void apply_ip_filter (bool b) const;
   void force_recheck () const;
   void save_resume_data (int flags = 0) const;
   bool need_save_resume_data () const;
   void auto_managed (bool m) const;
   void queue_position_down () const;
   void queue_position_top () const;
   int queue_position () const;
   void queue_position_bottom () const;
   void queue_position_up () const;
   void resolve_countries (bool r);
   bool resolve_countries () 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;
   boost::intrusive_ptr<torrent_info const> torrent_file () const;
   void use_interface (const char* net_interface) const;
   void piece_availability (std::vector<int>& avail) const;
   int piece_priority (int index) const;
   void piece_priority (int index, int priority) const;
   void prioritize_pieces (std::vector<int> const& pieces) const;
   std::vector<int> piece_priorities () const;
   int file_priority (int index) const;
   void prioritize_files (std::vector<int> const& files) const;
   void file_priority (int index, int priority) const;
   std::vector<int> file_priorities () const;
   void force_reannounce (int seconds = 0, int tracker_index = -1) const;
   void force_dht_announce () const;
   void scrape_tracker () const;
   int upload_limit () const;
   int download_limit () const;
   void set_upload_limit (int limit) const;
   void set_download_limit (int limit) const;
   void set_sequential_download (bool sd) const;
   void connect_peer (tcp::endpoint const& adr, int source = 0) 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 set_tracker_login (std::string const& name
      , std::string const& password) const;
   void move_storage (std::string const& save_path, int flags = 0) const;
   void rename_file (int index, std::string const& new_name) const;
   void super_seeding (bool on) const;
   sha1_hash info_hash () const;
   bool operator!= (const torrent_handle& h) const;
   bool operator< (const torrent_handle& h) const;
   bool operator== (const torrent_handle& h) const;
   boost::shared_ptr<torrent> native_handle () const;

   enum flags_t
   {
      overwrite_existing,
   };

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

   enum deadline_flags
   {
      alert_when_available,
   };

   enum file_progress_flags_t
   {
      piece_granularity,
   };

   enum pause_flags_t
   {
      graceful_pause,
   };

   enum save_resume_flags_t
   {
      flush_disk_cache,
      save_info_dict,
   };
};

torrent_handle()

torrent_handle ();

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

add_piece()

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

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

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

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

read_piece()

void read_piece (int piece) const;

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

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

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

have_piece()

bool have_piece (int piece) const;

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

get_peer_info()

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

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

status()

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

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

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

get_download_queue()

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

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

reset_piece_deadline() set_piece_deadline()

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

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

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

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

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

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

set_priority()

void set_priority (int prio) const;

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

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

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

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

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

file_progress()

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

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

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

clear_error()

void clear_error () const;

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

add_tracker() replace_trackers() trackers()

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

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

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

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

url_seeds() add_url_seed() remove_url_seed()

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

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

See http seeding for more information.

http_seeds() remove_http_seed() add_http_seed()

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

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

See http seeding for more information.

add_extension()

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

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

set_metadata()

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

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

is_valid()

bool is_valid () const;

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

pause() resume()

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

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

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

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

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.

set_upload_mode()

void set_upload_mode (bool b) const;

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

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

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

set_share_mode()

void set_share_mode (bool b) const;

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

flush_cache()

void flush_cache () const;

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

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

apply_ip_filter()

void apply_ip_filter (bool b) const;

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

force_recheck()

void force_recheck () const;

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

save_resume_data()

void save_resume_data (int flags = 0) const;

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

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

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

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

  1. The torrent handle is invalid.
  2. The torrent is checking (or is queued for checking) its storage, it will obviously not be ready to write resume data.
  3. 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 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:

extern int outstanding_resume_data; // global counter of outstanding resume data
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.is_valid()) continue;
        torrent_status s = h.status();
        if (!s.has_metadata) continue;
        if (!s.need_save_resume_data()) continue;

        h.save_resume_data();
        ++outstanding_resume_data;
}

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

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

        std::auto_ptr<alert> holder = ses.pop_alert();

        if (alert_cast<save_resume_data_failed_alert>(a))
        {
                process_alert(a);
                --outstanding_resume_data;
                continue;
        }

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

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

Note

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

need_save_resume_data()

bool need_save_resume_data () const;

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

Note

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

auto_managed()

void auto_managed (bool m) const;

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

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

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

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

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

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

The queue position is also available in the torrent_status.

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

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.

set_ssl_certificate_buffer() set_ssl_certificate()

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

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

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

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

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

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

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

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

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

get_storage_impl()

storage_interface* get_storage_impl () const;

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

torrent_file()

boost::intrusive_ptr<torrent_info const> torrent_file () const;

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

use_interface()

void use_interface (const char* 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 one or more, comma separated, ip-address (either an IPv4 or IPv6 address). When specifying multiple interfaces, the torrent will round-robin which interface to use for each outgoing conneciton. This is useful for clients that are multi-homed.

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 advertized having a particular piece. This is the information that libtorrent uses in order to prefer picking rare pieces.

piece_priority() prioritize_pieces() piece_priorities()

int piece_priority (int index) const;
void piece_priority (int index, int priority) 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:

  1. piece is not downloaded at all
  2. normal priority. Download order is dependent on availability
  3. higher than normal priority. Pieces are preferred over pieces with the same availability, but not over pieces with lower availability
  4. pieces are as likely to be picked as partial pieces.
  5. pieces are preferred over partial pieces, but not over pieces with lower availability
  6. currently the same as 4
  7. piece is as likely to be picked as any piece with availability 1
  8. 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_priorities() prioritize_files() file_priority()

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

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

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

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

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

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

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

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

force_reannounce() force_dht_announce()

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

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

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

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

force_dht_announce will announce the torrent to the DHT immediately.

scrape_tracker()

void scrape_tracker () 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.

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

void set_sequential_download (bool sd) const;

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

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

connect_peer()

void connect_peer (tcp::endpoint const& adr, int source = 0) const;

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

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

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

max_connections() returns the current settings.

set_tracker_login()

void set_tracker_login (std::string const& name
      , std::string const& password) const;

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.

move_storage()

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

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

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

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

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

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

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

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

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

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

rename_file()

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

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

super_seeding()

void super_seeding (bool on) const;

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

info_hash()

sha1_hash info_hash () const;

info_hash() returns the info-hash for the torrent.

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

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

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

native_handle()

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

This function is intended only for use by plugins and the alert dispatch function. Any code that runs in libtorrent's network thread may not use the public API of torrent_handle. Doing so results in a dead-lock. For such routines, the native_handle gives access to the underlying type representing the torrent. This type does not have a stable API and should be relied on as little as possible.

enum flags_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
overwrite_existing 1  

enum status_flags_t

Declared in "libtorrent/torrent_handle.hpp"

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

enum deadline_flags

Declared in "libtorrent/torrent_handle.hpp"

name value description
alert_when_available 1  

enum file_progress_flags_t

Declared in "libtorrent/torrent_handle.hpp"

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

enum pause_flags_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
graceful_pause 1  

enum save_resume_flags_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
flush_disk_cache 1 the disk cache will be flushed before creating the resume data. This avoids a problem with file timestamps in the resume data in case the cache hasn't been flushed yet.
save_info_dict 2 the resume data will contain the metadata from the torrent file as well. This is default for any torrent that's added without a torrent file (such as a magnet link or a URL).

torrent_status

Declared in "libtorrent/torrent_handle.hpp"

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

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

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

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

operator==()

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

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

enum state_t

Declared in "libtorrent/torrent_handle.hpp"

name value description
queued_for_checking 0 The torrent is in the queue for being checked. But there currently is another torrent that are being checked. This torrent will wait for its turn.
checking_files 1 The torrent has not started its download yet, and is currently checking existing files.
downloading_metadata 2 The torrent is trying to download metadata from peers. This assumes the metadata_transfer extension is in use.
downloading 3 The torrent is being downloaded. This is the state most torrents will be in most of the time. The progress meter will tell how much of the files that has been downloaded.
finished 4 In this state the torrent has finished downloading but still doesn't have the entire torrent. i.e. some pieces are filtered and won't get downloaded.
seeding 5 In this state the torrent has finished downloading and is a pure seeder.
allocating 6 If the torrent was started in full allocation mode, this indicates that the (disk) storage for the torrent is allocated.
checking_resume_data 7 The torrent is currently checking the fastresume data and comparing it to the files on disk. This is typically completed in a fraction of a second, but if you add a large number of torrents at once, they will queue up.
handle
a handle to the torrent whose status the object represents.
error
may be set to an error message 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 string is empty.
save_path
the path to the directory where this torrent's files are stored. It's typically the path as was given to async_add_torrent() or add_torrent() when this torrent was started. This field is only included if the torrent status is queried with torrent_handle::query_save_path.
name
the name of the torrent. Typically this is derived from the .torrent file. In case the torrent was started without metadata, and hasn't completely received it yet, it returns the name given to it when added to the session. See session::add_torrent. This field is only included if the torrent status is queried with torrent_handle::query_name.
torrent_file
set to point to the torrent_info object for this torrent. It's only included if the torrent status is queried with torrent_handle::query_torrent_file.
next_announce
the time until the torrent will announce itself to the tracker.
announce_interval
the time the tracker want us to wait until we announce ourself again the next time.
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.
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.
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.
pieces
a bitmask that represents which pieces we have (set to true) and the pieces we don't have. It's a pointer and may be set to 0 if the torrent isn't downloading or seeding.
verified_pieces
a bitmask representing which pieces has had their hash checked. This only applies to torrents in seed mode. If the torrent is not in seed mode, this bitmask may be empty.
total_done
the total number of bytes of the file(s) that we have. All this does not necessarily has to be downloaded during this session (that's total_payload_download).
total_wanted_done
the number of bytes we have downloaded, only counting the pieces that we actually want to download. i.e. excluding any pieces that we have but have priority 0 (i.e. not wanted).
total_wanted
The total number of bytes we want to download. This may be smaller than the total torrent size in case any pieces are prioritized to 0, i.e. not wanted
all_time_upload all_time_download
are accumulated upload and download payload byte counters. They are saved in and restored from resume data to keep totals across sessions.
added_time
the posix-time when this torrent was added. i.e. what time(NULL) returned at the time.
completed_time
the posix-time when this torrent was finished. If the torrent is not yet finished, this is 0.
last_seen_complete
the time when we, or one of our peers, last saw a complete copy of this torrent.
storage_mode
The allocation mode for the torrent. See storage_mode_t for the options. For more information, see storage allocation.
progress
a value in the range [0, 1], that represents the progress of the torrent's current task. It may be checking files or downloading.
progress_ppm
reflects the same value as progress, but instead in a range [0, 1000000] (ppm = parts per million). When floating point operations are disabled, this is the only alternative to the floating point value in progress.
queue_position
the position this torrent has in the download queue. If the torrent is a seed or finished, this is -1.
download_rate upload_rate
the total rates for all peers for this torrent. These will usually have better precision than summing the rates from all peers. The rates are given as the number of bytes per second.
download_payload_rate upload_payload_rate
the total transfer rate of payload only, not counting protocol chatter. This might be slightly smaller than the other rates, but if projected over a long time (e.g. when calculating ETA:s) the difference may be noticeable.
num_seeds
the number of peers that are seeding that this client is currently connected to.
num_peers
the number of peers this torrent currently is connected to. Peer connections that are in the half-open state (is attempting to connect) or are queued for later connection attempt do not count. Although they are visible in the peer list when you call get_peer_info().
num_complete num_incomplete
if the tracker sends scrape info in its announce reply, these fields will be set to the total number of peers that have the whole file and the total number of peers that are still downloading. set to -1 if the tracker did not send any scrape data in its announce reply.
list_seeds list_peers
the number of seeds in our peer list and the total number of peers (including seeds). We are not necessarily connected to all the peers in our peer list. This is the number of peers we know of in total, including banned peers and peers that we have failed to connect to.
connect_candidates
the number of peers in this torrent's peer list that is a candidate to be connected to. i.e. It has fewer connect attempts than the max fail count, it is not a seed if we are a seed, it is not banned etc. If this is 0, it means we don't know of any more peers that we can try.
num_pieces
the number of pieces that has been downloaded. It is equivalent to: std::accumulate(pieces->begin(), pieces->end()). So you don't have to count yourself. This can be used to see if anything has updated since last time if you want to keep a graph of the pieces up to date.
distributed_full_copies
the number of distributed copies of the torrent. Note that one copy may be spread out among many peers. It tells how many copies there are currently of the rarest piece(s) among the peers this client is connected to.
distributed_fraction

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

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

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

distributed_copies

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

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

announce_entry

Declared in "libtorrent/torrent_info.hpp"

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

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

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

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

announce_entry() ~announce_entry()

announce_entry (std::string const& u);
~announce_entry ();
announce_entry ();

constructs a tracker announce entry with u as the URL.

min_announce_in() next_announce_in()

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

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

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

reset()

void reset ();

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

failed()

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

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

can_announce()

bool can_announce (ptime now, bool is_seed) const;

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

is_working()

bool is_working () const;

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

trim()

void trim ();

trims whitespace characters from the beginning of the URL.

enum tracker_source

Declared in "libtorrent/torrent_info.hpp"

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

torrent_info

Declared in "libtorrent/torrent_info.hpp"

This class represents the information stored in a .torrent file

class torrent_info : public intrusive_ptr_base<torrent_info>
{
   torrent_info (std::string const& filename, int flags = 0);
   torrent_info (char const* buffer, int size, error_code& ec, int flags = 0);
   torrent_info (sha1_hash const& info_hash, int flags = 0);
   torrent_info (lazy_entry const& torrent_file, int flags = 0);
   torrent_info (char const* buffer, int size, int flags = 0);
   torrent_info (lazy_entry const& torrent_file, error_code& ec, int flags = 0);
   torrent_info (torrent_info const& t, int flags = 0);
   torrent_info (std::string const& filename, error_code& ec, int flags = 0);
   ~torrent_info ();
   file_storage const& files () const;
   file_storage const& orig_files () const;
   void rename_file (int index, std::string const& new_filename);
   void remap_files (file_storage const& f);
   std::vector<announce_entry> const& trackers () const;
   void add_tracker (std::string const& url, int tier = 0);
   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 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());
   int num_pieces () const;
   size_type total_size () const;
   int piece_length () const;
   const sha1_hash& info_hash () const;
   int num_files () const;
   file_entry 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, size_type offset, int size) const;
   std::string ssl_cert () const;
   bool is_valid () const;
   bool priv () const;
   bool is_i2p () const;
   sha1_hash hash_for_piece (int index) const;
   char const* hash_for_piece_ptr (int index) const;
   int piece_size (int index) const;
   std::vector<sha1_hash> const& merkle_tree () const;
   void set_merkle_tree (std::vector<sha1_hash>& h);
   boost::optional<time_t> creation_date () const;
   const std::string& name () const;
   const std::string& comment () const;
   const std::string& creator () const;
   nodes_t const& nodes () const;
   void add_node (std::pair<std::string, int> const& node);
   bool parse_info_section (lazy_entry const& e, error_code& ec, int flags);
   lazy_entry const* 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;
};

torrent_info()

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

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

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.

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

The flags argument is currently unused.

~torrent_info()

~torrent_info ();

frees all storage associated with this torrent_info object

orig_files() files()

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

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

orig_files() returns the original (unmodified) file storage for this torrent. This is used by the web server connection, which needs to request files with the original names. Filename may be 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);

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

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

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

remap_files()

void remap_files (file_storage const& f);

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

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

trackers() add_tracker()

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

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

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

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

The extern_auth argument can be used for other athorization schemese 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()

int num_pieces () const;
size_type total_size () const;
int piece_length () const;

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

info_hash()

const sha1_hash& info_hash () const;

returns the info-hash of the torrent

num_files() file_at()

int num_files () const;
file_entry 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. See file_slice.

map_file()

peer_request map_file (int file, size_type 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()

std::string ssl_cert () const;

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

is_valid()

bool is_valid () const;

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

priv()

bool priv () const;

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

is_i2p()

bool is_i2p () const;

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

hash_for_piece_ptr() hash_for_piece() piece_size()

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

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

set_merkle_tree() merkle_tree()

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

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

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

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

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

name() returns the name of the torrent.

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

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

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

nodes()

nodes_t const& nodes () const;

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

add_node()

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

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

parse_info_section()

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

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

info()

lazy_entry const* info (char const* key) const;

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

swap()

void swap (torrent_info& ti);

swap the content of this and ti`.

metadata_size() metadata()

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

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

is_merkle_torrent()

bool is_merkle_torrent () const;

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

make_magnet_uri()

Declared in "libtorrent/magnet_uri.hpp"

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

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

For more information about magnet links, see magnet links.

parse_magnet_uri()

Declared in "libtorrent/magnet_uri.hpp"

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

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

hash_value()

Declared in "libtorrent/torrent_handle.hpp"

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

allows torrent_handle to be used in unordered_map and unordered_set.

sign_mutable_item()

Declared in "libtorrent/kademlia/item.hpp"

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

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