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
use crate::peer::protocol::{Handshake, Message, UtpStream};
use crate::peer::{ConnectionProtocol, Error, Metrics, PeerId, PeerResponse, Result};
use byteorder::BigEndian;
use byteorder::ByteOrder;
use derive_more::Display;
use log::{debug, trace, warn};
use std::fmt::{Debug, Display, Formatter};
use std::io;
use std::net::SocketAddr;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, WriteHalf};
use tokio::net::TcpStream;
use tokio::select;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;

/// The bytes length of an expected handshake message
const HANDSHAKE_MESSAGE_LENGTH: usize = 68;

/// The connection between our peer and the remote peer.
#[derive(Debug)]
pub enum PeerConnection {
    Tcp(InnerConnection<TcpStream>),
    Utp(InnerConnection<UtpStream>),
}

impl PeerConnection {
    /// Create a new TCP peer connection.
    pub fn new_tcp(id: PeerId, addr: SocketAddr, stream: TcpStream, metrics: Metrics) -> Self {
        let cancellation_token = CancellationToken::new();
        let (sender, receiver) = unbounded_channel();
        let (reader, writer) = tokio::io::split(stream);

        let mut reader = PeerReader::new(
            id,
            addr,
            ConnectionProtocol::Tcp,
            reader,
            sender,
            metrics,
            cancellation_token.clone(),
        );
        spawn!("PeerReader::run", async move { reader.run().await });

        Self::Tcp(InnerConnection::<TcpStream> {
            id,
            addr,
            receiver: Mutex::new(receiver),
            writer: PeerWriter::new(writer),
            cancellation_token,
        })
    }

    /// Create a new uTP peer connection.
    pub fn new_utp(id: PeerId, addr: SocketAddr, stream: UtpStream, metrics: Metrics) -> Self {
        let cancellation_token = CancellationToken::new();
        let (sender, receiver) = unbounded_channel();
        let (reader, writer) = tokio::io::split(stream);

        let mut reader = PeerReader::new(
            id,
            addr,
            ConnectionProtocol::Utp,
            reader,
            sender,
            metrics,
            cancellation_token.clone(),
        );
        spawn!("PeerReader::run", async move { reader.run().await });

        Self::Utp(InnerConnection::<UtpStream> {
            id,
            addr,
            receiver: Mutex::new(receiver),
            writer: PeerWriter::new(writer),
            cancellation_token,
        })
    }

    /// Returns the protocol of the connection.
    pub fn protocol(&self) -> ConnectionProtocol {
        match self {
            PeerConnection::Tcp(_) => ConnectionProtocol::Tcp,
            PeerConnection::Utp(_) => ConnectionProtocol::Utp,
        }
    }

    /// Try to receive an incoming message from the remote peer through the connection.
    pub async fn recv(&self) -> Option<PeerResponse> {
        match self {
            PeerConnection::Tcp(conn) => conn.recv().await,
            PeerConnection::Utp(conn) => conn.recv().await,
        }
    }

    /// Try to write a message to the remote peer.
    ///
    /// ## Remark
    ///
    /// The caller should handle the write timeout.
    pub async fn write(&self, bytes: &[u8]) -> Result<()> {
        match self {
            PeerConnection::Tcp(conn) => conn.write(bytes).await,
            PeerConnection::Utp(conn) => conn.write(bytes).await,
        }
    }

    /// Returns `true` if the peer connection stream is closed.
    pub fn is_closed(&self) -> bool {
        match self {
            PeerConnection::Tcp(conn) => conn.is_closed(),
            PeerConnection::Utp(conn) => conn.is_closed(),
        }
    }

    /// Try to close the connection with the remote peer.
    pub async fn close(&self) -> Result<()> {
        match self {
            PeerConnection::Tcp(conn) => conn.close().await,
            PeerConnection::Utp(conn) => conn.close().await,
        }
    }
}

impl Display for PeerConnection {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let conn_type = match self {
            PeerConnection::Tcp(_) => "Tcp",
            PeerConnection::Utp(_) => "Utp",
        };
        let conn_info = match self {
            PeerConnection::Tcp(conn) => conn.to_string(),
            PeerConnection::Utp(conn) => conn.to_string(),
        };
        write!(f, "{}:{}", conn_type, conn_info)
    }
}

#[derive(Debug, Display)]
#[display("{}[{}]", id, addr)]
pub struct InnerConnection<W>
where
    W: AsyncWrite + Debug + Send,
{
    /// The unique peer id of the connection
    id: PeerId,
    /// The remote peer address
    addr: SocketAddr,
    /// The receiver of the peer connection reader
    receiver: Mutex<UnboundedReceiver<PeerReaderEvent>>,
    /// The writer of the connection
    writer: PeerWriter<W>,
    cancellation_token: CancellationToken,
}

impl<W> InnerConnection<W>
where
    W: AsyncWrite + Debug + Send,
{
    async fn recv(&self) -> Option<PeerResponse> {
        if let Some(event) = self.receiver.lock().await.recv().await {
            return Some(match event {
                PeerReaderEvent::Handshake(bytes) => {
                    match Handshake::from_bytes(&self.addr, bytes.as_slice()) {
                        Ok(e) => PeerResponse::Handshake(e),
                        Err(e) => PeerResponse::Error(e),
                    }
                }
                PeerReaderEvent::HandshakeFailed(e) => PeerResponse::Error(e),
                PeerReaderEvent::Message(message) => PeerResponse::Message(message),
                PeerReaderEvent::Closed => {
                    let _ = self.close().await;
                    PeerResponse::Closed
                }
            });
        }

        None
    }

    async fn write<'a>(&'a self, bytes: &'a [u8]) -> Result<()> {
        if self.cancellation_token.is_cancelled() {
            return Err(Error::Closed);
        }

        // make sure that we interrupt any writing operations if the connection is forcefully closed
        select! {
            _ = self.cancellation_token.cancelled() => Err(Error::Closed),
            result = self.writer.write(bytes) => result,
        }
    }

    fn is_closed(&self) -> bool {
        self.cancellation_token.is_cancelled()
    }

    async fn close(&self) -> Result<()> {
        trace!("Peer {} connection is closing", self);
        self.cancellation_token.cancel();
        self.writer.shutdown().await;
        Ok(())
    }
}

impl<W> Drop for InnerConnection<W>
where
    W: AsyncWrite + Debug + Send,
{
    fn drop(&mut self) {
        trace!("Peer {} connection is being dropped", self);
        self.cancellation_token.cancel();
    }
}

#[derive(Debug)]
struct PeerWriter<W>
where
    W: AsyncWrite + Debug,
{
    writer: Mutex<WriteHalf<W>>,
}

impl<W> PeerWriter<W>
where
    W: AsyncWrite + Debug,
{
    fn new(writer: WriteHalf<W>) -> Self {
        Self {
            writer: Mutex::new(writer),
        }
    }

    async fn write<'a>(&'a self, bytes: &'a [u8]) -> Result<()> {
        let mut writer = self.writer.lock().await;
        writer.write_all(bytes.as_ref()).await?;
        writer.flush().await?;
        Ok(())
    }

    async fn shutdown(&self) {
        let _ = self.writer.lock().await.shutdown().await;
    }
}

unsafe impl<W> Send for PeerWriter<W> where W: AsyncWrite + Debug {}

/// The events of the peer reader.
#[derive(Debug)]
enum PeerReaderEvent {
    /// Received a handshake bytes from the remote peer.
    Handshake(Vec<u8>),
    /// Handshake failed to be read from the remote peer.
    HandshakeFailed(Error),
    /// Received a message from the remote peer.
    Message(Message),
    /// The connection was closed by the remote peer.
    Closed,
}

/// The peer reader is a buffered reader which reads messages from the peer connection stream.
#[derive(Debug, Display)]
#[display("{}[{}:{}]", id, protocol, addr)]
struct PeerReader<R>
where
    R: AsyncRead + Unpin,
{
    id: PeerId,
    addr: SocketAddr,
    protocol: ConnectionProtocol,
    reader: BufReader<R>,
    sender: UnboundedSender<PeerReaderEvent>,
    metrics: Metrics,
    cancellation_token: CancellationToken,
}

impl<R> PeerReader<R>
where
    R: AsyncRead + Unpin,
{
    /// Create a new reader for the peer connection reader stream.
    fn new(
        id: PeerId,
        addr: SocketAddr,
        protocol: ConnectionProtocol,
        reader: R,
        sender: UnboundedSender<PeerReaderEvent>,
        metrics: Metrics,
        cancellation_token: CancellationToken,
    ) -> Self {
        Self {
            id,
            addr,
            protocol,
            reader: BufReader::new(reader),
            sender,
            metrics,
            cancellation_token,
        }
    }

    /// Run the main loop of the reader.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn run(&mut self) {
        // as initial message, try to read the handshake
        let cancellation_token = self.cancellation_token.clone();
        select! {
            _ = cancellation_token.cancelled() => return,
            read_result = self.read(HANDSHAKE_MESSAGE_LENGTH) => {
                match read_result {
                    Ok(buffer) => {
                        Self::send (
                            self.to_string().as_str(),
                            &self.sender,
                            PeerReaderEvent::Handshake(buffer)
                        );
                    }
                    Err(e) => {
                        debug!("Peer {} failed to read handshake, {}", self, e);
                        Self::send (
                            self.to_string().as_str(),
                            &self.sender,
                            PeerReaderEvent::HandshakeFailed(e),
                        );
                        return;
                    },
                }
            }
        }

        loop {
            let mut buffer = vec![0u8; 4];

            select! {
                _ = self.cancellation_token.cancelled() => break,
                read_result = self.reader.read_exact(&mut buffer) => {
                    match read_result {
                        Ok(0) => {
                            trace!("Peer {} reader received EOF", self);
                            break
                        },
                        Ok(buffer_size) => {
                            if let Err(e)  = self.read_next(&buffer, buffer_size).await {
                                if e != Error::Closed {
                                    warn!("Peer {} failed to read message, {}", self, e);
                                }
                                break
                            }
                        },
                        Err(e) => {
                            if e.kind() != io::ErrorKind::UnexpectedEof {
                                warn!("Peer {} reader encountered an error, {}", self, Error::from(e));
                            }
                            break
                        }
                    }
                }
            }
        }

        trace!("Peer {} main reader loop ended", self);
        let self_info = self.to_string();
        Self::send(self_info.as_str(), &self.sender, PeerReaderEvent::Closed);
    }

    /// Try to read a specific number of bytes from the stream.
    ///
    /// # Arguments
    ///
    /// * `len` - The number of bytes to read from the stream.
    async fn read(&mut self, len: usize) -> Result<Vec<u8>> {
        let mut buffer = vec![0u8; len];
        let read_result = self.reader.read_exact(&mut buffer).await;

        match read_result {
            Ok(0) => Err(Error::Closed),
            Ok(_) => {
                self.metrics.bytes_in.inc_by(len as u64);
                Ok(buffer)
            }
            Err(e) => Err(Error::Io(e)),
        }
    }

    async fn read_next(&mut self, buffer: &[u8], buffer_size: usize) -> Result<()> {
        // we expect to receive the incoming message length as a BigEndian
        if buffer_size != 4 {
            return Err(Error::InvalidLength(4, buffer_size as u32));
        }

        let len = BigEndian::read_u32(buffer);
        let bytes = self.read(len as usize).await?;

        // we want to unblock the reader thread as soon as possible
        // so we're going to move this whole process into a new separate thread
        let self_info = self.to_string();
        let sender = self.sender.clone();
        tokio::spawn(async move {
            match Message::try_from(bytes.as_ref()) {
                Ok(msg) => {
                    Self::send(self_info.as_str(), &sender, PeerReaderEvent::Message(msg));
                }
                Err(e) => warn!(
                    "Peer {} reader received invalid message payload, {}",
                    self_info, e
                ),
            }
        });

        Ok(())
    }

    fn send(self_info: &str, sender: &UnboundedSender<PeerReaderEvent>, event: PeerReaderEvent) {
        if let Err(e) = sender.send(event) {
            trace!("Peer {} reader failed to send event, {}", self_info, e)
        }
    }
}

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

    use crate::peer::protocol::Piece;
    use crate::peer::protocol::UtpPacketCapture;
    use crate::peer::ProtocolExtensionFlags;
    use crate::InfoHash;
    use std::net::Ipv4Addr;
    use std::str::FromStr;
    use tokio::net::TcpListener;

    mod utp {
        use super::*;

        #[tokio::test]
        async fn test_peer_connection_receive() {
            init_logger!();
            let data = "Mauris venenatis malesuada tellus vel imperdiet. Pellentesque quis blandit tellus. Aenean commodo neque id sem dictum aliquam at vel arcu.";
            let hash = "urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7";
            let info_hash = InfoHash::from_str(hash).unwrap();
            let peer_id = PeerId::new();
            let protocol_extension_flags = ProtocolExtensionFlags::LTEP;
            let incoming_capture = UtpPacketCapture::new();
            let outgoing_capture = UtpPacketCapture::new();
            let (incoming_socket, outgoing_socket) = create_utp_socket_pair!(
                vec![incoming_capture.clone().into()],
                vec![outgoing_capture.clone().into()]
            );
            let (incoming_stream, mut outgoing_stream) =
                create_utp_stream_pair!(&incoming_socket, &outgoing_socket);
            let connection = PeerConnection::new_utp(
                peer_id,
                incoming_stream.addr(),
                incoming_stream,
                Metrics::new(),
            );

            // write the handshake to the receiving connection
            let handshake = Handshake::new(info_hash.clone(), peer_id, protocol_extension_flags);
            let handshake_bytes = TryInto::<Vec<u8>>::try_into(handshake).unwrap();
            outgoing_stream.write_all(&handshake_bytes).await.unwrap();
            outgoing_stream.flush().await.unwrap();

            // try to get the handshake from the receiving stream
            let result = connection
                .recv()
                .await
                .expect("expected to receive the handshake");
            if let PeerResponse::Handshake(result) = result {
                assert_eq!(
                    info_hash, result.info_hash,
                    "expected the info hash to match"
                );
                assert_eq!(peer_id, result.peer_id, "expected the peer id to match");
                assert_eq!(
                    protocol_extension_flags, result.supported_extensions,
                    "expected the supported protocol extensions to match"
                );
            } else {
                assert!(
                    false,
                    "expected PeerResponse::Handshake, but got {:?} instead",
                    result
                );
            }

            // write some random data to the receiving connection
            let message = Message::Piece(Piece {
                index: 0,
                begin: 0,
                data: data.as_bytes().to_vec(),
            });
            let bytes = message_as_bytes(&message);
            outgoing_stream.write_all(&bytes).await.unwrap();
            outgoing_stream.flush().await.unwrap();

            // try to read the message from the receiving stream
            let result = connection
                .recv()
                .await
                .expect("expected to receive the message");
            if let PeerResponse::Message(result) = result {
                assert_eq!(message, result, "expected the message to match");
            } else {
                assert!(
                    false,
                    "expected PeerResponse::Message, but got {:?} instead",
                    result
                );
            }
        }

        #[tokio::test]
        async fn test_peer_connection_write() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let peer_id = PeerId::new();
            let protocol_extensions = ProtocolExtensionFlags::Fast;
            let handshake = Handshake::new(info_hash.clone(), peer_id, protocol_extensions);
            let handshake_bytes = TryInto::<Vec<u8>>::try_into(handshake).unwrap();
            let (incoming_socket, outgoing_socket) = create_utp_socket_pair!();
            let (mut incoming_stream, outgoing_stream) =
                create_utp_stream_pair!(&incoming_socket, &outgoing_socket);
            let outgoing_stream_addr = outgoing_stream.addr();
            let connection = PeerConnection::new_utp(
                peer_id,
                outgoing_stream_addr,
                outgoing_stream,
                Metrics::new(),
            );

            connection
                .write(handshake_bytes.as_slice())
                .await
                .expect("expected the handshake to have been written");

            let mut buffer = vec![0u8; HANDSHAKE_MESSAGE_LENGTH];
            let _ = timeout!(
                Duration::from_millis(500),
                incoming_stream.read_exact(&mut buffer),
                "expected to have received the handshake bytes"
            )
            .unwrap();

            let result = Handshake::from_bytes(&outgoing_stream_addr, buffer.as_slice()).unwrap();
            assert_eq!(
                info_hash, result.info_hash,
                "expected the info hash to match"
            );
            assert_eq!(peer_id, result.peer_id, "expected the peer id to match");
            assert_eq!(
                protocol_extensions, result.supported_extensions,
                "expected the supported protocol extensions to match"
            );
        }
    }

    mod peer_reader {
        use super::*;
        use std::pin::Pin;
        use std::task::{Context, Poll};
        use tokio::io::ReadBuf;
        use tokio::time;
        use tokio::time::Duration;

        struct HandshakeFailureReader;

        impl AsyncRead for HandshakeFailureReader {
            fn poll_read(
                self: Pin<&mut Self>,
                _: &mut Context<'_>,
                _: &mut ReadBuf<'_>,
            ) -> Poll<io::Result<()>> {
                Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::ConnectionReset,
                    "handshake failed",
                )))
            }
        }

        #[tokio::test]
        async fn test_handshake_failure() {
            init_logger!();
            let (sender, mut rx) = unbounded_channel();
            let mut reader = PeerReader::new(
                PeerId::new(),
                SocketAddr::from(([127, 0, 0, 1], 6881)),
                ConnectionProtocol::Tcp,
                HandshakeFailureReader {},
                sender,
                Metrics::new(),
                CancellationToken::new(),
            );

            let _ = select! {
                _ = time::sleep(Duration::from_millis(250)) => Err(Error::Io(io::Error::new(io::ErrorKind::TimedOut, "expected the reader main loop to have ended"))),
                _ = reader.run() => Ok(()),
            }.unwrap();

            let result = timeout!(
                Duration::from_millis(500),
                rx.recv(),
                "expected a peer reader event"
            )
            .unwrap();
            if let PeerReaderEvent::HandshakeFailed(_) = result {
            } else {
                assert!(
                    false,
                    "expected PeerReaderEvent::HandshakeFailed, but got {:?} instead",
                    result
                )
            }
        }
    }

    #[tokio::test]
    async fn test_peer_connection_shutdown() {
        init_logger!();
        let message = "Lorem ipsum dolor";
        let incoming = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
            .await
            .expect("expected the tcp listener to bind");
        let incoming_addr = incoming
            .local_addr()
            .expect("expected the tcp listener to have been bound to a local address");

        tokio::spawn(async move { while let Ok((_stream, _addr)) = incoming.accept().await {} });

        let outgoing_stream = TcpStream::connect(incoming_addr)
            .await
            .expect("expected to create an outgoing connection");
        let connection = PeerConnection::new_tcp(
            PeerId::new(),
            incoming_addr,
            outgoing_stream,
            Metrics::new(),
        );

        connection
            .close()
            .await
            .expect("expected the connection to close");
        let result = connection.write(message.as_bytes()).await;

        assert_eq!(
            Err(Error::Closed),
            result,
            "expected the connection write function to return Error::Closed"
        );
    }

    fn message_as_bytes(message: &Message) -> Vec<u8> {
        let mut bytes = vec![0u8; 4];
        let message_bytes = TryInto::<Vec<u8>>::try_into(message.clone()).unwrap();

        BigEndian::write_u32(&mut bytes[..4], message_bytes.len() as u32);
        bytes.extend_from_slice(message_bytes.as_slice());

        bytes
    }
}