14
libtorrent is a C++ library that aims to be a good alternative to all the
15
other bittorrent implementations around. It is a
16
library and not a full featured client, although it comes with a working
19
The main goals of libtorrent are:
22
* to be memory efficient
23
* to be very easy to use
15
libtorrent is a feature complete C++ bittorrent implementation focusing
16
on efficiency and scalability. It runs on embedded devices as well as
17
desktops. It boasts a well documented library interface that is easy to
18
use. It comes with a simple bittorrent client demonstrating the use of
28
libtorrent is still being developed, however it is stable. It is an ongoing
29
project (including this documentation). The current state includes the
32
* trackerless torrents (using the Mainline kademlia DHT protocol) with
33
some `DHT extensions`_.
35
* NAT-PMP and UPnP support (automatic port mapping on routers that supports it)
36
* uses a separate disk I/O thread to not have the disk ever block on network or
37
client interaction. (see threads_).
38
* supports the bittorrent `extension protocol`_. See extensions_.
39
* supports the uTorrent metadata transfer protocol (i.e. magnet links).
24
libtorrent is under active development. It is an ongoing project. Its
25
current state supports and includes the following features:
30
* plugin interface for implementing custom bittorrent extensions
31
without having to modify libtorrent
32
* supports trackerless torrents (using the Mainline kademlia DHT protocol) with
33
some `DHT extensions`_. `BEP 5`_.
34
* supports the bittorrent `extension protocol`_. See extensions_. `BEP 10`_.
35
* supports the uTorrent metadata transfer protocol `BEP 9`_ (i.e. magnet links).
40
36
* supports the uTorrent peer exchange protocol (PEX).
41
37
* supports local peer discovery (multicasts for peers on the same local network)
42
* adjusts the length of the request queue depending on download rate.
43
* has an adjustable read and write disk cache for improved disk throughput.
44
* multitracker extension support (supports both the `specification by John Hoffman`__
45
and the uTorrent interpretation).
38
* multitracker extension support (supports both strict `BEP 12`_ and the
39
uTorrent interpretation).
47
* supports both sparse files and compact file allocation (where pieces
48
are kept consolidated on disk)
41
* supports lt_trackers extension, to exchange trackers between peers
42
* `HTTP seeding`_, as specified in `BEP 17`_ and `BEP 19`_.
43
* supports the udp-tracker protocol. (`BEP 15`_).
44
* supports the ``no_peer_id=1`` extension that will ease the load off trackers.
45
* supports the ``compact=1`` tracker parameter.
46
* super seeding/initial seeding (`BEP 16`_).
47
* private torrents (`BEP 27`_).
48
* support for IPv6, including `BEP 7`_ and `BEP 24`_.
49
* support for merkle hash tree torrents. This makes the size of torrent files
50
scale well with the size of the content.
52
.. _extensions: manual.html#extensions
53
.. _`http seeding`: manual.html#http-seeding
58
* uses a separate disk I/O thread to not have the disk ever block on network or
59
client interaction. (see threads_).
49
60
* supports files > 2 gigabytes.
50
* serves multiple torrents on a single port and in a single thread
51
61
* fast resume support, a way to get rid of the costly piece check at the
52
62
start of a resumed torrent. Saves the storage state, piece_picker state
53
63
as well as all local peers in a separate fast-resume file.
54
* `HTTP seeding`_, as `specified by Michael Burford of GetRight`__.
64
* has an adjustable read and write disk cache for improved disk throughput.
65
* queues torrents for file check, instead of checking all of them in parallel.
66
* does not have any requirements on the piece order in a torrent that it
67
resumes. This means it can resume a torrent downloaded by any client.
68
* supports both sparse files and compact file allocation (where pieces
69
are kept consolidated on disk)
70
* seed mode, where the files on disk are assumed to be complete, and each
71
piece's hash is verified the first time it is requested.
73
.. _threads: manual.html#threads
78
* adjusts the length of the request queue depending on download rate.
79
* serves multiple torrents on a single port and in a single thread
55
80
* piece picking on block-level (as opposed to piece-level).
56
81
This means it can download parts of the same piece from different peers.
57
82
It will also prefer to download whole pieces from single peers if the
58
83
download speed is high enough from that particular peer.
59
* supports the `udp-tracker protocol`_ by Olaf van der Spek.
60
* queues torrents for file check, instead of checking all of them in parallel.
61
84
* supports http proxies and basic proxy authentication
62
* gzipped tracker-responses
85
* supports gzipped tracker-responses
63
86
* can limit the upload and download bandwidth usage and the maximum number of
65
* implements fair trade. User settable trade-ratio, must at least be 1:1,
66
but one can choose to trade 1 for 2 or any other ratio that isn't unfair
68
* supports the ``no_peer_id=1`` extension that will ease the load off trackers.
69
88
* possibility to limit the number of connections.
70
89
* delays have messages if there's no other outgoing traffic to the peer, and
71
90
doesn't send have messages to peers that already has the piece. This saves
73
* does not have any requirements on the piece order in a torrent that it
74
resumes. This means it can resume a torrent downloaded by any client.
75
* supports the ``compact=1`` tracker parameter.
76
92
* selective downloading. The ability to select which parts of a torrent you
78
94
* ip filter to disallow ip addresses and ip ranges from connecting and
96
* NAT-PMP and UPnP support (automatic port mapping on routers that supports it)
97
* implements automatic upload slots, to optimize download rate without spreading
98
upload capacity too thin. The number of upload slots is adjusted based on the
99
peers' download capacity to work even for connections that are orders of
100
magnitude faster than others.
81
103
.. _`DHT extensions`: dht_extensions.html
82
__ http://bittorrent.org/beps/bep_0012.html
83
__ http://www.getright.com/seedtorrent.html
104
.. _`BEP 5`: http://bittorrent.org/beps/bep_0005.html
105
.. _`BEP 7`: http://bittorrent.org/beps/bep_0007.html
106
.. _`BEP 9`: http://bittorrent.org/beps/bep_0009.html
107
.. _`BEP 10`: http://bittorrent.org/beps/bep_0010.html
108
.. _`BEP 12`: http://bittorrent.org/beps/bep_0012.html
109
.. _`BEP 15`: http://bittorrent.org/beps/bep_0015.html
110
.. _`BEP 16`: http://bittorrent.org/beps/bep_0016.html
111
.. _`BEP 17`: http://bittorrent.org/beps/bep_0017.html
112
.. _`BEP 19`: http://bittorrent.org/beps/bep_0019.html
113
.. _`BEP 24`: http://bittorrent.org/beps/bep_0024.html
114
.. _`BEP 27`: http://bittorrent.org/beps/bep_0027.html
84
115
.. _`extension protocol`: extension_protocol.html
85
.. _`udp-tracker protocol`: udp_tracker_protocol.html
123
All disk I/O in libtorrent is done asynchronously to the network thread, by the
124
disk io thread. When a block is read, the disk io thread reads all subsequent
125
blocks from that piece into the read cache, assuming that the peer requesting
126
the block will also request more blocks from the same piece. This decreases the
127
number of syscalls for reading data. It also decreases delay from seeking.
129
Similarly, for write requests, blocks are cached and flushed to disk once one full
130
piece is complete or the piece is the least recently updated one when more cache
131
space is needed. The cache dynamically allocates space between the write and read
132
cache. The write cache is strictly prioritized over the read cache.
134
The cache blocks that are in used, are locked into physical memory to avoid it
135
being paged out to disk. Allowing the disk cache to be paged out to disk means
136
that it would become extremely inefficient to flush it, since it would have to be
137
read back into physical memory only to be flushed back out to disk again.
139
In order to conserve memory, and system calls, iovec file operations are
140
used to flush multiple cache blocks in a single call.
142
On low-memory systems, the disk cache can be disabled altogether or set to smaller
143
limit, to save memory.
145
The disk caching algorithm is configurable between 'LRU' and 'largest contiguous'.
146
The largest contiguous algorithm is the default and flushes the largest contiguous
147
block of buffers, instead of flushing all blocks belonging to the piece which was
148
written to least recently.
150
For version 0.15 a lot of work went into optimizing the cache algorithm, trying
151
to increase the cache hit rate and utilization. The graph to the left shows the
152
memory utilization in 0.14. This cache is a straight forward, fairly naive, implementation.
153
Every block read will also read all subsequent blocks in that piece into the cache.
154
Whenever we need more space, the entire oldest piece is evicted from the cache. Caching
155
writes always takes presedence over the read cache. Whenever a piece is fully downloaded,
156
it is flushed to disk.
158
.. image:: disk_buffer_before_optimization.png
161
.. image:: disk_buffer.png
164
The left graph shows the problem of evicting entire pieces at a time, and waiting until
165
an entire piece is downloaded until flushing it. These graphs were generated for a torrent
166
with fairly large pieces. This means that granularity was poor in 0.14, since it only
167
dealt with entire pieces. In 0.15, the granularity problem has been fixed by evicting one
168
block at a time from the read cache. This maximizes the read cache utilization. The write
169
cache is also flushed when a sufficient number of contiguous blocks have been downloaded
170
for a piece, which is not tied to the piece size anymore. This way the cache scales a lot
171
better with piece sizes.
173
The graph to the right shows the same download but with the new optimized disk cache
174
algorithm. It clearly shows an increased utilization, which means higher read hit rates
175
or smaller caches with maintained hit rate.
177
high performance disk subsystem
178
-------------------------------
180
In some circumstances, the disk cache may not suffice to provide maximum performance.
181
One such example is high performance seeding, to a large number of peers, over a fast
182
up-link. In such a case, the amount of RAM may simply not be enough to cache disk
183
reads. When there's not enough RAM to cache disk reads, the disk throughput would
184
typically degrade to perform as poorly as with no cache at all, with the majority
185
of the time spent waiting for the disk head to seek.
187
To solve this problem, libtorrent sorts read requests by their physical offset on the
188
disk. They are processed by having the disk read head sweep back and forth over the drive.
190
This makes libtorrent very suitable for large scale, high-throughput seeding.
192
.. image:: disk_access_no_elevator.png
195
.. image:: disk_access_elevator.png
198
These plots illustrates the physical disk offset for reads over time. The left plot
199
is of a run where disk operation re-ordering is turned off and the righ is when it's
200
turned on. The right one has a relatively smooth sine wave shape whereas the left
201
one is more random and involves much longer seeks back and forth over the disk.
203
True physical disk offset queries are only supported on newer linux kernels, Mac OS X and
209
On CPUs with small L2 caches, copying memory can be expensive operations. It is important
210
to keep copying to a minimum on such machines. This mostly applies to embedded systems.
212
In order to minimize the number of times received data is copied, the receive buffer
213
for payload data is received directly into a page aligned disk buffer. If the connection
214
is encrypted, the buffer is decrypted in-place. The buffer is then moved into the disk
215
cache without being copied. Once all the blocks for a piece have been received, or the
216
cache needs to be flushed, all the blocks are passed directly to ``writev()`` to flush
217
them in a single syscall. This means a single copy into user space memory, and a single
218
copy back into kernel memory, as illustrated by this figure:
220
.. image:: write_disk_buffers.png
223
When seeding and uploading in general, unnecessary copying is avoided by caching blocks
224
in aligned buffers, that are copied once into the peer's send buffer. The peer's send buffer
225
is not guaranteed to be aligned, even though it is most of the time. The send buffer is
226
then encrypted with the peer specific key and chained onto the ``iovec`` for sending.
227
This means there is one user space copy in order to allow unaligned peer requests and
228
peer-specific encryption. This is illustrated by the following figure:
230
.. image:: read_disk_buffers.png
237
The piece picker is a central component in a bittorrent implementation. The piece picker
238
in libtorrent is optimized for quickly finding the rarest pieces. It keeps a list of all
239
available pieces sorted by rarity, and pieces with the same rarity, shuffled. The rarest
240
first mode is the dominant piece picker mode. Other modes are supported as well, and
241
used by peers in specific situations.
243
The piece picker allows to combine the availability of a piece with a priority. Together
244
they determine the sort order of the piece list. Pieces with priority 0 will never be
245
picked, which is used for the selective download feature.
247
In order to have as few partially finished pieces as possible, peers have an affinity
248
towards picking blocks from the same pieces as other peers in the same speed category.
249
The speed category is a coarse categorization of peers based on their download rate. This
250
makes slow peers pick blocks from the same piece, and fast peers pick from the same piece,
251
and hence decreasing the likelihood of slow peers blocking the completion of pieces.
253
The piece picker can also be set to download pieces in sequential order.
256
merkle hash tree torrents
257
-------------------------
259
Merkle hash tree torrents is an extension that lets a torrent file only contain the
260
root hash of the hash tree forming the piece hashes. The main benefit of this feature
261
is that regardless of how many pieces there is in a torrent, the .torrent file will
262
always be the same size. It will only grow with the number of files (since it still
263
has to contain the file names).
265
With regular torrents, clients have to request multiple blocks for pieces, typically
266
from different peers, before the data can be verified against the piece hash. The
267
larger the pieces are, the longer it will take to download a complete piece and verify
268
it. Before the piece is verified, it cannot be shared with the swarm, which means the
269
larger piece sizes, the slower turnaround data has when it is downloaded by peers.
270
Since on average the data has to sit around, waiting, in client buffers before it has
271
been verified and can be uploaded again.
273
Another problem with large piece sizes is that it is harder for a client to pinpoint
274
the malicious or buggy peer when a piece fails, and it will take longer to re-download
275
it and take more tries before the piece succeeds the larger the pieces are.
277
The piece size in regular torrents is a tradeoff between the size of the .torrent file
278
itself and the piece size. Often, for files that are 4 GB, the piece size is 2 or 4 MB,
279
just to avoid making the .torrent file too big.
281
Merkle torrents solves these problems by removing the tradeoff between .torrent size and
282
piece size. With merkle torrents, the piece size can be the minimum block size (16 kB),
283
which lets peers verify every block of data received from peers, immediately. This
284
gives a minimum turnaround time and completely removes the problem of identifying malicious
287
.. image:: merkle_tree.png
289
The root hash is built by hashing all the piece hashes pair-wise, until they all collapse
292
.. image:: storage.png
295
customizable file storage
296
-------------------------
298
libtorrent's storage implementation is customizable. That means a special purpose bittorrent
299
client can replace the default way to store files on disk.
301
When implementing a bittorrent cache, it doesn't matter how the data is stored on disk, as
302
long as it can be retrieved and seeded. In that case a new storage class can be implemented
303
(inheriting from the ``storage_interface`` class) that avoids the unnecessary step of mapping
304
slots to files and offsets. The storage can ignore the file boundaries and just store the
305
entire torrent in a single file (which will end up being all the files concatenated). The main
306
advantage of this, other than a slight cpu performance gain, is that all file operations would
307
be page (and sector) aligned. This enables efficient unbuffered I/O, and can potentially
308
lead to more efficient read caching (using the built in disk cache rather than relying on the
309
operating system's disk cache).
311
The storage interface supports operating systems where you can ask for sparse regions
312
(such as Windows and Solaris). The advantage of this is that when checking files, the regions
313
that are known to be sparse can be skipped, which can reduce the time to check a torrent
319
One of the design goals of the libtorrent API is to make common operations simple, but still
320
have it possible to do complicated and advanced operations. This is best illustrated by example
321
code to implement a simple bittorrent client::
324
#include "libtorrent/session.hpp"
326
// usage a.out [torrent-file]
327
int main(int argc, char* argv[]) try
329
using namespace libtorrent;
332
s.listen_on(std::make_pair(6881, 6889));
333
add_torrent_params p;
335
p.ti = new torrent_info(argv[1]);
338
// wait for the user to end
340
std::cin.unsetf(std::ios_base::skipws);
344
catch (std::exception& e)
346
std::cerr << ec.what() << std::endl;
350
This client doesn't give the user any status information or progress about the torrent, but
351
it is fully functional.
353
libtorrent also comes with python bindings for easy access for python developers.
90
libtorrent is portable at least among Windows, MacOS X and other UNIX-systems.
359
libtorrent runs on most major operating systems, including Windows,
360
MacOS X, Linux, BSD and Solaris.
91
361
It uses Boost.Thread, Boost.Filesystem, Boost.Date_time and various other
92
362
boost libraries as well as zlib_ (shipped) and asio_ (shipped). At least version
93
1.33.1 of boost is required.
363
1.34.1 of boost is required.
95
365
.. _zlib: http://www.zlib.org
96
366
.. _asio: http://asio.sf.net
98
Since libtorrent uses asio, it will take full advantage of high performance
368
libtorrent uses asio, hence it will take full advantage of high performance
99
369
network APIs on the most popular platforms. I/O completion ports on windows,
100
370
epoll on linux and kqueue on MacOS X and BSD.
102
372
libtorrent has been successfully compiled and tested on:
104
* Windows 2000 vc7.1, vc8
105
* Linux x86 GCC 3.3, GCC 3.4.2
374
* Windows 2000, XP and Vista vc7.1, vc8
375
* Linux x86 GCC 3.3, GCC 3.4.2, 4.x
376
* Linux PPC GCC 4.1.1
106
377
* MacOS X (darwin), (Apple's) GCC 3.3, (Apple's) GCC 4.0
378
* SunOS 5.8 GCC 3.1 and Sunpro
108
379
* Cygwin GCC 3.3.3