Skip to main content

weida_http_codec/
uri.rs

1//! `http` and `https` URLs on the client side, origin-form targets on the
2//! server side (RFC 9110 §4.2, RFC 9112 §3.2, RFC 3986 §3).
3//!
4//! Deliberately narrow: a client of this library names an origin and a path,
5//! and nothing else a URL can carry has a meaning for it. Userinfo is refused
6//! (RFC 9110 §4.2.4 deprecates it, and a credential in a URL ends up in logs);
7//! a fragment is dropped (it is never sent, RFC 9110 §7.1); every octet must
8//! be visible ASCII, so a caller with a space or a non-ASCII character in a
9//! path percent-encodes it first. No percent-decoding and no normalization
10//! happen here: the path goes onto the wire exactly as given.
11
12use crate::error::DecodeError;
13use std::borrow::Cow;
14
15/// The two schemes HTTP defines (RFC 9110 §4.2).
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub enum Scheme {
18    /// `http`, port 80.
19    Http,
20    /// `https`, port 443.
21    Https,
22}
23
24impl Scheme {
25    /// 80 or 443.
26    #[must_use]
27    pub const fn default_port(self) -> u16 {
28        match self {
29            Self::Http => 80,
30            Self::Https => 443,
31        }
32    }
33
34    /// `"http"` or `"https"`.
35    #[must_use]
36    pub const fn as_str(self) -> &'static str {
37        match self {
38            Self::Http => "http",
39            Self::Https => "https",
40        }
41    }
42}
43
44/// A parsed absolute URL: the origin and what is sent as the request target.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Target<'a> {
47    /// The scheme.
48    pub scheme: Scheme,
49    /// A registered name or an IP address; an IPv6 literal without its
50    /// brackets. Case as written.
51    pub host: &'a str,
52    /// The port, the scheme's default when the URL names none.
53    pub port: u16,
54    /// The path and query, never empty: an empty path is `/`, and a query
55    /// without a path is `/?query` (RFC 9112 §3.2.1).
56    pub path_and_query: Cow<'a, str>,
57}
58
59const fn malformed(what: &'static str) -> DecodeError {
60    DecodeError::Malformed { what }
61}
62
63fn is_reg_name_byte(b: u8) -> bool {
64    b.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=%".contains(&b)
65}
66
67impl<'a> Target<'a> {
68    /// The authority as sent in `Host` or `:authority`: brackets around an
69    /// IPv6 literal, `:port` only when it is not the scheme's default.
70    #[must_use]
71    pub fn authority(&self) -> String {
72        let mut out = String::with_capacity(self.host.len() + 8);
73        if self.host.contains(':') {
74            out.push('[');
75            out.push_str(self.host);
76            out.push(']');
77        } else {
78            out.push_str(self.host);
79        }
80        if self.port != self.scheme.default_port() {
81            out.push(':');
82            out.push_str(&self.port.to_string());
83        }
84        out
85    }
86
87    /// Parses an absolute `http` or `https` URL.
88    ///
89    /// # Errors
90    ///
91    /// [`DecodeError::Malformed`] naming the rule: `"scheme"`, `"userinfo"`,
92    /// `"host"`, `"IPv6 literal"`, `"port"`, or
93    /// `"a byte outside visible ASCII: percent-encode it"`.
94    pub fn parse(input: &'a str) -> Result<Target<'a>, DecodeError> {
95        if !input.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
96            return Err(malformed("a byte outside visible ASCII: percent-encode it"));
97        }
98        let (scheme, rest) = if input.len() >= 7 && input[..7].eq_ignore_ascii_case("http://") {
99            (Scheme::Http, &input[7..])
100        } else if input.len() >= 8 && input[..8].eq_ignore_ascii_case("https://") {
101            (Scheme::Https, &input[8..])
102        } else {
103            return Err(malformed("scheme"));
104        };
105        let rest = rest.split_once('#').map_or(rest, |(before, _)| before);
106        let split = rest.find(['/', '?']).unwrap_or(rest.len());
107        let (authority, path) = rest.split_at(split);
108        if authority.contains('@') {
109            return Err(malformed("userinfo"));
110        }
111
112        let (host, port) = if let Some(after) = authority.strip_prefix('[') {
113            let (literal, tail) = after.split_once(']').ok_or(malformed("IPv6 literal"))?;
114            if literal.parse::<core::net::Ipv6Addr>().is_err() {
115                return Err(malformed("IPv6 literal"));
116            }
117            let port = match tail {
118                "" => None,
119                _ => Some(tail.strip_prefix(':').ok_or(malformed("port"))?),
120            };
121            (literal, port)
122        } else {
123            match authority.split_once(':') {
124                Some((host, port)) => (host, Some(port)),
125                None => (authority, None),
126            }
127        };
128        if !authority.starts_with('[') && (host.is_empty() || !host.bytes().all(is_reg_name_byte)) {
129            return Err(malformed("host"));
130        }
131        let port = match port {
132            None | Some("") => scheme.default_port(),
133            Some(digits) => {
134                if digits.len() > 5 || !digits.bytes().all(|b| b.is_ascii_digit()) {
135                    return Err(malformed("port"));
136                }
137                match digits.parse::<u32>() {
138                    Ok(p @ 1..=65_535) => p as u16,
139                    _ => return Err(malformed("port")),
140                }
141            }
142        };
143        let path_and_query = if path.is_empty() {
144            Cow::Borrowed("/")
145        } else if path.starts_with('?') {
146            Cow::Owned(format!("/{path}"))
147        } else {
148            Cow::Borrowed(path)
149        };
150        Ok(Target {
151            scheme,
152            host,
153            port,
154            path_and_query,
155        })
156    }
157}
158
159/// Checks a request target in origin form (RFC 9112 §3.2.1): it starts with
160/// `/` and holds visible ASCII only.
161///
162/// # Errors
163///
164/// [`DecodeError::Malformed`] `"request target"`.
165pub fn parse_origin_form(input: &[u8]) -> Result<&str, DecodeError> {
166    if input.first() != Some(&b'/') || !input.iter().all(|b| (0x21..=0x7e).contains(b)) {
167        return Err(malformed("request target"));
168    }
169    core::str::from_utf8(input).map_err(|_| malformed("request target"))
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn what(input: &str) -> &'static str {
177        match Target::parse(input) {
178            Err(DecodeError::Malformed { what }) => what,
179            other => panic!("{input}: {other:?}"),
180        }
181    }
182
183    #[test]
184    fn an_ipv6_authority_keeps_its_brackets_and_a_non_default_port() {
185        let t = Target::parse("https://[::1]:8443/a?b").unwrap();
186        assert_eq!(t.host, "::1");
187        assert_eq!(t.port, 8443);
188        assert_eq!(t.path_and_query, "/a?b");
189        assert_eq!(t.authority(), "[::1]:8443");
190    }
191
192    #[test]
193    fn the_default_port_is_elided_from_the_authority() {
194        let t = Target::parse("HTTP://Example.com:80").unwrap();
195        assert_eq!(t.scheme, Scheme::Http);
196        assert_eq!(t.host, "Example.com");
197        assert_eq!(t.port, 80);
198        assert_eq!(t.path_and_query, "/");
199        assert_eq!(t.authority(), "Example.com");
200        assert_eq!(Target::parse("https://h:444").unwrap().authority(), "h:444");
201    }
202
203    #[test]
204    fn a_query_without_a_path_gets_the_root_path() {
205        assert_eq!(
206            Target::parse("http://h?x=1").unwrap().path_and_query,
207            "/?x=1"
208        );
209    }
210
211    #[test]
212    fn userinfo_is_refused() {
213        assert_eq!(what("https://user:pw@host/"), "userinfo");
214    }
215
216    #[test]
217    fn a_fragment_is_dropped() {
218        let t = Target::parse("http://h/p?q#frag").unwrap();
219        assert_eq!(t.path_and_query, "/p?q");
220    }
221
222    #[test]
223    fn every_rule_has_its_own_name() {
224        assert_eq!(what("ftp://h/"), "scheme");
225        assert_eq!(what("http:///p"), "host");
226        assert_eq!(what("http://h:0/"), "port");
227        assert_eq!(what("http://h:65536/"), "port");
228        assert_eq!(what("http://h:x/"), "port");
229        assert_eq!(what("http://[::g]/"), "IPv6 literal");
230        assert_eq!(
231            what("http://h/a b"),
232            "a byte outside visible ASCII: percent-encode it"
233        );
234        assert_eq!(
235            what("http://h/\u{e4}"),
236            "a byte outside visible ASCII: percent-encode it"
237        );
238        assert_eq!(what("http://h<x>/"), "host");
239    }
240
241    #[test]
242    fn origin_form_starts_with_a_slash() {
243        assert_eq!(parse_origin_form(b"/a?b").unwrap(), "/a?b");
244        assert!(parse_origin_form(b"a").is_err());
245        assert!(parse_origin_form(b"/a b").is_err());
246        assert!(parse_origin_form(b"").is_err());
247    }
248}