| 1 | use std::time::{Duration, Instant}; |
| 2 | |
| 3 | use crate::config::Platform; |
| 4 | use crate::error::BrowserError; |
| 5 | |
| 6 | pub(crate) fn parse_ss_pid(output: &str) -> Option<u32> { |
| 7 | let after = output.split("pid=").nth(1)?; |
| 8 | after |
| 9 | .chars() |
| 10 | .take_while(char::is_ascii_digit) |
| 11 | .collect::<String>() |
| 12 | .parse() |
| 13 | .ok() |
| 14 | } |
| 15 | |
| 16 | pub(crate) fn parse_netstat_pid(output: &str, port: u16) -> Option<u32> { |
| 17 | let suffix = format!(":{port}"); |
| 18 | output.lines().find_map(|line| { |
| 19 | let columns: Vec<&str> = line.split_whitespace().collect(); |
| 20 | let listening = columns |
| 21 | .iter() |
| 22 | .any(|column| column.eq_ignore_ascii_case("LISTENING")); |
| 23 | let local = columns.get(1)?; |
| 24 | if !listening || !local.ends_with(&suffix) { |
| 25 | return None; |
| 26 | } |
| 27 | columns.last()?.parse().ok() |
| 28 | }) |
| 29 | } |
| 30 | |
| 31 | /// First LISTEN row's PID column from `lsof -nP -iTCP:<port> -sTCP:LISTEN`. |
| 32 | pub(crate) fn parse_lsof_pid(output: &str) -> Option<u32> { |
| 33 | output.lines().skip(1).find_map(|line| { |
| 34 | let columns: Vec<&str> = line.split_whitespace().collect(); |
| 35 | columns.get(1)?.parse().ok() |
| 36 | }) |
| 37 | } |
| 38 | |
| 39 | fn run(program: &str, arguments: &[&str]) -> Result<String, BrowserError> { |
| 40 | let output = crate::host::command(program).args(arguments).output()?; |
| 41 | Ok(String::from_utf8_lossy(&output.stdout).into_owned()) |
| 42 | } |
| 43 | |
| 44 | fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> { |
| 45 | let pid = match platform { |
| 46 | Platform::Linux => parse_ss_pid(&run("ss", &["-ltnpH", &format!("sport = :{port}")])?), |
| 47 | Platform::Macos => parse_lsof_pid(&run( |
| 48 | "lsof", |
| 49 | &["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN"], |
| 50 | )?), |
| 51 | Platform::Windows => parse_netstat_pid(&run("netstat", &["-ano", "-p", "TCP"])?, port), |
| 52 | Platform::Wsl => parse_netstat_pid(&run("netstat.exe", &["-ano", "-p", "TCP"])?, port), |
| 53 | }; |
| 54 | pid.ok_or_else(|| BrowserError::Cdp(format!("no process listens on port {port}"))) |
| 55 | } |
| 56 | |
| 57 | /// Lowercased basename: macOS `ps -o comm=` may return a full path. |
| 58 | fn image_base(image_name: &str) -> String { |
| 59 | let trimmed = image_name.trim().trim_matches('"'); |
| 60 | let base = trimmed.rsplit(['/', '\\']).next().unwrap_or(trimmed).trim(); |
| 61 | base.to_ascii_lowercase() |
| 62 | } |
| 63 | |
| 64 | pub(crate) fn is_chrome_image(image_name: &str) -> bool { |
| 65 | let lowered = image_base(image_name); |
| 66 | lowered.starts_with("chrome") |
| 67 | || lowered.starts_with("google chrome") |
| 68 | || lowered.starts_with("chromium") |
| 69 | || lowered.starts_with("microsoft edge") |
| 70 | || lowered.starts_with("msedge") |
| 71 | || lowered.starts_with("brave") |
| 72 | || lowered.starts_with("helium") |
| 73 | || lowered.starts_with("vivaldi") |
| 74 | } |
| 75 | |
| 76 | pub(crate) fn is_firefox_image(image_name: &str) -> bool { |
| 77 | let lowered = image_base(image_name); |
| 78 | ["firefox", "zen", "librewolf", "floorp"] |
| 79 | .iter() |
| 80 | .any(|name| lowered.starts_with(name)) |
| 81 | } |
| 82 | |
| 83 | fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> { |
| 84 | let filter = format!("PID eq {pid}"); |
| 85 | let csv_arguments = ["/FI", filter.as_str(), "/FO", "CSV", "/NH"]; |
| 86 | let output = match platform { |
| 87 | Platform::Linux if crate::host::in_flatpak() => { |
| 88 | run("cat", &[&format!("/proc/{pid}/comm")])? |
| 89 | } |
| 90 | Platform::Linux => std::fs::read_to_string(format!("/proc/{pid}/comm"))?, |
| 91 | Platform::Macos => run("ps", &["-p", pid, "-o", "comm="])?, |
| 92 | Platform::Windows => run("tasklist", &csv_arguments)?, |
| 93 | Platform::Wsl => run("tasklist.exe", &csv_arguments)?, |
| 94 | }; |
| 95 | Ok(output.split(',').next().unwrap_or_default().to_owned()) |
| 96 | } |
| 97 | |
| 98 | const EXIT_WAIT: Duration = Duration::from_secs(10); |
| 99 | const EXIT_POLL: Duration = Duration::from_millis(100); |
| 100 | |
| 101 | /// Asks the browser holding `port` to quit with SIGTERM and waits until the process is gone, so |
| 102 | /// its profile is free again. Firefox on macOS keeps running after WebDriver BiDi `browser.close`. |
| 103 | pub(crate) fn terminate_listener(platform: Platform, port: u16) -> Result<(), BrowserError> { |
| 104 | let pid = browser_listener_pid(platform, port)?; |
| 105 | if !platform.uses_unix_paths() { |
| 106 | return kill_pid(platform, &pid); |
| 107 | } |
| 108 | crate::host::command("kill") |
| 109 | .args(["-TERM", &pid]) |
| 110 | .output()?; |
| 111 | let deadline = Instant::now() + EXIT_WAIT; |
| 112 | while Instant::now() < deadline { |
| 113 | let alive = crate::host::command("kill") |
| 114 | .args(["-0", &pid]) |
| 115 | .output()? |
| 116 | .status |
| 117 | .success(); |
| 118 | if !alive { |
| 119 | return Ok(()); |
| 120 | } |
| 121 | std::thread::sleep(EXIT_POLL); |
| 122 | } |
| 123 | Err(BrowserError::Cdp(format!( |
| 124 | "pid {pid} did not exit after SIGTERM" |
| 125 | ))) |
| 126 | } |
| 127 | |
| 128 | pub(crate) fn kill_listener(platform: Platform, port: u16) -> Result<(), BrowserError> { |
| 129 | let pid = browser_listener_pid(platform, port)?; |
| 130 | kill_pid(platform, &pid) |
| 131 | } |
| 132 | |
| 133 | /// The PID listening on `port`, only when it is a browser: never signal anything else. |
| 134 | fn browser_listener_pid(platform: Platform, port: u16) -> Result<String, BrowserError> { |
| 135 | let pid = listener_pid(platform, port)?.to_string(); |
| 136 | let image_name = process_image_name(platform, &pid)?; |
| 137 | if !is_chrome_image(&image_name) && !is_firefox_image(&image_name) { |
| 138 | return Err(BrowserError::Cdp(format!( |
| 139 | "port {port} is held by a process that is no known browser, not killing it" |
| 140 | ))); |
| 141 | } |
| 142 | Ok(pid) |
| 143 | } |
| 144 | |
| 145 | fn kill_pid(platform: Platform, pid: &str) -> Result<(), BrowserError> { |
| 146 | let (program, arguments): (&str, Vec<&str>) = match platform { |
| 147 | Platform::Linux | Platform::Macos => ("kill", vec!["-KILL", pid]), |
| 148 | Platform::Windows => ("taskkill", vec!["/PID", pid, "/T", "/F"]), |
| 149 | Platform::Wsl => ("taskkill.exe", vec!["/PID", pid, "/T", "/F"]), |
| 150 | }; |
| 151 | let status = crate::host::command(program) |
| 152 | .args(arguments) |
| 153 | .output()? |
| 154 | .status; |
| 155 | if status.success() { |
| 156 | Ok(()) |
| 157 | } else { |
| 158 | Err(BrowserError::Cdp(format!("{program} failed for pid {pid}"))) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | #[cfg(test)] |
| 163 | mod tests { |
| 164 | use super::*; |
| 165 | |
| 166 | #[test] |
| 167 | fn reads_pid_from_ss() { |
| 168 | let line = r#"LISTEN 0 511 127.0.0.1:9222 0.0.0.0:* users:(("chrome",pid=4242,fd=45))"#; |
| 169 | assert_eq!(parse_ss_pid(line), Some(4242)); |
| 170 | assert_eq!(parse_ss_pid(""), None); |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn only_chrome_images_are_killable() { |
| 175 | assert!(is_chrome_image("\"chrome.exe\"")); |
| 176 | assert!(is_chrome_image("chrome\n")); |
| 177 | assert!(is_chrome_image("Google Chrome")); |
| 178 | assert!(is_chrome_image("Chromium")); |
| 179 | assert!(is_chrome_image( |
| 180 | "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" |
| 181 | )); |
| 182 | assert!(is_chrome_image("/usr/bin/chromium")); |
| 183 | assert!(is_chrome_image( |
| 184 | "/Applications/Helium.app/Contents/MacOS/Helium" |
| 185 | )); |
| 186 | assert!(is_chrome_image( |
| 187 | "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge" |
| 188 | )); |
| 189 | assert!(is_chrome_image( |
| 190 | "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser" |
| 191 | )); |
| 192 | assert!(is_chrome_image("Vivaldi")); |
| 193 | assert!(!is_chrome_image("\"wslrelay.exe\"")); |
| 194 | assert!(!is_chrome_image( |
| 195 | "/Applications/Firefox.app/Contents/MacOS/firefox" |
| 196 | )); |
| 197 | assert!(!is_chrome_image("")); |
| 198 | } |
| 199 | |
| 200 | #[test] |
| 201 | fn firefox_family_images_are_recognised() { |
| 202 | assert!(is_firefox_image( |
| 203 | "/Applications/Firefox.app/Contents/MacOS/firefox" |
| 204 | )); |
| 205 | assert!(is_firefox_image("/Applications/Zen.app/Contents/MacOS/zen")); |
| 206 | assert!(is_firefox_image("zen-browser\n")); |
| 207 | assert!(is_firefox_image("librewolf")); |
| 208 | assert!(!is_firefox_image("/usr/bin/chromium")); |
| 209 | assert!(!is_firefox_image("")); |
| 210 | } |
| 211 | |
| 212 | #[test] |
| 213 | fn reads_pid_from_netstat() { |
| 214 | let table = " TCP 127.0.0.1:19222 0.0.0.0:0 LISTENING 111\r\n TCP 127.0.0.1:9222 0.0.0.0:0 LISTENING 5150\r\n TCP 127.0.0.1:9222 127.0.0.1:50000 ESTABLISHED 5150\r\n"; |
| 215 | assert_eq!(parse_netstat_pid(table, 9222), Some(5150)); |
| 216 | assert_eq!(parse_netstat_pid(table, 9333), None); |
| 217 | } |
| 218 | |
| 219 | #[test] |
| 220 | fn reads_pid_from_lsof() { |
| 221 | let table = "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME\nGoogle\\x20Ch 4242 joe 45u IPv4 0xabc 0t0 TCP 127.0.0.1:9222 (LISTEN)\n"; |
| 222 | assert_eq!(parse_lsof_pid(table), Some(4242)); |
| 223 | assert_eq!(parse_lsof_pid("COMMAND PID\n"), None); |
| 224 | } |
| 225 | } |