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
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
use crate::bencode;
use crate::channel::Reply;
use crate::peer::extension::{Error, ExtensionNumber, Result};
use crate::peer::protocol::Message;
use crate::peer::{BitTorrentPeerContext, Peer};
use log::{debug, trace, warn};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::{io, result};

/// The BEP55 holepunch extension message.
#[derive(Debug, Serialize, Deserialize)]
struct HolepunchMessage {
    /// Type of the holepunch message
    #[serde(rename = "msg_type")]
    message_type: MessageType,
    /// IP address family type
    addr_type: AddrType,
    #[serde(with = "serde_bytes")]
    addr: Vec<u8>,
    port: u16,
    #[serde(default, rename = "err_code", skip_serializing_if = "Option::is_none")]
    err_code: Option<ErrorCode>,
}

impl HolepunchMessage {
    /// Try to parse the target address given in the message.
    fn addr(&self) -> Result<SocketAddr> {
        match self.addr_type {
            AddrType::Ipv4 => {
                let octets: [u8; 4] = self.addr.as_slice().try_into().map_err(|_| {
                    Error::Parsing(format!("invalid Ipv4Addr, got {} bytes", self.addr.len()))
                })?;
                Ok(SocketAddr::new(
                    Ipv4Addr::from_octets(octets).into(),
                    self.port,
                ))
            }
            AddrType::Ipv6 => {
                let octets: [u8; 16] = self.addr.as_slice().try_into().map_err(|_| {
                    Error::Parsing(format!("invalid Ipv6Addr, got {} bytes", self.addr.len()))
                })?;
                Ok(SocketAddr::new(
                    Ipv6Addr::from_octets(octets).into(),
                    self.port,
                ))
            }
        }
    }
}

#[repr(u8)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(into = "u8", try_from = "u8")]
enum MessageType {
    Rendezvous = 0,
    Connect = 1,
    Error = 2,
}

impl From<MessageType> for u8 {
    fn from(value: MessageType) -> Self {
        value as u8
    }
}

impl TryFrom<u8> for MessageType {
    type Error = String;

    fn try_from(value: u8) -> result::Result<Self, String> {
        match value {
            0 => Ok(MessageType::Rendezvous),
            1 => Ok(MessageType::Connect),
            2 => Ok(MessageType::Error),
            _ => Err(format!("Invalid MessageType {}", value)),
        }
    }
}

#[repr(u8)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(into = "u8", try_from = "u8")]
enum AddrType {
    Ipv4 = 0,
    Ipv6 = 1,
}

impl From<AddrType> for u8 {
    fn from(value: AddrType) -> Self {
        value as u8
    }
}

impl TryFrom<u8> for AddrType {
    type Error = String;

    fn try_from(value: u8) -> result::Result<Self, String> {
        match value {
            0 => Ok(AddrType::Ipv4),
            1 => Ok(AddrType::Ipv6),
            _ => Err(format!("Invalid AddrType {}", value)),
        }
    }
}

#[repr(u32)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(into = "u32", try_from = "u32")]
enum ErrorCode {
    /// The target endpoint is invalid.
    NoSuchPeer = 1,
    /// The relaying peer is not connected to the target peer.
    NotConnected = 2,
    /// The target peer does not support the holepunch extension.
    NoSupport = 3,
    /// The target endpoint belongs to the relaying peer.
    NoSelf = 4,
}

impl From<ErrorCode> for u32 {
    fn from(value: ErrorCode) -> Self {
        value as u32
    }
}

impl TryFrom<u32> for ErrorCode {
    type Error = String;

    fn try_from(value: u32) -> result::Result<Self, String> {
        match value {
            1 => Ok(ErrorCode::NoSuchPeer),
            2 => Ok(ErrorCode::NotConnected),
            3 => Ok(ErrorCode::NoSupport),
            4 => Ok(ErrorCode::NoSelf),
            _ => Err(format!("Invalid ErrorCode {}", value)),
        }
    }
}

/// The holepunch extension as defined in BEP55
#[derive(Debug)]
pub struct HolepunchExtension {
    /// The outgoing rendezvous requests which have not yet been answered with a connect message.
    pending_rendezvous: HashMap<SocketAddr, Reply<Result<SocketAddr>>>,
}

impl HolepunchExtension {
    pub const NAME: &'static str = "ut_holepunch";

    /// Create a new extension instance.
    pub fn new() -> Self {
        Self {
            pending_rendezvous: Default::default(),
        }
    }

    /// Handle the given extension message payload which has been received from the remote peer.
    pub async fn on_message(&mut self, payload: &[u8], peer: &BitTorrentPeerContext) -> Result<()> {
        let message = bencode::from_bytes::<HolepunchMessage>(payload)?;
        let extension_number = match peer.find_remote_extension_number(Self::NAME) {
            None => return Err(Error::Unsupported),
            Some(e) => e,
        };

        match message.message_type {
            MessageType::Rendezvous => {
                let target_addr = message.addr()?;
                if let Err(error_code) = self.on_rendezvous(target_addr, peer).await {
                    self.send_err_code(error_code, &message, extension_number, peer)
                        .await?;
                }
            }
            MessageType::Connect => {
                if let Err(e) = self.on_connect(&message, peer).await {
                    debug!(
                        "Peer {} {} extension failed to process connect, {}",
                        peer,
                        Self::NAME,
                        e
                    );
                }
            }
            MessageType::Error => self.on_error(&message, peer).await,
        }
        Ok(())
    }

    /// Send a rendezvous message for the target addr to the remote peer.
    pub async fn send_rendezvous(
        &mut self,
        target: SocketAddr,
        response: Reply<Result<SocketAddr>>,
        peer: &BitTorrentPeerContext,
    ) {
        let extension_number = match peer.find_remote_extension_number(Self::NAME) {
            None => {
                response.send(Err(Error::Unsupported));
                return;
            }
            Some(e) => e,
        };
        let addr_type = if target.is_ipv4() {
            AddrType::Ipv4
        } else {
            AddrType::Ipv6
        };
        let addr = match target.ip() {
            IpAddr::V4(ip) => ip.octets().to_vec(),
            IpAddr::V6(ip) => ip.octets().to_vec(),
        };
        let message = match bencode::to_bytes(&HolepunchMessage {
            message_type: MessageType::Rendezvous,
            addr_type,
            addr,
            port: target.port(),
            err_code: None,
        }) {
            Err(e) => {
                debug!(
                    "Peer {} failed to send holepunch rendezvous message to {}",
                    peer, target
                );
                response.send(Err(Error::Parsing(e.to_string())));
                return;
            }
            Ok(e) => e,
        };

        match peer
            .send(Message::ExtendedPayload(extension_number, message))
            .await
        {
            Ok(_) => {
                self.pending_rendezvous.insert(target, response);
                trace!(
                    "Peer {} {} extension stored rendezvous task for {}",
                    peer,
                    Self::NAME,
                    target
                );
            }
            Err(e) => response.send(Err(Error::Io(io::Error::new(io::ErrorKind::Other, e)))),
        }
    }

    /// Try to connect to both the initiating peer and target peer.
    async fn on_rendezvous(
        &self,
        target_addr: SocketAddr,
        peer: &BitTorrentPeerContext,
    ) -> result::Result<(), ErrorCode> {
        // try to find the target peer in the torrent
        let target_peer = match peer.torrent().peer_by_addr(&target_addr).await {
            None => return Err(ErrorCode::NotConnected),
            Some(Peer::BitTorrent(peer)) => peer,
            _ => return Err(ErrorCode::NoSupport),
        };
        // check if the target peer supports the HolePunch extension
        let initiating_extension_number = match peer.find_remote_extension_number(Self::NAME) {
            None => return Err(ErrorCode::NoSupport),
            Some(e) => e,
        };
        let target_extension_number = match target_peer.remote_extension_number(Self::NAME).await {
            None => return Err(ErrorCode::NoSupport),
            Some(e) => e,
        };

        // send connect to the target peer with the remote peer addr
        let connect_message = Self::create_connect_message(peer.addr())?;
        if let Err(e) = target_peer
            .send(Message::ExtendedPayload(
                target_extension_number,
                connect_message,
            ))
            .await
        {
            debug!(
                "Peer {} {} extension failed to send message, {}",
                target_peer,
                Self::NAME,
                e
            );
            return Err(ErrorCode::NotConnected);
        }

        // send a connect to the initiating peer
        let connect_message = Self::create_connect_message(target_peer.addr())?;
        if let Err(e) = peer
            .send(Message::ExtendedPayload(
                initiating_extension_number,
                connect_message,
            ))
            .await
        {
            debug!(
                "Peer {} {} extension failed to send message, {}",
                peer,
                Self::NAME,
                e
            );
            return Err(ErrorCode::NotConnected);
        }

        Ok(())
    }

    /// Try to process a received [MessageType::Connect] message.
    async fn on_connect(
        &mut self,
        message: &HolepunchMessage,
        peer: &BitTorrentPeerContext,
    ) -> Result<()> {
        let addr = message.addr()?;
        // check if we've got a pending rendezvous task for the target addr
        if let Some(response) = self.pending_rendezvous.remove(&addr) {
            trace!(
                "Peer {} {} extension processed rendezvous message for {}",
                peer,
                Self::NAME,
                addr
            );
            response.send(Ok(addr));
        }

        if let Err(e) = peer.torrent().add_peer(addr).await {
            debug!("Peer {} failed to add target peer, {}", peer, e);
        }
        Ok(())
    }

    /// Process a received error message.
    async fn on_error(&mut self, message: &HolepunchMessage, peer: &BitTorrentPeerContext) {
        let addr = match message.addr() {
            Ok(addr) => addr,
            Err(_) => return,
        };
        let err_code = match message.err_code {
            Some(err_code) => err_code,
            None => {
                debug!(
                    "Peer {} {} extension received error without error code, {:?}",
                    peer,
                    Self::NAME,
                    message
                );
                return;
            }
        };
        if let Some(response) = self.pending_rendezvous.remove(&addr) {
            let reason = match err_code {
                ErrorCode::NoSuchPeer => "invalid target peer",
                ErrorCode::NotConnected => "not connected to target peer",
                ErrorCode::NoSupport => "holepunch not supported by target peer",
                ErrorCode::NoSelf => "no self connection allowed",
            };
            response.send(Err(Error::Operation(reason.to_string())));
        } else {
            debug!(
                "Peer {} {} extension received error from {}, {:?}",
                peer,
                Self::NAME,
                addr,
                message.err_code
            );
        }
    }

    async fn send_err_code(
        &self,
        err_code: ErrorCode,
        message: &HolepunchMessage,
        extension_number: ExtensionNumber,
        peer: &BitTorrentPeerContext,
    ) -> Result<()> {
        let payload = bencode::to_bytes(&HolepunchMessage {
            message_type: MessageType::Error,
            addr_type: message.addr_type,
            addr: message.addr.clone(),
            port: message.port,
            err_code: Some(err_code),
        })?;

        peer.send(Message::ExtendedPayload(extension_number, payload))
            .await
            .map_err(|e| Error::Io(io::Error::new(io::ErrorKind::Other, e)))
    }

    fn create_connect_message(addr: &SocketAddr) -> result::Result<Vec<u8>, ErrorCode> {
        let addr_type = if addr.is_ipv4() {
            AddrType::Ipv4
        } else {
            AddrType::Ipv6
        };

        let message = HolepunchMessage {
            message_type: MessageType::Connect,
            addr_type,
            addr: match addr.ip() {
                IpAddr::V4(ip) => ip.octets().to_vec(),
                IpAddr::V6(ip) => ip.octets().to_vec(),
            },
            port: addr.port(),
            err_code: None,
        };
        bencode::to_bytes(&message).map_err(|e| {
            warn!(
                "{} extension failed to serialize message, {}",
                Self::NAME,
                e
            );
            ErrorCode::NoSupport
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod on_message {
        use super::*;
        use crate::operation::ConnectPeersOperation;
        use crate::peer::{
            PeerDiscovery, PeerId, ProtocolExtensionFlags, TcpPeerDiscovery, UtpPeerDiscovery,
        };
        use crate::storage::MemoryStorage;
        use crate::{Torrent, TorrentConfig};
        use std::time::Duration;
        use tempfile::tempdir;

        #[tokio::test]
        async fn test_send_rendezvous() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let initiating_torrent =
                create_torrent(temp_path, UtpPeerDiscovery::new().await.unwrap().into()).await;
            let relay_discovery = UtpPeerDiscovery::new().await.unwrap();
            let relay_torrent =
                create_relay_torrent(temp_path, &[relay_discovery.clone().into()]).await;

            // connect the initiating torrent to the relay torrent
            let (initiating_peer, relay_peer1, _in_socket, _out_socket) = utp_peer_pair!(
                &initiating_torrent,
                &relay_torrent,
                vec![HolepunchExtension::new().into()],
                vec![HolepunchExtension::new().into()],
                ProtocolExtensionFlags::LTEP
            );
            initiating_torrent
                .inner
                .peer_connected(relay_peer1.into())
                .await;
            assert_timeout!(
                Duration::from_millis(250),
                initiating_torrent.active_peer_connections().await == 1,
                "expected the initiating torrent to have 1 active peer connection"
            );
            assert_timeout!(
                Duration::from_millis(550),
                initiating_peer
                    .remote_peer()
                    .await
                    .map(|e| e.extended_handshake)
                    .unwrap_or_default(),
                "expected the extended handshake to have been exchanged"
            );

            // create the target torrent
            let target_torrent =
                create_torrent(temp_path, UtpPeerDiscovery::new().await.unwrap().into()).await;
            let target_addr = SocketAddr::from((
                Ipv4Addr::LOCALHOST,
                target_torrent
                    .peer_port()
                    .await
                    .expect("expected a target torrent peer port"),
            ));

            // connect the relay torrent to the target torrent
            let relay_config = relay_torrent.inner.config().await.unwrap();
            let relay_data_pool = relay_torrent.inner.data_pool().await.unwrap();
            let relay_storage = relay_torrent.inner.storage().await.unwrap();
            let peer = relay_discovery
                .dial(
                    PeerId::new(),
                    target_addr,
                    relay_torrent.inner.peer_port().await,
                    relay_config.client_name().to_string(),
                    relay_torrent.inner.clone(),
                    relay_torrent.metadata().await.unwrap(),
                    relay_data_pool,
                    relay_storage,
                    ProtocolExtensionFlags::LTEP,
                    vec![HolepunchExtension::new().into()],
                    Duration::from_millis(250),
                )
                .await
                .expect("expected the target peer to be dialed");
            relay_torrent.inner.peer_connected(peer.clone()).await;
            assert_timeout!(
                Duration::from_millis(250),
                relay_torrent.active_peer_connections().await == 1,
                "expected the relay torrent to have 1 active peer connection"
            );
            let peer = match peer {
                Peer::BitTorrent(e) => e,
                _ => unreachable!(),
            };
            assert_timeout!(
                Duration::from_millis(550),
                peer.remote_peer()
                    .await
                    .map(|e| e.extended_handshake)
                    .unwrap_or_default(),
                "expected the extended handshake to have been exchanged"
            );

            // send the rendezvous message from the initiating peer to the relay peer
            let response = initiating_peer.holepunch(target_addr).await;
            // await the rendezvous response
            let result = timeout!(
                Duration::from_secs(1),
                response,
                "expected the rendezvous to complete"
            );
            assert_eq!(Ok(target_addr), result);
            assert_timeout!(
                Duration::from_secs(3),
                initiating_torrent.active_peer_connections().await == 2,
                "expected the HolePunch to succeed"
            );
        }

        #[tokio::test]
        async fn test_rendezvous_not_supported_by_target() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let initiating_torrent =
                create_torrent(temp_path, UtpPeerDiscovery::new().await.unwrap().into()).await;
            let relay_discovery = TcpPeerDiscovery::new().await.unwrap();
            let relay_torrent = create_relay_torrent(
                temp_path,
                &[
                    relay_discovery.clone().into(),
                    UtpPeerDiscovery::new().await.unwrap().into(),
                ],
            )
            .await;

            // connect the initiating torrent to the relay torrent
            let (initiating_peer, relay_peer1, _in_socket, _out_socket) = utp_peer_pair!(
                &initiating_torrent,
                &relay_torrent,
                vec![HolepunchExtension::new().into()],
                vec![HolepunchExtension::new().into()],
                ProtocolExtensionFlags::LTEP
            );
            initiating_torrent
                .inner
                .peer_connected(relay_peer1.into())
                .await;
            assert_timeout!(
                Duration::from_millis(250),
                initiating_torrent.active_peer_connections().await == 1,
                "expected the initiating torrent to have 1 active peer connection"
            );
            assert_timeout!(
                Duration::from_millis(550),
                initiating_peer
                    .remote_peer()
                    .await
                    .map(|e| e.extended_handshake)
                    .unwrap_or_default(),
                "expected the extended handshake to have been exchanged"
            );

            // create the target torrent
            let target_torrent =
                create_torrent(temp_path, TcpPeerDiscovery::new().await.unwrap().into()).await;
            let target_addr = SocketAddr::from((
                Ipv4Addr::LOCALHOST,
                target_torrent
                    .peer_port()
                    .await
                    .expect("expected a target torrent peer port"),
            ));

            // connect the relay torrent to the target torrent
            let relay_config = relay_torrent.inner.config().await.unwrap();
            let relay_data_pool = relay_torrent.inner.data_pool().await.unwrap();
            let relay_storage = relay_torrent.inner.storage().await.unwrap();
            let extensions = vec![HolepunchExtension::new().into()];
            let peer = relay_discovery
                .dial(
                    PeerId::new(),
                    target_addr,
                    relay_torrent.inner.peer_port().await,
                    relay_config.client_name().to_string(),
                    relay_torrent.inner.clone(),
                    relay_torrent.metadata().await.unwrap(),
                    relay_data_pool,
                    relay_storage,
                    ProtocolExtensionFlags::LTEP,
                    extensions,
                    Duration::from_millis(250),
                )
                .await
                .unwrap();
            relay_torrent.inner.peer_connected(peer.clone()).await;
            assert_timeout!(
                Duration::from_millis(250),
                relay_torrent.active_peer_connections().await == 1,
                "expected the relay torrent to have 1 active peer connection"
            );
            let peer = match peer {
                Peer::BitTorrent(e) => e,
                _ => unreachable!(),
            };
            assert_timeout!(
                Duration::from_millis(550),
                peer.remote_peer()
                    .await
                    .map(|e| e.extended_handshake)
                    .unwrap_or_default(),
                "expected the extended handshake to have been exchanged"
            );

            // send the rendezvous message from the initiating peer to the relay peer
            let response = initiating_peer.holepunch(target_addr).await;
            // await the rendezvous response
            let result = timeout!(
                Duration::from_secs(1),
                response,
                "expected the rendezvous to complete"
            );
            match result {
                Err(e) => match e {
                    Error::Operation(e) => assert_eq!(e, "holepunch not supported by target peer"),
                    _ => assert!(false, "expected Error::Operation, but got {:?}", e),
                },
                _ => assert!(
                    false,
                    "expected the rendezvous to fail, but got {:?}",
                    result
                ),
            }
        }

        async fn create_torrent(temp_path: &str, discovery: PeerDiscovery) -> Torrent {
            Torrent::request()
                .metadata(metadata!("debian-udp.torrent"))
                .config(TorrentConfig::builder().path(temp_path).build())
                .protocol_extensions(ProtocolExtensionFlags::LTEP)
                .extension(|| HolepunchExtension::new().into())
                .operations(vec![ConnectPeersOperation::new(false).into()])
                .peer_discovery(discovery)
                .storage(|_| MemoryStorage::new().into())
                .build()
                .unwrap()
        }

        async fn create_relay_torrent(temp_path: &str, discoveries: &[PeerDiscovery]) -> Torrent {
            Torrent::request()
                .metadata(metadata!("debian-udp.torrent"))
                .config(TorrentConfig::builder().path(temp_path).build())
                .protocol_extensions(ProtocolExtensionFlags::LTEP)
                .extension(|| HolepunchExtension::new().into())
                .operations(vec![])
                .peer_discoveries(discoveries.to_vec())
                .storage(|_| MemoryStorage::new().into())
                .build()
                .unwrap()
        }
    }
}