aria2-protocol 0.3.0

Multi-protocol networking stack for aria2-rust: HTTP/HTTPS client, FTP/SFTP, full BitTorrent (DHT/PEX/MSE), and Metalink V3/V4 parser
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
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tracing::{debug, info};

use super::state::PeerState;
use crate::bittorrent::message::handshake::Handshake;
use crate::bittorrent::message::types::{BtMessage, PieceBlockRequest};
use crate::bittorrent::peer::id;

#[derive(Debug, Clone, PartialEq)]
pub struct PeerAddr {
    pub ip: String,
    pub port: u16,
}

impl PeerAddr {
    pub fn new(ip: &str, port: u16) -> Self {
        Self {
            ip: ip.to_string(),
            port,
        }
    }

    /// Compact peer format sizes for IPv4 and IPv6.
    pub const COMPACT_SIZE_V4: usize = 6;
    pub const COMPACT_SIZE_V6: usize = 18;

    /// Decode from IPv4 compact format (4-byte IP + 2-byte port = 6 bytes).
    pub fn from_compact(data: &[u8]) -> Option<Self> {
        if data.len() < Self::COMPACT_SIZE_V4 {
            return None;
        }
        let ip = format!("{}.{}.{}.{}", data[0], data[1], data[2], data[3]);
        let port = u16::from_be_bytes([data[4], data[5]]);
        Some(Self { ip, port })
    }

    /// Decode from IPv6 compact format (16-byte IP + 2-byte port = 18 bytes).
    pub fn from_compact_v6(data: &[u8]) -> Option<Self> {
        if data.len() < Self::COMPACT_SIZE_V6 {
            return None;
        }
        let ip_bytes: [u8; 16] = data[..16].try_into().ok()?;
        let ipv6 = std::net::Ipv6Addr::from(ip_bytes);
        let port = u16::from_be_bytes([data[16], data[17]]);
        Some(Self {
            ip: ipv6.to_string(),
            port,
        })
    }

    pub fn to_socket_addr(&self) -> std::net::SocketAddr {
        format!("{}:{}", self.ip, self.port)
            .parse()
            .unwrap_or_else(|_| "0.0.0.0:0".parse().unwrap())
    }

    /// Encode to IPv4 compact format (4-byte IP + 2-byte port = 6 bytes).
    pub fn to_compact(&self) -> [u8; 6] {
        let mut buf = [0u8; 6];
        if let Ok(addr) = self.ip.parse::<std::net::Ipv4Addr>() {
            buf[..4].copy_from_slice(&addr.octets());
            buf[4..6].copy_from_slice(&self.port.to_be_bytes());
        }
        buf
    }

    /// Encode to IPv6 compact format (16-byte IP + 2-byte port = 18 bytes).
    pub fn to_compact_v6(&self) -> Option<[u8; 18]> {
        let addr = self.ip.parse::<std::net::Ipv6Addr>().ok()?;
        let mut buf = [0u8; 18];
        buf[..16].copy_from_slice(&addr.octets());
        buf[16..18].copy_from_slice(&self.port.to_be_bytes());
        Some(buf)
    }
}

pub struct PeerConnection {
    stream: TcpStream,
    remote_addr: Option<std::net::SocketAddr>,
    pub state: PeerState,
    pub remote_peer_id: Option<[u8; 20]>,
    pub remote_bitfield: Vec<u8>,
}

impl PeerConnection {
    pub async fn connect(addr: &PeerAddr, info_hash: &[u8; 20]) -> Result<Self, String> {
        let socket_addr = addr.to_socket_addr();
        debug!("Connecting to peer: {}", socket_addr);

        let stream = tokio::time::timeout(
            std::time::Duration::from_secs(15),
            tokio::net::TcpStream::connect(&socket_addr),
        )
        .await
        .map_err(|_| format!("Peer connection timeout: {}", socket_addr))?
        .map_err(|e| format!("Peer connection failed: {}", e))?;

        Self::from_stream(stream, info_hash).await
    }

    pub async fn from_stream(
        mut stream: tokio::net::TcpStream,
        info_hash: &[u8; 20],
    ) -> Result<Self, String> {
        let my_peer_id = id::generate_peer_id();
        let handshake = Handshake::new(info_hash, &my_peer_id);
        let handshake_bytes = handshake.to_bytes();

        stream
            .write_all(&handshake_bytes)
            .await
            .map_err(|e| format!("Failed to send handshake: {}", e))?;

        let remote_hs = Self::read_remote_handshake(&mut stream, info_hash).await?;
        Self::finish_handshake(stream, remote_hs)
    }

    /// Complete the server side of a BitTorrent handshake.
    ///
    /// Incoming peers send their handshake first.  The listener must validate
    /// the torrent identity before admitting the endpoint to PeerStorage, then
    /// reply with our handshake and keep the stream for the upload/download
    /// session.
    pub async fn from_incoming_stream(
        mut stream: tokio::net::TcpStream,
        info_hash: &[u8; 20],
        local_peer_id: &[u8; 20],
    ) -> Result<Self, String> {
        let mut response = [0u8; 68];
        read_exact_with_timeout(&mut stream, &mut response).await?;
        Self::from_incoming_handshake(stream, response, info_hash, local_peer_id).await
    }

    /// Complete a plain incoming handshake when the first 20 bytes were
    /// already consumed by a shared listener for route selection.
    pub async fn from_incoming_stream_with_prefix(
        mut stream: tokio::net::TcpStream,
        prefix: [u8; 20],
        info_hash: &[u8; 20],
        local_peer_id: &[u8; 20],
    ) -> Result<Self, String> {
        let mut response = [0u8; 68];
        response[..20].copy_from_slice(&prefix);
        read_exact_with_timeout(&mut stream, &mut response[20..]).await?;
        Self::from_incoming_handshake(stream, response, info_hash, local_peer_id).await
    }

    /// Complete a plain incoming handshake after a shared listener consumed
    /// the complete handshake for routing.
    pub async fn from_incoming_handshake_bytes(
        stream: tokio::net::TcpStream,
        response: [u8; 68],
        info_hash: &[u8; 20],
        local_peer_id: &[u8; 20],
    ) -> Result<Self, String> {
        Self::from_incoming_handshake(stream, response, info_hash, local_peer_id).await
    }

    async fn from_incoming_handshake(
        mut stream: tokio::net::TcpStream,
        response: [u8; 68],
        info_hash: &[u8; 20],
        local_peer_id: &[u8; 20],
    ) -> Result<Self, String> {
        let remote_hs = Handshake::parse(&response)?;
        if remote_hs.info_hash != *info_hash {
            return Err("info_hash mismatch".to_string());
        }
        let handshake = Handshake::new(info_hash, local_peer_id);
        stream
            .write_all(&handshake.to_bytes())
            .await
            .map_err(|e| format!("Failed to send handshake response: {}", e))?;
        Self::finish_handshake(stream, remote_hs)
    }

    async fn read_remote_handshake(
        stream: &mut tokio::net::TcpStream,
        info_hash: &[u8; 20],
    ) -> Result<Handshake, String> {
        let mut response = [0u8; 68];
        match tokio::time::timeout(
            std::time::Duration::from_secs(30),
            stream.read_exact(&mut response),
        )
        .await
        {
            Ok(Ok(_)) => {}
            Ok(Err(e)) => return Err(format!("Failed to read handshake response: {}", e)),
            Err(_) => return Err("Handshake response timeout".to_string()),
        }

        let remote_hs = Handshake::parse(&response)?;
        if remote_hs.info_hash != *info_hash {
            return Err("info_hash mismatch".to_string());
        }
        Ok(remote_hs)
    }

    fn finish_handshake(
        stream: tokio::net::TcpStream,
        remote_hs: Handshake,
    ) -> Result<Self, String> {
        info!(
            "Peer handshake successful: peer_id={}",
            remote_hs.peer_id_str()
        );
        let remote_addr = stream.peer_addr().ok();
        Ok(Self {
            stream,
            remote_addr,
            state: PeerState::new(),
            remote_peer_id: Some(remote_hs.peer_id),
            remote_bitfield: vec![],
        })
    }

    pub fn from_stream_with_peer(stream: tokio::net::TcpStream, peer_id: [u8; 20]) -> Self {
        let remote_addr = stream.peer_addr().ok();
        Self {
            stream,
            remote_addr,
            state: PeerState::new(),
            remote_peer_id: Some(peer_id),
            remote_bitfield: vec![],
        }
    }

    pub async fn send_message(&mut self, message: &BtMessage) -> Result<(), String> {
        use crate::bittorrent::message::serializer::serialize;
        let data = serialize(message);

        self.stream
            .write_all(&data)
            .await
            .map_err(|e| format!("Failed to send message: {}", e))?;
        self.stream
            .flush()
            .await
            .map_err(|e| format!("Failed to flush buffer: {}", e))?;

        debug!("Sent message: {:?}", message.message_id());
        Ok(())
    }

    pub async fn read_message(&mut self) -> Result<Option<BtMessage>, String> {
        use crate::bittorrent::message::factory::parse_message;

        let mut len_buf = [0u8; 4];
        match self.stream.read_exact(&mut len_buf).await {
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
            Err(e) => return Err(format!("Failed to read message length: {}", e)),
        }

        let msg_len = u32::from_be_bytes(len_buf) as usize;
        if msg_len == 0 {
            return Ok(Some(BtMessage::KeepAlive));
        }

        let mut payload_buf = vec![0u8; msg_len];
        self.stream
            .read_exact(&mut payload_buf)
            .await
            .map_err(|e| format!("Failed to read message body: {}", e))?;

        let mut full_msg = vec![0u8; 4 + msg_len];
        full_msg[0..4].copy_from_slice(&len_buf);
        full_msg[4..].copy_from_slice(&payload_buf);

        parse_message(&full_msg)
    }

    pub async fn send_choke(&mut self) -> Result<(), String> {
        self.state.am_choking = true;
        self.send_message(&BtMessage::Choke).await
    }

    pub async fn send_unchoke(&mut self) -> Result<(), String> {
        self.state.am_choking = false;
        self.send_message(&BtMessage::Unchoke).await
    }

    pub async fn send_interested(&mut self) -> Result<(), String> {
        self.state.am_interested = true;
        self.send_message(&BtMessage::Interested).await
    }

    pub async fn send_not_interested(&mut self) -> Result<(), String> {
        self.state.am_interested = false;
        self.send_message(&BtMessage::NotInterested).await
    }

    pub async fn send_have(&mut self, piece_index: u32) -> Result<(), String> {
        self.send_message(&BtMessage::Have { piece_index }).await
    }

    pub async fn send_request(&mut self, req: PieceBlockRequest) -> Result<(), String> {
        self.state.add_request(req.clone());
        self.send_message(&BtMessage::Request { request: req })
            .await
    }

    pub async fn send_cancel(&mut self, req: &PieceBlockRequest) -> Result<(), String> {
        self.state.remove_request(req);
        self.send_message(&BtMessage::Cancel {
            request: req.clone(),
        })
        .await
    }

    pub async fn send_bitfield(&mut self, bitfield: Vec<u8>) -> Result<(), String> {
        self.remote_bitfield = bitfield.clone();
        self.send_message(&BtMessage::Bitfield { data: bitfield })
            .await
    }

    pub fn is_connected(&self) -> bool {
        self.remote_peer_id.is_some()
    }

    pub fn remote_addr(&self) -> Option<std::net::SocketAddr> {
        self.remote_addr
    }

    pub async fn stream_write(&mut self, data: &[u8]) -> Result<(), String> {
        self.stream
            .write_all(data)
            .await
            .map_err(|e| format!("Stream write failed: {}", e))
    }

    pub async fn stream_flush(&mut self) -> Result<(), String> {
        self.stream
            .flush()
            .await
            .map_err(|e| format!("Stream flush failed: {}", e))
    }

    pub async fn stream_read_exact(&mut self, buf: &mut [u8]) -> Result<(), String> {
        self.stream
            .read_exact(buf)
            .await
            .map(|_| ())
            .map_err(|e| format!("Stream read failed: {}", e))
    }
}

async fn read_exact_with_timeout(
    stream: &mut tokio::net::TcpStream,
    buffer: &mut [u8],
) -> Result<(), String> {
    match tokio::time::timeout(
        std::time::Duration::from_secs(30),
        stream.read_exact(buffer),
    )
    .await
    {
        Ok(Ok(_)) => Ok(()),
        Ok(Err(error)) => Err(format!("Failed to read handshake: {error}")),
        Err(_) => Err("Handshake response timeout".to_string()),
    }
}

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

    #[test]
    fn test_peer_addr_compact_roundtrip() {
        let addr = PeerAddr::new("192.168.1.100", 6881);
        let compact = addr.to_compact();
        let parsed = PeerAddr::from_compact(&compact).unwrap();
        assert_eq!(parsed.ip, addr.ip);
        assert_eq!(parsed.port, addr.port);
    }

    #[test]
    fn test_peer_addr_from_compact() {
        let data: [u8; 6] = [127, 0, 0, 1, 0x1A, 0x0B];
        let addr = PeerAddr::from_compact(&data).unwrap();
        assert_eq!(addr.ip, "127.0.0.1");
        assert_eq!(addr.port, 6667);
    }

    #[test]
    fn test_peer_addr_too_short() {
        assert!(PeerAddr::from_compact(&[1, 2, 3]).is_none());
    }

    #[test]
    fn test_peer_addr_from_compact_v6() {
        // ::1 (loopback) + port 6881
        let mut data = [0u8; 18];
        data[15] = 1; // ::1 in 16 bytes
        data[16..18].copy_from_slice(&6881u16.to_be_bytes());
        let addr = PeerAddr::from_compact_v6(&data).unwrap();
        assert_eq!(addr.ip, "::1");
        assert_eq!(addr.port, 6881);
    }

    #[test]
    fn test_peer_addr_compact_v6_roundtrip() {
        let addr = PeerAddr::new("2001:db8::1", 6881);
        let compact = addr.to_compact_v6().unwrap();
        let parsed = PeerAddr::from_compact_v6(&compact).unwrap();
        assert_eq!(parsed.ip, addr.ip);
        assert_eq!(parsed.port, addr.port);
    }

    #[test]
    fn test_peer_addr_compact_v6_too_short() {
        assert!(PeerAddr::from_compact_v6(&[0u8; 17]).is_none());
    }

    #[test]
    fn test_peer_addr_to_compact_v6_non_ipv6() {
        let addr = PeerAddr::new("192.168.1.1", 6881);
        assert!(addr.to_compact_v6().is_none());
    }

    #[test]
    fn test_peer_addr_from_compact_v6_full_addr() {
        // 2001:0db8:85a3:0000:0000:8a2e:0370:7334 + port 1234
        let mut data = [0u8; 18];
        data[0..2].copy_from_slice(&[0x20, 0x01]);
        data[2..4].copy_from_slice(&[0x0d, 0xb8]);
        data[4..6].copy_from_slice(&[0x85, 0xa3]);
        data[6..8].copy_from_slice(&[0x00, 0x00]);
        data[8..10].copy_from_slice(&[0x00, 0x00]);
        data[10..12].copy_from_slice(&[0x8a, 0x2e]);
        data[12..14].copy_from_slice(&[0x03, 0x70]);
        data[14..16].copy_from_slice(&[0x73, 0x34]);
        data[16..18].copy_from_slice(&1234u16.to_be_bytes());

        let addr = PeerAddr::from_compact_v6(&data).unwrap();
        assert_eq!(addr.ip, "2001:db8:85a3::8a2e:370:7334");
        assert_eq!(addr.port, 1234);
    }
}