From cc449a548debc2017050a45a34828a15f7bd83bd Mon Sep 17 00:00:00 2001 From: Carlo Baratto Date: Fri, 13 Nov 2026 07:30:03 +0100 Subject: [PATCH] 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. --- desktop/appimage/build.sh | 4 + desktop/src/main.rs | 33 +- docs/10-roadmap.md | 9 +- engine/README.md | 5 + engine/include/engine.h | 8 +- engine/scripts/net-check.sh | 13 + engine/src/bin/mosaic-net.rs | 119 ++++++ engine/src/ffi.rs | 73 +++- engine/src/hpack_tabelle.rs | 330 +++++++++++++++ engine/src/http2.rs | 545 +++++++++++++++++++++++++ engine/src/invio.rs | 75 +++- engine/src/lib.rs | 2 + engine/src/net.rs | 481 +++++++++++++++++++++- engine/src/resource.rs | 1 + engine/tests/invio_multipart.rs | 240 +++++++++++ engine/tests/proxy.rs | 125 ++++++ engine/tests/rete_esterna.rs | 109 +++++ harbour-mosaic/include/engine.h | 8 +- harbour-mosaic/rpm/harbour-mosaic.spec | 9 +- harbour-mosaic/src/engineview.cpp | 64 ++- harbour-mosaic/src/engineview.h | 2 + 21 files changed, 2222 insertions(+), 33 deletions(-) create mode 100644 engine/src/bin/mosaic-net.rs create mode 100644 engine/src/hpack_tabelle.rs create mode 100644 engine/src/http2.rs create mode 100644 engine/tests/invio_multipart.rs create mode 100644 engine/tests/proxy.rs create mode 100644 engine/tests/rete_esterna.rs diff --git a/desktop/appimage/build.sh b/desktop/appimage/build.sh index 84c6333..bd03a0b 100755 --- a/desktop/appimage/build.sh +++ b/desktop/appimage/build.sh @@ -38,6 +38,10 @@ rm -rf "$APPDIR" mkdir -p "$APPDIR/usr/bin" "$APPDIR/usr/share/mosaic/fonts" \ "$APPDIR/usr/share/applications" "$APPDIR/usr/share/icons/hicolor/256x256/apps" install -m 755 "$BIN" "$APPDIR/usr/bin/mosaic-desktop" +# il servizio di rete separato: il desktop lo usa con --rete-esterna. Il binario +# appartiene al crate del motore, non a quello del guscio. +cargo build --release --manifest-path "$ROOT/../engine/Cargo.toml" --bin mosaic-net >/dev/null +install -m 755 "$ROOT/../engine/target/release/mosaic-net" "$APPDIR/usr/bin/mosaic-net" install -m 644 "$ROOT/demo.html" "$APPDIR/usr/share/mosaic/" install -m 644 "$ROOT/fonts/DejaVuSans.ttf" "$ROOT/fonts/DejaVuSerif.ttf" "$APPDIR/usr/share/mosaic/fonts/" diff --git a/desktop/src/main.rs b/desktop/src/main.rs index b86aa20..6ecbc22 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -290,7 +290,16 @@ fn esegui_invio( ) -> Result<(), String> { let limiti = engine::net::Limiti::default(); let risposta = match (&richiesta.corpo, richiesta.metodo.as_str()) { - (Some(corpo), "POST") => client.post(&richiesta.url, corpo, &limiti), + // il tipo di contenuto è quello preparato da `invio`: urlencoded, multipart o testo + (Some(corpo), "POST") => client.post_con( + &richiesta.url, + corpo, + richiesta + .content_type + .as_deref() + .unwrap_or("application/x-www-form-urlencoded"), + &limiti, + ), _ => client.get(&richiesta.url, &limiti), }?; let testo = risposta.text()?; @@ -341,6 +350,7 @@ fn main() { let mut args = std::env::args().skip(1); let mut html_path: Option = None; let mut url: Option = None; + let mut rete_esterna = false; let mut css_path: Option = None; let mut zoom = 1.0f64; let mut size = (1100u32, 800u32); @@ -356,6 +366,7 @@ fn main() { while let Some(a) = args.next() { match a.as_str() { + "--rete-esterna" => rete_esterna = true, "--html" => html_path = args.next().map(PathBuf::from), "--url" => url = args.next(), "--aspetta" => { @@ -427,7 +438,25 @@ fn main() { .unwrap_or_else(|| PathBuf::from(".")); // client con stato di sessione: cookie e cache vivono quanto la navigazione - let client = std::rc::Rc::new(engine::net::Client::new()); + // `--rete-esterna`: la rete vive in un processo a parte (i cookie stanno là) + let client = std::rc::Rc::new(if rete_esterna { + let programma = std::env::current_exe() + .ok() + .and_then(|e| e.parent().map(|d| d.join("mosaic-net"))) + .unwrap_or_else(|| std::path::PathBuf::from("mosaic-net")); + match engine::net::Client::con_servizio_esterno(&programma) { + Ok(c) => { + eprintln!("mosaic: rete in un processo separato ({})", programma.display()); + c + } + Err(e) => { + eprintln!("mosaic: servizio di rete non avviato ({}), resto in processo", e); + engine::net::Client::new() + } + } + } else { + engine::net::Client::new() + }); let mut page = match load( &html_path, diff --git a/docs/10-roadmap.md b/docs/10-roadmap.md index b468d8e..99757cd 100644 --- a/docs/10-roadmap.md +++ b/docs/10-roadmap.md @@ -67,7 +67,8 @@ gusci (Sailfish e desktop) ricostruiti sullo stesso motore. | M2.3 Tabelle | modello tabella, `colspan`, larghezze automatiche e dichiarate | **fatto** (casi 74–76); `rowspan` e `border-collapse` restano fuori | | M2.4 Formulari | input testo/password, checkbox, radio, select, textarea, pulsanti, fuoco, tastiera virtuale | **fatto** (casi 77–80); mancano invio del form, caret/selezione, menu a comparsa | | M2.5 Scripting | motore JS `Boa`, binding DOM, event loop | **fatto** per il perimetro dichiarato: script inline ed esterni nell'ordine del documento, `getElementById`/`querySelector`/`querySelectorAll`, testo, attributi, `dataset`, `style`, `classList`, navigazione, costruzione di nodi, `innerHTML` e `insertAdjacentHTML`, eventi `click`/`input`/`submit`/`keydown`/`focus`/`blur`/`change` con propagazione, `stopPropagation`, `preventDefault`, handler inline, `element.value`, `console.log`, timer con orologio iniettato, `fetch` con risposta consegnata dal guscio. **Fuori ambito dichiarato:** Promise vere (il `then` di `fetch` è una catena semplificata, `await` non funziona), cattura degli eventi, pseudo-classi nei selettori, `closest`, Canvas/SVG | -| M2.6 Rete | HTTP/1.1, `fetch`, cache, cookie, processo di rete separato | **fatto** per il perimetro dichiarato: `GET`/`POST` http e https con TLS, `Content-Length`/chunked, reindirizzamenti, limiti, sotto-risorse (CSS, immagini, script) con URL risolti sul documento, invio dei formulari, `Client` con **cookie** (`Set-Cookie`, `Domain`, `Path`, `Secure`, `Max-Age`, `Expires`) e **cache** con scadenza, usato da navigazione, invio, `fetch` e sotto-risorse. **Fuori ambito dichiarato:** HTTP/2 (richiede frame e HPACK: incremento a sé), processo di rete separato (serve un disegno di IPC), proxy, `multipart/form-data`. **Sul telefono** `fetch` e i cookie sono collegati: sessione di rete nel confine C (`engine_session_*`), documento creato con la sessione, richieste degli script eseguite dal guscio e consegnate al motore | +| M2.6 Rete | HTTP/1.1, `fetch`, cache, cookie, processo di rete separato | **fatto** per il perimetro dichiarato: `GET`/`POST` http e https con TLS, `Content-Length`/chunked, reindirizzamenti, limiti, sotto-risorse (CSS, immagini, script) con URL risolti sul documento, invio dei formulari, `Client` con **cookie** (`Set-Cookie`, `Domain`, `Path`, `Secure`, `Max-Age`, `Expires`) e **cache** con scadenza, usato da navigazione, invio, `fetch` e sotto-risorse. **Aggiunte in M2.6b:** **HTTP/2** (preface, `SETTINGS`, `HEADERS`/`CONTINUATION`, `DATA`, `WINDOW_UPDATE`, `PING`, `RST_STREAM`, `GOAWAY`; HPACK con tabella statica, dinamica e Huffman — tabelle generate dalla RFC 7541 e validate sui suoi esempi); **proxy** `http_proxy`/`https_proxy`/`all_proxy`/`no_proxy` con tunnel `CONNECT` e `Proxy-Authorization`; **`multipart/form-data`** e `text/plain` oltre al `urlencoded`; **processo di rete separato** (`mosaic-net`: IPC a lunghezza prefissata su stdin/stdout, cookie e cache nel servizio) usato dal desktop con `--rete-esterna`. +**Fuori ambito dichiarato:** multiplexing HTTP/2, `PUSH_PROMISE` e priorità; proxy SOCKS e PAC; invio di file (`input type=file`); sul telefono il servizio di rete resta nel processo, perché un'app sandboxata non avvia processi figli in modo affidabile. **Sul telefono** `fetch` e i cookie sono collegati: sessione di rete nel confine C (`engine_session_*`), documento creato con la sessione, richieste degli script eseguite dal guscio e consegnate al motore | | M2.7 Compositor | tile, danni, scroll compositato, animazioni (`wgpu`) | da fare | ### M2.6, stato preciso @@ -86,7 +87,7 @@ locale vero, più una prova manuale su `https://example.com`): | Charset dichiarato (`iso-8859-1` convertito, UTF-8 verificato) | fatto | | Errori di rete come messaggi, mai pagine mute | fatto | | Sotto-risorse: `link[rel=stylesheet]` e `img[src]`, con URL risolti sul documento | fatto (`resource.rs`, 4 prove con server locale) | -| `fetch` da JavaScript, cookie, cache, HTTP/2, processo di rete separato | **mancano** | +| `fetch` da JavaScript, cookie, cache, HTTP/2, processo di rete separato | **fatti** (HTTP/2 senza multiplexing; servizio di rete sul desktop) | | Sotto-risorse mancanti | `@import`, `srcset`, font via URL: **mancano**; l'errore è riportato in `resource_errors`, non silenzioso | Il TLS è l'unica parte del motore con **codice C** (l'assembly di `ring`): il resto @@ -106,13 +107,13 @@ Residui dichiarati dei formulari, con il costo stimato: |---|---|---| | Caret e selezione del testo | motore + gusci | **fatto** (casi 83–84); restano il clic che posiziona dentro il testo, il doppio clic sulla parola, gli appunti e la selezione su più righe | | Menu a tendina a comparsa | motore: elenco disegnato con le opzioni e la voce evidenziata; gusci: apertura e scelta | **fatto** (caso 85) | -| Invio del form (`action`, GET/POST, codifica dei campi) | motore + rete | **fatto**: `invio.rs`, GET con query e POST urlencoded, `preventDefault` rispettato; mancano `multipart/form-data` e i file | +| Invio del form (`action`, GET/POST, codifica dei campi) | motore + rete | **fatto**: `invio.rs`, GET con query, POST `urlencoded`/`multipart`/`text/plain`, `preventDefault` rispettato; mancano i file | Voci trasferite da M1: bidi (fatto, vedi M2.1) e harness WPT con soglia ≥ 90 % sul parsing (ancora da agganciare: richiede il corpus esterno). - Motore JS integrato (decisione DA-1) con binding IDL generati. -- Event loop, eventi, `fetch` sul processo di rete, stack HTTP/1.1–2, cache. +- Event loop, eventi, `fetch` sul processo di rete, stack HTTP/1.1 e HTTP/2, cache. - Flexbox e grid completi; tabelle base. - Processo di rete separato e compositor GPU (`wgpu`), tile, danni, scroll compositato. - Animazioni e transizioni compositate. diff --git a/engine/README.md b/engine/README.md index 6ad8c5e..992f19f 100644 --- a/engine/README.md +++ b/engine/README.md @@ -49,6 +49,11 @@ Nessun codice di WebKit, Blink, Gecko o Servo: parser, cascata, layout e raster | `fetch` con risposta consegnata dal guscio, `dataset`, `insertAdjacentHTML`, `keydown`/`focus`/`blur`/`change` | fatto (M2.5) | `richieste_pendenti`, `consegna_risposta`, `evento_tasto` | | Cookie e cache di sessione (`Client`) usati da navigazione, invio, `fetch` e sotto-risorse | fatto (M2.6) | `src/cookie.rs`, `net::Client` | | Sessione nel confine C: `engine_session_new/fetch/free`, `engine_doc_new_session`, `requests_json`, `deliver` | fatto (M2.6) | `src/ffi.rs`, entrambi i gusci | +| HTTP/2: preface, SETTINGS, HEADERS/CONTINUATION, DATA, WINDOW_UPDATE, PING, RST_STREAM, GOAWAY | fatto (M2.6b) | `src/http2.rs` | +| HPACK: tabella statica, dinamica, Huffman | fatto (M2.6b) | `src/hpack_tabelle.rs` (generato dalla RFC 7541) | +| Proxy `http_proxy`/`https_proxy`/`no_proxy`, tunnel `CONNECT` | fatto (M2.6b) | `src/net.rs` | +| `multipart/form-data` e `text/plain` oltre a `urlencoded` | fatto (M2.6b) | `src/invio.rs` | +| Processo di rete separato con IPC su stdin/stdout | fatto (M2.6b, desktop) | `src/bin/mosaic-net.rs` | | Rete: `GET` http/https con TLS, chunked, reindirizzamenti, limiti | fatto in parte (M2.6) | `src/net.rs`, `render --url`, `desktop --url` | | Sotto-risorse dalla rete: `link[rel=stylesheet]` e `img[src]` | fatto (M2.6) | `src/resource.rs`, `tests/risorse.rs` | | WPT (`html/syntax/parsing` ≥ 90 %) | mancante | — | diff --git a/engine/include/engine.h b/engine/include/engine.h index 4bcd364..6c0209d 100644 --- a/engine/include/engine.h +++ b/engine/include/engine.h @@ -83,6 +83,10 @@ int engine_doc_pump(EngineDoc *doc, uint64_t now_ms); /* Prima scadenza dei timer in ms, oppure -1. */ int64_t engine_doc_next_timer(EngineDoc *doc); +/* Invio del formulario in attesa (pulsante premuto senza preventDefault): + * JSON {metodo, url, corpo, tipo}, oppure NULL. Lo esegue il guscio. */ +char *engine_doc_invio_json(EngineDoc *doc, const char *state_json); + /* Errori degli script e messaggi di console.log, una voce per riga. */ char *engine_doc_errors(EngineDoc *doc); @@ -96,8 +100,8 @@ void engine_session_free(EngineSession *sessione); * Restituisce il corpo da liberare con engine_string_free(), o NULL; *status * riceve il codice HTTP (0 se non c'è stata risposta). */ char *engine_session_fetch(EngineSession *sessione, const char *url, - const char *metodo, const char *corpo, int *status, - char **error); + const char *metodo, const char *corpo, + const char *tipo, int *status, char **error); /* Indirizzo assoluto di un riferimento rispetto al documento (NULL se non è rete). */ char *engine_risolvi_url(const char *base, const char *riferito); diff --git a/engine/scripts/net-check.sh b/engine/scripts/net-check.sh index 7f11e3b..be25912 100644 --- a/engine/scripts/net-check.sh +++ b/engine/scripts/net-check.sh @@ -54,4 +54,17 @@ else fi fi +# 4. HTTP/2: il server deve negoziare h2 e la pagina deve arrivare +if MOSAIC_DEBUG=1 "$RENDER" --url https://example.com/ --font "$FONT" \ + --out "$USCITA/h2.png" --size 320x240 > "$USCITA/h2.out" 2> "$USCITA/h2.err"; then + if grep -q "richiesta in HTTP/2" "$USCITA/h2.err"; then + echo "ok HTTP/2: negoziato con example.com" + else + echo "warn HTTP/2 non negoziato (il server può non offrirlo)" + fi +else + echo "FAIL HTTP/2: la pagina non è arrivata" + fallisci=1 +fi + exit $fallisci diff --git a/engine/src/bin/mosaic-net.rs b/engine/src/bin/mosaic-net.rs new file mode 100644 index 0000000..37fcf08 --- /dev/null +++ b/engine/src/bin/mosaic-net.rs @@ -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 = 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() +} diff --git a/engine/src/ffi.rs b/engine/src/ffi.rs index 42b379b..d61f70f 100644 --- a/engine/src/ffi.rs +++ b/engine/src/ffi.rs @@ -370,6 +370,11 @@ pub struct EngineDoc { base_dir: PathBuf, /// ultimo impaginato: serve a sapere che nodo sta sotto il puntatore layout: Option, + /// 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, + /// indirizzo del documento, per risolvere `action` dei formulari + base_url: Option, } /// 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() + } + } +} diff --git a/engine/src/hpack_tabelle.rs b/engine/src/hpack_tabelle.rs new file mode 100644 index 0000000..40f3e6a --- /dev/null +++ b/engine/src/hpack_tabelle.rs @@ -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", ""), +]; diff --git a/engine/src/http2.rs b/engine/src/http2.rs new file mode 100644 index 0000000..eb721db --- /dev/null +++ b/engine/src/http2.rs @@ -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 { + 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 = None; + let mut intestazioni: Vec<(String, String)> = Vec::new(); + let mut corpo_risposta: Vec = Vec::new(); + let mut frammenti_header: Vec = 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 { + 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), 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 { + 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, 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, 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, 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> = 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 { + let tabella = tabella_huffman(); + let mut out: Vec = 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, String> { + Decodificatore::new().decodifica(blocco) +} diff --git a/engine/src/invio.rs b/engine/src/invio.rs index ebf6292..ebc3fd5 100644 --- a/engine/src/invio.rs +++ b/engine/src/invio.rs @@ -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, + /// `Content-Type` da mandare col corpo (`None` per GET) + pub content_type: Option, } /// Prepara l'invio del formulario che contiene `form_node`. @@ -68,11 +72,28 @@ pub fn prepara( .collect::>() .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(); diff --git a/engine/src/lib.rs b/engine/src/lib.rs index f735556..e43d39c 100644 --- a/engine/src/lib.rs +++ b/engine/src/lib.rs @@ -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; diff --git a/engine/src/net.rs b/engine/src/net.rs index 8c07a22..e75d0a7 100644 --- a/engine/src/net.rs +++ b/engine/src/net.rs @@ -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, cache: RefCell>, + /// se presente, le richieste le esegue un processo a parte e i cookie stanno là + esterno: RefCell>, } 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 { - 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 { + 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, @@ -188,6 +214,10 @@ impl Client { 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, @@ -243,7 +273,12 @@ pub fn get(url: &str, limiti: &Limiti) -> Result { 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 { + 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) } @@ -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> = 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, @@ -290,11 +674,16 @@ fn richiesta( limiti: &Limiti, ) -> Result { 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 = 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 = 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>, ) -> Result, 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, } } diff --git a/engine/src/resource.rs b/engine/src/resource.rs index e8ac092..47325b6 100644 --- a/engine/src/resource.rs +++ b/engine/src/resource.rs @@ -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, } } diff --git a/engine/tests/invio_multipart.rs b/engine/tests/invio_multipart.rs new file mode 100644 index 0000000..162c635 --- /dev/null +++ b/engine/tests/invio_multipart.rs @@ -0,0 +1,240 @@ +//! `enctype` dei formulari (M2.6), provato sul serio: un server locale riceve la +//! richiesta e il test guarda il corpo grezzo. Niente internet, CI deterministica. +//! +//! Il punto non è che il corpo «contenga i campi»: è che il server possa +//! *leggerli*, quindi il confine dichiarato nell'intestazione deve essere lo +//! stesso che separa le parti nel corpo, e la fine deve essere segnata. + +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::thread; + +use engine::invio::prepara; +use engine::net::{Client, Limiti}; +use engine::{ContenutoPagina, FormState}; + +const MODULO: &str = concat!( + "
", + "", + "
" +); + +/// Server che accetta una richiesta, ne cattura il testo completo e risponde `ok`. +fn server_che_riceve() -> (u16, std::sync::mpsc::Receiver) { + let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera"); + let porta = ascolto.local_addr().unwrap().port(); + let (invio, ricevi) = std::sync::mpsc::channel(); + thread::spawn(move || { + if let Some(Ok(mut flusso)) = ascolto.incoming().next() { + let mut grezzo = Vec::new(); + let mut buf = [0u8; 4096]; + // legge finché la richiesta è completa secondo Content-Length + loop { + let n = flusso.read(&mut buf).unwrap_or(0); + if n == 0 { + break; + } + grezzo.extend_from_slice(&buf[..n]); + let testo = String::from_utf8_lossy(&grezzo).to_string(); + if let Some(testa_corpo) = separa(&testo) { + if let Some(lunghezza) = lunghezza_dichiarata(&testo) { + if testa_corpo.1.len() >= lunghezza { + break; + } + } + } + } + let _ = invio.send(String::from_utf8_lossy(&grezzo).to_string()); + let risposta = + b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 2\r\n\r\nok"; + let _ = flusso.write_all(risposta); + } + }); + (porta, ricevi) +} + +fn separa(testo: &str) -> Option<(&str, &str)> { + let punto = testo.find("\r\n\r\n")?; + Some((&testo[..punto], &testo[punto + 4..])) +} + +fn lunghezza_dichiarata(testo: &str) -> Option { + for riga in testo.lines() { + let minuscola = riga.to_ascii_lowercase(); + if let Some(v) = minuscola.strip_prefix("content-length:") { + return v.trim().parse().ok(); + } + } + None +} + +/// Primo elemento con questo nome, in ordine di documento. +fn cerca(doc: &engine::Document, nome: &str) -> Option { + (0..doc.node_count()).find(|&i| doc.element_name(i) == Some(nome)) +} + +/// Nodi `input`/`textarea` con un `name` inviabile. +fn campi_di_testo(doc: &engine::Document) -> Vec { + (0..doc.node_count()) + .filter(|&i| matches!(doc.element_name(i), Some("input") | Some("textarea"))) + .filter(|&i| doc.attr(i, "name").is_some()) + .collect() +} + +/// Valore di un'intestazione: il nome si confronta senza distinzione di caso, +/// il valore si legge dalla riga originale (il confine è sensibile al caso). +fn campo(testo: &str, nome: &str) -> String { + for riga in testo.lines() { + if let Some(punto) = riga.find(':') { + if riga[..punto].trim().eq_ignore_ascii_case(nome) { + return riga[punto + 1..].trim().to_string(); + } + } + } + String::new() +} + +#[test] +fn multipart_dichiara_il_confine_e_lo_usa() { + let pagina = ContenutoPagina::da_html(MODULO); + let form_node = cerca(&pagina.doc, "form").expect("il modulo c'è"); + + let mut stato = FormState::default(); + let campi = campi_di_testo(&pagina.doc); + assert_eq!(campi.len(), 2, "due campi di testo"); + for (i, nodo) in campi.iter().enumerate() { + if let Some(chiave) = engine::layout::chiave_del_controllo(&pagina.doc, *nodo) { + stato.values.insert(chiave, format!("valore {}", i + 1)); + } + } + + let richiesta = prepara( + &pagina.doc, + &stato, + form_node, + Some("http://esempio.test/pagina"), + ) + .unwrap(); + assert_eq!(richiesta.metodo, "POST"); + assert_eq!(richiesta.url, "http://esempio.test/ricevi"); + + let tipo = richiesta.content_type.clone().expect("tipo dichiarato"); + let confine = tipo + .split("boundary=") + .nth(1) + .expect("il tipo dichiara il confine") + .to_string(); + assert!(tipo.starts_with("multipart/form-data; boundary=")); + + let corpo = richiesta.corpo.clone().expect("corpo presente"); + // il confine del corpo è quello dichiarato, o il server non sa dove tagliare + assert_eq!( + corpo.matches(&format!("--{}", confine)).count(), + 3, + "due parti più il terminatore" + ); + assert!(corpo.ends_with(&format!("--{}--\r\n", confine))); + assert!(corpo.contains("Content-Disposition: form-data; name=\"titolo\"")); + assert!(corpo.contains("valore 1")); + assert!(corpo.contains("valore 2")); +} + +#[test] +fn invio_multipart_arriva_leggibile_al_server() { + let pagina = ContenutoPagina::da_html(MODULO); + let form_node = cerca(&pagina.doc, "form").unwrap(); + + let mut stato = FormState::default(); + for (i, nodo) in campi_di_testo(&pagina.doc).iter().enumerate() { + if let Some(chiave) = engine::layout::chiave_del_controllo(&pagina.doc, *nodo) { + stato.values.insert(chiave, format!("riga {}", i)); + } + } + + let (porta, ricevi) = server_che_riceve(); + let base = format!("http://127.0.0.1:{}", porta); + let richiesta = prepara( + &pagina.doc, + &stato, + form_node, + Some(&format!("{}/pagina", base)), + ) + .unwrap(); + + let client = Client::new(); + let risposta = client + .post_con( + &richiesta.url, + richiesta.corpo.as_deref().unwrap_or(""), + richiesta.content_type.as_deref().unwrap(), + &Limiti::default(), + ) + .expect("la richiesta parte"); + assert_eq!(risposta.status, 200); + + let ricevuta = ricevi + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(); + let tipo = campo(&ricevuta, "content-type"); + assert!( + tipo.starts_with("multipart/form-data; boundary="), + "il server legge il tipo: {}", + tipo + ); + let confine = tipo.split("boundary=").nth(1).unwrap().trim().to_string(); + let corpo = separa(&ricevuta).expect("c'è il corpo").1; + assert_eq!( + corpo.matches(&format!("--{}", confine)).count(), + 3, + "il confine dichiarato separa davvero le parti" + ); + assert!(corpo.contains("riga 0") && corpo.contains("riga 1")); + assert_eq!( + lunghezza_dichiarata(&ricevuta), + Some(corpo.len()), + "Content-Length deve corrispondere al corpo" + ); +} + +#[test] +fn testo_semplice_non_e_urlencoded() { + let pagina = ContenutoPagina::da_html( + "
\ +
", + ); + let form_node = cerca(&pagina.doc, "form").unwrap(); + let mut stato = FormState::default(); + if let Some(nodo) = campi_di_testo(&pagina.doc).first() { + if let Some(chiave) = engine::layout::chiave_del_controllo(&pagina.doc, *nodo) { + stato + .values + .insert(chiave, "spazio e & commerciale".to_string()); + } + } + let richiesta = prepara(&pagina.doc, &stato, form_node, Some("http://e.test/p")).unwrap(); + assert_eq!(richiesta.content_type.as_deref(), Some("text/plain")); + let corpo = richiesta.corpo.unwrap(); + // in text/plain non si codifica nulla: il valore arriva com'è + assert!(corpo.contains("spazio e & commerciale")); + assert!(!corpo.contains('%')); +} + +#[test] +fn urlencoded_resta_il_predefinito() { + let pagina = ContenutoPagina::da_html( + "
", + ); + let form_node = cerca(&pagina.doc, "form").unwrap(); + let mut stato = FormState::default(); + if let Some(nodo) = campi_di_testo(&pagina.doc).first() { + if let Some(chiave) = engine::layout::chiave_del_controllo(&pagina.doc, *nodo) { + stato.values.insert(chiave, "a b".to_string()); + } + } + let richiesta = prepara(&pagina.doc, &stato, form_node, Some("http://e.test/p")).unwrap(); + assert_eq!( + richiesta.content_type.as_deref(), + Some("application/x-www-form-urlencoded") + ); + assert_eq!(richiesta.corpo.as_deref(), Some("a=a+b")); +} diff --git a/engine/tests/proxy.rs b/engine/tests/proxy.rs new file mode 100644 index 0000000..982add3 --- /dev/null +++ b/engine/tests/proxy.rs @@ -0,0 +1,125 @@ +//! Proxy HTTP (M2.6), provato sul serio: un server locale fa da proxy e il test +//! guarda la richiesta che riceve. Niente internet: l'host di destinazione è +//! inventato apposta, così se il client provasse a risolverlo il test fallirebbe. + +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::thread; + +use engine::net::{imposta_proxy, Limiti}; + +/// Server che accetta una connessione, cattura la testa della richiesta e +/// risponde con lo stato indicato. +fn proxy_che_riceve(stato: u16) -> (u16, std::sync::mpsc::Receiver) { + let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera"); + let porta = ascolto.local_addr().unwrap().port(); + let (invio, ricevi) = 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 testo = String::from_utf8_lossy(&buf[..n]).to_string(); + let testa = testo.split("\r\n\r\n").next().unwrap_or("").to_string(); + let _ = invio.send(testa); + let corpo = if stato == 200 { "ciao" } else { "" }; + let risposta = format!( + "HTTP/1.1 {} X\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}", + stato, + corpo.len(), + corpo + ); + let _ = flusso.write_all(risposta.as_bytes()); + } + }); + (porta, ricevi) +} + +#[test] +fn http_attraverso_il_proxy_usa_la_forma_assoluta() { + let (porta, ricevi) = proxy_che_riceve(200); + imposta_proxy(Some(&format!("http://127.0.0.1:{}", porta))); + + // host inesistente: se il client lo risolvesse, questa richiesta fallirebbe + let esito = engine::net::get( + "http://esempio-inventato.test/pagina?x=1", + &Limiti::default(), + ); + imposta_proxy(None); + + let risposta = esito.expect("la risposta arriva dal proxy"); + assert_eq!(risposta.status, 200); + assert_eq!(risposta.text().unwrap(), "ciao"); + + let testa = ricevi + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(); + let prima = testa.lines().next().unwrap_or(""); + assert_eq!( + prima, "GET http://esempio-inventato.test/pagina?x=1 HTTP/1.1", + "attraverso un proxy http la richiesta si manda in forma assoluta" + ); + assert!( + testa.contains("Host: esempio-inventato.test"), + "l'intestazione Host resta quella della destinazione: {}", + testa + ); +} + +#[test] +fn https_apre_il_tunnel_prima_di_parlare() { + // il finto proxy rifiuta il tunnel: il client deve dirlo, non fingere + let (porta, ricevi) = proxy_che_riceve(403); + imposta_proxy(Some(&format!("http://127.0.0.1:{}", porta))); + + let esito = engine::net::get("https://esempio-inventato.test/pagina", &Limiti::default()); + imposta_proxy(None); + + let errore = esito.expect_err("senza tunnel non c'è risposta"); + assert!( + errore.contains("tunnel") && errore.contains("403"), + "l'errore nomina il tunnel e lo stato: {}", + errore + ); + + let testa = ricevi + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(); + let prima = testa.lines().next().unwrap_or(""); + assert_eq!( + prima, "CONNECT esempio-inventato.test:443 HTTP/1.1", + "per https il proxy riceve CONNECT sull'host e la porta" + ); +} + +#[test] +fn le_credenziali_del_proxy_finiscono_nell_intestazione() { + let (porta, ricevi) = proxy_che_riceve(200); + imposta_proxy(Some(&format!("http://tizio:parola@127.0.0.1:{}", porta))); + let esito = engine::net::get("http://destinazione.test/", &Limiti::default()); + imposta_proxy(None); + esito.expect("richiesta eseguita"); + + let testa = ricevi + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(); + // "tizio:parola" in base64 + assert!( + testa.contains("Proxy-Authorization: Basic dGl6aW86cGFyb2xh"), + "le credenziali vanno codificate in base64: {}", + testa + ); +} + +#[test] +fn senza_proxy_la_destinazione_si_risolve_davvero() { + // controllo di non-regressione: senza proxy il client risolve l'host e + // fallisce, invece di mandare la richiesta a qualcuno + imposta_proxy(None); + let errore = engine::net::get("http://esempio-inventato.test/", &Limiti::default()) + .expect_err("l'host non esiste"); + assert!( + errore.contains("risoluzione") || errore.contains("connessione"), + "l'errore parla di risoluzione o connessione: {}", + errore + ); +} diff --git a/engine/tests/rete_esterna.rs b/engine/tests/rete_esterna.rs new file mode 100644 index 0000000..67a5691 --- /dev/null +++ b/engine/tests/rete_esterna.rs @@ -0,0 +1,109 @@ +//! Servizio di rete separato (M2.6), provato sul serio: il client parla con +//! `mosaic-net` in un altro processo, e i cookie restano *là*. Il test verifica +//! due cose distinte: che la richiesta arrivi davvero dal servizio, e che la +//! sessione non sia nel processo che chiama. + +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::path::PathBuf; +use std::thread; + +use engine::net::{Client, Limiti}; + +/// Server che accetta `quante` connessioni e risponde sempre `ok`, annotando le +/// intestazioni ricevute. +fn server(quante: usize) -> (u16, std::sync::mpsc::Receiver>) { + let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera"); + let porta = ascolto.local_addr().unwrap().port(); + let (invio, ricevi) = std::sync::mpsc::channel(); + thread::spawn(move || { + let mut viste = Vec::new(); + for flusso in ascolto.incoming().take(quante).flatten() { + let mut flusso = flusso; + let mut buf = [0u8; 4096]; + let n = flusso.read(&mut buf).unwrap_or(0); + viste.push(String::from_utf8_lossy(&buf[..n]).to_string()); + let _ = flusso.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nSet-Cookie: prova=1; Path=/\r\nContent-Length: 2\r\n\r\nok", + ); + } + let _ = invio.send(viste); + }); + (porta, ricevi) +} + +fn servizio() -> PathBuf { + PathBuf::from(env!("CARGO_BIN_EXE_mosaic-net")) +} + +#[test] +fn il_servizio_esegue_le_richieste_in_un_altro_processo() { + let (porta, ricevi) = server(1); + let client = Client::con_servizio_esterno(&servizio()).expect("servizio avviato"); + + let risposta = client + .get( + &format!("http://127.0.0.1:{}/pagina", porta), + &Limiti::default(), + ) + .expect("la risposta arriva dal servizio"); + assert_eq!(risposta.status, 200); + assert_eq!(risposta.text().unwrap(), "ok"); + + let viste = ricevi + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(); + assert_eq!(viste.len(), 1); + assert!( + viste[0].starts_with("GET /pagina HTTP/1.1"), + "il servizio manda una richiesta normale: {}", + viste[0] + ); +} + +#[test] +fn i_cookie_restano_nel_servizio_non_nel_chiamante() { + let (porta, ricevi) = server(2); + let client = Client::con_servizio_esterno(&servizio()).expect("servizio avviato"); + let limite = Limiti::default(); + + client + .get(&format!("http://127.0.0.1:{}/primo", porta), &limite) + .expect("prima richiesta"); + client + .get(&format!("http://127.0.0.1:{}/secondo", porta), &limite) + .expect("seconda richiesta"); + + let viste = ricevi + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(); + assert_eq!(viste.len(), 2); + // il cookie è tornato al server: è il servizio ad averlo tenuto + assert!( + viste[1].to_ascii_lowercase().contains("cookie: prova=1"), + "la seconda richiesta porta il cookie ricevuto dalla prima: {}", + viste[1] + ); + // e non è nel processo chiamante: la sessione non è nostra + assert!( + client + .cookies + .borrow() + .riga_per(&format!("http://127.0.0.1:{}", porta)) + .is_empty(), + "i cookie non devono stare nel processo dell'interfaccia" + ); +} + +#[test] +fn un_errore_di_rete_torna_come_errore_non_come_pagina_vuota() { + let client = Client::con_servizio_esterno(&servizio()).expect("servizio avviato"); + // porta chiusa di proposito + let esito = client.get("http://127.0.0.1:9/", &Limiti::default()); + let errore = esito.expect_err("la richiesta non può riuscire"); + assert!( + errore.contains("connessione") || errore.contains("rifiutata"), + "il motivo arriva dal servizio: {}", + errore + ); +} diff --git a/harbour-mosaic/include/engine.h b/harbour-mosaic/include/engine.h index 4bcd364..6c0209d 100644 --- a/harbour-mosaic/include/engine.h +++ b/harbour-mosaic/include/engine.h @@ -83,6 +83,10 @@ int engine_doc_pump(EngineDoc *doc, uint64_t now_ms); /* Prima scadenza dei timer in ms, oppure -1. */ int64_t engine_doc_next_timer(EngineDoc *doc); +/* Invio del formulario in attesa (pulsante premuto senza preventDefault): + * JSON {metodo, url, corpo, tipo}, oppure NULL. Lo esegue il guscio. */ +char *engine_doc_invio_json(EngineDoc *doc, const char *state_json); + /* Errori degli script e messaggi di console.log, una voce per riga. */ char *engine_doc_errors(EngineDoc *doc); @@ -96,8 +100,8 @@ void engine_session_free(EngineSession *sessione); * Restituisce il corpo da liberare con engine_string_free(), o NULL; *status * riceve il codice HTTP (0 se non c'è stata risposta). */ char *engine_session_fetch(EngineSession *sessione, const char *url, - const char *metodo, const char *corpo, int *status, - char **error); + const char *metodo, const char *corpo, + const char *tipo, int *status, char **error); /* Indirizzo assoluto di un riferimento rispetto al documento (NULL se non è rete). */ char *engine_risolvi_url(const char *base, const char *riferito); diff --git a/harbour-mosaic/rpm/harbour-mosaic.spec b/harbour-mosaic/rpm/harbour-mosaic.spec index 08b8491..55b571a 100644 --- a/harbour-mosaic/rpm/harbour-mosaic.spec +++ b/harbour-mosaic/rpm/harbour-mosaic.spec @@ -1,6 +1,6 @@ Name: harbour-mosaic Summary: Mosaic browser with an independent rendering engine -Version: 0.8.9 +Version: 0.8.10 Release: 1 Group: Qt/Qt License: MIT @@ -21,6 +21,13 @@ engine written from scratch (no WebKit, Blink, Gecko or Servo code). Milestone M0: HTML parsing, CSS cascade, block layout and CPU raster. %changelog +* Thu Nov 12 2026 Carlo Baratto - 0.8.10-1 +- Rete: HTTP/2 con HPACK (tabelle generate dalla RFC 7541), negoziato via ALPN +- Proxy http_proxy/https_proxy/no_proxy con tunnel CONNECT +- multipart/form-data e text/plain oltre a urlencoded: l'invio dei formulari + porta il tipo di contenuto giusto +- Il motivo di una richiesta fallita arriva al guscio e finisce nel log + * Thu Nov 12 2026 Carlo Baratto - 0.8.9-1 - Il motivo di una richiesta fallita non va piu' perso: engine_session_fetch ha un parametro d'errore, e il guscio lo scrive nel log insieme all'indirizzo diff --git a/harbour-mosaic/src/engineview.cpp b/harbour-mosaic/src/engineview.cpp index d145b0a..3ce6898 100644 --- a/harbour-mosaic/src/engineview.cpp +++ b/harbour-mosaic/src/engineview.cpp @@ -188,11 +188,70 @@ void EngineView::clicCss(qreal cssX, qreal cssY) } const int gestori = engine_doc_click(m_doc, float(cssX), float(cssY)); qDebug() << "mosaic: click js" << cssX << cssY << "gestori" << gestori; + + // pulsante di invio senza preventDefault: il formulario va mandato davvero + if (eseguiInvio()) { + return; // la risposta sostituisce la pagina e la ridisegna + } if (gestori > 0) { rerender(); } } +/// Esegue l'invio del formulario che il motore ha lasciato in attesa, se c'è. +/// Restituisce vero se la pagina è stata sostituita dalla risposta. +bool EngineView::eseguiInvio() +{ + if (!m_doc || !m_sessione) { + return false; + } + const QByteArray stato = stateJson().toUtf8(); + char *json = engine_doc_invio_json(m_doc, stato.constData()); + if (!json) { + return false; + } + const QJsonObject richiesta = QJsonDocument::fromJson(QByteArray(json)).object(); + engine_string_free(json); + if (richiesta.isEmpty()) { + return false; + } + + const QString metodo = richiesta.value(QStringLiteral("metodo")).toString(QStringLiteral("GET")); + const QString url = richiesta.value(QStringLiteral("url")).toString(); + const QString corpo = richiesta.value(QStringLiteral("corpo")).toString(); + const QString tipo = richiesta.value(QStringLiteral("tipo")).toString(); + if (url.isEmpty()) { + setError(QStringLiteral("invio senza indirizzo")); + return false; + } + qDebug() << "mosaic: invio" << metodo << url; + + int statoHttp = 0; + char *errore = nullptr; + char *testo = engine_session_fetch(m_sessione.get(), + url.toUtf8().constData(), + metodo.toUtf8().constData(), + corpo.toUtf8().constData(), + tipo.toUtf8().constData(), + &statoHttp, + &errore); + if (errore) { + setError(QStringLiteral("invio fallito — %1").arg(QString::fromUtf8(errore))); + engine_string_free(errore); + } + if (!testo) { + return false; + } + m_html = QString::fromUtf8(testo); + engine_string_free(testo); + m_url = url; + creaDocumento(); + rerender(); + emit htmlChanged(); + emit urlChanged(); + return true; +} + /// Fa avanzare i timer della pagina. Restituisce vero se qualcosa è cambiato. bool EngineView::serviFetch() { @@ -235,6 +294,7 @@ bool EngineView::serviFetch() url.constData(), metodo.toUtf8().constData(), corpo.toUtf8().constData(), + "", &stato, &messaggio_fetch); const QByteArray dati(corpo_risposta ? corpo_risposta : ""); @@ -555,8 +615,8 @@ void EngineView::loadUrl(const QString &url) int stato = 0; char *messaggio = nullptr; // con la sessione: i cookie ricevuti restano per le richieste successive - char *testo = engine_session_fetch(sessione.get(), u.c_str(), "GET", "", &stato, - &messaggio); + char *testo = engine_session_fetch(sessione.get(), u.c_str(), "GET", "", "", + &stato, &messaggio); if (testo) { html = testo; engine_string_free(testo); diff --git a/harbour-mosaic/src/engineview.h b/harbour-mosaic/src/engineview.h index a03bb1e..a3d33a1 100644 --- a/harbour-mosaic/src/engineview.h +++ b/harbour-mosaic/src/engineview.h @@ -131,6 +131,8 @@ private: void creaDocumento(); /// esegue le fetch accodate dagli script (cookie inclusi) bool serviFetch(); + /// esegue l'invio del formulario lasciato in attesa dal motore + bool eseguiInvio(); /// documento con stato (DOM + JavaScript); nullo se non ancora creato EngineDoc *m_doc = nullptr; /// sessione di rete: cookie e cache condivisi da documento, risorse e fetch.