Skip to main content

sark_http/h1/
target.rs

1//! HTTP/1 request-target and authority admission.
2
3use crate::{
4    field::{self, scan::Match},
5    h1::head::line::Version,
6    method::Known,
7    request::{self, span},
8    uri::{self, path},
9};
10
11#[derive(Clone, Copy, PartialEq, Eq, Debug)]
12pub enum Error {
13    InvalidHost,
14    MissingHost,
15    EmptyAuthority,
16    InvalidTarget,
17    Path(path::Error),
18    Authority(uri::Error),
19    Span(Operation, span::Error),
20    Layout(request::Error),
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum HostError {
25    Authority(uri::Error),
26    Duplicate,
27}
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct Invalid;
31
32#[derive(Clone, Copy, PartialEq, Eq)]
33#[repr(u8)]
34#[derive(Debug)]
35pub enum Operation {
36    Path,
37    Query,
38    Authority,
39    PathShift,
40    QueryShift,
41    AuthorityShift,
42}
43
44impl Operation {
45    fn check(self, start: usize, len: usize) -> Result<span::Span, Error> {
46        match span::Span::checked(start, len) {
47            Ok(span) => Ok(span),
48            Err(cause) => Err(Error::Span(self, cause)),
49        }
50    }
51
52    fn shift(self, span: span::Span, base: usize) -> Result<span::Span, Error> {
53        match span.shifted(base) {
54            Ok(span) => Ok(span),
55            Err(cause) => Err(Error::Span(self, cause)),
56        }
57    }
58}
59
60#[derive(Clone, Copy, PartialEq, Eq)]
61#[repr(u8)]
62pub enum Host {
63    Empty,
64    Authority,
65}
66
67#[derive(Clone, Copy, Default, PartialEq, Eq)]
68pub struct Request {
69    host: Option<Host>,
70}
71
72#[derive(Clone, Copy, PartialEq, Eq)]
73#[repr(u8)]
74pub enum Form {
75    Origin,
76    Absolute,
77    Authority,
78    Asterisk,
79}
80
81#[derive(Clone, Copy, PartialEq, Eq)]
82#[repr(u8)]
83enum Kind {
84    Origin,
85    AbsolutePath,
86    AbsoluteRoot,
87    AbsoluteOpaque,
88    Authority,
89    Asterisk,
90}
91
92/// Validated target ranges, relative until [`Target::shifted`] binds an owner.
93#[derive(Clone, Copy, PartialEq, Eq)]
94pub struct Target {
95    pub(super) ranges: Ranges,
96    pub(super) shape: Shape,
97}
98
99#[derive(Clone, Copy, PartialEq, Eq)]
100pub(super) struct Shape {
101    authority: Option<span::Span>,
102    kind: Kind,
103}
104
105impl Shape {
106    pub(super) const ORIGIN: Self = Self {
107        authority: None,
108        kind: Kind::Origin,
109    };
110}
111
112#[derive(Clone, Copy, Default, PartialEq, Eq)]
113pub(super) struct Ranges {
114    path: span::Span,
115    query: Option<span::Span>,
116}
117
118impl Ranges {
119    pub(super) fn try_new(scan: path::Plan, base: usize) -> Result<Self, Error> {
120        let path = Operation::Path.check(base, scan.path_end())?;
121        let query = match scan.query() {
122            Some(start) => {
123                Some(Operation::Query.check(base + start.get(), scan.end() - start.get())?)
124            }
125            None => None,
126        };
127        Ok(Self { path, query })
128    }
129}
130
131impl Target {
132    pub fn parse(method: &[u8], target: &[u8]) -> Result<Self, Error> {
133        if field::Error::name(method).is_err() {
134            return Err(Error::InvalidTarget);
135        }
136        Self::for_method(Self::method(method), target)
137    }
138
139    pub(super) fn method(bytes: &[u8]) -> Option<Known> {
140        match bytes {
141            b"CONNECT" => Some(Known::Connect),
142            b"OPTIONS" => Some(Known::Options),
143            _ => None,
144        }
145    }
146
147    fn for_method(method: Option<Known>, target: &[u8]) -> Result<Self, Error> {
148        if target.is_empty() {
149            return Err(Error::InvalidTarget);
150        }
151        if target == b"*" {
152            return if method == Some(Known::Options) {
153                Ok(Self {
154                    ranges: Ranges::default(),
155                    shape: Shape {
156                        authority: None,
157                        kind: Kind::Asterisk,
158                    },
159                })
160            } else {
161                Err(Error::InvalidTarget)
162            };
163        }
164        if method == Some(Known::Connect) {
165            return if uri::Authority::has_nonempty_port(target) == Ok(true) {
166                Ok(Self {
167                    ranges: Ranges::default(),
168                    shape: Shape {
169                        authority: Some(Operation::Authority.check(0, target.len())?),
170                        kind: Kind::Authority,
171                    },
172                })
173            } else {
174                Err(Error::InvalidTarget)
175            };
176        }
177        if target[0] == b'/' {
178            let scan = path::Scan::new(target).complete().map_err(Error::Path)?;
179            return Ok(Self {
180                ranges: Ranges::try_new(scan, 0)?,
181                shape: Shape::ORIGIN,
182            });
183        }
184
185        let rest = scheme(target).ok_or(Error::InvalidTarget)?;
186        let rest_at = target.len() - rest.len();
187        let (auth, path_at, suffix) = if let Some(rest) = rest.strip_prefix(b"//") {
188            let span_at = rest_at + 2;
189            let (value, suffix) = match Match::find2(b'/', b'?', rest) {
190                Some(found) => (found.prefix(), found.tail()),
191                None => (rest, &[][..]),
192            };
193            let auth = if value.is_empty() {
194                None
195            } else {
196                uri::Authority::validate(value).map_err(Error::Authority)?;
197                Some(Operation::Authority.check(span_at, value.len())?)
198            };
199            (auth, span_at + value.len(), suffix)
200        } else {
201            (None, rest_at, rest)
202        };
203
204        let scan = path::Scan::new(suffix).complete().map_err(Error::Path)?;
205        let ranges = Ranges::try_new(scan, path_at)?;
206        let kind = if ranges.path.is_empty() {
207            Kind::AbsoluteRoot
208        } else if suffix.starts_with(b"/") {
209            Kind::AbsolutePath
210        } else {
211            Kind::AbsoluteOpaque
212        };
213        Ok(Self {
214            ranges,
215            shape: Shape {
216                authority: auth,
217                kind,
218            },
219        })
220    }
221
222    pub(super) fn at(method: Option<Known>, bytes: &[u8], base: usize) -> Result<Self, Error> {
223        Self::for_method(method, bytes)?.shifted(base)
224    }
225
226    pub fn shifted(self, base: usize) -> Result<Self, Error> {
227        Ok(Self {
228            ranges: Ranges {
229                path: Operation::PathShift.shift(self.ranges.path, base)?,
230                query: self
231                    .ranges
232                    .query
233                    .map(|span| Operation::QueryShift.shift(span, base))
234                    .transpose()?,
235            },
236            shape: Shape {
237                authority: self
238                    .shape
239                    .authority
240                    .map(|span| Operation::AuthorityShift.shift(span, base))
241                    .transpose()?,
242                kind: self.shape.kind,
243            },
244        })
245    }
246
247    pub const fn form(self) -> Form {
248        match self.shape.kind {
249            Kind::Origin => Form::Origin,
250            Kind::AbsolutePath | Kind::AbsoluteRoot | Kind::AbsoluteOpaque => Form::Absolute,
251            Kind::Authority => Form::Authority,
252            Kind::Asterisk => Form::Asterisk,
253        }
254    }
255
256    /// The source range backing the normalized route path. An empty range is
257    /// intentional for an absolute URI whose omitted path routes as `/`.
258    pub const fn path_span(self) -> span::Span {
259        self.ranges.path
260    }
261
262    pub const fn query_span(self) -> Option<span::Span> {
263        self.ranges.query
264    }
265
266    pub const fn authority(self) -> Option<span::Span> {
267        self.shape.authority
268    }
269
270    pub(crate) fn layout(
271        self,
272        target: span::Span,
273        span: span::Span,
274    ) -> Result<request::Layout, Error> {
275        let (form, route) = match self.shape.kind {
276            Kind::Origin | Kind::AbsolutePath => (request::Form::Path, Some(self.ranges.path)),
277            Kind::AbsoluteRoot => (request::Form::Root, Some(self.ranges.path)),
278            Kind::AbsoluteOpaque => (request::Form::Path, None),
279            Kind::Authority => (request::Form::Authority, None),
280            Kind::Asterisk => (request::Form::Asterisk, None),
281        };
282        let selected = (!matches!(form, request::Form::Authority)).then_some(span);
283        request::Layout::try_new(form, target, selected, route).map_err(Error::Layout)
284    }
285
286    /// Projects the path used by an origin router without allocating or
287    /// rewriting the original request-target.
288    pub fn route_path<'a>(&self, request: &'a [u8]) -> Option<&'a [u8]> {
289        match self.shape.kind {
290            Kind::Origin | Kind::AbsolutePath => self.ranges.path.get(request),
291            Kind::AbsoluteRoot => Some(b"/"),
292            Kind::Authority | Kind::Asterisk => Some(b"*"),
293            Kind::AbsoluteOpaque => None,
294        }
295    }
296}
297
298#[derive(Clone, Copy, PartialEq, Eq)]
299#[repr(u8)]
300pub enum Source {
301    Empty,
302    Host,
303    Target,
304}
305
306#[derive(Clone, Copy, PartialEq, Eq)]
307#[repr(u8)]
308pub enum Policy {
309    AllowEmpty,
310    Require,
311}
312
313impl Request {
314    pub fn try_host(self, value: &[u8]) -> Result<Self, HostError> {
315        let host = Host::parse(value).map_err(HostError::Authority)?;
316        self.with_host(host)
317    }
318
319    pub(crate) fn with_host(self, host: Host) -> Result<Self, HostError> {
320        match self.host {
321            None => Ok(Self { host: Some(host) }),
322            Some(_) => Err(HostError::Duplicate),
323        }
324    }
325
326    pub const fn has_host(self) -> bool {
327        self.host.is_some()
328    }
329
330    /// Finalizes authority semantics from a request-target that was already
331    /// validated by the request-line parser.
332    pub fn finish(self, target: Target, version: Version, policy: Policy) -> Result<Source, Error> {
333        if version == Version::Eleven && self.host.is_none() {
334            return Err(Error::MissingHost);
335        }
336
337        match target.form() {
338            Form::Authority => Ok(Source::Target),
339            Form::Absolute if target.shape.authority.is_some() => Ok(Source::Target),
340            Form::Origin | Form::Asterisk if self.host == Some(Host::Authority) => Ok(Source::Host),
341            _ => match policy {
342                Policy::Require => Err(Error::EmptyAuthority),
343                Policy::AllowEmpty => Ok(Source::Empty),
344            },
345        }
346    }
347}
348
349impl Host {
350    pub fn parse(value: &[u8]) -> Result<Self, uri::Error> {
351        Self::parse_trimmed(field::Error::trim_ows(value))
352    }
353
354    pub(crate) fn parse_trimmed(value: &[u8]) -> Result<Self, uri::Error> {
355        if value.is_empty() {
356            return Ok(Self::Empty);
357        }
358        uri::Authority::validate(value)?;
359        Ok(Self::Authority)
360    }
361}
362
363fn scheme(value: &[u8]) -> Option<&[u8]> {
364    let mut bytes = value.iter();
365    if !bytes.next()?.is_ascii_alphabetic() {
366        return None;
367    }
368    while let Some(&byte) = bytes.next() {
369        if byte == b':' {
370            return Some(bytes.as_slice());
371        }
372        if !(byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.')) {
373            return None;
374        }
375    }
376    None
377}
378
379const _: () = assert!(core::mem::size_of::<Target>() <= 4 * core::mem::size_of::<usize>());
380const _: () =
381    assert!(core::mem::size_of::<Option<span::Span>>() == core::mem::size_of::<span::Span>());
382const _: () = assert!(core::mem::size_of::<Request>() == 1);
383const _: () = assert!(core::mem::size_of::<Operation>() == 1);
384const _: () = assert!(core::mem::size_of::<Error>() == 5 * core::mem::size_of::<usize>());
385const _: () = assert!(core::mem::size_of::<Option<Error>>() == core::mem::size_of::<Error>());