aria2-protocol 0.3.10

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
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
//! uTP socket implementation
//!
//! Implements the UDP-based socket for uTP protocol as specified in BEP 29.
//! Manages multiple uTP connections over a single UDP socket.

use std::collections::HashMap;
use std::net::{SocketAddr, UdpSocket};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};

use crate::bittorrent::utp::connection::{ConnectionError, ConnectionState, UtpConnection};
use crate::bittorrent::utp::packet::{PacketType, UtpPacket, UtpPacketError};
use crate::bittorrent::utp::timer::{TimerManager, TimerType};

mod close;
mod options;
#[cfg(test)]
mod tests;
mod timers;
pub use options::{
    DEFAULT_CONNECT_TIMEOUT, DEFAULT_IDLE_TIMEOUT, DEFAULT_KEEPALIVE_INTERVAL,
    DEFAULT_MAX_CONNECTIONS, UtpSocketOptions,
};

/// Maximum receive buffer size for UDP
const MAX_UDP_RECV_BUFFER: usize = 65535;

fn find_available_connection_id(
    start: u16,
    mut is_occupied: impl FnMut(u16) -> bool,
) -> Option<u16> {
    (0..=u16::MAX)
        .map(|offset| start.wrapping_add(offset))
        .find(|connection_id| !is_occupied(*connection_id))
}

/// Errors that can occur during socket operations
#[derive(Debug, thiserror::Error)]
pub enum UtpSocketError {
    #[error("Failed to bind UDP socket: {0}")]
    BindFailed(std::io::Error),

    #[error("Failed to send packet: {0}")]
    SendFailed(std::io::Error),

    #[error("Failed to receive packet: {0}")]
    RecvFailed(std::io::Error),

    #[error("Connection error: {0}")]
    ConnectionError(#[from] ConnectionError),

    #[error("Packet error: {0}")]
    PacketError(#[from] UtpPacketError),

    #[error("Maximum connections reached")]
    MaxConnectionsReached,

    #[error("Connection not found: {0}")]
    ConnectionNotFound(u16),

    #[error("Address not found for connection: {0}")]
    AddressNotFound(u16),

    #[error("Socket closed")]
    SocketClosed,

    #[error("Invalid packet from {addr}: {reason}")]
    InvalidPacket { addr: SocketAddr, reason: String },

    #[error("Timeout: {0}")]
    Timeout(String),
}

/// uTP socket that manages multiple connections over UDP
///
/// This is the main interface for uTP communication. It wraps a UDP socket
/// and provides connection-oriented semantics with congestion control.
pub struct UtpSocket {
    /// Underlying UDP socket
    socket: UdpSocket,
    /// Tokio registration for async read readiness.
    ///
    /// The synchronous socket remains the owner of the protocol state. This
    /// handle is initialized only from an async receive path and shares the
    /// same OS socket, allowing callers to await readiness without polling.
    async_socket: OnceLock<Arc<tokio::net::UdpSocket>>,
    /// Active connections indexed by connection ID
    connections: HashMap<u16, UtpConnection>,
    /// Timer management for all connections
    timers: TimerManager,
    /// Local socket address
    local_addr: SocketAddr,
    timestamp_origin: Instant,
    options: UtpSocketOptions,
    /// Whether the socket is closed
    is_closed: bool,
    /// Receive buffer
    recv_buffer: Vec<u8>,
}

impl UtpSocket {
    /// Create a new uTP socket bound to the specified address
    pub fn bind(addr: &str) -> Result<Self, UtpSocketError> {
        let address = addr.parse::<SocketAddr>().map_err(|error| {
            UtpSocketError::BindFailed(std::io::Error::new(std::io::ErrorKind::InvalidInput, error))
        })?;
        Self::bind_addr(address)
    }

    /// Create a new uTP socket bound to an explicit local socket address.
    pub fn bind_addr(addr: SocketAddr) -> Result<Self, UtpSocketError> {
        Self::bind_addr_with_options(addr, UtpSocketOptions::default())
    }

    /// Bind a uTP socket with explicit resource and connection-lifecycle settings.
    pub fn bind_addr_with_options(
        addr: SocketAddr,
        options: UtpSocketOptions,
    ) -> Result<Self, UtpSocketError> {
        let socket = UdpSocket::bind(addr).map_err(UtpSocketError::BindFailed)?;
        let local_addr = socket.local_addr().map_err(UtpSocketError::BindFailed)?;
        socket
            .set_nonblocking(true)
            .map_err(UtpSocketError::BindFailed)?;

        let timers = TimerManager::with_defaults(
            options.connect_timeout(),
            options.idle_timeout(),
            options.keepalive_interval(),
        );

        Ok(Self {
            socket,
            async_socket: OnceLock::new(),
            connections: HashMap::new(),
            timers,
            local_addr,
            timestamp_origin: Instant::now(),
            options,
            is_closed: false,
            recv_buffer: vec![0u8; MAX_UDP_RECV_BUFFER],
        })
    }

    /// Bind to any available port
    pub fn bind_any() -> Result<Self, UtpSocketError> {
        Self::bind("0.0.0.0:0")
    }

    /// Bind to a specific port
    pub fn bind_port(port: u16) -> Result<Self, UtpSocketError> {
        Self::bind(&format!("0.0.0.0:{}", port))
    }

    /// Get the local address this socket is bound to
    pub fn local_addr(&self) -> SocketAddr {
        self.local_addr
    }

    /// Return a Tokio handle for waiting on UDP read readiness.
    ///
    /// The handle is created lazily because the synchronous uTP API is also
    /// used by non-async callers and must remain constructible outside a
    /// Tokio runtime. The returned socket is only a readiness/receive view of
    /// the same underlying UDP socket; protocol state still lives here.
    pub fn readiness_socket(&self) -> Result<Arc<tokio::net::UdpSocket>, UtpSocketError> {
        if let Some(socket) = self.async_socket.get() {
            return Ok(Arc::clone(socket));
        }

        let socket = self
            .socket
            .try_clone()
            .map_err(UtpSocketError::RecvFailed)?;
        let async_socket =
            Arc::new(tokio::net::UdpSocket::from_std(socket).map_err(UtpSocketError::RecvFailed)?);
        let _ = self.async_socket.set(Arc::clone(&async_socket));
        Ok(self.async_socket.get().cloned().unwrap_or(async_socket))
    }

    /// Return the time remaining until the next connection timer expires.
    pub fn next_timer_delay(&self) -> Option<Duration> {
        self.timers.next_timer().map(|(_, _, remaining)| remaining)
    }

    /// Set connection timeout
    pub fn set_connect_timeout(&mut self, timeout: Duration) {
        self.options.set_connect_timeout(timeout);
        self.timers.set_default_connect_timeout(timeout);
    }

    /// Set idle timeout for connections
    pub fn set_idle_timeout(&mut self, timeout: Duration) {
        self.options.set_idle_timeout(timeout);
        self.timers.set_default_idle_timeout(timeout);
    }

    /// Set keepalive interval
    pub fn set_keepalive_interval(&mut self, interval: Duration) {
        self.options.set_keepalive_interval(interval);
        self.timers.set_default_keepalive_interval(interval);
    }

    /// Check if socket is closed
    pub fn is_closed(&self) -> bool {
        self.is_closed
    }

    /// Get number of active connections
    pub fn connection_count(&self) -> usize {
        self.connections.len()
    }

    /// Initiate a uTP connection to a remote peer
    pub fn connect(&mut self, remote_addr: SocketAddr) -> Result<u16, UtpSocketError> {
        if self.is_closed {
            return Err(UtpSocketError::SocketClosed);
        }

        if self.connections.len() >= self.options.max_connections() {
            return Err(UtpSocketError::MaxConnectionsReached);
        }

        let conn_id = find_available_connection_id(rand::random(), |connection_id| {
            self.connections.contains_key(&connection_id)
        })
        .ok_or(UtpSocketError::MaxConnectionsReached)?;
        let mut conn = UtpConnection::new();
        let syn_packet = conn.connect_with_local_id(remote_addr, conn_id)?;

        self.send_packet(&syn_packet, remote_addr)?;

        let rto = conn.rto();

        self.connections.insert(conn_id, conn);

        self.timers.set_timer(
            conn_id,
            TimerType::ConnectTimeout,
            self.options.connect_timeout(),
        );
        self.timers
            .set_timer(conn_id, TimerType::Retransmit(syn_packet.seq_nr), rto);

        Ok(conn_id)
    }

    /// Send a packet to a remote address
    fn send_packet(&self, packet: &UtpPacket, addr: SocketAddr) -> Result<(), UtpSocketError> {
        let data = packet.to_bytes();
        self.socket
            .send_to(&data, addr)
            .map_err(UtpSocketError::SendFailed)?;
        Ok(())
    }

    /// Send data on an established connection
    pub fn send(&mut self, conn_id: u16, data: &[u8]) -> Result<usize, UtpSocketError> {
        if self.is_closed {
            return Err(UtpSocketError::SocketClosed);
        }

        // Get connection info first
        let (remote_addr, rto) = {
            let conn = self
                .connections
                .get(&conn_id)
                .ok_or(UtpSocketError::ConnectionNotFound(conn_id))?;

            if !conn.is_established() {
                return Err(UtpSocketError::ConnectionError(
                    ConnectionError::NotConnected,
                ));
            }

            let remote_addr = conn
                .remote_addr()
                .ok_or(UtpSocketError::AddressNotFound(conn_id))?;
            (remote_addr, conn.rto())
        };

        // Get packets to send
        let packets = {
            let conn = self
                .connections
                .get_mut(&conn_id)
                .ok_or(UtpSocketError::ConnectionNotFound(conn_id))?;
            conn.send_data(data)?
        };

        // Send all packets
        let mut bytes_sent = 0;
        for packet in &packets {
            bytes_sent += packet.payload.len();
            self.send_packet(packet, remote_addr)?;
            if let Some(conn) = self.connections.get_mut(&conn_id) {
                conn.record_packet_sent(packet.seq_nr);
            }
            self.timers
                .set_timer(conn_id, TimerType::Retransmit(packet.seq_nr), rto);
        }

        Ok(bytes_sent)
    }

    /// Receive data from a connection
    pub fn recv(&mut self, conn_id: u16, buf: &mut [u8]) -> Result<usize, UtpSocketError> {
        if self.is_closed {
            return Err(UtpSocketError::SocketClosed);
        }

        // Process incoming packets first to potentially receive new data
        self.process_incoming_packets()?;

        // Get data from connection
        let conn = self
            .connections
            .get_mut(&conn_id)
            .ok_or(UtpSocketError::ConnectionNotFound(conn_id))?;

        Ok(conn.recv_into(buf))
    }

    /// Process incoming UDP packets
    fn process_incoming_packets(&mut self) -> Result<(), UtpSocketError> {
        let received = if let Some(socket) = self.async_socket.get() {
            socket.try_recv_from(&mut self.recv_buffer)
        } else {
            self.socket.recv_from(&mut self.recv_buffer)
        };

        match received {
            Ok((len, addr)) => {
                let packet = UtpPacket::from_bytes(&self.recv_buffer[..len])?;
                self.handle_packet(&packet, addr)?;
            }
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
            Err(e) => return Err(UtpSocketError::RecvFailed(e)),
        }
        Ok(())
    }

    /// Handle an incoming packet
    fn handle_packet(
        &mut self,
        packet: &UtpPacket,
        addr: SocketAddr,
    ) -> Result<(), UtpSocketError> {
        let packet_type = packet.packet_type()?;

        match packet_type {
            PacketType::StSyn => self.handle_syn(packet, addr)?,
            PacketType::StData | PacketType::StAck | PacketType::StFin => {
                let conn_id = self.find_connection_for_packet(packet, addr)?;
                if let Some(conn_id) = conn_id {
                    let (
                        response_packets,
                        acknowledged,
                        fast_retransmissions,
                        retransmission_timeout,
                        state,
                        keepalive_interval,
                    ) = {
                        let conn = self.connections.get_mut(&conn_id);
                        if let Some(conn) = conn {
                            let handling = conn.on_packet_received_with_acknowledgements(packet)?;
                            let mut congestion_loss_applied = false;
                            let mut fast_retransmissions = Vec::new();
                            for seq_nr in handling.fast_retransmit {
                                if let Some(retransmission) = conn.retransmit_packet(
                                    seq_nr,
                                    if congestion_loss_applied {
                                        super::connection::RetransmitEvent::None
                                    } else {
                                        super::connection::RetransmitEvent::Loss
                                    },
                                ) {
                                    if retransmission.packet_type().ok() == Some(PacketType::StData)
                                    {
                                        congestion_loss_applied = true;
                                    }
                                    conn.record_packet_sent(seq_nr);
                                    fast_retransmissions.push((seq_nr, retransmission));
                                }
                            }
                            let keepalive_interval = self.options.keepalive_interval();
                            (
                                handling.response_packets,
                                handling.acknowledged,
                                fast_retransmissions,
                                conn.rto(),
                                conn.state(),
                                keepalive_interval,
                            )
                        } else {
                            return Ok(());
                        }
                    };

                    for resp_packet in response_packets {
                        self.send_packet(&resp_packet, addr)?;
                    }

                    self.timers.cancel_timer(conn_id, TimerType::ConnectTimeout);
                    for seq_nr in acknowledged {
                        self.timers
                            .cancel_timer(conn_id, TimerType::Retransmit(seq_nr));
                    }
                    for (seq_nr, retransmission) in fast_retransmissions {
                        self.timers
                            .cancel_timer(conn_id, TimerType::Retransmit(seq_nr));
                        self.send_packet(&retransmission, addr)?;
                        self.timers.set_timer(
                            conn_id,
                            TimerType::Retransmit(seq_nr),
                            retransmission_timeout,
                        );
                    }
                    match state {
                        ConnectionState::Closed => {
                            self.close_connection_internal(conn_id)?;
                        }
                        ConnectionState::Established => {
                            self.timers.set_timer(
                                conn_id,
                                TimerType::Keepalive,
                                keepalive_interval,
                            );
                            self.timers.set_timer(
                                conn_id,
                                TimerType::IdleTimeout,
                                self.options.idle_timeout(),
                            );
                        }
                        ConnectionState::Closing => {
                            self.timers.set_timer(
                                conn_id,
                                TimerType::IdleTimeout,
                                self.options.idle_timeout(),
                            );
                        }
                        _ => {}
                    }
                }
            }
            PacketType::StReset => {
                let conn_id = self.find_connection_for_packet(packet, addr)?;
                if let Some(conn_id) = conn_id {
                    self.close_connection_internal(conn_id)?;
                }
            }
        }
        Ok(())
    }

    /// Handle incoming SYN packet
    fn handle_syn(&mut self, packet: &UtpPacket, addr: SocketAddr) -> Result<(), UtpSocketError> {
        let receive_id = packet.connection_id.wrapping_add(1);
        if let Some(conn) = self.connections.get_mut(&receive_id) {
            if conn.remote_addr() == Some(addr)
                && let Some(response) = conn.syn_response(packet)
            {
                self.send_packet(&response, addr)?;
            }
            return Ok(());
        }

        if self.connections.len() >= self.options.max_connections() {
            let mut reset = UtpPacket::reset(packet.connection_id);
            reset.timestamp_microseconds = self.timestamp_origin.elapsed().as_micros() as u32;
            self.send_packet(&reset, addr)?;
            return Err(UtpSocketError::MaxConnectionsReached);
        }

        let mut conn = UtpConnection::new();
        let syn_ack = conn.accept(packet, addr)?;
        let conn_id = conn.local_connection_id();

        self.send_packet(&syn_ack, addr)?;

        self.connections.insert(conn_id, conn);

        self.timers.set_timer(
            conn_id,
            TimerType::Keepalive,
            self.options.keepalive_interval(),
        );
        self.timers
            .set_timer(conn_id, TimerType::IdleTimeout, self.options.idle_timeout());

        Ok(())
    }

    /// Find the connection ID for an incoming packet
    fn find_connection_for_packet(
        &self,
        packet: &UtpPacket,
        addr: SocketAddr,
    ) -> Result<Option<u16>, UtpSocketError> {
        Ok(self
            .connections
            .get(&packet.connection_id)
            .filter(|conn| conn.remote_addr() == Some(addr))
            .map(|_| packet.connection_id))
    }

    /// Check connection state
    pub fn connection_state(&self, conn_id: u16) -> Result<ConnectionState, UtpSocketError> {
        let conn = self
            .connections
            .get(&conn_id)
            .ok_or(UtpSocketError::ConnectionNotFound(conn_id))?;
        Ok(conn.state())
    }

    /// Get connection statistics
    pub fn connection_stats(&self, conn_id: u16) -> Result<ConnectionStats, UtpSocketError> {
        let conn = self
            .connections
            .get(&conn_id)
            .ok_or(UtpSocketError::ConnectionNotFound(conn_id))?;

        Ok(ConnectionStats {
            state: conn.state(),
            local_connection_id: conn.local_connection_id(),
            remote_connection_id: conn.remote_connection_id(),
            remote_addr: conn.remote_addr(),
            rtt: conn.rtt(),
            rto: conn.rto(),
            congestion_window: conn.congestion_window(),
            receive_window: conn.receive_window(),
            bytes_in_flight: conn.bytes_in_flight(),
            idle_time: conn.idle_time(),
        })
    }

    /// Poll for incoming data (non-blocking)
    pub fn poll_recv(&mut self) -> Result<Vec<(u16, Vec<u8>)>, UtpSocketError> {
        self.process_incoming_packets()?;

        let mut results = Vec::new();
        let conn_ids: Vec<u16> = self.connections.keys().copied().collect();

        for conn_id in conn_ids {
            if let Some(conn) = self.connections.get_mut(&conn_id) {
                let data = conn.recv_data();
                if !data.is_empty() {
                    results.push((conn_id, data));
                }
            }
        }

        Ok(results)
    }

    /// Get list of active connection IDs
    pub fn connection_ids(&self) -> Vec<u16> {
        self.connections.keys().copied().collect()
    }
}

impl Drop for UtpSocket {
    fn drop(&mut self) {
        self.close();
    }
}

/// Connection statistics
#[derive(Debug, Clone)]
pub struct ConnectionStats {
    /// Current connection state
    pub state: ConnectionState,
    /// Connection ID expected on incoming packets.
    pub local_connection_id: u16,
    /// Connection ID used for outgoing packets after SYN.
    pub remote_connection_id: u16,
    /// Remote socket address
    pub remote_addr: Option<SocketAddr>,
    /// Estimated RTT
    pub rtt: Duration,
    /// Retransmission timeout
    pub rto: Duration,
    /// Congestion window size
    pub congestion_window: u32,
    /// Receive window size
    pub receive_window: u32,
    /// Bytes in flight
    pub bytes_in_flight: u32,
    /// Time since last activity
    pub idle_time: Duration,
}