1use std::fmt;
4use std::sync::Arc;
5
6use crate::error::{Error, ErrorKind, Recovery, Result};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum Scheme {
10 Http,
11 Https,
12}
13
14impl Scheme {
15 #[must_use]
16 pub const fn default_port(self) -> u16 {
17 match self {
18 Self::Http => 80,
19 Self::Https => 443,
20 }
21 }
22 #[must_use]
23 pub const fn as_str(self) -> &'static str {
24 match self {
25 Self::Http => "http",
26 Self::Https => "https",
27 }
28 }
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33pub enum Protocol {
34 Http1,
35 Http2,
36}
37
38#[derive(Clone, Debug, PartialEq, Eq, Hash)]
40pub struct OriginKey {
41 pub scheme: Scheme,
42 pub host: Arc<str>,
45 pub port: u16,
46}
47
48impl OriginKey {
49 pub fn from_uri(uri: &http::Uri) -> Result<Self> {
54 let scheme = match uri.scheme_str() {
55 Some(s) if s.eq_ignore_ascii_case("http") => Scheme::Http,
56 Some(s) if s.eq_ignore_ascii_case("https") => Scheme::Https,
57 Some(_) => return Err(invalid("unsupported URI scheme")),
58 None => return Err(invalid("URI has no scheme")),
59 };
60 let Some(host) = uri.host().filter(|h| !h.is_empty()) else {
61 return Err(invalid("URI has no authority/host"));
62 };
63 let port = uri.port_u16().unwrap_or_else(|| scheme.default_port());
64 let host: Arc<str> = if host.bytes().any(|b| b.is_ascii_uppercase()) {
65 host.to_ascii_lowercase().into()
66 } else {
67 host.into()
68 };
69 Ok(Self { scheme, host, port })
70 }
71
72 #[must_use]
74 pub fn connect_host(&self) -> &str {
75 self.host
76 .strip_prefix('[')
77 .and_then(|h| h.strip_suffix(']'))
78 .unwrap_or(&self.host)
79 }
80
81 #[must_use]
82 pub const fn is_tls(&self) -> bool {
83 matches!(self.scheme, Scheme::Https)
84 }
85}
86
87fn invalid(msg: &'static str) -> Error {
88 Error::with_source(ErrorKind::InvalidRequest, Recovery::Never, msg)
89}
90
91impl fmt::Display for OriginKey {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 write!(f, "{}://{}:{}", self.scheme.as_str(), self.host, self.port)
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 fn key(s: &str) -> Result<OriginKey> {
102 OriginKey::from_uri(&s.parse().unwrap())
103 }
104
105 #[test]
106 fn defaults_and_lowercase() {
107 let k = key("HTTPS://Example.COM/path?q").unwrap();
108 assert_eq!(
109 (k.scheme, &*k.host, k.port),
110 (Scheme::Https, "example.com", 443)
111 );
112 let k = key("http://a.b").unwrap();
113 assert_eq!((k.scheme, k.port), (Scheme::Http, 80));
114 assert_eq!(key("http://a.b:8080/").unwrap().port, 8080);
115 assert_eq!(key("http://a.b:80/").unwrap(), key("http://A.B/").unwrap());
116 }
117
118 #[test]
119 fn ipv6() {
120 let k = key("https://[::1]:8443/").unwrap();
121 assert_eq!(&*k.host, "[::1]");
122 assert_eq!(k.connect_host(), "::1");
123 assert_eq!(k.to_string(), "https://[::1]:8443");
124 }
125
126 #[test]
127 fn rejects() {
128 for u in ["/relative", "example.com:80", "ftp://x/", "*"] {
129 let e = u.parse::<http::Uri>().map(|u| OriginKey::from_uri(&u));
130 if let Ok(r) = e {
131 assert_eq!(r.unwrap_err().kind(), ErrorKind::InvalidRequest, "{u}");
132 }
133 }
134 assert_eq!(key("/x").unwrap_err().recovery(), Recovery::Never);
135 }
136}