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