troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
//! Linux `systemd --user` service unit rendering and installation.

use std::{
    env,
    fmt::Write as _,
    fs, io,
    path::{Path, PathBuf},
    process::{Command, ExitStatus, Stdio},
};

use crate::{error::CliError, platform};

use super::{CommandResult, ServiceResult, Systemctl};

const UNIT_FILE: &str = "troll.service";
const SYSTEMCTL: &str = "systemctl";
const RELOAD: &[&str] = &["--user", "daemon-reload"];
const ENABLE: &[&str] = &["--user", "enable", "--now", UNIT_FILE];
const CONFIG_HOME_NOTE: &str = "The systemd user manager reads units from its own config home. If `systemctl --user` cannot find troll.service, make the unit available under ~/.config/systemd/user.";

enum UnitChange {
    Unchanged,
    Create,
    Replace,
    Upgrade,
}

pub(crate) struct SystemdUnit {
    pub(crate) path: PathBuf,
    contents: String,
    legacy_contents: Vec<String>,
    note: Option<&'static str>,
}

impl SystemdUnit {
    pub(crate) fn for_homes(config_home: &Path, state_home: &Path) -> Result<Self, CliError> {
        let config_base = config_home
            .parent()
            .expect("troll config home has an XDG base directory");
        let state_base = state_home
            .parent()
            .expect("troll state home has an XDG base directory");
        let path = config_base.join("systemd/user").join(UNIT_FILE);
        let executable = env::current_exe()
            .map_err(|error| CliError::SetupIo("locate the executable for", path.clone(), error))?;
        let command = executable_word(&executable)?;
        let contents = unit_contents(&command, Some(config_base), Some(state_base))
            .map_err(|error| CliError::SetupIo("render the unit", path.clone(), error))?;
        let xdg_config = env::var_os("XDG_CONFIG_HOME");
        let xdg_state = env::var_os("XDG_STATE_HOME");
        let legacy_contents = [
            (None, None),
            (Some(config_base), None),
            (None, Some(state_base)),
            (Some(config_base), Some(state_base)),
            // The old renderer kept the literal spelling of current absolute
            // overrides, including a trailing slash the resolved base omits.
            (
                xdg_config.as_deref().map(Path::new),
                xdg_state.as_deref().map(Path::new),
            ),
        ]
        .into_iter()
        .filter_map(|(config, state)| legacy_unit_contents(&command, config, state))
        .collect();
        let note = xdg_config.map(|_| CONFIG_HOME_NOTE);
        Ok(Self {
            path,
            contents,
            legacy_contents,
            note,
        })
    }

    /// Preview without creating a directory or altering an existing unit.
    pub(crate) fn check(&self) -> Result<(), CliError> {
        self.change(false).map(|_| ())
    }

    pub(crate) fn install(&self, force: bool) -> Result<ServiceResult, CliError> {
        let dir = self
            .path
            .parent()
            .expect("systemd unit has a parent directory");
        let _lock = platform::lock_setup_dir(dir)
            .map_err(|error| CliError::SetupIo("lock the unit directory", dir.to_owned(), error))?;
        let status = match self.change(force)? {
            UnitChange::Unchanged => "unchanged",
            change => {
                let replace = !matches!(change, UnitChange::Create);
                platform::write_setup_file(dir, UNIT_FILE, self.contents.as_bytes(), replace)
                    .map_err(|error| {
                        if error.kind() == io::ErrorKind::AlreadyExists && !replace {
                            CliError::UnitExists(self.path.clone())
                        } else {
                            CliError::SetupIo("write the unit", self.path.clone(), error)
                        }
                    })?;
                if matches!(change, UnitChange::Upgrade) {
                    "updated"
                } else {
                    "written"
                }
            }
        };
        Ok(ServiceResult {
            kind_label: "Systemd user unit",
            path: self.path.to_string_lossy().into_owned(),
            status,
            next_commands: [command_label(RELOAD), command_label(ENABLE)].into(),
            activation: Vec::new(),
            note: self.note,
        })
    }

    fn change(&self, force: bool) -> Result<UnitChange, CliError> {
        let inspect_error = |error| CliError::SetupIo("inspect the unit", self.path.clone(), error);
        let entry = match self.path.symlink_metadata() {
            Ok(entry) => entry,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(UnitChange::Create),
            Err(error) => return Err(inspect_error(error)),
        };
        let is_file = if entry.is_symlink() {
            // A user may have linked a unit stored outside systemd/user.
            // Compare the target contents, but replace only the link with --force.
            match self.path.metadata() {
                Ok(target) => target.is_file(),
                Err(error) if error.kind() == io::ErrorKind::NotFound => false,
                Err(error) => return Err(inspect_error(error)),
            }
        } else {
            entry.is_file()
        };
        if is_file {
            let existing = fs::read(&self.path)
                .map_err(|error| CliError::SetupIo("read the unit", self.path.clone(), error))?;
            if existing == self.contents.as_bytes() {
                return Ok(UnitChange::Unchanged);
            }
            // Automatic upgrades replace units troll could have installed itself.
            if entry.is_file()
                && self
                    .legacy_contents
                    .iter()
                    .any(|legacy| legacy.as_bytes() == existing)
            {
                return Ok(UnitChange::Upgrade);
            }
        }
        if force {
            Ok(UnitChange::Replace)
        } else {
            Err(CliError::UnitExists(self.path.clone()))
        }
    }
}

pub(super) fn activate(result: &mut ServiceResult, runner: &mut dyn Systemctl) {
    for args in [RELOAD, ENABLE] {
        let (success, exit_code, status) = match runner.run(args) {
            Ok(status) => (status.success(), status.code(), status.to_string()),
            Err(error) => (false, None, format!("could not run: {error}")),
        };
        result.activation.push(CommandResult {
            command: command_label(args),
            success,
            exit_code,
            status,
        });
        if !success {
            // Starting the service after a reload failure could start an older unit.
            return;
        }
    }
    result.next_commands.clear();
}

pub(super) fn run_systemctl(args: &[&str]) -> io::Result<ExitStatus> {
    Command::new(SYSTEMCTL)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::inherit())
        .status()
}

fn command_label(args: &[&str]) -> String {
    format!("{SYSTEMCTL} {}", args.join(" "))
}

fn executable_word(executable: &Path) -> Result<String, CliError> {
    let path = executable
        .to_str()
        .filter(|path| {
            executable.is_absolute()
                && !path
                    .chars()
                    .any(|ch| ch.is_control() || matches!(ch, '"' | '\'' | '\\' | '*' | '?' | '['))
        })
        .ok_or_else(|| CliError::InvalidExecutablePath(executable.to_owned()))?;

    // Systemd expands % specifiers. A colon prefix disables $ substitution.
    let mut command = path.replace('%', "%%");
    if path.contains('$') {
        command.insert(0, ':');
    }
    if path.chars().any(char::is_whitespace) {
        command = format!("\"{command}\"");
    }
    Ok(command)
}

fn legacy_unit_contents(
    command: &str,
    config: Option<&Path>,
    state: Option<&Path>,
) -> Option<String> {
    let [config, state] = [config, state].map(|value| value.filter(|path| path.is_absolute()));
    if [config, state].into_iter().flatten().any(|path| {
        path.to_str()
            .is_none_or(|value| value.chars().any(char::is_control))
    }) {
        return None;
    }
    unit_contents(command, config, state).ok()
}

fn unit_contents(
    command: &str,
    config_base: Option<&Path>,
    state_base: Option<&Path>,
) -> io::Result<String> {
    let mut unit = format!(
        "[Unit]\nDescription=Troll port manager\n\n[Service]\nExecStart={command} serve\nRestart=on-failure\n"
    );
    for (name, value) in [
        ("XDG_CONFIG_HOME", config_base),
        ("XDG_STATE_HOME", state_base),
    ] {
        let Some(value) = value else { continue };
        let value = value
            .to_str()
            .filter(|value| {
                !value.chars().any(|ch| {
                    // Systemd's UTF-8 validator also rejects Unicode noncharacters.
                    ch == '\0'
                        || matches!(ch, '\u{FDD0}'..='\u{FDEF}')
                        || (u32::from(ch) & 0xFFFF) >= 0xFFFE
                })
            })
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("{name} must be valid systemd UTF-8 without NUL bytes"),
                )
            })?;
        write!(unit, "Environment=\"{name}=").expect("writing to a String cannot fail");
        for ch in value.chars() {
            match ch {
                '\t' => unit.push_str("\\t"),
                '\n' => unit.push_str("\\n"),
                '\\' => unit.push_str("\\\\"),
                '"' => unit.push_str("\\\""),
                '%' => unit.push_str("%%"),
                ch if ch.is_control() => {
                    for byte in ch.encode_utf8(&mut [0; 4]).bytes() {
                        write!(unit, "\\x{byte:02x}").expect("writing to a String cannot fail");
                    }
                }
                ch => unit.push(ch),
            }
        }
        unit.push_str("\"\n");
    }
    unit.push_str("\n[Install]\nWantedBy=default.target\n");
    Ok(unit)
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
    use super::*;

    #[test]
    fn unit_escapes_spaces_and_percent_in_executable_paths() {
        let path = Path::new("/opt/troll %disk/$HOME");
        let command = executable_word(path).unwrap();
        let unit = unit_contents(
            &command,
            Some(Path::new("/config")),
            Some(Path::new("/state")),
        )
        .unwrap();
        assert_eq!(
            unit.lines()
                .filter(|line| line.starts_with("ExecStart="))
                .collect::<Vec<_>>(),
            [r#"ExecStart=":/opt/troll %%disk/$HOME" serve"#]
        );
    }

    #[test]
    fn unit_refuses_quotes_backslashes_and_controls_in_executable_paths() {
        for path in [
            "/opt/it's troll",
            "/opt/a\"b/troll",
            "/opt/a\\b/troll",
            "/opt/a\nb/troll",
            "/opt/a\tb/troll",
        ] {
            let path = Path::new(path);
            assert!(
                matches!(executable_word(path), Err(CliError::InvalidExecutablePath(actual)) if actual == path)
            );
        }
    }

    #[test]
    fn unit_refuses_glob_characters_in_executable_paths() {
        for path in [
            "/opt/troll*/bin/troll",
            "/opt/what?/troll",
            "/opt/[x]/troll",
        ] {
            let path = Path::new(path);
            assert!(
                matches!(executable_word(path), Err(CliError::InvalidExecutablePath(actual)) if actual == path)
            );
        }
    }

    #[test]
    fn unit_refuses_nul_in_environment_assignments() {
        let error = unit_contents(
            "/bin/troll",
            Some(Path::new("/config")),
            Some(Path::new("/state\0home")),
        )
        .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(error.to_string().contains("XDG_STATE_HOME"));
    }
}