use std::{
ffi::OsString,
future::Future,
path::{Path, PathBuf},
process::Stdio,
time::Duration,
};
use rho_protocol::{
methods::{
HostStreamId, DAEMON_RESTART, DAEMON_UPDATE, DAEMON_UPDATE_CHECK, DAEMON_UPDATE_RESULT,
HOST_INFO,
},
Caller, ClientEnvironment, DaemonUpdateCheck, DaemonUpdateCheckParams, DaemonUpdateParams,
DaemonUpdateResponse, DaemonUpdateResult, DaemonUpdateResultParams, DeviceService, ErrorCode,
ForgeService, FsService, GitService, HostInfo, HostInfoParams, HostPath, HostService,
HostStreamWriter, RpcError, ShellService,
};
use tokio::sync::OnceCell;
use super::{
devices::Devices,
machine_forge::Web,
machine_shell::Shells,
machine_update::{self, Daemon, RhoInstall, Updates},
};
pub(super) const LOGIN_SHELL_DEADLINE: Duration = Duration::from_secs(30);
const ENV_MARKER: &str = "--rho-login-environment--";
const LOGIN_VARIABLES: &[&str] = &[
"USER",
"LOGNAME",
"PATH",
"LANG",
"LC_ALL",
"TZ",
"TMPDIR",
"XDG_RUNTIME_DIR",
];
pub(super) struct Machine {
rho_home: PathBuf,
environment: Environment,
forge_web: Web,
updates: Updates,
shells: Shells,
devices: Devices,
}
enum Environment {
Login(Login, OnceCell<(ClientEnvironment, Origin)>),
Daemon,
#[cfg(test)]
Given(ClientEnvironment),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Origin {
LoginShell,
Fallback,
Hung,
}
#[derive(Clone)]
struct Login {
home: PathBuf,
shell: PathBuf,
}
enum ShellFailed {
Hung,
Failed(String),
}
impl Machine {
pub(super) fn new(rho_home: &Path, daemon: Daemon) -> Self {
#[cfg(unix)]
let login = match crate::daemon::login_account() {
Ok(account) => Some(Login {
home: account.home,
shell: account.shell,
}),
Err(error) => {
tracing::warn!("host info names no login shell: {error:#}");
None
}
};
#[cfg(not(unix))]
let login = None;
Self::with_login(rho_home, login, daemon)
}
#[cfg(test)]
pub(super) fn without_login(rho_home: &Path) -> Self {
Self::with_login(rho_home, None, Daemon::idle())
}
#[cfg(test)]
pub(super) fn with_environment(rho_home: &Path, environment: ClientEnvironment) -> Self {
Self::with(rho_home, Environment::Given(environment), Daemon::idle())
}
fn with_login(rho_home: &Path, login: Option<Login>, daemon: Daemon) -> Self {
let environment = match login {
Some(login) => Environment::Login(login, OnceCell::new()),
None => Environment::Daemon,
};
Self::with(rho_home, environment, daemon)
}
fn with(rho_home: &Path, environment: Environment, daemon: Daemon) -> Self {
Self {
rho_home: rho_home.to_path_buf(),
environment,
forge_web: Web::public(),
updates: Updates::new(RhoInstall, daemon),
shells: Shells::default(),
devices: Devices::default(),
}
}
pub(super) fn updates(&self) -> &Updates {
&self.updates
}
fn login(&self) -> Option<&Login> {
match &self.environment {
Environment::Login(login, _) => Some(login),
_ => None,
}
}
pub(super) fn shells(&self) -> &Shells {
&self.shells
}
pub(super) fn login_shell(&self) -> Option<PathBuf> {
Some(self.login()?.shell.clone())
}
pub(super) fn forge_web(&self) -> &Web {
&self.forge_web
}
pub(super) async fn login_environment(&self) -> ClientEnvironment {
self.login_environment_and_origin().await.0
}
pub(super) async fn login_environment_and_origin(&self) -> (ClientEnvironment, Origin) {
let (login, read) = match &self.environment {
Environment::Login(login, read) => (login, read),
Environment::Daemon => return (ClientEnvironment::of_this_process(), Origin::Fallback),
#[cfg(test)]
Environment::Given(environment) => return (environment.clone(), Origin::LoginShell),
};
let read = read
.get_or_try_init(|| async {
match login_shell_environment(login).await {
Ok(environment) => Ok((environment, Origin::LoginShell)),
Err(ShellFailed::Hung) => {
tracing::warn!(
shell = %login.shell.display(),
"the login shell printed no environment within {} s, so host info gives the one it starts from until the daemon restarts",
LOGIN_SHELL_DEADLINE.as_secs()
);
Ok((starting_environment(login), Origin::Hung))
}
Err(ShellFailed::Failed(why)) => Err(why),
}
})
.await;
match read {
Ok(read) => read.clone(),
Err(why) => {
tracing::warn!(
shell = %login.shell.display(),
"the login shell printed no environment, so host info gives the one it starts from: {why}"
);
(starting_environment(login), Origin::Fallback)
}
}
}
}
impl HostService for Machine {
fn restart_asked(&self, caller: &Caller) {
log_call(caller, DAEMON_RESTART, []);
}
async fn host_info(&self, caller: Caller, _: HostInfoParams) -> Result<HostInfo, RpcError> {
log_call(&caller, HOST_INFO, []);
let home = crate::paths::home_dir()
.or_else(|| Some(self.login()?.home.clone()))
.ok_or_else(|| {
RpcError::new(
ErrorCode::InternalError,
"neither the daemon's environment nor the passwd database names a home directory",
)
})?;
let shell = self
.login()
.map(|login| host_path(&login.shell))
.transpose()?;
Ok(HostInfo::new(
host_path(&home)?,
host_path(&self.rho_home)?,
self.login_environment().await,
)
.with_shell(shell))
}
async fn update(
&self,
caller: Caller,
params: DaemonUpdateParams,
) -> Result<DaemonUpdateResponse, RpcError> {
log_call(&caller, DAEMON_UPDATE, []);
let environment = self.login_environment().await;
self.updates.start(caller, params, environment)
}
async fn update_result(
&self,
caller: Caller,
params: DaemonUpdateResultParams,
) -> Result<DaemonUpdateResult, RpcError> {
log_call(&caller, DAEMON_UPDATE_RESULT, []);
self.updates.result(&caller, params).await
}
async fn update_check(
&self,
caller: Caller,
_: DaemonUpdateCheckParams,
) -> Result<DaemonUpdateCheck, RpcError> {
log_call(&caller, DAEMON_UPDATE_CHECK, []);
let environment = self.login_environment().await;
machine_update::check(environment).await
}
fn fs(&self) -> &impl FsService {
self
}
fn git(&self) -> &impl GitService {
self
}
fn forge(&self) -> &impl ForgeService {
self
}
fn shell(&self) -> &impl ShellService {
self
}
fn devices(&self) -> &impl DeviceService {
&self.devices
}
}
pub(super) fn log_call<'a>(
caller: &Caller,
method: &str,
paths: impl IntoIterator<Item = &'a HostPath>,
) {
let paths: Vec<&str> = paths.into_iter().map(HostPath::as_str).collect();
let paths = (!paths.is_empty()).then(|| tracing::field::debug(paths));
tracing::info!(
connection = ?caller.connection,
client = ?caller.client.name,
client_version = ?caller.client.version,
method,
paths,
"host call"
);
}
pub(super) fn log_call_counted(caller: &Caller, method: &str, paths: &[HostPath]) {
tracing::info!(
connection = ?caller.connection,
client = ?caller.client.name,
client_version = ?caller.client.version,
method,
count = paths.len(),
"host call"
);
tracing::debug!(
connection = ?caller.connection,
method,
paths = ?paths.iter().map(HostPath::as_str).collect::<Vec<_>>(),
"host call paths"
);
}
pub(super) async fn blocking<T: Send + 'static>(
work: impl FnOnce() -> T + Send + 'static,
) -> Result<T, RpcError> {
tokio::task::spawn_blocking(work).await.map_err(|error| {
RpcError::new(
ErrorCode::InternalError,
format!("the work on the daemon's machine stopped: {error}"),
)
})
}
pub(super) fn failed(message: impl Into<String>) -> RpcError {
RpcError::new(ErrorCode::HostCallFailed, message)
}
pub(super) fn spawn_stream<F>(
caller: &Caller,
write: impl FnOnce(HostStreamWriter) -> F,
) -> Result<HostStreamId, RpcError>
where
F: Future<Output = ()> + Send + 'static,
{
let writer = caller.open_stream()?;
let stream = writer.id().clone();
tokio::spawn(write(writer));
Ok(stream)
}
#[cfg(unix)]
pub(super) fn kill_group(leader: Option<u32>) {
signal_group(leader, libc::SIGKILL);
}
#[cfg(unix)]
pub(super) fn signal_group(leader: Option<u32>, signal: libc::c_int) -> bool {
let Some(group) = leader.and_then(|id| libc::pid_t::try_from(id).ok()) else {
return false;
};
unsafe { libc::killpg(group, signal) == 0 }
}
pub(super) fn absolute(path: &HostPath) -> Result<&Path, RpcError> {
let local = Path::new(path.as_str());
if local.is_absolute() {
Ok(local)
} else {
Err(RpcError::new(
ErrorCode::InvalidParams,
format!("{path} isn't an absolute path"),
))
}
}
pub(super) fn host_path(path: &Path) -> Result<HostPath, RpcError> {
path.to_str().map(HostPath::new).ok_or_else(|| {
RpcError::new(
ErrorCode::InternalError,
format!(
"{} is not UTF-8, so a host call cannot name it",
path.display()
),
)
})
}
fn starting_variables(login: &Login) -> Vec<(OsString, OsString)> {
let mut variables: Vec<(OsString, OsString)> = LOGIN_VARIABLES
.iter()
.filter_map(|name| Some((OsString::from(name), std::env::var_os(name)?)))
.collect();
variables.push(("HOME".into(), login.home.clone().into()));
variables.push(("SHELL".into(), login.shell.clone().into()));
variables
}
fn starting_environment(login: &Login) -> ClientEnvironment {
starting_variables(login)
.into_iter()
.filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
.collect()
}
#[cfg(unix)]
async fn login_shell_environment(login: &Login) -> Result<ClientEnvironment, ShellFailed> {
let script = format!("printf '\\n%s\\n' {ENV_MARKER}; env");
let child = tokio::process::Command::new(&login.shell)
.arg("-l")
.arg("-c")
.arg(script)
.env_clear()
.envs(starting_variables(login))
.current_dir(&login.home)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.process_group(0)
.kill_on_drop(true)
.spawn()
.map_err(|error| ShellFailed::Failed(format!("it did not start: {error}")))?;
let group = child.id();
let output = match tokio::time::timeout(LOGIN_SHELL_DEADLINE, child.wait_with_output()).await {
Ok(output) => output.map_err(|error| ShellFailed::Failed(error.to_string()))?,
Err(_) => {
kill_group(group);
return Err(ShellFailed::Hung);
}
};
if !output.status.success() {
return Err(ShellFailed::Failed(format!(
"it exited with {}",
output.status
)));
}
let marker = format!("\n{ENV_MARKER}\n");
let start = output
.stdout
.windows(marker.len())
.position(|window| window == marker.as_bytes())
.ok_or_else(|| ShellFailed::Failed("its output was cut short".to_owned()))?;
Ok(parse_env(&output.stdout[start + marker.len()..]))
}
#[cfg(not(unix))]
async fn login_shell_environment(_: &Login) -> Result<ClientEnvironment, ShellFailed> {
Err(ShellFailed::Failed("no login shell here".to_owned()))
}
fn parse_env(output: &[u8]) -> ClientEnvironment {
let mut variables: Vec<(String, Option<String>)> = Vec::new();
let output = output.strip_suffix(b"\n").unwrap_or(output);
for line in output.split(|&byte| byte == b'\n') {
let line = std::str::from_utf8(line).ok();
match line.and_then(|line| line.split_once('=')) {
Some((name, value)) if !name.is_empty() && !name.contains(char::is_whitespace) => {
variables.push((name.to_owned(), Some(value.to_owned())));
}
_ => {
if let Some((_, value)) = variables.last_mut() {
*value = value.take().zip(line).map(|(mut value, line)| {
value.push('\n');
value.push_str(line);
value
});
}
}
}
}
variables
.into_iter()
.filter(|(name, _)| is_name(name))
.filter_map(|(name, value)| Some((name, value?)))
.collect()
}
fn is_name(name: &str) -> bool {
let mut chars = name.chars();
chars
.next()
.is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
#[cfg(all(test, unix))]
#[path = "machine_tests.rs"]
mod tests;