/
peer_list.cpp
1462 lines (1234 loc) · 40.9 KB
/
peer_list.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) 2003-2022, Arvid Norberg
Copyright (c) 2004, Magnus Jonsson
Copyright (c) 2009, Daniel Wallin
Copyright (c) 2016-2018, 2020-2021, Alden Torres
Copyright (c) 2016, Andrei Kurushin
Copyright (c) 2018, Steven Siloti
Copyright (c) 2020-2021, Paul-Louis Ageneau
All rights reserved.
You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/
#include <functional>
#include "libtorrent/aux_/peer_connection.hpp"
#include "libtorrent/aux_/web_peer_connection.hpp"
#include "libtorrent/aux_/peer_list.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/aux_/socket_type.hpp"
#include "libtorrent/aux_/invariant_check.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/aux_/session_interface.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/aux_/random.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/ip_filter.hpp"
#include "libtorrent/aux_/torrent_peer_allocator.hpp"
#include "libtorrent/aux_/ip_voter.hpp" // for external_ip
#include "libtorrent/aux_/ip_helpers.hpp" // for is_v6
#if TORRENT_USE_ASSERTS
#include "libtorrent/aux_/socket_io.hpp" // for print_endpoint
#endif
#ifndef TORRENT_DISABLE_LOGGING
#include "libtorrent/aux_/socket_io.hpp" // for print_endpoint
#endif
using namespace std::placeholders;
namespace {
using namespace libtorrent;
struct match_peer_endpoint
{
match_peer_endpoint(address const& addr, std::uint16_t port)
: m_addr(addr), m_port(port)
{}
bool operator()(aux::torrent_peer const* p) const
{
TORRENT_ASSERT(p->in_use);
return p->address() == m_addr && p->port == m_port;
}
address const& m_addr;
std::uint16_t m_port;
};
// this returns true if lhs is a better erase candidate than rhs
bool compare_peer_erase(aux::torrent_peer const& lhs, aux::torrent_peer const& rhs)
{
TORRENT_ASSERT(lhs.connection == nullptr);
TORRENT_ASSERT(rhs.connection == nullptr);
// primarily, prefer getting rid of peers we've already tried and failed
if (lhs.failcount != rhs.failcount)
return lhs.failcount > rhs.failcount;
bool const lhs_resume_data_source = lhs.peer_source() == peer_info::resume_data;
bool const rhs_resume_data_source = rhs.peer_source() == peer_info::resume_data;
// prefer to drop peers whose only source is resume data
if (lhs_resume_data_source != rhs_resume_data_source)
return int(lhs_resume_data_source) > int(rhs_resume_data_source);
if (lhs.connectable != rhs.connectable)
return int(lhs.connectable) < int(rhs.connectable);
return lhs.trust_points < rhs.trust_points;
}
// this returns true if lhs is a better connect candidate than rhs
bool compare_peer(aux::torrent_peer const* lhs, aux::torrent_peer const* rhs
, aux::external_ip const& external, int const external_port, bool const finished)
{
// prefer peers with lower failcount
if (lhs->failcount != rhs->failcount)
return lhs->failcount < rhs->failcount;
// Local peers should always be tried first
bool const lhs_local = aux::is_local(lhs->address());
bool const rhs_local = aux::is_local(rhs->address());
if (lhs_local != rhs_local) return int(lhs_local) > int(rhs_local);
if (lhs->last_connected != rhs->last_connected)
return lhs->last_connected < rhs->last_connected;
if (finished && lhs->maybe_upload_only != rhs->maybe_upload_only)
{
// if we're finished, de-prioritze peers we think may be seeds
// since being upload-only doesn't necessarily mean it's a good peer
// to be connected to as a downloader, we don't prioritize the
// inverse when we're not finished
return rhs->maybe_upload_only;
}
int const lhs_rank = aux::source_rank(lhs->peer_source());
int const rhs_rank = aux::source_rank(rhs->peer_source());
if (lhs_rank != rhs_rank) return lhs_rank > rhs_rank;
std::uint32_t const lhs_peer_rank = lhs->rank(external, external_port);
std::uint32_t const rhs_peer_rank = rhs->rank(external, external_port);
return lhs_peer_rank > rhs_peer_rank;
}
} // anonymous namespace
namespace libtorrent::aux {
peer_list::peer_list(torrent_peer_allocator_interface& alloc)
: m_locked_peer(nullptr)
, m_peer_allocator(alloc)
, m_num_seeds(0)
, m_finished(0)
{
thread_started();
}
void peer_list::clear()
{
for (auto* p : m_peers)
m_peer_allocator.free_peer_entry(p);
m_peers.clear();
m_candidate_cache.clear();
m_num_connect_candidates = 0;
m_num_seeds = 0;
}
peer_list::~peer_list()
{
for (auto* p : m_peers)
m_peer_allocator.free_peer_entry(p);
}
void peer_list::set_max_failcount(torrent_state* state)
{
INVARIANT_CHECK;
if (state->max_failcount == m_max_failcount) return;
recalculate_connect_candidates(state);
}
// disconnects and removes all peers that are now filtered fills in 'erased'
// with torrent_peer pointers that were removed from the peer list. Any
// references to these peers must be cleared immediately after this call
// returns. For instance, in the piece picker.
void peer_list::apply_ip_filter(ip_filter const& filter
, torrent_state* state, std::vector<address>& banned)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
for (auto i = m_peers.begin(); i != m_peers.end();)
{
if ((filter.access((*i)->address()) & ip_filter::blocked) == 0)
{
++i;
continue;
}
if (*i == m_locked_peer)
{
++i;
continue;
}
int const current = int(i - m_peers.begin());
TORRENT_ASSERT(current >= 0);
TORRENT_ASSERT(m_peers.size() > 0);
TORRENT_ASSERT(i != m_peers.end());
if ((*i)->connection)
{
// disconnecting the peer here may also delete the
// peer_info_struct. If that is the case, just continue
size_t count = m_peers.size();
peer_connection_interface* p = (*i)->connection;
banned.push_back(p->remote().address());
p->disconnect(errors::banned_by_ip_filter
, operation_t::bittorrent);
// what *i refers to has changed, i.e. cur was deleted
if (m_peers.size() < count)
{
i = m_peers.begin() + current;
continue;
}
TORRENT_ASSERT((*i)->connection == nullptr
|| (*i)->connection->peer_info_struct() == nullptr);
}
erase_peer(i, state);
i = m_peers.begin() + current;
}
}
void peer_list::clear_peer_prio()
{
INVARIANT_CHECK;
for (auto& p : m_peers)
p->peer_rank = 0;
}
// disconnects and removes all peers that are now filtered
// fills in 'erased' with torrent_peer pointers that were removed
// from the peer list. Any references to these peers must be cleared
// immediately after this call returns. For instance, in the piece picker.
void peer_list::apply_port_filter(port_filter const& filter
, torrent_state* state, std::vector<tcp::endpoint>& banned)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
for (auto i = m_peers.begin(); i != m_peers.end();)
{
if ((filter.access((*i)->port) & port_filter::blocked) == 0)
{
++i;
continue;
}
if (*i == m_locked_peer)
{
++i;
continue;
}
int const current = int(i - m_peers.begin());
TORRENT_ASSERT(current >= 0);
TORRENT_ASSERT(m_peers.size() > 0);
TORRENT_ASSERT(i != m_peers.end());
if ((*i)->connection)
{
// disconnecting the peer here may also delete the
// peer_info_struct. If that is the case, just continue
int count = int(m_peers.size());
peer_connection_interface* p = (*i)->connection;
banned.push_back(p->remote());
p->disconnect(errors::banned_by_port_filter, operation_t::bittorrent);
// what *i refers to has changed, i.e. cur was deleted
if (int(m_peers.size()) < count)
{
i = m_peers.begin() + current;
continue;
}
TORRENT_ASSERT((*i)->connection == nullptr
|| (*i)->connection->peer_info_struct() == nullptr);
}
erase_peer(i, state);
i = m_peers.begin() + current;
}
}
void peer_list::erase_peer(torrent_peer* p, torrent_state* state)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
TORRENT_ASSERT(p->in_use);
TORRENT_ASSERT(m_locked_peer != p);
auto const range = std::equal_range(m_peers.begin(), m_peers.end(), p, peer_address_compare{});
auto const iter = std::find_if(range.first, range.second, [&](torrent_peer const* needle) {
return torrent_peer_equal(needle, p);
});
if (iter == range.second) return;
erase_peer(iter, state);
}
// any peer that is erased from m_peers will be
// erased through this function. This way we can make
// sure that any references to the peer are removed
// as well, such as in the piece picker.
void peer_list::erase_peer(iterator i, torrent_state* state)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
TORRENT_ASSERT(i != m_peers.end());
TORRENT_ASSERT(m_locked_peer != *i);
state->erased.push_back(*i);
if ((*i)->seed)
{
TORRENT_ASSERT(m_num_seeds > 0);
--m_num_seeds;
}
if (is_connect_candidate(**i))
update_connect_candidates(-1);
TORRENT_ASSERT(m_num_connect_candidates < int(m_peers.size()));
if (m_round_robin > i - m_peers.begin()) --m_round_robin;
if (m_round_robin >= int(m_peers.size())) m_round_robin = 0;
// if this peer is in the connect candidate
// cache, erase it from there as well
auto const ci = std::find(m_candidate_cache.begin(), m_candidate_cache.end(), *i);
if (ci != m_candidate_cache.end()) m_candidate_cache.erase(ci);
m_peer_allocator.free_peer_entry(*i);
m_peers.erase(i);
}
bool peer_list::should_erase_immediately(torrent_peer const& p) const
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(p.in_use);
if (&p == m_locked_peer) return false;
return p.peer_source() == peer_info::resume_data;
}
bool peer_list::is_erase_candidate(torrent_peer const& pe) const
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(pe.in_use);
if (&pe == m_locked_peer) return false;
if (pe.connection) return false;
if (is_connect_candidate(pe)) return false;
return (pe.failcount > 0)
|| (pe.peer_source() == peer_info::resume_data);
}
bool peer_list::is_force_erase_candidate(torrent_peer const& pe) const
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(pe.in_use);
if (&pe == m_locked_peer) return false;
return pe.connection == nullptr;
}
void peer_list::erase_peers(torrent_state* state, erase_peer_flags_t const flags)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
int max_peerlist_size = state->max_peerlist_size;
if (max_peerlist_size == 0 || m_peers.empty()) return;
int erase_candidate = -1;
int force_erase_candidate = -1;
if (bool(m_finished) != state->is_finished)
recalculate_connect_candidates(state);
int round_robin = aux::numeric_cast<int>(random(std::uint32_t(m_peers.size() - 1)));
int low_watermark = max_peerlist_size * 95 / 100;
if (low_watermark == max_peerlist_size) --low_watermark;
for (int iterations = std::min(int(m_peers.size()), 300);
iterations > 0; --iterations)
{
if (int(m_peers.size()) < low_watermark)
break;
if (round_robin == int(m_peers.size())) round_robin = 0;
torrent_peer& pe = *m_peers[round_robin];
TORRENT_ASSERT(pe.in_use);
int const current = round_robin;
if (is_erase_candidate(pe)
&& (erase_candidate == -1
|| !compare_peer_erase(*m_peers[erase_candidate], pe)))
{
if (should_erase_immediately(pe))
{
if (erase_candidate > current) --erase_candidate;
if (force_erase_candidate > current) --force_erase_candidate;
TORRENT_ASSERT(current >= 0 && current < int(m_peers.size()));
erase_peer(m_peers.begin() + current, state);
continue;
}
else
{
erase_candidate = current;
}
}
if (is_force_erase_candidate(pe)
&& (force_erase_candidate == -1
|| !compare_peer_erase(*m_peers[force_erase_candidate], pe)))
{
force_erase_candidate = current;
}
++round_robin;
}
if (erase_candidate > -1)
{
TORRENT_ASSERT(erase_candidate >= 0 && erase_candidate < int(m_peers.size()));
erase_peer(m_peers.begin() + erase_candidate, state);
}
else if ((flags & force_erase) && force_erase_candidate > -1)
{
TORRENT_ASSERT(force_erase_candidate >= 0 && force_erase_candidate < int(m_peers.size()));
erase_peer(m_peers.begin() + force_erase_candidate, state);
}
}
// returns true if the peer was actually banned
bool peer_list::ban_peer(torrent_peer* p)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
TORRENT_ASSERT(p->in_use);
if (is_connect_candidate(*p))
update_connect_candidates(-1);
p->banned = true;
TORRENT_ASSERT(!is_connect_candidate(*p));
return true;
}
void peer_list::set_connection(torrent_peer* p, peer_connection_interface* c)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
TORRENT_ASSERT(p->in_use);
TORRENT_ASSERT(c);
const bool was_conn_cand = is_connect_candidate(*p);
p->connection = c;
// now that we're connected, no need to assume the peer is a seed
// anymore. We'll soon know.
p->maybe_upload_only = false;
if (was_conn_cand) update_connect_candidates(-1);
}
void peer_list::inc_failcount(torrent_peer* p)
{
INVARIANT_CHECK;
// failcount is a 5 bit value
if (p->failcount == 31) return;
bool const was_conn_cand = is_connect_candidate(*p);
++p->failcount;
if (was_conn_cand && !is_connect_candidate(*p))
update_connect_candidates(-1);
}
void peer_list::set_failcount(torrent_peer* p, int const f)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
TORRENT_ASSERT(p->in_use);
bool const was_conn_cand = is_connect_candidate(*p);
p->failcount = aux::numeric_cast<std::uint32_t>(f);
if (was_conn_cand != is_connect_candidate(*p))
{
update_connect_candidates(was_conn_cand ? -1 : 1);
}
}
bool peer_list::is_connect_candidate(torrent_peer const& p) const
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(p.in_use);
if (p.connection
|| p.banned
|| p.web_seed
|| !p.connectable
|| (p.seed && m_finished)
|| int(p.failcount) >= m_max_failcount)
return false;
#if TORRENT_USE_RTC
// unsolicited connections over RTC is not possible
if (p.is_rtc_addr) return false;
#endif
return true;
}
void peer_list::find_connect_candidates(std::vector<torrent_peer*>& peers
, int session_time, torrent_state* state)
{
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
const int candidate_count = 10;
peers.reserve(candidate_count);
int erase_candidate = -1;
if (bool(m_finished) != state->is_finished)
recalculate_connect_candidates(state);
aux::external_ip const& external = state->ip;
int external_port = state->port;
if (m_round_robin >= int(m_peers.size())) m_round_robin = 0;
int max_peerlist_size = state->max_peerlist_size;
// TODO: 2 it would be nice if there was a way to iterate over these
// torrent_peer objects in the order they are allocated in the pool
// instead. It would probably be more efficient
for (int iterations = std::min(int(m_peers.size()), 300);
iterations > 0; --iterations)
{
++state->loop_counter;
if (m_round_robin >= int(m_peers.size())) m_round_robin = 0;
torrent_peer& pe = *m_peers[m_round_robin];
TORRENT_ASSERT(pe.in_use);
int current = m_round_robin;
// if the number of peers is growing large
// we need to start weeding.
if (int(m_peers.size()) >= max_peerlist_size * 0.95
&& max_peerlist_size > 0)
{
if (is_erase_candidate(pe)
&& (erase_candidate == -1
|| !compare_peer_erase(*m_peers[erase_candidate], pe)))
{
if (should_erase_immediately(pe))
{
if (erase_candidate > current) --erase_candidate;
erase_peer(m_peers.begin() + current, state);
continue;
}
else
{
erase_candidate = current;
}
}
}
++m_round_robin;
if (!is_connect_candidate(pe)) continue;
if (pe.last_connected
&& session_time - pe.last_connected <
(int(pe.failcount) + 1) * state->min_reconnect_time)
continue;
// compare peer returns true if lhs is better than rhs. In this
// case, it returns true if the current candidate is better than
// pe, which is the peer m_round_robin points to. If it is, just
// keep looking.
if (peers.size() == candidate_count
&& compare_peer(peers.back(), &pe, external, external_port, m_finished)) continue;
if (peers.size() >= candidate_count)
peers.resize(candidate_count - 1);
// insert this candidate sorted into peers
auto const i = std::lower_bound(peers.begin(), peers.end()
, &pe, std::bind(&compare_peer, _1, _2, std::cref(external), external_port, bool(m_finished)));
peers.insert(i, &pe);
}
if (erase_candidate > -1)
{
erase_peer(m_peers.begin() + erase_candidate, state);
}
}
bool peer_list::new_connection(peer_connection_interface& c, int session_time
, torrent_state* state)
{
TORRENT_ASSERT(is_single_thread());
// TORRENT_ASSERT(!c.is_outgoing());
INVARIANT_CHECK;
iterator iter;
torrent_peer* i = nullptr;
#if TORRENT_USE_I2P
std::string const i2p_dest = c.destination();
#else
std::string const i2p_dest;
#endif
bool found = false;
// this check doesn't support i2p peers
if (state->allow_multiple_connections_per_ip && i2p_dest.empty())
{
auto const& remote = c.remote();
auto const addr = remote.address();
auto const range = find_peers(addr);
iter = std::find_if(range.first, range.second, match_peer_endpoint(addr, remote.port()));
if (iter != range.second)
{
TORRENT_ASSERT((*iter)->in_use);
found = true;
}
}
else
{
#if TORRENT_USE_I2P
if (!i2p_dest.empty())
{
iter = std::lower_bound(
m_peers.begin(), m_peers.end()
, i2p_dest, peer_address_compare()
);
if (iter != m_peers.end() && (*iter)->is_i2p_addr && (*iter)->dest() == i2p_dest)
{
TORRENT_ASSERT((*iter)->in_use);
found = true;
}
}
else
#endif
{
iter = std::lower_bound(
m_peers.begin(), m_peers.end()
, c.remote().address(), peer_address_compare()
);
if (iter != m_peers.end() && (*iter)->address() == c.remote().address())
{
TORRENT_ASSERT((*iter)->in_use);
found = true;
}
}
}
// make sure the iterator we got is properly sorted relative
// to the connection's address
// TORRENT_ASSERT(m_peers.empty()
// || (iter == m_peers.end() && (*(iter-1))->address() < c.remote().address())
// || (iter != m_peers.end() && c.remote().address() < (*iter)->address())
// || (iter != m_peers.end() && iter != m_peers.begin() && (*(iter-1))->address() < c.remote().address()));
if (found)
{
i = *iter;
TORRENT_ASSERT(i->in_use);
TORRENT_ASSERT(i->connection != &c);
TORRENT_ASSERT(i->address() == c.remote().address());
#ifndef TORRENT_DISABLE_LOGGING
if (i->connection != nullptr && c.should_log(peer_log_alert::info))
{
#if TORRENT_USE_I2P
if (!i2p_dest.empty())
{
c.peer_log(peer_log_alert::info, "DUPLICATE PEER", "destination: \"%s\""
, i2p_dest.c_str());
}
else
#endif
{
c.peer_log(peer_log_alert::info, "DUPLICATE PEER", "this: \"%s\" that: \"%s\""
, print_address(c.remote().address()).c_str()
, print_address(i->address()).c_str());
}
}
#endif
if (i->banned)
{
c.disconnect(errors::peer_banned, operation_t::bittorrent);
return false;
}
if (i->connection != nullptr)
{
bool self_connection = false;
#if TORRENT_USE_I2P
if (!i2p_dest.empty())
{
self_connection = i->connection->local_i2p_endpoint() == i2p_dest;
}
else
#endif
{
self_connection = i->connection->remote() == c.local_endpoint()
|| i->connection->local_endpoint() == c.remote();
}
if (self_connection)
{
c.disconnect(errors::self_connection, operation_t::bittorrent, peer_connection_interface::failure);
TORRENT_ASSERT(i->connection->peer_info_struct() == i);
i->connection->disconnect(errors::self_connection, operation_t::bittorrent, peer_connection_interface::failure);
TORRENT_ASSERT(i->connection == nullptr);
return false;
}
TORRENT_ASSERT(i->connection != &c);
// the new connection is a local (outgoing) connection
// or the current one is already connected
if (i->connection->is_outgoing() == c.is_outgoing())
{
// if the other end connected to us both times, just drop
// the second one. Or if we made both connections.
c.disconnect(errors::duplicate_peer_id, operation_t::bittorrent);
return false;
}
#if TORRENT_USE_I2P
else if (!i2p_dest.empty())
{
// duplicate connection resolution for i2p connections is
// simple. The smaller address takes priority for making the
// outgoing connection
std::string const& other_dest = i->connection->destination();
// decide which peer connection to disconnect
// if the ports are equal, pick on at random
bool disconnect1 = c.is_outgoing() && i2p_dest > other_dest;
#ifndef TORRENT_DISABLE_LOGGING
if (c.should_log(peer_log_alert::info))
{
c.peer_log(peer_log_alert::info, "DUPLICATE_PEER_RESOLUTION"
, "our: %s other: %s disconnecting: %s"
, i2p_dest.c_str(), other_dest.c_str(), disconnect1 ? "yes" : "no");
i->connection->peer_log(peer_log_alert::info, "DUPLICATE_PEER_RESOLUTION"
, "our: %s other: %s disconnecting: %s"
, other_dest.c_str(), i2p_dest.c_str(), disconnect1 ? "no" : "yes");
}
#endif
if (disconnect1)
{
c.disconnect(errors::duplicate_peer_id, operation_t::bittorrent);
return false;
}
TORRENT_ASSERT(m_locked_peer == nullptr);
m_locked_peer = i;
i->connection->disconnect(errors::duplicate_peer_id, operation_t::bittorrent);
m_locked_peer = nullptr;
}
#endif
else
{
// at this point, we need to disconnect either
// i->connection or c. In order for both this client
// and the client on the other end to decide to
// disconnect the same one, we need a consistent rule to
// select which one.
bool const outgoing1 = c.is_outgoing();
// for this, we compare our ports and whoever has the lower port
// should be the one keeping its outgoing connection. Since
// outgoing ports are selected at random by the OS, we need to
// be careful to only look at the target end of a connection for
// the endpoint.
int const our_port = outgoing1 ? i->connection->local_endpoint().port() : c.local_endpoint().port();
int const other_port = outgoing1 ? c.remote().port() : i->connection->remote().port();
// decide which peer connection to disconnect
// if the ports are equal, pick on at random
bool disconnect1 = ((our_port < other_port) && !outgoing1)
|| ((our_port > other_port) && outgoing1)
|| ((our_port == other_port) && random(1));
disconnect1 &= !i->connection->failed();
#ifndef TORRENT_DISABLE_LOGGING
if (c.should_log(peer_log_alert::info))
{
c.peer_log(peer_log_alert::info, "DUPLICATE_PEER_RESOLUTION"
, "our: %d other: %d disconnecting: %s"
, our_port, other_port, disconnect1 ? "yes" : "no");
i->connection->peer_log(peer_log_alert::info, "DUPLICATE_PEER_RESOLUTION"
, "our: %d other: %d disconnecting: %s"
, our_port, other_port, disconnect1 ? "no" : "yes");
}
#endif
if (disconnect1)
{
c.disconnect(errors::duplicate_peer_id, operation_t::bittorrent);
return false;
}
TORRENT_ASSERT(m_locked_peer == nullptr);
m_locked_peer = i;
i->connection->disconnect(errors::duplicate_peer_id, operation_t::bittorrent);
m_locked_peer = nullptr;
}
}
if (is_connect_candidate(*i))
update_connect_candidates(-1);
}
else
{
// we don't have any info about this peer.
// add a new entry
if (state->max_peerlist_size
&& int(m_peers.size()) >= state->max_peerlist_size)
{
// this may invalidate our iterator!
erase_peers(state, force_erase);
if (int(m_peers.size()) >= state->max_peerlist_size)
{
c.disconnect(errors::too_many_connections, operation_t::bittorrent);
return false;
}
// restore it
iter = std::lower_bound(
m_peers.begin(), m_peers.end()
, c.remote().address(), peer_address_compare()
);
}
#if TORRENT_USE_I2P
if (!i2p_dest.empty())
{
i = add_i2p_peer(i2p_dest, peer_info::incoming, {}, state);
// we're about to attach the new connection to this torrent_peer
if (is_connect_candidate(*i))
update_connect_candidates(-1);
}
else
#endif
{
bool const is_v6 = lt::aux::is_v6(c.remote());
torrent_peer* p = m_peer_allocator.allocate_peer_entry(
is_v6 ? torrent_peer_allocator_interface::ipv6_peer_type
: torrent_peer_allocator_interface::ipv4_peer_type);
if (p == nullptr) return false;
if (is_v6)
p = new (p) ipv6_peer(c.remote(), false, {});
else
p = new (p) ipv4_peer(c.remote(), false, {});
iter = m_peers.insert(iter, p);
if (m_round_robin >= iter - m_peers.begin()) ++m_round_robin;
i = *iter;
i->source = static_cast<std::uint8_t>(peer_info::incoming);
}
}
TORRENT_ASSERT(i);
c.set_peer_info(i);
TORRENT_ASSERT(i->connection == nullptr);
c.add_stat(std::int64_t(i->prev_amount_download) * 1024, std::int64_t(i->prev_amount_upload) * 1024);
i->prev_amount_download = 0;
i->prev_amount_upload = 0;
i->connection = &c;
TORRENT_ASSERT(i->connection);
if (!c.fast_reconnect())
i->last_connected = std::uint16_t(session_time);
// this cannot be a connect candidate anymore, since i->connection is set
TORRENT_ASSERT(!is_connect_candidate(*i));
TORRENT_ASSERT(has_connection(&c));
return true;
}
bool peer_list::update_peer_port(int const port, torrent_peer* p
, peer_source_flags_t const src, torrent_state* state)
{
TORRENT_ASSERT(p != nullptr);
TORRENT_ASSERT(p->connection);
TORRENT_ASSERT(p->in_use);
TORRENT_ASSERT(is_single_thread());
INVARIANT_CHECK;
#if TORRENT_USE_I2P
if (p->is_i2p_addr) return true;
#endif
if (p->port == port) return true;
if (state->allow_multiple_connections_per_ip)
{
auto const addr = p->address();
auto const range = find_peers(addr);
auto const i = std::find_if(range.first, range.second
, match_peer_endpoint(addr, std::uint16_t(port)));
if (i != range.second)
{
torrent_peer& pp = **i;
TORRENT_ASSERT(pp.in_use);
if (pp.connection)
{
bool const was_conn_cand = is_connect_candidate(pp);
// if we already have an entry with this
// new endpoint, disconnect this one
pp.connectable = true;
pp.source |= static_cast<std::uint8_t>(src);
if (!was_conn_cand && is_connect_candidate(pp))
update_connect_candidates(1);
// calling disconnect() on a peer, may actually end
// up "garbage collecting" its torrent_peer entry
// as well, if it's considered useless (which this specific)
// case will, since it was an incoming peer that just disconnected
// and we allow multiple connections per IP. Because of that,
// we need to make sure we don't let it do that, locking i
TORRENT_ASSERT(m_locked_peer == nullptr);
m_locked_peer = p;
p->connection->disconnect(errors::duplicate_peer_id, operation_t::bittorrent);
m_locked_peer = nullptr;
erase_peer(p, state);
return false;
}
erase_peer(i, state);
}
}
#if TORRENT_USE_ASSERTS
else
{
std::pair<iterator, iterator> range = find_peers(p->address());
TORRENT_ASSERT(std::distance(range.first, range.second) == 1);
}
#endif
bool const was_conn_cand = is_connect_candidate(*p);
p->port = std::uint16_t(port);
p->source |= static_cast<std::uint8_t>(src);
p->connectable = true;
if (was_conn_cand != is_connect_candidate(*p))
update_connect_candidates(was_conn_cand ? -1 : 1);
return true;
}
// it's important that we don't dereference
// p here, since it is allowed to be a dangling
// pointer. see smart_ban.cpp
bool peer_list::has_peer(torrent_peer const* p) const
{
TORRENT_ASSERT(is_single_thread());
// find p in m_peers
return std::find(m_peers.begin(), m_peers.end(), p) != m_peers.end();
}
void peer_list::set_seed(torrent_peer* p, bool s)
{
TORRENT_ASSERT(is_single_thread());
if (p == nullptr) return;
TORRENT_ASSERT(p->in_use);
if (bool(p->seed) == s) return;
bool const was_conn_cand = is_connect_candidate(*p);
p->seed = s;
if (was_conn_cand && !is_connect_candidate(*p))
update_connect_candidates(-1);
if (p->web_seed) return;
if (s)
{
TORRENT_ASSERT(m_num_seeds < int(m_peers.size()));
++m_num_seeds;
}
else
{
TORRENT_ASSERT(m_num_seeds > 0);
--m_num_seeds;
}
}
// this is an internal function
bool peer_list::insert_peer(torrent_peer* p, iterator iter
, pex_flags_t const flags
, torrent_state* state)
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(p);
TORRENT_ASSERT(p->in_use);
int const max_peerlist_size = state->max_peerlist_size;
if (max_peerlist_size
&& int(m_peers.size()) >= max_peerlist_size)