Skip to main content

netchan/
endpoint.rs

1// endpoint -- the server's and the client's protocol without I/O (docs/TRANSPORT.md "Handschlag")
2//
3//   ServerCore::new(ServerConfig, secret)
4//     .datagram(from, bytes, now)        a UDP datagram
5//     .stream_open(id, addr, now) / .stream_message(id, bytes, now) / .stream_closed(id, code)
6//                                        a WebSocket (or any reliable message stream)
7//     .tick(now)                         keep-alives, timeouts, streams that never said CONNECT
8//     .send(conn, payload, now) -> seq   .disconnect(conn, now)
9//     .send_reliable(conn, message, now) the reliable channel: any size up to max_message, in
10//                                        order, resent until it arrives (reliable.rs)
11//     .take_out() -> Out (what to send where, streams to close)   .poll_event() -> ServerEvent
12//     .set_static_key(secret) / .public_key()   a long-lived X25519 key clients may pin
13//   ClientCore::new(ClientConfig, random [32], stream)
14//     .start(now) / .packet(bytes, now) / .tick(now) / .send(payload, now) / .disconnect(now)
15//     .send_reliable(message, now)
16//     .transport_closed(code) / .take_out() -> bytes / .poll_event() -> ClientEvent
17//
18// Time and randomness are the caller's (microseconds; the server's secret, the client's 32 random
19// bytes), so tests run them on a virtual clock over a simulated network (apps/nettest), the same
20// on every run.  The UDP handshake: CONNECT (padded) -> CHALLENGE with a stateless cookie,
21// HMAC-SHA256 over the client's address, its nonce and the time -> RESPONSE (padded) with the
22// cookie and the client's ephemeral X25519 key -> ACCEPT with a random token, the server's
23// ephemeral key and `confirm`, the proof that it derived the same keys (seal.rs).  From then on
24// every DATA and DISCONNECT is sealed with ChaCha20-Poly1305 under keys of this connection alone:
25// who listens reads nothing, a changed, forged or replayed packet is dropped.  With
26// ClientConfig::server_key the keys also need the server's static secret, so nobody on the path
27// can take the server's place; without it they keep out only those who listen.  Nothing is kept
28// for an address before its RESPONSE proves it receives there, the answers before that are
29// smaller than the requests, and challenges_per_s bounds the work for all of them (an HMAC for a
30// CHALLENGE; for an ACCEPT two or three X25519, which a lost ACCEPT does not repeat).  A WebSocket
31// sends CONNECT and gets ACCEPT (token 0, no keys); TCP has proved the address, and wss:// is
32// its encryption.
33
34use alloc::collections::{BTreeMap, VecDeque};
35use alloc::vec::Vec;
36
37use plat::net::{IpAddr, SocketAddr};
38
39use crypto::x25519;
40
41use crate::conn::{Bucket, Conn, Event, Settings, Stats};
42use crate::packet::{self, Packet, DATA_HEADER, DISCONNECT_HEADER, FLAG_STATIC_KEY, HANDSHAKE_SIZE, MAX_UDP_PAYLOAD, TAG};
43use crate::reliable::{self, CHUNK_HEAD};
44use crate::seal::{self, Generator, Handshake, Keys};
45use crate::{Error, Reason, Transport};
46
47/// how long a cookie of a CHALLENGE stays good (seconds)
48const COOKIE_S: u32 = 10;
49/// DISCONNECT over UDP goes out this many times (it is not acknowledged)
50const BYE_COPIES: usize = 3;
51/// the share of challenges_per_s one address prefix (IPv4 /24, IPv6 /48) gets: 1 / PREFIX_SHARE
52const PREFIX_SHARE: u32 = 16;
53/// the prefixes whose key-work budget is kept (more: only the budget of all counts for the new one)
54const PREFIXES_MAX: usize = 4096;
55
56/// a server's limits and timing
57#[derive(Clone, Copy, Debug)]
58pub struct ServerConfig {
59    /// the app's protocol id: clients with another one are refused (another game, another version)
60    pub protocol: u32,
61    /// connections at once (UDP and WebSocket together)
62    pub max_connections: usize,
63    /// connections from one IP address
64    pub max_per_ip: usize,
65    /// the largest payload of a UDP message, both ways (at most MAX_UDP_PAYLOAD)
66    pub max_payload: usize,
67    /// the largest payload of a message over a WebSocket, both ways
68    pub max_stream_payload: usize,
69    /// nothing received for this long ends a connection
70    pub timeout_ms: u32,
71    /// an empty DATA packet after this long without sending (carries the acks)
72    pub keepalive_ms: u32,
73    /// packets a second from one client (UDP: more are dropped; WebSocket: it is disconnected)
74    pub packets_per_s: u32,
75    /// bytes a second from one client (as packets_per_s)
76    pub bytes_per_s: u32,
77    /// handshakes a second whose keys the server works out (two or three X25519 each), for all
78    /// addresses together; one address prefix (IPv4 /24, IPv6 /48) gets a sixteenth of it.  Counted
79    /// after the cookie checked, so a forged sender costs nothing of it; CONNECTs are answered without
80    /// it (a HMAC, and less goes back than came: a flood of them throttled new players)
81    pub challenges_per_s: u32,
82    /// a WebSocket must send its CONNECT within this long
83    pub handshake_ms: u32,
84    /// the largest message of the reliable channel, both ways (a client's larger one ends its
85    /// connection)
86    pub max_message: usize,
87    /// bytes of reliable messages queued for one client before send_reliable says Backlog
88    pub max_reliable_queued: usize,
89    /// bytes a second of reliable chunks to one client (below what its bytes_per_s takes)
90    pub reliable_bytes_per_s: u32,
91}
92
93impl Default for ServerConfig {
94    fn default() -> Self {
95        ServerConfig {
96            protocol: 0,
97            max_connections: 64,
98            max_per_ip: 16,
99            max_payload: 1200,
100            max_stream_payload: 64 * 1024,
101            timeout_ms: 5000,
102            keepalive_ms: 100,
103            packets_per_s: 300,
104            bytes_per_s: 256 * 1024,
105            challenges_per_s: 2000,
106            handshake_ms: 5000,
107            max_message: 1 << 20,
108            max_reliable_queued: 4 << 20,
109            reliable_bytes_per_s: 128 * 1024,
110        }
111    }
112}
113
114/// where a packet goes
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub enum Route {
117    /// a UDP datagram to this address
118    Udp(SocketAddr),
119    /// a message on this stream (WebSocket)
120    Stream(u32),
121}
122
123/// what a core wants done
124#[derive(Clone, Debug, PartialEq, Eq)]
125pub enum Out {
126    /// send these bytes
127    Send(Route, Vec<u8>),
128    /// close this stream (after what was sent on it)
129    Close(u32),
130}
131
132/// what happened on the server
133#[derive(Clone, Debug, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum ServerEvent {
136    /// a client came (`addr`: its address, if the transport knows it)
137    Connected { id: u32, transport: Transport, addr: Option<SocketAddr> },
138    /// a message of a client
139    Message { id: u32, seq: u16, data: Vec<u8> },
140    /// a message of a client's reliable channel, whole and in order
141    Reliable { id: u32, data: Vec<u8> },
142    /// a client has a packet the server sent
143    Delivered { id: u32, seq: u16 },
144    /// a packet the server sent did not reach the client (UDP)
145    Lost { id: u32, seq: u16 },
146    /// a client is gone
147    Disconnected { id: u32, reason: Reason },
148}
149
150/// what the server counted beyond its connections
151#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
152pub struct ServerStats {
153    /// CHALLENGE answers sent
154    pub challenges: u64,
155    /// connections taken
156    pub accepted: u64,
157    /// clients refused (full, protocol, address)
158    pub denied: u64,
159    /// packets that were no packet, a wrong kind, a wrong cookie or token, or a handshake with a
160    /// key that gives no shared secret (forged DATA of a connection: its Stats::forged)
161    pub bad: u64,
162    /// handshakes over challenges_per_s, left without an answer
163    pub throttled: u64,
164    /// RESPONSEs with another nonce or key from an address whose connection is still alive, left
165    /// without an answer (a client that starts again gets in once its old connection was quiet for
166    /// a second; someone on the path who saw a CHALLENGE ended the connection before)
167    pub kept: u64,
168    /// DATA from addresses without a connection
169    pub unknown: u64,
170}
171
172struct Peer {
173    conn: Conn,
174    route: Route,
175    nonce: u64,
176    addr: Option<SocketAddr>,
177    // UDP: the client's key and the ACCEPT, sent again when its RESPONSE comes again
178    client_key: [u8; 32],
179    accept: Vec<u8>,
180    // the payload a packet to this peer may have: the server's limit, the client's if smaller
181    room: usize,
182}
183
184/// the server's static X25519 key; zeroed when dropped
185struct StaticKey {
186    secret: [u8; 32],
187    public: [u8; 32],
188}
189
190impl Drop for StaticKey {
191    fn drop(&mut self) {
192        crypto::zeroize(&mut self.secret);
193    }
194}
195
196/// the server's protocol (see the top of this file)
197pub struct ServerCore {
198    cfg: ServerConfig,
199    // the key of the cookies and tokens (from the secret, which is not kept: the generator's seed
200    // cannot be had from this key, so a later leak does not give the past ephemeral keys)
201    mac_key: [u8; 32],
202    keygen: Generator,
203    static_key: Option<StaticKey>,
204    tokens: u64,
205    peers: BTreeMap<u32, Peer>,
206    by_addr: BTreeMap<SocketAddr, u32>,
207    by_stream: BTreeMap<u32, u32>,
208    pending: BTreeMap<u32, (u64, Option<SocketAddr>)>,
209    next_id: u32,
210    events: VecDeque<ServerEvent>,
211    out: VecDeque<Out>,
212    // the key-work budget: of all addresses, of each prefix
213    answers: Bucket,
214    prefixes: BTreeMap<[u8; 8], Bucket>,
215    stats: ServerStats,
216}
217
218impl ServerCore {
219    /// a server with these limits; `secret` keys the cookies and tokens and seeds the ephemeral
220    /// keys of the handshakes (random in a real server, fixed in tests)
221    pub fn new(cfg: ServerConfig, secret: [u8; 32], now: u64) -> ServerCore {
222        let mut secret = secret;
223        let mac_key = crypto::hmac::hmac_sha256(&secret, b"netchan v2 mac");
224        let keygen = Generator::new(&secret);
225        crypto::zeroize(&mut secret);
226        let mut cfg = cfg;
227        cfg.max_payload = cfg.max_payload.clamp(1, MAX_UDP_PAYLOAD);
228        cfg.max_stream_payload = cfg.max_stream_payload.max(1);
229        ServerCore {
230            cfg,
231            mac_key,
232            keygen,
233            static_key: None,
234            tokens: 0,
235            peers: BTreeMap::new(),
236            by_addr: BTreeMap::new(),
237            by_stream: BTreeMap::new(),
238            pending: BTreeMap::new(),
239            next_id: 1,
240            events: VecDeque::new(),
241            out: VecDeque::new(),
242            answers: Bucket::new(cfg.challenges_per_s, now),
243            prefixes: BTreeMap::new(),
244            stats: ServerStats::default(),
245        }
246    }
247
248    /// the limits in force (max_payload clamped)
249    pub fn config(&self) -> &ServerConfig {
250        &self.cfg
251    }
252
253    /// a long-lived X25519 secret: clients that know its public key (ClientConfig::server_key)
254    /// include it in their keys, so only this server can answer them.  Kept by the app (32 random
255    /// bytes, made once); clients without the key still connect with ephemeral keys only
256    pub fn set_static_key(&mut self, secret: [u8; 32]) {
257        let public = x25519::public_key(&secret);
258        self.static_key = Some(StaticKey { secret, public });
259    }
260
261    /// the public key of set_static_key (for the clients' ClientConfig::server_key)
262    pub fn public_key(&self) -> Option<[u8; 32]> {
263        self.static_key.as_ref().map(|k| k.public)
264    }
265
266    fn settings(&self) -> Settings {
267        Settings { timeout_ms: self.cfg.timeout_ms, keepalive_ms: self.cfg.keepalive_ms, packets_per_s: self.cfg.packets_per_s, bytes_per_s: self.cfg.bytes_per_s }
268    }
269
270    fn limits(&self) -> reliable::Limits {
271        reliable::Limits { max_message: self.cfg.max_message, max_queued: self.cfg.max_reliable_queued, bytes_per_s: self.cfg.reliable_bytes_per_s }
272    }
273
274    // the payload a packet to a peer on this route may have: the server's limit, the client's if it
275    // gave a smaller one (0: none given, a client of before)
276    fn room(&self, route: Route, client: u32) -> usize {
277        let own = if matches!(route, Route::Udp(_)) { self.cfg.max_payload } else { self.cfg.max_stream_payload };
278        if client == 0 { own } else { own.min((client as usize).max(CHUNK_HEAD + 1)) }
279    }
280
281    // how long a connection must have been quiet before a new handshake from its address replaces it
282    fn quiet_us(&self) -> u64 {
283        (self.cfg.keepalive_ms as u64 * 4).max(1000).min(self.cfg.timeout_ms.max(1) as u64) * 1000
284    }
285
286    // the key work of one handshake from `ip`: within the budget of all and of its prefix
287    fn key_budget(&mut self, ip: &IpAddr, now: u64) -> bool {
288        let pre = prefix(ip);
289        if !self.prefixes.contains_key(&pre) && self.prefixes.len() >= PREFIXES_MAX {
290            // the prefixes whose budget is full again have nothing to remember
291            self.prefixes.retain(|_, b| !b.full(now));
292        }
293        let share = (self.cfg.challenges_per_s / PREFIX_SHARE).max(1);
294        let room = self.prefixes.len() < PREFIXES_MAX;
295        let ok = match self.prefixes.get_mut(&pre) {
296            Some(b) => b.take(1, now),
297            None if room => {
298                let mut b = Bucket::new(share, now);
299                let ok = b.take(1, now);
300                self.prefixes.insert(pre, b);
301                ok
302            }
303            None => true,
304        };
305        ok && self.answers.take(1, now)
306    }
307
308    // the RELIABLE packets that are due for a peer
309    fn flush(&mut self, id: u32, now: u64) {
310        let Some(p) = self.peers.get_mut(&id) else { return };
311        let (route, room) = (p.route, p.room);
312        loop {
313            let mut b = Vec::new();
314            if p.conn.write_reliable(now, room, &mut b).is_none() {
315                break;
316            }
317            self.out.push_back(Out::Send(route, b));
318        }
319    }
320
321    fn cookie(&self, from: &SocketAddr, nonce: u64, time: u32) -> [u8; 16] {
322        let mut d = [0u8; 34];
323        d[..16].copy_from_slice(&ip16(&from.ip));
324        d[16..18].copy_from_slice(&from.port.to_le_bytes());
325        d[18..26].copy_from_slice(&nonce.to_le_bytes());
326        d[26..30].copy_from_slice(&time.to_le_bytes());
327        d[30..34].copy_from_slice(b"ck01");
328        let h = crypto::hmac::hmac_sha256(&self.mac_key, &d);
329        let mut m = [0u8; 16];
330        m.copy_from_slice(&h[..16]);
331        m
332    }
333
334    fn new_token(&mut self) -> u32 {
335        loop {
336            self.tokens += 1;
337            let mut d = [0u8; 12];
338            d[..8].copy_from_slice(&self.tokens.to_le_bytes());
339            d[8..].copy_from_slice(b"tk01");
340            let h = crypto::hmac::hmac_sha256(&self.mac_key, &d);
341            let t = u32::from_le_bytes([h[0], h[1], h[2], h[3]]);
342            if t != 0 {
343                return t;
344            }
345        }
346    }
347
348    fn send_raw(&mut self, route: Route, p: Packet<'_>) {
349        self.out.push_back(Out::Send(route, p.to_vec(false)));
350    }
351
352    fn new_id(&mut self) -> u32 {
353        let id = self.next_id;
354        self.next_id = self.next_id.wrapping_add(1).max(1);
355        id
356    }
357
358    // take a peer's events into the server's
359    fn drain(&mut self, id: u32) {
360        let Some(p) = self.peers.get_mut(&id) else { return };
361        while let Some(e) = p.conn.take_event() {
362            self.events.push_back(match e {
363                Event::Message { seq, data } => ServerEvent::Message { id, seq, data },
364                Event::Reliable(data) => ServerEvent::Reliable { id, data },
365                Event::Delivered(seq) => ServerEvent::Delivered { id, seq },
366                Event::Lost(seq) => ServerEvent::Lost { id, seq },
367            });
368        }
369    }
370
371    // a peer goes: its bye (UDP several times), its stream closed, the event
372    fn remove(&mut self, id: u32, bye: Option<u8>, reason: Reason) {
373        let Some(mut p) = self.peers.remove(&id) else { return };
374        let mut b = Vec::new();
375        if let Some(r) = bye {
376            p.conn.write_disconnect(r, &mut b);
377        }
378        match p.route {
379            Route::Udp(a) => {
380                self.by_addr.remove(&a);
381                if bye.is_some() {
382                    for _ in 0..BYE_COPIES {
383                        self.out.push_back(Out::Send(p.route, b.clone()));
384                    }
385                }
386            }
387            Route::Stream(s) => {
388                self.by_stream.remove(&s);
389                if bye.is_some() {
390                    self.out.push_back(Out::Send(p.route, b));
391                }
392                self.out.push_back(Out::Close(s));
393            }
394        }
395        self.events.push_back(ServerEvent::Disconnected { id, reason });
396    }
397
398    fn count_ip(&self, ip: &IpAddr) -> usize {
399        self.peers.values().filter(|p| p.addr.is_some_and(|a| a.ip == *ip)).count()
400    }
401
402    /// a UDP datagram from `from`
403    pub fn datagram(&mut self, from: SocketAddr, data: &[u8], now: u64) {
404        let Some(p) = packet::parse(data) else {
405            self.stats.bad += 1;
406            return;
407        };
408        match p {
409            Packet::Connect { protocol, nonce, .. } => {
410                if data.len() < HANDSHAKE_SIZE {
411                    self.stats.bad += 1;
412                    return;
413                }
414                if protocol != self.cfg.protocol {
415                    self.stats.denied += 1;
416                    self.send_raw(Route::Udp(from), Packet::Deny { nonce, reason: packet::DENY_PROTOCOL });
417                    return;
418                }
419                let time = (now / 1_000_000) as u32;
420                let mac = self.cookie(&from, nonce, time);
421                self.stats.challenges += 1;
422                self.send_raw(Route::Udp(from), Packet::Challenge { nonce, time, mac });
423            }
424            Packet::Response { protocol, nonce, time, mac, flags, key, max_payload: client_max } => {
425                if data.len() < HANDSHAKE_SIZE || protocol != self.cfg.protocol || flags & !FLAG_STATIC_KEY != 0 {
426                    self.stats.bad += 1;
427                    return;
428                }
429                let old = self.by_addr.get(&from).copied();
430                if let Some(id) = old {
431                    if let Some(p) = self.peers.get(&id).filter(|p| p.nonce == nonce && p.client_key == key) {
432                        // the ACCEPT was lost: the same bytes once more (no new keys)
433                        let b = p.accept.clone();
434                        self.out.push_back(Out::Send(Route::Udp(from), b));
435                        return;
436                    }
437                }
438                // the cookie first: a forged RESPONSE costs a HMAC and nothing of the budget
439                let now_s = (now / 1_000_000) as u32;
440                if time > now_s || now_s - time > COOKIE_S || !crypto::ct_eq(&mac, &self.cookie(&from, nonce, time)) {
441                    self.stats.bad += 1;
442                    return;
443                }
444                // a new handshake from an address with a connection replaces it only when it has been
445                // quiet (the client started again); a live one stays
446                if let Some(id) = old {
447                    let quiet = self.quiet_us();
448                    if self.peers.get(&id).is_some_and(|p| p.conn.quiet_for(now) < quiet) {
449                        self.stats.kept += 1;
450                        return;
451                    }
452                }
453                let stat = flags & FLAG_STATIC_KEY != 0;
454                if stat && self.static_key.is_none() {
455                    self.stats.denied += 1;
456                    self.send_raw(Route::Udp(from), Packet::Deny { nonce, reason: packet::DENY_KEY });
457                    return;
458                }
459                // the limits before the key work (the connection this one replaces does not count)
460                let replaced = old.is_some() as usize;
461                if self.peers.len() - replaced >= self.cfg.max_connections {
462                    self.stats.denied += 1;
463                    self.send_raw(Route::Udp(from), Packet::Deny { nonce, reason: packet::DENY_FULL });
464                    return;
465                }
466                if self.count_ip(&from.ip) - replaced >= self.cfg.max_per_ip {
467                    self.stats.denied += 1;
468                    self.send_raw(Route::Udp(from), Packet::Deny { nonce, reason: packet::DENY_ADDRESS });
469                    return;
470                }
471                if !self.key_budget(&from.ip, now) {
472                    self.stats.throttled += 1;
473                    return;
474                }
475                // the keys, before anything changes (a key without a shared secret: nothing happens)
476                let mut eph = self.keygen.next_secret();
477                let server_pub = x25519::public_key(&eph);
478                let dh1 = x25519::shared(&eph, &key);
479                crypto::zeroize(&mut eph);
480                let dh2 = match &self.static_key {
481                    Some(k) if stat => x25519::shared(&k.secret, &key).map(Some),
482                    _ => Some(None),
483                };
484                let (Some(mut dh1), Some(mut dh2)) = (dh1, dh2) else {
485                    self.stats.bad += 1;
486                    return;
487                };
488                let static_pub = self.static_key.as_ref().filter(|_| stat).map(|k| k.public);
489                let hs = Handshake { protocol, nonce, client: &key, server: &server_pub, stat: static_pub.as_ref() };
490                let keys = seal::derive(&hs, &dh1, dh2.as_ref());
491                crypto::zeroize(&mut dh1);
492                if let Some(d) = dh2.as_mut() {
493                    crypto::zeroize(d);
494                }
495                // the client started again: its old connection goes
496                if let Some(old) = old {
497                    self.remove(old, Some(packet::BYE_REPLACED), Reason::Replaced);
498                }
499                let id = self.new_id();
500                let token = self.new_token();
501                let max = self.cfg.max_payload as u16;
502                let mut accept = Packet::Accept { nonce, token, max_payload: max, key: server_pub, confirm: [0; 16] }.to_vec(false);
503                let at = accept.len() - 16;
504                let confirm = seal::confirm_tag(&keys.confirm, &accept[..at]);
505                accept[at..].copy_from_slice(&confirm);
506                let conn = Conn::new(token, false, self.settings(), now).with_keys(Keys::new(keys.s2c, keys.c2s)).with_reliable(self.limits());
507                let room = self.room(Route::Udp(from), client_max);
508                self.peers.insert(id, Peer { conn, route: Route::Udp(from), nonce, addr: Some(from), client_key: key, accept: accept.clone(), room });
509                self.by_addr.insert(from, id);
510                self.stats.accepted += 1;
511                self.out.push_back(Out::Send(Route::Udp(from), accept));
512                self.events.push_back(ServerEvent::Connected { id, transport: Transport::Udp, addr: Some(from) });
513            }
514            Packet::Data { token, seq, ack, bits, payload } => {
515                let Some(&id) = self.by_addr.get(&from) else {
516                    self.stats.unknown += 1;
517                    return;
518                };
519                let max = self.cfg.max_payload;
520                let Some(peer) = self.peers.get_mut(&id) else { return };
521                if token != peer.conn.token() {
522                    self.stats.bad += 1;
523                    return;
524                }
525                if payload.len() > max + TAG {
526                    peer.conn.count_dropped();
527                    return;
528                }
529                if !peer.conn.rate_ok(data.len(), now) {
530                    return;
531                }
532                let Some(plain) = peer.conn.open(data, DATA_HEADER, seq) else { return };
533                peer.conn.on_data(seq, ack, bits, &plain, now);
534                if peer.conn.ack_due() {
535                    let mut b = Vec::with_capacity(DATA_HEADER);
536                    peer.conn.write_data(&[], now, &mut b);
537                    self.out.push_back(Out::Send(Route::Udp(from), b));
538                }
539                // (acks free room in the reliable window)
540                self.flush(id, now);
541                self.drain(id);
542            }
543            Packet::Reliable { token, seq, ack, bits, payload } => {
544                let Some(&id) = self.by_addr.get(&from) else {
545                    self.stats.unknown += 1;
546                    return;
547                };
548                let max = self.cfg.max_payload;
549                let Some(peer) = self.peers.get_mut(&id) else { return };
550                if token != peer.conn.token() {
551                    self.stats.bad += 1;
552                    return;
553                }
554                if payload.len() > max + TAG {
555                    peer.conn.count_dropped();
556                    return;
557                }
558                if !peer.conn.rate_ok(data.len(), now) {
559                    return;
560                }
561                let Some(plain) = peer.conn.open(data, DATA_HEADER, seq) else { return };
562                if !peer.conn.on_reliable(seq, ack, bits, &plain, now) {
563                    // authentic, and against the protocol
564                    self.drain(id);
565                    return self.remove(id, Some(packet::BYE_PROTOCOL), Reason::Protocol);
566                }
567                if peer.conn.ack_due() {
568                    let mut b = Vec::with_capacity(DATA_HEADER);
569                    peer.conn.write_data(&[], now, &mut b);
570                    self.out.push_back(Out::Send(Route::Udp(from), b));
571                }
572                self.flush(id, now);
573                self.drain(id);
574            }
575            Packet::Disconnect { token, seq, reason, .. } => {
576                let Some(&id) = self.by_addr.get(&from) else { return };
577                let Some(peer) = self.peers.get_mut(&id).filter(|p| p.conn.token() == token) else {
578                    self.stats.bad += 1;
579                    return;
580                };
581                if peer.conn.open(data, DISCONNECT_HEADER, seq).is_some() {
582                    self.remove(id, None, Reason::Peer(reason));
583                }
584            }
585            _ => self.stats.bad += 1,
586        }
587    }
588
589    /// a stream (WebSocket) opened; it must send CONNECT within handshake_ms
590    pub fn stream_open(&mut self, stream: u32, addr: Option<SocketAddr>, now: u64) {
591        self.pending.insert(stream, (now, addr));
592    }
593
594    /// a message on a stream
595    pub fn stream_message(&mut self, stream: u32, data: &[u8], now: u64) {
596        if let Some(&id) = self.by_stream.get(&stream) {
597            match packet::parse(data) {
598                Some(Packet::Data { seq, ack, bits, payload, .. }) => {
599                    let max = self.cfg.max_stream_payload;
600                    let Some(peer) = self.peers.get_mut(&id) else { return };
601                    if payload.len() > max {
602                        self.remove(id, Some(packet::BYE_PROTOCOL), Reason::Protocol);
603                        return;
604                    }
605                    if !peer.conn.rate_ok(data.len(), now) {
606                        self.remove(id, Some(packet::BYE_RATE), Reason::RateLimit);
607                        return;
608                    }
609                    peer.conn.on_data(seq, ack, bits, payload, now);
610                    self.flush(id, now);
611                    self.drain(id);
612                }
613                Some(Packet::Reliable { seq, ack, bits, payload, .. }) => {
614                    let max = self.cfg.max_stream_payload;
615                    let Some(peer) = self.peers.get_mut(&id) else { return };
616                    if payload.len() > max {
617                        self.remove(id, Some(packet::BYE_PROTOCOL), Reason::Protocol);
618                        return;
619                    }
620                    if !peer.conn.rate_ok(data.len(), now) {
621                        self.remove(id, Some(packet::BYE_RATE), Reason::RateLimit);
622                        return;
623                    }
624                    if !peer.conn.on_reliable(seq, ack, bits, payload, now) {
625                        self.drain(id);
626                        self.remove(id, Some(packet::BYE_PROTOCOL), Reason::Protocol);
627                        return;
628                    }
629                    self.flush(id, now);
630                    self.drain(id);
631                }
632                Some(Packet::Disconnect { reason, .. }) => self.remove(id, None, Reason::Peer(reason)),
633                _ => {
634                    self.stats.bad += 1;
635                    self.remove(id, Some(packet::BYE_PROTOCOL), Reason::Protocol);
636                }
637            }
638            return;
639        }
640        let Some((_, addr)) = self.pending.remove(&stream) else { return };
641        let Some(Packet::Connect { protocol, nonce, max_payload: client_max }) = packet::parse(data) else {
642            self.stats.bad += 1;
643            self.out.push_back(Out::Close(stream));
644            return;
645        };
646        let deny = if protocol != self.cfg.protocol {
647            Some(packet::DENY_PROTOCOL)
648        } else if self.peers.len() >= self.cfg.max_connections {
649            Some(packet::DENY_FULL)
650        } else if addr.is_some_and(|a| self.count_ip(&a.ip) >= self.cfg.max_per_ip) {
651            Some(packet::DENY_ADDRESS)
652        } else {
653            None
654        };
655        if let Some(reason) = deny {
656            self.stats.denied += 1;
657            self.send_raw(Route::Stream(stream), Packet::Deny { nonce, reason });
658            self.out.push_back(Out::Close(stream));
659            return;
660        }
661        let id = self.new_id();
662        let conn = Conn::new(0, true, self.settings(), now).with_reliable(self.limits());
663        let room = self.room(Route::Stream(stream), client_max);
664        self.peers.insert(id, Peer { conn, route: Route::Stream(stream), nonce, addr, client_key: [0; 32], accept: Vec::new(), room });
665        self.by_stream.insert(stream, id);
666        self.stats.accepted += 1;
667        let max = self.cfg.max_stream_payload.min(u16::MAX as usize) as u16;
668        self.send_raw(Route::Stream(stream), Packet::Accept { nonce, token: 0, max_payload: max, key: [0; 32], confirm: [0; 16] });
669        self.events.push_back(ServerEvent::Connected { id, transport: Transport::WebSocket, addr });
670    }
671
672    /// a stream ended (`code`: its close code, 1006 without one)
673    pub fn stream_closed(&mut self, stream: u32, code: u16) {
674        self.pending.remove(&stream);
675        if let Some(&id) = self.by_stream.get(&stream) {
676            self.peers.remove(&id);
677            self.by_stream.remove(&stream);
678            self.events.push_back(ServerEvent::Disconnected { id, reason: Reason::Closed(code) });
679        }
680    }
681
682    /// keep-alives, timeouts, streams without a CONNECT
683    pub fn tick(&mut self, now: u64) {
684        let ids: Vec<u32> = self.peers.keys().copied().collect();
685        for id in ids {
686            let Some(p) = self.peers.get_mut(&id) else { continue };
687            if p.conn.timed_out(now) {
688                self.remove(id, Some(packet::BYE_TIMEOUT), Reason::Timeout);
689                continue;
690            }
691            // reliable chunks that are due (a RELIABLE packet carries the acks, as a keep-alive)
692            self.flush(id, now);
693            let Some(p) = self.peers.get_mut(&id) else { continue };
694            if p.conn.keepalive_due(now) {
695                let mut b = Vec::with_capacity(DATA_HEADER);
696                p.conn.write_data(&[], now, &mut b);
697                let route = p.route;
698                self.out.push_back(Out::Send(route, b));
699            }
700            self.drain(id);
701        }
702        let limit = self.cfg.handshake_ms as u64 * 1000;
703        let late: Vec<u32> = self.pending.iter().filter(|(_, (t, _))| now.saturating_sub(*t) >= limit).map(|(s, _)| *s).collect();
704        for s in late {
705            self.pending.remove(&s);
706            self.out.push_back(Out::Close(s));
707        }
708    }
709
710    /// send a message to a client -> its sequence number (Size: empty or over the limit of its
711    /// transport, or over the client's smaller one (max_payload); NotConnected: no such client)
712    pub fn send(&mut self, id: u32, payload: &[u8], now: u64) -> Result<u16, Error> {
713        let p = self.peers.get_mut(&id).ok_or(Error::NotConnected)?;
714        if payload.is_empty() || payload.len() > p.room {
715            return Err(Error::Size);
716        }
717        let mut b = Vec::with_capacity(DATA_HEADER + payload.len());
718        let seq = p.conn.write_data(payload, now, &mut b);
719        let route = p.route;
720        self.out.push_back(Out::Send(route, b));
721        self.drain(id);
722        Ok(seq)
723    }
724
725    /// send a message on a client's reliable channel: any size up to max_message, cut into
726    /// chunks of a packet each, in order, over UDP sent again until the client has it; it goes
727    /// out at reliable_bytes_per_s, so a large one takes a while (Size: empty or over
728    /// max_message; Backlog: more than max_reliable_queued would wait; NotConnected)
729    pub fn send_reliable(&mut self, id: u32, payload: &[u8], now: u64) -> Result<(), Error> {
730        let p = self.peers.get_mut(&id).ok_or(Error::NotConnected)?;
731        let chunk = p.room.saturating_sub(CHUNK_HEAD);
732        p.conn.send_reliable(payload, chunk)?;
733        self.flush(id, now);
734        self.drain(id);
735        Ok(())
736    }
737
738    /// end a client's connection (DISCONNECT goes out, Disconnected(Local) follows)
739    pub fn disconnect(&mut self, id: u32, reason: u8) {
740        self.remove(id, Some(reason), Reason::Local);
741    }
742
743    /// end every connection (the server stops)
744    pub fn disconnect_all(&mut self) {
745        let ids: Vec<u32> = self.peers.keys().copied().collect();
746        for id in ids {
747            self.remove(id, Some(packet::BYE_SHUTDOWN), Reason::Local);
748        }
749    }
750
751    /// the next thing to send or close
752    pub fn take_out(&mut self) -> Option<Out> {
753        self.out.pop_front()
754    }
755
756    /// the next event
757    pub fn poll_event(&mut self) -> Option<ServerEvent> {
758        self.events.pop_front()
759    }
760
761    /// connections now
762    pub fn connections(&self) -> usize {
763        self.peers.len()
764    }
765
766    /// the ids of the connections
767    pub fn ids(&self) -> Vec<u32> {
768        self.peers.keys().copied().collect()
769    }
770
771    /// a connection's counts and round-trip time
772    pub fn stats(&self, id: u32) -> Option<Stats> {
773        self.peers.get(&id).map(|p| p.conn.stats())
774    }
775
776    /// the largest payload the server sends a connection (its limit, the client's if smaller)
777    pub fn max_payload(&self, id: u32) -> Option<usize> {
778        self.peers.get(&id).map(|p| p.room)
779    }
780
781    /// a connection's transport and address
782    pub fn peer(&self, id: u32) -> Option<(Transport, Option<SocketAddr>)> {
783        self.peers.get(&id).map(|p| (if matches!(p.route, Route::Udp(_)) { Transport::Udp } else { Transport::WebSocket }, p.addr))
784    }
785
786    /// where a connection's packets go
787    pub fn route(&self, id: u32) -> Option<Route> {
788        self.peers.get(&id).map(|p| p.route)
789    }
790
791    /// what the server counted beyond its connections
792    pub fn server_stats(&self) -> ServerStats {
793        self.stats
794    }
795}
796
797impl Drop for ServerCore {
798    fn drop(&mut self) {
799        crypto::zeroize(&mut self.mac_key);
800    }
801}
802
803/// an address's prefix: IPv4 /24, IPv6 /48 (what one site has)
804fn prefix(ip: &IpAddr) -> [u8; 8] {
805    match ip {
806        IpAddr::V4(a) => [4, a[0], a[1], a[2], 0, 0, 0, 0],
807        IpAddr::V6(a) => [6, a[0], a[1], a[2], a[3], a[4], a[5], 0],
808    }
809}
810
811/// an address as 16 bytes (IPv4 mapped)
812fn ip16(ip: &IpAddr) -> [u8; 16] {
813    match ip {
814        IpAddr::V4(a) => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a[0], a[1], a[2], a[3]],
815        IpAddr::V6(a) => *a,
816    }
817}
818
819// ------------------------------------------------------------------ the client
820
821/// a client's limits and timing
822#[derive(Clone, Copy, Debug)]
823pub struct ClientConfig {
824    /// the app's protocol id (the server's must be the same)
825    pub protocol: u32,
826    /// the largest payload this side takes from the server (UDP at most MAX_UDP_PAYLOAD); the
827    /// handshake tells the server, which sends no more
828    pub max_payload: usize,
829    /// nothing received for this long ends the connection
830    pub timeout_ms: u32,
831    /// an empty DATA packet after this long without sending
832    pub keepalive_ms: u32,
833    /// the handshake within this long
834    pub connect_ms: u32,
835    /// UDP: CONNECT / RESPONSE again after this long without an answer
836    pub resend_ms: u32,
837    /// packets a second from the server, on average (more are dropped)
838    pub packets_per_s: u32,
839    /// bytes a second from the server, on average (more are dropped)
840    pub bytes_per_s: u32,
841    /// UDP: the server's static public key (ServerCore::set_static_key, Server::set_static_key).
842    /// Given, the keys need the server's secret, and a server without it is refused
843    /// (Reason::ServerKey); None: ephemeral keys only, safe from listeners but not from someone
844    /// on the path who answers in the server's place
845    pub server_key: Option<[u8; 32]>,
846    /// the largest message of the reliable channel, both ways (the server's larger one ends the
847    /// connection)
848    pub max_message: usize,
849    /// bytes of reliable messages queued before send_reliable says Backlog
850    pub max_reliable_queued: usize,
851    /// bytes a second of reliable chunks to the server (below its bytes_per_s)
852    pub reliable_bytes_per_s: u32,
853}
854
855impl Default for ClientConfig {
856    fn default() -> Self {
857        ClientConfig {
858            protocol: 0,
859            max_payload: 64 * 1024,
860            timeout_ms: 5000,
861            keepalive_ms: 100,
862            connect_ms: 5000,
863            resend_ms: 100,
864            packets_per_s: 4000,
865            bytes_per_s: 16 << 20,
866            server_key: None,
867            max_message: 1 << 20,
868            max_reliable_queued: 4 << 20,
869            reliable_bytes_per_s: 128 * 1024,
870        }
871    }
872}
873
874/// where a client stands
875#[derive(Clone, Debug, PartialEq, Eq)]
876pub enum State {
877    /// the handshake is on its way
878    Connecting,
879    /// the server took the connection
880    Connected,
881    /// ended, and why
882    Disconnected(Reason),
883}
884
885/// what happened on the client
886#[derive(Clone, Debug, PartialEq, Eq)]
887#[non_exhaustive]
888pub enum ClientEvent {
889    /// the server took the connection
890    Connected,
891    /// a message of the server
892    Message { seq: u16, data: Vec<u8> },
893    /// a message of the server's reliable channel, whole and in order
894    Reliable(Vec<u8>),
895    /// the server has a packet this side sent
896    Delivered(u16),
897    /// a packet this side sent did not reach the server (UDP)
898    Lost(u16),
899    /// the connection ended
900    Disconnected(Reason),
901}
902
903enum Phase {
904    Idle,
905    Connecting { started: u64, last: u64, cookie: Option<(u32, [u8; 16])> },
906    Connected { conn: Conn, max_send: usize },
907    Done(Reason),
908}
909
910/// the client's protocol (see the top of this file)
911pub struct ClientCore {
912    cfg: ClientConfig,
913    nonce: u64,
914    // the ephemeral X25519 key of this attempt (UDP; zeroed once the handshake is over)
915    eph: [u8; 32],
916    eph_pub: [u8; 32],
917    stream: bool,
918    phase: Phase,
919    out: VecDeque<Vec<u8>>,
920    events: VecDeque<ClientEvent>,
921}
922
923impl ClientCore {
924    /// a client; `random`: 32 random bytes of this attempt (its nonce and, over UDP, its
925    /// ephemeral key come from them: plat::random_bytes in a real client, fixed in tests);
926    /// `stream`: over a WebSocket
927    pub fn new(cfg: ClientConfig, random: [u8; 32], stream: bool) -> ClientCore {
928        let mut cfg = cfg;
929        if !stream {
930            cfg.max_payload = cfg.max_payload.clamp(1, MAX_UDP_PAYLOAD);
931        }
932        let n = crypto::hmac::hmac_sha256(&random, b"netchan v2 nonce");
933        let nonce = u64::from_le_bytes([n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7]]);
934        let (eph, eph_pub) = if stream {
935            ([0; 32], [0; 32])
936        } else {
937            let e = crypto::hmac::hmac_sha256(&random, b"netchan v2 ephemeral");
938            (e, x25519::public_key(&e))
939        };
940        ClientCore { cfg, nonce, eph, eph_pub, stream, phase: Phase::Idle, out: VecDeque::new(), events: VecDeque::new() }
941    }
942
943    fn response(&self, time: u32, mac: [u8; 16]) -> Vec<u8> {
944        let flags = if self.cfg.server_key.is_some() { FLAG_STATIC_KEY } else { 0 };
945        Packet::Response { protocol: self.cfg.protocol, nonce: self.nonce, time, mac, flags, key: self.eph_pub, max_payload: self.own_max() }.to_vec(true)
946    }
947
948    // the keys of an ACCEPT that came: None when its confirm does not check
949    fn accept_keys(&self, accept: &[u8], server_pub: &[u8; 32], confirm: &[u8; 16]) -> Option<Keys> {
950        let mut dh1 = x25519::shared(&self.eph, server_pub)?;
951        let mut dh2 = match &self.cfg.server_key {
952            Some(s) => Some(x25519::shared(&self.eph, s)?),
953            None => None,
954        };
955        let hs = Handshake { protocol: self.cfg.protocol, nonce: self.nonce, client: &self.eph_pub, server: server_pub, stat: self.cfg.server_key.as_ref() };
956        let keys = seal::derive(&hs, &dh1, dh2.as_ref());
957        crypto::zeroize(&mut dh1);
958        if let Some(d) = dh2.as_mut() {
959            crypto::zeroize(d);
960        }
961        let want = seal::confirm_tag(&keys.confirm, &accept[..accept.len() - 16]);
962        crypto::ct_eq(&want, confirm).then(|| Keys::new(keys.c2s, keys.s2c))
963    }
964
965    // the largest payload this side takes, as the handshake tells it
966    fn own_max(&self) -> u32 {
967        self.cfg.max_payload.min(u32::MAX as usize) as u32
968    }
969
970    fn connect_packet(&self) -> Vec<u8> {
971        Packet::Connect { protocol: self.cfg.protocol, nonce: self.nonce, max_payload: self.own_max() }.to_vec(!self.stream)
972    }
973
974    /// begin the handshake (CONNECT goes out)
975    pub fn start(&mut self, now: u64) {
976        if matches!(self.phase, Phase::Idle) {
977            self.out.push_back(self.connect_packet());
978            self.phase = Phase::Connecting { started: now, last: now, cookie: None };
979        }
980    }
981
982    fn end(&mut self, reason: Reason) {
983        crypto::zeroize(&mut self.eph);
984        if !matches!(self.phase, Phase::Done(_)) {
985            self.phase = Phase::Done(reason.clone());
986            self.events.push_back(ClientEvent::Disconnected(reason));
987        }
988    }
989
990    fn drain(&mut self) {
991        let Phase::Connected { conn, .. } = &mut self.phase else { return };
992        while let Some(e) = conn.take_event() {
993            self.events.push_back(match e {
994                Event::Message { seq, data } => ClientEvent::Message { seq, data },
995                Event::Reliable(data) => ClientEvent::Reliable(data),
996                Event::Delivered(s) => ClientEvent::Delivered(s),
997                Event::Lost(s) => ClientEvent::Lost(s),
998            });
999        }
1000    }
1001
1002    /// a packet from the server (the caller checked that it came from the server)
1003    pub fn packet(&mut self, data: &[u8], now: u64) {
1004        let Some(p) = packet::parse(data) else { return };
1005        let nonce = self.nonce;
1006        match (&mut self.phase, p) {
1007            (Phase::Connecting { last, cookie, .. }, Packet::Challenge { nonce: n, time, mac }) if n == nonce && !self.stream => {
1008                *cookie = Some((time, mac));
1009                *last = now;
1010                let r = self.response(time, mac);
1011                self.out.push_back(r);
1012            }
1013            (Phase::Connecting { .. }, Packet::Accept { nonce: n, token, max_payload, key, confirm }) if n == nonce => {
1014                let set = Settings { timeout_ms: self.cfg.timeout_ms, keepalive_ms: self.cfg.keepalive_ms, packets_per_s: self.cfg.packets_per_s, bytes_per_s: self.cfg.bytes_per_s };
1015                let cap = if self.stream { usize::MAX } else { MAX_UDP_PAYLOAD };
1016                let limits = reliable::Limits { max_message: self.cfg.max_message, max_queued: self.cfg.max_reliable_queued, bytes_per_s: self.cfg.reliable_bytes_per_s };
1017                let mut conn = Conn::new(token, self.stream, set, now).with_reliable(limits);
1018                if !self.stream {
1019                    match self.accept_keys(data, &key, &confirm) {
1020                        Some(k) => conn = conn.with_keys(k),
1021                        // a pinned key that does not check: the wrong server (or someone in its
1022                        // place); without one, an ACCEPT that is not the server's
1023                        None if self.cfg.server_key.is_some() => return self.end(Reason::ServerKey),
1024                        None => return,
1025                    }
1026                    crypto::zeroize(&mut self.eph);
1027                }
1028                self.phase = Phase::Connected { conn, max_send: (max_payload as usize).clamp(1, cap) };
1029                self.events.push_back(ClientEvent::Connected);
1030            }
1031            (Phase::Connecting { .. }, Packet::Deny { nonce: n, reason }) if n == nonce => {
1032                self.end(match reason {
1033                    packet::DENY_PROTOCOL => Reason::Protocol,
1034                    packet::DENY_KEY => Reason::ServerKey,
1035                    _ => Reason::Full,
1036                });
1037            }
1038            (Phase::Connected { conn, .. }, Packet::Data { token, seq, ack, bits, payload }) if token == conn.token() => {
1039                let tag = if conn.sealed() { TAG } else { 0 };
1040                if payload.len() > self.cfg.max_payload + tag || !conn.rate_ok(data.len(), now) {
1041                    if payload.len() > self.cfg.max_payload + tag {
1042                        conn.count_dropped();
1043                    }
1044                    return;
1045                }
1046                let Some(plain) = conn.open(data, DATA_HEADER, seq) else { return };
1047                conn.on_data(seq, ack, bits, &plain, now);
1048                if conn.ack_due() {
1049                    let mut b = Vec::with_capacity(DATA_HEADER);
1050                    conn.write_data(&[], now, &mut b);
1051                    self.out.push_back(b);
1052                }
1053                self.flush(now);
1054                self.drain();
1055            }
1056            (Phase::Connected { conn, .. }, Packet::Reliable { token, seq, ack, bits, payload }) if token == conn.token() => {
1057                let tag = if conn.sealed() { TAG } else { 0 };
1058                if payload.len() > self.cfg.max_payload + tag || !conn.rate_ok(data.len(), now) {
1059                    if payload.len() > self.cfg.max_payload + tag {
1060                        conn.count_dropped();
1061                    }
1062                    return;
1063                }
1064                let Some(plain) = conn.open(data, DATA_HEADER, seq) else { return };
1065                if !conn.on_reliable(seq, ack, bits, &plain, now) {
1066                    // authentic, and against the protocol
1067                    self.drain();
1068                    return self.abort();
1069                }
1070                if conn.ack_due() {
1071                    let mut b = Vec::with_capacity(DATA_HEADER);
1072                    conn.write_data(&[], now, &mut b);
1073                    self.out.push_back(b);
1074                }
1075                self.flush(now);
1076                self.drain();
1077            }
1078            (Phase::Connected { conn, .. }, Packet::Disconnect { token, seq, reason, .. }) if token == conn.token() => {
1079                if conn.open(data, DISCONNECT_HEADER, seq).is_some() {
1080                    self.end(Reason::Peer(reason));
1081                }
1082            }
1083            _ => {}
1084        }
1085    }
1086
1087    /// resends of the handshake, keep-alives, timeouts
1088    pub fn tick(&mut self, now: u64) {
1089        match &mut self.phase {
1090            Phase::Connecting { started, last, cookie } => {
1091                if now.saturating_sub(*started) >= self.cfg.connect_ms as u64 * 1000 {
1092                    self.end(Reason::ConnectTimeout);
1093                } else if !self.stream && now.saturating_sub(*last) >= self.cfg.resend_ms as u64 * 1000 {
1094                    *last = now;
1095                    let cookie = *cookie;
1096                    let p = match cookie {
1097                        Some((time, mac)) => self.response(time, mac),
1098                        None => self.connect_packet(),
1099                    };
1100                    self.out.push_back(p);
1101                }
1102            }
1103            Phase::Connected { conn, .. } => {
1104                if conn.timed_out(now) {
1105                    self.end(Reason::Timeout);
1106                    return;
1107                }
1108                // reliable chunks that are due (a RELIABLE packet carries the acks, as a keep-alive)
1109                self.flush(now);
1110                if let Phase::Connected { conn, .. } = &mut self.phase {
1111                    if conn.keepalive_due(now) {
1112                        let mut b = Vec::with_capacity(DATA_HEADER);
1113                        conn.write_data(&[], now, &mut b);
1114                        self.out.push_back(b);
1115                    }
1116                }
1117                self.drain();
1118            }
1119            _ => {}
1120        }
1121    }
1122
1123    /// send a message -> its sequence number (Size: empty or over the server's limit;
1124    /// NotConnected before Connected and after the end)
1125    pub fn send(&mut self, payload: &[u8], now: u64) -> Result<u16, Error> {
1126        let Phase::Connected { conn, max_send } = &mut self.phase else { return Err(Error::NotConnected) };
1127        if payload.is_empty() || payload.len() > *max_send {
1128            return Err(Error::Size);
1129        }
1130        let mut b = Vec::with_capacity(DATA_HEADER + payload.len());
1131        let seq = conn.write_data(payload, now, &mut b);
1132        self.out.push_back(b);
1133        self.drain();
1134        Ok(seq)
1135    }
1136
1137    /// send a message on the reliable channel: any size up to max_message, cut into chunks of
1138    /// a packet each, in order, over UDP sent again until the server has it; it goes out at
1139    /// reliable_bytes_per_s (Size: empty or over max_message; Backlog: more than
1140    /// max_reliable_queued would wait; NotConnected before Connected and after the end)
1141    pub fn send_reliable(&mut self, payload: &[u8], now: u64) -> Result<(), Error> {
1142        let Phase::Connected { conn, max_send } = &mut self.phase else { return Err(Error::NotConnected) };
1143        conn.send_reliable(payload, max_send.saturating_sub(CHUNK_HEAD))?;
1144        self.flush(now);
1145        self.drain();
1146        Ok(())
1147    }
1148
1149    // the RELIABLE packets that are due
1150    fn flush(&mut self, now: u64) {
1151        let Phase::Connected { conn, max_send } = &mut self.phase else { return };
1152        loop {
1153            let mut b = Vec::new();
1154            if conn.write_reliable(now, *max_send, &mut b).is_none() {
1155                break;
1156            }
1157            self.out.push_back(b);
1158        }
1159    }
1160
1161    // the server broke the protocol: a DISCONNECT and the end
1162    fn abort(&mut self) {
1163        if let Phase::Connected { conn, .. } = &mut self.phase {
1164            let mut b = Vec::new();
1165            conn.write_disconnect(packet::BYE_PROTOCOL, &mut b);
1166            for _ in 0..if self.stream { 1 } else { BYE_COPIES } {
1167                self.out.push_back(b.clone());
1168            }
1169        }
1170        self.end(Reason::Protocol);
1171    }
1172
1173    /// end the connection (DISCONNECT goes out; UDP several times)
1174    pub fn disconnect(&mut self) {
1175        if let Phase::Connected { conn, .. } = &mut self.phase {
1176            let mut b = Vec::new();
1177            conn.write_disconnect(packet::BYE_NORMAL, &mut b);
1178            for _ in 0..if self.stream { 1 } else { BYE_COPIES } {
1179                self.out.push_back(b.clone());
1180            }
1181        }
1182        self.end(Reason::Local);
1183    }
1184
1185    /// the transport under a stream ended (the WebSocket closed with `code`)
1186    pub fn transport_closed(&mut self, code: u16) {
1187        self.end(Reason::Closed(code));
1188    }
1189
1190    /// the next packet to send to the server
1191    pub fn take_out(&mut self) -> Option<Vec<u8>> {
1192        self.out.pop_front()
1193    }
1194
1195    /// the next event
1196    pub fn poll_event(&mut self) -> Option<ClientEvent> {
1197        self.events.pop_front()
1198    }
1199
1200    /// where it stands
1201    pub fn state(&self) -> State {
1202        match &self.phase {
1203            Phase::Idle | Phase::Connecting { .. } => State::Connecting,
1204            Phase::Connected { .. } => State::Connected,
1205            Phase::Done(r) => State::Disconnected(r.clone()),
1206        }
1207    }
1208
1209    /// the largest payload the server takes (0 before Connected)
1210    pub fn max_payload(&self) -> usize {
1211        match &self.phase {
1212            Phase::Connected { max_send, .. } => *max_send,
1213            _ => 0,
1214        }
1215    }
1216
1217    /// whether the transport is reliable (a WebSocket)
1218    pub fn reliable(&self) -> bool {
1219        self.stream
1220    }
1221
1222    /// the connection's counts (zeros before Connected)
1223    pub fn stats(&self) -> Stats {
1224        match &self.phase {
1225            Phase::Connected { conn, .. } => conn.stats(),
1226            _ => Stats::default(),
1227        }
1228    }
1229}
1230
1231impl Drop for ClientCore {
1232    fn drop(&mut self) {
1233        crypto::zeroize(&mut self.eph);
1234    }
1235}