//! 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() }