-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
peer-mgr.cc
2505 lines (2056 loc) · 68.3 KB
/
peer-mgr.cc
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
// This file Copyright © 2007-2023 Mnemosyne LLC.
// It may be used under GPLv2 (SPDX: GPL-2.0-only), GPLv3 (SPDX: GPL-3.0-only),
// or any future license endorsed by Mnemosyne LLC.
// License text can be found in the licenses/ folder.
#include <algorithm>
#include <array>
#include <cerrno> /* error codes ERANGE, ... */
#include <chrono>
#include <climits> /* INT_MAX */
#include <cmath>
#include <cstdint>
#include <ctime> // time_t
#include <map>
#include <iterator> // std::back_inserter
#include <memory>
#include <optional>
#include <tuple> // std::tie
#include <utility>
#include <vector>
#include <fmt/core.h>
#define LIBTRANSMISSION_PEER_MODULE
#include "libtransmission/transmission.h"
#include "libtransmission/announcer.h"
#include "libtransmission/bandwidth.h"
#include "libtransmission/blocklist.h"
#include "libtransmission/cache.h"
#include "libtransmission/clients.h"
#include "libtransmission/completion.h"
#include "libtransmission/crypto-utils.h"
#include "libtransmission/handshake.h"
#include "libtransmission/log.h"
#include "libtransmission/net.h"
#include "libtransmission/peer-io.h"
#include "libtransmission/peer-mgr-active-requests.h"
#include "libtransmission/peer-mgr-wishlist.h"
#include "libtransmission/peer-mgr.h"
#include "libtransmission/peer-msgs.h"
#include "libtransmission/session.h"
#include "libtransmission/timer.h"
#include "libtransmission/torrent.h"
#include "libtransmission/torrent-magnet.h"
#include "libtransmission/tr-assert.h"
#include "libtransmission/tr-utp.h"
#include "libtransmission/utils.h"
#include "libtransmission/webseed.h"
using namespace std::literals;
static auto constexpr CancelHistorySec = int{ 60 };
// ---
class HandshakeMediator final : public tr_handshake::Mediator
{
private:
[[nodiscard]] static std::optional<TorrentInfo> torrent(tr_torrent* tor)
{
if (tor == nullptr)
{
return {};
}
auto info = TorrentInfo{};
info.info_hash = tor->info_hash();
info.client_peer_id = tor->peer_id();
info.id = tor->id();
info.is_done = tor->is_done();
return info;
}
public:
explicit HandshakeMediator(tr_session& session) noexcept
: session_{ session }
{
}
[[nodiscard]] std::optional<TorrentInfo> torrent(tr_sha1_digest_t const& info_hash) const override
{
return torrent(session_.torrents().get(info_hash));
}
[[nodiscard]] std::optional<TorrentInfo> torrent_from_obfuscated(tr_sha1_digest_t const& info_hash) const override
{
return torrent(tr_torrentFindFromObfuscatedHash(&session_, info_hash));
}
[[nodiscard]] bool allows_dht() const override
{
return session_.allowsDHT();
}
[[nodiscard]] bool allows_tcp() const override
{
return session_.allowsTCP();
}
void set_utp_failed(tr_sha1_digest_t const& info_hash, std::pair<tr_address, tr_port> const& socket_address) override
{
if (auto* const tor = session_.torrents().get(info_hash); tor != nullptr)
{
tr_peerMgrSetUtpFailed(tor, socket_address, true);
}
}
[[nodiscard]] bool is_peer_known_seed(tr_torrent_id_t tor_id, std::pair<tr_address, tr_port> const& socket_address)
const override;
[[nodiscard]] libtransmission::TimerMaker& timer_maker() override
{
return session_.timerMaker();
}
[[nodiscard]] size_t pad(void* setme, size_t maxlen) const override
{
auto const len = tr_rand_int(maxlen);
tr_rand_buffer(setme, len);
return len;
}
private:
tr_session& session_;
};
/**
* Peer information that should be kept even before we've connected and
* after we've disconnected. These are kept in a pool of peer_atoms to decide
* which ones would make good candidates for connecting to, and to watch out
* for banned peers.
*
* @see tr_peer
* @see tr_peerMsgs
*/
struct peer_atom
{
peer_atom(std::pair<tr_address, tr_port> socket_address_in, uint8_t flags_in, uint8_t from)
: socket_address{ std::move(socket_address_in) }
, fromFirst{ from }
, fromBest{ from }
, flags{ flags_in }
{
++n_atoms;
}
peer_atom(peer_atom&&) = delete;
peer_atom(peer_atom const&) = delete;
peer_atom& operator=(peer_atom&&) = delete;
peer_atom& operator=(peer_atom const&) = delete;
~peer_atom()
{
[[maybe_unused]] auto const n_prev = n_atoms--;
TR_ASSERT(n_prev > 0U);
}
[[nodiscard]] static auto atom_count() noexcept
{
return n_atoms.load();
}
[[nodiscard]] constexpr auto isSeed() const noexcept
{
return (flags & ADDED_F_SEED_FLAG) != 0;
}
[[nodiscard]] constexpr auto const& addr() const noexcept
{
return socket_address.first;
}
[[nodiscard]] constexpr auto& port() noexcept
{
return socket_address.second;
}
[[nodiscard]] constexpr auto const& port() const noexcept
{
return socket_address.second;
}
[[nodiscard]] auto display_name() const
{
return addr().display_name(port());
}
[[nodiscard]] bool isBlocklisted(tr_session const* session) const
{
if (blocklisted_)
{
return *blocklisted_;
}
auto const value = session->addressIsBlocked(addr());
blocklisted_ = value;
return value;
}
[[nodiscard]] constexpr auto is_unreachable() const noexcept
{
return is_unreachable_;
}
constexpr void set_unreachable() noexcept
{
is_unreachable_ = true;
}
constexpr void set_reachable() noexcept
{
is_unreachable_ = false;
}
[[nodiscard]] constexpr int getReconnectIntervalSecs(time_t const now) const noexcept
{
auto sec = int{};
auto const unreachable = is_unreachable();
/* if we were recently connected to this peer and transferring piece
* data, try to reconnect to them sooner rather that later -- we don't
* want network troubles to get in the way of a good peer. */
if (!unreachable && now - this->piece_data_time <= MinimumReconnectIntervalSecs * 2)
{
sec = MinimumReconnectIntervalSecs;
}
/* otherwise, the interval depends on how many times we've tried
* and failed to connect to the peer */
else
{
auto step = this->num_fails;
/* penalize peers that were unreachable the last time we tried */
if (unreachable)
{
step += 2;
}
switch (step)
{
case 0:
sec = 0;
break;
case 1:
sec = 10;
break;
case 2:
sec = 60 * 2;
break;
case 3:
sec = 60 * 15;
break;
case 4:
sec = 60 * 30;
break;
case 5:
sec = 60 * 60;
break;
default:
sec = 60 * 120;
break;
}
}
return sec;
}
void setBlocklistedDirty()
{
blocklisted_.reset();
}
[[nodiscard]] constexpr auto is_banned() const noexcept
{
return is_banned_;
}
constexpr void ban() noexcept
{
is_banned_ = true;
}
std::pair<tr_address, tr_port> socket_address;
uint16_t num_fails = {};
time_t time = {}; /* when the peer's connection status last changed */
time_t piece_data_time = {};
time_t lastConnectionAttemptAt = {};
time_t lastConnectionAt = {};
uint8_t const fromFirst; /* where the peer was first found */
uint8_t fromBest; /* the "best" value of where the peer has been found */
uint8_t flags = {}; /* these match the added_f flags */
uint8_t flags2 = {}; /* flags that aren't defined in added_f */
bool utp_failed = false; /* We recently failed to connect over µTP */
bool is_connected = false;
private:
// the minimum we'll wait before attempting to reconnect to a peer
static auto constexpr MinimumReconnectIntervalSecs = int{ 5 };
static auto inline n_atoms = std::atomic<size_t>{};
mutable std::optional<bool> blocklisted_;
bool is_banned_ = false;
bool is_unreachable_ = false; // we tried to connect & failed
};
using Handshakes = std::map<std::pair<tr_address, tr_port>, tr_handshake>;
#define tr_logAddDebugSwarm(swarm, msg) tr_logAddDebugTor((swarm)->tor, msg)
#define tr_logAddTraceSwarm(swarm, msg) tr_logAddTraceTor((swarm)->tor, msg)
/** @brief Opaque, per-torrent data structure for peer connection information */
class tr_swarm
{
public:
[[nodiscard]] auto unique_lock() const
{
return tor->unique_lock();
}
tr_swarm(tr_peerMgr* manager_in, tr_torrent* tor_in) noexcept
: manager{ manager_in }
, tor{ tor_in }
, tags_{ {
tor_in->done_.observe([this](tr_torrent*, bool) { on_torrent_done(); }),
tor_in->doomed_.observe([this](tr_torrent*) { on_torrent_doomed(); }),
tor_in->got_bad_piece_.observe([this](tr_torrent*, tr_piece_index_t p) { on_got_bad_piece(p); }),
tor_in->got_metainfo_.observe([this](tr_torrent*) { on_got_metainfo(); }),
tor_in->piece_completed_.observe([this](tr_torrent*, tr_piece_index_t p) { on_piece_completed(p); }),
tor_in->started_.observe([this](tr_torrent*) { on_torrent_started(); }),
tor_in->stopped_.observe([this](tr_torrent*) { on_torrent_stopped(); }),
tor_in->swarm_is_all_seeds_.observe([this](tr_torrent* /*tor*/) { on_swarm_is_all_seeds(); }),
} }
{
rebuildWebseeds();
}
tr_swarm(tr_swarm&&) = delete;
tr_swarm(tr_swarm const&) = delete;
tr_swarm& operator=(tr_swarm&&) = delete;
tr_swarm& operator=(tr_swarm const&) = delete;
~tr_swarm()
{
auto const lock = unique_lock();
TR_ASSERT(!is_running);
TR_ASSERT(std::empty(outgoing_handshakes));
TR_ASSERT(std::empty(peers));
}
[[nodiscard]] bool peer_is_in_use(peer_atom const& atom) const;
void cancelOldRequests()
{
auto const now = tr_time();
auto const oldest = now - RequestTtlSecs;
for (auto const& [block, peer] : active_requests.sentBefore(oldest))
{
maybeSendCancelRequest(peer, block, nullptr);
active_requests.remove(block, peer);
}
}
void cancelAllRequestsForBlock(tr_block_index_t block, tr_peer const* no_notify)
{
for (auto* peer : active_requests.remove(block))
{
maybeSendCancelRequest(peer, block, no_notify);
}
}
[[nodiscard]] uint16_t countActiveWebseeds(uint64_t now) const noexcept
{
if (!tor->is_running() || tor->is_done())
{
return {};
}
return std::count_if(
std::begin(webseeds),
std::end(webseeds),
[&now](auto const& webseed) { return webseed->isTransferringPieces(now, TR_DOWN, nullptr); });
}
[[nodiscard]] TR_CONSTEXPR20 auto peerCount() const noexcept
{
return std::size(peers);
}
void stop()
{
auto const lock = unique_lock();
is_running = false;
removeAllPeers();
outgoing_handshakes.clear();
}
void removePeer(tr_peer* peer)
{
auto const lock = unique_lock();
auto* const atom = peer->atom;
TR_ASSERT(atom != nullptr);
atom->time = tr_time();
if (auto iter = std::find(std::begin(peers), std::end(peers), peer); iter != std::end(peers))
{
peers.erase(iter);
}
--stats.peer_count;
--stats.peer_from_count[atom->fromFirst];
TR_ASSERT(stats.peer_count == peerCount());
delete peer;
}
void removeAllPeers()
{
auto tmp = peers;
for (auto* peer : tmp)
{
removePeer(peer);
}
TR_ASSERT(stats.peer_count == 0);
}
void updateEndgame()
{
/* we consider ourselves to be in endgame if the number of bytes
we've got requested is >= the number of bytes left to download */
is_endgame_ = uint64_t(std::size(active_requests)) * tr_block_info::BlockSize >= tor->left_until_done();
}
[[nodiscard]] constexpr auto isEndgame() const noexcept
{
return is_endgame_;
}
void addStrike(tr_peer* peer) const
{
tr_logAddTraceSwarm(
this,
fmt::format("increasing peer {} strike count to {}", peer->display_name(), peer->strikes + 1));
if (++peer->strikes >= MaxBadPiecesPerPeer)
{
peer->atom->ban();
peer->do_purge = true;
tr_logAddTraceSwarm(this, fmt::format("banning peer {}", peer->display_name()));
}
}
void rebuildWebseeds()
{
auto const n = tor->webseed_count();
webseeds.clear();
webseeds.reserve(n);
for (size_t i = 0; i < n; ++i)
{
webseeds.emplace_back(tr_webseedNew(tor, tor->webseed(i), &tr_swarm::peerCallbackFunc, this));
}
webseeds.shrink_to_fit();
stats.active_webseed_count = 0;
}
[[nodiscard]] TR_CONSTEXPR20 auto isAllSeeds() const noexcept
{
if (!pool_is_all_seeds_)
{
pool_is_all_seeds_ = std::all_of(
std::begin(pool),
std::end(pool),
[](auto const& key_val) { return key_val.second.isSeed(); });
}
return *pool_is_all_seeds_;
}
[[nodiscard]] peer_atom* get_existing_atom(std::pair<tr_address, tr_port> const& socket_address) noexcept
{
auto&& it = pool.find(socket_address);
return it != pool.end() ? &it->second : nullptr;
}
[[nodiscard]] peer_atom const* get_existing_atom(std::pair<tr_address, tr_port> const& socket_address) const noexcept
{
auto const& it = pool.find(socket_address);
return it != pool.cend() ? &it->second : nullptr;
}
[[nodiscard]] bool peer_is_a_seed(std::pair<tr_address, tr_port> const& socket_address) const noexcept
{
auto const* const atom = get_existing_atom(socket_address);
return atom != nullptr && atom->isSeed();
}
peer_atom* ensure_atom_exists(std::pair<tr_address, tr_port> const& socket_address, uint8_t const flags, uint8_t const from)
{
TR_ASSERT(socket_address.first.is_valid());
TR_ASSERT(from < TR_PEER_FROM__MAX);
auto&& [atom_it, is_new] = pool.try_emplace(socket_address, socket_address, flags, from);
peer_atom* atom = &atom_it->second;
if (!is_new)
{
atom->fromBest = std::min(atom->fromBest, from);
atom->flags |= flags;
}
mark_all_seeds_flag_dirty();
return atom;
}
void mark_atom_as_seed(peer_atom& atom)
{
tr_logAddTraceSwarm(this, fmt::format("marking peer {} as a seed", atom.display_name()));
atom.flags |= ADDED_F_SEED_FLAG;
mark_all_seeds_flag_dirty();
}
static void peerCallbackFunc(tr_peer* peer, tr_peer_event const& event, void* vs)
{
TR_ASSERT(peer != nullptr);
auto* s = static_cast<tr_swarm*>(vs);
auto const lock = s->unique_lock();
switch (event.type)
{
case tr_peer_event::Type::ClientSentPieceData:
{
auto const now = tr_time();
auto* const tor = s->tor;
tor->uploadedCur += event.length;
tr_announcerAddBytes(tor, TR_ANN_UP, event.length);
tor->set_date_active(now);
tor->set_dirty();
tor->session->add_uploaded(event.length);
if (peer->atom != nullptr)
{
peer->atom->piece_data_time = now;
}
break;
}
case tr_peer_event::Type::ClientGotPieceData:
{
auto const now = tr_time();
auto* const tor = s->tor;
tor->downloadedCur += event.length;
tor->set_date_active(now);
tor->set_dirty();
tor->session->add_downloaded(event.length);
if (peer->atom != nullptr)
{
peer->atom->piece_data_time = now;
}
break;
}
case tr_peer_event::Type::ClientGotHave:
case tr_peer_event::Type::ClientGotHaveAll:
case tr_peer_event::Type::ClientGotHaveNone:
case tr_peer_event::Type::ClientGotBitfield:
/* TODO: if we don't need these, should these events be removed? */
/* noop */
break;
case tr_peer_event::Type::ClientGotRej:
s->active_requests.remove(s->tor->piece_loc(event.pieceIndex, event.offset).block, peer);
break;
case tr_peer_event::Type::ClientGotChoke:
s->active_requests.remove(peer);
break;
case tr_peer_event::Type::ClientGotPort:
if (peer->atom != nullptr)
{
peer->atom->port() = event.port;
}
break;
case tr_peer_event::Type::ClientGotSuggest:
case tr_peer_event::Type::ClientGotAllowedFast:
// not currently supported
break;
case tr_peer_event::Type::ClientGotBlock:
{
auto* const tor = s->tor;
auto const loc = tor->piece_loc(event.pieceIndex, event.offset);
s->cancelAllRequestsForBlock(loc.block, peer);
peer->blocks_sent_to_client.add(tr_time(), 1);
tr_torrentGotBlock(tor, loc.block);
break;
}
case tr_peer_event::Type::Error:
if (event.err == ERANGE || event.err == EMSGSIZE || event.err == ENOTCONN)
{
/* some protocol error from the peer */
peer->do_purge = true;
tr_logAddDebugSwarm(
s,
fmt::format(
"setting {} do_purge flag because we got an ERANGE, EMSGSIZE, or ENOTCONN error",
peer->display_name()));
}
else
{
tr_logAddDebugSwarm(s, fmt::format("unhandled error: {}", tr_strerror(event.err)));
}
break;
}
}
Handshakes outgoing_handshakes;
mutable tr_swarm_stats stats = {};
uint8_t optimistic_unchoke_time_scaler = 0;
bool is_running = false;
tr_peerMgr* const manager;
tr_torrent* const tor;
ActiveRequests active_requests;
// depends-on: active_requests
std::vector<std::unique_ptr<tr_peer>> webseeds;
// depends-on: active_requests
std::vector<tr_peerMsgs*> peers;
// tr_peers hold pointers to the items in this container,
// therefore references to elements within cannot invalidate
std::map<std::pair<tr_address, tr_port>, peer_atom> pool;
tr_peerMsgs* optimistic = nullptr; /* the optimistic peer, or nullptr if none */
time_t lastCancel = 0;
private:
static void maybeSendCancelRequest(tr_peer* peer, tr_block_index_t block, tr_peer const* muted)
{
auto* msgs = dynamic_cast<tr_peerMsgs*>(peer);
if (msgs != nullptr && msgs != muted)
{
peer->cancels_sent_to_peer.add(tr_time(), 1);
msgs->cancel_block_request(block);
}
}
void mark_all_seeds_flag_dirty() noexcept
{
pool_is_all_seeds_.reset();
}
void on_torrent_doomed()
{
auto const lock = tor->unique_lock();
stop();
tor->swarm = nullptr;
delete this;
}
void on_torrent_done()
{
std::for_each(std::begin(peers), std::end(peers), [](auto* const peer) { peer->set_interested(false); });
}
void on_swarm_is_all_seeds()
{
auto const lock = tor->unique_lock();
for (auto& [socket_address, atom] : pool)
{
mark_atom_as_seed(atom);
}
mark_all_seeds_flag_dirty();
}
void on_piece_completed(tr_piece_index_t piece)
{
bool piece_came_from_peers = false;
for (auto* const peer : peers)
{
// notify the peer that we now have this piece
peer->on_piece_completed(piece);
if (!piece_came_from_peers)
{
piece_came_from_peers = peer->blame.test(piece);
}
}
if (piece_came_from_peers) /* webseed downloads don't belong in announce totals */
{
tr_announcerAddBytes(tor, TR_ANN_DOWN, tor->piece_size(piece));
}
}
void on_got_bad_piece(tr_piece_index_t piece)
{
auto const byte_count = tor->piece_size(piece);
for (auto* const peer : peers)
{
if (peer->blame.test(piece))
{
tr_logAddTraceSwarm(
this,
fmt::format(
"peer {} contributed to corrupt piece ({}); now has {} strikes",
peer->display_name(),
piece,
peer->strikes + 1));
addStrike(peer);
}
}
tr_announcerAddBytes(tor, TR_ANN_CORRUPT, byte_count);
}
void on_got_metainfo()
{
// the webseed list may have changed...
rebuildWebseeds();
// some peer_msgs' progress fields may not be accurate if we
// didn't have the metadata before now... so refresh them all...
for (auto* peer : peers)
{
peer->onTorrentGotMetainfo();
if (peer->isSeed())
{
mark_atom_as_seed(*peer->atom);
}
}
}
void on_torrent_started();
void on_torrent_stopped();
// number of bad pieces a peer is allowed to send before we ban them
static auto constexpr MaxBadPiecesPerPeer = int{ 5 };
// how long we'll let requests we've made linger before we cancel them
static auto constexpr RequestTtlSecs = int{ 90 };
std::array<libtransmission::ObserverTag, 8> const tags_;
mutable std::optional<bool> pool_is_all_seeds_;
bool is_endgame_ = false;
};
struct tr_peerMgr
{
explicit tr_peerMgr(tr_session* session_in)
: session{ session_in }
, handshake_mediator_{ *session }
, bandwidth_timer_{ session->timerMaker().create([this]() { bandwidthPulse(); }) }
, rechoke_timer_{ session->timerMaker().create([this]() { rechokePulseMarshall(); }) }
, refill_upkeep_timer_{ session->timerMaker().create([this]() { refillUpkeep(); }) }
, blocklist_tag_{ session->blocklist_changed_.observe([this]() { on_blocklist_changed(); }) }
{
bandwidth_timer_->start_repeating(BandwidthPeriod);
rechoke_timer_->start_repeating(RechokePeriod);
refill_upkeep_timer_->start_repeating(RefillUpkeepPeriod);
}
tr_peerMgr(tr_peerMgr&&) = delete;
tr_peerMgr(tr_peerMgr const&) = delete;
tr_peerMgr& operator=(tr_peerMgr&&) = delete;
tr_peerMgr& operator=(tr_peerMgr const&) = delete;
[[nodiscard]] auto unique_lock() const
{
return session->unique_lock();
}
~tr_peerMgr()
{
auto const lock = unique_lock();
incoming_handshakes.clear();
}
void rechokeSoon() noexcept
{
rechoke_timer_->set_interval(100ms);
}
void bandwidthPulse();
void rechokePulse() const;
void reconnectPulse();
void refillUpkeep() const;
void makeNewPeerConnections(size_t max);
[[nodiscard]] tr_swarm* get_existing_swarm(tr_sha1_digest_t const& hash) const
{
auto* const tor = session->torrents().get(hash);
return tor == nullptr ? nullptr : tor->swarm;
}
tr_session* const session;
Handshakes incoming_handshakes;
HandshakeMediator handshake_mediator_;
private:
void rechokePulseMarshall()
{
rechokePulse();
rechoke_timer_->set_interval(RechokePeriod);
}
void on_blocklist_changed() const
{
/* we cache whether or not a peer is blocklisted...
since the blocklist has changed, erase that cached value */
for (auto* const tor : session->torrents())
{
for (auto& [socket_address, atom] : tor->swarm->pool)
{
atom.setBlocklistedDirty();
}
}
}
std::unique_ptr<libtransmission::Timer> const bandwidth_timer_;
std::unique_ptr<libtransmission::Timer> const rechoke_timer_;
std::unique_ptr<libtransmission::Timer> const refill_upkeep_timer_;
libtransmission::ObserverTag const blocklist_tag_;
static auto constexpr BandwidthPeriod = 500ms;
static auto constexpr RechokePeriod = 10s;
static auto constexpr RefillUpkeepPeriod = 10s;
// how frequently to decide which peers live and die
static auto constexpr ReconnectPeriodMsec = int{ 500 };
// max number of peers to ask for per second overall.
// this throttle is to avoid overloading the router
static auto constexpr MaxConnectionsPerSecond = size_t{ 12 };
};
// --- tr_peer virtual functions
tr_peer::tr_peer(tr_torrent const* tor, peer_atom* atom_in)
: session{ tor->session }
, swarm{ tor->swarm }
, atom{ atom_in }
, blame{ tor->block_count() }
{
}
tr_peer::~tr_peer()
{
if (swarm != nullptr)
{
swarm->active_requests.remove(this);
}
if (atom != nullptr)
{
atom->is_connected = false;
}
}
// ---
tr_peerMgr* tr_peerMgrNew(tr_session* session)
{
return new tr_peerMgr{ session };
}
void tr_peerMgrFree(tr_peerMgr* manager)
{
delete manager;
}
// ---
void tr_peerMgrSetUtpSupported(tr_torrent* tor, std::pair<tr_address, tr_port> const& socket_address)
{
if (auto* const atom = tor->swarm->get_existing_atom(socket_address); atom != nullptr)
{
atom->flags |= ADDED_F_UTP_FLAGS;
}
}
void tr_peerMgrSetUtpFailed(tr_torrent* tor, std::pair<tr_address, tr_port> const& socket_address, bool failed)
{
if (auto* const atom = tor->swarm->get_existing_atom(socket_address); atom != nullptr)
{
atom->utp_failed = failed;
}
}
/**
* REQUESTS
*
* There are two data structures associated with managing block requests:
*
* 1. tr_swarm::active_requests, an opaque class that tracks what requests
* we currently have, i.e. which blocks and from which peers.
* This is used for cancelling requests that have been waiting
* for too long and avoiding duplicate requests.
*
* 2. tr_swarm::pieces, an array of "struct weighted_piece" which lists the
* pieces that we want to request. It's used to decide which blocks to
* return next when tr_peerMgrGetBlockRequests() is called.
*/
// --- struct block_request
// TODO: if we keep this, add equivalent API to ActiveRequest
void tr_peerMgrClientSentRequests(tr_torrent* torrent, tr_peer* peer, tr_block_span_t span)
{
auto const now = tr_time();
for (tr_block_index_t block = span.begin; block < span.end; ++block)
{
torrent->swarm->active_requests.add(block, peer, now);
}
}
std::vector<tr_block_span_t> tr_peerMgrGetNextRequests(tr_torrent* torrent, tr_peer const* peer, size_t numwant)
{
class MediatorImpl final : public Wishlist::Mediator
{
public:
MediatorImpl(tr_torrent const* torrent_in, tr_peer const* peer_in)
: torrent_{ torrent_in }
, swarm_{ torrent_in->swarm }
, peer_{ peer_in }
{
}
MediatorImpl(MediatorImpl&&) = delete;
MediatorImpl(MediatorImpl const&) = delete;
MediatorImpl& operator=(MediatorImpl&&) = delete;
MediatorImpl& operator=(MediatorImpl const&) = delete;
~MediatorImpl() override = default;
[[nodiscard]] bool clientCanRequestBlock(tr_block_index_t block) const override
{
return !torrent_->has_block(block) && !swarm_->active_requests.has(block, peer_);
}
[[nodiscard]] bool clientCanRequestPiece(tr_piece_index_t piece) const override
{
return torrent_->piece_is_wanted(piece) && peer_->hasPiece(piece);
}
[[nodiscard]] bool isEndgame() const override
{
return swarm_->isEndgame();
}