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
@@ -0,0 +1,119 @@
|
||||
//! Servizio di rete separato (M2.6).
|
||||
//!
|
||||
//! Vive in un processo suo: riceve richieste dal motore e risponde. Il vantaggio
|
||||
//! non è la velocità, è l'isolamento — un blocco o un crash di rete non porta via
|
||||
//! la pagina — e il fatto che i cookie stiano qui: la sessione non appartiene al
|
||||
//! processo che disegna.
|
||||
//!
|
||||
//! Protocollo, deliberatamente stupido: `u32` little-endian con la lunghezza,
|
||||
//! poi un messaggio JSON. Il corpo viaggia in base64, così anche un'immagine
|
||||
//! passa intatta. Su stdin arrivano le richieste, su stdout le risposte; quando
|
||||
//! stdin si chiude il servizio esce.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use engine::net::{self, Client, Limiti};
|
||||
|
||||
fn main() {
|
||||
// il client è persistente: cookie e cache sopravvivono alle richieste
|
||||
let client = Client::new();
|
||||
let mut ingresso = std::io::stdin();
|
||||
let mut uscita = std::io::stdout();
|
||||
|
||||
loop {
|
||||
let mut testa = [0u8; 4];
|
||||
match ingresso.read_exact(&mut testa) {
|
||||
Ok(()) => {}
|
||||
Err(_) => break, // stdin chiuso: il guscio ha finito
|
||||
}
|
||||
let lunghezza = u32::from_le_bytes(testa) as usize;
|
||||
let mut dati = vec![0u8; lunghezza];
|
||||
if ingresso.read_exact(&mut dati).is_err() {
|
||||
break;
|
||||
}
|
||||
let richiesta: serde_json::Value = match serde_json::from_str(&String::from_utf8_lossy(
|
||||
&dati,
|
||||
)) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
let errore =
|
||||
serde_json::json!({"id": 0, "errore": format!("richiesta illeggibile: {}", e)});
|
||||
if scrivi(&mut uscita, &errore.to_string()).is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let risposta = esegui(&client, &richiesta);
|
||||
if scrivi(&mut uscita, &risposta.to_string()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn esegui(client: &Client, richiesta: &serde_json::Value) -> serde_json::Value {
|
||||
let id = richiesta.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let url = richiesta
|
||||
.get("url")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let metodo = richiesta
|
||||
.get("metodo")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("GET")
|
||||
.to_ascii_uppercase();
|
||||
let corpo = richiesta
|
||||
.get("corpo")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let tipo = richiesta
|
||||
.get("tipo")
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|t| !t.is_empty())
|
||||
.unwrap_or("application/x-www-form-urlencoded");
|
||||
|
||||
let mut limiti = Limiti::default();
|
||||
if let Some(ms) = richiesta.get("timeout_ms").and_then(|v| v.as_u64()) {
|
||||
if ms > 0 {
|
||||
limiti.timeout = std::time::Duration::from_millis(ms);
|
||||
}
|
||||
}
|
||||
if let Some(max) = richiesta.get("max_body").and_then(|v| v.as_u64()) {
|
||||
if max > 0 {
|
||||
limiti.max_body = max as usize;
|
||||
}
|
||||
}
|
||||
|
||||
let esito = if metodo == "POST" {
|
||||
client.post_con(&url, corpo, tipo, &limiti)
|
||||
} else {
|
||||
client.get(&url, &limiti)
|
||||
};
|
||||
|
||||
match esito {
|
||||
Ok(risposta) => {
|
||||
let intestazioni: Vec<serde_json::Value> = risposta
|
||||
.headers
|
||||
.iter()
|
||||
.map(|(n, v)| serde_json::json!({"nome": n, "valore": v}))
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
"id": id,
|
||||
"stato": risposta.status,
|
||||
"url": risposta.url,
|
||||
"intestazioni": intestazioni,
|
||||
"corpo": net::base64(&risposta.body),
|
||||
})
|
||||
}
|
||||
Err(errore) => serde_json::json!({"id": id, "errore": errore}),
|
||||
}
|
||||
}
|
||||
|
||||
fn scrivi(uscita: &mut impl Write, testo: &str) -> std::io::Result<()> {
|
||||
let dati = testo.as_bytes();
|
||||
uscita.write_all(&(dati.len() as u32).to_le_bytes())?;
|
||||
uscita.write_all(dati)?;
|
||||
uscita.flush()
|
||||
}
|
||||
+72
-1
@@ -370,6 +370,11 @@ pub struct EngineDoc {
|
||||
base_dir: PathBuf,
|
||||
/// ultimo impaginato: serve a sapere che nodo sta sotto il puntatore
|
||||
layout: Option<crate::layout::LayoutBox>,
|
||||
/// formulario da inviare: il pulsante è stato premuto e lo script non ha
|
||||
/// annullato l'evento. Il guscio lo legge e fa la richiesta.
|
||||
invio_pendente: Option<usize>,
|
||||
/// indirizzo del documento, per risolvere `action` dei formulari
|
||||
base_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Crea un documento, eseguendo subito gli script (anche esterni).
|
||||
@@ -421,6 +426,17 @@ pub extern "C" fn engine_doc_new(
|
||||
css,
|
||||
base_dir: cartella,
|
||||
layout: None,
|
||||
invio_pendente: None,
|
||||
base_url: if base_url.is_null() {
|
||||
None
|
||||
} else {
|
||||
let b = cstr_or_empty(base_url);
|
||||
if b.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(b)
|
||||
}
|
||||
},
|
||||
})
|
||||
}));
|
||||
match esito {
|
||||
@@ -524,6 +540,11 @@ fn clic_interno(doc: *mut EngineDoc, css_x: f32, css_y: f32) -> i32 {
|
||||
gestori += d
|
||||
.macchina
|
||||
.evento(&mut d.contenuto.doc, "submit", &catena, css_x, css_y);
|
||||
// senza `preventDefault` l'invio va fatto davvero: lo esegue il guscio,
|
||||
// che sa fare rete e conosce lo stato dei campi
|
||||
if !d.macchina.preventuto_default() {
|
||||
d.invio_pendente = Some(form_node);
|
||||
}
|
||||
}
|
||||
}
|
||||
let catena = crate::layout::catena_antenati(&d.contenuto.doc, nodo);
|
||||
@@ -614,6 +635,7 @@ pub extern "C" fn engine_session_fetch(
|
||||
url: *const c_char,
|
||||
metodo: *const c_char,
|
||||
corpo: *const c_char,
|
||||
tipo: *const c_char,
|
||||
status: *mut std::os::raw::c_int,
|
||||
error: *mut *mut c_char,
|
||||
) -> *mut c_char {
|
||||
@@ -633,10 +655,16 @@ pub extern "C" fn engine_session_fetch(
|
||||
let indirizzo = cstr_or_empty(url);
|
||||
let verbo = cstr_or_empty(metodo).to_ascii_uppercase();
|
||||
let dati = cstr_or_empty(corpo);
|
||||
let tipo_testo = cstr_or_empty(tipo);
|
||||
let tipo = if tipo_testo.is_empty() {
|
||||
"application/x-www-form-urlencoded"
|
||||
} else {
|
||||
tipo_testo.as_str()
|
||||
};
|
||||
let limiti = crate::net::Limiti::default();
|
||||
let esito = catch_unwind(AssertUnwindSafe(|| {
|
||||
if verbo == "POST" {
|
||||
s.client.post(&indirizzo, &dati, &limiti)
|
||||
s.client.post_con(&indirizzo, &dati, tipo, &limiti)
|
||||
} else {
|
||||
s.client.get(&indirizzo, &limiti)
|
||||
}
|
||||
@@ -773,3 +801,46 @@ fn panic_message(e: &(dyn std::any::Any + Send)) -> String {
|
||||
"errore interno".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Invio del formulario in attesa, in JSON: {metodo, url, corpo, tipo}.
|
||||
/// Restituisce NULL se non c'è nulla da inviare. `state_json` è lo stesso stato
|
||||
/// dei campi usato per il disegno (serve a leggere i valori digitati).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn engine_doc_invio_json(
|
||||
doc: *mut EngineDoc,
|
||||
state_json: *const c_char,
|
||||
) -> *mut c_char {
|
||||
if doc.is_null() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let esito = catch_unwind(AssertUnwindSafe(|| {
|
||||
let d = unsafe { &mut *doc };
|
||||
let Some(form_node) = d.invio_pendente.take() else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
let stato = cstr_or_empty(state_json);
|
||||
let modulo = parse_form_state(&stato);
|
||||
match crate::invio::prepara(&d.contenuto.doc, &modulo, form_node, d.base_url.as_deref()) {
|
||||
Ok(richiesta) => {
|
||||
let valore = serde_json::json!({
|
||||
"metodo": richiesta.metodo,
|
||||
"url": richiesta.url,
|
||||
"corpo": richiesta.corpo.unwrap_or_default(),
|
||||
"tipo": richiesta.content_type.unwrap_or_default(),
|
||||
});
|
||||
cstring_errore(valore.to_string())
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("mosaic: invio non preparabile: {}", e);
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
}
|
||||
}));
|
||||
match esito {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
eprintln!("mosaic: panic nell'invio: {}", panic_message(&e));
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! Tabelle HPACK, generate dalla RFC 7541 (Appendici A e B).
|
||||
//!
|
||||
//! Sono dati, non codice: un errore qui non si vede come un errore, si vede
|
||||
//! come una pagina vuota, quindi le ho generate invece di trascriverle.
|
||||
|
||||
/// `(codice, lunghezza in bit)` per ogni simbolo; 256 è la fine del flusso.
|
||||
pub const HUFFMAN: [(u32, u8); 257] = [
|
||||
(0x1ff8, 13),
|
||||
(0x7fffd8, 23),
|
||||
(0xfffffe2, 28),
|
||||
(0xfffffe3, 28),
|
||||
(0xfffffe4, 28),
|
||||
(0xfffffe5, 28),
|
||||
(0xfffffe6, 28),
|
||||
(0xfffffe7, 28),
|
||||
(0xfffffe8, 28),
|
||||
(0xffffea, 24),
|
||||
(0x3ffffffc, 30),
|
||||
(0xfffffe9, 28),
|
||||
(0xfffffea, 28),
|
||||
(0x3ffffffd, 30),
|
||||
(0xfffffeb, 28),
|
||||
(0xfffffec, 28),
|
||||
(0xfffffed, 28),
|
||||
(0xfffffee, 28),
|
||||
(0xfffffef, 28),
|
||||
(0xffffff0, 28),
|
||||
(0xffffff1, 28),
|
||||
(0xffffff2, 28),
|
||||
(0x3ffffffe, 30),
|
||||
(0xffffff3, 28),
|
||||
(0xffffff4, 28),
|
||||
(0xffffff5, 28),
|
||||
(0xffffff6, 28),
|
||||
(0xffffff7, 28),
|
||||
(0xffffff8, 28),
|
||||
(0xffffff9, 28),
|
||||
(0xffffffa, 28),
|
||||
(0xffffffb, 28),
|
||||
(0x14, 6),
|
||||
(0x3f8, 10),
|
||||
(0x3f9, 10),
|
||||
(0xffa, 12),
|
||||
(0x1ff9, 13),
|
||||
(0x15, 6),
|
||||
(0xf8, 8),
|
||||
(0x7fa, 11),
|
||||
(0x3fa, 10),
|
||||
(0x3fb, 10),
|
||||
(0xf9, 8),
|
||||
(0x7fb, 11),
|
||||
(0xfa, 8),
|
||||
(0x16, 6),
|
||||
(0x17, 6),
|
||||
(0x18, 6),
|
||||
(0x0, 5),
|
||||
(0x1, 5),
|
||||
(0x2, 5),
|
||||
(0x19, 6),
|
||||
(0x1a, 6),
|
||||
(0x1b, 6),
|
||||
(0x1c, 6),
|
||||
(0x1d, 6),
|
||||
(0x1e, 6),
|
||||
(0x1f, 6),
|
||||
(0x5c, 7),
|
||||
(0xfb, 8),
|
||||
(0x7ffc, 15),
|
||||
(0x20, 6),
|
||||
(0xffb, 12),
|
||||
(0x3fc, 10),
|
||||
(0x1ffa, 13),
|
||||
(0x21, 6),
|
||||
(0x5d, 7),
|
||||
(0x5e, 7),
|
||||
(0x5f, 7),
|
||||
(0x60, 7),
|
||||
(0x61, 7),
|
||||
(0x62, 7),
|
||||
(0x63, 7),
|
||||
(0x64, 7),
|
||||
(0x65, 7),
|
||||
(0x66, 7),
|
||||
(0x67, 7),
|
||||
(0x68, 7),
|
||||
(0x69, 7),
|
||||
(0x6a, 7),
|
||||
(0x6b, 7),
|
||||
(0x6c, 7),
|
||||
(0x6d, 7),
|
||||
(0x6e, 7),
|
||||
(0x6f, 7),
|
||||
(0x70, 7),
|
||||
(0x71, 7),
|
||||
(0x72, 7),
|
||||
(0xfc, 8),
|
||||
(0x73, 7),
|
||||
(0xfd, 8),
|
||||
(0x1ffb, 13),
|
||||
(0x7fff0, 19),
|
||||
(0x1ffc, 13),
|
||||
(0x3ffc, 14),
|
||||
(0x22, 6),
|
||||
(0x7ffd, 15),
|
||||
(0x3, 5),
|
||||
(0x23, 6),
|
||||
(0x4, 5),
|
||||
(0x24, 6),
|
||||
(0x5, 5),
|
||||
(0x25, 6),
|
||||
(0x26, 6),
|
||||
(0x27, 6),
|
||||
(0x6, 5),
|
||||
(0x74, 7),
|
||||
(0x75, 7),
|
||||
(0x28, 6),
|
||||
(0x29, 6),
|
||||
(0x2a, 6),
|
||||
(0x7, 5),
|
||||
(0x2b, 6),
|
||||
(0x76, 7),
|
||||
(0x2c, 6),
|
||||
(0x8, 5),
|
||||
(0x9, 5),
|
||||
(0x2d, 6),
|
||||
(0x77, 7),
|
||||
(0x78, 7),
|
||||
(0x79, 7),
|
||||
(0x7a, 7),
|
||||
(0x7b, 7),
|
||||
(0x7ffe, 15),
|
||||
(0x7fc, 11),
|
||||
(0x3ffd, 14),
|
||||
(0x1ffd, 13),
|
||||
(0xffffffc, 28),
|
||||
(0xfffe6, 20),
|
||||
(0x3fffd2, 22),
|
||||
(0xfffe7, 20),
|
||||
(0xfffe8, 20),
|
||||
(0x3fffd3, 22),
|
||||
(0x3fffd4, 22),
|
||||
(0x3fffd5, 22),
|
||||
(0x7fffd9, 23),
|
||||
(0x3fffd6, 22),
|
||||
(0x7fffda, 23),
|
||||
(0x7fffdb, 23),
|
||||
(0x7fffdc, 23),
|
||||
(0x7fffdd, 23),
|
||||
(0x7fffde, 23),
|
||||
(0xffffeb, 24),
|
||||
(0x7fffdf, 23),
|
||||
(0xffffec, 24),
|
||||
(0xffffed, 24),
|
||||
(0x3fffd7, 22),
|
||||
(0x7fffe0, 23),
|
||||
(0xffffee, 24),
|
||||
(0x7fffe1, 23),
|
||||
(0x7fffe2, 23),
|
||||
(0x7fffe3, 23),
|
||||
(0x7fffe4, 23),
|
||||
(0x1fffdc, 21),
|
||||
(0x3fffd8, 22),
|
||||
(0x7fffe5, 23),
|
||||
(0x3fffd9, 22),
|
||||
(0x7fffe6, 23),
|
||||
(0x7fffe7, 23),
|
||||
(0xffffef, 24),
|
||||
(0x3fffda, 22),
|
||||
(0x1fffdd, 21),
|
||||
(0xfffe9, 20),
|
||||
(0x3fffdb, 22),
|
||||
(0x3fffdc, 22),
|
||||
(0x7fffe8, 23),
|
||||
(0x7fffe9, 23),
|
||||
(0x1fffde, 21),
|
||||
(0x7fffea, 23),
|
||||
(0x3fffdd, 22),
|
||||
(0x3fffde, 22),
|
||||
(0xfffff0, 24),
|
||||
(0x1fffdf, 21),
|
||||
(0x3fffdf, 22),
|
||||
(0x7fffeb, 23),
|
||||
(0x7fffec, 23),
|
||||
(0x1fffe0, 21),
|
||||
(0x1fffe1, 21),
|
||||
(0x3fffe0, 22),
|
||||
(0x1fffe2, 21),
|
||||
(0x7fffed, 23),
|
||||
(0x3fffe1, 22),
|
||||
(0x7fffee, 23),
|
||||
(0x7fffef, 23),
|
||||
(0xfffea, 20),
|
||||
(0x3fffe2, 22),
|
||||
(0x3fffe3, 22),
|
||||
(0x3fffe4, 22),
|
||||
(0x7ffff0, 23),
|
||||
(0x3fffe5, 22),
|
||||
(0x3fffe6, 22),
|
||||
(0x7ffff1, 23),
|
||||
(0x3ffffe0, 26),
|
||||
(0x3ffffe1, 26),
|
||||
(0xfffeb, 20),
|
||||
(0x7fff1, 19),
|
||||
(0x3fffe7, 22),
|
||||
(0x7ffff2, 23),
|
||||
(0x3fffe8, 22),
|
||||
(0x1ffffec, 25),
|
||||
(0x3ffffe2, 26),
|
||||
(0x3ffffe3, 26),
|
||||
(0x3ffffe4, 26),
|
||||
(0x7ffffde, 27),
|
||||
(0x7ffffdf, 27),
|
||||
(0x3ffffe5, 26),
|
||||
(0xfffff1, 24),
|
||||
(0x1ffffed, 25),
|
||||
(0x7fff2, 19),
|
||||
(0x1fffe3, 21),
|
||||
(0x3ffffe6, 26),
|
||||
(0x7ffffe0, 27),
|
||||
(0x7ffffe1, 27),
|
||||
(0x3ffffe7, 26),
|
||||
(0x7ffffe2, 27),
|
||||
(0xfffff2, 24),
|
||||
(0x1fffe4, 21),
|
||||
(0x1fffe5, 21),
|
||||
(0x3ffffe8, 26),
|
||||
(0x3ffffe9, 26),
|
||||
(0xffffffd, 28),
|
||||
(0x7ffffe3, 27),
|
||||
(0x7ffffe4, 27),
|
||||
(0x7ffffe5, 27),
|
||||
(0xfffec, 20),
|
||||
(0xfffff3, 24),
|
||||
(0xfffed, 20),
|
||||
(0x1fffe6, 21),
|
||||
(0x3fffe9, 22),
|
||||
(0x1fffe7, 21),
|
||||
(0x1fffe8, 21),
|
||||
(0x7ffff3, 23),
|
||||
(0x3fffea, 22),
|
||||
(0x3fffeb, 22),
|
||||
(0x1ffffee, 25),
|
||||
(0x1ffffef, 25),
|
||||
(0xfffff4, 24),
|
||||
(0xfffff5, 24),
|
||||
(0x3ffffea, 26),
|
||||
(0x7ffff4, 23),
|
||||
(0x3ffffeb, 26),
|
||||
(0x7ffffe6, 27),
|
||||
(0x3ffffec, 26),
|
||||
(0x3ffffed, 26),
|
||||
(0x7ffffe7, 27),
|
||||
(0x7ffffe8, 27),
|
||||
(0x7ffffe9, 27),
|
||||
(0x7ffffea, 27),
|
||||
(0x7ffffeb, 27),
|
||||
(0xffffffe, 28),
|
||||
(0x7ffffec, 27),
|
||||
(0x7ffffed, 27),
|
||||
(0x7ffffee, 27),
|
||||
(0x7ffffef, 27),
|
||||
(0x7fffff0, 27),
|
||||
(0x3ffffee, 26),
|
||||
(0x3fffffff, 30),
|
||||
];
|
||||
|
||||
/// Tabella statica HPACK: `(nome, valore)`; l'indice è la posizione + 1.
|
||||
pub const STATICA: [(&str, &str); 61] = [
|
||||
(":authority", ""),
|
||||
(":method", "GET"),
|
||||
(":method", "POST"),
|
||||
(":path", "/"),
|
||||
(":path", "/index.html"),
|
||||
(":scheme", "http"),
|
||||
(":scheme", "https"),
|
||||
(":status", "200"),
|
||||
(":status", "204"),
|
||||
(":status", "206"),
|
||||
(":status", "304"),
|
||||
(":status", "400"),
|
||||
(":status", "404"),
|
||||
(":status", "500"),
|
||||
("accept-charset", ""),
|
||||
("accept-encoding", "gzip, deflate"),
|
||||
("accept-language", ""),
|
||||
("accept-ranges", ""),
|
||||
("accept", ""),
|
||||
("access-control-allow-origin", ""),
|
||||
("age", ""),
|
||||
("allow", ""),
|
||||
("authorization", ""),
|
||||
("cache-control", ""),
|
||||
("content-disposition", ""),
|
||||
("content-encoding", ""),
|
||||
("content-language", ""),
|
||||
("content-length", ""),
|
||||
("content-location", ""),
|
||||
("content-range", ""),
|
||||
("content-type", ""),
|
||||
("cookie", ""),
|
||||
("date", ""),
|
||||
("etag", ""),
|
||||
("expect", ""),
|
||||
("expires", ""),
|
||||
("from", ""),
|
||||
("host", ""),
|
||||
("if-match", ""),
|
||||
("if-modified-since", ""),
|
||||
("if-none-match", ""),
|
||||
("if-range", ""),
|
||||
("if-unmodified-since", ""),
|
||||
("last-modified", ""),
|
||||
("link", ""),
|
||||
("location", ""),
|
||||
("max-forwards", ""),
|
||||
("proxy-authenticate", ""),
|
||||
("proxy-authorization", ""),
|
||||
("range", ""),
|
||||
("referer", ""),
|
||||
("refresh", ""),
|
||||
("retry-after", ""),
|
||||
("server", ""),
|
||||
("set-cookie", ""),
|
||||
("strict-transport-security", ""),
|
||||
("transfer-encoding", ""),
|
||||
("user-agent", ""),
|
||||
("vary", ""),
|
||||
("via", ""),
|
||||
("www-authenticate", ""),
|
||||
];
|
||||
@@ -0,0 +1,545 @@
|
||||
//! HTTP/2 (M2.6): un client per una richiesta per connessione.
|
||||
//!
|
||||
//! Ambito dichiarato: una richiesta e una risposta per connessione, senza
|
||||
//! multiplexing e senza `PUSH_PROMISE`. Basta per caricare una pagina: il
|
||||
//! vantaggio rispetto a HTTP/1.1 è che il server sceglie il protocollo e che gli
|
||||
//! header viaggiano compressi (HPACK), non che apriamo più flussi insieme.
|
||||
//!
|
||||
//! Implementati: preface, `SETTINGS` (lettura e ACK), `HEADERS` con
|
||||
//! `CONTINUATION`, `DATA`, `WINDOW_UPDATE`, `PING`, `RST_STREAM`, `GOAWAY`;
|
||||
//! HPACK con tabella statica, tabella dinamica e Huffman.
|
||||
//!
|
||||
//! Fuori ambito: multiplexing, priorità, push, `PRIORITY` (ignorato).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::hpack_tabelle::{HUFFMAN, STATICA};
|
||||
use crate::net::{HttpUrl, Limiti, Response};
|
||||
|
||||
const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
|
||||
|
||||
const TIPO_DATA: u8 = 0x0;
|
||||
const TIPO_HEADERS: u8 = 0x1;
|
||||
const TIPO_RST_STREAM: u8 = 0x3;
|
||||
const TIPO_SETTINGS: u8 = 0x4;
|
||||
const TIPO_PUSH_PROMISE: u8 = 0x5;
|
||||
const TIPO_PING: u8 = 0x6;
|
||||
const TIPO_GOAWAY: u8 = 0x7;
|
||||
const TIPO_WINDOW_UPDATE: u8 = 0x8;
|
||||
const TIPO_CONTINUATION: u8 = 0x9;
|
||||
|
||||
const FLAG_END_STREAM: u8 = 0x1;
|
||||
const FLAG_ACK: u8 = 0x1;
|
||||
const FLAG_END_HEADERS: u8 = 0x4;
|
||||
|
||||
/// Finestra che annunciamo: grande, così una pagina intera ci arriva senza che
|
||||
/// dobbiamo chiedere pezzi (non è educato, ma è meglio che bloccarsi a 64 KB).
|
||||
const FINESTRA: u32 = 1 << 24;
|
||||
|
||||
/// Esegue una richiesta su una connessione già aperta e già in TLS con `h2`
|
||||
/// negoziato. `flusso` è la connessione: la funzione la consuma.
|
||||
pub fn esegui(
|
||||
flusso: &mut (impl Read + Write),
|
||||
u: &HttpUrl,
|
||||
metodo: &str,
|
||||
corpo: Option<(&str, &str)>,
|
||||
biscotti: Option<&str>,
|
||||
limiti: &Limiti,
|
||||
) -> Result<Response, String> {
|
||||
flusso
|
||||
.write_all(PREFACE)
|
||||
.map_err(|e| format!("preface HTTP/2 fallita: {}", e))?;
|
||||
|
||||
// SETTINGS: solo la finestra iniziale, per non farci strozzare dal server
|
||||
let mut impostazioni = Vec::new();
|
||||
impostazioni.extend_from_slice(&4u16.to_be_bytes()); // INITIAL_WINDOW_SIZE
|
||||
impostazioni.extend_from_slice(&FINESTRA.to_be_bytes());
|
||||
scrivi_frame(flusso, TIPO_SETTINGS, 0, 0, &impostazioni)?;
|
||||
// WINDOW_UPDATE sulla connessione: la finestra di connessione parte a 64 KB
|
||||
scrivi_frame(
|
||||
flusso,
|
||||
TIPO_WINDOW_UPDATE,
|
||||
0,
|
||||
0,
|
||||
&(FINESTRA - 65535).to_be_bytes(),
|
||||
)?;
|
||||
|
||||
// gli header della richiesta, compressi con HPACK
|
||||
let mut lista: Vec<(String, String)> = vec![
|
||||
(":method".into(), metodo.to_string()),
|
||||
(
|
||||
":scheme".into(),
|
||||
if u.tls { "https" } else { "http" }.into(),
|
||||
),
|
||||
(":authority".into(), u.host_da_intestazione()),
|
||||
(":path".into(), u.path.clone()),
|
||||
("user-agent".into(), "Mosaic/0.1".into()),
|
||||
("accept".into(), "text/html,*/*".into()),
|
||||
];
|
||||
if let Some(b) = biscotti {
|
||||
lista.push(("cookie".into(), b.to_string()));
|
||||
}
|
||||
if let Some((tipo, dati)) = corpo {
|
||||
lista.push(("content-type".into(), tipo.to_string()));
|
||||
lista.push(("content-length".into(), dati.len().to_string()));
|
||||
}
|
||||
let blocco = codifica_hpack(&lista);
|
||||
|
||||
let mut flag = FLAG_END_HEADERS;
|
||||
if corpo.is_none() {
|
||||
flag |= FLAG_END_STREAM;
|
||||
}
|
||||
scrivi_frame(flusso, TIPO_HEADERS, flag, 1, &blocco)?;
|
||||
if let Some((_, dati)) = corpo {
|
||||
scrivi_frame(flusso, TIPO_DATA, FLAG_END_STREAM, 1, dati.as_bytes())?;
|
||||
}
|
||||
|
||||
// --- lettura della risposta ---
|
||||
let mut decodificatore = Decodificatore::new();
|
||||
let mut stato: Option<u16> = None;
|
||||
let mut intestazioni: Vec<(String, String)> = Vec::new();
|
||||
let mut corpo_risposta: Vec<u8> = Vec::new();
|
||||
let mut frammenti_header: Vec<u8> = Vec::new();
|
||||
let mut finito = false;
|
||||
let scadenza = std::time::Instant::now() + limiti.timeout;
|
||||
|
||||
while !finito {
|
||||
if std::time::Instant::now() > scadenza {
|
||||
return Err("timeout in lettura (HTTP/2)".to_string());
|
||||
}
|
||||
let (tipo, flag, flusso_id, dati) = leggi_frame(flusso)?;
|
||||
match tipo {
|
||||
TIPO_SETTINGS => {
|
||||
if flag & FLAG_ACK == 0 {
|
||||
scrivi_frame(flusso, TIPO_SETTINGS, FLAG_ACK, 0, &[])?;
|
||||
}
|
||||
}
|
||||
TIPO_PING => {
|
||||
if flag & FLAG_ACK == 0 {
|
||||
scrivi_frame(flusso, TIPO_PING, FLAG_ACK, 0, &dati)?;
|
||||
}
|
||||
}
|
||||
TIPO_HEADERS => {
|
||||
// può seguire un CONTINUATION con il resto del blocco
|
||||
let mut blocco_header = dati;
|
||||
if let Some(padding) = padding(flag, &blocco_header) {
|
||||
blocco_header = blocco_header[padding..blocco_header.len() - padding].to_vec();
|
||||
}
|
||||
frammenti_header.extend_from_slice(&blocco_header);
|
||||
if flag & FLAG_END_HEADERS == 0 {
|
||||
continue;
|
||||
}
|
||||
let voci = decodificatore.decodifica(&frammenti_header)?;
|
||||
frammenti_header.clear();
|
||||
for (nome, valore) in voci {
|
||||
if nome == ":status" {
|
||||
stato = valore.trim().parse().ok();
|
||||
} else if !nome.starts_with(':') {
|
||||
intestazioni.push((nome, valore));
|
||||
}
|
||||
}
|
||||
if flag & FLAG_END_STREAM != 0 && flusso_id == 1 {
|
||||
finito = true;
|
||||
}
|
||||
}
|
||||
TIPO_CONTINUATION => {
|
||||
frammenti_header.extend_from_slice(&dati);
|
||||
if flag & FLAG_END_HEADERS != 0 {
|
||||
let voci = decodificatore.decodifica(&frammenti_header)?;
|
||||
frammenti_header.clear();
|
||||
for (nome, valore) in voci {
|
||||
if nome == ":status" {
|
||||
stato = valore.trim().parse().ok();
|
||||
} else if !nome.starts_with(':') {
|
||||
intestazioni.push((nome, valore));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
TIPO_DATA => {
|
||||
corpo_risposta.extend_from_slice(&dati);
|
||||
if corpo_risposta.len() > limiti.max_body {
|
||||
return Err(format!("corpo oltre {} byte", limiti.max_body));
|
||||
}
|
||||
// restituiamo la finestra, altrimenti il server si ferma
|
||||
let incremento = (dati.len() as u32).max(1);
|
||||
scrivi_frame(flusso, TIPO_WINDOW_UPDATE, 0, 0, &incremento.to_be_bytes())?;
|
||||
scrivi_frame(
|
||||
flusso,
|
||||
TIPO_WINDOW_UPDATE,
|
||||
0,
|
||||
flusso_id,
|
||||
&incremento.to_be_bytes(),
|
||||
)?;
|
||||
if flag & FLAG_END_STREAM != 0 {
|
||||
finito = true;
|
||||
}
|
||||
}
|
||||
TIPO_RST_STREAM => {
|
||||
let codice = dati
|
||||
.get(..4)
|
||||
.map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
.unwrap_or(0);
|
||||
return Err(format!(
|
||||
"il server ha azzerato il flusso (codice {})",
|
||||
codice
|
||||
));
|
||||
}
|
||||
TIPO_GOAWAY => {
|
||||
if !finito {
|
||||
return Err("il server ha chiuso la connessione (GOAWAY)".to_string());
|
||||
}
|
||||
}
|
||||
TIPO_PUSH_PROMISE => { /* fuori ambito: si ignora, e non lo abbiamo chiesto */ }
|
||||
_ => { /* PRIORITY e frame sconosciuti: ignorati per scelta */ }
|
||||
}
|
||||
let _ = TIPO_DATA;
|
||||
}
|
||||
|
||||
let stato = stato.ok_or("risposta senza :status")?;
|
||||
Ok(Response {
|
||||
status: stato,
|
||||
headers: intestazioni,
|
||||
body: corpo_risposta,
|
||||
url: format!(
|
||||
"{}://{}{}",
|
||||
if u.tls { "https" } else { "http" },
|
||||
u.host_da_intestazione(),
|
||||
u.path
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn padding(flag: u8, dati: &[u8]) -> Option<usize> {
|
||||
if flag & 0x8 == 0 {
|
||||
return None;
|
||||
}
|
||||
dati.first().map(|p| *p as usize + 1)
|
||||
}
|
||||
|
||||
fn scrivi_frame(
|
||||
flusso: &mut impl Write,
|
||||
tipo: u8,
|
||||
flag: u8,
|
||||
flusso_id: u32,
|
||||
dati: &[u8],
|
||||
) -> Result<(), String> {
|
||||
let lunghezza = dati.len();
|
||||
if lunghezza > 16_777_215 {
|
||||
return Err("frame troppo grande".to_string());
|
||||
}
|
||||
let mut testa = Vec::with_capacity(9);
|
||||
testa.extend_from_slice(&(lunghezza as u32).to_be_bytes()[1..]);
|
||||
testa.push(tipo);
|
||||
testa.push(flag);
|
||||
testa.extend_from_slice(&(flusso_id & 0x7fff_ffff).to_be_bytes());
|
||||
flusso
|
||||
.write_all(&testa)
|
||||
.and_then(|_| flusso.write_all(dati))
|
||||
.and_then(|_| flusso.flush())
|
||||
.map_err(|e| format!("scrittura frame fallita: {}", e))
|
||||
}
|
||||
|
||||
fn leggi_frame(flusso: &mut impl Read) -> Result<(u8, u8, u32, Vec<u8>), String> {
|
||||
let mut testa = [0u8; 9];
|
||||
flusso
|
||||
.read_exact(&mut testa)
|
||||
.map_err(|e| format!("lettura frame fallita: {}", e))?;
|
||||
let lunghezza = ((testa[0] as usize) << 16) | ((testa[1] as usize) << 8) | testa[2] as usize;
|
||||
if lunghezza > 16_777_215 {
|
||||
return Err("frame dichiarato troppo grande".to_string());
|
||||
}
|
||||
let mut dati = vec![0u8; lunghezza];
|
||||
if lunghezza > 0 {
|
||||
flusso
|
||||
.read_exact(&mut dati)
|
||||
.map_err(|e| format!("frame interrotto: {}", e))?;
|
||||
}
|
||||
let flusso_id = u32::from_be_bytes([testa[5] & 0x7f, testa[6], testa[7], testa[8]]);
|
||||
Ok((testa[3], testa[4], flusso_id, dati))
|
||||
}
|
||||
|
||||
// --- HPACK ---------------------------------------------------------------
|
||||
|
||||
/// Codifica un elenco di intestazioni. Si usa la forma indicizzata quando
|
||||
/// esiste una voce statica identica, altrimenti il nome indicizzato con valore
|
||||
/// letterale: è la stessa scelta di un client che vuole header corti.
|
||||
pub fn codifica_hpack(lista: &[(String, String)]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for (nome, valore) in lista {
|
||||
// corrispondenza esatta con la tabella statica → indice (bit 1)
|
||||
if let Some(indice) = STATICA.iter().position(|(n, v)| *n == nome && *v == valore) {
|
||||
out.push(0x80 | (indice as u8 + 1));
|
||||
continue;
|
||||
}
|
||||
// nome in tabella statica → nome indicizzato, valore letterale
|
||||
let indice_nome = STATICA
|
||||
.iter()
|
||||
.position(|(n, _)| *n == nome)
|
||||
.map(|i| i as u64 + 1);
|
||||
match indice_nome {
|
||||
Some(i) if i < 15 => out.push(i as u8), // 0000 + indice (4 bit)
|
||||
Some(i) => intero(&mut out, i, 4, 0x00),
|
||||
None => {
|
||||
out.push(0x00);
|
||||
stringa(&mut out, nome.as_bytes());
|
||||
}
|
||||
}
|
||||
stringa(&mut out, valore.as_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Intero con prefisso di `bit` bit (RFC 7541 §5.1). `bandiere` sono i bit alti
|
||||
/// della forma (per esempio 0 per "letterale senza Huffman"): il primo byte è
|
||||
/// `bandiere << bit` **oppure** il prefisso, non una congiunzione dei due.
|
||||
fn intero(out: &mut Vec<u8>, valore: u64, bit: u8, bandiere: u8) {
|
||||
let massimo = (1u64 << bit) - 1;
|
||||
if valore < massimo {
|
||||
out.push((bandiere << bit) | valore as u8);
|
||||
return;
|
||||
}
|
||||
out.push((bandiere << bit) | massimo as u8);
|
||||
let mut resto = valore - massimo;
|
||||
while resto >= 128 {
|
||||
out.push((resto % 128) as u8 | 0x80);
|
||||
resto /= 128;
|
||||
}
|
||||
out.push(resto as u8);
|
||||
}
|
||||
|
||||
/// Stringa letterale senza Huffman (più lunga, ma non serve un codificatore).
|
||||
fn stringa(out: &mut Vec<u8>, dati: &[u8]) {
|
||||
intero(out, dati.len() as u64, 7, 0x00);
|
||||
out.extend_from_slice(dati);
|
||||
}
|
||||
|
||||
struct Decodificatore {
|
||||
dinamica: Vec<(String, String)>,
|
||||
dimensione: usize,
|
||||
massima: usize,
|
||||
}
|
||||
|
||||
impl Decodificatore {
|
||||
fn new() -> Decodificatore {
|
||||
Decodificatore {
|
||||
dinamica: Vec::new(),
|
||||
dimensione: 0,
|
||||
massima: 4096,
|
||||
}
|
||||
}
|
||||
|
||||
fn voce(&self, indice: u64) -> Result<(String, String), String> {
|
||||
if indice == 0 {
|
||||
return Err("indice HPACK 0".to_string());
|
||||
}
|
||||
let statica = indice as usize;
|
||||
if statica <= STATICA.len() {
|
||||
let (n, v) = STATICA[statica - 1];
|
||||
return Ok((n.to_string(), v.to_string()));
|
||||
}
|
||||
let dinamica = statica - STATICA.len() - 1;
|
||||
self.dinamica
|
||||
.get(dinamica)
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("indice HPACK {} fuori tabella", indice))
|
||||
}
|
||||
|
||||
fn aggiungi(&mut self, nome: String, valore: String) {
|
||||
let peso = nome.len() + valore.len() + 32;
|
||||
self.dinamica.insert(0, (nome, valore));
|
||||
self.dimensione += peso;
|
||||
while self.dimensione > self.massima {
|
||||
if let Some((n, v)) = self.dinamica.pop() {
|
||||
self.dimensione -= n.len() + v.len() + 32;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decodifica(&mut self, dati: &[u8]) -> Result<Vec<(String, String)>, String> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < dati.len() {
|
||||
let primo = dati[i];
|
||||
if primo & 0x80 != 0 {
|
||||
// campo indicizzato
|
||||
let (indice, usati) = leggi_intero(&dati[i..], 7)?;
|
||||
i += usati;
|
||||
out.push(self.voce(indice)?);
|
||||
} else if primo & 0x40 != 0 {
|
||||
// letterale con indicizzazione incrementale
|
||||
let (indice, usati) = leggi_intero(&dati[i..], 6)?;
|
||||
i += usati;
|
||||
let nome = if indice == 0 {
|
||||
let (s, usati) = leggi_stringa(&dati[i..])?;
|
||||
i += usati;
|
||||
s
|
||||
} else {
|
||||
self.voce(indice)?.0
|
||||
};
|
||||
let (valore, usati) = leggi_stringa(&dati[i..])?;
|
||||
i += usati;
|
||||
self.aggiungi(nome.clone(), valore.clone());
|
||||
out.push((nome, valore));
|
||||
} else {
|
||||
// letterale senza indicizzazione (0000) o mai indicizzato (0001)
|
||||
let (indice, usati) = leggi_intero(&dati[i..], 4)?;
|
||||
i += usati;
|
||||
let nome = if indice == 0 {
|
||||
let (s, usati) = leggi_stringa(&dati[i..])?;
|
||||
i += usati;
|
||||
s
|
||||
} else {
|
||||
self.voce(indice)?.0
|
||||
};
|
||||
let (valore, usati) = leggi_stringa(&dati[i..])?;
|
||||
i += usati;
|
||||
out.push((nome, valore));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn leggi_intero(dati: &[u8], bit: u8) -> Result<(u64, usize), String> {
|
||||
let massimo = ((1u16 << bit) - 1) as u8;
|
||||
let primo = *dati.first().ok_or("intero HPACK mancante")?;
|
||||
let mut valore = (primo & massimo) as u64;
|
||||
if valore < massimo as u64 {
|
||||
return Ok((valore, 1));
|
||||
}
|
||||
let mut i = 1usize;
|
||||
let mut moltiplicatore = 1u64;
|
||||
loop {
|
||||
let b = *dati.get(i).ok_or("intero HPACK troncato")?;
|
||||
valore += ((b & 0x7f) as u64) * moltiplicatore;
|
||||
i += 1;
|
||||
if b & 0x80 == 0 {
|
||||
break;
|
||||
}
|
||||
moltiplicatore *= 128;
|
||||
if i > 10 {
|
||||
return Err("intero HPACK troppo lungo".to_string());
|
||||
}
|
||||
}
|
||||
Ok((valore, i))
|
||||
}
|
||||
|
||||
fn leggi_stringa(dati: &[u8]) -> Result<(String, usize), String> {
|
||||
let huffman = dati.first().map(|b| b & 0x80 != 0).unwrap_or(false);
|
||||
let (lunghezza, usati) = leggi_intero(dati, 7)?;
|
||||
let inizio = usati;
|
||||
let fine = inizio + lunghezza as usize;
|
||||
if fine > dati.len() {
|
||||
return Err("stringa HPACK troncata".to_string());
|
||||
}
|
||||
let grezzo = &dati[inizio..fine];
|
||||
let testo = if huffman {
|
||||
decodifica_huffman(grezzo)?
|
||||
} else {
|
||||
String::from_utf8_lossy(grezzo).to_string()
|
||||
};
|
||||
Ok((testo, fine))
|
||||
}
|
||||
|
||||
/// Tabella di decodifica: `(lunghezza, codice) → simbolo`.
|
||||
fn tabella_huffman() -> &'static HashMap<(u8, u32), u16> {
|
||||
static TABELLA: OnceLock<HashMap<(u8, u32), u16>> = OnceLock::new();
|
||||
TABELLA.get_or_init(|| {
|
||||
let mut m = HashMap::with_capacity(257);
|
||||
for (simbolo, (codice, lunghezza)) in HUFFMAN.iter().enumerate() {
|
||||
m.insert((*lunghezza, *codice), simbolo as u16);
|
||||
}
|
||||
m
|
||||
})
|
||||
}
|
||||
|
||||
fn decodifica_huffman(dati: &[u8]) -> Result<String, String> {
|
||||
let tabella = tabella_huffman();
|
||||
let mut out: Vec<u8> = Vec::new();
|
||||
let mut codice = 0u32;
|
||||
let mut lunghezza = 0u8;
|
||||
for byte in dati {
|
||||
for bit in (0..8).rev() {
|
||||
codice = (codice << 1) | ((byte >> bit) & 1) as u32;
|
||||
lunghezza += 1;
|
||||
if lunghezza > 30 {
|
||||
return Err("codice Huffman troppo lungo".to_string());
|
||||
}
|
||||
if let Some(simbolo) = tabella.get(&(lunghezza, codice)) {
|
||||
if *simbolo == 256 {
|
||||
return Err("simbolo EOS dentro una stringa Huffman".to_string());
|
||||
}
|
||||
out.push(*simbolo as u8);
|
||||
codice = 0;
|
||||
lunghezza = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
// il riempimento finale è tutto 1: se resta un codice non è zeri, è corretto
|
||||
Ok(String::from_utf8_lossy(&out).to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn huffman_della_rfc_si_decodifica() {
|
||||
// "www.example.com" codificato come nell'esempio della RFC 7541 §C.4.1
|
||||
let dati = [
|
||||
0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff,
|
||||
];
|
||||
assert_eq!(decodifica_huffman(&dati).unwrap(), "www.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_di_esempio_della_rfc() {
|
||||
// primo blocco dell'esempio C.3.1: :method GET, :scheme http, :path /,
|
||||
// :authority www.example.com
|
||||
let blocco = [
|
||||
0x82, 0x86, 0x84, 0x41, 0x0f, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70,
|
||||
0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d,
|
||||
];
|
||||
let voci = Decodificatore::new().decodifica(&blocco).unwrap();
|
||||
assert_eq!(
|
||||
voci,
|
||||
vec![
|
||||
(":method".to_string(), "GET".to_string()),
|
||||
(":scheme".to_string(), "http".to_string()),
|
||||
(":path".to_string(), "/".to_string()),
|
||||
(":authority".to_string(), "www.example.com".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_codificati_si_rileggono() {
|
||||
let lista = vec![
|
||||
(":method".to_string(), "GET".to_string()),
|
||||
(":path".to_string(), "/pagina?x=1".to_string()),
|
||||
("user-agent".to_string(), "Mosaic/0.1".to_string()),
|
||||
("cookie".to_string(), "a=1; b=2".to_string()),
|
||||
];
|
||||
let blocco = codifica_hpack(&lista);
|
||||
let voci = Decodificatore::new().decodifica(&blocco).unwrap();
|
||||
assert_eq!(voci, lista);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interi_lunghi_si_codificano_come_da_rfc() {
|
||||
// RFC 7541 §C.1.3: 1337 con prefisso 5 bit → 31, 154, 10
|
||||
let mut out = Vec::new();
|
||||
intero(&mut out, 1337, 5, 0x00);
|
||||
assert_eq!(out, vec![0x1f, 0x9a, 0x0a]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Solo per diagnosi: decodifica un blocco HPACK con un decodificatore nuovo.
|
||||
pub fn decodifica_pubblica(blocco: &[u8]) -> Result<Vec<(String, String)>, String> {
|
||||
Decodificatore::new().decodifica(blocco)
|
||||
}
|
||||
+71
-4
@@ -6,9 +6,11 @@
|
||||
//!
|
||||
//! Ambito dichiarato: `GET` e `POST`, campi di testo, password, textarea,
|
||||
//! caselle, radio e menu a tendina, valori presi dallo stato dei moduli del
|
||||
//! guscio. Fuori ambito: `multipart/form-data`, invio di file, `enctype` diversi,
|
||||
//! pulsanti con `formaction`/`formmethod`, e i campi senza `name` (che in HTML
|
||||
//! non vengono inviati — anche qui).
|
||||
//! guscio. `enctype` supportati: `application/x-www-form-urlencoded` (predefinito),
|
||||
//! `multipart/form-data` e `text/plain`. Fuori ambito: invio di file (non c'è
|
||||
//! ancora un selettore di file, quindi `input type=file` resta escluso),
|
||||
//! `formaction`/`formmethod`, e i campi senza `name` (che in HTML non vengono
|
||||
//! inviati — anche qui).
|
||||
|
||||
use crate::dom::{Document, Node, NodeKind};
|
||||
use crate::layout;
|
||||
@@ -23,6 +25,8 @@ pub struct Invio {
|
||||
pub url: String,
|
||||
/// corpo codificato, solo per POST
|
||||
pub corpo: Option<String>,
|
||||
/// `Content-Type` da mandare col corpo (`None` per GET)
|
||||
pub content_type: Option<String>,
|
||||
}
|
||||
|
||||
/// Prepara l'invio del formulario che contiene `form_node`.
|
||||
@@ -68,11 +72,28 @@ pub fn prepara(
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
|
||||
// `enctype` decide come si scrive il corpo: è una differenza reale, non un
|
||||
// dettaglio, perché il server legge i campi in modo diverso
|
||||
let enctype = doc
|
||||
.attr(form_node, "enctype")
|
||||
.unwrap_or("application/x-www-form-urlencoded")
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
|
||||
if metodo == "POST" {
|
||||
let (corpo, tipo) = match enctype.as_str() {
|
||||
"multipart/form-data" => {
|
||||
let (corpo, confine) = multipart(&campi);
|
||||
(corpo, format!("multipart/form-data; boundary={}", confine))
|
||||
}
|
||||
"text/plain" => (testo_semplice(&campi), "text/plain".to_string()),
|
||||
_ => (codificato, "application/x-www-form-urlencoded".to_string()),
|
||||
};
|
||||
Ok(Invio {
|
||||
metodo: metodo.to_string(),
|
||||
url,
|
||||
corpo: Some(codificato),
|
||||
corpo: Some(corpo),
|
||||
content_type: Some(tipo),
|
||||
})
|
||||
} else {
|
||||
let url = if codificato.is_empty() {
|
||||
@@ -86,10 +107,56 @@ pub fn prepara(
|
||||
metodo: metodo.to_string(),
|
||||
url,
|
||||
corpo: None,
|
||||
content_type: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Corpo `multipart/form-data`: un confine che non compare nei dati, poi una
|
||||
/// parte per campo. Restituisce corpo e valore del confine.
|
||||
fn multipart(campi: &[(String, String)]) -> (String, String) {
|
||||
// il confine non deve comparire nei valori, altrimenti il server taglia lì
|
||||
let mut confine = String::from("----MosaicBoundary7d1a93f2c");
|
||||
let mut tentativi = 0;
|
||||
while campi
|
||||
.iter()
|
||||
.any(|(k, v)| k.contains(&confine) || v.contains(&confine))
|
||||
{
|
||||
tentativi += 1;
|
||||
confine = format!("----MosaicBoundary7d1a93f2c{}", tentativi);
|
||||
}
|
||||
|
||||
let mut corpo = String::new();
|
||||
for (nome, valore) in campi {
|
||||
corpo.push_str("--");
|
||||
corpo.push_str(&confine);
|
||||
corpo.push_str("\r\n");
|
||||
// il nome va fra virgolette, con virgolette e ritorni a capo neutralizzati
|
||||
corpo.push_str(&format!(
|
||||
"Content-Disposition: form-data; name=\"{}\"\r\n\r\n",
|
||||
nome.replace('"', "%22").replace('\r', "").replace('\n', "")
|
||||
));
|
||||
corpo.push_str(valore);
|
||||
corpo.push_str("\r\n");
|
||||
}
|
||||
corpo.push_str("--");
|
||||
corpo.push_str(&confine);
|
||||
corpo.push_str("--\r\n");
|
||||
(corpo, confine)
|
||||
}
|
||||
|
||||
/// Corpo `text/plain`: `nome=valore` per riga.
|
||||
fn testo_semplice(campi: &[(String, String)]) -> String {
|
||||
let mut corpo = String::new();
|
||||
for (nome, valore) in campi {
|
||||
corpo.push_str(nome);
|
||||
corpo.push('=');
|
||||
corpo.push_str(valore);
|
||||
corpo.push_str("\r\n");
|
||||
}
|
||||
corpo
|
||||
}
|
||||
|
||||
/// Campi (nome, valore) nell'ordine del documento.
|
||||
fn campi_del_form(doc: &Document, form: &FormState, form_node: usize) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -10,6 +10,8 @@ pub mod css;
|
||||
pub mod dom;
|
||||
pub mod ffi;
|
||||
pub mod font;
|
||||
pub mod hpack_tabelle;
|
||||
pub mod http2;
|
||||
pub mod img;
|
||||
pub mod invio;
|
||||
pub mod layout;
|
||||
|
||||
+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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -112,6 +112,7 @@ fn limiti() -> net::Limiti {
|
||||
timeout: std::time::Duration::from_secs(10),
|
||||
max_body: MAX_SOTTO_RISORSA,
|
||||
max_redirect: 3,
|
||||
http2: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user