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_PEER_CONNECTION_HPP_INCLUDED
34 #define TORRENT_PEER_CONNECTION_HPP_INCLUDED
35 
36 #include "libtorrent/config.hpp"
37 #include "libtorrent/buffer.hpp"
38 #include "libtorrent/peer_id.hpp"
39 #include "libtorrent/stat.hpp"
40 #include "libtorrent/alert.hpp"
41 #include "libtorrent/peer_request.hpp"
42 #include "libtorrent/piece_block_progress.hpp"
43 #include "libtorrent/bandwidth_limit.hpp"
44 #include "libtorrent/assert.hpp"
45 #include "libtorrent/chained_buffer.hpp"
46 #include "libtorrent/disk_buffer_holder.hpp"
47 #include "libtorrent/bitfield.hpp"
48 #include "libtorrent/bandwidth_socket.hpp"
49 #include "libtorrent/error_code.hpp"
50 #include "libtorrent/sliding_average.hpp"
51 #include "libtorrent/peer_class.hpp"
52 #include "libtorrent/peer_class_set.hpp"
53 #include "libtorrent/aux_/session_settings.hpp"
54 #include "libtorrent/disk_observer.hpp"
55 #include "libtorrent/peer_connection_interface.hpp"
56 #include "libtorrent/socket.hpp" // for tcp::endpoint
57 #include "libtorrent/io_service_fwd.hpp"
58 #include "libtorrent/receive_buffer.hpp"
59 #include "libtorrent/aux_/allocating_handler.hpp"
60 #include "libtorrent/aux_/time.hpp"
61 #include "libtorrent/debug.hpp"
62 #include "libtorrent/span.hpp"
63 #include "libtorrent/piece_block.hpp"
64 #include "libtorrent/peer_info.hpp"
65 #include "libtorrent/aux_/vector.hpp"
66 #include "libtorrent/disk_interface.hpp"
67 #include "libtorrent/piece_picker.hpp" // for picker_options_t
68 #include "libtorrent/units.hpp"
69 
70 #include <ctime>
71 #include <algorithm>
72 #include <vector>
73 #include <string>
74 #include <utility> // for std::forward
75 #include <tuple> // for make_tuple
76 #include <array>
77 #include <cstdint>
78 
79 namespace libtorrent {
80 
81 	class torrent;
82 	struct torrent_peer;
83 	struct disk_interface;
84 
85 #ifndef TORRENT_DISABLE_EXTENSIONS
86 	struct peer_plugin;
87 #endif
88 
89 namespace aux {
90 
91 	struct socket_type;
92 	struct session_interface;
93 
94 }
95 
96 	struct pending_block
97 	{
pending_blocklibtorrent::pending_block98 		pending_block(piece_block const& b) // NOLINT
99 			: block(b), send_buffer_offset(not_in_buffer), not_wanted(false)
100 			, timed_out(false), busy(false)
101 		{}
102 
103 		piece_block block;
104 
105 		static constexpr std::uint32_t not_in_buffer = 0x1fffffff;
106 
107 		// the number of bytes into the send buffer this request is. Every time
108 		// some portion of the send buffer is transmitted, this offset is
109 		// decremented by the number of bytes sent. once this drops below 0, the
110 		// request_time field is set to the current time.
111 		// if the request has not been written to the send buffer, this field
112 		// remains not_in_buffer.
113 		std::uint32_t send_buffer_offset:29;
114 
115 		// if any of these are set to true, this block
116 		// is not allocated
117 		// in the piece picker anymore, and open for
118 		// other peers to pick. This may be caused by
119 		// it either timing out or being received
120 		// unexpectedly from the peer
121 		std::uint32_t not_wanted:1;
122 		std::uint32_t timed_out:1;
123 
124 		// the busy flag is set if the block was
125 		// requested from another peer when this
126 		// request was queued. We only allow a single
127 		// busy request at a time in each peer's queue
128 		std::uint32_t busy:1;
129 
operator ==libtorrent::pending_block130 		bool operator==(pending_block const& b) const
131 		{
132 			return b.block == block
133 				&& b.not_wanted == not_wanted
134 				&& b.timed_out == timed_out;
135 		}
136 	};
137 
138 	// argument pack passed to peer_connection constructor
139 	struct peer_connection_args
140 	{
141 		aux::session_interface* ses;
142 		aux::session_settings const* sett;
143 		counters* stats_counters;
144 		disk_interface* disk_thread;
145 		io_service* ios;
146 		std::weak_ptr<torrent> tor;
147 		std::shared_ptr<aux::socket_type> s;
148 		tcp::endpoint endp;
149 		torrent_peer* peerinfo;
150 		peer_id our_peer_id;
151 	};
152 
153 	struct TORRENT_EXTRA_EXPORT peer_connection_hot_members
154 	{
155 		// if tor is set, this is an outgoing connection
peer_connection_hot_memberslibtorrent::peer_connection_hot_members156 		peer_connection_hot_members(
157 			std::weak_ptr<torrent> t
158 			, aux::session_interface& ses
159 			, aux::session_settings const& sett)
160 			: m_torrent(std::move(t))
161 			, m_ses(ses)
162 			, m_settings(sett)
163 			, m_disconnecting(false)
164 			, m_connecting(!m_torrent.expired())
165 			, m_endgame_mode(false)
166 			, m_snubbed(false)
167 			, m_interesting(false)
168 			, m_choked(true)
169 			, m_ignore_stats(false)
170 		{}
171 
172 		// explicitly disallow assignment, to silence msvc warning
173 		peer_connection_hot_members& operator=(peer_connection_hot_members const&) = delete;
174 
175 	protected:
176 
177 		// the pieces the other end have
178 		typed_bitfield<piece_index_t> m_have_piece;
179 
180 		// this is the torrent this connection is
181 		// associated with. If the connection is an
182 		// incoming connection, this is set to zero
183 		// until the info_hash is received. Then it's
184 		// set to the torrent it belongs to.
185 
186 		// TODO: make this a raw pointer (to save size in
187 		// the first cache line) and make the constructor
188 		// take a raw pointer. torrent objects should always
189 		// outlive their peers
190 		std::weak_ptr<torrent> m_torrent;
191 
192 	public:
193 
194 		// a back reference to the session
195 		// the peer belongs to.
196 		aux::session_interface& m_ses;
197 
198 		// settings that apply to this peer
199 		aux::session_settings const& m_settings;
200 
201 	protected:
202 
203 		// this is true if this connection has been added
204 		// to the list of connections that will be closed.
205 		bool m_disconnecting:1;
206 
207 		// this is true until this socket has become
208 		// writable for the first time (i.e. the
209 		// connection completed). While connecting
210 		// the timeout will not be triggered. This is
211 		// because windows XP SP2 may delay connection
212 		// attempts, which means that the connection
213 		// may not even have been attempted when the
214 		// time out is reached.
215 		bool m_connecting:1;
216 
217 		// this is set to true if the last time we tried to
218 		// pick a piece to download, we could only find
219 		// blocks that were already requested from other
220 		// peers. In this case, we should not try to pick
221 		// another piece until the last one we requested is done
222 		bool m_endgame_mode:1;
223 
224 		// set to true when a piece request times out. The
225 		// result is that the desired pending queue size
226 		// is set to 1
227 		bool m_snubbed:1;
228 
229 		// the peer has pieces we are interested in
230 		bool m_interesting:1;
231 
232 		// we have choked the upload to the peer
233 		bool m_choked:1;
234 
235 		// when this is set, the transfer stats for this connection
236 		// is not included in the torrent or session stats
237 		bool m_ignore_stats:1;
238 	};
239 
240 	enum class connection_type : std::uint8_t
241 	{
242 		bittorrent,
243 		url_seed,
244 		http_seed
245 	};
246 
247 	using request_flags_t = flags::bitfield_flag<std::uint8_t, struct request_flags_tag>;
248 
249 	class TORRENT_EXTRA_EXPORT peer_connection
250 		: public peer_connection_hot_members
251 		, public bandwidth_socket
252 		, public peer_class_set
253 		, public disk_observer
254 		, public peer_connection_interface
255 		, public std::enable_shared_from_this<peer_connection>
256 		, public aux::error_handler_interface
257 	{
258 	friend class invariant_access;
259 	friend class torrent;
260 	friend struct cork;
261 	public:
262 
263 		void on_exception(std::exception const& e) override;
264 		void on_error(error_code const& ec) override;
265 
266 		virtual connection_type type() const = 0;
267 
268 		enum channels
269 		{
270 			upload_channel,
271 			download_channel,
272 			num_channels
273 		};
274 
275 		explicit peer_connection(peer_connection_args const& pack);
276 
277 		// this function is called after it has been constructed and properly
278 		// reference counted. It is safe to call self() in this function
279 		// and schedule events with references to itself (that is not safe to
280 		// do in the constructor).
281 		virtual void start();
282 
283 		~peer_connection() override;
284 
set_peer_info(torrent_peer * pi)285 		void set_peer_info(torrent_peer* pi) override
286 		{
287 			TORRENT_ASSERT(m_peer_info == nullptr || pi == nullptr );
288 			TORRENT_ASSERT(pi != nullptr || m_disconnect_started);
289 			m_peer_info = pi;
290 		}
291 
peer_info_struct() const292 		torrent_peer* peer_info_struct() const override
293 		{ return m_peer_info; }
294 
295 		// this is called when the peer object is created, in case
296 		// it was let in by the connections limit slack. This means
297 		// the peer needs to, as soon as the handshake is done, either
298 		// disconnect itself or another peer.
peer_exceeds_limit()299 		void peer_exceeds_limit()
300 		{ m_exceeded_limit = true; }
301 
302 		// this is called if this peer causes another peer
303 		// to be disconnected, in which case it has fulfilled
304 		// its requirement.
peer_disconnected_other()305 		void peer_disconnected_other()
306 		{ m_exceeded_limit = false; }
307 
308 		void send_allowed_set();
309 
310 #ifndef TORRENT_DISABLE_EXTENSIONS
311 		void add_extension(std::shared_ptr<peer_plugin>);
312 		peer_plugin const* find_plugin(string_view type);
313 #endif
314 
315 		// this function is called once the torrent associated
316 		// with this peer connection has retrieved the meta-
317 		// data. If the torrent was spawned with metadata
318 		// this is called from the constructor.
319 		void init();
320 
321 		// this is called when the metadata is retrieved
322 		// and the files has been checked
on_metadata()323 		virtual void on_metadata() {}
324 
325 		void on_metadata_impl();
326 
picker_options(picker_options_t o)327 		void picker_options(picker_options_t o) { m_picker_options = o; }
328 
prefer_contiguous_blocks() const329 		int prefer_contiguous_blocks() const
330 		{
331 			if (on_parole()) return 1;
332 			return m_prefer_contiguous_blocks;
333 		}
334 
335 		bool on_parole() const;
336 
337 		picker_options_t picker_options() const;
338 
prefer_contiguous_blocks(int num)339 		void prefer_contiguous_blocks(int num)
340 		{ m_prefer_contiguous_blocks = num; }
341 
request_large_blocks() const342 		bool request_large_blocks() const
343 		{ return m_request_large_blocks; }
344 
request_large_blocks(bool b)345 		void request_large_blocks(bool b)
346 		{ m_request_large_blocks = b; }
347 
348 		void set_endgame(bool b);
endgame() const349 		bool endgame() const { return m_endgame_mode; }
350 
no_download() const351 		bool no_download() const { return m_no_download; }
no_download(bool b)352 		void no_download(bool b) { m_no_download = b; }
353 
ignore_stats() const354 		bool ignore_stats() const { return m_ignore_stats; }
ignore_stats(bool b)355 		void ignore_stats(bool b) { m_ignore_stats = b; }
356 
357 		std::uint32_t peer_rank() const;
358 
359 		void fast_reconnect(bool r);
fast_reconnect() const360 		bool fast_reconnect() const override { return m_fast_reconnect; }
361 
362 		// this is called when we receive a new piece
363 		// (and it has passed the hash check)
364 		void received_piece(piece_index_t index);
365 
366 		// this adds an announcement in the announcement queue
367 		// it will let the peer know that we have the given piece
368 		void announce_piece(piece_index_t index);
369 
370 #ifndef TORRENT_DISABLE_SUPERSEEDING
371 		// this will tell the peer to announce the given piece
372 		// and only allow it to request that piece
373 		void superseed_piece(piece_index_t replace_piece, piece_index_t new_piece);
super_seeded_piece(piece_index_t index) const374 		bool super_seeded_piece(piece_index_t index) const
375 		{
376 			return m_superseed_piece[0] == index
377 				|| m_superseed_piece[1] == index;
378 		}
379 #endif
380 
381 		// tells if this connection has data it want to send
382 		// and has enough upload bandwidth quota left to send it.
383 		bool can_write() const;
384 		bool can_read();
385 
386 		bool is_seed() const;
num_have_pieces() const387 		int num_have_pieces() const { return m_num_pieces; }
388 
389 #ifndef TORRENT_DISABLE_SHARE_MODE
390 		void set_share_mode(bool m);
share_mode() const391 		bool share_mode() const { return m_share_mode; }
392 #endif
393 
394 		void set_upload_only(bool u);
upload_only() const395 		bool upload_only() const { return m_upload_only; }
396 
397 		void set_holepunch_mode() override;
398 
399 		// will send a keep-alive message to the peer
400 		void keep_alive();
401 
pid() const402 		peer_id const& pid() const override { return m_peer_id; }
set_pid(peer_id const & peer_id)403 		void set_pid(peer_id const& peer_id) { m_peer_id = peer_id; }
404 		bool has_piece(piece_index_t i) const;
405 
406 		std::vector<pending_block> const& download_queue() const;
407 		std::vector<pending_block> const& request_queue() const;
408 		std::vector<peer_request> const& upload_queue() const;
409 
410 		void clear_request_queue();
411 		void clear_download_queue();
412 
413 		// estimate of how long it will take until we have
414 		// received all piece requests that we have sent
415 		// if extra_bytes is specified, it will include those
416 		// bytes as if they've been requested
417 		time_duration download_queue_time(int extra_bytes = 0) const;
418 
is_interesting() const419 		bool is_interesting() const { return m_interesting; }
is_choked() const420 		bool is_choked() const override { return m_choked; }
421 
is_peer_interested() const422 		bool is_peer_interested() const { return m_peer_interested; }
has_peer_choked() const423 		bool has_peer_choked() const { return m_peer_choked; }
424 
425 		void choke_this_peer();
426 		void maybe_unchoke_this_peer();
427 
428 		void update_interest();
429 
430 		void get_peer_info(peer_info& p) const override;
431 
432 		// returns the torrent this connection is a part of
433 		// may be zero if the connection is an incoming connection
434 		// and it hasn't received enough information to determine
435 		// which torrent it should be associated with
associated_torrent() const436 		std::weak_ptr<torrent> associated_torrent() const
437 		{ return m_torrent; }
438 
statistics() const439 		stat const& statistics() const override { return m_statistics; }
440 		void add_stat(std::int64_t downloaded, std::int64_t uploaded) override;
441 		void sent_bytes(int bytes_payload, int bytes_protocol);
442 		void received_bytes(int bytes_payload, int bytes_protocol);
443 		void trancieve_ip_packet(int bytes, bool ipv6);
444 		void sent_syn(bool ipv6);
445 		void received_synack(bool ipv6);
446 
447 		// is called once every second by the main loop
448 		void second_tick(int tick_interval_ms);
449 
get_socket() const450 		std::shared_ptr<aux::socket_type> get_socket() const { return m_socket; }
remote() const451 		tcp::endpoint const& remote() const override { return m_remote; }
local_endpoint() const452 		tcp::endpoint local_endpoint() const override { return m_local; }
453 
454 		typed_bitfield<piece_index_t> const& get_bitfield() const;
455 		std::vector<piece_index_t> const& allowed_fast();
suggested_pieces() const456 		std::vector<piece_index_t> const& suggested_pieces() const { return m_suggested_pieces; }
457 
connected_time() const458 		time_point connected_time() const { return m_connect; }
last_received() const459 		time_point last_received() const { return m_last_receive; }
460 
461 		// this will cause this peer_connection to be disconnected.
462 		void disconnect(error_code const& ec
463 			, operation_t op, disconnect_severity_t = peer_connection_interface::normal) override;
464 
465 		// called when a connect attempt fails (not when an
466 		// established connection fails)
467 		void connect_failed(error_code const& e);
is_disconnecting() const468 		bool is_disconnecting() const override { return m_disconnecting; }
469 
470 		// this is called when the connection attempt has succeeded
471 		// and the peer_connection is supposed to set m_connecting
472 		// to false, and stop monitor writability
473 		void on_connection_complete(error_code const& e);
474 
475 		// returns true if this connection is still waiting to
476 		// finish the connection attempt
is_connecting() const477 		bool is_connecting() const { return m_connecting; }
478 
479 		// trust management.
480 		virtual void received_valid_data(piece_index_t index);
481 		// returns false if the peer should not be
482 		// disconnected
483 		virtual bool received_invalid_data(piece_index_t index, bool single_peer);
484 
485 		// a connection is local if it was initiated by us.
486 		// if it was an incoming connection, it is remote
is_outgoing() const487 		bool is_outgoing() const final { return m_outgoing; }
488 
received_listen_port() const489 		bool received_listen_port() const { return m_received_listen_port; }
received_listen_port()490 		void received_listen_port()
491 		{ m_received_listen_port = true; }
492 
493 		bool on_local_network() const;
494 		bool ignore_unchoke_slots() const;
495 
failed() const496 		bool failed() const override { return m_failed; }
497 
desired_queue_size() const498 		int desired_queue_size() const
499 		{
500 			// this peer is in end-game mode we only want
501 			// one outstanding request
502 			return (m_endgame_mode || m_snubbed) ? 1 : m_desired_queue_size;
503 		}
504 
505 		// compares this connection against the given connection
506 		// for which one is more eligible for an unchoke.
507 		// returns true if this is more eligible
508 
download_payload_rate() const509 		int download_payload_rate() const { return m_statistics.download_payload_rate(); }
510 
511 		// resets the byte counters that are used to measure
512 		// the number of bytes transferred within unchoke cycles
513 		void reset_choke_counters();
514 
515 		// if this peer connection is useless (neither party is
516 		// interested in the other), disconnect it
517 		// returns true if the connection was disconnected
518 		bool disconnect_if_redundant();
519 
520 #if TORRENT_ABI_VERSION == 1
521 		void increase_est_reciprocation_rate();
522 		void decrease_est_reciprocation_rate();
est_reciprocation_rate() const523 		int est_reciprocation_rate() const { return m_est_reciprocation_rate; }
524 #endif
525 
526 #ifndef TORRENT_DISABLE_LOGGING
527 		bool should_log(peer_log_alert::direction_t direction) const final;
528 		void peer_log(peer_log_alert::direction_t direction
529 			, char const* event, char const* fmt, ...) const noexcept final TORRENT_FORMAT(4,5);
530 		void peer_log(peer_log_alert::direction_t direction
531 			, char const* event) const noexcept;
532 #endif
533 
534 		// the message handlers are called
535 		// each time a recv() returns some new
536 		// data, the last time it will be called
537 		// is when the entire packet has been
538 		// received, then it will no longer
539 		// be called. i.e. most handlers need
540 		// to check how much of the packet they
541 		// have received before any processing
542 		void incoming_keepalive();
543 		void incoming_choke();
544 		void incoming_unchoke();
545 		void incoming_interested();
546 		void incoming_not_interested();
547 		void incoming_have(piece_index_t piece_index);
548 		void incoming_dont_have(piece_index_t piece_index);
549 		void incoming_bitfield(typed_bitfield<piece_index_t> const& bits);
550 		void incoming_request(peer_request const& r);
551 		void incoming_piece(peer_request const& p, char const* data);
552 		void incoming_piece_fragment(int bytes);
553 		void start_receive_piece(peer_request const& r);
554 		void incoming_cancel(peer_request const& r);
555 
556 		bool can_disconnect(error_code const& ec) const;
557 		void incoming_dht_port(int listen_port);
558 
559 		void incoming_reject_request(peer_request const& r);
560 		void incoming_have_all();
561 		void incoming_have_none();
562 		void incoming_allowed_fast(piece_index_t index);
563 		void incoming_suggest(piece_index_t index);
564 
set_has_metadata(bool m)565 		void set_has_metadata(bool m) { m_has_metadata = m; }
has_metadata() const566 		bool has_metadata() const { return m_has_metadata; }
567 
568 		// the following functions appends messages
569 		// to the send buffer
570 		bool send_choke();
571 		bool send_unchoke();
572 		void send_interested();
573 		void send_not_interested();
574 		void send_suggest(piece_index_t piece);
575 		void send_upload_only(bool enabled);
576 
577 		void snub_peer();
578 		// reject any request in the request
579 		// queue from this piece
580 		void reject_piece(piece_index_t index);
581 
582 		bool can_request_time_critical() const;
583 
584 		// returns true if the specified block was actually made time-critical.
585 		// if the block was already time-critical, it returns false.
586 		bool make_time_critical(piece_block const& block);
587 
588 		static constexpr request_flags_t time_critical = 0_bit;
589 		static constexpr request_flags_t busy = 1_bit;
590 
591 		// adds a block to the request queue
592 		// returns true if successful, false otherwise
593 		bool add_request(piece_block const& b, request_flags_t flags = {});
594 
595 		// clears the request queue and sends cancels for all messages
596 		// in the download queue
597 		void cancel_all_requests();
598 
599 		// removes a block from the request queue or download queue
600 		// sends a cancel message if appropriate
601 		// refills the request queue, and possibly ignoring pieces requested
602 		// by peers in the ignore list (to avoid recursion)
603 		// if force is true, the blocks is also freed from the piece
604 		// picker, allowing another peer to request it immediately
605 		void cancel_request(piece_block const& b, bool force = false);
606 		void send_block_requests();
607 
608 		void assign_bandwidth(int channel, int amount) override;
609 
610 #if TORRENT_USE_INVARIANT_CHECKS
611 		void check_invariant() const;
612 #endif
613 
614 		// is true until we can be sure that the other end
615 		// speaks our protocol (be it bittorrent or http).
616 		virtual bool in_handshake() const = 0;
617 
618 		// returns the block currently being
619 		// downloaded. And the progress of that
620 		// block. If the peer isn't downloading
621 		// a piece for the moment, implementors
622 		// must return an object with the piece_index
623 		// value invalid (the default constructor).
624 		virtual piece_block_progress downloading_piece_progress() const;
625 
626 		void send_buffer(span<char const> buf);
627 		void setup_send();
628 
629 		template <typename Holder>
append_send_buffer(Holder buffer,int size)630 		void append_send_buffer(Holder buffer, int size)
631 		{
632 			TORRENT_ASSERT(is_single_thread());
633 			m_send_buffer.append_buffer(std::move(buffer), size);
634 		}
635 
outstanding_bytes() const636 		int outstanding_bytes() const { return m_outstanding_bytes; }
637 
send_buffer_size() const638 		int send_buffer_size() const
639 		{ return m_send_buffer.size(); }
640 
send_buffer_capacity() const641 		int send_buffer_capacity() const
642 		{ return m_send_buffer.capacity(); }
643 
644 		void max_out_request_queue(int s);
645 		int max_out_request_queue() const;
646 
647 #if TORRENT_USE_ASSERTS
648 		bool piece_failed;
649 #endif
650 
last_seen_complete() const651 		std::time_t last_seen_complete() const { return m_last_seen_complete; }
set_last_seen_complete(int ago)652 		void set_last_seen_complete(int ago) { m_last_seen_complete = ::time(nullptr) - ago; }
653 
uploaded_in_last_round() const654 		std::int64_t uploaded_in_last_round() const
655 		{ return m_statistics.total_payload_upload() - m_uploaded_at_last_round; }
656 
downloaded_in_last_round() const657 		std::int64_t downloaded_in_last_round() const
658 		{ return m_statistics.total_payload_download() - m_downloaded_at_last_round; }
659 
uploaded_since_unchoked() const660 		std::int64_t uploaded_since_unchoked() const
661 		{ return m_statistics.total_payload_upload() - m_uploaded_at_last_unchoke; }
662 
663 		// the time we last unchoked this peer
time_of_last_unchoke() const664 		time_point time_of_last_unchoke() const
665 		{ return m_last_unchoke; }
666 
667 		// called when the disk write buffer is drained again, and we can
668 		// start downloading payload again
669 		void on_disk() override;
670 
num_reading_bytes() const671 		int num_reading_bytes() const { return m_reading_bytes; }
672 
673 		void setup_receive();
674 
self()675 		std::shared_ptr<peer_connection> self()
676 		{
677 			TORRENT_ASSERT(!m_destructed);
678 			TORRENT_ASSERT(m_in_use == 1337);
679 			TORRENT_ASSERT(!m_in_constructor);
680 			return shared_from_this();
681 		}
682 
stats_counters() const683 		counters& stats_counters() const { return m_counters; }
684 
685 		int get_priority(int channel) const;
686 
687 	protected:
688 
689 		virtual void get_specific_peer_info(peer_info& p) const = 0;
690 
691 		virtual void write_choke() = 0;
692 		virtual void write_unchoke() = 0;
693 		virtual void write_interested() = 0;
694 		virtual void write_not_interested() = 0;
695 		virtual void write_request(peer_request const& r) = 0;
696 		virtual void write_cancel(peer_request const& r) = 0;
697 		virtual void write_have(piece_index_t index) = 0;
698 		virtual void write_dont_have(piece_index_t index) = 0;
699 		virtual void write_keepalive() = 0;
700 		virtual void write_piece(peer_request const& r, disk_buffer_holder buffer) = 0;
701 		virtual void write_suggest(piece_index_t piece) = 0;
702 		virtual void write_bitfield() = 0;
703 
704 		virtual void write_reject_request(peer_request const& r) = 0;
705 		virtual void write_allow_fast(piece_index_t piece) = 0;
706 		virtual void write_upload_only(bool enabled) = 0;
707 
708 		virtual void on_connected() = 0;
on_tick()709 		virtual void on_tick() {}
710 
711 		// implemented by concrete connection classes
712 		virtual void on_receive(error_code const& error
713 			, std::size_t bytes_transferred) = 0;
714 		virtual void on_sent(error_code const& error
715 			, std::size_t bytes_transferred) = 0;
716 
717 		void send_piece_suggestions(int num);
718 
719 		virtual
720 		std::tuple<int, span<span<char const>>>
hit_send_barrier(span<span<char>>)721 		hit_send_barrier(span<span<char>> /* iovec */)
722 		{
723 			return std::make_tuple(INT_MAX
724 				, span<span<char const>>());
725 		}
726 
727 		void attach_to_torrent(sha1_hash const& ih);
728 
729 		bool verify_piece(peer_request const& p) const;
730 
731 		void update_desired_queue_size();
732 
set_send_barrier(int bytes)733 		void set_send_barrier(int bytes)
734 		{
735 			TORRENT_ASSERT(bytes == INT_MAX || bytes <= send_buffer_size());
736 			m_send_barrier = bytes;
737 		}
738 
get_send_barrier() const739 		int get_send_barrier() const { return m_send_barrier; }
740 
741 		virtual int timeout() const;
742 
get_io_service()743 		io_service& get_io_service() { return m_ios; }
744 
745 	private:
746 
747 		// callbacks for data being sent or received
748 		void on_send_data(error_code const& error
749 			, std::size_t bytes_transferred);
750 		void on_receive_data(error_code const& error
751 			, std::size_t bytes_transferred);
752 
753 		void account_received_bytes(int bytes_transferred);
754 
755 		// explicitly disallow assignment, to silence msvc warning
756 		peer_connection& operator=(peer_connection const&);
757 
758 		void do_update_interest();
759 		void fill_send_buffer();
760 		void on_disk_read_complete(disk_buffer_holder disk_block, disk_job_flags_t flags
761 			, storage_error const& error, peer_request const& r, time_point issue_time);
762 		void on_disk_write_complete(storage_error const& error
763 			, peer_request const &r, std::shared_ptr<torrent> t);
764 		void on_seed_mode_hashed(piece_index_t piece
765 			, sha1_hash const& piece_hash, storage_error const& error);
766 		int request_timeout() const;
767 		void check_graceful_pause();
768 
769 		int wanted_transfer(int channel);
770 		int request_bandwidth(int channel, int bytes = 0);
771 
772 		std::shared_ptr<aux::socket_type> m_socket;
773 
774 		// the queue of blocks we have requested
775 		// from this peer
776 		aux::vector<pending_block> m_download_queue;
777 
778 		// the queue of requests we have got
779 		// from this peer that haven't been issued
780 		// to the disk thread yet
781 		aux::vector<peer_request> m_requests;
782 
783 		// this peer's peer info struct. This may
784 		// be 0, in case the connection is incoming
785 		// and hasn't been added to a torrent yet.
786 		torrent_peer* m_peer_info;
787 
788 		// stats counters
789 		counters& m_counters;
790 
791 		// the number of pieces this peer
792 		// has. Must be the same as
793 		// std::count(m_have_piece.begin(),
794 		// m_have_piece.end(), true)
795 		int m_num_pieces;
796 
797 
798 	public:
799 		// upload and download channel state
800 		// enum from peer_info::bw_state
801 		bandwidth_state_flags_t m_channel_state[2];
802 
803 	protected:
804 		receive_buffer m_recv_buffer;
805 
806 		// number of bytes this peer can send and receive
807 		int m_quota[2];
808 
809 		// the blocks we have reserved in the piece
810 		// picker and will request from this peer.
811 		std::vector<pending_block> m_request_queue;
812 
813 		// this is the limit on the number of outstanding requests
814 		// we have to this peer. This is initialized to the settings
815 		// in the settings_pack. But it may be lowered
816 		// if the peer is known to require a smaller limit (like BitComet).
817 		// or if the extended handshake sets a limit.
818 		// web seeds also has a limit on the queue size.
819 		int m_max_out_request_queue;
820 
821 		// this is the peer we're actually talking to
822 		// it may not necessarily be the peer we're
823 		// connected to, in case we use a proxy
824 		tcp::endpoint m_remote;
825 
826 	public:
827 		chained_buffer m_send_buffer;
828 	private:
829 
830 		// the disk thread to use to issue disk jobs to
831 		disk_interface& m_disk_thread;
832 
833 		// io service
834 		io_service& m_ios;
835 
836 	protected:
837 #ifndef TORRENT_DISABLE_EXTENSIONS
838 		std::list<std::shared_ptr<peer_plugin>> m_extensions;
839 #endif
840 	private:
841 
842 		// the average time between incoming pieces. Or, if there is no
843 		// outstanding request, the time since the piece was requested. It
844 		// is essentially an estimate of the time it will take to completely
845 		// receive a payload message after it has been requested.
846 		sliding_average<int, 20> m_request_time;
847 
848 		// keep the io_service running as long as we
849 		// have peer connections
850 		io_service::work m_work;
851 
852 		// the time when we last got a part of a
853 		// piece packet from this peer
854 		time_point m_last_piece = aux::time_now();
855 
856 		// the time we sent a request to
857 		// this peer the last time
858 		time_point m_last_request = aux::time_now();
859 		// the time we received the last
860 		// piece request from the peer
861 		time_point m_last_incoming_request = min_time();
862 
863 		// the time when we unchoked this peer
864 		time_point m_last_unchoke = aux::time_now();
865 
866 		// if we're unchoked by this peer, this
867 		// was the time
868 		time_point m_last_unchoked = aux::time_now();
869 
870 		// the time we last choked this peer. min_time() in
871 		// case we never unchoked it
872 		time_point m_last_choke = min_time();
873 
874 		// timeouts
875 		time_point m_last_receive = aux::time_now();
876 		time_point m_last_sent = aux::time_now();
877 
878 		// the last time we filled our send buffer with payload
879 		// this is used for timeouts
880 		time_point m_last_sent_payload = aux::time_now();
881 
882 		// the time when the first entry in the request queue was requested. Used
883 		// for request timeout. it doesn't necessarily represent the time when a
884 		// specific request was made. Since requests can be handled out-of-order,
885 		// it represents whichever request the other end decided to respond to.
886 		// Once we get that response, we set it to the current time.
887 		// for more information, see the blog post at:
888 		// http://blog.libtorrent.org/2011/11/block-request-time-outs/
889 		time_point m_requested = aux::time_now();
890 
891 		// the time when async_connect was called
892 		// or when the incoming connection was established
893 		time_point m_connect = aux::time_now();
894 
895 		// the time when this peer sent us a not_interested message
896 		// the last time.
897 		time_point m_became_uninterested = aux::time_now();
898 
899 		// the time when we sent a not_interested message to
900 		// this peer the last time.
901 		time_point m_became_uninteresting = aux::time_now();
902 
903 		// the total payload download bytes
904 		// at the last unchoke round. This is used to
905 		// measure the number of bytes transferred during
906 		// an unchoke cycle, to unchoke peers the more bytes
907 		// they sent us
908 		std::int64_t m_downloaded_at_last_round = 0;
909 		std::int64_t m_uploaded_at_last_round = 0;
910 
911 		// this is the number of bytes we had uploaded the
912 		// last time this peer was unchoked. This does not
913 		// reset each unchoke interval/round. This is used to
914 		// track upload across rounds, for the full duration of
915 		// the peer being unchoked. Specifically, it's used
916 		// for the round-robin unchoke algorithm.
917 		std::int64_t m_uploaded_at_last_unchoke = 0;
918 
919 		// the number of payload bytes downloaded last second tick
920 		std::int32_t m_downloaded_last_second = 0;
921 
922 		// the number of payload bytes uploaded last second tick
923 		std::int32_t m_uploaded_last_second = 0;
924 
925 		// the number of bytes that the other
926 		// end has to send us in order to respond
927 		// to all outstanding piece requests we
928 		// have sent to it
929 		int m_outstanding_bytes = 0;
930 
931 		aux::handler_storage<TORRENT_READ_HANDLER_MAX_SIZE> m_read_handler_storage;
932 		aux::handler_storage<TORRENT_WRITE_HANDLER_MAX_SIZE> m_write_handler_storage;
933 
934 		// these are pieces we have recently sent suggests for to this peer.
935 		// it just serves as a queue to remember what we've sent, to avoid
936 		// re-sending suggests for the same piece
937 		// i.e. outgoing suggest pieces
938 		aux::vector<piece_index_t> m_suggest_pieces;
939 
940 		// the pieces we will send to the peer
941 		// if requested (regardless of choke state)
942 		std::vector<piece_index_t> m_accept_fast;
943 
944 		// a sent-piece counter for the allowed fast set
945 		// to avoid exploitation. Each slot is a counter
946 		// for one of the pieces from the allowed-fast set
947 		aux::vector<std::uint16_t> m_accept_fast_piece_cnt;
948 
949 		// the pieces the peer will send us if
950 		// requested (regardless of choke state)
951 		std::vector<piece_index_t> m_allowed_fast;
952 
953 		// pieces that has been suggested to be downloaded from this peer
954 		// i.e. incoming suggestions
955 		// TODO: 2 this should really be a circular buffer
956 		aux::vector<piece_index_t> m_suggested_pieces;
957 
958 		// the time when this peer last saw a complete copy
959 		// of this torrent
960 		time_t m_last_seen_complete = 0;
961 
962 		// the block we're currently receiving. Or
963 		// (-1, -1) if we're not receiving one
964 		piece_block m_receiving_block = piece_block::invalid;
965 
966 		// the local endpoint for this peer, i.e. our address
967 		// and our port. If this is set for outgoing connections
968 		// before the connection completes, it means we want to
969 		// force the connection to be bound to the specified interface.
970 		// if it ends up being bound to a different local IP, the connection
971 		// is closed.
972 		tcp::endpoint m_local;
973 
974 		// remote peer's id
975 		peer_id m_peer_id;
976 
977 	protected:
978 
979 		template <typename Fun, typename... Args>
980 		void wrap(Fun f, Args&&... a);
981 
982 		// statistics about upload and download speeds
983 		// and total amount of uploads and downloads for
984 		// this peer
985 		// TODO: factor this out into its own class with a virtual interface
986 		// torrent and session should implement this interface
987 		stat m_statistics;
988 
989 		// the number of outstanding bytes expected
990 		// to be received by extensions
991 		int m_extension_outstanding_bytes = 0;
992 
993 		// the number of time critical requests
994 		// queued up in the m_request_queue that
995 		// soon will be committed to the download
996 		// queue. This is included in download_queue_time()
997 		// so that it can be used while adding more
998 		// requests and take the previous requests
999 		// into account without submitting it all
1000 		// immediately
1001 		int m_queued_time_critical = 0;
1002 
1003 		// the number of bytes we are currently reading
1004 		// from disk, that will be added to the send
1005 		// buffer as soon as they complete
1006 		int m_reading_bytes = 0;
1007 
1008 		// options used for the piece picker. These flags will
1009 		// be augmented with flags controlled by other settings
1010 		// like sequential download etc. These are here to
1011 		// let plugins control flags that should always be set
1012 		picker_options_t m_picker_options{};
1013 
1014 		// the number of invalid piece-requests
1015 		// we have got from this peer. If the request
1016 		// queue gets empty, and there have been
1017 		// invalid requests, we can assume the
1018 		// peer is waiting for those pieces.
1019 		// we can then clear its download queue
1020 		// by sending choke, unchoke.
1021 		int m_num_invalid_requests = 0;
1022 
1023 #ifndef TORRENT_DISABLE_SUPERSEEDING
1024 		// if [0] is -1, super-seeding is not active. If it is >= 0
1025 		// this is the piece that is available to this peer. Only
1026 		// these two pieces can be downloaded from us by this peer.
1027 		// This will remain the current piece for this peer until
1028 		// another peer sends us a have message for this piece
1029 		std::array<piece_index_t, 2> m_superseed_piece = {{piece_index_t(-1), piece_index_t(-1)}};
1030 #endif
1031 
1032 		// the number of bytes send to the disk-io
1033 		// thread that hasn't yet been completely written.
1034 		int m_outstanding_writing_bytes = 0;
1035 
1036 		// max transfer rates seen on this peer
1037 		int m_download_rate_peak = 0;
1038 		int m_upload_rate_peak = 0;
1039 
1040 #if TORRENT_ABI_VERSION == 1
1041 		// when using the BitTyrant choker, this is our
1042 		// estimated reciprocation rate. i.e. the rate
1043 		// we need to send to this peer for it to unchoke
1044 		// us
1045 		int m_est_reciprocation_rate;
1046 #endif
1047 
1048 		// stop sending data after this many bytes, INT_MAX = inf
1049 		int m_send_barrier = INT_MAX;
1050 
1051 		// the number of request we should queue up
1052 		// at the remote end.
1053 		// TODO: 2 rename this target queue size
1054 		std::uint16_t m_desired_queue_size = 4;
1055 
1056 		// if set to non-zero, this peer will always prefer
1057 		// to request entire n pieces, rather than blocks.
1058 		// where n is the value of this variable.
1059 		// if it is 0, the download rate limit setting
1060 		// will be used to determine if whole pieces
1061 		// are preferred.
1062 		int m_prefer_contiguous_blocks = 0;
1063 
1064 		// this is the number of times this peer has had
1065 		// a request rejected because of a disk I/O failure.
1066 		// once this reaches a certain threshold, the
1067 		// peer is disconnected in order to avoid infinite
1068 		// loops of consistent failures
1069 		std::uint8_t m_disk_read_failures = 0;
1070 
1071 		// this is used in seed mode whenever we trigger a hash check
1072 		// for a piece, before we read it. It's used to throttle
1073 		// the hash checks to just a few per peer at a time.
1074 		std::uint8_t m_outstanding_piece_verification:3;
1075 
1076 		// is true if it was we that connected to the peer
1077 		// and false if we got an incoming connection
1078 		// could be considered: true = local, false = remote
1079 		bool m_outgoing:1;
1080 
1081 		// is true if we learn the incoming connections listening
1082 		// during the extended handshake
1083 		bool m_received_listen_port:1;
1084 
1085 		// if this is true, the disconnection
1086 		// timestamp is not updated when the connection
1087 		// is closed. This means the time until we can
1088 		// reconnect to this peer is shorter, and likely
1089 		// immediate.
1090 		bool m_fast_reconnect:1;
1091 
1092 		// this is set to true if the connection timed
1093 		// out or closed the connection. In that
1094 		// case we will not try to reconnect to
1095 		// this peer
1096 		bool m_failed:1;
1097 
1098 		// this is set to true if the connection attempt
1099 		// succeeded. i.e. the TCP 3-way handshake
1100 		bool m_connected:1;
1101 
1102 		// if this is true, the blocks picked by the piece
1103 		// picker will be merged before passed to the
1104 		// request function. i.e. subsequent blocks are
1105 		// merged into larger blocks. This is used by
1106 		// the http-downloader, to request whole pieces
1107 		// at a time.
1108 		bool m_request_large_blocks:1;
1109 
1110 #ifndef TORRENT_DISABLE_SHARE_MODE
1111 		// set to true if this peer is in share mode
1112 		bool m_share_mode:1;
1113 #endif
1114 
1115 		// set to true when this peer is only uploading
1116 		bool m_upload_only:1;
1117 
1118 		// this is set to true once the bitfield is received
1119 		bool m_bitfield_received:1;
1120 
1121 		// if this is set to true, the client will not
1122 		// pick any pieces from this peer
1123 		bool m_no_download:1;
1124 
1125 		// 1 bit
1126 
1127 		// set to true while we're trying to holepunch
1128 		bool m_holepunch_mode:1;
1129 
1130 		// the other side has told us that it won't send anymore
1131 		// data to us for a while
1132 		bool m_peer_choked:1;
1133 
1134 		// this is set to true when a have_all
1135 		// message is received. This information
1136 		// is used to fill the bitmask in init()
1137 		bool m_have_all:1;
1138 
1139 		// other side says that it's interested in downloading
1140 		// from us.
1141 		bool m_peer_interested:1;
1142 
1143 		// set to true when we should recalculate interest
1144 		// for this peer. Since this is a fairly expensive
1145 		// operation, it's delayed until the second_tick is
1146 		// fired, so that multiple events that wants to recalc
1147 		// interest are coalesced into only triggering it once
1148 		// the actual computation is done in do_update_interest().
1149 		bool m_need_interest_update:1;
1150 
1151 		// set to true if this peer has metadata, and false
1152 		// otherwise.
1153 		bool m_has_metadata:1;
1154 
1155 		// this is set to true if this peer was accepted exceeding
1156 		// the connection limit. It means it has to disconnect
1157 		// itself, or some other peer, as soon as it's completed
1158 		// the handshake. We need to wait for the handshake in
1159 		// order to know which torrent it belongs to, to know which
1160 		// other peers to compare it to.
1161 		bool m_exceeded_limit:1;
1162 
1163 		// this is slow-start at the bittorrent layer. It affects how we increase
1164 		// desired queue size (i.e. the number of outstanding requests we keep).
1165 		// While the underlying transport protocol is in slow-start, the number of
1166 		// outstanding requests need to increase at the same pace to keep up.
1167 		bool m_slow_start:1;
1168 
1169 #if TORRENT_USE_ASSERTS
1170 	public:
1171 		bool m_in_constructor = true;
1172 		bool m_disconnect_started = false;
1173 		bool m_initialized = false;
1174 		int m_in_use = 1337;
1175 		int m_received_in_piece = 0;
1176 		bool m_destructed = false;
1177 		// this is true while there is an outstanding
1178 		// async write job on the socket
1179 		bool m_socket_is_writing = false;
1180 		bool is_single_thread() const;
1181 #endif
1182 	};
1183 
1184 	struct cork
1185 	{
corklibtorrent::cork1186 		explicit cork(peer_connection& p): m_pc(p)
1187 		{
1188 			if (m_pc.m_channel_state[peer_connection::upload_channel] & peer_info::bw_network)
1189 				return;
1190 
1191 			// pretend that there's an outstanding send operation already, to
1192 			// prevent future calls to setup_send() from actually causing an
1193 			// async_send() to be issued.
1194 			m_pc.m_channel_state[peer_connection::upload_channel] |= peer_info::bw_network;
1195 			m_need_uncork = true;
1196 		}
1197 		cork(cork const&) = delete;
1198 		cork& operator=(cork const&) = delete;
1199 
~corklibtorrent::cork1200 		~cork()
1201 		{
1202 			if (!m_need_uncork) return;
1203 			try {
1204 				m_pc.m_channel_state[peer_connection::upload_channel] &= ~peer_info::bw_network;
1205 				m_pc.setup_send();
1206 			}
1207 			catch (std::bad_alloc const&) {
1208 				m_pc.disconnect(make_error_code(boost::system::errc::not_enough_memory)
1209 					, operation_t::sock_write);
1210 			}
1211 			catch (boost::system::system_error const& err) {
1212 				m_pc.disconnect(err.code(), operation_t::sock_write);
1213 			}
1214 			catch (...) {
1215 				m_pc.disconnect(make_error_code(boost::system::errc::not_enough_memory)
1216 					, operation_t::sock_write);
1217 			}
1218 		}
1219 	private:
1220 		peer_connection& m_pc;
1221 		bool m_need_uncork = false;
1222 	};
1223 
1224 }
1225 
1226 #endif // TORRENT_PEER_CONNECTION_HPP_INCLUDED
1227