//! HTTP client construction and a fetch routine that records redirect //! chains, caps body size and decodes legacy charsets. use std::time::{Duration, Instant}; use anyhow::{Context, Result}; use encoding_rs::{Encoding, UTF_8}; use reqwest::header::{ ACCEPT, ACCEPT_LANGUAGE, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, LOCATION, USER_AGENT, }; use reqwest::{Client, Method, Proxy, redirect}; use thiserror::Error; use crate::db::HttpMethod; pub const DEFAULT_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"; /// A handful of realistic desktop user agents for `--random-ua`. pub const UA_POOL: &[&str] = &[ DEFAULT_UA, "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15", "Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0", ]; pub fn random_user_agent() -> &'static str { use rand::Rng; UA_POOL[rand::thread_rng().gen_range(0..UA_POOL.len())] } pub const MAX_REDIRECT_HOPS: usize = 6; #[derive(Clone, Debug)] pub struct ClientOptions { pub timeout: Duration, pub proxy: Option, pub user_agent: String, pub insecure: bool, } impl Default for ClientOptions { fn default() -> Self { ClientOptions { timeout: Duration::from_secs(10), proxy: None, user_agent: DEFAULT_UA.to_string(), insecure: false, } } } /// Build the shared HTTP client. Redirects are handled manually by `fetch`. pub fn build_client(o: &ClientOptions) -> Result { let mut default_headers = HeaderMap::new(); default_headers.insert(ACCEPT, HeaderValue::from_static("text/html,application/xhtml+xml,application/xml;q=0.9,application/json;q=0.9,*/*;q=0.8")); default_headers.insert(ACCEPT_LANGUAGE, HeaderValue::from_static("en-US,en;q=0.9")); let mut b = Client::builder() .redirect(redirect::Policy::none()) .timeout(o.timeout) .connect_timeout(o.timeout.min(Duration::from_secs(15))) .user_agent(&o.user_agent) .default_headers(default_headers) .gzip(true) .brotli(true) .deflate(true) .pool_max_idle_per_host(6) .tcp_keepalive(Duration::from_secs(30)) .danger_accept_invalid_certs(o.insecure); if let Some(p) = &o.proxy { b = b.proxy(Proxy::all(p).with_context(|| format!("invalid proxy URL '{p}'"))?); } b.build().context("building HTTP client") } /// A fully rendered request. #[derive(Clone, Debug)] pub struct Prepared { pub method: HttpMethod, pub url: String, pub headers: Vec<(String, String)>, pub body: Option, pub follow_redirects: bool, pub encoding: Option, } /// What came back. #[derive(Clone, Debug, Default)] pub struct Exchange { pub url: String, pub first_status: u16, pub final_status: u16, pub final_url: String, pub hops: Vec, pub location: Option, pub headers: Vec<(String, String)>, pub content_type: Option, pub body: String, pub bytes: usize, pub truncated: bool, pub elapsed_ms: u64, } impl Exchange { pub fn header(&self, name: &str) -> Option<&str> { self.headers .iter() .find(|(k, _)| k.eq_ignore_ascii_case(name)) .map(|(_, v)| v.as_str()) } pub fn redirected(&self) -> bool { !self.hops.is_empty() || matches!(self.final_status, 301 | 302 | 303 | 307 | 308) } } #[derive(Debug, Error, Clone)] pub enum FetchError { #[error("timeout")] Timeout, #[error("connection failed: {0}")] Connect(String), #[error("request failed: {0}")] Request(String), #[error("body read failed: {0}")] Body(String), #[error("invalid redirect target: {0}")] Redirect(String), } impl FetchError { /// Whether a retry could plausibly succeed. pub fn is_transient(&self) -> bool { matches!( self, FetchError::Timeout | FetchError::Connect(_) | FetchError::Body(_) ) } pub fn short(&self) -> String { match self { FetchError::Timeout => "timeout".into(), FetchError::Connect(m) => format!("connect: {}", crate::util::truncate(m, 60)), FetchError::Request(m) => format!("request: {}", crate::util::truncate(m, 60)), FetchError::Body(m) => format!("body: {}", crate::util::truncate(m, 60)), FetchError::Redirect(m) => format!("redirect: {}", crate::util::truncate(m, 60)), } } } fn innermost_message(e: &reqwest::Error) -> String { let mut msg = e.to_string(); let mut src: Option<&(dyn std::error::Error + 'static)> = std::error::Error::source(e); while let Some(s) = src { msg = s.to_string(); src = s.source(); } // reqwest prefixes messages with the URL; keep the interesting tail. if let Some(idx) = msg.find("): ") { msg = msg[idx + 3..].to_string(); } msg } fn map_err(e: reqwest::Error) -> FetchError { if e.is_timeout() { FetchError::Timeout } else if e.is_connect() { FetchError::Connect(innermost_message(&e)) } else if e.is_body() || e.is_decode() { FetchError::Body(innermost_message(&e)) } else { let msg = innermost_message(&e); if msg.to_ascii_lowercase().contains("timed out") { FetchError::Timeout } else { FetchError::Request(msg) } } } fn resolve_location(base: &str, location: &str) -> Option { let base = url::Url::parse(base).ok()?; let next = base.join(location).ok()?; if !matches!(next.scheme(), "http" | "https") { return None; } Some(next.to_string()) } async fn read_capped( mut resp: reqwest::Response, max: usize, ) -> Result<(Vec, bool), FetchError> { let mut buf: Vec = Vec::with_capacity(16 * 1024); let mut truncated = false; loop { match resp.chunk().await { Ok(Some(chunk)) => { buf.extend_from_slice(&chunk); if buf.len() >= max { truncated = true; break; } } Ok(None) => break, Err(e) => { if buf.is_empty() { return Err(map_err(e)); } truncated = true; break; } } } Ok((buf, truncated)) } fn charset_from_content_type(ct: &str) -> Option { ct.split(';').skip(1).find_map(|part| { let (k, v) = part.trim().split_once('=')?; if k.trim().eq_ignore_ascii_case("charset") { Some(v.trim().trim_matches('"').to_string()) } else { None } }) } fn sniff_charset(bytes: &[u8]) -> Option { let head = &bytes[..bytes.len().min(4096)]; let s = String::from_utf8_lossy(head).to_ascii_lowercase(); let idx = s.find("charset=")?; let rest = &s[idx + "charset=".len()..]; let val: String = rest .trim_start_matches(['"', '\'']) .chars() .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') .collect(); if val.is_empty() { None } else { Some(val) } } /// Decode a response body using the declared or sniffed charset. pub fn decode_body(bytes: &[u8], content_type: Option<&str>, hint: Option<&str>) -> String { if bytes.is_empty() { return String::new(); } let label = hint .map(String::from) .or_else(|| content_type.and_then(charset_from_content_type)) .or_else(|| sniff_charset(bytes)); let enc = label .and_then(|l| Encoding::for_label(l.as_bytes())) .unwrap_or(UTF_8); let (text, _, _) = enc.decode(bytes); text.into_owned() } /// Perform a request, following redirects manually (when asked) so both the /// first and the final status are known to the detector. pub async fn fetch( client: &Client, req: &Prepared, max_body: usize, ua_override: Option<&str>, ) -> Result { let start = Instant::now(); let mut method = req.method; let mut url = req.url.clone(); let mut body = req.body.clone(); let mut hops: Vec = Vec::new(); let mut first_status: Option = None; loop { let m = match method { HttpMethod::Get => Method::GET, HttpMethod::Post => Method::POST, HttpMethod::Head => Method::HEAD, HttpMethod::Put => Method::PUT, }; let mut rb = client.request(m, &url); let mut has_ua = false; for (k, v) in &req.headers { if k.eq_ignore_ascii_case("user-agent") { has_ua = true; } let name = HeaderName::from_bytes(k.as_bytes()) .map_err(|e| FetchError::Request(format!("bad header name '{k}': {e}")))?; let value = HeaderValue::from_str(v) .map_err(|e| FetchError::Request(format!("bad header value for '{k}': {e}")))?; rb = rb.header(name, value); } if !has_ua { if let Some(ua) = ua_override { rb = rb.header(USER_AGENT, ua); } } if let Some(b) = &body { rb = rb.body(b.clone()); } let resp = rb.send().await.map_err(map_err)?; let status = resp.status().as_u16(); if first_status.is_none() { first_status = Some(status); } let location = resp .headers() .get(LOCATION) .map(|v| String::from_utf8_lossy(v.as_bytes()).to_string()); let is_redirect = matches!(status, 301 | 302 | 303 | 307 | 308); if is_redirect && req.follow_redirects && hops.len() < MAX_REDIRECT_HOPS { if let Some(loc) = &location { if let Some(next) = resolve_location(&url, loc) { if status == 303 || ((status == 301 || status == 302) && !matches!(method, HttpMethod::Get | HttpMethod::Head)) { method = HttpMethod::Get; body = None; } hops.push(next.clone()); url = next; continue; } } } let headers: Vec<(String, String)> = resp .headers() .iter() .map(|(k, v)| { ( k.as_str().to_string(), String::from_utf8_lossy(v.as_bytes()).to_string(), ) }) .collect(); let content_type = resp .headers() .get(CONTENT_TYPE) .map(|v| String::from_utf8_lossy(v.as_bytes()).to_string()); let (bytes, truncated) = if method == HttpMethod::Head { (Vec::new(), false) } else { read_capped(resp, max_body).await? }; let text = decode_body(&bytes, content_type.as_deref(), req.encoding.as_deref()); return Ok(Exchange { url: req.url.clone(), first_status: first_status.unwrap_or(status), final_status: status, final_url: url, hops, location, headers, content_type, bytes: bytes.len(), body: text, truncated, elapsed_ms: start.elapsed().as_millis() as u64, }); } } #[cfg(test)] mod tests { use super::*; #[test] fn charset_handling() { assert_eq!( charset_from_content_type("text/html; charset=windows-1251").as_deref(), Some("windows-1251") ); assert_eq!(charset_from_content_type("text/html"), None); assert_eq!( sniff_charset(b"").as_deref(), Some("koi8-r") ); let cp1251 = [0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]; // "Привет" in windows-1251 assert_eq!( decode_body(&cp1251, Some("text/html; charset=windows-1251"), None), "Привет" ); assert_eq!(decode_body("héllo".as_bytes(), None, None), "héllo"); assert_eq!(decode_body(&cp1251, None, Some("windows-1251")), "Привет"); } #[test] fn redirect_resolution() { assert_eq!( resolve_location("https://a.com/x/y", "/z").as_deref(), Some("https://a.com/z") ); assert_eq!( resolve_location("https://a.com/x/y", "https://b.com/").as_deref(), Some("https://b.com/") ); assert_eq!( resolve_location("https://a.com/x/", "q").as_deref(), Some("https://a.com/x/q") ); assert!(resolve_location("https://a.com/", "javascript:alert(1)").is_none()); } }