1use crate::error::DecodeError;
13use std::borrow::Cow;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub enum Scheme {
18 Http,
20 Https,
22}
23
24impl Scheme {
25 #[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 #[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#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Target<'a> {
47 pub scheme: Scheme,
49 pub host: &'a str,
52 pub port: u16,
54 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 #[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 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
159pub 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}