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
use crate::peer::extension::PeerExtension;
use crate::peer::{
ConnectionProtocol, Peer, PeerId, PeerStream, ProtocolExtensionFlags, Result, TcpPeerDiscovery,
UtpPeerDiscovery,
};
use crate::storage::Storage;
use crate::torrent::InnerTorrent;
use crate::torrent_data::DataPool;
use crate::TorrentMetadata;
use async_trait::async_trait;
#[cfg(test)]
pub use mock::*;
use std::fmt::Debug;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
/// A received peer entry incoming connection.
#[derive(Debug)]
pub struct PeerEntry {
/// The peer address
pub socket_addr: SocketAddr,
/// The peer incoming tcp stream
pub stream: PeerStream,
}
impl PeerEntry {
/// Returns the connection protocol of the peer entry.
pub fn protocol(&self) -> ConnectionProtocol {
match &self.stream {
PeerStream::Tcp(_) => ConnectionProtocol::Tcp,
PeerStream::Utp(_) => ConnectionProtocol::Utp,
}
}
}
impl PartialEq for PeerStream {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(PeerStream::Tcp(_), PeerStream::Tcp(_)) => true,
(PeerStream::Utp(_), PeerStream::Utp(_)) => true,
_ => false,
}
}
}
/// The discovery strategy for creating outgoing and receiving incoming peer connections.
#[derive(Debug, Clone)]
pub enum PeerDiscovery {
Tcp(TcpPeerDiscovery),
Utp(UtpPeerDiscovery),
Other(Arc<dyn Discovery>),
}
impl PeerDiscovery {
/// Returns the address on which this peer discovery is listening on.
pub fn addr(&self) -> &SocketAddr {
match self {
PeerDiscovery::Tcp(discovery) => discovery.addr(),
PeerDiscovery::Utp(discovery) => discovery.addr(),
PeerDiscovery::Other(discovery) => discovery.addr(),
}
}
/// Returns the underlying protocol of the peer discovery.
pub fn protocol(&self) -> ConnectionProtocol {
match self {
PeerDiscovery::Tcp(_) => ConnectionProtocol::Tcp,
PeerDiscovery::Utp(_) => ConnectionProtocol::Utp,
PeerDiscovery::Other(discovery) => discovery.protocol(),
}
}
/// Try to dial (_create outgoing connection with_) to the target peer address.
pub async fn dial(
&self,
peer_id: PeerId,
peer_addr: SocketAddr,
peer_port: Option<u16>,
peer_client_name: impl Into<String>,
torrent: InnerTorrent,
metadata: TorrentMetadata,
data_pool: DataPool,
storage: Storage,
protocol_extensions: ProtocolExtensionFlags,
extensions: Vec<PeerExtension>,
connection_timeout: Duration,
) -> Result<Peer> {
match self {
PeerDiscovery::Tcp(discovery) => {
discovery
.dial(
peer_id,
peer_addr,
peer_port,
peer_client_name.into(),
torrent,
metadata,
data_pool,
storage,
protocol_extensions,
extensions,
connection_timeout,
)
.await
}
PeerDiscovery::Utp(discovery) => {
discovery
.dial(
peer_id,
peer_addr,
peer_port,
peer_client_name.into(),
torrent,
metadata,
data_pool,
storage,
protocol_extensions,
extensions,
connection_timeout,
)
.await
}
PeerDiscovery::Other(discovery) => {
discovery
.dial(
peer_id,
peer_addr,
peer_port,
peer_client_name.into(),
torrent,
metadata,
data_pool,
storage,
protocol_extensions,
extensions,
connection_timeout,
)
.await
}
}
}
/// Try to receive an incoming peer connection from the peer discovery.
/// Returns [None] if the peer discovery connection has been closed.
pub async fn recv(&self) -> Option<PeerEntry> {
match self {
PeerDiscovery::Tcp(discovery) => discovery.recv().await,
PeerDiscovery::Utp(discovery) => discovery.recv().await,
PeerDiscovery::Other(discovery) => discovery.recv().await,
}
}
/// Close the peer discovery connection.
pub fn close(&self) {
match self {
PeerDiscovery::Tcp(discovery) => discovery.close(),
PeerDiscovery::Utp(discovery) => discovery.close(),
PeerDiscovery::Other(discovery) => discovery.close(),
}
}
}
impl From<TcpPeerDiscovery> for PeerDiscovery {
fn from(discovery: TcpPeerDiscovery) -> Self {
Self::Tcp(discovery)
}
}
impl From<UtpPeerDiscovery> for PeerDiscovery {
fn from(discovery: UtpPeerDiscovery) -> Self {
Self::Utp(discovery)
}
}
impl<D> From<D> for PeerDiscovery
where
D: Discovery + 'static,
{
fn from(discovery: D) -> Self {
Self::Other(Arc::from(discovery))
}
}
/// A peer discovery is responsible for discovering outgoing and incoming peer connections.
#[async_trait]
pub trait Discovery: Debug + Send + Sync {
/// Get the address on which this peer listener is listening on.
fn addr(&self) -> &SocketAddr;
/// Returns the underlying protocol of the peer discovery.
fn protocol(&self) -> ConnectionProtocol;
/// Tries to dial (_create outgoing connection with_) the given peer address.
///
/// # Arguments
///
/// * `peer_id` - The unique peer identifier of the torrent.
/// * `peer_addr` - The address of the peer to dial.
/// * `peer_port` - The peer port on which the torrent is listening for incoming connections.
/// * `peer_client_name` - The client name of the peer.
/// * `torrent` - The torrent to use for the connection.
/// * `metadata` - The current known metadata of the torrent.
/// * `data_pool` - The torrent data pool to use for the connection.
/// * `storage` - The storage of the torrent.
/// * `protocol_extensions` - The peer protocol extensions that should be enabled for the connection. (BEP4)
/// * `extensions` - The peer extensions that should be enabled for the connection. (BEP10)
/// * `connection_timeout` - The timeout of a peer connection.
///
/// # Returns
///
/// It returns a [TorrentPeer] if the connection was established.
async fn dial(
&self,
peer_id: PeerId,
peer_addr: SocketAddr,
peer_port: Option<u16>,
peer_client_name: String,
torrent: InnerTorrent,
metadata: TorrentMetadata,
data_pool: DataPool,
storage: Storage,
protocol_extensions: ProtocolExtensionFlags,
extensions: Vec<PeerExtension>,
connection_timeout: Duration,
) -> Result<Peer>;
/// Receive an incoming peer connection from the peer listener.
///
/// # Returns
///
/// It returns [None] when the listener has been dropped.
async fn recv(&self) -> Option<PeerEntry>;
/// Close the peer listener.
/// This will prevent any new incoming connections from being received.
fn close(&self);
}
#[cfg(test)]
pub mod mock {
use super::*;
use mockall::mock;
mock! {
#[derive(Debug)]
pub Discovery {}
#[async_trait]
impl Discovery for Discovery {
fn addr(&self) -> &SocketAddr;
fn protocol(&self) -> ConnectionProtocol;
async fn dial(
&self,
peer_id: PeerId,
peer_addr: SocketAddr,
peer_port: Option<u16>,
peer_client_name: String,
torrent: InnerTorrent,
metadata: TorrentMetadata,
data_pool: DataPool,
storage: Storage,
protocol_extensions: ProtocolExtensionFlags,
extensions: Vec<PeerExtension>,
connection_timeout: Duration,
) -> Result<Peer>;
async fn recv(&self) -> Option<PeerEntry>;
fn close(&self);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_discovery_addr() {
let addr = SocketAddr::from(([127, 0, 0, 1], 6881));
let mut discovery = MockDiscovery::new();
discovery.expect_addr().times(1).return_const(addr);
let discovery: PeerDiscovery = discovery.into();
let result = discovery.addr();
assert_eq!(&addr, result);
}
#[test]
fn test_discovery_protocol() {
let mut discovery = MockDiscovery::new();
discovery
.expect_protocol()
.times(1)
.return_const(ConnectionProtocol::Tcp);
let discovery: PeerDiscovery = discovery.into();
let result = discovery.protocol();
assert_eq!(ConnectionProtocol::Tcp, result);
}
#[test]
fn test_discovery_close() {
let mut discovery = MockDiscovery::new();
discovery.expect_close().times(1).return_const(());
let discovery: PeerDiscovery = discovery.into();
discovery.close();
}
}