forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
2221 lines (1849 loc) · 83.5 KB
/
mod.rs
File metadata and controls
2221 lines (1849 loc) · 83.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
//! The core `tracker` module contains the generic `BitTorrent` tracker logic which is independent of the delivery layer.
//!
//! It contains the tracker services and their dependencies. It's a domain layer which does not
//! specify how the end user should connect to the `Tracker`.
//!
//! Typically this module is intended to be used by higher modules like:
//!
//! - A UDP tracker
//! - A HTTP tracker
//! - A tracker REST API
//!
//! ```text
//! Delivery layer Domain layer
//!
//! HTTP tracker |
//! UDP tracker |> Core tracker
//! Tracker REST API |
//! ```
//!
//! # Table of contents
//!
//! - [Tracker](#tracker)
//! - [Announce request](#announce-request)
//! - [Scrape request](#scrape-request)
//! - [Torrents](#torrents)
//! - [Peers](#peers)
//! - [Configuration](#configuration)
//! - [Services](#services)
//! - [Authentication](#authentication)
//! - [Statistics](#statistics)
//! - [Persistence](#persistence)
//!
//! # Tracker
//!
//! The `Tracker` is the main struct in this module. `The` tracker has some groups of responsibilities:
//!
//! - **Core tracker**: it handles the information about torrents and peers.
//! - **Authentication**: it handles authentication keys which are used by HTTP trackers.
//! - **Authorization**: it handles the permission to perform requests.
//! - **Whitelist**: when the tracker runs in `listed` or `private_listed` mode all operations are restricted to whitelisted torrents.
//! - **Statistics**: it keeps and serves the tracker statistics.
//!
//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) crate docs to get more information about the tracker settings.
//!
//! ## Announce request
//!
//! Handling `announce` requests is the most important task for a `BitTorrent` tracker.
//!
//! A `BitTorrent` swarm is a network of peers that are all trying to download the same torrent.
//! When a peer wants to find other peers it announces itself to the swarm via the tracker.
//! The peer sends its data to the tracker so that the tracker can add it to the swarm.
//! The tracker responds to the peer with the list of other peers in the swarm so that
//! the peer can contact them to start downloading pieces of the file from them.
//!
//! Once you have instantiated the `Tracker` you can `announce` a new [`peer::Peer`] with:
//!
//! ```rust,no_run
//! use std::net::SocketAddr;
//! use std::net::IpAddr;
//! use std::net::Ipv4Addr;
//! use std::str::FromStr;
//!
//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId};
//! use torrust_tracker_primitives::DurationSinceUnixEpoch;
//! use torrust_tracker_primitives::peer;
//! use bittorrent_primitives::info_hash::InfoHash;
//!
//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap();
//!
//! let peer = peer::Peer {
//! peer_id: PeerId(*b"-qB00000000000000001"),
//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081),
//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0),
//! uploaded: NumberOfBytes::new(0),
//! downloaded: NumberOfBytes::new(0),
//! left: NumberOfBytes::new(0),
//! event: AnnounceEvent::Completed,
//! };
//!
//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap());
//! ```
//!
//! ```text
//! let announce_data = tracker.announce(&info_hash, &mut peer, &peer_ip).await;
//! ```
//!
//! The `Tracker` returns the list of peers for the torrent with the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`,
//! filtering out the peer that is making the `announce` request.
//!
//! > **NOTICE**: that the peer argument is mutable because the `Tracker` can change the peer IP if the peer is using a loopback IP.
//!
//! The `peer_ip` argument is the resolved peer ip. It's a common practice that trackers ignore the peer ip in the `announce` request params,
//! and resolve the peer ip using the IP of the client making the request. As the tracker is a domain service, the peer IP must be provided
//! for the `Tracker` user, which is usually a higher component with access the the request metadata, for example, connection data, proxy headers,
//! etcetera.
//!
//! The returned struct is:
//!
//! ```rust,no_run
//! use torrust_tracker_primitives::peer;
//! use torrust_tracker_configuration::AnnouncePolicy;
//!
//! pub struct AnnounceData {
//! pub peers: Vec<peer::Peer>,
//! pub swarm_stats: SwarmMetadata,
//! pub policy: AnnouncePolicy, // the tracker announce policy.
//! }
//!
//! pub struct SwarmMetadata {
//! pub completed: u32, // The number of peers that have ever completed downloading
//! pub seeders: u32, // The number of active peers that have completed downloading (seeders)
//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers)
//! }
//!
//! // Core tracker configuration
//! pub struct AnnounceInterval {
//! // ...
//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker
//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this
//! // ...
//! }
//! ```
//!
//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request:
//!
//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html)
//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html)
//! - [Vuze docs](https://wiki.vuze.com/w/Announce)
//!
//! ## Scrape request
//!
//! The `scrape` request allows clients to query metadata about the swarm in bulk.
//!
//! An `scrape` request includes a list of infohashes whose swarm metadata you want to collect.
//!
//! The returned struct is:
//!
//! ```rust,no_run
//! use bittorrent_primitives::info_hash::InfoHash;
//! use std::collections::HashMap;
//!
//! pub struct ScrapeData {
//! pub files: HashMap<InfoHash, SwarmMetadata>,
//! }
//!
//! pub struct SwarmMetadata {
//! pub complete: u32, // The number of active peers that have completed downloading (seeders)
//! pub downloaded: u32, // The number of peers that have ever completed downloading
//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers)
//! }
//! ```
//!
//! The JSON representation of a sample `scrape` response would be like the following:
//!
//! ```json
//! {
//! 'files': {
//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19},
//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20}
//! }
//! }
//! ```
//!
//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays.
//! There are two data structures for infohashes: byte arrays and hex strings:
//!
//! ```rust,no_run
//! use bittorrent_primitives::info_hash::InfoHash;
//! use std::str::FromStr;
//!
//! let info_hash: InfoHash = [255u8; 20].into();
//!
//! assert_eq!(
//! info_hash,
//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap()
//! );
//! ```
//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request:
//!
//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html)
//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html)
//! - [Vuze docs](https://wiki.vuze.com/w/Scrape)
//!
//! ## Torrents
//!
//! The [`torrent`] module contains all the data structures stored by the `Tracker` except for peers.
//!
//! We can represent the data stored in memory internally by the `Tracker` with this JSON object:
//!
//! ```json
//! {
//! "c1277613db1d28709b034a017ab2cae4be07ae10": {
//! "completed": 0,
//! "peers": {
//! "-qB00000000000000001": {
//! "peer_id": "-qB00000000000000001",
//! "peer_addr": "2.137.87.41:1754",
//! "updated": 1672419840,
//! "uploaded": 120,
//! "downloaded": 60,
//! "left": 60,
//! "event": "started"
//! },
//! "-qB00000000000000002": {
//! "peer_id": "-qB00000000000000002",
//! "peer_addr": "23.17.287.141:2345",
//! "updated": 1679415984,
//! "uploaded": 80,
//! "downloaded": 20,
//! "left": 40,
//! "event": "started"
//! }
//! }
//! }
//! }
//! ```
//!
//! The `Tracker` maintains an indexed-by-info-hash list of torrents. For each torrent, it stores a torrent `Entry`.
//! The torrent entry has two attributes:
//!
//! - `completed`: which is hte number of peers that have completed downloading the torrent file/s. As they have completed downloading,
//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders".
//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request.
//!
//! The [`torrent`] module not only contains the original data obtained from peer via `announce` requests, it also contains
//! aggregate data that can be derived from the original data. For example:
//!
//! ```rust,no_run
//! pub struct SwarmMetadata {
//! pub complete: u32, // The number of active peers that have completed downloading (seeders)
//! pub downloaded: u32, // The number of peers that have ever completed downloading
//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers)
//! }
//!
//! ```
//!
//! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders".
//!
//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata`
//! is used for the rest of cases.
//!
//! Refer to [`torrent`] module for more details about these data structures.
//!
//! ## Peers
//!
//! A `Peer` is the struct used by the `Tracker` to keep peers data:
//!
//! ```rust,no_run
//! use std::net::SocketAddr;
//! use aquatic_udp_protocol::PeerId;
//! use torrust_tracker_primitives::DurationSinceUnixEpoch;
//! use aquatic_udp_protocol::NumberOfBytes;
//! use aquatic_udp_protocol::AnnounceEvent;
//!
//! pub struct Peer {
//! pub peer_id: PeerId, // The peer ID
//! pub peer_addr: SocketAddr, // Peer socket address
//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated
//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far
//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far
//! pub left: NumberOfBytes, // The number of bytes this peer still has to download
//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped`
//! }
//! ```
//!
//! Notice that most of the attributes are obtained from the `announce` request.
//! For example, an HTTP announce request would contain the following `GET` parameters:
//!
//! <http://0.0.0.0:7070/announce?info_hash=%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00&peer_addr=2.137.87.41&downloaded=0&uploaded=0&peer_id=-qB00000000000000001&port=17548&left=0&event=completed&compact=0>
//!
//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics.
//!
//! We can represent the data stored in memory with this JSON object:
//!
//! ```json
//! {
//! "c1277613db1d28709b034a017ab2cae4be07ae10": {
//! "completed": 0,
//! "peers": {
//! "-qB00000000000000001": {
//! "peer_id": "-qB00000000000000001",
//! "peer_addr": "2.137.87.41:1754",
//! "updated": 1672419840,
//! "uploaded": 120,
//! "downloaded": 60,
//! "left": 60,
//! "event": "started"
//! },
//! "-qB00000000000000002": {
//! "peer_id": "-qB00000000000000002",
//! "peer_addr": "23.17.287.141:2345",
//! "updated": 1679415984,
//! "uploaded": 80,
//! "downloaded": 20,
//! "left": 40,
//! "event": "started"
//! }
//! }
//! }
//! }
//! ```
//!
//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data.
//!
//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers
//! that have a full version of the torrent data, also known as seeders.
//!
//! Refer to [`peer`] module for more information about peers.
//!
//! # Configuration
//!
//! You can control the behavior of this module with the module settings:
//!
//! ```toml
//! [logging]
//! threshold = "debug"
//!
//! [core]
//! inactive_peer_cleanup_interval = 600
//! listed = false
//! private = false
//! tracker_usage_statistics = true
//!
//! [core.announce_policy]
//! interval = 120
//! interval_min = 120
//!
//! [core.database]
//! driver = "sqlite3"
//! path = "./storage/tracker/lib/database/sqlite3.db"
//!
//! [core.net]
//! on_reverse_proxy = false
//! external_ip = "2.137.87.41"
//!
//! [core.tracker_policy]
//! max_peer_timeout = 900
//! persistent_torrent_completed_stat = false
//! remove_peerless_torrents = true
//! ```
//!
//! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options.
//!
//! # Services
//!
//! Services are domain services on top of the core tracker. Right now there are two types of service:
//!
//! - For statistics
//! - For torrents
//!
//! Services usually format the data inside the tracker to make it easier to consume by other parts.
//! They also decouple the internal data structure, used by the tracker, from the way we deliver that data to the consumers.
//! The internal data structure is designed for performance or low memory consumption. And it should be changed
//! without affecting the external consumers.
//!
//! Services can include extra features like pagination, for example.
//!
//! Refer to [`services`] module for more information about services.
//!
//! # Authentication
//!
//! One of the core `Tracker` responsibilities is to create and keep authentication keys. Auth keys are used by HTTP trackers
//! when the tracker is running in `private` or `private_listed` mode.
//!
//! HTTP tracker's clients need to obtain an auth key before starting requesting the tracker. Once the get one they have to include
//! a `PATH` param with the key in all the HTTP requests. For example, when a peer wants to `announce` itself it has to use the
//! HTTP tracker endpoint `GET /announce/:key`.
//!
//! The common way to obtain the keys is by using the tracker API directly or via other applications like the [Torrust Index](https://github.com/torrust/torrust-index).
//!
//! To learn more about tracker authentication, refer to the following modules :
//!
//! - [`auth`] module.
//! - [`core`](crate::core) module.
//! - [`http`](crate::servers::http) module.
//!
//! # Statistics
//!
//! The `Tracker` keeps metrics for some events:
//!
//! ```rust,no_run
//! pub struct Metrics {
//! // IP version 4
//!
//! // HTTP tracker
//! pub tcp4_connections_handled: u64,
//! pub tcp4_announces_handled: u64,
//! pub tcp4_scrapes_handled: u64,
//!
//! // UDP tracker
//! pub udp4_connections_handled: u64,
//! pub udp4_announces_handled: u64,
//! pub udp4_scrapes_handled: u64,
//!
//! // IP version 6
//!
//! // HTTP tracker
//! pub tcp6_connections_handled: u64,
//! pub tcp6_announces_handled: u64,
//! pub tcp6_scrapes_handled: u64,
//!
//! // UDP tracker
//! pub udp6_connections_handled: u64,
//! pub udp6_announces_handled: u64,
//! pub udp6_scrapes_handled: u64,
//! }
//! ```
//!
//! The metrics maintained by the `Tracker` are:
//!
//! - `connections_handled`: number of connections handled by the tracker
//! - `announces_handled`: number of `announce` requests handled by the tracker
//! - `scrapes_handled`: number of `scrape` handled requests by the tracker
//!
//! > **NOTICE**: as the HTTP tracker does not have an specific `connection` request like the UDP tracker, `connections_handled` are
//! > increased on every `announce` and `scrape` requests.
//!
//! The tracker exposes an event sender API that allows the tracker users to send events. When a higher application service handles a
//! `connection` , `announce` or `scrape` requests, it notifies the `Tracker` by sending statistics events.
//!
//! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4.
//!
//! ```text
//! tracker.send_stats_event(statistics::Event::Tcp4Announce).await
//! ```
//!
//! Refer to [`statistics`] module for more information about statistics.
//!
//! # Persistence
//!
//! Right now the `Tracker` is responsible for storing and load data into and
//! from the database, when persistence is enabled.
//!
//! There are three types of persistent object:
//!
//! - Authentication keys (only expiring keys)
//! - Torrent whitelist
//! - Torrent metrics
//!
//! Refer to [`databases`] module for more information about persistence.
pub mod auth;
pub mod databases;
pub mod error;
pub mod services;
pub mod statistics;
pub mod torrent;
pub mod peer_tests;
use std::cmp::max;
use std::collections::HashMap;
use std::net::IpAddr;
use std::panic::Location;
use std::sync::Arc;
use std::time::Duration;
use auth::PeerKey;
use bittorrent_primitives::info_hash::InfoHash;
use databases::driver::Driver;
use derive_more::Constructor;
use error::PeerKeyError;
use tokio::sync::mpsc::error::SendError;
use torrust_tracker_clock::clock::Time;
use torrust_tracker_configuration::v2_0_0::database;
use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT};
use torrust_tracker_located_error::Located;
use torrust_tracker_primitives::swarm_metadata::SwarmMetadata;
use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics;
use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch};
use torrust_tracker_torrent_repository::entry::EntrySync;
use torrust_tracker_torrent_repository::repository::Repository;
use self::auth::Key;
use self::error::Error;
use self::torrent::Torrents;
use crate::core::databases::Database;
use crate::CurrentClock;
/// The domain layer tracker service.
///
/// Its main responsibility is to handle the `announce` and `scrape` requests.
/// But it's also a container for the `Tracker` configuration, persistence,
/// authentication and other services.
///
/// > **NOTICE**: the `Tracker` is not responsible for handling the network layer.
/// > Typically, the `Tracker` is used by a higher application service that handles
/// > the network layer.
pub struct Tracker {
/// The tracker configuration.
config: Core,
/// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite)
/// or [`MySQL`](crate::core::databases::mysql)
database: Arc<Box<dyn Database>>,
/// Tracker users' keys. Only for private trackers.
keys: tokio::sync::RwLock<std::collections::HashMap<Key, auth::PeerKey>>,
/// The list of allowed torrents. Only for listed trackers.
whitelist: tokio::sync::RwLock<std::collections::HashSet<InfoHash>>,
/// The in-memory torrents repository.
torrents: Arc<Torrents>,
/// Service to send stats events.
stats_event_sender: Option<Box<dyn statistics::EventSender>>,
/// The in-memory stats repo.
stats_repository: statistics::Repo,
}
/// Structure that holds the data returned by the `announce` request.
#[derive(Clone, Debug, PartialEq, Constructor, Default)]
pub struct AnnounceData {
/// The list of peers that are downloading the same torrent.
/// It excludes the peer that made the request.
pub peers: Vec<Arc<peer::Peer>>,
/// Swarm statistics
pub stats: SwarmMetadata,
pub policy: AnnouncePolicy,
}
/// How many peers the peer announcing wants in the announce response.
#[derive(Clone, Debug, PartialEq, Default)]
pub enum PeersWanted {
/// The peer wants as many peers as possible in the announce response.
#[default]
All,
/// The peer only wants a certain amount of peers in the announce response.
Only { amount: usize },
}
impl PeersWanted {
#[must_use]
pub fn only(limit: u32) -> Self {
let amount: usize = match limit.try_into() {
Ok(amount) => amount,
Err(_) => TORRENT_PEERS_LIMIT,
};
Self::Only { amount }
}
fn limit(&self) -> usize {
match self {
PeersWanted::All => TORRENT_PEERS_LIMIT,
PeersWanted::Only { amount } => *amount,
}
}
}
impl From<i32> for PeersWanted {
fn from(value: i32) -> Self {
if value > 0 {
match value.try_into() {
Ok(peers_wanted) => Self::Only { amount: peers_wanted },
Err(_) => Self::All,
}
} else {
Self::All
}
}
}
/// Structure that holds the data returned by the `scrape` request.
#[derive(Debug, PartialEq, Default)]
pub struct ScrapeData {
/// A map of infohashes and swarm metadata for each torrent.
pub files: HashMap<InfoHash, SwarmMetadata>,
}
impl ScrapeData {
/// Creates a new empty `ScrapeData` with no files (torrents).
#[must_use]
pub fn empty() -> Self {
let files: HashMap<InfoHash, SwarmMetadata> = HashMap::new();
Self { files }
}
/// Creates a new `ScrapeData` with zeroed metadata for each torrent.
#[must_use]
pub fn zeroed(info_hashes: &Vec<InfoHash>) -> Self {
let mut scrape_data = Self::empty();
for info_hash in info_hashes {
scrape_data.add_file(info_hash, SwarmMetadata::zeroed());
}
scrape_data
}
/// Adds a torrent to the `ScrapeData`.
pub fn add_file(&mut self, info_hash: &InfoHash, swarm_metadata: SwarmMetadata) {
self.files.insert(*info_hash, swarm_metadata);
}
/// Adds a torrent to the `ScrapeData` with zeroed metadata.
pub fn add_file_with_zeroed_metadata(&mut self, info_hash: &InfoHash) {
self.files.insert(*info_hash, SwarmMetadata::zeroed());
}
}
/// This type contains the info needed to add a new tracker key.
///
/// You can upload a pre-generated key or let the app to generate a new one.
/// You can also set an expiration date or leave it empty (`None`) if you want
/// to create a permanent key that does not expire.
#[derive(Debug)]
pub struct AddKeyRequest {
/// The pre-generated key. Use `None` to generate a random key.
pub opt_key: Option<String>,
/// How long the key will be valid in seconds. Use `None` for permanent keys.
pub opt_seconds_valid: Option<u64>,
}
impl Tracker {
/// `Tracker` constructor.
///
/// # Errors
///
/// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence.
pub fn new(
config: &Core,
stats_event_sender: Option<Box<dyn statistics::EventSender>>,
stats_repository: statistics::Repo,
) -> Result<Tracker, databases::error::Error> {
let driver = match config.database.driver {
database::Driver::Sqlite3 => Driver::Sqlite3,
database::Driver::MySQL => Driver::MySQL,
};
let database = Arc::new(databases::driver::build(&driver, &config.database.path)?);
Ok(Tracker {
config: config.clone(),
keys: tokio::sync::RwLock::new(std::collections::HashMap::new()),
whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()),
torrents: Arc::default(),
stats_event_sender,
stats_repository,
database,
})
}
/// Returns `true` is the tracker is in public mode.
pub fn is_public(&self) -> bool {
!self.config.private
}
/// Returns `true` is the tracker is in private mode.
pub fn is_private(&self) -> bool {
self.config.private
}
/// Returns `true` is the tracker is in whitelisted mode.
pub fn is_listed(&self) -> bool {
self.config.listed
}
/// Returns `true` if the tracker requires authentication.
pub fn requires_authentication(&self) -> bool {
self.is_private()
}
/// Returns `true` is the tracker is in whitelisted mode.
pub fn is_behind_reverse_proxy(&self) -> bool {
self.config.net.on_reverse_proxy
}
pub fn get_announce_policy(&self) -> AnnouncePolicy {
self.config.announce_policy
}
pub fn get_maybe_external_ip(&self) -> Option<IpAddr> {
self.config.net.external_ip
}
/// It handles an announce request.
///
/// # Context: Tracker
///
/// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html).
pub fn announce(
&self,
info_hash: &InfoHash,
peer: &mut peer::Peer,
remote_client_ip: &IpAddr,
peers_wanted: &PeersWanted,
) -> AnnounceData {
// code-review: maybe instead of mutating the peer we could just return
// a tuple with the new peer and the announce data: (Peer, AnnounceData).
// It could even be a different struct: `StoredPeer` or `PublicPeer`.
// code-review: in the `scrape` function we perform an authorization check.
// We check if the torrent is whitelisted. Should we also check authorization here?
// I think so because the `Tracker` has the responsibility for checking authentication and authorization.
// The `Tracker` has delegated that responsibility to the handlers
// (because we want to return a friendly error response) but that does not mean we should
// double-check authorization at this domain level too.
// I would propose to return a `Result<AnnounceData, Error>` here.
// Besides, regarding authentication the `Tracker` is also responsible for authentication but
// we are actually handling authentication at the handlers level. So I would extract that
// responsibility into another authentication service.
tracing::debug!("Before: {peer:?}");
peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip));
tracing::debug!("After: {peer:?}");
let stats = self.upsert_peer_and_get_stats(info_hash, peer);
let peers = self.get_peers_for(info_hash, peer, peers_wanted.limit());
AnnounceData {
peers,
stats,
policy: self.get_announce_policy(),
}
}
/// It handles a scrape request.
///
/// # Context: Tracker
///
/// BEP 48: [Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html).
pub async fn scrape(&self, info_hashes: &Vec<InfoHash>) -> ScrapeData {
let mut scrape_data = ScrapeData::empty();
for info_hash in info_hashes {
let swarm_metadata = match self.authorize(info_hash).await {
Ok(()) => self.get_swarm_metadata(info_hash),
Err(_) => SwarmMetadata::zeroed(),
};
scrape_data.add_file(info_hash, swarm_metadata);
}
scrape_data
}
/// It returns the data for a `scrape` response.
fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata {
match self.torrents.get(info_hash) {
Some(torrent_entry) => torrent_entry.get_swarm_metadata(),
None => SwarmMetadata::default(),
}
}
/// It loads the torrents from database into memory. It only loads the torrent entry list with the number of seeders for each torrent.
/// Peers data is not persisted.
///
/// # Context: Tracker
///
/// # Errors
///
/// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database.
pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> {
let persistent_torrents = self.database.load_persistent_torrents()?;
self.torrents.import_persistent(&persistent_torrents);
Ok(())
}
/// # Context: Tracker
///
/// Get torrent peers for a given torrent and client.
///
/// It filters out the client making the request.
fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec<Arc<peer::Peer>> {
match self.torrents.get(info_hash) {
None => vec![],
Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(max(limit, TORRENT_PEERS_LIMIT))),
}
}
/// # Context: Tracker
///
/// Get torrent peers for a given torrent.
pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec<Arc<peer::Peer>> {
match self.torrents.get(info_hash) {
None => vec![],
Some(entry) => entry.get_peers(Some(TORRENT_PEERS_LIMIT)),
}
}
/// It updates the torrent entry in memory, it also stores in the database
/// the torrent info data which is persistent, and finally return the data
/// needed for a `announce` request response.
///
/// # Context: Tracker
pub fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata {
let swarm_metadata_before = match self.torrents.get_swarm_metadata(info_hash) {
Some(swarm_metadata) => swarm_metadata,
None => SwarmMetadata::zeroed(),
};
self.torrents.upsert_peer(info_hash, peer);
let swarm_metadata_after = match self.torrents.get_swarm_metadata(info_hash) {
Some(swarm_metadata) => swarm_metadata,
None => SwarmMetadata::zeroed(),
};
if swarm_metadata_before != swarm_metadata_after {
self.persist_stats(info_hash, &swarm_metadata_after);
}
swarm_metadata_after
}
/// It stores the torrents stats into the database (if persistency is enabled).
///
/// # Context: Tracker
fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) {
if self.config.tracker_policy.persistent_torrent_completed_stat {
let completed = swarm_metadata.downloaded;
let info_hash = *info_hash;
drop(self.database.save_persistent_torrent(&info_hash, completed));
}
}
/// It calculates and returns the general `Tracker`
/// [`TorrentsMetrics`]
///
/// # Context: Tracker
///
/// # Panics
/// Panics if unable to get the torrent metrics.
pub fn get_torrents_metrics(&self) -> TorrentsMetrics {
self.torrents.get_metrics()
}
/// Remove inactive peers and (optionally) peerless torrents.
///
/// # Context: Tracker
pub fn cleanup_torrents(&self) {
let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout)))
.unwrap_or_default();
self.torrents.remove_inactive_peers(current_cutoff);
if self.config.tracker_policy.remove_peerless_torrents {
self.torrents.remove_peerless_torrents(&self.config.tracker_policy);
}
}
/// It authenticates the peer `key` against the `Tracker` authentication
/// key list.
///
/// # Errors
///
/// Will return an error if the the authentication key cannot be verified.
///
/// # Context: Authentication
pub async fn authenticate(&self, key: &Key) -> Result<(), auth::Error> {
if self.is_private() {
self.verify_auth_key(key).await
} else {
Ok(())
}
}
/// Adds new peer keys to the tracker.
///
/// Keys can be pre-generated or randomly created. They can also be permanent or expire.
///
/// # Errors
///
/// Will return an error if:
///
/// - The key duration overflows the duration type maximum value.
/// - The provided pre-generated key is invalid.
/// - The key could not been persisted due to database issues.
pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result<auth::PeerKey, PeerKeyError> {
// code-review: all methods related to keys should be moved to a new independent "keys" service.
match add_key_req.opt_key {
// Upload pre-generated key
Some(pre_existing_key) => {
if let Some(seconds_valid) = add_key_req.opt_seconds_valid {
// Expiring key
let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else {
return Err(PeerKeyError::DurationOverflow { seconds_valid });
};
let key = pre_existing_key.parse::<Key>();
match key {
Ok(key) => match self.add_auth_key(key, Some(valid_until)).await {
Ok(auth_key) => Ok(auth_key),
Err(err) => Err(PeerKeyError::DatabaseError {
source: Located(err).into(),
}),
},
Err(err) => Err(PeerKeyError::InvalidKey {
key: pre_existing_key,
source: Located(err).into(),
}),
}
} else {
// Permanent key
let key = pre_existing_key.parse::<Key>();
match key {
Ok(key) => match self.add_permanent_auth_key(key).await {
Ok(auth_key) => Ok(auth_key),
Err(err) => Err(PeerKeyError::DatabaseError {
source: Located(err).into(),
}),
},
Err(err) => Err(PeerKeyError::InvalidKey {
key: pre_existing_key,
source: Located(err).into(),
}),
}
}
}
// Generate a new random key
None => match add_key_req.opt_seconds_valid {
// Expiring key
Some(seconds_valid) => match self.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await {
Ok(auth_key) => Ok(auth_key),
Err(err) => Err(PeerKeyError::DatabaseError {
source: Located(err).into(),
}),
},
// Permanent key
None => match self.generate_permanent_auth_key().await {
Ok(auth_key) => Ok(auth_key),
Err(err) => Err(PeerKeyError::DatabaseError {
source: Located(err).into(),
}),
},
},
}
}
/// It generates a new permanent authentication key.
///
/// Authentication keys are used by HTTP trackers.
///
/// # Context: Authentication
///
/// # Errors
///
/// Will return a `database::Error` if unable to add the `auth_key` to the database.
pub async fn generate_permanent_auth_key(&self) -> Result<auth::PeerKey, databases::error::Error> {
self.generate_auth_key(None).await
}
/// It generates a new expiring authentication key.
///
/// Authentication keys are used by HTTP trackers.
///
/// # Context: Authentication
///
/// # Errors
///
/// Will return a `database::Error` if unable to add the `auth_key` to the database.
///
/// # Arguments
///
/// * `lifetime` - The duration in seconds for the new key. The key will be
/// no longer valid after `lifetime` seconds.
pub async fn generate_auth_key(&self, lifetime: Option<Duration>) -> Result<auth::PeerKey, databases::error::Error> {
let auth_key = auth::generate_key(lifetime);
self.database.add_key_to_keys(&auth_key)?;
self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone());
Ok(auth_key)
}
/// It adds a pre-generated permanent authentication key.
///
/// Authentication keys are used by HTTP trackers.
///
/// # Context: Authentication
///
/// # Errors
///
/// Will return a `database::Error` if unable to add the `auth_key` to the
/// database. For example, if the key already exist.
///
/// # Arguments
///
/// * `key` - The pre-generated key.
pub async fn add_permanent_auth_key(&self, key: Key) -> Result<auth::PeerKey, databases::error::Error> {
self.add_auth_key(key, None).await
}
/// It adds a pre-generated authentication key.
///
/// Authentication keys are used by HTTP trackers.
///
/// # Context: Authentication
///
/// # Errors
///