Reply to non-UTF8 lines on the control channel (#118)

Clients cannot tell a refused non-UTF8 request from a dropped connection, unlike malformed JSON which gets an explicit error reply.

Make the TCP control servers reply with an error for non-UTF8 lines, closing before auth and continuing after auth like bad JSON.

Test: non_utf8_line_before_auth_gets_refusal_reply failed before the change and passes after.

Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-06 10:10:38 +01:00
1 parent d05d2bf0a9
commit a0180da9b6
2 files changed
+34 -6

No files matched your search

+21 -1
View File
@@ -111,7 +111,15 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, 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::<Value>(&reply).unwrap()["ok"], false);
}
#[test]
fn connections_are_limited_and_idle_ones_time_out() {
let addr = server();
+13 -5
View File
@@ -158,11 +158,19 @@ fn serve_connection(h: &Mutex<Headless>, 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))?;