1use 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
38const QUEUE: usize = 8192;
40pub const LINK_UNSENT: usize = 1 << 20;
42const 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
59struct 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#[derive(Clone)]
103pub struct WsEndpoint(Arc<Shared>);
104
105impl WsEndpoint {
106 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 pub fn connections(&self) -> usize {
115 self.0.acceptor.connections()
116 }
117}
118
119fn 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
135fn 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
178fn 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
210pub 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 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 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 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 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 pub fn ws_endpoint(&self) -> WsEndpoint {
275 WsEndpoint(self.sh.clone())
276 }
277
278 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 pub fn udp_addr(&self) -> Option<SocketAddr> {
295 self.udp.as_ref().and_then(|(s, _, _)| s.local_addr().ok())
296 }
297
298 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 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 for id in full {
353 if let Some(l) = self.sh.links.lock().get(&id) {
354 l.close();
355 }
356 }
357 }
358
359 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 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 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 pub fn disconnect(&mut self, id: u32) {
397 self.core.disconnect(id, packet::BYE_NORMAL);
398 self.flush();
399 }
400
401 pub fn set_static_key(&mut self, secret: [u8; 32]) {
405 self.core.set_static_key(secret);
406 }
407
408 pub fn public_key(&self) -> Option<[u8; 32]> {
410 self.core.public_key()
411 }
412
413 pub fn connections(&self) -> usize {
415 self.core.connections()
416 }
417
418 pub fn ids(&self) -> Vec<u32> {
420 self.core.ids()
421 }
422
423 pub fn stats(&self, id: u32) -> Option<Stats> {
425 self.core.stats(id)
426 }
427
428 pub fn peer(&self, id: u32) -> Option<(Transport, Option<SocketAddr>)> {
430 self.core.peer(id)
431 }
432
433 pub fn server_stats(&self) -> ServerStats {
435 self.core.server_stats()
436 }
437
438 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}