73
71
using namespace libtorrent;
75
size_type collect_free_download(
76
torrent::peer_iterator start
77
, torrent::peer_iterator end)
79
size_type accumulator = 0;
80
for (torrent::peer_iterator i = start; i != end; ++i)
82
// if the peer is interested in us, it means it may
83
// want to trade it's surplus uploads for downloads itself
84
// (and we should not consider it free). If the share diff is
85
// negative, there's no free download to get from this peer.
86
size_type diff = (*i)->share_diff();
87
TORRENT_ASSERT(diff < (std::numeric_limits<size_type>::max)());
88
if ((*i)->is_peer_interested() || diff <= 0)
91
TORRENT_ASSERT(diff > 0);
92
(*i)->add_free_upload(-diff);
94
TORRENT_ASSERT(accumulator > 0);
96
TORRENT_ASSERT(accumulator >= 0);
101
// returns the amount of free upload left after
102
// it has been distributed to the peers
103
size_type distribute_free_upload(
104
torrent::peer_iterator start
105
, torrent::peer_iterator end
106
, size_type free_upload)
108
if (free_upload <= 0) return free_upload;
110
size_type total_diff = 0;
111
for (torrent::peer_iterator i = start; i != end; ++i)
113
size_type d = (*i)->share_diff();
114
TORRENT_ASSERT(d < (std::numeric_limits<size_type>::max)());
116
if (!(*i)->is_peer_interested() || (*i)->share_diff() >= 0) continue;
120
if (num_peers == 0) return free_upload;
121
size_type upload_share;
124
upload_share = (std::min)(free_upload, total_diff) / num_peers;
128
upload_share = (free_upload + total_diff) / num_peers;
130
if (upload_share < 0) return free_upload;
132
for (torrent::peer_iterator i = start; i != end; ++i)
134
peer_connection* p = *i;
135
if (!p->is_peer_interested() || p->share_diff() >= 0) continue;
136
p->add_free_upload(upload_share);
137
free_upload -= upload_share;
142
73
struct match_peer_endpoint
144
75
match_peer_endpoint(tcp::endpoint const& ep)
148
bool operator()(std::pair<const address, policy::peer> const& p) const
149
{ return p.second.addr == m_ep.address() && p.second.port == m_ep.port(); }
79
bool operator()(policy::peer const* p) const
80
{ return p->address() == m_ep.address() && p->port == m_ep.port(); }
151
82
tcp::endpoint const& m_ep;
406
381
if (m_torrent->has_picker())
407
m_torrent->picker().clear_peer(&i->second);
408
if (i->second.seed) --m_num_seeds;
409
if (is_connect_candidate(i->second, m_finished))
382
m_torrent->picker().clear_peer(*i);
383
if ((*i)->seed) --m_num_seeds;
384
if (is_connect_candidate(**i, m_finished))
411
386
TORRENT_ASSERT(m_num_connect_candidates > 0);
412
387
--m_num_connect_candidates;
414
if (m_round_robin == i) ++m_round_robin;
389
TORRENT_ASSERT(m_num_connect_candidates < m_peers.size());
390
if (m_round_robin > i - m_peers.begin()) --m_round_robin;
393
if ((*i)->is_v6_addr)
394
m_torrent->session().m_ipv6_peer_pool.destroy(
395
static_cast<ipv6_peer*>(*i));
398
m_torrent->session().m_ipv4_peer_pool.destroy(
399
static_cast<ipv4_peer*>(*i));
416
400
m_peers.erase(i);
403
bool policy::should_erase_immediately(peer const& p) const
405
return p.source == peer_info::resume_data
410
bool policy::is_erase_candidate(peer const& pe, bool finished) const
412
return pe.connection == 0
413
&& pe.last_connected != 0
415
&& !is_connect_candidate(pe, m_finished);
418
void policy::erase_peers()
422
int max_peerlist_size = m_torrent->is_paused()
423
?m_torrent->settings().max_paused_peerlist_size
424
:m_torrent->settings().max_peerlist_size;
426
if (max_peerlist_size == 0 || m_peers.empty()) return;
428
int erase_candidate = -1;
430
TORRENT_ASSERT(m_finished == m_torrent->is_finished());
432
int round_robin = rand() % m_peers.size();
434
for (int iterations = (std::min)(int(m_peers.size()), 300);
435
iterations > 0; --iterations)
437
if (m_peers.size() < max_peerlist_size * 0.95)
440
if (round_robin == m_peers.size()) round_robin = 0;
442
peer& pe = *m_peers[round_robin];
443
int current = round_robin;
446
if (is_erase_candidate(pe, m_finished)
447
&& (erase_candidate == -1
448
|| !compare_peer_erase(*m_peers[erase_candidate], pe)))
450
if (should_erase_immediately(pe))
452
if (erase_candidate > current) --erase_candidate;
453
erase_peer(m_peers.begin() + current);
457
erase_candidate = current;
465
if (erase_candidate > -1)
466
erase_peer(m_peers.begin() + erase_candidate);
419
469
void policy::ban_peer(policy::peer* p)
491
572
// if the number of peers is growing large
492
573
// we need to start weeding.
493
// don't remove peers we're connected to
494
// don't remove peers we've never even tried
495
// don't remove banned peers unless they're 2
496
// hours old. They should remain banned for
497
// at least that long
498
// don't remove peers that we still can try again
499
if (pe.connection == 0
500
&& pe.connected != min_time()
501
&& (!pe.banned || now - pe.connected > hours(2))
502
&& !is_connect_candidate(pe, m_finished)
503
&& m_peers.size() >= m_torrent->settings().max_peerlist_size * 0.9)
575
if (m_peers.size() >= max_peerlist_size * 0.95
576
&& max_peerlist_size > 0)
505
erase_peer(m_round_robin++);
578
if (is_erase_candidate(pe, m_finished)
579
&& (erase_candidate == -1
580
|| !compare_peer_erase(*m_peers[erase_candidate], pe)))
582
if (should_erase_immediately(pe))
584
if (erase_candidate > current) --erase_candidate;
585
if (candidate > current) --candidate;
586
erase_peer(m_peers.begin() + current);
590
erase_candidate = current;
511
597
if (!is_connect_candidate(pe, m_finished)) continue;
513
if (candidate != m_peers.end()
514
&& compare_peer(candidate->second, pe, external_ip)) continue;
599
// compare peer returns true if lhs is better than rhs. In this
600
// case, it returns true if the current candidate is better than
601
// pe, which is the peer m_round_robin points to. If it is, just
604
&& compare_peer(*m_peers[candidate], pe, external_ip)) continue;
516
if (now - pe.connected <
517
seconds((pe.failcount + 1) * min_reconnect_time))
606
if (pe.last_connected
607
&& session_time - pe.last_connected <
608
(int(pe.failcount) + 1) * min_reconnect_time)
520
611
candidate = current;
614
if (erase_candidate > -1)
616
if (candidate > erase_candidate) --candidate;
617
erase_peer(m_peers.begin() + erase_candidate);
523
620
#if defined TORRENT_LOGGING || defined TORRENT_VERBOSE_LOGGING
524
if (candidate != m_peers.end())
526
623
(*m_torrent->session().m_logger) << time_now_string()
527
624
<< " *** FOUND CONNECTION CANDIDATE ["
528
" ip: " << candidate->second.ip() <<
529
" d: " << cidr_distance(external_ip, candidate->second.addr) <<
625
" ip: " << m_peers[candidate]->ip() <<
626
" d: " << cidr_distance(external_ip, m_peers[candidate]->address()) <<
530
627
" external: " << external_ip <<
531
" t: " << total_seconds(time_now() - candidate->second.connected) <<
628
" t: " << (session_time - m_peers[candidate]->last_connected) <<
633
if (candidate == -1) return m_peers.end();
634
return m_peers.begin() + candidate;
539
637
void policy::pulse()
543
// ------------------------
545
// ------------------------
547
// this part will shift downloads
548
// from peers that are seeds and peers
549
// that don't want to download from us
550
// to peers that cannot upload anything
551
// to us. The shifting will make sure
552
// that the torrent's share ratio
553
// will be maintained
555
// if the share ratio is 0 (infinite)
556
// m_available_free_upload isn't used
557
// because it isn't necessary
558
if (m_torrent->ratio() != 0.f)
560
// accumulate all the free download we get
561
// and add it to the available free upload
562
m_available_free_upload
563
+= collect_free_download(
567
// distribute the free upload among the peers
568
m_available_free_upload = distribute_free_upload(
571
, m_available_free_upload);
575
bool policy::new_connection(peer_connection& c)
644
bool policy::new_connection(peer_connection& c, int session_time)
577
646
TORRENT_ASSERT(!c.is_local());
691
775
if (int(m_peers.size()) >= m_torrent->settings().max_peerlist_size)
693
c.disconnect("peer list size exceeded, refusing incoming connection");
777
c.disconnect(errors::too_many_connections);
697
peer p(c.remote(), peer::not_connectable, 0);
698
i = m_peers.insert(std::make_pair(c.remote().address(), p));
781
if (m_round_robin > iter - m_peers.begin()) ++m_round_robin;
783
bool is_v6 = c.remote().address().is_v6();
787
is_v6 ? (peer*)m_torrent->session().m_ipv6_peer_pool.malloc() :
789
(peer*)m_torrent->session().m_ipv4_peer_pool.malloc();
790
if (p == 0) return false;
793
m_torrent->session().m_ipv6_peer_pool.set_next_size(500);
796
m_torrent->session().m_ipv4_peer_pool.set_next_size(500);
800
new (p) ipv6_peer(c.remote(), false, 0);
803
new (p) ipv4_peer(c.remote(), false, 0);
805
iter = m_peers.insert(iter, p);
699
808
#ifndef TORRENT_DISABLE_GEO_IP
700
809
int as = ses.as_for_ip(c.remote().address());
701
810
#ifdef TORRENT_DEBUG
702
i->second.inet_as_num = as;
704
i->second.inet_as = ses.lookup_as(as);
706
i->second.source = peer_info::incoming;
813
i->inet_as = ses.lookup_as(as);
815
i->source = peer_info::incoming;
709
c.set_peer_info(&i->second);
710
TORRENT_ASSERT(i->second.connection == 0);
711
c.add_stat(i->second.prev_amount_download, i->second.prev_amount_upload);
712
i->second.prev_amount_download = 0;
713
i->second.prev_amount_upload = 0;
714
i->second.connection = &c;
715
TORRENT_ASSERT(i->second.connection);
820
TORRENT_ASSERT(i->connection == 0);
821
c.add_stat(i->prev_amount_download, i->prev_amount_upload);
823
// restore transfer rate limits
825
rate_limit = i->upload_rate_limit;
826
if (rate_limit) c.set_upload_limit(rate_limit);
827
rate_limit = i->download_rate_limit;
828
if (rate_limit) c.set_download_limit(rate_limit);
830
i->prev_amount_download = 0;
831
i->prev_amount_upload = 0;
833
TORRENT_ASSERT(i->connection);
716
834
if (!c.fast_reconnect())
717
i->second.connected = time_now();
835
i->last_connected = session_time;
837
// this cannot be a connect candidate anymore, since i->connection is set
838
TORRENT_ASSERT(!is_connect_candidate(*i, m_finished));
839
TORRENT_ASSERT(has_connection(&c));
951
// if the IP is blocked, don't add it
952
if (ses.m_ip_filter.access(remote.address()) & ip_filter::blocked)
954
if (ses.m_alerts.should_post<peer_blocked_alert>())
956
ses.m_alerts.post_alert(peer_blocked_alert(remote.address()));
964
int max_peerlist_size = m_torrent->is_paused()
965
?m_torrent->settings().max_paused_peerlist_size
966
:m_torrent->settings().max_peerlist_size;
813
969
if (m_torrent->settings().allow_multiple_connections_per_ip)
815
std::pair<iterator, iterator> range = m_peers.equal_range(remote.address());
816
i = std::find_if(range.first, range.second, match_peer_endpoint(remote));
817
if (i == range.second) i = m_peers.end();
971
std::pair<iterator, iterator> range = find_peers(remote.address());
972
iter = std::find_if(range.first, range.second, match_peer_endpoint(remote));
973
if (iter != range.second) found = true;
821
i = m_peers.find(remote.address());
977
iter = std::lower_bound(
978
m_peers.begin(), m_peers.end()
979
, remote.address(), peer_address_compare()
982
if (iter != m_peers.end() && (*iter)->address() == remote.address()) found = true;
824
if (i == m_peers.end())
826
// if the IP is blocked, don't add it
827
if (ses.m_ip_filter.access(remote.address()) & ip_filter::blocked)
987
if (max_peerlist_size
988
&& int(m_peers.size()) >= max_peerlist_size)
829
if (ses.m_alerts.should_post<peer_blocked_alert>())
831
ses.m_alerts.post_alert(peer_blocked_alert(remote.address()));
990
if (src == peer_info::resume_data) return 0;
993
if (int(m_peers.size()) >= max_peerlist_size)
996
// since some peers were removed, we need to
997
// update the iterator to make it valid again
998
iter = std::lower_bound(
999
m_peers.begin(), m_peers.end()
1000
, remote.address(), peer_address_compare()
836
if (int(m_peers.size()) >= m_torrent->settings().max_peerlist_size)
1004
if (m_round_robin > iter - m_peers.begin()) ++m_round_robin;
839
1006
// we don't have any info about this peer.
840
1007
// add a new entry
841
i = m_peers.insert(std::make_pair(remote.address()
842
, peer(remote, peer::connectable, src)));
1008
#if TORRENT_USE_IPV6
1009
bool is_v6 = remote.address().is_v6();
1012
#if TORRENT_USE_IPV6
1013
is_v6 ? (peer*)m_torrent->session().m_ipv6_peer_pool.malloc() :
1015
(peer*)m_torrent->session().m_ipv4_peer_pool.malloc();
1016
if (p == 0) return 0;
1017
#if TORRENT_USE_IPV6
1019
m_torrent->session().m_ipv6_peer_pool.set_next_size(500);
1022
m_torrent->session().m_ipv4_peer_pool.set_next_size(500);
1024
#if TORRENT_USE_IPV6
1026
new (p) ipv6_peer(remote, true, src);
1029
new (p) ipv4_peer(remote, true, src);
1031
iter = m_peers.insert(iter, p);
843
1034
#ifndef TORRENT_DISABLE_ENCRYPTION
844
if (flags & 0x01) i->second.pe_support = true;
1035
if (flags & 0x01) i->pe_support = true;
846
1037
if (flags & 0x02)
848
i->second.seed = true;
852
1043
#ifndef TORRENT_DISABLE_GEO_IP
853
1044
int as = ses.as_for_ip(remote.address());
854
1045
#ifdef TORRENT_DEBUG
855
i->second.inet_as_num = as;
857
i->second.inet_as = ses.lookup_as(as);
859
if (is_connect_candidate(i->second, m_finished))
1046
i->inet_as_num = as;
1048
i->inet_as = ses.lookup_as(as);
1050
if (is_connect_candidate(*i, m_finished))
860
1051
++m_num_connect_candidates;
864
bool was_conn_cand = is_connect_candidate(i->second, m_finished);
866
i->second.type = peer::connectable;
868
i->second.set_ip(remote);
869
i->second.source |= src;
1057
bool was_conn_cand = is_connect_candidate(*i, m_finished);
1059
i->connectable = true;
1061
TORRENT_ASSERT(i->address() == remote.address());
1062
i->port = remote.port();
871
1065
// if this peer has failed before, decrease the
872
1066
// counter to allow it another try, since somebody
873
1067
// else is appearantly able to connect to it
874
1068
// only trust this if it comes from the tracker
875
if (i->second.failcount > 0 && src == peer_info::tracker)
876
--i->second.failcount;
1069
if (i->failcount > 0 && src == peer_info::tracker)
878
1072
// if we're connected to this peer
879
1073
// we already know if it's a seed or not
880
1074
// so we don't have to trust this source
881
if ((flags & 0x02) && !i->second.connection)
1075
if ((flags & 0x02) && !i->connection)
883
if (!i->second.seed) ++m_num_seeds;
884
i->second.seed = true;
1077
if (!i->seed) ++m_num_seeds;
887
1081
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING
888
if (i->second.connection)
890
1084
// this means we're already connected
891
1085
// to this peer. don't connect to
895
m_torrent->debug_log("already connected to peer: " + remote.address().to_string(ec) + ":"
896
+ boost::lexical_cast<std::string>(remote.port()) + " "
897
+ boost::lexical_cast<std::string>(i->second.connection->pid()));
1090
to_hex((char*)&i->connection->pid()[0], 20, hex_pid);
1092
snprintf(msg, 200, "already connected to peer: %s %s"
1093
, print_endpoint(remote).c_str(), hex_pid);
1094
m_torrent->debug_log(msg);
899
TORRENT_ASSERT(i->second.connection->associated_torrent().lock().get() == m_torrent);
1096
TORRENT_ASSERT(i->connection->associated_torrent().lock().get() == m_torrent);
903
if (was_conn_cand != is_connect_candidate(i->second, m_torrent->is_finished()))
1100
if (was_conn_cand != is_connect_candidate(*i, m_finished))
905
1102
m_num_connect_candidates += was_conn_cand ? -1 : 1;
906
1103
if (m_num_connect_candidates < 0) m_num_connect_candidates = 0;
913
// this is called when we are unchoked by a peer
914
// i.e. a peer lets us know that we will receive
916
void policy::unchoked(peer_connection& c)
919
if (c.is_interesting())
921
request_a_block(*m_torrent, c);
922
c.send_block_requests();
926
// called when a peer is interested in us
927
void policy::interested(peer_connection& c)
931
TORRENT_ASSERT(std::find_if(m_peers.begin(), m_peers.end()
932
, boost::bind<bool>(std::equal_to<peer_connection*>(), bind(&peer::connection
933
, bind(&iterator::value_type::second, _1)), &c)) != m_peers.end());
935
aux::session_impl& ses = m_torrent->session();
937
// if the peer is choked and we have upload slots left,
938
// then unchoke it. Another condition that has to be met
939
// is that the torrent doesn't keep track of the individual
940
// up/down ratio for each peer (ratio == 0) or (if it does
941
// keep track) this particular connection isn't a leecher.
942
// If the peer was choked because it was leeching, don't
944
// The exception to this last condition is if we're a seed.
945
// In that case we don't care if people are leeching, they
946
// can't pay for their downloads anyway.
948
&& ses.num_uploads() < ses.max_uploads()
949
&& (m_torrent->ratio() == 0
950
|| c.share_diff() >= -free_upload_amount
951
|| m_torrent->is_finished()))
955
#if defined TORRENT_VERBOSE_LOGGING
956
else if (c.is_choked())
959
if (ses.num_uploads() >= ses.max_uploads())
961
reason = "the number of uploads ("
962
+ boost::lexical_cast<std::string>(ses.num_uploads())
963
+ ") is more than or equal to the limit ("
964
+ boost::lexical_cast<std::string>(ses.max_uploads())
969
reason = "the share ratio ("
970
+ boost::lexical_cast<std::string>(c.share_diff())
971
+ ") is <= free_upload_amount ("
972
+ boost::lexical_cast<std::string>(int(free_upload_amount))
973
+ ") and we are not seeding and the ratio ("
974
+ boost::lexical_cast<std::string>(m_torrent->ratio())
977
(*c.m_logger) << time_now_string() << " DID NOT UNCHOKE [ " << reason << " ]\n";
982
// called when a peer is no longer interested in us
983
void policy::not_interested(peer_connection& c)
987
if (m_torrent->ratio() != 0.f)
989
TORRENT_ASSERT(c.share_diff() < (std::numeric_limits<size_type>::max)());
990
size_type diff = c.share_diff();
991
if (diff > 0 && c.is_seed())
993
// the peer is a seed and has sent
994
// us more than we have sent it back.
995
// consider the download as free download
996
m_available_free_upload += diff;
997
c.add_free_upload(-diff);
1002
bool policy::unchoke_one_peer()
1006
iterator p = find_unchoke_candidate();
1007
if (p == m_peers.end()) return false;
1008
TORRENT_ASSERT(p->connection);
1009
TORRENT_ASSERT(!p->connection->is_disconnecting());
1011
TORRENT_ASSERT(p->connection->is_choked());
1012
p->connection->send_unchoke();
1013
p->last_optimistically_unchoked = time_now();
1018
void policy::choke_one_peer()
1022
iterator p = find_choke_candidate();
1023
if (p == m_peers.end()) return;
1024
TORRENT_ASSERT(p->connection);
1025
TORRENT_ASSERT(!p->connection->is_disconnecting());
1026
TORRENT_ASSERT(!p->connection->is_choked());
1027
p->connection->send_choke();
1031
bool policy::connect_one_peer()
1110
bool policy::connect_one_peer(int session_time)
1033
1112
INVARIANT_CHECK;
1035
1114
TORRENT_ASSERT(m_torrent->want_more_peers());
1037
iterator p = find_connect_candidate();
1038
if (p == m_peers.end()) return false;
1116
iterator i = find_connect_candidate(session_time);
1117
if (i == m_peers.end()) return false;
1040
TORRENT_ASSERT(!p->second.banned);
1041
TORRENT_ASSERT(!p->second.connection);
1042
TORRENT_ASSERT(p->second.type == peer::connectable);
1120
TORRENT_ASSERT(!p.banned);
1121
TORRENT_ASSERT(!p.connection);
1122
TORRENT_ASSERT(p.connectable);
1044
1124
TORRENT_ASSERT(m_finished == m_torrent->is_finished());
1045
TORRENT_ASSERT(is_connect_candidate(p->second, m_finished));
1046
if (!m_torrent->connect_to_peer(&p->second))
1125
TORRENT_ASSERT(is_connect_candidate(p, m_finished));
1126
if (!m_torrent->connect_to_peer(&p))
1048
++p->second.failcount;
1049
if (!is_connect_candidate(p->second, m_finished))
1128
// failcount is a 5 bit value
1129
const bool was_conn_cand = is_connect_candidate(p, m_finished);
1130
if (p.failcount < 31) ++p.failcount;
1131
if (was_conn_cand && !is_connect_candidate(p, m_finished))
1050
1132
--m_num_connect_candidates;
1053
TORRENT_ASSERT(p->second.connection);
1054
TORRENT_ASSERT(!is_connect_candidate(p->second, m_finished));
1055
--m_num_connect_candidates;
1135
TORRENT_ASSERT(p.connection);
1136
TORRENT_ASSERT(!is_connect_candidate(p, m_finished));
1059
1140
// this is called whenever a peer connection is closed
1060
void policy::connection_closed(const peer_connection& c)
1141
void policy::connection_closed(const peer_connection& c, int session_time)
1062
1143
INVARIANT_CHECK;
1081
1168
// update the timestamp, and it will remain
1082
1169
// the time when we initiated the connection.
1083
1170
if (!c.fast_reconnect())
1084
p->connected = time_now();
1171
p->last_connected = session_time;
1086
1173
if (c.failed())
1089
// p->connected = time_now();
1175
// failcount is a 5 bit value
1176
if (p->failcount < 31) ++p->failcount;
1092
1179
if (is_connect_candidate(*p, m_finished))
1093
1180
++m_num_connect_candidates;
1095
// if the share ratio is 0 (infinite), the
1096
// m_available_free_upload isn't used,
1097
// because it isn't necessary.
1098
if (m_torrent->ratio() != 0.f)
1100
TORRENT_ASSERT(c.associated_torrent().lock().get() == m_torrent);
1101
TORRENT_ASSERT(c.share_diff() < (std::numeric_limits<size_type>::max)());
1102
m_available_free_upload += c.share_diff();
1104
TORRENT_ASSERT(p->prev_amount_upload == 0);
1105
TORRENT_ASSERT(p->prev_amount_download == 0);
1106
p->prev_amount_download += c.statistics().total_payload_download();
1107
p->prev_amount_upload += c.statistics().total_payload_upload();
1182
// if we're already a seed, it's not as important
1183
// to keep all the possibly stale peers
1184
// if we're not a seed, but we have too many peers
1185
// start weeding the ones we only know from resume
1187
// at this point it may be tempting to erase peers
1188
// from the peer list, but keep in mind that we might
1189
// have gotten to this point through new_connection, just
1190
// disconnecting an old peer, relying on this policy::peer
1191
// to still exist when we get back there, to assign the new
1192
// peer connection pointer to it. The peer list must
1110
1196
void policy::peer_is_interesting(peer_connection& c)
1112
1198
INVARIANT_CHECK;
1200
// no peer should be interesting if we're finished
1201
TORRENT_ASSERT(!m_torrent->is_finished());
1114
1203
if (c.in_handshake()) return;
1115
1204
c.send_interested();
1116
1205
if (c.has_peer_choked()