use crate::error::{BrowserError, Result};
use crate::pipe_transport::{ParentPipes, PipeBridge};
use rightkit_child_process::{OwnedChild, OwnedCommand};
#[cfg(windows)]
use rightkit_sandbox::{
EnvPolicy, NetworkPolicy as SandboxNetworkPolicy, ResourceAuthority, ResourceProfile, Sandbox,
SandboxCommand, SandboxPolicy, SandboxedChild,
};
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 stderr_tail: StderrTail,
pipe_parent: Option<ParentPipes>,
pipe_bridge: Option<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<()> {
self.begin_transport_shutdown();
#[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,
)
}
pub(crate) fn launch_detail(&mut self) -> String {
let exit = match self.child.try_wait() {
Ok(Some(status)) => format!("exited with {status}"),
Ok(None) => "still running".to_string(),
Err(error) => format!("status unavailable: {error}"),
};
#[cfg(windows)]
if self.fixture_log.is_some() {
return format!("process {exit}; {}", self.fixture_diagnostics());
}
format!("process {exit}; stderr: {}", self.stderr_tail.text())
}
pub(crate) fn start_pipe_bridge(
&mut self,
handshake_deadline: std::time::Instant,
relay_deadline: Option<std::time::Instant>,
) -> Result<String> {
let (to_child, from_child) = self
.pipe_parent
.take()
.ok_or_else(|| BrowserError::Launch("CDP pipe ownership is absent".into()))?;
let bridge = PipeBridge::start(to_child, from_child, handshake_deadline, relay_deadline)?;
let url = bridge.websocket_url().to_owned();
self.pipe_bridge = Some(bridge);
Ok(url)
}
pub(crate) fn begin_transport_shutdown(&self) {
if let Some(bridge) = &self.pipe_bridge {
bridge.begin_shutdown();
}
}
pub(crate) async fn finish_transport_shutdown(
&mut self,
deadline: std::time::Instant,
) -> Result<()> {
let bridge = self
.pipe_bridge
.as_mut()
.ok_or_else(|| BrowserError::Launch("CDP transport ownership is absent".into()))?;
bridge.shutdown(deadline).await
}
}
struct ChildEnds {
#[cfg(unix)]
_held: Vec<std::os::fd::OwnedFd>,
#[cfg(windows)]
_held: Vec<std::os::windows::io::OwnedHandle>,
}
struct DevtoolsPipe {
parent: ParentPipes,
child: ChildEnds,
#[cfg(windows)]
child_values: (u32, u32),
#[cfg(unix)]
child_fds: (std::os::fd::RawFd, std::os::fd::RawFd),
}
#[cfg(unix)]
const CHROME_READ_FD: std::os::fd::RawFd = 3;
#[cfg(unix)]
const CHROME_WRITE_FD: std::os::fd::RawFd = 4;
#[cfg(unix)]
const FIRST_PARENT_FD: std::os::fd::RawFd = 5;
#[cfg(unix)]
fn devtools_pipe() -> Result<DevtoolsPipe> {
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
fn launch(error: std::io::Error) -> BrowserError {
BrowserError::Launch(format!("DevTools pipe: {error}"))
}
fn lift(fd: OwnedFd) -> Result<OwnedFd> {
let lifted = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, FIRST_PARENT_FD) };
if lifted < 0 {
return Err(launch(std::io::Error::last_os_error()));
}
Ok(unsafe { OwnedFd::from_raw_fd(lifted) })
}
let mut held = Vec::new();
for _ in 0..=FIRST_PARENT_FD {
let placeholder = OwnedFd::from(std::fs::File::open("/dev/null").map_err(launch)?);
let above = placeholder.as_raw_fd() >= FIRST_PARENT_FD;
held.push(placeholder);
if above {
break;
}
}
let (command_read, command_write) = std::io::pipe().map_err(launch)?;
let (reply_read, reply_write) = std::io::pipe().map_err(launch)?;
let child_read = lift(OwnedFd::from(command_read))?;
let to_child = lift(OwnedFd::from(command_write))?;
let from_child = lift(OwnedFd::from(reply_read))?;
let child_write = lift(OwnedFd::from(reply_write))?;
let child_fds = (child_read.as_raw_fd(), child_write.as_raw_fd());
held.push(child_read);
held.push(child_write);
Ok(DevtoolsPipe {
parent: (to_child, from_child),
child: ChildEnds { _held: held },
child_fds,
})
}
#[cfg(windows)]
mod win32 {
use std::ffi::c_void;
#[link(name = "kernel32")]
extern "system" {
pub fn CreateNamedPipeW(
name: *const u16,
open_mode: u32,
pipe_mode: u32,
max_instances: u32,
out_buffer_size: u32,
in_buffer_size: u32,
default_timeout: u32,
attributes: *const c_void,
) -> *mut c_void;
pub fn CreateFileW(
name: *const u16,
desired_access: u32,
share_mode: u32,
security: *const c_void,
creation_disposition: u32,
flags_and_attributes: u32,
template: *mut c_void,
) -> *mut c_void;
}
pub const PIPE_ACCESS_INBOUND: u32 = 0x0000_0001;
pub const PIPE_ACCESS_OUTBOUND: u32 = 0x0000_0002;
pub const FILE_FLAG_OVERLAPPED: u32 = 0x4000_0000;
pub const FILE_FLAG_FIRST_PIPE_INSTANCE: u32 = 0x0008_0000;
pub const PIPE_REJECT_REMOTE_CLIENTS: u32 = 0x0000_0008;
pub const GENERIC_READ: u32 = 0x8000_0000;
pub const GENERIC_WRITE: u32 = 0x4000_0000;
pub const OPEN_EXISTING: u32 = 3;
pub const INVALID_HANDLE_VALUE: isize = -1;
}
#[cfg(windows)]
fn windows_pipe(
parent_reads: bool,
) -> Result<(
std::os::windows::io::OwnedHandle,
std::os::windows::io::OwnedHandle,
)> {
use std::os::windows::io::{FromRawHandle, OwnedHandle};
use std::sync::atomic::{AtomicU64, Ordering};
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
let mut random = [0u8; 16];
getrandom::fill(&mut random)
.map_err(|error| BrowserError::Launch(format!("DevTools pipe random source: {error}")))?;
let name: Vec<u16> = format!(
r"\\.\pipe\rightkit-browser-cdp-{}-{}-{}",
std::process::id(),
SEQUENCE.fetch_add(1, Ordering::Relaxed),
crate::pipe_transport::hex(&random)
)
.encode_utf16()
.chain(std::iter::once(0))
.collect();
let (server_access, client_access) = if parent_reads {
(win32::PIPE_ACCESS_INBOUND, win32::GENERIC_WRITE)
} else {
(win32::PIPE_ACCESS_OUTBOUND, win32::GENERIC_READ)
};
let server = unsafe {
win32::CreateNamedPipeW(
name.as_ptr(),
server_access | win32::FILE_FLAG_OVERLAPPED | win32::FILE_FLAG_FIRST_PIPE_INSTANCE,
win32::PIPE_REJECT_REMOTE_CLIENTS,
1,
64 * 1024,
64 * 1024,
0,
std::ptr::null(),
)
};
if server.is_null() || server as isize == win32::INVALID_HANDLE_VALUE {
return Err(BrowserError::Launch(format!(
"DevTools pipe CreateNamedPipeW: {}",
std::io::Error::last_os_error()
)));
}
let server = unsafe { OwnedHandle::from_raw_handle(server) };
let client = unsafe {
win32::CreateFileW(
name.as_ptr(),
client_access,
0,
std::ptr::null(),
win32::OPEN_EXISTING,
0,
std::ptr::null_mut(),
)
};
if client.is_null() || client as isize == win32::INVALID_HANDLE_VALUE {
return Err(BrowserError::Launch(format!(
"DevTools pipe client open: {}",
std::io::Error::last_os_error()
)));
}
Ok((server, unsafe { OwnedHandle::from_raw_handle(client) }))
}
#[cfg(windows)]
fn devtools_pipe() -> Result<DevtoolsPipe> {
use std::os::windows::io::AsRawHandle;
let (to_child, child_read) = windows_pipe(false)?;
let (from_child, child_write) = windows_pipe(true)?;
let value = |handle: &std::os::windows::io::OwnedHandle| {
u32::try_from(handle.as_raw_handle() as usize)
.map_err(|_| BrowserError::Launch("DevTools pipe handle does not fit in u32".into()))
};
let child_values = (value(&child_read)?, value(&child_write)?);
Ok(DevtoolsPipe {
parent: (to_child, from_child),
child: ChildEnds {
_held: vec![child_read, child_write],
},
child_values,
})
}
#[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], pipe: &DevtoolsPipe) -> OwnedCommand {
let mut cmd = OwnedCommand::new(exe);
cmd.windows_hide();
#[cfg(any(target_os = "linux", target_os = "macos"))]
cmd.kill_on_parent_exit(true);
#[cfg(windows)]
let pipe_flag = [OsString::from(format!(
"--remote-debugging-io-pipes={},{}",
pipe.child_values.0, pipe.child_values.1
))];
#[cfg(not(windows))]
let pipe_flag: [OsString; 0] = [];
cmd.command_mut()
.args(pipe_flag)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped());
#[cfg(unix)]
{
let (read_fd, write_fd) = pipe.child_fds;
unsafe {
cmd.pre_exec_last(move || {
dup_onto(read_fd, CHROME_READ_FD)?;
dup_onto(write_fd, CHROME_WRITE_FD)
});
}
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
cmd.windows_spawn_config(rightkit_child_process::WindowsSpawnConfig {
stdin: rightkit_child_process::WindowsStdio::Null,
stdout: rightkit_child_process::WindowsStdio::Null,
stderr: rightkit_child_process::WindowsStdio::Piped,
inherit_environment: true,
raw_arguments: Vec::new(),
});
let mut inherited = Vec::new();
for handle in &pipe.child._held {
inherited.push(handle.as_raw_handle());
}
cmd.inherit_handles_only(inherited);
}
cmd
}
#[cfg(unix)]
fn dup_onto(from: std::os::fd::RawFd, to: std::os::fd::RawFd) -> std::io::Result<()> {
loop {
if unsafe { libc::dup2(from, to) } >= 0 {
return Ok(());
}
let error = std::io::Error::last_os_error();
if error.raw_os_error() != Some(libc::EINTR) {
return Err(error);
}
}
}
#[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], job: CallerJob) -> Result<ChromeProc> {
let pipe = devtools_pipe()?;
let cmd = chrome_command(exe, args, &pipe);
spawn_chrome_command(cmd, pipe, job)
}
#[cfg(target_os = "macos")]
pub(crate) fn spawn_chrome_fixture(
exe: &Path,
args: &[OsString],
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 pipe = devtools_pipe()?;
let mut cmd = chrome_command(exe, &fixture_args, &pipe);
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, pipe, None)
}
type LauncherJob = Box<dyn FnOnce() + Send>;
static LAUNCHER: std::sync::OnceLock<std::sync::mpsc::Sender<LauncherJob>> =
std::sync::OnceLock::new();
fn launcher_sender() -> std::io::Result<&'static std::sync::mpsc::Sender<LauncherJob>> {
if let Some(sender) = LAUNCHER.get() {
return Ok(sender);
}
let (tx, rx) = std::sync::mpsc::channel::<LauncherJob>();
std::thread::Builder::new()
.name("rightkit-browser-launcher".into())
.spawn(move || {
while let Ok(job) = rx.recv() {
job();
}
})?;
let _ = LAUNCHER.set(tx);
LAUNCHER.get().ok_or_else(launcher_gone)
}
fn launcher_gone() -> std::io::Error {
std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"browser launcher thread is gone",
)
}
fn run_on_launcher_thread<T: Send + 'static>(
job: impl FnOnce() -> T + Send + 'static,
) -> std::io::Result<T> {
let sender = launcher_sender()?;
let (result_tx, result_rx) = std::sync::mpsc::channel::<T>();
let boxed: LauncherJob = Box::new(move || {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)) {
Ok(value) => {
let _ = result_tx.send(value);
}
Err(_) => drop(result_tx),
}
});
sender.send(boxed).map_err(|_| launcher_gone())?;
result_rx.recv().map_err(|_| launcher_gone())
}
fn spawn_chrome_command(
#[cfg_attr(not(windows), allow(unused_mut))] mut cmd: OwnedCommand,
pipe: DevtoolsPipe,
job: CallerJob,
) -> Result<ChromeProc> {
let DevtoolsPipe {
parent: pipe_parent,
child: child_ends,
..
} = pipe;
#[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 = run_on_launcher_thread(move || {
let spawned = cmd.spawn();
drop(child_ends);
spawned
})
.map_err(|e| BrowserError::Launch(e.to_string()))?
.map_err(|e| BrowserError::Launch(e.to_string()))?;
let stderr = child
.take_stderr()
.ok_or_else(|| BrowserError::Launch("no stderr".into()))?;
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(_) => {}
}
tail.push(&String::from_utf8_lossy(&line));
}
});
let watchdog = spawn_watchdog(child.id());
Ok(ChromeProc {
child: ChromeChild::Owned(child),
_watchdog: watchdog,
stderr_tail,
pipe_parent: Some(pipe_parent),
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,
stderr_tail: StderrTail::default(),
pipe_parent: Some(spawn.io.into_parent_handles()),
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
}