netchan/lib.rs
1// netchan -- message channels for games (G7d, docs/TRANSPORT.md)
2//
3// Client::connect(Endpoint::Udp(addr) | Endpoint::WebSocket(url), ClientConfig)
4// poll() -> ClientEvent (Connected, Message { seq, data }, Reliable(data),
5// Delivered(seq), Lost(seq), Disconnected(reason)), send(payload) -> seq,
6// send_reliable(message), state, reliable, max_payload, stats
7// Server::new(ServerConfig) [.bind_udp(addr)] [.listen_ws(addr, path) | .ws_endpoint()]
8// poll() -> ServerEvent, send(id, payload) -> seq, send_reliable(id, message),
9// disconnect(id), stats(id)
10// (Windows, Linux, Apple: it needs netio's HTTP server)
11// WebSocket::connect(url): one non-blocking client type for the browser and the desktop
12// packet / conn / endpoint / seal / reliable: the wire format, the sequence numbers and acks,
13// the handshake, its keys, the reliable channel -- without I/O, for tests on a
14// simulated network and for other transports
15//
16// The same channel over two transports: unreliable and unordered over UDP (a handshake with a
17// stateless cookie and X25519 keys, every packet after it sealed with ChaCha20-Poly1305,
18// keep-alives and timeouts; optionally a static server key the client pins), reliable and
19// ordered over a WebSocket (the browser's only way, docs/GAME.md E8; wss:// encrypts it). Both carry the same header: a
20// sequence number per packet and acks of the newest 33 received, so the netcode (G7e) learns
21// which packets arrived over either. Beside the packets, a reliable, ordered channel on both
22// (send_reliable, reliable.rs): messages up to max_message (1 MiB), over UDP in chunks of a
23// packet, resent until acknowledged, sent at a fixed pace. Limits everywhere: payload sizes,
24// packets and bytes a second per connection, connections per server and per address, handshake
25// answers a second, the reliable channel's message size, queue and pace.
26//
27// Why a crate of its own and not netio: netio is not built for the browser and Android (plat had
28// no sockets there), and the client side must run in the browser; the WebSocket client type
29// needs netio on the desktop (names on Linux go through netio::dns) and plat's JS host in the
30// browser, which only a crate above both can choose per target. Not lib/game either (G7b builds
31// it at the same time; the transport has no game in it).
32#![no_std]
33#![forbid(unsafe_code)]
34
35extern crate alloc;
36
37use alloc::string::String;
38
39/// a game client's channel to its server (UDP or WebSocket, never blocking)
40pub mod client;
41/// one connection's sequence numbers, acks, keep-alives and round-trip time, without I/O
42pub mod conn;
43/// the server's and the client's protocol without I/O (the caller's clock)
44pub mod endpoint;
45/// the wire format
46pub mod packet;
47/// the reliable, ordered channel beside the packets: chunks, their resends, the reassembly
48pub mod reliable;
49/// the handshake's keys and the sealing of UDP packets
50pub mod seal;
51#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
52mod reap;
53#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
54/// a game server's channels: UDP and WebSocket clients in one table
55pub mod server;
56/// one WebSocket client type for every target
57pub mod ws;
58
59pub use client::{Client, Endpoint};
60pub use conn::Stats;
61pub use endpoint::{ClientConfig, ClientEvent, ServerConfig, ServerEvent, State};
62#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
63pub use server::{Server, WsEndpoint};
64pub use ws::{WebSocket, WsMessage, WsOptions, WsState};
65
66/// which transport a connection runs over
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub enum Transport {
69 /// UDP: unreliable, unordered
70 Udp,
71 /// a WebSocket: reliable, ordered
72 WebSocket,
73}
74
75/// why a connection ended
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub enum Reason {
78 /// this side ended it
79 Local,
80 /// the peer sent DISCONNECT with this code (packet::BYE_*)
81 Peer(u8),
82 /// nothing came for timeout_ms
83 Timeout,
84 /// the handshake did not finish within connect_ms
85 ConnectTimeout,
86 /// the server refused: it is full (or the address has max_per_ip connections)
87 Full,
88 /// the server speaks another protocol id
89 Protocol,
90 /// the peer broke the rate limits (the server ended it)
91 RateLimit,
92 /// the WebSocket under it closed with this code (1006: without a close frame)
93 Closed(u16),
94 /// the same address made a new handshake
95 Replaced,
96 /// the server did not prove the static key of ClientConfig::server_key: it has none (DENY),
97 /// or its ACCEPT did not check (another server, or someone on the path in its place)
98 ServerKey,
99}
100
101/// why a call failed
102#[derive(Clone, Debug, PartialEq, Eq)]
103#[non_exhaustive]
104pub enum Error {
105 /// not on this target: UDP in the browser; everything on Android for now (plat has no sockets
106 /// there yet, docs/ANDROID.md)
107 Unsupported,
108 /// the network; NetErrorKind::Denied: the app's permissions (net.connect / net.listen)
109 Net(plat::net::NetError),
110 /// not a ws:// or wss:// URL (or "/path" in the browser)
111 Url(String),
112 /// an empty payload, or one over the limit of the connection
113 Size,
114 /// more waits to be sent than the WebSocket's queue takes (WsOptions::max_unsent)
115 Backlog,
116 /// not connected (yet, or any more)
117 NotConnected,
118}
119
120impl core::fmt::Display for Error {
121 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
122 match self {
123 Error::Unsupported => f.write_str("not supported on this target"),
124 Error::Net(e) => write!(f, "{}", e),
125 Error::Url(u) => write!(f, "not a WebSocket URL: {}", u),
126 Error::Size => f.write_str("payload empty or too large"),
127 Error::Backlog => f.write_str("too much waits to be sent"),
128 Error::NotConnected => f.write_str("not connected"),
129 }
130 }
131}
132
133impl From<plat::net::NetError> for Error {
134 fn from(e: plat::net::NetError) -> Self {
135 Error::Net(e)
136 }
137}