zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `zc agent install | uninstall` on Windows: a per-user Task Scheduler task,
//! the counterpart of the macOS LaunchAgent (`launchd.rs`) and the Linux
//! systemd user unit (`systemd.rs`).
//!
//! The task starts `zc agent run` at logon, as the user, without elevation,
//! and restarts it when it fails. Task Scheduler cannot redirect output or set
//! environment variables, so both travel as arguments: `--service-log <file>`
//! (the agent points its stdout/stderr at it) and `--set KEY=VALUE` for the
//! settings `launchd::carried_env` keeps. zc is a console program: started
//! straight from the task it would open a console window, and every process
//! the agent starts would open its own. It runs inside `conhost --headless`
//! instead, a console with no window, which those processes inherit.
//!
//! Rendering is a pure function tested everywhere; installing and
//! uninstalling take an injected `schtasks` runner, so the logic is tested on
//! every platform.

use std::io;
use std::path::Path;

/// The task's path in Task Scheduler (folder `Zakuro`, task `Agent`).
pub const TASK: &str = r"\Zakuro\Agent";

/// The task definition written next to `agent.json` for `schtasks /XML`.
pub const TASK_XML: &str = "agent-task.xml";

/// A `schtasks <args>` invocation, injected so tests never shell out:
/// `(succeeded, stdout + stderr)`.
pub type Schtasks<'a> = &'a dyn Fn(&[&str]) -> io::Result<(bool, String)>;

/// Escape for XML text content.
fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

/// Quote one argument for a Windows command line (the rules
/// `CommandLineToArgvW` and the Rust runtime parse): backslashes are literal
/// except before a quote, where they are doubled.
pub fn quote_arg(arg: &str) -> String {
    let mut out = String::from("\"");
    let mut backslashes = 0;
    for c in arg.chars() {
        match c {
            '\\' => backslashes += 1,
            '"' => {
                out.extend(std::iter::repeat_n('\\', backslashes * 2 + 1));
                out.push('"');
                backslashes = 0;
            }
            _ => {
                out.extend(std::iter::repeat_n('\\', backslashes));
                out.push(c);
                backslashes = 0;
            }
        }
    }
    out.extend(std::iter::repeat_n('\\', backslashes * 2));
    out.push('"');
    out
}

/// The `<Arguments>` of the task's action: conhost runs zc headless.
pub fn action_arguments(zc_path: &str, log_path: &str, env: &[(&str, String)]) -> String {
    let mut args = vec![
        "--headless".to_string(),
        quote_arg(zc_path),
        "agent".into(),
        "run".into(),
        "--service-log".into(),
        quote_arg(log_path),
    ];
    for (k, v) in env {
        args.push("--set".into());
        args.push(quote_arg(&format!("{k}={v}")));
    }
    args.join(" ")
}

/// The task definition (Task Scheduler schema 1.2, Windows 7+): a logon
/// trigger and an interactive, non-elevated principal for `user`
/// (`DOMAIN\name`), restart every minute on failure, no time limit, one
/// instance, and no battery conditions (a laptop on battery keeps lending).
pub fn render_task_xml(
    conhost: &str,
    zc_path: &str,
    user: &str,
    env: &[(&str, String)],
    log_path: &str,
) -> String {
    format!(
        r#"<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Description>Zakuro agent (zc agent run). Installed by zc agent install.</Description>
    <URI>{task}</URI>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger>
      <Enabled>true</Enabled>
      <UserId>{user}</UserId>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>{user}</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>false</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
    <RestartOnFailure>
      <Interval>PT1M</Interval>
      <Count>999</Count>
    </RestartOnFailure>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>{conhost}</Command>
      <Arguments>{args}</Arguments>
    </Exec>
  </Actions>
</Task>
"#,
        task = xml_escape(TASK),
        user = xml_escape(user),
        conhost = xml_escape(conhost),
        args = xml_escape(&action_arguments(zc_path, log_path, env)),
    )
}

/// UTF-16LE with a BOM: the encoding `schtasks /Create /XML` reads reliably.
pub fn utf16le_bom(s: &str) -> Vec<u8> {
    let mut out = vec![0xFF, 0xFE];
    for u in s.encode_utf16() {
        out.extend_from_slice(&u.to_le_bytes());
    }
    out
}

fn run(schtasks: Schtasks, args: &[&str]) -> Result<(), String> {
    match schtasks(args) {
        Ok((true, _)) => Ok(()),
        Ok((false, out)) => Err(format!("schtasks {} failed: {}", args[0], out.trim())),
        Err(e) => Err(format!("could not run schtasks: {e}")),
    }
}

/// Rotate the agent token, write the task definition, register it (replacing
/// any earlier one) and start it. A running agent is ended first so the new
/// one starts with the new token.
pub fn install(
    schtasks: Schtasks,
    conhost: &str,
    zc_path: &Path,
    user: &str,
    env: &[(&str, String)],
    agent_dir: &Path,
    port: u16,
) -> Result<(), String> {
    crate::agent::files::load_or_init_agent_file(agent_dir, port, true)
        .map_err(|e| e.to_string())?;
    let log = agent_dir.join(crate::agent::files::LOG_FILE);
    let xml_path = agent_dir.join(TASK_XML);
    let xml = render_task_xml(
        conhost,
        &zc_path.to_string_lossy(),
        user,
        env,
        &log.to_string_lossy(),
    );
    std::fs::write(&xml_path, utf16le_bom(&xml)).map_err(|e| e.to_string())?;
    // Not running, or not installed yet: both fine.
    let _ = schtasks(&["/End", "/TN", TASK]);
    let xml_arg = xml_path.to_string_lossy();
    run(schtasks, &["/Create", "/F", "/TN", TASK, "/XML", &xml_arg])?;
    run(schtasks, &["/Run", "/TN", TASK])
}

/// End and delete the task when it exists. `~/.zakuro/agent/` is kept.
pub fn uninstall(schtasks: Schtasks) -> Result<(), String> {
    if !matches!(schtasks(&["/Query", "/TN", TASK]), Ok((true, _))) {
        return Ok(());
    }
    let _ = schtasks(&["/End", "/TN", TASK]);
    run(schtasks, &["/Delete", "/F", "/TN", TASK])
}

/// `DOMAIN\name` of the user running zc.
pub fn current_user(lookup: impl Fn(&str) -> Option<String>) -> Option<String> {
    let name = lookup("USERNAME").filter(|v| !v.is_empty())?;
    Some(match lookup("USERDOMAIN").filter(|v| !v.is_empty()) {
        Some(domain) => format!("{domain}\\{name}"),
        None => name,
    })
}

/// `%SystemRoot%\System32\conhost.exe`.
pub fn conhost_path(lookup: impl Fn(&str) -> Option<String>) -> String {
    let root = lookup("SystemRoot")
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| r"C:\Windows".into());
    format!(r"{root}\System32\conhost.exe")
}

/// The real `schtasks`, with no console window.
#[cfg(windows)]
pub fn run_schtasks(args: &[&str]) -> io::Result<(bool, String)> {
    use std::os::windows::process::CommandExt;
    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
    let out = std::process::Command::new("schtasks")
        .args(args)
        .creation_flags(CREATE_NO_WINDOW)
        .output()?;
    Ok((
        out.status.success(),
        format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        ),
    ))
}

/// `zc agent run --service-log <file>` on Windows: send this process's
/// stdout and stderr, and those of the processes it starts, to `log`. Rust's
/// stdio and `Stdio::inherit` read the standard handles on every use, so
/// replacing them here takes effect everywhere.
#[cfg(windows)]
pub fn redirect_std_to(log: &Path) -> io::Result<()> {
    use std::os::windows::io::IntoRawHandle;
    const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
    const STD_ERROR_HANDLE: u32 = -12i32 as u32;
    extern "system" {
        fn SetStdHandle(std_handle: u32, handle: *mut std::ffi::c_void) -> i32;
    }
    if let Some(dir) = log.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log)?;
    // Kept open for the life of the process.
    let handle = file.into_raw_handle();
    for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
        // SAFETY: `handle` is a valid, open file handle that is never closed.
        if unsafe { SetStdHandle(which, handle) } == 0 {
            return Err(io::Error::last_os_error());
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::files::tests::tmp;
    use std::cell::RefCell;

    #[test]
    fn quoting_follows_the_windows_command_line_rules() {
        assert_eq!(
            quote_arg(r"C:\Program Files\Zakuro\zc.exe"),
            r#""C:\Program Files\Zakuro\zc.exe""#
        );
        assert_eq!(quote_arg(r"C:\dir\"), r#""C:\dir\\""#);
        assert_eq!(quote_arg(r#"a"b"#), r#""a\"b""#);
        assert_eq!(quote_arg(r#"a\"b"#), r#""a\\\"b""#);
        assert_eq!(quote_arg(""), r#""""#);
    }

    #[test]
    fn the_task_runs_the_agent_headless_at_logon_with_its_log_and_settings() {
        let x = render_task_xml(
            r"C:\Windows\System32\conhost.exe",
            r"C:\Users\jo\AppData\Local\Zakuro\zc.exe",
            r"PC\jo",
            &[("ZAKURO_HOME", r"D:\zk & co".to_string())],
            r"C:\Users\jo\.zakuro\agent\agent.log",
        );
        assert!(
            x.contains(r"<Command>C:\Windows\System32\conhost.exe</Command>"),
            "{x}"
        );
        assert!(
            x.contains(
                r#"<Arguments>--headless &quot;C:\Users\jo\AppData\Local\Zakuro\zc.exe&quot; agent run --service-log &quot;C:\Users\jo\.zakuro\agent\agent.log&quot; --set &quot;ZAKURO_HOME=D:\zk &amp; co&quot;</Arguments>"#
            ),
            "{x}"
        );
        assert_eq!(x.matches(r"<UserId>PC\jo</UserId>").count(), 2);
        assert!(x.contains("<LogonTrigger>"));
        assert!(x.contains("<RunLevel>LeastPrivilege</RunLevel>"));
        assert!(x.contains("<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>"));
        assert!(x.contains("<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"));
        assert!(x.contains("<RestartOnFailure>"));
    }

    #[test]
    fn the_xml_is_written_as_utf16le_with_a_bom() {
        let b = utf16le_bom("<a/>");
        assert_eq!(&b[..4], &[0xFF, 0xFE, b'<', 0]);
        assert_eq!(b.len(), 2 + 4 * 2);
    }

    #[test]
    fn user_and_conhost_come_from_the_environment() {
        let env = |k: &str| match k {
            "USERNAME" => Some("jo".to_string()),
            "USERDOMAIN" => Some("PC".to_string()),
            "SystemRoot" => Some(r"D:\Win".to_string()),
            _ => None,
        };
        assert_eq!(current_user(env).as_deref(), Some(r"PC\jo"));
        assert_eq!(conhost_path(env), r"D:\Win\System32\conhost.exe");
        assert_eq!(current_user(|_| None), None);
        assert_eq!(conhost_path(|_| None), r"C:\Windows\System32\conhost.exe");
    }

    #[test]
    fn install_writes_the_task_then_replaces_and_starts_it() {
        let dir = tmp("schtasks-install");
        let calls = RefCell::new(Vec::<String>::new());
        let fake = |a: &[&str]| -> io::Result<(bool, String)> {
            calls.borrow_mut().push(a.join(" "));
            // /End fails when nothing runs: install must not care.
            Ok((a[0] != "/End", String::new()))
        };
        install(
            &fake,
            r"C:\Windows\System32\conhost.exe",
            Path::new(r"C:\zc.exe"),
            r"PC\jo",
            &[],
            &dir,
            7465,
        )
        .unwrap();
        let xml = dir.join(TASK_XML);
        assert!(std::fs::read(&xml).unwrap().starts_with(&[0xFF, 0xFE]));
        assert!(dir.join("agent.json").exists());
        let calls = calls.into_inner();
        assert_eq!(calls.len(), 3, "{calls:?}");
        assert_eq!(calls[0], format!("/End /TN {TASK}"));
        assert_eq!(
            calls[1],
            format!("/Create /F /TN {TASK} /XML {}", xml.display())
        );
        assert_eq!(calls[2], format!("/Run /TN {TASK}"));
    }

    #[test]
    fn install_reports_a_failed_create() {
        let dir = tmp("schtasks-install-fail");
        let fake = |a: &[&str]| -> io::Result<(bool, String)> {
            Ok((a[0] != "/Create", "ERROR: Access is denied.\n".into()))
        };
        let e = install(&fake, "conhost", Path::new("zc"), "jo", &[], &dir, 7465).unwrap_err();
        assert_eq!(e, "schtasks /Create failed: ERROR: Access is denied.");
    }

    #[test]
    fn uninstall_deletes_only_an_existing_task() {
        let calls = RefCell::new(Vec::<String>::new());
        let missing = |a: &[&str]| -> io::Result<(bool, String)> {
            calls.borrow_mut().push(a[0].to_string());
            Ok((false, String::new()))
        };
        uninstall(&missing).unwrap();
        assert_eq!(*calls.borrow(), ["/Query"]);

        calls.borrow_mut().clear();
        let present = |a: &[&str]| -> io::Result<(bool, String)> {
            calls.borrow_mut().push(a[0].to_string());
            Ok((true, String::new()))
        };
        uninstall(&present).unwrap();
        assert_eq!(*calls.borrow(), ["/Query", "/End", "/Delete"]);
    }
}