-
-
Notifications
You must be signed in to change notification settings - Fork 995
/
peer_connection.cpp
6883 lines (5893 loc) · 200 KB
/
peer_connection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2016, tnextday
Copyright (c) 2003-2022, Arvid Norberg
Copyright (c) 2004, Magnus Jonsson
Copyright (c) 2015, Mikhail Titov
Copyright (c) 2016-2018, 2020, Alden Torres
Copyright (c) 2016, Andrei Kurushin
Copyright (c) 2016-2018, Steven Siloti
Copyright (c) 2017-2018, Pavel Pimenov
Copyright (c) 2020, Viktor Elofsson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <functional>
#include <cstdint>
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/logic/tribool.hpp>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/aux_/invariant_check.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/aux_/session_interface.hpp"
#include "libtorrent/peer_list.hpp"
#include "libtorrent/aux_/socket_type.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/error.hpp"
#include "libtorrent/aux_/alloca.hpp"
#include "libtorrent/disk_interface.hpp"
#include "libtorrent/aux_/bandwidth_manager.hpp"
#include "libtorrent/request_blocks.hpp" // for request_a_block
#include "libtorrent/performance_counters.hpp" // for counters
#include "libtorrent/aux_/alert_manager.hpp" // for alert_manager
#include "libtorrent/ip_filter.hpp"
#include "libtorrent/kademlia/node_id.hpp"
#include "libtorrent/close_reason.hpp"
#include "libtorrent/aux_/has_block.hpp"
#include "libtorrent/aux_/time.hpp"
#include "libtorrent/aux_/buffer.hpp"
#include "libtorrent/aux_/array.hpp"
#include "libtorrent/aux_/set_socket_buffer.hpp"
#include "libtorrent/aux_/set_traffic_class.hpp"
#if TORRENT_USE_ASSERTS
#include <set>
#endif
#ifndef TORRENT_DISABLE_LOGGING
#include <cstdarg> // for va_start, va_end
#include <cstdio> // for vsnprintf
#include "libtorrent/socket_io.hpp"
#include "libtorrent/hex.hpp" // to_hex
#endif
#include "libtorrent/aux_/torrent_impl.hpp"
//#define TORRENT_CORRUPT_DATA
using namespace std::placeholders;
namespace libtorrent {
constexpr request_flags_t peer_connection::time_critical;
constexpr request_flags_t peer_connection::busy;
namespace {
// the limits of the download queue size
constexpr int min_request_queue = 2;
bool pending_block_in_buffer(pending_block const& pb)
{
return pb.send_buffer_offset != pending_block::not_in_buffer;
}
}
constexpr piece_index_t piece_block_progress::invalid_index;
constexpr disconnect_severity_t peer_connection_interface::normal;
constexpr disconnect_severity_t peer_connection_interface::failure;
constexpr disconnect_severity_t peer_connection_interface::peer_error;
#if TORRENT_USE_ASSERTS
bool peer_connection::is_single_thread() const
{
#ifdef TORRENT_USE_INVARIANT_CHECKS
std::shared_ptr<torrent> t = m_torrent.lock();
if (!t) return true;
return t->is_single_thread();
#else
return true;
#endif
}
#endif
peer_connection::peer_connection(peer_connection_args& pack)
: peer_connection_hot_members(pack.tor, *pack.ses, *pack.sett)
, m_socket(std::move(pack.s))
, m_peer_info(pack.peerinfo)
, m_counters(*pack.stats_counters)
, m_num_pieces(0)
, m_max_out_request_queue(aux::clamp_assign<std::uint16_t>(m_settings.get_int(settings_pack::max_out_request_queue)))
, m_remote(pack.endp)
, m_disk_thread(*pack.disk_thread)
, m_ios(*pack.ios)
, m_work(make_work_guard(m_ios))
, m_outstanding_piece_verification(0)
, m_outgoing(!pack.tor.expired())
, m_received_listen_port(false)
, m_fast_reconnect(false)
, m_failed(false)
, m_connected(pack.tor.expired())
, m_request_large_blocks(false)
#ifndef TORRENT_DISABLE_SHARE_MODE
, m_share_mode(false)
#endif
, m_upload_only(false)
, m_bitfield_received(false)
, m_no_download(false)
, m_deferred_send_block_requests(false)
, m_holepunch_mode(false)
, m_peer_choked(true)
, m_have_all(false)
, m_peer_interested(false)
, m_need_interest_update(false)
, m_has_metadata(true)
, m_exceeded_limit(false)
, m_slow_start(true)
{
m_counters.inc_stats_counter(counters::num_tcp_peers
+ static_cast<std::uint8_t>(socket_type_idx(m_socket)));
std::shared_ptr<torrent> t = m_torrent.lock();
// the protocol_v2 flag should not be set for non-v2 torrents
TORRENT_ASSERT(!t || t->info_hash().has_v2() || !m_peer_info->protocol_v2);
if (m_connected)
m_counters.inc_stats_counter(counters::num_peers_connected);
else if (m_connecting)
m_counters.inc_stats_counter(counters::num_peers_half_open);
// if t is nullptr, we better not be connecting, since
// we can't decrement the connecting counter
TORRENT_ASSERT(t || !m_connecting);
m_channel_state[upload_channel] = peer_info::bw_idle;
m_channel_state[download_channel] = peer_info::bw_idle;
m_quota[0] = 0;
m_quota[1] = 0;
TORRENT_ASSERT(pack.peerinfo == nullptr || pack.peerinfo->banned == false);
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(m_outgoing ? peer_log_alert::outgoing : peer_log_alert::incoming))
{
error_code ec;
TORRENT_ASSERT(m_socket.remote_endpoint(ec) == m_remote || ec);
tcp::endpoint local_ep = m_socket.local_endpoint(ec);
peer_log(m_outgoing ? peer_log_alert::outgoing : peer_log_alert::incoming
, m_outgoing ? "OUTGOING_CONNECTION" : "INCOMING_CONNECTION"
, "ep: %s type: %s seed: %d p: %p local: %s"
, print_endpoint(m_remote).c_str()
, socket_type_name(m_socket)
, m_peer_info ? m_peer_info->seed : 0
, static_cast<void*>(m_peer_info)
, print_endpoint(local_ep).c_str());
}
#endif
// this counter should not be incremented until we know constructing this
// peer object can't fail anymore
if (m_connecting && t) t->inc_num_connecting(m_peer_info);
#if TORRENT_USE_ASSERTS
m_in_constructor = false;
#endif
}
template <typename Fun, typename... Args>
void peer_connection::wrap(Fun f, Args&&... a)
#ifndef BOOST_NO_EXCEPTIONS
try
#endif
{
(this->*f)(std::forward<Args>(a)...);
}
#ifndef BOOST_NO_EXCEPTIONS
catch (std::bad_alloc const&) {
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "EXCEPTION", "bad_alloc");
#endif
disconnect(make_error_code(boost::system::errc::not_enough_memory)
, operation_t::unknown);
}
catch (system_error const& e) {
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "EXCEPTION", "(%d %s) %s"
, e.code().value()
, e.code().message().c_str()
, e.what());
#endif
disconnect(e.code(), operation_t::unknown);
}
catch (std::exception const& e) {
TORRENT_UNUSED(e);
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "EXCEPTION", "%s", e.what());
#endif
disconnect(make_error_code(boost::system::errc::not_enough_memory)
, operation_t::sock_write);
}
#endif // BOOST_NO_EXCEPTIONS
int peer_connection::timeout() const
{
TORRENT_ASSERT(is_single_thread());
int ret = m_settings.get_int(settings_pack::peer_timeout);
#if TORRENT_USE_I2P
if (m_peer_info && m_peer_info->is_i2p_addr)
{
// quadruple the timeout for i2p peers
ret *= 4;
}
#endif
return ret;
}
void peer_connection::on_exception(std::exception const& e)
{
TORRENT_UNUSED(e);
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "PEER_ERROR", "ERROR: %s"
, e.what());
#endif
disconnect(error_code(), operation_t::unknown, peer_error);
}
void peer_connection::on_error(error_code const& ec)
{
disconnect(ec, operation_t::unknown, peer_error);
}
int peer_connection::get_priority(int const channel) const
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(channel >= 0 && channel < 2);
int prio = 1;
for (int i = 0; i < num_classes(); ++i)
{
int class_prio = m_ses.peer_classes().at(class_at(i))->priority[channel];
if (prio < class_prio) prio = class_prio;
}
std::shared_ptr<torrent> t = associated_torrent().lock();
if (t)
{
for (int i = 0; i < t->num_classes(); ++i)
{
int class_prio = m_ses.peer_classes().at(t->class_at(i))->priority[channel];
if (prio < class_prio) prio = class_prio;
}
}
return prio;
}
void peer_connection::reset_choke_counters()
{
TORRENT_ASSERT(is_single_thread());
m_downloaded_at_last_round= m_statistics.total_payload_download();
m_uploaded_at_last_round = m_statistics.total_payload_upload();
}
void peer_connection::start()
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(m_peer_info == nullptr || m_peer_info->connection == this);
std::shared_ptr<torrent> t = m_torrent.lock();
if (!m_outgoing)
{
error_code ec;
m_socket.non_blocking(true, ec);
if (ec)
{
disconnect(ec, operation_t::iocontrol);
return;
}
m_remote = m_socket.remote_endpoint(ec);
if (ec)
{
disconnect(ec, operation_t::getpeername);
return;
}
m_local = m_socket.local_endpoint(ec);
if (ec)
{
disconnect(ec, operation_t::getname);
return;
}
if (m_settings.get_int(settings_pack::peer_dscp) != 0)
{
int const value = m_settings.get_int(settings_pack::peer_dscp);
aux::set_traffic_class(m_socket, value, ec);
#ifndef TORRENT_DISABLE_LOGGING
if (ec && should_log(peer_log_alert::outgoing))
{
peer_log(peer_log_alert::outgoing, "SET_DSCP", "value: %d e: %s"
, value, ec.message().c_str());
}
#endif
}
}
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::info))
{
peer_log(peer_log_alert::info, "SET_PEER_CLASS", "a: %s"
, print_address(m_remote.address()).c_str());
}
#endif
m_ses.set_peer_classes(this, m_remote.address(), socket_type_idx(m_socket));
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::info))
{
std::string classes;
for (int i = 0; i < num_classes(); ++i)
{
classes += m_ses.peer_classes().at(class_at(i))->label;
classes += ' ';
}
peer_log(peer_log_alert::info, "CLASS", "%s"
, classes.c_str());
}
#endif
if (t && t->ready_for_connections())
{
init();
}
// if this is an incoming connection, we're done here
if (!m_connecting)
{
error_code err;
aux::set_socket_buffer_size(m_socket, m_settings, err);
#ifndef TORRENT_DISABLE_LOGGING
if (err && should_log(peer_log_alert::incoming))
{
peer_log(peer_log_alert::incoming, "SOCKET_BUFFER", "%s %s"
, print_endpoint(m_remote).c_str()
, print_error(err).c_str());
}
#endif
return;
}
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::outgoing))
{
peer_log(peer_log_alert::outgoing, "OPEN", "protocol: %s"
, (aux::is_v4(m_remote) ? "IPv4" : "IPv6"));
}
#endif
error_code ec;
m_socket.open(m_remote.protocol(), ec);
if (ec)
{
disconnect(ec, operation_t::sock_open);
return;
}
tcp::endpoint const bound_ip = m_ses.bind_outgoing_socket(m_socket
, m_remote.address(), ec);
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::outgoing))
{
peer_log(peer_log_alert::outgoing, "BIND", "dst: %s ec: %s"
, print_endpoint(bound_ip).c_str()
, ec.message().c_str());
}
#else
TORRENT_UNUSED(bound_ip);
#endif
if (ec)
{
disconnect(ec, operation_t::sock_bind);
return;
}
{
error_code err;
aux::set_socket_buffer_size(m_socket, m_settings, err);
#ifndef TORRENT_DISABLE_LOGGING
if (err && should_log(peer_log_alert::outgoing))
{
peer_log(peer_log_alert::outgoing, "SOCKET_BUFFER", "%s %s"
, print_endpoint(m_remote).c_str()
, print_error(err).c_str());
}
#endif
}
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::outgoing))
{
peer_log(peer_log_alert::outgoing, "ASYNC_CONNECT", "dst: %s"
, print_endpoint(m_remote).c_str());
}
#endif
ADD_OUTSTANDING_ASYNC("peer_connection::on_connection_complete");
auto conn = self();
m_socket.async_connect(m_remote
, [conn](error_code const& e) { conn->wrap(&peer_connection::on_connection_complete, e); });
m_connect = aux::time_now();
sent_syn(aux::is_v6(m_remote));
if (t && t->alerts().should_post<peer_connect_alert>())
{
t->alerts().emplace_alert<peer_connect_alert>(
t->get_handle(), remote(), pid(), socket_type_idx(m_socket), peer_connect_alert::direction_t::out);
}
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::info))
{
peer_log(peer_log_alert::info, "LOCAL ENDPOINT", "e: %s"
, print_endpoint(m_socket.local_endpoint(ec)).c_str());
}
#endif
}
void peer_connection::update_interest()
{
TORRENT_ASSERT(is_single_thread());
if (!m_need_interest_update)
{
// we're the first to request an interest update
// post a message in order to delay it enough for
// any potential other messages already in the queue
// to not trigger another one. This effectively defer
// the update until the current message queue is
// flushed
auto conn = self();
post(m_ios, [conn] { conn->wrap(&peer_connection::do_update_interest); });
}
m_need_interest_update = true;
}
void peer_connection::do_update_interest()
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(m_need_interest_update);
m_need_interest_update = false;
std::shared_ptr<torrent> t = m_torrent.lock();
if (!t) return;
// if m_have_piece is 0, it means the connections
// have not been initialized yet. The interested
// flag will be updated once they are.
if (m_have_piece.empty())
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "UPDATE_INTEREST", "connections not initialized");
#endif
return;
}
if (!t->ready_for_connections())
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "UPDATE_INTEREST", "not ready for connections");
#endif
return;
}
bool interested = false;
if (!t->is_upload_only())
{
t->need_picker();
piece_picker const& p = t->picker();
piece_index_t const end_piece(p.num_pieces());
for (piece_index_t j(0); j != end_piece; ++j)
{
if (m_have_piece[j]
&& t->piece_priority(j) > dont_download
&& !p.has_piece_passed(j))
{
interested = true;
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "UPDATE_INTEREST", "interesting, piece: %d"
, static_cast<int>(j));
#endif
break;
}
}
}
#ifndef TORRENT_DISABLE_LOGGING
if (!interested)
peer_log(peer_log_alert::info, "UPDATE_INTEREST", "not interesting");
#endif
if (!interested) send_not_interested();
else t->peer_is_interesting(*this);
TORRENT_ASSERT(in_handshake() || is_interesting() == interested);
disconnect_if_redundant();
}
#ifndef TORRENT_DISABLE_LOGGING
bool peer_connection::should_log(peer_log_alert::direction_t) const
{
return m_ses.alerts().should_post<peer_log_alert>();
}
void peer_connection::peer_log(peer_log_alert::direction_t direction
, char const* event) const noexcept
{
peer_log(direction, event, "");
}
TORRENT_FORMAT(4,5)
void peer_connection::peer_log(peer_log_alert::direction_t direction
, char const* event, char const* fmt, ...) const noexcept try
{
TORRENT_ASSERT(is_single_thread());
if (!m_ses.alerts().should_post<peer_log_alert>()) return;
va_list v;
va_start(v, fmt);
torrent_handle h;
std::shared_ptr<torrent> t = m_torrent.lock();
if (t) h = t->get_handle();
m_ses.alerts().emplace_alert<peer_log_alert>(
h, m_remote, m_peer_id, direction, event, fmt, v);
va_end(v);
}
catch (std::exception const&) {}
#endif
#ifndef TORRENT_DISABLE_EXTENSIONS
void peer_connection::add_extension(std::shared_ptr<peer_plugin> ext)
{
TORRENT_ASSERT(is_single_thread());
m_extensions.push_back(ext);
}
peer_plugin const* peer_connection::find_plugin(string_view type)
{
TORRENT_ASSERT(is_single_thread());
auto p = std::find_if(m_extensions.begin(), m_extensions.end()
, [&](std::shared_ptr<peer_plugin> const& e) { return e->type() == type; });
return p != m_extensions.end() ? p->get() : nullptr;
}
#endif
void peer_connection::send_allowed_set()
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
std::shared_ptr<torrent> t = m_torrent.lock();
TORRENT_ASSERT(t);
if (!t->valid_metadata())
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ALLOWED", "skipping allowed set because we don't have metadata");
#endif
return;
}
#ifndef TORRENT_DISABLE_SUPERSEEDING
if (t->super_seeding())
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ALLOWED", "skipping allowed set because of super seeding");
#endif
return;
}
#endif
if (upload_only())
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ALLOWED", "skipping allowed set because peer is upload only");
#endif
return;
}
int const num_allowed_pieces = m_settings.get_int(settings_pack::allowed_fast_set_size);
if (num_allowed_pieces <= 0) return;
if (!t->valid_metadata()) return;
int const num_pieces = t->torrent_file().num_pieces();
if (num_allowed_pieces >= num_pieces)
{
// this is a special case where we have more allowed
// fast pieces than pieces in the torrent. Just send
// an allowed fast message for every single piece
for (auto const i : t->torrent_file().piece_range())
{
// there's no point in offering fast pieces
// that the peer already has
if (has_piece(i)) continue;
write_allow_fast(i);
TORRENT_ASSERT(std::find(m_accept_fast.begin()
, m_accept_fast.end(), i)
== m_accept_fast.end());
if (m_accept_fast.empty())
{
m_accept_fast.reserve(10);
m_accept_fast_piece_cnt.reserve(10);
}
m_accept_fast.push_back(i);
m_accept_fast_piece_cnt.push_back(0);
}
return;
}
std::string x;
address const& addr = m_remote.address();
if (addr.is_v4())
{
address_v4::bytes_type bytes = addr.to_v4().to_bytes();
x.assign(reinterpret_cast<char*>(bytes.data()), bytes.size());
}
else
{
address_v6::bytes_type bytes = addr.to_v6().to_bytes();
x.assign(reinterpret_cast<char*>(bytes.data()), bytes.size());
}
x.append(associated_info_hash().data(), 20);
sha1_hash hash = hasher(x).final();
int attempts = 0;
int loops = 0;
for (;;)
{
char const* p = hash.data();
for (int i = 0; i < int(hash.size() / sizeof(std::uint32_t)); ++i)
{
++loops;
TORRENT_ASSERT(num_pieces > 0);
piece_index_t const piece(int(aux::read_uint32(p) % std::uint32_t(num_pieces)));
if (std::find(m_accept_fast.begin(), m_accept_fast.end(), piece)
!= m_accept_fast.end())
{
// this is our safety-net to make sure this loop terminates, even
// under the worst conditions
if (++loops > 500) return;
continue;
}
if (!has_piece(piece))
{
write_allow_fast(piece);
if (m_accept_fast.empty())
{
m_accept_fast.reserve(10);
m_accept_fast_piece_cnt.reserve(10);
}
m_accept_fast.push_back(piece);
m_accept_fast_piece_cnt.push_back(0);
}
if (++attempts >= num_allowed_pieces) return;
}
hash = hasher(hash).final();
}
}
void peer_connection::on_metadata_impl()
{
TORRENT_ASSERT(is_single_thread());
std::shared_ptr<torrent> t = associated_torrent().lock();
m_have_piece.resize(t->torrent_file().num_pieces(), m_have_all);
m_num_pieces = m_have_piece.count();
piece_index_t const limit(m_num_pieces);
// now that we know how many pieces there are
// remove any invalid allowed_fast and suggest pieces
// now that we know what the number of pieces are
m_allowed_fast.erase(std::remove_if(m_allowed_fast.begin(), m_allowed_fast.end()
, [=](piece_index_t const p) { return p >= limit; })
, m_allowed_fast.end());
// remove any piece suggested to us whose index is invalid
// now that we know how many pieces there are
m_suggested_pieces.erase(
std::remove_if(m_suggested_pieces.begin(), m_suggested_pieces.end()
, [=](piece_index_t const p) { return p >= limit; })
, m_suggested_pieces.end());
on_metadata();
if (m_disconnecting) return;
}
void peer_connection::init()
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
std::shared_ptr<torrent> t = m_torrent.lock();
TORRENT_ASSERT(t);
TORRENT_ASSERT(t->valid_metadata());
TORRENT_ASSERT(t->ready_for_connections());
m_have_piece.resize(t->torrent_file().num_pieces(), m_have_all);
if (m_have_all)
{
m_num_pieces = t->torrent_file().num_pieces();
m_have_piece.set_all();
}
#if TORRENT_USE_ASSERTS
TORRENT_ASSERT(!m_initialized);
m_initialized = true;
#endif
// now that we have a piece_picker,
// update it with this peer's pieces
TORRENT_ASSERT(m_num_pieces == m_have_piece.count());
if (m_num_pieces == m_have_piece.size())
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "INIT", "this is a seed p: %p"
, static_cast<void*>(m_peer_info));
#endif
TORRENT_ASSERT(m_have_piece.all_set());
TORRENT_ASSERT(m_have_piece.count() == m_have_piece.size());
TORRENT_ASSERT(m_have_piece.size() == t->torrent_file().num_pieces());
// if this is a web seed. we don't have a peer_info struct
t->set_seed(m_peer_info, true);
TORRENT_ASSERT(is_seed());
t->peer_has_all(this);
#if TORRENT_USE_INVARIANT_CHECKS
if (t && t->has_picker())
t->picker().check_peer_invariant(m_have_piece, peer_info_struct());
#endif
if (t->is_upload_only()) send_not_interested();
else t->peer_is_interesting(*this);
disconnect_if_redundant();
return;
}
TORRENT_ASSERT(!is_seed());
// if we're a seed, we don't keep track of piece availability
if (t->has_picker())
{
TORRENT_ASSERT(m_have_piece.size() == t->torrent_file().num_pieces());
t->peer_has(m_have_piece, this);
bool interesting = false;
for (auto const i : m_have_piece.range())
{
if (!m_have_piece[i]) continue;
// if the peer has a piece and we don't, the peer is interesting
if (!t->have_piece(i)
&& t->picker().piece_priority(i) != dont_download)
interesting = true;
}
if (interesting) t->peer_is_interesting(*this);
else send_not_interested();
}
else
{
update_interest();
}
}
peer_connection::~peer_connection()
{
m_counters.inc_stats_counter(counters::num_tcp_peers
+ static_cast<std::uint8_t>(socket_type_idx(m_socket)), -1);
// INVARIANT_CHECK;
TORRENT_ASSERT(!m_in_constructor);
TORRENT_ASSERT(!m_destructed);
#if TORRENT_USE_ASSERTS
m_destructed = true;
#endif
#if TORRENT_USE_ASSERTS
m_in_use = 0;
#endif
// decrement the stats counter
set_endgame(false);
if (m_interesting)
m_counters.inc_stats_counter(counters::num_peers_down_interested, -1);
if (m_peer_interested)
m_counters.inc_stats_counter(counters::num_peers_up_interested, -1);
if (!m_choked)
{
m_counters.inc_stats_counter(counters::num_peers_up_unchoked_all, -1);
if (!ignore_unchoke_slots())
m_counters.inc_stats_counter(counters::num_peers_up_unchoked, -1);
}
if (!m_peer_choked)
m_counters.inc_stats_counter(counters::num_peers_down_unchoked, -1);
if (m_connected)
m_counters.inc_stats_counter(counters::num_peers_connected, -1);
m_connected = false;
if (!m_download_queue.empty())
m_counters.inc_stats_counter(counters::num_peers_down_requests, -1);
// defensive
std::shared_ptr<torrent> t = m_torrent.lock();
// if t is nullptr, we better not be connecting, since
// we can't decrement the connecting counter
TORRENT_ASSERT(t || !m_connecting);
// we should really have dealt with this already
if (m_connecting)
{
m_counters.inc_stats_counter(counters::num_peers_half_open, -1);
if (t) t->dec_num_connecting(m_peer_info);
m_connecting = false;
}
#ifndef TORRENT_DISABLE_EXTENSIONS
m_extensions.clear();
#endif
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "CONNECTION CLOSED");
#endif
TORRENT_ASSERT(m_request_queue.empty());
TORRENT_ASSERT(m_download_queue.empty());
}
bool peer_connection::on_parole() const
{ return peer_info_struct() && peer_info_struct()->on_parole; }
picker_options_t peer_connection::picker_options() const
{
TORRENT_ASSERT(is_single_thread());
picker_options_t ret = m_picker_options;
std::shared_ptr<torrent> t = m_torrent.lock();
TORRENT_ASSERT(t);
if (!t) return {};
if (t->is_sequential_download())
{
ret |= piece_picker::sequential;
}
else if (t->num_have() < m_settings.get_int(settings_pack::initial_picker_threshold))
{
// if we have fewer pieces than a certain threshold
// don't pick rare pieces, just pick random ones,
// and prioritize finishing them
ret |= piece_picker::prioritize_partials;
}
else
{
ret |= piece_picker::rarest_first;
if (m_snubbed)
{
// snubbed peers should request
// the common pieces first, just to make
// it more likely for all snubbed peers to
// request blocks from the same piece
ret |= piece_picker::reverse;
}
else
{
if (m_settings.get_bool(settings_pack::piece_extent_affinity)
&& t->num_time_critical_pieces() == 0)
ret |= piece_picker::piece_extent_affinity;
}
}
if (m_settings.get_bool(settings_pack::prioritize_partial_pieces))
ret |= piece_picker::prioritize_partials;
if (on_parole()) ret |= piece_picker::on_parole
| piece_picker::prioritize_partials;
// only one of rarest_first and sequential can be set. i.e. the sum of
// whether the bit is set or not may only be 0 or 1 (never 2)
TORRENT_ASSERT(((ret & piece_picker::rarest_first) ? 1 : 0)
+ ((ret & piece_picker::sequential) ? 1 : 0) <= 1);
return ret;
}
void peer_connection::fast_reconnect(bool r)
{
TORRENT_ASSERT(is_single_thread());
if (!peer_info_struct() || peer_info_struct()->fast_reconnects > 1)
return;
m_fast_reconnect = r;
peer_info_struct()->last_connected = std::uint16_t(m_ses.session_time());
int const rewind = m_settings.get_int(settings_pack::min_reconnect_time)
* m_settings.get_int(settings_pack::max_failcount);
if (int(peer_info_struct()->last_connected) < rewind) peer_info_struct()->last_connected = 0;
else peer_info_struct()->last_connected -= std::uint16_t(rewind);
if (peer_info_struct()->fast_reconnects < 15)
++peer_info_struct()->fast_reconnects;
}
void peer_connection::received_piece(piece_index_t const index)
{
TORRENT_ASSERT(is_single_thread());
// dont announce during handshake
if (in_handshake()) return;
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::incoming, "RECEIVED", "piece: %d"
, static_cast<int>(index));
#endif
// remove suggested pieces once we have them
auto i = std::find(m_suggested_pieces.begin(), m_suggested_pieces.end(), index);
if (i != m_suggested_pieces.end()) m_suggested_pieces.erase(i);
// remove allowed fast pieces
i = std::find(m_allowed_fast.begin(), m_allowed_fast.end(), index);
if (i != m_allowed_fast.end()) m_allowed_fast.erase(i);
if (has_piece(index))
{
// if we got a piece that this peer has
// it might have been the last interesting
// piece this peer had. We might not be
// interested anymore
update_interest();
if (is_disconnecting()) return;
}
if (disconnect_if_redundant()) return;
#if TORRENT_USE_ASSERTS
std::shared_ptr<torrent> t = m_torrent.lock();
TORRENT_ASSERT(t);
#endif