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;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionState {
Closed,
SynSent,
SynReceived,
Established,
FinWait,
Closing,
TimeWait,
}
#[derive(Clone, Copy)]
pub(crate) enum RetransmitEvent {
None,
Loss,
Timeout,
}
#[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,
}
const RECV_BUFFER_SIZE: usize = 64 * 1024;
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>,
}
pub struct UtpConnection {
state: ConnectionState,
local_conn_id: u16,
remote_conn_id: u16,
seq_nr: u16,
ack_nr: u16,
timestamp_origin: Instant,
reply_micro: u32,
syn_seq_nr: u16,
syn_sent_at: Option<Instant>,
syn_retransmitted: bool,
remote_addr: Option<SocketAddr>,
congestion: LedbatController,
rtt_estimator: Option<RttEstimator>,
recv_buffer: Vec<u8>,
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: Instant,
recv_window: u32,
}
impl UtpConnection {
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
}
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)
}
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)
}
pub fn recv_data(&mut self) -> Vec<u8> {
let data = std::mem::take(&mut self.recv_buffer);
self.update_receive_window();
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
}
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)
}
}
}
pub fn check_timeout(&mut self, idle_timeout: Duration) -> bool {
if self.last_activity.elapsed() >= idle_timeout {
self.state = ConnectionState::Closed;
return true;
}
false
}
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
}
pub fn state(&self) -> ConnectionState {
self.state
}
pub fn is_established(&self) -> bool {
self.state == ConnectionState::Established
}
pub fn local_connection_id(&self) -> u16 {
self.local_conn_id
}
pub fn remote_connection_id(&self) -> u16 {
self.remote_conn_id
}
pub fn remote_addr(&self) -> Option<SocketAddr> {
self.remote_addr
}
pub fn current_seq_nr(&self) -> u16 {
self.seq_nr
}
pub fn current_ack_nr(&self) -> u16 {
self.ack_nr
}
pub fn rto(&self) -> Duration {
self.rtt_estimator
.as_ref()
.map_or(Duration::from_secs(1), |estimator| {
estimator.rto().max(Duration::from_millis(500))
})
}
pub fn rtt(&self) -> Duration {
self.rtt_estimator
.as_ref()
.map_or(Duration::from_millis(100), RttEstimator::srtt)
}
pub fn congestion_window(&self) -> u32 {
self.congestion.get_window_size()
}
pub fn receive_window(&self) -> u32 {
self.recv_window
}
pub fn bytes_in_flight(&self) -> u32 {
self.congestion.get_bytes_in_flight()
}
pub fn idle_time(&self) -> Duration {
self.last_activity.elapsed()
}
}
impl Default for UtpConnection {
fn default() -> Self {
Self::new()
}
}
fn rand_connection_id() -> u16 {
rand::random()
}
#[cfg(test)]
mod tests;