1 /*
2 
3 Copyright (c) 2003-2018, Arvid Norberg
4 All rights reserved.
5 
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9 
10     * Redistributions of source code must retain the above copyright
11       notice, this list of conditions and the following disclaimer.
12     * Redistributions in binary form must reproduce the above copyright
13       notice, this list of conditions and the following disclaimer in
14       the documentation and/or other materials provided with the distribution.
15     * Neither the name of the author nor the names of its
16       contributors may be used to endorse or promote products derived
17       from this software without specific prior written permission.
18 
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 POSSIBILITY OF SUCH DAMAGE.
30 
31 */
32 
33 #ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED
34 #define TORRENT_TORRENT_HANDLE_HPP_INCLUDED
35 
36 #include "libtorrent/config.hpp"
37 
38 #include <vector>
39 #include <set>
40 #include <functional>
41 #include <memory>
42 
43 #include "libtorrent/aux_/disable_warnings_push.hpp"
44 #if TORRENT_ABI_VERSION == 1
45 // for deprecated force_reannounce
46 #include <boost/date_time/posix_time/posix_time_duration.hpp>
47 #endif
48 #include "libtorrent/aux_/disable_warnings_pop.hpp"
49 
50 #include "libtorrent/fwd.hpp"
51 #include "libtorrent/address.hpp"
52 #include "libtorrent/socket.hpp" // tcp::endpoint
53 #include "libtorrent/span.hpp"
54 #include "libtorrent/sha1_hash.hpp"
55 #include "libtorrent/units.hpp"
56 #include "libtorrent/aux_/vector.hpp"
57 #include "libtorrent/storage_defs.hpp"
58 #include "libtorrent/torrent_flags.hpp"
59 #include "libtorrent/peer_info.hpp" // for peer_source_flags_t
60 #include "libtorrent/download_priority.hpp"
61 #include "libtorrent/pex_flags.hpp"
62 #include "libtorrent/broadcast_socket.hpp" // for is_v6
63 
64 namespace libtorrent {
65 namespace aux {
66 	struct session_impl;
67 }
68 
69 #if TORRENT_ABI_VERSION == 1
70 	struct peer_list_entry;
71 #endif
72 	class torrent;
73 
74 #ifndef BOOST_NO_EXCEPTIONS
75 	[[noreturn]] void throw_invalid_handle();
76 #endif
77 
78 	using status_flags_t = flags::bitfield_flag<std::uint32_t, struct status_flags_tag>;
79 	using add_piece_flags_t = flags::bitfield_flag<std::uint8_t, struct add_piece_flags_tag>;
80 	using pause_flags_t = flags::bitfield_flag<std::uint8_t, struct pause_flags_tag>;
81 	using deadline_flags_t = flags::bitfield_flag<std::uint8_t, struct deadline_flags_tag>;
82 	using resume_data_flags_t = flags::bitfield_flag<std::uint8_t, struct resume_data_flags_tag>;
83 	using reannounce_flags_t = flags::bitfield_flag<std::uint8_t, struct reannounce_flags_tag>;
84 	using queue_position_t = aux::strong_typedef<int, struct queue_position_tag>;
85 
86 	// holds the state of a block in a piece. Who we requested
87 	// it from and how far along we are at downloading it.
88 	struct TORRENT_EXPORT block_info
89 	{
90 		// this is the enum used for the block_info::state field.
91 		enum block_state_t
92 		{
93 			// This block has not been downloaded or requested form any peer.
94 			none,
95 			// The block has been requested, but not completely downloaded yet.
96 			requested,
97 			// The block has been downloaded and is currently queued for being
98 			// written to disk.
99 			writing,
100 			// The block has been written to disk.
101 			finished
102 		};
103 
104 	private:
105 		union addr_t
106 		{
107 			address_v4::bytes_type v4;
108 			address_v6::bytes_type v6;
109 		};
110 		addr_t addr;
111 
112 		std::uint16_t port;
113 	public:
114 
115 		// The peer is the ip address of the peer this block was downloaded from.
set_peerlibtorrent::block_info116 		void set_peer(tcp::endpoint const& ep)
117 		{
118 			is_v6_addr = is_v6(ep);
119 			if (is_v6_addr)
120 				addr.v6 = ep.address().to_v6().to_bytes();
121 			else
122 				addr.v4 = ep.address().to_v4().to_bytes();
123 			port = ep.port();
124 		}
peerlibtorrent::block_info125 		tcp::endpoint peer() const
126 		{
127 			if (is_v6_addr)
128 				return tcp::endpoint(address_v6(addr.v6), port);
129 			else
130 				return tcp::endpoint(address_v4(addr.v4), port);
131 		}
132 
133 		// the number of bytes that have been received for this block
134 		unsigned bytes_progress:15;
135 
136 		// the total number of bytes in this block.
137 		unsigned block_size:15;
138 
139 		// the state this block is in (see block_state_t)
140 		unsigned state:2;
141 
142 		// the number of peers that is currently requesting this block. Typically
143 		// this is 0 or 1, but at the end of the torrent blocks may be requested
144 		// by more peers in parallel to speed things up.
145 		unsigned num_peers:14;
146 	private:
147 		// the type of the addr union
148 		bool is_v6_addr:1;
149 	};
150 
151 	// This class holds information about pieces that have outstanding requests
152 	// or outstanding writes
153 	struct TORRENT_EXPORT partial_piece_info
154 	{
155 #if TORRENT_ABI_VERSION == 1
156 #include "libtorrent/aux_/disable_warnings_push.hpp"
157 		partial_piece_info() = default;
158 		partial_piece_info(partial_piece_info&&) noexcept = default;
159 		partial_piece_info(partial_piece_info const&) = default;
160 		partial_piece_info& operator=(partial_piece_info const&) = default;
161 		partial_piece_info& operator=(partial_piece_info&&) noexcept = default;
162 #include "libtorrent/aux_/disable_warnings_pop.hpp"
163 #endif
164 		// the index of the piece in question. ``blocks_in_piece`` is the number
165 		// of blocks in this particular piece. This number will be the same for
166 		// most pieces, but
167 		// the last piece may have fewer blocks than the standard pieces.
168 		piece_index_t piece_index;
169 
170 		// the number of blocks in this piece
171 		int blocks_in_piece;
172 
173 		// the number of blocks that are in the finished state
174 		int finished;
175 
176 		// the number of blocks that are in the writing state
177 		int writing;
178 
179 		// the number of blocks that are in the requested state
180 		int requested;
181 
182 		// this is an array of ``blocks_in_piece`` number of
183 		// items. One for each block in the piece.
184 		//
185 		// .. warning:: This is a pointer that points to an array
186 		//	that's owned by the session object. The next time
187 		//	get_download_queue() is called, it will be invalidated.
188 		block_info* blocks;
189 
190 #if TORRENT_ABI_VERSION == 1
191 		// the speed classes. These may be used by the piece picker to
192 		// coalesce requests of similar download rates
193 		enum state_t { none, slow, medium, fast };
194 
195 		// the download speed class this piece falls into.
196 		// this is used internally to cluster peers of the same
197 		// speed class together when requesting blocks.
198 		//
199 		// set to either ``fast``, ``medium``, ``slow`` or ``none``. It tells
200 		// which download rate category the peers downloading this piece falls
201 		// into. ``none`` means that no peer is currently downloading any part of
202 		// the piece. Peers prefer picking pieces from the same category as
203 		// themselves. The reason for this is to keep the number of partially
204 		// downloaded pieces down. Pieces set to ``none`` can be converted into
205 		// any of ``fast``, ``medium`` or ``slow`` as soon as a peer want to
206 		// download from it.
207 		state_t TORRENT_DEPRECATED_MEMBER piece_state;
208 #endif
209 	};
210 
211 	// for std::hash (and to support using this type in unordered_map etc.)
212 	TORRENT_EXPORT std::size_t hash_value(torrent_handle const& h);
213 
214 	// You will usually have to store your torrent handles somewhere, since it's
215 	// the object through which you retrieve information about the torrent and
216 	// aborts the torrent.
217 	//
218 	// .. warning::
219 	// 	Any member function that returns a value or fills in a value has to be
220 	// 	made synchronously. This means it has to wait for the main thread to
221 	// 	complete the query before it can return. This might potentially be
222 	// 	expensive if done from within a GUI thread that needs to stay
223 	// 	responsive. Try to avoid querying for information you don't need, and
224 	// 	try to do it in as few calls as possible. You can get most of the
225 	// 	interesting information about a torrent from the
226 	// 	torrent_handle::status() call.
227 	//
228 	// The default constructor will initialize the handle to an invalid state.
229 	// Which means you cannot perform any operation on it, unless you first
230 	// assign it a valid handle. If you try to perform any operation on an
231 	// uninitialized handle, it will throw ``invalid_handle``.
232 	//
233 	// .. warning::
234 	// 	All operations on a torrent_handle may throw system_error
235 	// 	exception, in case the handle is no longer referring to a torrent.
236 	// 	There is one exception is_valid() will never throw. Since the torrents
237 	// 	are processed by a background thread, there is no guarantee that a
238 	// 	handle will remain valid between two calls.
239 	//
240 	struct TORRENT_EXPORT torrent_handle
241 	{
242 		friend struct aux::session_impl;
243 		friend struct session_handle;
244 		friend class torrent;
245 		friend TORRENT_EXPORT std::size_t hash_value(torrent_handle const& th);
246 
247 		// constructs a torrent handle that does not refer to a torrent.
248 		// i.e. is_valid() will return false.
249 		torrent_handle() noexcept = default;
250 
251 		// hidden
252 		torrent_handle(torrent_handle const& t) = default;
253 		torrent_handle(torrent_handle&& t) noexcept = default;
254 		torrent_handle& operator=(torrent_handle const&) = default;
255 		torrent_handle& operator=(torrent_handle&&) noexcept = default;
256 
257 
258 #if TORRENT_ABI_VERSION == 1
259 		using flags_t = add_piece_flags_t;
260 		using status_flags_t = libtorrent::status_flags_t;
261 		using pause_flags_t = libtorrent::pause_flags_t;
262 		using save_resume_flags_t = libtorrent::resume_data_flags_t;
263 		using reannounce_flags_t = libtorrent::reannounce_flags_t;
264 #endif
265 
266 		// instruct libtorrent to overwrite any data that may already have been
267 		// downloaded with the data of the new piece being added. Using this
268 		// flag when adding a piece that is actively being downloaded from other
269 		// peers may have some unexpected consequences, as blocks currently
270 		// being downloaded from peers may not be replaced.
271 		static constexpr add_piece_flags_t overwrite_existing = 0_bit;
272 
273 		// This function will write ``data`` to the storage as piece ``piece``,
274 		// as if it had been downloaded from a peer. ``data`` is expected to
275 		// point to a buffer of as many bytes as the size of the specified piece.
276 		// The data in the buffer is copied and passed on to the disk IO thread
277 		// to be written at a later point.
278 		//
279 		// By default, data that's already been downloaded is not overwritten by
280 		// this buffer. If you trust this data to be correct (and pass the piece
281 		// hash check) you may pass the overwrite_existing flag. This will
282 		// instruct libtorrent to overwrite any data that may already have been
283 		// downloaded with this data.
284 		//
285 		// Since the data is written asynchronously, you may know that is passed
286 		// or failed the hash check by waiting for piece_finished_alert or
287 		// hash_failed_alert.
288 		//
289 		// Adding pieces while the torrent is being checked (i.e. in
290 		// torrent_status::checking_files state) is not supported.
291 		void add_piece(piece_index_t piece, char const* data, add_piece_flags_t flags = {}) const;
292 
293 		// This function starts an asynchronous read operation of the specified
294 		// piece from this torrent. You must have completed the download of the
295 		// specified piece before calling this function.
296 		//
297 		// When the read operation is completed, it is passed back through an
298 		// alert, read_piece_alert. Since this alert is a response to an explicit
299 		// call, it will always be posted, regardless of the alert mask.
300 		//
301 		// Note that if you read multiple pieces, the read operations are not
302 		// guaranteed to finish in the same order as you initiated them.
303 		void read_piece(piece_index_t piece) const;
304 
305 		// Returns true if this piece has been completely downloaded and written
306 		// to disk, and false otherwise.
307 		bool have_piece(piece_index_t piece) const;
308 
309 #if TORRENT_ABI_VERSION == 1
310 		// internal
311 		TORRENT_DEPRECATED
312 		void get_full_peer_list(std::vector<peer_list_entry>& v) const;
313 #endif
314 
315 		// takes a reference to a vector that will be cleared and filled with one
316 		// entry for each peer connected to this torrent, given the handle is
317 		// valid. If the torrent_handle is invalid, it will throw
318 		// system_error exception. Each entry in the vector contains
319 		// information about that particular peer. See peer_info.
320 		void get_peer_info(std::vector<peer_info>& v) const;
321 
322 		// calculates ``distributed_copies``, ``distributed_full_copies`` and
323 		// ``distributed_fraction``.
324 		static constexpr status_flags_t query_distributed_copies = 0_bit;
325 
326 		// includes partial downloaded blocks in ``total_done`` and
327 		// ``total_wanted_done``.
328 		static constexpr status_flags_t query_accurate_download_counters = 1_bit;
329 
330 		// includes ``last_seen_complete``.
331 		static constexpr status_flags_t query_last_seen_complete = 2_bit;
332 		// populate the ``pieces`` field in torrent_status.
333 		static constexpr status_flags_t query_pieces = 3_bit;
334 		// includes ``verified_pieces`` (only applies to torrents in *seed
335 		// mode*).
336 		static constexpr status_flags_t query_verified_pieces = 4_bit;
337 		// includes ``torrent_file``, which is all the static information from
338 		// the .torrent file.
339 		static constexpr status_flags_t query_torrent_file = 5_bit;
340 		// includes ``name``, the name of the torrent. This is either derived
341 		// from the .torrent file, or from the ``&dn=`` magnet link argument
342 		// or possibly some other source. If the name of the torrent is not
343 		// known, this is an empty string.
344 		static constexpr status_flags_t query_name = 6_bit;
345 		// includes ``save_path``, the path to the directory the files of the
346 		// torrent are saved to.
347 		static constexpr status_flags_t query_save_path = 7_bit;
348 
349 		// ``status()`` will return a structure with information about the status
350 		// of this torrent. If the torrent_handle is invalid, it will throw
351 		// system_error exception. See torrent_status. The ``flags``
352 		// argument filters what information is returned in the torrent_status.
353 		// Some information in there is relatively expensive to calculate, and if
354 		// you're not interested in it (and see performance issues), you can
355 		// filter them out.
356 		//
357 		// By default everything is included. The flags you can use to decide
358 		// what to *include* are defined in this class.
359 		torrent_status status(status_flags_t flags = status_flags_t::all()) const;
360 
361 		// ``get_download_queue()`` takes a non-const reference to a vector which
362 		// it will fill with information about pieces that are partially
363 		// downloaded or not downloaded at all but partially requested. See
364 		// partial_piece_info for the fields in the returned vector.
365 		void get_download_queue(std::vector<partial_piece_info>& queue) const;
366 
367 		// used to ask libtorrent to send an alert once the piece has been
368 		// downloaded, by passing alert_when_available. When set, the
369 		// read_piece_alert alert will be delivered, with the piece data, when
370 		// it's downloaded.
371 		static constexpr deadline_flags_t alert_when_available = 0_bit;
372 
373 		// This function sets or resets the deadline associated with a specific
374 		// piece index (``index``). libtorrent will attempt to download this
375 		// entire piece before the deadline expires. This is not necessarily
376 		// possible, but pieces with a more recent deadline will always be
377 		// prioritized over pieces with a deadline further ahead in time. The
378 		// deadline (and flags) of a piece can be changed by calling this
379 		// function again.
380 		//
381 		// If the piece is already downloaded when this call is made, nothing
382 		// happens, unless the alert_when_available flag is set, in which case it
383 		// will have the same effect as calling read_piece() for ``index``.
384 		//
385 		// ``deadline`` is the number of milliseconds until this piece should be
386 		// completed.
387 		//
388 		// ``reset_piece_deadline`` removes the deadline from the piece. If it
389 		// hasn't already been downloaded, it will no longer be considered a
390 		// priority.
391 		//
392 		// ``clear_piece_deadlines()`` removes deadlines on all pieces in
393 		// the torrent. As if reset_piece_deadline() was called on all pieces.
394 		void set_piece_deadline(piece_index_t index, int deadline, deadline_flags_t flags = {}) const;
395 		void reset_piece_deadline(piece_index_t index) const;
396 		void clear_piece_deadlines() const;
397 
398 #if TORRENT_ABI_VERSION == 1
399 		// This sets the bandwidth priority of this torrent. The priority of a
400 		// torrent determines how much bandwidth its peers are assigned when
401 		// distributing upload and download rate quotas. A high number gives more
402 		// bandwidth. The priority must be within the range [0, 255].
403 		//
404 		// The default priority is 0, which is the lowest priority.
405 		//
406 		// To query the priority of a torrent, use the
407 		// ``torrent_handle::status()`` call.
408 		//
409 		// Torrents with higher priority will not necessarily get as much
410 		// bandwidth as they can consume, even if there's is more quota. Other
411 		// peers will still be weighed in when bandwidth is being distributed.
412 		// With other words, bandwidth is not distributed strictly in order of
413 		// priority, but the priority is used as a weight.
414 		//
415 		// Peers whose Torrent has a higher priority will take precedence when
416 		// distributing unchoke slots. This is a strict prioritisation where
417 		// every interested peer on a high priority torrent will be unchoked
418 		// before any other, lower priority, torrents have any peers unchoked.
419 		// deprecated in 1.2
420 		TORRENT_DEPRECATED
421 		void set_priority(int prio) const;
422 
423 #if !TORRENT_NO_FPU
424 		// fills the specified vector with the download progress [0, 1]
425 		// of each file in the torrent. The files are ordered as in
426 		// the torrent_info.
427 		TORRENT_DEPRECATED
428 		void file_progress(std::vector<float>& progress) const;
429 #endif
430 
431 		TORRENT_DEPRECATED
432 		void file_status(std::vector<open_file_state>& status) const;
433 #endif
434 
435 		// flags to be passed in file_progress().
436 		enum file_progress_flags_t
437 		{
438 			// only calculate file progress at piece granularity. This makes
439 			// the file_progress() call cheaper and also only takes bytes that
440 			// have passed the hash check into account, so progress cannot
441 			// regress in this mode.
442 			piece_granularity = 1
443 		};
444 
445 		// This function fills in the supplied vector with the number of
446 		// bytes downloaded of each file in this torrent. The progress values are
447 		// ordered the same as the files in the torrent_info. This operation is
448 		// not very cheap. Its complexity is *O(n + mj)*. Where *n* is the number
449 		// of files, *m* is the number of downloading pieces and *j* is the
450 		// number of blocks in a piece.
451 		//
452 		// The ``flags`` parameter can be used to specify the granularity of the
453 		// file progress. If left at the default value of 0, the progress will be
454 		// as accurate as possible, but also more expensive to calculate. If
455 		// ``torrent_handle::piece_granularity`` is specified, the progress will
456 		// be specified in piece granularity. i.e. only pieces that have been
457 		// fully downloaded and passed the hash check count. When specifying
458 		// piece granularity, the operation is a lot cheaper, since libtorrent
459 		// already keeps track of this internally and no calculation is required.
460 		void file_progress(std::vector<std::int64_t>& progress, int flags = 0) const;
461 
462 		// This function returns a vector with status about files
463 		// that are open for this torrent. Any file that is not open
464 		// will not be reported in the vector, i.e. it's possible that
465 		// the vector is empty when returning, if none of the files in the
466 		// torrent are currently open.
467 		//
468 		// See open_file_state
469 		std::vector<open_file_state> file_status() const;
470 
471 		// If the torrent is in an error state (i.e. ``torrent_status::error`` is
472 		// non-empty), this will clear the error and start the torrent again.
473 		void clear_error() const;
474 
475 		// ``trackers()`` will return the list of trackers for this torrent. The
476 		// announce entry contains both a string ``url`` which specify the
477 		// announce url for the tracker as well as an int ``tier``, which is
478 		// specifies the order in which this tracker is tried. If you want
479 		// libtorrent to use another list of trackers for this torrent, you can
480 		// use ``replace_trackers()`` which takes a list of the same form as the
481 		// one returned from ``trackers()`` and will replace it. If you want an
482 		// immediate effect, you have to call force_reannounce(). See
483 		// announce_entry.
484 		//
485 		// ``add_tracker()`` will look if the specified tracker is already in the
486 		// set. If it is, it doesn't do anything. If it's not in the current set
487 		// of trackers, it will insert it in the tier specified in the
488 		// announce_entry.
489 		//
490 		// The updated set of trackers will be saved in the resume data, and when
491 		// a torrent is started with resume data, the trackers from the resume
492 		// data will replace the original ones.
493 		std::vector<announce_entry> trackers() const;
494 		void replace_trackers(std::vector<announce_entry> const&) const;
495 		void add_tracker(announce_entry const&) const;
496 
497 		// TODO: 3 unify url_seed and http_seed with just web_seed, using the
498 		// web_seed_entry.
499 
500 		// ``add_url_seed()`` adds another url to the torrent's list of url
501 		// seeds. If the given url already exists in that list, the call has no
502 		// effect. The torrent will connect to the server and try to download
503 		// pieces from it, unless it's paused, queued, checking or seeding.
504 		// ``remove_url_seed()`` removes the given url if it exists already.
505 		// ``url_seeds()`` return a set of the url seeds currently in this
506 		// torrent. Note that URLs that fails may be removed automatically from
507 		// the list.
508 		//
509 		// See http-seeding_ for more information.
510 		void add_url_seed(std::string const& url) const;
511 		void remove_url_seed(std::string const& url) const;
512 		std::set<std::string> url_seeds() const;
513 
514 		// These functions are identical as the ``*_url_seed()`` variants, but
515 		// they operate on `BEP 17`_ web seeds instead of `BEP 19`_.
516 		//
517 		// See http-seeding_ for more information.
518 		void add_http_seed(std::string const& url) const;
519 		void remove_http_seed(std::string const& url) const;
520 		std::set<std::string> http_seeds() const;
521 
522 		// add the specified extension to this torrent. The ``ext`` argument is
523 		// a function that will be called from within libtorrent's context
524 		// passing in the internal torrent object and the specified userdata
525 		// pointer. The function is expected to return a shared pointer to
526 		// a torrent_plugin instance.
527 		void add_extension(
528 			std::function<std::shared_ptr<torrent_plugin>(torrent_handle const&, void*)> const& ext
529 			, void* userdata = nullptr);
530 
531 		// ``set_metadata`` expects the *info* section of metadata. i.e. The
532 		// buffer passed in will be hashed and verified against the info-hash. If
533 		// it fails, a ``metadata_failed_alert`` will be generated. If it passes,
534 		// a ``metadata_received_alert`` is generated. The function returns true
535 		// if the metadata is successfully set on the torrent, and false
536 		// otherwise. If the torrent already has metadata, this function will not
537 		// affect the torrent, and false will be returned.
538 		bool set_metadata(span<char const> metadata) const;
539 
540 #if TORRENT_ABI_VERSION == 1
541 		TORRENT_DEPRECATED
set_metadatalibtorrent::torrent_handle542 		bool set_metadata(char const* metadata, int size) const
543 		{ return set_metadata({metadata, size}); }
544 #endif
545 
546 		// Returns true if this handle refers to a valid torrent and false if it
547 		// hasn't been initialized or if the torrent it refers to has been
548 		// removed from the session AND destructed.
549 		//
550 		// To tell if the torrent_handle is in the session, use
551 		// torrent_handle::in_session(). This will return true before
552 		// session_handle::remove_torrent() is called, and false
553 		// afterward.
554 		//
555 		// Clients should only use is_valid() to determine if the result of
556 		// session::find_torrent() was successful.
557 		//
558 		// Unlike other member functions which return a value, is_valid()
559 		// completes immediately, without blocking on a result from the
560 		// network thread. Also unlike other functions, it never throws
561 		// the system_error exception.
562 		bool is_valid() const;
563 
564 		// will delay the disconnect of peers that we're still downloading
565 		// outstanding requests from. The torrent will not accept any more
566 		// requests and will disconnect all idle peers. As soon as a peer is done
567 		// transferring the blocks that were requested from it, it is
568 		// disconnected. This is a graceful shut down of the torrent in the sense
569 		// that no downloaded bytes are wasted.
570 		static constexpr pause_flags_t graceful_pause = 0_bit;
571 		static constexpr pause_flags_t clear_disk_cache = 1_bit;
572 
573 		// ``pause()``, and ``resume()`` will disconnect all peers and reconnect
574 		// all peers respectively. When a torrent is paused, it will however
575 		// remember all share ratios to all peers and remember all potential (not
576 		// connected) peers. Torrents may be paused automatically if there is a
577 		// file error (e.g. disk full) or something similar. See
578 		// file_error_alert.
579 		//
580 		// To know if a torrent is paused or not, call
581 		// ``torrent_handle::status()`` and inspect ``torrent_status::paused``.
582 		//
583 		// .. note::
584 		// 	Torrents that are auto-managed may be automatically resumed again. It
585 		// 	does not make sense to pause an auto-managed torrent without making it
586 		// 	not auto-managed first. Torrents are auto-managed by default when added
587 		// 	to the session. For more information, see queuing_.
588 		//
589 		void pause(pause_flags_t flags = {}) const;
590 		void resume() const;
591 
592 		// sets and gets the torrent state flags. See torrent_flags_t.
593 		// The ``set_flags`` overload that take a mask will affect all
594 		// flags part of the mask, and set their values to what the
595 		// ``flags`` argument is set to. This allows clearing and
596 		// setting flags in a single function call.
597 		// The ``set_flags`` overload that just takes flags, sets all
598 		// the specified flags and leave any other flags unchanged.
599 		// ``unset_flags`` clears the specified flags, while leaving
600 		// any other flags unchanged.
601 		//
602 		// The `seed_mode` flag is special, it can only be cleared once the
603 		// torrent has been added, and it can only be set as part of the
604 		// add_torrent_params flags, when adding the torrent.
605 		torrent_flags_t flags() const;
606 		void set_flags(torrent_flags_t flags, torrent_flags_t mask) const;
607 		void set_flags(torrent_flags_t flags) const;
608 		void unset_flags(torrent_flags_t flags) const;
609 
610 		// Instructs libtorrent to flush all the disk caches for this torrent and
611 		// close all file handles. This is done asynchronously and you will be
612 		// notified that it's complete through cache_flushed_alert.
613 		//
614 		// Note that by the time you get the alert, libtorrent may have cached
615 		// more data for the torrent, but you are guaranteed that whatever cached
616 		// data libtorrent had by the time you called
617 		// ``torrent_handle::flush_cache()`` has been written to disk.
618 		void flush_cache() const;
619 
620 		// ``force_recheck`` puts the torrent back in a state where it assumes to
621 		// have no resume data. All peers will be disconnected and the torrent
622 		// will stop announcing to the tracker. The torrent will be added to the
623 		// checking queue, and will be checked (all the files will be read and
624 		// compared to the piece hashes). Once the check is complete, the torrent
625 		// will start connecting to peers again, as normal.
626 		// The torrent will be placed last in queue, i.e. its queue position
627 		// will be the highest of all torrents in the session.
628 		void force_recheck() const;
629 
630 		// the disk cache will be flushed before creating the resume data.
631 		// This avoids a problem with file timestamps in the resume data in
632 		// case the cache hasn't been flushed yet.
633 		static constexpr resume_data_flags_t flush_disk_cache = 0_bit;
634 
635 		// the resume data will contain the metadata from the torrent file as
636 		// well. This is default for any torrent that's added without a
637 		// torrent file (such as a magnet link or a URL).
638 		static constexpr resume_data_flags_t save_info_dict = 1_bit;
639 
640 		// if nothing significant has changed in the torrent since the last
641 		// time resume data was saved, fail this attempt. Significant changes
642 		// primarily include more data having been downloaded, file or piece
643 		// priorities having changed etc. If the resume data doesn't need
644 		// saving, a save_resume_data_failed_alert is posted with the error
645 		// resume_data_not_modified.
646 		static constexpr resume_data_flags_t only_if_modified = 2_bit;
647 
648 		// ``save_resume_data()`` asks libtorrent to generate fast-resume data for
649 		// this torrent.
650 		//
651 		// This operation is asynchronous, ``save_resume_data`` will return
652 		// immediately. The resume data is delivered when it's done through an
653 		// save_resume_data_alert.
654 		//
655 		// The fast resume data will be empty in the following cases:
656 		//
657 		//	1. The torrent handle is invalid.
658 		//	2. The torrent hasn't received valid metadata and was started without
659 		//	   metadata (see libtorrent's metadata-from-peers_ extension)
660 		//
661 		// Note that by the time you receive the fast resume data, it may already
662 		// be invalid if the torrent is still downloading! The recommended
663 		// practice is to first pause the session, then generate the fast resume
664 		// data, and then close it down. Make sure to not remove_torrent() before
665 		// you receive the save_resume_data_alert though. There's no need to
666 		// pause when saving intermittent resume data.
667 		//
668 		//.. warning::
669 		//   If you pause every torrent individually instead of pausing the
670 		//   session, every torrent will have its paused state saved in the
671 		//   resume data!
672 		//
673 		//.. note::
674 		//   It is typically a good idea to save resume data whenever a torrent
675 		//   is completed or paused. In those cases you don't need to pause the
676 		//   torrent or the session, since the torrent will do no more writing to
677 		//   its files. If you save resume data for torrents when they are
678 		//   paused, you can accelerate the shutdown process by not saving resume
679 		//   data again for paused torrents. Completed torrents should have their
680 		//   resume data saved when they complete and on exit, since their
681 		//   statistics might be updated.
682 		//
683 		//	In full allocation mode the resume data is never invalidated by
684 		//	subsequent writes to the files, since pieces won't move around. This
685 		//	means that you don't need to pause before writing resume data in full
686 		//	or sparse mode. If you don't, however, any data written to disk after
687 		//	you saved resume data and before the session closed is lost.
688 		//
689 		// It also means that if the resume data is out dated, libtorrent will
690 		// not re-check the files, but assume that it is fairly recent. The
691 		// assumption is that it's better to loose a little bit than to re-check
692 		// the entire file.
693 		//
694 		// It is still a good idea to save resume data periodically during
695 		// download as well as when closing down.
696 		//
697 		// Example code to pause and save resume data for all torrents and wait
698 		// for the alerts:
699 		//
700 		// .. code:: c++
701 		//
702 		//	extern int outstanding_resume_data; // global counter of outstanding resume data
703 		//	std::vector<torrent_handle> handles = ses.get_torrents();
704 		//	ses.pause();
705 		//	for (torrent_handle const& h : handles) try
706 		//	{
707 		//		torrent_status s = h.status();
708 		//		if (!s.has_metadata || !s.need_save_resume_data()) continue;
709 		//
710 		//		h.save_resume_data();
711 		//		++outstanding_resume_data;
712 		//	}
713 		//	catch (lt::system_error const& e)
714 		//	{
715 		//		// the handle was invalid, ignore this one and move to the next
716 		//	}
717 		//
718 		//	while (outstanding_resume_data > 0)
719 		//	{
720 		//		alert const* a = ses.wait_for_alert(seconds(10));
721 		//
722 		//		// if we don't get an alert within 10 seconds, abort
723 		//		if (a == nullptr) break;
724 		//
725 		//		std::vector<alert*> alerts;
726 		//		ses.pop_alerts(&alerts);
727 		//
728 		//		for (alert* i : alerts)
729 		//		{
730 		//			if (alert_cast<save_resume_data_failed_alert>(i))
731 		//			{
732 		//				process_alert(i);
733 		//				--outstanding_resume_data;
734 		//				continue;
735 		//			}
736 		//
737 		//			save_resume_data_alert const* rd = alert_cast<save_resume_data_alert>(i);
738 		//			if (rd == nullptr)
739 		//			{
740 		//				process_alert(i);
741 		//				continue;
742 		//			}
743 		//
744 		//			torrent_handle h = rd->handle;
745 		//			torrent_status st = h.status(torrent_handle::query_save_path
746 		//				| torrent_handle::query_name);
747 		//			std::ofstream out((st.save_path
748 		//				+ "/" + st.name + ".fastresume").c_str()
749 		//				, std::ios_base::binary);
750 		//			std::vector<char> buf = write_resume_data_buf(rd->params);
751 		//			out.write(buf.data(), buf.size());
752 		//			--outstanding_resume_data;
753 		//		}
754 		//	}
755 		//
756 		//.. note::
757 		//	Note how ``outstanding_resume_data`` is a global counter in this
758 		//	example. This is deliberate, otherwise there is a race condition for
759 		//	torrents that was just asked to save their resume data, they posted
760 		//	the alert, but it has not been received yet. Those torrents would
761 		//	report that they don't need to save resume data again, and skipped by
762 		//	the initial loop, and thwart the counter otherwise.
763 		void save_resume_data(resume_data_flags_t flags = {}) const;
764 
765 		// This function returns true if any whole chunk has been downloaded
766 		// since the torrent was first loaded or since the last time the resume
767 		// data was saved. When saving resume data periodically, it makes sense
768 		// to skip any torrent which hasn't downloaded anything since the last
769 		// time.
770 		//
771 		//.. note::
772 		//	A torrent's resume data is considered saved as soon as the
773 		//	save_resume_data_alert is posted. It is important to make sure this
774 		//	alert is received and handled in order for this function to be
775 		//	meaningful.
776 		bool need_save_resume_data() const;
777 
778 		// Every torrent that is added is assigned a queue position exactly one
779 		// greater than the greatest queue position of all existing torrents.
780 		// Torrents that are being seeded have -1 as their queue position, since
781 		// they're no longer in line to be downloaded.
782 		//
783 		// When a torrent is removed or turns into a seed, all torrents with
784 		// greater queue positions have their positions decreased to fill in the
785 		// space in the sequence.
786 		//
787 		// ``queue_position()`` returns the torrent's position in the download
788 		// queue. The torrents with the smallest numbers are the ones that are
789 		// being downloaded. The smaller number, the closer the torrent is to the
790 		// front of the line to be started.
791 		//
792 		// The queue position is also available in the torrent_status.
793 		//
794 		// The ``queue_position_*()`` functions adjust the torrents position in
795 		// the queue. Up means closer to the front and down means closer to the
796 		// back of the queue. Top and bottom refers to the front and the back of
797 		// the queue respectively.
798 		queue_position_t queue_position() const;
799 		void queue_position_up() const;
800 		void queue_position_down() const;
801 		void queue_position_top() const;
802 		void queue_position_bottom() const;
803 
804 		// updates the position in the queue for this torrent. The relative order
805 		// of all other torrents remain intact but their numerical queue position
806 		// shifts to make space for this torrent's new position
807 		void queue_position_set(queue_position_t p) const;
808 
809 		// For SSL torrents, use this to specify a path to a .pem file to use as
810 		// this client's certificate. The certificate must be signed by the
811 		// certificate in the .torrent file to be valid.
812 		//
813 		// The set_ssl_certificate_buffer() overload takes the actual certificate,
814 		// private key and DH params as strings, rather than paths to files.
815 		//
816 		// ``cert`` is a path to the (signed) certificate in .pem format
817 		// corresponding to this torrent.
818 		//
819 		// ``private_key`` is a path to the private key for the specified
820 		// certificate. This must be in .pem format.
821 		//
822 		// ``dh_params`` is a path to the Diffie-Hellman parameter file, which
823 		// needs to be in .pem format. You can generate this file using the
824 		// openssl command like this: ``openssl dhparam -outform PEM -out
825 		// dhparams.pem 512``.
826 		//
827 		// ``passphrase`` may be specified if the private key is encrypted and
828 		// requires a passphrase to be decrypted.
829 		//
830 		// Note that when a torrent first starts up, and it needs a certificate,
831 		// it will suspend connecting to any peers until it has one. It's
832 		// typically desirable to resume the torrent after setting the SSL
833 		// certificate.
834 		//
835 		// If you receive a torrent_need_cert_alert, you need to call this to
836 		// provide a valid cert. If you don't have a cert you won't be allowed to
837 		// connect to any peers.
838 		void set_ssl_certificate(std::string const& certificate
839 			, std::string const& private_key
840 			, std::string const& dh_params
841 			, std::string const& passphrase = "");
842 		void set_ssl_certificate_buffer(std::string const& certificate
843 			, std::string const& private_key
844 			, std::string const& dh_params);
845 
846 		// Returns the storage implementation for this torrent. This depends on the
847 		// storage constructor function that was passed to add_torrent.
848 		storage_interface* get_storage_impl() const;
849 
850 		// Returns a pointer to the torrent_info object associated with this
851 		// torrent. The torrent_info object may be a copy of the internal object.
852 		// If the torrent doesn't have metadata, the pointer will not be
853 		// initialized (i.e. a nullptr). The torrent may be in a state
854 		// without metadata only if it was started without a .torrent file, e.g.
855 		// by being added by magnet link
856 		std::shared_ptr<const torrent_info> torrent_file() const;
857 
858 #if TORRENT_ABI_VERSION == 1
859 
860 		// ================ start deprecation ============
861 
862 		// deprecated in 1.2
863 		// use set_flags() and unset_flags() instead
864 		TORRENT_DEPRECATED
865 		void stop_when_ready(bool b) const;
866 		TORRENT_DEPRECATED
867 		void set_upload_mode(bool b) const;
868 		TORRENT_DEPRECATED
869 		void set_share_mode(bool b) const;
870 		TORRENT_DEPRECATED
871 		void apply_ip_filter(bool b) const;
872 		TORRENT_DEPRECATED
873 		void auto_managed(bool m) const;
874 		TORRENT_DEPRECATED
875 		void set_pinned(bool p) const;
876 		TORRENT_DEPRECATED
877 		void set_sequential_download(bool sd) const;
878 
879 
880 		// deprecated in 1.0
881 		// use status() instead (with query_save_path)
882 		TORRENT_DEPRECATED
883 		std::string save_path() const;
884 
885 		// deprecated in 1.0
886 		// use status() instead (with query_name)
887 		// returns the name of this torrent, in case it doesn't
888 		// have metadata it returns the name assigned to it
889 		// when it was added.
890 		TORRENT_DEPRECATED
891 		std::string name() const;
892 
893 		// use torrent_file() instead
894 		TORRENT_DEPRECATED
895 		const torrent_info& get_torrent_info() const;
896 
897 		// deprecated in 0.16, feature will be removed
898 		TORRENT_DEPRECATED
899 		int get_peer_upload_limit(tcp::endpoint ip) const;
900 		TORRENT_DEPRECATED
901 		int get_peer_download_limit(tcp::endpoint ip) const;
902 		TORRENT_DEPRECATED
903 		void set_peer_upload_limit(tcp::endpoint ip, int limit) const;
904 		TORRENT_DEPRECATED
905 		void set_peer_download_limit(tcp::endpoint ip, int limit) const;
906 
907 		// deprecated in 0.16, feature will be removed
908 		TORRENT_DEPRECATED
909 		void set_ratio(float up_down_ratio) const;
910 
911 		// deprecated in 0.16. use status() instead, and inspect the
912 		// torrent_status::flags field. Alternatively, call flags() directly on
913 		// the torrent_handle
914 		TORRENT_DEPRECATED
915 		bool is_seed() const;
916 		TORRENT_DEPRECATED
917 		bool is_finished() const;
918 		TORRENT_DEPRECATED
919 		bool is_paused() const;
920 		TORRENT_DEPRECATED
921 		bool is_auto_managed() const;
922 		TORRENT_DEPRECATED
923 		bool is_sequential_download() const;
924 		TORRENT_DEPRECATED
925 		bool has_metadata() const;
926 		TORRENT_DEPRECATED
927 		bool super_seeding() const;
928 
929 		// deprecated in 0.14
930 		// use save_resume_data() instead. It is async. and
931 		// will return the resume data in an alert
932 		TORRENT_DEPRECATED
933 		entry write_resume_data() const;
934 
935 		// ``use_interface()`` sets the network interface this torrent will use
936 		// when it opens outgoing connections. By default, it uses the same
937 		// interface as the session uses to listen on. The parameter must be a
938 		// string containing one or more, comma separated, ip-address (either an
939 		// IPv4 or IPv6 address). When specifying multiple interfaces, the
940 		// torrent will round-robin which interface to use for each outgoing
941 		// connection. This is useful for clients that are multi-homed.
942 		TORRENT_DEPRECATED
943 		void use_interface(const char* net_interface) const;
944 		// ================ end deprecation ============
945 #endif
946 
947 		// Fills the specified ``std::vector<int>`` with the availability for
948 		// each piece in this torrent. libtorrent does not keep track of
949 		// availability for seeds, so if the torrent is seeding the availability
950 		// for all pieces is reported as 0.
951 		//
952 		// The piece availability is the number of peers that we are connected
953 		// that has advertised having a particular piece. This is the information
954 		// that libtorrent uses in order to prefer picking rare pieces.
955 		void piece_availability(std::vector<int>& avail) const;
956 
957 		// These functions are used to set and get the priority of individual
958 		// pieces. By default all pieces have priority 4. That means that the
959 		// random rarest first algorithm is effectively active for all pieces.
960 		// You may however change the priority of individual pieces. There are 8
961 		// priority levels. 0 means not to download the piece at all. Otherwise,
962 		// lower priority values means less likely to be picked. Piece priority
963 		// takes precedence over piece availability. Every piece with priority 7
964 		// will be attempted to be picked before a priority 6 piece and so on.
965 		//
966 		// The default priority of pieces is 4.
967 		//
968 		// Piece priorities can not be changed for torrents that have not
969 		// downloaded the metadata yet. Magnet links won't have metadata
970 		// immediately. see the metadata_received_alert.
971 		//
972 		// ``piece_priority`` sets or gets the priority for an individual piece,
973 		// specified by ``index``.
974 		//
975 		// ``prioritize_pieces`` takes a vector of integers, one integer per
976 		// piece in the torrent. All the piece priorities will be updated with
977 		// the priorities in the vector.
978 		// The second overload of ``prioritize_pieces`` that takes a vector of pairs
979 		// will update the priorities of only select pieces, and leave all other
980 		// unaffected. Each pair is (piece, priority). That is, the first item is
981 		// the piece index and the second item is the priority of that piece.
982 		// Invalid entries, where the piece index or priority is out of range, are
983 		// not allowed.
984 		//
985 		// ``get_piece_priorities`` returns a vector with one element for each piece
986 		// in the torrent. Each element is the current priority of that piece.
987 		//
988 		// It's possible to cancel the effect of *file* priorities by setting the
989 		// priorities for the affected pieces. Care has to be taken when mixing
990 		// usage of file- and piece priorities.
991 		void piece_priority(piece_index_t index, download_priority_t priority) const;
992 		download_priority_t piece_priority(piece_index_t index) const;
993 		void prioritize_pieces(std::vector<download_priority_t> const& pieces) const;
994 		void prioritize_pieces(std::vector<std::pair<piece_index_t, download_priority_t>> const& pieces) const;
995 		std::vector<download_priority_t> get_piece_priorities() const;
996 
997 #if TORRENT_ABI_VERSION == 1
998 		TORRENT_DEPRECATED
999 		void prioritize_pieces(std::vector<int> const& pieces) const;
1000 		TORRENT_DEPRECATED
1001 		void prioritize_pieces(std::vector<std::pair<piece_index_t, int>> const& pieces) const;
1002 		TORRENT_DEPRECATED
1003 		std::vector<int> piece_priorities() const;
1004 #endif
1005 
1006 		// ``index`` must be in the range [0, number_of_files).
1007 		//
1008 		// ``file_priority()`` queries or sets the priority of file ``index``.
1009 		//
1010 		// ``prioritize_files()`` takes a vector that has at as many elements as
1011 		// there are files in the torrent. Each entry is the priority of that
1012 		// file. The function sets the priorities of all the pieces in the
1013 		// torrent based on the vector.
1014 		//
1015 		// ``get_file_priorities()`` returns a vector with the priorities of all
1016 		// files.
1017 		//
1018 		// The priority values are the same as for piece_priority(). See
1019 		// download_priority_t.
1020 		//
1021 		// Whenever a file priority is changed, all other piece priorities are
1022 		// reset to match the file priorities. In order to maintain special
1023 		// priorities for particular pieces, piece_priority() has to be called
1024 		// again for those pieces.
1025 		//
1026 		// You cannot set the file priorities on a torrent that does not yet have
1027 		// metadata or a torrent that is a seed. ``file_priority(int, int)`` and
1028 		// prioritize_files() are both no-ops for such torrents.
1029 		//
1030 		// Since changing file priorities may involve disk operations (of moving
1031 		// files in- and out of the part file), the internal accounting of file
1032 		// priorities happen asynchronously. i.e. setting file priorities and then
1033 		// immediately querying them may not yield the same priorities just set.
1034 		// However, the *piece* priorities are updated immediately.
1035 		//
1036 		// when combining file- and piece priorities, the resume file will record
1037 		// both. When loading the resume data, the file priorities will be applied
1038 		// first, then the piece priorities.
1039 		void file_priority(file_index_t index, download_priority_t priority) const;
1040 		download_priority_t file_priority(file_index_t index) const;
1041 		void prioritize_files(std::vector<download_priority_t> const& files) const;
1042 		std::vector<download_priority_t> get_file_priorities() const;
1043 
1044 #if TORRENT_ABI_VERSION == 1
1045 		TORRENT_DEPRECATED
1046 		void prioritize_files(std::vector<int> const& files) const;
1047 		TORRENT_DEPRECATED
1048 		std::vector<int> file_priorities() const;
1049 #endif
1050 
1051 		// by default, force-reannounce will still honor the min-interval
1052 		// published by the tracker. If this flag is set, it will be ignored
1053 		// and the tracker is announced immediately.
1054 		static constexpr reannounce_flags_t ignore_min_interval = 0_bit;
1055 
1056 		// ``force_reannounce()`` will force this torrent to do another tracker
1057 		// request, to receive new peers. The ``seconds`` argument specifies how
1058 		// many seconds from now to issue the tracker announces.
1059 		//
1060 		// If the tracker's ``min_interval`` has not passed since the last
1061 		// announce, the forced announce will be scheduled to happen immediately
1062 		// as the ``min_interval`` expires. This is to honor trackers minimum
1063 		// re-announce interval settings.
1064 		//
1065 		// The ``tracker_index`` argument specifies which tracker to re-announce.
1066 		// If set to -1 (which is the default), all trackers are re-announce.
1067 		//
1068 		// The ``flags`` argument can be used to affect the re-announce. See
1069 		// ignore_min_interval.
1070 		//
1071 		// ``force_dht_announce`` will announce the torrent to the DHT
1072 		// immediately.
1073 		void force_reannounce(int seconds = 0, int tracker_index = -1, reannounce_flags_t = {}) const;
1074 		void force_dht_announce() const;
1075 
1076 #if TORRENT_ABI_VERSION == 1
1077 		// forces a reannounce in the specified amount of time.
1078 		// This overrides the default announce interval, and no
1079 		// announce will take place until the given time has
1080 		// timed out.
1081 		TORRENT_DEPRECATED
1082 		void force_reannounce(boost::posix_time::time_duration) const;
1083 #endif
1084 
1085 		// ``scrape_tracker()`` will send a scrape request to a tracker. By
1086 		// default (``idx`` = -1) it will scrape the last working tracker. If
1087 		// ``idx`` is >= 0, the tracker with the specified index will scraped.
1088 		//
1089 		// A scrape request queries the tracker for statistics such as total
1090 		// number of incomplete peers, complete peers, number of downloads etc.
1091 		//
1092 		// This request will specifically update the ``num_complete`` and
1093 		// ``num_incomplete`` fields in the torrent_status struct once it
1094 		// completes. When it completes, it will generate a scrape_reply_alert.
1095 		// If it fails, it will generate a scrape_failed_alert.
1096 		void scrape_tracker(int idx = -1) const;
1097 
1098 		// ``set_upload_limit`` will limit the upload bandwidth used by this
1099 		// particular torrent to the limit you set. It is given as the number of
1100 		// bytes per second the torrent is allowed to upload.
1101 		// ``set_download_limit`` works the same way but for download bandwidth
1102 		// instead of upload bandwidth. Note that setting a higher limit on a
1103 		// torrent then the global limit
1104 		// (``settings_pack::upload_rate_limit``) will not override the global
1105 		// rate limit. The torrent can never upload more than the global rate
1106 		// limit.
1107 		//
1108 		// ``upload_limit`` and ``download_limit`` will return the current limit
1109 		// setting, for upload and download, respectively.
1110 		//
1111 		// Local peers are not rate limited by default. see peer-classes_.
1112 		void set_upload_limit(int limit) const;
1113 		int upload_limit() const;
1114 		void set_download_limit(int limit) const;
1115 		int download_limit() const;
1116 
1117 		// ``connect_peer()`` is a way to manually connect to peers that one
1118 		// believe is a part of the torrent. If the peer does not respond, or is
1119 		// not a member of this torrent, it will simply be disconnected. No harm
1120 		// can be done by using this other than an unnecessary connection attempt
1121 		// is made. If the torrent is uninitialized or in queued or checking
1122 		// mode, this will throw system_error. The second (optional)
1123 		// argument will be bitwise ORed into the source mask of this peer.
1124 		// Typically this is one of the source flags in peer_info. i.e.
1125 		// ``tracker``, ``pex``, ``dht`` etc.
1126 		//
1127 		// For possible values of ``flags``, see pex_flags_t.
1128 		void connect_peer(tcp::endpoint const& adr, peer_source_flags_t source = {}
1129 			, pex_flags_t flags = pex_encryption | pex_utp | pex_holepunch) const;
1130 
1131 		// This will disconnect all peers and clear the peer list for this
1132 		// torrent. New peers will have to be acquired before resuming, from
1133 		// trackers, DHT or local service discovery, for example.
1134 		void clear_peers();
1135 
1136 		// ``set_max_uploads()`` sets the maximum number of peers that's unchoked
1137 		// at the same time on this torrent. If you set this to -1, there will be
1138 		// no limit. This defaults to infinite. The primary setting controlling
1139 		// this is the global unchoke slots limit, set by unchoke_slots_limit in
1140 		// settings_pack.
1141 		//
1142 		// ``max_uploads()`` returns the current settings.
1143 		void set_max_uploads(int max_uploads) const;
1144 		int max_uploads() const;
1145 
1146 		// ``set_max_connections()`` sets the maximum number of connection this
1147 		// torrent will open. If all connections are used up, incoming
1148 		// connections may be refused or poor connections may be closed. This
1149 		// must be at least 2. The default is unlimited number of connections. If
1150 		// -1 is given to the function, it means unlimited. There is also a
1151 		// global limit of the number of connections, set by
1152 		// ``connections_limit`` in settings_pack.
1153 		//
1154 		// ``max_connections()`` returns the current settings.
1155 		void set_max_connections(int max_connections) const;
1156 		int max_connections() const;
1157 
1158 #if TORRENT_ABI_VERSION == 1
1159 		// sets a username and password that will be sent along in the HTTP-request
1160 		// of the tracker announce. Set this if the tracker requires authorization.
1161 		TORRENT_DEPRECATED
1162 		void set_tracker_login(std::string const& name
1163 			, std::string const& password) const;
1164 #endif
1165 
1166 		// Moves the file(s) that this torrent are currently seeding from or
1167 		// downloading to. If the given ``save_path`` is not located on the same
1168 		// drive as the original save path, the files will be copied to the new
1169 		// drive and removed from their original location. This will block all
1170 		// other disk IO, and other torrents download and upload rates may drop
1171 		// while copying the file.
1172 		//
1173 		// Since disk IO is performed in a separate thread, this operation is
1174 		// also asynchronous. Once the operation completes, the
1175 		// ``storage_moved_alert`` is generated, with the new path as the
1176 		// message. If the move fails for some reason,
1177 		// ``storage_moved_failed_alert`` is generated instead, containing the
1178 		// error message.
1179 		//
1180 		// The ``flags`` argument determines the behavior of the copying/moving
1181 		// of the files in the torrent. see move_flags_t.
1182 		//
1183 		// ``always_replace_files`` is the default and replaces any file that
1184 		// exist in both the source directory and the target directory.
1185 		//
1186 		// ``fail_if_exist`` first check to see that none of the copy operations
1187 		// would cause an overwrite. If it would, it will fail. Otherwise it will
1188 		// proceed as if it was in ``always_replace_files`` mode. Note that there
1189 		// is an inherent race condition here. If the files in the target
1190 		// directory appear after the check but before the copy or move
1191 		// completes, they will be overwritten. When failing because of files
1192 		// already existing in the target path, the ``error`` of
1193 		// ``move_storage_failed_alert`` is set to
1194 		// ``boost::system::errc::file_exists``.
1195 		//
1196 		// The intention is that a client may use this as a probe, and if it
1197 		// fails, ask the user which mode to use. The client may then re-issue
1198 		// the ``move_storage`` call with one of the other modes.
1199 		//
1200 		// ``dont_replace`` always keeps the existing file in the target
1201 		// directory, if there is one. The source files will still be removed in
1202 		// that case. Note that it won't automatically re-check files. If an
1203 		// incomplete torrent is moved into a directory with the complete files,
1204 		// pause, move, force-recheck and resume. Without the re-checking, the
1205 		// torrent will keep downloading and files in the new download directory
1206 		// will be overwritten.
1207 		//
1208 		// Files that have been renamed to have absolute paths are not moved by
1209 		// this function. Keep in mind that files that don't belong to the
1210 		// torrent but are stored in the torrent's directory may be moved as
1211 		// well. This goes for files that have been renamed to absolute paths
1212 		// that still end up inside the save path.
1213 		void move_storage(std::string const& save_path
1214 			, move_flags_t flags = move_flags_t::always_replace_files
1215 			) const;
1216 
1217 #if TORRENT_ABI_VERSION == 1
1218 		// deprecated in 1.2
1219 		TORRENT_DEPRECATED
1220 		void move_storage(std::string const& save_path, int flags) const;
1221 #endif
1222 
1223 		// Renames the file with the given index asynchronously. The rename
1224 		// operation is complete when either a file_renamed_alert or
1225 		// file_rename_failed_alert is posted.
1226 		void rename_file(file_index_t index, std::string const& new_name) const;
1227 
1228 #if TORRENT_ABI_VERSION == 1
1229 		// all wstring APIs are deprecated since 0.16.11
1230 		// instead, use the wchar -> utf8 conversion functions
1231 		// and pass in utf8 strings
1232 #ifdef TORRENT_WINDOWS
1233 		TORRENT_DEPRECATED
1234 		void move_storage(std::wstring const& save_path, int flags = 0) const;
1235 		TORRENT_DEPRECATED
1236 		void rename_file(file_index_t index, std::wstring const& new_name) const;
1237 #endif // TORRENT_WINDOWS
1238 
1239 		// Enables or disabled super seeding/initial seeding for this torrent.
1240 		// The torrent needs to be a seed for this to take effect.
1241 		TORRENT_DEPRECATED
1242 		void super_seeding(bool on) const;
1243 #endif // TORRENT_ABI_VERSION
1244 
1245 		// ``info_hash()`` returns the info-hash of the torrent. If this handle
1246 		// is to a torrent that hasn't loaded yet (for instance by being added)
1247 		// by a URL, the returned value is undefined.
1248 		sha1_hash info_hash() const;
1249 
1250 		// comparison operators. The order of the torrents is unspecified
1251 		// but stable.
operator ==libtorrent::torrent_handle1252 		bool operator==(const torrent_handle& h) const
1253 		{ return !m_torrent.owner_before(h.m_torrent) && !h.m_torrent.owner_before(m_torrent); }
operator !=libtorrent::torrent_handle1254 		bool operator!=(const torrent_handle& h) const
1255 		{ return m_torrent.owner_before(h.m_torrent) || h.m_torrent.owner_before(m_torrent); }
operator <libtorrent::torrent_handle1256 		bool operator<(const torrent_handle& h) const
1257 		{ return m_torrent.owner_before(h.m_torrent); }
1258 
1259 		// returns a unique identifier for this torrent. It's not a dense index.
1260 		// It's not preserved across sessions.
idlibtorrent::torrent_handle1261 		std::uint32_t id() const
1262 		{
1263 			uintptr_t ret = reinterpret_cast<uintptr_t>(m_torrent.lock().get());
1264 			// a torrent object is about 1024 (2^10) bytes, so
1265 			// it's safe to shift 10 bits
1266 			return std::uint32_t(ret >> 10);
1267 		}
1268 
1269 		// This function is intended only for use by plugins and the alert
1270 		// dispatch function. This type does not have a stable ABI and should
1271 		// be relied on as little as possible. Accessing the handle returned by
1272 		// this function is not thread safe outside of libtorrent's internal
1273 		// thread (which is used to invoke plugin callbacks).
1274 		// The ``torrent`` class is not only eligible for changing ABI across
1275 		// minor versions of libtorrent, its layout is also dependent on build
1276 		// configuration. This adds additional requirements on a client to be
1277 		// built with the exact same build configuration as libtorrent itself.
1278 		// i.e. the ``TORRENT_`` macros must match between libtorrent and the
1279 		// client builds.
1280 		std::shared_ptr<torrent> native_handle() const;
1281 
1282 		// Returns true if the torrent is in the session. It returns true before
1283 		// session::remove_torrent() is called, and false afterward.
1284 		//
1285 		// Note that this is a blocking function, unlike torrent_handle::is_valid()
1286 		// which returns immediately.
1287 		bool in_session() const;
1288 
1289 	private:
1290 
1291 		template<typename Fun, typename... Args>
1292 		void async_call(Fun f, Args&&... a) const;
1293 
1294 		template<typename Fun, typename... Args>
1295 		void sync_call(Fun f, Args&&... a) const;
1296 
1297 		template<typename Ret, typename Fun, typename... Args>
1298 		Ret sync_call_ret(Ret def, Fun f, Args&&... a) const;
1299 
torrent_handlelibtorrent::torrent_handle1300 		explicit torrent_handle(std::weak_ptr<torrent> const& t)
1301 		{ if (!t.expired()) m_torrent = t; }
1302 
1303 		std::weak_ptr<torrent> m_torrent;
1304 	};
1305 }
1306 
1307 namespace std
1308 {
1309 	template <>
1310 	struct hash<libtorrent::torrent_handle>
1311 	{
operator ()std::hash1312 		std::size_t operator()(libtorrent::torrent_handle const& th) const
1313 		{
1314 			return libtorrent::hash_value(th);
1315 		}
1316 	};
1317 }
1318 
1319 #endif // TORRENT_TORRENT_HANDLE_HPP_INCLUDED
1320