use anyhow::{Context, Result, bail};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeCapture {
pub version: u32,
pub hwnd: String,
pub selected_tab: Option<usize>,
pub tabs: Vec<NativeTab>,
pub processes: Vec<NativeProcess>,
pub connections: Vec<NativeConnection>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeTab {
pub title: String,
pub panes: Vec<NativePane>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativePane {
pub console_pid: u32,
pub console_start_ticks: u64,
pub title: String,
pub rect: NativeRect,
pub members: Vec<u32>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeRect {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeProcess {
pub pid: u32,
pub parent_pid: u32,
pub start_ticks: u64,
pub executable: String,
pub argv: Vec<String>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeConnection {
pub pid: u32,
pub local_address: String,
pub local_port: u16,
pub remote_address: String,
pub remote_port: u16,
pub state: u32,
pub created_filetime: u64,
}
pub fn collect(window: Option<&str>) -> Result<NativeCapture> {
let capture: NativeCapture =
serde_json::from_slice(&run(window, false)?).context("invalid native capture response")?;
capture.validate()?;
Ok(capture)
}
pub fn processes() -> Result<Vec<NativeProcess>> {
let records: Vec<NativeProcess> = serde_json::from_slice(&run(None, true)?)
.context("invalid native process metadata response")?;
validate_processes(&records)?;
Ok(records)
}
fn validate_processes(records: &[NativeProcess]) -> Result<()> {
let mut seen = std::collections::HashSet::new();
if records.len() > 8192 {
bail!("native process count exceeds bound");
}
for p in records {
if p.pid == 0
|| p.parent_pid == p.pid
|| p.start_ticks == 0
|| !seen.insert(p.pid)
|| p.executable.is_empty()
|| p.argv.is_empty()
|| p.argv.len() > 4096
|| p.argv.iter().any(|a| a.len() > 131_072 || a.contains('\0'))
{
bail!("invalid or ambiguous native process identity");
}
}
Ok(())
}
impl NativeCapture {
fn validate(&self) -> Result<()> {
validate_processes(&self.processes)?;
if self.version != 1
|| self.hwnd.parse::<u64>().ok().filter(|h| *h != 0).is_none()
|| self.tabs.is_empty()
|| self.tabs.len() > 128
|| self.selected_tab.is_none_or(|i| i >= self.tabs.len())
{
bail!("invalid native terminal scope");
}
let mut seen = std::collections::HashSet::new();
for tab in &self.tabs {
if tab.panes.is_empty() || tab.panes.len() > 64 {
bail!("invalid native pane count");
}
for pane in &tab.panes {
let r = &pane.rect;
if ![r.x, r.y, r.width, r.height].iter().all(|n| n.is_finite())
|| r.width <= 0.0
|| r.height <= 0.0
|| !seen.insert(pane.console_pid)
|| !pane.members.contains(&pane.console_pid)
|| pane.members.len() > 4096
|| !self.processes.iter().any(|p| {
p.pid == pane.console_pid && p.start_ticks == pane.console_start_ticks
})
{
bail!("invalid or ambiguous native pane binding");
}
}
}
if seen.len() != self.processes.len() {
bail!("native process/pane membership mismatch");
}
if self.connections.len() > 16384
|| self.connections.iter().any(|c| {
!seen.contains(&c.pid)
|| !self.processes.iter().any(|p| {
p.pid == c.pid
&& p.start_ticks
.checked_sub(504_911_232_000_000_000)
.is_some_and(|start| c.created_filetime >= start)
&& p.executable
.rsplit(['\\', '/'])
.next()
.is_some_and(|name| name.eq_ignore_ascii_case("ssh.exe"))
})
|| c.local_address.parse::<std::net::IpAddr>().is_err()
|| c.remote_address.parse::<std::net::IpAddr>().is_err()
|| c.local_port == 0
|| c.remote_port == 0
|| c.created_filetime == 0
})
{
bail!("invalid native socket metadata");
}
Ok(())
}
}
#[cfg(not(windows))]
fn run(_window: Option<&str>, _processes_only: bool) -> Result<Vec<u8>> {
bail!("live terminal capture requires Windows");
}
#[cfg(windows)]
fn wait_for_watchdog(receipt: &serde_json::Value) -> Result<()> {
use std::ffi::c_void;
type Handle = *mut c_void;
#[repr(C)]
#[derive(Default)]
struct FileTime {
low: u32,
high: u32,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn OpenProcess(access: u32, inherit: i32, pid: u32) -> Handle;
fn GetProcessTimes(
handle: Handle,
creation: *mut FileTime,
exit: *mut FileTime,
kernel: *mut FileTime,
user: *mut FileTime,
) -> i32;
fn WaitForSingleObject(handle: Handle, milliseconds: u32) -> u32;
fn CloseHandle(handle: Handle) -> i32;
fn GetLastError() -> u32;
}
let pid = receipt
.get("pid")
.and_then(|v| v.as_u64())
.and_then(|n| u32::try_from(n).ok())
.filter(|n| *n != 0)
.context("invalid watchdog process receipt")?;
let expected = receipt
.get("start_ticks")
.and_then(|v| v.as_u64())
.context("watchdog creation identity missing")?;
unsafe {
let handle = OpenProcess(0x0010_0000 | 0x1000, 0, pid);
if handle.is_null() {
if GetLastError() == 87 {
return Ok(());
}
bail!("cannot observe selection watchdog exit");
}
struct Close(Handle);
impl Drop for Close {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
let _close = Close(handle);
let (mut creation, mut exit, mut kernel, mut user) = (
FileTime::default(),
FileTime::default(),
FileTime::default(),
FileTime::default(),
);
if GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) == 0 {
bail!("watchdog creation identity unavailable");
}
let ticks = ((u64::from(creation.high) << 32) | u64::from(creation.low))
.checked_add(504_911_232_000_000_000);
if ticks != Some(expected) {
return Ok(());
} if WaitForSingleObject(handle, 5000) != 0 {
bail!("selection watchdog did not exit after receipt");
}
}
Ok(())
}
#[cfg(windows)]
fn run(window: Option<&str>, processes_only: bool) -> Result<Vec<u8>> {
use std::os::windows::process::CommandExt;
use std::{
fs,
io::Read,
process::{Command, Stdio},
sync::mpsc,
thread,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
const OUTPUT_LIMIT: usize = 8 * 1024 * 1024;
const ERROR_LIMIT: usize = 8192;
if window.is_some_and(|w| w.len() > 32768 || w.contains(['\0', '\r', '\n'])) {
bail!("invalid Terminal window selector");
}
let root = std::env::temp_dir().join(format!(
"agent-ssh-capture-{}-{}",
std::process::id(),
SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos()
));
fs::create_dir(&root).context("cannot create private native capture directory")?;
struct Cleanup {
root: std::path::PathBuf,
remove: bool,
}
impl Drop for Cleanup {
fn drop(&mut self) {
if !self.remove {
return;
}
if let (Ok(root), Ok(temporary)) = (
self.root.canonicalize(),
std::env::temp_dir().canonicalize(),
) && root.parent() == Some(temporary.as_path())
&& root
.file_name()
.is_some_and(|n| n.to_string_lossy().starts_with("agent-ssh-capture-"))
{
let _ = std::fs::remove_dir_all(root);
}
}
}
let mut cleanup = Cleanup {
root: root.clone(),
remove: true,
};
fs::write(
root.join("capture-windows.ps1"),
include_str!("../scripts/capture-windows.ps1"),
)?;
fs::write(
root.join("console-probe.cs"),
include_str!("../scripts/console-probe.cs"),
)?;
fs::write(
root.join("selection-watchdog.cs"),
include_str!("../scripts/selection-watchdog.cs"),
)?;
let windows = std::env::var_os("SystemRoot").context("SystemRoot unavailable")?;
let powershell =
std::path::PathBuf::from(windows).join("System32/WindowsPowerShell/v1.0/powershell.exe");
let mut command = Command::new(powershell);
command
.args([
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-File",
])
.arg(root.join("capture-windows.ps1"))
.arg("-ControlDirectory")
.arg(&root)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.creation_flags(0x0800_0000);
if processes_only {
command.arg("-ProcessesOnly");
}
if let Some(selector) = window {
command.arg("-WindowSelector").arg(selector);
}
let mut child = command
.spawn()
.context("could not start native Windows metadata collector")?;
let stdout = child
.stdout
.take()
.context("collector stdout unavailable")?;
let stderr = child
.stderr
.take()
.context("collector stderr unavailable")?;
let (send, receive) = mpsc::channel();
let sender = send.clone();
thread::spawn(move || {
let mut b = Vec::new();
let r = stdout
.take((OUTPUT_LIMIT + 1) as u64)
.read_to_end(&mut b)
.map(|_| b);
let _ = sender.send((true, r));
});
thread::spawn(move || {
let mut b = Vec::new();
let r = stderr
.take((ERROR_LIMIT + 1) as u64)
.read_to_end(&mut b)
.map(|_| b);
let _ = send.send((false, r));
});
let deadline = Instant::now() + Duration::from_secs(if processes_only { 20 } else { 110 });
let mut timed_out = false;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
timed_out = true;
break child
.try_wait()?
.context("native collector did not terminate")?;
}
thread::sleep(Duration::from_millis(10));
};
if root.join("selection-watchdog-started").exists() {
let cleanup_deadline = Instant::now() + Duration::from_secs(8);
let receipt_path = root.join("selection-watchdog-receipt.json");
let receipt = loop {
if let Ok(bytes) = fs::read(&receipt_path)
&& bytes.len() <= 8192
&& let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes)
{
break Some(value);
}
if Instant::now() >= cleanup_deadline {
break None;
}
thread::sleep(Duration::from_millis(20));
};
if receipt
.as_ref()
.and_then(|r| r.get("status"))
.and_then(|s| s.as_str())
.is_none_or(|s| {
!matches!(
s,
"normal_stop_acknowledged"
| "restored"
| "no_owned_selection"
| "skipped_window_identity_changed"
| "skipped_window_missing"
| "skipped_physical_input_changed"
| "skipped_hwnd_reused"
| "skipped_selection_changed"
)
})
{
cleanup.remove = false;
bail!(
"selection cleanup failed or was not acknowledged; retained diagnostics at {}",
root.display()
);
}
if let Err(error) = wait_for_watchdog(receipt.as_ref().expect("receipt validated above")) {
cleanup.remove = false;
bail!("{}; retained diagnostics at {}", error, root.display());
}
}
if !status.success() {
const TITLE_HELPER_LEASE_GRACE: Duration = Duration::from_secs(3);
thread::sleep(TITLE_HELPER_LEASE_GRACE);
}
if timed_out {
bail!("native capture timed out; independent cleanup acknowledged");
}
let mut output = None;
let mut errors = None;
for _ in 0..2 {
let (is_stdout, bytes) = receive
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
.context("native capture output did not close before deadline")?;
let bytes = bytes?;
if is_stdout {
output = Some(bytes);
} else {
errors = Some(bytes);
}
}
let output = output.context("native capture stdout missing")?;
let errors = errors.context("native capture stderr missing")?;
if root.join("binding-diagnostic.json").is_file() {
cleanup.remove = false;
}
if output.len() > OUTPUT_LIMIT || errors.len() > ERROR_LIMIT {
bail!("native capture output exceeds bound");
}
if !status.success() {
let reason: String = String::from_utf8_lossy(&errors)
.chars()
.filter(|c| !c.is_control() || *c == '\n')
.take(4096)
.collect();
bail!("native capture failed: {}", reason.trim());
}
if !errors.is_empty() {
bail!("native capture reported an error despite successful exit");
}
Ok(output)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_only_ssh_owned_endpoint_metadata() {
let mut capture: NativeCapture = serde_json::from_value(serde_json::json!({
"version":1,"hwnd":"10","selected_tab":0,
"tabs":[{"title":"tab","panes":[{"console_pid":12,"console_start_ticks":504911232000000100u64,
"title":"pane","rect":{"x":0,"y":0,"width":100,"height":100},"members":[12]}]}],
"processes":[{"pid":12,"parent_pid":1,"start_ticks":504911232000000100u64,"executable":"codex.exe","argv":["codex.exe"]}],
"connections":[{"pid":12,"local_address":"127.0.0.1","local_port":1000,
"remote_address":"127.0.0.2","remote_port":22,"state":5,"created_filetime":101}]
})).unwrap();
assert!(capture.validate().is_err());
capture.processes[0].executable = r"C:\Windows\System32\OpenSSH\SSH.EXE".into();
capture.processes[0].argv = vec!["ssh.exe".into()];
assert!(capture.validate().is_ok());
capture.connections[0].state = 1;
assert!(capture.validate().is_ok());
capture.connections[0].created_filetime = 99;
assert!(capture.validate().is_err());
capture.connections[0].created_filetime = 101;
capture.connections.clear();
capture.processes[0].executable =
r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe".into();
capture.processes[0].argv = vec!["powershell.exe".into()];
assert!(capture.validate().is_ok());
}
#[test]
fn rejects_duplicate_pid_identity_and_unmapped_native_leaf() {
let record = r#"{"pid":12,"parent_pid":1,"start_ticks":100,"executable":"codex.exe","argv":["codex.exe"]}"#;
let duplicate: Vec<NativeProcess> =
serde_json::from_str(&format!("[{record},{record}]")).unwrap();
assert!(validate_processes(&duplicate).is_err());
let capture: NativeCapture = serde_json::from_str(&format!(r#"{{"version":1,"hwnd":"10","selected_tab":0,"tabs":[{{"title":"tab","panes":[{{"console_pid":13,"console_start_ticks":100,"title":"pane","rect":{{"x":0,"y":0,"width":100,"height":100}},"members":[13]}}]}}],"processes":[{record}],"connections":[]}}"#)).unwrap();
assert!(capture.validate().is_err());
}
}