eoka 0.17.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! A running Chrome's user-data directory: its singleton lock, its DevTools
//! port file and its process argv. Used to attach to (or refuse) a Chrome
//! that already owns a profile.

/// Read the pid out of `<user_data_dir>/SingletonLock`. Chrome writes this
/// as a symlink whose target is `<hostname>-<pid>` — a POSIX-only mechanism
/// (Windows Chrome uses a named mutex instead), so this is `None` outside
/// Unix. Also `None` when no lock is present (nothing else has this profile
/// open).
pub(crate) fn read_singleton_lock(user_data_dir: &std::path::Path) -> Option<u32> {
    #[cfg(unix)]
    {
        let target = std::fs::read_link(user_data_dir.join("SingletonLock")).ok()?;
        target.to_str()?.rsplit('-').next()?.parse().ok()
    }
    #[cfg(not(unix))]
    {
        let _ = user_data_dir;
        None
    }
}

/// Whether `pid` refers to a live process.
pub(crate) fn pid_is_alive(pid: u32) -> bool {
    #[cfg(target_os = "linux")]
    {
        std::path::Path::new(&format!("/proc/{pid}")).exists()
    }
    #[cfg(not(target_os = "linux"))]
    {
        no_proc_pid_is_alive(pid)
    }
}

/// Read the port Chrome is listening on from `<user_data_dir>/DevToolsActivePort`,
/// written when Chrome is launched with `--remote-debugging-port` (including
/// `=0`). Returns `None` if the file is
/// missing (that Chrome wasn't given a debug port).
pub(crate) fn read_devtools_active_port(user_data_dir: &std::path::Path) -> Option<u16> {
    let contents = std::fs::read_to_string(user_data_dir.join("DevToolsActivePort")).ok()?;
    contents.lines().next()?.trim().parse().ok()
}

/// Read a process's argv. Used to detect a headless/headed mismatch before
/// attaching to a Chrome we didn't spawn ourselves. `None` if it can't be
/// determined (unsupported platform, or the process/tool is unreadable).
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn read_process_argv(pid: u32) -> Option<Vec<String>> {
    #[cfg(target_os = "linux")]
    {
        let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
        // Reads as empty for zombies, kernel threads, and a process still in
        // execve. An empty argv proves nothing about its flags.
        let argv = parse_proc_cmdline(&raw);
        (!argv.is_empty()).then_some(argv)
    }
    #[cfg(target_os = "macos")]
    {
        // No /proc/<pid>/cmdline on macOS; shell out to `ps` instead.
        let output = std::process::Command::new("ps")
            .args(["-ww", "-p", &pid.to_string(), "-o", "args="])
            .output()
            .ok()?;
        if !output.status.success() {
            return None;
        }
        Some(
            String::from_utf8_lossy(&output.stdout)
                .split_whitespace()
                .map(str::to_owned)
                .collect(),
        )
    }
}

/// Split `/proc/<pid>/cmdline`. Chrome may rewrite its process title so the
/// whole command line becomes one space-joined string (Chrome for Testing 156
/// does); split that back into words so switch detection still sees each flag.
#[cfg(any(target_os = "linux", test))]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn parse_proc_cmdline(raw: &[u8]) -> Vec<String> {
    let pieces: Vec<String> = raw
        .split(|&b| b == 0)
        .filter(|piece| !piece.is_empty())
        .map(|piece| String::from_utf8_lossy(piece).into_owned())
        .collect();
    match pieces.as_slice() {
        [title] if title.contains(char::is_whitespace) => {
            title.split_whitespace().map(str::to_owned).collect()
        }
        _ => pieces,
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub(crate) fn read_process_argv(_: u32) -> Option<Vec<String>> {
    None
}

/// Signal 0 checks that the process exists (and may be signalled) without
/// touching it, as `kill -0` does.
#[cfg(all(unix, not(target_os = "linux")))]
fn no_proc_pid_is_alive(pid: u32) -> bool {
    let Ok(pid) = libc::pid_t::try_from(pid) else {
        return false;
    };
    // SAFETY: signal 0 performs only the existence and permission check.
    unsafe { libc::kill(pid, 0) == 0 }
}

#[cfg(not(unix))]
fn no_proc_pid_is_alive(_: u32) -> bool {
    false
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::os::unix::fs::symlink;

    fn temp_profile_dir(name: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "eoka-profile-test-{}-{}-{}",
            std::process::id(),
            name,
            fastrand::u64(..)
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn read_singleton_lock_parses_trailing_pid() {
        let dir = temp_profile_dir("lock");
        symlink("some-host-54321", dir.join("SingletonLock")).unwrap();
        assert_eq!(read_singleton_lock(&dir), Some(54321));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn read_singleton_lock_missing_is_none() {
        let dir = temp_profile_dir("no-lock");
        assert!(read_singleton_lock(&dir).is_none());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn proc_cmdline_splits_rewritten_process_title() {
        let argv =
            parse_proc_cmdline(b"/opt/chrome --headless=new --no-sandbox --user-data-dir=/p\0");
        assert_eq!(
            argv,
            [
                "/opt/chrome",
                "--headless=new",
                "--no-sandbox",
                "--user-data-dir=/p"
            ]
        );
        let argv =
            parse_proc_cmdline(b"/opt/chrome\0--user-agent=Mozilla/5.0 (X11)\0--headless=new\0");
        assert_eq!(
            argv,
            [
                "/opt/chrome",
                "--user-agent=Mozilla/5.0 (X11)",
                "--headless=new"
            ]
        );
    }

    #[test]
    fn pid_is_alive_true_for_self() {
        assert!(pid_is_alive(std::process::id()));
    }

    #[test]
    fn read_devtools_active_port_parses_first_line() {
        let dir = temp_profile_dir("port");
        std::fs::write(
            dir.join("DevToolsActivePort"),
            "37469\n/devtools/browser/00000000-0000-0000-0000-000000000000\n",
        )
        .unwrap();
        assert_eq!(read_devtools_active_port(&dir), Some(37469));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn read_devtools_active_port_missing_is_none() {
        let dir = temp_profile_dir("no-port");
        assert!(read_devtools_active_port(&dir).is_none());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn read_process_argv_reads_own_cmdline() {
        let argv = read_process_argv(std::process::id()).expect("own /proc entry must exist");
        assert!(!argv.is_empty());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn empty_cmdline_is_unverified_not_an_empty_argv() {
        // An unreaped zombie keeps its /proc entry with an empty cmdline.
        let mut child = std::process::Command::new("true").spawn().unwrap();
        let stat = format!("/proc/{}/stat", child.id());
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        crate::cdp::poll::poll_blocking(
            Some(deadline),
            std::time::Duration::from_millis(5),
            || {
                std::fs::read_to_string(&stat)
                    .unwrap()
                    .rsplit_once(')')
                    .is_some_and(|(_, rest)| rest.trim_start().starts_with('Z'))
                    .then_some(())
            },
        )
        .expect("the exited child must become a zombie");
        assert_eq!(read_process_argv(child.id()), None);
        child.wait().unwrap();
    }
}