Branchwell

Clearwake / app · clearwake.ai / crates / clearwake-core / src / url.rs

Raw 9.3 KB on 50233c80eae1be554eda84594e30c13efcafb9d4
1//! Web addresses: parsing, joining links to the page they sit on, and
2//! percent-encoding. Only what a browser that never runs scripts needs.
3
4use alloc::string::{String, ToString};
5use alloc::vec::Vec;
6use core::fmt;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct Url {
10 /// Lower-case: "https", "http" or "about".
11 pub scheme: String,
12 /// Lower-case host name, without the port. Empty for "about:".
13 pub host: String,
14 pub port: Option<u16>,
15 /// Starts with "/" for web addresses; the page name for "about:".
16 pub path: String,
17 /// Without the leading "?".
18 pub query: Option<String>,
19}
20
21impl Url {
22 pub fn parse(input: &str) -> Option<Url> {
23 let s = input.trim();
24 let colon = s.find(':')?;
25 let scheme = s[..colon].to_ascii_lowercase();
26 if scheme.is_empty() || !scheme.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') {
27 return None;
28 }
29 let rest = &s[colon + 1..];
30 if scheme == "about" {
31 let page = rest.split(['?', '#']).next().unwrap_or("");
32 return Some(Url { scheme, host: String::new(), port: None, path: page.to_ascii_lowercase(), query: None });
33 }
34 if scheme != "http" && scheme != "https" {
35 return None;
36 }
37 let rest = rest.strip_prefix("//")?;
38 let rest = rest.split('#').next().unwrap_or("");
39 let auth_end = rest.find(['/', '?']).unwrap_or(rest.len());
40 let authority = &rest[..auth_end];
41 // Drop any user:password@ part; Clearwake never sends it.
42 let hostport = authority.rsplit('@').next().unwrap_or("");
43 let (host, port) = split_host_port(hostport)?;
44 if host.is_empty() || host.contains(' ') {
45 return None;
46 }
47 let after = &rest[auth_end..];
48 let (path, query) = match after.find('?') {
49 Some(q) => (&after[..q], Some(after[q + 1..].to_string())),
50 None => (after, None),
51 };
52 let path = if path.is_empty() { "/".to_string() } else { remove_dots(path) };
53 let port = match (scheme.as_str(), port) {
54 ("http", Some(80)) | ("https", Some(443)) => None,
55 (_, p) => p,
56 };
57 Some(Url { scheme, host: host.to_ascii_lowercase(), port, path, query })
58 }
59
60 /// Resolve a link found on this page. Returns None for links Clearwake
61 /// does not follow (scripts, mail, data, phone, page-internal anchors).
62 pub fn join(&self, href: &str) -> Option<Url> {
63 let h = href.trim();
64 if h.is_empty() || h.starts_with('#') {
65 return None;
66 }
67 if let Some(colon) = h.find(':') {
68 let before = &h[..colon];
69 if !before.is_empty() && !before.contains(['/', '?', '#']) {
70 return Url::parse(h);
71 }
72 }
73 if self.scheme == "about" {
74 return None;
75 }
76 if let Some(rest) = h.strip_prefix("//") {
77 let mut s = self.scheme.clone();
78 s.push_str("://");
79 s.push_str(rest);
80 return Url::parse(&s);
81 }
82 let h = h.split('#').next().unwrap_or("");
83 let mut out = self.clone();
84 if let Some(q) = h.strip_prefix('?') {
85 out.query = Some(q.to_string());
86 return Some(out);
87 }
88 let (p, q) = match h.find('?') {
89 Some(i) => (&h[..i], Some(h[i + 1..].to_string())),
90 None => (h, None),
91 };
92 out.query = q;
93 if p.starts_with('/') {
94 out.path = remove_dots(p);
95 } else {
96 let dir = match self.path.rfind('/') {
97 Some(i) => &self.path[..=i],
98 None => "/",
99 };
100 let mut joined = String::from(dir);
101 joined.push_str(p);
102 out.path = remove_dots(&joined);
103 }
104 Some(out)
105 }
106
107 pub fn origin(&self) -> String {
108 let mut s = self.scheme.clone();
109 s.push_str("://");
110 s.push_str(&self.host);
111 if let Some(p) = self.port {
112 s.push(':');
113 s.push_str(&p.to_string());
114 }
115 s
116 }
117
118 pub fn is_about(&self) -> bool {
119 self.scheme == "about"
120 }
121
122 /// The host without a leading "www.", for showing in the address bar.
123 pub fn display_host(&self) -> &str {
124 self.host.strip_prefix("www.").unwrap_or(&self.host)
125 }
126
127 /// Ends with one of the given extensions (".png" etc.), ignoring case.
128 pub fn path_ends_with_any(&self, exts: &[&str]) -> bool {
129 let p = self.path.to_ascii_lowercase();
130 exts.iter().any(|e| p.ends_with(e))
131 }
132}
133
134impl fmt::Display for Url {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 if self.scheme == "about" {
137 return write!(f, "about:{}", self.path);
138 }
139 write!(f, "{}{}", self.origin(), self.path)?;
140 if let Some(q) = &self.query {
141 write!(f, "?{}", q)?;
142 }
143 Ok(())
144 }
145}
146
147fn split_host_port(s: &str) -> Option<(&str, Option<u16>)> {
148 if let Some(rest) = s.strip_prefix('[') {
149 // IPv6 literal.
150 let end = rest.find(']')?;
151 let host = &s[..end + 2];
152 let after = &rest[end + 1..];
153 let port = match after.strip_prefix(':') {
154 Some(p) if !p.is_empty() => Some(p.parse().ok()?),
155 _ => None,
156 };
157 return Some((host, port));
158 }
159 match s.rfind(':') {
160 Some(i) => {
161 let p = &s[i + 1..];
162 let port = if p.is_empty() { None } else { Some(p.parse().ok()?) };
163 Some((&s[..i], port))
164 }
165 None => Some((s, None)),
166 }
167}
168
169/// Remove "." and ".." path segments.
170fn remove_dots(path: &str) -> String {
171 let mut out: Vec<&str> = Vec::new();
172 let segs: Vec<&str> = path.split('/').collect();
173 let last = segs.len().saturating_sub(1);
174 let mut trailing = false;
175 for (i, seg) in segs.iter().enumerate() {
176 match *seg {
177 "." => trailing = i == last,
178 ".." => {
179 if out.len() > 1 {
180 out.pop();
181 }
182 trailing = i == last;
183 }
184 "" if i == 0 => out.push(""),
185 s => {
186 out.push(s);
187 trailing = false;
188 }
189 }
190 }
191 if out.first() != Some(&"") {
192 out.insert(0, "");
193 }
194 let mut s = out.join("/");
195 if trailing || s.is_empty() {
196 s.push('/');
197 }
198 s
199}
200
201/// Percent-encode for a query value (spaces become "+").
202pub fn encode_component(s: &str) -> String {
203 let mut out = String::new();
204 for b in s.bytes() {
205 match b {
206 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
207 b' ' => out.push('+'),
208 _ => {
209 const HEX: &[u8; 16] = b"0123456789ABCDEF";
210 out.push('%');
211 out.push(HEX[(b >> 4) as usize] as char);
212 out.push(HEX[(b & 15) as usize] as char);
213 }
214 }
215 }
216 out
217}
218
219/// Decode a percent-encoded query value ("+" becomes a space).
220pub fn decode_component(s: &str) -> String {
221 let b = s.as_bytes();
222 let mut out = Vec::with_capacity(b.len());
223 let mut i = 0;
224 while i < b.len() {
225 match b[i] {
226 b'+' => out.push(b' '),
227 b'%' if i + 2 < b.len() => {
228 let hv = |c: u8| (c as char).to_digit(16);
229 match (hv(b[i + 1]), hv(b[i + 2])) {
230 (Some(h), Some(l)) => {
231 out.push((h * 16 + l) as u8);
232 i += 2;
233 }
234 _ => out.push(b'%'),
235 }
236 }
237 c => out.push(c),
238 }
239 i += 1;
240 }
241 String::from_utf8_lossy(&out).into_owned()
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 fn j(base: &str, href: &str) -> String {
249 Url::parse(base).unwrap().join(href).map(|u| u.to_string()).unwrap_or_default()
250 }
251
252 #[test]
253 fn parse_and_print() {
254 assert_eq!(Url::parse("HTTPS://Example.COM").unwrap().to_string(), "https://example.com/");
255 assert_eq!(Url::parse("https://a.com:443/x?y=1#z").unwrap().to_string(), "https://a.com/x?y=1");
256 assert_eq!(Url::parse("http://a.com:8080/").unwrap().to_string(), "http://a.com:8080/");
257 assert_eq!(Url::parse("https://u:p@a.com/").unwrap().host, "a.com");
258 assert!(Url::parse("javascript:alert(1)").is_none());
259 assert!(Url::parse("file:///etc/passwd").is_none());
260 }
261
262 #[test]
263 fn joins() {
264 assert_eq!(j("https://a.com/b/c.html", "d.html"), "https://a.com/b/d.html");
265 assert_eq!(j("https://a.com/b/c.html", "../d"), "https://a.com/d");
266 assert_eq!(j("https://a.com/b/", "./"), "https://a.com/b/");
267 assert_eq!(j("https://a.com/b/c", "/x?y"), "https://a.com/x?y");
268 assert_eq!(j("https://a.com/b/c", "?q=1"), "https://a.com/b/c?q=1");
269 assert_eq!(j("https://a.com/b/c", "//cdn.b.com/i.png"), "https://cdn.b.com/i.png");
270 assert_eq!(j("https://a.com/", "http://c.com"), "http://c.com/");
271 assert_eq!(j("https://a.com/", "#top"), "");
272 assert_eq!(j("https://a.com/", "javascript:void(0)"), "");
273 assert_eq!(j("https://a.com/", "mailto:x@y.z"), "");
274 }
275
276 #[test]
277 fn encoding() {
278 assert_eq!(encode_component("a b&c"), "a+b%26c");
279 assert_eq!(decode_component("a+b%26c%"), "a b&c%");
280 }
281}