//! Rete (milestone M2.6, primo incremento): client HTTP/1.1 minimo. //! //! Ambito dichiarato: `GET` su `http://` con connessione diretta, header di //! risposta, `Content-Length` e `Transfer-Encoding: chunked`, catena di //! reindirizzamenti, limiti di tempo e di dimensione. //! //! TLS (`https://`) con `rustls` e le radici di `webpki-roots`: la catena di //! certificati si verifica contro le autorità di fiducia, e un certificato non //! valido è un errore, non un avviso ignorabile. //! //! Fuori ambito, per ora: proxy, cookie, cache, HTTP/2, `fetch` da JavaScript. //! Le funzioni che non coprono il caso lo dicono con un errore esplicito, non //! restituiscono una pagina vuota. use std::cell::RefCell; use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::io::{Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration, Instant}; use crate::cookie::CookieJar; /// Esito di una richiesta. #[derive(Debug, Clone)] pub struct Response { pub status: u16, pub headers: Vec<(String, String)>, pub body: Vec, /// URL finale dopo i reindirizzamenti pub url: String, } impl Response { pub fn header(&self, nome: &str) -> Option<&str> { self.headers .iter() .find(|(k, _)| k.eq_ignore_ascii_case(nome)) .map(|(_, v)| v.as_str()) } /// Corpo come testo: si dichiara l'errore se non è UTF-8 valido e non c'è un /// charset conosciuto, invece di mostrare caratteri casuali. pub fn text(&self) -> Result { let charset = self .header("content-type") .and_then(|v| { v.split(';') .map(|p| p.trim()) .find_map(|p| p.strip_prefix("charset=")) }) .map(|c| c.trim_matches('"').to_ascii_lowercase()) .unwrap_or_else(|| "utf-8".to_string()); match charset.as_str() { "iso-8859-1" | "latin1" | "latin-1" => { // conversione esplicita: un byte latino non è un carattere UTF-8 Ok(self.body.iter().map(|b| *b as char).collect()) } _ => String::from_utf8(self.body.clone()) .map_err(|_| format!("corpo non UTF-8 (charset dichiarato: {})", charset)), } } } /// Parti di un URL `http://host[:porta]/percorso?query`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HttpUrl { pub host: String, pub port: u16, pub path: String, // (l'intestazione `Host` porta la porta solo se non è quella predefinita) /// vero per `https://`: la connessione va avvolta in TLS pub tls: bool, } impl HttpUrl { pub fn parse(url: &str) -> Result { let (resto, tls, porta_predefinita) = if let Some(r) = url.strip_prefix("https://") { (r, true, 443) } else if let Some(r) = url.strip_prefix("http://") { (r, false, 80) } else { return Err(format!("schema non supportato: {}", url)); }; let (autorita, percorso) = match resto.find('/') { Some(i) => (&resto[..i], &resto[i..]), None => (resto, "/"), }; if autorita.is_empty() { return Err("host mancante".to_string()); } let (host, port) = match autorita.rsplit_once(':') { Some((h, p)) => ( h.to_string(), p.parse::() .map_err(|_| format!("porta non valida: {}", p))?, ), None => (autorita.to_string(), porta_predefinita), }; Ok(HttpUrl { host, port, path: percorso.to_string(), tls, }) } } /// Limiti espliciti: una risposta ostile non deve poter saturare la memoria. pub struct Limiti { pub timeout: Duration, pub max_body: usize, pub max_redirect: u32, /// negozia HTTP/2 quando il server lo offre (richiede TLS) pub http2: bool, } impl Default for Limiti { fn default() -> Self { Limiti { timeout: Duration::from_secs(15), max_body: 8 * 1024 * 1024, max_redirect: 5, http2: true, } } } /// Client con stato di sessione: cookie e cache. È quello che il guscio tiene /// per tutta la navigazione; le funzioni libere `get`/`post` ne creano uno usa e /// getta, per i test e per le chiamate senza sessione. pub struct Client { pub cookies: RefCell, cache: RefCell>, /// se presente, le richieste le esegue un processo a parte e i cookie stanno là esterno: RefCell>, } struct VoceCache { corpo: Vec, intestazioni: Vec<(String, String)>, status: u16, url: String, scade: Option, } impl Default for Client { fn default() -> Self { Client::new() } } impl Client { pub fn new() -> Self { Client { cookies: RefCell::new(CookieJar::new()), cache: RefCell::new(HashMap::new()), esterno: RefCell::new(None), } } pub fn get(&self, url: &str, limiti: &Limiti) -> Result { // cache: solo se il server ha detto per quanto tempo vale if let Some(v) = self.cache.borrow().get(url) { if v.scade.map(|s| s > Instant::now()).unwrap_or(false) { return Ok(Response { status: v.status, headers: v.intestazioni.clone(), body: v.corpo.clone(), url: v.url.clone(), }); } } let risposta = self.esegui(url, "GET", None, limiti)?; self.ricorda(url, &risposta); Ok(risposta) } pub fn post(&self, url: &str, corpo: &str, limiti: &Limiti) -> Result { self.post_con(url, corpo, "application/x-www-form-urlencoded", limiti) } /// POST con un tipo di contenuto esplicito: serve a `multipart/form-data`, /// dove il corpo non è leggibile senza il confine dichiarato nell'intestazione. pub fn post_con( &self, url: &str, corpo: &str, tipo: &str, limiti: &Limiti, ) -> Result { let risposta = self.esegui(url, "POST", Some((tipo, corpo)), limiti)?; // una POST invalida la copia in cache dello stesso indirizzo self.cache.borrow_mut().remove(url); Ok(risposta) } /// Il client delega la rete a un processo separato: cookie e connessioni /// vivono là, e un blocco non ferma chi disegna. pub fn con_servizio_esterno(programma: &std::path::Path) -> Result { let servizio = ServizioEsterno::avvia(programma)?; Ok(Client { cookies: RefCell::new(CookieJar::new()), cache: RefCell::new(HashMap::new()), esterno: RefCell::new(Some(servizio)), }) } fn esegui( &self, url: &str, metodo: &str, corpo: Option<(&str, &str)>, limiti: &Limiti, ) -> Result { // con il servizio esterno non si tiene nulla di locale: la sessione è sua if let Some(servizio) = self.esterno.borrow_mut().as_mut() { return servizio.richiedi(url, metodo, corpo, limiti); } let biscotti = self.cookies.borrow().riga_per(url); let risposta = richiesta_con_biscotti( url, metodo, corpo, if biscotti.is_empty() { None } else { Some(biscotti.as_str()) }, limiti, )?; // i cookie si raccolgono sull'indirizzo finale, dopo i reindirizzamenti self.cookies .borrow_mut() .raccogli(&risposta.url, &risposta.headers); Ok(risposta) } fn ricorda(&self, url: &str, risposta: &Response) { let direttive = risposta .header("cache-control") .unwrap_or("") .to_ascii_lowercase(); if direttive.contains("no-store") || direttive.contains("no-cache") { return; } let scade = direttive .split(',') .filter_map(|d| d.trim().strip_prefix("max-age=")) .filter_map(|n| n.trim().parse::().ok()) .next() .map(|n| Instant::now() + Duration::from_secs(n)); let Some(scade) = scade else { return }; if risposta.body.len() > 4 * 1024 * 1024 { return; } self.cache.borrow_mut().insert( url.to_string(), VoceCache { corpo: risposta.body.clone(), intestazioni: risposta.headers.clone(), status: risposta.status, url: risposta.url.clone(), scade: Some(scade), }, ); } } /// Richiesta GET, seguendo i reindirizzamenti fino al limite indicato. pub fn get(url: &str, limiti: &Limiti) -> Result { Client::new().get(url, limiti) } /// `POST` con corpo e tipo dichiarato (`multipart/form-data` incluso). pub fn post_con(url: &str, corpo: &str, tipo: &str, limiti: &Limiti) -> Result { Client::new().post_con(url, corpo, tipo, limiti) } /// `POST` con corpo `application/x-www-form-urlencoded`. pub fn post(url: &str, corpo: &str, limiti: &Limiti) -> Result { Client::new().post(url, corpo, limiti) } /// Qualunque cosa sappia leggere e scrivere: un socket o un socket sotto TLS. trait Legame: Read + Write {} impl Legame for T {} /// Richiesta con reindirizzamenti, cookie e — per il client — cache. fn richiesta_con_biscotti( url: &str, metodo: &str, corpo: Option<(&str, &str)>, biscotti: Option<&str>, limiti: &Limiti, ) -> Result { let mut corrente = url.to_string(); for _ in 0..=limiti.max_redirect { let risposta = richiesta(&corrente, metodo, corpo, biscotti, limiti)?; let reindirizzo = matches!(risposta.status, 301 | 302 | 303 | 307 | 308) .then(|| risposta.header("location").map(|l| l.to_string())) .flatten(); match reindirizzo { // relativo o assoluto: si risolve rispetto all'URL corrente Some(loc) if loc.starts_with('/') => { let base = HttpUrl::parse(&corrente)?; corrente = format!("http://{}:{}{}", base.host, base.port, loc); } Some(loc) => corrente = loc, None => return Ok(risposta), } } Err(format!( "troppi reindirizzamenti (oltre {})", limiti.max_redirect )) } // --- Proxy --------------------------------------------------------------- // // Regole, le stesse che usano gli altri client: `https_proxy` (o `HTTPS_PROXY`) // per gli indirizzi TLS e `http_proxy` per gli altri, `all_proxy` come ripiego, // `no_proxy` come elenco di host (o suffissi, o `*`) che vanno contattati // direttamente. Il valore è un indirizzo `http://[utente:parola@]host:porta`. // Fuori ambito, dichiarato: proxy SOCKS, proxy configurati via `Proxy-Auto-Config`. thread_local! { /// Proxy imposto dal chiamante (serve ai test: l'ambiente è del processo, non del test) static PROXY_IMPOSTO: RefCell> = const { RefCell::new(None) }; } /// Imposta l'indirizzo del proxy per il thread corrente, ignorando l'ambiente. pub fn imposta_proxy(valore: Option<&str>) { PROXY_IMPOSTO.with(|c| *c.borrow_mut() = valore.map(|v| v.to_string())); } /// Proxy da usare per un indirizzo, se ce n'è uno. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Proxy { pub host: String, pub port: u16, /// `utente:parola` se l'indirizzo del proxy li contiene pub auth: Option, } impl HttpUrl { /// Valore per l'intestazione `Host`: la porta compare solo se non è quella /// predefinita dello schema, come fanno i browser. pub fn host_da_intestazione(&self) -> String { let predefinita = if self.tls { 443 } else { 80 }; if self.port == predefinita { self.host.clone() } else { format!("{}:{}", self.host, self.port) } } } impl Proxy { fn da_indirizzo(valore: &str) -> Option { let testo = valore.trim(); if testo.is_empty() { return None; } let senza_schema = testo .strip_prefix("http://") .or_else(|| testo.strip_prefix("https://")) .unwrap_or(testo); let (credenziali, resto) = match senza_schema.rsplit_once('@') { Some((c, r)) => (Some(c.to_string()), r), None => (None, senza_schema), }; let (host, porta) = match resto.rsplit_once(':') { Some((h, p)) if p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty() => { (h.to_string(), p.parse().ok()?) } _ => (resto.to_string(), 80), }; if host.is_empty() { return None; } Some(Proxy { host, port: porta, auth: credenziali, }) } } /// Vero se l'host va contattato senza passare dal proxy (`no_proxy`). fn escluso_dal_proxy(host: &str, no_proxy: &str) -> bool { let host = host.to_ascii_lowercase(); no_proxy.split(',').any(|voce| { let voce = voce.trim().to_ascii_lowercase(); if voce.is_empty() { return false; } if voce == "*" { return true; } // `example.com` copre anche `www.example.com`, come fanno gli altri client let senza_punto = voce.strip_prefix('.').unwrap_or(&voce); host == senza_punto || host.ends_with(&format!(".{}", senza_punto)) }) } fn variabile(nomi: &[&str]) -> Option { nomi.iter().find_map(|n| match std::env::var(n) { Ok(v) if !v.trim().is_empty() => Some(v), _ => None, }) } /// Il proxy da usare per `u`, oppure `None` per la connessione diretta. fn proxy_per(u: &HttpUrl) -> Option { let imposto = PROXY_IMPOSTO.with(|c| c.borrow().clone()); if let Some(valore) = imposto { return Proxy::da_indirizzo(&valore); } if let Some(no) = variabile(&["no_proxy", "NO_PROXY"]) { if escluso_dal_proxy(&u.host, &no) { return None; } } let scelto = if u.tls { variabile(&["https_proxy", "HTTPS_PROXY"]) .or_else(|| variabile(&["all_proxy", "ALL_PROXY"])) } else { variabile(&["http_proxy", "HTTP_PROXY"]).or_else(|| variabile(&["all_proxy", "ALL_PROXY"])) }; scelto.and_then(|v| Proxy::da_indirizzo(&v)) } /// Base64 per `Proxy-Authorization` (le credenziali del proxy non sono segreti /// del nostro codice: sono nell'ambiente dell'utente e vanno solo codificate). pub fn base64(dati: &[u8]) -> String { const ALFABETO: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; let mut out = String::new(); for pezzo in dati.chunks(3) { let b = [ pezzo[0], *pezzo.get(1).unwrap_or(&0), *pezzo.get(2).unwrap_or(&0), ]; let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32; out.push(ALFABETO[(n >> 18) as usize & 63] as char); out.push(ALFABETO[(n >> 12) as usize & 63] as char); out.push(if pezzo.len() > 1 { ALFABETO[(n >> 6) as usize & 63] as char } else { '=' }); out.push(if pezzo.len() > 2 { ALFABETO[n as usize & 63] as char } else { '=' }); } out } /// Apre il tunnel `CONNECT` verso `destinazione` attraverso il proxy. fn tunnel(flusso: TcpStream, destinazione: &str, proxy: &Proxy) -> Result { let mut scrittura = flusso.try_clone().map_err(|e| e.to_string())?; let mut richiesta = format!( "CONNECT {0} HTTP/1.1\r\nHost: {0}\r\nUser-Agent: Mosaic/0.1\r\n", destinazione ); if let Some(credenziali) = &proxy.auth { richiesta.push_str(&format!( "Proxy-Authorization: Basic {}\r\n", base64(credenziali.as_bytes()) )); } richiesta.push_str("\r\n"); scrittura .write_all(richiesta.as_bytes()) .map_err(|e| format!("CONNECT al proxy fallita: {}", e))?; // la risposta del proxy sono righe di intestazione, poi il flusso è opaco let mut lettura = BufReader::new(flusso.try_clone().map_err(|e| e.to_string())?); let mut riga = String::new(); lettura .read_line(&mut riga) .map_err(|e| format!("risposta del proxy illeggibile: {}", e))?; let stato = riga .split_whitespace() .nth(1) .and_then(|s| s.parse::().ok()) .ok_or_else(|| format!("risposta del proxy non valida: {}", riga.trim()))?; if stato != 200 { return Err(format!("il proxy ha rifiutato il tunnel: HTTP {}", stato)); } loop { let mut riga = String::new(); let n = lettura .read_line(&mut riga) .map_err(|e| format!("risposta del proxy illeggibile: {}", e))?; if n == 0 || riga == "\r\n" || riga == "\n" { break; } } Ok(flusso) } // --- Servizio di rete separato ------------------------------------------- // // La rete può vivere in un processo a parte: qui il client parla con lui, e i // cookie stanno là (come in un browser vero, dove la sessione non è nel processo // della pagina). Il protocollo è deliberatamente stupido: una lunghezza in // quattro byte, poi JSON. Un corpo binario viaggia in base64. // // Il processo è utile perché: un blocco in rete non ferma l'interfaccia, un // crash nella rete non porta via la pagina, e la sessione sopravvive alla // navigazione. Su Sailfish un'app sandboxata non può avviare processi figli in // modo affidabile, quindi il telefono usa il percorso interno: è una differenza // dichiarata, non una svista. /// Avvia `mosaic-net` e ci parla. pub struct ServizioEsterno { figlio: std::process::Child, ingresso: std::process::ChildStdin, uscita: std::process::ChildStdout, prossimo_id: u64, } impl ServizioEsterno { /// Avvia il programma indicato (di solito accanto all'eseguibile principale). pub fn avvia(programma: &std::path::Path) -> Result { let mut figlio = std::process::Command::new(programma) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::inherit()) .spawn() .map_err(|e| format!("avvio di {} fallito: {}", programma.display(), e))?; let ingresso = figlio.stdin.take().ok_or("ingresso del servizio assente")?; let uscita = figlio.stdout.take().ok_or("uscita del servizio assente")?; Ok(ServizioEsterno { figlio, ingresso, uscita, prossimo_id: 1, }) } /// Chiede al servizio di eseguire la richiesta e aspetta la risposta. pub fn richiedi( &mut self, url: &str, metodo: &str, corpo: Option<(&str, &str)>, limiti: &Limiti, ) -> Result { let id = self.prossimo_id; self.prossimo_id += 1; let richiesta = serde_json::json!({ "id": id, "url": url, "metodo": metodo, "corpo": corpo.map(|(_, d)| d).unwrap_or(""), "tipo": corpo.map(|(t, _)| t).unwrap_or(""), "max_body": limiti.max_body, "timeout_ms": limiti.timeout.as_millis() as u64, }); scrivi_messaggio(&mut self.ingresso, &richiesta.to_string())?; let risposta = leggi_messaggio(&mut self.uscita)?; let valore: serde_json::Value = serde_json::from_str(&risposta).map_err(|e| format!("risposta illeggibile: {}", e))?; if valore.get("id").and_then(|v| v.as_u64()) != Some(id) { return Err("risposta fuori ordine dal servizio di rete".to_string()); } if let Some(errore) = valore.get("errore").and_then(|v| v.as_str()) { return Err(errore.to_string()); } let corpo = decodifica_base64(valore.get("corpo").and_then(|v| v.as_str()).unwrap_or("")); let mut headers = Vec::new(); if let Some(elenco) = valore.get("intestazioni").and_then(|v| v.as_array()) { for voce in elenco { if let (Some(n), Some(v)) = ( voce.get("nome").and_then(|v| v.as_str()), voce.get("valore").and_then(|v| v.as_str()), ) { headers.push((n.to_string(), v.to_string())); } } } Ok(Response { status: valore.get("stato").and_then(|v| v.as_u64()).unwrap_or(0) as u16, headers, body: corpo, url: valore .get("url") .and_then(|v| v.as_str()) .unwrap_or(url) .to_string(), }) } } impl Drop for ServizioEsterno { fn drop(&mut self) { // chiudendo l'ingresso il servizio esce dal suo ciclo e termina let _ = self.figlio.kill(); let _ = self.figlio.wait(); } } fn scrivi_messaggio(destinazione: &mut impl Write, testo: &str) -> Result<(), String> { let dati = testo.as_bytes(); let lunghezza = (dati.len() as u32).to_le_bytes(); destinazione .write_all(&lunghezza) .and_then(|_| destinazione.write_all(dati)) .and_then(|_| destinazione.flush()) .map_err(|e| format!("scrittura al servizio di rete fallita: {}", e)) } fn leggi_messaggio(origine: &mut impl Read) -> Result { let mut testa = [0u8; 4]; origine .read_exact(&mut testa) .map_err(|e| format!("il servizio di rete non risponde: {}", e))?; let lunghezza = u32::from_le_bytes(testa) as usize; if lunghezza > 64 * 1024 * 1024 { return Err(format!("messaggio troppo grande: {} byte", lunghezza)); } let mut dati = vec![0u8; lunghezza]; origine .read_exact(&mut dati) .map_err(|e| format!("messaggio interrotto: {}", e))?; Ok(String::from_utf8_lossy(&dati).to_string()) } fn decodifica_base64(testo: &str) -> Vec { let mut out = Vec::new(); let byte = |c: u8| -> Option { match c { b'A'..=b'Z' => Some(c - b'A'), b'a'..=b'z' => Some(c - b'a' + 26), b'0'..=b'9' => Some(c - b'0' + 52), b'+' => Some(62), b'/' => Some(63), _ => None, } }; let pulito: Vec = testo .bytes() .filter(|b| !b.is_ascii_whitespace() && *b != b'=') .collect(); for pezzo in pulito.chunks(4) { let mut n = 0u32; for (i, c) in pezzo.iter().enumerate() { if let Some(v) = byte(*c) { n |= (v as u32) << (18 - 6 * i); } } out.push((n >> 16) as u8); if pezzo.len() > 2 { out.push((n >> 8) as u8); } if pezzo.len() > 3 { out.push(n as u8); } } out } fn richiesta( url: &str, metodo: &str, corpo: Option<(&str, &str)>, biscotti: Option<&str>, limiti: &Limiti, ) -> Result { let u = HttpUrl::parse(url)?; let proxy = proxy_per(&u); let (host_connesso, porta_connessa) = match &proxy { Some(p) => (p.host.clone(), p.port), None => (u.host.clone(), u.port), }; let indirizzo = format!("{}:{}", host_connesso, porta_connessa); let flusso = TcpStream::connect_timeout( &indirizzo .to_socket_addrs() .map_err(|e| format!("risoluzione di {} fallita: {}", host_connesso, e))? .next() .ok_or_else(|| format!("nessun indirizzo per {}", u.host))?, limiti.timeout, ) .map_err(|e| format!("connessione a {} fallita: {}", indirizzo, e))?; flusso .set_read_timeout(Some(limiti.timeout)) .map_err(|e| e.to_string())?; flusso .set_write_timeout(Some(limiti.timeout)) .map_err(|e| e.to_string())?; // con un proxy: tunnel per https, richiesta in forma assoluta per http let flusso = match &proxy { Some(p) if u.tls => tunnel(flusso, &format!("{}:{}", u.host, u.port), p)?, _ => flusso, }; // con http2 abilitato si annuncia `h2` per primo: se il server lo sceglie si // parla HTTP/2, altrimenti resta HTTP/1.1 sulla stessa connessione let alpn = if u.tls && limiti.http2 { vec![b"h2".to_vec(), b"http/1.1".to_vec()] } else { vec![b"http/1.1".to_vec()] }; let (mut tls, senza_tls) = if u.tls { (Some(apri_tls(flusso, &u.host, alpn)?), None) } else { (None, Some(flusso)) }; // rustls stringe la mano alla prima lettura/scrittura: senza forzarla, // `alpn_protocol()` è ancora vuoto e si finirebbe sempre in HTTP/1.1 if let Some(t) = tls.as_mut() { t.conn .complete_io(&mut t.sock) .map_err(|e| format!("TLS con {}: {}", u.host, e))?; } // `MOSAIC_DEBUG=1` racconta quale protocollo è stato negoziato: senza questo // si finisce per indovinare (mi è successo: credevo di parlare h2 e parlavo h1) if std::env::var("MOSAIC_DEBUG").is_ok() { if let Some(t) = tls.as_ref() { let negoziato = t .conn .alpn_protocol() .map(|p| String::from_utf8_lossy(p).to_string()) .unwrap_or_else(|| "nessuno".to_string()); eprintln!("mosaic: ALPN negoziato con {}: {}", u.host, negoziato); } } if matches!( tls.as_ref().map(|t| t.conn.alpn_protocol() == Some(b"h2")), Some(true) ) { if std::env::var("MOSAIC_DEBUG").is_ok() { eprintln!("mosaic: richiesta in HTTP/2"); } let mut connessione = tls.take().expect("il flusso TLS c'è"); return crate::http2::esegui(&mut connessione, &u, metodo, corpo, biscotti, limiti); } let mut flusso: Box = match tls { Some(t) => Box::new(t), // senza TLS il socket è ancora qui: `flusso` è stato consumato solo nel ramo TLS None => Box::new(senza_tls.ok_or("socket TLS mancante")?), }; // forma assoluta solo per http attraverso un proxy: nei tunnel è il server // a parlare, e vuole il percorso let bersaglio = match &proxy { Some(_) if !u.tls => format!("http://{}{}", u.host_da_intestazione(), u.path), _ => u.path.clone(), }; let mut richiesta = format!( "{} {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: Mosaic/0.1\r\nAccept: text/html,*/*\r\nConnection: close\r\n", metodo, bersaglio, u.host_da_intestazione() ); if let (Some(p), false) = (&proxy, u.tls) { if let Some(credenziali) = &p.auth { richiesta.push_str(&format!( "Proxy-Authorization: Basic {}\r\n", base64(credenziali.as_bytes()) )); } } if let Some(b) = biscotti { richiesta.push_str(&format!("Cookie: {}\r\n", b)); } if let Some((tipo, dati)) = corpo { richiesta.push_str(&format!( "Content-Type: {}\r\nContent-Length: {}\r\n", tipo, dati.len() )); } richiesta.push_str("\r\n"); if let Some((_, dati)) = corpo { richiesta.push_str(dati); } flusso .write_all(richiesta.as_bytes()) .map_err(|e| format!("invio fallito: {}", e))?; let mut grezzo: Vec = Vec::new(); let mut blocco = [0u8; 8192]; loop { match flusso.read(&mut blocco) { Ok(0) => break, Ok(n) => { grezzo.extend_from_slice(&blocco[..n]); if grezzo.len() > limiti.max_body + 64 * 1024 { return Err(format!("risposta oltre {} byte", limiti.max_body)); } } Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { return Err("timeout in lettura".to_string()) } Err(e) => return Err(format!("lettura fallita: {}", e)), } } let separatore = grezzo .windows(4) .position(|w| w == b"\r\n\r\n") .ok_or_else(|| "risposta senza intestazioni".to_string())?; let intestazioni = String::from_utf8_lossy(&grezzo[..separatore]).to_string(); let corpo_grezzo = grezzo[separatore + 4..].to_vec(); let mut righe = intestazioni.split("\r\n"); let prima = righe.next().unwrap_or(""); let status = prima .split_whitespace() .nth(1) .and_then(|s| s.parse::().ok()) .ok_or_else(|| format!("riga di stato non valida: {}", prima))?; let mut headers: Vec<(String, String)> = Vec::new(); for riga in righe { if let Some((nome, valore)) = riga.split_once(':') { headers.push((nome.trim().to_string(), valore.trim().to_string())); } } let mut risposta = Response { status, headers, body: Vec::new(), url: url.to_string(), }; let chunked = risposta .header("transfer-encoding") .map(|v| v.to_ascii_lowercase().contains("chunked")) .unwrap_or(false); risposta.body = if chunked { decodifica_chunked(&corpo_grezzo, limiti.max_body)? } else if let Some(len) = risposta .header("content-length") .and_then(|v| v.trim().parse::().ok()) { if len > limiti.max_body { return Err(format!("corpo dichiarato oltre {} byte", limiti.max_body)); } corpo_grezzo[..len.min(corpo_grezzo.len())].to_vec() } else { corpo_grezzo }; Ok(risposta) } /// Avvolge il socket in TLS verificando la catena contro le radici di fiducia. fn apri_tls( flusso: TcpStream, host: &str, alpn: Vec>, ) -> Result, String> { let radici = rustls::RootCertStore { roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(), }; let mut configurazione = rustls::ClientConfig::builder_with_provider(std::sync::Arc::new( rustls::crypto::ring::default_provider(), )) .with_safe_default_protocol_versions() .map_err(|e| format!("versioni TLS: {}", e))? .with_root_certificates(radici) .with_no_client_auth(); // annunciare il protocollo: alcuni server (e CDN) rifiutano chi non negozia nulla configurazione.alpn_protocols = alpn; let nome = rustls::pki_types::ServerName::try_from(host.to_string()) .map_err(|_| format!("nome del server non valido: {}", host))?; let connessione = rustls::ClientConnection::new(std::sync::Arc::new(configurazione), nome) .map_err(|e| format!("TLS con {}: {}", host, e))?; Ok(rustls::StreamOwned::new(connessione, flusso)) } /// `Transfer-Encoding: chunked`: dimensione in esadecimale, dati, CRLF, fino a 0. fn decodifica_chunked(corpo: &[u8], max: usize) -> Result, String> { let mut out: Vec = Vec::new(); let mut i = 0usize; loop { let fine_riga = corpo[i..] .windows(2) .position(|w| w == b"\r\n") .map(|p| i + p) .ok_or_else(|| "chunk senza fine riga".to_string())?; let dimensione_txt = String::from_utf8_lossy(&corpo[i..fine_riga]).to_string(); let dimensione_txt = dimensione_txt.split(';').next().unwrap_or("").trim(); let dimensione = usize::from_str_radix(dimensione_txt, 16) .map_err(|_| format!("dimensione di chunk non valida: {}", dimensione_txt))?; i = fine_riga + 2; if dimensione == 0 { break; } if out.len() + dimensione > max { return Err(format!("corpo oltre {} byte", max)); } let fine = (i + dimensione).min(corpo.len()); out.extend_from_slice(&corpo[i..fine]); i = fine + 2; if i >= corpo.len() { break; } } Ok(out) } #[cfg(test)] mod tests { use super::*; use std::io::Read; use std::net::TcpListener; use std::thread; /// Server usa-e-getta: risponde con `risposta` a ogni richiesta e chiude. fn server(risposta: &'static str) -> u16 { let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera"); let porta = ascolto.local_addr().unwrap().port(); thread::spawn(move || { for flusso in ascolto.incoming().flatten() { let mut flusso = flusso; let mut buf = [0u8; 2048]; let _ = flusso.read(&mut buf); let _ = flusso.write_all(risposta.as_bytes()); } }); porta } fn limiti() -> Limiti { Limiti { timeout: Duration::from_secs(3), max_body: 1024 * 1024, max_redirect: 5, http2: false, } } #[test] fn url_http_semplice() { let u = HttpUrl::parse("http://esempio.test/pagina?x=1").unwrap(); assert_eq!(u.host, "esempio.test"); assert_eq!(u.port, 80); assert_eq!(u.path, "/pagina?x=1"); let u = HttpUrl::parse("http://esempio.test:8080").unwrap(); assert_eq!(u.port, 8080); assert_eq!(u.path, "/"); let s = HttpUrl::parse("https://esempio.test/p").unwrap(); assert!(s.tls && s.port == 443 && s.path == "/p"); assert!(!HttpUrl::parse("http://esempio.test/").unwrap().tls); assert!(HttpUrl::parse("ftp://esempio.test/").is_err()); } #[test] fn risposta_con_content_length() { let porta = server( "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: 5\r\n\r\nciao!", ); let r = get(&format!("http://127.0.0.1:{}/", porta), &limiti()).unwrap(); assert_eq!(r.status, 200); assert_eq!(r.text().unwrap(), "ciao!"); } #[test] fn risposta_chunked() { let porta = server( "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nciao\r\n2\r\n!!\r\n0\r\n\r\n", ); let r = get(&format!("http://127.0.0.1:{}/", porta), &limiti()).unwrap(); assert_eq!(r.text().unwrap(), "ciao!!"); } #[test] fn redirect_seguito() { // il primo server rimanda al secondo let porta_due = server("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); let risposta_uno = format!( "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{}/\r\nContent-Length: 0\r\n\r\n", porta_due ); let porta_uno = server(Box::leak(risposta_uno.into_boxed_str())); let r = get(&format!("http://127.0.0.1:{}/", porta_uno), &limiti()).unwrap(); assert_eq!(r.status, 200); assert_eq!(r.text().unwrap(), "ok"); } #[test] fn errore_di_stato_arriva_come_risposta() { let porta = server("HTTP/1.1 404 Not Found\r\nContent-Length: 3\r\n\r\nno!"); let r = get(&format!("http://127.0.0.1:{}/", porta), &limiti()).unwrap(); assert_eq!(r.status, 404); assert_eq!(r.text().unwrap(), "no!"); } #[test] fn connessione_rifiutata_e_errore_esplicito() { // porta quasi certamente chiusa let err = get("http://127.0.0.1:1/", &limiti()).unwrap_err(); assert!(err.contains("connessione"), "errore: {}", err); } #[test] fn il_client_rimanda_i_cookie_ricevuti() { use std::sync::mpsc::channel; let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera"); let porta = ascolto.local_addr().unwrap().port(); let (tx, rx) = channel::(); thread::spawn(move || { // prima richiesta: si risponde con Set-Cookie if let Some(Ok(mut f)) = ascolto.incoming().next() { let mut b = [0u8; 2048]; let _ = f.read(&mut b); let _ = f.write_all( b"HTTP/1.1 200 OK\r\nSet-Cookie: sess=xyz; Path=/\r\nContent-Length: 2\r\n\r\nok", ); } // seconda: si registra cosa è arrivato if let Some(Ok(mut f)) = ascolto.incoming().next() { let mut b = [0u8; 2048]; let n = f.read(&mut b).unwrap_or(0); let _ = tx.send(String::from_utf8_lossy(&b[..n]).to_string()); let _ = f.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); } }); let client = Client::new(); let url = format!("http://127.0.0.1:{}/a", porta); client.get(&url, &limiti()).expect("prima richiesta"); client.get(&url, &limiti()).expect("seconda richiesta"); let ricevuta = rx.recv().expect("seconda richiesta registrata"); assert!( ricevuta.to_ascii_lowercase().contains("cookie: sess=xyz"), "cookie non rimandato: {}", ricevuta ); } #[test] fn la_cache_evita_la_seconda_richiesta() { use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera"); let porta = ascolto.local_addr().unwrap().port(); let conteggio = Arc::new(AtomicUsize::new(0)); let c2 = conteggio.clone(); thread::spawn(move || { for flusso in ascolto.incoming().flatten() { let mut f = flusso; c2.fetch_add(1, Ordering::SeqCst); let mut b = [0u8; 2048]; let _ = f.read(&mut b); let _ = f.write_all( b"HTTP/1.1 200 OK\r\nCache-Control: max-age=60\r\nContent-Length: 5\r\n\r\nciao!", ); } }); let client = Client::new(); let url = format!("http://127.0.0.1:{}/x", porta); assert_eq!( client.get(&url, &limiti()).unwrap().text().unwrap(), "ciao!" ); assert_eq!( client.get(&url, &limiti()).unwrap().text().unwrap(), "ciao!" ); assert_eq!( conteggio.load(Ordering::SeqCst), 1, "la seconda richiesta è uscita lo stesso" ); } #[test] fn no_store_non_si_memorizza() { use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera"); let porta = ascolto.local_addr().unwrap().port(); let conteggio = Arc::new(AtomicUsize::new(0)); let c2 = conteggio.clone(); thread::spawn(move || { for flusso in ascolto.incoming().flatten() { let mut f = flusso; c2.fetch_add(1, Ordering::SeqCst); let mut b = [0u8; 2048]; let _ = f.read(&mut b); let _ = f.write_all( b"HTTP/1.1 200 OK\r\nCache-Control: no-store, max-age=60\r\nContent-Length: 2\r\n\r\nno", ); } }); let client = Client::new(); let url = format!("http://127.0.0.1:{}/y", porta); client.get(&url, &limiti()).unwrap(); client.get(&url, &limiti()).unwrap(); assert_eq!(conteggio.load(Ordering::SeqCst), 2); } #[test] fn post_manda_metodo_e_corpo() { // il server di prova rimanda indietro la richiesta ricevuta let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera"); let porta = ascolto.local_addr().unwrap().port(); let (tx, rx) = std::sync::mpsc::channel::(); thread::spawn(move || { if let Some(Ok(mut flusso)) = ascolto.incoming().next() { let mut buf = [0u8; 4096]; let n = flusso.read(&mut buf).unwrap_or(0); let _ = tx.send(String::from_utf8_lossy(&buf[..n]).to_string()); let _ = flusso.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); } }); let r = post( &format!("http://127.0.0.1:{}/invia", porta), "nome=ciao&n=1", &limiti(), ) .expect("risposta"); assert_eq!(r.status, 200); let ricevuta = rx.recv().expect("richiesta registrata"); assert!(ricevuta.starts_with("POST /invia HTTP/1.1"), "{}", ricevuta); assert!(ricevuta.contains("Content-Type: application/x-www-form-urlencoded")); assert!(ricevuta.contains("Content-Length: 13")); assert!( ricevuta.trim_end().ends_with("nome=ciao&n=1"), "{}", ricevuta ); } #[test] fn schema_sconosciuto_lo_dice() { let err = get("ftp://esempio.test/", &limiti()).unwrap_err(); assert!(err.contains("schema"), "errore: {}", err); } #[test] fn latin1_viene_convertito() { // il byte 0xE8 in latin-1 è "è": se restasse grezzo non sarebbe UTF-8 let r = Response { status: 200, headers: vec![( "content-type".to_string(), "text/html; charset=iso-8859-1".to_string(), )], body: vec![b'c', b'a', 0xE8], url: String::new(), }; assert_eq!(r.text().unwrap(), "caè"); } }