Skip to main content

labstream_proto/
header.rs

1//! The header block parser, and the status line.
2//!
3//! liblsl parses request headers and answer headers with the same code
4//! (`src/tcp_server.cpp:602-632`, `src/data_receiver.cpp:215-258`). The rules
5//! are in SPEC.md 4.3.
6
7use core::fmt;
8
9/// The largest line that liblsl reads. `src/tcp_server.cpp:601`.
10pub const LINE_LIMIT: usize = 16384;
11
12/// A parsed header block.
13#[derive(Debug, Clone, Default, PartialEq, Eq)]
14pub struct Headers {
15    /// Name and value pairs, in the order that they arrived. Names are lower
16    /// case, because the parser lowercases every line.
17    pub fields: Vec<(String, String)>,
18    /// Lines that held no colon. liblsl logs and ignores them.
19    pub ignored: Vec<String>,
20}
21
22impl Headers {
23    /// The value of the first field with this name.
24    ///
25    /// The caller passes a lower case name, because every parsed name is lower
26    /// case.
27    pub fn get(&self, name: &str) -> Option<&str> {
28        self.fields
29            .iter()
30            .find(|(k, _)| k == name)
31            .map(|(_, v)| v.as_str())
32    }
33
34    /// The value of a field, read as an integer.
35    pub fn get_int(&self, name: &str) -> Option<i64> {
36        self.get(name).and_then(parse_leading_int)
37    }
38
39    /// The value of a field, read as a floating point number.
40    pub fn get_f64(&self, name: &str) -> Option<f64> {
41        self.get(name).and_then(parse_leading_f64)
42    }
43
44    /// The value of a field, read as a flag.
45    ///
46    /// liblsl reads a flag with `from_string<bool>`, which accepts `1` and `0`.
47    pub fn get_bool(&self, name: &str) -> Option<bool> {
48        self.get(name)
49            .map(|v| v.trim() == "1" || v.trim() == "true")
50    }
51}
52
53/// liblsl reads a number with `std::stoi`, which stops at the first character
54/// that does not belong to a number. It does not reject trailing text.
55fn parse_leading_int(s: &str) -> Option<i64> {
56    let t = s.trim_start();
57    let mut end = 0;
58    for (i, c) in t.char_indices() {
59        if c.is_ascii_digit() || (i == 0 && (c == '-' || c == '+')) {
60            end = i + c.len_utf8();
61        } else {
62            break;
63        }
64    }
65    t[..end].parse().ok()
66}
67
68/// liblsl reads a real number with `std::stod`, which behaves the same way.
69fn parse_leading_f64(s: &str) -> Option<f64> {
70    let t = s.trim_start();
71    let mut end = 0;
72    for (i, c) in t.char_indices() {
73        if c.is_ascii_digit()
74            || c == '.'
75            || ((c == '-' || c == '+') && i == 0)
76            || c == 'e'
77            || c == 'E'
78        {
79            end = i + c.len_utf8();
80        } else {
81            break;
82        }
83    }
84    t[..end].parse().ok()
85}
86
87/// Split a line into a header name and a value.
88///
89/// The rules, from SPEC.md 4.3 and `src/tcp_server.cpp:604-616`:
90///
91/// 1. A line with no colon is ignored.
92/// 2. A semicolon starts a comment. The parser removes it and the rest.
93/// 3. The parser lowercases the whole line, so names are case-insensitive.
94/// 4. The parser trims the name and the value.
95///
96/// liblsl finds the colon before it removes the comment, and it then uses the
97/// old position. A semicolon before the colon therefore reads past the end of
98/// the shortened line. This function returns `None` for that input, which is
99/// the safe reading of a path that no upstream test covers. SPEC.md 4.3 records
100/// the behavior as observed.
101pub fn split_line(line: &str) -> Option<(String, String)> {
102    let colon = line.find(':')?;
103    let cut = match line.find(';') {
104        Some(semi) => &line[..semi],
105        None => line,
106    };
107    let lower = cut.to_ascii_lowercase();
108    if colon >= lower.len() {
109        // The comment removed the colon. liblsl reads past the end here.
110        return None;
111    }
112    let name = lower[..colon].trim().to_string();
113    let value = lower[colon + 1..].trim().to_string();
114    Some((name, value))
115}
116
117/// Read a header block. The block ends at a line that starts with a carriage
118/// return, or at an empty line.
119///
120/// Returns the headers and the number of bytes that the block used. Returns
121/// `None` when the buffer holds no complete block.
122pub fn parse_block(buf: &[u8]) -> Option<(Headers, usize)> {
123    let mut headers = Headers::default();
124    let mut pos = 0usize;
125
126    loop {
127        let rest = &buf[pos..];
128        let nl = rest.iter().position(|&b| b == b'\n')?;
129        let raw = &rest[..nl];
130        pos += nl + 1;
131
132        // liblsl checks the first byte for a carriage return
133        // (`src/tcp_server.cpp:602`). An empty line ends the block too.
134        if raw.first() == Some(&b'\r') || raw.is_empty() {
135            return Some((headers, pos));
136        }
137
138        let line = String::from_utf8_lossy(raw)
139            .trim_end_matches('\r')
140            .to_string();
141        match split_line(&line) {
142            Some((k, v)) => headers.fields.push((k, v)),
143            None => headers.ignored.push(line),
144        }
145    }
146}
147
148/// A status line, such as `LSL/110 200 OK`.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct StatusLine {
151    /// The protocol version that the other side runs.
152    pub version: i32,
153    /// The status code.
154    pub code: i32,
155    /// The message after the code. It can hold spaces.
156    pub message: String,
157}
158
159/// What a client does with a status code. SPEC.md 4.5.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum StatusAction {
162    /// Read the answer headers and continue.
163    Proceed,
164    /// Treat the stream as lost, then resolve again.
165    StreamLost,
166    /// Treat this as a redirect, which also marks the stream lost.
167    Redirect,
168    /// Raise an error.
169    Fail,
170}
171
172impl StatusLine {
173    /// Write the line as liblsl writes it. `src/tcp_server.cpp:673`.
174    pub fn to_wire(&self) -> String {
175        format!("LSL/{} {} {}\r\n", self.version, self.code, self.message)
176    }
177
178    /// Read a status line.
179    ///
180    /// liblsl splits on spaces and needs three parts. The first part starts
181    /// with `LSL/` (`src/data_receiver.cpp:196-199`).
182    pub fn parse(line: &str) -> Result<Self, Error> {
183        let clean = line.trim_end_matches(['\r', '\n']);
184        let parts: Vec<&str> = clean.split(' ').filter(|p| !p.is_empty()).collect();
185        if parts.len() < 3 || !parts[0].starts_with("LSL/") {
186            return Err(Error::MalformedStatusLine(clean.to_string()));
187        }
188        let version = parts[0][4..]
189            .parse()
190            .map_err(|_| Error::MalformedStatusLine(clean.to_string()))?;
191        let code = parts[1]
192            .parse()
193            .map_err(|_| Error::MalformedStatusLine(clean.to_string()))?;
194        Ok(StatusLine {
195            version,
196            code,
197            message: parts[2..].join(" "),
198        })
199    }
200
201    /// What a client does with this code. SPEC.md 4.5.
202    ///
203    /// liblsl checks ranges and not exact values
204    /// (`src/data_receiver.cpp:207-212`). The order matters: 404 comes before
205    /// the test for 400 and above.
206    pub fn action(&self) -> StatusAction {
207        if self.code == 404 {
208            StatusAction::StreamLost
209        } else if self.code >= 400 {
210            StatusAction::Fail
211        } else if self.code >= 300 {
212            StatusAction::Redirect
213        } else {
214            StatusAction::Proceed
215        }
216    }
217}
218
219/// A protocol error.
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub enum Error {
222    /// The status line held fewer than three parts, or a wrong prefix.
223    MalformedStatusLine(String),
224    /// The server agreed to a version that this implementation does not read.
225    ///
226    /// Protocol 1.00 carries every sample in a Boost archive
227    /// (`src/sample.cpp:330`). Reading one is out of scope, so a feed that
228    /// agrees to 1.00 stops here rather than decoding the bytes as 1.10.
229    VersionTooOld {
230        /// The version that the server named.
231        theirs: i32,
232    },
233    /// The other side runs a newer major version.
234    VersionTooNew {
235        /// The version that the other side reported.
236        theirs: i32,
237        /// The version that this side supports.
238        ours: i32,
239    },
240    /// The answer named a UID that does not match this connection.
241    UidMismatch {
242        /// The UID that this connection holds.
243        expected: String,
244        /// The UID that the answer named.
245        actual: String,
246    },
247    /// The answer asked for a byte order that this side cannot produce.
248    ByteOrderNotSupported(i32),
249    /// The other side answered with a status code that stops the feed.
250    Status(StatusLine),
251    /// The buffer held no complete block.
252    Incomplete,
253}
254
255impl fmt::Display for Error {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        match self {
258            Error::MalformedStatusLine(l) => write!(f, "the status line is malformed: {l}"),
259            Error::VersionTooOld { theirs } => {
260                write!(
261                    f,
262                    "the server agreed to protocol {theirs}, and this implementation reads 1.10 and above"
263                )
264            }
265            Error::VersionTooNew { theirs, ours } => {
266                write!(
267                    f,
268                    "the other side runs version {theirs} and this side runs {ours}"
269                )
270            }
271            Error::UidMismatch { expected, actual } => {
272                write!(
273                    f,
274                    "the answer named the UID {actual} and this connection holds {expected}"
275                )
276            }
277            Error::ByteOrderNotSupported(v) => write!(f, "the byte order {v} is not supported"),
278            Error::Status(s) => write!(f, "the other side answered {} {}", s.code, s.message),
279            Error::Incomplete => write!(f, "the buffer holds no complete block"),
280        }
281    }
282}
283
284impl std::error::Error for Error {}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn a_line_with_no_colon_is_ignored() {
292        assert_eq!(split_line("this line has no colon"), None);
293    }
294
295    #[test]
296    fn a_semicolon_starts_a_comment() {
297        assert_eq!(
298            split_line("Max-Chunk-Length: 32 ; the rest is a comment"),
299            Some(("max-chunk-length".into(), "32".into()))
300        );
301    }
302
303    #[test]
304    fn a_name_is_case_insensitive() {
305        assert_eq!(
306            split_line("NaTiVe-ByTe-OrDeR: 1234"),
307            Some(("native-byte-order".into(), "1234".into()))
308        );
309    }
310
311    #[test]
312    fn a_comment_before_the_colon_yields_nothing() {
313        // SPEC.md 4.3 records this path as observed. liblsl reads past the end
314        // of the shortened line. This parser refuses instead.
315        assert_eq!(split_line("; a comment: with a colon"), None);
316    }
317
318    #[test]
319    fn a_block_ends_at_a_blank_line() {
320        let buf = b"A: 1\r\nB: 2\r\n\r\ntrailing";
321        let (h, used) = parse_block(buf).expect("a complete block");
322        assert_eq!(
323            h.fields,
324            vec![("a".into(), "1".into()), ("b".into(), "2".into())]
325        );
326        assert_eq!(&buf[used..], b"trailing");
327    }
328
329    #[test]
330    fn an_incomplete_block_returns_nothing() {
331        assert_eq!(parse_block(b"A: 1\r\nB: 2\r\n"), None);
332    }
333
334    #[test]
335    fn a_status_line_round_trips() {
336        let s = StatusLine {
337            version: 110,
338            code: 200,
339            message: "OK".into(),
340        };
341        assert_eq!(s.to_wire(), "LSL/110 200 OK\r\n");
342        assert_eq!(StatusLine::parse(&s.to_wire()).unwrap(), s);
343    }
344
345    #[test]
346    fn a_status_message_can_hold_spaces() {
347        let s = StatusLine::parse("LSL/110 505 Version not supported").unwrap();
348        assert_eq!(s.code, 505);
349        assert_eq!(s.message, "Version not supported");
350        assert_eq!(s.action(), StatusAction::Fail);
351    }
352
353    #[test]
354    fn status_codes_map_to_the_documented_action() {
355        let mk = |c| StatusLine {
356            version: 110,
357            code: c,
358            message: "x".into(),
359        };
360        assert_eq!(mk(200).action(), StatusAction::Proceed);
361        assert_eq!(mk(301).action(), StatusAction::Redirect);
362        assert_eq!(mk(404).action(), StatusAction::StreamLost);
363        assert_eq!(mk(500).action(), StatusAction::Fail);
364        assert_eq!(mk(505).action(), StatusAction::Fail);
365    }
366
367    #[test]
368    fn a_malformed_status_line_is_rejected() {
369        assert!(StatusLine::parse("HTTP/1.1 200 OK").is_err());
370        assert!(StatusLine::parse("LSL/110 200").is_err());
371    }
372
373    #[test]
374    fn a_number_stops_at_trailing_text() {
375        // liblsl reads a number with std::stoi, which ignores trailing text.
376        let mut h = Headers::default();
377        h.fields.push(("value-size".into(), "4 bytes".into()));
378        assert_eq!(h.get_int("value-size"), Some(4));
379    }
380}