forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.rs
More file actions
198 lines (175 loc) · 6.13 KB
/
handlers.rs
File metadata and controls
198 lines (175 loc) · 6.13 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
use std::collections::HashMap;
use std::convert::Infallible;
use std::net::IpAddr;
use std::sync::Arc;
use log::debug;
use warp::http::Response;
use warp::{reject, Rejection, Reply};
use crate::http::{
AnnounceRequest, AnnounceResponse, ErrorResponse, Peer, ScrapeRequest, ScrapeResponse, ScrapeResponseEntry, ServerError,
WebResult,
};
use crate::peer::TorrentPeer;
use crate::tracker::key::AuthKey;
use crate::tracker::statistics::TrackerStatisticsEvent;
use crate::tracker::torrent::{TorrentError, TorrentStats};
use crate::tracker::tracker::TorrentTracker;
use crate::InfoHash;
/// Authenticate InfoHash using optional AuthKey
pub async fn authenticate(
info_hash: &InfoHash,
auth_key: &Option<AuthKey>,
tracker: Arc<TorrentTracker>,
) -> Result<(), ServerError> {
match tracker.authenticate_request(info_hash, auth_key).await {
Ok(_) => Ok(()),
Err(e) => {
let err = match e {
TorrentError::TorrentNotWhitelisted => ServerError::TorrentNotWhitelisted,
TorrentError::PeerNotAuthenticated => ServerError::PeerNotAuthenticated,
TorrentError::PeerKeyNotValid => ServerError::PeerKeyNotValid,
TorrentError::NoPeersFound => ServerError::NoPeersFound,
TorrentError::CouldNotSendResponse => ServerError::InternalServerError,
TorrentError::InvalidInfoHash => ServerError::InvalidInfoHash,
};
Err(err)
}
}
}
/// Handle announce request
pub async fn handle_announce(
announce_request: AnnounceRequest,
auth_key: Option<AuthKey>,
tracker: Arc<TorrentTracker>,
) -> WebResult<impl Reply> {
if let Err(e) = authenticate(&announce_request.info_hash, &auth_key, tracker.clone()).await {
return Err(reject::custom(e));
}
debug!("{:?}", announce_request);
let peer =
TorrentPeer::from_http_announce_request(&announce_request, announce_request.peer_addr, tracker.config.get_ext_ip());
let torrent_stats = tracker
.update_torrent_with_peer_and_get_stats(&announce_request.info_hash, &peer)
.await;
// get all torrent peers excluding the peer_addr
let peers = tracker.get_torrent_peers(&announce_request.info_hash, &peer.peer_addr).await;
let announce_interval = tracker.config.announce_interval;
// send stats event
match announce_request.peer_addr {
IpAddr::V4(_) => {
tracker.send_stats_event(TrackerStatisticsEvent::Tcp4Announce).await;
}
IpAddr::V6(_) => {
tracker.send_stats_event(TrackerStatisticsEvent::Tcp6Announce).await;
}
}
send_announce_response(
&announce_request,
torrent_stats,
peers,
announce_interval,
tracker.config.min_announce_interval,
)
}
/// Handle scrape request
pub async fn handle_scrape(
scrape_request: ScrapeRequest,
auth_key: Option<AuthKey>,
tracker: Arc<TorrentTracker>,
) -> WebResult<impl Reply> {
let mut files: HashMap<InfoHash, ScrapeResponseEntry> = HashMap::new();
let db = tracker.get_torrents().await;
for info_hash in scrape_request.info_hashes.iter() {
let scrape_entry = match db.get(&info_hash) {
Some(torrent_info) => {
if authenticate(info_hash, &auth_key, tracker.clone()).await.is_ok() {
let (seeders, completed, leechers) = torrent_info.get_stats();
ScrapeResponseEntry {
complete: seeders,
downloaded: completed,
incomplete: leechers,
}
} else {
ScrapeResponseEntry {
complete: 0,
downloaded: 0,
incomplete: 0,
}
}
}
None => ScrapeResponseEntry {
complete: 0,
downloaded: 0,
incomplete: 0,
},
};
files.insert(info_hash.clone(), scrape_entry);
}
// send stats event
match scrape_request.peer_addr {
IpAddr::V4(_) => {
tracker.send_stats_event(TrackerStatisticsEvent::Tcp4Scrape).await;
}
IpAddr::V6(_) => {
tracker.send_stats_event(TrackerStatisticsEvent::Tcp6Scrape).await;
}
}
send_scrape_response(files)
}
/// Send announce response
fn send_announce_response(
announce_request: &AnnounceRequest,
torrent_stats: TorrentStats,
peers: Vec<TorrentPeer>,
interval: u32,
interval_min: u32,
) -> WebResult<impl Reply> {
let http_peers: Vec<Peer> = peers
.iter()
.map(|peer| Peer {
peer_id: peer.peer_id.to_string(),
ip: peer.peer_addr.ip(),
port: peer.peer_addr.port(),
})
.collect();
let res = AnnounceResponse {
interval,
interval_min,
complete: torrent_stats.seeders,
incomplete: torrent_stats.leechers,
peers: http_peers,
};
// check for compact response request
if let Some(1) = announce_request.compact {
match res.write_compact() {
Ok(body) => Ok(Response::new(body)),
Err(_) => Err(reject::custom(ServerError::InternalServerError)),
}
} else {
Ok(Response::new(res.write().into()))
}
}
/// Send scrape response
fn send_scrape_response(files: HashMap<InfoHash, ScrapeResponseEntry>) -> WebResult<impl Reply> {
let res = ScrapeResponse { files };
match res.write() {
Ok(body) => Ok(Response::new(body)),
Err(_) => Err(reject::custom(ServerError::InternalServerError)),
}
}
/// Handle all server errors and send error reply
pub async fn send_error(r: Rejection) -> std::result::Result<impl Reply, Infallible> {
let body = if let Some(server_error) = r.find::<ServerError>() {
debug!("{:?}", server_error);
ErrorResponse {
failure_reason: server_error.to_string(),
}
.write()
} else {
ErrorResponse {
failure_reason: ServerError::InternalServerError.to_string(),
}
.write()
};
Ok(Response::new(body))
}