feat(tun): replace lwip and smoltcp with a built-in Rust netstack

The TUN inbound now runs a userspace stack under proxy::tun::netstack:
IP parsing, fragment reassembly, UDP and a TCP engine written in Rust.
netstack-lwip and netstack-smoltcp are dropped, and the tun2socks
setting is ignored.
This commit is contained in:
eric committed 2026-11-26 17:46:47 +08:00
1 parent 5e8d94759c
commit 16cdec05c3
24 files changed
+5416 -328

No files matched your search

+2 -4
View File
@@ -136,7 +136,7 @@ inbound-shadowsocks = ["hkdf", "sha-1", "md-5", "tokio-util"]
inbound-socks = []
inbound-http = ["http"]
inbound-hc = []
inbound-tun = ["tun", "netstack-lwip", "netstack-smoltcp", "pnet_datalink"]
inbound-tun = ["tun", "pnet_datalink"]
inbound-ws = ["tungstenite", "tokio-tungstenite", "url", "http"]
inbound-amux = ["tokio-util"]
inbound-quic = ["rustls", "rustls-pemfile-old"]
@@ -152,7 +152,7 @@ ctrlc = ["tokio/signal"]
[dependencies]
# Common
tokio = { version = "1", features = ["sync", "io-util", "net", "time", "rt", "rt-multi-thread"] }
tokio = { version = "1", features = ["sync", "io-util", "net", "time", "rt", "rt-multi-thread", "macros"] }
protobuf = "3.6"
thiserror = "1.0"
futures = "0.3"
@@ -271,8 +271,6 @@ notify = { version = "6", optional = true }
# TUN
tun = { version = "0.7", features = ["async"], optional = true }
netstack-lwip = { git = "https://github.com/eycorsican/netstack-lwip", rev = "4943435", optional = true }
netstack-smoltcp = { git = "https://github.com/eycorsican/netstack-smoltcp", branch = "pr-16-initialize-unfilled", optional = true }
[target.'cfg(target_os = "windows")'.dependencies]
ipconfig = "0.3"
+50 -318
View File
@@ -1,5 +1,4 @@
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use anyhow::{anyhow, Result};
@@ -7,7 +6,6 @@ use futures::{sink::SinkExt, stream::StreamExt};
use protobuf::Message;
use tokio::sync::mpsc::channel as tokio_channel;
use tokio::sync::mpsc::{Receiver as TokioReceiver, Sender as TokioSender};
use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};
use crate::{
@@ -21,14 +19,10 @@ use crate::{
Runner,
};
#[cfg(feature = "netstack-lwip")]
use super::netstack_lwip as lwip;
#[cfg(feature = "netstack-smoltcp")]
use super::netstack_smoltcp as smoltcp;
use super::netstack;
#[cfg(feature = "netstack-lwip")]
async fn handle_inbound_stream_lwip(
stream: Pin<Box<lwip::TcpStream>>,
async fn handle_inbound_stream(
stream: netstack::TcpStream,
local_addr: SocketAddr,
remote_addr: SocketAddr,
inbound_tag: String,
@@ -67,50 +61,8 @@ async fn handle_inbound_stream_lwip(
dispatcher.dispatch_stream(sess, stream).await;
}
#[cfg(feature = "netstack-smoltcp")]
async fn handle_inbound_stream_smoltcp(
stream: Pin<Box<smoltcp::TcpStream>>,
local_addr: SocketAddr,
remote_addr: SocketAddr,
inbound_tag: String,
dispatcher: Arc<Dispatcher>,
fakedns: Option<Arc<FakeDns>>,
) {
let mut sess = Session {
network: Network::Tcp,
source: local_addr,
local_addr: remote_addr,
destination: SocksAddr::Ip(remote_addr),
inbound_tag,
..Default::default()
};
// Whether to override the destination according to Fake DNS.
if let Some(fakedns) = fakedns {
if fakedns.is_fake_ip(&remote_addr.ip()).await {
if let Some(domain) = fakedns.query_domain(&remote_addr.ip()).await {
sess.destination = SocksAddr::Domain(domain, remote_addr.port());
} else {
// Although requests targeting fake IPs are assumed
// never happen in real network traffic, which are
// likely caused by poisoned DNS cache records, we
// still have a chance to sniff the request domain
// for TLS traffic in dispatcher.
if remote_addr.port() != 443 && remote_addr.port() != 80 {
debug!(
"No paired domain found for this fake IP: {}, connection is rejected.",
&remote_addr.ip()
);
return;
}
}
}
}
dispatcher.dispatch_stream(sess, stream).await;
}
#[cfg(feature = "netstack-lwip")]
async fn handle_inbound_datagram_lwip(
socket: Pin<Box<lwip::UdpSocket>>,
async fn handle_inbound_datagram(
socket: netstack::UdpSocket,
inbound_tag: String,
nat_manager: Arc<NatManager>,
fakedns: Option<Arc<FakeDns>>,
@@ -157,131 +109,13 @@ async fn handle_inbound_datagram_lwip(
});
// Accept datagrams from netstack and send to NAT manager.
loop {
match lr.recv_from().await {
Err(e) => {
warn!("Failed to accept a datagram from netstack: {}", e);
}
Ok((data, src_addr, dst_addr)) => {
// Fake DNS logic.
if dst_addr.port() == 53 {
if let Some(fakedns) = &fakedns {
match fakedns.generate_fake_response(&data).await {
Ok(resp) => {
if let Err(e) = ls.send_to(resp.as_ref(), &dst_addr, &src_addr) {
warn!("A packet failed to send to the netstack: {}", e);
}
continue;
}
Err(err) => {
debug!("generate fake ip failed: {}", err);
}
}
}
}
// Whether to override the destination according to Fake DNS.
//
// WARNING
//
// This allows datagram to have a domain name as destination,
// but real UDP traffic are sent with IP address only. If the
// outbound for this datagram is a direct one, the outbound
// would resolve the domain to IP address before sending out
// the datagram. If the outbound is a proxy one, it would
// require a proxy server with the ability to handle datagrams
// with domain name destination, leaf itself of course supports
// this feature very well.
let dst_addr = if let Some(fakedns) = &fakedns {
if fakedns.is_fake_ip(&dst_addr.ip()).await {
if let Some(domain) = fakedns.query_domain(&dst_addr.ip()).await {
SocksAddr::Domain(domain, dst_addr.port())
} else {
debug!(
"No paired domain found for this fake IP: {}, datagram is rejected.",
&dst_addr.ip()
);
continue;
}
} else {
SocksAddr::Ip(dst_addr)
}
} else {
SocksAddr::Ip(dst_addr)
};
let dgram_src = DatagramSource::new(src_addr, None);
let pkt = UdpPacket::new(data, SocksAddr::Ip(src_addr), dst_addr);
nat_manager
.send(None, &dgram_src, &inbound_tag, &l_tx, pkt)
.await;
}
}
}
}
#[cfg(feature = "netstack-smoltcp")]
async fn handle_inbound_datagram_smoltcp(
socket: smoltcp::UdpSocket,
inbound_tag: String,
nat_manager: Arc<NatManager>,
fakedns: Option<Arc<FakeDns>>,
) {
// The socket to receive/send packets from/to the netstack.
let (mut lr, ls) = socket.split();
let ls = Arc::new(Mutex::new(ls));
// The channel for sending back datagrams from NAT manager to netstack.
let (l_tx, mut l_rx): (TokioSender<UdpPacket>, TokioReceiver<UdpPacket>) =
tokio_channel(*crate::option::UDP_DOWNLINK_CHANNEL_SIZE);
// Receive datagrams from NAT manager and send back to netstack.
let fakedns_cloned = fakedns.clone();
let ls_cloned = ls.clone();
tokio::spawn(async move {
while let Some(pkt) = l_rx.recv().await {
let src_addr = match pkt.src_addr {
SocksAddr::Ip(a) => a,
SocksAddr::Domain(domain, port) => {
if let Some(fakedns) = &fakedns_cloned {
if let Some(ip) = fakedns.query_fake_ip(&domain).await {
SocketAddr::new(ip, port)
} else {
warn!(
"Received datagram with source address {}:{} without paired fake IP found.",
&domain, &port
);
continue;
}
} else {
warn!(
"Received datagram with source address {}:{} but fake DNS is disabled.",
&domain, &port
);
continue;
}
}
};
if let Err(e) = ls_cloned
.lock()
.await
.send((pkt.data, src_addr, *pkt.dst_addr.must_ip()))
.await
{
warn!("A packet failed to send to the netstack: {}", e);
}
}
});
// Accept datagrams from netstack and send to NAT manager.
while let Some(item) = lr.next().await {
let (data, src_addr, dst_addr) = item;
while let Some((data, src_addr, dst_addr)) = lr.next().await {
// Fake DNS logic.
if dst_addr.port() == 53 {
if let Some(fakedns) = &fakedns {
match fakedns.generate_fake_response(&data).await {
Ok(resp) => {
if let Err(e) = ls.lock().await.send((resp, dst_addr, src_addr)).await {
if let Err(e) = ls.send_to(resp.as_ref(), &dst_addr, &src_addr) {
warn!("A packet failed to send to the netstack: {}", e);
}
continue;
@@ -303,8 +137,7 @@ async fn handle_inbound_datagram_smoltcp(
// would resolve the domain to IP address before sending out
// the datagram. If the outbound is a proxy one, it would
// require a proxy server with the ability to handle datagrams
// with domain name destination, leaf itself of course supports
// this feature very well.
// with domain name destination.
let dst_addr = if let Some(fakedns) = &fakedns {
if fakedns.is_fake_ip(&dst_addr.ip()).await {
if let Some(domain) = fakedns.query_domain(&dst_addr.ip()).await {
@@ -331,56 +164,52 @@ async fn handle_inbound_datagram_smoltcp(
}
}
#[cfg(feature = "netstack-lwip")]
fn new_lwip(
fn new_netstack(
inbound: Inbound,
dispatcher: Arc<Dispatcher>,
nat_manager: Arc<NatManager>,
fakedns: Option<Arc<FakeDns>>,
tun: tun::AsyncDevice,
mtu: Option<usize>,
) -> Result<Runner> {
let (stack, mut tcp_listener, udp_socket) = lwip::NetStack::with_buffer_size(
*crate::option::NETSTACK_OUTPUT_CHANNEL_SIZE,
*crate::option::NETSTACK_UDP_UPLINK_CHANNEL_SIZE,
)?;
let mut config = netstack::Config {
max_output_packets: *crate::option::NETSTACK_OUTPUT_CHANNEL_SIZE,
max_udp_queue: *crate::option::NETSTACK_UDP_UPLINK_CHANNEL_SIZE,
..Default::default()
};
if let Some(mtu) = mtu {
config.limits.mtu = mtu;
}
let (stack, mut tcp_listener, udp_socket) = netstack::new(config);
Ok(Box::pin(async move {
let inbound_tag = inbound.tag.clone();
let framed = tun.into_framed();
let (mut tun_sink, mut tun_stream) = framed.split();
let (mut stack_sink, mut stack_stream) = stack.split();
let mut stack_output = stack.output();
let driver = stack.driver();
let mut futs: Vec<Runner> = Vec::new();
// Reads packet from stack and sends to TUN.
// Runs the stack's timers: retransmission, keep-alive, closes.
futs.push(Box::pin(driver));
// Reads packets from stack and sends to TUN.
futs.push(Box::pin(async move {
while let Some(pkt) = stack_stream.next().await {
match pkt {
Ok(pkt) => {
if let Err(e) = tun_sink.send(pkt).await {
// TODO Return the error
error!("Sending packet to TUN failed: {}", e);
return;
}
}
Err(e) => {
error!("Net stack erorr: {}", e);
return;
}
while let Some(pkt) = stack_output.next().await {
if let Err(e) = tun_sink.send(pkt).await {
error!("Sending packet to TUN failed: {}", e);
return;
}
}
}));
// Reads packet from TUN and sends to stack.
// Reads packets from TUN and feeds them to the stack. This future
// owns the stack: when it ends the stack shuts down.
futs.push(Box::pin(async move {
while let Some(pkt) = tun_stream.next().await {
match pkt {
Ok(pkt) => {
if let Err(e) = stack_sink.send(pkt).await {
error!("Sending packet to NetStack failed: {}", e);
return;
}
}
Ok(pkt) => stack.input(&pkt),
Err(e) => {
error!("TUN error: {}", e);
return;
@@ -394,7 +223,7 @@ fn new_lwip(
let fakedns_cloned = fakedns.clone();
futs.push(Box::pin(async move {
while let Some((stream, local_addr, remote_addr)) = tcp_listener.next().await {
tokio::spawn(handle_inbound_stream_lwip(
tokio::spawn(handle_inbound_stream(
stream,
local_addr,
remote_addr,
@@ -408,108 +237,10 @@ fn new_lwip(
// Receive and send UDP packets between netstack and NAT manager. The NAT
// manager would maintain UDP sessions and send them to the dispatcher.
futs.push(Box::pin(async move {
handle_inbound_datagram_lwip(udp_socket, inbound_tag, nat_manager, fakedns.clone())
.await;
handle_inbound_datagram(udp_socket, inbound_tag, nat_manager, fakedns.clone()).await;
}));
info!("start tun inbound (lwip)");
futures::future::select_all(futs).await;
}))
}
#[cfg(feature = "netstack-smoltcp")]
fn new_smoltcp(
inbound: Inbound,
dispatcher: Arc<Dispatcher>,
nat_manager: Arc<NatManager>,
fakedns: Option<Arc<FakeDns>>,
tun: tun::AsyncDevice,
) -> Result<Runner> {
let (stack, runner, udp_socket, tcp_listener) = smoltcp::StackBuilder::default()
.enable_tcp(true)
.enable_udp(true)
.enable_icmp(true)
.stack_buffer_size(*crate::option::NETSTACK_OUTPUT_CHANNEL_SIZE)
.udp_buffer_size(*crate::option::NETSTACK_UDP_UPLINK_CHANNEL_SIZE)
.tcp_buffer_size(*crate::option::NETSTACK_UDP_UPLINK_CHANNEL_SIZE)
.build()
.map_err(|e| anyhow!("stack build failed: {}", e))?;
if let Some(runner) = runner {
tokio::spawn(runner);
}
let mut tcp_listener = tcp_listener.ok_or_else(|| anyhow!("no tcp listener"))?;
let udp_socket = udp_socket.ok_or_else(|| anyhow!("no udp socket"))?;
Ok(Box::pin(async move {
let inbound_tag = inbound.tag.clone();
let framed = tun.into_framed();
let (mut tun_sink, mut tun_stream) = framed.split();
let (mut stack_sink, mut stack_stream) = stack.split();
let mut futs: Vec<Runner> = Vec::new();
// Reads packet from stack and sends to TUN.
futs.push(Box::pin(async move {
while let Some(pkt) = stack_stream.next().await {
match pkt {
Ok(pkt) => {
if let Err(e) = tun_sink.send(pkt).await {
error!("Sending packet to TUN failed: {}", e);
return;
}
}
Err(e) => {
error!("Net stack erorr: {}", e);
return;
}
}
}
}));
// Reads packet from TUN and sends to stack.
futs.push(Box::pin(async move {
while let Some(pkt) = tun_stream.next().await {
match pkt {
Ok(pkt) => {
if let Err(e) = stack_sink.send(pkt).await {
error!("Sending packet to NetStack failed: {}", e);
return;
}
}
Err(e) => {
error!("TUN error: {}", e);
return;
}
}
}
}));
// Extracts TCP connections from stack and sends them to the dispatcher.
let inbound_tag_cloned = inbound_tag.clone();
let fakedns_cloned = fakedns.clone();
futs.push(Box::pin(async move {
while let Some((stream, local_addr, remote_addr)) = tcp_listener.next().await {
tokio::spawn(handle_inbound_stream_smoltcp(
Box::pin(stream),
local_addr,
remote_addr,
inbound_tag_cloned.clone(),
dispatcher.clone(),
fakedns_cloned.clone(),
));
}
}));
// Receive and send UDP packets between netstack and NAT manager. The NAT
// manager would maintain UDP sessions and send them to the dispatcher.
futs.push(Box::pin(async move {
handle_inbound_datagram_smoltcp(udp_socket, inbound_tag, nat_manager, fakedns.clone())
.await;
}));
info!("start tun inbound (smoltcp)");
info!("start tun inbound");
futures::future::select_all(futs).await;
}))
}
@@ -535,6 +266,19 @@ pub fn new(
let settings = TunInboundSettings::parse_from_bytes(&inbound.settings)?;
// The MTU the stack segments for, when leaf configures the device
// itself; with a TUN fd the platform owns it and the stack's default
// (1500) stands.
let mtu: Option<usize> = if settings.fd >= 0 {
None
} else if settings.auto {
Some(1500)
} else if settings.mtu > 0 {
Some(settings.mtu as usize)
} else {
None
};
let mut cfg = tun::Configuration::default();
if settings.fd >= 0 {
cfg.raw_fd(settings.fd);
@@ -614,18 +358,6 @@ pub fn new(
assert!(settings.fd == -1, "tun-auto is not compatible with tun-fd");
}
match settings.tun2socks.as_str() {
"smoltcp" => {
#[cfg(feature = "netstack-smoltcp")]
return new_smoltcp(inbound, dispatcher, nat_manager, fakedns, tun);
#[cfg(not(feature = "netstack-smoltcp"))]
return Err(anyhow!("netstack-smoltcp feature is not enabled"));
}
_ => {
#[cfg(feature = "netstack-lwip")]
return new_lwip(inbound, dispatcher, nat_manager, fakedns, tun);
#[cfg(not(feature = "netstack-lwip"))]
return Err(anyhow!("netstack-lwip feature is not enabled"));
}
}
// There is one network stack; the `tun2socks` setting is ignored.
new_netstack(inbound, dispatcher, nat_manager, fakedns, tun, mtu)
}
+1 -6
View File
@@ -1,7 +1,2 @@
pub mod inbound;
#[cfg(feature = "netstack-lwip")]
pub use netstack_lwip;
#[cfg(feature = "netstack-smoltcp")]
pub use netstack_smoltcp;
pub mod netstack;
+41
View File
@@ -0,0 +1,41 @@
//! Byte queues that grow by doubling, as `VecDeque` does, but never past the
//! most they can ever hold — a 46 KiB window must not cost 64 KiB — and that
//! give their memory back once empty.
use std::collections::VecDeque;
/// Appends `data`, growing `buf` geometrically up to `limit` bytes of
/// capacity (beyond it only as far as needed, when `data` itself is larger).
pub fn extend_bounded(buf: &mut VecDeque<u8>, data: &[u8], limit: usize) {
let needed = buf.len() + data.len();
if needed > buf.capacity() {
let target = (buf.capacity() * 2).max(needed).min(limit.max(needed));
buf.reserve_exact(target - buf.len());
}
buf.extend(data);
}
/// Shrinks a map-like collection whose length has fallen far below its
/// capacity, so a burst of connections does not keep its memory for good.
pub fn should_shrink(len: usize, capacity: usize) -> bool {
capacity > 64 && len * 4 < capacity
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn growth_stops_at_the_limit() {
let mut buf = VecDeque::new();
for _ in 0..32 {
extend_bounded(&mut buf, &[0u8; 1460], 46_720);
}
assert_eq!(buf.len(), 46_720);
assert!(
buf.capacity() < 46_720 + 1460,
"capacity {}",
buf.capacity()
);
}
}
+98
View File
@@ -0,0 +1,98 @@
//! The types the TCP engine and the stack around it share: the clock it is
//! handed, connection ids, the limits it runs within and what it reports.
use std::net::SocketAddr;
use std::time::Duration;
/// Time since the stack was created. Engines never read a clock of their own.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant(u64);
impl Instant {
pub const ZERO: Instant = Instant(0);
pub const fn from_micros(micros: u64) -> Self {
Instant(micros)
}
pub const fn as_micros(self) -> u64 {
self.0
}
pub const fn as_millis(self) -> u64 {
self.0 / 1000
}
}
impl std::ops::Add<Duration> for Instant {
type Output = Instant;
fn add(self, rhs: Duration) -> Instant {
let micros = u64::try_from(rhs.as_micros()).unwrap_or(u64::MAX);
Instant(self.0.saturating_add(micros))
}
}
/// Identifies one accepted connection for its whole life. Never reused, so a
/// stale id can only ever miss, never reach a newer connection.
pub type ConnId = u64;
/// A connection whose handshake has completed and that the application has
/// not picked up yet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Accepted {
pub id: ConnId,
/// The application's end, behind the TUN device.
pub client: SocketAddr,
/// Where the application was connecting to.
pub target: SocketAddr,
}
/// Bounds on what one engine may hold. Per connection the sizes are lwIP's,
/// fixed (a 32-segment window, a 16-segment send buffer, 12
/// retransmissions), so the stack-wide bounds are here.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
/// Connections in any state, the half-open ones included. A SYN beyond it
/// is answered with RST.
pub max_connections: usize,
/// Idle time before a keep-alive probe; `None` sends none.
pub keepalive: Option<Duration>,
/// The MTU of the link; segments are sized to fit it.
pub mtu: usize,
/// Payload bytes buffered across all connections together. Past it
/// windows close and writes block, so the whole stack stays within it
/// whatever the number of connections. `None` leaves only the
/// per-connection bounds. Backends that allocate whole buffers up front
/// cannot honour it and ignore it.
pub memory_budget: Option<usize>,
}
impl Default for Limits {
/// Sized for where the stack runs. On iOS the packet tunnel extension is
/// killed past 50 MB, so everything buffered across all connections
/// shares a 4 MiB budget there.
fn default() -> Self {
#[cfg(target_os = "ios")]
let budget = 4 << 20;
#[cfg(not(target_os = "ios"))]
let budget = 16 << 20;
Limits {
max_connections: 1024,
keepalive: Some(Duration::from_secs(60)),
mtu: 1500,
memory_budget: Some(budget),
}
}
}
/// What an engine reports about itself, for the memory and leak checks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EngineStats {
/// Connections the engine still holds state for, in any TCP state.
pub connections: usize,
/// Connections the application still holds a handle to.
pub open_handles: usize,
/// Payload bytes buffered in either direction across all connections.
pub buffered_bytes: usize,
}
+309
View File
@@ -0,0 +1,309 @@
//! IPv4 and IPv6 fragment reassembly, ahead of every backend.
//!
//! Bounded in count, bytes and time: fragments are input the network
//! controls, and the stack runs where memory is the scarcest resource.
use std::collections::HashMap;
use std::net::IpAddr;
use std::time::Duration;
use crate::proxy::tun::netstack::engine::Instant;
use crate::proxy::tun::netstack::ip::{self, IpView};
use crate::proxy::tun::netstack::wire;
/// The largest payload a datagram can reassemble to and still be one packet:
/// IPv4's total length counts its header, IPv6's payload length does not.
fn max_payload(addr: IpAddr) -> usize {
match addr {
IpAddr::V4(_) => usize::from(u16::MAX) - wire::IPV4_HEADER_LEN,
IpAddr::V6(_) => usize::from(u16::MAX),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ReassemblyLimits {
/// Datagrams being reassembled at once.
pub max_datagrams: usize,
/// Payload bytes held across all of them.
pub max_bytes: usize,
/// How long an incomplete datagram is kept.
pub timeout: Duration,
}
impl Default for ReassemblyLimits {
fn default() -> Self {
ReassemblyLimits {
max_datagrams: 32,
max_bytes: 256 * 1024,
timeout: Duration::from_secs(10),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct Key {
src: IpAddr,
dst: IpAddr,
protocol: u8,
id: u32,
}
struct Partial {
data: Vec<u8>,
/// Received byte ranges, sorted and disjoint.
received: Vec<(usize, usize)>,
/// Payload length, known once the last fragment has arrived.
total: Option<usize>,
expires: Instant,
}
impl Partial {
/// Records `[offset, offset + chunk.len())`. False when it overlaps data
/// already received with different bytes — the datagram is then dropped
/// (RFC 5722), since no answer about which copy is right is safe.
fn insert(&mut self, offset: usize, chunk: &[u8]) -> bool {
let end = offset + chunk.len();
for &(start, stop) in &self.received {
if offset < stop && start < end {
let overlap_start = offset.max(start);
let overlap_end = end.min(stop);
let old = &self.data[overlap_start..overlap_end];
let new = &chunk[overlap_start - offset..overlap_end - offset];
if old != new {
return false;
}
}
}
if self.data.len() < end {
self.data.resize(end, 0);
}
self.data[offset..end].copy_from_slice(chunk);
self.received.push((offset, end));
self.received.sort_unstable();
let mut merged: Vec<(usize, usize)> = Vec::with_capacity(self.received.len());
for &(start, stop) in &self.received {
match merged.last_mut() {
Some(last) if start <= last.1 => last.1 = last.1.max(stop),
_ => merged.push((start, stop)),
}
}
self.received = merged;
true
}
fn is_complete(&self) -> bool {
match (self.total, self.received.as_slice()) {
(Some(total), [(0, end)]) => *end == total,
_ => false,
}
}
}
#[derive(Default)]
pub struct Reassembler {
limits: ReassemblyLimits,
partials: HashMap<Key, Partial>,
bytes: usize,
/// Datagrams given up on: evicted, timed out, overlapping or malformed.
pub dropped: u64,
}
impl Reassembler {
pub fn new(limits: ReassemblyLimits) -> Self {
Reassembler {
limits,
..Default::default()
}
}
pub fn held_bytes(&self) -> usize {
self.bytes
}
/// Takes one fragment. Returns the whole datagram, rebuilt as a single IP
/// packet without options, once its last missing piece arrives.
pub fn push(&mut self, now: Instant, view: &IpView<'_>) -> Option<Vec<u8>> {
let fragment = view.fragment?;
let key = Key {
src: view.src,
dst: view.dst,
protocol: view.protocol,
id: fragment.id,
};
let end = fragment.offset + view.payload.len();
let misaligned = fragment.more && !view.payload.len().is_multiple_of(8);
if end > max_payload(key.src) || misaligned || view.payload.is_empty() {
self.drop_datagram(&key);
self.dropped += 1;
return None;
}
if !self.partials.contains_key(&key) {
self.expire(now);
if self.partials.len() >= self.limits.max_datagrams {
self.evict_oldest();
}
self.partials.insert(
key,
Partial {
data: Vec::new(),
received: Vec::new(),
total: None,
expires: now + self.limits.timeout,
},
);
}
let grows_by = {
let partial = self.partials.get(&key)?;
end.saturating_sub(partial.data.len())
};
while self.bytes + grows_by > self.limits.max_bytes && self.partials.len() > 1 {
if !self.evict_oldest_except(&key) {
break;
}
}
if self.bytes + grows_by > self.limits.max_bytes {
self.drop_datagram(&key);
self.dropped += 1;
return None;
}
let partial = self.partials.get_mut(&key)?;
let total_conflicts = match partial.total {
Some(total) => end > total || (!fragment.more && end != total),
None => !fragment.more && partial.received.iter().any(|&(_, stop)| stop > end),
};
let before = partial.data.len();
if total_conflicts || !partial.insert(fragment.offset, view.payload) {
self.drop_datagram(&key);
self.dropped += 1;
return None;
}
if !fragment.more {
partial.total = Some(end);
}
self.bytes += partial.data.len() - before;
if !partial.is_complete() {
return None;
}
let partial = self.partials.remove(&key)?;
self.bytes -= partial.data.len();
ip::build_packet(key.src, key.dst, key.protocol, &partial.data)
}
/// Drops the datagrams whose time is up.
pub fn expire(&mut self, now: Instant) {
let before = self.partials.len();
let mut freed = 0;
self.partials.retain(|_, partial| {
let keep = partial.expires > now;
if !keep {
freed += partial.data.len();
}
keep
});
self.bytes -= freed;
self.dropped += (before - self.partials.len()) as u64;
}
/// When the oldest incomplete datagram times out.
pub fn next_expiry(&self) -> Option<Instant> {
self.partials.values().map(|p| p.expires).min()
}
fn drop_datagram(&mut self, key: &Key) {
if let Some(partial) = self.partials.remove(key) {
self.bytes -= partial.data.len();
}
}
fn evict_oldest(&mut self) -> bool {
let oldest = self
.partials
.iter()
.min_by_key(|(_, p)| p.expires)
.map(|(k, _)| *k);
match oldest {
Some(key) => {
self.drop_datagram(&key);
self.dropped += 1;
true
}
None => false,
}
}
fn evict_oldest_except(&mut self, keep: &Key) -> bool {
let oldest = self
.partials
.iter()
.filter(|(k, _)| *k != keep)
.min_by_key(|(_, p)| p.expires)
.map(|(k, _)| *k);
match oldest {
Some(key) => {
self.drop_datagram(&key);
self.dropped += 1;
true
}
None => false,
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::proxy::tun::netstack::ip::Fragment;
/// Two fragments whose payload ends at `end`: one big piece, then the rest.
fn reassemble(src: &str, dst: &str, end: usize) -> (Option<Vec<u8>>, Reassembler) {
let mut reassembler = Reassembler::new(ReassemblyLimits::default());
let payload = vec![7u8; end];
let split = 65_504;
let now = Instant::from_micros(1000);
let mut result = None;
for (offset, more) in [(0, true), (split, false)] {
let stop = if more { split } else { end };
let view = IpView {
src: src.parse().unwrap(),
dst: dst.parse().unwrap(),
protocol: ip::PROTO_UDP,
payload: &payload[offset..stop],
fragment: Some(Fragment {
id: 1,
offset,
more,
}),
};
result = reassembler.push(now, &view);
}
(result, reassembler)
}
#[test]
fn an_ipv4_datagram_reassembles_up_to_what_one_packet_holds() {
let (packet, reassembler) = reassemble("10.0.0.2", "10.0.0.1", 65_515);
assert_eq!(packet.map(|p| p.len()), Some(65_535));
assert_eq!(reassembler.dropped, 0);
}
#[test]
fn an_ipv4_datagram_past_one_packet_is_counted_as_dropped() {
let (packet, reassembler) = reassemble("10.0.0.2", "10.0.0.1", 65_520);
assert!(packet.is_none());
assert_eq!(reassembler.dropped, 1);
assert_eq!(reassembler.held_bytes(), 0);
}
#[test]
fn an_ipv6_payload_may_fill_its_whole_length_field() {
let (packet, reassembler) = reassemble("fd00::2", "fd00::1", 65_520);
assert_eq!(packet.map(|p| p.len()), Some(40 + 65_520));
assert_eq!(reassembler.dropped, 0);
}
}
+298
View File
@@ -0,0 +1,298 @@
//! IP-layer parsing and building shared by every backend: telling TCP from
//! UDP, finding fragments, and writing the UDP datagrams that go back out.
//!
//! Everything here takes bytes straight off a TUN device, so nothing may
//! panic on malformed input — every length is checked before it is used.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use crate::proxy::tun::netstack::wire::{
self, Ipv4Fields, IPV4_HEADER_LEN, IPV6_HEADER_LEN, UDP_HEADER_LEN,
};
pub use crate::proxy::tun::netstack::wire::{PROTO_TCP, PROTO_UDP};
const IPV6_FRAGMENT_HEADER_LEN: usize = 8;
const IPV6_NEXT_HOP_BY_HOP: u8 = 0;
const IPV6_NEXT_ROUTING: u8 = 43;
const IPV6_NEXT_FRAGMENT: u8 = 44;
const IPV6_NEXT_DEST_OPTIONS: u8 = 60;
const DEFAULT_TTL: u8 = 64;
/// Where a fragment sits in its datagram.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Fragment {
pub id: u32,
/// Byte offset of this fragment's payload within the datagram's payload.
pub offset: usize,
pub more: bool,
}
/// A parsed IP packet. `payload` is what follows every IP header, extension
/// headers included: the transport header and data, or a fragment of them.
#[derive(Debug)]
pub struct IpView<'a> {
pub src: IpAddr,
pub dst: IpAddr,
pub protocol: u8,
pub payload: &'a [u8],
pub fragment: Option<Fragment>,
}
impl IpView<'_> {
pub fn is_fragment(&self) -> bool {
self.fragment.is_some()
}
}
pub fn parse(packet: &[u8]) -> Option<IpView<'_>> {
match packet.first()? >> 4 {
4 => parse_v4(packet),
6 => parse_v6(packet),
_ => None,
}
}
fn parse_v4(packet: &[u8]) -> Option<IpView<'_>> {
let ip = wire::read_ipv4(packet)?;
let payload = packet.get(ip.header_len..ip.total_len)?;
let fragment = (ip.more_fragments || ip.fragment_offset != 0).then_some(Fragment {
id: u32::from(ip.ident),
offset: ip.fragment_offset,
more: ip.more_fragments,
});
Some(IpView {
src: IpAddr::V4(ip.src),
dst: IpAddr::V4(ip.dst),
protocol: ip.protocol,
payload,
fragment,
})
}
fn parse_v6(packet: &[u8]) -> Option<IpView<'_>> {
let ip = wire::read_ipv6(packet)?;
let mut rest = packet.get(IPV6_HEADER_LEN..IPV6_HEADER_LEN + ip.payload_len)?;
let mut next = ip.next_header;
let mut fragment = None;
loop {
match next {
IPV6_NEXT_HOP_BY_HOP | IPV6_NEXT_ROUTING | IPV6_NEXT_DEST_OPTIONS => {
let header_len = (usize::from(*rest.get(1)?) + 1) * 8;
next = *rest.first()?;
rest = rest.get(header_len..)?;
}
IPV6_NEXT_FRAGMENT => {
let header = rest.get(..IPV6_FRAGMENT_HEADER_LEN)?;
next = header[0];
let offset_and_flags = u16::from_be_bytes([header[2], header[3]]);
let id = u32::from_be_bytes([header[4], header[5], header[6], header[7]]);
let offset = usize::from(offset_and_flags & !0x7);
let more = offset_and_flags & 1 == 1;
rest = &rest[IPV6_FRAGMENT_HEADER_LEN..];
// An atomic fragment (offset 0, no more) is a whole datagram.
if offset != 0 || more {
fragment = Some(Fragment { id, offset, more });
break;
}
}
_ => break,
}
}
Some(IpView {
src: IpAddr::V6(ip.src),
dst: IpAddr::V6(ip.dst),
protocol: next,
payload: rest,
fragment,
})
}
fn v4_fields(src: Ipv4Addr, dst: Ipv4Addr, protocol: u8, total_len: u16) -> Ipv4Fields {
Ipv4Fields {
src,
dst,
protocol,
total_len,
ident: 0,
dont_fragment: false,
more_fragments: false,
fragment_offset: 0,
ttl: DEFAULT_TTL,
}
}
/// A whole IP packet carrying `payload` as `protocol`, with no options or
/// extension headers. Used to rebuild a reassembled datagram.
pub fn build_packet(src: IpAddr, dst: IpAddr, protocol: u8, payload: &[u8]) -> Option<Vec<u8>> {
match (src, dst) {
(IpAddr::V4(src), IpAddr::V4(dst)) => {
let total = IPV4_HEADER_LEN + payload.len();
let total_u16 = u16::try_from(total).ok()?;
let mut buf = vec![0u8; total];
wire::write_ipv4(&mut buf, &v4_fields(src, dst, protocol, total_u16));
buf[IPV4_HEADER_LEN..].copy_from_slice(payload);
Some(buf)
}
(IpAddr::V6(src), IpAddr::V6(dst)) => {
let payload_len = u16::try_from(payload.len()).ok()?;
let mut buf = vec![0u8; IPV6_HEADER_LEN + payload.len()];
wire::write_ipv6(&mut buf, src, dst, protocol, payload_len, DEFAULT_TTL);
buf[IPV6_HEADER_LEN..].copy_from_slice(payload);
Some(buf)
}
_ => None,
}
}
/// Why a datagram could not be written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildError {
/// Source and destination are of different IP families.
MixedFamilies,
/// More than an IP datagram can carry.
TooLarge,
}
/// Writes `payload` as a UDP datagram from `src` to `dst`, fragmented to fit
/// `mtu`, appending one IP packet per fragment to `out`. `next_id` numbers
/// the fragmented datagrams.
pub fn build_udp(
src: SocketAddr,
dst: SocketAddr,
payload: &[u8],
mtu: usize,
next_id: &mut u32,
out: &mut Vec<Vec<u8>>,
) -> Result<(), BuildError> {
if src.is_ipv4() != dst.is_ipv4() {
return Err(BuildError::MixedFamilies);
}
let udp_len = UDP_HEADER_LEN + payload.len();
if udp_len > usize::from(u16::MAX) {
return Err(BuildError::TooLarge);
}
let mut segment = vec![0u8; udp_len];
segment[UDP_HEADER_LEN..].copy_from_slice(payload);
wire::write_udp(&mut segment, src.ip(), dst.ip(), src.port(), dst.port());
match (src.ip(), dst.ip()) {
(IpAddr::V4(s), IpAddr::V4(d)) => fragment_v4(s, d, PROTO_UDP, &segment, mtu, next_id, out),
(IpAddr::V6(s), IpAddr::V6(d)) => fragment_v6(s, d, PROTO_UDP, &segment, mtu, next_id, out),
_ => Err(BuildError::MixedFamilies),
}
}
fn fragment_v4(
src: Ipv4Addr,
dst: Ipv4Addr,
protocol: u8,
segment: &[u8],
mtu: usize,
next_id: &mut u32,
out: &mut Vec<Vec<u8>>,
) -> Result<(), BuildError> {
if IPV4_HEADER_LEN + segment.len() > usize::from(u16::MAX) {
return Err(BuildError::TooLarge);
}
let ident = (*next_id & 0xffff) as u16;
*next_id = next_id.wrapping_add(1);
// Every fragment but the last carries a multiple of 8 bytes.
let per_fragment = (mtu.max(68) - IPV4_HEADER_LEN) & !7;
let mut offset = 0;
loop {
let end = (offset + per_fragment).min(segment.len());
let more = end < segment.len();
let chunk = &segment[offset..end];
let total = IPV4_HEADER_LEN + chunk.len();
let mut buf = vec![0u8; total];
let fields = Ipv4Fields {
ident,
more_fragments: more,
// Both fit: the datagram's size was checked above.
fragment_offset: u16::try_from(offset).map_err(|_| BuildError::TooLarge)?,
..v4_fields(
src,
dst,
protocol,
u16::try_from(total).map_err(|_| BuildError::TooLarge)?,
)
};
wire::write_ipv4(&mut buf, &fields);
buf[IPV4_HEADER_LEN..].copy_from_slice(chunk);
out.push(buf);
if !more {
return Ok(());
}
offset = end;
}
}
fn fragment_v6(
src: Ipv6Addr,
dst: Ipv6Addr,
protocol: u8,
segment: &[u8],
mtu: usize,
next_id: &mut u32,
out: &mut Vec<Vec<u8>>,
) -> Result<(), BuildError> {
let mtu = mtu.max(1280);
if IPV6_HEADER_LEN + segment.len() <= mtu {
let payload_len = u16::try_from(segment.len()).map_err(|_| BuildError::TooLarge)?;
let mut buf = vec![0u8; IPV6_HEADER_LEN + segment.len()];
wire::write_ipv6(&mut buf, src, dst, protocol, payload_len, DEFAULT_TTL);
buf[IPV6_HEADER_LEN..].copy_from_slice(segment);
out.push(buf);
return Ok(());
}
if segment.len() > usize::from(u16::MAX) {
return Err(BuildError::TooLarge);
}
let ident = *next_id;
*next_id = next_id.wrapping_add(1);
let per_fragment = (mtu - IPV6_HEADER_LEN - IPV6_FRAGMENT_HEADER_LEN) & !7;
let mut offset = 0;
loop {
let end = (offset + per_fragment).min(segment.len());
let more = end < segment.len();
let chunk = &segment[offset..end];
let payload_len = IPV6_FRAGMENT_HEADER_LEN + chunk.len();
let payload_len_u16 = u16::try_from(payload_len).map_err(|_| BuildError::TooLarge)?;
let offset_u16 = u16::try_from(offset).map_err(|_| BuildError::TooLarge)?;
let mut buf = vec![0u8; IPV6_HEADER_LEN + payload_len];
wire::write_ipv6(
&mut buf,
src,
dst,
IPV6_NEXT_FRAGMENT,
payload_len_u16,
DEFAULT_TTL,
);
let frag = &mut buf[IPV6_HEADER_LEN..IPV6_HEADER_LEN + IPV6_FRAGMENT_HEADER_LEN];
frag[0] = protocol;
frag[1] = 0;
frag[2..4].copy_from_slice(&(offset_u16 | u16::from(more)).to_be_bytes());
frag[4..8].copy_from_slice(&ident.to_be_bytes());
buf[IPV6_HEADER_LEN + IPV6_FRAGMENT_HEADER_LEN..].copy_from_slice(chunk);
out.push(buf);
if !more {
return Ok(());
}
offset = end;
}
}
/// The UDP datagram in a whole (unfragmented) IP payload, as
/// `(src port, dst port, data)`. A datagram whose length field disagrees
/// with the packet, or whose checksum is wrong, is `None`.
pub fn parse_udp<'a>(view: &IpView<'a>) -> Option<(u16, u16, &'a [u8])> {
let udp = wire::read_udp(view.payload)?;
let segment = &view.payload[..udp.len];
// A zero checksum means "none", over IPv4 only.
let checksum_absent = udp.checksum == 0 && view.src.is_ipv4();
if !checksum_absent && !wire::transport_checksum_ok(view.src, view.dst, PROTO_UDP, segment) {
return None;
}
Some((udp.src_port, udp.dst_port, &segment[UDP_HEADER_LEN..]))
}
+29
View File
@@ -0,0 +1,29 @@
//! Initial sequence numbers (RFC 6528): a keyed hash of the connection's
//! addresses plus a clock ticking every 4 µs, keyed by a random secret.
use std::hash::{DefaultHasher, Hash, Hasher};
use std::net::SocketAddr;
use crate::proxy::tun::netstack::engine::Instant;
#[derive(Clone, Copy, Debug)]
pub struct IsnGenerator {
secret: [u64; 2],
}
impl IsnGenerator {
pub fn new() -> Self {
IsnGenerator {
secret: [rand::random(), rand::random()],
}
}
pub fn isn(&self, now: Instant, client: SocketAddr, target: SocketAddr) -> u32 {
// `DefaultHasher::new()` has fixed keys; the secret goes into the
// input, which keys it just the same.
let mut h = DefaultHasher::new();
self.secret.hash(&mut h);
(client, target).hash(&mut h);
(h.finish() as u32).wrapping_add((now.as_micros() / 4) as u32)
}
}
+16
View File
@@ -0,0 +1,16 @@
//! A userspace network stack for the TUN inbound: IP packets in and out on
//! one side, accepted TCP streams and UDP datagrams on the other.
//!
//! IP parsing, fragment reassembly, UDP and the async driver around a TCP
//! engine written in Rust (`tcp`).
mod buf;
mod engine;
mod frag;
mod ip;
mod isn;
mod stack;
mod tcp;
mod wire;
pub use stack::{new, Config, TcpStream, UdpSocket};
+645
View File
@@ -0,0 +1,645 @@
//! The async face of the stack: one engine behind a lock, the packet queues
//! to and from the TUN device, and the TCP streams and UDP socket the
//! inbound hands to the dispatcher.
//!
//! Every operation runs against the engine synchronously under the lock and
//! then flushes what it produced — packets to send, connections to wake —
//! so the engine's buffers are the only place data waits. Nothing is copied
//! into a second per-connection buffer on the way to the application.
use std::collections::{HashMap, VecDeque};
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::time::Duration;
use futures::Stream;
use parking_lot::Mutex;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::sync::Notify;
use crate::proxy::tun::netstack::engine::{Accepted, ConnId, EngineStats, Instant, Limits};
use crate::proxy::tun::netstack::frag::{Reassembler, ReassemblyLimits};
use crate::proxy::tun::netstack::ip;
use crate::proxy::tun::netstack::tcp::TcpEngine;
/// Everything the stack is sized by.
#[derive(Clone, Copy, Debug)]
pub struct Config {
pub limits: Limits,
pub reassembly: ReassemblyLimits,
/// Packets waiting for the TUN device. Beyond it packets are dropped —
/// TCP retransmits them — rather than queued without bound.
pub max_output_packets: usize,
/// UDP datagrams received and not yet taken by the application.
pub max_udp_queue: usize,
}
impl Default for Config {
fn default() -> Self {
Config {
limits: Limits::default(),
reassembly: ReassemblyLimits::default(),
max_output_packets: 512,
max_udp_queue: 256,
}
}
}
/// Counters for the memory and loss checks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StackStats {
pub engine: EngineStats,
pub output_queued: usize,
pub output_queued_bytes: usize,
pub output_dropped: u64,
pub udp_queued: usize,
pub udp_queued_bytes: usize,
pub udp_dropped: u64,
pub accept_queued: usize,
pub fragments_held_bytes: usize,
pub fragments_dropped: u64,
/// Packets from the TUN device that were neither TCP nor UDP, or were
/// malformed.
pub input_ignored: u64,
}
#[derive(Default)]
struct Wakers {
read: Option<Waker>,
write: Option<Waker>,
}
struct Core {
engine: TcpEngine,
config: Config,
reassembler: Reassembler,
wakers: HashMap<ConnId, Wakers>,
accepted: VecDeque<Accepted>,
accept_waker: Option<Waker>,
output: VecDeque<Vec<u8>>,
output_bytes: usize,
output_waker: Option<Waker>,
output_dropped: u64,
udp_in: VecDeque<Datagram>,
udp_in_bytes: usize,
udp_waker: Option<Waker>,
udp_dropped: u64,
next_fragment_id: u32,
input_ignored: u64,
shut_down: bool,
scratch_packets: Vec<Vec<u8>>,
scratch_ready: Vec<ConnId>,
}
/// One UDP datagram as the application sees it.
pub type Datagram = (Vec<u8>, SocketAddr, SocketAddr);
impl Core {
/// Moves what the last engine call produced to where it goes, collecting
/// the wakers to call once the lock is released.
fn flush(&mut self, wake: &mut Vec<Waker>) {
self.engine.drain_output(&mut self.scratch_packets);
for packet in self.scratch_packets.drain(..) {
if self.output.len() >= self.config.max_output_packets {
self.output_dropped += 1;
continue;
}
self.output_bytes += packet.len();
self.output.push_back(packet);
}
if !self.output.is_empty() {
wake.extend(self.output_waker.take());
}
if !self.udp_in.is_empty() {
wake.extend(self.udp_waker.take());
}
self.engine.drain_ready(&mut self.scratch_ready);
for id in self.scratch_ready.drain(..) {
if let Some(w) = self.wakers.get_mut(&id) {
wake.extend(w.read.take());
wake.extend(w.write.take());
}
}
let mut accepted_any = false;
while let Some(conn) = self.engine.accept() {
if self.shut_down {
self.engine.abort(Instant::ZERO, conn.id);
continue;
}
self.wakers.insert(conn.id, Wakers::default());
self.accepted.push_back(conn);
accepted_any = true;
}
if accepted_any {
wake.extend(self.accept_waker.take());
}
}
fn input(&mut self, now: Instant, packet: &[u8]) {
let Some(view) = ip::parse(packet) else {
self.input_ignored += 1;
return;
};
if view.is_fragment() {
if let Some(whole) = self.reassembler.push(now, &view) {
self.input_whole(now, &whole);
}
return;
}
match view.protocol {
ip::PROTO_TCP => self.engine.input(now, packet),
ip::PROTO_UDP => self.input_udp(&view),
_ => self.input_ignored += 1,
}
}
fn input_whole(&mut self, now: Instant, packet: &[u8]) {
let Some(view) = ip::parse(packet) else {
self.input_ignored += 1;
return;
};
match view.protocol {
ip::PROTO_TCP => self.engine.input(now, packet),
ip::PROTO_UDP => self.input_udp(&view),
_ => self.input_ignored += 1,
}
}
fn input_udp(&mut self, view: &ip::IpView<'_>) {
let Some((src_port, dst_port, data)) = ip::parse_udp(view) else {
self.input_ignored += 1;
return;
};
if self.udp_in.len() >= self.config.max_udp_queue {
self.udp_dropped += 1;
return;
}
let src = SocketAddr::new(view.src, src_port);
let dst = SocketAddr::new(view.dst, dst_port);
self.udp_in_bytes += data.len();
self.udp_in.push_back((data.to_vec(), src, dst));
}
fn stats(&self) -> StackStats {
StackStats {
engine: self.engine.stats(),
output_queued: self.output.len(),
output_queued_bytes: self.output_bytes,
output_dropped: self.output_dropped,
udp_queued: self.udp_in.len(),
udp_queued_bytes: self.udp_in_bytes,
udp_dropped: self.udp_dropped,
accept_queued: self.accepted.len(),
fragments_held_bytes: self.reassembler.held_bytes(),
fragments_dropped: self.reassembler.dropped,
input_ignored: self.input_ignored,
}
}
}
struct Shared {
core: Mutex<Core>,
epoch: tokio::time::Instant,
/// Tells the timer task that an application call may have armed an
/// earlier timer than the one it sleeps on.
timer: Notify,
}
impl Shared {
fn now(&self) -> Instant {
let elapsed = self.epoch.elapsed();
Instant::from_micros(u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX))
}
fn deadline(&self, at: Instant) -> tokio::time::Instant {
self.epoch + Duration::from_micros(at.as_micros())
}
/// Runs `f` on the core under the lock, flushes, and wakes whoever the
/// call made ready once the lock is gone.
fn with_core<R>(&self, f: impl FnOnce(&mut Core, Instant) -> R) -> R {
let mut wake = Vec::new();
let result = {
let mut core = self.core.lock();
let now = self.now();
let result = f(&mut core, now);
core.flush(&mut wake);
result
};
for waker in wake {
waker.wake();
}
result
}
}
/// The stack. Dropping it shuts it down: every connection is reset, and the
/// streams, listener and UDP socket still held report the stack gone.
pub struct NetStack {
shared: Arc<Shared>,
}
/// Builds a stack and the two endpoints the inbound serves from it.
pub fn new(config: Config) -> (NetStack, TcpListener, UdpSocket) {
let core = Core {
engine: TcpEngine::new(config.limits),
config,
reassembler: Reassembler::new(config.reassembly),
wakers: HashMap::new(),
accepted: VecDeque::new(),
accept_waker: None,
output: VecDeque::new(),
output_bytes: 0,
output_waker: None,
output_dropped: 0,
udp_in: VecDeque::new(),
udp_in_bytes: 0,
udp_waker: None,
udp_dropped: 0,
next_fragment_id: rand::random(),
input_ignored: 0,
shut_down: false,
scratch_packets: Vec::new(),
scratch_ready: Vec::new(),
};
let shared = Arc::new(Shared {
core: Mutex::new(core),
epoch: tokio::time::Instant::now(),
timer: Notify::new(),
});
(
NetStack {
shared: shared.clone(),
},
TcpListener {
shared: shared.clone(),
},
UdpSocket { shared },
)
}
impl NetStack {
/// Feeds one IP packet read from the TUN device.
pub fn input(&self, packet: &[u8]) {
self.shared.with_core(|core, now| {
if !core.shut_down {
core.input(now, packet);
}
});
self.shared.timer.notify_one();
}
/// Packets for the TUN device, in order.
pub fn output(&self) -> PacketStream {
PacketStream {
shared: self.shared.clone(),
}
}
/// Runs the engine's timers. Must be polled for as long as the stack is
/// in use: retransmission, keep-alive and the end of every close happen
/// here.
pub fn driver(&self) -> impl Future<Output = ()> + Send + 'static {
let shared = self.shared.clone();
async move {
loop {
let deadline = {
let mut core = shared.core.lock();
if core.shut_down {
return;
}
let now = shared.now();
let engine_at = core.engine.poll_at(now);
let fragments_at = core.reassembler.next_expiry();
match (engine_at, fragments_at) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
};
match deadline {
Some(at) => {
tokio::select! {
_ = tokio::time::sleep_until(shared.deadline(at)) => {}
_ = shared.timer.notified() => {}
}
}
None => shared.timer.notified().await,
}
shared.with_core(|core, now| {
core.engine.poll(now);
core.reassembler.expire(now);
});
}
}
}
pub fn stats(&self) -> StackStats {
self.shared.core.lock().stats()
}
}
impl Drop for NetStack {
fn drop(&mut self) {
let mut wake = Vec::new();
{
let mut core = self.shared.core.lock();
core.shut_down = true;
let now = self.shared.now();
let ids: Vec<ConnId> = core.wakers.keys().copied().collect();
for id in ids {
core.engine.abort(now, id);
}
for conn in std::mem::take(&mut core.accepted) {
core.engine.abort(now, conn.id);
}
core.flush(&mut wake);
// The engine's memory goes now, not with the last stream still
// held somewhere: an empty engine takes its place, and every
// path to it checks `shut_down` first.
core.engine = TcpEngine::new(core.config.limits);
for w in core.wakers.values_mut() {
wake.extend(w.read.take());
wake.extend(w.write.take());
}
wake.extend(core.accept_waker.take());
wake.extend(core.udp_waker.take());
wake.extend(core.output_waker.take());
}
for waker in wake {
waker.wake();
}
self.shared.timer.notify_one();
}
}
/// Packets the stack wants written to the TUN device. Ends when the stack
/// has shut down and everything queued has been taken.
pub struct PacketStream {
shared: Arc<Shared>,
}
impl Stream for PacketStream {
type Item = Vec<u8>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Vec<u8>>> {
let mut core = self.shared.core.lock();
if let Some(packet) = core.output.pop_front() {
core.output_bytes -= packet.len();
return Poll::Ready(Some(packet));
}
if core.shut_down {
return Poll::Ready(None);
}
core.output_waker = Some(cx.waker().clone());
Poll::Pending
}
}
/// Connections the stack accepted, as `(stream, client, target)` — the
/// application's address and the one it was connecting to.
pub struct TcpListener {
shared: Arc<Shared>,
}
impl Stream for TcpListener {
type Item = (TcpStream, SocketAddr, SocketAddr);
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut core = self.shared.core.lock();
if let Some(conn) = core.accepted.pop_front() {
let stream = TcpStream {
shared: self.shared.clone(),
id: conn.id,
client: conn.client,
target: conn.target,
};
return Poll::Ready(Some((stream, conn.client, conn.target)));
}
if core.shut_down {
return Poll::Ready(None);
}
core.accept_waker = Some(cx.waker().clone());
Poll::Pending
}
}
/// One accepted connection. Dropping it closes the connection; data the
/// application never read resets it, as on a kernel socket.
pub struct TcpStream {
shared: Arc<Shared>,
id: ConnId,
client: SocketAddr,
target: SocketAddr,
}
impl TcpStream {
pub fn id(&self) -> ConnId {
self.id
}
/// The application's address.
pub fn client_addr(&self) -> SocketAddr {
self.client
}
/// The address the application connected to.
pub fn target_addr(&self) -> SocketAddr {
self.target
}
/// Resets the connection.
pub fn abort(&self) {
let id = self.id;
self.shared
.with_core(|core, now| core.engine.abort(now, id));
}
}
fn stack_gone() -> io::Error {
io::Error::new(io::ErrorKind::ConnectionAborted, "network stack shut down")
}
impl AsyncRead for TcpStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let id = self.id;
let result = self.shared.with_core(|core, now| {
if core.shut_down {
return Poll::Ready(Err(stack_gone()));
}
match core.engine.recv(now, id, buf.initialize_unfilled()) {
Ok(n) => {
buf.advance(n);
Poll::Ready(Ok(()))
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
if let Some(w) = core.wakers.get_mut(&id) {
w.read = Some(cx.waker().clone());
}
Poll::Pending
}
Err(e) => Poll::Ready(Err(e)),
}
});
// Reading opens the window: the update the engine queued may come
// with a timer.
self.shared.timer.notify_one();
result
}
}
impl AsyncWrite for TcpStream {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
data: &[u8],
) -> Poll<io::Result<usize>> {
let id = self.id;
let result = self.shared.with_core(|core, now| {
if core.shut_down {
return Poll::Ready(Err(stack_gone()));
}
match core.engine.send(now, id, data) {
Ok(n) => Poll::Ready(Ok(n)),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
if let Some(w) = core.wakers.get_mut(&id) {
w.write = Some(cx.waker().clone());
}
Poll::Pending
}
Err(e) => Poll::Ready(Err(e)),
}
});
self.shared.timer.notify_one();
result
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let id = self.id;
self.shared.with_core(|core, now| {
if !core.shut_down {
core.engine.shutdown_write(now, id);
}
});
self.shared.timer.notify_one();
Poll::Ready(Ok(()))
}
}
impl Drop for TcpStream {
fn drop(&mut self) {
let id = self.id;
self.shared.with_core(|core, now| {
core.wakers.remove(&id);
if !core.shut_down {
core.engine.close(now, id);
}
});
self.shared.timer.notify_one();
}
}
/// UDP to and from every address behind the TUN device.
pub struct UdpSocket {
shared: Arc<Shared>,
}
impl UdpSocket {
pub fn split(self) -> (UdpSendHalf, UdpRecvHalf) {
(
UdpSendHalf {
shared: self.shared.clone(),
},
UdpRecvHalf {
shared: self.shared,
},
)
}
}
pub struct UdpSendHalf {
shared: Arc<Shared>,
}
impl UdpSendHalf {
/// Sends `data` to the application at `dst`, as if from `src`.
pub fn send_to(&self, data: &[u8], src: &SocketAddr, dst: &SocketAddr) -> io::Result<()> {
let mut wake = Vec::new();
let result = {
let mut core = self.shared.core.lock();
if core.shut_down {
return Err(stack_gone());
}
let mtu = core.config.limits.mtu;
let mut packets = std::mem::take(&mut core.scratch_packets);
let mut next_id = core.next_fragment_id;
let built = ip::build_udp(*src, *dst, data, mtu, &mut next_id, &mut packets);
core.next_fragment_id = next_id;
let result = match built {
Ok(()) => {
// All fragments or none: a partial datagram is useless.
if core.output.len() + packets.len() > core.config.max_output_packets {
core.output_dropped += packets.len() as u64;
packets.clear();
}
for packet in packets.drain(..) {
core.output_bytes += packet.len();
core.output.push_back(packet);
}
Ok(())
}
Err(e) => {
packets.clear();
Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("{e:?}"),
))
}
};
core.scratch_packets = packets;
if !core.output.is_empty() {
wake.extend(core.output_waker.take());
}
result
};
for waker in wake {
waker.wake();
}
result
}
}
/// UDP datagrams from the applications, as `(data, src, dst)`.
pub struct UdpRecvHalf {
shared: Arc<Shared>,
}
impl Stream for UdpRecvHalf {
type Item = Datagram;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Datagram>> {
let mut core = self.shared.core.lock();
if let Some(datagram) = core.udp_in.pop_front() {
core.udp_in_bytes -= datagram.0.len();
return Poll::Ready(Some(datagram));
}
if core.shut_down {
return Poll::Ready(None);
}
core.udp_waker = Some(cx.waker().clone());
Poll::Pending
}
}
+196
View File
@@ -0,0 +1,196 @@
//! The application's side of each connection: what it has been told, what
//! it may still read, and the readiness it is woken for.
//!
//! Received data is copied out of the connection as it arrives; the window
//! reopens only as the application reads it, so the window still measures
//! what the application has consumed.
use std::collections::{HashMap, VecDeque};
use std::net::SocketAddr;
use super::config::WINDOW;
use super::conn::Handler;
use super::stack::ConnKey;
use crate::proxy::tun::netstack::engine::{Accepted, ConnId};
pub struct AppConn {
/// The connection while the stack still holds one for it.
pub conn: Option<ConnKey>,
/// Both FINs are out and the stack finishes the connection alone,
/// counted among its connections rather than here.
pub handed_over: bool,
pub rx: VecDeque<u8>,
pub fin: bool,
pub reset: bool,
pub write_shut: bool,
/// Taken by `accept`.
pub open: bool,
}
/// How a connection ended under the application.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Ending {
/// Both FINs exchanged and acknowledged.
Closed,
/// Reset by the peer, or aborted for a timeout.
Reset,
}
pub struct Apps {
pub conns: HashMap<ConnId, AppConn>,
pub accepted: VecDeque<Accepted>,
pub ready: Vec<ConnId>,
next_id: ConnId,
max_connections: usize,
pub rx_bytes: usize,
/// Entries of `conns` that still have a connection.
attached: usize,
/// Entries of `conns` whose connection was handed over.
handed_over: usize,
}
impl Apps {
pub fn new(max_connections: usize) -> Apps {
Apps {
conns: HashMap::new(),
accepted: VecDeque::new(),
ready: Vec::new(),
next_id: 1,
max_connections,
rx_bytes: 0,
attached: 0,
handed_over: 0,
}
}
/// Takes on a connection whose handshake completed; `None` when the
/// application already holds as many as it may.
pub fn accept(
&mut self,
key: ConnKey,
client: SocketAddr,
target: SocketAddr,
) -> Option<ConnId> {
if self.attached >= self.max_connections {
return None;
}
let id = self.next_id;
self.next_id += 1;
self.conns.insert(
id,
AppConn {
conn: Some(key),
handed_over: false,
rx: VecDeque::new(),
fin: false,
reset: false,
write_shut: false,
open: false,
},
);
self.attached += 1;
self.accepted.push_back(Accepted { id, client, target });
Some(id)
}
/// Something may have changed for the application holding `handler`:
/// space to write, or just the periodic nudge.
pub fn wake(&mut self, handler: Handler) {
if let Some(id) = handler.app() {
self.ready.push(id);
}
}
pub fn data(&mut self, id: ConnId, chunk: &[u8]) {
if let Some(conn) = self.conns.get_mut(&id) {
self.rx_bytes += chunk.len();
// No more than the window is ever outstanding.
crate::proxy::tun::netstack::buf::extend_bounded(
&mut conn.rx,
chunk,
usize::from(WINDOW),
);
self.ready.push(id);
}
}
pub fn fin(&mut self, id: ConnId) {
if let Some(conn) = self.conns.get_mut(&id) {
conn.fin = true;
self.ready.push(id);
}
}
pub fn ended(&mut self, handler: Handler, how: Ending) {
let Some(id) = handler.app() else {
return;
};
let Some(conn) = self.conns.get_mut(&id) else {
return;
};
if conn.conn.take().is_some() {
self.attached -= 1;
}
match how {
Ending::Closed => conn.fin = true,
Ending::Reset => {
// As on a kernel socket, a reset discards what was not read:
// the next read reports the reset.
conn.reset = true;
self.rx_bytes -= conn.rx.len();
conn.rx = VecDeque::new();
}
}
self.ready.push(id);
}
/// The connection behind `id`, no longer the application's to use.
pub fn detach(&mut self, id: ConnId) -> Option<ConnKey> {
let key = self.conns.get_mut(&id)?.conn.take()?;
self.attached -= 1;
Some(key)
}
/// The application lets go of a connection whose FINs are both out;
/// reading what is left no longer reopens the window.
pub fn hand_over(&mut self, id: ConnId) {
let Some(conn) = self.conns.get_mut(&id) else {
return;
};
if conn.conn.take().is_some() {
self.attached -= 1;
conn.handed_over = true;
self.handed_over += 1;
}
}
pub fn remove(&mut self, id: ConnId) -> Option<AppConn> {
let conn = self.conns.remove(&id)?;
self.rx_bytes -= conn.rx.len();
if conn.conn.is_some() {
self.attached -= 1;
}
if conn.handed_over {
self.handed_over -= 1;
}
Some(conn)
}
/// Entries the application holds with no connection behind them.
pub fn orphans(&self) -> usize {
self.conns.len() - self.attached - self.handed_over
}
pub fn shrink(&mut self) {
let shrink = crate::proxy::tun::netstack::buf::should_shrink;
if shrink(self.conns.len(), self.conns.capacity()) {
self.conns.shrink_to(self.conns.len() * 2);
}
if shrink(self.ready.len(), self.ready.capacity()) {
self.ready.shrink_to(self.ready.len() * 2);
}
if shrink(self.accepted.len(), self.accepted.capacity()) {
self.accepted.shrink_to(self.accepted.len() * 2);
}
}
}
+65
View File
@@ -0,0 +1,65 @@
//! The configuration this TCP runs with: lwIP's options as set for a TUN
//! stack, the lwIP defaults left in place, and the per-connection settings
//! applied on accept.
pub const MSS: u16 = 1460;
/// The receive window, which is also the most a connection buffers unread.
pub const WINDOW: u16 = 32 * MSS;
/// Bytes the application may have queued unacknowledged.
pub const SEND_BUFFER: u16 = 16 * MSS;
/// Pbufs the send queue may hold: four per maximum segment of the buffer.
pub const SEND_QUEUE_PBUFS: u16 = (4 * SEND_BUFFER as u32).div_ceil(MSS as u32) as u16;
const SEND_QUEUE_OVERFLOW: u16 = 0xffff - 3;
/// The limit a write's pbufs are checked against.
pub const SEND_QUEUE_LIMIT: u16 = if SEND_QUEUE_PBUFS < SEND_QUEUE_OVERFLOW {
SEND_QUEUE_PBUFS
} else {
SEND_QUEUE_OVERFLOW
};
/// How far reading must reopen the window before it is announced at once.
pub const WINDOW_UPDATE_THRESHOLD: u32 = {
let quarter = WINDOW as u32 / 4;
let four_mss = MSS as u32 * 4;
if quarter < four_mss {
quarter
} else {
four_mss
}
};
pub const OUT_OF_ORDER_MAX_BYTES: u32 = WINDOW as u32;
pub const OUT_OF_ORDER_MAX_SEGMENTS: u16 = 64;
/// Extra room a send pbuf is given when more writes may fill it.
pub const OVERSIZE: u16 = MSS;
pub const MEM_ALIGNMENT: u16 = 8;
pub const TTL: u8 = 64;
pub const MAX_RETRANSMITS: u8 = 12;
pub const INITIAL_MSS: u16 = 536;
/// Pushed segments are acknowledged at once, not on the next fast-timer
/// tick, which a Nagle-using peer would otherwise wait out on every write.
pub const ACK_PUSHED_AT_ONCE: bool = true;
/// The TCP timer runs this often; every other run is a slow tick.
pub const TIMER_INTERVAL_MS: u32 = 250;
pub const SLOW_TICK_MS: u32 = 2 * TIMER_INTERVAL_MS;
pub const FIN_WAIT_2_TIMEOUT_TICKS: u32 = 20_000 / SLOW_TICK_MS;
pub const SYN_RECEIVED_TIMEOUT_TICKS: u32 = 20_000 / SLOW_TICK_MS;
/// Twice the maximum segment lifetime: how long TIME-WAIT and LAST-ACK last.
pub const TWO_MSL_TICKS: u32 = 2 * 60_000 / SLOW_TICK_MS;
/// Out-of-order data is dropped after this many RTOs without a segment.
pub const OUT_OF_ORDER_TIMEOUT_RTOS: u32 = 6;
pub const INITIAL_RTO_TICKS: i16 = (3000 / SLOW_TICK_MS) as i16;
/// RTO multipliers by retransmission count (as shifts).
pub const RTO_BACKOFF: [u8; 13] = [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7];
/// Slow ticks between window probes, by persist round.
pub const PERSIST_BACKOFF: [u8; 7] = [3, 6, 12, 24, 48, 96, 120];
/// Keep-alive as configured on accept.
pub const KEEPALIVE_INTERVAL_MS: u32 = 10_000;
pub const KEEPALIVE_PROBES: u32 = 6;
/// Connections the stack holds at once (lwIP's PCB pool).
pub const CONNECTION_POOL: usize = if cfg!(target_os = "ios") { 256 } else { 1024 };
/// Pbufs packets from the TUN device are read into.
pub const PBUF_POOL_SIZE: usize = if cfg!(target_os = "ios") { 128 } else { 256 };
/// Bytes per pool pbuf: MSS plus IPv6, TCP and link headers, aligned.
pub const PBUF_POOL_BUFSIZE: usize = 1536;
+352
View File
@@ -0,0 +1,352 @@
//! One connection's state, grouped by what each part is for. The logic
//! lives beside it, by side: `receive`, `send`, `input`, `timer`.
use std::collections::VecDeque;
use std::net::SocketAddr;
use super::config::{INITIAL_MSS, INITIAL_RTO_TICKS, SEND_BUFFER, WINDOW};
use super::segment::Segment;
use super::seq::{SeqNum, Ticks};
use super::stack::ConnKey;
use crate::proxy::tun::netstack::engine::ConnId;
/// The TCP states a passive connection goes through.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
SynReceived,
Established,
FinWait1,
FinWait2,
CloseWait,
Closing,
LastAck,
TimeWait,
Closed,
}
impl State {
/// Past the handshake.
pub fn is_synchronized(self) -> bool {
!matches!(self, State::SynReceived | State::Closed)
}
/// Still taking data from the peer: no FIN received yet.
pub fn receives_data(self) -> bool {
matches!(
self,
State::SynReceived | State::Established | State::FinWait1 | State::FinWait2
)
}
/// The application may still queue data.
pub fn accepts_writes(self) -> bool {
matches!(
self,
State::Established | State::CloseWait | State::SynReceived
)
}
}
/// Who hears about the connection.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Handler {
/// Not accepted yet: data is consumed on the application's behalf and
/// a FIN closes the connection.
Unaccepted,
/// Held by the application as this id.
App(ConnId),
/// The application let go: data resets the connection, and nothing is
/// reported.
Released,
}
impl Handler {
pub fn app(self) -> Option<ConnId> {
match self {
Handler::App(id) => Some(id),
_ => None,
}
}
}
/// An ACK owed to the peer. lwIP keeps "owed, may wait for the fast timer"
/// and "send now" apart: both can be set, and the fast timer acts on the
/// first whether or not the second is set.
#[derive(Clone, Copy, Debug, Default)]
pub struct AckState {
pub delayed: bool,
pub now: bool,
}
impl AckState {
/// One more segment to acknowledge: the second in a row is answered at
/// once.
pub fn owe(&mut self) {
if self.delayed {
self.delayed = false;
self.now = true;
} else {
self.delayed = true;
}
}
pub fn sent(&mut self) {
*self = AckState::default();
}
}
/// The receive half.
#[derive(Debug)]
pub struct Receiver {
pub next: SeqNum,
/// Room left in the window, data received and not yet read counted out.
pub window: u16,
/// The window last put in a segment.
pub announced: u16,
/// Where the last announced window ends.
pub announced_edge: SeqNum,
/// Segments past a hole, in sequence order.
pub out_of_order: VecDeque<Segment>,
}
/// The send half. `unacked` holds what is in flight, `unsent` what the
/// windows have not let out yet, both in sequence order.
#[derive(Debug)]
pub struct Sender {
/// Everything before this is acknowledged.
pub acked: SeqNum,
pub next: SeqNum,
/// One past the last byte the application queued.
pub queued_end: SeqNum,
pub window: u16,
pub max_window: u16,
/// The segment that last updated `window` (its sequence and ACK).
pub window_seq: SeqNum,
pub window_ack: SeqNum,
/// Bytes the application may still queue.
pub space: u16,
/// Pbufs the queues hold.
pub queued_pbufs: u16,
/// Spare room of the last unsent segment's pbuf.
pub oversize: u16,
pub unsent: VecDeque<Segment>,
pub unacked: VecDeque<Segment>,
}
/// The retransmission timer, in slow ticks since it was (re)started;
/// stopped is below every RTO but a negative one.
#[derive(Clone, Copy, Debug)]
pub struct RetransmitTimer(i16);
impl RetransmitTimer {
pub const STOPPED: RetransmitTimer = RetransmitTimer(-1);
pub fn restart(&mut self) {
self.0 = 0;
}
pub fn stop(&mut self) {
*self = Self::STOPPED;
}
pub fn start_if_stopped(&mut self) {
if self.0 < 0 {
self.0 = 0;
}
}
pub fn is_running(self) -> bool {
self.0 >= 0
}
pub fn tick(&mut self) {
if self.0 >= 0 && self.0 < i16::MAX {
self.0 += 1;
}
}
pub fn reached(self, rto: i16) -> bool {
self.0 >= rto
}
}
/// Jacobson's estimator, in ticks scaled as lwIP scales them: `sa` holds
/// eight times the mean, `sv` four times the deviation.
#[derive(Clone, Copy, Debug)]
pub struct RttEstimator {
pub sa: i16,
pub sv: i16,
}
impl RttEstimator {
pub fn rto(self) -> i16 {
(i32::from(self.sa >> 3) + i32::from(self.sv)) as i16
}
pub fn sample(&mut self, rtt_ticks: i16) {
let mut m = rtt_ticks;
m = (i32::from(m) - i32::from(self.sa >> 3)) as i16;
self.sa = (i32::from(self.sa) + i32::from(m)) as i16;
if m < 0 {
m = (-i32::from(m)) as i16;
}
m = (i32::from(m) - i32::from(self.sv >> 2)) as i16;
self.sv = (i32::from(self.sv) + i32::from(m)) as i16;
}
}
/// Retransmission and congestion state.
#[derive(Debug)]
pub struct Retransmission {
pub timer: RetransmitTimer,
pub rto: i16,
pub rtt: RttEstimator,
/// The segment being timed: when it was sent and where it starts.
pub timing: Option<(Ticks, SeqNum)>,
/// Retransmissions since the last new ACK.
pub count: u8,
pub dupacks: u8,
pub cwnd: u16,
pub ssthresh: u16,
pub bytes_acked: u16,
pub fast_recovery: bool,
/// After an RTO, the end of what was in flight: slow start grows by one
/// segment per ACK until it is acknowledged.
pub rto_recovery_end: Option<SeqNum>,
}
/// Probing a window too small for the next segment.
#[derive(Clone, Copy, Debug)]
pub struct Persist {
/// Slow ticks counted toward the next probe.
pub ticks: u8,
/// Which probe interval (1-based, into `PERSIST_BACKOFF`).
pub round: u8,
/// Zero-window probes sent unanswered.
pub probes: u8,
}
/// Keep-alive probing; how long to wait is the engine's, not the
/// connection's.
#[derive(Clone, Copy, Debug, Default)]
pub struct KeepAlive {
/// Probes sent unanswered.
pub sent: u8,
}
pub struct Connection {
pub key: ConnKey,
pub local: SocketAddr,
pub remote: SocketAddr,
pub state: State,
pub handler: Handler,
pub mss: u16,
/// When the peer was last heard from (kept still once the application
/// has stopped reading).
pub last_activity: Ticks,
pub ack: AckState,
/// Nagle is off.
pub nodelay: bool,
/// The application will read no more.
pub rx_closed: bool,
/// A FIN is queued.
pub fin_queued: bool,
/// A close waits for memory to queue its FIN.
pub close_pending: bool,
/// A write failed for want of memory: send what is queued regardless of
/// Nagle.
pub write_failed: bool,
pub rcv: Receiver,
pub snd: Sender,
pub rtx: Retransmission,
pub persist: Option<Persist>,
pub keepalive: Option<KeepAlive>,
/// The stack has let it go; it is dropped instead of put back.
pub forget: bool,
}
impl Connection {
/// A connection for a SYN from `remote` to `local`, our ISN `iss`.
pub fn new(
key: ConnKey,
local: SocketAddr,
remote: SocketAddr,
now: Ticks,
peer_isn: SeqNum,
iss: SeqNum,
) -> Connection {
let rcv_next = peer_isn + 1;
Connection {
key,
local,
remote,
state: State::SynReceived,
handler: Handler::Unaccepted,
mss: INITIAL_MSS,
last_activity: now,
ack: AckState::default(),
nodelay: false,
rx_closed: false,
fin_queued: false,
close_pending: false,
write_failed: false,
rcv: Receiver {
next: rcv_next,
window: WINDOW,
announced: WINDOW,
announced_edge: rcv_next,
out_of_order: VecDeque::new(),
},
snd: Sender {
acked: iss,
next: iss,
queued_end: iss,
window: 0,
max_window: 0,
window_seq: peer_isn - 1,
window_ack: iss,
space: SEND_BUFFER,
queued_pbufs: 0,
oversize: 0,
unsent: VecDeque::new(),
unacked: VecDeque::new(),
},
rtx: Retransmission {
timer: RetransmitTimer::STOPPED,
rto: INITIAL_RTO_TICKS,
rtt: RttEstimator {
sa: 0,
sv: INITIAL_RTO_TICKS,
},
timing: None,
count: 0,
dupacks: 0,
cwnd: 1,
ssthresh: SEND_BUFFER,
bytes_acked: 0,
fast_recovery: false,
rto_recovery_end: None,
},
persist: None,
keepalive: None,
forget: false,
}
}
/// Payload bytes the queues hold.
pub fn buffered(&self) -> usize {
let sum = |q: &VecDeque<Segment>| q.iter().map(|s| s.data.len()).sum::<usize>();
sum(&self.snd.unsent) + sum(&self.snd.unacked) + sum(&self.rcv.out_of_order)
}
/// Drops every queued segment of a connection that is going away.
pub fn purge(&mut self) {
if !matches!(self.state, State::Closed | State::TimeWait) {
self.rcv.out_of_order.clear();
self.rtx.timer.stop();
self.snd.unsent.clear();
self.snd.unacked.clear();
self.snd.oversize = 0;
}
}
}
+465
View File
@@ -0,0 +1,465 @@
//! A packet from the TUN device: the drops IP makes before TCP sees it,
//! finding its connection (or opening one for a SYN), and the connection's
//! state machine.
use std::net::{IpAddr, SocketAddr};
use super::app::Ending;
use super::config::{MSS, WINDOW};
use super::conn::{Connection, Handler, KeepAlive, State};
use super::receive::Chunk;
use super::segment::TcpFlags;
use super::seq::SeqNum;
use super::stack::{Env, Stack};
use crate::proxy::tun::netstack::ip;
use crate::proxy::tun::netstack::wire::{self, TCP_HEADER_LEN};
/// One received segment's header and payload.
pub struct Incoming<'a> {
pub local: SocketAddr,
pub remote: SocketAddr,
pub seq: SeqNum,
pub ack: SeqNum,
pub flags: TcpFlags,
pub window: u16,
/// Sequence space taken: payload, plus one for a SYN or FIN.
pub len: u16,
pub options: &'a [u8],
pub payload: &'a [u8],
}
/// What processing a segment found, for what follows it.
#[derive(Default)]
pub struct Received<'a> {
/// An acceptable RST.
pub reset: bool,
/// Our FIN was acknowledged in LAST-ACK: the connection is over.
pub closed: bool,
pub got_fin: bool,
/// Bytes newly acknowledged.
pub acked: u16,
/// Data now in order, for the application.
pub data: Vec<Chunk<'a>>,
}
/// The segment in `packet`, or `None` for what IP or TCP would drop.
fn parse(packet: &[u8]) -> Option<Incoming<'_>> {
let view = ip::parse(packet)?;
if view.is_fragment() || view.protocol != wire::PROTO_TCP {
return None;
}
if view.src.is_ipv4() && !wire::ipv4_header_checksum_ok(packet) {
return None;
}
let broadcast =
|a: IpAddr| matches!(a, IpAddr::V4(v4) if v4.is_broadcast() || v4.is_unspecified());
if broadcast(view.src) || view.src.is_multicast() {
return None;
}
let segment = view.payload;
if segment.len() < TCP_HEADER_LEN || broadcast(view.dst) || view.dst.is_multicast() {
return None;
}
if !wire::transport_checksum_ok(view.src, view.dst, wire::PROTO_TCP, segment) {
return None;
}
let header = wire::read_tcp(segment)?;
let flags = TcpFlags::from_header(segment[13]);
let payload = &segment[header.header_len..];
let mut len = payload.len() as u16;
if flags.has_any(TcpFlags::SYN | TcpFlags::FIN) {
len = len.checked_add(1)?;
}
Some(Incoming {
local: SocketAddr::new(view.dst, header.dst_port),
remote: SocketAddr::new(view.src, header.src_port),
seq: SeqNum::new(header.seq),
ack: SeqNum::new(header.ack),
flags,
window: header.window,
len,
options: &segment[TCP_HEADER_LEN..header.header_len],
payload,
})
}
/// The MSS option among `options`, as lwIP reads it: up to the end-of-list
/// or a malformed option; zero or more than our MSS means our MSS.
fn mss_option(options: &[u8]) -> Option<u16> {
let mut mss = None;
let mut i = 0;
while i < options.len() {
match options[i] {
0 => break,
1 => i += 1,
2 => {
if options.get(i + 1) != Some(&4) || i + 4 > options.len() {
break;
}
let value = u16::from_be_bytes([options[i + 2], options[i + 3]]);
mss = Some(if value > MSS || value == 0 {
MSS
} else {
value
});
i += 4;
}
_ => match options.get(i + 1) {
Some(&len) if len >= 2 => i += usize::from(len),
_ => break,
},
}
}
mss
}
impl Stack {
/// Finds the segment's connection and hands it the segment.
pub fn on_packet(&mut self, packet: &[u8]) {
let Some(seg) = parse(packet) else {
return;
};
let Some(key) = self.find(seg.local, seg.remote) else {
self.on_unknown(&seg);
return;
};
self.touch(key);
self.with_conn(key, |conn, env| {
if conn.state == State::TimeWait {
conn.on_time_wait_segment(&seg, env);
} else {
conn.on_segment(&seg, env);
}
});
}
/// A segment for no connection: a SYN opens one, anything else
/// acknowledging something is answered with a reset.
fn on_unknown(&mut self, seg: &Incoming<'_>) {
if seg.flags.has(TcpFlags::RST) {
return;
}
if seg.flags.has(TcpFlags::ACK) {
self.env
.net
.send_reset(seg.local, seg.remote, seg.ack, seg.seq + u32::from(seg.len));
return;
}
if !seg.flags.has(TcpFlags::SYN) {
return;
}
// No room for it: the SYN goes unanswered.
let Some(key) = self.open() else {
return;
};
let env = &mut self.env;
let iss = SeqNum::new(env.isn.isn(env.now, seg.remote, seg.local));
let mut conn = Connection::new(key, seg.local, seg.remote, env.ticks, seg.seq, iss);
conn.on_syn(seg, env);
self.adopt(conn);
}
}
impl Connection {
/// Answers the SYN that opened the connection.
fn on_syn(&mut self, seg: &Incoming<'_>, env: &mut Env) {
if let Some(mss) = mss_option(seg.options) {
self.mss = mss;
}
self.snd.window = seg.window;
self.snd.max_window = seg.window;
self.mss = env.net.effective_mss(self.mss, self.remote);
if self
.queue_control(TcpFlags::SYN | TcpFlags::ACK, env)
.is_err()
{
self.abandon(false, env);
return;
}
self.output(env);
}
/// TIME-WAIT answers anything with sequence space by acknowledging it
/// again; a FIN restarts the wait, a SYN in the window is reset.
fn on_time_wait_segment(&mut self, seg: &Incoming<'_>, env: &mut Env) {
if seg.flags.has(TcpFlags::RST) {
return;
}
if seg.flags.has(TcpFlags::SYN) {
let window_end = self.rcv.next + u32::from(self.rcv.window);
if seg.seq.within(self.rcv.next, window_end) {
env.net.send_reset(
self.local,
self.remote,
seg.ack,
seg.seq + u32::from(seg.len),
);
return;
}
} else if seg.flags.has(TcpFlags::FIN) {
self.last_activity = env.ticks;
}
if seg.len > 0 {
self.ack.now = true;
self.output(env);
}
}
/// A segment for a connection past its SYN: the state machine, then the
/// application hears what it brought, then whatever can go out goes.
pub fn on_segment<'a>(&mut self, seg: &Incoming<'a>, env: &mut Env) {
let mut rx = Received::default();
env.input = Some(self.key);
env.closed_during_input = false;
match self.process(seg, &mut rx, env) {
Some(()) if rx.reset => {
env.apps.ended(self.handler, Ending::Reset);
self.retire(env);
}
Some(()) => self.deliver(rx, env),
None => {}
}
env.input = None;
}
/// The state machine for one segment; `None` if the connection was
/// aborted on the way.
fn process<'a>(
&mut self,
seg: &Incoming<'a>,
rx: &mut Received<'a>,
env: &mut Env,
) -> Option<()> {
if seg.flags.has(TcpFlags::RST) {
if seg.seq == self.rcv.next {
rx.reset = true;
self.ack.delayed = false;
} else if seg
.seq
.within(self.rcv.next, self.rcv.next + u32::from(self.rcv.window))
{
// RFC 5961: a RST in the window but not exactly next gets a
// challenge ACK.
self.ack.now = true;
}
return Some(());
}
if seg.flags.has(TcpFlags::SYN) && self.state != State::SynReceived {
self.ack.now = true;
return Some(());
}
if !self.rx_closed {
self.last_activity = env.ticks;
}
if let Some(keepalive) = self.keepalive.as_mut() {
keepalive.sent = 0;
}
if let Some(persist) = self.persist.as_mut() {
persist.probes = 0;
}
match self.state {
State::SynReceived => self.on_handshake_segment(seg, rx, env)?,
State::Established | State::CloseWait => {
self.on_ack(seg, rx, env);
self.on_data(seg, rx, env);
if rx.got_fin {
self.ack.now = true;
self.state = State::CloseWait;
}
}
State::FinWait1 => {
self.on_ack(seg, rx, env);
self.on_data(seg, rx, env);
let all_acked = self.acks_everything(seg);
if rx.got_fin {
self.ack.now = true;
if all_acked {
self.enter_time_wait();
} else {
self.state = State::Closing;
}
} else if all_acked {
self.state = State::FinWait2;
}
}
State::FinWait2 => {
self.on_ack(seg, rx, env);
self.on_data(seg, rx, env);
if rx.got_fin {
self.ack.now = true;
self.enter_time_wait();
}
}
State::Closing => {
self.on_ack(seg, rx, env);
self.on_data(seg, rx, env);
if self.acks_everything(seg) {
self.enter_time_wait();
}
}
State::LastAck => {
self.on_ack(seg, rx, env);
self.on_data(seg, rx, env);
if self.acks_everything(seg) {
rx.closed = true;
}
}
State::TimeWait | State::Closed => {}
}
Some(())
}
/// The segment acknowledges all we have sent, FIN included, with
/// nothing left unsent.
fn acks_everything(&self, seg: &Incoming<'_>) -> bool {
seg.flags.has(TcpFlags::ACK) && seg.ack == self.snd.next && self.snd.unsent.is_empty()
}
/// SYN-RECEIVED: a repeated SYN gets the SYN-ACK again; the ACK of ours
/// completes the handshake and hands the connection to the
/// application — or resets it if the application holds too many.
fn on_handshake_segment<'a>(
&mut self,
seg: &Incoming<'a>,
rx: &mut Received<'a>,
env: &mut Env,
) -> Option<()> {
if seg.flags.has(TcpFlags::SYN) {
if seg.seq == self.rcv.next - 1 {
self.retransmit_oldest();
}
return Some(());
}
if !seg.flags.has(TcpFlags::ACK) {
return Some(());
}
if !seg.ack.within(self.snd.acked + 1, self.snd.next) {
env.net.send_reset(
self.local,
self.remote,
seg.ack,
seg.seq + u32::from(seg.len),
);
return Some(());
}
self.state = State::Established;
let Some(id) = env.apps.accept(self.key, self.remote, self.local) else {
self.abort(env);
return None;
};
self.handler = Handler::App(id);
self.nodelay = true;
if env.keepalive_idle_ms != 0 {
self.keepalive = Some(KeepAlive::default());
}
self.on_ack(seg, rx, env);
self.on_data(seg, rx, env);
// The SYN-ACK counted as one acknowledged byte.
rx.acked = rx.acked.saturating_sub(1);
self.rtx.cwnd = initial_cwnd(self.mss);
if rx.got_fin {
self.ack.now = true;
self.state = State::CloseWait;
}
Some(())
}
fn enter_time_wait(&mut self) {
self.purge();
self.state = State::TimeWait;
}
/// After the state machine: the application hears what was
/// acknowledged, the data, and the FIN, in that order; then the
/// connection ends if it is over, or sends what it can.
fn deliver<'a>(&mut self, mut rx: Received<'a>, env: &mut Env) {
if rx.acked > 0 {
env.apps.wake(self.handler);
rx.acked = 0;
}
if self.close_if_over(&rx, env) {
return;
}
if !rx.data.is_empty() && !self.give_data(&rx.data, env) {
return;
}
if rx.got_fin {
if self.rcv.window != WINDOW {
self.rcv.window += 1;
}
if !self.give_fin(env) {
return;
}
}
env.input = None;
if self.close_if_over(&rx, env) {
return;
}
self.output(env);
}
/// Ends the connection if it is over: closed in LAST-ACK, or reset by
/// a close while the segment was processed.
fn close_if_over(&mut self, rx: &Received<'_>, env: &mut Env) -> bool {
if !rx.closed && !env.closed_during_input {
return false;
}
if !self.rx_closed {
env.apps.ended(self.handler, Ending::Closed);
}
self.retire(env);
true
}
/// In-order data to whoever handles the connection; false if that
/// aborted it.
fn give_data(&mut self, data: &[Chunk<'_>], env: &mut Env) -> bool {
if self.rx_closed {
self.abort(env);
return false;
}
match self.handler {
Handler::Unaccepted => {
let len: usize = data.iter().map(|c| c.bytes().len()).sum();
self.app_read(len as u16, env);
true
}
Handler::Released => {
self.abort(env);
false
}
Handler::App(id) => {
for chunk in data {
env.apps.data(id, chunk.bytes());
}
true
}
}
}
/// The peer's FIN to whoever handles the connection; false if that
/// aborted it.
fn give_fin(&mut self, env: &mut Env) -> bool {
match self.handler {
Handler::Unaccepted => {
self.close(env);
true
}
Handler::Released => true,
Handler::App(id) => {
env.apps.fin(id);
if matches!(self.state, State::Closing | State::TimeWait) {
env.apps.hand_over(id);
self.handler = Handler::Released;
}
true
}
}
}
}
/// The congestion window a connection starts with (RFC 3390).
fn initial_cwnd(mss: u16) -> u16 {
let mss = u32::from(mss);
(4 * mss).min((2 * mss).max(4380)) as u16
}
@@ -0,0 +1,117 @@
//! How a connection ends: closed by the application or by the peer,
//! aborted, or given up on.
use super::app::Ending;
use super::config::WINDOW;
use super::conn::{Connection, Handler, State};
use super::stack::Env;
impl Connection {
/// Leaves the connection for good: queues dropped, an owed delayed ACK
/// sent first, then the stack forgets it.
pub fn retire(&mut self, env: &mut Env) {
self.purge();
if !matches!(self.state, State::TimeWait) && self.ack.delayed {
self.ack.now = true;
self.output(env);
}
self.state = State::Closed;
self.forget = true;
}
/// Drops the connection, resetting it if `reset` and it was still
/// synchronised; the application hears it as a reset.
pub fn abandon(&mut self, reset: bool, env: &mut Env) {
if self.state == State::TimeWait {
self.state = State::Closed;
self.forget = true;
return;
}
let (seq, ack, handler) = (self.snd.next, self.rcv.next, self.handler);
let was_open = self.state != State::Closed;
if was_open {
self.retire(env);
}
self.snd.unacked.clear();
self.snd.unsent.clear();
self.rcv.out_of_order.clear();
if reset && was_open {
env.net.send_reset(self.local, self.remote, seq, ack);
}
self.forget = true;
env.apps.ended(handler, Ending::Reset);
}
pub fn abort(&mut self, env: &mut Env) {
self.abandon(true, env);
}
/// The application will neither read nor write any more.
pub fn close(&mut self, env: &mut Env) {
self.rx_closed = true;
self.shut_down(true, env);
}
/// The application will write no more: a FIN once what is queued is
/// out.
pub fn shutdown_write(&mut self, env: &mut Env) {
if matches!(
self.state,
State::SynReceived | State::Established | State::CloseWait
) {
self.shut_down(false, env);
}
}
/// The application let go of the connection: it closes on its own,
/// and nothing more is reported.
pub fn release(&mut self, env: &mut Env) {
self.handler = Handler::Released;
self.close(env);
}
/// The application reset the connection.
pub fn abort_by_app(&mut self, env: &mut Env) {
self.handler = Handler::Released;
self.abort(env);
}
/// Closes the sending side; with `reset_unread`, data the application
/// never read resets the connection instead, as on a kernel socket.
fn shut_down(&mut self, reset_unread: bool, env: &mut Env) {
let unread = self.rcv.window != WINDOW;
if reset_unread && matches!(self.state, State::Established | State::CloseWait) && unread {
env.net
.send_reset(self.local, self.remote, self.snd.next, self.rcv.next);
self.purge();
if env.holds_output(self.key) {
env.closed_during_input = true;
} else {
self.forget = true;
}
return;
}
if self.state == State::Closed {
self.forget = true;
return;
}
self.close_with_fin(env);
}
/// Queues the FIN and moves on to FIN-WAIT-1 or LAST-ACK; without the
/// memory for it, the close waits for the fast timer.
pub fn close_with_fin(&mut self, env: &mut Env) {
let next = match self.state {
State::SynReceived | State::Established => State::FinWait1,
State::CloseWait => State::LastAck,
_ => return,
};
match self.queue_fin(env) {
Ok(()) => {
self.state = next;
self.output(env);
}
Err(super::send::NoMemory) => self.close_pending = true,
}
}
}
+243
View File
@@ -0,0 +1,243 @@
//! A TCP in Rust, following the logic of lwIP 2.2.1's TCP with a few fixes
//! to it (noted where they apply).
//!
//! Where it is lwIP's implementation rather than its behaviour that is
//! left out:
//! - lwIP's heap (`MEM_SIZE`) and segment pool (`MEMP_NUM_TCP_SEG`) are not
//! reproduced; queueing fails only past `Limits::memory_budget`, where
//! lwIP would fail at its fixed heap size instead. The connection pool
//! (`MEMP_NUM_TCP_PCB`), the pbuf pool packets are read into
//! (`PBUF_POOL_SIZE`), and what lwIP frees when either runs out are.
//! - The IPv4 identification field counts per engine from 0, where lwIP's
//! counter is per process.
//! - lwIP's other timers (ND6's, every second) are not run: they never act
//! on TCP, so only when the engine asks to be polled differs.
//! - Received IPv6 extension headers are walked as the shared IP layer
//! walks them.
mod app;
mod config;
mod conn;
mod input;
mod lifecycle;
mod receive;
mod retransmit;
mod segment;
mod send;
mod seq;
mod stack;
mod timer;
use std::io;
use std::time::Duration;
use stack::Stack;
use crate::proxy::tun::netstack::engine::{Accepted, ConnId, EngineStats, Instant, Limits};
use crate::proxy::tun::netstack::isn::IsnGenerator;
/// The TCP engine, sans-IO: it is handed whole IP packets carrying TCP and
/// the time, and drained of the packets it wants sent. It only ever accepts
/// connections — it terminates the TCP that applications behind the TUN
/// device open, whatever their destination.
///
/// The `io::Result`s follow the socket conventions so the driver can hand
/// them straight to the application: `WouldBlock` for "not now", `Ok(0)` from
/// [`TcpEngine::recv`] for end of stream, `ConnectionReset` once the peer has
/// reset, `BrokenPipe` for a write after shutdown, `NotConnected` for an id
/// the engine no longer knows.
pub struct TcpEngine {
stack: Stack,
}
impl TcpEngine {
pub fn new(limits: Limits) -> Self {
let isn = IsnGenerator::new();
let mtu = u16::try_from(limits.mtu).unwrap_or(1500);
let keepalive_idle_ms = limits.keepalive.map_or(0, |d| {
u32::try_from(d.as_millis()).unwrap_or(u32::MAX).max(1)
});
TcpEngine {
stack: Stack::new(
isn,
mtu,
keepalive_idle_ms,
limits.max_connections,
limits.memory_budget,
),
}
}
fn open_conn(&mut self, id: ConnId) -> io::Result<&mut app::AppConn> {
match self.stack.env.apps.conns.get_mut(&id) {
Some(conn) if conn.open => Ok(conn),
_ => Err(io::ErrorKind::NotConnected.into()),
}
}
/// One whole IP packet (v4 or v6) carrying TCP, from the TUN device.
pub fn input(&mut self, now: Instant, packet: &[u8]) {
self.stack.set_now(now);
self.stack.receive_packet(packet);
self.stack.shrink();
}
/// Runs whatever timers have come due.
pub fn poll(&mut self, now: Instant) {
self.stack.set_now(now);
self.stack.poll();
self.stack.shrink();
}
/// When [`TcpEngine::poll`] next has something to do; `None` when no
/// timer is armed.
pub fn poll_at(&mut self, now: Instant) -> Option<Instant> {
self.stack.set_now(now);
let due = self.stack.timer_due()?;
let ms = due.until(self.stack.now_ms());
Some(now + Duration::from_millis(u64::from(ms)))
}
/// Moves the IP packets the engine wants sent into `out`.
pub fn drain_output(&mut self, out: &mut Vec<Vec<u8>>) {
out.append(&mut self.stack.env.net.packets);
}
/// Next connection with a completed handshake.
pub fn accept(&mut self) -> Option<Accepted> {
let apps = &mut self.stack.env.apps;
let conn = apps.accepted.pop_front()?;
if let Some(c) = apps.conns.get_mut(&conn.id) {
c.open = true;
}
Some(conn)
}
pub fn recv(&mut self, now: Instant, id: ConnId, buf: &mut [u8]) -> io::Result<usize> {
self.stack.set_now(now);
let conn = self.open_conn(id)?;
if !conn.rx.is_empty() {
let n = buf.len().min(conn.rx.len());
for (dst, src) in buf.iter_mut().zip(conn.rx.drain(..n)) {
*dst = src;
}
let key = conn.conn;
self.stack.env.apps.rx_bytes -= n;
if let Some(key) = key {
self.stack.with_conn(key, |c, env| {
let mut left = n;
while left > 0 {
let chunk = left.min(0xffff);
c.app_read(chunk as u16, env);
left -= chunk;
}
});
}
return Ok(n);
}
if conn.reset {
return Err(io::ErrorKind::ConnectionReset.into());
}
if conn.fin || conn.conn.is_none() {
return Ok(0);
}
Err(io::ErrorKind::WouldBlock.into())
}
pub fn send(&mut self, now: Instant, id: ConnId, data: &[u8]) -> io::Result<usize> {
self.stack.set_now(now);
let conn = self.open_conn(id)?;
if conn.reset {
return Err(io::ErrorKind::ConnectionReset.into());
}
if conn.write_shut {
return Err(io::ErrorKind::BrokenPipe.into());
}
let Some(key) = conn.conn else {
return Err(io::ErrorKind::NotConnected.into());
};
if data.is_empty() {
return Ok(0);
}
let n = self
.stack
.with_conn(key, |c, env| c.write(data, env))
.unwrap_or(0);
if n == 0 {
return Err(io::ErrorKind::WouldBlock.into());
}
Ok(n)
}
/// No more data from the application: FIN once what is queued is sent.
pub fn shutdown_write(&mut self, now: Instant, id: ConnId) {
self.stack.set_now(now);
let Ok(conn) = self.open_conn(id) else {
return;
};
if conn.write_shut || conn.reset {
return;
}
conn.write_shut = true;
if let Some(key) = conn.conn {
self.stack.with_conn(key, |c, env| c.shutdown_write(env));
}
}
/// The application let go of the connection. The engine finishes the
/// close on its own and frees it; as on a kernel socket, data that was
/// never read, or that arrives afterwards, resets the connection.
pub fn close(&mut self, now: Instant, id: ConnId) {
self.stack.set_now(now);
if self.open_conn(id).is_err() {
return;
}
let Some(conn) = self.stack.env.apps.remove(id) else {
return;
};
if let Some(key) = conn.conn {
self.stack.with_conn(key, |c, env| c.release(env));
}
}
/// Reset the connection now.
pub fn abort(&mut self, now: Instant, id: ConnId) {
self.stack.set_now(now);
let apps = &mut self.stack.env.apps;
let Some(conn) = apps.conns.get_mut(&id) else {
return;
};
conn.reset = true;
apps.rx_bytes -= conn.rx.len();
conn.rx = std::collections::VecDeque::new();
let forget = !conn.open;
let key = apps.detach(id);
apps.ready.push(id);
if let Some(key) = key {
self.stack.with_conn(key, |c, env| c.abort_by_app(env));
}
if forget {
let apps = &mut self.stack.env.apps;
apps.remove(id);
apps.accepted.retain(|a| a.id != id);
}
}
/// Moves into `out` the connections whose readiness may have changed
/// since the last call — data or a FIN arrived, buffer space was freed,
/// the connection reset. Spurious entries are allowed; missing ones are
/// bugs.
pub fn drain_ready(&mut self, out: &mut Vec<ConnId>) {
out.append(&mut self.stack.env.apps.ready);
self.stack.shrink();
}
pub fn stats(&self) -> EngineStats {
let apps = &self.stack.env.apps;
EngineStats {
connections: self.stack.connections() + apps.orphans(),
open_handles: apps.conns.values().filter(|c| c.open).count(),
buffered_bytes: apps.rx_bytes + self.stack.buffered(),
}
}
}
+461
View File
@@ -0,0 +1,461 @@
//! The receive side of a segment: what its ACK says about our data, and
//! where its data goes — to the application in order, into the out-of-order
//! queue, or nowhere — and the window and ACK that follow.
use super::config::{
ACK_PUSHED_AT_ONCE, OUT_OF_ORDER_MAX_BYTES, OUT_OF_ORDER_MAX_SEGMENTS, WINDOW,
WINDOW_UPDATE_THRESHOLD,
};
use super::conn::{Connection, Receiver, State};
use super::input::{Incoming, Received};
use super::segment::{Segment, TcpFlags};
use super::seq::SeqNum;
use super::stack::Env;
/// A received segment's payload as it is trimmed to fit, still borrowed
/// from the packet.
pub struct InSeg<'a> {
pub seq: SeqNum,
pub flags: TcpFlags,
pub data: &'a [u8],
}
impl InSeg<'_> {
fn len(&self) -> u16 {
self.data.len() as u16
}
fn seq_len(&self) -> u32 {
u32::from(self.len()) + u32::from(self.flags.has_any(TcpFlags::SYN | TcpFlags::FIN))
}
fn truncate(&mut self, len: u16) {
self.data = &self.data[..usize::from(len).min(self.data.len())];
}
fn to_segment(&self) -> Segment {
let mut seg = Segment::data(self.seq, self.data.to_vec());
seg.flags = self.flags;
seg
}
}
/// Data for the application: borrowed from the packet when it arrived in
/// order, owned when it waited in the out-of-order queue.
pub enum Chunk<'a> {
Borrowed(&'a [u8]),
Owned(Vec<u8>),
}
impl Chunk<'_> {
pub fn bytes(&self) -> &[u8] {
match self {
Chunk::Borrowed(b) => b,
Chunk::Owned(v) => v,
}
}
}
impl Receiver {
/// Moves the announced window up to what is free, once that has grown
/// by enough to be worth announcing; otherwise keeps the edge already
/// promised. Returns how far the edge moved.
pub fn update_announced(&mut self, mss: u16) -> u32 {
let new_edge = self.next + u32::from(self.window);
let threshold = u32::from((WINDOW / 2).min(mss));
if new_edge >= self.announced_edge + threshold {
self.announced = self.window;
return new_edge.since(self.announced_edge);
}
self.announced = if self.next > self.announced_edge {
0
} else {
self.announced_edge.since(self.next) as u16
};
0
}
/// The window holds `[next, next + window - 1]`.
fn window_holds(&self, seq: SeqNum) -> bool {
seq.within(self.next, self.next + u32::from(self.window) - 1)
}
}
impl Connection {
/// The application read `len` bytes: the window reopens by as much,
/// announced at once if it moved far enough.
pub fn app_read(&mut self, len: u16, env: &mut Env) {
let window = self.rcv.window.wrapping_add(len);
self.rcv.window = if window > WINDOW || window < self.rcv.window {
WINDOW
} else {
window
};
if self.rcv.update_announced(self.mss) >= WINDOW_UPDATE_THRESHOLD {
self.ack.now = true;
self.output(env);
}
}
/// The ACK half of a segment: the send window, then what it
/// acknowledges — new data, or a duplicate.
pub fn on_ack(&mut self, seg: &Incoming<'_>, rx: &mut Received<'_>, env: &mut Env) {
if !seg.flags.has(TcpFlags::ACK) {
return;
}
let ack = seg.ack;
let right_edge = self.snd.window_ack + u32::from(self.snd.window);
let newer = self.snd.window_seq < seg.seq
|| (self.snd.window_seq == seg.seq && self.snd.window_ack < ack)
|| (self.snd.window_ack == ack && seg.window > self.snd.window)
// An ACK that moves `acked` updates the window too, as Linux
// does (lwIP does not).
|| (self.snd.acked < ack && ack <= self.snd.next);
if newer {
self.snd.window = seg.window;
self.snd.max_window = self.snd.max_window.max(seg.window);
self.snd.window_seq = seg.seq;
self.snd.window_ack = ack;
}
if ack <= self.snd.acked {
let pure_duplicate = seg.len == 0
&& self.snd.window_ack + u32::from(self.snd.window) == right_edge
&& self.rtx.timer.is_running()
&& self.snd.acked == ack;
if pure_duplicate {
self.on_duplicate_ack();
}
} else if ack.within(self.snd.acked + 1, self.snd.next) {
self.on_new_ack(ack, rx);
} else {
self.send_ack(env);
}
if let Some((sent_at, seq)) = self.rtx.timing {
if seq < ack {
self.rtx.rtt.sample(env.ticks.since(sent_at) as i16);
self.rtx.rto = self.rtx.rtt.rto();
self.rtx.timing = None;
}
}
}
fn on_duplicate_ack(&mut self) {
self.rtx.dupacks = self.rtx.dupacks.saturating_add(1);
if self.rtx.dupacks > 3 {
grow(&mut self.rtx.cwnd, self.mss);
}
if self.rtx.dupacks >= 3 {
self.fast_retransmit();
}
}
/// An ACK for data not acknowledged before: leave fast recovery, grow
/// the congestion window, free what is acknowledged.
fn on_new_ack(&mut self, ack: SeqNum, rx: &mut Received<'_>) {
if self.rtx.fast_recovery {
self.rtx.fast_recovery = false;
self.rtx.cwnd = self.rtx.ssthresh;
self.rtx.bytes_acked = 0;
}
self.rtx.count = 0;
self.rtx.rto = self.rtx.rtt.rto();
let acked = ack.since(self.snd.acked) as u16;
self.rtx.dupacks = 0;
self.snd.acked = ack;
if self.state.is_synchronized() {
if self.rtx.cwnd < self.rtx.ssthresh {
let segments: u16 = if self.rtx.rto_recovery_end.is_some() {
1
} else {
2
};
grow(
&mut self.rtx.cwnd,
acked.min(segments.wrapping_mul(self.mss)),
);
} else {
grow(&mut self.rtx.bytes_acked, acked);
if self.rtx.bytes_acked >= self.rtx.cwnd {
self.rtx.bytes_acked -= self.rtx.cwnd;
grow(&mut self.rtx.cwnd, self.mss);
}
}
}
rx.acked = rx.acked.wrapping_add(self.free_acknowledged(ack, true));
rx.acked = rx.acked.wrapping_add(self.free_acknowledged(ack, false));
if self.snd.unacked.is_empty() {
self.rtx.timer.stop();
} else {
self.rtx.timer.restart();
}
if self.snd.unsent.is_empty() {
self.snd.oversize = 0;
}
self.snd.space = self.snd.space.wrapping_add(rx.acked);
if let Some(end) = self.rtx.rto_recovery_end {
let done = match (self.snd.unacked.front(), self.snd.unsent.front()) {
(None, None) => true,
(None, Some(next)) | (Some(next), _) => end <= next.seq,
};
if done {
self.rtx.rto_recovery_end = None;
}
}
}
/// Drops the segments `ack` covers from the front of the in-flight
/// (`unacked`) or the unsent queue; returns their payload bytes.
fn free_acknowledged(&mut self, ack: SeqNum, unacked: bool) -> u16 {
let queue = if unacked {
&mut self.snd.unacked
} else {
&mut self.snd.unsent
};
let mut freed: u16 = 0;
while queue.front().is_some_and(|seg| seg.end() <= ack) {
let Some(seg) = queue.pop_front() else {
break;
};
self.snd.queued_pbufs = self.snd.queued_pbufs.wrapping_sub(seg.pbufs.count());
freed = freed.wrapping_add(seg.len());
}
freed
}
/// The data half of a segment.
pub fn on_data<'a>(&mut self, seg: &Incoming<'a>, rx: &mut Received<'a>, env: &mut Env) {
if seg.len == 0 || !self.state.receives_data() {
if !self.rcv.window_holds(seg.seq) {
self.ack.now = true;
}
return;
}
let mut inseg = InSeg {
seq: seg.seq,
flags: seg.flags,
data: seg.payload,
};
let seg_last = seg.seq + u32::from(seg.len) - 1;
if self.rcv.next.within(seg.seq + 1, seg_last) {
// It starts before what is expected: drop what was had already.
let off = self.rcv.next.since(seg.seq) as usize;
inseg.data = inseg.data.get(off..).unwrap_or(&[]);
inseg.seq = self.rcv.next;
} else if seg.seq < self.rcv.next {
self.ack.now = true;
}
if !self.rcv.window_holds(inseg.seq) {
self.send_ack(env);
return;
}
if inseg.seq == self.rcv.next {
self.receive_in_order(inseg, seg.flags, rx);
} else {
self.queue_out_of_order(inseg, seg.len);
self.send_ack(env);
}
}
fn receive_in_order<'a>(
&mut self,
mut inseg: InSeg<'a>,
seg_flags: TcpFlags,
rx: &mut Received<'a>,
) {
let seq = inseg.seq;
let mut len = inseg.seq_len() as u16;
if len > self.rcv.window {
inseg.flags.remove(TcpFlags::FIN);
let mut fits = self.rcv.window;
if inseg.flags.has(TcpFlags::SYN) {
fits = fits.wrapping_sub(1);
}
inseg.truncate(fits);
len = inseg.seq_len() as u16;
}
if !self.rcv.out_of_order.is_empty() {
if inseg.flags.has(TcpFlags::FIN) {
self.rcv.out_of_order.clear();
} else {
while let Some(next) = self.rcv.out_of_order.front() {
if seq + u32::from(len) < next.data_end() {
break;
}
if next.flags.has(TcpFlags::FIN) && !inseg.flags.has(TcpFlags::SYN) {
// The FIN stays where the peer put it: nothing past
// it can be data.
inseg.truncate(next.data_end().since(seq) as u16);
inseg.flags.insert(TcpFlags::FIN);
len = inseg.seq_len() as u16;
self.rcv.out_of_order.clear();
break;
}
self.rcv.out_of_order.pop_front();
}
if let Some(next) = self.rcv.out_of_order.front() {
if seq + u32::from(len) > next.seq {
let mut fits = next.seq.since(seq) as u16;
if inseg.flags.has(TcpFlags::SYN) {
fits = fits.wrapping_sub(1);
}
inseg.truncate(fits);
len = inseg.seq_len() as u16;
}
}
}
}
self.rcv.next = seq + u32::from(len);
self.rcv.window = self.rcv.window.wrapping_sub(len);
self.rcv.update_announced(self.mss);
if !inseg.data.is_empty() {
rx.data.push(Chunk::Borrowed(inseg.data));
}
if inseg.flags.has(TcpFlags::FIN) {
rx.got_fin = true;
}
while self
.rcv
.out_of_order
.front()
.is_some_and(|s| s.seq == self.rcv.next)
{
let Some(next) = self.rcv.out_of_order.pop_front() else {
break;
};
let len = next.seq_len();
self.rcv.next = self.rcv.next + len;
self.rcv.window = self.rcv.window.wrapping_sub(len as u16);
self.rcv.update_announced(self.mss);
let fin = next.flags.has(TcpFlags::FIN);
if !next.data.is_empty() {
rx.data.push(Chunk::Owned(next.data));
}
if fin {
rx.got_fin = true;
if self.state == State::Established {
self.state = State::CloseWait;
}
}
}
if ACK_PUSHED_AT_ONCE && seg_flags.has(TcpFlags::PSH) {
self.ack.now = true;
} else {
self.ack.owe();
}
}
/// Files a segment past a hole among the ones already waiting: trimmed
/// where it overlaps them, replacing a shorter one at the same place,
/// clipped to the window at the end. Then the queue is cut back to its
/// byte and segment limits.
fn queue_out_of_order(&mut self, inseg: InSeg<'_>, seg_len: u16) {
let seq = inseg.seq;
let queue = &mut self.rcv.out_of_order;
if queue.is_empty() {
queue.push_back(inseg.to_segment());
} else {
let mut prev: Option<usize> = None;
let mut i = 0;
while i < queue.len() {
let next_seq = queue[i].seq;
let is_last = i + 1 == queue.len();
if seq == next_seq {
// Same start: keep the longer, unless the one queued is
// last — then it was cut to the window, and stays.
if inseg.len() > queue[i].len() && !is_last {
let rest = queue.split_off(i);
queue.extend(cover(seq, inseg.to_segment(), rest));
}
break;
}
match prev {
None if seq < next_seq => {
let rest = std::mem::take(queue);
*queue = cover(seq, inseg.to_segment(), rest);
break;
}
Some(p) if seq.within(queue[p].seq + 1, next_seq - 1) => {
let before = &mut queue[p];
if before.data_end() > seq {
let fits = seq.since(before.seq) as u16;
before.truncate(fits);
}
let rest = queue.split_off(i);
queue.extend(cover(seq, inseg.to_segment(), rest));
break;
}
_ => {}
}
prev = Some(i);
if is_last && seq > next_seq {
let last = &mut queue[i];
if last.flags.has(TcpFlags::FIN) {
break;
}
if last.data_end() > seq {
let fits = seq.since(last.seq) as u16;
last.truncate(fits);
}
let mut tail = inseg.to_segment();
let window_end = self.rcv.next + u32::from(self.rcv.window);
if seq + u32::from(seg_len) > window_end {
tail.flags.remove(TcpFlags::FIN);
tail.truncate(window_end.since(seq) as u16);
}
queue.push_back(tail);
break;
}
i += 1;
}
}
let mut bytes: u32 = 0;
let mut segments: u16 = 0;
let cut = queue.iter().position(|seg| {
bytes = bytes.wrapping_add(u32::from(seg.len()));
segments = segments.wrapping_add(seg.pbufs.count());
bytes > OUT_OF_ORDER_MAX_BYTES || segments > OUT_OF_ORDER_MAX_SEGMENTS
});
if let Some(cut) = cut {
queue.truncate(cut);
}
}
}
/// `seg` placed ahead of `rest`: the queued segments it covers whole go, and
/// it is cut short of the next one. A FIN-carrying `seg` ends the queue; a
/// FIN it covers stays where it was, `seg` ending there and the queue too.
fn cover(
seq: SeqNum,
mut seg: Segment,
mut rest: std::collections::VecDeque<Segment>,
) -> std::collections::VecDeque<Segment> {
if seg.flags.has(TcpFlags::FIN) {
rest.clear();
} else {
while let Some(next) = rest.front() {
if seq + u32::from(seg.len()) < next.data_end() {
break;
}
if next.flags.has(TcpFlags::FIN) {
seg.truncate(next.data_end().since(seq) as u16);
seg.flags.insert(TcpFlags::FIN);
rest.clear();
break;
}
rest.pop_front();
}
if let Some(next) = rest.front() {
if seq + u32::from(seg.len()) > next.seq {
seg.truncate(next.seq.since(seq) as u16);
}
}
}
rest.push_front(seg);
rest
}
/// Adds to a window, saturating at its largest value.
fn grow(window: &mut u16, by: u16) {
let sum = window.wrapping_add(by);
*window = if sum >= *window { sum } else { u16::MAX };
}
@@ -0,0 +1,58 @@
//! Sending again what was lost: the oldest segment on a duplicate ACK or a
//! repeated SYN, everything in flight on a timeout.
use super::conn::Connection;
impl Connection {
/// Moves the oldest in-flight segment back among the unsent, where the
/// next output sends it again. False when nothing is in flight.
pub fn retransmit_oldest(&mut self) -> bool {
let Some(seg) = self.snd.unacked.pop_front() else {
return false;
};
let at = self
.snd
.unsent
.iter()
.position(|u| u.seq >= seg.seq)
.unwrap_or(self.snd.unsent.len());
self.snd.unsent.insert(at, seg);
if at + 1 == self.snd.unsent.len() {
self.snd.oversize = 0;
}
self.rtx.count = self.rtx.count.saturating_add(1);
self.rtx.timing = None;
true
}
/// Third duplicate ACK: retransmit the oldest segment and enter fast
/// recovery with the congestion window halved.
pub fn fast_retransmit(&mut self) {
if self.snd.unacked.is_empty() || self.rtx.fast_recovery || !self.retransmit_oldest() {
return;
}
let rtx = &mut self.rtx;
rtx.ssthresh = rtx.cwnd.min(self.snd.window) / 2;
if u32::from(rtx.ssthresh) < 2 * u32::from(self.mss) {
rtx.ssthresh = self.mss.wrapping_mul(2);
}
rtx.cwnd = rtx.ssthresh.wrapping_add(self.mss.wrapping_mul(3));
rtx.fast_recovery = true;
rtx.timer.restart();
}
/// Puts everything in flight back at the head of the unsent queue, to
/// be sent again from the first unacknowledged byte. False when nothing
/// is in flight.
pub fn requeue_in_flight(&mut self) -> bool {
let Some(last) = self.snd.unacked.back() else {
return false;
};
self.rtx.rto_recovery_end = Some(last.end());
let mut requeued = std::mem::take(&mut self.snd.unacked);
requeued.append(&mut self.snd.unsent);
self.snd.unsent = requeued;
self.rtx.timing = None;
true
}
}
+198
View File
@@ -0,0 +1,198 @@
//! A segment as the queues hold it: sequence space, header flags, payload,
//! and the pbuf chain lwIP would keep it in — the send queue is limited in
//! pbufs, so how many a segment takes is part of its behaviour.
use super::config::OVERSIZE;
use super::seq::SeqNum;
/// The TCP header's control bits.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TcpFlags(u8);
impl TcpFlags {
pub const FIN: TcpFlags = TcpFlags(0x01);
pub const SYN: TcpFlags = TcpFlags(0x02);
pub const RST: TcpFlags = TcpFlags(0x04);
pub const PSH: TcpFlags = TcpFlags(0x08);
pub const ACK: TcpFlags = TcpFlags(0x10);
pub const NONE: TcpFlags = TcpFlags(0);
/// The six control bits of a header byte.
pub fn from_header(byte: u8) -> TcpFlags {
TcpFlags(byte & 0x3f)
}
pub fn bits(self) -> u8 {
self.0
}
pub fn has(self, flag: TcpFlags) -> bool {
self.0 & flag.0 != 0
}
pub fn has_any(self, flags: TcpFlags) -> bool {
self.0 & flags.0 != 0
}
pub fn insert(&mut self, flag: TcpFlags) {
self.0 |= flag.0;
}
pub fn remove(&mut self, flag: TcpFlags) {
self.0 &= !flag.0;
}
}
impl std::ops::BitOr for TcpFlags {
type Output = TcpFlags;
fn bitor(self, rhs: TcpFlags) -> TcpFlags {
TcpFlags(self.0 | rhs.0)
}
}
/// The pbuf chain behind a segment: the payload bytes each pbuf holds.
/// One pbuf needs no allocation.
#[derive(Clone, Debug)]
pub enum Pbufs {
One(u16),
/// Two or more.
Chain(Vec<u16>),
}
impl Pbufs {
pub fn single(len: u16) -> Pbufs {
Pbufs::One(len)
}
fn sizes(&self) -> &[u16] {
match self {
Pbufs::One(len) => std::slice::from_ref(len),
Pbufs::Chain(sizes) => sizes,
}
}
pub fn count(&self) -> u16 {
self.sizes().len() as u16
}
pub fn push(&mut self, len: u16) {
match self {
Pbufs::One(first) => *self = Pbufs::Chain(vec![*first, len]),
Pbufs::Chain(sizes) => sizes.push(len),
}
}
/// The last pbuf takes `len` more bytes into its spare room.
pub fn grow_last(&mut self, len: u16) {
let last = match self {
Pbufs::One(only) => Some(only),
Pbufs::Chain(sizes) => sizes.last_mut(),
};
if let Some(last) = last {
*last += len;
}
}
/// The chain after cutting the payload to `len` bytes: the pbuf where
/// the cut falls is the last one kept.
fn truncate(&mut self, len: u16) {
match self {
Pbufs::One(only) => *only = (*only).min(len),
Pbufs::Chain(sizes) => {
let mut remaining = len;
let mut kept = sizes.len();
for (i, size) in sizes.iter_mut().enumerate() {
if remaining > *size {
remaining -= *size;
} else {
*size = remaining;
kept = i + 1;
break;
}
}
sizes.truncate(kept);
if let [only] = sizes[..] {
*self = Pbufs::One(only);
}
}
}
}
}
#[derive(Clone, Debug)]
pub struct Segment {
pub seq: SeqNum,
pub flags: TcpFlags,
/// Carries the MSS option (a SYN).
pub mss_option: bool,
pub data: Vec<u8>,
pub pbufs: Pbufs,
}
impl Segment {
/// A segment of just control bits, in one empty pbuf.
pub fn control(seq: SeqNum, flags: TcpFlags) -> Segment {
Segment {
seq,
flags,
mss_option: flags.has(TcpFlags::SYN),
data: Vec::new(),
pbufs: Pbufs::single(0),
}
}
/// A segment of data in one pbuf.
pub fn data(seq: SeqNum, data: Vec<u8>) -> Segment {
let len = data.len() as u16;
Segment {
seq,
flags: TcpFlags::NONE,
mss_option: false,
data,
pbufs: Pbufs::single(len),
}
}
pub fn len(&self) -> u16 {
self.data.len() as u16
}
/// Sequence space taken: payload, plus one for a SYN or FIN.
pub fn seq_len(&self) -> u32 {
u32::from(self.len()) + u32::from(self.flags.has_any(TcpFlags::SYN | TcpFlags::FIN))
}
/// One past the last payload byte.
pub fn data_end(&self) -> SeqNum {
self.seq + u32::from(self.len())
}
/// One past the last sequence number taken, SYN or FIN included.
pub fn end(&self) -> SeqNum {
self.seq + self.seq_len()
}
pub fn options_len(&self) -> u16 {
if self.mss_option {
4
} else {
0
}
}
/// Cuts the payload to `len` bytes, dropping the pbufs no longer
/// needed.
pub fn truncate(&mut self, len: u16) {
self.pbufs.truncate(len);
self.data.truncate(usize::from(len));
}
}
/// The spare room of a pbuf allocated for `length` payload bytes, when more
/// writes may come to fill it.
pub fn oversize_for(length: u16, max_length: u16) -> u16 {
let align = super::config::MEM_ALIGNMENT;
let padded = length.wrapping_add(OVERSIZE).wrapping_add(align - 1) & !(align - 1);
max_length.min(padded).wrapping_sub(length)
}
+413
View File
@@ -0,0 +1,413 @@
//! The send side: queueing what the application writes in segments, and
//! sending what the windows allow.
use super::config::{SEND_QUEUE_LIMIT, SEND_QUEUE_PBUFS};
use super::conn::Connection;
use super::segment::{oversize_for, Segment, TcpFlags};
use super::seq::SeqNum;
use super::stack::{Env, Header};
/// Queueing failed for want of memory (the budget or the send queue).
#[derive(Debug, PartialEq, Eq)]
pub struct NoMemory;
#[derive(Debug, PartialEq, Eq)]
pub enum WriteError {
/// The connection no longer takes data.
Closed,
NoMemory,
}
impl Connection {
/// What the application writes, as much as the send buffer takes in one
/// queueing — halved until it fits the send queue — then sent as far as
/// the windows allow. Returns the bytes taken.
pub fn write(&mut self, data: &[u8], env: &mut Env) -> usize {
let mut n = data.len().min(usize::from(self.snd.space)).min(0xffff);
while n > 0 {
match self.queue_write(&data[..n], env) {
Ok(()) => break,
Err(WriteError::NoMemory) => n /= 2,
Err(WriteError::Closed) => return 0,
}
}
self.output(env);
n
}
/// Segments `data` onto the send queue: first into the room the last
/// unsent segment has left, then in new segments of at most an MSS (or
/// half the largest window the peer has offered). All or nothing.
fn queue_write(&mut self, data: &[u8], env: &mut Env) -> Result<(), WriteError> {
let len = data.len() as u16;
let mut mss = self.mss.min(self.snd.max_window / 2);
if mss == 0 {
mss = self.mss;
}
if !self.state.accepts_writes() {
return Err(WriteError::Closed);
}
if len == 0 {
return Ok(());
}
if len > self.snd.space || self.snd.queued_pbufs >= SEND_QUEUE_PBUFS {
self.write_failed = true;
return Err(WriteError::NoMemory);
}
let mut pbufs = self.snd.queued_pbufs;
let mut pos: u16 = 0;
let mut oversize: u16 = 0;
let mut oversize_used: u16 = 0;
let mut appended: Option<u16> = None;
// Where PSH goes: the last segment this write touched.
let mut pushed: Option<PushTarget> = None;
if let Some(last) = self.snd.unsent.back() {
let mut space = mss.wrapping_sub(last.len().wrapping_add(last.options_len()));
oversize = self.snd.oversize;
if oversize > 0 {
pushed = Some(PushTarget::LastUnsent);
oversize_used = space.min(oversize.min(len));
pos += oversize_used;
oversize -= oversize_used;
space -= oversize_used;
}
if pos < len && space > 0 && last.len() > 0 {
let seglen = space.min(len - pos);
pushed = Some(PushTarget::LastUnsent);
oversize = self.pbuf_spare(seglen, space, true, env)?;
appended = Some(seglen);
pbufs = pbufs.wrapping_add(1);
pos += seglen;
}
}
let appended_at = oversize_used;
let mut queue: Vec<Segment> = Vec::new();
while pos < len {
let seglen = (len - pos).min(mss);
oversize = self.pbuf_spare(seglen, mss, queue.is_empty(), env)?;
pbufs = pbufs.wrapping_add(1);
if pbufs > SEND_QUEUE_LIMIT {
self.write_failed = true;
return Err(WriteError::NoMemory);
}
let range = usize::from(pos)..usize::from(pos + seglen);
queue.push(Segment::data(
self.snd.queued_end + u32::from(pos),
data[range].to_vec(),
));
pushed = Some(PushTarget::New(queue.len() - 1));
pos += seglen;
}
if let Some(last) = self.snd.unsent.back_mut() {
if oversize_used > 0 {
last.data
.extend_from_slice(&data[..usize::from(oversize_used)]);
last.pbufs.grow_last(oversize_used);
}
if let Some(n) = appended {
let start = usize::from(appended_at);
last.data
.extend_from_slice(&data[start..start + usize::from(n)]);
last.pbufs.push(n);
}
}
self.snd.oversize = oversize;
let first_new = self.snd.unsent.len();
self.snd.unsent.extend(queue);
self.snd.queued_end = self.snd.queued_end + u32::from(len);
self.snd.space = self.snd.space.wrapping_sub(len);
self.snd.queued_pbufs = pbufs;
let target = match pushed {
Some(PushTarget::New(i)) => Some(first_new + i),
Some(PushTarget::LastUnsent) => first_new.checked_sub(1),
None => None,
};
if let Some(seg) = target.and_then(|i| self.snd.unsent.get_mut(i)) {
seg.flags.insert(TcpFlags::PSH);
}
Ok(())
}
/// The spare room of a pbuf for `length` bytes of a write — some when
/// Nagle may hold the segment for more — or `NoMemory` past the budget.
fn pbuf_spare(
&mut self,
length: u16,
max_length: u16,
first_segment: bool,
env: &Env,
) -> Result<u16, WriteError> {
let may_grow = !self.nodelay
&& (!first_segment || !self.snd.unsent.is_empty() || !self.snd.unacked.is_empty());
let spare = if length < max_length && may_grow {
oversize_for(length, max_length)
} else {
0
};
if !env.budget.allows(usize::from(length)) {
self.write_failed = true;
return Err(WriteError::NoMemory);
}
Ok(spare)
}
/// Splits the first unsent segment so its first part fits `size`; PSH
/// and FIN move to the second (a FIN left on the first would end the
/// stream at the split point). False when there is none to split, or no
/// memory to split it.
pub fn fit_unsent_head(&mut self, size: u16, env: &Env) -> bool {
let Some(head) = self.snd.unsent.front() else {
return false;
};
if size == 0 {
return false;
}
if head.len() <= size {
return true;
}
let remainder = head.len() - size;
if !env.budget.allows(usize::from(remainder)) {
return false;
}
let mut moved = TcpFlags::NONE;
for flag in [TcpFlags::PSH, TcpFlags::FIN] {
if head.flags.has(flag) {
moved.insert(flag);
}
}
let mut tail = Segment::data(
head.seq + u32::from(size),
head.data[usize::from(size)..].to_vec(),
);
tail.flags = moved;
tail.mss_option = head.mss_option;
let Some(head) = self.snd.unsent.front_mut() else {
return false;
};
self.snd.queued_pbufs = self.snd.queued_pbufs.wrapping_sub(head.pbufs.count());
head.truncate(size);
head.flags.remove(moved);
self.snd.queued_pbufs = self
.snd
.queued_pbufs
.wrapping_add(head.pbufs.count())
.wrapping_add(tail.pbufs.count());
self.snd.unsent.insert(1, tail);
if self.snd.unsent.len() == 2 {
self.snd.oversize = 0;
}
true
}
/// Queues a FIN: on the last unsent segment if it can carry one, else
/// on its own.
pub fn queue_fin(&mut self, env: &Env) -> Result<(), NoMemory> {
if let Some(last) = self.snd.unsent.back_mut() {
if !last
.flags
.has_any(TcpFlags::SYN | TcpFlags::FIN | TcpFlags::RST)
{
last.flags.insert(TcpFlags::FIN);
self.fin_queued = true;
return Ok(());
}
}
self.queue_control(TcpFlags::FIN, env)
}
/// Queues a segment of control bits alone (a SYN-ACK or a FIN).
pub fn queue_control(&mut self, flags: TcpFlags, env: &Env) -> Result<(), NoMemory> {
if !env.budget.allows(0) {
self.write_failed = true;
return Err(NoMemory);
}
self.snd
.unsent
.push_back(Segment::control(self.snd.queued_end, flags));
self.snd.oversize = 0;
if flags.has_any(TcpFlags::SYN | TcpFlags::FIN) {
self.snd.queued_end = self.snd.queued_end + 1;
}
if flags.has(TcpFlags::FIN) {
self.fin_queued = true;
}
self.snd.queued_pbufs = self.snd.queued_pbufs.wrapping_add(1);
Ok(())
}
/// Nagle: hold back a small segment while data is unacknowledged,
/// unless there is reason not to.
fn nagle_lets_go(&self) -> bool {
self.snd.unacked.is_empty()
|| self.nodelay
|| self.rtx.fast_recovery
|| self
.snd
.unsent
.front()
.is_some_and(|u| self.snd.unsent.len() > 1 || u.len() >= self.mss)
|| self.snd.space == 0
|| self.snd.queued_pbufs >= SEND_QUEUE_PBUFS
}
/// Sends what the congestion and send windows allow from the unsent
/// queue, or an owed ACK if nothing can go. A segment that does not fit
/// a window that is not the congestion window's doing starts the
/// persist timer. Held while a segment for this connection is being
/// processed.
pub fn output(&mut self, env: &mut Env) {
if env.holds_output(self.key) {
return;
}
let window = u32::from(self.snd.window.min(self.rtx.cwnd));
let needed = |seg: &Segment, acked: SeqNum| seg.data_end().since(acked);
let Some(first) = self.snd.unsent.front() else {
if self.ack.now {
self.send_ack(env);
} else {
self.write_failed = false;
}
return;
};
if needed(first, self.snd.acked) > window {
if window == u32::from(self.snd.window)
&& self.snd.unacked.is_empty()
&& self.persist.is_none()
{
self.persist = Some(super::conn::Persist {
ticks: 0,
round: 1,
probes: 0,
});
}
if self.ack.now {
self.send_ack(env);
} else {
self.write_failed = false;
}
return;
}
self.persist = None;
while let Some(seg) = self.snd.unsent.front() {
if needed(seg, self.snd.acked) > window {
break;
}
if !self.nagle_lets_go() && !self.write_failed && !self.fin_queued {
break;
}
let Some(mut seg) = self.snd.unsent.pop_front() else {
break;
};
seg.flags.insert(TcpFlags::ACK);
self.send_segment(&seg, env);
self.ack.sent();
if self.snd.next < seg.end() {
self.snd.next = seg.end();
}
if seg.seq_len() > 0 {
self.add_unacked(seg);
}
}
if self.snd.unsent.is_empty() {
self.snd.oversize = 0;
}
self.write_failed = false;
}
/// Files a sent segment in sequence order; it usually goes last.
fn add_unacked(&mut self, seg: Segment) {
let goes_before_last = self.snd.unacked.back().is_some_and(|u| seg.seq < u.seq);
if goes_before_last {
let at = self
.snd
.unacked
.iter()
.position(|u| u.seq >= seg.seq)
.unwrap_or(self.snd.unacked.len());
self.snd.unacked.insert(at, seg);
} else {
self.snd.unacked.push_back(seg);
}
}
/// One queued segment on the wire, with the current ACK and window; it
/// starts the retransmission timer and, if none is running, an RTT
/// measurement.
fn send_segment(&mut self, seg: &Segment, env: &mut Env) {
let mss_option = seg
.mss_option
.then(|| env.net.effective_mss(super::config::MSS, self.remote));
self.rcv.announced_edge = self.rcv.next + u32::from(self.rcv.announced);
self.rtx.timer.start_if_stopped();
if self.rtx.timing.is_none() {
self.rtx.timing = Some((env.ticks, seg.seq));
}
let header = Header {
seq: seg.seq,
ack: self.rcv.next,
flags: seg.flags,
window: self.rcv.announced,
mss_option,
};
env.net.send(self.local, self.remote, &header, &seg.data);
}
/// A segment that is not queued, carrying the current ACK and window;
/// the window is then the one announced.
fn send_unqueued(&mut self, seq: SeqNum, flags: TcpFlags, payload: &[u8], env: &mut Env) {
let header = Header {
seq,
ack: self.rcv.next,
flags,
window: self.rcv.announced,
mss_option: None,
};
self.rcv.announced_edge = self.rcv.next + u32::from(self.rcv.announced);
env.net.send(self.local, self.remote, &header, payload);
}
/// An ACK alone.
pub fn send_ack(&mut self, env: &mut Env) {
self.send_unqueued(self.snd.next, TcpFlags::ACK, &[], env);
self.ack.sent();
}
/// A keep-alive probe: an ACK for old sequence space, which the peer
/// must answer.
pub fn send_keepalive(&mut self, env: &mut Env) {
self.send_unqueued(self.snd.next - 1, TcpFlags::ACK, &[], env);
}
/// Probes a closed window with the first byte of the unsent queue (or
/// its FIN, if that is all it holds).
pub fn send_window_probe(&mut self, env: &mut Env) {
let Some(seg) = self.snd.unsent.front() else {
return;
};
let is_fin = seg.flags.has(TcpFlags::FIN) && seg.len() == 0;
let seq = seg.seq;
let byte = [seg.data.first().copied().unwrap_or(0)];
let payload: &[u8] = if is_fin { &[] } else { &byte };
if let Some(persist) = self.persist.as_mut() {
persist.probes = persist.probes.saturating_add(1);
}
let probe_end = seq + 1;
if self.snd.next < probe_end {
self.snd.next = probe_end;
}
let flags = if is_fin {
TcpFlags::ACK | TcpFlags::FIN
} else {
TcpFlags::ACK
};
self.send_unqueued(seq, flags, payload, env);
}
}
enum PushTarget {
LastUnsent,
New(usize),
}
+119
View File
@@ -0,0 +1,119 @@
//! The two clocks of TCP's arithmetic, both modulo 2^32: sequence numbers
//! and timer ticks.
use std::cmp::Ordering;
use std::ops::{Add, Sub};
/// A TCP sequence number. Ordered by the sign of the 32-bit difference, so
/// it orders correctly across wrap-around within half the number space.
/// Exactly half a space apart, `a < b` and `b < a` both hold, as in every
/// TCP that compares this way.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct SeqNum(u32);
impl SeqNum {
pub const fn new(raw: u32) -> Self {
SeqNum(raw)
}
pub const fn raw(self) -> u32 {
self.0
}
/// How far past `earlier` this is.
pub fn since(self, earlier: SeqNum) -> u32 {
self.0.wrapping_sub(earlier.0)
}
/// `low <= self <= high`.
pub fn within(self, low: SeqNum, high: SeqNum) -> bool {
self >= low && self <= high
}
fn before(self, other: SeqNum) -> bool {
(self.0.wrapping_sub(other.0) as i32) < 0
}
}
impl PartialOrd for SeqNum {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some((self.0.wrapping_sub(other.0) as i32).cmp(&0))
}
fn lt(&self, other: &Self) -> bool {
self.before(*other)
}
fn le(&self, other: &Self) -> bool {
!other.before(*self)
}
fn gt(&self, other: &Self) -> bool {
other.before(*self)
}
fn ge(&self, other: &Self) -> bool {
!self.before(*other)
}
}
impl Add<u32> for SeqNum {
type Output = SeqNum;
fn add(self, n: u32) -> SeqNum {
SeqNum(self.0.wrapping_add(n))
}
}
impl Sub<u32> for SeqNum {
type Output = SeqNum;
fn sub(self, n: u32) -> SeqNum {
SeqNum(self.0.wrapping_sub(n))
}
}
/// The slow timer's count: every timeout, the RTO and RTT samples are kept
/// in these half-second ticks, not in time.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Ticks(u32);
impl Ticks {
pub fn next(self) -> Ticks {
Ticks(self.0.wrapping_add(1))
}
/// Ticks elapsed since `earlier`.
pub fn since(self, earlier: Ticks) -> u32 {
self.0.wrapping_sub(earlier.0)
}
}
/// The stack's millisecond clock, on which the TCP timer is scheduled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Millis(u32);
impl Millis {
pub fn from_instant(now: crate::proxy::tun::netstack::engine::Instant) -> Millis {
Millis(now.as_millis() as u32)
}
pub fn after(self, ms: u32) -> Millis {
Millis(self.0.wrapping_add(ms))
}
/// Whether this time is still ahead of `now`.
pub fn is_after(self, now: Millis) -> bool {
(now.0.wrapping_sub(self.0) as i32) < 0
}
/// Milliseconds from `now` until this time; zero once it has passed.
pub fn until(self, now: Millis) -> u32 {
let ahead = self.0.wrapping_sub(now.0);
if (ahead as i32) < 0 {
0
} else {
ahead
}
}
}
+721
View File
@@ -0,0 +1,721 @@
//! The stack around the connections: where they are kept and found, the
//! order lwIP walks them in, the timer that drives them, the pools that
//! bound them, and what every operation on one of them shares (`Env`).
//!
//! A connection being worked on is taken out of the table and handed to its
//! own methods with the `Env`; `settle` puts it back and brings the lists,
//! the demultiplexer and the pool counts up to date with what the operation
//! did. One operation only ever changes the one connection, so deferring
//! that bookkeeping to the end of it leaves every list in the order lwIP's
//! immediate updates would.
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use super::app::Apps;
use super::config::{
CONNECTION_POOL, PBUF_POOL_BUFSIZE, PBUF_POOL_SIZE, TIMER_INTERVAL_MS, TWO_MSL_TICKS,
};
use super::conn::{Connection, State};
use super::segment::TcpFlags;
use super::seq::{Millis, SeqNum, Ticks};
use crate::proxy::tun::netstack::engine::Instant;
use crate::proxy::tun::netstack::isn::IsnGenerator;
use crate::proxy::tun::netstack::wire::{
self, Ipv4Fields, IPV4_HEADER_LEN, IPV6_HEADER_LEN, PROTO_TCP, TCP_HEADER_LEN,
};
/// Names a connection for as long as it lives; a freed slot's next tenant
/// gets a new generation, so a stale key misses.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ConnKey {
index: u32,
generation: u32,
}
struct Slot {
generation: u32,
conn: Option<Box<Connection>>,
}
/// The connections, by key.
#[derive(Default)]
struct Slab {
slots: Vec<Slot>,
vacant: Vec<u32>,
/// Keys handed out and not freed: connections, in the table or being
/// worked on.
live: usize,
}
impl Slab {
fn reserve(&mut self) -> ConnKey {
self.live += 1;
match self.vacant.pop() {
Some(index) => ConnKey {
index,
generation: self.slots[index as usize].generation,
},
None => {
self.slots.push(Slot {
generation: 0,
conn: None,
});
ConnKey {
index: (self.slots.len() - 1) as u32,
generation: 0,
}
}
}
}
fn slot(&mut self, key: ConnKey) -> Option<&mut Slot> {
self.slots
.get_mut(key.index as usize)
.filter(|s| s.generation == key.generation)
}
fn take(&mut self, key: ConnKey) -> Option<Box<Connection>> {
self.slot(key)?.conn.take()
}
fn get_mut(&mut self, key: ConnKey) -> Option<&mut Connection> {
self.slot(key)?.conn.as_deref_mut()
}
fn get(&self, key: ConnKey) -> Option<&Connection> {
self.slots
.get(key.index as usize)
.filter(|s| s.generation == key.generation)?
.conn
.as_deref()
}
fn put(&mut self, conn: Box<Connection>) {
if let Some(slot) = self.slot(conn.key) {
slot.conn = Some(conn);
}
}
fn free(&mut self, key: ConnKey) {
if let Some(slot) = self.slot(key) {
slot.generation = slot.generation.wrapping_add(1);
slot.conn = None;
self.vacant.push(key.index);
self.live -= 1;
}
}
fn key_at(&self, index: u32) -> Option<ConnKey> {
let slot = self.slots.get(index as usize)?;
Some(ConnKey {
index,
generation: slot.generation,
})
}
fn values(&self) -> impl Iterator<Item = &Connection> {
self.slots.iter().filter_map(|s| s.conn.as_deref())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ListKind {
Active,
TimeWait,
}
#[derive(Clone, Copy, Default)]
struct Link {
list: Option<ListKind>,
prev: Option<u32>,
next: Option<u32>,
}
/// lwIP's two connection lists, which it pushes onto at the head and walks
/// from it; the order decides which connection's segments a timer tick
/// sends first. Linked through slot indices, so every operation is O(1).
#[derive(Default)]
struct Lists {
active: Option<u32>,
time_wait: Option<u32>,
active_len: usize,
time_wait_len: usize,
links: Vec<Link>,
}
impl Lists {
fn link(&mut self, index: u32) -> &mut Link {
let i = index as usize;
if self.links.len() <= i {
self.links.resize(i + 1, Link::default());
}
&mut self.links[i]
}
fn list_of(&self, index: u32) -> Option<ListKind> {
self.links.get(index as usize).and_then(|l| l.list)
}
fn head(&self, kind: ListKind) -> Option<u32> {
match kind {
ListKind::Active => self.active,
ListKind::TimeWait => self.time_wait,
}
}
fn next(&self, index: u32) -> Option<u32> {
self.links.get(index as usize).and_then(|l| l.next)
}
fn push_front(&mut self, kind: ListKind, index: u32) {
self.remove(index);
let old = self.head(kind);
if let Some(old) = old {
self.link(old).prev = Some(index);
}
*self.link(index) = Link {
list: Some(kind),
prev: None,
next: old,
};
match kind {
ListKind::Active => {
self.active = Some(index);
self.active_len += 1;
}
ListKind::TimeWait => {
self.time_wait = Some(index);
self.time_wait_len += 1;
}
}
}
fn remove(&mut self, index: u32) {
let Some(link) = self.links.get(index as usize).copied() else {
return;
};
let Some(kind) = link.list else {
return;
};
match link.prev {
Some(p) => self.link(p).next = link.next,
None => match kind {
ListKind::Active => self.active = link.next,
ListKind::TimeWait => self.time_wait = link.next,
},
}
if let Some(n) = link.next {
self.link(n).prev = link.prev;
}
*self.link(index) = Link::default();
match kind {
ListKind::Active => self.active_len -= 1,
ListKind::TimeWait => self.time_wait_len -= 1,
}
}
fn is_empty(&self) -> bool {
self.active_len == 0 && self.time_wait_len == 0
}
/// The indices of a list, head first.
fn indices(&self, kind: ListKind) -> Vec<u32> {
let mut out = Vec::new();
let mut cursor = self.head(kind);
while let Some(index) = cursor {
out.push(index);
cursor = self.next(index);
}
out
}
}
/// Packets on their way to the TUN device.
pub struct Net {
pub packets: Vec<Vec<u8>>,
/// The IPv4 identification of the next packet.
ip_id: u16,
pub mtu: u16,
}
/// A TCP header's fields, for `Net::send`.
pub struct Header {
pub seq: SeqNum,
pub ack: SeqNum,
pub flags: TcpFlags,
pub window: u16,
pub mss_option: Option<u16>,
}
impl Net {
/// The MSS for a peer at `remote`: `wanted`, capped by the link.
pub fn effective_mss(&self, wanted: u16, remote: SocketAddr) -> u16 {
if self.mtu == 0 {
return wanted;
}
let headers = if remote.is_ipv6() { 60 } else { 40 };
wanted.min(self.mtu.saturating_sub(headers))
}
/// One segment from `local` to `remote`, wrapped in IP.
pub fn send(&mut self, local: SocketAddr, remote: SocketAddr, header: &Header, payload: &[u8]) {
let ip_header = match (local.ip(), remote.ip()) {
(IpAddr::V4(_), IpAddr::V4(_)) => IPV4_HEADER_LEN,
(IpAddr::V6(_), IpAddr::V6(_)) => IPV6_HEADER_LEN,
_ => return,
};
let options_len = if header.mss_option.is_some() { 4 } else { 0 };
let header_len = TCP_HEADER_LEN + options_len;
let mut packet = vec![0u8; ip_header + header_len + payload.len()];
let segment = &mut packet[ip_header..];
segment[0..2].copy_from_slice(&local.port().to_be_bytes());
segment[2..4].copy_from_slice(&remote.port().to_be_bytes());
segment[4..8].copy_from_slice(&header.seq.raw().to_be_bytes());
segment[8..12].copy_from_slice(&header.ack.raw().to_be_bytes());
segment[12] = ((header_len / 4) as u8) << 4;
segment[13] = header.flags.bits();
segment[14..16].copy_from_slice(&header.window.to_be_bytes());
if let Some(mss) = header.mss_option {
segment[20..24].copy_from_slice(&(0x0204_0000u32 | u32::from(mss)).to_be_bytes());
}
segment[header_len..].copy_from_slice(payload);
wire::fill_transport_checksum(local.ip(), remote.ip(), PROTO_TCP, segment, 16);
let segment_len = segment.len();
match (local.ip(), remote.ip()) {
(IpAddr::V4(src), IpAddr::V4(dst)) => {
wire::write_ipv4(
&mut packet,
&Ipv4Fields {
src,
dst,
protocol: PROTO_TCP,
total_len: (IPV4_HEADER_LEN + segment_len) as u16,
ident: self.ip_id,
dont_fragment: false,
more_fragments: false,
fragment_offset: 0,
ttl: super::config::TTL,
},
);
self.ip_id = self.ip_id.wrapping_add(1);
}
(IpAddr::V6(src), IpAddr::V6(dst)) => {
wire::write_ipv6(
&mut packet,
src,
dst,
PROTO_TCP,
segment_len as u16,
super::config::TTL,
);
}
_ => return,
}
self.packets.push(packet);
}
/// A reset, from no connection in particular.
pub fn send_reset(&mut self, local: SocketAddr, remote: SocketAddr, seq: SeqNum, ack: SeqNum) {
let window = super::config::WINDOW;
let header = Header {
seq,
ack,
flags: TcpFlags::RST | TcpFlags::ACK,
window,
mss_option: None,
};
self.send(local, remote, &header, &[]);
}
}
/// The memory budget, as it stands for the connection being worked on.
pub struct Budget {
cap: Option<usize>,
/// Bytes queued by every connection but the one being worked on.
others: usize,
}
impl Budget {
/// Whether `more` bytes may be queued. What the connection being
/// worked on already holds is not counted.
pub fn allows(&self, more: usize) -> bool {
self.cap.is_none_or(|cap| self.others + more <= cap)
}
}
/// What every operation on a connection shares.
pub struct Env {
pub now: Instant,
pub ticks: Ticks,
pub net: Net,
pub apps: Apps,
pub isn: IsnGenerator,
/// Keep-alive idle time set on accept; 0 for none.
pub keepalive_idle_ms: u32,
pub budget: Budget,
/// The connection a segment is being processed for: its output waits
/// until the processing is done.
pub input: Option<ConnKey>,
/// A close during that processing reset the connection; it is freed
/// once the processing is done.
pub closed_during_input: bool,
}
impl Env {
pub fn holds_output(&self, key: ConnKey) -> bool {
self.input == Some(key)
}
}
pub struct Stack {
conns: Slab,
lists: Lists,
/// (local, remote) → the connection in either list.
demux: HashMap<(SocketAddr, SocketAddr), ConnKey>,
/// When the TCP timer next runs; `None` while there is nothing to time.
timer_due: Option<Millis>,
now_ms: Millis,
/// The TCP timer's next run is a slow tick as well as a fast one.
slow_tick_next: bool,
/// Pool pbufs held by out-of-order segments.
pool_in_use: usize,
/// The pool ran dry: the next packet or timer run frees out-of-order
/// data to make room.
pool_exhausted: bool,
/// Payload bytes queued across every connection in the table.
queued_total: usize,
pub env: Env,
}
/// What `settle` compares a connection against.
struct Before {
out_of_order: usize,
queued: usize,
}
impl Stack {
pub fn new(
isn: IsnGenerator,
mtu: u16,
keepalive_idle_ms: u32,
max_connections: usize,
budget: Option<usize>,
) -> Stack {
Stack {
conns: Slab::default(),
lists: Lists::default(),
demux: HashMap::new(),
timer_due: None,
now_ms: Millis::default(),
slow_tick_next: true,
pool_in_use: 0,
pool_exhausted: false,
queued_total: 0,
env: Env {
now: Instant::ZERO,
ticks: Ticks::default().next(),
net: Net {
packets: Vec::new(),
ip_id: 0,
mtu,
},
apps: Apps::new(max_connections),
isn,
keepalive_idle_ms,
budget: Budget {
cap: budget,
others: 0,
},
input: None,
closed_during_input: false,
},
}
}
pub fn set_now(&mut self, now: Instant) {
self.env.now = now;
self.now_ms = Millis::from_instant(now);
}
// ---- Connections ------------------------------------------------------
/// Runs `f` on a connection taken out of the table, then settles it.
pub fn with_conn<R>(
&mut self,
key: ConnKey,
f: impl FnOnce(&mut Connection, &mut Env) -> R,
) -> Option<R> {
let mut conn = self.conns.take(key)?;
let before = self.lend(&conn);
let result = f(&mut conn, &mut self.env);
self.settle(conn, before);
Some(result)
}
fn lend(&mut self, conn: &Connection) -> Before {
let before = Before {
out_of_order: conn.rcv.out_of_order.len(),
queued: conn.buffered(),
};
self.env.budget.others = self.queued_total - before.queued;
before
}
/// Puts a connection back after an operation, or lets it go, and
/// brings the lists and counts in line with what it now is.
fn settle(&mut self, conn: Box<Connection>, before: Before) {
self.pool_in_use -= before.out_of_order;
self.queued_total -= before.queued;
let key = conn.key;
let pair = (conn.local, conn.remote);
if conn.forget {
self.lists.remove(key.index);
if self.demux.get(&pair) == Some(&key) {
self.demux.remove(&pair);
}
self.conns.free(key);
return;
}
self.pool_in_use += conn.rcv.out_of_order.len();
self.queued_total += conn.buffered();
match (self.lists.list_of(key.index), conn.state) {
(Some(ListKind::Active), State::TimeWait) => {
self.lists.push_front(ListKind::TimeWait, key.index);
self.timer_needed();
}
(None, _) => {
self.lists.push_front(ListKind::Active, key.index);
self.demux.insert(pair, key);
self.timer_needed();
}
_ => {}
}
self.conns.put(conn);
}
/// A key for a new connection, freeing an old one first if the pool is
/// full, as lwIP does: one pending close, the longest-idle TIME-WAIT,
/// LAST-ACK and CLOSING connection in turn. `None` when none of that
/// made room.
fn allocate(&mut self) -> Option<ConnKey> {
if self.conns.live >= CONNECTION_POOL {
self.finish_pending_closes();
self.abandon_longest_idle(ListKind::TimeWait, None, true);
for state in [State::LastAck, State::Closing] {
if self.conns.live >= CONNECTION_POOL {
self.abandon_longest_idle(ListKind::Active, Some(state), false);
}
}
if self.conns.live >= CONNECTION_POOL {
return None;
}
}
Some(self.conns.reserve())
}
/// A key for a connection a SYN is opening, or `None` when the pool
/// has no room. lwIP registers the connection at once, which starts the
/// TCP timer if it was idle — even if the connection goes again before
/// `adopt` — so that happens here.
pub fn open(&mut self) -> Option<ConnKey> {
let key = self.allocate()?;
if self.timer_due.is_none() {
self.timer_due = Some(self.now_ms.after(TIMER_INTERVAL_MS));
}
self.env.budget.others = self.queued_total;
Some(key)
}
/// Takes in the connection `open` was for, set up, or lets its key go
/// if setting it up failed.
pub fn adopt(&mut self, conn: Connection) {
if conn.forget {
self.conns.free(conn.key);
return;
}
let before = Before {
out_of_order: 0,
queued: 0,
};
self.settle(Box::new(conn), before);
}
pub fn find(&self, local: SocketAddr, remote: SocketAddr) -> Option<ConnKey> {
self.demux.get(&(local, remote)).copied()
}
/// Moves a connection a segment arrived for to the head of its list.
pub fn touch(&mut self, key: ConnKey) {
if self.lists.list_of(key.index) == Some(ListKind::Active) {
self.lists.push_front(ListKind::Active, key.index);
}
}
fn finish_pending_closes(&mut self) {
for index in self.lists.indices(ListKind::Active) {
let Some(key) = self.conns.key_at(index) else {
continue;
};
self.with_conn(key, |conn, env| {
if conn.close_pending {
conn.close_pending = false;
conn.close_with_fin(env);
}
});
}
}
/// Of the connections in `kind` (in `state`, if given), the one heard
/// from longest ago — the later one of a tie — abandoned, or aborted
/// with a reset.
fn abandon_longest_idle(&mut self, kind: ListKind, state: Option<State>, reset: bool) {
let ticks = self.env.ticks;
let mut longest = 0u32;
let mut chosen = None;
for index in self.lists.indices(kind) {
let Some(conn) = self.conns.key_at(index).and_then(|k| self.conns.get(k)) else {
continue;
};
if state.is_some_and(|s| conn.state != s) {
continue;
}
let idle = ticks.since(conn.last_activity);
if idle >= longest {
longest = idle;
chosen = Some(conn.key);
}
}
if let Some(key) = chosen {
self.with_conn(key, |conn, env| conn.abandon(reset, env));
}
}
// ---- The pbuf pool ------------------------------------------------------
/// After the pool ran dry, the out-of-order data of the first active
/// connection (in list order) that holds some is dropped.
fn free_out_of_order_if_exhausted(&mut self) {
if !std::mem::take(&mut self.pool_exhausted) {
return;
}
for index in self.lists.indices(ListKind::Active) {
let Some(conn) = self.conns.key_at(index).and_then(|k| self.conns.get_mut(k)) else {
continue;
};
if conn.rcv.out_of_order.is_empty() {
continue;
}
let bytes: usize = conn.rcv.out_of_order.iter().map(|s| s.data.len()).sum();
self.pool_in_use -= conn.rcv.out_of_order.len();
self.queued_total -= bytes;
conn.rcv.out_of_order.clear();
return;
}
}
/// A packet from the TUN device, read into pool pbufs: dropped when
/// there are not enough free.
pub fn receive_packet(&mut self, packet: &[u8]) {
if packet.len() > 0xffff {
return;
}
self.free_out_of_order_if_exhausted();
let needed = packet.len().div_ceil(PBUF_POOL_BUFSIZE).max(1);
if self.pool_in_use + needed > PBUF_POOL_SIZE {
self.pool_exhausted = true;
return;
}
self.on_packet(packet);
}
// ---- The timer ----------------------------------------------------------
fn timer_needed(&mut self) {
if self.timer_due.is_none() && !self.lists.is_empty() {
self.timer_due = Some(self.now_ms.after(TIMER_INTERVAL_MS));
}
}
pub fn timer_due(&self) -> Option<Millis> {
self.timer_due
}
pub fn now_ms(&self) -> Millis {
self.now_ms
}
/// Runs the TCP timer if it is due; it reschedules itself while any
/// connection is left.
pub fn poll(&mut self) {
self.free_out_of_order_if_exhausted();
while let Some(due) = self.timer_due {
if due.is_after(self.now_ms) {
return;
}
self.timer_due = None;
self.run_timer();
if !self.lists.is_empty() {
self.timer_due = Some(self.now_ms.after(TIMER_INTERVAL_MS));
}
}
}
/// One run of the TCP timer: a fast tick for every active connection,
/// and every other run a slow tick.
fn run_timer(&mut self) {
for key in self.keys(ListKind::Active) {
self.with_conn(key, |conn, env| conn.on_fast_tick(env));
}
let slow = self.slow_tick_next;
self.slow_tick_next = !slow;
if !slow {
return;
}
self.env.ticks = self.env.ticks.next();
for key in self.keys(ListKind::Active) {
self.with_conn(key, |conn, env| conn.on_slow_tick(env));
}
let ticks = self.env.ticks;
for key in self.keys(ListKind::TimeWait) {
self.with_conn(key, |conn, _| {
if ticks.since(conn.last_activity) > TWO_MSL_TICKS {
conn.forget = true;
}
});
}
}
/// The keys of a list, head first, as they stand now.
fn keys(&self, kind: ListKind) -> Vec<ConnKey> {
self.lists
.indices(kind)
.into_iter()
.filter_map(|i| self.conns.key_at(i))
.collect()
}
// ---- Accounting ---------------------------------------------------------
pub fn connections(&self) -> usize {
self.lists.active_len + self.lists.time_wait_len
}
pub fn buffered(&self) -> usize {
self.conns.values().map(Connection::buffered).sum()
}
/// Gives back what tables and queues hold beyond a few times their
/// contents, once connections have gone.
pub fn shrink(&mut self) {
let shrink = crate::proxy::tun::netstack::buf::should_shrink;
if shrink(self.demux.len(), self.demux.capacity()) {
self.demux.shrink_to(self.demux.len() * 2);
}
let packets = &mut self.env.net.packets;
if shrink(packets.len(), packets.capacity()) {
packets.shrink_to(packets.len() * 2);
}
self.env.apps.shrink();
}
}
+152
View File
@@ -0,0 +1,152 @@
//! What each connection does on the TCP timer: delayed ACKs and pending
//! closes on every (fast) tick; retransmission, window probes, keep-alive
//! and the state timeouts on every slow tick.
use super::app::Ending;
use super::config::{
FIN_WAIT_2_TIMEOUT_TICKS, KEEPALIVE_INTERVAL_MS, KEEPALIVE_PROBES, MAX_RETRANSMITS,
OUT_OF_ORDER_TIMEOUT_RTOS, PERSIST_BACKOFF, RTO_BACKOFF, SLOW_TICK_MS,
SYN_RECEIVED_TIMEOUT_TICKS, TWO_MSL_TICKS,
};
use super::conn::{Connection, State};
use super::stack::Env;
/// Why a slow tick ends a connection.
enum GiveUp {
/// Silently: retransmissions or probes unanswered, or a state timed out.
Quietly,
/// With a reset: keep-alive found the peer gone.
WithReset,
}
impl Connection {
pub fn on_fast_tick(&mut self, env: &mut Env) {
if self.ack.delayed {
self.ack.now = true;
self.output(env);
self.ack.sent();
}
if self.close_pending {
self.close_pending = false;
self.close_with_fin(env);
}
}
pub fn on_slow_tick(&mut self, env: &mut Env) {
let idle = env.ticks.since(self.last_activity);
let mut give_up = None;
if self.rtx.count >= MAX_RETRANSMITS {
give_up = Some(GiveUp::Quietly);
} else if let Some(persist) = self.persist {
if persist.probes >= MAX_RETRANSMITS {
give_up = Some(GiveUp::Quietly);
} else {
self.persist_tick(env);
}
} else {
self.retransmit_tick(env);
}
if self.state == State::FinWait2 && self.rx_closed && idle > FIN_WAIT_2_TIMEOUT_TICKS {
give_up = Some(GiveUp::Quietly);
}
if let Some(keepalive) = self.keepalive {
if matches!(self.state, State::Established | State::CloseWait) {
let idle_ms = env.keepalive_idle_ms;
let all_probes = KEEPALIVE_PROBES.wrapping_mul(KEEPALIVE_INTERVAL_MS);
let sent_probes = u32::from(keepalive.sent).wrapping_mul(KEEPALIVE_INTERVAL_MS);
if idle > idle_ms.wrapping_add(all_probes) / SLOW_TICK_MS {
give_up = Some(GiveUp::WithReset);
} else if idle > idle_ms.wrapping_add(sent_probes) / SLOW_TICK_MS {
self.send_keepalive(env);
if let Some(keepalive) = self.keepalive.as_mut() {
keepalive.sent = keepalive.sent.wrapping_add(1);
}
}
}
}
let rtos = (self.rtx.rto as u32).wrapping_mul(OUT_OF_ORDER_TIMEOUT_RTOS);
if !self.rcv.out_of_order.is_empty() && idle >= rtos {
self.rcv.out_of_order.clear();
}
if self.state == State::SynReceived && idle > SYN_RECEIVED_TIMEOUT_TICKS {
give_up = Some(GiveUp::Quietly);
}
if self.state == State::LastAck && idle > TWO_MSL_TICKS {
give_up = Some(GiveUp::Quietly);
}
match give_up {
Some(how) => {
let handler = self.handler;
self.purge();
if matches!(how, GiveUp::WithReset) {
env.net
.send_reset(self.local, self.remote, self.snd.next, self.rcv.next);
}
self.forget = true;
env.apps.ended(handler, Ending::Reset);
}
None => {
env.apps.wake(self.handler);
self.output(env);
}
}
}
/// A slow tick while the window is too small for the next segment: when
/// the round's ticks are up, probe a closed window or send what fits an
/// open one, then wait a longer round.
fn persist_tick(&mut self, env: &mut Env) {
let Some(persist) = self.persist.as_mut() else {
return;
};
let round_ticks = PERSIST_BACKOFF[usize::from(persist.round - 1)];
if persist.ticks < round_ticks {
persist.ticks += 1;
}
if persist.ticks < round_ticks {
return;
}
let mut next_round = true;
if self.snd.window == 0 {
self.send_window_probe(env);
} else if self.fit_unsent_head(self.snd.window, env) {
self.output(env);
next_round = false;
}
if next_round {
if let Some(persist) = self.persist.as_mut() {
persist.ticks = 0;
if usize::from(persist.round) < PERSIST_BACKOFF.len() {
persist.round += 1;
}
}
}
}
/// A slow tick of the retransmission timer: once it reaches the RTO,
/// everything in flight goes again, the RTO backs off and the
/// congestion window restarts from one segment.
fn retransmit_tick(&mut self, env: &mut Env) {
self.rtx.timer.tick();
if !self.rtx.timer.reached(self.rtx.rto) {
return;
}
let something_to_send = self.requeue_in_flight()
|| (self.snd.unacked.is_empty() && !self.snd.unsent.is_empty());
if !something_to_send {
return;
}
let backoff = RTO_BACKOFF[usize::from(self.rtx.count).min(RTO_BACKOFF.len() - 1)];
let base = i32::from(self.rtx.rtt.sa >> 3) + i32::from(self.rtx.rtt.sv);
self.rtx.rto = (base << backoff).min(0x7FFF) as i16;
self.rtx.timer.restart();
let flight_window = self.rtx.cwnd.min(self.snd.window);
self.rtx.ssthresh = (flight_window >> 1).max(self.mss << 1);
self.rtx.cwnd = self.mss;
self.rtx.bytes_acked = 0;
self.rtx.count = self.rtx.count.saturating_add(1);
self.output(env);
}
}
+367
View File
@@ -0,0 +1,367 @@
//! Header layouts and the Internet checksum: reading and writing IPv4,
//! IPv6, TCP and UDP headers by byte offset.
//!
//! Readers take untrusted bytes and check every length before using it;
//! writers take buffers their caller sized for them.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
pub const IPV4_HEADER_LEN: usize = 20;
pub const IPV6_HEADER_LEN: usize = 40;
pub const TCP_HEADER_LEN: usize = 20;
pub const UDP_HEADER_LEN: usize = 8;
pub const PROTO_TCP: u8 = 6;
pub const PROTO_UDP: u8 = 17;
fn be16(b: &[u8], at: usize) -> u16 {
u16::from_be_bytes([b[at], b[at + 1]])
}
fn be32(b: &[u8], at: usize) -> u32 {
u32::from_be_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
}
// ---- Checksum ----------------------------------------------------------
/// The one's-complement sum of RFC 1071, fed in any number of pieces.
#[derive(Default)]
pub struct Checksum {
sum: u64,
/// The first byte of a 16-bit word whose second byte has not come yet.
pending: Option<u8>,
}
impl Checksum {
pub fn new() -> Self {
Checksum::default()
}
pub fn add(&mut self, mut data: &[u8]) {
if let Some(high) = self.pending.take() {
match data.split_first() {
Some((&low, rest)) => {
self.sum += u64::from(u16::from_be_bytes([high, low]));
data = rest;
}
None => {
self.pending = Some(high);
return;
}
}
}
let (words, remainder) = data.as_chunks::<2>();
for w in words {
self.sum += u64::from(u16::from_be_bytes(*w));
}
if let [last] = remainder {
self.pending = Some(*last);
}
}
/// The pseudo-header of RFC 9293 §3.1 / RFC 8200 §8.1.
pub fn add_pseudo_header(&mut self, src: IpAddr, dst: IpAddr, protocol: u8, len: usize) {
match (src, dst) {
(IpAddr::V4(s), IpAddr::V4(d)) => {
self.add(&s.octets());
self.add(&d.octets());
self.add(&[0, protocol]);
self.add(&(len as u16).to_be_bytes());
}
_ => {
self.add(&ipv6_of(src).octets());
self.add(&ipv6_of(dst).octets());
self.add(&(len as u32).to_be_bytes());
self.add(&[0, 0, 0, protocol]);
}
}
}
pub fn finish(mut self) -> u16 {
if let Some(high) = self.pending.take() {
self.sum += u64::from(u16::from_be_bytes([high, 0]));
}
while self.sum >> 16 != 0 {
self.sum = (self.sum & 0xffff) + (self.sum >> 16);
}
!(self.sum as u16)
}
}
fn ipv6_of(ip: IpAddr) -> Ipv6Addr {
match ip {
IpAddr::V6(v6) => v6,
IpAddr::V4(v4) => v4.to_ipv6_mapped(),
}
}
/// Whether a TCP or UDP segment's checksum is right.
pub fn transport_checksum_ok(src: IpAddr, dst: IpAddr, protocol: u8, segment: &[u8]) -> bool {
let mut sum = Checksum::new();
sum.add_pseudo_header(src, dst, protocol, segment.len());
sum.add(segment);
sum.finish() == 0
}
/// Fills in the checksum of the TCP or UDP segment in `segment`, whose
/// checksum field is at `field`.
pub fn fill_transport_checksum(
src: IpAddr,
dst: IpAddr,
protocol: u8,
segment: &mut [u8],
field: usize,
) {
segment[field..field + 2].copy_from_slice(&[0, 0]);
let mut sum = Checksum::new();
sum.add_pseudo_header(src, dst, protocol, segment.len());
sum.add(segment);
let mut value = sum.finish();
if protocol == PROTO_UDP && value == 0 {
// Zero means "no checksum" in UDP; its one's-complement twin is sent.
value = 0xffff;
}
segment[field..field + 2].copy_from_slice(&value.to_be_bytes());
}
// ---- IPv4 / IPv6 -------------------------------------------------------
/// The fields of an IPv4 header the stack uses.
pub struct Ipv4Header {
pub header_len: usize,
pub total_len: usize,
pub ident: u16,
pub more_fragments: bool,
/// In bytes.
pub fragment_offset: usize,
pub protocol: u8,
pub src: Ipv4Addr,
pub dst: Ipv4Addr,
}
pub fn read_ipv4(packet: &[u8]) -> Option<Ipv4Header> {
if packet.len() < IPV4_HEADER_LEN || packet[0] >> 4 != 4 {
return None;
}
let header_len = usize::from(packet[0] & 0x0f) * 4;
let total_len = usize::from(be16(packet, 2));
if header_len < IPV4_HEADER_LEN || total_len < header_len || total_len > packet.len() {
return None;
}
let flags_offset = be16(packet, 6);
Some(Ipv4Header {
header_len,
total_len,
ident: be16(packet, 4),
more_fragments: flags_offset & 0x2000 != 0,
fragment_offset: usize::from(flags_offset & 0x1fff) * 8,
protocol: packet[9],
src: Ipv4Addr::new(packet[12], packet[13], packet[14], packet[15]),
dst: Ipv4Addr::new(packet[16], packet[17], packet[18], packet[19]),
})
}
pub fn ipv4_header_checksum_ok(packet: &[u8]) -> bool {
let Some(header) = read_ipv4(packet) else {
return false;
};
let mut sum = Checksum::new();
sum.add(&packet[..header.header_len]);
sum.finish() == 0
}
pub struct Ipv4Fields {
pub src: Ipv4Addr,
pub dst: Ipv4Addr,
pub protocol: u8,
pub total_len: u16,
pub ident: u16,
pub dont_fragment: bool,
pub more_fragments: bool,
/// In bytes; a multiple of 8.
pub fragment_offset: u16,
pub ttl: u8,
}
/// Writes a 20-byte IPv4 header, checksum included, at the start of `buf`.
pub fn write_ipv4(buf: &mut [u8], f: &Ipv4Fields) {
let h = &mut buf[..IPV4_HEADER_LEN];
h[0] = 0x45;
h[1] = 0;
h[2..4].copy_from_slice(&f.total_len.to_be_bytes());
h[4..6].copy_from_slice(&f.ident.to_be_bytes());
let mut flags_offset = f.fragment_offset / 8;
if f.dont_fragment {
flags_offset |= 0x4000;
}
if f.more_fragments {
flags_offset |= 0x2000;
}
h[6..8].copy_from_slice(&flags_offset.to_be_bytes());
h[8] = f.ttl;
h[9] = f.protocol;
h[10..12].copy_from_slice(&[0, 0]);
h[12..16].copy_from_slice(&f.src.octets());
h[16..20].copy_from_slice(&f.dst.octets());
let mut sum = Checksum::new();
sum.add(h);
let value = sum.finish();
h[10..12].copy_from_slice(&value.to_be_bytes());
}
pub struct Ipv6Header {
pub payload_len: usize,
pub next_header: u8,
pub src: Ipv6Addr,
pub dst: Ipv6Addr,
}
pub fn read_ipv6(packet: &[u8]) -> Option<Ipv6Header> {
if packet.len() < IPV6_HEADER_LEN || packet[0] >> 4 != 6 {
return None;
}
let payload_len = usize::from(be16(packet, 4));
if IPV6_HEADER_LEN + payload_len > packet.len() {
return None;
}
let mut src = [0u8; 16];
let mut dst = [0u8; 16];
src.copy_from_slice(&packet[8..24]);
dst.copy_from_slice(&packet[24..40]);
Some(Ipv6Header {
payload_len,
next_header: packet[6],
src: Ipv6Addr::from(src),
dst: Ipv6Addr::from(dst),
})
}
/// Writes a 40-byte IPv6 header at the start of `buf`.
pub fn write_ipv6(
buf: &mut [u8],
src: Ipv6Addr,
dst: Ipv6Addr,
next: u8,
payload_len: u16,
hop_limit: u8,
) {
let h = &mut buf[..IPV6_HEADER_LEN];
h[0..4].copy_from_slice(&[0x60, 0, 0, 0]);
h[4..6].copy_from_slice(&payload_len.to_be_bytes());
h[6] = next;
h[7] = hop_limit;
h[8..24].copy_from_slice(&src.octets());
h[24..40].copy_from_slice(&dst.octets());
}
// ---- TCP ---------------------------------------------------------------
pub struct TcpHeader {
pub src_port: u16,
pub dst_port: u16,
pub seq: u32,
pub ack: u32,
pub header_len: usize,
pub window: u16,
}
/// Reads a TCP segment's header; the options are `segment[20..header_len]`
/// and the payload `segment[header_len..]`.
pub fn read_tcp(segment: &[u8]) -> Option<TcpHeader> {
if segment.len() < TCP_HEADER_LEN {
return None;
}
let header_len = usize::from(segment[12] >> 4) * 4;
if header_len < TCP_HEADER_LEN || header_len > segment.len() {
return None;
}
Some(TcpHeader {
src_port: be16(segment, 0),
dst_port: be16(segment, 2),
seq: be32(segment, 4),
ack: be32(segment, 8),
header_len,
window: be16(segment, 14),
})
}
// ---- UDP ---------------------------------------------------------------
pub struct UdpHeader {
pub src_port: u16,
pub dst_port: u16,
pub len: usize,
pub checksum: u16,
}
pub fn read_udp(segment: &[u8]) -> Option<UdpHeader> {
if segment.len() < UDP_HEADER_LEN {
return None;
}
let len = usize::from(be16(segment, 4));
if len < UDP_HEADER_LEN || len > segment.len() {
return None;
}
Some(UdpHeader {
src_port: be16(segment, 0),
dst_port: be16(segment, 2),
len,
checksum: be16(segment, 6),
})
}
/// Writes the UDP header at the start of `segment`, which already holds
/// the payload after it and is exactly the datagram's length.
pub fn write_udp(segment: &mut [u8], src: IpAddr, dst: IpAddr, src_port: u16, dst_port: u16) {
let len = segment.len() as u16;
segment[0..2].copy_from_slice(&src_port.to_be_bytes());
segment[2..4].copy_from_slice(&dst_port.to_be_bytes());
segment[4..6].copy_from_slice(&len.to_be_bytes());
fill_transport_checksum(src, dst, PROTO_UDP, segment, 6);
}
#[cfg(test)]
mod tests {
//! Known answers computed outside this code.
use super::*;
#[test]
fn ipv4_header_checksum_matches_the_textbook_example() {
// The worked example on Wikipedia's "IPv4 header checksum" page.
let mut header = [
0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0xc0, 0xa8,
0x00, 0x01, 0xc0, 0xa8, 0x00, 0xc7,
];
let mut sum = Checksum::new();
sum.add(&header);
assert_eq!(sum.finish(), 0xb861);
header[10..12].copy_from_slice(&0xb861u16.to_be_bytes());
let mut packet = header.to_vec();
packet.resize(0x73, 0);
assert!(ipv4_header_checksum_ok(&packet));
}
#[test]
fn udp6_checksum_of_an_odd_length_datagram() {
let src: IpAddr = "fd00::2".parse().unwrap();
let dst: IpAddr = "2001:db8::1".parse().unwrap();
let mut segment = vec![0u8; UDP_HEADER_LEN + 5];
segment[UDP_HEADER_LEN..].copy_from_slice(b"hello");
write_udp(&mut segment, src, dst, 5353, 53);
assert_eq!(u16::from_be_bytes([segment[6], segment[7]]), 0x7c27);
assert!(transport_checksum_ok(src, dst, PROTO_UDP, &segment));
}
#[test]
fn a_checksum_fed_in_odd_pieces_equals_one_fed_whole() {
let data: Vec<u8> = (0..=255u8).cycle().take(1001).collect();
let mut whole = Checksum::new();
whole.add(&data);
let mut pieces = Checksum::new();
for chunk in data.chunks(7) {
pieces.add(chunk);
}
assert_eq!(whole.finish(), pieces.finish());
}
}