docs

您正在閱讀 v0.1.0 的文件。Nabi 0.1.0 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#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:

LayerItemsWhat it fixes
low levelSocket (3.2.9)nothing: domain, type, protocol and every option are the caller's; each call is one system call
typedTcpStream::connect, TcpListener::bind, UdpSocket::bind / connect / send_tothe socket type; addresses through ToSocketAddrs (3.2.4)
convenienttcp_connect, tcp_listen, udp_bind (3.2.6)the same calls as free functions
  • The tier-wide argument conventions apply: a Path parameter is P: AsPath, and data being written (write / write_all / send / send_to / send_with_fd and their _async forms) accepts str, List<u8> and Slice<u8> through AsBytes. The read buffer is a SliceMut<u8> (2.23.1): read(buf) fills the first n bytes of buf and returns n; 0 is the end of the stream.
  • Socket types are OS handles and affine (2.13.4): let b = s moves the socket; only try_clone duplicates the fd.
  • Sockets (Socket, TcpStream, TcpListener, UdpSocket, the Unix sockets), tls::Client / tls::Server and the halves of a split connection (ReadHalf / WriteHalf, split halves) implement io::Close (2.23.3): closing can fail, so the owner closes each one, try s.close() or using (2.13.4); leaving its scope open is a compile error. Drop releases one only on a path an error leaves by, dropping the close's error. Using a closed socket is an IoError (InvalidInput). A *_async operation pending on the socket when another task closes it completes with that error; after shutdown(Read | Both) a pending read completes with 0.
  • TcpStream, os::unix::net::UnixStream and the halves of a split connection (ReadHalf: the read traits, WriteHalf: the write traits; split halves) implement io::Read + io::Write and io::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 implements io::AsyncClose: try await s.close_async(). The *_async methods take ref self (0.5.13).

#Blocking and *_async

Methods come in two sets.

FormHow 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.

blockingasync
TcpListener::acceptTcpListener::accept_async
TcpStream::connectTcpStream::connect_async
Socket::connect / acceptSocket::connect_async / accept_async
Read::readAsyncRead::read_async
Read::read_to_endAsyncRead::read_to_end_async
Write::writeAsyncWrite::write_async
Write::write_allAsyncWrite::write_all_async
Write::flushAsyncWrite::flush_async
Close::closeAsyncClose::close_async
TcpStream::shutdown (and Socket, UnixStream)shutdown_async
UdpSocket::connectUdpSocket::connect_async
UdpSocket::send_toUdpSocket::send_to_async
UdpSocket::recv_fromUdpSocket::recv_from_async
UdpSocket::sendUdpSocket::send_async
UdpSocket::recvUdpSocket::recv_async
Socket::send_to / recv_fromSocket::send_to_async / recv_from_async
UnixListener::acceptUnixListener::accept_async
UnixDatagram::connect / send / recvUnixDatagram::connect_async / send_async / recv_async
send_with_fd / recv_with_fd (UnixStream, UnixDatagram)send_with_fd_async / recv_with_fd_async
tcp_connecttcp_connect_async
tls::Client::new / with_configtls::Client::new_async / with_config_async
tls::Server::newtls::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.

nabi
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.

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.

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.

nabi
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

nabi
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.

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.

resolve obtains a list of addresses with the OS's getaddrinfo and blocks the calling thread. host accepts:

hostResult
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 onlyIts 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.

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.

nabi
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").

nabi
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.

Itemlinux/macos/windowswasiNotes
TCP✓✓wasi:sockets
UDP✓✓wasi:sockets
Unix socketlinux/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
sendfilelinux✗os::linux::net::TcpStreamExt
splicelinux✗os::linux::net::TcpStreamExt
MSG_ZEROCOPYlinux 4.14+✗os::linux::net::TcpStreamExt
Socket✓wasip2SocketType::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.

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.

nabi
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