Skip to main content

sark_http/request/
mod.rs

1use core::{num::NonZero, ops};
2
3use crate::field::{
4    head::Qualities,
5    metadata::{block, map::record, section::storage},
6};
7
8mod bound;
9pub mod query;
10pub mod raw;
11pub mod span;
12pub use bound::Bound;
13
14mod bytes;
15mod id;
16mod seq;
17mod source;
18
19pub use bytes::Bytes;
20pub use id::Id;
21pub use seq::Seq;
22pub use source::Source;
23use span::Span;
24
25#[repr(transparent)]
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct Tag(u16);
28
29impl Tag {
30    pub const fn new(actual: u16) -> Self {
31        Self(actual)
32    }
33
34    pub const fn actual(self) -> u16 {
35        self.0
36    }
37}
38
39pub trait Slot: Copy {
40    fn into_tag(self) -> storage::Slot;
41
42    fn from_tag(tag: storage::Slot) -> Result<Self, Tag>;
43}
44
45#[derive(Clone, Copy)]
46pub enum Prefix<S> {
47    User(S, usize),
48    Miss(usize),
49    Short,
50}
51
52pub trait Fields: Sized {
53    type Header: Slot;
54    type RawHeaders: Copy + Default;
55    type Error;
56
57    const FULL: bool = false;
58    const ENCODING: bool = false;
59
60    fn prefix(input: &[u8]) -> Prefix<Self::Header>;
61
62    fn slice(name: &[u8]) -> Option<Self::Header>;
63
64    fn span(name: record::Span<'_>) -> Option<Self::Header>;
65
66    fn set(
67        headers: &mut Self::RawHeaders,
68        slot: Self::Header,
69        value: &[u8],
70        span: Span,
71    ) -> Result<(), Self::Error>;
72
73    fn set_encoding(
74        headers: &mut Self::RawHeaders,
75        slot: Self::Header,
76        value: &[u8],
77        span: Span,
78        _encoding: Qualities,
79    ) -> Result<(), Self::Error> {
80        Self::set(headers, slot, value, span)
81    }
82}
83
84#[derive(Clone, Copy)]
85pub enum Discard {}
86
87impl Slot for Discard {
88    fn into_tag(self) -> storage::Slot {
89        match self {}
90    }
91
92    fn from_tag(tag: storage::Slot) -> Result<Self, Tag> {
93        Err(Tag::new(tag.get() as u16))
94    }
95}
96
97impl Fields for () {
98    type Header = Discard;
99    type RawHeaders = ();
100    type Error = core::convert::Infallible;
101
102    fn prefix(_: &[u8]) -> Prefix<Discard> {
103        Prefix::Miss(0)
104    }
105
106    fn slice(_: &[u8]) -> Option<Discard> {
107        None
108    }
109
110    fn span(_: record::Span<'_>) -> Option<Discard> {
111        None
112    }
113
114    fn set(_: &mut (), slot: Discard, _: &[u8], _: Span) -> Result<(), Self::Error> {
115        match slot {}
116    }
117}
118
119const _: () = {
120    assert!(core::mem::size_of::<Tag>() == core::mem::size_of::<u16>());
121    assert!(core::mem::size_of::<Discard>() == 0);
122};
123
124#[repr(u8)]
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub enum RangeError {
127    Order {
128        start: usize,
129        end: usize,
130        capacity: usize,
131    },
132    Bounds {
133        start: usize,
134        end: usize,
135        capacity: usize,
136    },
137}
138
139impl RangeError {
140    pub fn get(raw: &[u8], range: ops::Range<usize>) -> Result<&[u8], Self> {
141        let start = range.start;
142        let end = range.end;
143        let capacity = raw.len();
144        if start > end {
145            return Err(Self::Order {
146                start,
147                end,
148                capacity,
149            });
150        }
151        raw.get(start..end).ok_or(Self::Bounds {
152            start,
153            end,
154            capacity,
155        })
156    }
157}
158
159#[derive(Clone, Copy, PartialEq, Eq)]
160#[repr(u8)]
161pub enum Form {
162    Path = 0,
163    Root = 1,
164    Asterisk = 2,
165    Authority = 3,
166    Extended = 4,
167}
168
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170pub enum Error {
171    Span(span::Error),
172    InvalidRange,
173    OutOfBounds,
174    MissingAuthority,
175}
176
177impl From<span::Error> for Error {
178    fn from(error: span::Error) -> Self {
179        Self::Span(error)
180    }
181}
182
183#[derive(Clone, Copy, PartialEq, Eq)]
184pub struct Target {
185    packed_start_form_plus_one: NonZero<u32>,
186    len: u32,
187}
188
189const TARGET_LANE: usize = 16;
190
191fn target_lane_invalid<const N: usize>(lane: &[u8; N]) -> bool {
192    let mut invalid = false;
193    for &byte in lane {
194        invalid |= (byte <= 0x20) | (byte == 0x7f);
195    }
196    invalid
197}
198
199impl Target {
200    const FORM_BITS: u32 = 3;
201    const FORM_MASK: u32 = (1 << Self::FORM_BITS) - 1;
202
203    pub fn is_valid(bytes: &[u8]) -> bool {
204        let (blocks, tail) = bytes.as_chunks::<{ TARGET_LANE * 4 }>();
205        for block in blocks {
206            if target_lane_invalid(block) {
207                return false;
208            }
209        }
210        let (lanes, tail) = tail.as_chunks::<TARGET_LANE>();
211        for lane in lanes {
212            if target_lane_invalid(lane) {
213                return false;
214            }
215        }
216        tail.iter().all(|&byte| byte > 0x20 && byte != 0x7f)
217    }
218
219    pub const fn check_start(start: usize) -> Result<(), Error> {
220        if start >= (1usize << (u32::BITS - Self::FORM_BITS)) {
221            Err(Error::OutOfBounds)
222        } else {
223            Ok(())
224        }
225    }
226
227    pub const fn from_span(form: Form, span: Span) -> Result<Self, Error> {
228        let start = span.start();
229        if let Err(error) = Self::check_start(start) {
230            return Err(error);
231        }
232        let packed = ((start as u32) << Self::FORM_BITS) | form as u32;
233        let packed = NonZero::<u32>::MIN.saturating_add(packed);
234        Ok(Self {
235            packed_start_form_plus_one: packed,
236            len: span.len() as u32,
237        })
238    }
239
240    pub const fn form(self) -> Form {
241        match (self.packed_start_form_plus_one.get() - 1) & Self::FORM_MASK {
242            0 => Form::Path,
243            1 => Form::Root,
244            2 => Form::Asterisk,
245            3 => Form::Authority,
246            4..=u32::MAX => Form::Extended,
247        }
248    }
249
250    pub const fn start(self) -> usize {
251        ((self.packed_start_form_plus_one.get() - 1) >> Self::FORM_BITS) as usize
252    }
253
254    pub const fn len(self) -> usize {
255        self.len as usize
256    }
257
258    pub const fn is_empty(self) -> bool {
259        self.len == 0
260    }
261
262    pub const fn end(self) -> usize {
263        self.start() + self.len()
264    }
265
266    pub fn get(self, input: &[u8]) -> Option<&[u8]> {
267        input.get(self.start()..self.end())
268    }
269}
270
271#[repr(C)]
272#[derive(Clone, Copy, PartialEq, Eq)]
273pub struct Layout {
274    target: Target,
275    authority: Option<Span>,
276    route: Option<Span>,
277}
278
279impl Layout {
280    /// The single checked construction path for a retained layout: the target
281    /// span is packed for `form` and the companion spans are proved to sit
282    /// inside that target before they are stored.
283    pub fn try_new(
284        form: Form,
285        target: Span,
286        peer: Option<Span>,
287        route: Option<Span>,
288    ) -> Result<Self, Error> {
289        let layout = Self::new(Target::from_span(form, target)?, peer, route);
290        if layout.is_shaped() {
291            Ok(layout)
292        } else {
293            Err(Error::InvalidRange)
294        }
295    }
296
297    /// Stores pre-packed parts without re-checking the shape they must share.
298    ///
299    /// Binding must prove the shape, ranges and bytes for the exact owner,
300    /// either with [`Self::is_valid`] or by preserving parser admission.
301    pub const fn new(target: Target, peer: Option<Span>, route: Option<Span>) -> Self {
302        Self {
303            target,
304            authority: peer,
305            route,
306        }
307    }
308
309    fn from_kept(
310        owner: &[u8],
311        path: Option<ops::Range<usize>>,
312        path_len: Option<usize>,
313        pseudo: Option<ops::Range<usize>>,
314        host: Option<ops::Range<usize>>,
315        plan: block::Plan,
316    ) -> Result<Self, Error> {
317        let path = checked_span(path)?;
318        let pseudo = checked_span(pseudo)?;
319        let host = checked_span(host)?;
320        if path.is_some_and(|span| span.end() > owner.len())
321            || pseudo.is_some_and(|span| span.end() > owner.len())
322            || host.is_some_and(|span| span.end() > owner.len())
323        {
324            return Err(Error::InvalidRange);
325        }
326        let layout = Self::from_spans(path, path_len, pseudo, host, plan)?;
327        if layout.checked(owner).is_some() {
328            Ok(layout)
329        } else {
330            Err(Error::InvalidRange)
331        }
332    }
333
334    fn from_spans(
335        path: Option<Span>,
336        path_len: Option<usize>,
337        pseudo: Option<Span>,
338        host: Option<Span>,
339        plan: block::Plan,
340    ) -> Result<Self, Error> {
341        let selected = match plan.authority() {
342            block::Authority::None => None,
343            block::Authority::Pseudo | block::Authority::Target => pseudo,
344            block::Authority::Host => host,
345        };
346        let (target, peer, route) = match plan.form() {
347            block::Form::Path | block::Form::ExtendedConnect => {
348                let target = path.ok_or(Error::InvalidRange)?;
349                let len = path_len.ok_or(Error::InvalidRange)?;
350                let route = Span::checked(target.start(), len).map_err(Error::Span)?;
351                (target, selected, Some(route))
352            }
353            block::Form::Asterisk => (path.ok_or(Error::InvalidRange)?, selected, None),
354            block::Form::Connect => (selected.ok_or(Error::MissingAuthority)?, None, None),
355        };
356        let form = match plan.form() {
357            block::Form::Path => Form::Path,
358            block::Form::Asterisk => Form::Asterisk,
359            block::Form::Connect => Form::Authority,
360            block::Form::ExtendedConnect => Form::Extended,
361        };
362        let target = Target::from_span(form, target)?;
363        Ok(Self::new(target, peer, route))
364    }
365
366    pub const fn target(self) -> Target {
367        self.target
368    }
369
370    pub const fn authority(self) -> Option<Span> {
371        if matches!(self.target.form(), Form::Authority) {
372            Some(Span::from_target(self.target))
373        } else {
374            self.authority
375        }
376    }
377
378    pub const fn route(self) -> Option<Span> {
379        self.route
380    }
381
382    pub fn route_path(self, owner: &[u8]) -> Option<&[u8]> {
383        match self.target.form() {
384            Form::Root => Some(b"/"),
385            Form::Asterisk | Form::Authority => Some(b"*"),
386            Form::Path | Form::Extended => self.route?.get(owner),
387        }
388    }
389
390    pub fn authority_in(self, owner: &[u8]) -> Option<&[u8]> {
391        self.authority()?.get(owner)
392    }
393
394    pub const fn require(self) -> Result<Self, Error> {
395        if matches!(self.target.form(), Form::Authority) || self.authority.is_some() {
396            Ok(self)
397        } else {
398            Err(Error::MissingAuthority)
399        }
400    }
401
402    /// The owner-independent structure every retained layout shares.
403    const fn is_shaped(self) -> bool {
404        match self.target.form() {
405            Form::Path | Form::Extended => match self.route {
406                Some(route) => {
407                    route.start() >= self.target.start() && route.end() <= self.target.end()
408                }
409                None => false,
410            },
411            Form::Root => match self.route {
412                Some(route) => {
413                    route.is_empty()
414                        && route.start() >= self.target.start()
415                        && route.start() <= self.target.end()
416                }
417                None => false,
418            },
419            Form::Asterisk | Form::Authority => self.route.is_none(),
420        }
421    }
422
423    pub fn is_valid(self, owner: &[u8]) -> bool {
424        self.checked(owner).is_some_and(Target::is_valid)
425    }
426
427    fn checked(self, owner: &[u8]) -> Option<&[u8]> {
428        if !self.is_shaped() || self.authority.is_some_and(|span| span.end() > owner.len()) {
429            return None;
430        }
431        let target = self.target.get(owner)?;
432        let shaped = match self.target.form() {
433            Form::Path | Form::Extended => self.route.is_some_and(|route| {
434                route.end() == self.target.end() || owner.get(route.end()) == Some(&b'?')
435            }),
436            Form::Root => self.route.is_some_and(|route| {
437                route.start() == self.target.end() || owner.get(route.start()) == Some(&b'?')
438            }),
439            Form::Asterisk => target == b"*",
440            Form::Authority => true,
441        };
442        shaped.then_some(target)
443    }
444}
445
446fn checked_span(range: Option<ops::Range<usize>>) -> Result<Option<Span>, Error> {
447    range.map(Span::from_range).transpose().map_err(Error::Span)
448}
449
450const _: () = assert!(core::mem::size_of::<Target>() == 8);
451const _: () = assert!(core::mem::size_of::<Option<Target>>() == 8);
452const _: () = assert!(core::mem::size_of::<Layout>() == 24);