Skip to main content

xila_http/
framing.rs

1//! Sans-I/O response framing. The caller owns the head and body buffers.
2//! Head parsing uses `N * size_of::<httparse::Header>()` bytes of stack.
3//! Body decoding has constant storage and compacts payload in place.
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum Error {
7    InvalidHead,
8    HeadersTooLarge,
9    InvalidFraming,
10    Truncated,
11    UnsupportedUpgrade,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum BodyKind {
16    Empty,
17    Length(u64),
18    Chunked,
19    UntilClose,
20}
21
22#[derive(Debug, Clone, Copy)]
23pub struct ResponseHead {
24    pub length: usize,
25    pub status: u16,
26    pub body: BodyKind,
27}
28
29/// Parse a contiguous head without allocating. `None` requests more bytes.
30/// The caller must bound the input buffer and handle informational responses.
31pub fn parse_response_head<const N: usize>(
32    input: &[u8],
33    head_request: bool,
34) -> Result<Option<ResponseHead>, Error> {
35    let mut headers = [httparse::EMPTY_HEADER; N];
36    let mut response = httparse::Response::new(&mut headers);
37    let length = match response.parse(input) {
38        Ok(httparse::Status::Partial) => return Ok(None),
39        Ok(httparse::Status::Complete(n)) => n,
40        Err(httparse::Error::TooManyHeaders) => return Err(Error::HeadersTooLarge),
41        Err(_) => return Err(Error::InvalidHead),
42    };
43    let status = response.code.ok_or(Error::InvalidHead)?;
44    if status == 101 {
45        return Err(Error::UnsupportedUpgrade);
46    }
47    if head_request || (100..200).contains(&status) || status == 204 || status == 304 {
48        return Ok(Some(ResponseHead {
49            length,
50            status,
51            body: BodyKind::Empty,
52        }));
53    }
54    let mut content_length = None;
55    let mut transfer = false;
56    let mut chunked = false;
57    for header in response.headers.iter() {
58        if header.name.eq_ignore_ascii_case("Transfer-Encoding") {
59            transfer = true;
60            let value = core::str::from_utf8(header.value).map_err(|_| Error::InvalidFraming)?;
61            for coding in value.split(',') {
62                if chunked || coding.trim().is_empty() {
63                    return Err(Error::InvalidFraming);
64                }
65                chunked = coding.trim().eq_ignore_ascii_case("chunked");
66            }
67        }
68    }
69    if !transfer {
70        for header in response.headers.iter() {
71            if header.name.eq_ignore_ascii_case("Content-Length") {
72                for value in header.value.split(|b| *b == b',') {
73                    let value = core::str::from_utf8(value)
74                        .map_err(|_| Error::InvalidFraming)?
75                        .trim();
76                    if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
77                        return Err(Error::InvalidFraming);
78                    }
79                    let value = value.parse::<u64>().map_err(|_| Error::InvalidFraming)?;
80                    if content_length.is_some_and(|previous| previous != value) {
81                        return Err(Error::InvalidFraming);
82                    }
83                    content_length = Some(value);
84                }
85            }
86        }
87    }
88    let body = if chunked {
89        BodyKind::Chunked
90    } else if transfer {
91        BodyKind::UntilClose
92    } else if let Some(n) = content_length {
93        BodyKind::Length(n)
94    } else {
95        BodyKind::UntilClose
96    };
97    Ok(Some(ResponseHead {
98        length,
99        status,
100        body,
101    }))
102}
103
104#[derive(Debug, Clone, Copy)]
105enum ChunkState {
106    Size,
107    SizeWhitespace,
108    Extension,
109    SizeLf,
110    Data(u64),
111    DataCr,
112    DataLf,
113    Trailer,
114    TrailerLf,
115    Done,
116}
117
118pub struct BodyDecoder {
119    kind: BodyKind,
120    state: ChunkState,
121    // At most 16 hexadecimal digits plus CRLF for httparse.
122    digits: [u8; 18],
123    digits_len: u8,
124    line_len: u16,
125}
126
127impl BodyDecoder {
128    pub fn new(kind: BodyKind) -> Self {
129        Self {
130            kind,
131            state: ChunkState::Size,
132            digits: [0; 18],
133            digits_len: 0,
134            line_len: 0,
135        }
136    }
137    pub fn is_complete(&self) -> bool {
138        matches!(self.kind, BodyKind::Empty | BodyKind::Length(0))
139            || matches!(self.state, ChunkState::Done)
140    }
141    pub fn finish(&self) -> Result<(), Error> {
142        if self.is_complete() || self.kind == BodyKind::UntilClose {
143            Ok(())
144        } else {
145            Err(Error::Truncated)
146        }
147    }
148    /// Consume all input, replacing it with decoded payload. Bytes beyond the
149    /// framed message are ignored (this client does not pipeline responses).
150    pub fn decode(&mut self, input: &mut [u8]) -> Result<usize, Error> {
151        match &mut self.kind {
152            BodyKind::Empty => return Ok(0),
153            BodyKind::UntilClose => return Ok(input.len()),
154            BodyKind::Length(remaining) => {
155                let n = (*remaining).min(input.len() as u64) as usize;
156                *remaining -= n as u64;
157                return Ok(n);
158            }
159            BodyKind::Chunked => {}
160        }
161        let mut output = 0;
162        for i in 0..input.len() {
163            let byte = input[i];
164            match self.state {
165                ChunkState::Size => {
166                    if byte.is_ascii_hexdigit() {
167                        if self.digits_len == 16 {
168                            return Err(Error::InvalidFraming);
169                        }
170                        self.digits[self.digits_len as usize] = byte;
171                        self.digits_len += 1;
172                    } else if matches!(byte, b' ' | b'\t') && self.digits_len > 0 {
173                        self.state = ChunkState::SizeWhitespace;
174                    } else if byte == b';' && self.digits_len > 0 {
175                        self.state = ChunkState::Extension;
176                    } else if byte == b'\r' && self.digits_len > 0 {
177                        self.state = ChunkState::SizeLf;
178                    } else {
179                        return Err(Error::InvalidFraming);
180                    }
181                }
182                ChunkState::SizeWhitespace => {
183                    if byte == b';' {
184                        self.state = ChunkState::Extension;
185                    } else if !matches!(byte, b' ' | b'\t') {
186                        return Err(Error::InvalidFraming);
187                    }
188                }
189                ChunkState::Extension => {
190                    self.line_len = self.line_len.checked_add(1).ok_or(Error::InvalidFraming)?;
191                    if byte == b'\r' {
192                        self.state = ChunkState::SizeLf;
193                    } else if byte == b'\n' || byte < 0x20 && byte != b'\t' {
194                        return Err(Error::InvalidFraming);
195                    }
196                }
197                ChunkState::SizeLf => {
198                    if byte != b'\n' {
199                        return Err(Error::InvalidFraming);
200                    }
201                    let n = self.digits_len as usize;
202                    self.digits[n..n + 2].copy_from_slice(b"\r\n");
203                    let size = match httparse::parse_chunk_size(&self.digits[..n + 2]) {
204                        Ok(httparse::Status::Complete((_, size))) => size,
205                        _ => return Err(Error::InvalidFraming),
206                    };
207                    self.digits_len = 0;
208                    self.line_len = 0;
209                    self.state = if size == 0 {
210                        ChunkState::Trailer
211                    } else {
212                        ChunkState::Data(size)
213                    };
214                }
215                ChunkState::Data(remaining) => {
216                    input[output] = byte;
217                    output += 1;
218                    self.state = if remaining == 1 {
219                        ChunkState::DataCr
220                    } else {
221                        ChunkState::Data(remaining - 1)
222                    };
223                }
224                ChunkState::DataCr => {
225                    if byte != b'\r' {
226                        return Err(Error::InvalidFraming);
227                    }
228                    self.state = ChunkState::DataLf;
229                }
230                ChunkState::DataLf => {
231                    if byte != b'\n' {
232                        return Err(Error::InvalidFraming);
233                    }
234                    self.state = ChunkState::Size;
235                }
236                ChunkState::Trailer => {
237                    if byte == b'\r' {
238                        self.state = ChunkState::TrailerLf;
239                    } else if byte == b'\n' {
240                        return Err(Error::InvalidFraming);
241                    } else {
242                        self.line_len =
243                            self.line_len.checked_add(1).ok_or(Error::InvalidFraming)?;
244                    }
245                }
246                ChunkState::TrailerLf => {
247                    if byte != b'\n' {
248                        return Err(Error::InvalidFraming);
249                    }
250                    self.state = if self.line_len == 0 {
251                        ChunkState::Done
252                    } else {
253                        ChunkState::Trailer
254                    };
255                    self.line_len = 0;
256                }
257                ChunkState::Done => break,
258            }
259        }
260        Ok(output)
261    }
262}