diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rs index ed78ef5f5..4f1e8b70b 100644 --- a/apps/solidcraft/src/control_server.rs +++ b/apps/solidcraft/src/control_server.rs @@ -24,9 +24,9 @@ const MAX_BAD_LINES: usize = 8; const EVENT_GAP: Duration = Duration::from_millis(100); static OPEN: AtomicUsize = AtomicUsize::new(0); -/// The token files this launch wrote (its control port, the agent chat's endpoint), removed -/// when the app ends. -static TOKEN_FILES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// The token files this launch wrote (its control port, the agent chat's endpoint) and the +/// token in each, removed when the app ends unless another launch has written the file since. +static TOKEN_FILES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); /// A new random token: 32 bytes from the operating system, as hex. fn new_token() -> Option { @@ -35,20 +35,21 @@ fn new_token() -> Option { Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) } -/// Remove this launch's token file (at exit). +/// Remove this launch's token files and discovery file (at exit), leaving any that another +/// launch has written since (#8794). pub fn remove_token_file() { if let Ok(files) = TOKEN_FILES.lock() { - for p in files.iter() { - control_auth::remove_token_file(p); + for (path, token) in files.iter() { + control_auth::remove_token_file(path, token); } } - if let Some(port) = APP_PORT.lock().ok().and_then(|p| *p) { - control_auth::remove_current_port(port); + if let Some((port, token)) = APP_PORT.lock().ok().and_then(|p| p.clone()) { + control_auth::remove_current_port(port, &token); } } -/// The port the app's own channel listens on, for removing the discovery file at exit. -static APP_PORT: std::sync::Mutex> = std::sync::Mutex::new(None); +/// The port the app's own channel listens on and its token, for removing the discovery file at exit. +static APP_PORT: std::sync::Mutex> = std::sync::Mutex::new(None); pub fn start(listen_on: control_auth::Listen, ctx: egui::Context) -> Receiver { let (tx, rx) = channel::(); @@ -61,7 +62,7 @@ pub fn start(listen_on: control_auth::Listen, ctx: egui::Context) -> Receiver { - if let Some(port) = listen_on_listener(l, token, tx, ctx, false) { + if let Some(port) = listen_on_listener(l, token.clone(), tx, ctx, false) { if matches!(listen_on, control_auth::Listen::Default) { eprintln!("solidcraft: control channel on the default port 127.0.0.1:{port} (Preferences > Assistant turns it off)"); } @@ -69,7 +70,7 @@ pub fn start(listen_on: control_auth::Listen, ctx: egui::Context) -> Receiver { if let Ok(mut p) = APP_PORT.lock() { - *p = Some(port); + *p = Some((port, token)); } } Err(e) => eprintln!("solidcraft: could not write the control discovery file ({e})"), @@ -112,7 +113,7 @@ fn listen_on_listener(listener: TcpListener, token: String, tx: Sender { eprintln!("solidcraft: control server listening on 127.0.0.1:{port} (token in {})", path.display()); if let Ok(mut files) = TOKEN_FILES.lock() { - files.push(path); + files.push((path, token.clone())); } } Err(e) => eprintln!( diff --git a/crates/engine/src/control_auth.rs b/crates/engine/src/control_auth.rs index 43b624b2a..c93541923 100644 --- a/crates/engine/src/control_auth.rs +++ b/crates/engine/src/control_auth.rs @@ -91,15 +91,28 @@ fn parse_port(text: &str) -> Option { text.trim().parse::().ok().filter(|p| *p != 0) } -/// Remove the discovery file at exit, unless a later app has taken it over (it names another port). -pub fn remove_current_port(port: u16) { - if read_current_port() == Some(port) - && let Some(path) = current_port_path() - { - let _ = std::fs::remove_file(path); +/// Remove the discovery file (and its process file) at exit, unless a later app has taken it +/// over: it names another port, or another launch now holds this port's token file. Under +/// Flatpak every instance has its own loopback, so two windows can listen on the same port +/// number and write the same file names; the one closing first must leave the other's (#8794). +/// Run it after [`remove_token_file`], which takes this launch's own token file away first. +pub fn remove_current_port(port: u16, token: &str) { + if let (Some(current), Some(file)) = (current_port_path(), token_path(port)) { + remove_discovery(¤t, &file, port, token); } } +/// [`remove_current_port`] on given files: `current` is the discovery file, `file` the token file +/// of `port`. +fn remove_discovery(current: &Path, file: &Path, port: u16, token: &str) { + let named = std::fs::read_to_string(current).ok().filter(|t| t.len() <= 64).and_then(|t| parse_port(&t)); + if named != Some(port) || held_by_another(file, token) { + return; + } + let _ = std::fs::remove_file(current); + let _ = std::fs::remove_file(pid_path(current)); +} + /// A token set on purpose with `SOLIDCRAFT_CONTROL_TOKEN` (test harnesses, sandboxed packages /// whose data folder the client can't see), if it is long enough. pub fn env_token() -> Option { @@ -289,10 +302,28 @@ pub fn write_token_file(path: &Path, token: &str) -> Result<()> { Ok(()) } -/// Remove a token file this launch wrote, and its process file. -pub fn remove_token_file(path: &Path) { - let _ = std::fs::remove_file(path); - let _ = std::fs::remove_file(pid_path(path)); +/// Remove a token file this launch wrote, and its process file, while it still holds `token`. +/// Another launch may have written the same file since (a second window on the same port, +/// #8794); its file stays. The process id can't tell the two apart, as every Flatpak instance +/// has the same one, but each launch's token is its own. +pub fn remove_token_file(path: &Path, token: &str) { + if read_token(path).is_some_and(|held| tokens_match(&held, token.trim())) { + let _ = std::fs::remove_file(path); + let _ = std::fs::remove_file(pid_path(path)); + } +} + +/// The token a token file holds, trimmed; `None` when there is no readable token file. +fn read_token(path: &Path) -> Option { + let mut text = String::new(); + std::fs::File::open(path).ok()?.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).ok()?; + let token = text.trim(); + (text.len() as u64 <= MAX_TOKEN_FILE && !token.is_empty()).then(|| token.to_string()) +} + +/// Whether the token file at `path` holds a token other than `token`: another launch's. +fn held_by_another(path: &Path, token: &str) -> bool { + read_token(path).is_some_and(|held| !tokens_match(&held, token.trim())) } /// How long `icacls` may take (#6145). It finishes at once; on some computers the new process @@ -341,12 +372,12 @@ fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Re } } -/// Removes the token file when the app ends. -pub struct TokenFile(pub PathBuf); +/// Removes the token file (path, token) when the app ends, while it still holds that token. +pub struct TokenFile(pub PathBuf, pub String); impl Drop for TokenFile { fn drop(&mut self) { - remove_token_file(&self.0); + remove_token_file(&self.0, &self.1); } } @@ -490,8 +521,43 @@ mod tests { assert_eq!(std::fs::read_to_string(&path).unwrap().trim(), "0123456789abcdef0123456789abcdef"); let writer = read_token_file(&path).unwrap().file.unwrap().writer; assert_eq!(writer.map(|(pid, _)| pid), Some(std::process::id())); - drop(TokenFile(path.clone())); + drop(TokenFile(path.clone(), "0123456789abcdef0123456789abcdef".into())); assert!(!path.exists() && !pid_path(&path).exists()); let _ = std::fs::remove_dir_all(&dir); } + + /// #8794: under Flatpak two windows can listen on the same port number (each has its own + /// loopback) and write the same files. The one closing first leaves the other's token, process + /// and discovery files; the last one takes them all away, `current.pid` too. + #[test] + fn a_closing_launch_leaves_another_launchs_files() { + let dir = std::env::temp_dir().join(format!("solidcraft-control-two-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (file, current) = (dir.join("27878.token"), dir.join("current.port")); + let (first, second) = ("a".repeat(64), "b".repeat(64)); + // The first window, then the second on the same port, each writing both files. + for token in [&first, &second] { + write_token_file(&file, token).unwrap(); + write_token_file(¤t, "27878").unwrap(); + } + // The first closes: the second's files stay. + remove_token_file(&file, &first); + remove_discovery(¤t, &file, 27878, &first); + assert_eq!(read_token(&file).as_deref(), Some(second.as_str())); + assert!(pid_path(&file).exists() && current.exists() && pid_path(¤t).exists()); + // Another port named in the discovery file is another app's too. + remove_discovery(¤t, &file, 27879, &second); + assert!(current.exists()); + // The second closes: nothing of either is left. + remove_token_file(&file, &format!(" {second}\n")); + remove_discovery(¤t, &file, 27878, &second); + assert!(!file.exists() && !pid_path(&file).exists() && !current.exists() && !pid_path(¤t).exists()); + // With no token file left (removed by hand, or never written), the discovery file of the + // port still goes; a missing file is no error. + write_token_file(¤t, "27878").unwrap(); + remove_token_file(&file, &second); + remove_discovery(¤t, &file, 27878, &second); + assert!(!current.exists()); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dc868e5af..bd2a9a07e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -26,7 +26,9 @@ channel changes neither for a normal launch. Each app that opens its channel writes the port to a discovery file beside the token files, `control/current.port` (same folders and permissions as below), and removes it at exit if no later -app has replaced it. It holds only the port, never the token. `solidcraft-cli mcp` with no +app has replaced it: it names another port, or another app now holds that port's token file (two +Flatpak windows, each with its own loopback, can listen on the same port number). It holds only +the port, never the token. `solidcraft-cli mcp` with no arguments reads it, checks that something listens there and bridges to that app; with no app running, or with `--headless`, it runs a session of its own. `--connect HOST:PORT` and the other arguments still decide first. With several windows open, the most recently started one is @@ -52,7 +54,8 @@ launch and writes it, as one line of hex, to a file only the user can read: On Unix the folder is `0700` and the file `0600`; on Windows the file's inherited permissions are replaced by a single entry for the user. `SOLIDCRAFT_CONTROL_DIR` moves the folder. The file is -removed when the app exits, and the next launch writes a new token. The token file's path is +removed when the app exits, unless another launch has written its own token there since, and the +next launch writes a new token. The token file's path is printed to stderr at start-up. Beside it, `.pid` holds the app's process id (and, on Linux, its start time).