use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, Ordering};
use windows::core::{BOOL, HRESULT};
use windows::Win32::Foundation::{
ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, HANDLE, WAIT_EVENT, WAIT_FAILED, WAIT_OBJECT_0,
};
use windows::Win32::System::Console::{
AttachConsole, FreeConsole, GenerateConsoleCtrlEvent, GetConsoleProcessList, SetConsoleCtrlHandler,
CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_C_EVENT, CTRL_SHUTDOWN_EVENT,
};
use windows::Win32::System::Threading::{CreateEventW, ResetEvent, SetEvent, WaitForMultipleObjects, INFINITE};
use super::protocol::{CtrlEvent, ProxyAnswer, ProxyArgs};
use crate::error::{Error, RecordErrorKind};
use crate::identity::{Platform, ProcessId, ProcessIdRecord, RECORD_VERSION};
use crate::process::Process;
use crate::role;
pub(crate) fn run(args: &ProxyArgs) -> ProxyAnswer {
match send(args) {
Ok(()) => ProxyAnswer::Sent,
Err(answer) => answer,
}
}
fn send(args: &ProxyArgs) -> Result<(), ProxyAnswer> {
let _target = open_target(args)?;
if let Err(e) = unsafe { FreeConsole() } {
if e.code() != HRESULT::from_win32(ERROR_INVALID_HANDLE.0) {
role::line(role::PROXY, format_args!("FreeConsole before the attach failed: {e}"));
return Err(ProxyAnswer::NothingSent);
}
}
let _attached = Attached::attach(args.target)?;
let event = match args.event {
CtrlEvent::CtrlC => CTRL_C_EVENT,
CtrlEvent::CtrlBreak => CTRL_BREAK_EVENT,
};
let watch = Watch::install(event)?;
if args.event == CtrlEvent::CtrlC {
unsafe { SetConsoleCtrlHandler(None, false) }.map_err(|e| {
role::line(role::PROXY, format_args!("re-enabling Ctrl+C failed: {e}"));
ProxyAnswer::NothingSent
})?;
}
let holds = console_holds(args.caller).map_err(|e| {
role::line(
role::PROXY,
format_args!("reading the console's process list failed: {e}"),
);
ProxyAnswer::NothingSent
})?;
if holds {
return Err(ProxyAnswer::ConsoleIsCallers);
}
watch.generate(event)?;
watch.wait()
}
fn open_target(args: &ProxyArgs) -> Result<Process, ProxyAnswer> {
let record = ProcessIdRecord {
version: RECORD_VERSION,
platform: Platform::Windows,
pid: args.target,
token: args.target_key,
boot_id: None,
pid_ns: None,
token_kind: None,
};
let id = match ProcessId::try_from(&record) {
Ok(id) => id,
Err(Error::IdentityRecord {
kind: RecordErrorKind::InvalidPid,
..
}) => return Err(ProxyAnswer::TargetGone),
Err(e) => {
debug_assert!(
false,
"a Windows record of this version is refused only for its pid: {e}"
);
role::line(role::PROXY, format_args!("the target's identity is refused: {e}"));
return Err(ProxyAnswer::TargetUnreadable);
}
};
match Process::open(id) {
Ok(Some(target)) => Ok(target),
Ok(None) => Err(ProxyAnswer::TargetGone),
Err(e) => {
role::line(
role::PROXY,
format_args!(
"the target cannot be opened or its identity read: {}",
crate::error::Report(&e)
),
);
Err(ProxyAnswer::TargetUnreadable)
}
}
}
pub(super) fn answer_for_failed_attach(code: HRESULT) -> ProxyAnswer {
if code == HRESULT::from_win32(ERROR_INVALID_HANDLE.0) {
ProxyAnswer::TargetHasNoConsole
} else if code == HRESULT::from_win32(ERROR_ACCESS_DENIED.0) {
ProxyAnswer::AttachDenied
} else if code == HRESULT::from_win32(ERROR_INVALID_PARAMETER.0) {
ProxyAnswer::TargetGone
} else {
ProxyAnswer::NothingSent
}
}
struct Attached;
impl Attached {
fn attach(target: u32) -> Result<Attached, ProxyAnswer> {
match unsafe { AttachConsole(target) } {
Ok(()) => Ok(Attached),
Err(e) => {
let answer = answer_for_failed_attach(e.code());
if answer == ProxyAnswer::NothingSent {
role::line(role::PROXY, format_args!("AttachConsole({target}) failed: {e}"));
}
Err(answer)
}
}
}
}
impl Drop for Attached {
fn drop(&mut self) {
if let Err(e) = unsafe { FreeConsole() } {
role::line(role::PROXY, format_args!("FreeConsole after the answer failed: {e}"));
}
}
}
pub(crate) fn console_holds(pid: u32) -> std::io::Result<bool> {
let mut list = vec![0u32; 16];
loop {
let n = unsafe { GetConsoleProcessList(&mut list) } as usize;
if n == 0 {
return Err(std::io::Error::last_os_error());
}
if n <= list.len() {
return Ok(list[..n].contains(&pid));
}
list.resize(n, 0);
}
}
static OWN_COPY: AtomicIsize = AtomicIsize::new(0);
static WANTED: AtomicU32 = AtomicU32::new(u32::MAX);
static CLOSING_EVENT: AtomicIsize = AtomicIsize::new(0);
static CLOSING: AtomicBool = AtomicBool::new(false);
fn signal(handle: &AtomicIsize) {
let handle = handle.load(Ordering::Acquire);
if handle != 0 {
if let Err(e) = unsafe { SetEvent(HANDLE(handle as *mut c_void)) } {
role::line(role::PROXY, format_args!("SetEvent in the handler routine failed: {e}"));
}
}
}
unsafe extern "system" fn routine(event: u32) -> BOOL {
if matches!(event, CTRL_CLOSE_EVENT | CTRL_SHUTDOWN_EVENT) {
CLOSING.store(true, Ordering::Release);
signal(&CLOSING_EVENT);
loop {
std::thread::park();
}
}
if event == WANTED.load(Ordering::Acquire) {
signal(&OWN_COPY);
}
BOOL(1)
}
struct Watch {
own_copy: HANDLE,
closing: HANDLE,
}
impl Watch {
fn install(event: u32) -> Result<Watch, ProxyAnswer> {
debug_assert_eq!(OWN_COPY.load(Ordering::Relaxed), 0, "the proxy watches once");
let make = || {
unsafe { CreateEventW(None, true, false, None) }.map_err(|e| {
role::line(role::PROXY, format_args!("CreateEventW failed: {e}"));
ProxyAnswer::NothingSent
})
};
let (own_copy, closing) = (make()?, make()?);
WANTED.store(event, Ordering::Release);
OWN_COPY.store(own_copy.0 as isize, Ordering::Release);
CLOSING_EVENT.store(closing.0 as isize, Ordering::Release);
unsafe { SetConsoleCtrlHandler(Some(routine), true) }.map_err(|e| {
role::line(role::PROXY, format_args!("installing the handler routine failed: {e}"));
ProxyAnswer::NothingSent
})?;
Ok(Watch { own_copy, closing })
}
fn generate(&self, event: u32) -> Result<(), ProxyAnswer> {
unsafe { ResetEvent(self.own_copy) }.map_err(|e| {
role::line(role::PROXY, format_args!("ResetEvent failed: {e}"));
ProxyAnswer::NothingSent
})?;
if CLOSING.load(Ordering::Acquire) {
return Err(ProxyAnswer::NothingSent);
}
unsafe { GenerateConsoleCtrlEvent(event, 0) }.map_err(|e| {
role::line(role::PROXY, format_args!("GenerateConsoleCtrlEvent failed: {e}"));
ProxyAnswer::NothingSent
})
}
fn wait(&self) -> Result<(), ProxyAnswer> {
let waited = unsafe { WaitForMultipleObjects(&[self.own_copy, self.closing], false, INFINITE) };
match waited {
WAIT_OBJECT_0 => Ok(()),
w if w == WAIT_EVENT(WAIT_OBJECT_0.0 + 1) => Err(ProxyAnswer::Unconfirmed),
WAIT_FAILED => {
role::line(
role::PROXY,
format_args!("WaitForMultipleObjects failed: {}", std::io::Error::last_os_error()),
);
Err(ProxyAnswer::Unconfirmed)
}
other => {
debug_assert!(false, "WaitForMultipleObjects returned {other:?}");
role::line(role::PROXY, format_args!("WaitForMultipleObjects returned {other:?}"));
Err(ProxyAnswer::Unconfirmed)
}
}
}
}
#[cfg(test)]
#[path = "run_tests.rs"]
mod run_tests;