| 1 | use std::process::Command; |
| 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.chars().take_while(char::is_ascii_digit).collect::<String>().parse().ok() |
| 9 | } |
| 10 | |
| 11 | pub(crate) fn parse_netstat_pid(output: &str, port: u16) -> Option<u32> { |
| 12 | let suffix = format!(":{port}"); |
| 13 | output.lines().find_map(|line| { |
| 14 | let columns: Vec<&str> = line.split_whitespace().collect(); |
| 15 | let listening = columns.iter().any(|column| column.eq_ignore_ascii_case("LISTENING")); |
| 16 | let local = columns.get(1)?; |
| 17 | if !listening || !local.ends_with(&suffix) { |
| 18 | return None; |
| 19 | } |
| 20 | columns.last()?.parse().ok() |
| 21 | }) |
| 22 | } |
| 23 | |
| 24 | fn run(program: &str, arguments: &[&str]) -> Result<String, BrowserError> { |
| 25 | let output = Command::new(program).args(arguments).output()?; |
| 26 | Ok(String::from_utf8_lossy(&output.stdout).into_owned()) |
| 27 | } |
| 28 | |
| 29 | fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> { |
| 30 | let pid = match platform { |
| 31 | Platform::Linux => parse_ss_pid(&run("ss", &["-ltnpH", &format!("sport = :{port}")])?), |
| 32 | Platform::Windows => parse_netstat_pid(&run("netstat", &["-ano", "-p", "TCP"])?, port), |
| 33 | Platform::Wsl => parse_netstat_pid(&run("netstat.exe", &["-ano", "-p", "TCP"])?, port), |
| 34 | }; |
| 35 | pid.ok_or_else(|| BrowserError::Cdp(format!("no process listens on port {port}"))) |
| 36 | } |
| 37 | |
| 38 | pub(crate) fn is_chrome_image(image_name: &str) -> bool { |
| 39 | let lowered = image_name.trim().trim_matches('"').to_ascii_lowercase(); |
| 40 | lowered.starts_with("chrome") |
| 41 | } |
| 42 | |
| 43 | fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> { |
| 44 | let filter = format!("PID eq {pid}"); |
| 45 | let csv_arguments = ["/FI", filter.as_str(), "/FO", "CSV", "/NH"]; |
| 46 | let output = match platform { |
| 47 | Platform::Linux => std::fs::read_to_string(format!("/proc/{pid}/comm"))?, |
| 48 | Platform::Windows => run("tasklist", &csv_arguments)?, |
| 49 | Platform::Wsl => run("tasklist.exe", &csv_arguments)?, |
| 50 | }; |
| 51 | Ok(output.split(',').next().unwrap_or_default().to_owned()) |
| 52 | } |
| 53 | |
| 54 | pub(crate) fn kill_listener(platform: Platform, port: u16) -> Result<(), BrowserError> { |
| 55 | let pid = listener_pid(platform, port)?.to_string(); |
| 56 | let image_name = process_image_name(platform, &pid)?; |
| 57 | if !is_chrome_image(&image_name) { |
| 58 | return Err(BrowserError::Cdp(format!("port {port} is held by a non-Chrome process, not killing it"))); |
| 59 | } |
| 60 | let (program, arguments): (&str, Vec<&str>) = match platform { |
| 61 | Platform::Linux => ("kill", vec!["-KILL", &pid]), |
| 62 | Platform::Windows => ("taskkill", vec!["/PID", &pid, "/T", "/F"]), |
| 63 | Platform::Wsl => ("taskkill.exe", vec!["/PID", &pid, "/T", "/F"]), |
| 64 | }; |
| 65 | let status = Command::new(program).args(arguments).output()?.status; |
| 66 | if status.success() { Ok(()) } else { Err(BrowserError::Cdp(format!("{program} failed for pid {pid}"))) } |
| 67 | } |
| 68 | |
| 69 | #[cfg(test)] |
| 70 | mod tests { |
| 71 | use super::*; |
| 72 | |
| 73 | #[test] |
| 74 | fn reads_pid_from_ss() { |
| 75 | let line = r#"LISTEN 0 511 127.0.0.1:9222 0.0.0.0:* users:(("chrome",pid=4242,fd=45))"#; |
| 76 | assert_eq!(parse_ss_pid(line), Some(4242)); |
| 77 | assert_eq!(parse_ss_pid(""), None); |
| 78 | } |
| 79 | |
| 80 | #[test] |
| 81 | fn only_chrome_images_are_killable() { |
| 82 | assert!(is_chrome_image("\"chrome.exe\"")); |
| 83 | assert!(is_chrome_image("chrome\n")); |
| 84 | assert!(!is_chrome_image("\"wslrelay.exe\"")); |
| 85 | assert!(!is_chrome_image("")); |
| 86 | } |
| 87 | |
| 88 | #[test] |
| 89 | fn reads_pid_from_netstat() { |
| 90 | 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"; |
| 91 | assert_eq!(parse_netstat_pid(table, 9222), Some(5150)); |
| 92 | assert_eq!(parse_netstat_pid(table, 9333), None); |
| 93 | } |
| 94 | } |