mirror of
https://github.com/zhom/donutbrowser.git
synced 2026-12-05 10:03:44 +01:00
419 lines
13 KiB
Rust
419 lines
13 KiB
Rust
/// True if a process command line refers to `profile_path` as a real browser
|
|
/// profile/data-dir argument. Only the `--user-data-dir=<path>` /
|
|
/// `-profile=<path>` flag form counts, because the results feed a SIGKILL loop:
|
|
/// a substring match, or the path accepted as a standalone argv token, also
|
|
/// caught unrelated processes that legitimately name the directory (`du -sh
|
|
/// <profile>`, `tar czf backup.tgz <profile>`, an editor, a sibling profile
|
|
/// whose path has this one as a prefix). `wayfern_manager.rs` only ever emits
|
|
/// the flag form, so nothing Donut launches is missed.
|
|
///
|
|
/// Only the macOS and Linux process-kill paths use this; Windows has no
|
|
/// profile-path sweep, so gate it to avoid a dead-code error there.
|
|
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
|
fn cmd_matches_profile_path(cmd: &[std::ffi::OsString], profile_path: &str) -> bool {
|
|
cmd.iter().filter_map(|a| a.to_str()).any(|arg| {
|
|
arg
|
|
.strip_prefix("--user-data-dir=")
|
|
.or_else(|| arg.strip_prefix("-profile="))
|
|
.is_some_and(|val| val == profile_path)
|
|
})
|
|
}
|
|
|
|
/// The profile sweep only ever wants browser processes. Every other sweep in
|
|
/// the app (`wayfern_manager`, `profile::manager`) already filters on the
|
|
/// executable name; without it a stray match here becomes a SIGKILL on an
|
|
/// unrelated process.
|
|
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
|
fn is_browser_process_name(name: &std::ffi::OsStr) -> bool {
|
|
let exe_name = name.to_string_lossy().to_lowercase();
|
|
exe_name.contains("wayfern") || exe_name.contains("chromium") || exe_name.contains("chrome")
|
|
}
|
|
|
|
/// Process lookups for the kill paths: one refresh of only what is read, instead
|
|
/// of a full system scan (CPU, disks, networks, every process field) per call.
|
|
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
|
mod unix_processes {
|
|
use std::collections::HashMap;
|
|
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
|
|
|
|
/// Every process with its command line. Parents come with any refresh.
|
|
pub fn snapshot() -> System {
|
|
let mut system = crate::proxy_storage::process_table(sysinfo::RefreshKind::nothing());
|
|
system.refresh_processes_specifics(
|
|
ProcessesToUpdate::All,
|
|
true,
|
|
ProcessRefreshKind::nothing()
|
|
.with_cmd(UpdateKind::OnlyIfNotSet)
|
|
.without_tasks(),
|
|
);
|
|
system
|
|
}
|
|
|
|
/// Browser processes started on `profile_path`.
|
|
pub fn on_profile_path(system: &System, profile_path: &str) -> Vec<u32> {
|
|
system
|
|
.processes()
|
|
.iter()
|
|
.filter(|(_, process)| {
|
|
!process.cmd().is_empty()
|
|
&& super::is_browser_process_name(process.name())
|
|
&& super::cmd_matches_profile_path(process.cmd(), profile_path)
|
|
})
|
|
.map(|(pid, _)| pid.as_u32())
|
|
.collect()
|
|
}
|
|
|
|
/// Every descendant of `parent_pid`.
|
|
pub fn descendants(system: &System, parent_pid: u32) -> Vec<u32> {
|
|
let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
|
|
for (pid, process) in system.processes() {
|
|
if let Some(parent) = process.parent() {
|
|
children
|
|
.entry(parent.as_u32())
|
|
.or_default()
|
|
.push(pid.as_u32());
|
|
}
|
|
}
|
|
let mut descendants = Vec::new();
|
|
let mut to_check = vec![parent_pid];
|
|
let mut checked = std::collections::HashSet::new();
|
|
while let Some(current) = to_check.pop() {
|
|
if !checked.insert(current) {
|
|
continue;
|
|
}
|
|
for &child in children
|
|
.get(¤t)
|
|
.map(Vec::as_slice)
|
|
.unwrap_or_default()
|
|
{
|
|
if !checked.contains(&child) {
|
|
descendants.push(child);
|
|
to_check.push(child);
|
|
}
|
|
}
|
|
}
|
|
descendants
|
|
}
|
|
|
|
/// Which of `pids` are still alive, from one refresh of those processes.
|
|
pub fn still_alive(pids: &[u32]) -> Vec<u32> {
|
|
let wanted: Vec<Pid> = pids.iter().map(|pid| Pid::from_u32(*pid)).collect();
|
|
let mut system = crate::proxy_storage::process_table(sysinfo::RefreshKind::nothing());
|
|
system.refresh_processes_specifics(
|
|
ProcessesToUpdate::Some(&wanted),
|
|
true,
|
|
ProcessRefreshKind::nothing(),
|
|
);
|
|
pids
|
|
.iter()
|
|
.copied()
|
|
.filter(|pid| {
|
|
system
|
|
.process(Pid::from_u32(*pid))
|
|
.is_some_and(crate::proxy_storage::snapshot_process_is_alive)
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
pub fn sigkill(pid: u32) {
|
|
use nix::sys::signal::{kill, Signal};
|
|
let _ = kill(nix::unistd::Pid::from_raw(pid as i32), Signal::SIGKILL);
|
|
}
|
|
|
|
/// `pkill` without blocking the async runtime.
|
|
pub async fn pkill(args: &[&str]) {
|
|
let _ = tokio::process::Command::new("pkill")
|
|
.args(args)
|
|
.stdin(std::process::Stdio::null())
|
|
.stdout(std::process::Stdio::null())
|
|
.stderr(std::process::Stdio::null())
|
|
.status()
|
|
.await;
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn this_process_is_alive_and_a_child_is_its_descendant() {
|
|
let me = std::process::id();
|
|
assert_eq!(still_alive(&[me]), vec![me]);
|
|
|
|
let mut child = std::process::Command::new("sleep")
|
|
.arg("30")
|
|
.spawn()
|
|
.unwrap();
|
|
let system = snapshot();
|
|
assert!(descendants(&system, me).contains(&child.id()));
|
|
sigkill(child.id());
|
|
let _ = child.wait();
|
|
assert!(still_alive(&[child.id()]).is_empty());
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(all(test, any(target_os = "macos", target_os = "linux")))]
|
|
mod profile_path_match_tests {
|
|
use super::{cmd_matches_profile_path, is_browser_process_name};
|
|
use std::ffi::{OsStr, OsString};
|
|
|
|
fn cmd(args: &[&str]) -> Vec<OsString> {
|
|
args.iter().map(OsString::from).collect()
|
|
}
|
|
|
|
#[test]
|
|
fn bare_path_argument_does_not_match() {
|
|
let profile = "/tmp/donut/profiles/work";
|
|
assert!(!cmd_matches_profile_path(
|
|
&cmd(&["du", "-sh", profile]),
|
|
profile
|
|
));
|
|
assert!(!cmd_matches_profile_path(
|
|
&cmd(&["tar", "czf", "backup.tgz", profile]),
|
|
profile
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn user_data_dir_flag_matches() {
|
|
let profile = "/tmp/donut/profiles/work";
|
|
assert!(cmd_matches_profile_path(
|
|
&cmd(&["wayfern", &format!("--user-data-dir={profile}")]),
|
|
profile
|
|
));
|
|
assert!(cmd_matches_profile_path(
|
|
&cmd(&["wayfern", &format!("-profile={profile}")]),
|
|
profile
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn a_sibling_profile_prefix_does_not_match() {
|
|
let profile = "/tmp/donut/profiles/work";
|
|
assert!(!cmd_matches_profile_path(
|
|
&cmd(&["wayfern", "--user-data-dir=/tmp/donut/profiles/work-2"]),
|
|
profile
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn only_browser_executables_are_swept() {
|
|
assert!(is_browser_process_name(OsStr::new("Wayfern Helper")));
|
|
assert!(is_browser_process_name(OsStr::new("chromium")));
|
|
assert!(!is_browser_process_name(OsStr::new("du")));
|
|
assert!(!is_browser_process_name(OsStr::new("rsync")));
|
|
}
|
|
}
|
|
|
|
// Platform-specific modules
|
|
#[cfg(target_os = "macos")]
|
|
#[allow(dead_code)]
|
|
pub mod macos {
|
|
pub async fn kill_browser_process_impl(
|
|
pid: u32,
|
|
profile_data_path: Option<&str>,
|
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
|
use super::unix_processes::{
|
|
descendants, on_profile_path, pkill, sigkill, snapshot, still_alive,
|
|
};
|
|
|
|
let mut pids_to_kill = vec![pid];
|
|
|
|
let profile_path = profile_data_path.map(str::to_string);
|
|
let (descendant_pids, profile_pids) = tokio::task::spawn_blocking(move || {
|
|
let system = snapshot();
|
|
(
|
|
descendants(&system, pid),
|
|
profile_path
|
|
.map(|path| on_profile_path(&system, &path))
|
|
.unwrap_or_default(),
|
|
)
|
|
})
|
|
.await
|
|
.unwrap_or_default();
|
|
pids_to_kill.extend(descendant_pids);
|
|
for p in profile_pids {
|
|
if !pids_to_kill.contains(&p) {
|
|
log::debug!("Found another process on the profile path pid={p}");
|
|
pids_to_kill.push(p);
|
|
}
|
|
}
|
|
|
|
log::debug!("Force killing browser processes pid={pid} pids={pids_to_kill:?}");
|
|
|
|
for &p in &pids_to_kill {
|
|
sigkill(p);
|
|
}
|
|
|
|
let pid_str = pid.to_string();
|
|
pkill(&["-KILL", "-P", &pid_str]).await;
|
|
pkill(&["-KILL", "-g", &pid_str]).await;
|
|
|
|
for p in still_alive(&pids_to_kill) {
|
|
log::debug!("Process still running, killing again pid={p}");
|
|
sigkill(p);
|
|
}
|
|
|
|
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
|
|
|
|
let still_running = still_alive(&pids_to_kill);
|
|
if !still_running.is_empty() {
|
|
log::debug!("Processes still running, final kill pids={still_running:?}");
|
|
|
|
for &p in &still_running {
|
|
sigkill(p);
|
|
}
|
|
|
|
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
|
|
|
|
let final_still_running = still_alive(&pids_to_kill);
|
|
if !final_still_running.is_empty() {
|
|
return Err(
|
|
format!(
|
|
"Failed to terminate browser processes {:?} - still running",
|
|
final_still_running
|
|
)
|
|
.into(),
|
|
);
|
|
}
|
|
}
|
|
|
|
log::debug!(
|
|
"Browser processes killed pid={pid} count={}",
|
|
pids_to_kill.len()
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "windows")]
|
|
#[allow(dead_code)]
|
|
pub mod windows {
|
|
pub async fn kill_browser_process_impl(
|
|
pid: u32,
|
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
|
// First try using sysinfo (cross-platform approach), refreshing only this
|
|
// process.
|
|
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate};
|
|
let sysinfo_pid = Pid::from_u32(pid);
|
|
let mut system = crate::proxy_storage::process_table(sysinfo::RefreshKind::nothing());
|
|
system.refresh_processes_specifics(
|
|
ProcessesToUpdate::Some(&[sysinfo_pid]),
|
|
true,
|
|
ProcessRefreshKind::nothing(),
|
|
);
|
|
if let Some(process) = system.process(sysinfo_pid) {
|
|
if process.kill() {
|
|
log::debug!("Browser process killed pid={pid}");
|
|
return Ok(());
|
|
}
|
|
}
|
|
|
|
// Fallback: taskkill, awaited without blocking the async runtime.
|
|
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
|
let output = tokio::process::Command::new("taskkill")
|
|
.args(["/F", "/PID", &pid.to_string()])
|
|
.creation_flags(CREATE_NO_WINDOW)
|
|
.output()
|
|
.await;
|
|
|
|
match output {
|
|
Ok(result) => {
|
|
if result.status.success() {
|
|
log::debug!("Browser process killed with taskkill pid={pid}");
|
|
Ok(())
|
|
} else {
|
|
Err(
|
|
format!(
|
|
"Failed to kill process {} with taskkill: {}",
|
|
pid,
|
|
String::from_utf8_lossy(&result.stderr)
|
|
)
|
|
.into(),
|
|
)
|
|
}
|
|
}
|
|
Err(e) => Err(format!("Failed to execute taskkill for process {}: {}", pid, e).into()),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
#[allow(dead_code)]
|
|
pub mod linux {
|
|
pub async fn kill_browser_process_impl(
|
|
pid: u32,
|
|
profile_data_path: Option<&str>,
|
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
|
use super::unix_processes::{
|
|
descendants, on_profile_path, pkill, sigkill, snapshot, still_alive,
|
|
};
|
|
|
|
let mut pids_to_kill = vec![pid];
|
|
|
|
// Find all descendant processes, and other processes on the same profile
|
|
// path, from one scan off the async runtime.
|
|
let profile_path = profile_data_path.map(str::to_string);
|
|
let (descendant_pids, profile_pids) = tokio::task::spawn_blocking(move || {
|
|
let system = snapshot();
|
|
(
|
|
descendants(&system, pid),
|
|
profile_path
|
|
.map(|path| on_profile_path(&system, &path))
|
|
.unwrap_or_default(),
|
|
)
|
|
})
|
|
.await
|
|
.unwrap_or_default();
|
|
pids_to_kill.extend(descendant_pids);
|
|
for p in profile_pids {
|
|
if !pids_to_kill.contains(&p) {
|
|
log::debug!("Found another process on the profile path pid={p}");
|
|
pids_to_kill.push(p);
|
|
}
|
|
}
|
|
|
|
log::debug!("Force killing browser processes pid={pid} pids={pids_to_kill:?}");
|
|
|
|
// Send SIGKILL to all identified processes
|
|
for &p in &pids_to_kill {
|
|
sigkill(p);
|
|
}
|
|
|
|
// Also kill by parent PID
|
|
pkill(&["-KILL", "-P", &pid.to_string()]).await;
|
|
|
|
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
|
|
|
|
// Verify processes are dead
|
|
let still_running = still_alive(&pids_to_kill);
|
|
if !still_running.is_empty() {
|
|
log::debug!("Processes still running, final kill pids={still_running:?}");
|
|
|
|
for &p in &still_running {
|
|
sigkill(p);
|
|
}
|
|
|
|
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
|
|
|
|
let final_still_running = still_alive(&pids_to_kill);
|
|
if !final_still_running.is_empty() {
|
|
return Err(
|
|
format!(
|
|
"Failed to terminate browser processes {:?} - still running",
|
|
final_still_running
|
|
)
|
|
.into(),
|
|
);
|
|
}
|
|
}
|
|
|
|
log::debug!(
|
|
"Browser processes killed pid={pid} count={}",
|
|
pids_to_kill.len()
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|