aria2-protocol 0.3.8

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
//! uTP Connection implementation
//!
//! Implements the BEP 29 uTP connection state machine, sequencing, and data transfer.

use std::collections::{HashMap, VecDeque};
use std::io;
use std::net::SocketAddr;
use std::time::{Duration, Instant};

use super::congestion::LedbatController;
use super::metrics::RttEstimator;
use super::packet::{PacketType, UtpPacket, UtpPacketError};

mod receive;
mod send;

/// Connection state in the uTP state machine
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionState {
    /// Initial state, no connection established
    Closed,
    /// SYN sent, waiting for SYN-ACK
    SynSent,
    /// SYN-ACK sent (received SYN), waiting for ACK
    SynReceived,
    /// Connection established, data transfer possible
    Established,
    /// FIN sent, waiting for FIN-ACK
    FinWait,
    /// Close requested, waiting for FIN
    Closing,
    /// Time wait after close
    TimeWait,
}

/// Errors that can occur during uTP connection operations
#[derive(Debug, thiserror::Error)]
pub enum ConnectionError {
    #[error("Connection not established")]
    NotConnected,

    #[error("Connection already exists")]
    AlreadyExists,

    #[error("Connection closed by remote")]
    ClosedByRemote,

    #[error("Connection timed out")]
    Timeout,

    #[error("Invalid packet: {0}")]
    InvalidPacket(String),

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

    #[error("IO error: {0}")]
    IoError(#[from] io::Error),

    #[error("Sequence number mismatch: expected {expected}, got {actual}")]
    SeqMismatch { expected: u16, actual: u16 },

    #[error("Connection reset by remote")]
    Reset,

    #[error("Connection aborted")]
    Aborted,
}

/// Maximum receive buffer size per connection
const RECV_BUFFER_SIZE: usize = 64 * 1024;

/// Maximum send buffer size per connection
const SEND_BUFFER_SIZE: usize = 64 * 1024;

struct SentPacket {
    packet: UtpPacket,
    sent_at: Instant,
    retransmitted: bool,
    selectively_acked: bool,
    selectively_acked_after: u16,
    fast_retransmitted: bool,
}

pub(crate) struct PacketHandling {
    pub response_packets: Vec<UtpPacket>,
    pub acknowledged: Vec<u16>,
    pub fast_retransmit: Vec<u16>,
}

/// uTP Connection implementing the BEP 29 state machine
///
/// Each connection manages its own sequence numbers, congestion window,
/// and retransmission state independently.
pub struct UtpConnection {
    /// Current connection state
    state: ConnectionState,

    /// Connection ID expected on incoming packets.
    local_conn_id: u16,

    /// Connection ID used for outgoing packets after SYN.
    remote_conn_id: u16,

    /// Next sequence number to send
    seq_nr: u16,

    /// Next expected acknowledgment number
    ack_nr: u16,

    timestamp_origin: Instant,
    reply_micro: u32,

    /// Sequence number of the last SYN
    syn_seq_nr: u16,
    syn_sent_at: Option<Instant>,
    syn_retransmitted: bool,

    /// Remote socket address
    remote_addr: Option<SocketAddr>,

    /// Congestion window size in bytes.
    congestion: LedbatController,

    rtt_estimator: Option<RttEstimator>,

    /// Receive buffer for incoming data
    recv_buffer: Vec<u8>,

    /// Send buffer for outgoing data not yet acknowledged
    send_buffer: VecDeque<SentPacket>,
    pending_receive: HashMap<u16, UtpPacket>,
    pending_receive_bytes: usize,
    accepted_syn_seq: Option<u16>,
    peer_window: u32,
    last_peer_ack_nr: Option<u16>,
    duplicate_ack_count: u8,
    local_fin_acked: bool,
    remote_fin_received: bool,

    /// Last activity timestamp
    last_activity: Instant,

    /// Receive window size
    recv_window: u32,
}

impl UtpConnection {
    /// Create a new uTP connection in Closed state
    pub fn new() -> Self {
        let now = Instant::now();
        Self {
            state: ConnectionState::Closed,
            local_conn_id: 0,
            remote_conn_id: 0,
            seq_nr: 1,
            ack_nr: 0,
            timestamp_origin: now,
            reply_micro: 0,
            syn_seq_nr: 0,
            syn_sent_at: None,
            syn_retransmitted: false,
            remote_addr: None,
            congestion: LedbatController::with_mss(1400),
            rtt_estimator: None,
            recv_buffer: Vec::with_capacity(RECV_BUFFER_SIZE),
            send_buffer: VecDeque::new(),
            pending_receive: HashMap::new(),
            pending_receive_bytes: 0,
            accepted_syn_seq: None,
            peer_window: 0,
            last_peer_ack_nr: None,
            duplicate_ack_count: 0,
            local_fin_acked: false,
            remote_fin_received: false,
            last_activity: now,
            recv_window: RECV_BUFFER_SIZE as u32,
        }
    }

    fn timestamp_now_microseconds(&self) -> u32 {
        self.timestamp_origin.elapsed().as_micros() as u32
    }

    fn stamp_packet(&self, packet: &mut UtpPacket) {
        packet.timestamp_microseconds = self.timestamp_now_microseconds();
        packet.timestamp_difference_microseconds = self.reply_micro;
    }

    fn update_reply_delay(&mut self, packet: &UtpPacket) {
        self.reply_micro = self
            .timestamp_now_microseconds()
            .wrapping_sub(packet.timestamp_microseconds);
    }

    pub(crate) fn state_packet(&self) -> UtpPacket {
        let mut packet = UtpPacket::ack(
            self.remote_conn_id,
            self.ack_nr,
            self.seq_nr,
            self.recv_window,
        );
        self.stamp_packet(&mut packet);
        self.add_selective_ack(&mut packet);
        packet
    }

    /// Accept an incoming connection (server-side) - creates SYN-ACK packet
    pub fn accept(
        &mut self,
        syn_packet: &UtpPacket,
        remote_addr: SocketAddr,
    ) -> Result<UtpPacket, ConnectionError> {
        if self.state != ConnectionState::Closed {
            return Err(ConnectionError::AlreadyExists);
        }

        if syn_packet.packet_type()? != PacketType::StSyn {
            return Err(ConnectionError::InvalidPacket("Expected SYN".to_string()));
        }
        self.remote_addr = Some(remote_addr);
        self.remote_conn_id = syn_packet.connection_id;
        self.accepted_syn_seq = Some(syn_packet.seq_nr);
        self.peer_window = syn_packet.wnd_size;
        self.ack_nr = syn_packet.seq_nr;
        self.local_conn_id = syn_packet.connection_id.wrapping_add(1);
        self.update_reply_delay(syn_packet);
        self.seq_nr = rand_connection_id();
        self.syn_seq_nr = self.seq_nr;
        self.state = ConnectionState::Established;

        let mut syn_ack = UtpPacket::syn_ack(
            self.remote_conn_id,
            self.seq_nr,
            self.ack_nr,
            self.recv_window,
        );
        self.stamp_packet(&mut syn_ack);
        self.seq_nr = self.seq_nr.wrapping_add(1);

        Ok(syn_ack)
    }

    /// Repeat the original STATE response when an accepted SYN is retried.
    pub(crate) fn syn_response(&mut self, syn: &UtpPacket) -> Option<UtpPacket> {
        let matches = self.remote_conn_id == syn.connection_id
            && self.accepted_syn_seq == Some(syn.seq_nr)
            && self.local_conn_id == syn.connection_id.wrapping_add(1);
        if !matches {
            return None;
        }
        self.update_reply_delay(syn);
        let mut response = UtpPacket::syn_ack(
            self.remote_conn_id,
            self.syn_seq_nr,
            syn.seq_nr,
            self.recv_window,
        );
        self.stamp_packet(&mut response);
        Some(response)
    }

    /// Receive data from the connection buffer
    pub fn recv_data(&mut self) -> Vec<u8> {
        let data = std::mem::take(&mut self.recv_buffer);
        self.update_receive_window();
        data
    }

    /// Read up to the caller's buffer capacity without discarding unread data.
    pub(crate) fn recv_into(&mut self, buffer: &mut [u8]) -> usize {
        let length = buffer.len().min(self.recv_buffer.len());
        buffer[..length].copy_from_slice(&self.recv_buffer[..length]);
        self.recv_buffer.drain(..length);
        self.update_receive_window();
        length
    }

    /// Handle an incoming packet - returns response packets to send
    pub fn on_packet_received(
        &mut self,
        packet: &UtpPacket,
    ) -> Result<Vec<UtpPacket>, ConnectionError> {
        self.on_packet_received_with_acknowledgements(packet)
            .map(|handling| handling.response_packets)
    }

    pub(crate) fn on_packet_received_with_acknowledgements(
        &mut self,
        packet: &UtpPacket,
    ) -> Result<PacketHandling, ConnectionError> {
        if packet.connection_id != self.local_conn_id {
            return Err(ConnectionError::InvalidPacket(
                "Unexpected connection ID".to_string(),
            ));
        }
        self.last_activity = Instant::now();
        let packet_type = packet.packet_type()?;
        self.update_reply_delay(packet);

        match packet_type {
            PacketType::StSyn => Err(ConnectionError::InvalidPacket("Unexpected SYN".to_string())),
            PacketType::StData => self.handle_data_packet(packet),
            PacketType::StAck => self.handle_ack_packet(packet),
            PacketType::StFin => self.handle_fin_packet(packet),
            PacketType::StReset => {
                self.state = ConnectionState::Closed;
                Err(ConnectionError::Reset)
            }
        }
    }

    /// Check if connection has timed out
    pub fn check_timeout(&mut self, idle_timeout: Duration) -> bool {
        if self.last_activity.elapsed() >= idle_timeout {
            self.state = ConnectionState::Closed;
            return true;
        }
        false
    }

    /// Get packets that need to be retransmitted
    pub fn get_sendable_packets(&mut self) -> Vec<UtpPacket> {
        let mut packets = self
            .send_buffer
            .iter()
            .filter(|sent| !sent.selectively_acked)
            .map(|sent| {
                let mut packet = sent.packet.clone();
                packet.ack_nr = self.ack_nr;
                packet.wnd_size = self.recv_window;
                packet
            })
            .collect::<Vec<_>>();
        for packet in &mut packets {
            self.stamp_packet(packet);
        }
        packets
    }

    // --- Accessors ---

    /// Get current connection state
    pub fn state(&self) -> ConnectionState {
        self.state
    }

    /// Check if connection is in Established state
    pub fn is_established(&self) -> bool {
        self.state == ConnectionState::Established
    }

    /// Get the connection ID expected on incoming packets.
    pub fn local_connection_id(&self) -> u16 {
        self.local_conn_id
    }

    /// Get the connection ID used for outgoing packets after SYN.
    pub fn remote_connection_id(&self) -> u16 {
        self.remote_conn_id
    }

    /// Get remote socket address
    pub fn remote_addr(&self) -> Option<SocketAddr> {
        self.remote_addr
    }

    /// Get current sequence number
    pub fn current_seq_nr(&self) -> u16 {
        self.seq_nr
    }

    /// Get current acknowledgment number
    pub fn current_ack_nr(&self) -> u16 {
        self.ack_nr
    }

    /// Get current RTO
    pub fn rto(&self) -> Duration {
        self.rtt_estimator
            .as_ref()
            .map_or(Duration::from_secs(1), |estimator| {
                estimator.rto().max(Duration::from_millis(500))
            })
    }

    /// Get smoothed RTT
    pub fn rtt(&self) -> Duration {
        self.rtt_estimator
            .as_ref()
            .map_or(Duration::from_millis(100), RttEstimator::srtt)
    }

    /// Get congestion window size
    pub fn congestion_window(&self) -> u32 {
        self.congestion.get_window_size()
    }

    /// Get receive window size
    pub fn receive_window(&self) -> u32 {
        self.recv_window
    }

    /// Get bytes in flight
    pub fn bytes_in_flight(&self) -> u32 {
        self.congestion.get_bytes_in_flight()
    }

    /// Get idle time since last activity
    pub fn idle_time(&self) -> Duration {
        self.last_activity.elapsed()
    }
}

impl Default for UtpConnection {
    fn default() -> Self {
        Self::new()
    }
}

/// Generate a random connection ID
fn rand_connection_id() -> u16 {
    rand::random()
}

#[cfg(test)]
mod tests;