use std::io;
use std::path::Path;
pub const TASK: &str = r"\Zakuro\Agent";
pub const TASK_XML: &str = "agent-task.xml";
pub type Schtasks<'a> = &'a dyn Fn(&[&str]) -> io::Result<(bool, String)>;
fn xml_escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
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
}
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(" ")
}
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)),
)
}
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}")),
}
}
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())?;
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])
}
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])
}
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,
})
}
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")
}
#[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)
),
))
}
#[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)?;
let handle = file.into_raw_handle();
for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
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 "C:\Users\jo\AppData\Local\Zakuro\zc.exe" agent run --service-log "C:\Users\jo\.zakuro\agent\agent.log" --set "ZAKURO_HOME=D:\zk & co"</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(" "));
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"]);
}
}