use std::ffi::{OsStr, OsString};
use std::sync::atomic::{AtomicBool, Ordering};
use crate::role;
use crate::stop::proxy::protocol::{ProxyAnswer, ProxyArgs};
static HELPERS_INITIALIZED: AtomicBool = AtomicBool::new(false);
pub fn init_helpers() {
#[cfg(unix)]
start(None);
#[cfg(not(unix))]
start();
}
#[doc(hidden)]
pub fn ctrl_proxy_main() -> ! {
init_helpers();
role::line(
role::PROXY,
format_args!(
"this is a helper that cosca starts, with {}={} set; run by hand it does nothing",
role::HELPER_ENV,
role::CTRL_PROXY
),
);
std::process::exit(ProxyAnswer::Usage.code())
}
pub fn helpers_initialized() -> bool {
HELPERS_INITIALIZED.load(Ordering::Relaxed)
}
#[doc(hidden)]
#[cfg(unix)]
pub fn init_helpers_with_test_hooks(hooks: &'static dyn crate::elevation::shim::ShimTestHooks) {
start(Some(hooks));
}
fn start(#[cfg(unix)] hooks: Option<&'static dyn crate::elevation::shim::ShimTestHooks>) {
HELPERS_INITIALIZED.store(true, Ordering::Relaxed);
let argv: Vec<OsString> = std::env::args_os().collect();
match helper_role() {
Some(helper) => play(&helper, &argv),
#[cfg(unix)]
None => crate::elevation::shim::run_if_invoked(&argv, hooks),
#[cfg(not(unix))]
None => {}
}
}
fn helper_role() -> Option<OsString> {
std::env::var_os(role::HELPER_ENV)
}
fn play(helper: &OsStr, argv: &[OsString]) -> ! {
if helper != role::CTRL_PROXY {
let answer = role::UNKNOWN_HELPER_ROLE;
role::line(
role::HELPER,
format_args!(
"{}: no such helper role in this build (it has {:?}); the program was not started (exit {answer})",
role::started_with(helper),
role::CTRL_PROXY
),
);
std::process::exit(answer);
}
std::process::exit(run_proxy(argv))
}
fn run_proxy(argv: &[OsString]) -> i32 {
match ProxyArgs::parse(argv) {
Ok(args) => serve(&args),
Err(e) => {
let answer = e.answer();
role::line(
role::PROXY,
format_args!(
"{}: {}; nothing was sent (exit {})",
role::started_with(OsStr::new(role::CTRL_PROXY)),
crate::error::Report(&e),
answer.code()
),
);
answer.code()
}
}
}
#[cfg(windows)]
fn serve(args: &ProxyArgs) -> i32 {
let answer = crate::stop::proxy::run::run(args);
if answer != ProxyAnswer::Sent {
role::line(
role::PROXY,
format_args!("answering {answer:?} (exit {})", answer.code()),
);
}
answer.code()
}
#[cfg(not(windows))]
fn serve(_: &ProxyArgs) -> i32 {
let answer = ProxyAnswer::NoProxyHere;
role::line(
role::PROXY,
format_args!(
"{}: this platform has no console-event proxy; nothing was sent (exit {})",
role::started_with(OsStr::new(role::CTRL_PROXY)),
answer.code()
),
);
answer.code()
}
#[cfg(test)]
#[path = "init_tests.rs"]
mod init_tests;