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