ferravex_net/websocket/
gateway.rs

1use super::*;
2use std::{
3    collections::VecDeque,
4    io::{self, Read, Write},
5    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpListener, TcpStream, UdpSocket},
6    time::{Duration, Instant},
7};
8const MAX_CONNECTIONS: usize = 16;
9const MAX_PENDING: usize = 64 * 1024;
10#[derive(Clone, Debug)]
11pub struct Config {
12    pub bind: SocketAddr,
13    pub authority: SocketAddr,
14    pub allowed_origins: Vec<String>,
15}
16impl Config {
17    pub fn new(bind: SocketAddr, mut authority: SocketAddr) -> Self {
18        if authority.ip().is_unspecified() {
19            authority.set_ip(if authority.is_ipv4() {
20                IpAddr::V4(Ipv4Addr::LOCALHOST)
21            } else {
22                IpAddr::V6(Ipv6Addr::LOCALHOST)
23            });
24        }
25        Self {
26            bind,
27            authority,
28            allowed_origins: vec![
29                "http://127.0.0.1:8087".into(),
30                "http://localhost:8087".into(),
31                "http://[::1]:8087".into(),
32            ],
33        }
34    }
35}
36#[derive(Clone, Copy, Debug, Default)]
37pub struct Stats {
38    pub accepted: u64,
39    pub closed: u64,
40    pub rejected: u64,
41    pub io_errors: u64,
42    pub client_bytes: u64,
43    pub authority_bytes: u64,
44}
45/// Nonblocking first-party WebSocket → UDP bridge. Each browser gets a distinct
46/// UDP endpoint/session at the existing authority. Call poll before/after its
47/// fixed tick. The bridge never computes movement, accepts hits or invents ACKs.
48pub struct Gateway {
49    listener: TcpListener,
50    config: Config,
51    peers: Vec<Peer>,
52    stats: Stats,
53}
54impl Gateway {
55    pub fn bind(config: Config) -> io::Result<Self> {
56        if config.authority.port() == 0
57            || config.allowed_origins.len() > 32
58            || config
59                .allowed_origins
60                .iter()
61                .any(|s| s.len() > 512 || s.bytes().any(|b| b < 32 || b == 127))
62        {
63            return Err(io::Error::new(
64                io::ErrorKind::InvalidInput,
65                "invalid gateway configuration",
66            ));
67        }
68        let listener = TcpListener::bind(config.bind)?;
69        listener.set_nonblocking(true)?;
70        Ok(Self {
71            listener,
72            config,
73            peers: Vec::with_capacity(MAX_CONNECTIONS),
74            stats: Stats::default(),
75        })
76    }
77    pub fn local_addr(&self) -> io::Result<SocketAddr> {
78        self.listener.local_addr()
79    }
80    pub fn connection_count(&self) -> usize {
81        self.peers.len()
82    }
83    pub fn stats(&self) -> Stats {
84        self.stats
85    }
86    pub fn poll(&mut self) -> io::Result<()> {
87        for _ in 0..4 {
88            let (stream, _) = match self.listener.accept() {
89                Ok(v) => v,
90                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
91                Err(e) => return Err(e),
92            };
93            if self.peers.len() == MAX_CONNECTIONS {
94                self.stats.rejected += 1;
95                continue;
96            }
97            match Peer::new(stream, self.config.authority) {
98                Ok(peer) => {
99                    self.peers.push(peer);
100                    self.stats.accepted += 1;
101                }
102                Err(_) => self.stats.io_errors += 1,
103            }
104        }
105        let origins = &self.config.allowed_origins;
106        let stats = &mut self.stats;
107        self.peers
108            .retain_mut(|peer| match peer.poll(origins, stats) {
109                Ok(true) => true,
110                Ok(false) => {
111                    stats.closed += 1;
112                    false
113                }
114                Err(_) => {
115                    stats.closed += 1;
116                    stats.io_errors += 1;
117                    false
118                }
119            });
120        Ok(())
121    }
122}
123struct Peer {
124    tcp: TcpStream,
125    udp: UdpSocket,
126    decoder: Decoder,
127    ready: bool,
128    created: Instant,
129    last: Instant,
130    closing: Option<Instant>,
131    out: VecDeque<Vec<u8>>,
132    offset: usize,
133    pending: usize,
134}
135impl Peer {
136    fn new(tcp: TcpStream, authority: SocketAddr) -> io::Result<Self> {
137        tcp.set_nonblocking(true)?;
138        tcp.set_nodelay(true)?;
139        let udp = UdpSocket::bind(if authority.is_ipv4() {
140            SocketAddr::from(([0, 0, 0, 0], 0))
141        } else {
142            SocketAddr::from((Ipv6Addr::UNSPECIFIED, 0))
143        })?;
144        udp.connect(authority)?;
145        udp.set_nonblocking(true)?;
146        let now = Instant::now();
147        Ok(Self {
148            tcp,
149            udp,
150            decoder: Decoder::default(),
151            ready: false,
152            created: now,
153            last: now,
154            closing: None,
155            out: VecDeque::new(),
156            offset: 0,
157            pending: 0,
158        })
159    }
160    fn queue(&mut self, bytes: Vec<u8>) -> io::Result<()> {
161        if bytes.len() > MAX_PENDING - self.pending || self.out.len() == 256 {
162            return Err(io::Error::new(
163                io::ErrorKind::ConnectionAborted,
164                "WebSocket backpressure limit",
165            ));
166        }
167        self.pending += bytes.len();
168        self.out.push_back(bytes);
169        Ok(())
170    }
171    fn close(&mut self, code: u16) -> io::Result<()> {
172        self.out.clear();
173        self.pending = 0;
174        self.offset = 0;
175        self.closing = Some(Instant::now());
176        self.queue(frame(8, &code.to_be_bytes()))
177    }
178    fn flush(&mut self) -> io::Result<()> {
179        for _ in 0..8 {
180            let Some(bytes) = self.out.front() else { break };
181            match self.tcp.write(&bytes[self.offset..]) {
182                Ok(0) => return Err(io::Error::from(io::ErrorKind::WriteZero)),
183                Ok(n) => {
184                    self.offset += n;
185                    self.pending -= n;
186                    if self.offset == bytes.len() {
187                        self.out.pop_front();
188                        self.offset = 0;
189                    }
190                }
191                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
192                Err(e) => return Err(e),
193            }
194        }
195        Ok(())
196    }
197    fn poll(&mut self, origins: &[String], stats: &mut Stats) -> io::Result<bool> {
198        if self.closing.is_none() {
199            let mut buffer = [0u8; 4096];
200            match self.tcp.read(&mut buffer) {
201                Ok(0) => return Ok(false),
202                Ok(n) => {
203                    if let Err(code) = self.decoder.append(&buffer[..n]) {
204                        stats.rejected += 1;
205                        if self.ready {
206                            self.close(code)?;
207                        } else {
208                            return Ok(false);
209                        }
210                    }
211                }
212                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}
213                Err(e) => return Err(e),
214            }
215            if !self.ready && self.closing.is_none() {
216                if self.created.elapsed() > Duration::from_secs(5) {
217                    return Ok(false);
218                }
219                match handshake(&self.decoder.bytes, origins) {
220                    Ok(Some((used, response))) => {
221                        self.decoder.bytes.drain(..used);
222                        self.queue(response)?;
223                        self.ready = true;
224                        self.last = Instant::now();
225                    }
226                    Ok(None) => {}
227                    Err(code) => {
228                        stats.rejected += 1;
229                        self.closing = Some(Instant::now());
230                        self.queue(format!("HTTP/1.1 {code} Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n").into_bytes())?;
231                    }
232                }
233            }
234            if self.ready && self.closing.is_none() {
235                for _ in 0..16 {
236                    match self.decoder.next() {
237                        Ok(None) => break,
238                        Ok(Some(message)) => {
239                            self.last = Instant::now();
240                            match message {
241                                Message::Binary(bytes) => match self.udp.send(&bytes) {
242                                    Ok(n) => stats.client_bytes += n as u64,
243                                    Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}
244                                    Err(e) => return Err(e),
245                                },
246                                Message::Ping(bytes) => self.queue(frame(10, &bytes))?,
247                                Message::Pong => {}
248                                Message::Close(bytes) => {
249                                    self.out.clear();
250                                    self.offset = 0;
251                                    self.pending = 0;
252                                    self.closing = Some(Instant::now());
253                                    self.queue(frame(8, &bytes))?;
254                                    break;
255                                }
256                            }
257                        }
258                        Err(code) => {
259                            stats.rejected += 1;
260                            self.close(code)?;
261                            break;
262                        }
263                    }
264                }
265                if self.last.elapsed() > Duration::from_secs(10) {
266                    self.close(1001)?;
267                }
268                if self.closing.is_none() {
269                    let mut data = [0u8; MAX_PACKET_BYTES + 1];
270                    for _ in 0..16 {
271                        match self.udp.recv(&mut data) {
272                            Ok(n) if n <= MAX_PACKET_BYTES => {
273                                self.queue(frame(2, &data[..n]))?;
274                                stats.authority_bytes += n as u64;
275                            }
276                            Ok(_) => stats.rejected += 1,
277                            Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
278                            Err(e) => return Err(e),
279                        }
280                    }
281                }
282            }
283        }
284        self.flush()?;
285        Ok(self
286            .closing
287            .is_none_or(|started| self.pending != 0 && started.elapsed() < Duration::from_secs(1)))
288    }
289}
290#[cfg(test)]
291mod tests {
292    use super::*;
293    // A single poll cannot guarantee that loopback TCP bytes have reached the
294    // kernel receive queue, especially on a loaded macOS runner. Keep driving
295    // the nonblocking gateway while awaiting each real transport milestone.
296    fn pump_until<T>(
297        gateway: &mut Gateway,
298        mut receive: impl FnMut() -> io::Result<Option<T>>,
299    ) -> T {
300        let deadline = Instant::now() + Duration::from_secs(3);
301        loop {
302            gateway.poll().unwrap();
303            match receive() {
304                Ok(Some(value)) => return value,
305                Ok(None) => {}
306                Err(error)
307                    if matches!(
308                        error.kind(),
309                        io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
310                    ) => {}
311                Err(error) => panic!("loopback I/O failed: {error}"),
312            }
313            assert!(
314                Instant::now() < deadline,
315                "gateway loopback milestone timed out"
316            );
317            std::thread::sleep(Duration::from_millis(1));
318        }
319    }
320    fn read_until(
321        gateway: &mut Gateway,
322        client: &mut TcpStream,
323        complete: impl Fn(&[u8]) -> bool,
324    ) -> Vec<u8> {
325        let mut bytes = Vec::new();
326        pump_until(gateway, || {
327            let mut part = [0; 4096];
328            let count = client.read(&mut part)?;
329            if count == 0 {
330                return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
331            }
332            bytes.extend_from_slice(&part[..count]);
333            assert!(bytes.len() <= 4096, "unexpected loopback response size");
334            Ok(complete(&bytes).then_some(()))
335        });
336        bytes
337    }
338    #[test]
339    fn actual_tcp_upgrade_binary_udp_return_and_close() {
340        let authority = UdpSocket::bind("127.0.0.1:0").unwrap();
341        authority.set_nonblocking(true).unwrap();
342        let mut gateway = Gateway::bind(Config::new(
343            "127.0.0.1:0".parse().unwrap(),
344            authority.local_addr().unwrap(),
345        ))
346        .unwrap();
347        let mut client = TcpStream::connect(gateway.local_addr().unwrap()).unwrap();
348        client.set_nonblocking(true).unwrap();
349        client.write_all(b"GET /ferravex HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n").unwrap();
350        let header = read_until(&mut gateway, &mut client, |bytes| {
351            bytes.ends_with(b"\r\n\r\n")
352        });
353        assert!(
354            std::str::from_utf8(&header)
355                .unwrap()
356                .contains("101 Switching Protocols")
357        );
358        client
359            .write_all(&super::super::tests::masked(2, true, b"packet"))
360            .unwrap();
361        let mut buf = [0; 4096];
362        let (n, source) = pump_until(&mut gateway, || authority.recv_from(&mut buf).map(Some));
363        assert_eq!(&buf[..n], b"packet");
364        authority.send_to(b"reply", source).unwrap();
365        let reply = frame(2, b"reply");
366        assert_eq!(
367            read_until(&mut gateway, &mut client, |bytes| bytes.len()
368                >= reply.len()),
369            reply
370        );
371        client
372            .write_all(&super::super::tests::masked(
373                8,
374                true,
375                &1000u16.to_be_bytes(),
376            ))
377            .unwrap();
378        let closed = frame(8, &1000u16.to_be_bytes());
379        assert_eq!(
380            read_until(&mut gateway, &mut client, |bytes| bytes.len()
381                >= closed.len()),
382            closed
383        );
384        assert_eq!(gateway.connection_count(), 0);
385        assert_eq!(gateway.stats().client_bytes, 6);
386    }
387}