garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/browser.rs

raw

//! A page photographed by a headless Chromium, driven over its DevTools pipe
//! (`--remote-debugging-pipe`: JSON messages ending in a NUL on fds 3 and 4).
//! Chromium's own `--screenshot` never returns in the agent container (tried
//! 2026-11-19 with old and new headless, with and without a profile), while
//! the same browser driven over DevTools does; the pipe needs no WebSocket.
//! Scripts are off and the network points nowhere: what a page shows is its
//! own markup and the local files it links.

use std::io::{BufRead, BufReader, Write};
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use serde_json::{json, Value};

/// The browser: `MIDAS_CHROMIUM`, else `chromium` in `~/bin` or on the path.
fn browser() -> String {
    crate::client::setting("MIDAS_CHROMIUM").unwrap_or_else(|| {
        let own = std::env::var("HOME").map(|h| format!("{h}/bin/chromium")).unwrap_or_default();
        if !own.is_empty() && std::path::Path::new(&own).exists() { own } else { "chromium".into() }
    })
}

fn pipe() -> Result<(OwnedFd, OwnedFd)> {
    // pipe and then close-on-exec, not pipe2: the hub's build makes the Mac nodes' binary too, and
    // macOS has no pipe2 (a deploy failed on it, 2026-11-19).
    let mut fds = [0; 2];
    if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
        bail!("no pipe: {}", std::io::Error::last_os_error());
    }
    let pair = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) };
    for fd in fds {
        if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
            bail!("no pipe: {}", std::io::Error::last_os_error());
        }
    }
    Ok(pair)
}

/// `url` photographed at `width` by `height` CSS pixels, as a PNG, within `limit`.
pub fn photograph(url: &str, width: u32, height: u32, limit: Duration) -> Result<Vec<u8>> {
    let started = Instant::now();
    let profile = std::env::temp_dir().join(format!("midas-browser-{}-{}", std::process::id(),
        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)));
    // fd 3 is what the browser reads, fd 4 what it writes.
    let (in_r, in_w) = pipe()?;
    let (out_r, out_w) = pipe()?;
    let (a, b) = (std::os::fd::AsRawFd::as_raw_fd(&in_r), std::os::fd::AsRawFd::as_raw_fd(&out_w));
    let mut cmd = Command::new(browser());
    cmd.args(["--headless=new", "--no-sandbox", "--disable-gpu", "--hide-scrollbars", "--mute-audio", "--no-first-run",
        "--no-default-browser-check", "--disable-background-networking", "--disable-component-update", "--disable-sync",
        "--disable-extensions", "--remote-debugging-pipe", "--blink-settings=scriptEnabled=false",
        "--proxy-server=127.0.0.1:9", "--proxy-bypass-list=<-loopback>"])
        .arg(format!("--user-data-dir={}", profile.display()))
        .arg("about:blank")
        .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
    unsafe {
        cmd.pre_exec(move || {
            // Out of the way first, so neither lands on the other's number; dup2 clears close-on-exec.
            let (x, y) = (libc::fcntl(a, libc::F_DUPFD, 10), libc::fcntl(b, libc::F_DUPFD, 10));
            if x < 0 || y < 0 || libc::dup2(x, 3) < 0 || libc::dup2(y, 4) < 0 {
                return Err(std::io::Error::last_os_error());
            }
            // No core dump, ever: a crashed browser left 28 MB of its memory —
            // this process's environment in it — in the folder it drew for,
            // and twelve of those were committed beside the mockups (2026-11).
            let none = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
            libc::setrlimit(libc::RLIMIT_CORE, &none);
            Ok(())
        });
    }
    let mut child = cmd.spawn().context("could not start the browser (MIDAS_CHROMIUM)")?;
    drop(in_r);
    drop(out_w);
    let result = (|| -> Result<Vec<u8>> {
        let mut to = std::fs::File::from(in_w);
        let from = BufReader::new(std::fs::File::from(out_r));
        let (tx, rx) = mpsc::channel::<Value>();
        std::thread::spawn(move || {
            for msg in from.split(0) {
                let Ok(msg) = msg else { break };
                if let Ok(v) = serde_json::from_slice::<Value>(&msg) {
                    if tx.send(v).is_err() {
                        break;
                    }
                }
            }
        });
        let mut id = 0;
        let left = || limit.checked_sub(started.elapsed()).filter(|d| !d.is_zero());
        // The events seen while waiting for answers: the load may come before navigate's answer does.
        let mut seen: Vec<String> = Vec::new();
        let next = |seen: &mut Vec<String>| -> Result<Value> {
            let v = rx.recv_timeout(left().context("the browser took too long")?).context("the browser went quiet")?;
            if let Some(m) = v["method"].as_str() {
                seen.push(m.to_string());
            }
            Ok(v)
        };
        // A message to the browser, and its answer.
        let mut ask = |method: &str, params: Value, session: Option<&str>, seen: &mut Vec<String>| -> Result<Value> {
            id += 1;
            let mut m = json!({"id": id, "method": method, "params": params});
            if let Some(s) = session {
                m["sessionId"] = json!(s);
            }
            to.write_all(m.to_string().as_bytes())?;
            to.write_all(&[0])?;
            to.flush()?;
            loop {
                let v = next(seen)?;
                if v["id"] == id {
                    if let Some(e) = v.get("error") {
                        bail!("{method}: {}", e["message"].as_str().unwrap_or("failed"));
                    }
                    return Ok(v);
                }
            }
        };
        // A tab of its own: the one it opens with may not be there yet.
        let made = ask("Target.createTarget", json!({"url": "about:blank"}), None, &mut seen)?;
        let target = made["result"]["targetId"].as_str().context("the browser opened no tab")?.to_string();
        let attached = ask("Target.attachToTarget", json!({"targetId": target, "flatten": true}), None, &mut seen)?;
        let s = attached["result"]["sessionId"].as_str().context("no session on the page")?.to_string();
        let s = Some(s.as_str());
        ask("Emulation.setDeviceMetricsOverride", json!({"width": width, "height": height, "deviceScaleFactor": 2, "mobile": false}), s, &mut seen)?;
        ask("Emulation.setScriptExecutionDisabled", json!({"value": true}), s, &mut seen)?;
        ask("Page.enable", json!({}), s, &mut seen)?;
        ask("Page.navigate", json!({"url": url}), s, &mut seen)?;
        // The load, then a moment for the fonts and pictures it linked to be drawn.
        while !seen.iter().any(|m| m == "Page.loadEventFired") {
            next(&mut seen)?;
        }
        std::thread::sleep(Duration::from_millis(600));
        let shot = ask("Page.captureScreenshot", json!({"format": "png"}), s, &mut seen)?;
        let data = shot["result"]["data"].as_str().context("no picture")?;
        let _ = ask("Browser.close", json!({}), None, &mut seen);
        data_encoding::BASE64.decode(data.as_bytes()).context("a picture that is not base64")
    })();
    // Closed by now, or not: never left running.
    for _ in 0..20 {
        if matches!(child.try_wait(), Ok(Some(_))) {
            break;
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    let _ = child.kill();
    let _ = child.wait();
    let _ = std::fs::remove_dir_all(&profile);
    result
}