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
1805 lines (1508 loc) · 68.8 KB
/
mod.rs
File metadata and controls
1805 lines (1508 loc) · 68.8 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`](crate::tracker::peer::Peer) with:
//!
//! ```rust,no_run
//! use torrust_tracker::tracker::peer;
//! use torrust_tracker::shared::bit_torrent::info_hash::InfoHash;
//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch;
//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes};
//! use std::net::SocketAddr;
//! use std::net::IpAddr;
//! use std::net::Ipv4Addr;
//! use std::str::FromStr;
//!
//!
//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap();
//!
//! let peer = peer::Peer {
//! peer_id: peer::Id(*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(0),
//! downloaded: NumberOfBytes(0),
//! left: NumberOfBytes(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::tracker::peer::Peer;
//!
//! pub struct AnnounceData {
//! pub peers: Vec<Peer>,
//! pub swarm_stats: SwarmStats,
//! pub interval: u32, // Option `announce_interval` from core tracker configuration
//! pub interval_min: u32, // Option `min_announce_interval` from core tracker configuration
//! }
//!
//! pub struct SwarmStats {
//! 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 Configuration {
//! // ...
//! pub announce_interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker
//! pub min_announce_interval: 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 torrust_tracker::shared::bit_torrent::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 torrust_tracker::shared::bit_torrent::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`](crate::tracker::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`](crate::tracker::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)
//! }
//!
//! pub struct SwarmStats {
//! 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)
//! }
//! ```
//!
//! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders".
//!
//! `SwarmStats` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmStats`
//! is used for the rest of cases.
//!
//! Refer to [`torrent`](crate::tracker::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 torrust_tracker::tracker::peer::Id;
//! use std::net::SocketAddr;
//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch;
//! use aquatic_udp_protocol::NumberOfBytes;
//! use aquatic_udp_protocol::AnnounceEvent;
//!
//! pub struct Peer {
//! pub peer_id: Id, // 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`](crate::tracker::peer) module for more information about peers.
//!
//! # Configuration
//!
//! You can control the behavior of this module with the module settings:
//!
//! ```toml
//! log_level = "debug"
//! mode = "public"
//! db_driver = "Sqlite3"
//! db_path = "./storage/database/data.db"
//! announce_interval = 120
//! min_announce_interval = 120
//! max_peer_timeout = 900
//! on_reverse_proxy = false
//! external_ip = "2.137.87.41"
//! tracker_usage_statistics = true
//! persistent_torrent_completed_stat = true
//! inactive_peer_cleanup_interval = 600
//! remove_peerless_torrents = false
//! ```
//!
//! 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`](crate::tracker::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`](crate::tracker::auth) module.
//! - [`tracker`](crate::tracker) 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`](crate::tracker::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`](crate::tracker::databases) module for more information about persistence.
pub mod auth;
pub mod databases;
pub mod error;
pub mod peer;
pub mod services;
pub mod statistics;
pub mod torrent;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::net::IpAddr;
use std::panic::Location;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc::error::SendError;
use tokio::sync::{RwLock, RwLockReadGuard};
use torrust_tracker_configuration::Configuration;
use torrust_tracker_primitives::TrackerMode;
use self::auth::Key;
use self::error::Error;
use self::peer::Peer;
use self::torrent::{SwarmMetadata, SwarmStats};
use crate::shared::bit_torrent::info_hash::InfoHash;
use crate::tracker::databases::Database;
/// 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 {
/// `Tracker` configuration. See [`torrust-tracker-configuration`](torrust_tracker_configuration)
pub config: Arc<Configuration>,
/// A database driver implementation: [`Sqlite3`](crate::tracker::databases::sqlite)
/// or [`MySQL`](crate::tracker::databases::mysql)
pub database: Box<dyn Database>,
mode: TrackerMode,
keys: RwLock<std::collections::HashMap<Key, auth::ExpiringKey>>,
whitelist: RwLock<std::collections::HashSet<InfoHash>>,
torrents: RwLock<std::collections::BTreeMap<InfoHash, torrent::Entry>>,
stats_event_sender: Option<Box<dyn statistics::EventSender>>,
stats_repository: statistics::Repo,
}
/// Structure that holds general `Tracker` torrents metrics.
///
/// Metrics are aggregate values for all torrents.
#[derive(Debug, PartialEq, Default)]
pub struct TorrentsMetrics {
/// Total number of seeders for all torrents
pub seeders: u64,
/// Total number of peers that have ever completed downloading for all torrents.
pub completed: u64,
/// Total number of leechers for all torrents.
pub leechers: u64,
/// Total number of torrents.
pub torrents: u64,
}
/// Structure that holds the data returned by the `announce` request.
#[derive(Debug, PartialEq, 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<Peer>,
/// Swarm statistics
pub swarm_stats: SwarmStats,
/// The interval in seconds that the client should wait between sending
/// regular requests to the tracker.
/// Refer to [`announce_interval`](torrust_tracker_configuration::Configuration::announce_interval).
pub interval: u32,
/// The minimum announce interval in seconds that the client should wait.
/// Refer to [`min_announce_interval`](torrust_tracker_configuration::Configuration::min_announce_interval).
pub interval_min: u32,
}
/// 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());
}
}
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: Arc<Configuration>,
stats_event_sender: Option<Box<dyn statistics::EventSender>>,
stats_repository: statistics::Repo,
) -> Result<Tracker, databases::error::Error> {
let database = databases::driver::build(&config.db_driver, &config.db_path)?;
let mode = config.mode;
Ok(Tracker {
config,
mode,
keys: RwLock::new(std::collections::HashMap::new()),
whitelist: RwLock::new(std::collections::HashSet::new()),
torrents: RwLock::new(std::collections::BTreeMap::new()),
stats_event_sender,
stats_repository,
database,
})
}
/// Returns `true` is the tracker is in public mode.
pub fn is_public(&self) -> bool {
self.mode == TrackerMode::Public
}
/// Returns `true` is the tracker is in private mode.
pub fn is_private(&self) -> bool {
self.mode == TrackerMode::Private || self.mode == TrackerMode::PrivateListed
}
/// Returns `true` is the tracker is in whitelisted mode.
pub fn is_whitelisted(&self) -> bool {
self.mode == TrackerMode::Listed || self.mode == TrackerMode::PrivateListed
}
/// Returns `true` if the tracker requires authentication.
pub fn requires_authentication(&self) -> bool {
self.is_private()
}
/// It handles an announce request.
///
/// # Context: Tracker
///
/// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html).
pub async fn announce(&self, info_hash: &InfoHash, peer: &mut Peer, remote_client_ip: &IpAddr) -> 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.
peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.get_ext_ip()));
let swarm_stats = self.update_torrent_with_peer_and_get_stats(info_hash, peer).await;
let peers = self.get_peers_for_peer(info_hash, peer).await;
AnnounceData {
peers,
swarm_stats,
interval: self.config.announce_interval,
interval_min: self.config.min_announce_interval,
}
}
/// 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).await,
Err(_) => SwarmMetadata::zeroed(),
};
scrape_data.add_file(info_hash, swarm_metadata);
}
scrape_data
}
/// It returns the data for a `scrape` response.
async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata {
let torrents = self.get_torrents().await;
match 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 async fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> {
let persistent_torrents = self.database.load_persistent_torrents().await?;
let mut torrents = self.torrents.write().await;
for (info_hash, completed) in persistent_torrents {
// Skip if torrent entry already exists
if torrents.contains_key(&info_hash) {
continue;
}
let torrent_entry = torrent::Entry {
peers: BTreeMap::default(),
completed,
};
torrents.insert(info_hash, torrent_entry);
}
Ok(())
}
async fn get_peers_for_peer(&self, info_hash: &InfoHash, peer: &Peer) -> Vec<peer::Peer> {
let read_lock = self.torrents.read().await;
match read_lock.get(info_hash) {
None => vec![],
Some(entry) => entry.get_peers_for_peer(peer).into_iter().copied().collect(),
}
}
/// # Context: Tracker
///
/// Get all torrent peers for a given torrent
pub async fn get_all_torrent_peers(&self, info_hash: &InfoHash) -> Vec<peer::Peer> {
let read_lock = self.torrents.read().await;
match read_lock.get(info_hash) {
None => vec![],
Some(entry) => entry.get_all_peers().into_iter().copied().collect(),
}
}
/// 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 async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> torrent::SwarmStats {
// code-review: consider splitting the function in two (command and query segregation).
// `update_torrent_with_peer` and `get_stats`
let mut torrents = self.torrents.write().await;
let torrent_entry = match torrents.entry(*info_hash) {
Entry::Vacant(vacant) => vacant.insert(torrent::Entry::new()),
Entry::Occupied(entry) => entry.into_mut(),
};
let stats_updated = torrent_entry.update_peer(peer);
// todo: move this action to a separate worker
if self.config.persistent_torrent_completed_stat && stats_updated {
let _: Result<(), databases::error::Error> = self
.database
.save_persistent_torrent(info_hash, torrent_entry.completed)
.await;
}
let (seeders, completed, leechers) = torrent_entry.get_stats();
torrent::SwarmStats {
completed,
seeders,
leechers,
}
}
pub async fn get_torrents(&self) -> RwLockReadGuard<'_, BTreeMap<InfoHash, torrent::Entry>> {
self.torrents.read().await
}
/// It calculates and returns the general `Tracker`
/// [`TorrentsMetrics`](crate::tracker::TorrentsMetrics)
///
/// # Context: Tracker
pub async fn get_torrents_metrics(&self) -> TorrentsMetrics {
let mut torrents_metrics = TorrentsMetrics {
seeders: 0,
completed: 0,
leechers: 0,
torrents: 0,
};
let db = self.get_torrents().await;
db.values().for_each(|torrent_entry| {
let (seeders, completed, leechers) = torrent_entry.get_stats();
torrents_metrics.seeders += u64::from(seeders);
torrents_metrics.completed += u64::from(completed);
torrents_metrics.leechers += u64::from(leechers);
torrents_metrics.torrents += 1;
});
torrents_metrics
}
/// Remove inactive peers and (optionally) peerless torrents
///
/// # Context: Tracker
pub async fn cleanup_torrents(&self) {
let mut torrents_lock = self.torrents.write().await;
// If we don't need to remove torrents we will use the faster iter
if self.config.remove_peerless_torrents {
torrents_lock.retain(|_, torrent_entry| {
torrent_entry.remove_inactive_peers(self.config.max_peer_timeout);
if self.config.persistent_torrent_completed_stat {
torrent_entry.completed > 0 || !torrent_entry.peers.is_empty()
} else {
!torrent_entry.peers.is_empty()
}
});
} else {
for (_, torrent_entry) in torrents_lock.iter_mut() {
torrent_entry.remove_inactive_peers(self.config.max_peer_timeout);
}
}
}
/// 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(())
}
}
/// It generates a new expiring authentication key.
/// `lifetime` param is the duration in seconds for the new key.
/// The key will be no longer valid after `lifetime` seconds.
/// 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_auth_key(&self, lifetime: Duration) -> Result<auth::ExpiringKey, databases::error::Error> {
let auth_key = auth::generate(lifetime);
self.database.add_key_to_keys(&auth_key).await?;
self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone());
Ok(auth_key)
}
/// It removes an authentication key.
///
/// # Context: Authentication
///
/// # Errors
///
/// Will return a `database::Error` if unable to remove the `key` to the database.
///
/// # Panics
///
/// Will panic if key cannot be converted into a valid `Key`.
pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> {
self.database.remove_key_from_keys(key).await?;
self.keys.write().await.remove(key);
Ok(())
}
/// It verifies an authentication key.
///
/// # Context: Authentication
///
/// # Errors
///
/// Will return a `key::Error` if unable to get any `auth_key`.
pub async fn verify_auth_key(&self, key: &Key) -> Result<(), auth::Error> {
// code-review: this function is public only because it's used in a test.
// We should change the test and make it private.
match self.keys.read().await.get(key) {
None => Err(auth::Error::UnableToReadKey {
location: Location::caller(),
key: Box::new(key.clone()),
}),
Some(key) => auth::verify(key),
}
}
/// The `Tracker` stores the authentication keys in memory and in the database.
/// In case you need to restart the `Tracker` you can load the keys from the database
/// into memory with this function. Keys are automatically stored in the database when they
/// are generated.
///
/// # Context: Authentication
///
/// # Errors
///
/// Will return a `database::Error` if unable to `load_keys` from the database.
pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> {
let keys_from_database = self.database.load_keys().await?;
let mut keys = self.keys.write().await;
keys.clear();
for key in keys_from_database {
keys.insert(key.key.clone(), key);
}
Ok(())
}
/// It authenticates and authorizes a UDP tracker request.
///
/// # Context: Authentication and Authorization
///
/// # Errors
///
/// Will return a `torrent::Error::PeerKeyNotValid` if the `key` is not valid.
///
/// Will return a `torrent::Error::PeerNotAuthenticated` if the `key` is `None`.
///
/// Will return a `torrent::Error::TorrentNotWhitelisted` if the the Tracker is in listed mode and the `info_hash` is not whitelisted.
#[deprecated(since = "3.0.0", note = "please use `authenticate` and `authorize` instead")]
pub async fn authenticate_request(&self, info_hash: &InfoHash, key: &Option<Key>) -> Result<(), Error> {
// todo: this is a deprecated method.
// We're splitting authentication and authorization responsibilities.
// Use `authenticate` and `authorize` instead.
// Authentication
// no authentication needed in public mode
if self.is_public() {
return Ok(());
}
// check if auth_key is set and valid
if self.is_private() {
match key {
Some(key) => {
if let Err(e) = self.verify_auth_key(key).await {
return Err(Error::PeerKeyNotValid {
key: key.clone(),
source: (Arc::new(e) as Arc<dyn std::error::Error + Send + Sync>).into(),
});
}
}
None => {
return Err(Error::PeerNotAuthenticated {
location: Location::caller(),
});
}
}
}
// Authorization
// check if info_hash is whitelisted
if self.is_whitelisted() && !self.is_info_hash_whitelisted(info_hash).await {
return Err(Error::TorrentNotWhitelisted {
info_hash: *info_hash,
location: Location::caller(),
});
}
Ok(())
}
/// Right now, there is only authorization when the `Tracker` runs in
/// `listed` or `private_listed` modes.
///
/// # Context: Authorization
///
/// # Errors
///
/// Will return an error if the tracker is running in `listed` mode
/// and the infohash is not whitelisted.
pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), Error> {
if !self.is_whitelisted() {
return Ok(());
}
if self.is_info_hash_whitelisted(info_hash).await {
return Ok(());
}
return Err(Error::TorrentNotWhitelisted {
info_hash: *info_hash,
location: Location::caller(),
});
}
/// It adds a torrent to the whitelist.
/// Adding torrents is not relevant to public trackers.
///
/// # Context: Whitelist
///
/// # Errors
///
/// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database.
pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> {
self.add_torrent_to_database_whitelist(info_hash).await?;
self.add_torrent_to_memory_whitelist(info_hash).await;
Ok(())
}
/// It adds a torrent to the whitelist if it has not been whitelisted previously
async fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> {
let is_whitelisted = self.database.is_info_hash_whitelisted(info_hash).await?;
if is_whitelisted {
return Ok(());
}
self.database.add_info_hash_to_whitelist(*info_hash).await?;
Ok(())
}