1
============================
2
libtorrent API Documentation
3
============================
5
:Author: Arvid Norberg, arvid@rasterbar.com
8
.. contents:: Table of contents
15
The interface of libtorrent consists of a few classes. The main class is
16
the ``session``, it contains the main loop that serves all torrents.
18
The basic usage is as follows:
21
* parse .torrent-files and add them to the session (see `bdecode() bencode()`_ and `add_torrent()`_)
22
* main loop (see session_)
24
* query the torrent_handles for progress (see torrent_handle_)
25
* query the session for information
26
* add and remove torrents from the session at run-time
28
* save resume data for all torrent_handles (optional, see
29
`write_resume_data()`_)
30
* destruct session object
32
Each class and function is described in this manual.
37
There are a few typedefs in the ``libtorrent`` namespace which pulls
38
in network types from the ``asio`` namespace. These are::
40
typedef asio::ip::address address;
41
typedef asio::ip::address_v4 address_v4;
42
typedef asio::ip::address_v6 address_v6;
46
These are declared in the ``<libtorrent/socket.hpp>`` header.
48
The ``using`` statements will give easy access to::
53
Which are the endpoint types used in libtorrent. An endpoint is an address
54
with an associated port.
56
For documentation on these types, please refer to the `asio documentation`_.
58
.. _`asio documentation`: http://asio.sourceforge.net/asio-0.3.8/doc/asio/reference.html
64
The ``session`` class has the following synopsis::
66
class session: public boost::noncopyable
69
session(fingerprint const& print
70
= libtorrent::fingerprint(
74
fingerprint const& print
75
, std::pair<int, int> listen_port_range
76
, char const* listen_interface = 0);
78
torrent_handle add_torrent(
79
boost::intrusive_ptr<torrent_info> const& ti
80
, boost::filesystem::path const& save_path
81
, entry const& resume_data = entry()
82
, storage_mode_t storage_mode = storage_mode_sparse
84
, storage_constructor_type sc = default_storage_constructor
85
, void* userdata = 0);
87
torrent_handle add_torrent(
88
char const* tracker_url
89
, sha1_hash const& info_hash
91
, boost::filesystem::path const& save_path
92
, entry const& resume_data = entry()
93
, storage_mode_t storage_mode = storage_mode_sparse
95
, storage_constructor_type sc = default_storage_constructor
96
, void* userdata = 0);
98
session_proxy abort();
106
void remove_torrent(torrent_handle const& h, int options = none);
107
torrent_handle find_torrent(sha_hash const& ih);
108
std::vector<torrent_handle> get_torrents() const;
110
void set_settings(session_settings const& settings);
111
void set_pe_settings(pe_settings const& settings);
113
void set_upload_rate_limit(int bytes_per_second);
114
int upload_rate_limit() const;
115
void set_download_rate_limit(int bytes_per_second);
116
int download_rate_limit() const;
117
void set_max_uploads(int limit);
118
void set_max_connections(int limit);
119
void set_max_half_open_connections(int limit);
120
int max_half_open_connections() const;
122
void set_peer_proxy(proxy_settings const& s);
123
void set_web_seed_proxy(proxy_settings const& s);
124
void set_tracker_proxy(proxy_settings const& s);
126
proxy_settings const& peer_proxy() const;
127
proxy_settings const& web_seed_proxy() const;
128
proxy_settings const& tracker_proxy() const;
130
int num_uploads() const;
131
int num_connections() const;
133
void set_ip_filter(ip_filter const& f);
135
session_status status() const;
137
bool is_listening() const;
138
unsigned short listen_port() const;
140
std::pair<int, int> const& port_range
141
, char const* interface = 0);
143
std::auto_ptr<alert> pop_alert();
144
alert const* wait_for_alert(time_duration max_wait);
145
void set_severity_level(alert::severity_t s);
147
void add_extension(boost::function<
148
boost::shared_ptr<torrent_plugin>(torrent*)> ext);
152
void set_dht_settings(
153
dht_settings const& settings);
154
entry dht_state() const;
155
void add_dht_node(std::pair<std::string
157
void add_dht_router(std::pair<std::string
170
Once it's created, the session object will spawn the main thread that will do all the work.
171
The main thread will be idle as long it doesn't have any torrents to participate in.
178
session(fingerprint const& print
179
= libtorrent::fingerprint("LT", 0, 1, 0, 0));
180
session(fingerprint const& print
181
, std::pair<int, int> listen_port_range
182
, char const* listen_interface = 0);
184
If the fingerprint in the first overload is omited, the client will get a default
185
fingerprint stating the version of libtorrent. The fingerprint is a short string that will be
186
used in the peer-id to identify the client and the client's version. For more details see the
187
fingerprint_ class. The constructor that only takes a fingerprint will not open a
188
listen port for the session, to get it running you'll have to call ``session::listen_on()``.
189
The other constructor, that takes a port range and an interface as well as the fingerprint
190
will automatically try to listen on a port on the given interface. For more information about
191
the parameters, see ``listen_on()`` function.
196
The destructor of session will notify all trackers that our torrents have been shut down.
197
If some trackers are down, they will time out. All this before the destructor of session
198
returns. So, it's advised that any kind of interface (such as windows) are closed before
199
destructing the session object. Because it can take a few second for it to finish. The
200
timeout can be set with ``set_settings()``.
207
session_proxy abort();
209
In case you want to destruct the session asynchrounously, you can request a session
210
destruction proxy. If you don't do this, the destructor of the session object will
211
block while the trackers are contacted. If you keep one ``session_proxy`` to the
212
session when destructing it, the destructor will not block, but start to close down
213
the session, the destructor of the proxy will then synchronize the threads. So, the
214
destruction of the session is performed from the ``session`` destructor call until the
215
``session_proxy`` destructor call. The ``session_proxy`` does not have any operations
216
on it (since the session is being closed down, no operations are allowed on it). The
217
only valid operation is calling the destructor::
232
typedef storage_interface* (&storage_constructor_type)(
233
boost::intrusive_ptr<torrent_info const>, fs::path const&
236
torrent_handle add_torrent(
237
boost::intrusive_ptr<torrent_info> const& ti
238
, boost::filesystem::path const& save_path
239
, entry const& resume_data = entry()
240
, storage_mode_t storage_mode = storage_mode_sparse
241
, bool paused = false
242
, storage_constructor_type sc = default_storage_constructor
243
, void* userdata = 0);
245
torrent_handle add_torrent(
246
char const* tracker_url
247
, sha1_hash const& info_hash
249
, boost::filesystem::path const& save_path
250
, entry const& resume_data = entry()
251
, storage_mode_t storage_mode = storage_mode_sparse
252
, bool paused = false
253
, storage_constructor_type sc = default_storage_constructor
254
, void* userdata = 0);
256
You add torrents through the ``add_torrent()`` function where you give an
257
object representing the information found in the torrent file and the path where you
258
want to save the files. The ``save_path`` will be prepended to the directory
259
structure in the torrent-file.
261
If the torrent you are trying to add already exists in the session (is either queued
262
for checking, being checked or downloading) ``add_torrent()`` will throw
263
duplicate_torrent_ which derives from ``std::exception``.
265
The optional parameter, ``resume_data`` can be given if up to date fast-resume data
266
is available. The fast-resume data can be acquired from a running torrent by calling
267
``torrent_handle::write_resume_data()``. See `fast resume`_.
269
The ``storage_mode`` parameter refers to the layout of the storage for this torrent.
270
There are 3 different modes:
273
All pieces will be written to the place where they belong and sparse files
274
will be used. This is the recommended, and default mode.
276
storage_mode_allocate
277
All pieces will be allocated, zeroes will be written to the files, before
278
the data is downloaded and written to the file. This might be useful for
279
filesystems that don't support sparse files.
282
The storage will grow as more pieces are downloaded, and pieces
283
are rearranged to finally be in their correct places once the entire torrent has been
286
For more information, see `storage allocation`_.
288
``paused`` is a boolean that specifies whether or not the torrent is to be started in
289
a paused state. I.e. it won't connect to the tracker or any of the peers until it's
290
resumed. This is typically a good way of avoiding race conditions when setting
291
configuration options on torrents before starting them.
293
``storage_constructor`` can be used to customize how the data is stored. The default
294
storage will simply write the data to the files it belongs to, but it could be
295
overridden to save everything to a single file at a specific location or encrypt the
296
content on disk for instance. For more information about the ``storage_interface``
297
that needs to be implemented for a custom storage, see `storage_interface`_.
299
The torrent_handle_ returned by ``add_torrent()`` can be used to retrieve information
300
about the torrent's progress, its peers etc. It is also used to abort a torrent.
302
The ``userdata`` parameter is optional and will be passed on to the extension
303
constructor functions, if any (see `add_extension()`_).
305
The second overload that takes a tracker url and an info-hash instead of metadata
306
(``torrent_info``) can be used with torrents where (at least some) peers support
307
the metadata extension. For the overload to be available, libtorrent must be built
308
with extensions enabled (``TORRENT_DISABLE_EXTENSIONS`` must not be defined). It also
309
takes an optional ``name`` argument. This may be 0 in case no name should be assigned
310
to the torrent. In case it's not 0, the name is used for the torrent as long as it doesn't
311
have metadata. See ``torrent_handle::name``.
313
If the torrent doesn't have a tracker, but relies on the DHT to find peers, the
314
``tracker_url`` can be 0.
322
void remove_torrent(torrent_handle const& h, int options = none);
324
``remove_torrent()`` will close all peer connections associated with the torrent and tell
325
the tracker that we've stopped participating in the swarm. The optional second argument
326
``options`` can be used to delete all the files downloaded by this torrent. To do this, pass
327
in the value ``session::delete_files``. The removal of the torrent is asyncronous, there is
328
no guarantee that adding the same torrent immediately after it was removed will not throw
329
a duplicate_torrent_ exception.
331
find_torrent() get_torrents()
332
-----------------------------
336
torrent_handle find_torrent(sha_hash const& ih);
337
std::vector<torrent_handle> get_torrents() const;
339
``find_torrent()`` looks for a torrent with the given info-hash. In case there
340
is such a torrent in the session, a torrent_handle to that torrent is returned.
341
In case the torrent cannot be found, an invalid torrent_handle is returned.
343
See ``torrent_handle::is_valid()`` to know if the torrent was found or not.
345
``get_torrents()`` returns a vector of torrent_handles to all the torrents
346
currently in the session.
349
set_upload_rate_limit() set_download_rate_limit() upload_rate_limit() download_rate_limit()
350
-------------------------------------------------------------------------------------------
354
void set_upload_rate_limit(int bytes_per_second);
355
void set_download_rate_limit(int bytes_per_second);
356
int upload_rate_limit() const;
357
int download_rate_limit() const;
359
``set_upload_rate_limit()`` set the maximum number of bytes allowed to be
360
sent to peers per second. This bandwidth is distributed among all the peers. If
361
you don't want to limit upload rate, you can set this to -1 (the default).
362
``set_download_rate_limit()`` works the same way but for download rate instead
364
``download_rate_limit()`` and ``upload_rate_limit()`` returns the previously
368
set_max_uploads() set_max_connections()
369
---------------------------------------
373
void set_max_uploads(int limit);
374
void set_max_connections(int limit);
376
These functions will set a global limit on the number of unchoked peers (uploads)
377
and the number of connections opened. The number of connections is set to a hard
378
minimum of at least two connections per torrent, so if you set a too low
379
connections limit, and open too many torrents, the limit will not be met. The
380
number of uploads is at least one per torrent.
383
num_uploads() num_connections()
384
-------------------------------
388
int num_uploads() const;
389
int num_connections() const;
391
Returns the number of currently unchoked peers and the number of connections
392
(including half-open ones) respectively.
395
set_max_half_open_connections() max_half_open_connections()
396
-----------------------------------------------------------
400
void set_max_half_open_connections(int limit);
401
int max_half_open_connections() const;
403
Sets the maximum number of half-open connections libtorrent will have when
404
connecting to peers. A half-open connection is one where connect() has been
405
called, but the connection still hasn't been established (nor failed). Windows
406
XP Service Pack 2 sets a default, system wide, limit of the number of half-open
407
connections to 10. So, this limit can be used to work nicer together with
408
other network applications on that system. The default is to have no limit,
409
and passing -1 as the limit, means to have no limit. When limiting the number
410
of simultaneous connection attempts, peers will be put in a queue waiting for
411
their turn to get connected.
413
``max_half_open_connections()`` returns the set limit. This limit defaults
422
void set_ip_filter(ip_filter const& filter);
424
Sets a filter that will be used to reject and accept incoming as well as outgoing
425
connections based on their originating ip address. The default filter will allow
426
connections to any ip address. To build a set of rules for which addresses are
427
accepted and not, see ip_filter_.
429
Each time a peer is blocked because of the IP filter, a peer_blocked_alert_ is
438
session_status status() const;
440
``status()`` returns session wide-statistics and status. The ``session_status``
441
struct has the following members::
443
struct session_status
445
bool has_incoming_connections;
450
float payload_upload_rate;
451
float payload_download_rate;
453
size_type total_download;
454
size_type total_upload;
456
size_type total_payload_download;
457
size_type total_payload_upload;
464
int dht_global_nodes;
467
``has_incoming_connections`` is false as long as no incoming connections have been
468
established on the listening socket. Every time you change the listen port, this will
471
``upload_rate``, ``download_rate``, ``payload_download_rate`` and ``payload_upload_rate``
472
are the total download and upload rates accumulated from all torrents. The payload
473
versions is the payload download only.
475
``total_download`` and ``total_upload`` are the total number of bytes downloaded and
476
uploaded to and from all torrents. ``total_payload_download`` and ``total_payload_upload``
477
are the same thing but where only the payload is considered.
479
``num_peers`` is the total number of peer connections this session has. This includes
480
incoming connections that still hasn't sent their handshake or outgoing connections
481
that still hasn't completed the TCP connection. This number may be slightly higher
482
than the sum of all peers of all torrents because the incoming connections may not
483
be assigned a torrent yet.
485
``dht_nodes``, ``dht_cache_nodes`` and ``dht_torrents`` are only available when
486
built with DHT support. They are all set to 0 if the DHT isn't running. When
487
the DHT is running, ``dht_nodes`` is set to the number of nodes in the routing
488
table. This number only includes *active* nodes, not cache nodes. The
489
``dht_cache_nodes`` is set to the number of nodes in the node cache. These nodes
490
are used to replace the regular nodes in the routing table in case any of them
491
becomes unresponsive.
493
``dht_torrents`` are the number of torrents tracked by the DHT at the moment.
495
``dht_global_nodes`` is an estimation of the total number of nodes in the DHT
498
is_listening() listen_port() listen_on()
499
----------------------------------------
503
bool is_listening() const;
504
unsigned short listen_port() const;
506
std::pair<int, int> const& port_range
507
, char const* interface = 0);
509
``is_listening()`` will tell you whether or not the session has successfully
510
opened a listening port. If it hasn't, this function will return false, and
511
then you can use ``listen_on()`` to make another try.
513
``listen_port()`` returns the port we ended up listening on. Since you just pass
514
a port-range to the constructor and to ``listen_on()``, to know which port it
515
ended up using, you have to ask the session using this function.
517
``listen_on()`` will change the listen port and/or the listen interface. If the
518
session is already listening on a port, this socket will be closed and a new socket
519
will be opened with these new settings. The port range is the ports it will try
520
to listen on, if the first port fails, it will continue trying the next port within
521
the range and so on. The interface parameter can be left as 0, in that case the
522
os will decide which interface to listen on, otherwise it should be the ip-address
523
of the interface you want the listener socket bound to. ``listen_on()`` returns true
524
if it managed to open the socket, and false if it failed. If it fails, it will also
525
generate an appropriate alert (listen_failed_alert_).
527
The interface parameter can also be a hostname that will resolve to the device you
530
If you're also starting the DHT, it is a good idea to do that after you've called
531
``listen_on()``, since the default listen port for the DHT is the same as the tcp
532
listen socket. If you start the DHT first, it will assume the tcp port is free and
533
open the udp socket on that port, then later, when ``listen_on()`` is called, it
534
may turn out that the tcp port is in use. That results in the DHT and the bittorrent
535
socket listening on different ports. If the DHT is active when ``listen_on`` is
536
called, the udp port will be rebound to the new port, if it was configured to use
537
the same port as the tcp socket, and if the listen_on call failed to bind to the
538
same port that the udp uses.
540
The reason why it's a good idea to run the DHT and the bittorrent socket on the same
541
port is because that is an assumption that may be used to increase performance. One
542
way to accelerate the connecting of peers on windows may be to first ping all peers
543
with a DHT ping packet, and connect to those that responds first. On windows one
544
can only connect to a few peers at a time because of a built in limitation (in XP
547
pop_alert() set_severity_level() wait_for_alert()
548
-------------------------------------------------
552
std::auto_ptr<alert> pop_alert();
553
alert const* wait_for_alert(time_duration max_wait);
554
void set_severity_level(alert::severity_t s);
556
``pop_alert()`` is used to ask the session if any errors or events has occurred. With
557
``set_severity_level()`` you can filter how serious the event has to be for you to
558
receive it through ``pop_alert()``. For information, see alerts_.
560
``wait_for_alert`` blocks until an alert is available, or for no more than ``max_wait``
561
time. If ``wait_for_alert`` returns because of the time-out, and no alerts are available,
562
it returns 0. If at least one alert was generated, a pointer to that alert is returned.
563
The alert is not popped, any subsequent calls to ``wait_for_alert`` will return the
564
same pointer until the alert is popped by calling ``pop_alert``. This is useful for
565
leaving any alert dispatching mechanism independent of this blocking call, the dispatcher
566
can be called and it can pop the alert independently.
574
void add_extension(boost::function<
575
boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext);
577
This function adds an extension to this session. The argument is a function
578
object that is called with a ``torrent*`` and which should return a
579
``boost::shared_ptr<torrent_plugin>``. To write custom plugins, see
580
`libtorrent plugins`_. The main plugins implemented in libtorrent are:
583
Allows peers to download the metadata (.torren files) from the swarm
584
directly. Makes it possible to join a swarm with just a tracker and
587
uTorrent peer exchange
588
Exchanges peers between clients.
590
To use these, imclude ``<libtorrent/extensions/metadata_transfer.hpp>``
591
or ``<libtorrent/extensions/ut_pex.hpp>``. The functions to pass in to
592
``add_extension()`` are ``libtorrent::create_metadata_plugin`` and
593
``libtorrent::create_ut_pex_plugin`` respectively.
599
ses.add_extension(&libtorrent::create_metadata_plugin);
600
ses.add_extension(&libtorrent::create_ut_pex_plugin);
602
.. _`libtorrent plugins`: libtorrent_plugins.html
604
set_settings() set_pe_settings()
605
--------------------------------
609
void set_settings(session_settings const& settings);
610
void set_pe_settings(pe_settings const& settings);
612
Sets the session settings and the packet encryption settings respectively.
613
See session_settings_ and pe_settings_ for more information on available
617
set_peer_proxy() set_web_seed_proxy() set_tracker_proxy() set_dht_proxy()
618
-------------------------------------------------------------------------
622
void set_peer_proxy(proxy_settings const& s);
623
void set_web_seed_proxy(proxy_settings const& s);
624
void set_tracker_proxy(proxy_settings const& s);
625
void set_dht_proxy(proxy_settings const& s);
627
The ``set_dht_proxy`` is not available when DHT is disabled. These functions
628
sets the proxy settings for different kinds of connections, bittorrent peers,
629
web seeds, trackers and the DHT traffic.
631
``set_peer_proxy`` affects regular bittorrent peers. ``set_web_seed_proxy``
632
affects only web seeds. see `HTTP seeding`_.
634
``set_tracker_proxy`` only affects HTTP tracker connections (UDP tracker
635
connections are affected if the given proxy supports UDP, e.g. SOCKS5).
637
``set_dht_proxy`` affects the DHT messages. Since they are sent over UDP,
638
it only has any effect if the proxy supports UDP.
640
For more information on what settings are available for proxies, see
644
peer_proxy() web_seed_proxy() tracker_proxy() dht_proxy()
645
---------------------------------------------------------
649
proxy_settings const& peer_proxy() const;
650
proxy_settings const& web_seed_proxy() const;
651
proxy_settings const& tracker_proxy() const;
652
proxy_settings const& dht_proxy() const;
654
These functions returns references to their respective current settings.
656
The ``dht_proxy`` is not available when DHT is disabled.
659
start_dht() stop_dht() set_dht_settings() dht_state()
660
-----------------------------------------------------
664
void start_dht(entry const& startup_state);
666
void set_dht_settings(dht_settings const& settings);
667
entry dht_state() const;
669
These functions are not available in case ``TORRENT_DISABLE_DHT`` is
670
defined. ``start_dht`` starts the dht node and makes the trackerless service
671
available to torrents. The startup state is optional and can contain nodes
672
and the node id from the previous session. The dht node state is a bencoded
673
dictionary with the following entries:
676
A list of strings, where each string is a node endpoint encoded in binary. If
677
the string is 6 bytes long, it is an IPv4 address of 4 bytes, encoded in
678
network byte order (big endian), followed by a 2 byte port number (also
679
network byte order). If the string is 18 bytes long, it is 16 bytes of IPv6
680
address followed by a 2 bytes port number (also network byte order).
683
The node id written as a readable string as a hexadecimal number.
685
``dht_state`` will return the current state of the dht node, this can be used
686
to start up the node again, passing this entry to ``start_dht``. It is a good
687
idea to save this to disk when the session is closed, and read it up again
690
If the port the DHT is supposed to listen on is already in use, and exception
691
is thrown, ``asio::error``.
693
``stop_dht`` stops the dht node.
695
``add_dht_node`` adds a node to the routing table. This can be used if your
696
client has its own source of bootstrapping nodes.
698
``set_dht_settings`` sets some parameters availavle to the dht node. The
699
struct has the following members::
704
int search_branching;
709
``max_peers_reply`` is the maximum number of peers the node will send in
710
response to a ``get_peers`` message from another node.
712
``search_branching`` is the number of concurrent search request the node will
713
send when announcing and refreshing the routing table. This parameter is
714
called alpha in the kademlia paper.
716
``service_port`` is the udp port the node will listen to. This will default
717
to 0, which means the udp listen port will be the same as the tcp listen
718
port. This is in general a good idea, since some NAT implementations
719
reserves the udp port for any mapped tcp port, and vice versa. NAT-PMP
720
guarantees this for example.
722
``max_fail_count`` is the maximum number of failed tries to contact a node
723
before it is removed from the routing table. If there are known working nodes
724
that are ready to replace a failing node, it will be replaced immediately,
725
this limit is only used to clear out nodes that don't have any node that can
729
add_dht_node() add_dht_router()
730
-------------------------------
734
void add_dht_node(std::pair<std::string, int> const& node);
735
void add_dht_router(std::pair<std::string, int> const& node);
737
``add_dht_node`` takes a host name and port pair. That endpoint will be
738
pinged, and if a valid DHT reply is received, the node will be added to
741
``add_dht_router`` adds the given endpoint to a list of DHT router nodes.
742
If a search is ever made while the routing table is empty, those nodes will
743
be used as backups. Nodes in the router node list will also never be added
744
to the regular routing table, which effectively means they are only used
745
for bootstrapping, to keep the load off them.
747
An example routing node that you could typically add is
748
``router.bittorrent.com``.
751
start_lsd() stop_lsd()
752
----------------------
759
Starts and stops Local Service Discovery. This service will broadcast
760
the infohashes of all the non-private torrents on the local network to
761
look for peers on the same swarm within multicast reach.
763
It is turned off by default.
765
start_upnp() stop_upnp()
766
------------------------
773
Starts and stops the UPnP service. When started, the listen port and the DHT
774
port are attempted to be forwarded on local UPnP router devices.
776
It is off by default.
778
start_natpmp() stop_natpmp()
779
----------------------------
786
Starts and stops the NAT-PMP service. When started, the listen port and the DHT
787
port are attempted to be forwarded on the router through NAT-PMP.
789
It is off by default.
795
The ``entry`` class represents one node in a bencoded hierarchy. It works as a
796
variant type, it can be either a list, a dictionary (``std::map``), an integer
797
or a string. This is its synopsis::
803
typedef std::map<std::string, entry> dictionary_type;
804
typedef std::string string_type;
805
typedef std::list<entry> list_type;
806
typedef size_type integer_type;
817
data_type type() const;
819
entry(dictionary_type const&);
820
entry(string_type const&);
821
entry(list_type const&);
822
entry(integer_type const&);
826
entry(entry const& e);
829
void operator=(entry const& e);
830
void operator=(dictionary_type const&);
831
void operator=(string_type const&);
832
void operator=(list_type const&);
833
void operator=(integer_type const&);
835
integer_type& integer();
836
integer_type const& integer() const;
837
string_type& string();
838
string_type const& string() const;
840
list_type const& list() const;
841
dictionary_type& dict();
842
dictionary_type const& dict() const;
844
// these functions requires that the entry
845
// is a dictionary, otherwise they will throw
846
entry& operator[](char const* key);
847
entry& operator[](std::string const& key);
848
entry const& operator[](char const* key) const;
849
entry const& operator[](std::string const& key) const;
850
entry* find_key(char const* key);
851
entry const* find_key(char const* key) const;
853
void print(std::ostream& os, int indent = 0) const;
856
*TODO: finish documentation of entry.*
858
integer() string() list() dict() type()
859
---------------------------------------
863
integer_type& integer();
864
integer_type const& integer() const;
865
string_type& string();
866
string_type const& string() const;
868
list_type const& list() const;
869
dictionary_type& dict();
870
dictionary_type const& dict() const;
872
The ``integer()``, ``string()``, ``list()`` and ``dict()`` functions
873
are accessors that return the respective type. If the ``entry`` object isn't of the
874
type you request, the accessor will throw type_error_ (which derives from
875
``std::runtime_error``). You can ask an ``entry`` for its type through the
878
The ``print()`` function is there for debug purposes only.
880
If you want to create an ``entry`` you give it the type you want it to have in its
881
constructor, and then use one of the non-const accessors to get a reference which you then
882
can assign the value you want it to have.
884
The typical code to get info from a torrent file will then look like this::
889
// throws if this is not a dictionary
890
entry::dictionary_type const& dict = torrent_file.dict();
891
entry::dictionary_type::const_iterator i;
892
i = dict.find("announce");
895
std::string tracker_url = i->second.string();
896
std::cout << tracker_url << "\n";
900
The following code is equivalent, but a little bit shorter::
905
// throws if this is not a dictionary
906
if (entry* i = torrent_file.find_key("announce"))
908
std::string tracker_url = i->string();
909
std::cout << tracker_url << "\n";
913
To make it easier to extract information from a torrent file, the class torrent_info_
922
entry& operator[](char const* key);
923
entry& operator[](std::string const& key);
924
entry const& operator[](char const* key) const;
925
entry const& operator[](std::string const& key) const;
927
All of these functions requires the entry to be a dictionary, if it isn't they
928
will throw ``libtorrent::type_error``.
930
The non-const versions of the ``operator[]`` will return a reference to either
931
the existing element at the given key or, if there is no element with the
932
given key, a reference to a newly inserted element at that key.
934
The const version of ``operator[]`` will only return a reference to an
935
existing element at the given key. If the key is not found, it will throw
936
``libtorrent::type_error``.
944
entry* find_key(char const* key);
945
entry const* find_key(char const* key) const;
947
These functions requires the entry to be a dictionary, if it isn't they
948
will throw ``libtorrent::type_error``.
950
They will look for an element at the given key in the dictionary, if the
951
element cannot be found, they will return 0. If an element with the given
952
key is found, the return a pointer to it.
958
The ``torrent_info`` has the following synopsis::
965
torrent_info(sha1_hash const& info_hash);
966
torrent_info(entry const& torrent_file);
968
entry create_torrent() const;
969
void set_comment(char const* str);
970
void set_piece_size(int size);
971
void set_creator(char const* str);
972
void set_hash(int index, sha1_hash const& h);
973
void add_tracker(std::string const& url, int tier = 0);
974
void add_file(boost::filesystem::path file, size_type size);
975
void add_url_seed(std::string const& url);
977
typedef std::vector<file_entry>::const_iterator file_iterator;
978
typedef std::vector<file_entry>::const_reverse_iterator
979
reverse_file_iterator;
981
bool remap_files(std::vector<file_entry> const& map);
983
file_iterator begin_files(bool storage = false) const;
984
file_iterator end_files(bool storage = false) const;
985
reverse_file_iterator rbegin_files(bool storage = false) const;
986
reverse_file_iterator rend_files(bool storage = false) const;
988
int num_files(bool storage = false) const;
989
file_entry const& file_at(int index, bool storage = false) const;
991
std::vector<file_slice> map_block(int piece, size_type offset
992
, int size, bool storage = false) const;
993
peer_request map_file(int file_index, size_type file_offset
994
, int size, bool storage = false) const;
996
std::vector<announce_entry> const& trackers() const;
999
void set_priv(bool v);
1001
std::vector<std::string> const& url_seeds() const;
1003
size_type total_size() const;
1004
size_type piece_length() const;
1005
int num_pieces() const;
1006
sha1_hash const& info_hash() const;
1007
std::string const& name() const;
1008
std::string const& comment() const;
1009
std::string const& creator() const;
1011
std::vector<std::pair<std::string, int> > const& nodes() const;
1012
void add_node(std::pair<std::string, int> const& node);
1014
boost::optional<boost::posix_time::ptime>
1015
creation_date() const;
1017
void print(std::ostream& os) const;
1019
size_type piece_size(unsigned int index) const;
1020
sha1_hash const& hash_for_piece(unsigned int index) const;
1029
torrent_info(sha1_hash const& info_hash);
1030
torrent_info(entry const& torrent_file);
1032
The default constructor of ``torrent_info`` is used when creating torrent files. It will
1033
initialize the object to an empty torrent, containing no files. The info hash will be set
1034
to 0 when this constructor is used. To use the empty ``torrent_info`` object, add files
1035
and piece hashes, announce URLs and optionally a creator tag and comment. To do this you
1036
use the members ``set_comment()``, ``set_piece_size()``, ``set_creator()``, ``set_hash()``
1039
The constructor that takes an info-hash is identical to the default constructor with the
1040
exception that it will initialize the info-hash to the given value. This is used internally
1041
when downloading torrents without the metadata. The metadata will be created by libtorrent
1042
as soon as it has been downloaded from the swarm.
1044
The last constructor is the one that is used in most cases. It will create a ``torrent_info``
1045
object from the information found in the given torrent_file. The ``entry`` represents a tree
1046
node in an bencoded file. To load an ordinary .torrent file into an ``entry``, use bdecode(),
1047
see `bdecode() bencode()`_.
1049
set_comment() set_piece_size() set_creator() set_hash() add_tracker() add_file()
1050
--------------------------------------------------------------------------------
1054
void set_comment(char const* str);
1055
void set_piece_size(int size);
1056
void set_creator(char const* str);
1057
void set_hash(int index, sha1_hash const& h);
1058
void add_tracker(std::string const& url, int tier = 0);
1059
void add_file(boost::filesystem::path file, size_type size);
1061
These files are used when creating a torrent file. ``set_comment()`` will simply set
1062
the comment that belongs to this torrent. The comment can be retrieved with the
1063
``comment()`` member. The string should be UTF-8 encoded.
1065
``set_piece_size()`` will set the size of each piece in this torrent. The piece size must
1066
be an even multiple of 2. i.e. usually something like 256 kiB, 512 kiB, 1024 kiB etc. The
1067
size is given in number of bytes.
1069
``set_creator()`` is an optional attribute that can be used to identify your application
1070
that was used to create the torrent file. The string should be UTF-8 encoded.
1072
``set_hash()`` writes the hash for the piece with the given piece-index. You have to call
1073
this function for every piece in the torrent. Usually the hasher_ is used to calculate
1074
the sha1-hash for a piece.
1076
``add_tracker()`` adds a tracker to the announce-list. The ``tier`` determines the order in
1077
which the trackers are to be tried. For more information see `trackers()`_.
1079
``add_file()`` adds a file to the torrent. The order in which you add files will determine
1080
the order in which they are placed in the torrent file. You have to add at least one file
1081
to the torrent. The ``path`` you give has to be a relative path from the root directory
1082
of the torrent. The ``size`` is given in bytes.
1084
When you have added all the files and hashes to your torrent, you can generate an ``entry``
1085
which then can be encoded as a .torrent file. You do this by calling `create_torrent()`_.
1087
For a complete example of how to create a torrent from a file structure, see make_torrent_.
1095
entry create_torrent();
1097
Returns an ``entry`` representing the bencoded tree of data that makes up a .torrent file.
1098
You can save this data as a torrent file with bencode() (see `bdecode() bencode()`_), for a
1099
complete example, see make_torrent_.
1101
.. _make_torrent: examples.html#make_torrent
1103
This function is not const because it will also set the info-hash of the ``torrent_info``
1106
Note that a torrent file must include at least one file, and it must have at
1107
least one tracker url or at least one DHT node.
1115
bool remap_files(std::vector<file_entry> const& map);
1117
This call will create a new mapping of the data in this torrent to other files. The
1118
``torrent_info`` maintains 2 views of the file storage. One that is true to the torrent
1119
file, and one that represents what is actually saved on disk. This call will change
1120
what the files on disk are called.
1122
The each entry in the vector ``map`` is a ``file_entry``. The only fields in this struct
1123
that are used in this case are ``path``, ``size`` and ``file_base``.
1125
The return value indicates if the remap was successful or not. True means success and
1126
false means failure. The sum of all the files passed in through ``map`` has to be exactly
1127
the same as the total_size of the torrent. If the number of bytes that are mapped do not
1128
match, false will be returned (this is the only case this function may fail).
1130
Changing this mapping for an existing torrent will not move or rename files. If some files
1131
should be renamed, this can be done before the torrent is added.
1134
begin_files() end_files() rbegin_files() rend_files()
1135
-----------------------------------------------------
1139
file_iterator begin_files(bool storage = false) const;
1140
file_iterator end_files(bool storage = false) const;
1141
reverse_file_iterator rbegin_files(bool storage = false) const;
1142
reverse_file_iterator rend_files(bool storage = false) const;
1144
This class will need some explanation. First of all, to get a list of all files
1145
in the torrent, you can use ``begin_files()``, ``end_files()``,
1146
``rbegin_files()`` and ``rend_files()``. These will give you standard vector
1147
iterators with the type ``file_entry``.
1149
The ``storage`` parameter specifies which view of the files you want. The default
1150
is false, which means you will see the content of the torrent file. If set to
1151
true, you will see the file that the storage class uses to save the files to
1152
disk. Typically these views are the same, but in case the files have been
1153
remapped, they may differ. For more info, see `remap_files()`_.
1159
boost::filesystem::path path;
1162
size_type file_base;
1163
boost::shared_ptr<const boost::filesystem::path> orig_path;
1166
The ``path`` is the full (relative) path of each file. i.e. if it is a multi-file
1167
torrent, all the files starts with a directory with the same name as ``torrent_info::name()``.
1168
The filenames are encoded with UTF-8.
1170
``size`` is the size of the file (in bytes) and ``offset`` is the byte offset
1171
of the file within the torrent. i.e. the sum of all the sizes of the files
1172
before it in the list.
1174
``file_base`` is the offset in the file where the storage should start. The normal
1175
case is to have this set to 0, so that the storage starts saving data at the start
1176
if the file. In cases where multiple files are mapped into the same file though,
1177
the ``file_base`` should be set to an offset so that the different regions do
1178
not overlap. This is used when mapping "unselected" files into a so-called part
1181
``orig_path`` is set to 0 in case the path element is an exact copy of that
1182
found in the metadata. In case the path in the original metadata was
1183
incorrectly encoded, and had to be fixed in order to be acceptable utf-8,
1184
the original string is preserved in ``orig_path``. The reason to keep it
1185
is to be able to reproduce the info-section exactly, with the correct
1190
num_files() file_at()
1191
---------------------
1195
int num_files(bool storage = false) const;
1196
file_entry const& file_at(int index, bool storage = false) const;
1198
If you need index-access to files you can use the ``num_files()`` and ``file_at()``
1199
to access files using indices.
1202
The ``storage`` parameter specifies which view of the files you want. The default
1203
is false, which means you will see the content of the torrent file. If set to
1204
true, you will see the file that the storage class uses to save the files to
1205
disk. Typically these views are the same, but in case the files have been
1206
remapped, they may differ. For more info, see `remap_files()`_.
1214
std::vector<file_slice> map_block(int piece, size_type offset
1215
, int size, bool storage = false) const;
1217
This function will map a piece index, a byte offset within that piece and
1218
a size (in bytes) into the corresponding files with offsets where that data
1219
for that piece is supposed to be stored.
1221
The file slice struct looks like this::
1231
The ``file_index`` refers to the index of the file (in the torrent_info).
1232
To get the path and filename, use ``file_at()`` and give the ``file_index``
1233
as argument. The ``offset`` is the byte offset in the file where the range
1234
starts, and ``size`` is the number of bytes this range is. The size + offset
1235
will never be greater than the file size.
1237
The ``storage`` parameter specifies which view of the files you want. The default
1238
is false, which means you will see the content of the torrent file. If set to
1239
true, you will see the file that the storage class uses to save the files to
1240
disk. Typically these views are the same, but in case the files have been
1241
remapped, they may differ. For more info, see `remap_files()`_.
1249
peer_request map_file(int file_index, size_type file_offset
1250
, int size, bool storage = false) const;
1252
This function will map a range in a specific file into a range in the torrent.
1253
The ``file_offset`` parameter is the offset in the file, given in bytes, where
1254
0 is the start of the file.
1255
The ``peer_request`` structure looks like this::
1262
bool operator==(peer_request const& r) const;
1265
``piece`` is the index of the piece in which the range starts.
1266
``start`` is the offset within that piece where the range starts.
1267
``length`` is the size of the range, in bytes.
1269
The input range is assumed to be valid within the torrent. ``file_offset``
1270
+ ``size`` is not allowed to be greater than the file size. ``file_index``
1271
must refer to a valid file, i.e. it cannot be >= ``num_files()``.
1274
url_seeds() add_url_seed()
1275
--------------------------
1279
std::vector<std::string> const& url_seeds() const;
1280
void add_url_seed(std::string const& url);
1282
If there are any url-seeds in this torrent, ``url_seeds()`` will return a
1283
vector of those urls. If you're creating a torrent file, ``add_url_seed()``
1284
adds one url to the list of url-seeds. Currently, the only transport protocol
1285
supported for the url is http.
1287
The ``storage`` parameter specifies which view of the files you want. The default
1288
is false, which means you will see the content of the torrent file. If set to
1289
true, you will see the file that the storage class uses to save the files to
1290
disk. Typically these views are the same, but in case the files have been
1291
remapped, they may differ. For more info, see `remap_files()`_.
1293
See `HTTP seeding`_ for more information.
1301
void print(std::ostream& os) const;
1303
The ``print()`` function is there for debug purposes only. It will print the info from
1304
the torrent file to the given outstream. This function has been deprecated and will
1305
be removed from future releases.
1313
std::vector<announce_entry> const& trackers() const;
1315
The ``trackers()`` function will return a sorted vector of ``announce_entry``.
1316
Each announce entry contains a string, which is the tracker url, and a tier index. The
1317
tier index is the high-level priority. No matter which trackers that works or not, the
1318
ones with lower tier will always be tried before the one with higher tier number.
1322
struct announce_entry
1324
announce_entry(std::string const& url);
1330
total_size() piece_length() piece_size() num_pieces()
1331
-----------------------------------------------------
1335
size_type total_size() const;
1336
size_type piece_length() const;
1337
size_type piece_size(unsigned int index) const;
1338
int num_pieces() const;
1341
``total_size()``, ``piece_length()`` and ``num_pieces()`` returns the total
1342
number of bytes the torrent-file represents (all the files in it), the number of byte for
1343
each piece and the total number of pieces, respectively. The difference between
1344
``piece_size()`` and ``piece_length()`` is that ``piece_size()`` takes
1345
the piece index as argument and gives you the exact size of that piece. It will always
1346
be the same as ``piece_length()`` except in the case of the last piece, which may
1350
hash_for_piece() info_hash()
1351
----------------------------
1355
size_type piece_size(unsigned int index) const;
1356
sha1_hash const& hash_for_piece(unsigned int index) const;
1358
``hash_for_piece()`` takes a piece-index and returns the 20-bytes sha1-hash for that
1359
piece and ``info_hash()`` returns the 20-bytes sha1-hash for the info-section of the
1360
torrent file. For more information on the ``sha1_hash``, see the big_number_ class.
1361
``info_hash()`` will only return a valid hash if the torrent_info was read from a
1362
``.torrent`` file or if an ``entry`` was created from it (through ``create_torrent``).
1365
name() comment() creation_date() creator()
1366
------------------------------------------
1370
std::string const& name() const;
1371
std::string const& comment() const;
1372
boost::optional<boost::posix_time::ptime> creation_date() const;
1374
``name()`` returns the name of the torrent.
1376
``comment()`` returns the comment associated with the torrent. If there's no comment,
1377
it will return an empty string. ``creation_date()`` returns a `boost::posix_time::ptime`__
1378
object, representing the time when this torrent file was created. If there's no time stamp
1379
in the torrent file, this will return a date of January 1:st 1970.
1381
Both the name and the comment is UTF-8 encoded strings.
1383
``creator()`` returns the creator string in the torrent. If there is no creator string
1384
it will return an empty string.
1386
__ http://www.boost.org/doc/html/date_time/posix_time.html#date_time.posix_time.ptime_class
1395
void set_priv(bool v);
1397
``priv()`` returns true if this torrent is private. i.e., it should not be
1398
distributed on the trackerless network (the kademlia DHT).
1400
``set_priv()`` sets or clears the private flag on this torrent.
1408
std::vector<std::pair<std::string, int> > const& nodes() const;
1410
If this torrent contains any DHT nodes, they are put in this vector in their original
1411
form (host name and port number).
1419
void add_node(std::pair<std::string, int> const& node);
1421
This is used when creating torrent. Use this to add a known DHT node. It may
1422
be used, by the client, to bootstrap into the DHT network.
1428
You will usually have to store your torrent handles somewhere, since it's the
1429
object through which you retrieve information about the torrent and aborts the torrent.
1430
Its declaration looks like this::
1432
struct torrent_handle
1436
torrent_status status();
1437
void file_progress(std::vector<float>& fp);
1438
void get_download_queue(std::vector<partial_piece_info>& queue) const;
1439
void get_peer_info(std::vector<peer_info>& v) const;
1440
torrent_info const& get_torrent_info() const;
1441
bool is_valid() const;
1443
std::string name() const;
1445
entry write_resume_data() const;
1446
void force_reannounce() const;
1447
void force_reannounce(boost::posix_time::time_duration) const;
1448
void scrape_tracker() const;
1449
void connect_peer(asio::ip::tcp::endpoint const& adr, int source = 0) const;
1451
void set_tracker_login(std::string const& username
1452
, std::string const& password) const;
1454
std::vector<announce_entry> const& trackers() const;
1455
void replace_trackers(std::vector<announce_entry> const&);
1457
void add_url_seed(std::string const& url);
1458
void remove_url_seed(std::string const& url);
1459
std::set<std::string> url_seeds() const;
1461
void set_ratio(float ratio) const;
1462
void set_max_uploads(int max_uploads) const;
1463
void set_max_connections(int max_connections) const;
1464
void set_upload_limit(int limit) const;
1465
int upload_limit() const;
1466
void set_download_limit(int limit) const;
1467
int download_limit() const;
1468
void set_sequenced_download_threshold(int threshold) const;
1470
void set_peer_upload_limit(asio::ip::tcp::endpoint ip, int limit) const;
1471
void set_peer_download_limit(asio::ip::tcp::endpoint ip, int limit) const;
1473
void use_interface(char const* net_interface) const;
1476
void resume() const;
1477
bool is_paused() const;
1478
bool is_seed() const;
1480
void resolve_countries(bool r);
1481
bool resolve_countries() const;
1483
void piece_priority(int index, int priority) const;
1484
int piece_priority(int index) const;
1486
void prioritize_pieces(std::vector<int> const& pieces) const;
1487
std::vector<int> piece_priorities() const;
1489
void prioritize_files(std::vector<int> const& files) const;
1491
// these functions are deprecated
1492
void filter_piece(int index, bool filter) const;
1493
void filter_pieces(std::vector<bool> const& bitmask) const;
1494
bool is_piece_filtered(int index) const;
1495
std::vector<bool> filtered_pieces() const;
1496
void filter_files(std::vector<bool> const& files) const;
1498
bool has_metadata() const;
1500
boost::filesystem::path save_path() const;
1501
void move_storage(boost::filesystem::path const& save_path) const;
1503
sha1_hash info_hash() const;
1505
bool operator==(torrent_handle const&) const;
1506
bool operator!=(torrent_handle const&) const;
1507
bool operator<(torrent_handle const&) const;
1510
The default constructor will initialize the handle to an invalid state. Which
1511
means you cannot perform any operation on it, unless you first assign it a
1512
valid handle. If you try to perform any operation on an uninitialized handle,
1513
it will throw ``invalid_handle``.
1515
.. warning:: All operations on a ``torrent_handle`` may throw invalid_handle_
1516
exception, in case the handle is no longer refering to a torrent. There are
1517
two exceptions, ``info_hash()`` and ``is_valid()`` will never throw.
1518
Since the torrents are processed by a background thread, there is no
1519
guarantee that a handle will remain valid between two calls.
1522
piece_priority() prioritize_pieces() piece_priorities() prioritize_files()
1523
--------------------------------------------------------------------------
1527
void piece_priority(int index, int priority) const;
1528
int piece_priority(int index) const;
1529
void prioritize_pieces(std::vector<int> const& pieces) const;
1530
std::vector<int> piece_priorities() const;
1531
void prioritize_files(std::vector<int> const& files) const;
1533
These functions are used to set and get the prioritiy of individual pieces.
1534
By default all pieces have priority 1. That means that the random rarest
1535
first algorithm is effectively active for all pieces. You may however
1536
change the priority of individual pieces. There are 8 different priority
1539
0. piece is not downloaded at all
1540
1. normal priority. Download order is dependent on availability
1541
2. higher than normal priority. Pieces are preferred over pieces with
1542
the same availability, but not over pieces with lower availability
1543
3. pieces are as likely to be picked as partial pieces.
1544
4. pieces are preferred over partial pieces, but not over pieces with
1546
5. *currently the same as 4*
1547
6. piece is as likely to be picked as any piece with availability 1
1548
7. maximum priority, availability is disregarded, the piece is preferred
1549
over any other piece with lower priority
1551
The exact definitions of these priorities are implementation details, and
1552
subject to change. The interface guarantees that higher number means higher
1553
priority, and that 0 means do not download.
1555
``piece_priority`` sets or gets the priority for an individual piece,
1556
specified by ``index``.
1558
``prioritize_pieces`` takes a vector of integers, one integer per piece in
1559
the torrent. All the piece priorities will be updated with the priorities
1562
``piece_priorities`` returns a vector with one element for each piece in the
1563
torrent. Each element is the current priority of that piece.
1565
``prioritize_files`` takes a vector that has at as many elements as there are
1566
files in the torrent. Each entry is the priority of that file. The function
1567
sets the priorities of all the pieces in the torrent based on the vector.
1575
void file_progress(std::vector<float>& fp);
1577
This function fills in the supplied vector with the progress (a value in the
1578
range [0, 1]) describing the download progress of each file in this torrent.
1579
The progress values are ordered the same as the files in the `torrent_info`_.
1580
This operation is not very cheap.
1588
boost::filesystem::path save_path() const;
1590
``save_path()`` returns the path that was given to `add_torrent()`_ when this torrent
1598
void move_storage(boost::filesystem::path const& save_path) const;
1600
Moves the file(s) that this torrent are currently seeding from or downloading to. This
1601
operation will only have the desired effect if the given ``save_path`` is located on
1602
the same drive as the original save path. Since disk IO is performed in a separate
1603
thread, this operation is also asynchronous. Once the operation completes, the
1604
``storage_moved_alert`` is generated, with the new path as the message.
1611
void force_reannounce() const;
1612
void force_reannounce(boost::posix_time::time_duration) const;
1614
``force_reannounce()`` will force this torrent to do another tracker request, to receive new
1615
peers. The second overload of ``force_reannounce`` that takes a ``time_duration`` as
1616
argument will schedule a reannounce in that amount of time from now.
1623
void scrape_tracker() const;
1625
``scrape_tracker()`` will send a scrape request to the tracker. A scrape request queries the
1626
tracker for statistics such as total number of incomplete peers, complete peers, number of
1629
This request will specifically update the ``num_complete`` and ``num_incomplete`` fields in
1630
the torrent_status_ struct once it completes. When it completes, it will generate a
1631
scrape_reply_alert_. If it fails, it will generate a scrape_failed_alert_.
1638
void connect_peer(asio::ip::tcp::endpoint const& adr, int source = 0) const;
1640
``connect_peer()`` is a way to manually connect to peers that one believe is a part of the
1641
torrent. If the peer does not respond, or is not a member of this torrent, it will simply
1642
be disconnected. No harm can be done by using this other than an unnecessary connection
1643
attempt is made. If the torrent is uninitialized or in queued or checking mode, this
1644
will throw invalid_handle_. The second (optional) argument will be bitwised ORed into
1645
the source mask of this peer. Typically this is one of the source flags in peer_info_.
1646
i.e. ``tracker``, ``pex``, ``dht`` etc.
1654
std::string name() const;
1656
Returns the name of the torrent. i.e. the name from the metadata associated with it. In
1657
case the torrent was started without metadata, and hasn't completely received it yet,
1658
it returns the name given to it when added to the session. See ``session::add_torrent``.
1666
void set_ratio(float ratio) const;
1668
``set_ratio()`` sets the desired download / upload ratio. If set to 0, it is considered being
1669
infinite. i.e. the client will always upload as much as it can, no matter how much it gets back
1670
in return. With this setting it will work much like the standard clients.
1672
Besides 0, the ratio can be set to any number greater than or equal to 1. It means how much to
1673
attempt to upload in return for each download. e.g. if set to 2, the client will try to upload
1674
2 bytes for every byte received. The default setting for this is 0, which will make it work
1675
as a standard client.
1678
set_upload_limit() set_download_limit() upload_limit() download_limit()
1679
-----------------------------------------------------------------------
1683
void set_upload_limit(int limit) const;
1684
void set_download_limit(int limit) const;
1685
int upload_limit() const;
1686
int download_limit() const;
1688
``set_upload_limit`` will limit the upload bandwidth used by this particular torrent to the
1689
limit you set. It is given as the number of bytes per second the torrent is allowed to upload.
1690
``set_download_limit`` works the same way but for download bandwidth instead of upload bandwidth.
1691
Note that setting a higher limit on a torrent then the global limit (``session::set_upload_rate_limit``)
1692
will not override the global rate limit. The torrent can never upload more than the global rate
1695
``upload_limit`` and ``download_limit`` will return the current limit setting, for upload and
1696
download, respectively.
1699
set_sequenced_download_threshold()
1700
----------------------------------
1704
void set_sequenced_download_threshold(int threshold);
1706
sequenced-download threshold is the limit on how popular a piece has to be
1707
(popular == inverse of rarity) to be downloaded in sequence instead of in
1708
random (rarest first) order. It can be used to tweak disk performance in
1709
settings where the random download property is less necessary. For example, if
1710
the threshold is 10, all pieces which 10 or more peers have, will be downloaded
1711
in index order. This setting defaults to 100, which means that it is disabled
1714
Setting this threshold to a very small value will affect the piece distribution
1715
negatively in the swarm. It should basically only be used in situations where
1716
the random seeks on the disk is the download bottleneck.
1719
set_peer_upload_limit() set_peer_download_limit()
1720
-------------------------------------------------
1724
void set_peer_upload_limit(asio::ip::tcp::endpoint ip, int limit) const;
1725
void set_peer_download_limit(asio::ip::tcp::endpoint ip, int limit) const;
1727
Works like ``set_upload_limit`` and ``set_download_limit`` respectively, but controls individual
1728
peer instead of the whole torrent.
1730
pause() resume() is_paused()
1731
----------------------------
1736
void resume() const;
1737
bool is_paused() const;
1739
``pause()``, and ``resume()`` will disconnect all peers and reconnect all peers respectively.
1740
When a torrent is paused, it will however remember all share ratios to all peers and remember
1741
all potential (not connected) peers. You can use ``is_paused()`` to determine if a torrent
1742
is currently paused. Torrents may be paused automatically if there is a file error (e.g. disk full)
1743
or something similar. See file_error_alert_.
1750
void resolve_countries(bool r);
1751
bool resolve_countries() const;
1753
Sets or gets the flag that derermines if countries should be resolved for the peers of this
1754
torrent. It defaults to false. If it is set to true, the peer_info_ structure for the peers
1755
in this torrent will have their ``country`` member set. See peer_info_ for more information
1756
on how to interpret this field.
1763
bool is_seed() const;
1765
Returns true if the torrent is in seed mode (i.e. if it has finished downloading).
1773
bool has_metadata() const;
1775
Returns true if this torrent has metadata (either it was started from a .torrent file or the
1776
metadata has been downloaded). The only scenario where this can return false is when the torrent
1777
was started torrent-less (i.e. with just an info-hash and tracker ip). Note that if the torrent
1778
doesn't have metadata, the member `get_torrent_info()`_ will throw.
1785
void set_tracker_login(std::string const& username
1786
, std::string const& password) const;
1788
``set_tracker_login()`` sets a username and password that will be sent along in the HTTP-request
1789
of the tracker announce. Set this if the tracker requires authorization.
1792
trackers() replace_trackers()
1793
-----------------------------
1797
std::vector<announce_entry> const& trackers() const;
1798
void replace_trackers(std::vector<announce_entry> const&) const;
1800
``trackers()`` will return the list of trackers for this torrent. The
1801
announce entry contains both a string ``url`` which specify the announce url
1802
for the tracker as well as an int ``tier``, which is specifies the order in
1803
which this tracker is tried. If you want libtorrent to use another list of
1804
trackers for this torrent, you can use ``replace_trackers()`` which takes
1805
a list of the same form as the one returned from ``trackers()`` and will
1806
replace it. If you want an immediate effect, you have to call
1807
`force_reannounce()`_.
1810
add_url_seed() remove_url_seed() url_seeds()
1811
--------------------------------------------
1815
void add_url_seed(std::string const& url);
1816
void remove_url_seed(std::string const& url);
1817
std::set<std::string> url_seeds() const;
1819
``add_url_seed()`` adds another url to the torrent's list of url seeds. If the
1820
given url already exists in that list, the call has no effect. The torrent
1821
will connect to the server and try to download pieces from it, unless it's
1822
paused, queued, checking or seeding. ``remove_url_seed()`` removes the given
1823
url if it exists already. ``url_seeds()`` return a set of the url seeds
1824
currently in this torrent. Note that urls that fails may be removed
1825
automatically from the list.
1827
See `HTTP seeding`_ for more information.
1835
void use_interface(char const* net_interface) const;
1837
``use_interface()`` sets the network interface this torrent will use when it opens outgoing
1838
connections. By default, it uses the same interface as the session_ uses to listen on. The
1839
parameter must be a string containing an ip-address (either an IPv4 or IPv6 address). If
1840
the string does not conform to this format and exception is thrown.
1848
sha1_hash info_hash() const;
1850
``info_hash()`` returns the info-hash for the torrent.
1853
set_max_uploads() set_max_connections()
1854
---------------------------------------
1858
void set_max_uploads(int max_uploads) const;
1859
void set_max_connections(int max_connections) const;
1861
``set_max_uploads()`` sets the maximum number of peers that's unchoked at the same time on this
1862
torrent. If you set this to -1, there will be no limit.
1864
``set_max_connections()`` sets the maximum number of connection this torrent will open. If all
1865
connections are used up, incoming connections may be refused or poor connections may be closed.
1866
This must be at least 2. The default is unlimited number of connections. If -1 is given to the
1867
function, it means unlimited.
1875
entry write_resume_data() const;
1877
``write_resume_data()`` generates fast-resume data and returns it as an entry_. This entry_
1878
is suitable for being bencoded. For more information about how fast-resume works, see `fast resume`_.
1880
There are three cases where this function will just return an empty ``entry``:
1882
1. The torrent handle is invalid.
1883
2. The torrent is checking (or is queued for checking) its storage, it will obviously
1884
not be ready to write resume data.
1885
3. The torrent hasn't received valid metadata and was started without metadata
1886
(see libtorrent's `metadata from peers`_ extension)
1888
Note that by the time this function returns, the resume data may already be invalid if the torrent
1889
is still downloading! The recommended practice is to first pause the torrent, then generate the
1890
fast resume data, and then close it down. Since the disk IO is done in a separate thread, in order
1891
to synchronize, you shoule to wait for the ``torrent_paused_alert`` before you write the resume
1894
In full allocation mode the reume data is never invalidated by subsequent
1895
writes to the files, since pieces won't move around. This means that you don't need to
1896
pause before writing resume data in full or sparse mode. If you don't, however, any data written to
1897
disk after you saved resume data and before the session closed is lost.
1899
It also means that if the resume data is out dated, libtorrent will not re-check the files, but assume
1900
that it is fairly recent. The assumption is that it's better to loose a little bit than to re-check
1903
It is still a good idea to save resume data periodically during download as well as when
1912
torrent_status status() const;
1914
``status()`` will return a structure with information about the status of this
1915
torrent. If the torrent_handle_ is invalid, it will throw invalid_handle_ exception.
1916
See torrent_status_.
1919
get_download_queue()
1920
--------------------
1924
void get_download_queue(std::vector<partial_piece_info>& queue) const;
1926
``get_download_queue()`` takes a non-const reference to a vector which it will fill with
1927
information about pieces that are partially downloaded or not downloaded at all but partially
1928
requested. The entry in the vector (``partial_piece_info``) looks like this::
1930
struct partial_piece_info
1933
int blocks_in_piece;
1934
block_info blocks[256];
1935
enum state_t { none, slow, medium, fast };
1936
state_t piece_state;
1939
``piece_index`` is the index of the piece in question. ``blocks_in_piece`` is the
1940
number of blocks in this particular piece. This number will be the same for most pieces, but
1941
the last piece may have fewer blocks than the standard pieces.
1943
``piece_state`` is set to either ``fast``, ``medium``, ``slow`` or ``none``. It tells which
1944
download rate category the peers downloading this piece falls into. ``none`` means that no
1945
peer is currently downloading any part of the piece. Peers prefer picking pieces from
1946
the same category as themselves. The reason for this is to keep the number of partially
1947
downloaded pieces down. Pieces set to ``none`` can be converted into any of ``fast``,
1948
``medium`` or ``slow`` as soon as a peer want to download from it.
1955
{ none, requested, writing, finished };
1959
unsigned num_peers:14;
1963
The ``block_info`` array contains data for each individual block in the piece. Each block has
1964
a state (``state``) which is any of:
1966
* ``none`` - This block has not been downloaded or requested form any peer.
1967
* ``requested`` - The block has been requested, but not completely downloaded yet.
1968
* ``writing`` - The block has been downloaded and is currently queued for being written to disk.
1969
* ``finished`` - The block has been written to disk.
1971
The ``peer`` field is the ip address of the peer this block was downloaded from.
1972
``num_peers`` is the number of peers that is currently requesting this block. Typically this
1973
is 0 or 1, but at the end of the torrent blocks may be requested by more peers in parallel to
1981
void get_peer_info(std::vector<peer_info>&) const;
1983
``get_peer_info()`` takes a reference to a vector that will be cleared and filled
1984
with one entry for each peer connected to this torrent, given the handle is valid. If the
1985
torrent_handle_ is invalid, it will throw invalid_handle_ exception. Each entry in
1986
the vector contains information about that particular peer. See peer_info_.
1994
torrent_info const& get_torrent_info() const;
1996
Returns a const reference to the torrent_info_ object associated with this torrent.
1997
This reference is valid as long as the torrent_handle_ is valid, no longer. If the
1998
torrent_handle_ is invalid or if it doesn't have any metadata, invalid_handle_
1999
exception will be thrown. The torrent may be in a state without metadata only if
2000
it was started without a .torrent file, i.e. by using the libtorrent extension of
2001
just supplying a tracker and info-hash.
2009
bool is_valid() const;
2011
Returns true if this handle refers to a valid torrent and false if it hasn't been initialized
2012
or if the torrent it refers to has been aborted. Note that a handle may become invalid after
2013
it has been added to the session. Usually this is because the storage for the torrent is
2014
somehow invalid or if the filenames are not allowed (and hence cannot be opened/created) on
2015
your filesystem. If such an error occurs, a file_error_alert_ is generated and all handles
2016
that refers to that torrent will become invalid.
2018
*TODO: document storage*
2024
It contains the following fields::
2026
struct torrent_status
2030
queued_for_checking,
2032
connecting_to_tracker,
2033
downloading_metadata,
2043
boost::posix_time::time_duration next_announce;
2044
boost::posix_time::time_duration announce_interval;
2046
std::string current_tracker;
2048
size_type total_download;
2049
size_type total_upload;
2051
size_type total_payload_download;
2052
size_type total_payload_upload;
2054
size_type total_failed_bytes;
2055
size_type total_redundant_bytes;
2057
float download_rate;
2060
float download_payload_rate;
2061
float upload_payload_rate;
2071
const std::vector<bool>* pieces;
2074
size_type total_done;
2075
size_type total_wanted_done;
2076
size_type total_wanted;
2079
float distributed_copies;
2084
int num_connections;
2086
int connections_limit;
2088
storage_mode_t storage_mode;
2090
int up_bandwidth_queue;
2091
int down_bandwidth_queue;
2094
``progress`` is a value in the range [0, 1], that represents the progress of the
2095
torrent's current task. It may be checking files or downloading. The torrent's
2096
current task is in the ``state`` member, it will be one of the following:
2098
+--------------------------+----------------------------------------------------------+
2099
|``queued_for_checking`` |The torrent is in the queue for being checked. But there |
2100
| |currently is another torrent that are being checked. |
2101
| |This torrent will wait for its turn. |
2102
+--------------------------+----------------------------------------------------------+
2103
|``checking_files`` |The torrent has not started its download yet, and is |
2104
| |currently checking existing files. |
2105
+--------------------------+----------------------------------------------------------+
2106
|``connecting_to_tracker`` |The torrent has sent a request to the tracker and is |
2107
| |currently waiting for a response |
2108
+--------------------------+----------------------------------------------------------+
2109
|``downloading_metadata`` |The torrent is trying to download metadata from peers. |
2110
| |This assumes the metadata_transfer extension is in use. |
2111
+--------------------------+----------------------------------------------------------+
2112
|``downloading`` |The torrent is being downloaded. This is the state |
2113
| |most torrents will be in most of the time. The progress |
2114
| |meter will tell how much of the files that has been |
2116
+--------------------------+----------------------------------------------------------+
2117
|``finished`` |In this state the torrent has finished downloading but |
2118
| |still doesn't have the entire torrent. i.e. some pieces |
2119
| |are filtered and won't get downloaded. |
2120
+--------------------------+----------------------------------------------------------+
2121
|``seeding`` |In this state the torrent has finished downloading and |
2122
| |is a pure seeder. |
2123
+--------------------------+----------------------------------------------------------+
2124
|``allocating`` |If the torrent was started in full allocation mode, this |
2125
| |indicates that the (disk) storage for the torrent is |
2127
+--------------------------+----------------------------------------------------------+
2130
When downloading, the progress is ``total_wanted_done`` / ``total_wanted``.
2132
``paused`` is set to true if the torrent is paused and false otherwise.
2134
``next_announce`` is the time until the torrent will announce itself to the tracker. And
2135
``announce_interval`` is the time the tracker want us to wait until we announce ourself
2136
again the next time.
2138
``current_tracker`` is the URL of the last working tracker. If no tracker request has
2139
been successful yet, it's set to an empty string.
2141
``total_download`` and ``total_upload`` is the number of bytes downloaded and
2142
uploaded to all peers, accumulated, *this session* only.
2144
``total_payload_download`` and ``total_payload_upload`` counts the amount of bytes
2145
send and received this session, but only the actual payload data (i.e the interesting
2146
data), these counters ignore any protocol overhead.
2148
``total_failed_bytes`` is the number of bytes that has been downloaded and that
2149
has failed the piece hash test. In other words, this is just how much crap that
2150
has been downloaded.
2152
``total_redundant_bytes`` is the number of bytes that has been downloaded even
2153
though that data already was downloaded. The reason for this is that in some
2154
situations the same data can be downloaded by mistake. When libtorrent sends
2155
requests to a peer, and the peer doesn't send a response within a certain
2156
timeout, libtorrent will re-request that block. Another situation when
2157
libtorrent may re-request blocks is when the requests it sends out are not
2158
replied in FIFO-order (it will re-request blocks that are skipped by an out of
2159
order block). This is supposed to be as low as possible.
2161
``pieces`` is the bitmask that represents which pieces we have (set to true) and
2162
the pieces we don't have. It's a pointer and may be set to 0 if the torrent isn't
2163
downloading or seeding.
2165
``num_pieces`` is the number of pieces that has been downloaded. It is equivalent
2166
to: ``std::accumulate(pieces->begin(), pieces->end())``. So you don't have to
2167
count yourself. This can be used to see if anything has updated since last time
2168
if you want to keep a graph of the pieces up to date.
2170
``download_rate`` and ``upload_rate`` are the total rates for all peers for this
2171
torrent. These will usually have better precision than summing the rates from
2172
all peers. The rates are given as the number of bytes per second. The
2173
``download_payload_rate`` and ``upload_payload_rate`` respectively is the
2174
total transfer rate of payload only, not counting protocol chatter. This might
2175
be slightly smaller than the other rates, but if projected over a long time
2176
(e.g. when calculating ETA:s) the difference may be noticeable.
2178
``num_peers`` is the number of peers this torrent currently is connected to.
2179
Peer connections that are in the half-open state (is attempting to connect)
2180
or are queued for later connection attempt do not count. Although they are
2181
visible in the peer list when you call `get_peer_info()`_.
2183
``num_complete`` and ``num_incomplete`` are set to -1 if the tracker did not
2184
send any scrape data in its announce reply. This data is optional and may
2185
not be available from all trackers. If these are not -1, they are the total
2186
number of peers that are seeding (complete) and the total number of peers
2187
that are still downloading (incomplete) this torrent.
2189
``list_seeds`` and ``list_peers`` are the number of seeds in our peer list
2190
and the total number of peers (including seeds) respectively. We are not
2191
necessarily connected to all the peers in our peer list. This is the number
2192
of peers we know of in total, including banned peers and peers that we have
2193
failed to connect to.
2195
``total_done`` is the total number of bytes of the file(s) that we have. All
2196
this does not necessarily has to be downloaded during this session (that's
2197
``total_payload_download``).
2199
``total_wanted_done`` is the number of bytes we have downloaded, only counting the
2200
pieces that we actually want to download. i.e. excluding any pieces that we have but
2201
are filtered as not wanted.
2203
``total_wanted`` is the total number of bytes we want to download. This is also
2204
excluding pieces that have been filtered.
2206
``num_seeds`` is the number of peers that are seeding that this client is
2207
currently connected to.
2209
``distributed_copies`` is the number of distributed copies of the torrent.
2210
Note that one copy may be spread out among many peers. The integer part
2211
tells how many copies there are currently of the rarest piece(s) among the
2212
peers this client is connected to. The fractional part tells the share of
2213
pieces that have more copies than the rarest piece(s). For example: 2.5 would
2214
mean that the rarest pieces have only 2 copies among the peers this torrent is
2215
connected to, and that 50% of all the pieces have more than two copies.
2217
If we are a seed, the piece picker is deallocated as an optimization, and
2218
piece availability is no longer tracked. In this case the distributed
2219
copies is set to -1.
2221
``block_size`` is the size of a block, in bytes. A block is a sub piece, it
2222
is the number of bytes that each piece request asks for and the number of
2223
bytes that each bit in the ``partial_piece_info``'s bitset represents
2224
(see `get_download_queue()`_). This is typically 16 kB, but it may be
2225
larger if the pieces are larger.
2227
``num_uploads`` is the number of unchoked peers in this torrent.
2229
``num_connections`` is the number of peer connections this torrent has, including
2230
half-open connections that hasn't completed the bittorrent handshake yet. This is
2231
always <= ``num_peers``.
2233
``uploads_limit`` is the set limit of upload slots (unchoked peers) for this torrent.
2235
``connections_limit`` is the set limit of number of connections for this torrent.
2237
``storage_mode`` is one of ``storage_mode_allocate``, ``storage_mode_sparse`` or
2238
``storage_mode_compact``. Identifies which storage mode this torrent is being saved
2239
with. See `Storage allocation`_.
2241
``up_bandwidth_queue`` and ``down_bandwidth_queue`` are the number of peers in this
2242
torrent that are waiting for more bandwidth quota from the torrent rate limiter.
2243
This can determine if the rate you get from this torrent is bound by the torrents
2244
limit or not. If there is no limit set on this torrent, the peers might still be
2245
waiting for bandwidth quota from the global limiter, but then they are counted in
2246
the ``session_status`` object.
2252
It contains the following fields::
2260
remote_interested = 0x4,
2261
remote_choked = 0x8,
2262
supports_extensions = 0x10,
2263
local_connection = 0x20,
2269
optimistic_unchoke = 0x800,
2270
rc4_encrypted = 0x100000,
2271
plaintext_encrypted = 0x200000
2276
enum peer_source_flags
2286
asio::ip::tcp::endpoint ip;
2289
float payload_up_speed;
2290
float payload_down_speed;
2291
size_type total_download;
2292
size_type total_upload;
2294
std::vector<bool> pieces;
2298
time_duration last_request;
2299
time_duration last_active;
2301
int send_buffer_size;
2302
int used_send_buffer;
2308
size_type load_balancing;
2310
int download_queue_length;
2311
int upload_queue_length;
2315
int downloading_piece_index;
2316
int downloading_block_index;
2317
int downloading_progress;
2318
int downloading_total;
2324
standard_bittorrent = 0,
2327
int connection_type;
2330
The ``flags`` attribute tells you in which state the peer is. It is set to
2331
any combination of the enums above. The following table describes each flag:
2333
+-------------------------+-------------------------------------------------------+
2334
| ``interesting`` | **we** are interested in pieces from this peer. |
2335
+-------------------------+-------------------------------------------------------+
2336
| ``choked`` | **we** have choked this peer. |
2337
+-------------------------+-------------------------------------------------------+
2338
| ``remote_interested`` | the peer is interested in **us** |
2339
+-------------------------+-------------------------------------------------------+
2340
| ``remote_choked`` | the peer has choked **us**. |
2341
+-------------------------+-------------------------------------------------------+
2342
| ``support_extensions`` | means that this peer supports the |
2343
| | `extension protocol`__. |
2344
+-------------------------+-------------------------------------------------------+
2345
| ``local_connection`` | The connection was initiated by us, the peer has a |
2346
| | listen port open, and that port is the same as in the |
2347
| | address of this peer. If this flag is not set, this |
2348
| | peer connection was opened by this peer connecting to |
2350
+-------------------------+-------------------------------------------------------+
2351
| ``handshake`` | The connection is opened, and waiting for the |
2352
| | handshake. Until the handshake is done, the peer |
2353
| | cannot be identified. |
2354
+-------------------------+-------------------------------------------------------+
2355
| ``connecting`` | The connection is in a half-open state (i.e. it is |
2356
| | being connected). |
2357
+-------------------------+-------------------------------------------------------+
2358
| ``queued`` | The connection is currently queued for a connection |
2359
| | attempt. This may happen if there is a limit set on |
2360
| | the number of half-open TCP connections. |
2361
+-------------------------+-------------------------------------------------------+
2362
| ``on_parole`` | The peer has participated in a piece that failed the |
2363
| | hash check, and is now "on parole", which means we're |
2364
| | only requesting whole pieces from this peer until |
2365
| | it either fails that piece or proves that it doesn't |
2366
| | send bad data. |
2367
+-------------------------+-------------------------------------------------------+
2368
| ``seed`` | This peer is a seed (it has all the pieces). |
2369
+-------------------------+-------------------------------------------------------+
2370
| ``optimistic_unchoke`` | This peer is subject to an optimistic unchoke. It has |
2371
| | been unchoked for a while to see if it might unchoke |
2372
| | us in return an earn an upload/unchoke slot. If it |
2373
| | doesn't within some period of time, it will be choked |
2374
| | and another peer will be optimistically unchoked. |
2375
+-------------------------+-------------------------------------------------------+
2377
__ extension_protocol.html
2379
``source`` is a combination of flags describing from which sources this peer
2380
was received. The flags are:
2382
+------------------------+--------------------------------------------------------+
2383
| ``tracker`` | The peer was received from the tracker. |
2384
+------------------------+--------------------------------------------------------+
2385
| ``dht`` | The peer was received from the kademlia DHT. |
2386
+------------------------+--------------------------------------------------------+
2387
| ``pex`` | The peer was received from the peer exchange |
2389
+------------------------+--------------------------------------------------------+
2390
| ``lsd`` | The peer was received from the local service |
2391
| | discovery (The peer is on the local network). |
2392
+------------------------+--------------------------------------------------------+
2393
| ``resume_data`` | The peer was added from the fast resume data. |
2394
+------------------------+--------------------------------------------------------+
2396
The ``ip`` field is the IP-address to this peer. The type is an asio endpoint. For
2397
more info, see the asio_ documentation.
2399
.. _asio: http://asio.sf.net
2401
``up_speed`` and ``down_speed`` contains the current upload and download speed
2402
we have to and from this peer (including any protocol messages). The transfer rates
2403
of payload data only are found in ``payload_up_speed`` and ``payload_down_speed``.
2404
These figures are updated approximately once every second.
2406
``total_download`` and ``total_upload`` are the total number of bytes downloaded
2407
from and uploaded to this peer. These numbers do not include the protocol chatter, but only
2410
``pid`` is the peer's id as used in the bit torrent protocol. This id can be used to
2411
extract 'fingerprints' from the peer. Sometimes it can tell you which client the peer
2412
is using. See identify_client()_
2414
``pieces`` is a vector of booleans that has as many entries as there are pieces
2415
in the torrent. Each boolean tells you if the peer has that piece (if it's set to true)
2416
or if the peer miss that piece (set to false).
2418
``seed`` is true if this peer is a seed.
2420
``upload_limit`` is the number of bytes per second we are allowed to send to this
2421
peer every second. It may be -1 if there's no local limit on the peer. The global
2422
limit and the torrent limit is always enforced anyway.
2424
``download_limit`` is the number of bytes per second this peer is allowed to
2425
receive. -1 means it's unlimited.
2427
``last_request`` and ``last_active`` is the time since we last sent a request
2428
to this peer and since any transfer occurred with this peer, respectively.
2430
``send_buffer_size`` and ``used_send_buffer`` is the number of bytes allocated
2431
and used for the peer's send buffer, respectively.
2433
``num_hashfails`` is the number of pieces this peer has participated in
2434
sending us that turned out to fail the hash check.
2436
``country`` is the two letter `ISO 3166 country code`__ for the country the peer
2437
is connected from. If the country hasn't been resolved yet, both chars are set
2438
to 0. If the resolution failed for some reason, the field is set to "--". If the
2439
resolution service returns an invalid country code, it is set to "!!".
2440
The ``countries.nerd.dk`` service is used to look up countries. This field will
2441
remain set to 0 unless the torrent is set to resolve countries, see `resolve_countries()`_.
2443
__ http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
2445
``load_balancing`` is a measurement of the balancing of free download (that we get)
2446
and free upload that we give. Every peer gets a certain amount of free upload, but
2447
this member says how much *extra* free upload this peer has got. If it is a negative
2448
number it means that this was a peer from which we have got this amount of free
2451
``download_queue_length`` is the number of piece-requests we have sent to this peer
2452
that hasn't been answered with a piece yet.
2454
``upload_queue_length`` is the number of piece-requests we have received from this peer
2455
that we haven't answered with a piece yet.
2457
``failcount`` is the number of times this peer has "failed". i.e. failed to connect
2458
or disconnected us. The failcount is decremented when we see this peer in a tracker
2459
response or peer exchange message.
2461
You can know which piece, and which part of that piece, that is currently being
2462
downloaded from a specific peer by looking at the next four members.
2463
``downloading_piece_index`` is the index of the piece that is currently being downloaded.
2464
This may be set to -1 if there's currently no piece downloading from this peer. If it is
2465
>= 0, the other three members are valid. ``downloading_block_index`` is the index of the
2466
block (or sub-piece) that is being downloaded. ``downloading_progress`` is the number
2467
of bytes of this block we have received from the peer, and ``downloading_total`` is
2468
the total number of bytes in this block.
2470
``client`` is a string describing the software at the other end of the connection.
2471
In some cases this information is not available, then it will contain a string
2472
that may give away something about which software is running in the other end.
2473
In the case of a web seed, the server type and version will be a part of this
2476
``connection_type`` can currently be one of ``standard_bittorrent`` or
2477
``web_seed``. These are currently the only implemented protocols.
2482
You have some control over tracker requests through the ``session_settings`` object. You
2483
create it and fill it with your settings and then use ``session::set_settings()``
2484
to apply them. You have control over proxy and authorization settings and also the user-agent
2485
that will be sent to the tracker. The user-agent is a good way to identify your client.
2489
struct session_settings
2492
std::string user_agent;
2493
int tracker_completion_timeout;
2494
int tracker_receive_timeout;
2495
int stop_tracker_timeout;
2496
int tracker_maximum_response_length;
2499
float request_queue_time;
2500
int max_allowed_in_request_queue;
2501
int max_out_request_queue;
2502
int whole_pieces_threshold;
2504
int urlseed_timeout;
2505
int urlseed_pipeline_size;
2507
bool allow_multiple_connections_per_ip;
2509
int min_reconnect_time;
2510
int peer_connect_timeout;
2511
bool ignore_limits_on_local_network;
2512
int connection_speed;
2513
bool send_redundant_have;
2514
bool lazy_bitfields;
2515
int inactivity_timeout;
2516
int unchoke_interval;
2517
int optimistic_unchoke_multiplier;
2518
address announce_ip;
2520
int initial_picker_threshold;
2521
int allowed_fast_set_size;
2522
int max_outstanding_disk_bytes_per_connection;
2523
int handshake_timeout;
2524
bool use_dht_as_fallback;
2525
bool free_torrent_hashes;
2526
bool upnp_ignore_nonrouters;
2529
``user_agent`` this is the client identification to the tracker.
2530
The recommended format of this string is:
2531
"ClientName/ClientVersion libtorrent/libtorrentVersion".
2532
This name will not only be used when making HTTP requests, but also when
2533
sending extended headers to peers that support that extension.
2535
``tracker_completion_timeout`` is the number of seconds the tracker
2536
connection will wait from when it sent the request until it considers the
2537
tracker to have timed-out. Default value is 60 seconds.
2539
``tracker_receive_timeout`` is the number of seconds to wait to receive
2540
any data from the tracker. If no data is received for this number of
2541
seconds, the tracker will be considered as having timed out. If a tracker
2542
is down, this is the kind of timeout that will occur. The default value
2545
``stop_tracker_timeout`` is the time to wait for tracker responses when
2546
shutting down the session object. This is given in seconds. Default is
2549
``tracker_maximum_response_length`` is the maximum number of bytes in a
2550
tracker response. If a response size passes this number it will be rejected
2551
and the connection will be closed. On gzipped responses this size is measured
2552
on the uncompressed data. So, if you get 20 bytes of gzip response that'll
2553
expand to 2 megs, it will be interrupted before the entire response has been
2554
uncompressed (given your limit is lower than 2 megs). Default limit is
2557
``piece_timeout`` controls the number of seconds from a request is sent until
2558
it times out if no piece response is returned.
2560
``request_queue_time`` is the length of the request queue given in the number
2561
of seconds it should take for the other end to send all the pieces. i.e. the
2562
actual number of requests depends on the download rate and this number.
2564
``max_allowed_in_request_queue`` is the number of outstanding block requests
2565
a peer is allowed to queue up in the client. If a peer sends more requests
2566
than this (before the first one has been handled) the last request will be
2567
dropped. The higher this is, the faster upload speeds the client can get to a
2570
``max_out_request_queue`` is the maximum number of outstanding requests to
2571
send to a peer. This limit takes precedence over ``request_queue_time``. i.e.
2572
no matter the download speed, the number of outstanding requests will never
2575
``whole_pieces_threshold`` is a limit in seconds. if a whole piece can be
2576
downloaded in at least this number of seconds from a specific peer, the
2577
peer_connection will prefer requesting whole pieces at a time from this peer.
2578
The benefit of this is to better utilize disk caches by doing localized
2579
accesses and also to make it easier to identify bad peers if a piece fails
2582
``peer_timeout`` is the number of seconds the peer connection should
2583
wait (for any activity on the peer connection) before closing it due
2584
to time out. This defaults to 120 seconds, since that's what's specified
2585
in the protocol specification. After half the time out, a keep alive message
2588
``urlseed_timeout`` is the same as ``peer_timeout`` but applies only to
2589
url seeds. This value defaults to 20 seconds.
2591
``urlseed_pipeline_size`` controls the pipelining with the web server. When
2592
using persistent connections to HTTP 1.1 servers, the client is allowed to
2593
send more requests before the first response is received. This number controls
2594
the number of outstanding requests to use with url-seeds. Default is 5.
2596
``file_pool_size`` is the the upper limit on the total number of files this
2597
session will keep open. The reason why files are left open at all is that
2598
some anti virus software hooks on every file close, and scans the file for
2599
viruses. deferring the closing of the files will be the difference between
2600
a usable system and a completely hogged down system. Most operating systems
2601
also has a limit on the total number of file descriptors a process may have
2602
open. It is usually a good idea to find this limit and set the number of
2603
connections and the number of files limits so their sum is slightly below it.
2605
``allow_multiple_connections_per_ip`` determines if connections from the
2606
same IP address as existing connections should be rejected or not. Multiple
2607
connections from the same IP address is not allowed by default, to prevent
2608
abusive behavior by peers. It may be useful to allow such connections in
2609
cases where simulations are run on the same machie, and all peers in a
2610
swarm has the same IP address.
2612
``max_failcount`` is the maximum times we try to connect to a peer before
2613
stop connecting again. If a peer succeeds, the failcounter is reset. If
2614
a peer is retrieved from a peer source (other than DHT) the failcount is
2615
decremented by one, allowing another try.
2617
``min_reconnect_time`` is the time to wait between connection attempts. If
2618
the peer fails, the time is multiplied by fail counter.
2620
``peer_connect_timeout`` the number of seconds to wait after a connection
2621
attempt is initiated to a peer until it is considered as having timed out.
2622
The default is 10 seconds. This setting is especially important in case
2623
the number of half-open connections are limited, since stale half-open
2624
connection may delay the connection of other peers considerably.
2626
``ignore_limits_on_local_network``, if set to true, upload, download and
2627
unchoke limits are ignored for peers on the local network.
2629
``connection_speed`` is the number of connection attempts that
2630
are made per second. If a number <= 0 is specified, it will default to
2631
200 connections per second.
2633
``send_redundant_have`` controls if have messages will be sent
2634
to peers that already have the piece. This is typically not necessary,
2635
but it might be necessary for collecting statistics in some cases.
2638
``lazy_bitfields`` prevents outgoing bitfields from being full. If the
2639
client is seed, a few bits will be set to 0, and later filled in with
2640
have-messages. This is to prevent certain ISPs from stopping people
2643
``inactivity_timeout``, if a peer is uninteresting and uninterested
2644
for longer than this number of seconds, it will be disconnected.
2645
Default is 10 minutes
2647
``unchoke_interval`` is the number of seconds between chokes/unchokes.
2648
On this interval, peers are re-evaluated for being choked/unchoked. This
2649
is defined as 30 seconds in the protocol, and it should be significantly
2650
longer than what it takes for TCP to ramp up to it's max rate.
2652
``optimistic_unchoke_multiplier`` is the number of unchoke intervals between
2653
each *optimistic* unchoke interval. On this timer, the currently optimistically
2654
unchoked peer will change.
2656
``announce_ip`` is the ip address passed along to trackers as the ``&ip=`` parameter.
2657
If left as the default (default constructed), that parameter is ommited.
2659
``num_want`` is the number of peers we want from each tracker request. It defines
2660
what is sent as the ``&num_want=`` parameter to the tracker.
2662
``initial_picker_threshold`` specifies the number of pieces we need before we
2663
switch to rarest first picking. This defaults to 4, which means the 4 first
2664
pieces in any torrent are picked at random, the following pieces are picked
2665
in rarest first order.
2667
``allowed_fast_set_size`` is the number of pieces we allow peers to download
2668
from us without being unchoked.
2670
``max_outstanding_disk_bytes_per_connection`` is the number of bytes each
2671
connection is allowed to have waiting in the disk I/O queue before it is
2672
throttled back. This limit is meant to stop fast internet connections to
2673
queue up bufferes indefinitely on slow hard-drives or storage.
2675
``handshake_timeout`` specifies the number of seconds we allow a peer to
2676
delay responding to a protocol handshake. If no response is received within
2677
this time, the connection is closed.
2679
``use_dht_as_fallback`` determines how the DHT is used. If this is true
2680
(which it is by default), the DHT will only be used for torrents where
2681
all trackers in its tracker list has failed. Either by an explicit error
2682
message or a time out.
2684
``free_torrent_hashes`` determines whether or not the torrent's piece hashes
2685
are kept in memory after the torrent becomes a seed or not. If it is set to
2686
``true`` the hashes are freed once the torrent is a seed (they're not
2687
needed anymore since the torrent won't download anything more). If it's set
2688
to false they are not freed. If they are freed, the torrent_info_ returned
2689
by get_torrent_info() will return an object that may be incomplete, that
2690
cannot be passed back to `add_torrent()`_ for instance.
2692
``upnp_ignore_nonrouters`` indicates whether or not the UPnP implementation
2693
should ignore any broadcast response from a device whose address is not the
2694
configured router for this machine. i.e. it's a way to not talk to other
2695
people's routers by mistake.
2700
The ``pe_settings`` structure is used to control the settings related
2701
to peer protocol encryption::
2721
enc_policy out_enc_policy;
2722
enc_policy in_enc_policy;
2723
enc_level allowed_enc_level;
2728
``in_enc_policy`` and ``out_enc_policy`` control the settings for incoming
2729
and outgoing connections respectively. The settings for these are:
2731
* ``forced`` - Only encrypted connections are allowed. Incoming connections
2732
that are not encrypted are closed and if the encrypted outgoing connection
2733
fails, a non-encrypted retry will not be made.
2735
* ``enabled`` - encrypted connections are enabled, but non-encrypted
2736
connections are allowed. An incoming non-encrypted connection will
2737
be accepted, and if an outgoing encrypted connection fails, a non-
2738
encrypted connection will be tried.
2740
* ``disabled`` - only non-encrypted connections are allowed.
2742
``allowed_enc_level`` determines the encryption level of the
2743
connections. This setting will adjust which encryption scheme is
2744
offered to the other peer, as well as which encryption scheme is
2745
selected by the client. The settings are:
2747
* ``plaintext`` - only the handshake is encrypted, the bulk of the traffic
2750
* ``rc4`` - the entire stream is encrypted with RC4
2752
* ``both`` - both RC4 and plaintext connections are allowed.
2754
``prefer_rc4`` can be set to true if you want to prefer the RC4 encrypted stream.
2760
The ``proxy_settings`` structs contains the information needed to
2761
direct certain traffic to a proxy.
2765
struct proxy_settings
2769
std::string hostname;
2772
std::string username;
2773
std::string password;
2788
``hostname`` is the name or IP of the proxy server. ``port`` is the
2789
port number the proxy listens to. If required, ``username`` and ``password``
2790
can be set to authenticate with the proxy.
2792
The ``type`` tells libtorrent what kind of proxy server it is. The following
2793
options are available:
2795
* ``none`` - This is the default, no proxy server is used, all other fields
2798
* ``socks4`` - The server is assumed to be a `SOCKS4 server`_ that
2799
requires a username.
2801
* ``socks5`` - The server is assumed to be a SOCKS5 server (`RFC 1928`_) that
2802
does not require any authentication. The username and password are ignored.
2804
* ``socks5_pw`` - The server is assumed to be a SOCKS5 server that supports
2805
plain text username and password authentication (`RFC 1929`_). The username
2806
and password specified may be sent to the proxy if it requires.
2808
* ``http`` - The server is assumed to be an HTTP proxy. If the transport used
2809
for the connection is non-HTTP, the server is assumed to support the
2810
CONNECT_ method. i.e. for web seeds and HTTP trackers, a plain proxy will
2811
suffice. The proxy is assumed to not require authorization. The username
2812
and password will not be used.
2814
* ``http_pw`` - The server is assumed to be an HTTP proxy that requires
2815
user authorization. The username and password will be sent to the proxy.
2817
.. _`SOCKS4 server`: http://www.ufasoft.com/doc/socks4_protocol.htm
2818
.. _`RFC 1928`: http://www.faqs.org/rfcs/rfc1928.html
2819
.. _`RFC 1929`: http://www.faqs.org/rfcs/rfc1929.html
2820
.. _CONNECT: draft-luotonen-web-proxy-tunneling-01.txt
2825
The ``ip_filter`` class is a set of rules that uniquely categorizes all
2826
ip addresses as allowed or disallowed. The default constructor creates
2827
a single rule that allows all addresses (0.0.0.0 - 255.255.255.255 for
2828
the IPv4 range, and the equivalent range covering all addresses for the
2833
template <class Addr>
2844
enum access_flags { blocked = 1 };
2847
void add_rule(address first, address last, int flags);
2848
int access(address const& addr) const;
2850
typedef boost::tuple<std::vector<ip_range<address_v4> >
2851
, std::vector<ip_range<address_v6> > > filter_tuple_t;
2853
filter_tuple_t export_filter() const;
2864
Creates a default filter that doesn't filter any address.
2867
``access(x) == 0`` for every ``x``
2875
void add_rule(address first, address last, int flags);
2877
Adds a rule to the filter. ``first`` and ``last`` defines a range of
2878
ip addresses that will be marked with the given flags. The ``flags``
2879
can currently be 0, which means allowed, or ``ip_filter::blocked``, which
2883
``first.is_v4() == last.is_v4() && first.is_v6() == last.is_v6()``
2886
``access(x) == flags`` for every ``x`` in the range [``first``, ``last``]
2888
This means that in a case of overlapping ranges, the last one applied takes
2897
int access(address const& addr) const;
2899
Returns the access permissions for the given address (``addr``). The permission
2900
can currently be 0 or ``ip_filter::blocked``. The complexity of this operation
2901
is O(``log`` n), where n is the minimum number of non-overlapping ranges to describe
2910
boost::tuple<std::vector<ip_range<address_v4> >
2911
, std::vector<ip_range<address_v6> > > export_filter() const;
2913
This function will return the current state of the filter in the minimum number of
2914
ranges possible. They are sorted from ranges in low addresses to high addresses. Each
2915
entry in the returned vector is a range with the access control specified in its
2918
The return value is a tuple containing two range-lists. One for IPv4 addresses
2919
and one for IPv6 addresses.
2925
Both the ``peer_id`` and ``sha1_hash`` types are typedefs of the class
2926
``big_number``. It represents 20 bytes of data. Its synopsis follows::
2931
bool operator==(const big_number& n) const;
2932
bool operator!=(const big_number& n) const;
2933
bool operator<(const big_number& n) const;
2935
const unsigned char* begin() const;
2936
const unsigned char* end() const;
2938
unsigned char* begin();
2939
unsigned char* end();
2942
The iterators gives you access to individual bytes.
2949
This class creates sha1-hashes. Its declaration looks like this::
2955
hasher(char const* data, unsigned int len);
2957
void update(char const* data, unsigned int len);
2963
You use it by first instantiating it, then call ``update()`` to feed it
2964
with data. i.e. you don't have to keep the entire buffer of which you want to
2965
create the hash in memory. You can feed the hasher parts of it at a time. When
2966
You have fed the hasher with all the data, you call ``final()`` and it
2967
will return the sha1-hash of the data.
2969
The constructor that takes a ``char const*`` and an integer will construct the
2970
sha1 context and feed it the data passed in.
2972
If you want to reuse the hasher object once you have created a hash, you have to
2973
call ``reset()`` to reinitialize it.
2975
The sha1-algorithm used was implemented by Steve Reid and released as public domain.
2976
For more info, see ``src/sha1.cpp``.
2982
The fingerprint class represents information about a client and its version. It is used
2983
to encode this information into the client's peer id.
2985
This is the class declaration::
2989
fingerprint(const char* id_string, int major, int minor
2990
, int revision, int tag);
2992
std::string to_string() const;
2997
char revision_version;
3002
The constructor takes a ``char const*`` that should point to a string constant containing
3003
exactly two characters. These are the characters that should be unique for your client. Make
3004
sure not to clash with anybody else. Here are some taken id's:
3006
+----------+-----------------------+
3007
| id chars | client |
3008
+==========+=======================+
3010
+----------+-----------------------+
3011
| 'LT' | libtorrent (default) |
3012
+----------+-----------------------+
3013
| 'BX' | BittorrentX |
3014
+----------+-----------------------+
3015
| 'MT' | Moonlight Torrent |
3016
+----------+-----------------------+
3017
| 'TS' | Torrent Storm |
3018
+----------+-----------------------+
3019
| 'SS' | Swarm Scope |
3020
+----------+-----------------------+
3021
| 'XT' | Xan Torrent |
3022
+----------+-----------------------+
3024
There's currently an informal directory of client id's here__.
3026
__ http://wiki.theory.org/BitTorrentSpecification#peer_id
3029
The ``major``, ``minor``, ``revision`` and ``tag`` parameters are used to identify the
3030
version of your client. All these numbers must be within the range [0, 9].
3032
``to_string()`` will generate the actual string put in the peer-id, and return it.
3043
std::string identify_client(peer_id const& id);
3045
This function is declared in the header ``<libtorrent/identify_client.hpp>``. It can can be used
3046
to extract a string describing a client version from its peer-id. It will recognize most clients
3047
that have this kind of identification in the peer-id.
3050
client_fingerprint()
3051
--------------------
3055
boost::optional<fingerprint> client_fingerprint(peer_id const& p);
3057
Returns an optional fingerprint if any can be identified from the peer id. This can be used
3058
to automate the identification of clients. It will not be able to identify peers with non-
3059
standard encodings. Only Azureus style, Shadow's style and Mainline style. This function is
3060
declared in the header ``<libtorrent/identify_client.hpp>``.
3068
template<class InIt> entry bdecode(InIt start, InIt end);
3069
template<class OutIt> void bencode(OutIt out, const entry& e);
3072
These functions will encode data to bencoded_ or decode bencoded_ data.
3074
.. _bencoded: http://wiki.theory.org/index.php/BitTorrentSpecification
3076
The entry_ class is the internal representation of the bencoded data
3077
and it can be used to retrieve information, an entry_ can also be build by
3078
the program and given to ``bencode()`` to encode it into the ``OutIt``
3081
The ``OutIt`` and ``InIt`` are iterators
3082
(InputIterator_ and OutputIterator_ respectively). They
3083
are templates and are usually instantiated as ostream_iterator_,
3084
back_insert_iterator_ or istream_iterator_. These
3085
functions will assume that the iterator refers to a character
3086
(``char``). So, if you want to encode entry ``e`` into a buffer
3087
in memory, you can do it like this::
3089
std::vector<char> buffer;
3090
bencode(std::back_inserter(buf), e);
3092
.. _InputIterator: http://www.sgi.com/tech/stl/InputIterator.html
3093
.. _OutputIterator: http://www.sgi.com/tech/stl/OutputIterator.html
3094
.. _ostream_iterator: http://www.sgi.com/tech/stl/ostream_iterator.html
3095
.. _back_insert_iterator: http://www.sgi.com/tech/stl/back_insert_iterator.html
3096
.. _istream_iterator: http://www.sgi.com/tech/stl/istream_iterator.html
3098
If you want to decode a torrent file from a buffer in memory, you can do it like this::
3100
std::vector<char> buffer;
3102
entry e = bdecode(buf.begin(), buf.end());
3104
Or, if you have a raw char buffer::
3108
entry e = bdecode(buf, buf + data_size);
3110
Now we just need to know how to retrieve information from the entry_.
3112
If ``bdecode()`` encounters invalid encoded data in the range given to it
3113
it will throw invalid_encoding_.
3119
The ``pop_alert()`` function on session is the interface for retrieving
3120
alerts, warnings, messages and errors from libtorrent. If there hasn't
3121
occurred any errors (matching your severity level) ``pop_alert()`` will
3122
return a zero pointer. If there has been some error, it will return a pointer
3123
to an alert object describing it. You can then use the alert object and query
3124
it for information about the error or message. To retrieve any alerts, you have
3125
to select a severity level using ``session::set_severity_level()``. It defaults to
3126
``alert::none``, which means that you don't get any messages at all, ever.
3127
You have the following levels to select among:
3129
+--------------+----------------------------------------------------------+
3130
| ``none`` | No alert will ever have this severity level, which |
3131
| | effectively filters all messages. |
3133
+--------------+----------------------------------------------------------+
3134
| ``fatal`` | Fatal errors will have this severity level. Examples can |
3135
| | be disk full or something else that will make it |
3136
| | impossible to continue normal execution. |
3138
+--------------+----------------------------------------------------------+
3139
| ``critical`` | Signals errors that requires user interaction or |
3140
| | messages that almost never should be ignored. For |
3141
| | example, a chat message received from another peer is |
3142
| | announced as severity ``critical``. |
3144
+--------------+----------------------------------------------------------+
3145
| ``warning`` | Messages with the warning severity can be a tracker that |
3146
| | times out or responds with invalid data. It will be |
3147
| | retried automatically, and the possible next tracker in |
3148
| | a multitracker sequence will be tried. It does not |
3149
| | require any user interaction. |
3151
+--------------+----------------------------------------------------------+
3152
| ``info`` | Events that can be considered normal, but still deserves |
3153
| | an event. This could be a piece hash that fails. |
3155
+--------------+----------------------------------------------------------+
3156
| ``debug`` | This will include a lot of debug events that can be used |
3157
| | both for debugging libtorrent but also when debugging |
3158
| | other clients that are connected to libtorrent. It will |
3159
| | report strange behaviors among the connected peers. |
3161
+--------------+----------------------------------------------------------+
3163
When setting a severity level, you will receive messages of that severity and all
3164
messages that are more sever. If you set ``alert::none`` (the default) you will not receive
3167
When you set a severity level other than ``none``, you have the responsibility to call
3168
``pop_alert()`` from time to time. If you don't do that, the alert queue will just grow.
3170
When you get an alert, you can use ``typeid()`` or ``dynamic_cast<>`` to get more detailed
3171
information on exactly which type it is. i.e. what kind of error it is. You can also use a
3172
dispatcher_ mechanism that's available in libtorrent.
3174
All alert types are defined in the ``<libtorrent/alert_types.hpp>`` header file.
3176
The ``alert`` class is the base class that specific messages are derived from. This
3183
enum severity_t { debug, info, warning, critical, fatal, none };
3185
alert(severity_t severity, std::string const& msg);
3188
std::string const& msg() const;
3189
severity_t severity() const;
3191
virtual std::auto_ptr<alert> clone() const = 0;
3194
This means that all alerts have at least a string describing it. They also
3195
have a severity level that can be used to sort them or present them to the
3196
user in different ways.
3198
There's another alert base class that all most alerts derives from, all the
3199
alerts that are generated for a specific torrent are derived from::
3201
struct torrent_alert: alert
3203
torrent_alert(torrent_handle const& h, severity_t s, std::string const& msg);
3205
torrent_handle handle;
3208
The specific alerts, that all derives from ``alert``, are:
3214
This alert is generated when none of the ports, given in the port range, to
3215
session_ can be opened for listening. This alert is generated as severity
3220
struct listen_failed_alert: alert
3222
listen_failed_alert(const std::string& msg);
3223
virtual std::auto_ptr<alert> clone() const;
3229
This alert is generated when a NAT router was successfully found but some
3230
part of the port mapping request failed. It contains a text message that
3231
may help the user figure out what is wrong. This alert is not generated in
3232
case it appears the client is not running on a NAT:ed network or if it
3233
appears there is no NAT router that can be remote controlled to add port
3236
The alert is generated as severity ``warning``, since it should be displayed
3237
to the user somehow, and could mean reduced preformance.
3241
struct portmap_error_alert: alert
3243
portmap_error_alert(const std::string& msg);
3244
virtual std::auto_ptr<alert> clone() const;
3250
This alert is generated when a NAT router was successfully found and
3251
a port was successfully mapped on it. On a NAT:ed network with a NAT-PMP
3252
capable router, this is typically generated once when mapping the TCP
3253
port and, if DHT is enabled, when the UDP port is mapped. This is merely
3254
an informational alert, and is generated at severity level ``info``.
3258
struct portmap_alert: alert
3260
portmap_alert(const std::string& msg);
3261
virtual std::auto_ptr<alert> clone() const;
3267
If the storage fails to read or write files that it needs access to, this alert is
3268
generated and the torrent is paused. It is generated as severity level ``fatal``.
3272
struct file_error_alert: torrent_alert
3275
const torrent_handle& h
3276
, const std::string& msg);
3278
virtual std::auto_ptr<alert> clone() const;
3282
tracker_announce_alert
3283
----------------------
3285
This alert is generated each time a tracker announce is sent (or attempted to be sent).
3286
It is generated at severity level ``info``.
3290
struct tracker_announce_alert: torrent_alert
3292
tracker_announce_alert(
3293
const torrent_handle& h
3294
, const std::string& msg);
3296
virtual std::auto_ptr<alert> clone() const;
3303
This alert is generated on tracker time outs, premature disconnects, invalid response or
3304
a HTTP response other than "200 OK". From the alert you can get the handle to the torrent
3305
the tracker belongs to. This alert is generated as severity level ``warning``.
3307
The ``times_in_row`` member says how many times in a row this tracker has failed.
3308
``status_code`` is the code returned from the HTTP server. 401 means the tracker needs
3309
authentication, 404 means not found etc. If the tracker timed out, the code will be set
3314
struct tracker_alert: torrent_alert
3316
tracker_alert(torrent_handle const& h, int times, int status
3317
, const std::string& msg);
3318
virtual std::auto_ptr<alert> clone() const;
3328
This alert is only for informational purpose. It is generated when a tracker announce
3329
succeeds. It is generated regardless what kind of tracker was used, be it UDP, HTTP or
3330
the DHT. It is generated with severity level ``info``.
3334
struct tracker_reply_alert: torrent_alert
3336
tracker_reply_alert(const torrent_handle& h
3338
, const std::string& msg);
3342
virtual std::auto_ptr<alert> clone() const;
3345
The ``num_peers`` tells how many peers were returned from the tracker. This is
3346
not necessarily all new peers, some of them may already be connected.
3348
tracker_warning_alert
3349
---------------------
3351
This alert is triggered if the tracker reply contains a warning field. Usually this
3352
means that the tracker announce was successful, but the tracker has a message to
3353
the client. The message string in the alert will contain the warning message from
3354
the tracker. It is generated with severity level ``warning``.
3358
struct tracker_warning_alert: torrent_alert
3360
tracker_warning_alert(torrent_handle const& h
3361
, std::string const& msg);
3363
virtual std::auto_ptr<alert> clone() const;
3371
struct scrape_reply_alert: torrent_alert
3373
scrape_reply_alert(torrent_handle const& h
3376
, std::string const& msg);
3381
virtual std::auto_ptr<alert> clone() const;
3384
This alert is generated when a scrape request succeeds. ``incomplete``
3385
and ``complete`` is the data returned in the scrape response. These numbers
3386
may be -1 if the reponse was malformed.
3393
struct scrape_failed_alert: torrent_alert
3395
scrape_failed_alert(torrent_handle const& h
3396
, std::string const& msg);
3398
virtual std::auto_ptr<alert> clone() const;
3401
If a scrape request fails, this alert is generated. This might be due
3402
to the tracker timing out, refusing connection or returning an http response
3403
code indicating an error.
3408
This alert is generated when a HTTP seed name lookup fails. This alert is
3409
generated as severity level ``warning``.
3411
It contains ``url`` to the HTTP seed that failed along with an error message.
3415
struct url_seed_alert: torrent_alert
3417
url_seed_alert(torrent_handle const& h, std::string const& url
3418
, const std::string& msg);
3419
virtual std::auto_ptr<alert> clone() const;
3428
This alert is generated when a finished piece fails its hash check. You can get the handle
3429
to the torrent which got the failed piece and the index of the piece itself from the alert.
3430
This alert is generated as severity level ``info``.
3434
struct hash_failed_alert: torrent_alert
3437
torrent_handle const& h
3439
, const std::string& msg);
3441
virtual std::auto_ptr<alert> clone() const;
3450
This alert is generated when a peer is banned because it has sent too many corrupt pieces
3451
to us. It is generated at severity level ``info``. The ``handle`` member is a torrent_handle_
3452
to the torrent that this peer was a member of.
3456
struct peer_ban_alert: torrent_alert
3459
asio::ip::tcp::endpoint const& pip
3461
, const std::string& msg);
3463
virtual std::auto_ptr<alert> clone() const;
3465
asio::ip::tcp::endpoint ip;
3472
This alert is generated when a peer sends invalid data over the peer-peer protocol. The peer
3473
will be disconnected, but you get its ip address from the alert, to identify it. This alert
3474
is generated as severity level ``debug``.
3478
struct peer_error_alert: alert
3481
asio::ip::tcp::endpoint const& pip
3482
, peer_id const& pid
3483
, const std::string& msg);
3485
virtual std::auto_ptr<alert> clone() const;
3486
asio::ip::tcp::endpoint ip;
3491
invalid_request_alert
3492
---------------------
3494
This is a debug alert that is generated by an incoming invalid piece request. The ``handle``
3495
is a handle to the torrent the peer is a member of. ``�p`` is the address of the peer and the
3496
``request`` is the actual incoming request from the peer. The alert is generated as severity level
3501
struct invalid_request_alert: torrent_alert
3503
invalid_request_alert(
3504
peer_request const& r
3505
, torrent_handle const& h
3506
, asio::ip::tcp::endpoint const& send
3507
, peer_id const& pid
3508
, std::string const& msg);
3510
virtual std::auto_ptr<alert> clone() const;
3512
asio::ip::tcp::endpoint ip;
3513
peer_request request;
3523
bool operator==(peer_request const& r) const;
3527
The ``peer_request`` contains the values the client sent in its ``request`` message. ``piece`` is
3528
the index of the piece it want data from, ``start`` is the offset within the piece where the data
3529
should be read, and ``length`` is the amount of data it wants.
3531
torrent_finished_alert
3532
----------------------
3534
This alert is generated when a torrent switches from being a downloader to a seed.
3535
It will only be generated once per torrent. It contains a torrent_handle to the
3536
torrent in question. This alert is generated as severity level ``info``.
3540
struct torrent_finished_alert: torrent_alert
3542
torrent_finished_alert(
3543
const torrent_handle& h
3544
, const std::string& msg);
3546
virtual std::auto_ptr<alert> clone() const;
3550
metadata_failed_alert
3551
---------------------
3553
This alert is generated when the metadata has been completely received and the info-hash
3554
failed to match it. i.e. the metadata that was received was corrupt. libtorrent will
3555
automatically retry to fetch it in this case. This is only relevant when running a
3556
torrent-less download, with the metadata extension provided by libtorrent.
3557
It is generated at severity level ``info``.
3561
struct metadata_failed_alert: torrent_alert
3563
metadata_failed_alert(
3564
torrent_handle const& h
3565
, std::string const& msg);
3567
virtual std::auto_ptr<alert> clone() const;
3571
metadata_received_alert
3572
-----------------------
3574
This alert is generated when the metadata has been completely received and the torrent
3575
can start downloading. It is not generated on torrents that are started with metadata, but
3576
only those that needs to download it from peers (when utilizing the libtorrent extension).
3577
It is generated at severity level ``info``.
3581
struct metadata_received_alert: torrent_alert
3583
metadata_received_alert(
3584
torrent_handle const_& h
3585
, std::string const& msg);
3587
virtual std::auto_ptr<alert> clone() const;
3591
fastresume_rejected_alert
3592
-------------------------
3594
This alert is generated when a fastresume file has been passed to ``add_torrent`` but the
3595
files on disk did not match the fastresume file. The string explains the reason why the
3596
resume file was rejected. It is generated at severity level ``warning``.
3600
struct fastresume_rejected_alert: torrent_alert
3602
fastresume_rejected_alert(torrent_handle const& h
3603
, std::string const& msg);
3605
virtual std::auto_ptr<alert> clone() const;
3612
This alert is generated when a peer is blocked by the IP filter. It has the severity leve
3613
``info``. The ``ip`` member is the address that was blocked.
3617
struct peer_blocked_alert: alert
3619
peer_blocked_alert(address const& ip_
3620
, std::string const& msg);
3624
virtual std::auto_ptr<alert> clone() const;
3630
The ``storage_moved_alert`` is generated when all the disk IO has completed and the
3631
files have been moved, as an effect of a call to ``torrent_handle::move_storage``. This
3632
is useful to synchronize with the actual disk.
3636
struct storage_moved_alert: torrent_alert
3638
storage_moved_alert(torrent_handle const& h, std::string const& path);
3639
virtual std::auto_ptr<alert> clone() const;
3642
torrent_paused_alert
3643
--------------------
3645
This alert is generated as a response to a ``torrent_handle::pause`` request. It is
3646
generated once all disk IO is complete and the files in the torrent have been closed.
3647
This is useful for synchronizing with the disk.
3651
struct torrent_paused_alert: torrent_alert
3653
torrent_paused_alert(torrent_handle const& h, std::string const& msg);
3654
virtual std::auto_ptr<alert> clone() const;
3661
The ``handle_alert`` class is defined in ``<libtorrent/alert.hpp>``.
3667
void operator()(portmap_error_alert const& a)
3669
std::cout << "Portmapper: " << a.msg << std::endl;
3672
void operator()(tracker_warning_alert const& a)
3674
std::cout << "Tracker warning: " << a.msg << std::endl;
3677
void operator()(torrent_finished_alert const& a)
3679
// write fast resume data
3682
std::cout << a.handle.get_torrent_info().name() << "completed"
3689
std::auto_ptr<alert> a;
3690
a = ses.pop_alert();
3694
handle_alert<portmap_error_alert
3695
, tracker_warning_alert
3696
, torrent_finished_alert
3697
>::handle_alert(h, a);
3698
a = ses.pop_alert();
3701
In this example 3 alert types are used. You can use any number of template
3702
parameters to select between more types. If the number of types are more than
3703
15, you can define ``TORRENT_MAX_ALERT_TYPES`` to a greater number before
3704
including ``<libtorrent/alert.hpp>``.
3710
There are a number of exceptions that can be thrown from different places in libtorrent,
3711
here's a complete list with description.
3717
This exception is thrown when querying information from a torrent_handle_ that hasn't
3718
been initialized or that has become invalid.
3722
struct invalid_handle: std::exception
3724
const char* what() const throw();
3731
This is thrown by `add_torrent()`_ if the torrent already has been added to
3732
the session. Since `remove_torrent()`_ is asynchronous, this exception may
3733
be thrown if the torrent is removed and then immediately added again.
3737
struct duplicate_torrent: std::exception
3739
const char* what() const throw();
3746
This is thrown by ``bdecode()`` if the input data is not a valid bencoding.
3750
struct invalid_encoding: std::exception
3752
const char* what() const throw();
3759
This is thrown from the accessors of ``entry`` if the data type of the ``entry`` doesn't
3760
match the type you want to extract from it.
3764
struct type_error: std::runtime_error
3766
type_error(const char* error);
3770
invalid_torrent_file
3771
--------------------
3773
This exception is thrown from the constructor of ``torrent_info`` if the given bencoded information
3774
doesn't meet the requirements on what information has to be present in a torrent file.
3778
struct invalid_torrent_file: std::exception
3780
const char* what() const throw();
3787
The storage interface is a pure virtual class that can be implemented to
3788
change the behavior of the actual file storage. The interface looks like
3791
struct storage_interface
3793
virtual void initialize(bool allocate_files) = 0;
3794
virtual size_type read(char* buf, int slot, int offset, int size) = 0;
3795
virtual void write(const char* buf, int slot, int offset, int size) = 0;
3796
virtual bool move_storage(fs::path save_path) = 0;
3797
virtual bool verify_resume_data(entry& rd, std::string& error) = 0;
3798
virtual void write_resume_data(entry& rd) const = 0;
3799
virtual void move_slot(int src_slot, int dst_slot) = 0;
3800
virtual void swap_slots(int slot1, int slot2) = 0;
3801
virtual void swap_slots3(int slot1, int slot2, int slot3) = 0;
3802
virtual sha1_hash hash_for_slot(int slot, partial_hash& h, int piece_size) = 0;
3803
virtual void release_files() = 0;
3804
virtual void delete_files() = 0;
3805
virtual ~storage_interface() {}
3814
void initialize(bool allocate_files) = 0;
3816
This function is called when the storage is to be initialized. The default storage
3817
will create directories and empty files at this point. If ``allocate_files`` is true,
3818
it will also ``ftruncate`` all files to their target size.
3826
size_type read(char* buf, int slot, int offset, int size) = 0;
3828
This function should read the data in the given slot and at the given offset
3829
and ``size`` number of bytes. The data is to be copied to ``buf``.
3831
The return value is the number of bytes actually read.
3839
void write(const char* buf, int slot, int offset, int size) = 0;
3841
This function should write the data in ``buf`` to the given slot (``slot``) at offset
3842
``offset`` in that slot. The buffer size is ``size``.
3850
bool move_storage(fs::path save_path) = 0;
3852
This function should move all the files belonging to the storage to the new save_path.
3853
The default storage moves the single file or the directory of the torrent.
3855
Before moving the files, any open file handles may have to be closed, like
3856
``release_files()``.
3859
verify_resume_data()
3860
--------------------
3864
bool verify_resume_data(entry& rd, std::string& error) = 0;
3866
This function should verify the resume data ``rd`` with the files
3867
on disk. If the resume data seems to be up-to-date, return true. If
3868
not, set ``error`` to a description of what mismatched and return false.
3870
The default storage may compare file sizes and time stamps of the files.
3873
write_resume_data( )
3874
--------------------
3878
void write_resume_data(entry& rd) const = 0;
3880
This function should fill in resume data, the current state of the
3881
storage, in ``rd``. The default storage adds file timestamps and
3890
void move_slot(int src_slot, int dst_slot) = 0;
3892
This function should copy or move the data in slot ``src_slot`` to
3893
the slot ``dst_slot``. This is only used in compact mode.
3895
If the storage caches slots, this could be implemented more
3896
efficient than reading and writing the data.
3904
void swap_slots(int slot1, int slot2) = 0;
3906
This function should swap the data in ``slot1`` and ``slot2``. The default
3907
storage uses a scratch buffer to read the data into, then moving the other
3908
slot and finally writing back the temporary slot's data
3910
This is only used in compact mode.
3918
void swap_slots3(int slot1, int slot2, int slot3) = 0;
3920
This function should do a 3-way swap, or shift of the slots. ``slot1``
3921
should move to ``slot2``, which should be moved to ``slot3`` which in turn
3922
should be moved to ``slot1``.
3924
This is only used in compact mode.
3932
sha1_hash hash_for_slot(int slot, partial_hash& h, int piece_size) = 0;
3934
The function should read the remaining bytes of the slot and hash it with the
3935
sha-1 state in ``partion_hash``. The ``partial_hash`` struct looks like this::
3944
``offset`` is the number of bytes in the slot that has already been hashed, and
3945
``h`` is the sha-1 state of that hash. ``piece_size`` is the size of the piece
3946
that is stored in the given slot.
3948
The function should return the hash of the piece stored in the slot.
3956
void release_files() = 0;
3958
This function should release all the file handles that it keeps open to files
3959
belonging to this storage. The default implementation just calls
3960
``file_pool::release_files(this)``.
3968
void delete_files() = 0;
3970
This function should delete all files and directories belonging to this storage.
3976
The fast resume mechanism is a way to remember which pieces are downloaded
3977
and where they are put between sessions. You can generate fast resume data by
3978
calling ``torrent_handle::write_resume_data()`` on torrent_handle_. You can
3979
then save this data to disk and use it when resuming the torrent. libtorrent
3980
will not check the piece hashes then, and rely on the information given in the
3981
fast-resume data. The fast-resume data also contains information about which
3982
blocks, in the unfinished pieces, were downloaded, so it will not have to
3983
start from scratch on the partially downloaded pieces.
3985
To use the fast-resume data you simply give it to `add_torrent()`_, and it
3986
will skip the time consuming checks. It may have to do the checking anyway, if
3987
the fast-resume data is corrupt or doesn't fit the storage for that torrent,
3988
then it will not trust the fast-resume data and just do the checking.
3993
The file format is a bencoded dictionary containing the following fields:
3995
+----------------------+--------------------------------------------------------------+
3996
| ``file-format`` | string: "libtorrent resume file" |
3998
+----------------------+--------------------------------------------------------------+
3999
| ``file-version`` | integer: 1 |
4001
+----------------------+--------------------------------------------------------------+
4002
| ``info-hash`` | string, the info hash of the torrent this data is saved for. |
4004
+----------------------+--------------------------------------------------------------+
4005
| ``blocks per piece`` | integer, the number of blocks per piece. Must be: piece_size |
4006
| | / (16 * 1024). Clamped to be within the range [1, 256]. It |
4007
| | is the number of blocks per (normal sized) piece. Usually |
4008
| | each block is 16 * 1024 bytes in size. But if piece size is |
4009
| | greater than 4 megabytes, the block size will increase. |
4011
+----------------------+--------------------------------------------------------------+
4012
| ``slots`` | list of integers. The list maps slots to piece indices. It |
4013
| | tells which piece is on which slot. If piece index is -2 it |
4014
| | means it is free, that there's no piece there. If it is -1, |
4015
| | means the slot isn't allocated on disk yet. The pieces have |
4016
| | to meet the following requirement: |
4018
| | If there's a slot at the position of the piece index, |
4019
| | the piece must be located in that slot. |
4021
+----------------------+--------------------------------------------------------------+
4022
| ``peers`` | list of dictionaries. Each dictionary has the following |
4025
| | +----------+-----------------------------------------------+ |
4026
| | | ``ip`` | string, the ip address of the peer. This is | |
4027
| | | | not a binary representation of the ip | |
4028
| | | | address, but the string representation. It | |
4029
| | | | may be an IPv6 string or an IPv4 string. | |
4030
| | +----------+-----------------------------------------------+ |
4031
| | | ``port`` | integer, the listen port of the peer | |
4032
| | +----------+-----------------------------------------------+ |
4034
| | These are the local peers we were connected to when this |
4035
| | fast-resume data was saved. |
4037
+----------------------+--------------------------------------------------------------+
4038
| ``unfinished`` | list of dictionaries. Each dictionary represents an |
4039
| | piece, and has the following layout: |
4041
| | +-------------+--------------------------------------------+ |
4042
| | | ``piece`` | integer, the index of the piece this entry | |
4043
| | | | refers to. | |
4044
| | +-------------+--------------------------------------------+ |
4045
| | | ``bitmask`` | string, a binary bitmask representing the | |
4046
| | | | blocks that have been downloaded in this | |
4048
| | +-------------+--------------------------------------------+ |
4049
| | | ``adler32`` | The adler32 checksum of the data in the | |
4050
| | | | blocks specified by ``bitmask``. | |
4052
| | +-------------+--------------------------------------------+ |
4054
+----------------------+--------------------------------------------------------------+
4055
| ``file sizes`` | list where each entry corresponds to a file in the file list |
4056
| | in the metadata. Each entry has a list of two values, the |
4057
| | first value is the size of the file in bytes, the second |
4058
| | is the time stamp when the last time someone wrote to it. |
4059
| | This information is used to compare with the files on disk. |
4060
| | All the files must match exactly this information in order |
4061
| | to consider the resume data as current. Otherwise a full |
4062
| | re-check is issued. |
4063
+----------------------+--------------------------------------------------------------+
4064
| ``allocation`` | The allocation mode for the storage. Can be either ``full`` |
4065
| | or ``compact``. If this is full, the file sizes and |
4066
| | timestamps are disregarded. Pieces are assumed not to have |
4067
| | moved around even if the files have been modified after the |
4068
| | last resume data checkpoint. |
4069
+----------------------+--------------------------------------------------------------+
4074
libtorrent starts 2 or 3 threads.
4076
* The first thread is the main thread that will sit
4077
idle in a ``select()`` call most of the time. This thread runs the main loop
4078
that will send and receive data on all connections.
4080
* The second thread is a hash-check thread. Whenever a torrent is added it will
4081
first be passed to this thread for checking the files that may already have been
4082
downloaded. If there is any resume data this thread will make sure it is valid
4083
and matches the files. Once the torrent has been checked, it is passed on to the
4084
main thread that will start it. The hash-check thread has a queue of torrents,
4085
it will only check one torrent at a time.
4087
* The third thread is spawned by asio on systems that don't support
4088
non-blocking host name resolution to simulate non-blocking behavior.
4094
There are three modes in which storage (files on disk) are allocated in libtorrent.
4096
1. The traditional *full allocation* mode, where the entire files are filled up with
4097
zeros before anything is downloaded. libtorrent will look for sparse files support
4098
in the filesystem that is used for storage, and use sparse files or file system
4099
zero fill support if present. This means that on NTFS, full allocation mode will
4100
only allocate storage for the downloaded pieces.
4102
2. The *compact allocation* mode, where only files are allocated for actual
4103
pieces that have been downloaded. This is the default allocation mode in libtorrent.
4105
3. The *sparce allocation*, sparse files are used, and pieces are downloaded directly
4106
to where they belong. This is the recommended (and default) mode.
4108
The allocation mode is selected when a torrent is started. It is passed as an
4109
argument to ``session::add_torrent()`` (see `add_torrent()`_).
4111
The decision to use full allocation or compact allocation typically depends on whether
4112
any files are filtered and if the filesystem supports sparse files.
4117
On filesystems that supports sparse files, this allocation mode will only use
4118
as much space as has been downloaded.
4120
* It does not require an allocation pass on startup.
4122
* It supports skipping files (setting prioirty to 0 to not download).
4124
* Fast resume data will remain valid even when file time stamps are out of date.
4130
When a torrent is started in full allocation mode, the checker thread (see threads_)
4131
will make sure that the entire storage is allocated, and fill any gaps with zeros.
4132
This will be skipped if the filesystem supports sparse files or automatic zero filling.
4133
It will of course still check for existing pieces and fast resume data. The main
4134
drawbacks of this mode are:
4136
* It may take longer to start the torrent, since it will need to fill the files
4137
with zeros on some systems. This delay is linearly dependent on the size of
4140
* The download may occupy unnecessary disk space between download sessions. In case
4141
sparse files are not supported.
4143
* Disk caches usually perform extremely poorly with random access to large files
4144
and may slow down a download considerably.
4146
The benefits of this mode are:
4148
* Downloaded pieces are written directly to their final place in the files and the
4149
total number of disk operations will be fewer and may also play nicer to
4150
filesystems' file allocation, and reduce fragmentation.
4152
* No risk of a download failing because of a full disk during download. Unless
4153
sparse files are being used.
4155
* The fast resume data will be more likely to be usable, regardless of crashes or
4156
out of date data, since pieces won't move around.
4158
* Can be used with the filter files feature.
4163
The compact allocation will only allocate as much storage as it needs to keep the
4164
pieces downloaded so far. This means that pieces will be moved around to be placed
4165
at their final position in the files while downloading (to make sure the completed
4166
download has all its pieces in the correct place). So, the main drawbacks are:
4168
* More disk operations while downloading since pieces are moved around.
4170
* Potentially more fragmentation in the filesystem.
4172
* Cannot be used while filtering files.
4174
The benefits though, are:
4176
* No startup delay, since the files doesn't need allocating.
4178
* The download will not use unnecessary disk space.
4180
* Disk caches perform much better than in full allocation and raises the download
4181
speed limit imposed by the disk.
4183
* Works well on filesystems that doesn't support sparse files.
4185
The algorithm that is used when allocating pieces and slots isn't very complicated.
4186
For the interested, a description follows.
4190
1. let **A** be a newly downloaded piece, with index **n**.
4191
2. let **s** be the number of slots allocated in the file we're
4192
downloading to. (the number of pieces it has room for).
4193
3. if **n** >= **s** then allocate a new slot and put the piece there.
4194
4. if **n** < **s** then allocate a new slot, move the data at
4195
slot **n** to the new slot and put **A** in slot **n**.
4197
allocating a new slot:
4199
1. if there's an unassigned slot (a slot that doesn't
4200
contain any piece), return that slot index.
4201
2. append the new slot at the end of the file (or find an unused slot).
4202
3. let **i** be the index of newly allocated slot
4203
4. if we have downloaded piece index **i** already (to slot **j**) then
4205
1. move the data at slot **j** to slot **i**.
4206
2. return slot index **j** as the newly allocated free slot.
4208
5. return **i** as the newly allocated slot.
4214
These extensions all operates within the `extension protocol`__. The
4215
name of the extension is the name used in the extension-list packets,
4216
and the payload is the data in the extended message (not counting the
4217
length-prefix, message-id nor extension-id).
4219
__ extension_protocol.html
4221
Note that since this protocol relies on one of the reserved bits in the
4222
handshake, it may be incompatible with future versions of the mainline
4225
These are the extensions that are currently implemented.
4230
Extension name: "LT_metadata"
4232
The point with this extension is that you don't have to distribute the
4233
metadata (.torrent-file) separately. The metadata can be distributed
4234
through the bittorrent swarm. The only thing you need to download such
4235
a torrent is the tracker url and the info-hash of the torrent.
4237
It works by assuming that the initial seeder has the metadata and that
4238
the metadata will propagate through the network as more peers join.
4240
There are three kinds of messages in the metadata extension. These packets
4241
are put as payload to the extension message. The three packets are:
4245
* don't have metadata
4249
+-----------+---------------+----------------------------------------+
4250
| size | name | description |
4251
+===========+===============+========================================+
4252
| uint8_t | msg_type | Determines the kind of message this is |
4253
| | | 0 means 'request metadata' |
4254
+-----------+---------------+----------------------------------------+
4255
| uint8_t | start | The start of the metadata block that |
4256
| | | is requested. It is given in 256:ths |
4257
| | | of the total size of the metadata, |
4258
| | | since the requesting client don't know |
4259
| | | the size of the metadata. |
4260
+-----------+---------------+----------------------------------------+
4261
| uint8_t | size | The size of the metadata block that is |
4262
| | | requested. This is also given in |
4263
| | | 256:ths of the total size of the |
4264
| | | metadata. The size is given as size-1. |
4265
| | | That means that if this field is set |
4266
| | | 0, the request wants one 256:th of the |
4268
+-----------+---------------+----------------------------------------+
4272
+-----------+---------------+----------------------------------------+
4273
| size | name | description |
4274
+===========+===============+========================================+
4275
| uint8_t | msg_type | 1 means 'metadata' |
4276
+-----------+---------------+----------------------------------------+
4277
| int32_t | total_size | The total size of the metadata, given |
4278
| | | in number of bytes. |
4279
+-----------+---------------+----------------------------------------+
4280
| int32_t | offset | The offset of where the metadata block |
4281
| | | in this message belongs in the final |
4282
| | | metadata. This is given in bytes. |
4283
+-----------+---------------+----------------------------------------+
4284
| uint8_t[] | metadata | The actual metadata block. The size of |
4285
| | | this part is given implicit by the |
4286
| | | length prefix in the bittorrent |
4287
| | | protocol packet. |
4288
+-----------+---------------+----------------------------------------+
4290
Don't have metadata:
4292
+-----------+---------------+----------------------------------------+
4293
| size | name | description |
4294
+===========+===============+========================================+
4295
| uint8_t | msg_type | 2 means 'I don't have metadata'. |
4296
| | | This message is sent as a reply to a |
4297
| | | metadata request if the the client |
4298
| | | doesn't have any metadata. |
4299
+-----------+---------------+----------------------------------------+
4304
The HTTP seed extension implements `this specification`__.
4306
The libtorrent implementation assumes that, if the URL ends with a slash
4307
('/'), the filename should be appended to it in order to request pieces from
4308
that file. The way this works is that if the torrent is a single-file torrent,
4309
only that filename is appended. If the torrent is a multi-file torrent, the
4310
torrent's name '/' the file name is appended. This is the same directory
4311
structure that libtorrent will download torrents into.
4313
__ http://www.getright.com/seedtorrent.html
4319
Boost.Filesystem will by default check all its paths to make sure they conform
4320
to filename requirements on many platforms. If you don't want this check, you can
4321
set it to either only check for native filesystem requirements or turn it off
4322
altogether. You can use::
4324
boost::filesystem::path::default_name_check(boost::filesystem::native);
4326
for example. For more information, see the `Boost.Filesystem docs`__.
4328
__ http://www.boost.org/libs/filesystem/doc/index.htm
4334
Written by Arvid Norberg. Copyright |copy| 2003-2006
4336
Contributions by Magnus Jonsson, Daniel Wallin and Cory Nelson
4338
Lots of testing, suggestions and contributions by Massaroddel and Tianhao Qiu.
4340
Big thanks to Michael Wojciechowski and Peter Koeleman for making the autotools
4343
Thanks to Reimond Retz for bugfixes, suggestions and testing
4345
Thanks to `University of Ume�`__ for providing development and test hardware.
4347
Project is hosted by sourceforge.
4351
.. |copy| unicode:: 0xA9 .. copyright sign
4352
__ http://www.cs.umu.se
4353
.. |sf_logo| image:: http://sourceforge.net/sflogo.php?group_id=7994
4354
__ http://sourceforge.net