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,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!(
|
||||
"<!doctype html><html><body><form method=\"post\" action=\"/ricevi\" enctype=\"multipart/form-data\">",
|
||||
"<input name=\"titolo\"><input name=\"nota\">",
|
||||
"<button type=\"submit\">Invia</button></form></body></html>"
|
||||
);
|
||||
|
||||
/// Server che accetta una richiesta, ne cattura il testo completo e risponde `ok`.
|
||||
fn server_che_riceve() -> (u16, std::sync::mpsc::Receiver<String>) {
|
||||
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<usize> {
|
||||
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<usize> {
|
||||
(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<usize> {
|
||||
(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(
|
||||
"<html><body><form method=\"post\" action=\"/x\" enctype=\"text/plain\">\
|
||||
<input name=\"a\"></form></body></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(
|
||||
"<html><body><form method=\"post\" action=\"/x\"><input name=\"a\"></form></body></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"));
|
||||
}
|
||||
Reference in new issue
Block a user