//! Web addresses: parsing, joining links to the page they sit on, and //! percent-encoding. Only what a browser that never runs scripts needs. use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Url { /// Lower-case: "https", "http" or "about". pub scheme: String, /// Lower-case host name, without the port. Empty for "about:". pub host: String, pub port: Option, /// Starts with "/" for web addresses; the page name for "about:". pub path: String, /// Without the leading "?". pub query: Option, } impl Url { pub fn parse(input: &str) -> Option { let s = input.trim(); let colon = s.find(':')?; let scheme = s[..colon].to_ascii_lowercase(); if scheme.is_empty() || !scheme.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') { return None; } let rest = &s[colon + 1..]; if scheme == "about" { let page = rest.split(['?', '#']).next().unwrap_or(""); return Some(Url { scheme, host: String::new(), port: None, path: page.to_ascii_lowercase(), query: None }); } if scheme != "http" && scheme != "https" { return None; } let rest = rest.strip_prefix("//")?; let rest = rest.split('#').next().unwrap_or(""); let auth_end = rest.find(['/', '?']).unwrap_or(rest.len()); let authority = &rest[..auth_end]; // Drop any user:password@ part; Clearwake never sends it. let hostport = authority.rsplit('@').next().unwrap_or(""); let (host, port) = split_host_port(hostport)?; if host.is_empty() || host.contains(' ') { return None; } let after = &rest[auth_end..]; let (path, query) = match after.find('?') { Some(q) => (&after[..q], Some(after[q + 1..].to_string())), None => (after, None), }; let path = if path.is_empty() { "/".to_string() } else { remove_dots(path) }; let port = match (scheme.as_str(), port) { ("http", Some(80)) | ("https", Some(443)) => None, (_, p) => p, }; Some(Url { scheme, host: host.to_ascii_lowercase(), port, path, query }) } /// Resolve a link found on this page. Returns None for links Clearwake /// does not follow (scripts, mail, data, phone, page-internal anchors). pub fn join(&self, href: &str) -> Option { let h = href.trim(); if h.is_empty() || h.starts_with('#') { return None; } if let Some(colon) = h.find(':') { let before = &h[..colon]; if !before.is_empty() && !before.contains(['/', '?', '#']) { return Url::parse(h); } } if self.scheme == "about" { return None; } if let Some(rest) = h.strip_prefix("//") { let mut s = self.scheme.clone(); s.push_str("://"); s.push_str(rest); return Url::parse(&s); } let h = h.split('#').next().unwrap_or(""); let mut out = self.clone(); if let Some(q) = h.strip_prefix('?') { out.query = Some(q.to_string()); return Some(out); } let (p, q) = match h.find('?') { Some(i) => (&h[..i], Some(h[i + 1..].to_string())), None => (h, None), }; out.query = q; if p.starts_with('/') { out.path = remove_dots(p); } else { let dir = match self.path.rfind('/') { Some(i) => &self.path[..=i], None => "/", }; let mut joined = String::from(dir); joined.push_str(p); out.path = remove_dots(&joined); } Some(out) } pub fn origin(&self) -> String { let mut s = self.scheme.clone(); s.push_str("://"); s.push_str(&self.host); if let Some(p) = self.port { s.push(':'); s.push_str(&p.to_string()); } s } pub fn is_about(&self) -> bool { self.scheme == "about" } /// The host without a leading "www.", for showing in the address bar. pub fn display_host(&self) -> &str { self.host.strip_prefix("www.").unwrap_or(&self.host) } /// Ends with one of the given extensions (".png" etc.), ignoring case. pub fn path_ends_with_any(&self, exts: &[&str]) -> bool { let p = self.path.to_ascii_lowercase(); exts.iter().any(|e| p.ends_with(e)) } } impl fmt::Display for Url { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.scheme == "about" { return write!(f, "about:{}", self.path); } write!(f, "{}{}", self.origin(), self.path)?; if let Some(q) = &self.query { write!(f, "?{}", q)?; } Ok(()) } } fn split_host_port(s: &str) -> Option<(&str, Option)> { if let Some(rest) = s.strip_prefix('[') { // IPv6 literal. let end = rest.find(']')?; let host = &s[..end + 2]; let after = &rest[end + 1..]; let port = match after.strip_prefix(':') { Some(p) if !p.is_empty() => Some(p.parse().ok()?), _ => None, }; return Some((host, port)); } match s.rfind(':') { Some(i) => { let p = &s[i + 1..]; let port = if p.is_empty() { None } else { Some(p.parse().ok()?) }; Some((&s[..i], port)) } None => Some((s, None)), } } /// Remove "." and ".." path segments. fn remove_dots(path: &str) -> String { let mut out: Vec<&str> = Vec::new(); let segs: Vec<&str> = path.split('/').collect(); let last = segs.len().saturating_sub(1); let mut trailing = false; for (i, seg) in segs.iter().enumerate() { match *seg { "." => trailing = i == last, ".." => { if out.len() > 1 { out.pop(); } trailing = i == last; } "" if i == 0 => out.push(""), s => { out.push(s); trailing = false; } } } if out.first() != Some(&"") { out.insert(0, ""); } let mut s = out.join("/"); if trailing || s.is_empty() { s.push('/'); } s } /// Percent-encode for a query value (spaces become "+"). pub fn encode_component(s: &str) -> String { let mut out = String::new(); for b in s.bytes() { match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char), b' ' => out.push('+'), _ => { const HEX: &[u8; 16] = b"0123456789ABCDEF"; out.push('%'); out.push(HEX[(b >> 4) as usize] as char); out.push(HEX[(b & 15) as usize] as char); } } } out } /// Decode a percent-encoded query value ("+" becomes a space). pub fn decode_component(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; while i < b.len() { match b[i] { b'+' => out.push(b' '), b'%' if i + 2 < b.len() => { let hv = |c: u8| (c as char).to_digit(16); match (hv(b[i + 1]), hv(b[i + 2])) { (Some(h), Some(l)) => { out.push((h * 16 + l) as u8); i += 2; } _ => out.push(b'%'), } } c => out.push(c), } i += 1; } String::from_utf8_lossy(&out).into_owned() } #[cfg(test)] mod tests { use super::*; fn j(base: &str, href: &str) -> String { Url::parse(base).unwrap().join(href).map(|u| u.to_string()).unwrap_or_default() } #[test] fn parse_and_print() { assert_eq!(Url::parse("HTTPS://Example.COM").unwrap().to_string(), "https://example.com/"); assert_eq!(Url::parse("https://a.com:443/x?y=1#z").unwrap().to_string(), "https://a.com/x?y=1"); assert_eq!(Url::parse("http://a.com:8080/").unwrap().to_string(), "http://a.com:8080/"); assert_eq!(Url::parse("https://u:p@a.com/").unwrap().host, "a.com"); assert!(Url::parse("javascript:alert(1)").is_none()); assert!(Url::parse("file:///etc/passwd").is_none()); } #[test] fn joins() { assert_eq!(j("https://a.com/b/c.html", "d.html"), "https://a.com/b/d.html"); assert_eq!(j("https://a.com/b/c.html", "../d"), "https://a.com/d"); assert_eq!(j("https://a.com/b/", "./"), "https://a.com/b/"); assert_eq!(j("https://a.com/b/c", "/x?y"), "https://a.com/x?y"); assert_eq!(j("https://a.com/b/c", "?q=1"), "https://a.com/b/c?q=1"); assert_eq!(j("https://a.com/b/c", "//cdn.b.com/i.png"), "https://cdn.b.com/i.png"); assert_eq!(j("https://a.com/", "http://c.com"), "http://c.com/"); assert_eq!(j("https://a.com/", "#top"), ""); assert_eq!(j("https://a.com/", "javascript:void(0)"), ""); assert_eq!(j("https://a.com/", "mailto:x@y.z"), ""); } #[test] fn encoding() { assert_eq!(encode_component("a b&c"), "a+b%26c"); assert_eq!(decode_component("a+b%26c%"), "a b&c%"); } }