mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Fail control startup promptly when its loopback port is occupied
This commit is contained in:
1 parent
2a952f164c
commit
ef2eed6d4f
3 files changed
+97
-42
No files matched your search
@@ -16,16 +16,12 @@ use photocraft_ui_egui::ControlRequest;
|
||||
use photocraft_ui_egui::control::REPLY_DEADLINE;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn start(port: u16, token: String, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
/// Start serving a listener already bound during startup, before a window is opened.
|
||||
pub fn start(listener: TcpListener, token: String, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let listener = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
eprintln!("photocraft: control server failed to bind 127.0.0.1:{port}: {e}");
|
||||
return rx;
|
||||
}
|
||||
};
|
||||
eprintln!("photocraft: control server listening on 127.0.0.1:{port}");
|
||||
if let Ok(address) = listener.local_addr() {
|
||||
eprintln!("photocraft: control server listening on {address}");
|
||||
}
|
||||
std::thread::spawn(move || {
|
||||
let limiter = ConnectionLimiter::new(MAX_CONNECTIONS);
|
||||
let token = Arc::new(token);
|
||||
@@ -131,6 +127,30 @@ mod tests {
|
||||
use super::*;
|
||||
use std::io::BufRead;
|
||||
|
||||
#[test]
|
||||
fn a_prebound_listener_authenticates_and_dispatches_requests() {
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let requests = start(listener, TOKEN.into(), egui::Context::default());
|
||||
let mut stream = TcpStream::connect(address).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut replies = BufReader::new(stream.try_clone().unwrap());
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap();
|
||||
let mut line = String::new();
|
||||
replies.read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"]["authenticated"], true);
|
||||
writeln!(stream, "{}", json!({"id": 2, "method": "test.bound"})).unwrap();
|
||||
let request = requests.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert_eq!(request.method, "test.bound");
|
||||
request.reply.send(json!({"ok": true, "result": "served"})).unwrap();
|
||||
line.clear();
|
||||
replies.read_line(&mut line).unwrap();
|
||||
let reply: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(reply["id"], 2);
|
||||
assert_eq!(reply["result"], "served");
|
||||
}
|
||||
|
||||
/// #4965: a connection that keeps sending without authenticating is closed at the deadline
|
||||
/// (releasing its connection permit), and nothing it sent is dispatched.
|
||||
#[test]
|
||||
|
||||
+39
-29
@@ -284,6 +284,43 @@ fn main() -> eframe::Result {
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
// Complete control setup before display/GPU initialization: a failed grant must exit 2,
|
||||
// including an occupied port (#6428), rather than open a window without a control server.
|
||||
let control = if let Some(port) = control_port {
|
||||
let listener = match std::net::TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(listener) => listener,
|
||||
Err(error) => {
|
||||
eprintln!("photocraft: control server failed to bind 127.0.0.1:{port}: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let (supplied, token_file) = photocraft_automation::security::token_inputs(control_token, control_token_file);
|
||||
let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) {
|
||||
Ok(token) => token,
|
||||
Err(e) => {
|
||||
eprintln!("photocraft: cannot configure control authentication: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
if let Some(path) = token_file {
|
||||
eprintln!("photocraft: control token file: {}", path.display());
|
||||
} else if supplied.is_none() {
|
||||
eprintln!("photocraft: control token: {token}");
|
||||
} else {
|
||||
eprintln!("photocraft: using supplied control token");
|
||||
}
|
||||
let workspace = match photocraft_automation::AuthorizedWorkspace::new(automation_read_root.as_deref(), automation_write_root.as_deref()) {
|
||||
Ok(workspace) => workspace,
|
||||
Err(error) => {
|
||||
eprintln!("photocraft: cannot configure automation workspace: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
Some((listener, token, workspace))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// The log file lives under the settings directory; opened after the arguments, so `--version`
|
||||
// and usage errors leave no file behind. Records logged until now are written to it first.
|
||||
if let (Some(logger), Some(dir)) = (logger, services::config_dir()) {
|
||||
@@ -365,33 +402,6 @@ fn main() -> eframe::Result {
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let control = if let Some(port) = control_port {
|
||||
let (supplied, token_file) = photocraft_automation::security::token_inputs(control_token, control_token_file);
|
||||
let token = match photocraft_automation::security::server_token(supplied.as_deref(), token_file.as_deref()) {
|
||||
Ok(token) => token,
|
||||
Err(e) => {
|
||||
eprintln!("photocraft: cannot configure control authentication: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
if let Some(path) = token_file {
|
||||
eprintln!("photocraft: control token file: {}", path.display());
|
||||
} else if supplied.is_none() {
|
||||
eprintln!("photocraft: control token: {token}");
|
||||
} else {
|
||||
eprintln!("photocraft: using supplied control token");
|
||||
}
|
||||
let workspace = match photocraft_automation::AuthorizedWorkspace::new(automation_read_root.as_deref(), automation_write_root.as_deref()) {
|
||||
Ok(workspace) => workspace,
|
||||
Err(error) => {
|
||||
eprintln!("photocraft: cannot configure automation workspace: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
Some((port, token, workspace))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Finder / Dock / Open With deliver files as Apple events, not arguments; catch the one that
|
||||
// launched us as well as later ones. Lives until the event loop returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -582,8 +592,8 @@ fn main() -> eframe::Result {
|
||||
log::warn!("couldn't remember GPU backend {}: {e}", b.name());
|
||||
}
|
||||
});
|
||||
if let Some((port, token, _)) = control {
|
||||
let rx = control_server::start(port, token, cc.egui_ctx.clone());
|
||||
if let Some((listener, token, _)) = control {
|
||||
let rx = control_server::start(listener, token, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
//! status 0 believes the control server is running when it is not.
|
||||
//!
|
||||
//! These tests run the real binary as a subprocess and assert the exit code,
|
||||
//! covering both failure paths in `main.rs`: control authentication and the
|
||||
//! automation workspace.
|
||||
//! covering control authentication, the automation workspace and listener binding.
|
||||
|
||||
/// A syntactically valid 64-hex-char token, so the workspace test reaches the
|
||||
/// workspace check instead of failing on token validation first.
|
||||
@@ -17,7 +16,7 @@ fn run_photocraft(args: &[&str]) -> (std::process::ExitStatus, String) {
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-control-exit-{}-{n}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft"))
|
||||
let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft"))
|
||||
.args(args)
|
||||
.env("PHOTOCRAFT_CONFIG_DIR", &dir)
|
||||
// Isolate from the host environment so the test is reproducible.
|
||||
@@ -29,12 +28,38 @@ fn run_photocraft(args: &[&str]) -> (std::process::ExitStatus, String) {
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.output()
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.expect("failed to run photocraft binary");
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
let timed_out = loop {
|
||||
if child.try_wait().unwrap().is_some() {
|
||||
break false;
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
break true;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
};
|
||||
let output = child.wait_with_output().unwrap();
|
||||
let gpu_started = dir.join("gpu-starting.json").exists();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(!timed_out, "PhotoCraft did not exit: {}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(!gpu_started, "control setup errors must exit before GPU startup");
|
||||
(output.status, String::from_utf8_lossy(&output.stderr).into_owned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_occupied_control_port_exits_with_status_2() {
|
||||
let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = held.local_addr().unwrap().port().to_string();
|
||||
let (status, stderr) = run_photocraft(&["--control", &port, "--control-token", VALID_TOKEN]);
|
||||
assert_eq!(status.code(), Some(2), "occupied control port must exit 2, stderr: {stderr}");
|
||||
assert!(stderr.contains(&format!("failed to bind 127.0.0.1:{port}")), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_control_token_exits_with_status_2() {
|
||||
// `validate_token` rejects a token that is not exactly 64 hex characters.
|
||||
|
||||
Reference in new issue
Block a user