#3.2. net:::网络(TCP / UDP / Unix + TLS 1.3)
本页内容
std::net 模块把底层网络原语与 TLS 1.3 一起作为一个整体提供。HTTP、HTTP/2 和 HTTP/3 等高层协议被有意排除在范围之外,交给 http 等单独的包。这个选择也避免了 Go 的老路:Go 的标准库在 1.0 时冻结,之后不再演进。
#3.2.0. 通用规则
net 为同一套套接字提供三个层次:
| 层次 | 项 | 固定了什么 |
|---|---|---|
| 底层 | Socket(3.2.9) | 什么都不固定:域、类型、协议和每个选项都由调用者决定;每次调用就是一个系统调用 |
| 类型化 | TcpStream::connect、TcpListener::bind、UdpSocket::bind / connect / send_to | 套接字类型;地址通过 ToSocketAddrs 给出(3.2.4) |
| 便捷 | tcp_connect、tcp_listen、udp_bind(3.2.6) | 以自由函数形式提供同样的调用 |
- 整个层级共用的参数约定在此适用:
Path参数即P: AsPath;要写出的数据(write/write_all/send/send_to/send_with_fd及其_async形式)通过AsBytes接受str、List<u8>和Slice<u8>。读取缓冲区是SliceMut<u8>(2.23.1):read(buf)填充buf的前n个字节并返回n;0表示流结束。 - 套接字类型是操作系统句柄,是仿射的(2.13.4):
let b = s移动套接字;只有try_clone会复制 fd。 - 套接字(
Socket、TcpStream、TcpListener、UdpSocket、Unix 套接字)、tls::Client/tls::Server以及拆分后连接的两半(ReadHalf/WriteHalf,拆分为两半)都实现了io::Close(2.23.3):关闭可能失败,所以所有者必须逐个关闭它们,写try s.close()或使用using(2.13.4);让它在未关闭的状态下离开作用域是编译错误。Drop只在因错误而离开的路径上释放它,并丢弃关闭时的错误。使用已关闭的套接字是IoError(InvalidInput)。另一个任务关闭套接字时,正在该套接字上等待的*_async操作以这个错误完成;shutdown(Read | Both)之后,等待中的读取以 0 完成。 TcpStream、os::unix::net::UnixStream以及拆分后连接的两半(ReadHalf:读取 trait,WriteHalf:写入 trait;拆分为两半)实现了io::Read+io::Write以及io::AsyncRead+io::AsyncWrite(2.23);它们的读写就是这些 trait 方法,没有重复的固有方法。在挂起期间被取消的读或写不会传输任何字节。每个套接字和 TLS 连接都实现了io::AsyncClose:try await s.close_async()。*_async方法接受ref self(0.5.13)。
#阻塞与 *_async
方法分为两组。
| 形式 | 等待方式 |
|---|---|
accept、read、write .. | 阻塞调用它的操作系统线程(在任务中还会阻塞其工作线程) |
accept_async、read_async .. | 只挂起任务;工作线程去运行其他任务 |
*_async 方法是 async fn,用法是 try await s.read_async(buf)。等待就绪由 I/O 驱动负责。普通函数无法挂起无栈协程,所以在任务中,同名的同步调用不会自行挂起。
| 阻塞 | 异步 |
|---|---|
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(以及 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(以及 Server) | read_async ... key_update_async |
UnixStream 的读写对应 Read / Write 两行。各类型的完整列表见 0.5.13。
超时只作用于阻塞的一侧(set_read_timeout / set_write_timeout;超时会得到 TimedOut)。在异步一侧,用 task::timeout(等待一个任务)或 task::select(2.18.1)包装。select 会取消落败的一方,因此很适合用来放弃一次读取。
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 },
]);
使用 set_nonblocking(true) 时,阻塞方法不会等待,而是抛出 WouldBlock。
在 wasm32-wasip2 上,std::net(TCP / UDP 的 connect、bind、listen、accept、DNS)通过 wasi:sockets 工作;主机必须授予网络访问权限(例如 wasmtime 的 -S inherit-network -S allow-ip-name-lookup)。在 wasm32-wasip1-threads 上只有 TcpListener::inherited() 监听器可用;connect / bind / DNS 抛出 Unsupported。
#3.2.1. TCP
TCP 围绕 TcpListener 和 TcpStream 两个类型构建。监听器负责 bind 和 accept 流程;流提供读、写和选项控制。
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() 返回主机交给进程的监听器:WASI 的预打开套接字、Unix 上 systemd 的 LISTEN_FDS 套接字激活;在 Windows 上没有。
Incoming 是监听器的作用域视图(2.23.1:它停留在监听器的作用域内,监听器仍由其所有者关闭;into_incoming() 则拥有监听器,适用于在单独任务中运行的循环),也是一个 TryIterator(2.7.13):每次 next 调用一次 accept,失败的 accept 以其错误结束 try for 循环。它不会自行结束。如果对端在写入期间关闭,进程不会被 SIGPIPE 终止;写入产生 IoError(BrokenPipe)。
#拆分为两半
split 把一个连接拆成读半部分和写半部分,使一个任务或线程读取的同时另一个写入。它定义在 TcpStream、os::unix::net::UnixStream(3.10.4)、tls::Client 和 tls::Server(3.2.5)上;T 指出半部分来自哪种连接。
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 把连接移入两个半部分:与 let b = s 一样,原来的绑定被移动(2.13.4)。每个半部分是其方向上的仿射所有者,像任何套接字一样由其所有者关闭(3.2.0)。两者都不是连接的第二个句柄:读半部分读到的内容,写半部分看不到;两者可以同时在两个线程或任务中使用。
在读半部分仍打开时关闭写半部分,会为对端结束流:执行 shutdown(Write)(TLS 写半部分先发送 close_notify),此后对端的读取返回 0;读半部分继续读取回复。只关闭读半部分不发送任何东西:不再读取对端发来的数据,套接字为写半部分保持打开。第二个半部分关闭时套接字关闭(TLS 连接的密钥此时被擦除);这次关闭抛出操作系统报告的错误。半部分的 close_async 与其 close 相同,只是挂起任务而不是阻塞。
关闭方向是对套接字的操作,所以两个半部分都有 shutdown(how),它作用于两半共同指向的套接字:Read、Write 或 Both,与 TcpStream::shutdown 相同。从任一半部分执行 Both 都会唤醒阻塞在另一半上的读或写,与 POSIX 的 shutdown(SHUT_RDWR)(Windows 上为 SD_BOTH)一样:等待中的读取返回 0,等待中的写入失败。在 TLS 连接上,Write 和 Both 会先发送 close_notify。写入方向已关闭后再关闭的写半部分不会再次执行 shutdown。shutdown_async 相同,只是等待 close_notify 而不是阻塞。
r.unsplit(w) 从同一次 split 得到的两个半部分取回连接;两者都被消耗,不关闭也不 shutdown 任何东西。来自另一个连接的 w 会触发 panic。
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;
#示例
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
UDP 只用一个 UdpSocket 类型承担所有角色。基础是数据报的收发;用 connect 固定对端之后,只用 send / recv 即可。组播成员关系和 TTL 等选项也一并提供;考虑到 QUIC 这类负载,它还包括用于 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 把单个数据报接收到 buf 中。比 buf 长的数据报,其余部分被丢弃。
#3.2.3. Unix 域套接字
Unix 域套接字只存在于 Unix 上,所以位于 std::os::unix::net(3.10.4),形式与这里的 TCP 类型相同。
#3.2.4. SocketAddr / IpAddr
地址表示以 SocketAddr 枚举(IPv4 与 IPv6 的联合)和 IpAddr(对单纯地址的同样联合)为中心。SocketAddrV4 / SocketAddrV6 的各部分是私有的:通过 getter 读取,通过 setter(ref self)修改;副本是独立的值,所以 let b = a; b.set_port(p); 不会改变 a。== 逐部分比较。字符串解析通过 FromStr 实现完成,主机名的 DNS 查询由单独的函数提供。
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 用操作系统的 getaddrinfo 获取地址列表,会阻塞调用它的线程。host 接受:
host | 结果 |
|---|---|
套接字地址("10.0.0.1:80"、"[::1]:80") | 该单个地址(不查询) |
"name:port" | name 的各个地址,端口为 port |
"[v6]:port" | 该 IPv6 地址,端口为 port |
| 只有名称或 IP | 它的各个地址,端口为 0 |
找不到名称时是 IoError(NotFound;解析器的其他失败为 Other),消息中包含解析器的描述。解析器失败没有 os_code()(2.23.0),但 Windows 例外,那里的解析器报告 Winsock 错误码。某个名称和端口的第一个地址是 resolve(f"{host}:{port}")[0](IPv6 主机写在 [..] 中)。
close 抛出操作系统报告的错误(0.5.9);关闭已关闭的套接字不做任何事。Drop 也会关闭套接字,并丢弃错误(3.2.0)。
#3.2.5. TLS 1.3:net::tls
TLS 位于 net::tls 子模块中,从一开始就只支持 1.3。它基于 core::crypto 实现,属于实验性功能,未经独立审计(2.21.5)。ClientConfig 和 ServerConfig 表达证书、密码套件和 ALPN 协议列表,后量子选项启用 ML-KEM 混合密钥交换。两者都是 #[non_exhaustive] 记录,除 root_certs、cert_chain 和 private_key 外,公开字段都有默认值(6.2.10):字面量只写出与默认不同的部分,以后新增的每个字段也都有默认值。握手之后,Client / Server 的行为与明文流相同,现有的 I/O 代码几乎不用修改就能放在上面。
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 和 Server 实现了 io::Read、io::Write、io::AsyncRead 和 io::AsyncWrite(2.23)、io::Close(close,见下文;所有者逐个关闭它们,3.2.0)以及 Drop(在错误路径上做同样的事,并丢弃其错误)。握手失败时会关闭交给它的流;握手成功后拥有该流。连接是仿射的(2.13.4):let b = c 移动它,并且同一时间只由一个线程使用(!Sync)。要同时有读取者和写入者,就对它执行 split(3.2.1):读半部分读取的同时写半部分写入。两个半部分可以在不同的线程或任务中使用。关闭写半部分会发送 close_notify,然后关闭套接字的写方向。Certificate 是 Sync。
记录按生成的顺序发出。读取收到的 KeyUpdate 请求由连接接下来的记录应答:没有写入正在进行时立即应答,否则紧跟在正在进行的写入的记录之后应答,所以读取绝不会等待阻塞在已满套接字上的写入。close_notify 发出后,不再应答 KeyUpdate 请求(close_notify 之后不再有任何东西)。
*_async 方法遵循 3.2.0:套接字未就绪时只挂起任务,握手(new_async、with_config_async)在对端的消息之间也是如此。阻塞形式和异步形式可以在同一个连接上混用。
协议栈由实现提供,用 Nabi 基于 core::crypto(2.21)编写:不使用操作系统或第三方的 TLS 库,用户也不会调用这样的库。只使用 TLS 1.3(RFC 8446);TLS 1.2 及更早的版本被拒绝。握手支持 X25519 和 X25519MLKEM768 混合(ML-KEM-768 + X25519,enable_post_quantum)、HelloRetryRequest(用于组或 cookie)、ALPN、SNI、KeyUpdate、close_notify、客户端证书、OCSP stapling,以及带 0-RTT 数据的会话恢复。
会话恢复:带有 ticket_store 的服务器在每次握手之后发送一个 NewSessionTicket;存储区保存会话(最多 4096 个,丢弃最旧的;有效期 2 小时),每个票据最多兑现一次。带有 session_cache 的客户端把收到的票据按它所连接的服务器名保存(最多 64 个),并提供其中最新的、仍然有效的、且其密码套件的哈希也在自己提供之列的票据,只提供一次(仅 psk_dhe_ke:恢复的握手仍然进行新的密钥交换)。恢复的连接跳过证书认证;peer_certificates() 返回原始连接的证书链。票据在客户端读取时接收。
0-RTT:当 early_data 不为空且票据允许这么多字节时,客户端把它作为早期数据随 ClientHello 发送;否则,或者服务器拒绝时,它作为握手之后的第一份应用数据发送(is_early_data_accepted() 表明是哪一种)。服务器只在以下条件下接受早期数据:max_early_data > 0,针对第一个被提供的票据,没有 HelloRetryRequest,使用票据的密码套件和 ALPN 协议,并且客户端的票据年龄与服务器的相差在 10 秒以内;它通过 early_data() 交出数据,并跳过它拒绝的早期数据。由于每个票据只能从其 TicketStore 兑现一次,重放的 ClientHello 不会恢复任何会话,其早期数据会被跳过(RFC 8446 8.1);需要相互拒绝对方重放的服务器必须共享同一个存储区。早期数据相对于票据仍然不具备前向保密性,应当是幂等的。
客户端证书:client_roots 不为空的服务器发送 CertificateRequest;客户端的证书链像服务器的证书链一样(见下文)针对 client_roots 验证,要求 extendedKeyUsage clientAuth,不检查名称,并检查其 CertificateVerify。没有证书的客户端,在 require_client_cert 时以 certificate_required 使握手失败,否则继续,且没有 peer_certificates()。当服务器接受某个适用于 client_key 的签名方案时,客户端用 client_cert_chain 和由 client_key 签名的 CertificateVerify 应答 CertificateRequest,否则以空的 Certificate 应答。不属于第一个证书的 client_key 会使 Client::with_config 在发送任何东西之前失败。
服务器认证:证书路径从对端的证书链构建到 root_certs 之一,并按 RFC 5280 验证(签名、当前时间的有效期、basicConstraints、keyUsage、extendedKeyUsage serverAuth、DNS 和 IP 名称约束;未知的关键扩展导致失败)。服务器名只与 subjectAltName 匹配(RFC 6125:不区分大小写,通配符必须是整个最左侧标签);IP 字面量与 iPAddress 条目匹配,并且不发送 SNI。接受的签名:Ed25519,使用 SHA-256/384/512 的 ECDSA P-256 / P-384,RSA PKCS #1 v1.5(仅限证书),以及使用 SHA-256/384/512 的 RSA-PSS(2048-4096 位密钥,rsaEncryption 或 id-RSASSA-PSS;证书中允许任意盐长度,并遵守 id-RSASSA-PSS 密钥的哈希和最小盐长度)。吊销:客户端请求 OCSP 响应(status_request)。stapled 的响应必须是成功的基本 OCSP 响应(RFC 6960),由叶证书的签发者或由签发者以 extendedKeyUsage OCSPSigning 签发的证书签名,带有指向叶证书的 SHA-1 或 SHA-2 CertID,thisUpdate 最多超前 5 分钟,nextUpdate 必须存在且尚未过去;状态为 revoked 时以 certificate_revoked 失败,其他任何问题(包括状态未知)以 bad_certificate_status_response 失败。带有 status_request 的 TLS feature 扩展(RFC 7633)的叶证书要求 stapled 响应。既没有 staple 也没有该扩展时,证书被接受;不使用 CRL,也不通过网络进行 OCSP 查询。
已过期或尚未生效的证书以 certificate_expired 失败,extendedKeyUsage 不允许该角色的证书以 unsupported_certificate 失败,没有到 root_certs 的路径的证书以 unknown_ca 失败,其他任何失败以 bad_certificate 失败。ServerHello、HelloRetryRequest、EncryptedExtensions 或某个 Certificate 条目中出现客户端未请求的扩展时,以 unsupported_extension 失败。失败的握手先发送其告警,然后关闭流。
双方都用其密钥的签名方案签署 CertificateVerify:ed25519、ecdsa_secp256r1_sha256、ecdsa_secp384r1_sha384;对于 rsaEncryption 证书,取对端提供的 rsa_pss_rsae_sha256 / _sha384 / _sha512 中的第一个;对于 id-RSASSA-PSS 证书,取对端提供的、密钥参数允许的 rsa_pss_pss_sha256 / _sha384 / _sha512 中的第一个。PrivateKey 读取 PKCS #8(Ed25519、P-256 / P-384 上的 id-ecPublicKey、rsaEncryption、id-RSASSA-PSS)、RFC 5915 EC PRIVATE KEY 和 PKCS #1 RSA PRIVATE KEY。当 cert_chain 为空,或密钥的公钥部分不是叶证书的公钥时,ServerConfig::new、Server::new 和 Server::new_async 失败(TlsErrorKind::Certificate)。
协议栈把流量密钥、握手和会话恢复的秘密、记录密钥、密钥交换秘密、票据 PSK 以及 Ed25519 / EC 私钥保存在秘密存储中(2.21.5),并在 KeyUpdate 时、握手结束时和关闭时擦除它们。
无法读取操作系统信任存储时(找不到存储、无法读取的证书包、任何 wasm 目标),ClientConfig::new() 抛出 system_roots() 的错误;Client::new 和 Client::new_async 用它构建配置,并抛出同样的错误。其他字段用结构体更新语法在它的基础上设置:ClientConfig { alpn_protocols: [..], ..try ClientConfig::new() }。没有存储时,写出带 root_certs 的字面量:ClientConfig { root_certs: roots }。
Client::close 和 Server::close 在连接正常时发送 close_notify(其失败不报告),然后关闭套接字并抛出操作系统报告的错误;无论哪种情况密钥都会被擦除。
system_roots() 读取操作系统的信任存储:macOS 钥匙串的锚点(加上无条件信任的管理员 / 用户证书)、Windows 的 ROOT 存储、Linux 上找到的第一个 CA 证书包(/etc/ssl/certs/ca-certificates.crt、/etc/pki/tls/certs/ca-bundle.crt……)、Android 的根证书(Android 14 起为 /apex/com.android.conscrypt/cacerts,否则为 /system/etc/security/cacerts)。SSL_CERT_FILE 会覆盖它。wasm 目标没有存储:请传入 root_certs。
对端发送 close_notify 之后,read 返回 0;没有 close_notify 就结束的连接是 IoError(UnexpectedEof);协议失败在发送致命告警之后成为 IoError(InvalidData)。TLS 记录整体写出,所以 write 写出 buf 的全部内容。
#示例
实际使用很简单:在明文 TCP 连接之上放一个 TLS 客户端,然后在它上面调用明文 I/O。
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. 便捷函数
以自由函数形式提供的类型化构造函数,用于常见情形。它们接受同样的 ToSocketAddrs(3.2.4),所以可以直接传入主机名,例如 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 按顺序尝试各个地址,返回第一个连接成功的;bind 绑定第一个可用的;如果全部失败,抛出最后一个错误,空列表为 InvalidInput。
#3.2.7. zerocopy 钩子(进阶)
sendfile、splice 和 write_zerocopy 只存在于 Linux 上,所以它们是 std::os::linux::net 中的 trait TcpStreamExt(3.10.6),在 Linux 上位于 prelude 中:在那里 stream.sendfile(ref f, 0, n) 不需要 use。套接字的操作系统描述符通过 AsRawFd(unix)或 AsRawSocket(Windows)获取(3.10.2)。
#3.2.8. 模块映射
各平台的支持情况汇总如下。核心功能在两种桌面操作系统和 wasi 上都可用,但 Unix 套接字和 zerocopy 钩子等依赖 Linux 特有设施的项只在有限的地方启用。
| 项 | linux/macos/windows | wasi | 说明 |
|---|---|---|---|
| TCP | ✓ | ✓ | wasi:sockets |
| UDP | ✓ | ✓ | wasi:sockets |
| Unix 套接字 | linux/macos | ✗ | os::unix::net;没有 Windows 形式(命名管道是另外的东西) |
| TLS 1.3 | ✓ | ✓(没有信任存储:传入 root_certs) | Nabi 自有实现,基于 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 和 set_reuse_port:Windows 和 WASI 上没有 |
#3.2.9. Socket:底层层次
Socket 是操作系统所看到的套接字,形式与 Rust 的 socket2 相同:调用者选择域、类型和协议并设置每个选项,每个方法都是其名称所示的那一个系统调用。bind 不设置 SO_REUSEADDR,connect 不做任何解析,listen 接受 backlog。设置完成后,TcpStream::from(s)、TcpListener::from(s) 或 UdpSocket::from(s) 接管该套接字(s 被移动),Socket::from 则反向转换。
#[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
与本模块中的每个套接字一样,新套接字在底层是非阻塞的,并且不被子进程继承;阻塞调用按 3.2.0 所述的方式等待。
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);
发现错误? 在 GitHub 上编辑此页 最后更新: