Skip to main content

capsid_protocol/
forwarding.rs

1use std::{num::NonZeroU16, time::Duration};
2
3use serde::{Deserialize, Serialize};
4
5use crate::{AttemptId, Error, Result, VERSION};
6
7pub const MAX_PORTS: usize = 16;
8
9pub const MAX_CONNECTIONS: usize = 16;
10
11pub const MAX_DATA_BYTES: usize = 16 * 1024;
12
13pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
14
15pub const DATA_HEADER_BYTES: usize = 4;
16
17pub const RECEIPT: &[u8; 4] = b"DONE";
18
19// A forwarded stream travels as data frames: a big-endian length, then that
20// many bytes. A zero length ends the stream in that direction, and each side
21// then sends `RECEIPT` once both directions have ended.
22pub fn data_header(count: usize) -> Result<[u8; DATA_HEADER_BYTES]> {
23    if count > MAX_DATA_BYTES {
24        return Err(Error::DataFrameSize);
25    }
26    Ok((count as u32).to_be_bytes())
27}
28
29// The length a data frame header announces; `None` ends the stream.
30pub fn data_length(header: [u8; DATA_HEADER_BYTES]) -> Result<Option<usize>> {
31    match u32::from_be_bytes(header) as usize {
32        0 => Ok(None),
33        count if count > MAX_DATA_BYTES => Err(Error::DataFrameSize),
34        count => Ok(Some(count)),
35    }
36}
37
38pub fn verify_receipt(receipt: [u8; RECEIPT.len()]) -> Result<()> {
39    if receipt != *RECEIPT {
40        return Err(Error::Receipt);
41    }
42    Ok(())
43}
44
45#[derive(Debug, Serialize, Deserialize)]
46#[serde(deny_unknown_fields)]
47pub struct Request {
48    pub version: u32,
49
50    pub attempt: AttemptId,
51
52    pub port: NonZeroU16,
53}
54
55impl Request {
56    pub fn new(attempt: AttemptId, port: NonZeroU16) -> Self {
57        Self {
58            version: VERSION,
59            attempt,
60            port,
61        }
62    }
63
64    pub fn is_for(&self, attempt: AttemptId) -> bool {
65        self.version == VERSION && self.attempt == attempt
66    }
67}
68
69#[derive(Debug, Serialize, Deserialize)]
70#[serde(deny_unknown_fields)]
71pub struct Response {
72    pub version: u32,
73
74    pub attempt: AttemptId,
75
76    pub accepted: bool,
77}
78
79impl Response {
80    pub fn new(attempt: AttemptId, accepted: bool) -> Self {
81        Self {
82            version: VERSION,
83            attempt,
84            accepted,
85        }
86    }
87
88    pub fn verify(&self, attempt: AttemptId) -> Result<()> {
89        if self.version != VERSION || self.attempt != attempt || !self.accepted {
90            return Err(Error::Rejected);
91        }
92        Ok(())
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use crate::testing;
100
101    #[test]
102    fn test_data_headers_round_trip_and_bound_the_frame() -> testing::Result {
103        assert_eq!(data_length(data_header(0)?)?, None);
104        assert_eq!(
105            data_length(data_header(MAX_DATA_BYTES)?)?,
106            Some(MAX_DATA_BYTES)
107        );
108        assert!(data_header(MAX_DATA_BYTES + 1).is_err());
109        assert!(data_length(((MAX_DATA_BYTES + 1) as u32).to_be_bytes()).is_err());
110        assert!(verify_receipt(*RECEIPT).is_ok());
111        assert!(verify_receipt(*b"DONT").is_err());
112        Ok(())
113    }
114
115    #[test]
116    fn test_responses_verify_version_attempt_and_acceptance() {
117        let (a, b) = (AttemptId::new(), AttemptId::new());
118        assert!(Response::new(a, true).verify(a).is_ok());
119        assert!(Response::new(a, false).verify(a).is_err());
120        assert!(Response::new(b, true).verify(a).is_err());
121        let mut stale = Response::new(a, true);
122        stale.version = VERSION - 1;
123        assert!(stale.verify(a).is_err());
124    }
125}