Skip to main content

netchan/
client.rs

1// client -- a game client's channel to its server (G7d)
2//
3//   Client::connect(Endpoint, ClientConfig) -> Result<Client, Error>    Connecting at once
4//   client.poll() -> Option<ClientEvent>    every frame until None: reads, keep-alives, timeouts
5//   client.send(payload) -> Result<u16, Error>    the message's sequence number
6//   client.send_reliable(message) -> Result<(), Error>    the reliable channel (ClientEvent::Reliable
7//                                           on the other side); poll() sends what is due
8//   client.state() / reliable() / max_payload() / stats() / rtt_ms() / disconnect()
9//
10// Nothing blocks.  UDP (Windows, Linux, Apple): a thread of its own reads the socket, keeps only
11// the server's datagrams (a bounded queue) and wakes the UI (plat::wake); sends go out at once.
12// WebSocket: netchan::ws (the browser's own, or netio's on threads); a packet of the client's own
13// that it cannot queue (max_unsent bytes waiting) ends the connection, Disconnected(Closed(1011)).
14// In the browser only Endpoint::WebSocket exists; on Android nothing yet (Unsupported).
15
16use alloc::string::String;
17
18use crate::endpoint::{ClientConfig, ClientCore, ClientEvent, State};
19use crate::packet::DATA_HEADER;
20use crate::ws::{WebSocket, WsMessage, WsOptions, WsState};
21use crate::{Error, Stats};
22
23#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
24use alloc::{collections::VecDeque, sync::Arc, vec::Vec};
25#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
26use core::sync::atomic::{AtomicBool, Ordering};
27
28/// datagrams the UDP thread keeps until poll takes them
29#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
30const UDP_QUEUE: usize = 4096;
31
32/// the close code when the WebSocket cannot take the client's own packets (RFC 6455: an
33/// unexpected condition); Disconnected(Closed(1011)) tells the app
34const CLOSE_BACKLOG: u16 = 1011;
35
36/// where a client connects to
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum Endpoint {
39    /// a server's UDP socket (not in the browser)
40    Udp(plat::net::SocketAddr),
41    /// a server's WebSocket: ws://host:port/path, wss://..., in the browser also "/path"
42    WebSocket(String),
43}
44
45#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
46struct Udp {
47    sock: Arc<plat::net::UdpSocket>,
48    server: plat::net::SocketAddr,
49    inbox: Arc<plat::sync::Mutex<VecDeque<Vec<u8>>>>,
50    stop: Arc<AtomicBool>,
51}
52
53enum Io {
54    #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
55    Udp(Udp),
56    Ws { ws: WebSocket, started: bool, max_unsent: usize },
57}
58
59/// a client's channel (see the top of this file)
60pub struct Client {
61    core: ClientCore,
62    io: Io,
63}
64
65fn now() -> u64 {
66    plat::time_us()
67}
68
69#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
70fn udp_reader(sock: Arc<plat::net::UdpSocket>, server: plat::net::SocketAddr, inbox: Arc<plat::sync::Mutex<VecDeque<Vec<u8>>>>, stop: Arc<AtomicBool>, max: usize) {
71    let mut buf = alloc::vec![0u8; 65536];
72    while !stop.load(Ordering::Acquire) {
73        match sock.recv_from(&mut buf, 100) {
74            // (larger than a packet of the server can be: dropped before the queue, which held up to
75            // 256 MiB of them)
76            Ok((n, from)) if from == server && n <= max => {
77                let mut q = inbox.lock();
78                if q.len() < UDP_QUEUE {
79                    q.push_back(buf[..n].to_vec());
80                }
81                drop(q);
82                plat::wake();
83            }
84            Ok(_) => {}
85            Err(e) if e.kind == plat::net::NetErrorKind::TimedOut => {}
86            // (Windows reports an ICMP port unreachable of an earlier send as a reset)
87            Err(_) => plat::sleep_ms(5),
88        }
89    }
90}
91
92impl Client {
93    /// connect: the handshake starts at once (UDP) or once the WebSocket is open; poll() reports
94    /// Connected or Disconnected(reason)
95    pub fn connect(ep: Endpoint, cfg: ClientConfig) -> Result<Client, Error> {
96        match ep {
97            Endpoint::Udp(addr) => {
98                #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
99                {
100                    use plat::net::{IpAddr, SocketAddr, UdpSocket};
101                    if !plat::policy::net_connect_allowed(&addr) {
102                        return Err(Error::Net(plat::net::NetError::new(plat::net::NetErrorKind::Denied, 0)));
103                    }
104                    let any = if matches!(addr.ip, IpAddr::V4(_)) { IpAddr::UNSPECIFIED_V4 } else { IpAddr::V6([0; 16]) };
105                    let sock = Arc::new(UdpSocket::bind(&SocketAddr::new(any, 0))?);
106                    let inbox = Arc::new(plat::sync::Mutex::new(VecDeque::new()));
107                    let stop = Arc::new(AtomicBool::new(false));
108                    let (s, i, st) = (sock.clone(), inbox.clone(), stop.clone());
109                    let max = crate::packet::max_datagram(cfg.max_payload.clamp(1, crate::packet::MAX_UDP_PAYLOAD));
110                    if !crate::reap::spawn(128 * 1024, move || udp_reader(s, addr, i, st, max)) {
111                        return Err(Error::Net(plat::net::NetError::new(plat::net::NetErrorKind::Other, 0)));
112                    }
113                    let mut core = ClientCore::new(cfg, plat::random_bytes::<32>(), false);
114                    core.start(now());
115                    let mut c = Client { core, io: Io::Udp(Udp { sock, server: addr, inbox, stop }) };
116                    c.flush();
117                    Ok(c)
118                }
119                #[cfg(not(any(windows, target_os = "linux", target_vendor = "apple")))]
120                {
121                    let _ = (addr, cfg);
122                    Err(Error::Unsupported)
123                }
124            }
125            Endpoint::WebSocket(url) => {
126                let o = WsOptions { max_message: cfg.max_payload + DATA_HEADER, connect_ms: cfg.connect_ms, idle_ms: cfg.timeout_ms.saturating_mul(2), ping_ms: 0, ..WsOptions::default() };
127                let ws = WebSocket::connect_with(&url, o)?;
128                Ok(Client { core: ClientCore::new(cfg, ws_random(), true), io: Io::Ws { ws, started: false, max_unsent: o.max_unsent } })
129            }
130        }
131    }
132
133    // what came, the clock, what is to send
134    fn pump(&mut self) {
135        let t = now();
136        match &mut self.io {
137            #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
138            Io::Udp(u) => {
139                let got: Vec<Vec<u8>> = u.inbox.lock().drain(..).collect();
140                for d in got {
141                    self.core.packet(&d, t);
142                }
143            }
144            Io::Ws { ws, started, .. } => {
145                if !*started && ws.state() == WsState::Open {
146                    *started = true;
147                    self.core.start(t);
148                }
149                while let Some(m) = ws.recv() {
150                    if let WsMessage::Binary(b) = m {
151                        self.core.packet(&b, t);
152                    }
153                }
154                if ws.state() == WsState::Closed {
155                    let code = ws.close_info().map(|c| c.0).unwrap_or(1006);
156                    self.core.transport_closed(code);
157                }
158            }
159        }
160        self.core.tick(t);
161        self.flush();
162    }
163
164    fn flush(&mut self) {
165        while let Some(b) = self.core.take_out() {
166            match &self.io {
167                #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
168                Io::Udp(u) => {
169                    let _ = u.sock.send_to(&b, &u.server);
170                }
171                Io::Ws { ws, .. } => match ws.send_binary(&b) {
172                    Ok(()) => {}
173                    // over a stream an ack says that everything before it came: a packet that is
174                    // not sent may not leave a gap (Delivered for it, the server waiting for a
175                    // chunk forever).  One the WebSocket cannot queue (WsOptions::max_unsent
176                    // bytes waiting: the reliable channel, acks, keep-alives) ends the
177                    // connection, as the server ends one that does not take what it is sent
178                    Err(Error::Backlog) => {
179                        ws.close(CLOSE_BACKLOG, "backlog");
180                        self.core.transport_closed(CLOSE_BACKLOG);
181                        while self.core.take_out().is_some() {}
182                        return;
183                    }
184                    // (not open: it is ending, and pump reports how; nothing after it goes out)
185                    Err(_) => {
186                        while self.core.take_out().is_some() {}
187                        return;
188                    }
189                },
190            }
191        }
192    }
193
194    /// the next event; call it until None every frame (it reads, sends keep-alives, notices
195    /// timeouts)
196    pub fn poll(&mut self) -> Option<ClientEvent> {
197        if let Some(e) = self.core.poll_event() {
198            return Some(e);
199        }
200        self.pump();
201        self.core.poll_event()
202    }
203
204    /// send a message -> its sequence number (Delivered / Lost name it later; Backlog: the
205    /// WebSocket has WsOptions::max_unsent bytes waiting, nothing was sent)
206    pub fn send(&mut self, payload: &[u8]) -> Result<u16, Error> {
207        let backlog = match &self.io {
208            Io::Ws { ws, max_unsent, .. } => ws.unsent() + payload.len() + DATA_HEADER > *max_unsent,
209            #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
210            Io::Udp(_) => false,
211        };
212        if backlog {
213            return Err(Error::Backlog);
214        }
215        let seq = self.core.send(payload, now())?;
216        self.flush();
217        Ok(seq)
218    }
219
220    /// send a message on the reliable channel: any size up to ClientConfig::max_message, in
221    /// order, over UDP sent again until the server has it (endpoint::ClientCore::send_reliable).
222    /// It goes out at reliable_bytes_per_s, the rest with the next polls
223    pub fn send_reliable(&mut self, payload: &[u8]) -> Result<(), Error> {
224        self.core.send_reliable(payload, now())?;
225        self.flush();
226        Ok(())
227    }
228
229    /// where it stands
230    pub fn state(&self) -> State {
231        self.core.state()
232    }
233
234    /// whether the transport is reliable and ordered (a WebSocket)
235    pub fn reliable(&self) -> bool {
236        self.core.reliable()
237    }
238
239    /// the largest payload the server takes (0 before Connected)
240    pub fn max_payload(&self) -> usize {
241        self.core.max_payload()
242    }
243
244    /// the connection's counts
245    pub fn stats(&self) -> Stats {
246        self.core.stats()
247    }
248
249    /// the smoothed round-trip time in ms (0 before the first ack)
250    pub fn rtt_ms(&self) -> f32 {
251        self.core.stats().rtt_ms
252    }
253
254    /// end the connection (DISCONNECT goes out; Disconnected(Local) follows)
255    pub fn disconnect(&mut self) {
256        self.core.disconnect();
257        self.flush();
258        match &self.io {
259            Io::Ws { ws, .. } => ws.close(1000, ""),
260            #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
261            Io::Udp(_) => {}
262        }
263    }
264}
265
266impl Drop for Client {
267    fn drop(&mut self) {
268        if self.core.state() == State::Connected {
269            self.disconnect();
270        }
271        #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
272        if let Io::Udp(u) = &self.io {
273            u.stop.store(true, Ordering::Release);
274        }
275    }
276}
277
278// the random bytes of a WebSocket attempt (only its nonce comes from them): random where the
279// system has a generator; the browser's needs none that is secret (TCP proved the address, and a
280// WebSocket has no keys of its own)
281fn ws_random() -> [u8; 32] {
282    #[cfg(any(windows, target_os = "linux", target_vendor = "apple", target_os = "android"))]
283    {
284        plat::random_bytes::<32>()
285    }
286    #[cfg(not(any(windows, target_os = "linux", target_vendor = "apple", target_os = "android")))]
287    {
288        let mut r = [0u8; 32];
289        r[..8].copy_from_slice(&(plat::time_us() ^ 0x9e37_79b9_7f4a_7c15).to_le_bytes());
290        r
291    }
292}