1use std::collections::VecDeque;
15use std::io::{ErrorKind, Read, Write};
16use std::net::{Shutdown, SocketAddr, TcpStream, UdpSocket};
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::{Arc, Mutex};
19use std::thread;
20use std::time::Duration;
21
22use serde::Deserialize;
23use serde_json::json;
24
25use crate::desktop::{offline_only, post_json, DesktopCall, GAMES_PATH_PREFIX};
26use crate::error::SdkError;
27use crate::p2p::validate_id;
28
29pub const MAX_UNRELIABLE_MESSAGE: usize = 1200;
32pub const MAX_RELIABLE_MESSAGE: usize = 65535;
34
35const FRAME_VERSION: u8 = 1;
36const HEADER_LEN: usize = 8;
37const KIND_HELLO: u8 = 1;
38const KIND_SEND: u8 = 2;
39const KIND_MESSAGE: u8 = 16;
40const KIND_PEER_CONNECTED: u8 = 17;
41const KIND_QUALITY: u8 = 18;
42const KIND_PEER_DISCONNECTED: u8 = 19;
43const KIND_RELAY_REFUSED: u8 = 20;
44const PEER_HOST: u16 = 0xFFFE;
45const PEER_ALL: u16 = 0xFFFF;
46
47const SESSION_KEY_LEN: usize = 16;
48const OPEN_TIMEOUT: Duration = Duration::from_secs(15);
49const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
50const CLOSE_TIMEOUT: Duration = Duration::from_secs(2);
51const UDP_HELLO_PERIOD: Duration = Duration::from_secs(2);
52const MAX_QUEUED_BYTES: usize = 64 * 1024 * 1024;
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub enum Channel {
57 Reliable,
60 Unreliable,
63}
64
65impl Channel {
66 fn limit(self) -> usize {
67 match self {
68 Self::Reliable => MAX_RELIABLE_MESSAGE,
69 Self::Unreliable => MAX_UNRELIABLE_MESSAGE,
70 }
71 }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub enum Peer {
77 Host,
79 All,
82 Index(u16),
85}
86
87impl Peer {
88 fn wire(self) -> u16 {
89 match self {
90 Self::Host => PEER_HOST,
91 Self::All => PEER_ALL,
92 Self::Index(index) => index,
93 }
94 }
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
99#[serde(rename_all = "snake_case")]
100pub enum Route {
101 Direct,
103 Relayed,
105}
106
107impl Route {
108 pub fn as_str(&self) -> &'static str {
110 match self {
111 Self::Direct => "direct",
112 Self::Relayed => "relayed",
113 }
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub struct NetOptions {
120 pub allow_relay: bool,
124}
125
126impl Default for NetOptions {
127 fn default() -> Self {
128 Self { allow_relay: true }
129 }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct NetMessage {
135 pub peer: u16,
137 pub channel: Channel,
138 pub data: Vec<u8>,
139}
140
141#[derive(Debug, Clone, PartialEq)]
143pub enum NetEvent {
144 PeerConnected {
146 peer: u16,
147 user_id: String,
148 route: Route,
149 is_host: bool,
150 },
151 Quality {
154 peer: u16,
155 user_id: String,
156 route: Route,
157 rtt_ms: Option<f64>,
158 loss_pct: f64,
159 jitter_ms: Option<f64>,
160 },
161 PeerDisconnected {
164 peer: u16,
165 user_id: String,
166 reason: String,
167 },
168 RelayRefused { peer: u16, user_id: String },
171 Closed { reason: String },
174}
175
176#[derive(Deserialize)]
177struct WireOpened {
178 udp_port: u16,
179 tcp_port: u16,
180 session_key: String,
181}
182
183#[derive(Deserialize)]
184struct WireOk {
185 #[allow(dead_code)]
186 ok: bool,
187}
188
189#[derive(Deserialize)]
190struct WirePeer {
191 #[serde(default)]
192 user_id: String,
193 #[serde(default)]
194 route: Option<Route>,
195 #[serde(default)]
196 is_host: bool,
197 #[serde(default)]
198 rtt_ms: Option<f64>,
199 #[serde(default)]
200 loss_pct: f64,
201 #[serde(default)]
202 jitter_ms: Option<f64>,
203 #[serde(default)]
204 reason: String,
205}
206
207#[derive(Default)]
208struct Inbox {
209 messages: VecDeque<NetMessage>,
210 events: VecDeque<NetEvent>,
211 queued_bytes: usize,
212 closed: bool,
213}
214
215struct Link {
216 tcp: Mutex<TcpStream>,
217 udp: UdpSocket,
218 desktop_udp: SocketAddr,
219 udp_hello: Vec<u8>,
220 inbox: Mutex<Inbox>,
221 running: AtomicBool,
222}
223
224impl Link {
225 fn push_message(&self, message: NetMessage) {
226 let mut inbox = self.inbox.lock().unwrap_or_else(|e| e.into_inner());
227 if inbox.closed {
228 return;
229 }
230 if inbox.queued_bytes + message.data.len() > MAX_QUEUED_BYTES {
231 if message.channel == Channel::Unreliable {
232 return;
233 }
234 drop(inbox);
235 self.stop("receive_overflow");
236 return;
237 }
238 inbox.queued_bytes += message.data.len();
239 inbox.messages.push_back(message);
240 }
241
242 fn push_event(&self, event: NetEvent) {
243 let mut inbox = self.inbox.lock().unwrap_or_else(|e| e.into_inner());
244 if !inbox.closed {
245 inbox.events.push_back(event);
246 }
247 }
248
249 fn stop(&self, reason: &str) {
250 if !self.running.swap(false, Ordering::SeqCst) {
251 return;
252 }
253 if let Ok(tcp) = self.tcp.lock() {
254 let _ = tcp.shutdown(Shutdown::Both);
255 }
256 let mut inbox = self.inbox.lock().unwrap_or_else(|e| e.into_inner());
257 inbox.events.push_back(NetEvent::Closed {
258 reason: reason.to_string(),
259 });
260 inbox.closed = true;
261 }
262
263 fn is_running(&self) -> bool {
264 self.running.load(Ordering::SeqCst)
265 }
266}
267
268pub(crate) struct NetState {
269 link: Mutex<Option<Arc<Link>>>,
270}
271
272impl std::fmt::Debug for NetState {
273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274 f.debug_struct("NetState")
275 .field(
276 "open",
277 &self.current().is_some_and(|link| link.is_running()),
278 )
279 .finish()
280 }
281}
282
283impl NetState {
284 pub(crate) fn new() -> Self {
285 Self {
286 link: Mutex::new(None),
287 }
288 }
289
290 fn current(&self) -> Option<Arc<Link>> {
291 self.link
292 .lock()
293 .unwrap_or_else(|e| e.into_inner())
294 .as_ref()
295 .cloned()
296 }
297
298 fn replace(&self, link: Option<Arc<Link>>) -> Option<Arc<Link>> {
299 let mut slot = self.link.lock().unwrap_or_else(|e| e.into_inner());
300 std::mem::replace(&mut *slot, link)
301 }
302}
303
304pub struct Net<'a> {
307 game_id: &'a str,
308 state: &'a NetState,
309}
310
311impl<'a> Net<'a> {
312 pub(crate) fn new(game_id: &'a str, state: &'a NetState) -> Self {
313 Self { game_id, state }
314 }
315
316 pub fn open(&self, lobby_id: &str, options: NetOptions) -> Result<(), SdkError> {
332 validate_id("lobby_id", lobby_id)?;
333 if offline_only() {
334 return Err(SdkError::network_required(
335 "Opening the coop network needs the Arcane desktop app.",
336 )
337 .with_hint("Unset ARCANE_OFFLINE_ONLY to use the coop network."));
338 }
339
340 let body = json!({ "lobby_id": lobby_id, "allow_relay": options.allow_relay });
341 let opened: WireOpened = post_json(&self.path("open"), Some(body), OPEN_TIMEOUT)
342 .map_err(|call| call.into_sdk_error().with_context("lobby_id", lobby_id))?;
343
344 let link = attach(&opened).map_err(|err| err.with_context("lobby_id", lobby_id))?;
345 if let Some(previous) = self.state.replace(Some(Arc::clone(&link))) {
346 previous.stop("replaced");
347 }
348 spawn_readers(link);
349 Ok(())
350 }
351
352 pub fn send(&self, peer: Peer, channel: Channel, data: &[u8]) -> Result<(), SdkError> {
365 if data.len() > channel.limit() {
366 return Err(
367 SdkError::invalid_argument("The message is too large for its channel.")
368 .with_hint(format!(
369 "Reliable messages are at most {MAX_RELIABLE_MESSAGE} bytes, unreliable \
370 ones at most {MAX_UNRELIABLE_MESSAGE}. Split larger state."
371 ))
372 .with_context("bytes", data.len()),
373 );
374 }
375 let link = self.open_link()?;
376 let frame = encode(KIND_SEND, peer.wire(), data);
377 let sent = match channel {
378 Channel::Reliable => {
379 let mut tcp = link.tcp.lock().unwrap_or_else(|e| e.into_inner());
380 tcp.write_all(&frame)
381 }
382 Channel::Unreliable => link.udp.send_to(&frame, link.desktop_udp).map(|_| ()),
383 };
384 sent.map_err(|e| {
385 SdkError::arcane_unavailable(format!("The coop network socket failed: {e}"))
386 .with_hint("Reopen the network; if it keeps failing, restart Arcane Powered.")
387 })
388 }
389
390 pub fn receive(&self) -> Option<NetMessage> {
396 let link = self.state.current()?;
397 let mut inbox = link.inbox.lock().unwrap_or_else(|e| e.into_inner());
398 let message = inbox.messages.pop_front()?;
399 inbox.queued_bytes -= message.data.len();
400 Some(message)
401 }
402
403 pub fn poll_events(&self) -> Vec<NetEvent> {
405 let Some(link) = self.state.current() else {
406 return Vec::new();
407 };
408 let mut inbox = link.inbox.lock().unwrap_or_else(|e| e.into_inner());
409 inbox.events.drain(..).collect()
410 }
411
412 pub(crate) fn receive_into(&self, buf: &mut [u8]) -> ReceiveInto {
413 let Some(link) = self.state.current() else {
414 return ReceiveInto::Empty;
415 };
416 let mut inbox = link.inbox.lock().unwrap_or_else(|e| e.into_inner());
417 let Some(front) = inbox.messages.front() else {
418 return ReceiveInto::Empty;
419 };
420 if front.data.len() > buf.len() {
421 return ReceiveInto::TooSmall;
422 }
423 let Some(message) = inbox.messages.pop_front() else {
424 return ReceiveInto::Empty;
425 };
426 inbox.queued_bytes -= message.data.len();
427 buf[..message.data.len()].copy_from_slice(&message.data);
428 ReceiveInto::Received {
429 peer: message.peer,
430 channel: message.channel,
431 len: message.data.len(),
432 }
433 }
434
435 pub(crate) fn events_json(&self) -> (String, usize) {
436 let Some(link) = self.state.current() else {
437 return (render_events(std::iter::empty()), 0);
438 };
439 let inbox = link.inbox.lock().unwrap_or_else(|e| e.into_inner());
440 (render_events(inbox.events.iter()), inbox.events.len())
441 }
442
443 pub(crate) fn discard_events(&self, count: usize) {
444 if let Some(link) = self.state.current() {
445 let mut inbox = link.inbox.lock().unwrap_or_else(|e| e.into_inner());
446 let count = count.min(inbox.events.len());
447 inbox.events.drain(..count);
448 }
449 }
450
451 pub fn is_open(&self) -> bool {
453 self.state.current().is_some_and(|link| link.is_running())
454 }
455
456 pub fn close(&self) {
463 let Some(link) = self.state.replace(None) else {
464 return;
465 };
466 link.stop("closed");
467 if !offline_only() {
468 let _: Result<WireOk, DesktopCall> =
469 post_json(&self.path("close"), None, CLOSE_TIMEOUT);
470 }
471 }
472
473 fn open_link(&self) -> Result<Arc<Link>, SdkError> {
474 match self.state.current() {
475 Some(link) if link.is_running() => Ok(link),
476 _ => Err(SdkError::lobby_closed("The coop network is not open.")
477 .with_hint("Call Net::open on a lobby first; reopen it after NetEvent::Closed.")),
478 }
479 }
480
481 fn path(&self, action: &str) -> String {
482 format!("{GAMES_PATH_PREFIX}/{}/net/{action}", self.game_id)
483 }
484}
485
486pub(crate) enum ReceiveInto {
487 Empty,
488 TooSmall,
489 Received {
490 peer: u16,
491 channel: Channel,
492 len: usize,
493 },
494}
495
496pub(crate) fn event_json(event: &NetEvent) -> serde_json::Value {
497 match event {
498 NetEvent::PeerConnected {
499 peer,
500 user_id,
501 route,
502 is_host,
503 } => json!({
504 "type": "peer_connected",
505 "peer": peer,
506 "user_id": user_id,
507 "route": route.as_str(),
508 "is_host": is_host,
509 }),
510 NetEvent::Quality {
511 peer,
512 user_id,
513 route,
514 rtt_ms,
515 loss_pct,
516 jitter_ms,
517 } => json!({
518 "type": "quality",
519 "peer": peer,
520 "user_id": user_id,
521 "route": route.as_str(),
522 "rtt_ms": rtt_ms,
523 "loss_pct": loss_pct,
524 "jitter_ms": jitter_ms,
525 }),
526 NetEvent::PeerDisconnected {
527 peer,
528 user_id,
529 reason,
530 } => json!({
531 "type": "peer_disconnected",
532 "peer": peer,
533 "user_id": user_id,
534 "reason": reason,
535 }),
536 NetEvent::RelayRefused { peer, user_id } => json!({
537 "type": "relay_refused",
538 "peer": peer,
539 "user_id": user_id,
540 }),
541 NetEvent::Closed { reason } => json!({ "type": "closed", "reason": reason }),
542 }
543}
544
545fn render_events<'a>(events: impl Iterator<Item = &'a NetEvent>) -> String {
546 let events: Vec<serde_json::Value> = events.map(event_json).collect();
547 json!({ "events": events }).to_string()
548}
549
550fn attach(opened: &WireOpened) -> Result<Arc<Link>, SdkError> {
551 let key = decode_key(&opened.session_key)?;
552 let local_failure = |what: &str, e: std::io::Error| {
553 SdkError::arcane_unavailable(format!("Could not {what}: {e}"))
554 .with_hint("Restart the Arcane Powered desktop app, then retry.")
555 };
556
557 let tcp_addr = SocketAddr::from(([127, 0, 0, 1], opened.tcp_port));
558 let mut tcp = TcpStream::connect_timeout(&tcp_addr, CONNECT_TIMEOUT)
559 .map_err(|e| local_failure("reach the coop network", e))?;
560 let _ = tcp.set_nodelay(true);
561 tcp.write_all(&encode(KIND_HELLO, 0, &key))
562 .map_err(|e| local_failure("attach to the coop network", e))?;
563
564 let udp = UdpSocket::bind(("127.0.0.1", 0))
565 .map_err(|e| local_failure("open a local UDP socket", e))?;
566 udp.set_read_timeout(Some(UDP_HELLO_PERIOD))
567 .map_err(|e| local_failure("configure the local UDP socket", e))?;
568 let desktop_udp = SocketAddr::from(([127, 0, 0, 1], opened.udp_port));
569 let udp_hello = encode(KIND_HELLO, 0, &key);
570 udp.send_to(&udp_hello, desktop_udp)
571 .map_err(|e| local_failure("attach to the coop network", e))?;
572
573 Ok(Arc::new(Link {
574 tcp: Mutex::new(tcp),
575 udp,
576 desktop_udp,
577 udp_hello,
578 inbox: Mutex::new(Inbox::default()),
579 running: AtomicBool::new(true),
580 }))
581}
582
583fn decode_key(hex_key: &str) -> Result<Vec<u8>, SdkError> {
584 match hex::decode(hex_key.trim()) {
585 Ok(key) if key.len() == SESSION_KEY_LEN => Ok(key),
586 _ => Err(SdkError::arcane_unavailable(
587 "The Arcane desktop app answered an unreadable network key.",
588 )
589 .with_hint("The Arcane desktop app may be older than this SDK — update it.")),
590 }
591}
592
593fn spawn_readers(link: Arc<Link>) {
594 let tcp = {
595 let guard = link.tcp.lock().unwrap_or_else(|e| e.into_inner());
596 guard.try_clone()
597 };
598
599 let tcp_link = Arc::clone(&link);
600 let spawned = match tcp {
601 Ok(stream) => thread::Builder::new()
602 .name("arcane-net-tcp".into())
603 .spawn(move || read_tcp(tcp_link, stream))
604 .is_ok(),
605 Err(_) => false,
606 };
607 if !spawned {
608 link.stop("socket_error");
609 return;
610 }
611
612 let udp_link = Arc::clone(&link);
613 if thread::Builder::new()
614 .name("arcane-net-udp".into())
615 .spawn(move || read_udp(udp_link))
616 .is_err()
617 {
618 link.stop("socket_error");
619 }
620}
621
622fn read_tcp(link: Arc<Link>, mut stream: TcpStream) {
623 let mut buf: Vec<u8> = Vec::new();
624 let mut chunk = vec![0u8; 16 * 1024];
625 while link.is_running() {
626 loop {
627 match decode(&buf) {
628 Decoded::Frame {
629 kind,
630 peer,
631 data,
632 used,
633 } => {
634 handle_frame(&link, kind, peer, data, Channel::Reliable);
635 buf.drain(..used);
636 }
637 Decoded::Incomplete => break,
638 Decoded::Invalid => {
639 link.stop("protocol_error");
640 return;
641 }
642 }
643 }
644 match stream.read(&mut chunk) {
645 Ok(0) => break,
646 Ok(read) => buf.extend_from_slice(&chunk[..read]),
647 Err(e) if e.kind() == ErrorKind::Interrupted => {}
648 Err(_) => break,
649 }
650 }
651 link.stop("desktop_closed");
652}
653
654fn read_udp(link: Arc<Link>) {
655 let mut buf = vec![0u8; 2048];
656 while link.is_running() {
657 match link.udp.recv_from(&mut buf) {
658 Ok((len, from)) => {
659 if from != link.desktop_udp {
660 continue;
661 }
662 if let Decoded::Frame {
663 kind, peer, data, ..
664 } = decode(&buf[..len])
665 {
666 handle_frame(&link, kind, peer, data, Channel::Unreliable);
667 }
668 }
669 Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
670 let _ = link.udp.send_to(&link.udp_hello, link.desktop_udp);
671 }
672 Err(e) if e.kind() == ErrorKind::Interrupted => {}
673 Err(_) => {}
674 }
675 }
676}
677
678fn handle_frame(link: &Link, kind: u8, peer: u16, data: &[u8], channel: Channel) {
679 if kind == KIND_MESSAGE {
680 link.push_message(NetMessage {
681 peer,
682 channel,
683 data: data.to_vec(),
684 });
685 return;
686 }
687 let Ok(body) = serde_json::from_slice::<WirePeer>(data) else {
688 return;
689 };
690 let route = body.route.unwrap_or(Route::Direct);
691 let event = match kind {
692 KIND_PEER_CONNECTED => NetEvent::PeerConnected {
693 peer,
694 user_id: body.user_id,
695 route,
696 is_host: body.is_host,
697 },
698 KIND_QUALITY => NetEvent::Quality {
699 peer,
700 user_id: body.user_id,
701 route,
702 rtt_ms: body.rtt_ms,
703 loss_pct: body.loss_pct,
704 jitter_ms: body.jitter_ms,
705 },
706 KIND_PEER_DISCONNECTED => NetEvent::PeerDisconnected {
707 peer,
708 user_id: body.user_id,
709 reason: body.reason,
710 },
711 KIND_RELAY_REFUSED => NetEvent::RelayRefused {
712 peer,
713 user_id: body.user_id,
714 },
715 _ => return,
716 };
717 link.push_event(event);
718}
719
720fn encode(kind: u8, peer: u16, data: &[u8]) -> Vec<u8> {
721 let mut out = Vec::with_capacity(HEADER_LEN + data.len());
722 out.push(FRAME_VERSION);
723 out.push(kind);
724 out.extend_from_slice(&peer.to_be_bytes());
725 out.extend_from_slice(&(data.len() as u32).to_be_bytes());
726 out.extend_from_slice(data);
727 out
728}
729
730enum Decoded<'a> {
731 Frame {
732 kind: u8,
733 peer: u16,
734 data: &'a [u8],
735 used: usize,
736 },
737 Incomplete,
738 Invalid,
739}
740
741fn decode(buf: &[u8]) -> Decoded<'_> {
742 if buf.len() < HEADER_LEN {
743 return Decoded::Incomplete;
744 }
745 if buf[0] != FRAME_VERSION {
746 return Decoded::Invalid;
747 }
748 let kind = buf[1];
749 let peer = u16::from_be_bytes([buf[2], buf[3]]);
750 let len = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
751 if len > MAX_RELIABLE_MESSAGE {
752 return Decoded::Invalid;
753 }
754 if buf.len() < HEADER_LEN + len {
755 return Decoded::Incomplete;
756 }
757 Decoded::Frame {
758 kind,
759 peer,
760 data: &buf[HEADER_LEN..HEADER_LEN + len],
761 used: HEADER_LEN + len,
762 }
763}