-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolicy.cpp
More file actions
executable file
·1419 lines (1216 loc) · 37.5 KB
/
policy.cpp
File metadata and controls
executable file
·1419 lines (1216 loc) · 37.5 KB
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, Arvid Norberg
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 <iostream>
#include "libtorrent/peer_connection.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/web_peer_connection.hpp"
#include "libtorrent/policy.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/aux_/session_impl.hpp"
namespace libtorrent
{
class peer_connection;
}
using namespace boost::posix_time;
using boost::bind;
namespace
{
using namespace libtorrent;
// the case where ignore_peer is motivated is if two peers
// have only one piece that we don't have, and it's the
// same piece for both peers. Then they might get into an
// infinite loop, fighting to request the same blocks.
void request_a_block(
torrent& t
, peer_connection& c
, std::vector<peer_connection*> ignore = std::vector<peer_connection*>())
{
int num_requests = c.desired_queue_size()
- (int)c.download_queue().size()
- (int)c.request_queue().size();
// if our request queue is already full, we
// don't have to make any new requests yet
if (num_requests <= 0) return;
piece_picker& p = t.picker();
std::vector<piece_block> interesting_pieces;
interesting_pieces.reserve(100);
// picks the interesting pieces from this peer
// the integer is the number of pieces that
// should be guaranteed to be available for download
// (if num_requests is too big, too many pieces are
// picked and cpu-time is wasted)
// the last argument is if we should prefer whole pieces
// for this peer. If we're downloading one piece in 20 seconds
// then use this mode.
bool prefer_whole_pieces = c.statistics().download_payload_rate()
* t.settings().whole_pieces_threshold
> t.torrent_file().piece_length();
// if we prefer whole pieces, the piece picker will pick at least
// the number of blocks we want, but it will try to make the picked
// blocks be from whole pieces, possibly by returning more blocks
// than we requested.
#ifndef NDEBUG
assert(c.remote() == c.get_socket()->remote_endpoint());
#endif
p.pick_pieces(c.get_bitfield(), interesting_pieces
, num_requests, prefer_whole_pieces, c.remote());
// this vector is filled with the interesting pieces
// that some other peer is currently downloading
// we should then compare this peer's download speed
// with the other's, to see if we should abort another
// peer_connection in favour of this one
std::vector<piece_block> busy_pieces;
busy_pieces.reserve(10);
for (std::vector<piece_block>::iterator i = interesting_pieces.begin();
i != interesting_pieces.end(); ++i)
{
if (p.is_downloading(*i))
{
busy_pieces.push_back(*i);
continue;
}
// ok, we found a piece that's not being downloaded
// by somebody else. request it from this peer
// and return
c.add_request(*i);
num_requests--;
}
c.send_block_requests();
// in this case, we could not find any blocks
// that was free. If we couldn't find any busy
// blocks as well, we cannot download anything
// more from this peer.
if (busy_pieces.empty()) return;
// first look for blocks that are just queued
// and not actually sent to us yet
// (then we can cancel those and request them
// from this peer instead)
while (num_requests > 0)
{
peer_connection* peer = 0;
const int initial_queue_size = (int)c.download_queue().size()
+ (int)c.request_queue().size();
// This peer's weight will be the minimum, to prevent
// cancelling requests from a faster peer.
float min_weight = initial_queue_size == 0
? std::numeric_limits<float>::max()
: c.statistics().download_payload_rate() / initial_queue_size;
// find the peer with the lowest download
// speed that also has a piece that this
// peer could send us
for (torrent::peer_iterator i = t.begin();
i != t.end(); ++i)
{
// don't try to take over blocks from ourself
if (i->second == &c)
continue;
// ignore all peers in the ignore list
if (std::find(ignore.begin(), ignore.end(), i->second) != ignore.end())
continue;
const std::deque<piece_block>& download_queue = i->second->download_queue();
const std::deque<piece_block>& request_queue = i->second->request_queue();
const int queue_size = (int)i->second->download_queue().size()
+ (int)i->second->request_queue().size();
const float weight = queue_size == 0
? std::numeric_limits<float>::max()
: i->second->statistics().download_payload_rate() / queue_size;
// if the peer's (i) weight is less than the lowest we've found so
// far (weight == priority) and it has blocks in its request-
// or download queue that we could request from this peer (c),
// replace the currently lowest ranking peer.
if (weight < min_weight
&& (std::find_first_of(
busy_pieces.begin()
, busy_pieces.end()
, request_queue.begin()
, request_queue.end()) != busy_pieces.end()
|| std::find_first_of(
busy_pieces.begin()
, busy_pieces.end()
, download_queue.begin()
, download_queue.end()) != busy_pieces.end()))
{
peer = i->second;
min_weight = weight;
}
}
if (peer == 0)
{
// we probably couldn't request the block because
// we are ignoring some peers
break;
}
// find a suitable block to take over from this peer
std::deque<piece_block>::const_reverse_iterator common_block =
std::find_first_of(
peer->request_queue().rbegin()
, peer->request_queue().rend()
, busy_pieces.begin()
, busy_pieces.end());
if (common_block == peer->request_queue().rend())
{
common_block = std::find_first_of(
peer->download_queue().rbegin()
, peer->download_queue().rend()
, busy_pieces.begin()
, busy_pieces.end());
assert(common_block != peer->download_queue().rend());
}
piece_block block = *common_block;
peer->cancel_request(block);
c.add_request(block);
// the one we interrupted may need to request a new piece.
// make sure it doesn't take over a block from the peer
// that just took over its block
ignore.push_back(&c);
request_a_block(t, *peer, ignore);
num_requests--;
const int queue_size = (int)c.download_queue().size()
+ (int)c.request_queue().size();
const float weight = queue_size == 0
? std::numeric_limits<float>::max()
: c.statistics().download_payload_rate() / queue_size;
// this peer doesn't have a faster connection than the
// slowest peer. Don't take over any blocks
if (weight <= min_weight) break;
}
c.send_block_requests();
}
size_type collect_free_download(
torrent::peer_iterator start
, torrent::peer_iterator end)
{
size_type accumulator = 0;
for (torrent::peer_iterator i = start; i != end; ++i)
{
// if the peer is interested in us, it means it may
// want to trade it's surplus uploads for downloads itself
// (and we should not consider it free). If the share diff is
// negative, there's no free download to get from this peer.
size_type diff = i->second->share_diff();
assert(diff < std::numeric_limits<size_type>::max());
if (i->second->is_peer_interested() || diff <= 0)
continue;
assert(diff > 0);
i->second->add_free_upload(-diff);
accumulator += diff;
assert(accumulator > 0);
}
assert(accumulator >= 0);
return accumulator;
}
// returns the amount of free upload left after
// it has been distributed to the peers
size_type distribute_free_upload(
torrent::peer_iterator start
, torrent::peer_iterator end
, size_type free_upload)
{
if (free_upload <= 0) return free_upload;
int num_peers = 0;
size_type total_diff = 0;
for (torrent::peer_iterator i = start; i != end; ++i)
{
size_type d = i->second->share_diff();
assert(d < std::numeric_limits<size_type>::max());
total_diff += d;
if (!i->second->is_peer_interested() || i->second->share_diff() >= 0) continue;
++num_peers;
}
if (num_peers == 0) return free_upload;
size_type upload_share;
if (total_diff >= 0)
{
upload_share = std::min(free_upload, total_diff) / num_peers;
}
else
{
upload_share = (free_upload + total_diff) / num_peers;
}
if (upload_share < 0) return free_upload;
for (torrent::peer_iterator i = start; i != end; ++i)
{
peer_connection* p = i->second;
if (!p->is_peer_interested() || p->share_diff() >= 0) continue;
p->add_free_upload(upload_share);
free_upload -= upload_share;
}
return free_upload;
}
struct match_peer_ip
{
match_peer_ip(const tcp::endpoint& ip)
: m_ip(ip)
{}
bool operator()(const policy::peer& p) const
{ return p.ip.address() == m_ip.address(); }
tcp::endpoint m_ip;
};
struct match_peer_connection
{
match_peer_connection(const peer_connection& c)
: m_conn(c)
{}
bool operator()(const policy::peer& p) const
{ return p.connection == &m_conn; }
const peer_connection& m_conn;
};
}
namespace libtorrent
{
policy::policy(torrent* t)
: m_torrent(t)
// , m_max_uploads(std::numeric_limits<int>::max())
// , m_max_connections(std::numeric_limits<int>::max())
, m_num_unchoked(0)
, m_available_free_upload(0)
, m_last_optimistic_disconnect(boost::gregorian::date(1970,boost::gregorian::Jan,1))
{ assert(t); }
// finds the peer that has the worst download rate
// and returns it. May return 0 if all peers are
// choked.
policy::peer* policy::find_choke_candidate()
{
INVARIANT_CHECK;
peer* worst_peer = 0;
size_type min_weight = std::numeric_limits<int>::min();
#ifndef NDEBUG
int unchoked_counter = m_num_unchoked;
#endif
// TODO: make this selection better
for (std::vector<peer>::iterator i = m_peers.begin();
i != m_peers.end(); ++i)
{
peer_connection* c = i->connection;
if (c == 0) continue;
if (c->is_choked()) continue;
#ifndef NDEBUG
unchoked_counter--;
#endif
if (c->is_disconnecting()) continue;
// if the peer isn't interested, just choke it
if (!c->is_peer_interested())
return &(*i);
size_type diff = i->total_download()
- i->total_upload();
size_type weight = static_cast<int>(c->statistics().download_rate() * 10.f)
+ diff
+ ((c->is_interesting() && c->has_peer_choked())?-10:10)*1024;
if (weight >= min_weight && worst_peer) continue;
min_weight = weight;
worst_peer = &(*i);
continue;
}
assert(unchoked_counter == 0);
return worst_peer;
}
policy::peer* policy::find_unchoke_candidate()
{
INVARIANT_CHECK;
// if all of our peers are unchoked, there's
// no left to unchoke
if (m_num_unchoked == m_torrent->num_peers())
return 0;
using namespace boost::posix_time;
using namespace boost::gregorian;
peer* unchoke_peer = 0;
ptime min_time(date(9999,Jan,1));
float max_down_speed = 0.f;
// TODO: make this selection better
for (std::vector<peer>::iterator i = m_peers.begin();
i != m_peers.end(); ++i)
{
peer_connection* c = i->connection;
if (c == 0) continue;
if (c->is_disconnecting()) continue;
if (!c->is_choked()) continue;
if (!c->is_peer_interested()) continue;
if (c->share_diff() < -free_upload_amount
&& m_torrent->ratio() != 0) continue;
if (c->statistics().download_rate() < max_down_speed) continue;
// if (i->last_optimistically_unchoked > min_time) continue;
min_time = i->last_optimistically_unchoked;
max_down_speed = c->statistics().download_rate();
unchoke_peer = &(*i);
}
return unchoke_peer;
}
policy::peer* policy::find_disconnect_candidate()
{
peer *disconnect_peer = 0;
double slowest_transfer_rate = std::numeric_limits<double>::max();
boost::posix_time::ptime local_time
= second_clock::universal_time();
for (std::vector<peer>::iterator i = m_peers.begin();
i != m_peers.end(); ++i)
{
peer_connection* c = i->connection;
if(c == 0)
continue;
if(c->is_disconnecting())
continue;
double transferred_amount
= (double)c->statistics().total_payload_download();
boost::posix_time::time_duration connected_time
= local_time - i->connected;
double connected_time_in_seconds
= connected_time.seconds()
+ connected_time.minutes()*60.0
+ connected_time.hours()*60.0*60.0;
double transfer_rate
= transferred_amount / (connected_time_in_seconds+1);
if (transfer_rate <= slowest_transfer_rate)
{
slowest_transfer_rate = transfer_rate;
disconnect_peer = &(*i);
}
}
return disconnect_peer;
}
policy::peer *policy::find_connect_candidate()
{
boost::posix_time::ptime local_time=second_clock::universal_time();
boost::posix_time::ptime ptime(local_time);
policy::peer* candidate =0;
for (std::vector<peer>::iterator i = m_peers.begin();
i != m_peers.end(); ++i)
{
if(i->connection) continue;
if(i->banned) continue;
if(i->type == peer::not_connectable) continue;
assert(i->connected <= local_time);
boost::posix_time::ptime next_connect = i->connected;
if (next_connect <= ptime)
{
ptime = next_connect;
candidate = &(*i);
}
}
assert(ptime <= local_time);
return candidate;
}
policy::peer* policy::find_seed_choke_candidate()
{
INVARIANT_CHECK;
assert(m_num_unchoked > 0);
// first choice candidate.
// it is a candidate we owe nothing to and which has been unchoked
// the longest.
using namespace boost::posix_time;
using namespace boost::gregorian;
peer* candidate = 0;
// not valid when candidate == 0
ptime last_unchoke = ptime(date(1970, Jan, 1));
// second choice candidate.
// if there is no first choice candidate, this candidate will be chosen.
// it is the candidate that we owe the least to.
peer* second_candidate = 0;
size_type lowest_share_diff = 0; // not valid when secondCandidate==0
for (std::vector<peer>::iterator i = m_peers.begin();
i != m_peers.end(); ++i)
{
peer_connection* c = i->connection;
// ignore peers that are choked or
// whose connection is closed
if (c == 0) continue;
if (c->is_choked()) continue;
if (c->is_disconnecting()) continue;
size_type share_diff = c->share_diff();
// select as second candidate the one that we owe the least
// to
if (!second_candidate || share_diff <= lowest_share_diff)
{
lowest_share_diff = share_diff;
second_candidate = &(*i);
}
// select as first candidate the one that we don't owe anything to
// and has been waiting for an unchoke the longest
if (share_diff > 0) continue;
if (!candidate || last_unchoke > i->last_optimistically_unchoked)
{
last_unchoke = i->last_optimistically_unchoked;
candidate = &(*i);
}
}
if (candidate) return candidate;
if (second_candidate) return second_candidate;
assert(false);
return 0;
}
policy::peer* policy::find_seed_unchoke_candidate()
{
INVARIANT_CHECK;
peer* candidate = 0;
boost::posix_time::ptime last_unchoke
= second_clock::universal_time();
for (std::vector<peer>::iterator i = m_peers.begin();
i != m_peers.end(); ++i)
{
peer_connection* c = i->connection;
if (c == 0) continue;
if (!c->is_choked()) continue;
if (!c->is_peer_interested()) continue;
if (c->is_disconnecting()) continue;
if (last_unchoke < i->last_optimistically_unchoked) continue;
last_unchoke = i->last_optimistically_unchoked;
candidate = &(*i);
}
return candidate;
}
bool policy::seed_unchoke_one_peer()
{
INVARIANT_CHECK;
peer* p = find_seed_unchoke_candidate();
if (p != 0)
{
assert(p->connection->is_choked());
p->connection->send_unchoke();
p->last_optimistically_unchoked
= second_clock::universal_time();
++m_num_unchoked;
}
return p != 0;
}
void policy::seed_choke_one_peer()
{
INVARIANT_CHECK;
peer* p = find_seed_choke_candidate();
if (p != 0)
{
assert(!p->connection->is_choked());
p->connection->send_choke();
--m_num_unchoked;
}
}
void policy::pulse()
{
INVARIANT_CHECK;
if (m_torrent->is_paused()) return;
using namespace boost::posix_time;
// TODO: we must also remove peers that
// we failed to connect to from this list
// to avoid being part of a DDOS-attack
// remove old disconnected peers from the list
m_peers.erase(
std::remove_if(m_peers.begin()
, m_peers.end()
, old_disconnected_peer())
, m_peers.end());
// -------------------------------------
// maintain the number of connections
// -------------------------------------
// count the number of connected peers except for peers
// that are currently in the process of disconnecting
int num_connected_peers = 0;
for (std::vector<peer>::iterator i = m_peers.begin();
i != m_peers.end(); ++i)
{
if (i->connection && !i->connection->is_disconnecting())
++num_connected_peers;
}
if (m_torrent->m_connections_quota.given != std::numeric_limits<int>::max())
{
int max_connections = m_torrent->m_connections_quota.given;
if (num_connected_peers >= max_connections)
{
// every minute, disconnect the worst peer in hope of finding a better peer
boost::posix_time::ptime local_time = second_clock::universal_time();
if (m_last_optimistic_disconnect + boost::posix_time::seconds(120) <= local_time)
{
m_last_optimistic_disconnect = local_time;
--max_connections; // this will have the effect of disconnecting the worst peer
}
}
else
{
// don't do a disconnect earlier than 1 minute after some peer was connected
m_last_optimistic_disconnect = second_clock::universal_time();
}
while (num_connected_peers > max_connections)
{
bool ret = disconnect_one_peer();
(void)ret;
assert(ret);
--num_connected_peers;
}
}
while (m_torrent->num_peers() < m_torrent->m_connections_quota.given)
{
if (!connect_one_peer())
break;
}
// ------------------------
// upload shift
// ------------------------
// this part will shift downloads
// from peers that are seeds and peers
// that don't want to download from us
// to peers that cannot upload anything
// to us. The shifting will make sure
// that the torrent's share ratio
// will be maintained
// if the share ratio is 0 (infinite)
// m_available_free_upload isn't used
// because it isn't necessary
if (m_torrent->ratio() != 0.f)
{
// accumulate all the free download we get
// and add it to the available free upload
m_available_free_upload
+= collect_free_download(
m_torrent->begin()
, m_torrent->end());
// distribute the free upload among the peers
m_available_free_upload = distribute_free_upload(
m_torrent->begin()
, m_torrent->end()
, m_available_free_upload);
}
// ------------------------
// seed choking policy
// ------------------------
if (m_torrent->is_seed())
{
if (m_num_unchoked > m_torrent->m_uploads_quota.given)
{
do
{
peer* p = find_seed_choke_candidate();
--m_num_unchoked;
assert(p != 0);
if (p == 0) break;
assert(!p->connection->is_choked());
p->connection->send_choke();
} while (m_num_unchoked > m_torrent->m_uploads_quota.given);
}
else if (m_num_unchoked > 0)
{
// optimistic unchoke. trade the 'worst'
// unchoked peer with one of the choked
// TODO: This rotation should happen
// far less frequent than this!
assert(m_num_unchoked <= m_torrent->num_peers());
peer* p = find_seed_unchoke_candidate();
if (p)
{
assert(p->connection->is_choked());
seed_choke_one_peer();
p->connection->send_unchoke();
++m_num_unchoked;
}
}
// make sure we have enough
// unchoked peers
while (m_num_unchoked < m_torrent->m_uploads_quota.given)
{
if (!seed_unchoke_one_peer()) break;
}
#ifndef NDEBUG
check_invariant();
#endif
}
// ----------------------------
// downloading choking policy
// ----------------------------
else
{
if (m_torrent->ratio() != 0)
{
// choke peers that have leeched too much without giving anything back
for (std::vector<peer>::iterator i = m_peers.begin();
i != m_peers.end(); ++i)
{
peer_connection* c = i->connection;
if (c == 0) continue;
size_type diff = i->connection->share_diff();
if (diff < -free_upload_amount
&& !c->is_choked())
{
// if we have uploaded more than a piece for free, choke peer and
// wait until we catch up with our download.
c->send_choke();
--m_num_unchoked;
}
}
}
if (m_torrent->m_uploads_quota.given < m_torrent->num_peers())
{
assert(m_torrent->m_uploads_quota.given >= 0);
// make sure we don't have too many
// unchoked peers
if (m_num_unchoked > m_torrent->m_uploads_quota.given)
{
do
{
peer* p = find_choke_candidate();
if (!p) break;
assert(p);
assert(!p->connection->is_choked());
p->connection->send_choke();
--m_num_unchoked;
} while (m_num_unchoked > m_torrent->m_uploads_quota.given);
}
else
{
// optimistic unchoke. trade the 'worst'
// unchoked peer with one of the choked
// TODO: This rotation should happen
// far less frequent than this!
assert(m_num_unchoked <= m_torrent->num_peers());
peer* p = find_unchoke_candidate();
if (p)
{
assert(p->connection->is_choked());
choke_one_peer();
p->connection->send_unchoke();
++m_num_unchoked;
}
}
}
// make sure we have enough
// unchoked peers
while (m_num_unchoked < m_torrent->m_uploads_quota.given
&& unchoke_one_peer());
}
}
void policy::ban_peer(const peer_connection& c)
{
INVARIANT_CHECK;
std::vector<peer>::iterator i = std::find_if(
m_peers.begin()
, m_peers.end()
, match_peer_connection(c));
if (i == m_peers.end())
{
// this is probably an http seed
if (web_peer_connection const* p = dynamic_cast<web_peer_connection const*>(&c))
{
m_torrent->remove_url_seed(p->url());
}
return;
}
i->type = peer::not_connectable;
i->ip.port(0);
i->banned = true;
}
void policy::new_connection(peer_connection& c)
{
assert(!c.is_local());
/*
#ifndef NDEBUG
// avoid the invariant check to fail
peer p(tcp::endpoint("0.0.0.0", 0), peer::not_connectable);
p.connection = &c;
m_peers.push_back(p);
#endif
*/
INVARIANT_CHECK;
/*
#ifndef NDEBUG
// avoid the invariant check to fail
m_peers.erase(m_peers.end() - 1);
#endif
*/
// if the connection comes from the tracker,
// it's probably just a NAT-check. Ignore the
// num connections constraint then.
// TODO: only allow _one_ connection to use this
// override at a time
#ifndef NDEBUG
assert(c.remote() == c.get_socket()->remote_endpoint());
#endif
if (m_torrent->num_peers() >= m_torrent->m_connections_quota.given
&& c.remote().address() != m_torrent->current_tracker().address())
{
throw protocol_error("too many connections, refusing incoming connection"); // cause a disconnect
}
#if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING)
if (c.remote().address() == m_torrent->current_tracker().address())
{
m_torrent->debug_log("overriding connection limit for tracker NAT-check");
}
#endif
std::vector<peer>::iterator i = std::find_if(
m_peers.begin()
, m_peers.end()
, match_peer_ip(c.remote()));
if (i != m_peers.end())
{
if (i->banned)
throw protocol_error("ip address banned, closing");
if (i->connection != 0)
{
// the new connection is a local (outgoing) connection
// or the current one is already connected
if (!i->connection->is_connecting() || c.is_local())
{
throw protocol_error("duplicate connection, closing");
}
else
{
#if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING)
m_torrent->debug_log("duplicate connection. existing connection"
" is connecting and this connection is incoming. closing existing "
"connection in favour of this one");
#endif
i->connection->disconnect();
i->connection = 0;
}
}
}
else
{
using namespace boost::posix_time;
using namespace boost::gregorian;
// we don't have ny info about this peer.
// add a new entry
#ifndef NDEBUG
assert(c.remote() == c.get_socket()->remote_endpoint());
#endif
peer p(c.remote(), peer::not_connectable);
m_peers.push_back(p);
i = m_peers.end()-1;
}
assert(i->connection == 0);
c.add_stat(i->prev_amount_download, i->prev_amount_upload);
i->prev_amount_download = 0;
i->prev_amount_upload = 0;
i->connection = &c;
assert(i->connection);
i->connected = second_clock::universal_time();
m_last_optimistic_disconnect = second_clock::universal_time();
}
void policy::peer_from_tracker(const tcp::endpoint& remote, const peer_id& pid)
{
INVARIANT_CHECK;
// just ignore the obviously invalid entries from the tracker
if(remote.address() == address() || remote.port() == 0)
return;
try
{
std::vector<peer>::iterator i = std::find_if(
m_peers.begin()
, m_peers.end()
, match_peer_ip(remote));
bool just_added = false;
if (i == m_peers.end())
{
using namespace boost::posix_time;
using namespace boost::gregorian;
// we don't have any info about this peer.
// add a new entry
peer p(remote, peer::connectable);
m_peers.push_back(p);
// the iterator is invalid
// because of the push_back()
i = m_peers.end() - 1;
just_added = true;
}
else
{
i->type = peer::connectable;
// in case we got the ip from a remote connection, port is
// not known, so save it. Client may also have changed port