Skip to main content

net_io/
lib.rs

1//! # net_io
2//!
3//! The network IO substrate for the `-net` and `-io` crates: the entrance and
4//! exit every service shares. It owns listeners and sockets, the life of each
5//! connection, the limits and timeouts that keep a peer from holding what it
6//! should not, graceful drain, and the seams a connection gate and a TLS engine
7//! plug into. It is protocol-free and has no runtime dependencies.
8//!
9//! ## Quick start
10//!
11//! ```no_run
12//! fn main() -> Result<(), net_io::NetError> {
13//!     // An echo server: one handler call per connection on a bounded worker pool,
14//!     // with every default limit (idle, read, write, minimum rate, caps) applied.
15//!     let server = net_io::serve("127.0.0.1:7000", |conn| {
16//!         let mut buf = [0u8; 4096];
17//!         loop {
18//!             let n = conn.recv(&mut buf)?;
19//!             if n == 0 {
20//!                 return Ok(()); // the peer closed its side
21//!             }
22//!             conn.send_all(&buf[..n])?;
23//!         }
24//!     })?;
25//!
26//!     // A client.
27//!     let mut conn = net_io::connect("127.0.0.1:7000")?;
28//!     conn.send_all(b"ping")?;
29//!     let mut reply = [0u8; 4];
30//!     conn.recv_exact(&mut reply)?;
31//!     assert_eq!(&reply, b"ping");
32//!
33//!     // Stop: close the door, drain open connections, join the workers.
34//!     server.handle().request_stop();
35//!     let report = server.wait_for_stop();
36//!     println!("{} closed gracefully, {} killed", report.graceful, report.killed);
37//!     Ok(())
38//! }
39//! ```
40//!
41//! Everything else (several listeners, a gate, events, the control line) goes
42//! through [`ServerBuilder`]. The full reference with every item, its errors,
43//! and its cost is `docs/API.md` in the
44//! [repository](https://github.com/jamesgober/net-io).
45//!
46//! ## Status
47//!
48//! `0.7.3`: the reactor on epoll, kqueue, and IOCP, and the blocking pool, on
49//! Linux, macOS, FreeBSD, and Windows. TCP with a client that reconnects with
50//! backoff, Unix domain sockets (AF_UNIX on Windows), Windows named pipes, and UDP
51//! with batches and sessions; zero-copy file sends and file receives; the PROXY
52//! protocol, the TLS seam, systemd and FastCGI inheritance, listener hand-off on Unix
53//! and Windows, and the public [`Driver`] interface. Hardened: an attack test per
54//! threat, continuous fuzzing, and a 24-hour soak. A second, independent review
55//! (2026-11-11) found more: its critical and high findings are fixed here, and
56//! the rest are fixed in `0.8.0`.
57
58#![doc(html_root_url = "https://docs.rs/net-io")]
59#![cfg_attr(docsrs, feature(doc_cfg))]
60#![deny(unsafe_code)]
61#![deny(unsafe_op_in_unsafe_fn)]
62#![deny(missing_docs)]
63#![cfg_attr(
64    not(test),
65    deny(
66        clippy::unwrap_used,
67        clippy::expect_used,
68        clippy::panic,
69        clippy::todo,
70        clippy::unimplemented,
71        clippy::dbg_macro,
72        clippy::print_stdout,
73        clippy::print_stderr
74    )
75)]
76
77mod accept;
78mod addr;
79mod buf;
80mod completer;
81mod control;
82mod crc32c;
83mod driver;
84mod error;
85mod events;
86mod gate;
87mod handoff;
88mod id;
89mod info;
90mod inherit;
91mod limits;
92mod link;
93#[cfg(feature = "local")]
94mod local;
95#[cfg(all(windows, feature = "local"))]
96mod local_windows;
97mod opts;
98#[cfg(all(windows, feature = "local"))]
99mod pipe;
100mod proxy;
101#[cfg(feature = "proxy")]
102mod proxy_parse;
103mod rate;
104mod retry;
105mod server;
106mod session;
107mod sys;
108mod tcp;
109#[cfg(test)]
110mod testing;
111mod time;
112mod tls;
113mod trusted;
114#[cfg(feature = "udp")]
115mod udp;
116#[cfg_attr(not(test), allow(dead_code))]
117mod wheel;
118
119/// Entry points for net-io's fuzz targets (`fuzz/`), compiled only under
120/// cargo-fuzz (`--cfg fuzzing`). Not part of the public API and not covered by semver.
121#[cfg(fuzzing)]
122#[doc(hidden)]
123pub mod __fuzz {
124    /// The hand-off manifest decoder.
125    pub fn manifest(data: &[u8]) {
126        crate::handoff::fuzz_manifest(data);
127    }
128
129    /// The systemd environment reader.
130    pub fn systemd_env(data: &[u8]) {
131        crate::inherit::fuzz_systemd_env(data);
132    }
133
134    /// The timing wheel against a model.
135    pub fn wheel(data: &[u8]) {
136        crate::wheel::fuzz_wheel(data);
137    }
138
139    /// The minimum-rate counter's invariants.
140    pub fn rate(data: &[u8]) {
141        crate::rate::fuzz_rate(data);
142    }
143
144    /// The UDP guard's tables, verification, and budgets against a model.
145    #[cfg(feature = "udp")]
146    pub fn udp(data: &[u8]) {
147        crate::udp::fuzz_udp(data);
148    }
149}
150
151/// Fault injection for net-io's own tests, compiled only with `--cfg net_io_shim`.
152/// Not part of the public API and not covered by semver.
153#[cfg(net_io_shim)]
154#[doc(hidden)]
155pub mod __shim {
156    pub use crate::sys::shim::{Fault, Op, clear, counted, program, start_counting, stop_counting};
157}
158
159use std::net::ToSocketAddrs;
160
161pub use addr::{AddrError, Cidr, PrefixKey, PrefixPolicy, normalize, normalize_socket};
162pub use buf::{Buffer, BufferPool, PoolStats};
163pub use completer::{Completer, PostError};
164pub use control::{ControlLine, ControlState, NoControl, SimpleControl};
165#[cfg(feature = "reactor")]
166pub use driver::new_reactor_driver;
167pub use driver::{
168    Completion, Completions, Driver, DriverKind, DriverWaker, Operation, OperationKind, Rejected,
169    SendChunks, SharedSocket, Token,
170};
171pub use error::{
172    CloseReason, ConfigReason, Direction, ErrorClass, KillReason, LimitKind, NetError,
173    OsErrorClass, RefusalCause, TimeoutKind,
174};
175pub use events::{CoalescedKind, Event, EventSink, NoopSink};
176pub use gate::{AdmitStage, Admitted, AllowAll, Denial, Gate, KillHandle, Refusal, WriteCheck};
177pub use handoff::{HandoffError, HandoffPeer, ListenerHandle};
178#[cfg(all(windows, feature = "local"))]
179pub use handoff::{SharedListeners, receive_shared, share_listeners};
180#[cfg(all(unix, feature = "local"))]
181pub use handoff::{recv_listeners, send_listeners};
182pub use id::{ConnectionId, ListenerId, WorkerId};
183pub use info::{
184    ConnectionInfo, Endpoint, GateTag, Lane, Origin, PeerCredentials, PipeName, Transport, UnixPath,
185};
186#[cfg(unix)]
187pub use inherit::fastcgi_listener;
188pub use inherit::{InheritError, InheritedListener, systemd, systemd_named};
189pub use limits::{Limits, LimitsBuilder, MinRate, Pressure, SizeClass, descriptor_limit};
190#[cfg(all(unix, feature = "local"))]
191pub use local::{Descriptors, UnixConnection, UnixListener};
192#[cfg(feature = "local")]
193pub use local::{LocalConnection, LocalListener};
194#[cfg(all(windows, feature = "local"))]
195pub use local_windows::{UnixConnection, UnixListener};
196pub use opts::{Keepalive, Linger, ListenOptions, LocalOptions, SocketOptions, TcpOptions};
197#[cfg(all(windows, feature = "local"))]
198pub use pipe::{PipeConnection, PipeListener, PipeOptions, PipeSecurity};
199pub use proxy::{ProxyError, ProxyFacts, ProxyMode, ProxyVersions};
200#[cfg(feature = "proxy")]
201pub use proxy_parse::{
202    ProxyAddress, ProxyCommand, ProxyHeader, ProxyParser, ProxyProgress, ProxySsl, ProxyTransport,
203    Tlv, Tlvs, encode_v1, encode_v2,
204};
205pub use retry::Backoff;
206#[cfg(feature = "udp")]
207pub use server::UdpOnly;
208pub use server::{
209    AdoptSpec, BlockingHandler, DoorState, DrainReport, ListenerSpec, NoGate, NoWork, Placement,
210    Server, ServerBuilder, ServerHandle, Sessions, Stats, Workload,
211};
212pub use session::{
213    Input, Output, OutputFull, Phase, Session, SessionContext, SessionFactory, Step, SwapError,
214};
215pub use tcp::{ConnectOptions, Drained, Health, ListenerInfo, TcpConnection, TcpListener};
216pub use time::{Clock, ManualClock, MonotonicClock, monotonic_micros};
217pub use tls::{
218    NoTls, NoTlsSession, TlsAcceptor, TlsCloseKind, TlsError, TlsEvent, TlsFailure, TlsInfo,
219    TlsProgress, TlsSession,
220};
221pub use trusted::TrustedProxies;
222#[cfg(feature = "udp")]
223pub use udp::{
224    Datagram, DatagramBuffer, MulticastInterface, OutgoingDatagram, UdpBudget, UdpContext,
225    UdpOptions, UdpSession, UdpSessionFactory, UdpSocket, UdpStats,
226};
227
228/// Crate version string, populated by Cargo at build time.
229///
230/// ```
231/// assert!(!net_io::VERSION.is_empty());
232/// ```
233pub const VERSION: &str = env!("CARGO_PKG_VERSION");
234
235/// Binds a TCP listener with safe defaults: backlog 1,024 (capped by the OS);
236/// `SO_REUSEADDR` on Unix; `SO_EXCLUSIVEADDRUSE` on Windows; IPv6-only for IPv6
237/// addresses; close-on-exec. The first resolved address that binds wins.
238///
239/// # Errors
240///
241/// `AddrInUse`, `PermissionDenied`, `AddrNotAvailable`, `NoAddresses`, `Bind`.
242///
243/// # Examples
244///
245/// ```
246/// let listener = net_io::listen("127.0.0.1:0")?;
247/// let addr = listener.local_addr()?;
248/// println!("listening on {addr}, backlog {:?}", listener.info().backlog);
249/// # Ok::<(), net_io::NetError>(())
250/// ```
251pub fn listen<A: ToSocketAddrs>(addr: A) -> Result<TcpListener, NetError> {
252    TcpListener::bind(addr)
253}
254
255/// Connects with a total timeout of 10 s across every resolved address,
256/// `TCP_NODELAY` on, and default limits (read and write timeouts 30 s).
257///
258/// # Errors
259///
260/// `ConnectTimeout`, `ConnectionRefused`, `HostUnreachable`, `NetworkUnreachable`, `NoAddresses`.
261///
262/// # Examples
263///
264/// ```no_run
265/// let mut conn = net_io::connect("example.com:80")?;
266/// conn.send_all(b"HEAD / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")?;
267/// let mut head = [0u8; 512];
268/// let n = conn.recv(&mut head)?;
269/// println!("{}", String::from_utf8_lossy(&head[..n]));
270/// # Ok::<(), net_io::NetError>(())
271/// ```
272pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpConnection, NetError> {
273    TcpConnection::connect(addr)
274}
275
276/// Starts a server on the blocking driver that runs `handler` once per
277/// connection on a pool worker, with default limits and [`AllowAll`] as the
278/// gate; the door is open on return. `Ok(())` closes the connection
279/// gracefully; `Err` closes it abortively.
280///
281/// Keep the returned `Server`: dropping it stops the server. A server facing
282/// the internet should set a [`Gate`] through [`ServerBuilder`].
283///
284/// # Errors
285///
286/// As [`listen`]; `InvalidConfig` when the worker count exceeds the descriptor limit.
287///
288/// # Examples
289///
290/// ```no_run
291/// use std::io::{BufRead, BufReader, Write};
292///
293/// // Handlers can use std::io traits: TcpConnection implements Read and Write.
294/// let server = net_io::serve("127.0.0.1:7001", |conn| {
295///     let mut line = String::new();
296///     BufReader::new(&mut *conn).read_line(&mut line)?;
297///     conn.write_all(line.to_uppercase().as_bytes())?;
298///     Ok(())
299/// })?;
300/// server.wait_for_stop();
301/// # Ok::<(), net_io::NetError>(())
302/// ```
303pub fn serve<A, F>(addr: A, handler: F) -> Result<Server, NetError>
304where
305    A: ToSocketAddrs,
306    F: Fn(&mut TcpConnection) -> Result<(), NetError> + Send + Sync + 'static,
307{
308    let server = ServerBuilder::new()
309        .listener(ListenerSpec::tcp(addr))
310        .driver(DriverKind::Blocking)
311        .handler(handler)
312        .gate(AllowAll)
313        .build()?;
314    server.open_door()?;
315    Ok(server)
316}
317
318/// Starts a server that drives sans-IO [`Session`]s, with default limits and
319/// [`AllowAll`] as the gate; the door is open on return. Any
320/// `Fn(&ConnectionInfo) -> S` is a factory.
321///
322/// # Errors
323///
324/// As [`serve`].
325///
326/// # Examples
327///
328/// ```no_run
329/// use net_io::{Input, Session, SessionContext, Step};
330///
331/// struct Echo;
332/// impl Session for Echo {
333///     fn on_data(&mut self, cx: &mut SessionContext<'_>, input: &mut Input) -> Step {
334///         let taken = cx.output().push_partial(input.bytes());
335///         input.consume(taken);
336///         Step::Write
337///     }
338/// }
339///
340/// let server = net_io::serve_sessions("127.0.0.1:7002", |_info: &net_io::ConnectionInfo| Echo)?;
341/// server.wait_for_stop();
342/// # Ok::<(), net_io::NetError>(())
343/// ```
344pub fn serve_sessions<A, F>(addr: A, factory: F) -> Result<Server, NetError>
345where
346    A: ToSocketAddrs,
347    F: SessionFactory,
348{
349    let server = ServerBuilder::new()
350        .listener(ListenerSpec::tcp(addr))
351        .sessions(factory)
352        .gate(AllowAll)
353        .build()?;
354    server.open_door()?;
355    Ok(server)
356}
357
358/// Opens a local IPC listener: on Unix, a Unix domain socket at the path `name`
359/// with mode `0600` (only the owner may connect; [`LocalOptions`] and
360/// `UnixListener::bind_with` for more). On Windows, the named pipe
361/// `\\\\.\\pipe\\<name>`, owner only, remote clients rejected.
362///
363/// # Errors
364///
365/// `PathTooLong`, `StaleSocketInUse` (a live listener owns the path, or it is
366/// not a socket), `PermissionDenied`, `NotFound`, `Unsupported`, `Os`.
367///
368/// ```no_run
369/// let listener = net_io::listen_local("/run/myapp/control.sock")?;
370/// let (mut conn, info) = listener.accept()?;
371/// println!("peer process {:?}", info.peer_credentials.and_then(|c| c.pid));
372/// conn.send_all(b"ok\n")?;
373/// # Ok::<(), net_io::NetError>(())
374/// ```
375#[cfg(feature = "local")]
376pub fn listen_local(name: &str) -> Result<LocalListener, NetError> {
377    local::listen(name)
378}
379
380/// Connects to a local IPC listener (see [`listen_local`]); waits up to 10 s
381/// when its backlog is full.
382///
383/// # Errors
384///
385/// `NotFound` (no socket, or nobody listening), `PermissionDenied`,
386/// `TimedOut { kind: Connect }`, `PathTooLong`, `Unsupported`, `Os`.
387///
388/// ```no_run
389/// let mut conn = net_io::connect_local("/run/myapp/control.sock")?;
390/// conn.send_all(b"status\n")?;
391/// # Ok::<(), net_io::NetError>(())
392/// ```
393#[cfg(feature = "local")]
394pub fn connect_local(name: &str) -> Result<LocalConnection, NetError> {
395    local::connect(name)
396}
397
398#[cfg(test)]
399mod tests {
400    use super::VERSION;
401
402    #[test]
403    fn test_version_matches_manifest() {
404        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
405        assert_eq!(VERSION.split('.').count(), 3, "expected MAJOR.MINOR.PATCH");
406    }
407}