Skip to main content

unbanished_net/
protocol.rs

1//! The relay protocol, version [`PROTOCOL`]: what a game and the relay say to each other.
2//!
3//! A game's first message is [`ToRelay::Hello`]. The relay answers [`FromRelay::Welcome`] when
4//! it speaks the same protocol, and [`FromRelay::Error`] with the reason when it does not. Then
5//! the lobby: list the rooms, host one (with a password if wanted), join one, leave, ping. The
6//! players of one room must run the same engine, the same game data and the same mods; the relay
7//! compares each joining game's `Hello` with the host's and says what differs. Inside a room the
8//! game's own messages (lockstep turns, saves) travel as [`ToRelay::Send`] and
9//! [`FromRelay::Data`], which the relay never reads. The digests of the players' games go to the
10//! server itself ([`ToRelay::Digest`]): it compares them (`crate::checks`) and, when the players
11//! differ, asks one whose game most players share for its save ([`FromRelay::SaveWanted`]).
12//!
13//! Before Un-Banished 1.0 a new protocol version replaces the old one; there is no
14//! compatibility between versions.
15
16use serde::{Deserialize, Serialize};
17
18/// The protocol version this crate speaks.
19pub const PROTOCOL: u16 = 4;
20
21/// Who a game is: the protocol it speaks, and what its players must share.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Hello {
24    /// The protocol version ([`PROTOCOL`]).
25    pub protocol: u16,
26    /// The engine's name and version, for example `Un-Banished 0.4.0-707cfea`.
27    pub engine: String,
28    /// A fingerprint of the game data (the original's packages).
29    pub data: u32,
30    /// A fingerprint of the enabled mods, in their order.
31    pub mods: u32,
32    /// A fingerprint of the rule hooks, in their order (0: none).
33    pub hooks: u32,
34}
35
36impl Hello {
37    /// This game's `Hello` with the current protocol.
38    pub fn new(engine: &str, data: u32, mods: u32) -> Hello {
39        Hello {
40            protocol: PROTOCOL,
41            engine: engine.to_string(),
42            data,
43            mods,
44            hooks: 0,
45        }
46    }
47
48    /// This `Hello` with the rule hooks' fingerprint.
49    pub fn with_hooks(mut self, hooks: u32) -> Hello {
50        self.hooks = hooks;
51        self
52    }
53
54    /// Why a game saying `other` cannot play in a room with this one, if it cannot.
55    pub fn differs(&self, other: &Hello) -> Option<String> {
56        if self.engine != other.engine {
57            return Some(format!(
58                "the host runs {}, and this game runs {}: use the same version",
59                self.engine, other.engine
60            ));
61        }
62        if self.data != other.data {
63            return Some("this game's data differs from the host's".into());
64        }
65        if self.mods != other.mods {
66            return Some("this game's mods differ from the host's: enable the same ones".into());
67        }
68        if self.hooks != other.hooks {
69            return Some(
70                "this game's rule hooks differ from the host's: use the same Hooks folder".into(),
71            );
72        }
73        None
74    }
75}
76
77/// A room in the relay's list.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct RoomInfo {
80    /// The room's code.
81    pub code: String,
82    /// How many players are in it.
83    pub players: u8,
84    /// Whether it asks for a password.
85    pub password: bool,
86}
87
88/// A game to the relay.
89#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
90pub enum ToRelay {
91    /// The first message: who this game is.
92    Hello(Hello),
93    /// The rooms open on this relay.
94    ListRooms,
95    /// Open a room (the code it asks for, or a new one) and be its host, player 0.
96    Host {
97        /// The code to use, or none for a new one.
98        room: Option<String>,
99        /// A password the players must give, or none.
100        password: Option<String>,
101    },
102    /// Join a room.
103    Join {
104        /// The room's code.
105        room: String,
106        /// The room's password, if it has one.
107        password: Option<String>,
108    },
109    /// Leave the room (the connection stays open).
110    Leave,
111    /// Data for one player, or for every other player in the room.
112    Send {
113        /// The player it is for, or none for every other player.
114        to: Option<u8>,
115        /// The data; the relay does not read it.
116        data: Vec<u8>,
117    },
118    /// Is the relay there? It answers [`FromRelay::Pong`] with the same number.
119    Ping(u32),
120    /// The host's town, for the server to keep (when it keeps rooms): the save made when
121    /// `update` updates had begun.
122    Keep {
123        /// The update the save was made at.
124        update: u64,
125        /// The save file's bytes.
126        bytes: Vec<u8>,
127    },
128    /// The town the server keeps for this room: it answers [`FromRelay::Kept`].
129    Fetch,
130    /// A digest of this game's state when `update` updates had begun, made in `epoch` (the
131    /// resyncs it has been through), for the server's check.
132    Digest {
133        /// The resyncs this game has been through.
134        epoch: u32,
135        /// The update.
136        update: u64,
137        /// The CRC-32 of the game state.
138        crc: u32,
139    },
140}
141
142/// The relay to a game.
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
144pub enum FromRelay {
145    /// The relay speaks this game's protocol.
146    Welcome {
147        /// The relay's protocol version.
148        protocol: u16,
149    },
150    /// The rooms open on this relay.
151    Rooms(Vec<RoomInfo>),
152    /// The room is open: its code (this game is player 0).
153    Hosted {
154        /// The room's code.
155        room: String,
156        /// Whether the server keeps rooms' towns: the host sends it its saves ([`ToRelay::Keep`]).
157        keeps: bool,
158        /// The update of the town kept for this room from an earlier game, if there is one.
159        kept: Option<u64>,
160    },
161    /// The town kept for this room.
162    Kept {
163        /// The update the save was made at.
164        update: u64,
165        /// The save file's bytes.
166        bytes: Vec<u8>,
167    },
168    /// This game joined the room as `player`.
169    Joined {
170        /// The room's code.
171        room: String,
172        /// This game's player number.
173        player: u8,
174    },
175    /// Another player came into the room.
176    PeerJoined {
177        /// Its player number.
178        player: u8,
179    },
180    /// Another player left the room.
181    PeerLeft {
182        /// Its player number.
183        player: u8,
184    },
185    /// Data from a player.
186    Data {
187        /// The sender's player number.
188        from: u8,
189        /// The data.
190        data: Vec<u8>,
191    },
192    /// The answer to [`ToRelay::Ping`].
193    Pong(u32),
194    /// The server's check of `update`, to every player in the room: the games agree, or not.
195    Checked {
196        /// The update checked.
197        update: u64,
198        /// Whether every player's game was the same.
199        agree: bool,
200    },
201    /// The players' games differed at `update`, and this game is the one to keep: send the
202    /// others a save at the next update boundary.
203    SaveWanted {
204        /// The update where the games differed.
205        update: u64,
206    },
207    /// A request failed, with the reason (no such room, a wrong password, another version...).
208    Error {
209        /// What went wrong, for the player to read.
210        message: String,
211    },
212}
213
214/// Encodes a protocol value (or a game message) for a WebSocket binary message.
215pub fn encode<T: Serialize>(value: &T) -> Vec<u8> {
216    postcard::to_stdvec(value).expect("a protocol value encodes")
217}
218
219/// Decodes a WebSocket binary message. A cut-off or unknown message is an error, never a panic.
220pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T, String> {
221    postcard::from_bytes(bytes).map_err(|e| e.to_string())
222}