Skip to main content

nexo_plugin_browser/
chrome.rs

1use std::time::Duration;
2
3use anyhow::anyhow;
4use tokio::io::AsyncBufReadExt;
5use tokio::process::Command;
6
7use nexo_config::BrowserConfig;
8
9pub struct RunningChrome {
10    pub ws_url: String,
11    pub pid: u32,
12    child: tokio::process::Child,
13}
14
15impl RunningChrome {
16    /// Kill Chrome and reap the process entry.
17    /// Must be called from an async context before the value goes out of scope.
18    /// Consuming self ensures the Child is dropped only after wait() completes,
19    /// preventing a <defunct> entry in the process table.
20    pub async fn shutdown(mut self) {
21        let _ = self.child.kill().await;
22        let _ = self.child.wait().await;
23    }
24}
25
26impl Drop for RunningChrome {
27    fn drop(&mut self) {
28        // Safety-net: reached only on unexpected drops (panic path, test teardown).
29        // Normal teardown must go through shutdown() to avoid zombie processes.
30        tracing::warn!(
31            pid = self.pid,
32            "RunningChrome dropped without shutdown() — Chrome process may become a zombie"
33        );
34        let _ = self.child.start_kill();
35    }
36}
37
38pub struct ChromeLauncher;
39
40impl ChromeLauncher {
41    pub async fn launch(config: &BrowserConfig) -> anyhow::Result<RunningChrome> {
42        let exe = if config.executable.is_empty() {
43            find_chrome_executable().ok_or_else(|| {
44                anyhow!("no Chrome/Chromium executable found — install google-chrome or chromium")
45            })?
46        } else {
47            config.executable.clone()
48        };
49
50        let mut args = vec![
51            format!("--remote-debugging-port=0"),
52            format!("--user-data-dir={}", config.user_data_dir),
53            format!(
54                "--window-size={},{}",
55                config.window_width, config.window_height
56            ),
57            "--no-first-run".to_string(),
58            "--no-default-browser-check".to_string(),
59            "--disable-background-networking".to_string(),
60            "--disable-client-side-phishing-detection".to_string(),
61            "--disable-default-apps".to_string(),
62            "--disable-extensions".to_string(),
63            "--disable-hang-monitor".to_string(),
64            "--disable-popup-blocking".to_string(),
65            "--disable-prompt-on-repost".to_string(),
66            "--disable-sync".to_string(),
67            "--disable-translate".to_string(),
68            "--metrics-recording-only".to_string(),
69            "--safebrowsing-disable-auto-update".to_string(),
70            "about:blank".to_string(),
71        ];
72
73        if config.headless {
74            args.push("--headless=new".to_string());
75            args.push("--disable-gpu".to_string());
76        }
77
78        // Operator-supplied extra flags (`browser.args` in YAML). Appended
79        // after our built-ins so the operator can override if a flag
80        // conflicts — later args win with Chrome's CLI parser.
81        for extra in &config.args {
82            args.push(extra.clone());
83        }
84
85        let mut child = Command::new(&exe)
86            .args(&args)
87            .stderr(std::process::Stdio::piped())
88            .stdout(std::process::Stdio::null())
89            .kill_on_drop(true)
90            .spawn()
91            .map_err(|e| anyhow!("failed to spawn Chrome ({exe}): {e}"))?;
92
93        let pid = child.id().unwrap_or(0);
94
95        let stderr = child
96            .stderr
97            .take()
98            .ok_or_else(|| anyhow!("failed to capture Chrome stderr"))?;
99
100        let ws_url = wait_for_devtools_url(stderr, config.connect_timeout_ms)
101            .await
102            .inspect_err(|_e| {
103                let _ = child.start_kill();
104            })?;
105
106        Ok(RunningChrome { ws_url, pid, child })
107    }
108
109    /// Attach to an already-running Chrome at a CDP HTTP URL.
110    pub async fn connect_existing(cdp_url: &str, timeout_ms: u64) -> anyhow::Result<String> {
111        // Delegate to the canonical discovery path in cdp::client which also
112        // rewrites the authority of the returned webSocketDebuggerUrl
113        // (Chrome echoes the Host header and drops the real port).
114        crate::cdp::CdpClient::discover_ws_url(cdp_url, timeout_ms).await
115    }
116}
117
118async fn wait_for_devtools_url(
119    stderr: tokio::process::ChildStderr,
120    timeout_ms: u64,
121) -> anyhow::Result<String> {
122    let reader = tokio::io::BufReader::new(stderr);
123    let mut lines = reader.lines();
124
125    let timeout = Duration::from_millis(timeout_ms);
126    let deadline = tokio::time::Instant::now() + timeout;
127
128    loop {
129        let remaining = deadline
130            .checked_duration_since(tokio::time::Instant::now())
131            .unwrap_or(Duration::ZERO);
132
133        if remaining.is_zero() {
134            return Err(anyhow!("timed out waiting for Chrome DevTools URL"));
135        }
136
137        let line = tokio::time::timeout(remaining, lines.next_line())
138            .await
139            .map_err(|_| anyhow!("timed out waiting for Chrome DevTools URL"))?
140            .map_err(|e| anyhow!("error reading Chrome stderr: {e}"))?;
141
142        let Some(line) = line else {
143            return Err(anyhow!("Chrome exited before DevTools URL appeared"));
144        };
145
146        if let Some(rest) = line.strip_prefix("DevTools listening on ") {
147            return Ok(rest.trim().to_string());
148        }
149    }
150}
151
152fn find_chrome_executable() -> Option<String> {
153    let candidates = [
154        "google-chrome",
155        "google-chrome-stable",
156        "chromium-browser",
157        "chromium",
158        "/usr/bin/google-chrome",
159        "/usr/bin/chromium-browser",
160        "/usr/bin/chromium",
161        "/snap/bin/chromium",
162    ];
163
164    for candidate in &candidates {
165        if which_exists(candidate) {
166            return Some(candidate.to_string());
167        }
168    }
169    None
170}
171
172fn which_exists(name: &str) -> bool {
173    // Fast check: try to find in PATH using `which` or just test if absolute path exists
174    if name.starts_with('/') {
175        return std::path::Path::new(name).exists();
176    }
177    // Search PATH
178    if let Ok(path_var) = std::env::var("PATH") {
179        for dir in path_var.split(':') {
180            let full = format!("{dir}/{name}");
181            if std::path::Path::new(&full).exists() {
182                return true;
183            }
184        }
185    }
186    false
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use tokio::process::Command as TokioCommand;
193
194    fn make_running_chrome(child: tokio::process::Child, pid: u32) -> RunningChrome {
195        RunningChrome {
196            ws_url: String::new(),
197            pid,
198            child,
199        }
200    }
201
202    #[tokio::test]
203    async fn shutdown_reaps_process() {
204        let child = TokioCommand::new("sleep")
205            .arg("30")
206            .kill_on_drop(false)
207            .spawn()
208            .expect("failed to spawn sleep");
209        let pid = child.id().expect("missing PID");
210        let running = make_running_chrome(child, pid);
211
212        running.shutdown().await;
213
214        // After shutdown(), the process must be reaped.
215        // kill(pid, 0) returns ESRCH when no such process exists.
216        let alive = unsafe { libc::kill(pid as libc::pid_t, 0) == 0 };
217        assert!(!alive, "process {pid} still exists after shutdown()");
218    }
219}