Skip to main content

sark_http/h1/field/
mod.rs

1//! HTTP/1 field syntax and borrow-free field state.
2
3use core::{mem, num::NonZero};
4
5use crate::{
6    field::{
7        self,
8        head::{Error::Routing, Flags, Name, Qualities, headers::Known},
9        scan::{self, Match},
10        text::{Ascii, IntError},
11    },
12    h1::head::{self, Admission, line::Version, request::Fields},
13    request::{self, span},
14};
15
16mod cursor;
17pub mod expect;
18pub mod syntax;
19mod transfer;
20pub mod value;
21
22pub use cursor::Cursor;
23pub use transfer::Transfer;
24
25#[derive(Clone, Copy, PartialEq, Eq)]
26pub struct Entry<'owner> {
27    name: &'owner [u8],
28    value: &'owner [u8],
29    name_span: span::Span,
30    value_span: span::Span,
31    line_span: span::Span,
32}
33
34impl<'owner> Entry<'owner> {
35    /// Splits one CRLF-terminated field without validating its name or value.
36    /// Admitted sections retain their grammar proof; arbitrary input returns `None`
37    /// when a required delimiter is missing. The value retains its original OWS.
38    pub fn split(bytes: &[u8]) -> Option<(&[u8], &[u8], &[u8])> {
39        let end = Match::find(b'\r', bytes)?;
40        let rest = end.suffix().strip_prefix(b"\n")?;
41        let colon = Match::find(b':', end.prefix())?;
42        Some((colon.prefix(), colon.suffix(), rest))
43    }
44
45    pub(crate) fn kind(&self) -> Name {
46        match Name::from_h1(self.name()) {
47            Some(name) => name,
48            None => Name::Regular,
49        }
50    }
51
52    pub fn name(&self) -> &'owner [u8] {
53        self.name
54    }
55
56    pub fn value(&self) -> &'owner [u8] {
57        self.value
58    }
59
60    pub const fn name_span(&self) -> span::Span {
61        self.name_span
62    }
63
64    pub const fn value_span(&self) -> span::Span {
65        self.value_span
66    }
67
68    pub const fn line_span(&self) -> span::Span {
69        self.line_span
70    }
71
72    pub fn apply<R: request::Fields, A: Admission, const NEGOTIATE: bool>(
73        self,
74        raw: &mut R::RawHeaders,
75        permit: &mut A,
76        fields: &mut Fields,
77        flags: &mut Flags,
78        version: Version,
79    ) -> Result<(), head::Error<R::Error, A::Error>> {
80        let slot = R::slice(self.name);
81        let known = Known::from_name(self.name);
82        let mut encoding = None;
83        if let Some(known) = known {
84            let skip =
85                matches!(known, Known::AcceptEncoding) && slot.is_none() && !R::FULL && !NEGOTIATE;
86            if !skip {
87                encoding = if R::ENCODING && matches!(known, Known::AcceptEncoding) {
88                    Qualities::try_apply(&mut fields.message, flags, self.value).map(Some)
89                } else {
90                    known
91                        .apply(fields, flags, self.value, version)
92                        .map(|()| None)
93                }
94                .map_err(|cause| head::Error::Field {
95                    start: self.line_span.start(),
96                    available: self.line_span.len(),
97                    cause,
98                })?;
99            }
100            if matches!(known, Known::Host) {
101                fields.routing = fields.routing.try_host(self.value_span).map_err(|cause| {
102                    head::Error::Field {
103                        start: self.line_span.start(),
104                        available: self.line_span.len(),
105                        cause: Routing(cause),
106                    }
107                })?;
108            }
109        }
110        if let Some(slot) = slot {
111            match encoding {
112                Some(encoding) => R::set_encoding(raw, slot, self.value, self.value_span, encoding),
113                None => R::set(raw, slot, self.value, self.value_span),
114            }
115            .map_err(head::Error::Header)?;
116        }
117        if A::FIELDS {
118            permit
119                .field(self.name, self.value, self.value_span)
120                .map_err(head::Error::Admission)?;
121        }
122        Ok(())
123    }
124}
125
126const _: () = assert!(mem::size_of::<Entry<'_>>() == 56);
127
128pub struct Line {
129    start: u32,
130    raw: u32,
131    end: u32,
132}
133
134impl Line {
135    pub const fn start(&self) -> usize {
136        self.start as usize
137    }
138
139    pub const fn wire_end(&self) -> usize {
140        self.end as usize + 2
141    }
142
143    pub fn bind(self, bytes: &[u8]) -> Result<Entry<'_>, syntax::Error> {
144        let start = self.start as usize;
145        let raw = (self.raw - self.start) as usize;
146        let end = (self.end - self.start) as usize;
147        let name = bytes.get(..raw - 1).ok_or(syntax::Error::Invalid)?;
148        let text = bytes.get(raw..end).ok_or(syntax::Error::Invalid)?;
149        let trimmed = text.trim_ascii_start();
150        let pos = self.end as usize - trimmed.len();
151        let value = crate::field::Error::trim_ows(trimmed);
152        Ok(Entry {
153            name,
154            value,
155            name_span: span::Span::from_range(start..self.raw as usize - 1)
156                .or(Err(syntax::Error::Invalid))?,
157            value_span: span::Span::checked(pos, value.len()).or(Err(syntax::Error::Invalid))?,
158            line_span: span::Span::from_range(start..self.end as usize + 2)
159                .or(Err(syntax::Error::Invalid))?,
160        })
161    }
162}
163
164#[derive(Clone, Copy, PartialEq, Eq)]
165pub struct End {
166    fields: u32,
167    wire: NonZero<u32>,
168}
169
170impl End {
171    const fn new(fields: u32, wire: NonZero<u32>) -> Self {
172        Self { fields, wire }
173    }
174
175    pub const fn fields(self) -> u32 {
176        self.fields
177    }
178
179    pub const fn wire_len(self) -> NonZero<u32> {
180        self.wire
181    }
182}
183
184const _: () = {
185    assert!(mem::size_of::<End>() == 8);
186    assert!(mem::size_of::<Option<End>>() == 8);
187};
188
189pub enum Progress {
190    Field(Line),
191    More,
192    End(End),
193}
194
195const _: () = assert!(mem::size_of::<Progress>() == 16);
196
197#[derive(Clone, Copy, PartialEq, Eq)]
198pub(in crate::h1) struct Limit {
199    count: u32,
200    line_bytes: u32,
201}
202
203impl Limit {
204    pub(in crate::h1) const fn new(count: usize, line: usize) -> Self {
205        Self {
206            count: Self::narrow(count),
207            line_bytes: Self::narrow(line),
208        }
209    }
210
211    const fn narrow(value: usize) -> u32 {
212        if value > u32::MAX as usize {
213            u32::MAX
214        } else {
215            value as u32
216        }
217    }
218}
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
221pub enum Error {
222    DuplicateContentLength,
223    ContentLengthWithTransferEncoding,
224    InvalidContentLength(IntError),
225    InvalidTransferEncoding(value::Error),
226}
227
228/// Accumulated connection-option semantics shared by request and response
229/// scanners. Unknown valid tokens are intentionally ignored; malformed token
230/// bytes fail admission.
231#[repr(transparent)]
232#[derive(Clone, Copy, Default, PartialEq, Eq)]
233pub struct Connection(u8);
234
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub struct TokenError {
237    pub index: usize,
238    pub byte: u8,
239}
240
241impl Connection {
242    pub(crate) const CLOSE: Self = Self(1 << 0);
243    pub(crate) const KEEP_ALIVE: Self = Self(1 << 1);
244    const UPGRADE: u8 = 1 << 2;
245
246    pub fn try_push(mut self, value: &[u8]) -> Result<Self, TokenError> {
247        let mut rest = value;
248        while !rest.is_empty() {
249            let (token, tail) = scan::split_token(field::trim_ows_start(rest));
250            if token.eq_ignore_ascii_case(b"close") {
251                self.0 |= Self::CLOSE.0;
252            } else if token.eq_ignore_ascii_case(b"keep-alive") {
253                self.0 |= Self::KEEP_ALIVE.0;
254            } else if token.eq_ignore_ascii_case(b"upgrade") {
255                self.0 |= Self::UPGRADE;
256            }
257            let [first, ..] = tail else { break };
258            match field::trim_ows_start(tail) {
259                [b',', next @ ..] => rest = next,
260                [] => break,
261                _ => {
262                    return Err(TokenError {
263                        index: value.len() - tail.len(),
264                        byte: *first,
265                    });
266                }
267            }
268        }
269        Ok(self)
270    }
271
272    /// Merges connection options that were parsed by another scanner branch.
273    #[doc(hidden)]
274    pub fn append(&mut self, fields: Self) {
275        self.0 |= fields.0;
276    }
277
278    pub const fn is_close(self) -> bool {
279        self.0 & Self::CLOSE.0 != 0
280    }
281
282    pub const fn is_keep(self) -> bool {
283        self.0 & Self::KEEP_ALIVE.0 != 0
284    }
285
286    pub const fn can_persist(self, version: Version) -> bool {
287        !self.is_close() && (matches!(version, Version::Eleven) || self.is_keep())
288    }
289
290    pub const fn is_upgrade(self) -> bool {
291        self.0 & Self::UPGRADE != 0
292    }
293}
294
295/// Advisory persistence parameters accumulated across every `Keep-Alive`
296/// field. Malformed and unknown parameters are ignored because they cannot
297/// change message framing; the shortest valid timeout wins deterministically.
298#[derive(Clone, Copy, Default, PartialEq, Eq)]
299pub struct KeepAlive {
300    timeout: Option<u64>,
301}
302
303impl KeepAlive {
304    pub(crate) fn parse(mut prior: Option<u64>, value: &[u8]) -> Option<u64> {
305        for raw in value.split(|byte| *byte == b',') {
306            let param = field::Error::trim_ows(raw);
307            let Some(split) = param.iter().position(|byte| *byte == b'=') else {
308                continue;
309            };
310            let name = field::Error::trim_ows(&param[..split]);
311            if !name.eq_ignore_ascii_case(b"timeout") {
312                continue;
313            }
314            let Ok(timeout) = Ascii::new(field::Error::trim_ows(&param[split + 1..])).parse_u64()
315            else {
316                continue;
317            };
318            prior = Some(prior.map_or(timeout, |current| current.min(timeout)));
319        }
320        prior
321    }
322
323    pub(crate) const fn new(timeout: Option<u64>) -> Self {
324        Self { timeout }
325    }
326
327    pub const fn timeout_secs(self) -> Option<u64> {
328        self.timeout
329    }
330}
331
332const _: () = assert!(mem::size_of::<Connection>() == 1);