eoka 0.14.3

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! Chrome child ownership, launch and DevTools endpoint discovery.

mod version;

pub(crate) use version::chrome_version_output;

use crate::cdp::poll::poll_blocking;
use crate::{Error, Result};
use std::{
    io::{BufRead, BufReader},
    path::Path,
    process::{Child, Command, Stdio},
    sync::atomic::{AtomicBool, Ordering},
    time::{Duration, Instant},
};

/// Terminate and reap a managed Chrome child without treating an already
/// exited process as an error.
pub(crate) fn stop_child(child: &mut Child) -> std::io::Result<()> {
    if child.try_wait()?.is_some() {
        return Ok(());
    }

    if let Err(kill_error) = child.kill() {
        if child.try_wait()?.is_none() {
            return Err(kill_error);
        }
        return Ok(());
    }

    child.wait()?;
    Ok(())
}

/// How long to retry an exec that fails with `ETXTBSY`.
const EXECUTABLE_BUSY_RETRY: Duration = Duration::from_secs(2);

/// Spawn `command`, retrying briefly while its executable is busy.
///
/// Linux refuses to exec a file that any process holds open for writing. A
/// file this process just wrote (the patched Chrome copy, or a script) can
/// still be open in a child that another thread forked before the write
/// descriptor was closed; that copy closes at the child's own exec. Retry
/// until then instead of reporting a launch failure.
fn spawn_executable(
    command: &mut Command,
    cancelled: Option<&AtomicBool>,
) -> std::io::Result<Child> {
    let deadline = Instant::now() + EXECUTABLE_BUSY_RETRY;
    let mut delay = Duration::from_millis(5);
    loop {
        match command.spawn() {
            Err(error)
                if error.kind() == std::io::ErrorKind::ExecutableFileBusy
                    && Instant::now() < deadline
                    && !cancelled.is_some_and(|cancelled| cancelled.load(Ordering::Acquire)) =>
            {
                std::thread::sleep(delay);
                delay = (delay * 2).min(Duration::from_millis(100));
            }
            result => return result,
        }
    }
}

/// Own a Chrome child until it is handed to `Transport`. If the async
/// WebSocket connection future is cancelled, dropping this guard still kills
/// and reaps the process.
pub(super) struct ChildCleanupGuard {
    child: Option<Child>,
}

impl ChildCleanupGuard {
    pub(super) fn new(child: Child) -> Self {
        Self { child: Some(child) }
    }

    pub(super) fn take(&mut self) -> Result<Child> {
        self.child
            .take()
            .ok_or_else(|| Error::transport("Chrome child ownership was already transferred"))
    }
}

impl Drop for ChildCleanupGuard {
    fn drop(&mut self) {
        if let Some(mut child) = self.child.take() {
            if let Err(error) = stop_child(&mut child) {
                tracing::warn!("Failed to clean up an unclaimed Chrome child: {}", error);
            }
        }
    }
}

fn debugging_port_argument(args: &[String], live_session: bool) -> Result<Option<String>> {
    if args
        .iter()
        .any(|arg| arg == "--remote-debugging-port" || arg.starts_with("--remote-debugging-port="))
    {
        return Ok(None);
    }
    let port = if live_session {
        std::net::TcpListener::bind("127.0.0.1:0")?
            .local_addr()?
            .port()
    } else {
        0
    };
    Ok(Some(format!("--remote-debugging-port={port}")))
}

pub(crate) fn launch_chrome_with_profile_dir(
    path: &Path,
    args: &[String],
    profile_dir: &Path,
    live_session: bool,
    runtime: &Path,
    cancelled: &AtomicBool,
) -> Result<(Child, String)> {
    let mut cmd = Command::new(path);
    cmd.args(args)
        .env("TMPDIR", runtime)
        .env("TMP", runtime)
        .env("TEMP", runtime);
    let debugging_argument = debugging_port_argument(args, live_session)?;
    if let Some(argument) = &debugging_argument {
        cmd.arg(argument);
    }
    let effective_port = debugging_argument.as_deref().or_else(|| {
        args.iter()
            .rev()
            .find(|arg| {
                arg.as_str() == "--remote-debugging-port"
                    || arg.starts_with("--remote-debugging-port=")
            })
            .map(String::as_str)
    });
    let fallback_profile_dir =
        (effective_port == Some("--remote-debugging-port=0")).then_some(profile_dir);
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped()); // We need stderr to get the DevTools URL

    if cancelled.load(Ordering::Acquire) {
        return Err(Error::launch("Browser launch was cancelled"));
    }
    if let Some(profile) = fallback_profile_dir {
        // Chrome leaves this file behind on exit. Discovery must only consume
        // the endpoint written by the process we are about to spawn.
        if let Err(error) = std::fs::remove_file(profile.join("DevToolsActivePort")) {
            if error.kind() != std::io::ErrorKind::NotFound {
                return Err(Error::launch(format!(
                    "Failed to remove stale DevToolsActivePort before launch: {error}"
                )));
            }
        }
    }
    let mut guard = ChildCleanupGuard::new(
        spawn_executable(&mut cmd, Some(cancelled))
            .map_err(|e| Error::launch(format!("Failed to launch Chrome: {e}")))?,
    );
    let child = guard
        .child
        .as_mut()
        .expect("new child guard owns its process");
    let stderr = child
        .stderr
        .take()
        .ok_or(Error::launch("No stderr from Chrome"))?;

    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || drain_chrome_stderr(BufReader::new(stderr), tx));

    let ws_url = match wait_for_chrome_devtools_url(child, &rx, fallback_profile_dir, cancelled) {
        Ok(url) => url,
        Err(error) => {
            return match stop_child(child) {
                Ok(()) => {
                    guard.child = None;
                    Err(error)
                }
                Err(cleanup) => Err(Error::launch(format!(
                    "{error}; Chrome cleanup failed: {cleanup}"
                ))),
            };
        }
    };

    tracing::info!("Chrome DevTools URL: {}", ws_url);

    Ok((guard.take()?, ws_url))
}

fn drain_chrome_stderr(
    reader: impl BufRead,
    sender: std::sync::mpsc::Sender<std::result::Result<String, String>>,
) {
    let mut sender = Some(sender);
    let mut stderr_tail = Vec::new();
    for line in reader.lines() {
        let line = match line {
            Ok(line) => line,
            Err(error) => {
                if let Some(sender) = sender.take() {
                    let _ = sender.send(Err(format!("failed to read Chrome stderr: {error}")));
                } else {
                    tracing::warn!("Chrome stderr reader failed after startup: {error}");
                }
                return;
            }
        };
        tracing::trace!("Chrome stderr: {}", line);
        if sender.is_none() {
            continue;
        }
        if let Some((_, endpoint)) = line.split_once("DevTools listening on ws://") {
            let _ = sender
                .take()
                .unwrap()
                .send(Ok(format!("ws://{}", endpoint.trim())));
            stderr_tail = Vec::new();
        } else {
            stderr_tail.push(line);
            if stderr_tail.len() > 20 {
                stderr_tail.remove(0);
            }
        }
    }
    if let Some(sender) = sender {
        let message = if stderr_tail.is_empty() {
            "Chrome exited before printing DevTools URL and produced no stderr".to_string()
        } else {
            format!(
                "Chrome exited before printing DevTools URL. stderr:\n{}",
                stderr_tail.join("\n")
            )
        };
        let _ = sender.send(Err(message));
    }
}

/// How often the wait also checks cancellation, DevToolsActivePort and exit.
const DEVTOOLS_CHECK_INTERVAL: Duration = Duration::from_millis(50);

fn wait_for_chrome_devtools_url(
    child: &mut Child,
    rx: &std::sync::mpsc::Receiver<std::result::Result<String, String>>,
    profile_dir: Option<&Path>,
    cancelled: &AtomicBool,
) -> Result<String> {
    let deadline = Instant::now() + Duration::from_secs(30);

    // Blocks on the stderr channel between checks, so the URL is picked up
    // the moment Chrome prints it.
    poll_blocking(Some(deadline), Duration::ZERO, || {
        if cancelled.load(Ordering::Acquire) {
            return Some(Err(Error::launch("Browser launch was cancelled")));
        }
        match rx.recv_timeout(DEVTOOLS_CHECK_INTERVAL) {
            Ok(Ok(url)) => return Some(Ok(url)),
            Ok(Err(stderr)) => {
                let status = child
                    .try_wait()
                    .ok()
                    .flatten()
                    .map_or_else(|| "still running".to_string(), |status| status.to_string());
                return Some(Err(Error::launch(format!(
                    "Failed waiting for Chrome DevTools URL: process {status}; {stderr}"
                ))));
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                return Some(Err(Error::launch(
                    "Failed waiting for Chrome DevTools URL: stderr reader exited unexpectedly",
                )));
            }
        }

        if let Some(dir) = profile_dir {
            if let Some(port) = crate::cdp::profile::read_devtools_active_port(dir) {
                return Some(
                    crate::cdp::discover::discover_browser_ws("127.0.0.1", port).map_err(|error| {
                        Error::launch(format!(
                            "Chrome wrote DevToolsActivePort ({port}) but discovery failed: {error}"
                        ))
                    }),
                );
            }
        }

        if let Ok(Some(status)) = child.try_wait() {
            let stderr = rx
                .recv_timeout(Duration::from_millis(250))
                .ok()
                .and_then(std::result::Result::err)
                .unwrap_or_else(|| "Chrome exited before printing DevTools URL".to_string());
            return Some(Err(Error::launch(format!(
                "Failed waiting for Chrome DevTools URL: process {status}; {stderr}"
            ))));
        }

        None
    })
    .unwrap_or_else(|| {
        Err(Error::launch(
            "Failed waiting for Chrome DevTools URL after 30s",
        ))
    })
}

#[cfg(test)]
mod tests;