use std::{
ffi::{OsStr, OsString},
io,
os::windows::{io::AsRawHandle, process::CommandExt},
process::{Child, Command},
};
use tokio::signal::windows::{ctrl_break, ctrl_c, CtrlBreak, CtrlC};
use windows_sys::Win32::{
Foundation::{SetHandleInformation, HANDLE, HANDLE_FLAG_INHERIT},
System::Threading::{CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW},
};
use super::pipe::{self, Opened, PipeServer};
use crate::daemon::paths::DaemonPaths;
pub(in crate::daemon) const MACHINE_VARIABLES: &[&str] = &[
"USERPROFILE",
"HOMEDRIVE",
"HOMEPATH",
"HOME",
"USERNAME",
"USERDOMAIN",
"APPDATA",
"LOCALAPPDATA",
"PROGRAMDATA",
"ALLUSERSPROFILE",
"PUBLIC",
"ProgramFiles",
"ProgramFiles(x86)",
"ProgramW6432",
"CommonProgramFiles",
"CommonProgramFiles(x86)",
"CommonProgramW6432",
"SystemRoot",
"SystemDrive",
"windir",
"OS",
"PROCESSOR_ARCHITECTURE",
"NUMBER_OF_PROCESSORS",
"PATH",
"PATHEXT",
"COMSPEC",
"PSModulePath",
"TEMP",
"TMP",
"XDG_CACHE_HOME",
"XDG_CONFIG_HOME",
"GIT_CONFIG_GLOBAL",
"LANG",
"LC_ALL",
"LC_CTYPE",
"TZ",
];
pub(in crate::daemon) fn is_variable(name: &str, listed: &str) -> bool {
name.eq_ignore_ascii_case(listed)
}
pub(in crate::daemon) fn spawn_detached(
command: &mut Command,
paths: &DaemonPaths,
) -> io::Result<Child> {
for stream in [
io::stdin().as_raw_handle(),
io::stdout().as_raw_handle(),
io::stderr().as_raw_handle(),
] {
unsafe { SetHandleInformation(stream as HANDLE, HANDLE_FLAG_INHERIT, 0) };
}
command
.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)
.current_dir(&paths.home);
command.spawn()
}
fn stop_pipe(paths: &DaemonPaths) -> OsString {
let mut name = paths.socket.clone().into_os_string();
name.push("-stop");
name
}
pub(in crate::daemon) fn request_stop(paths: &DaemonPaths, _pid: u32) -> io::Result<()> {
let pipe = stop_pipe(paths);
match pipe::probe(&pipe)? {
Opened::Client(_) => Ok(()),
Opened::Missing => Err(io::Error::new(
io::ErrorKind::NotFound,
format!(
"the rho daemon is not listening for a stop on {}",
pipe.display()
),
)),
Opened::Busy => Ok(()),
Opened::Foreign => Err(pipe::foreign(&pipe)),
}
}
pub(crate) struct StopRequests {
pipe: Option<PipeServer>,
ctrl_c: CtrlC,
ctrl_break: CtrlBreak,
}
impl StopRequests {
pub(crate) fn listen(paths: &DaemonPaths) -> io::Result<Self> {
Ok(Self {
pipe: Some(PipeServer::create(&stop_pipe(paths))?),
ctrl_c: ctrl_c()?,
ctrl_break: ctrl_break()?,
})
}
pub(crate) async fn recv(&mut self) -> &'static str {
loop {
let asked = async {
match &mut self.pipe {
Some(pipe) => pipe.accept().await.map(drop),
None => std::future::pending().await,
}
};
tokio::select! {
asked = asked => match asked {
Ok(()) => return "stop request",
Err(error) => {
tracing::warn!(%error, "the stop pipe failed; only a protocol request or the console stops this daemon now");
self.pipe = None;
}
},
_ = self.ctrl_c.recv() => return "Ctrl+C",
_ = self.ctrl_break.recv() => return "Ctrl+Break",
}
}
}
}
pub(crate) fn stderr_is_journal_stream(_stream: &OsStr) -> bool {
false
}