use crate::error::{BrowserError, Result};
use rightkit_child_process::{OwnedChild, OwnedCommand};
#[cfg(windows)]
use rightkit_sandbox::{
EnvPolicy, NetworkPolicy as SandboxNetworkPolicy, ResourceAuthority, ResourceProfile, Sandbox,
SandboxCommand, SandboxPolicy, SandboxedChild, WindowsAuxiliaryIo,
};
use std::ffi::OsString;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
#[cfg(windows)]
use std::{
fs::File,
io::{Read, Seek, SeekFrom},
};
#[cfg(windows)]
const FIXTURE_LOG_TAIL_BYTES: u64 = 16 * 1024;
pub(crate) struct ChromeProc {
child: ChromeChild,
pub _watchdog: Option<OwnedChild>,
pub ws_url: String,
pub stderr_tail: StderrTail,
#[cfg(windows)]
pipe_io: Option<WindowsAuxiliaryIo>,
#[cfg(windows)]
pipe_bridge: Option<crate::pipe_transport::PipeBridge>,
#[cfg(windows)]
fixture_log: Option<std::path::PathBuf>,
#[cfg(windows)]
launch_params: String,
#[cfg(windows)]
acl_targets: Vec<std::path::PathBuf>,
}
enum ChromeChild {
Owned(OwnedChild),
#[cfg(windows)]
Confined(SandboxedChild),
}
impl ChromeChild {
fn id(&self) -> u32 {
match self {
Self::Owned(child) => child.id(),
#[cfg(windows)]
Self::Confined(child) => child.id(),
}
}
fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
match self {
Self::Owned(child) => child.try_wait(),
#[cfg(windows)]
Self::Confined(child) => child.try_wait(),
}
}
fn has_exited(&self) -> std::io::Result<bool> {
match self {
Self::Owned(child) => child.process_handle()?.wait_exited_timeout(Duration::ZERO),
#[cfg(windows)]
Self::Confined(child) => child.has_exited(),
}
}
#[cfg(windows)]
fn observed_exit_code(&self) -> std::io::Result<Option<u32>> {
match self {
Self::Owned(_) => Ok(None),
Self::Confined(child) => child.observed_exit_code(),
}
}
fn terminate_tree_bounded(
&mut self,
timeout: Duration,
) -> std::io::Result<rightkit_child_process::ReapOutcome> {
match self {
Self::Owned(child) => child.terminate_tree_bounded(timeout),
#[cfg(windows)]
Self::Confined(child) => child.terminate_tree_bounded(timeout),
}
}
#[cfg(unix)]
fn wait_or_kill(&mut self, grace: Duration) -> std::io::Result<()> {
match self {
Self::Owned(child) => child.wait_or_kill(grace).map(|_| ()),
#[cfg(windows)]
Self::Confined(child) => match child.terminate_tree_bounded(grace)? {
rightkit_child_process::ReapOutcome::Exited(_) => Ok(()),
rightkit_child_process::ReapOutcome::TimedOut => Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"confined browser process tree did not exit",
)),
},
}
}
}
#[derive(Clone, Default)]
pub(crate) struct StderrTail(std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<String>>>);
impl StderrTail {
const LINES: usize = 30;
const LINE_CHARS: usize = 300;
fn push(&self, line: &str) {
let line = line.trim();
if line.is_empty() {
return;
}
let mut lines = self.0.lock().unwrap_or_else(|e| e.into_inner());
if lines.len() == Self::LINES {
lines.pop_front();
}
lines.push_back(line.chars().take(Self::LINE_CHARS).collect());
}
pub(crate) fn text(&self) -> String {
let lines = self.0.lock().unwrap_or_else(|e| e.into_inner());
if lines.is_empty() {
"(nothing)".into()
} else {
lines.iter().cloned().collect::<Vec<_>>().join(" | ")
}
}
}
impl ChromeProc {
pub(crate) fn terminate_gracefully(&mut self, grace: Duration) -> std::io::Result<()> {
#[cfg(unix)]
{
if !matches!(self.child.try_wait(), Ok(Some(_))) {
self.child.wait_or_kill(grace)?;
}
}
#[cfg(not(unix))]
{
let _ = grace;
match self.child.terminate_tree_bounded(Duration::from_secs(2))? {
rightkit_child_process::ReapOutcome::Exited(_) => {}
rightkit_child_process::ReapOutcome::TimedOut => {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"browser process tree did not exit after termination",
));
}
}
}
if let Some(w) = self._watchdog.as_mut() {
w.wait_or_kill(Duration::from_secs(1))?;
}
Ok(())
}
pub(crate) fn terminate_fixture_tree(&mut self) -> std::io::Result<()> {
match self.child.terminate_tree_bounded(Duration::from_secs(5))? {
rightkit_child_process::ReapOutcome::Exited(_) => {}
rightkit_child_process::ReapOutcome::TimedOut => {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"fixture browser process tree did not stop",
));
}
}
if let Some(watchdog) = self._watchdog.as_mut() {
watchdog.wait_or_kill(Duration::from_secs(1))?;
}
Ok(())
}
pub(crate) fn id(&self) -> u32 {
self.child.id()
}
pub(crate) fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
self.child.try_wait()
}
pub(crate) fn has_exited(&self) -> std::io::Result<bool> {
self.child.has_exited()
}
#[cfg(windows)]
pub(crate) fn fixture_diagnostics(&self) -> String {
let live_exit = match self.has_exited() {
Ok(exited) => exited.to_string(),
Err(error) => format!("unavailable ({error})"),
};
let exit_code = match self.child.observed_exit_code() {
Ok(Some(code)) => describe_exit_code(code),
Ok(None) => "running".into(),
Err(error) => format!("unavailable ({error})"),
};
let acls = self
.acl_targets
.iter()
.filter(|path| !path.as_os_str().is_empty())
.map(|path| format!("{} => {}", path.display(), icacls_summary(path)))
.collect::<Vec<_>>()
.join(" | ");
let log_tail = self
.fixture_log
.as_ref()
.and_then(|path| bounded_file_tail(path).ok())
.unwrap_or_else(|| "(chrome stderr file unavailable)".into());
format!(
"windows fixture diagnostic chrome_exited={live_exit}; chrome_exit_code={exit_code}; \
{launch_params}; acls=[{acls}]; chrome_stderr_tail (stdout+stderr inherited file \
chrome-stderr.txt)={log_tail}",
launch_params = self.launch_params,
)
}
#[cfg(windows)]
pub(crate) fn start_fixture_pipe_bridge(
&mut self,
deadline: std::time::Instant,
) -> Result<String> {
let io = self.pipe_io.take().ok_or_else(|| {
BrowserError::Launch("Windows fixture CDP pipe ownership is absent".into())
})?;
let (to_child, from_child) = io.into_parent_handles();
let bridge = crate::pipe_transport::PipeBridge::start(to_child, from_child, deadline)?;
let url = bridge.websocket_url().to_owned();
self.pipe_bridge = Some(bridge);
Ok(url)
}
#[cfg(windows)]
pub(crate) fn begin_fixture_transport_shutdown(&self) {
if let Some(bridge) = &self.pipe_bridge {
bridge.begin_shutdown();
}
}
#[cfg(windows)]
pub(crate) async fn finish_fixture_transport_shutdown(
&mut self,
deadline: std::time::Instant,
) -> Result<()> {
let bridge = self.pipe_bridge.as_mut().ok_or_else(|| {
BrowserError::Launch("Windows fixture transport ownership is absent".into())
})?;
bridge.shutdown(deadline).await
}
#[cfg(not(windows))]
pub(crate) fn begin_fixture_transport_shutdown(&self) {}
}
#[cfg(windows)]
pub(crate) type CallerJob = Option<std::sync::Arc<std::os::windows::io::OwnedHandle>>;
#[cfg(not(windows))]
pub(crate) type CallerJob = Option<std::convert::Infallible>;
pub(crate) fn profile_arg(path: &Path) -> OsString {
let mut arg = OsString::from("--user-data-dir=");
arg.push(path.as_os_str());
arg
}
fn chrome_command(exe: &Path, args: &[OsString]) -> OwnedCommand {
let mut cmd = OwnedCommand::new(exe);
cmd.windows_hide();
cmd.command_mut()
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped());
cmd
}
#[cfg_attr(not(any(target_os = "macos", windows)), allow(dead_code))]
pub(crate) fn fixture_chrome_args(args: &[OsString]) -> Vec<OsString> {
let mut fixture_args = args.to_vec();
if !fixture_args.iter().any(|arg| arg == "--no-sandbox") {
fixture_args.push("--no-sandbox".into());
}
for flag in [
"--disable-gpu",
"--disable-crash-reporter",
"--disable-breakpad",
] {
if !fixture_args.iter().any(|arg| arg == flag) {
fixture_args.push(flag.into());
}
}
if !fixture_args
.iter()
.any(|arg| arg.to_string_lossy().starts_with("--disable-features="))
{
fixture_args.push("--disable-features=RendererCodeIntegrity".into());
}
fixture_args
}
pub(crate) fn spawn_chrome(
exe: &Path,
args: &[OsString],
timeout: Duration,
job: CallerJob,
) -> Result<ChromeProc> {
spawn_chrome_command(chrome_command(exe, args), timeout, job)
}
#[cfg(target_os = "macos")]
pub(crate) fn spawn_chrome_fixture(
exe: &Path,
args: &[OsString],
timeout: Duration,
profile_dir: &Path,
proxy_addr: std::net::SocketAddr,
) -> Result<ChromeProc> {
use rightkit_sandbox::seatbelt::{BrowserFixturePolicy, Prepared};
use std::os::unix::process::CommandExt;
let policy = BrowserFixturePolicy {
chrome_executable: exe.to_path_buf(),
profile_dir: profile_dir.to_path_buf(),
proxy_addr,
};
let prepared = Prepared::for_browser_fixture(&policy).map_err(|error| {
BrowserError::Launch(format!("fixture confinement unavailable: {error}"))
})?;
let fixture_args = fixture_chrome_args(args);
let mut cmd = chrome_command(exe, &fixture_args);
cmd.env_allowlist(std::iter::empty::<&str>());
cmd.command_mut()
.env("HOME", profile_dir)
.env("TMPDIR", profile_dir)
.env("TMP", profile_dir)
.env("TEMP", profile_dir);
cmd.inherit_handles_only(std::iter::empty());
unsafe {
cmd.command_mut().pre_exec(move || prepared.apply());
}
spawn_chrome_command(cmd, timeout, None)
}
fn spawn_chrome_command(
#[cfg_attr(not(windows), allow(unused_mut))] mut cmd: OwnedCommand,
timeout: Duration,
job: CallerJob,
) -> Result<ChromeProc> {
#[cfg(windows)]
if let Some(job) = &job {
use std::os::windows::io::AsHandle;
cmd.windows_job(job.as_handle())
.map_err(|e| BrowserError::Launch(e.to_string()))?;
}
#[cfg(not(windows))]
let _ = job;
let mut child = cmd
.spawn()
.map_err(|e| BrowserError::Launch(e.to_string()))?;
let stderr = child
.take_stderr()
.ok_or_else(|| BrowserError::Launch("no stderr".into()))?;
let (tx, rx) = std::sync::mpsc::channel::<String>();
let stderr_tail = StderrTail::default();
let tail = stderr_tail.clone();
std::thread::spawn(move || {
let mut reader = BufReader::new(stderr);
let mut line = Vec::new();
loop {
line.clear();
match reader.read_until(b'\n', &mut line) {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
let text = String::from_utf8_lossy(&line);
if let Some(u) = text.split("DevTools listening on ").nth(1) {
let _ = tx.send(u.trim().to_string());
} else {
tail.push(&text);
}
}
});
let ws_url = match rx.recv_timeout(timeout) {
Ok(url) => url,
Err(_) => {
std::thread::sleep(Duration::from_millis(200));
let exit = match child.try_wait() {
Ok(Some(status)) => format!("exited with {status}"),
Ok(None) => "still running".to_string(),
Err(error) => format!("status unavailable: {error}"),
};
return Err(BrowserError::Launch(format!(
"chrome did not report a DevTools endpoint; process {exit}; stderr: {}",
stderr_tail.text()
)));
}
};
let watchdog = spawn_watchdog(child.id());
Ok(ChromeProc {
child: ChromeChild::Owned(child),
_watchdog: watchdog,
ws_url,
stderr_tail,
#[cfg(windows)]
pipe_io: None,
#[cfg(windows)]
pipe_bridge: None,
#[cfg(windows)]
fixture_log: None,
#[cfg(windows)]
launch_params: String::new(),
#[cfg(windows)]
acl_targets: Vec::new(),
})
}
#[cfg(windows)]
pub(crate) fn spawn_chrome_fixture_windows(
exe: &Path,
args: &[OsString],
profile_dir: &Path,
) -> Result<ChromeProc> {
let args: Vec<OsString> = fixture_chrome_args(args)
.into_iter()
.filter(|arg| !arg.to_string_lossy().starts_with("--headless"))
.collect();
let args = args.as_slice();
let log_path = profile_dir.join("chrome-stderr.txt");
let policy = SandboxPolicy::new()
.allow_exec(exe)
.allow_write(profile_dir)
.network(SandboxNetworkPolicy::Deny)
.env(EnvPolicy {
inherit: false,
keep: FIXTURE_ENV_KEEP.iter().map(|k| k.to_string()).collect(),
set: FIXTURE_ENV_SET
.iter()
.map(|k| (k.to_string(), profile_dir.to_string_lossy().into_owned()))
.collect(),
});
let policy = FIXTURE_NAMED_CAPABILITIES
.iter()
.fold(policy, |policy, name| policy.named_capability(*name));
let command = SandboxCommand::new(exe)
.args(args.iter().cloned())
.args(FIXTURE_LOGGING_ARGS);
let launch_params = fixture_launch_params(exe, args, profile_dir);
let sandbox = Sandbox::new(ResourceAuthority::new(ResourceProfile::Practical));
let spawn = sandbox
.spawn_with_pipe_pair_stdio_file(
&policy,
command,
"--remote-debugging-io-pipes",
Some(&log_path),
)
.map_err(|error| {
BrowserError::Launch(format!(
"Windows fixture AppContainer: {error}; {launch_params}"
))
})?;
Ok(ChromeProc {
child: ChromeChild::Confined(spawn.child),
_watchdog: None,
ws_url: String::new(),
stderr_tail: StderrTail::default(),
pipe_io: Some(spawn.io),
pipe_bridge: None,
fixture_log: Some(log_path),
launch_params,
acl_targets: vec![
profile_dir.to_path_buf(),
exe.parent().map(Path::to_path_buf).unwrap_or_default(),
],
})
}
#[cfg(windows)]
const FIXTURE_LOGGING_ARGS: [&str; 2] = ["--enable-logging=stderr", "--v=1"];
#[cfg(windows)]
const FIXTURE_ENV_KEEP: [&str; 2] = ["SystemRoot", "windir"];
#[cfg(windows)]
const FIXTURE_ENV_SET: [&str; 5] = ["TEMP", "TMP", "LOCALAPPDATA", "APPDATA", "USERPROFILE"];
#[cfg(windows)]
const FIXTURE_NAMED_CAPABILITIES: [&str; 2] = ["lpacChromeInstallFiles", "registryRead"];
#[cfg(windows)]
fn describe_exit_code(code: u32) -> String {
let meaning = match code {
0 => "success",
0xC000_0005 => "STATUS_ACCESS_VIOLATION",
0xC000_0022 => "STATUS_ACCESS_DENIED",
0xC000_0135 => "STATUS_DLL_NOT_FOUND",
0xC000_0142 => "STATUS_DLL_INIT_FAILED",
0xC000_0409 => "STATUS_STACK_BUFFER_OVERRUN (fast-fail)",
0xC000_041D => "STATUS_FATAL_USER_CALLBACK_EXCEPTION",
0x8000_0003 => "breakpoint (Chrome CHECK/fatal)",
_ => "unclassified",
};
format!("{code} (0x{code:08X}, {meaning})")
}
#[cfg(windows)]
fn fixture_launch_params(exe: &Path, args: &[OsString], profile_dir: &Path) -> String {
let flags: Vec<String> = args
.iter()
.map(|arg| arg.to_string_lossy().into_owned())
.filter(|arg| arg.starts_with("--") && !arg.starts_with("--user-data-dir"))
.collect();
let has = |name: &str| {
flags
.iter()
.any(|flag| flag == name || flag.starts_with(&format!("{name}=")))
};
format!(
"launch_params{{exe={}, exec_grant={}, write_grant={}, network=Deny, \
capabilities=[{}] (no internetClient), \
env=[inherit=false; kept {}; set to write grant {}; sandbox adds ComSpec Path SystemDrive \
SystemRoot windir LOCALAPPDATA TEMP TMP NODE_OPTIONS], no_sandbox={}, disable_gpu={}, headless={}, flags=[{}]}}",
exe.display(),
exe.display(),
profile_dir.display(),
FIXTURE_NAMED_CAPABILITIES.join(", "),
FIXTURE_ENV_KEEP.join(","),
FIXTURE_ENV_SET.join(","),
has("--no-sandbox"),
has("--disable-gpu"),
flags.iter().any(|flag| flag.starts_with("--headless"))
|| exe
.file_name()
.is_some_and(|name| name.to_string_lossy().contains("headless-shell")),
flags.join(" "),
)
}
#[cfg(windows)]
fn icacls_summary(path: &Path) -> String {
use std::os::windows::process::CommandExt;
match std::process::Command::new("icacls")
.creation_flags(0x0800_0000) .arg(path)
.stdin(Stdio::null())
.output()
{
Ok(output) => {
let text = String::from_utf8_lossy(&output.stdout);
let joined = text.split_whitespace().collect::<Vec<_>>().join(" ");
joined.chars().take(1500).collect()
}
Err(error) => format!("icacls unavailable ({error})"),
}
}
#[cfg(windows)]
fn bounded_file_tail(path: &Path) -> std::io::Result<String> {
let mut reader = File::open(path)?;
let length = reader.metadata()?.len();
reader.seek(SeekFrom::Start(
length.saturating_sub(FIXTURE_LOG_TAIL_BYTES),
))?;
let mut bytes = Vec::with_capacity(FIXTURE_LOG_TAIL_BYTES as usize);
reader
.take(FIXTURE_LOG_TAIL_BYTES)
.read_to_end(&mut bytes)?;
if bytes.is_empty() {
Ok("(chrome stderr file empty: Chrome wrote nothing before dying)".into())
} else {
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
}
#[cfg(unix)]
fn spawn_watchdog(chrome_pgid: u32) -> Option<OwnedChild> {
let script = r#"while kill -0 "$1" 2>/dev/null && kill -0 "$2" 2>/dev/null; do sleep 0.2; done
if kill -0 "$2" 2>/dev/null; then
kill -TERM -- "-$2" 2>/dev/null
i=0
while [ "$i" -lt 25 ] && kill -0 -- "-$2" 2>/dev/null; do sleep 0.2; i=$((i+1)); done
kill -KILL -- "-$2" 2>/dev/null
fi
exit 0"#;
let mut cmd = OwnedCommand::new("/bin/sh");
cmd.command_mut()
.args([
"-c",
script,
"rk-watchdog",
&std::process::id().to_string(),
&chrome_pgid.to_string(),
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
cmd.spawn().ok()
}
#[cfg(not(unix))]
fn spawn_watchdog(_chrome_pid: u32) -> Option<OwnedChild> {
None
}