troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
//! Windows Task Scheduler per-user logon task XML rendering and installation.

use std::path::Path;
#[cfg(target_os = "windows")]
use std::{
    env, fs, io,
    path::PathBuf,
    process::{Command, ExitStatus, Stdio},
};

use crate::error::CliError;
#[cfg(target_os = "windows")]
use crate::platform;

#[cfg(target_os = "windows")]
use super::{CommandResult, ServiceResult, Systemctl};

#[cfg(target_os = "windows")]
const TASK_XML_FILE: &str = "troll-serve-task.xml";
const TASK_NAME: &str = "TrollServe";
#[cfg(target_os = "windows")]
const SCHTASKS: &str = "schtasks";

#[cfg(target_os = "windows")]
enum TaskChange {
    Unchanged,
    Create,
    Replace,
}

#[cfg(target_os = "windows")]
pub(crate) struct ScheduledTask {
    pub(crate) path: PathBuf,
    contents: String,
}

#[cfg(target_os = "windows")]
impl ScheduledTask {
    pub(crate) fn for_homes(config_home: &Path, _state_home: &Path) -> Result<Self, CliError> {
        let path = config_home.join(TASK_XML_FILE);
        let executable = env::current_exe()
            .map_err(|error| CliError::SetupIo("locate the executable for", path.clone(), error))?;
        let contents = task_xml_contents(&executable)?;
        Ok(Self { path, contents })
    }

    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("task XML file has a parent directory");
        let _lock = platform::lock_setup_dir(dir).map_err(|error| {
            CliError::SetupIo("lock the config directory", dir.to_owned(), error)
        })?;
        let status = match self.change(force)? {
            TaskChange::Unchanged => "unchanged",
            change => {
                let replace = matches!(change, TaskChange::Replace);
                platform::write_setup_file(dir, TASK_XML_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 scheduled task XML", self.path.clone(), error)
                    }
                })?;
                "written"
            }
        };
        let path_str = self.path.to_string_lossy().into_owned();
        Ok(ServiceResult {
            kind_label: "Windows Task Scheduler definition",
            path: path_str.clone(),
            status,
            next_commands: vec![
                format!("schtasks /Create /TN \"{TASK_NAME}\" /XML \"{path_str}\" /F"),
                format!("schtasks /Run /TN \"{TASK_NAME}\""),
            ],
            activation: Vec::new(),
            note: None,
        })
    }

    fn change(&self, force: bool) -> Result<TaskChange, CliError> {
        let inspect_error =
            |error| CliError::SetupIo("inspect the scheduled task XML", self.path.clone(), error);
        let entry = match self.path.symlink_metadata() {
            Ok(entry) => entry,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(TaskChange::Create),
            Err(error) => return Err(inspect_error(error)),
        };
        if entry.is_file() {
            let existing = fs::read(&self.path).map_err(|error| {
                CliError::SetupIo("read the scheduled task XML", self.path.clone(), error)
            })?;
            if existing == self.contents.as_bytes() {
                return Ok(TaskChange::Unchanged);
            }
        }
        if force {
            Ok(TaskChange::Replace)
        } else {
            Err(CliError::UnitExists(self.path.clone()))
        }
    }
}

#[cfg(target_os = "windows")]
pub(super) fn run_schtasks(args: &[&str]) -> io::Result<ExitStatus> {
    Command::new(SCHTASKS)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::inherit())
        .status()
}

#[cfg(target_os = "windows")]
pub(super) fn activate(result: &mut ServiceResult, runner: &mut dyn Systemctl) {
    let create_args = [
        "/Create",
        "/TN",
        TASK_NAME,
        "/XML",
        result.path.as_str(),
        "/F",
    ];
    let run_args = ["/Run", "/TN", TASK_NAME];
    for args in [&create_args[..], &run_args[..]] {
        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: format!("{SCHTASKS} {}", args.join(" ")),
            success,
            exit_code,
            status,
        });
        if !success {
            return;
        }
    }
    result.next_commands.clear();
}

/// Render a Windows Task Scheduler 1.2 XML definition for `troll serve`.
/// Compiled on all platforms so unit tests verify XML escaping everywhere.
#[allow(dead_code)]
pub(crate) fn task_xml_contents(executable: &Path) -> Result<String, CliError> {
    let exe = executable
        .to_str()
        .filter(|p| {
            let is_abs = executable.is_absolute()
                || (p.len() >= 3
                    && p.as_bytes()[0].is_ascii_alphabetic()
                    && p.as_bytes()[1] == b':'
                    && matches!(p.as_bytes()[2], b'\\' | b'/'));
            is_abs && !p.chars().any(char::is_control)
        })
        .ok_or_else(|| CliError::InvalidExecutablePath(executable.to_owned()))?;

    Ok(format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Description>Troll local port manager ({TASK_NAME})</Description>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <RestartOnFailure>
      <Interval>PT1M</Interval>
      <Count>3</Count>
    </RestartOnFailure>
    <Enabled>true</Enabled>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>{exe}</Command>
      <Arguments>serve</Arguments>
    </Exec>
  </Actions>
</Task>
"#,
        exe = xml_escape(exe),
    ))
}

fn xml_escape(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            ch => out.push(ch),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn windows_task_xml_renders_and_escapes_executable_path() {
        let xml = task_xml_contents(Path::new(r"C:\Users\Demo & Co\.cargo\bin\troll.exe")).unwrap();
        assert!(
            xml.contains("<Command>C:\\Users\\Demo &amp; Co\\.cargo\\bin\\troll.exe</Command>")
        );
        assert!(xml.contains("<Arguments>serve</Arguments>"));
        assert!(xml.contains("<RunLevel>LeastPrivilege</RunLevel>"));
        assert!(xml.contains("<LogonTrigger>"));
    }

    #[test]
    fn windows_task_xml_rejects_relative_and_control_paths() {
        for bad in ["relative\\troll.exe", "C:\\bad\npath\\troll.exe"] {
            assert!(matches!(
                task_xml_contents(Path::new(bad)),
                Err(CliError::InvalidExecutablePath(_))
            ));
        }
    }
}