本页尚未翻译,以下为英文原文。
#3.2. net:: - networking (TCP / UDP / Unix + TLS 1.3)
本页内容
The std::net module provides low-level network primitives together with TLS 1.3 as one bundle. High-level protocols such as HTTP, HTTP/2 and HTTP/3 are deliberately out of scope and delegated to separate packages such as http. This choice also avoids Go's path, where the standard library froze at 1.0 and stopped evolving.
#3.2.0. Common rules
net has three layers for the same sockets:
| Layer | Items | What it fixes |
|---|---|---|
| low level | Socket (3.2.9) | nothing: domain, type, protocol and every option are the caller's; each call is one system call |
| typed | TcpStream::connect, TcpListener::bind, UdpSocket::bind / connect / send_to | the socket type; addresses through ToSocketAddrs (3.2.4) |
| convenient | tcp_connect, tcp_listen, udp_bind (3.2.6) | the same calls as free functions |
- The tier-wide argument conventions apply: a
Pathparameter isP: AsPath, and data being written (write/write_all/send/send_to/send_with_fdand their_asyncforms) acceptsstr,List<u8>andSlice<u8>throughAsBytes. The read buffer is aSliceMut<u8>(2.23.1):read(buf)fills the firstnbytes ofbufand returnsn;0is the end of the stream. - Socket types are OS handles and affine (2.13.4):
let b = smoves the socket; onlytry_cloneduplicates the fd. - Sockets (
Socket,TcpStream,TcpListener,UdpSocket, the Unix sockets),tls::Client/tls::Serverand the halves of a split connection (ReadHalf/WriteHalf, split halves) implementio::Close(2.23.3): closing can fail, so the owner closes each one,try s.close()orusing(2.13.4); leaving its scope open is a compile error.Dropreleases one only on a path an error leaves by, dropping the close's error. Using a closed socket is anIoError(InvalidInput). A*_asyncoperation pending on the socket when another task closes it completes with that error; aftershutdown(Read | Both)a pending read completes with 0. TcpStream,os::unix::net::UnixStreamand the halves of a split connection (ReadHalf: the read traits,WriteHalf: the write traits; split halves) implementio::Read+io::Writeandio::AsyncRead+io::AsyncWrite(2.23); their reads and writes are those trait methods, with no inherent duplicates. A read or write cancelled while suspended moved no bytes. Every socket and TLS connection implementsio::AsyncClose:try await s.close_async(). The*_asyncmethods takeref self(0.5.13).
#Blocking and *_async
Methods come in two sets.
| Form | How it waits |
|---|---|
accept, read, write .. | Blocks the calling OS thread (and, inside a task, its worker) |
accept_async, read_async .. | Suspends only the task; the worker runs other tasks |
*_async methods are async fns, used as try await s.read_async(buf). Waiting for readiness is the job of the I/O driver. An ordinary function cannot suspend a stackless coroutine, so the sync call of the same name does not suspend on its own inside a task.
| blocking | async |
|---|---|
TcpListener::accept | TcpListener::accept_async |
TcpStream::connect | TcpStream::connect_async |
Socket::connect / accept | Socket::connect_async / accept_async |
Read::read | AsyncRead::read_async |
Read::read_to_end | AsyncRead::read_to_end_async |
Write::write | AsyncWrite::write_async |
Write::write_all | AsyncWrite::write_all_async |
Write::flush | AsyncWrite::flush_async |
Close::close | AsyncClose::close_async |
TcpStream::shutdown (and Socket, UnixStream) | shutdown_async |
UdpSocket::connect | UdpSocket::connect_async |
UdpSocket::send_to | UdpSocket::send_to_async |
UdpSocket::recv_from | UdpSocket::recv_from_async |
UdpSocket::send | UdpSocket::send_async |
UdpSocket::recv | UdpSocket::recv_async |
Socket::send_to / recv_from | Socket::send_to_async / recv_from_async |
UnixListener::accept | UnixListener::accept_async |
UnixDatagram::connect / send / recv | UnixDatagram::connect_async / send_async / recv_async |
send_with_fd / recv_with_fd (UnixStream, UnixDatagram) | send_with_fd_async / recv_with_fd_async |
tcp_connect | tcp_connect_async |
tls::Client::new / with_config | tls::Client::new_async / with_config_async |
tls::Server::new | tls::Server::new_async |
tls::Client::read ... key_update (and Server) | read_async ... key_update_async |
The UnixStream reads and writes are the Read / Write rows. The full list per type is 0.5.13.
Timeouts apply only to the blocking side (set_read_timeout / set_write_timeout; exceeding them gives TimedOut). On the async side, wrap with task::timeout (waits on a task) or task::select (2.18.1). select cancels the losing side, which makes it a good fit for abandoning a read.
enum Got { Data(usize), Timeout }
let (_, got) = await task::select([
async { Got::Data(try await s.read_async(buf) catch _ { 0 }) },
async { await task::sleep(Duration::secs(5)); Got::Timeout },
]);
With set_nonblocking(true), blocking methods do not wait and throw WouldBlock.
On wasm32-wasip2, std::net (TCP / UDP connect, bind, listen, accept, DNS) works through wasi:sockets; the host must grant network access (e.g. wasmtime -S inherit-network -S allow-ip-name-lookup). On wasm32-wasip1-threads only TcpListener::inherited() listeners work; connect / bind / DNS throw Unsupported.
#3.2.1. TCP
TCP is built around two types, TcpListener and TcpStream. The listener handles bind and the accept flow; the stream exposes reading, writing and option control.
struct TcpListener { /* OS handle */ }
struct TcpStream { /* OS handle */ }
impl TcpListener {
fn bind<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpListener; // the first address that binds;
// SO_REUSEADDR (not on Windows), backlog 128
fn inherited() -> List<TcpListener>; // listeners the host hands to the process
fn accept(self) throws (IoError) -> (TcpStream, SocketAddr);
async fn accept_async(ref self) throws (IoError) -> (TcpStream, SocketAddr);
fn local_addr(self) throws (IoError) -> SocketAddr; // the actual port after binding to port 0
fn try_clone(self) throws (IoError) -> TcpListener;
fn set_nonblocking(self, nb: bool);
fn incoming(ref self) -> Incoming; // view; TryIterator<Item = TcpStream, Error = IoError>
fn into_incoming(self) -> io::Owned<Incoming, TcpListener>; // owns the listener
fn set_ttl(self, ttl: u32) throws (IoError); // IP_TTL
fn ttl(self) throws (IoError) -> u32;
fn close(self) throws (IoError); // throws what the OS reports
}
impl TcpStream {
fn connect<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpStream; // the first address that accepts
fn connect_timeout(addr: SocketAddr, dur: Duration) throws (IoError) -> TcpStream;
async fn connect_async<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpStream;
fn peer_addr(self) throws (IoError) -> SocketAddr;
fn local_addr(self) throws (IoError) -> SocketAddr;
fn shutdown(self, how: Shutdown) throws (IoError);
async fn shutdown_async(ref self, how: Shutdown) throws (IoError); // shutdown never waits
fn try_clone(self) throws (IoError) -> TcpStream;
fn split(self) -> (ReadHalf<TcpStream>, WriteHalf<TcpStream>); // split halves, below
fn close(self) throws (IoError); // throws what the OS reports
// TCP options
fn set_nodelay(self, nodelay: bool) throws (IoError); // TCP_NODELAY
fn nodelay(self) throws (IoError) -> bool;
fn set_ttl(self, ttl: u32) throws (IoError); // IP_TTL
fn ttl(self) throws (IoError) -> u32;
fn set_keepalive(self, alive: Duration | none) throws (IoError); // SO_KEEPALIVE + idle (seconds), none = off
fn set_read_timeout(self, dur: Duration | none);
fn set_write_timeout(self, dur: Duration | none);
fn read_timeout(self) -> Duration | none;
fn write_timeout(self) -> Duration | none;
fn set_nonblocking(self, nb: bool);
}
impl io::Read for TcpStream { ... } // read, read_to_end, ..
impl io::Write for TcpStream { ... } // write, write_all, flush (no-op)
impl io::AsyncRead for TcpStream { ... }
impl io::AsyncWrite for TcpStream { ... }
impl io::Close for TcpStream { ... }
impl io::Close for TcpListener { ... }
impl io::AsyncClose for TcpStream { ... }
impl io::AsyncClose for TcpListener { ... }
impl Drop for TcpStream { ... } // releases on an error path
impl Drop for TcpListener { ... }
impl From<Socket> for TcpStream { ... } // a connected stream Socket (3.2.9)
impl From<Socket> for TcpListener { ... } // a bound, listening stream Socket
enum Shutdown { Read, Write, Both }
TcpListener::inherited() returns the listeners the host hands to the process: WASI pre-opened sockets, systemd LISTEN_FDS socket activation on Unix, and none on Windows.
Incoming is a scoped view of the listener (2.23.1: it stays in the listener's scope, and the listener stays its owner's to close; into_incoming() owns the listener instead, for a loop that runs in a task of its own) and a TryIterator (2.7.13): each next calls accept once, and a failed accept ends a try for loop with its error. It never ends on its own. If the peer closes during a write, the process is not terminated by SIGPIPE; the write yields an IoError (BrokenPipe).
#Split halves
split takes a connection apart into a read half and a write half, so that one task or thread reads while another writes. It is defined on TcpStream, os::unix::net::UnixStream (3.10.4), tls::Client and tls::Server (3.2.5); T names the connection a half came from.
struct ReadHalf<T> { .. } // Send, not Sync: one owner
struct WriteHalf<T> { .. } // Send, not Sync: one owner
impl<T> ReadHalf<T> {
fn close(self) throws (IoError); // the socket closes once both halves are closed
fn shutdown(self, how: Shutdown) throws (IoError); // the shared socket (see below)
async fn shutdown_async(ref self, how: Shutdown) throws (IoError);
}
impl<T> WriteHalf<T> {
fn close(self) throws (IoError); // ends the stream for the peer (see below)
fn shutdown(self, how: Shutdown) throws (IoError);
async fn shutdown_async(ref self, how: Shutdown) throws (IoError);
}
impl ReadHalf<TcpStream> {
fn unsplit(self, w: WriteHalf<TcpStream>) -> TcpStream;
}
// and ReadHalf<UnixStream>, ReadHalf<tls::Client>, ReadHalf<tls::Server>
impl<T> io::Read for ReadHalf<T> { ... }
impl<T> io::AsyncRead for ReadHalf<T> { ... }
impl<T> io::Write for WriteHalf<T> { ... }
impl<T> io::AsyncWrite for WriteHalf<T> { ... }
impl<T> io::Close for ReadHalf<T> { ... } // and WriteHalf<T>; io::AsyncClose for both
impl<T> Drop for ReadHalf<T> { ... } // and WriteHalf<T>: releases on an error path
split moves the connection into the halves: the old binding is moved, as for let b = s (2.13.4). Each half is the affine owner of its direction and is closed by its owner like any socket (3.2.0). Neither is a second handle of the connection: what the read half reads, the write half does not see, and the two may be used at the same time from two threads or tasks.
Closing the write half while the read half is open ends the stream for the peer: shutdown(Write) (a TLS write half sends close_notify first), and the peer's reads then return 0; the read half goes on reading the reply. Closing the read half alone sends nothing: further data from the peer is not read, and the socket stays open for the write half. The socket closes when the second half is closed (a TLS connection's keys are wiped then); that close throws the error the OS reports. A half's close_async is the same as its close, suspending the task instead of blocking.
Shutting down is an operation on the socket, so either half has shutdown(how), and it acts on the socket both halves name: Read, Write or Both, as TcpStream::shutdown. Both from either half wakes a read or write blocked on the other half, as POSIX shutdown(SHUT_RDWR) does (SD_BOTH on Windows): a pending read returns 0, a pending write fails. On a TLS connection, Write and Both send close_notify first. A write half closed after its writing was shut down does not shut it down again. shutdown_async is the same, awaiting close_notify instead of blocking.
r.unsplit(w) gives the connection back from the two halves of one split; both are spent, and nothing is closed or shut down. A w from another connection panics.
let (r, w) = (try await TcpStream::connect_async(addr)).split();
let writer = task::spawn(async {
try! await w.write_all_async(request);
try! await w.close_async(); // the peer reads end of stream
0
});
let reply = try await r.read_to_end_async();
try r.close(); // the socket closes here
await writer;
#Examples
use core::task;
use std::net::{tcp_listen, TcpListener, TcpStream};
// blocking: this thread waits in accept and handle
using l = try TcpListener::bind("127.0.0.1:8080") {
try for c in l.incoming() {
handle(c); // fn handle(c: TcpStream) closes c
}
}
// async: one task per connection; while waiting, the worker runs other tasks
async fn serve_all(l: TcpListener) throws (IoError) {
loop {
let (s, _) = try await l.accept_async();
task::spawn(serve(s)); // async fn serve(s: TcpStream)
}
}
#3.2.2. UDP
For UDP, a single UdpSocket type covers every role. Datagram send/receive is the baseline, and once a peer is fixed with connect, send / recv alone suffice. Options such as multicast membership and TTL are exposed too, and with workloads like QUIC in mind it includes segment size control for GSO/GRO.
struct UdpSocket { /* OS handle */ }
impl UdpSocket {
fn bind<A: ToSocketAddrs>(addr: A) throws (IoError) -> UdpSocket; // the first address that binds
fn send_to<B: AsBytes, A: ToSocketAddrs>(self, buf: B, addr: A) throws (IoError) -> usize; // to the first address
fn recv_from(self, buf: SliceMut<u8>) throws (IoError) -> (usize, SocketAddr);
fn connect<A: ToSocketAddrs>(self, addr: A) throws (IoError); // fix the peer: the first address that takes it
async fn connect_async<A: ToSocketAddrs>(ref self, addr: A) throws (IoError); // never waits on the socket
fn send<B: AsBytes>(self, buf: B) throws (IoError) -> usize;
fn recv(self, buf: SliceMut<u8>) throws (IoError) -> usize;
// + send_to_async / recv_from_async / send_async / recv_async (ref self)
fn local_addr(self) throws (IoError) -> SocketAddr;
fn peer_addr(self) throws (IoError) -> SocketAddr;
fn set_broadcast(self, on: bool) throws (IoError); // SO_BROADCAST
fn broadcast(self) throws (IoError) -> bool;
fn set_ttl(self, ttl: u32) throws (IoError); // IP_TTL
fn ttl(self) throws (IoError) -> u32;
fn set_read_timeout(self, dur: Duration | none);
fn set_write_timeout(self, dur: Duration | none);
fn read_timeout(self) -> Duration | none;
fn write_timeout(self) -> Duration | none;
fn set_nonblocking(self, nb: bool);
fn try_clone(self) throws (IoError) -> UdpSocket;
fn close(self) throws (IoError); // throws what the OS reports
// multicast (IPv4)
fn join_multicast_v4(self, addr: Ipv4Addr, interface: Ipv4Addr) throws (IoError);
fn leave_multicast_v4(self, addr: Ipv4Addr, interface: Ipv4Addr) throws (IoError);
fn set_multicast_loop_v4(self, on: bool) throws (IoError);
fn set_multicast_ttl_v4(self, ttl: u32) throws (IoError);
// for QUIC (GSO / GRO)
fn set_segment_size(self, size: u16) throws (IoError); // UDP_SEGMENT, Unsupported outside Linux
}
impl io::Close for UdpSocket { ... }
impl io::AsyncClose for UdpSocket { ... }
impl Drop for UdpSocket { ... } // releases on an error path
impl From<Socket> for UdpSocket { ... } // a datagram Socket (3.2.9)
recv_from / recv receive a single datagram into buf. The remainder of a datagram longer than buf is discarded.
#3.2.3. Unix domain socket
Unix domain sockets are Unix-only, so they live in std::os::unix::net (3.10.4), with the same shape as the TCP types here.
#3.2.4. SocketAddr / IpAddr
Address representation centers on the SocketAddr enum, the union of IPv4 and IPv6, and IpAddr, the same union for a bare address. SocketAddrV4 / SocketAddrV6 keep their parts private: getters read them and setters (ref self) change them; a copy is a separate value, so let b = a; b.set_port(p); leaves a as it was. == compares the parts. String parsing works through FromStr implementations, and DNS lookup of host names is provided by separate functions.
enum IpAddr { V4(Ipv4Addr), V6(Ipv6Addr) }
impl IpAddr {
fn is_ipv4(self) -> bool;
fn is_ipv6(self) -> bool;
fn is_loopback(self) -> bool;
}
impl From<Ipv4Addr> for IpAddr { ... }
impl From<Ipv6Addr> for IpAddr { ... }
enum SocketAddr {
V4(SocketAddrV4),
V6(SocketAddrV6),
}
struct SocketAddrV4 { /* ip, port */ }
struct SocketAddrV6 { /* ip, port, flow_info, scope_id */ }
impl SocketAddrV4 {
fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4;
fn ip(self) -> Ipv4Addr;
fn port(self) -> u16;
fn set_ip(ref self, ip: Ipv4Addr);
fn set_port(ref self, port: u16);
}
impl SocketAddrV6 {
fn new(ip: Ipv6Addr, port: u16, flow_info: u32 = 0, scope_id: u32 = 0) -> SocketAddrV6;
fn ip(self) -> Ipv6Addr;
fn port(self) -> u16;
fn flow_info(self) -> u32;
fn scope_id(self) -> u32;
fn set_ip(ref self, ip: Ipv6Addr);
fn set_port(ref self, port: u16);
fn set_flow_info(ref self, flow_info: u32);
fn set_scope_id(ref self, scope_id: u32);
}
impl SocketAddr {
fn new(ip: IpAddr, port: u16) -> SocketAddr; // IPv6: flow_info = scope_id = 0
fn ip(self) -> IpAddr;
fn port(self) -> u16;
fn set_ip(ref self, ip: IpAddr); // the other family replaces the whole address
fn set_port(ref self, port: u16);
fn is_ipv4(self) -> bool;
fn is_ipv6(self) -> bool;
}
impl From<SocketAddrV4> for SocketAddr { ... }
impl From<SocketAddrV6> for SocketAddr { ... }
// what names the addresses to try, in order
trait ToSocketAddrs {
fn to_socket_addrs(self) throws (IoError) -> List<SocketAddr>;
}
impl ToSocketAddrs for SocketAddr { ... } // itself
impl ToSocketAddrs for SocketAddrV4 { ... }
impl ToSocketAddrs for SocketAddrV6 { ... }
impl ToSocketAddrs for str { ... } // resolve(self): "host:port", names looked up
impl ToSocketAddrs for (IpAddr, u16) { ... }
impl ToSocketAddrs for List<SocketAddr> { ... } // in order
struct Ipv4Addr { .. } // private fields
struct Ipv6Addr { .. }
impl Ipv4Addr {
const LOCALHOST: Ipv4Addr; // 127.0.0.1
const UNSPECIFIED: Ipv4Addr; // 0.0.0.0
fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr;
fn octets(self) -> [u8; 4];
fn to_bits(self) -> u32; // big-endian: a.b.c.d is a << 24 | ..
fn is_loopback(self) -> bool;
fn is_unspecified(self) -> bool;
fn is_multicast(self) -> bool;
}
impl Ipv6Addr {
const LOCALHOST: Ipv6Addr; // ::1
const UNSPECIFIED: Ipv6Addr; // ::
fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr;
fn segments(self) -> [u16; 8];
fn is_loopback(self) -> bool;
}
// parsing / printing
impl FromStr for SocketAddr { ... } // "127.0.0.1:8080" / "[::1]:8080"; Err = ParseError
impl FromStr for IpAddr { ... } // "127.0.0.1" / "::1"
impl FromStr for Ipv4Addr { ... }
impl FromStr for Ipv6Addr { ... } // "::" abbreviation allowed
impl Display for SocketAddr { ... } // "127.0.0.1:8080" / "[::1]:8080"; also SocketAddrV4 / V6
impl Display for IpAddr { ... }
impl Display for Ipv4Addr { ... } // "127.0.0.1"
impl Display for Ipv6Addr { ... } // RFC 5952 form: "::1"
impl From<u32> for Ipv4Addr { ... }
// all of them implement Clone, Copy, PartialEq, Eq and Hash (part by part),
// and Debug, written as Display; Ipv4Addr and Ipv6Addr also PartialOrd and Ord
// DNS (getaddrinfo)
fn resolve(host: str) throws (IoError) -> List<SocketAddr>;
resolve obtains a list of addresses with the OS's getaddrinfo and blocks the calling thread. host accepts:
host | Result |
|---|---|
A socket address ("10.0.0.1:80", "[::1]:80") | That single address (no lookup) |
"name:port" | The addresses of name, with port port |
"[v6]:port" | That IPv6 address, with port port |
| A name or IP only | Its addresses, with port 0 |
If the name is not found it is an IoError (NotFound; another resolver failure is Other), and the message includes the resolver's description. A resolver failure has no os_code() (2.23.0), except on Windows, where the resolver reports Winsock codes. The first address of a name and port is resolve(f"{host}:{port}")[0] (an IPv6 host in [..]).
close throws the error the OS reports (0.5.9); closing a closed socket is a no-op. Drop closes the socket too and drops the error (3.2.0).
#3.2.5. TLS 1.3 - net::tls
TLS lives in the net::tls submodule and assumes 1.3 only from the start. It is implemented on core::crypto and is experimental, not independently audited (2.21.5). ClientConfig and ServerConfig express certificates, cipher suites and the ALPN protocol list, and the post-quantum option enables ML-KEM hybrid key exchange. Both are #[non_exhaustive] records whose public fields have defaults, except root_certs, cert_chain and private_key (6.2.10): a literal names only what differs, and every field added later has a default. After the handshake, Client / Server behave like plaintext streams, so existing I/O code can sit on top almost unchanged.
use std::net::tls;
#[non_exhaustive]
struct ClientConfig {
pub root_certs: List<Certificate>; // trust anchors (no default)
pub cipher_suites: List<CipherSuite> = CipherSuite::all(); // TLS 1.3 suites, preference order
pub alpn_protocols: List<List<u8>> = []; // ["h2", "http/1.1"], etc.
pub enable_post_quantum: bool = true; // post-quantum (X25519MLKEM768 hybrid)
pub client_cert_chain: List<Certificate> = []; // sent when the server asks: leaf first; empty: none
pub client_key: PrivateKey | none = none; // the client leaf's key
pub session_cache: SessionCache | none = SessionCache::new(); // tickets to resume from; none: never resume
pub early_data: List<u8> = []; // 0-RTT data, else the first data after the handshake
}
impl ClientConfig {
fn new() throws (TlsError) -> ClientConfig; // ClientConfig { root_certs: system_roots() }
}
#[non_exhaustive]
struct ServerConfig {
pub cert_chain: List<Certificate>; // leaf first, then intermediates (no default)
pub private_key: PrivateKey; // the leaf's key (no default)
pub cipher_suites: List<CipherSuite> = CipherSuite::all();
pub alpn_protocols: List<List<u8>> = [];
pub client_roots: List<Certificate> = []; // non-empty: ask for a client certificate, validated against these
pub require_client_cert: bool = true; // with client_roots: refuse a client without one
pub ocsp_response: List<u8> = []; // DER OCSPResponse stapled when asked; empty: none
pub ticket_store: TicketStore | none = TicketStore::new(); // resumption; none: no tickets
pub max_early_data: u32 = 0; // 0-RTT bytes accepted per connection; 0: none
}
impl ServerConfig {
fn new(cert_chain: List<Certificate>, private_key: PrivateKey) throws (TlsError) -> ServerConfig;
// ServerConfig { cert_chain, private_key }, checked now: the key must belong to cert_chain[0]
}
struct SessionCache { .. } // the client's tickets by server name; copies share them
impl SessionCache {
fn new() -> SessionCache;
fn len(self) -> usize;
fn clear(self);
}
struct TicketStore { .. } // the server's resumable sessions; copies share them
impl TicketStore {
fn new() -> TicketStore;
fn len(self) -> usize;
}
#[non_exhaustive]
enum CipherSuite { Aes128GcmSha256, Aes256GcmSha384, ChaCha20Poly1305Sha256 }
impl CipherSuite {
fn all() -> List<CipherSuite>; // all three, in the default preference order
}
struct Certificate { .. } // Sync: shared across threads
impl Certificate {
fn from_der<B: AsBytes>(der: B) throws (TlsError) -> Certificate;
fn from_pem(text: str) throws (TlsError) -> List<Certificate>;
fn to_der(self) -> List<u8>; // a copy of the DER encoding
fn dns_names(self) -> List<str>;
fn not_before(self) -> SystemTime; // whole seconds (3.3)
fn not_after(self) -> SystemTime;
}
struct PrivateKey { .. } // Ed25519, ECDSA P-256 / P-384, RSA (2048..4096 bits), RSASSA-PSS
impl PrivateKey {
fn from_der<B: AsBytes>(der: B) throws (TlsError) -> PrivateKey; // PKCS #8
fn from_pem(text: str) throws (TlsError) -> PrivateKey; // PRIVATE KEY, EC PRIVATE KEY or RSA PRIVATE KEY
}
fn system_roots() throws (TlsError) -> List<Certificate>; // the OS trust store (read on each call)
#[non_exhaustive]
enum TlsErrorKind { Io, Certificate, Protocol, PeerAlert }
struct TlsError { .. } // private fields (0.5.10); + Display, Debug, Error, PartialEq, Eq, Clone
impl TlsError {
fn new(kind: TlsErrorKind, message: str, alert: u8) -> TlsError;
fn kind(self) -> TlsErrorKind;
fn message(self) -> str; // without the "tls: " Display adds
fn alert(self) -> u8; // the alert sent (received, for PeerAlert)
}
struct Client { .. }
impl Client {
fn new(stream: TcpStream, server_name: str) throws (TlsError) -> Client;
fn with_config(stream: TcpStream, server_name: str, cfg: ClientConfig) throws (TlsError) -> Client;
async fn new_async(stream: TcpStream, server_name: str) throws (TlsError) -> Client;
async fn with_config_async(stream: TcpStream, server_name: str, cfg: ClientConfig) throws (TlsError) -> Client;
fn close_notify(self) throws (IoError);
fn key_update(self) throws (IoError);
fn close(self) throws (IoError);
async fn close_notify_async(ref self) throws (IoError);
async fn key_update_async(ref self) throws (IoError);
fn negotiated_alpn(self) -> List<u8> | none;
fn peer_certificates(self) -> List<Certificate>;
fn is_resumed(self) -> bool; // the handshake resumed a session
fn is_early_data_accepted(self) -> bool; // early_data went out as 0-RTT data
fn split(self) -> (ReadHalf<Client>, WriteHalf<Client>); // 3.2.1 split halves
}
impl WriteHalf<Client> { // and WriteHalf<Server>
fn key_update(self) throws (IoError);
async fn key_update_async(ref self) throws (IoError);
}
struct Server { .. }
impl Server {
fn new(stream: TcpStream, cfg: ServerConfig) throws (TlsError) -> Server;
async fn new_async(stream: TcpStream, cfg: ServerConfig) throws (TlsError) -> Server;
// close_notify, key_update, close, their *_async forms,
// negotiated_alpn, peer_certificates and split as on Client, and:
fn server_name(self) -> str | none; // the client's SNI
fn is_resumed(self) -> bool;
fn early_data(self) -> List<u8>; // the 0-RTT data accepted; read returns what follows
}
Client and Server implement io::Read, io::Write, io::AsyncRead and io::AsyncWrite (2.23), io::Close (close, below; the owner closes each one, 3.2.0) and Drop (the same on an error path, its error dropped). A handshake that fails closes the stream it was given; one that succeeds owns it. A connection is affine (2.13.4): let b = c moves it, and it is used by one thread at a time (!Sync). For a reader and a writer at once, split it (3.2.1): the read half reads while the write half writes. The two halves may be used from different threads or tasks. Closing the write half sends close_notify, then shuts the socket down for writing. Certificate is Sync.
Records go out in the order they are made. A KeyUpdate request that a read receives is answered with the connection's next records: at once when no write is in progress, else right after the records of the write in progress, so a read never waits on a write blocked on a full socket. Once close_notify is sent, a KeyUpdate request is not answered (nothing follows close_notify).
The *_async methods follow 3.2.0: they suspend only the task while the socket is not ready, and the handshake (new_async, with_config_async) does the same between the peer's messages. The blocking and async forms may be mixed on one connection.
The stack is implementation-provided and written in Nabi on core::crypto (2.21): no operating-system or third-party TLS library is used, and users never call one. Only TLS 1.3 (RFC 8446) is spoken; TLS 1.2 and earlier are refused. The handshake supports X25519 and the X25519MLKEM768 hybrid (ML-KEM-768 + X25519, enable_post_quantum), HelloRetryRequest (for a group or a cookie), ALPN, SNI, KeyUpdate, close_notify, client certificates, OCSP stapling, and resumption with 0-RTT data.
Resumption: a server with a ticket_store sends one NewSessionTicket after each handshake; the store keeps the session (at most 4096, the oldest dropped; lifetime 2 hours) and redeems a ticket at most once. A client with a session_cache keeps the tickets it receives under the server name it connected to (at most 64), and offers the newest live one whose cipher suite's hash it also offers, once (psk_dhe_ke only: the resumed handshake still does a fresh key exchange). A resumed connection skips certificate authentication; peer_certificates() returns the original connection's chain. A ticket is received while the client reads.
0-RTT: when early_data is non-empty and the ticket allows that many bytes, the client sends it as early data with the ClientHello; otherwise, or if the server declines, it is sent as the first application data after the handshake (is_early_data_accepted() tells which). A server accepts early data only with max_early_data > 0, on the first offered ticket, without HelloRetryRequest, with the ticket's cipher suite and ALPN protocol, and when the client's ticket age is within 10 seconds of the server's; it hands the data out through early_data() and skips early data it declines. Since every ticket is redeemed once from its TicketStore, a replayed ClientHello resumes nothing and its early data is skipped (RFC 8446 8.1); servers that should reject each other's replays must share one store. Early data is still not forward-secret with respect to the ticket and should be idempotent.
Client certificates: a server with non-empty client_roots sends a CertificateRequest; the client's chain is validated against client_roots like a server's (below) with extendedKeyUsage clientAuth and no name check, and its CertificateVerify checked. A client without a certificate fails the handshake with certificate_required if require_client_cert, else continues with no peer_certificates(). A client answers a CertificateRequest with client_cert_chain and a CertificateVerify by client_key when the server accepts a scheme for that key, else with an empty Certificate. A client_key that does not belong to the first certificate makes Client::with_config fail before anything is sent.
Server authentication: the certificate path is built from the peer's chain to one of root_certs and validated per RFC 5280 (signatures, validity at the current time, basicConstraints, keyUsage, extendedKeyUsage serverAuth, DNS and IP name constraints; unknown critical extensions fail). The server name is matched against subjectAltName only (RFC 6125: case-insensitive, a wildcard is the whole leftmost label); an IP literal is matched against iPAddress entries and sends no SNI. Accepted signatures: Ed25519, ECDSA P-256 / P-384 with SHA-256/384/512, RSA PKCS #1 v1.5 (certificates only) and RSA-PSS with SHA-256/384/512 (2048-4096-bit keys, rsaEncryption or id-RSASSA-PSS; in certificates any salt length, honoring an id-RSASSA-PSS key's hash and minimum salt). Revocation: the client asks for an OCSP response (status_request). A stapled response must be a successful basic OCSP response (RFC 6960) signed by the leaf's issuer or by a certificate the issuer issued with extendedKeyUsage OCSPSigning, with a SHA-1 or SHA-2 CertID naming the leaf, thisUpdate not more than 5 minutes ahead and nextUpdate present and not past; status revoked fails with certificate_revoked, any other problem (unknown status included) with bad_certificate_status_response. A leaf with the TLS feature extension for status_request (RFC 7633) requires a stapled response. Without a staple and without that extension the certificate is accepted; CRLs and OCSP queries over the network are not used.
A certificate that is expired or not yet valid fails with certificate_expired, one whose extendedKeyUsage does not allow the role with unsupported_certificate, one with no path to root_certs with unknown_ca, and any other failure with bad_certificate. An extension in ServerHello, HelloRetryRequest, EncryptedExtensions or a Certificate entry that the client did not request fails with unsupported_extension. A failed handshake sends its alert, then closes the stream.
Either side signs its CertificateVerify with its key's scheme: ed25519, ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, for an rsaEncryption certificate the first of rsa_pss_rsae_sha256 / _sha384 / _sha512 the peer offers, and for an id-RSASSA-PSS certificate the first of rsa_pss_pss_sha256 / _sha384 / _sha512 the peer offers that the key's parameters allow. PrivateKey reads PKCS #8 (Ed25519, id-ecPublicKey on P-256 / P-384, rsaEncryption, id-RSASSA-PSS), RFC 5915 EC PRIVATE KEY and PKCS #1 RSA PRIVATE KEY. ServerConfig::new, Server::new and Server::new_async fail (TlsErrorKind::Certificate) when cert_chain is empty or the key's public half is not the leaf's.
The stack keeps its traffic, handshake and resumption secrets, record keys, key-exchange secrets, ticket PSKs and Ed25519 / EC private keys in secret storage (2.21.5), and wipes them on KeyUpdate, at the end of the handshake and on close.
ClientConfig::new() throws the system_roots() error when the OS trust store cannot be read (no store found, an unreadable bundle, any wasm target); Client::new and Client::new_async build their config with it and throw the same error. Other fields are set from it with a struct update: ClientConfig { alpn_protocols: [..], ..try ClientConfig::new() }. Without a store, write the literal with root_certs: ClientConfig { root_certs: roots }.
Client::close and Server::close send close_notify when the connection is healthy (its failure is not reported), then close the socket and throw the error the OS reports; the keys are wiped either way.
system_roots() reads the OS trust store: the macOS keychain anchors (plus admin / user certificates trusted unconditionally), the Windows ROOT store, the first CA bundle found on Linux (/etc/ssl/certs/ca-certificates.crt, /etc/pki/tls/certs/ca-bundle.crt, ...), Android's roots (/apex/com.android.conscrypt/cacerts from Android 14, else /system/etc/security/cacerts). SSL_CERT_FILE overrides it. wasm targets have no store: pass root_certs.
read returns 0 after the peer's close_notify; a connection that ends without one is an IoError (UnexpectedEof); a protocol failure is an IoError (InvalidData) after a fatal alert is sent. TLS records are written whole, so write writes all of buf.
#Example
Actual use is simple: put a TLS client on top of a plaintext TCP connection and call plaintext I/O on it.
use std::net::{tcp_connect, tls};
let conn = try tcp_connect("example.com:443");
let tls_conn = try tls::Client::new(conn, "example.com");
try tls_conn.write_all(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
let resp = try tls_conn.read_to_end();
try tls_conn.close(); // close_notify, then the socket
#3.2.6. Convenience functions
The typed constructors as free functions, for the common case. They take the same ToSocketAddrs (3.2.4), so a host name can be passed directly, as in tcp_connect("example.com:80").
fn tcp_connect<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpStream; // TcpStream::connect(addr)
async fn tcp_connect_async<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpStream; // TcpStream::connect_async(addr)
fn tcp_listen<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpListener; // TcpListener::bind(addr)
fn udp_bind<A: ToSocketAddrs>(addr: A) throws (IoError) -> UdpSocket; // UdpSocket::bind(addr)
connect tries the addresses in order and returns the first that connects; bind binds the first that works; if all fail, they throw the last error, and an empty list is InvalidInput.
#3.2.7. zerocopy hooks (advanced)
sendfile, splice and write_zerocopy are Linux-only, so they are the trait TcpStreamExt in std::os::linux::net (3.10.6), in the prelude on Linux: stream.sendfile(ref f, 0, n) there needs no use. The OS descriptor of a socket is AsRawFd (unix) or AsRawSocket (Windows) (3.10.2).
#3.2.8. Module mapping
Per-platform support is summarized below. Core features work on both desktop OSes and wasi, but items that depend on Linux-specific facilities, such as Unix sockets and zerocopy hooks, are enabled only in limited places.
| Item | linux/macos/windows | wasi | Notes |
|---|---|---|---|
| TCP | ✓ | ✓ | wasi:sockets |
| UDP | ✓ | ✓ | wasi:sockets |
| Unix socket | linux/macos | ✗ | os::unix::net; no Windows form (named pipes are separate) |
| TLS 1.3 | ✓ | ✓ (no trust store: pass root_certs) | Nabi's own, on core::crypto |
| sendfile | linux | ✗ | os::linux::net::TcpStreamExt |
| splice | linux | ✗ | os::linux::net::TcpStreamExt |
| MSG_ZEROCOPY | linux 4.14+ | ✗ | os::linux::net::TcpStreamExt |
Socket | ✓ | wasip2 | SocketType::Raw and set_reuse_port: not on Windows or WASI |
#3.2.9. Socket - the low-level layer
Socket is the socket as the operating system has it, in the shape of Rust's socket2: the caller picks the domain, type and protocol and sets each option, and every method is the one system call its name says. bind sets no SO_REUSEADDR, connect resolves nothing, and listen takes the backlog. Once set up, TcpStream::from(s), TcpListener::from(s) or UdpSocket::from(s) takes the socket over (s is moved), and Socket::from goes back the other way.
#[non_exhaustive]
enum Domain { Ipv4, Ipv6 } // AF_INET, AF_INET6; Clone, Copy, PartialEq, Eq, Hash, Debug
impl Domain {
fn for_address(addr: SocketAddr) -> Domain;
}
#[non_exhaustive]
enum SocketType { Stream, Datagram, Raw } // SOCK_STREAM, SOCK_DGRAM, SOCK_RAW; Clone, Copy, PartialEq, Eq, Hash, Debug
struct Protocol { /* an IP protocol number */ } // Clone, Copy, PartialEq, Eq, Hash, Debug
impl Protocol {
const ICMPV4: Protocol; // 1
const TCP: Protocol; // 6
const UDP: Protocol; // 17
const ICMPV6: Protocol; // 58
fn new(number: i32) -> Protocol;
fn number(self) -> i32;
}
struct Socket { /* OS handle */ } // Debug prints `Socket`
impl Socket {
fn new(domain: Domain, ty: SocketType, protocol: Protocol | none = none) throws (IoError) -> Socket;
// none: the type's default protocol
fn bind(self, addr: SocketAddr) throws (IoError);
fn listen(self, backlog: i32) throws (IoError);
fn connect(self, addr: SocketAddr) throws (IoError); // in non-blocking mode: WouldBlock while in progress
fn connect_timeout(self, addr: SocketAddr, dur: Duration) throws (IoError);
async fn connect_async(ref self, addr: SocketAddr) throws (IoError);
fn accept(self) throws (IoError) -> (Socket, SocketAddr);
async fn accept_async(ref self) throws (IoError) -> (Socket, SocketAddr);
fn local_addr(self) throws (IoError) -> SocketAddr;
fn peer_addr(self) throws (IoError) -> SocketAddr;
fn shutdown(self, how: Shutdown) throws (IoError);
async fn shutdown_async(ref self, how: Shutdown) throws (IoError);
fn send_to<B: AsBytes>(self, buf: B, addr: SocketAddr) throws (IoError) -> usize;
fn recv_from(self, buf: SliceMut<u8>) throws (IoError) -> (usize, SocketAddr);
// + send_to_async / recv_from_async (ref self)
// options: each setter has a getter of the same name, except set_keepalive and set_nonblocking
fn set_reuse_address(self, on: bool) throws (IoError); // SO_REUSEADDR
fn set_reuse_port(self, on: bool) throws (IoError); // SO_REUSEPORT; Unsupported off Unix
fn set_nodelay(self, on: bool) throws (IoError); // TCP_NODELAY
fn set_broadcast(self, on: bool) throws (IoError); // SO_BROADCAST
fn set_recv_buffer_size(self, size: usize) throws (IoError); // SO_RCVBUF (the OS may round it)
fn set_send_buffer_size(self, size: usize) throws (IoError); // SO_SNDBUF
fn set_ttl(self, ttl: u32) throws (IoError); // IP_TTL
fn set_only_v6(self, on: bool) throws (IoError); // IPV6_V6ONLY
fn set_linger(self, dur: Duration | none) throws (IoError); // SO_LINGER, whole seconds; none: off
fn set_keepalive(self, alive: Duration | none) throws (IoError); // as on TcpStream (no getter)
fn set_nonblocking(self, nb: bool);
fn set_read_timeout(self, dur: Duration | none);
fn set_write_timeout(self, dur: Duration | none);
fn read_timeout(self) -> Duration | none;
fn write_timeout(self) -> Duration | none;
fn try_clone(self) throws (IoError) -> Socket;
fn close(self) throws (IoError);
}
impl io::Read for Socket { ... } // and io::Write, io::AsyncRead, io::AsyncWrite
impl io::Close for Socket { ... }
impl Drop for Socket { ... } // releases on an error path
impl From<TcpStream> for Socket { ... } // and TcpListener, UdpSocket
A new socket is non-blocking underneath and not inherited by child processes, like every socket in this module; the blocking calls wait as 3.2.0 says.
use std::net::{Socket, Domain, SocketType, Protocol, TcpListener};
let s = try Socket::new(Domain::Ipv6, SocketType::Stream, Protocol::TCP);
try s.set_only_v6(false); // IPv4 too, on one socket
try s.set_reuse_address(true);
try s.bind(try "[::]:8080".parse());
try s.listen(1024);
let l = TcpListener::from(s);
Found a mistake? Edit this page on GitHub. Last updated