use std::{
ffi::OsStr,
io::{self, Write},
os::{
fd::AsFd,
unix::{fs::MetadataExt, process::CommandExt},
},
process::Command,
time::SystemTime,
};
use tokio::signal::unix::{signal, Signal, SignalKind};
use crate::daemon::paths::DaemonPaths;
pub(in crate::daemon) const MACHINE_VARIABLES: &[&str] = &[
"HOME",
"USER",
"LOGNAME",
"PATH",
"TMPDIR",
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
"XDG_RUNTIME_DIR",
"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 == listed
}
pub(in crate::daemon) fn spawn_detached(
command: &mut Command,
paths: &DaemonPaths,
) -> io::Result<()> {
command
.process_group(0)
.current_dir("/");
#[cfg(target_os = "macos")]
if let (super::gui_login::Placement::LaunchAgent, _) = super::gui_login::new_daemon_placement()
{
match super::launch_agent::start_in_gui_login(command, paths) {
Ok(()) => return Ok(()),
Err(error) => warn_in_daemon_log(
paths,
&format!(
"could not start the rho daemon in your GUI login through launchd, so it runs in this login, where it cannot use the login keychain: {error}"
),
),
}
}
let mut child = command.spawn()?;
super::user_scope::leave_caller_unit(child.id(), paths);
std::thread::spawn(move || child.wait());
Ok(())
}
pub(super) fn warn_in_daemon_log(paths: &DaemonPaths, warning: &str) {
tracing::warn!("{warning}");
let line = format!(
"{} WARN {}: {warning}\n",
humantime::format_rfc3339_micros(SystemTime::now()),
module_path!()
);
if let Err(error) = paths
.open_log_file()
.and_then(|mut log| log.write_all(line.as_bytes()))
{
tracing::warn!(%error, log_file = %paths.log_file.display(), "could not write to the rho daemon log");
}
}
pub(in crate::daemon) fn request_stop(_paths: &DaemonPaths, pid: u32) -> io::Result<()> {
let pid = libc::pid_t::try_from(pid)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
if unsafe { libc::kill(pid, libc::SIGTERM) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub(crate) struct StopRequests {
interrupt: Signal,
terminate: Signal,
}
impl StopRequests {
pub(crate) fn listen(_paths: &DaemonPaths) -> io::Result<Self> {
Ok(Self {
interrupt: signal(SignalKind::interrupt())?,
terminate: signal(SignalKind::terminate())?,
})
}
pub(crate) async fn recv(&mut self) -> &'static str {
tokio::select! {
_ = self.interrupt.recv() => "SIGINT",
_ = self.terminate.recv() => "SIGTERM",
}
}
}
pub(crate) fn stderr_is_journal_stream(stream: &OsStr) -> bool {
let Some((device, inode)) = stream.to_str().and_then(|value| value.split_once(':')) else {
return false;
};
let (Ok(device), Ok(inode)) = (device.parse::<u64>(), inode.parse::<u64>()) else {
return false;
};
io::stderr()
.as_fd()
.try_clone_to_owned()
.and_then(|fd| std::fs::File::from(fd).metadata())
.is_ok_and(|stderr| stderr.dev() == device && stderr.ino() == inode)
}