HTTP/2, proxy, multipart e processo di rete separato (M2.6b)
HTTP/2 (src/http2.rs): preface, SETTINGS, HEADERS/CONTINUATION, DATA, WINDOW_UPDATE, PING, RST_STREAM, GOAWAY; HPACK con tabella statica, dinamica e Huffman. Le tabelle sono generate dalla RFC 7541 (src/hpack_tabelle.rs) e validate sui suoi esempi, non trascritte a mano. Ambito dichiarato: una richiesta per connessione, senza multiplexing ne' push. Proxy (src/net.rs): http_proxy/https_proxy/all_proxy/no_proxy, tunnel CONNECT per https, Proxy-Authorization con base64. Provato con un finto proxy locale: forma assoluta per http, CONNECT per https, rifiuto del tunnel riportato. multipart/form-data e text/plain oltre a urlencoded (src/invio.rs): il corpo viaggia col tipo dichiarato, e il test verifica che il confine annunciato nell'intestazione separi davvero le parti che il server riceve. Processo di rete separato (src/bin/mosaic-net.rs): IPC a lunghezza prefissata su stdin/stdout, corpo in base64; il servizio tiene cookie e cache. Il desktop lo usa con --rete-esterna. Sul telefono la rete resta nel processo: un'app sandboxata non avvia figli in modo affidabile. Due difetti trovati dai test e non dalla lettura: - intero() in HPACK mascherava con AND invece di comporre con OR: ogni lunghezza di stringa finiva a zero. Era il GOAWAY dei siti veri. - rustls stringe la mano pigramente: alpn_protocol() era vuoto e si finiva sempre in HTTP/1.1 senza dirlo. Ora l'handshake e' forzato e MOSAIC_DEBUG lo stampa.
This commit is contained in:
1 parent
befb3f289f
commit
cc449a548d
21 files changed
+2222
-33
No files matched your search
+466
-15
@@ -14,6 +14,7 @@
|
||||
|
||||
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};
|
||||
@@ -68,6 +69,7 @@ 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,
|
||||
}
|
||||
@@ -110,6 +112,8 @@ 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 {
|
||||
@@ -118,6 +122,7 @@ impl Default for Limiti {
|
||||
timeout: Duration::from_secs(15),
|
||||
max_body: 8 * 1024 * 1024,
|
||||
max_redirect: 5,
|
||||
http2: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,6 +133,8 @@ impl Default for Limiti {
|
||||
pub struct Client {
|
||||
pub cookies: RefCell<CookieJar>,
|
||||
cache: RefCell<HashMap<String, VoceCache>>,
|
||||
/// se presente, le richieste le esegue un processo a parte e i cookie stanno là
|
||||
esterno: RefCell<Option<ServizioEsterno>>,
|
||||
}
|
||||
|
||||
struct VoceCache {
|
||||
@@ -149,6 +156,7 @@ impl Client {
|
||||
Client {
|
||||
cookies: RefCell::new(CookieJar::new()),
|
||||
cache: RefCell::new(HashMap::new()),
|
||||
esterno: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,17 +178,35 @@ impl Client {
|
||||
}
|
||||
|
||||
pub fn post(&self, url: &str, corpo: &str, limiti: &Limiti) -> Result<Response, String> {
|
||||
let risposta = self.esegui(
|
||||
url,
|
||||
"POST",
|
||||
Some(("application/x-www-form-urlencoded", corpo)),
|
||||
limiti,
|
||||
)?;
|
||||
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<Response, String> {
|
||||
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<Client, String> {
|
||||
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,
|
||||
@@ -188,6 +214,10 @@ impl Client {
|
||||
corpo: Option<(&str, &str)>,
|
||||
limiti: &Limiti,
|
||||
) -> Result<Response, String> {
|
||||
// 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,
|
||||
@@ -243,7 +273,12 @@ pub fn get(url: &str, limiti: &Limiti) -> Result<Response, String> {
|
||||
Client::new().get(url, limiti)
|
||||
}
|
||||
|
||||
/// `POST` con corpo `application/x-www-form-urlencoded` (invio dei formulari).
|
||||
/// `POST` con corpo e tipo dichiarato (`multipart/form-data` incluso).
|
||||
pub fn post_con(url: &str, corpo: &str, tipo: &str, limiti: &Limiti) -> Result<Response, String> {
|
||||
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<Response, String> {
|
||||
Client::new().post(url, corpo, limiti)
|
||||
}
|
||||
@@ -282,6 +317,355 @@ fn richiesta_con_biscotti(
|
||||
))
|
||||
}
|
||||
|
||||
// --- 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<Option<String>> = 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<String>,
|
||||
}
|
||||
|
||||
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<Proxy> {
|
||||
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<String> {
|
||||
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<Proxy> {
|
||||
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<TcpStream, String> {
|
||||
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::<u16>().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<ServizioEsterno, String> {
|
||||
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<Response, String> {
|
||||
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<String, String> {
|
||||
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<u8> {
|
||||
let mut out = Vec::new();
|
||||
let byte = |c: u8| -> Option<u8> {
|
||||
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<u8> = 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,
|
||||
@@ -290,11 +674,16 @@ fn richiesta(
|
||||
limiti: &Limiti,
|
||||
) -> Result<Response, String> {
|
||||
let u = HttpUrl::parse(url)?;
|
||||
let indirizzo = format!("{}:{}", u.host, u.port);
|
||||
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: {}", u.host, e))?
|
||||
.map_err(|e| format!("risoluzione di {} fallita: {}", host_connesso, e))?
|
||||
.next()
|
||||
.ok_or_else(|| format!("nessun indirizzo per {}", u.host))?,
|
||||
limiti.timeout,
|
||||
@@ -307,16 +696,76 @@ fn richiesta(
|
||||
.set_write_timeout(Some(limiti.timeout))
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut flusso: Box<dyn Legame> = if u.tls {
|
||||
Box::new(apri_tls(flusso, &u.host)?)
|
||||
// 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 {
|
||||
Box::new(flusso)
|
||||
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<dyn Legame> = 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, u.path, u.host
|
||||
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));
|
||||
}
|
||||
@@ -406,6 +855,7 @@ fn richiesta(
|
||||
fn apri_tls(
|
||||
flusso: TcpStream,
|
||||
host: &str,
|
||||
alpn: Vec<Vec<u8>>,
|
||||
) -> Result<rustls::StreamOwned<rustls::ClientConnection, TcpStream>, String> {
|
||||
let radici = rustls::RootCertStore {
|
||||
roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
|
||||
@@ -417,8 +867,8 @@ fn apri_tls(
|
||||
.map_err(|e| format!("versioni TLS: {}", e))?
|
||||
.with_root_certificates(radici)
|
||||
.with_no_client_auth();
|
||||
// annunciare HTTP/1.1: alcuni server (e CDN) rifiutano chi non negozia nulla
|
||||
configurazione.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
// 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))?;
|
||||
@@ -485,6 +935,7 @@ mod tests {
|
||||
timeout: Duration::from_secs(3),
|
||||
max_body: 1024 * 1024,
|
||||
max_redirect: 5,
|
||||
http2: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user