netchan#
Message channels for games: UDP with sequence numbers and acks, WebSocket, the browser's network -- crate root lib/netchan/src/lib.rs
netchan -- message channels for games (G7d, docs/TRANSPORT.md)
Client::connect(Endpoint::Udp(addr) | Endpoint::WebSocket(url), ClientConfig)
poll() -> ClientEvent (Connected, Message { seq, data }, Reliable(data),
Delivered(seq), Lost(seq), Disconnected(reason)), send(payload) -> seq,
send_reliable(message), state, reliable, max_payload, stats
Server::new(ServerConfig) [.bind_udp(addr)] [.listen_ws(addr, path) | .ws_endpoint()]
poll() -> ServerEvent, send(id, payload) -> seq, send_reliable(id, message),
disconnect(id), stats(id)
(Windows, Linux, Apple: it needs netio's HTTP server)
WebSocket::connect(url): one non-blocking client type for the browser and the desktop
packet / conn / endpoint / seal / reliable: the wire format, the sequence numbers and acks,
the handshake, its keys, the reliable channel -- without I/O, for tests on a
simulated network and for other transports
The same channel over two transports: unreliable and unordered over UDP (a handshake with a
stateless cookie and X25519 keys, every packet after it sealed with ChaCha20-Poly1305,
keep-alives and timeouts; optionally a static server key the client pins), reliable and
ordered over a WebSocket (the browser's only way, docs/GAME.md E8; wss:// encrypts it). Both carry the same header: a
sequence number per packet and acks of the newest 33 received, so the netcode (G7e) learns
which packets arrived over either. Beside the packets, a reliable, ordered channel on both
(send_reliable, reliable.rs): messages up to max_message (1 MiB), over UDP in chunks of a
packet, resent until acknowledged, sent at a fixed pace. Limits everywhere: payload sizes,
packets and bytes a second per connection, connections per server and per address, handshake
answers a second, the reliable channel's message size, queue and pace.
Why a crate of its own and not netio: netio is not built for the browser and Android (plat had
no sockets there), and the client side must run in the browser; the WebSocket client type
needs netio on the desktop (names on Linux go through netio::dns) and plat's JS host in the
browser, which only a crate above both can choose per target. Not lib/game either (G7b builds
it at the same time; the transport has no game in it).
netchan crate root#
enum Transportwhich transport a connection runs overUdp-- UDP: unreliable, unorderedWebSocket-- a WebSocket: reliable, ordered
enum Reasonwhy a connection endedLocal-- this side ended itPeer(u8)-- the peer sent DISCONNECT with this code (packet::BYE_*)Timeout-- nothing came for timeout_msConnectTimeout-- the handshake did not finish within connect_msFull-- the server refused: it is full (or the address has max_per_ip connections)Protocol-- the server speaks another protocol idRateLimit-- the peer broke the rate limits (the server ended it)Closed(u16)-- the WebSocket under it closed with this code (1006: without a close frame)Replaced-- the same address made a new handshakeServerKey-- the server did not prove the static key of ClientConfig::server_key: it has none (DENY), or its ACCEPT did not check (another server, or someone on the path in its place)
enum Errorwhy a call failedUnsupported-- not on this target: UDP in the browser; everything on Android for now (plat has no sockets there yet, docs/ANDROID.md)Net(plat::net::NetError)-- the network; NetErrorKind::Denied: the app's permissions (net.connect / net.listen)Url(String)-- not a ws:// or wss:// URL (or "/path" in the browser)Size-- an empty payload, or one over the limit of the connectionBacklog-- more waits to be sent than the WebSocket's queue takes (WsOptions::max_unsent)NotConnected-- not connected (yet, or any more)
netchan/src/client.rs#
Source: lib/netchan/src/client.rs
client -- a game client's channel to its server (G7d)
Client::connect(Endpoint, ClientConfig) -> Result<Client, Error> Connecting at once
client.poll() -> Option<ClientEvent> every frame until None: reads, keep-alives, timeouts
client.send(payload) -> Result<u16, Error> the message's sequence number
client.send_reliable(message) -> Result<(), Error> the reliable channel (ClientEvent::Reliable
on the other side); poll() sends what is due
client.state() / reliable() / max_payload() / stats() / rtt_ms() / disconnect()
Nothing blocks. UDP (Windows, Linux, Apple): a thread of its own reads the socket, keeps only
the server's datagrams (a bounded queue) and wakes the UI (plat::wake); sends go out at once.
WebSocket: netchan::ws (the browser's own, or netio's on threads); a packet of the client's own
that it cannot queue (max_unsent bytes waiting) ends the connection, Disconnected(Closed(1011)).
In the browser only Endpoint::WebSocket exists; on Android nothing yet (Unsupported).
enum Endpointwhere a client connects toUdp(plat::net::SocketAddr)-- a server's UDP socket (not in the browser)WebSocket(String)-- a server's WebSocket: ws://host:port/path, wss://..., in the browser also "/path"
struct Clienta client's channel (see the top of this file)
impl Client
fn connect(ep: Endpoint, cfg: ClientConfig) -> Result<Client, Error>connect: the handshake starts at once (UDP) or once the WebSocket is open; poll() reports Connected or Disconnected(reason)fn poll(&mut self) -> Option<ClientEvent>the next event; call it until None every frame (it reads, sends keep-alives, notices timeouts)fn send(&mut self, payload: &[u8]) -> Result<u16, Error>send a message -> its sequence number (Delivered / Lost name it later; Backlog: the WebSocket has WsOptions::max_unsent bytes waiting, nothing was sent)fn send_reliable(&mut self, payload: &[u8]) -> Result<(), Error>send a message on the reliable channel: any size up to ClientConfig::max_message, in order, over UDP sent again until the server has it (endpoint::ClientCore::send_reliable). It goes out at reliable_bytes_per_s, the rest with the next pollsfn state(&self) -> Statewhere it standsfn reliable(&self) -> boolwhether the transport is reliable and ordered (a WebSocket)fn max_payload(&self) -> usizethe largest payload the server takes (0 before Connected)fn stats(&self) -> Statsthe connection's countsfn rtt_ms(&self) -> f32the smoothed round-trip time in ms (0 before the first ack)fn disconnect(&mut self)end the connection (DISCONNECT goes out; Disconnected(Local) follows)
netchan/src/conn.rs#
Source: lib/netchan/src/conn.rs
conn -- one connection's sequence numbers and acks, without I/O (docs/TRANSPORT.md "Folgenummern")
Conn::new(token, reliable, Settings, now_us)
conn.write_data(payload, now, &mut out) -> seq a DATA packet (empty payload: keep-alive)
conn.on_data(seq, ack, bits, payload, now) a DATA packet that came (token checked by
the caller)
conn.take_event() -> Message / Delivered / Lost conn.rate_ok(bytes, now), keepalive_due,
timed_out, stats, rtt_ms
Conn::new(..).with_keys(Keys) sealed (UDP): write_data and
write_disconnect seal, open(wire, head,
seq) checks and decrypts what came
conn.send_reliable(message, chunk_max) the reliable channel (reliable.rs):
conn.write_reliable(now, room, &mut out) -> seq RELIABLE packets of the chunks due,
conn.on_reliable(seq, ack, bits, payload, now) what came (Event::Reliable: whole
messages in order); with_reliable(Limits)
Every DATA packet has its own sequence number (u16, wrapping) and acknowledges the newest
number received plus the 32 before it as bits. Unreliable (UDP): packets may come late, twice
or not at all; a number seen before (1024 back) is dropped, older ones too; whatever arrives
new is delivered at once, in the order it came. A sent packet is Delivered when an ack names
it, Lost when the acks have moved more than 32 past it without naming it. Reliable (WebSocket):
the transport keeps order and loses nothing, so an ack of n delivers everything up to n.
A peer that only receives (or sends less than one packet per 32 received) would let packets
pass the bits unacknowledged: after ACK_EVERY packets without one of its own, an unreliable
connection owes an empty DATA packet at once (ack_due). RELIABLE packets are acknowledged
sooner, after two or within ACK_DELAY_US: their sender times its resends by the acks.
The round-trip time comes from the newest ack only (bits name older packets, whose wait would
count twice), smoothed as TCP does (RFC 6298).
Sealed (seal.rs): each packet sent takes the next packet number (u64; its low 16 bits are the
sequence number), the nonce of ChaCha20-Poly1305; open() takes the number nearest the largest
authenticated one and leaves the state alone when the tag does not check (Stats::forged). The
receive window above then drops a replayed packet as a duplicate or stale: only after the tag.
RELIABLE packets take numbers and acks from the same sequence as DATA; their Delivered and
Lost come as events like those of keep-alives, and tell the reliable sender which chunks the
peer has.
/// how far back sequence numbers are remembered (sent and received)
WINDOW: usize = 1024
/// (unreliable) packets received without sending one, after which an ack is due (half the bits)
ACK_EVERY: u32 = 16
/// (unreliable) RELIABLE packets received without sending one, after which an ack is due: the
/// peer waits for it to free its window and to send nothing twice (as TCP's delayed ack)
ACK_EVERY_RELIABLE: u32 = 2
/// (unreliable) the longest a RELIABLE packet waits for its ack (keepalive_due then holds)
ACK_DELAY_US: u64 = 10_000
struct Settingsthe timing and limits of a connectiontimeout_ms: u32-- nothing received for this long ends the connectionkeepalive_ms: u32-- an empty DATA packet goes out when nothing was sent for this long (it carries the acks)packets_per_s: u32-- packets a second from the peer, on average (bursts of two seconds)bytes_per_s: u32-- bytes a second from the peer, on average (bursts of two seconds)
struct Statswhat a connection countedsent: u64-- DATA packets sent (keep-alives included)received: u64-- DATA packets taken in (duplicates and stale ones not counted)delivered: u64-- sent packets an ack namedlost: u64-- sent packets the acks passed byduplicates: u64-- packets that came a second timestale: u64-- packets older than the windowdropped: u64-- packets dropped for the rate limits or their sizeforged: u64-- sealed packets with this connection's token whose tag did not check (forged or damaged; nothing else was done with them)bytes_sent: u64-- bytes of DATA packets sent (headers included)bytes_received: u64-- bytes of DATA packets taken in (headers included)resent: u64-- chunks of the reliable channel sent again (UDP: lost, or no ack within the timeout)reliable_queued: u64-- bytes of reliable messages the peer does not have yetrtt_ms: f32-- the smoothed round-trip time (0 before the first sample)rtt_var_ms: f32-- its variation
enum Eventwhat a connection reportsMessage { seq: u16, data: Vec<u8> }-- a message of the peer with its sequence numberReliable(Vec<u8>)-- a message of the peer's reliable channel, whole and in orderDelivered(u16)-- the peer has a packet this side sentLost(u16)-- the peer's acks passed this packet by
struct Connthe state of one connection (see the top of this file)
impl Conn
fn new(token: u32, reliable: bool, set: Settings, now_us: u64) -> Conna connection with the token both sides put into DATA (0 over a WebSocket)fn with_reliable(mut self, limits: Limits) -> Connthe reliable channel with these limits (instead of Limits::default())fn with_keys(mut self, keys: Keys) -> Connthe connection sealed with these keys (UDP after the handshake): every packet written is encrypted and authenticated, every packet taken in must pass open()fn sealed(&self) -> boolwhether its packets are sealedfn token(&self) -> u32the token of DATA and DISCONNECT packetsfn open(&mut self, wire: &[u8], head: usize, seq: u16) -> Option<Vec<u8>>check and decrypt a packet that came:wirethe whole packet,headthe bytes before its payload (DATA_HEADER, DISCONNECT_HEADER),seqits sequence number -> the payload (unsealed connections: the bytes after the header as they are). None: too short or a wrong tag (counted as forged); the connection's state is not touched thenfn reliable(&self) -> boolwhether the transport is reliable (a WebSocket)fn ack_fields(&self) -> (u16, u32)the newest number received and the bits of the 32 before it (0xffff, 0 before any)fn write_data(&mut self, payload: &[u8], now: u64, out: &mut Vec<u8>) -> u16append a DATA packet withpayload(empty: a keep-alive), sealed if the connection is -> its sequence numberfn write_disconnect(&mut self, reason: u8, out: &mut Vec<u8>)append a DISCONNECT withreason(BYE_*), sealed if the connection is; it takes a sequence number of its own, so its seal never shares a nonce with a DATA packetfn rate_ok(&mut self, bytes: usize, now: u64) -> boolwhether a packet ofbytesfrom the peer stays within the rate limits (false: drop it, or end a reliable connection)fn count_dropped(&mut self)count a packet dropped by the caller (its size)fn send_reliable(&mut self, msg: &[u8], chunk_max: usize) -> Result<(), Error>queue a message on the reliable channel, cut into chunks of at mostchunk_maxbytes (the room of a packet less reliable::CHUNK_HEAD); Size: empty or over Limits::max_message, Backlog: more than Limits::max_queued would waitfn write_reliable(&mut self, now: u64, room: usize, out: &mut Vec<u8>) -> Option<u16>append a RELIABLE packet with the chunks that are due (new ones, and over UDP those whose packet was lost or went unacknowledged past the timeout), at mostroombytes of payload -> its sequence number; None: nothing due now (or the rate of the channel spent)fn reliable_pending(&self) -> boolwhether the reliable channel has chunks the peer does not have yetfn on_data(&mut self, seq: u16, ack: u16, bits: u32, payload: &[u8], now: u64)a DATA packet of the peer (its token already checked)fn on_reliable(&mut self, seq: u16, ack: u16, bits: u32, payload: &[u8], now: u64) -> boola RELIABLE packet of the peer (its token checked, opened) -> false when its chunks break the protocol (malformed, a message over max_message): the caller ends the connectionfn take_event(&mut self) -> Option<Event>the next event (messages, deliveries, losses in the order they happened)fn ack_due(&self) -> bool(unreliable) whether an empty DATA packet is due at once: ACK_EVERY packets came without one of this side's, so the older ones would pass the bits unacknowledged (or ACK_EVERY_RELIABLE RELIABLE packets, whose sender waits for the acks)fn keepalive_due(&self, now: u64) -> boolwhether a keep-alive is due (nothing sent for keepalive_ms; unreliable: or a RELIABLE packet waited ACK_DELAY_US for its ack)fn quiet_for(&self, now: u64) -> u64µs since the last packet of the peer that passed (authentic over UDP)fn timed_out(&self, now: u64) -> boolwhether nothing came for timeout_msfn stats(&self) -> Statswhat the connection countedfn rtt_ms(&self) -> f32the smoothed round-trip time in ms (0 before the first ack)fn next_seq(&self) -> u16the sequence number the next packet gets
netchan/src/endpoint.rs#
Source: lib/netchan/src/endpoint.rs
endpoint -- the server's and the client's protocol without I/O (docs/TRANSPORT.md "Handschlag")
ServerCore::new(ServerConfig, secret)
.datagram(from, bytes, now) a UDP datagram
.stream_open(id, addr, now) / .stream_message(id, bytes, now) / .stream_closed(id, code)
a WebSocket (or any reliable message stream)
.tick(now) keep-alives, timeouts, streams that never said CONNECT
.send(conn, payload, now) -> seq .disconnect(conn, now)
.send_reliable(conn, message, now) the reliable channel: any size up to max_message, in
order, resent until it arrives (reliable.rs)
.take_out() -> Out (what to send where, streams to close) .poll_event() -> ServerEvent
.set_static_key(secret) / .public_key() a long-lived X25519 key clients may pin
ClientCore::new(ClientConfig, random [32], stream)
.start(now) / .packet(bytes, now) / .tick(now) / .send(payload, now) / .disconnect(now)
.send_reliable(message, now)
.transport_closed(code) / .take_out() -> bytes / .poll_event() -> ClientEvent
Time and randomness are the caller's (microseconds; the server's secret, the client's 32 random
bytes), so tests run them on a virtual clock over a simulated network (apps/nettest), the same
on every run. The UDP handshake: CONNECT (padded) -> CHALLENGE with a stateless cookie,
HMAC-SHA256 over the client's address, its nonce and the time -> RESPONSE (padded) with the
cookie and the client's ephemeral X25519 key -> ACCEPT with a random token, the server's
ephemeral key and `confirm`, the proof that it derived the same keys (seal.rs). From then on
every DATA and DISCONNECT is sealed with ChaCha20-Poly1305 under keys of this connection alone:
who listens reads nothing, a changed, forged or replayed packet is dropped. With
ClientConfig::server_key the keys also need the server's static secret, so nobody on the path
can take the server's place; without it they keep out only those who listen. Nothing is kept
for an address before its RESPONSE proves it receives there, the answers before that are
smaller than the requests, and challenges_per_s bounds the work for all of them (an HMAC for a
CHALLENGE; for an ACCEPT two or three X25519, which a lost ACCEPT does not repeat). A WebSocket
sends CONNECT and gets ACCEPT (token 0, no keys); TCP has proved the address, and wss:// is
its encryption.
struct ServerConfiga server's limits and timingprotocol: u32-- the app's protocol id: clients with another one are refused (another game, another version)max_connections: usize-- connections at once (UDP and WebSocket together)max_per_ip: usize-- connections from one IP addressmax_payload: usize-- the largest payload of a UDP message, both ways (at most MAX_UDP_PAYLOAD)max_stream_payload: usize-- the largest payload of a message over a WebSocket, both waystimeout_ms: u32-- nothing received for this long ends a connectionkeepalive_ms: u32-- an empty DATA packet after this long without sending (carries the acks)packets_per_s: u32-- packets a second from one client (UDP: more are dropped; WebSocket: it is disconnected)bytes_per_s: u32-- bytes a second from one client (as packets_per_s)challenges_per_s: u32-- handshakes a second whose keys the server works out (two or three X25519 each), for all addresses together; one address prefix (IPv4 /24, IPv6 /48) gets a sixteenth of it. Counted after the cookie checked, so a forged sender costs nothing of it; CONNECTs are answered without it (a HMAC, and less goes back than came: a flood of them throttled new players)handshake_ms: u32-- a WebSocket must send its CONNECT within this longmax_message: usize-- the largest message of the reliable channel, both ways (a client's larger one ends its connection)max_reliable_queued: usize-- bytes of reliable messages queued for one client before send_reliable says Backlogreliable_bytes_per_s: u32-- bytes a second of reliable chunks to one client (below what its bytes_per_s takes)
enum Routewhere a packet goesUdp(SocketAddr)-- a UDP datagram to this addressStream(u32)-- a message on this stream (WebSocket)
enum Outwhat a core wants doneSend(Route, Vec<u8>)-- send these bytesClose(u32)-- close this stream (after what was sent on it)
enum ServerEventwhat happened on the serverConnected { id: u32, transport: Transport, addr: Option<SocketAddr> }-- a client came (addr: its address, if the transport knows it)Message { id: u32, seq: u16, data: Vec<u8> }-- a message of a clientReliable { id: u32, data: Vec<u8> }-- a message of a client's reliable channel, whole and in orderDelivered { id: u32, seq: u16 }-- a client has a packet the server sentLost { id: u32, seq: u16 }-- a packet the server sent did not reach the client (UDP)Disconnected { id: u32, reason: Reason }-- a client is gone
struct ServerStatswhat the server counted beyond its connectionschallenges: u64-- CHALLENGE answers sentaccepted: u64-- connections takendenied: u64-- clients refused (full, protocol, address)bad: u64-- packets that were no packet, a wrong kind, a wrong cookie or token, or a handshake with a key that gives no shared secret (forged DATA of a connection: its Stats::forged)throttled: u64-- handshakes over challenges_per_s, left without an answerkept: u64-- RESPONSEs with another nonce or key from an address whose connection is still alive, left without an answer (a client that starts again gets in once its old connection was quiet for a second; someone on the path who saw a CHALLENGE ended the connection before)unknown: u64-- DATA from addresses without a connection
struct ServerCorethe server's protocol (see the top of this file)
impl ServerCore
fn new(cfg: ServerConfig, secret: [u8; 32], now: u64) -> ServerCorea server with these limits;secretkeys the cookies and tokens and seeds the ephemeral keys of the handshakes (random in a real server, fixed in tests)fn config(&self) -> &ServerConfigthe limits in force (max_payload clamped)fn set_static_key(&mut self, secret: [u8; 32])a long-lived X25519 secret: clients that know its public key (ClientConfig::server_key) include it in their keys, so only this server can answer them. Kept by the app (32 random bytes, made once); clients without the key still connect with ephemeral keys onlyfn public_key(&self) -> Option<[u8; 32]>the public key of set_static_key (for the clients' ClientConfig::server_key)fn datagram(&mut self, from: SocketAddr, data: &[u8], now: u64)a UDP datagram fromfromfn stream_open(&mut self, stream: u32, addr: Option<SocketAddr>, now: u64)a stream (WebSocket) opened; it must send CONNECT within handshake_msfn stream_message(&mut self, stream: u32, data: &[u8], now: u64)a message on a streamfn stream_closed(&mut self, stream: u32, code: u16)a stream ended (code: its close code, 1006 without one)fn tick(&mut self, now: u64)keep-alives, timeouts, streams without a CONNECTfn send(&mut self, id: u32, payload: &[u8], now: u64) -> Result<u16, Error>send a message to a client -> its sequence number (Size: empty or over the limit of its transport, or over the client's smaller one (max_payload); NotConnected: no such client)fn send_reliable(&mut self, id: u32, payload: &[u8], now: u64) -> Result<(), Error>send a message on a client's reliable channel: any size up to max_message, cut into chunks of a packet each, in order, over UDP sent again until the client has it; it goes out at reliable_bytes_per_s, so a large one takes a while (Size: empty or over max_message; Backlog: more than max_reliable_queued would wait; NotConnected)fn disconnect(&mut self, id: u32, reason: u8)end a client's connection (DISCONNECT goes out, Disconnected(Local) follows)fn disconnect_all(&mut self)end every connection (the server stops)fn take_out(&mut self) -> Option<Out>the next thing to send or closefn poll_event(&mut self) -> Option<ServerEvent>the next eventfn connections(&self) -> usizeconnections nowfn ids(&self) -> Vec<u32>the ids of the connectionsfn stats(&self, id: u32) -> Option<Stats>a connection's counts and round-trip timefn max_payload(&self, id: u32) -> Option<usize>the largest payload the server sends a connection (its limit, the client's if smaller)fn peer(&self, id: u32) -> Option<(Transport, Option<SocketAddr>)>a connection's transport and addressfn route(&self, id: u32) -> Option<Route>where a connection's packets gofn server_stats(&self) -> ServerStatswhat the server counted beyond its connectionsstruct ClientConfiga client's limits and timingprotocol: u32-- the app's protocol id (the server's must be the same)max_payload: usize-- the largest payload this side takes from the server (UDP at most MAX_UDP_PAYLOAD); the handshake tells the server, which sends no moretimeout_ms: u32-- nothing received for this long ends the connectionkeepalive_ms: u32-- an empty DATA packet after this long without sendingconnect_ms: u32-- the handshake within this longresend_ms: u32-- UDP: CONNECT / RESPONSE again after this long without an answerpackets_per_s: u32-- packets a second from the server, on average (more are dropped)bytes_per_s: u32-- bytes a second from the server, on average (more are dropped)server_key: Option<[u8; 32]>-- UDP: the server's static public key (ServerCore::set_static_key, Server::set_static_key). Given, the keys need the server's secret, and a server without it is refused (Reason::ServerKey); None: ephemeral keys only, safe from listeners but not from someone on the path who answers in the server's placemax_message: usize-- the largest message of the reliable channel, both ways (the server's larger one ends the connection)max_reliable_queued: usize-- bytes of reliable messages queued before send_reliable says Backlogreliable_bytes_per_s: u32-- bytes a second of reliable chunks to the server (below its bytes_per_s)
enum Statewhere a client standsConnecting-- the handshake is on its wayConnected-- the server took the connectionDisconnected(Reason)-- ended, and why
enum ClientEventwhat happened on the clientConnected-- the server took the connectionMessage { seq: u16, data: Vec<u8> }-- a message of the serverReliable(Vec<u8>)-- a message of the server's reliable channel, whole and in orderDelivered(u16)-- the server has a packet this side sentLost(u16)-- a packet this side sent did not reach the server (UDP)Disconnected(Reason)-- the connection ended
struct ClientCorethe client's protocol (see the top of this file)
impl ClientCore
fn new(cfg: ClientConfig, random: [u8; 32], stream: bool) -> ClientCorea client;random: 32 random bytes of this attempt (its nonce and, over UDP, its ephemeral key come from them: plat::random_bytes in a real client, fixed in tests);stream: over a WebSocketfn start(&mut self, now: u64)begin the handshake (CONNECT goes out)fn packet(&mut self, data: &[u8], now: u64)a packet from the server (the caller checked that it came from the server)fn tick(&mut self, now: u64)resends of the handshake, keep-alives, timeoutsfn send(&mut self, payload: &[u8], now: u64) -> Result<u16, Error>send a message -> its sequence number (Size: empty or over the server's limit; NotConnected before Connected and after the end)fn send_reliable(&mut self, payload: &[u8], now: u64) -> Result<(), Error>send a message on the reliable channel: any size up to max_message, cut into chunks of a packet each, in order, over UDP sent again until the server has it; it goes out at reliable_bytes_per_s (Size: empty or over max_message; Backlog: more than max_reliable_queued would wait; NotConnected before Connected and after the end)fn disconnect(&mut self)end the connection (DISCONNECT goes out; UDP several times)fn transport_closed(&mut self, code: u16)the transport under a stream ended (the WebSocket closed withcode)fn take_out(&mut self) -> Option<Vec<u8>>the next packet to send to the serverfn poll_event(&mut self) -> Option<ClientEvent>the next eventfn state(&self) -> Statewhere it standsfn max_payload(&self) -> usizethe largest payload the server takes (0 before Connected)fn reliable(&self) -> boolwhether the transport is reliable (a WebSocket)fn stats(&self) -> Statsthe connection's counts (zeros before Connected)
netchan/src/packet.rs#
Source: lib/netchan/src/packet.rs
packet -- the channel's wire format, version 2 (docs/TRANSPORT.md "Paketformat")
byte 0: VERSION << 4 | kind; then, little-endian:
CONNECT client -> server protocol u32, nonce u64, 17 bytes (UDP: padded to 96)
max payload u32
CHALLENGE server -> client nonce u64, time u32, mac [16] 29 bytes (UDP only)
RESPONSE client -> server protocol u32, nonce u64, time u32, 70 bytes (UDP only, padded
mac [16], flags u8, key [32], to 96)
max payload u32
ACCEPT server -> client nonce u64, token u32, max payload 63 bytes
u16, key [32], confirm [16]
DENY server -> client nonce u64, reason u8 10 bytes
DATA both token u32, seq u16, ack u16, ack bits u32, payload
13 + n (UDP: + 16)
RELIABLE both as DATA; the payload: chunk records of the reliable channel
(reliable.rs: id u16, flags u8, len u16, bytes)
DISCONNECT both token u32, seq u16, reason u8 8 bytes (UDP: + 16)
Over UDP the handshake agrees on keys (RESPONSE: the client's ephemeral X25519 key; ACCEPT: the
server's and `confirm`, the proof that the server derived the same keys; seal.rs), and every
DATA and DISCONNECT after it is sealed with ChaCha20-Poly1305: the payload is encrypted, the
header before it is authenticated with it, and the 16-byte tag follows (DATA's payload as
parse() returns it is the ciphertext and the tag). RELIABLE is sealed as DATA and shares its
sequence numbers and acks; DATA itself stays as it was, so a channel that sends nothing
reliably writes the same bytes as before. A UDP client pads CONNECT and RESPONSE to
HANDSHAKE_SIZE, and every answer of the server before a connection is smaller: a forged sender
address gets back less than was sent (no amplification). Over a WebSocket the CONNECT is not
padded, CHALLENGE / RESPONSE do not occur (TCP has proved the address), ACCEPT's key and
confirm are zeros and nothing is sealed (wss:// is the encryption there). parse() reads
untrusted bytes: exact sizes, no panics, no allocation.
The client's max payload (the largest payload it takes from the server) came with the third
review: a server sent up to its own limit, and a client with a smaller one dropped what came, so
reliable chunks went again for ever (a WebSocket closed with 1009). It sits after the fields of
before, where a client of before has its padding (zeros) or nothing: 0 there means "not given",
and the server sends up to its own limit as before.
/// the format's version (the high nibble of byte 0)
VERSION: u8 = 2
/// a client asks for a connection
KIND_CONNECT: u8 = 1
/// the server's stateless cookie for a UDP client
KIND_CHALLENGE: u8 = 2
/// the client returns the cookie with its key
KIND_RESPONSE: u8 = 3
/// the server took the client
KIND_ACCEPT: u8 = 4
/// the server refused the client
KIND_DENY: u8 = 5
/// a message (or an empty keep-alive) with sequence number and acks
KIND_DATA: u8 = 6
/// one side ends the connection
KIND_DISCONNECT: u8 = 7
/// chunks of the reliable channel, with sequence number and acks as DATA
KIND_RELIABLE: u8 = 8
/// the bytes of a DATA packet before its payload
DATA_HEADER: usize = 13
/// the bytes of a DISCONNECT packet before its tag
DISCONNECT_HEADER: usize = 8
/// the tag after a sealed DATA or DISCONNECT (UDP)
TAG: usize = 16
/// the size a UDP client pads CONNECT and RESPONSE to (at most the server takes)
HANDSHAKE_SIZE: usize = 96
/// the largest payload of a UDP DATA packet that may be configured (1400 + 13 + 16 + 8 + 40
/// bytes stay below the 1500 of Ethernet also over IPv6)
MAX_UDP_PAYLOAD: usize = 1400
fn max_datagram(max_payload: usize) -> usizethe largest UDP datagram of a side whose payloads are at mostmax_payload(DATA with its tag, at least a padded handshake): the reading threads drop larger ones before they queue them
/// RESPONSE flags: the client knows the server's static key (ClientConfig::server_key), and the
/// keys include a Diffie-Hellman with it
FLAG_STATIC_KEY: u8 = 1
/// DENY: the server has max_connections clients
DENY_FULL: u8 = 1
/// DENY: the client speaks another protocol id (another game or version)
DENY_PROTOCOL: u8 = 2
/// DENY: the client's address has max_per_ip connections
DENY_ADDRESS: u8 = 3
/// DENY: the client expects a static key, and the server has none
DENY_KEY: u8 = 4
/// DISCONNECT: an orderly end
BYE_NORMAL: u8 = 0
/// DISCONNECT: nothing came for timeout_ms
BYE_TIMEOUT: u8 = 1
/// DISCONNECT: the peer broke the rate limits
BYE_RATE: u8 = 2
/// DISCONNECT: the peer sent something malformed
BYE_PROTOCOL: u8 = 3
/// DISCONNECT: the same address connected again
BYE_REPLACED: u8 = 4
/// DISCONNECT: the server stops
BYE_SHUTDOWN: u8 = 5
enum Packet<'a>one packet, borrowed from the bytes it was read fromConnect { protocol: u32, nonce: u64, max_payload: u32 }-- a client asks: the app's protocol id, the nonce of this attempt, the largest payload it takes (0: not given)Challenge { nonce: u64, time: u32, mac: [u8; 16] }-- the server's cookie for a UDP client: the time (seconds) and the MAC over address, nonce, timeResponse { protocol: u32, nonce: u64, time: u32, mac: [u8; 16], flags: u8, key: [u8; 32], max_payload: u32 }-- the client returns the cookie with FLAG_*, its ephemeral X25519 public key and the largest payload it takes (0: not given)Accept { nonce: u64, token: u32, max_payload: u16, key: [u8; 32], confirm: [u8; 16] }-- the server took the client: the token of its packets, the largest payload it takes, its ephemeral X25519 public key and the proof of the keys (over a WebSocket: zeros)Deny { nonce: u64, reason: u8 }-- the server refused the client (DENY_*)Data { token: u32, seq: u16, ack: u16, bits: u32, payload: &'a [u8] }-- a message (empty: a keep-alive) with its number, the newest number received and the bits of the 32 before; over UDPpayloadis the ciphertext and its tagReliable { token: u32, seq: u16, ack: u16, bits: u32, payload: &'a [u8] }-- chunks of the reliable channel (reliable.rs), numbered and acknowledged as DATA; over UDPpayloadis the ciphertext and its tagDisconnect { token: u32, seq: u16, reason: u8, tag: &'a [u8] }-- one side ends the connection (BYE_*) under the sequence number it took; over UDPtagholds the 16 bytes of the seal, over a WebSocket nothing
fn parse(b: &[u8]) -> Option<Packet<'_>>read one packet: None for anything that is not exactly a packet of this version (handshake packets between their size and HANDSHAKE_SIZE, the fixed-size ones exactly, DISCONNECT with or without its tag)
impl Packet<'_>
fn write(&self, out: &mut Vec<u8>, pad: bool)append the packet toout;pad: CONNECT and RESPONSE filled with zeros to HANDSHAKE_SIZE. DATA and DISCONNECT are written as given (Conn seals them)fn to_vec(&self, pad: bool) -> Vec<u8>the packet as new bytesfn seq_newer(a: u16, b: u16) -> boolwhether sequence numberais newer thanb(wrapping: within half the range ahead)
netchan/src/reliable.rs#
Source: lib/netchan/src/reliable.rs
reliable -- the reliable, ordered channel beside the packets (docs/TRANSPORT.md "Zuverlässige
Nachrichten"), without I/O
Sender::push(message, chunk_max) -> Size / Backlog a message cut into chunks
Sender::fill(now, rto, resend, room, bucket, out) -> ids the chunks a RELIABLE packet carries
Sender::sent(seq, ids) / delivered(seq) / lost(seq) the fate of the packets that carried them
Receiver::take(payload) -> Err(protocol) / Ok the chunks of a packet that came
Receiver::message() -> Option<Vec<u8>> the next whole message, in order
A message is cut into chunks of at most `chunk_max` bytes, each with a number of its own (u16,
wrapping) and a flag "more chunks of this message follow". A RELIABLE packet carries one or
more chunk records: id u16 | flags u8 (1: more) | len u16 | len bytes. The packet is
acknowledged as every packet (conn.rs); a chunk is done when a packet that carried it is
Delivered. Over UDP a chunk goes again when a packet that carried it is Lost, or when no ack
came within the retransmission timeout (the round-trip time, four times its variation and the
peer's ack delay, doubled for every retry up to a second); over a WebSocket never, since the transport loses
nothing. The receiver keeps the chunks that came early and hands out whole messages in the
order they were sent.
Limits: at most WINDOW chunks after the oldest open one are in flight (the receiver drops what
lies further ahead, which a sender that keeps the window never sends); the sender's queue holds
at most `max_queued` bytes (push: Backlog); a message has at most `max_message` bytes on both
sides (the receiver ends the connection on more), the chunks kept before their turn at most
EARLY_MAX bytes (more: the connection ends too); the bytes a second of reliable chunks come
from a token bucket (`reliable_bytes_per_s` of the configs), so a large message does not run
into the peer's rate limits.
/// chunks in flight after the oldest open one
WINDOW: u16 = 256
/// the bytes of a chunk record before its data
CHUNK_HEAD: usize = 5
/// the bytes of chunks a receiver keeps before their turn (a sender within the window over UDP
/// has at most WINDOW * MAX_UDP_PAYLOAD in flight; over a WebSocket chunks come in order)
EARLY_MAX: usize = 512 * 1024
struct Limitsthe limits of the reliable channel of a connectionmax_message: usize-- the largest message, sent or takenmax_queued: usize-- bytes this side keeps queued until the peer has them (push: Backlog beyond)bytes_per_s: u32-- bytes a second of reliable chunks this side sends
fn rto_us(srtt_us: f64, rttvar_us: f64) -> u64the retransmission timeout from the smoothed round-trip time and its variation (µs): as QUIC's probe timeout, the round trip, four times the variation (at least 10 ms) and the longest the peer may hold an ack back (conn::ACK_DELAY_US)struct Senderwhat a connection sends reliablyresent: u64-- chunks sent again
impl Sender
fn new(limits: Limits, now: u64) -> Senderfn push(&mut self, msg: &[u8], chunk_max: usize) -> Result<(), Error>queue a message, cut into chunks of at mostchunk_maxbytes (Size: empty or over max_message; Backlog: more than max_queued would wait)fn queued(&self) -> usizebytes queued that the peer does not have yetfn pending(&self) -> boolwhether a chunk is waiting to go out (now or after a timeout)fn fill(&mut self, now: u64, rto: u64, resend: bool, room: usize, out: &mut Vec<u8>) -> Vec<u16>append the records of the chunks that are due toout, at mostroombytes of them -> their ids (empty: nothing due, or the bucket is empty).resend: chunks whose packet went unacknowledged forrtoµs go again (UDP; a WebSocket loses nothing)fn sent(&mut self, seq: u16, ids: Vec<u16>)the packetseqcarried these chunksfn delivered(&mut self, seq: u16)the peer has packetseq: its chunks are donefn lost(&mut self, seq: u16)packetseqdid not reach the peer: its chunks are due again (UDP)struct Receiverwhat a connection takes in reliably
impl Receiver
fn new(max_message: usize) -> Receiverfn take(&mut self, mut b: &[u8]) -> Result<(), ()>the chunk records of a RELIABLE packet that came (authentic, not a duplicate) -> Err when they are malformed or a message grows past max_message (the peer breaks the protocol)fn message(&mut self) -> Option<Vec<u8>>the next whole message, in the order they were sent
netchan/src/seal.rs#
Source: lib/netchan/src/seal.rs
seal -- the keys of the UDP handshake and the sealing of its packets (docs/TRANSPORT.md
"Verschlüsselung")
derive(&Handshake, &dh1, dh2) -> Derived { c2s, s2c, confirm } the keys of a connection
confirm_tag(&confirm, accept_bytes) -> [u8; 16] ACCEPT's proof of the keys
Keys::new(send, recv) one side's keys (Conn::with_keys)
full_pn(largest, seq) -> u64 the packet number a 16-bit sequence number stands for
nonce(pn) -> [u8; 12] ChaCha20-Poly1305's nonce of a packet number
Generator::new(seed) / next_secret() -> [u8; 32] the server's ephemeral secrets (forward secure)
Both sides have an ephemeral X25519 key per connection; the client may also know the server's
static key (ClientConfig::server_key), as in Noise's NK pattern. The transcript hash h is
SHA-256 over a label, the protocol id, the nonce, the flags and the public keys (the client's,
the server's ephemeral one, the static one if used); the keys are HKDF-SHA256 with salt h over
dh1 (ephemeral with ephemeral) and dh2 (the client's ephemeral with the static key): 32 bytes
client to server, 32 bytes server to client, 32 bytes for `confirm`. Without a static key the
channel is safe from those who only listen and from blind senders, not from someone on the path
who answers the handshake in the server's place; with it, only the holder of the static secret
can make an ACCEPT whose confirm checks.
Every sealed packet takes the next packet number of its direction (u64, from 0), and its 16-bit
sequence number is that number's low bits. The receiver takes the number closest to the one
after the largest it authenticated (as QUIC does with its truncated numbers, RFC 9000 A.3), so
the nonce never repeats under one key and a replay of an old packet fails its tag or is found
by the receive window of conn.rs.
struct Keysone side's keys of a connection; zeroed when dropped
impl Keys
fn new(send: [u8; 32], recv: [u8; 32]) -> Keysthe key this side seals with and the one it opens withstruct Handshake<'a>what the transcript hash covers: the handshake as both sides saw itprotocol: u32nonce: u64client: &'a [u8; 32]-- the client's ephemeral public key (RESPONSE)server: &'a [u8; 32]-- the server's ephemeral public key (ACCEPT)stat: Option<&'a [u8; 32]>-- the server's static public key, when the client uses it (FLAG_STATIC_KEY)
struct Derivedthe keys of one connection; zeroed when droppedc2s: [u8; 32]-- client to servers2c: [u8; 32]-- server to clientconfirm: [u8; 32]-- the key of ACCEPT's confirm
fn derive(hs: &Handshake<'_>, dh1: &[u8; 32], dh2: Option<&[u8; 32]>) -> Derivedthe keys of a connection:dh1= X25519(ephemeral, ephemeral),dh2= X25519(the client's ephemeral, the static key) when hs.stat is set (both must be given together)fn confirm_tag(key: &[u8; 32], accept: &[u8]) -> [u8; 16]ACCEPT's confirm: the first 16 bytes of HMAC-SHA256 under the confirm key over the ACCEPT before it (kind, nonce, token, max payload, the server's key)fn nonce(pn: u64) -> [u8; 12]the nonce of packet numberpn(the keys differ per direction, so both may count from 0)fn full_pn(largest: Option<u64>, seq: u16) -> u64the packet number that sequence numberseqstands for: the one closest to the number afterlargest, the largest authenticated so far (None: nothing yet, so the next is 0)struct Generatora forward-secure source of the server's ephemeral secrets: each one comes from the state, which is replaced by a hash of itself, so what leaks later does not give the earlier ones. Seeded once with 32 random bytes (fixed in tests: the same keys on every run)
impl Generator
fn new(seed: &[u8; 32]) -> Generatora generator from 32 secret bytesfn next_secret(&mut self) -> [u8; 32]the next 32 secret bytes
netchan/src/server.rs#
Source: lib/netchan/src/server.rs
server -- a game server's channels (G7d): UDP and WebSocket clients in one table
Server::new(ServerConfig) -> Server
server.bind_udp(&addr) -> NetResult<SocketAddr> a UDP socket with its reading thread
server.listen_ws(&addr, "/game") -> NetResult<SocketAddr> a netio HTTP server for the
WebSockets (404 elsewhere); or server.ws_endpoint() and
endpoint.accept(&req) in the app's own handler (with
its page's files beside it, say)
server.poll() -> Option<ServerEvent> send(id, payload) -> seq disconnect(id)
server.send_reliable(id, message) the reliable channel (ClientEvent::Reliable at the client)
server.wait(ms) sleep until something arrives (a loop without a tick)
connections() / ids() / stats(id) / peer(id) / server_stats() / stop()
set_static_key(secret) / public_key() the key clients may pin (ClientConfig::server_key)
Threads: one reads the UDP socket; each WebSocket has a reading one (netio's thread of the
upgrade) and a writing one, so neither a full socket buffer nor a slow client holds the
game's loop. What they read goes into one bounded queue (UDP drops when it is full, a
WebSocket waits); poll() takes it on the caller's thread, where the protocol runs
(endpoint::ServerCore). send to a WebSocket client with LINK_UNSENT bytes waiting fails with
Error::Backlog; one that still does not take what the server's own packets add is closed.
/// bytes a WebSocket client may have waiting to be written; more close it
LINK_UNSENT: usize = 1 << 20
struct WsEndpoint(Arc<Shared>)what an HTTP handler needs to hand WebSockets to a Server (clone it into the handler)
impl WsEndpoint
fn accept(&self, req: &Request) -> Responseanswer an upgrade request on the game's path: 101 and the client joins the server's table once it sent CONNECT, or the Acceptor's 4xx / 503fn connections(&self) -> usizeWebSockets open now (also those that have not sent CONNECT yet)struct Servera game server's channels (see the top of this file). Dropping it stops it
impl Server
fn new(cfg: ServerConfig) -> Servera server with these limits and no transport yet (bind_udp, listen_ws, ws_endpoint)fn bind_udp(&mut self, addr: &SocketAddr) -> NetResult<SocketAddr>listen for UDP clients onaddr(port 0: a free one) -> the address it gotfn ws_endpoint(&self) -> WsEndpointthe handle an HTTP handler hands WebSockets in withfn listen_ws(&mut self, addr: &SocketAddr, path: &str) -> NetResult<SocketAddr>a netio HTTP server onaddrwhosepathtakes the WebSockets (404 elsewhere) -> its addressfn udp_addr(&self) -> Option<SocketAddr>the UDP socket's addressfn ws_addr(&self) -> Option<SocketAddr>the address of listen_ws's HTTP serverfn wait(&mut self, ms: u32)sleep until a datagram or a WebSocket message arrives, at mostms(a server without a tick of its own; keepmsbelow keepalive_ms). poll() then reports itfn poll(&mut self) -> Option<ServerEvent>the next event; call it until None every tick (it takes what came, sends keep-alives, ends connections that timed out)fn send(&mut self, id: u32, payload: &[u8]) -> Result<u16, Error>send a message to a client -> its sequence number (Backlog: a WebSocket client has LINK_UNSENT bytes waiting)fn send_reliable(&mut self, id: u32, payload: &[u8]) -> Result<(), Error>send a message on a client's reliable channel: any size up to ServerConfig::max_message, in order, over UDP sent again until the client has it (endpoint::ServerCore::send_reliable). It goes out at reliable_bytes_per_s, the rest with the next pollsfn disconnect(&mut self, id: u32)end a client's connection (Disconnected(Local) follows)fn set_static_key(&mut self, secret: [u8; 32])a long-lived X25519 secret (32 random bytes the app made once and keeps): clients with its public key in ClientConfig::server_key can tell this server from anyone in its place (endpoint::ServerCore::set_static_key)fn public_key(&self) -> Option<[u8; 32]>the public key of set_static_key, for the clientsfn connections(&self) -> usizeconnections nowfn ids(&self) -> Vec<u32>the ids of the connectionsfn stats(&self, id: u32) -> Option<Stats>a connection's counts and round-trip timefn peer(&self, id: u32) -> Option<(Transport, Option<SocketAddr>)>a connection's transport and addressfn server_stats(&self) -> ServerStatswhat the server counted beyond its connectionsfn stop(self)end every connection, stop the threads and the HTTP server
netchan/src/ws.rs#
Source: lib/netchan/src/ws.rs
ws -- one WebSocket client type for every target, which never blocks (G7d)
WebSocket::connect(url) / connect_with(url, WsOptions) -> Result<WebSocket, Error>
ws://host:port/path, wss://... (the browser; on the desktop wss:// is part 2), and in
the browser "/path" for the page's own server
ws.state() -> WsState send_text / send_binary (queued) recv() -> Option<WsMessage>
ws.close(code, reason) / close_info()
The browser: plat::net::WebSocket (the page's, through the JS host). Windows, Linux, Apple:
netio::ws::connect on a thread of its own, which then reads; a second thread writes what send
queues, so no call waits for the network. Both wake the UI (plat::wake) when a message comes.
Android: Unsupported for now. net.connect is checked on the URL's host and port before
anything else (Error::Net with NetErrorKind::Denied).
enum WsStatewhere a WebSocket standsConnecting-- connecting (TCP, TLS, the upgrade)Open-- connected: messages go both waysClosing-- close() was called; the end has not come yetClosed-- ended: close_info() says how
enum WsMessagea whole messageText(String)-- a text messageBinary(Vec<u8>)-- a binary message
struct WsOptionsa WebSocket's limitsmax_message: usize-- the largest message received; bigger ones close the connection (1009)max_queued: usize-- bytes received and not taken by recv; more close the connection (1009)max_unsent: usize-- (desktop) bytes queued by send and not written yet; send fails with Error::Backlog beyondconnect_ms: u32-- (desktop) the connection and the upgrade within this longidle_ms: u32-- (desktop) nothing received for this long ends the connectionping_ms: u32-- (desktop) a ping after this long without anything received (0: none)
struct WebSocketa WebSocket client that never blocks (see the top of this file); dropping it closes it
impl WebSocket
fn connect(url: &str) -> Result<WebSocket, Error>connect with the default limitsfn connect_with(url: &str, o: WsOptions) -> Result<WebSocket, Error>connect with these limits: Connecting at once, Open once the upgrade is donefn state(&self) -> WsStatewhere it standsfn send_text(&self, s: &str) -> Result<(), Error>send a text message (Open only; desktop: queued, Backlog beyond max_unsent)fn send_binary(&self, b: &[u8]) -> Result<(), Error>send a binary message (as send_text)fn recv(&self) -> Option<WsMessage>the next message, or None (never waits)fn close(&self, code: u16, reason: &str)close withcode(1000, 3000-4999) and a reason (at most 123 bytes)fn close_info(&self) -> Option<(u16, String)>how it ended (code and reason; 1006: without a close frame or never connected); None while it is not Closedfn unsent(&self) -> usize(desktop) bytes queued by send and not written yet (the browser buffers on its own: 0)