fx-torrent 0.10.3

FX Torrent is a feature rich Bittorrent protocol implementation written in rust supporting Linux, MacOS and Windows.
Documentation
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
use crate::peer::extension::{Error, ExtensionNumber, Result};
use crate::peer::protocol::Message;
use crate::peer::{
    BitTorrentPeerContext, ConnectionDirection, ConnectionProtocol, Peer, ProtocolExtensionFlags,
};
use crate::{bencode, CompactIpv4Addrs, CompactIpv6Addrs, InnerTorrent, TorrentEvent};
use bitmask_enum::bitmask;
use fx_callback::{Callback, Subscription};
use log::{debug, trace, warn};
use serde::{Deserialize, Serialize};
use std::hash::Hash;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;

/// The Peer Exchange message.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct PexMessage {
    /// The added ipv4 peer addresses
    #[serde(default)]
    pub added: CompactIpv4Addrs,
    /// The flags of the added ipv4 peer addresses
    #[serde(default, rename = "added.f", with = "pex_flags")]
    pub added_flags: Vec<PexFlag>,
    /// The added ipv6 peer addresses
    #[serde(default)]
    pub added6: CompactIpv6Addrs,
    /// The flags of the added ipv6 peer addresses
    #[serde(default, rename = "added6.f", with = "pex_flags")]
    pub added6_flags: Vec<PexFlag>,
    /// The dropped ipv4 peer addresses
    #[serde(default)]
    pub dropped: CompactIpv4Addrs,
    /// The dropped ipv6 peer addresses
    #[serde(default)]
    pub dropped6: CompactIpv6Addrs,
}

impl PexMessage {
    /// Get all the discovered peers by the swarm
    fn discovered_peers(&self) -> Vec<SocketAddr> {
        let mut peers: Vec<SocketAddr> = self.added.iter().map(|e| SocketAddr::from(e)).collect();
        peers.extend(self.added6.iter().map(|e| SocketAddr::from(e)));
        peers
    }

    /// Get all the dropped peers from the swarm
    fn dropped_peers(&self) -> Vec<SocketAddr> {
        let mut peers: Vec<SocketAddr> = self.dropped.iter().map(|e| SocketAddr::from(e)).collect();
        peers.extend(self.dropped6.iter().map(|e| SocketAddr::from(e)));
        peers
    }

    /// Check if the message is empty.
    /// It returns `true` if the message is empty, else `false`.
    fn is_empty(&self) -> bool {
        self.added.is_empty()
            && self.added6.is_empty()
            && self.dropped.is_empty()
            && self.dropped6.is_empty()
    }
}

#[bitmask(u8)]
#[bitmask_config(vec_debug, flags_iter)]
pub enum PexFlag {
    /// prefers encryption, as indicated by e field in extension handshake
    EncryptionPreferred = 0x01,
    /// seed/upload_only
    UploadOnly = 0x02,
    /// supports utp
    UtpSupported = 0x04,
    /// peer indicated ut_holepunch support in extension handshake
    HolepunchSupported = 0x08,
    /// outgoing connection
    OutgoingConnection = 0x10,
}

impl Serialize for PexFlag {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serde::Serialize::serialize(&self.bits(), serializer)
    }
}

impl<'de> Deserialize<'de> for PexFlag {
    fn deserialize<D>(deserializer: D) -> std::result::Result<PexFlag, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value: u8 = Deserialize::deserialize(deserializer)?;
        Ok(PexFlag::from(value))
    }
}

/// The PEX extensions as defined in BEP11.
#[derive(Debug)]
pub struct PexExtension {
    /// The pool which is used to manage the pex peer addresses
    pool: PexPool,
    torrent_event_receiver: Option<Subscription<TorrentEvent>>,
    interval: Duration,
    last_informed: Instant,
    initialized: bool,
    pex_supported: bool,
}

impl PexExtension {
    pub const NAME: &'static str = "ut_pex";

    /// Create a new pex extension with the given announce interval.
    pub fn new(interval: Duration) -> Self {
        Self {
            pool: PexPool::new(),
            torrent_event_receiver: None,
            interval,
            last_informed: Instant::now(),
            initialized: false,
            pex_supported: false,
        }
    }

    /// Process an incoming extension message payload which has been received from the remote peer.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn on_message(&self, payload: &[u8], peer: &BitTorrentPeerContext) -> Result<()> {
        let message: PexMessage = bencode::from_bytes(payload)?;
        debug!("Peer {} received PEX message {:?}", peer, message);

        let discovered_peers = message.discovered_peers();
        if discovered_peers.len() > 0 {
            peer.torrent().add_peers(discovered_peers).await;
        }

        let dropped_peers = message.dropped_peers();
        if dropped_peers.len() > 0 {
            peer.torrent().decrease_peer_priority(dropped_peers).await;
        }

        Ok(())
    }

    /// Invoked once per tick (typically once per second), providing a tick interval for the extension
    /// to process data.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn tick(&mut self, peer: &BitTorrentPeerContext) {
        if self.initialized && !self.pex_supported {
            return;
        }

        self.initialize(peer);
        self.process_torrent_events(peer.torrent()).await;
        self.inform_peer(peer).await;
    }

    fn initialize(&mut self, peer: &BitTorrentPeerContext) {
        if self.initialized || peer.remote_peer().is_none() {
            return;
        }
        // early exit if the peer doesn't support LTEP
        if !peer
            .remote_peer()
            .map(|e| e.protocol_extensions.contains(ProtocolExtensionFlags::LTEP))
            .unwrap_or_default()
        {
            self.initialized = true;
            return;
        }
        // wait for the extended handshake to be completed
        if !peer
            .remote_peer()
            .map(|e| e.extended_handshake)
            .unwrap_or_default()
        {
            return;
        }
        if !peer.is_extension_supported(Self::NAME) {
            self.initialized = true;
            return;
        }

        self.torrent_event_receiver = Some(peer.torrent().subscribe());
        self.pex_supported = true;
        self.initialized = true;
        trace!("Peer {} PEX has been initialized", peer);
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn process_torrent_events(&mut self, torrent: &InnerTorrent) {
        let events = {
            let receiver = match self.torrent_event_receiver.as_mut() {
                None => return,
                Some(r) => r,
            };

            let mut events = vec![];
            while let Ok(event) = receiver.try_recv() {
                events.push(event.clone());
            }
            events
        };

        // offload to a separate task, to prevent a deadlock between the torrent and peer
        // FIXME: improve the pex peers
        let torrent = torrent.clone();
        let pool = self.pool.clone();
        spawn!("PexExtension::process_torrent_events", async move {
            for event in events {
                match &*event {
                    TorrentEvent::PeerConnected(peer_addr) => {
                        let peer = match torrent.peer(peer_addr).await {
                            None => continue,
                            Some(peer) => peer,
                        };
                        pool.peer_added(peer).await
                    }
                    TorrentEvent::PeerDisconnected(peer_addr) => {
                        let peer = match torrent.peer(peer_addr).await {
                            None => continue,
                            Some(peer) => peer,
                        };

                        pool.peer_removed(peer).await
                    }
                    _ => {}
                }
            }
        });
    }

    async fn inform_peer(&mut self, peer: &BitTorrentPeerContext) {
        if !self.initialized || self.last_informed.elapsed() < self.interval {
            return;
        }
        let extension_number = match peer.find_remote_extension_number(Self::NAME) {
            None => return,
            Some(e) => e,
        };

        if self.pool.inform_peer(&extension_number, peer).await {
            self.last_informed = Instant::now();
        }
    }
}

#[derive(Debug, Clone)]
struct PexPool {
    inner: Arc<Mutex<InnerPool>>,
}

impl PexPool {
    fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(InnerPool {
                added_peers: Default::default(),
                dropped_peers: Default::default(),
            })),
        }
    }

    async fn peer_added(&self, peer: Peer) {
        let mut flags = PexFlag::none();

        if peer.connection_type() == &ConnectionDirection::Outbound {
            flags |= PexFlag::OutgoingConnection;
        }
        if peer.protocol() == &ConnectionProtocol::Utp {
            flags |= PexFlag::UtpSupported;
        }

        self.inner.lock().await.added_peers.push(PexPeer {
            addr: *peer.addr(),
            flags,
        });
        trace!("Pex peer {} (added) to pool", peer.addr());
    }

    async fn peer_removed(&self, peer: Peer) {
        let mut flags = PexFlag::none();

        if peer.connection_type() == &ConnectionDirection::Outbound {
            flags |= PexFlag::OutgoingConnection;
        }
        if peer.protocol() == &ConnectionProtocol::Utp {
            flags |= PexFlag::UtpSupported;
        }

        self.inner.lock().await.dropped_peers.push(PexPeer {
            addr: *peer.addr(),
            flags,
        });
        trace!("Pex peer {} (dropped) to pool", peer.addr());
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn inform_peer(
        &mut self,
        extension_number: &ExtensionNumber,
        peer: &BitTorrentPeerContext,
    ) -> bool {
        let message = self.message().await;
        if message.is_empty() {
            return false;
        }

        let message_info = format!("{:?}", message);
        match self.try_inform_peer(message, extension_number, peer).await {
            Ok(_) => {
                debug!("Peer {} sent PEX message {}", peer, message_info);
                true
            }
            Err(e) => {
                debug!(
                    "Peer {} failed to send PEX message {}, {}",
                    peer, message_info, e
                );
                false
            }
        }
    }

    async fn try_inform_peer(
        &self,
        message: PexMessage,
        extension_number: &ExtensionNumber,
        peer: &BitTorrentPeerContext,
    ) -> Result<()> {
        let message_bytes = bencode::to_bytes(&message)?;

        peer.send(Message::ExtendedPayload(
            extension_number.clone(),
            message_bytes,
        ))
        .await
        .map_err(|e| Error::Operation(e.to_string()))
    }

    /// Get the PEX message to send to the peer and reset the pool.
    async fn message(&mut self) -> PexMessage {
        let added_peers = std::mem::take(&mut self.inner.lock().await.added_peers);
        let dropped_peers = std::mem::take(&mut self.inner.lock().await.dropped_peers);
        let mut added = vec![];
        let mut added_flags = vec![];
        let mut added6 = vec![];
        let mut added6_flags = vec![];
        let mut dropped = vec![];
        let mut dropped6 = vec![];

        for peer in added_peers {
            if peer.addr.is_ipv4() {
                match peer.addr.try_into() {
                    Ok(compact) => {
                        added.push(compact);
                        added_flags.push(peer.flags);
                    }
                    Err(e) => warn!("Failed to convert peer address to compact, {}", e),
                }
            } else {
                match peer.addr.try_into() {
                    Ok(compact) => {
                        added6.push(compact);
                        added6_flags.push(peer.flags);
                    }
                    Err(e) => warn!("Failed to convert peer address to compact, {}", e),
                }
            }
        }
        for peer in dropped_peers {
            if peer.addr.is_ipv4() {
                match peer.addr.try_into() {
                    Ok(compact) => dropped.push(compact),
                    Err(e) => warn!("Failed to convert peer address to compact, {}", e),
                }
            } else {
                match peer.addr.try_into() {
                    Ok(compact) => dropped6.push(compact),
                    Err(e) => warn!("Failed to convert peer address to compact, {}", e),
                }
            }
        }

        PexMessage {
            added: added.into(),
            added_flags,
            added6: added6.into(),
            added6_flags,
            dropped: dropped.into(),
            dropped6: dropped6.into(),
        }
    }
}

#[derive(Debug)]
struct InnerPool {
    added_peers: Vec<PexPeer>,
    dropped_peers: Vec<PexPeer>,
}

#[derive(Debug)]
struct PexPeer {
    addr: SocketAddr,
    flags: PexFlag,
}

mod pex_flags {
    use super::*;
    use serde::Deserializer;

    struct PexFlagsVisitor;

    impl<'de> serde::de::Visitor<'de> for PexFlagsVisitor {
        type Value = Vec<PexFlag>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("expected a bytes array or sequence of bytes")
        }

        fn visit_bytes<E>(self, value: &[u8]) -> std::result::Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            let mut flags = Vec::new();

            for byte in value {
                flags.push(PexFlag::from(*byte));
            }

            Ok(flags)
        }

        fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
        where
            A: serde::de::SeqAccess<'de>,
        {
            let mut flags = Vec::new();

            while let Some(byte) = seq.next_element::<u8>()? {
                flags.push(PexFlag::from(byte));
            }

            Ok(flags)
        }
    }

    pub fn serialize<S>(flags: &[PexFlag], serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let bytes = flags.iter().map(|f| f.bits()).collect::<Vec<u8>>();
        serde::Serialize::serialize(&bytes, serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> std::result::Result<Vec<PexFlag>, D::Error>
    where
        D: Deserializer<'de>,
    {
        D::deserialize_any(deserializer, PexFlagsVisitor {})
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::peer::ProtocolExtensionFlags;
    use crate::storage::MemoryStorage;
    use crate::{Torrent, TorrentConfig};
    use tempfile::tempdir;

    #[test]
    fn test_pex_flags() {
        let expected_result = PexFlag::UtpSupported | PexFlag::OutgoingConnection;
        let bytes = bencode::to_bytes(&expected_result).unwrap();

        let result = bencode::from_bytes::<PexFlag>(&bytes).unwrap();
        assert_eq!(expected_result, result);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_on_message() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        let source_torrent = create_pex_torrent(temp_path).await;
        let in_between_torrent = create_pex_torrent(temp_path).await;
        let target_torrent = create_pex_torrent(temp_path).await;

        // connect the source to the in-between torrent
        let (source, in_between) = tcp_peer_pair!(
            &source_torrent,
            &in_between_torrent,
            vec![PexExtension::new(Duration::from_millis(500)).into()],
            vec![PexExtension::new(Duration::from_millis(500)).into()],
            ProtocolExtensionFlags::LTEP
        );
        source_torrent.inner.peer_connected(source.into()).await;
        in_between_torrent
            .inner
            .peer_connected(in_between.into())
            .await;
        assert_timeout!(
            Duration::from_millis(500),
            source_torrent.active_peer_connections().await == 1,
            "expected the source torrent to be connected to the in-between"
        );

        // connect the in-between to the target torrent
        let (in_between, target) = tcp_peer_pair!(
            &in_between_torrent,
            &target_torrent,
            vec![PexExtension::new(Duration::from_millis(500)).into()],
            vec![PexExtension::new(Duration::from_millis(500)).into()],
            ProtocolExtensionFlags::LTEP
        );
        in_between_torrent
            .inner
            .peer_connected(in_between.into())
            .await;
        target_torrent.inner.peer_connected(target.into()).await;

        // wait for the pex extension to exchange target addr to the source
        assert_timeout!(
            Duration::from_secs(4),
            source_torrent.inner.peer_addrs_len().await == 2,
            "expected the source torrent to be connected to the target"
        );
    }

    async fn create_pex_torrent(temp_path: &str) -> Torrent {
        Torrent::request()
            .metadata(metadata!("debian-udp.torrent"))
            .config(TorrentConfig::builder().path(temp_path).build())
            .protocol_extensions(ProtocolExtensionFlags::LTEP)
            .extension(|| PexExtension::new(Duration::from_secs(1)).into())
            .operations(vec![])
            .storage(|_| MemoryStorage::new().into())
            .build()
            .unwrap()
    }
}