ferravex_net/
wire_v4.rs

1//! Session extensions. Legacy input/full snapshots remain available within v4.
2use super::*;
3pub const MAX_CLOCK_US: u64 = 1 << 53;
4#[derive(Clone, Copy, Debug, Default, PartialEq)]
5pub struct TimedInput {
6    pub input: InputFrame,
7    pub shot_tick: Option<u32>,
8}
9#[derive(Clone, Debug, PartialEq)]
10pub enum Client {
11    Inputs {
12        session: u64,
13        inputs: Vec<TimedInput>,
14    },
15    SnapshotAck {
16        session: u64,
17        tick: Option<u32>,
18    },
19    Ping {
20        session: u64,
21        nonce: u32,
22        client_us: u64,
23    },
24    Command {
25        session: u64,
26        event: reliable::EventPacket,
27    },
28}
29#[derive(Clone, Debug, PartialEq)]
30pub enum Server {
31    SnapshotDelta {
32        session: u64,
33        delta: delta::Delta,
34    },
35    Pong {
36        session: u64,
37        nonce: u32,
38        client_us: u64,
39        receive_us: u64,
40        send_us: u64,
41        tick: u32,
42    },
43    CommandAck {
44        session: u64,
45        sequence: u64,
46    },
47}
48fn session(out: &mut Encoder<'_>, id: u64) -> Result<(), EncodeError> {
49    valid_session(id)?;
50    put_u64(out, id);
51    Ok(())
52}
53fn put_tick(out: &mut Encoder<'_>, tick: Option<u32>) {
54    out.push(tick.is_some() as u8);
55    put_u32(out, tick.unwrap_or(0));
56}
57fn read_tick(r: &mut Reader<'_>) -> Result<Option<u32>, ProtocolError> {
58    let present = r.boolean()?;
59    let tick = r.u32()?;
60    if !present && tick != 0 {
61        return Err(ProtocolError::Invalid);
62    }
63    Ok(present.then_some(tick))
64}
65fn read_session(r: &mut Reader<'_>) -> Result<u64, ProtocolError> {
66    let id = r.u64()?;
67    if id == 0 {
68        Err(ProtocolError::Invalid)
69    } else {
70        Ok(id)
71    }
72}
73fn payload(r: &mut Reader<'_>, max: usize) -> Result<Vec<u8>, ProtocolError> {
74    let n = r.u16()? as usize;
75    if n > max {
76        return Err(ProtocolError::TooLarge);
77    }
78    let end = r.pos.checked_add(n).ok_or(ProtocolError::Invalid)?;
79    let bytes = r.data.get(r.pos..end).ok_or(ProtocolError::Truncated)?;
80    r.pos = end;
81    Ok(bytes.to_vec())
82}
83#[cfg(test)]
84pub(super) fn encode_client(p: &Client) -> Result<Vec<u8>, ProtocolError> {
85    encode_allocated(|out| write_client(p, out))
86}
87pub(super) fn write_client(p: &Client, out: &mut Encoder<'_>) -> Result<(), EncodeError> {
88    if let Client::Command { session, event } = p {
89        return BorrowedEvent::Command {
90            session: *session,
91            event,
92        }
93        .write(out);
94    }
95    out.header(match p {
96        Client::Inputs { .. } => 7,
97        Client::SnapshotAck { .. } => 8,
98        Client::Ping { .. } => 9,
99        Client::Command { .. } => unreachable!("command encoded above"),
100    });
101    match p {
102        Client::Inputs {
103            session: id,
104            inputs,
105        } => {
106            session(out, *id)?;
107            valid_len("inputs", inputs.len(), 1, MAX_INPUTS_PER_PACKET)?;
108            out.push(inputs.len() as u8);
109            for (index, t) in inputs.iter().enumerate() {
110                validate_input(&t.input, index)?;
111                put_input(out, &t.input);
112                put_tick(out, t.shot_tick);
113            }
114        }
115        Client::SnapshotAck { session: id, tick } => {
116            session(out, *id)?;
117            put_tick(out, *tick);
118        }
119        Client::Ping {
120            session: id,
121            nonce,
122            client_us,
123        } => {
124            session(out, *id)?;
125            valid_field(*client_us <= MAX_CLOCK_US, "client_us", None)?;
126            put_u32(out, *nonce);
127            put_u64(out, *client_us);
128        }
129        Client::Command { .. } => unreachable!("command encoded above"),
130    }
131    Ok(())
132}
133pub(super) fn decode_client(r: &mut Reader<'_>, kind: u8) -> Result<Client, ProtocolError> {
134    let session = read_session(r)?;
135    Ok(match kind {
136        7 => {
137            let n = r.u8()? as usize;
138            if !(1..=MAX_INPUTS_PER_PACKET).contains(&n) {
139                return Err(ProtocolError::Invalid);
140            }
141            let mut inputs = Vec::with_capacity(n);
142            for _ in 0..n {
143                inputs.push(TimedInput {
144                    input: r.input()?,
145                    shot_tick: read_tick(r)?,
146                });
147            }
148            Client::Inputs { session, inputs }
149        }
150        8 => Client::SnapshotAck {
151            session,
152            tick: read_tick(r)?,
153        },
154        9 => {
155            let nonce = r.u32()?;
156            let client_us = r.u64()?;
157            if client_us > MAX_CLOCK_US {
158                return Err(ProtocolError::Invalid);
159            }
160            Client::Ping {
161                session,
162                nonce,
163                client_us,
164            }
165        }
166        10 => {
167            let sequence = r.u64()?;
168            let payload = payload(r, reliable::EVENT_BYTES)?;
169            if payload.is_empty() {
170                return Err(ProtocolError::Invalid);
171            }
172            Client::Command {
173                session,
174                event: reliable::EventPacket { sequence, payload },
175            }
176        }
177        _ => return Err(ProtocolError::Kind),
178    })
179}
180#[cfg(test)]
181pub(super) fn encode_server(p: &Server) -> Result<Vec<u8>, ProtocolError> {
182    encode_allocated(|out| write_server(p, out))
183}
184pub(super) fn write_server(p: &Server, out: &mut Encoder<'_>) -> Result<(), EncodeError> {
185    out.header(match p {
186        Server::SnapshotDelta { .. } => 11,
187        Server::Pong { .. } => 12,
188        Server::CommandAck { .. } => 13,
189    });
190    match p {
191        Server::SnapshotDelta { session: id, delta } => {
192            session(out, *id)?;
193            valid_field(
194                sequence_newer(delta.tick, delta.base_tick),
195                "delta.tick",
196                None,
197            )?;
198            valid_len("delta.bytes", delta.bytes.len(), 3, MAX_PACKET_BYTES - 24)?;
199            put_u32(out, delta.base_tick);
200            put_u32(out, delta.tick);
201            put_u16(out, delta.bytes.len() as u16);
202            out.extend_from_slice(&delta.bytes);
203        }
204        Server::Pong {
205            session: id,
206            nonce,
207            client_us,
208            receive_us,
209            send_us,
210            tick,
211        } => {
212            session(out, *id)?;
213            valid_field(*client_us <= MAX_CLOCK_US, "client_us", None)?;
214            valid_field(*receive_us <= MAX_CLOCK_US, "receive_us", None)?;
215            valid_field(*send_us <= MAX_CLOCK_US, "send_us", None)?;
216            valid_field(send_us >= receive_us, "pong.send_order", None)?;
217            valid_field(
218                send_us - receive_us <= 5_000_000,
219                "pong.processing_us",
220                None,
221            )?;
222            put_u32(out, *nonce);
223            for value in [client_us, receive_us, send_us] {
224                put_u64(out, *value);
225            }
226            put_u32(out, *tick);
227        }
228        Server::CommandAck {
229            session: id,
230            sequence,
231        } => {
232            session(out, *id)?;
233            put_u64(out, *sequence);
234        }
235    }
236    Ok(())
237}
238fn validate_pong(client: u64, receive: u64, send: u64) -> Result<(), ProtocolError> {
239    if client > MAX_CLOCK_US
240        || receive > MAX_CLOCK_US
241        || send > MAX_CLOCK_US
242        || send < receive
243        || send - receive > 5_000_000
244    {
245        Err(ProtocolError::Invalid)
246    } else {
247        Ok(())
248    }
249}
250pub(super) fn decode_server(r: &mut Reader<'_>, kind: u8) -> Result<Server, ProtocolError> {
251    let session = read_session(r)?;
252    Ok(match kind {
253        11 => {
254            let base_tick = r.u32()?;
255            let tick = r.u32()?;
256            let bytes = payload(r, MAX_PACKET_BYTES - 24)?;
257            if !sequence_newer(tick, base_tick) || bytes.len() < 3 {
258                return Err(ProtocolError::Invalid);
259            }
260            Server::SnapshotDelta {
261                session,
262                delta: delta::Delta {
263                    base_tick,
264                    tick,
265                    bytes,
266                },
267            }
268        }
269        12 => {
270            let nonce = r.u32()?;
271            let client_us = r.u64()?;
272            let receive_us = r.u64()?;
273            let send_us = r.u64()?;
274            let tick = r.u32()?;
275            validate_pong(client_us, receive_us, send_us)?;
276            Server::Pong {
277                session,
278                nonce,
279                client_us,
280                receive_us,
281                send_us,
282                tick,
283            }
284        }
285        13 => Server::CommandAck {
286            session,
287            sequence: r.u64()?,
288        },
289        _ => return Err(ProtocolError::Kind),
290    })
291}
292#[cfg(test)]
293mod tests {
294    use super::*;
295    #[test]
296    fn extension_roundtrips_reject_truncation_versions_trailing_and_semantics() {
297        let clients = [
298            Client::Inputs {
299                session: 1,
300                inputs: vec![TimedInput {
301                    input: InputFrame::default(),
302                    shot_tick: Some(u32::MAX),
303                }],
304            },
305            Client::SnapshotAck {
306                session: 1,
307                tick: None,
308            },
309            Client::Ping {
310                session: 1,
311                nonce: 7,
312                client_us: 100,
313            },
314            Client::Command {
315                session: 1,
316                event: reliable::EventPacket {
317                    sequence: 2,
318                    payload: vec![1, 3],
319                },
320            },
321        ];
322        for p in clients {
323            let p = ClientPacket::Extension(p);
324            let b = super::super::encode_client(&p).unwrap();
325            assert_eq!(super::super::decode_client(&b).unwrap(), p);
326            for n in 0..b.len() {
327                assert!(super::super::decode_client(&b[..n]).is_err());
328            }
329            let mut bad = b;
330            bad.push(0);
331            assert!(super::super::decode_client(&bad).is_err());
332        }
333        let servers = [
334            Server::SnapshotDelta {
335                session: 2,
336                delta: delta::Delta::between(u32::MAX, &[0; 20], 0, &[0; 20]).unwrap(),
337            },
338            Server::Pong {
339                session: 1,
340                nonce: 3,
341                client_us: 100,
342                receive_us: 1000,
343                send_us: 1001,
344                tick: 0,
345            },
346            Server::CommandAck {
347                session: 1,
348                sequence: 3,
349            },
350        ];
351        for p in servers {
352            let p = ServerPacket::Extension(p);
353            let b = super::super::encode_server(&p).unwrap();
354            assert_eq!(super::super::decode_server(&b).unwrap(), p);
355            for n in 0..b.len() {
356                assert!(super::super::decode_server(&b[..n]).is_err());
357            }
358        }
359        assert!(
360            encode_client(&Client::Ping {
361                session: 0,
362                nonce: 0,
363                client_us: 0
364            })
365            .is_err()
366        );
367        assert!(
368            encode_server(&Server::Pong {
369                session: 1,
370                nonce: 0,
371                client_us: 0,
372                receive_us: 2,
373                send_us: 1,
374                tick: 0
375            })
376            .is_err()
377        );
378        let mut bad = super::super::encode_client(&ClientPacket::Extension(Client::SnapshotAck {
379            session: 1,
380            tick: None,
381        }))
382        .unwrap();
383        bad[15] = 1;
384        assert!(super::super::decode_client(&bad).is_err());
385        bad[4] = 4;
386        assert_eq!(
387            super::super::decode_client(&bad),
388            Err(ProtocolError::Version)
389        );
390    }
391}