Skip to main content

netchan/
server.rs

1// server -- a game server's channels (G7d): UDP and WebSocket clients in one table
2//
3//   Server::new(ServerConfig) -> Server
4//   server.bind_udp(&addr) -> NetResult<SocketAddr>        a UDP socket with its reading thread
5//   server.listen_ws(&addr, "/game") -> NetResult<SocketAddr>   a netio HTTP server for the
6//                                        WebSockets (404 elsewhere); or server.ws_endpoint() and
7//                                        endpoint.accept(&req) in the app's own handler (with
8//                                        its page's files beside it, say)
9//   server.poll() -> Option<ServerEvent>   send(id, payload) -> seq   disconnect(id)
10//   server.send_reliable(id, message)      the reliable channel (ClientEvent::Reliable at the client)
11//   server.wait(ms)                        sleep until something arrives (a loop without a tick)
12//   connections() / ids() / stats(id) / peer(id) / server_stats() / stop()
13//   set_static_key(secret) / public_key()  the key clients may pin (ClientConfig::server_key)
14//
15// Threads: one reads the UDP socket; each WebSocket has a reading one (netio's thread of the
16// upgrade) and a writing one, so neither a full socket buffer nor a slow client holds the
17// game's loop.  What they read goes into one bounded queue (UDP drops when it is full, a
18// WebSocket waits); poll() takes it on the caller's thread, where the protocol runs
19// (endpoint::ServerCore).  send to a WebSocket client with LINK_UNSENT bytes waiting fails with
20// Error::Backlog; one that still does not take what the server's own packets add is closed.
21
22use alloc::collections::{BTreeMap, VecDeque};
23use alloc::string::String;
24use alloc::sync::Arc;
25use alloc::vec::Vec;
26use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
27
28use netio::ws::{self as nws, Message};
29use netio::{Request, Response};
30use plat::net::{NetResult, SocketAddr, UdpSocket};
31use plat::sync::{channel, Condvar, Mutex, Receiver, Sender};
32
33use crate::conn::Stats;
34use crate::endpoint::{Out, Route, ServerConfig, ServerCore, ServerEvent, ServerStats};
35use crate::packet::{self, DATA_HEADER};
36use crate::{Error, Transport};
37
38/// what the reading threads keep until poll takes it
39const QUEUE: usize = 8192;
40/// bytes a WebSocket client may have waiting to be written; more close it
41pub const LINK_UNSENT: usize = 1 << 20;
42/// what poll takes from the queue at most per call
43const POLL_TAKE: usize = 4096;
44
45enum Inbound {
46    Datagram(SocketAddr, Vec<u8>),
47    Open(u32, Option<SocketAddr>),
48    Msg(u32, Vec<u8>),
49    Closed(u32, u16),
50}
51
52struct LinkQ {
53    q: VecDeque<Vec<u8>>,
54    bytes: usize,
55    close: bool,
56    gone: bool,
57}
58
59// the writing side of one WebSocket
60struct Link {
61    q: Mutex<LinkQ>,
62    cv: Condvar,
63    close_since: AtomicU64,
64}
65
66impl Link {
67    fn push(&self, b: Vec<u8>) -> bool {
68        let mut q = self.q.lock();
69        if q.close || q.gone {
70            return true;
71        }
72        if q.bytes + b.len() > LINK_UNSENT {
73            return false;
74        }
75        q.bytes += b.len();
76        q.q.push_back(b);
77        drop(q);
78        self.cv.notify_all();
79        true
80    }
81
82    fn unsent(&self) -> usize {
83        self.q.lock().bytes
84    }
85
86    fn close(&self) {
87        self.q.lock().close = true;
88        let _ = self.close_since.compare_exchange(0, plat::time_us().max(1), Ordering::AcqRel, Ordering::Acquire);
89        self.cv.notify_all();
90    }
91}
92
93struct Shared {
94    tx: Sender<Inbound>,
95    links: Mutex<BTreeMap<u32, Arc<Link>>>,
96    next_stream: AtomicU32,
97    acceptor: nws::Acceptor,
98    stop: AtomicBool,
99}
100
101/// what an HTTP handler needs to hand WebSockets to a Server (clone it into the handler)
102#[derive(Clone)]
103pub struct WsEndpoint(Arc<Shared>);
104
105impl WsEndpoint {
106    /// answer an upgrade request on the game's path: 101 and the client joins the server's
107    /// table once it sent CONNECT, or the Acceptor's 4xx / 503
108    pub fn accept(&self, req: &Request) -> Response {
109        let sh = self.0.clone();
110        self.0.acceptor.accept(req, move |ws| ws_conn(ws, sh))
111    }
112
113    /// WebSockets open now (also those that have not sent CONNECT yet)
114    pub fn connections(&self) -> usize {
115        self.0.acceptor.connections()
116    }
117}
118
119// queue what a reader read: wait while the queue is full, unless the server stops
120fn queue(sh: &Shared, mut v: Inbound) -> bool {
121    loop {
122        match sh.tx.try_send(v) {
123            Ok(()) => return true,
124            Err(back) => {
125                if sh.stop.load(Ordering::Acquire) {
126                    return false;
127                }
128                v = back;
129                plat::sleep_ms(1);
130            }
131        }
132    }
133}
134
135// one WebSocket: its link and writer, then reading until it ends (netio's thread of the upgrade)
136fn ws_conn(ws: nws::WebSocket, sh: Arc<Shared>) {
137    let id = sh.next_stream.fetch_add(1, Ordering::Relaxed);
138    let ws = Arc::new(ws);
139    let link = Arc::new(Link { q: Mutex::new(LinkQ { q: VecDeque::new(), bytes: 0, close: false, gone: false }), cv: Condvar::new(), close_since: AtomicU64::new(0) });
140    sh.links.lock().insert(id, link.clone());
141    let (w, l) = (ws.clone(), link.clone());
142    if !queue(&sh, Inbound::Open(id, ws.peer())) || !crate::reap::spawn(128 * 1024, move || ws_writer(w, l)) {
143        sh.links.lock().remove(&id);
144        ws.close(nws::CLOSE_INTERNAL, "");
145        return;
146    }
147    let code = loop {
148        match ws.recv_timeout(Some(200)) {
149            Ok(Some(Message::Binary(b))) => {
150                if !queue(&sh, Inbound::Msg(id, b)) {
151                    break nws::CLOSE_GOING_AWAY;
152                }
153            }
154            Ok(Some(Message::Text(_))) => {
155                ws.close(nws::CLOSE_UNSUPPORTED, "binary only");
156                break nws::CLOSE_UNSUPPORTED;
157            }
158            Ok(None) => {
159                let since = link.close_since.load(Ordering::Acquire);
160                if since != 0 && plat::time_us().saturating_sub(since) > 1_000_000 {
161                    break nws::CLOSE_NORMAL;
162                }
163            }
164            Err(nws::WsError::Closed(c, _)) => break c,
165            Err(nws::WsError::Protocol(c)) => break c,
166            Err(_) => break nws::CLOSE_ABNORMAL,
167        }
168    };
169    {
170        let mut q = link.q.lock();
171        q.gone = true;
172    }
173    link.cv.notify_all();
174    sh.links.lock().remove(&id);
175    queue(&sh, Inbound::Closed(id, code));
176}
177
178// write what the server queued for one WebSocket; close when asked
179fn ws_writer(ws: Arc<nws::WebSocket>, link: Arc<Link>) {
180    loop {
181        let job = {
182            let mut q = link.q.lock();
183            loop {
184                if let Some(b) = q.q.pop_front() {
185                    q.bytes -= b.len();
186                    break Some(b);
187                }
188                if q.close || q.gone {
189                    break None;
190                }
191                q = link.cv.wait_timeout(q, Some(1000)).0;
192            }
193        };
194        match job {
195            Some(b) => {
196                if ws.send_binary(&b).is_err() {
197                    return;
198                }
199            }
200            None => {
201                if link.q.lock().close {
202                    ws.close(nws::CLOSE_NORMAL, "");
203                }
204                return;
205            }
206        }
207    }
208}
209
210/// a game server's channels (see the top of this file).  Dropping it stops it
211pub struct Server {
212    core: ServerCore,
213    sh: Arc<Shared>,
214    rx: Receiver<Inbound>,
215    udp: Option<(Arc<UdpSocket>, Arc<AtomicBool>, plat::Thread)>,
216    http: Option<netio::Server>,
217}
218
219impl Server {
220    /// a server with these limits and no transport yet (bind_udp, listen_ws, ws_endpoint)
221    pub fn new(cfg: ServerConfig) -> Server {
222        let (tx, rx) = channel(QUEUE);
223        let lim = nws::Limits {
224            max_message: cfg.max_stream_payload + DATA_HEADER,
225            max_frame: cfg.max_stream_payload + DATA_HEADER,
226            messages_per_s: cfg.packets_per_s.saturating_mul(2).saturating_add(16),
227            bytes_per_s: cfg.bytes_per_s.saturating_mul(2).saturating_add(64 * 1024),
228            idle_ms: cfg.timeout_ms.saturating_mul(2),
229            ping_ms: 0,
230            max_connections: cfg.max_connections.saturating_mul(2),
231            ..nws::Limits::default()
232        };
233        let sh = Arc::new(Shared { tx, links: Mutex::new(BTreeMap::new()), next_stream: AtomicU32::new(1), acceptor: nws::Acceptor::new(lim), stop: AtomicBool::new(false) });
234        let mut secret = plat::random_bytes::<32>();
235        let core = ServerCore::new(cfg, secret, plat::time_us());
236        crypto::zeroize(&mut secret);
237        Server { core, sh, rx, udp: None, http: None }
238    }
239
240    /// listen for UDP clients on `addr` (port 0: a free one) -> the address it got
241    pub fn bind_udp(&mut self, addr: &SocketAddr) -> NetResult<SocketAddr> {
242        let sock = Arc::new(UdpSocket::bind(addr)?);
243        let local = sock.local_addr()?;
244        let stop = Arc::new(AtomicBool::new(false));
245        let (s, st, sh) = (sock.clone(), stop.clone(), self.sh.clone());
246        // (larger than a packet can be: dropped before the queue, which held up to 512 MiB of them)
247        let max = packet::max_datagram(self.core.config().max_payload);
248        let t = plat::thread_spawn(
249            128 * 1024,
250            alloc::boxed::Box::new(move || {
251                let mut buf = alloc::vec![0u8; 65536];
252                while !st.load(Ordering::Acquire) {
253                    match s.recv_from(&mut buf, 100) {
254                        // (the queue full: dropped, as the network would)
255                        Ok((n, from)) if n <= max => {
256                            let _ = sh.tx.try_send(Inbound::Datagram(from, buf[..n].to_vec()));
257                        }
258                        Ok(_) => {}
259                        Err(e) if e.kind == plat::net::NetErrorKind::TimedOut => {}
260                        Err(_) => plat::sleep_ms(5),
261                    }
262                }
263            }),
264        )
265        .ok_or(plat::net::NetError::new(plat::net::NetErrorKind::Other, 0))?;
266        if let Some((_, old, t)) = self.udp.replace((sock, stop, t)) {
267            old.store(true, Ordering::Release);
268            t.join();
269        }
270        Ok(local)
271    }
272
273    /// the handle an HTTP handler hands WebSockets in with
274    pub fn ws_endpoint(&self) -> WsEndpoint {
275        WsEndpoint(self.sh.clone())
276    }
277
278    /// a netio HTTP server on `addr` whose `path` takes the WebSockets (404 elsewhere) -> its
279    /// address
280    pub fn listen_ws(&mut self, addr: &SocketAddr, path: &str) -> NetResult<SocketAddr> {
281        let ep = self.ws_endpoint();
282        let path = String::from(path);
283        let handler: netio::server::Handler = Arc::new(move |req: &Request| if req.path() == path { ep.accept(req) } else { Response::new(404) });
284        let cfg = netio::ServerConfig { threads: 4, max_body: 0, idle_ms: 5000, read_ms: 5000, ..netio::ServerConfig::default() };
285        let s = netio::Server::start(addr, cfg, handler)?;
286        let a = s.local_addr();
287        if let Some(old) = self.http.replace(s) {
288            old.stop();
289        }
290        Ok(a)
291    }
292
293    /// the UDP socket's address
294    pub fn udp_addr(&self) -> Option<SocketAddr> {
295        self.udp.as_ref().and_then(|(s, _, _)| s.local_addr().ok())
296    }
297
298    /// the address of listen_ws's HTTP server
299    pub fn ws_addr(&self) -> Option<SocketAddr> {
300        self.http.as_ref().map(|h| h.local_addr())
301    }
302
303    fn take(&mut self, i: Inbound, now: u64) {
304        match i {
305            Inbound::Datagram(from, d) => self.core.datagram(from, &d, now),
306            Inbound::Open(s, a) => self.core.stream_open(s, a, now),
307            Inbound::Msg(s, d) => self.core.stream_message(s, &d, now),
308            Inbound::Closed(s, c) => self.core.stream_closed(s, c),
309        }
310    }
311
312    fn take_in(&mut self, now: u64) {
313        for _ in 0..POLL_TAKE {
314            let Some(i) = self.rx.try_recv() else { break };
315            self.take(i, now);
316        }
317    }
318
319    /// sleep until a datagram or a WebSocket message arrives, at most `ms` (a server without a
320    /// tick of its own; keep `ms` below keepalive_ms).  poll() then reports it
321    pub fn wait(&mut self, ms: u32) {
322        if let Ok(i) = self.rx.recv_timeout(ms) {
323            self.take(i, plat::time_us());
324        }
325    }
326
327    fn flush(&mut self) {
328        let mut full: Vec<u32> = Vec::new();
329        while let Some(o) = self.core.take_out() {
330            match o {
331                Out::Send(Route::Udp(a), b) => {
332                    if let Some((s, _, _)) = &self.udp {
333                        let _ = s.send_to(&b, &a);
334                    }
335                }
336                Out::Send(Route::Stream(id), b) => {
337                    let link = self.sh.links.lock().get(&id).cloned();
338                    if let Some(l) = link {
339                        if !l.push(b) {
340                            full.push(id);
341                        }
342                    }
343                }
344                Out::Close(id) => {
345                    if let Some(l) = self.sh.links.lock().get(&id) {
346                        l.close();
347                    }
348                }
349            }
350        }
351        // a client that does not take what it is sent: closed (Disconnected(Closed) follows)
352        for id in full {
353            if let Some(l) = self.sh.links.lock().get(&id) {
354                l.close();
355            }
356        }
357    }
358
359    /// the next event; call it until None every tick (it takes what came, sends keep-alives,
360    /// ends connections that timed out)
361    pub fn poll(&mut self) -> Option<ServerEvent> {
362        if let Some(e) = self.core.poll_event() {
363            return Some(e);
364        }
365        let now = plat::time_us();
366        self.take_in(now);
367        self.core.tick(now);
368        self.flush();
369        self.core.poll_event()
370    }
371
372    /// send a message to a client -> its sequence number (Backlog: a WebSocket client has
373    /// LINK_UNSENT bytes waiting)
374    pub fn send(&mut self, id: u32, payload: &[u8]) -> Result<u16, Error> {
375        if let Some(Route::Stream(s)) = self.core.route(id) {
376            let link = self.sh.links.lock().get(&s).cloned();
377            if link.is_some_and(|l| l.unsent() + payload.len() + DATA_HEADER > LINK_UNSENT) {
378                return Err(Error::Backlog);
379            }
380        }
381        let seq = self.core.send(id, payload, plat::time_us())?;
382        self.flush();
383        Ok(seq)
384    }
385
386    /// send a message on a client's reliable channel: any size up to ServerConfig::max_message,
387    /// in order, over UDP sent again until the client has it (endpoint::ServerCore::send_reliable).
388    /// It goes out at reliable_bytes_per_s, the rest with the next polls
389    pub fn send_reliable(&mut self, id: u32, payload: &[u8]) -> Result<(), Error> {
390        self.core.send_reliable(id, payload, plat::time_us())?;
391        self.flush();
392        Ok(())
393    }
394
395    /// end a client's connection (Disconnected(Local) follows)
396    pub fn disconnect(&mut self, id: u32) {
397        self.core.disconnect(id, packet::BYE_NORMAL);
398        self.flush();
399    }
400
401    /// a long-lived X25519 secret (32 random bytes the app made once and keeps): clients with its
402    /// public key in ClientConfig::server_key can tell this server from anyone in its place
403    /// (endpoint::ServerCore::set_static_key)
404    pub fn set_static_key(&mut self, secret: [u8; 32]) {
405        self.core.set_static_key(secret);
406    }
407
408    /// the public key of set_static_key, for the clients
409    pub fn public_key(&self) -> Option<[u8; 32]> {
410        self.core.public_key()
411    }
412
413    /// connections now
414    pub fn connections(&self) -> usize {
415        self.core.connections()
416    }
417
418    /// the ids of the connections
419    pub fn ids(&self) -> Vec<u32> {
420        self.core.ids()
421    }
422
423    /// a connection's counts and round-trip time
424    pub fn stats(&self, id: u32) -> Option<Stats> {
425        self.core.stats(id)
426    }
427
428    /// a connection's transport and address
429    pub fn peer(&self, id: u32) -> Option<(Transport, Option<SocketAddr>)> {
430        self.core.peer(id)
431    }
432
433    /// what the server counted beyond its connections
434    pub fn server_stats(&self) -> ServerStats {
435        self.core.server_stats()
436    }
437
438    /// end every connection, stop the threads and the HTTP server
439    pub fn stop(self) {}
440
441    fn shutdown(&mut self) {
442        self.core.disconnect_all();
443        self.flush();
444        self.sh.stop.store(true, Ordering::Release);
445        if let Some(h) = self.http.take() {
446            h.stop();
447        }
448        if let Some((_, stop, t)) = self.udp.take() {
449            stop.store(true, Ordering::Release);
450            t.join();
451        }
452    }
453}
454
455impl Drop for Server {
456    fn drop(&mut self) {
457        self.shutdown();
458    }
459}