diff --git a/apps/materialcraft/src/control_server.rs b/apps/materialcraft/src/control_server.rs index 5e89276..7e1c94f 100644 --- a/apps/materialcraft/src/control_server.rs +++ b/apps/materialcraft/src/control_server.rs @@ -111,7 +111,15 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender, ctx: &egui reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"})); return; } - Ok(LineRead::Eof) | Err(_) => return, + Ok(LineRead::Eof) => return, + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { + let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": "request is not UTF-8"})); + if !sent || deadline.is_some() { + return; + } + continue; + } + Err(_) => return, } if line.trim().is_empty() { continue; @@ -230,6 +238,18 @@ mod tests { assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection"); } + #[test] + fn non_utf8_line_before_auth_gets_refusal_reply() { + let addr = server(); + let (mut w, mut r) = connect(addr); + w.write_all(b"\xff\n").unwrap(); + w.flush().unwrap(); + let mut reply = String::new(); + let n = r.read_line(&mut reply).unwrap(); + assert!(n > 0, "a non-UTF8 first line gets a refusal reply, not a silent close"); + assert_eq!(serde_json::from_str::(&reply).unwrap()["ok"], false); + } + #[test] fn connections_are_limited_and_idle_ones_time_out() { let addr = server(); diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index dae2611..427d7a7 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -158,11 +158,19 @@ fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &st let mut authed = false; let mut deadline = Some(AuthDeadline::start(&w, AUTH_TIMEOUT)?); loop { - match read_bounded_line(&mut r, &mut line)? { - LineRead::Eof => return Ok(()), - LineRead::TooLong => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})), - LineRead::Line if line.trim().is_empty() => continue, - LineRead::Line => {} + match read_bounded_line(&mut r, &mut line) { + Ok(LineRead::Eof) => return Ok(()), + Ok(LineRead::TooLong) => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})), + Ok(LineRead::Line) if line.trim().is_empty() => continue, + Ok(LineRead::Line) => {} + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { + write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request is not UTF-8"}))?; + if !authed { + return Ok(()); + } + continue; + } + Err(e) => return Err(e), } if authed { write_reply(&mut w, &respond(h, &line))?;