//! Link previews (FEEDBACK-4 B4, chat CONTRACT.md "Link previews"): fetched by the sender's own phone, never the//! server. The phone does the fetching (its network, no cookies); this decides which link, reads the page it hands//! back, and checks the card that goes with the message.usesuper::shapes::PreviewCard;usecrate::messages::links::{display_domain, extract_first_url};usecrate::messages::MessageLinkPreview;/// A card's title, description and site, in characters at most.pubconst TITLE_MAX: usize = 200;pubconst DESCRIPTION_MAX: usize = 300;pubconst SITE_MAX: usize = 80;/// Whether the phone may fetch `url`: http or https, to a name or a public address. Never this phone, its network, or/// a private address: a link someone writes must not make the phone knock on the router.pubfn fetchable(url: &str) -> bool {letOk(parsed) = url::Url::parse(url) else { returnfalse };if !matches!(parsed.scheme(), "http" | "https") {returnfalse; }match parsed.host() {Some(url::Host::Domain(name)) => {let name = name.trim_end_matches('.').to_ascii_lowercase(); !(name.is_empty() || name == "localhost" || name.ends_with(".localhost") || name.ends_with(".local") || name.ends_with(".internal") || !name.contains('.')) }Some(url::Host::Ipv4(ip)) => !(ip.is_private() || ip.is_loopback() || ip.is_link_local() || ip.is_unspecified() || ip.is_broadcast() || ip.octets()[0] == 100 && (ip.octets()[1] & 0xC0) == 64),Some(url::Host::Ipv6(ip)) => {let first = ip.segments()[0]; !(ip.is_loopback() || ip.is_unspecified() || (first & 0xFE00) == 0xFC00 || (first & 0xFFC0) == 0xFE80 || ip.to_ipv4_mapped().is_some()) }None => false, }}/// The link the words being written offer a card for: the first, when the phone may fetch it.pubfn offer(text: &str) -> Option<String> { extract_first_url(text).filter(|url| fetchable(url))}/// `page` (the HTML the phone fetched from `url`) as its card: `og:*`, then `twitter:*`, then `<title>` and the/// description meta; the site the page's own name or the address's domain; the picture made absolute. None when the/// page names no title.pubfn read_page(url: &str, page: &str) -> Option<PreviewCard> {let head = &page[..cut(page, 512 * 1024)];let metas = metas(head);let find = |keys: &[&str]| keys.iter().find_map(|k| metas.iter().find(|(name, _)| name == k).map(|(_, v)| v.clone())).filter(|v| !v.is_empty());let title = find(&["og:title", "twitter:title"]).or_else(|| title_tag(head)).map(|t| clip(&t, TITLE_MAX)).filter(|t| !t.is_empty())?;let description = find(&["og:description", "twitter:description", "description"]).map(|d| clip(&d, DESCRIPTION_MAX)).filter(|d| !d.is_empty());let site = find(&["og:site_name"]).map(|s| clip(&s, SITE_MAX)).or_else(|| Some(display_domain(url)).filter(|d| !d.is_empty()));let base = url::Url::parse(url).ok();let image = find(&["og:image:secure_url", "og:image", "og:image:url", "twitter:image", "twitter:image:src"]) .and_then(|i| base.as_ref().and_then(|b| b.join(&i).ok())) .map(|i| i.to_string()) .filter(|i| fetchable(i));Some(PreviewCard { url: url.to_string(), site, title: Some(title), description, image })}/// The card a send carries, as it is kept and travels: only for a link in the words the phone may fetch, its words/// within their limits, its picture a small JPEG (else it goes without one). None when it is no card of these words.pubfn checked(card: &serde_json::Value, words: &str) -> Option<MessageLinkPreview> {let url = card.get("url")?.as_str()?.trim().to_string();if url.is_empty() || !words.contains(url.as_str()) || !fetchable(&url) {returnNone; }let text = |key: &str, most: usize| card.get(key).and_then(|v| v.as_str()).map(|v| clip(v, most)).filter(|v| !v.is_empty());let title = text("title", TITLE_MAX)?;Some(MessageLinkPreview { url, title: Some(title), description: text("description", DESCRIPTION_MAX), site_name: text("site", SITE_MAX).or_else(|| text("siteName", SITE_MAX)), thumb: card.get("thumb").and_then(|v| v.as_str()).and_then(crate::chat::payload::preview_of), })}/// Words made one line: entities read, runs of space one, trimmed, at most `most` characters (an ellipsis when cut).fn clip(text: &str, most: usize) -> String {let read = entities(text);let one: String = read.split_whitespace().collect::<Vec<_>>().join(" ");if one.chars().count() <= most {return one; }letmut cut: String = one.chars().take(most.saturating_sub(1)).collect(); cut = cut.trim_end().to_string(); cut.push('…'); cut}/// The largest char boundary at or below `most`.fn cut(text: &str, most: usize) -> usize {if text.len() <= most {return text.len(); }letmut at = most;while !text.is_char_boundary(at) { at -= 1; } at}/// The page's `<meta>` tags as (property or name, lower case; content).fn metas(html: &str) -> Vec<(String, String)> {let lower = html.to_ascii_lowercase();letmut out = Vec::new();letmut from = 0;whileletSome(at) = lower[from..].find("<meta") {let start = from + at;letSome(end) = lower[start..].find('>').map(|e| start + e) else { break };let attrs = attributes(&html[start + 5..end]);let name = attrs.iter().find(|(k, _)| k == "property" || k == "name").map(|(_, v)| v.trim().to_ascii_lowercase());let content = attrs.iter().find(|(k, _)| k == "content").map(|(_, v)| v.clone());iflet (Some(name), Some(content)) = (name, content) { out.push((name, content)); } from = end + 1; } out}/// A tag's attributes as (name lower case, value).fn attributes(tag: &str) -> Vec<(String, String)> {letmut out = Vec::new();let chars: Vec<char> = tag.chars().collect();letmut i = 0;while i < chars.len() {while i < chars.len() && (chars[i].is_whitespace() || chars[i] == '/') { i += 1; }let start = i;while i < chars.len() && !chars[i].is_whitespace() && chars[i] != '=' && chars[i] != '/' { i += 1; }let name: String = chars[start..i].iter().collect::<String>().to_ascii_lowercase();while i < chars.len() && chars[i].is_whitespace() { i += 1; }if i < chars.len() && chars[i] == '=' { i += 1;while i < chars.len() && chars[i].is_whitespace() { i += 1; }let value = if i < chars.len() && (chars[i] == '"' || chars[i] == '\'') {let quote = chars[i]; i += 1;let begin = i;while i < chars.len() && chars[i] != quote { i += 1; }let v: String = chars[begin..i].iter().collect(); i += 1; v } else {let begin = i;while i < chars.len() && !chars[i].is_whitespace() { i += 1; } chars[begin..i].iter().collect() };if !name.is_empty() { out.push((name, value)); } } elseif name.is_empty() { i += 1; } } out}/// The page's `<title>`.fn title_tag(html: &str) -> Option<String> {let lower = html.to_ascii_lowercase();let open = lower.find("<title")?;let start = open + lower[open..].find('>')? + 1;let end = start + lower[start..].find("</title")?;Some(html[start..end].to_string())}/// The few entities a page's head uses.fn entities(text: &str) -> String {letmut out = String::with_capacity(text.len());letmut rest = text;whileletSome(at) = rest.find('&') { out.push_str(&rest[..at]);let tail = &rest[at..];letSome(semi) = tail[..tail.len().min(10)].find(';') else { out.push('&'); rest = &tail[1..];continue; };let name = &tail[1..semi];let read = match name {"amp" => Some('&'),"lt" => Some('<'),"gt" => Some('>'),"quot" => Some('"'),"apos" => Some('\''),"nbsp" => Some(' '), _ => name .strip_prefix("#x") .or_else(|| name.strip_prefix("#X")) .and_then(|h| u32::from_str_radix(h, 16).ok()) .or_else(|| name.strip_prefix('#').and_then(|d| d.parse().ok())) .and_then(char::from_u32), };match read {Some(c) => { out.push(c); rest = &tail[semi + 1..]; }None => { out.push('&'); rest = &tail[1..]; } } } out.push_str(rest); out}#[cfg(test)]mod tests {usesuper::*;/// RULE (FEEDBACK-4 B4): only a link the phone may fetch is offered; never this phone or its network. #[test]fn only_a_public_web_address_is_offered() { assert_eq!(offer("look at https://example.org/walks today").as_deref(), Some("https://example.org/walks")); assert_eq!(offer("no link here"), None);for private in ["http://localhost:8080/x", "http://192.168.1.1/", "http://10.0.0.7/a", "http://172.20.1.1/", "http://127.0.0.1/", "http://169.254.169.254/latest", "http://[::1]/", "http://[fd00::1]/", "http://router.local/", "http://printer/", "ftp://example.org/f", "http://100.64.0.1/"] { assert!(!fetchable(private), "{private}"); } assert!(fetchable("http://93.184.216.34/")); assert!(fetchable("https://www.example.org/a?b=c")); }/// RULE (FEEDBACK-4 B4): the card is the page's own words: og first, then twitter, then the title tag; the/// site the page's name or its domain; the picture made absolute; entities read; long words cut. #[test]fn a_page_reads_as_its_card() {let page = r#"<html><head><title>Fallback & title</title> <meta property="og:title" content="Hill walks near Pune & Lonavala"> <meta name='description' content='Ten walks.'> <meta property="og:description" content="Ten walks within two hours of the city."> <meta property="og:image" content="/img/hills.jpg" /> </head><body>…</body></html>"#;let card = read_page("https://www.example.org/walks", page).unwrap(); assert_eq!(card.title.as_deref(), Some("Hill walks near Pune & Lonavala")); assert_eq!(card.description.as_deref(), Some("Ten walks within two hours of the city.")); assert_eq!(card.site.as_deref(), Some("example.org")); assert_eq!(card.image.as_deref(), Some("https://www.example.org/img/hills.jpg"));let plain = read_page("https://example.net/", "<TITLE>\n A plain page </TITLE><META NAME=description CONTENT=\"Short.\"><meta property=og:site_name content=Plain>").unwrap(); assert_eq!((plain.title.as_deref(), plain.description.as_deref(), plain.site.as_deref(), plain.image), (Some("A plain page"), Some("Short."), Some("Plain"), None)); assert!(read_page("https://example.net/", "<html><body>no head</body></html>").is_none(), "no title, no card");let long = format!("<title>{}</title>", "word ".repeat(100)); assert_eq!(read_page("https://example.net/", &long).unwrap().title.unwrap().chars().count(), TITLE_MAX);let inner = read_page("https://example.net/", r#"<title>t</title><meta property="og:image" content="http://192.168.0.2/x.jpg">"#).unwrap(); assert_eq!(inner.image, None, "never a picture on his network"); }/// RULE (FEEDBACK-4 B4): a sent card is kept only for a link in its words, a title, its words within limits, and/// a picture that is a small JPEG (else it goes without one). #[test]fn a_sent_card_is_checked() {let jpeg = {use base64::Engineas _; base64::engine::general_purpose::STANDARD.encode([0xFF, 0xD8, 0xFF, 0xE0, 0, 16]) };let card = serde_json::json!({ "url": "https://example.org/walks", "site": "Example", "title": "Hill walks", "description": "Ten.", "thumb": jpeg });let kept = checked(&card, "see https://example.org/walks").unwrap(); assert_eq!((kept.title.as_deref(), kept.site_name.as_deref(), kept.thumb.as_deref()), (Some("Hill walks"), Some("Example"), Some(jpeg.as_str()))); assert!(checked(&card, "another message").is_none(), "its link must be in the words"); assert!(checked(&serde_json::json!({ "url": "https://example.org/walks" }), "https://example.org/walks").is_none(), "no title");let odd = serde_json::json!({ "url": "https://example.org/walks", "title": "T", "thumb": "bm90IGEganBlZw==" }); assert_eq!(checked(&odd, "https://example.org/walks").unwrap().thumb, None, "not a JPEG: no picture");let private = serde_json::json!({ "url": "http://10.0.0.1/", "title": "T" }); assert!(checked(&private, "http://10.0.0.1/").is_none()); }}