Skip to main content

snip_sync/
startup.rs

1//! Cross-platform startup registration for the foreground `snip-sync` server.
2//!
3//! This module renders small supervisor records and owns only the records it
4//! writes. The server remains a normal foreground process; cron and Task
5//! Scheduler invoke `croncheck`, while systemd and launchd invoke `serve`.
6
7use crate::cli::StartupMethodArg;
8use crate::{Config, parse_bool_env};
9use std::fs;
10use std::io::{Read, Write};
11use std::net::{IpAddr, TcpStream, ToSocketAddrs};
12use std::path::{Path, PathBuf};
13use std::process::{Command, Output, Stdio};
14use std::time::{Duration, Instant};
15
16pub const SYSTEMD_UNIT_NAME: &str = "snip-sync.service";
17pub const LAUNCHD_LABEL: &str = "com.eggstack.snip-sync";
18pub const OWNERSHIP_MARKER: &str = "snip-sync startup managed file";
19pub const CRON_BEGIN: &str = "# snip-sync managed startup (begin)";
20pub const CRON_END: &str = "# snip-sync managed startup (end)";
21pub const TASK_STARTUP_NAME: &str = "snip-sync startup (startup)";
22pub const TASK_WATCHDOG_NAME: &str = "snip-sync startup (watchdog)";
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum StartupMethod {
26    Systemd,
27    Launchd,
28    Cron,
29    TaskScheduler,
30    Direct,
31}
32
33/// Whether an update must activate a new server process after replacing the
34/// executable. The installed manager is retained so restart uses the same
35/// lifecycle path that owns the service.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum UpdateLifecycle {
38    ManagedRunning(StartupMethod),
39    ManagedStopped(StartupMethod),
40    DirectRunning,
41    NotRunning,
42}
43
44impl StartupMethod {
45    pub fn as_str(self) -> &'static str {
46        match self {
47            Self::Systemd => "systemd",
48            Self::Launchd => "launchd",
49            Self::Cron => "cron",
50            Self::TaskScheduler => "task-scheduler",
51            Self::Direct => "direct",
52        }
53    }
54}
55
56impl std::str::FromStr for StartupMethod {
57    type Err = String;
58
59    fn from_str(value: &str) -> Result<Self, Self::Err> {
60        match value {
61            "systemd" => Ok(Self::Systemd),
62            "launchd" => Ok(Self::Launchd),
63            "cron" => Ok(Self::Cron),
64            "task-scheduler" => Ok(Self::TaskScheduler),
65            "direct" => Ok(Self::Direct),
66            other => Err(format!("unknown startup method {other:?}")),
67        }
68    }
69}
70
71#[derive(Clone, Debug, PartialEq, Eq)]
72pub struct TransportEnvironment {
73    pub entries: Vec<(String, String)>,
74}
75
76pub fn method_from_arg(method: StartupMethodArg) -> Option<StartupMethod> {
77    Some(match method {
78        StartupMethodArg::Auto => return None,
79        StartupMethodArg::Systemd => StartupMethod::Systemd,
80        StartupMethodArg::Launchd => StartupMethod::Launchd,
81        StartupMethodArg::Cron => StartupMethod::Cron,
82        StartupMethodArg::TaskScheduler => StartupMethod::TaskScheduler,
83    })
84}
85
86pub fn resolve_method(method: StartupMethodArg) -> Result<StartupMethod, String> {
87    if let Some(method) = method_from_arg(method) {
88        return Ok(method);
89    }
90    auto_detect_method()
91}
92
93pub fn auto_detect_method() -> Result<StartupMethod, String> {
94    #[cfg(target_os = "linux")]
95    {
96        if systemd_is_running() {
97            return Ok(StartupMethod::Systemd);
98        }
99        if command_available("crontab") {
100            return Ok(StartupMethod::Cron);
101        }
102        Err(
103            "systemd is not running and no POSIX crontab command is available; use startup instructions --method systemd or install cron"
104                .into(),
105        )
106    }
107    #[cfg(target_os = "macos")]
108    {
109        Ok(StartupMethod::Launchd)
110    }
111    #[cfg(windows)]
112    {
113        Ok(StartupMethod::TaskScheduler)
114    }
115    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
116    {
117        if command_available("crontab") {
118            Ok(StartupMethod::Cron)
119        } else {
120            Err("no supported startup manager or POSIX crontab command is available".into())
121        }
122    }
123}
124
125/// A bounded systemd check. Merely finding `systemctl` is intentionally not
126/// enough: containers commonly have the client binary but no systemd PID 1.
127pub fn systemd_is_running() -> bool {
128    #[cfg(target_os = "linux")]
129    {
130        if Path::new("/run/systemd/system").exists() {
131            return true;
132        }
133        if fs::read_to_string("/proc/1/comm")
134            .ok()
135            .is_some_and(|value| value.trim() == "systemd")
136        {
137            return true;
138        }
139        if !command_available("systemctl") || !command_available("timeout") {
140            return false;
141        }
142        let output = Command::new("timeout")
143            .args(["--signal=TERM", "1s", "systemctl", "is-system-running"])
144            .stdin(Stdio::null())
145            .output();
146        output.is_ok_and(|output| {
147            let state = String::from_utf8_lossy(&output.stdout);
148            matches!(
149                state.trim(),
150                "running" | "degraded" | "starting" | "maintenance"
151            )
152        })
153    }
154    #[cfg(not(target_os = "linux"))]
155    {
156        false
157    }
158}
159
160pub fn command_available(command: &str) -> bool {
161    if command == "crontab" {
162        return Command::new(command)
163            .arg("-l")
164            .stdout(Stdio::null())
165            .stderr(Stdio::null())
166            .status()
167            .is_ok();
168    }
169    Command::new(command)
170        .arg("--version")
171        .stdout(Stdio::null())
172        .stderr(Stdio::null())
173        .status()
174        .is_ok()
175}
176
177pub fn systemd_unit_path() -> PathBuf {
178    PathBuf::from("/etc/systemd/system").join(SYSTEMD_UNIT_NAME)
179}
180
181pub fn launchd_plist_path() -> PathBuf {
182    PathBuf::from("/Library/LaunchDaemons").join(format!("{LAUNCHD_LABEL}.plist"))
183}
184
185fn startup_state_path() -> PathBuf {
186    crate::paths::state_dir().join("startup-method")
187}
188
189fn has_control_characters(value: &str) -> bool {
190    value.chars().any(|ch| ch.is_control())
191}
192
193pub fn shell_quote(value: &Path) -> Result<String, String> {
194    let value = value.to_string_lossy();
195    if has_control_characters(&value) {
196        return Err(format!("path contains control characters: {value:?}"));
197    }
198    Ok(format!("'{}'", value.replace('\'', "'\\''")))
199}
200
201fn systemd_quote(value: &str) -> Result<String, String> {
202    if has_control_characters(value) {
203        return Err("systemd value contains a control character".into());
204    }
205    Ok(format!(
206        "\"{}\"",
207        value
208            .replace('\\', "\\\\")
209            .replace('"', "\\\"")
210            .replace('$', "\\$")
211            .replace('`', "\\`")
212    ))
213}
214
215fn xml_escape(value: &str) -> Result<String, String> {
216    if has_control_characters(value) {
217        return Err("launchd value contains a control character".into());
218    }
219    Ok(value
220        .replace('&', "&amp;")
221        .replace('<', "&lt;")
222        .replace('>', "&gt;")
223        .replace('"', "&quot;")
224        .replace('\'', "&apos;"))
225}
226
227fn windows_quote(value: &Path) -> Result<String, String> {
228    let value = value.to_string_lossy();
229    if has_control_characters(&value) {
230        return Err(format!("path contains control characters: {value:?}"));
231    }
232    // This is the CommandLineToArgvW-compatible quoting needed for a single
233    // executable argument. The task action itself is passed as one argument
234    // to schtasks, not through a shell.
235    let mut quoted = String::from("\"");
236    let mut slashes = 0;
237    for ch in value.chars() {
238        if ch == '\\' {
239            slashes += 1;
240        } else if ch == '"' {
241            quoted.push_str(&"\\".repeat(slashes * 2 + 1));
242            quoted.push('"');
243            slashes = 0;
244        } else {
245            quoted.push_str(&"\\".repeat(slashes));
246            quoted.push(ch);
247            slashes = 0;
248        }
249    }
250    quoted.push_str(&"\\".repeat(slashes * 2));
251    quoted.push('"');
252    Ok(quoted)
253}
254
255fn is_loopback_host(host: &str, port: u16) -> Result<bool, String> {
256    let host = host.trim();
257    if let Ok(ip) = host.parse::<IpAddr>() {
258        return Ok(ip.is_loopback());
259    }
260    let addresses = (host, port)
261        .to_socket_addrs()
262        .map_err(|e| format!("could not resolve configured bind host {host:?}: {e}"))?;
263    let mut found = false;
264    for address in addresses {
265        found = true;
266        if !address.ip().is_loopback() {
267            return Ok(false);
268        }
269    }
270    Ok(found)
271}
272
273/// Centralized safety policy for plaintext operation.
274pub fn validate_transport_policy(
275    tls_enabled: bool,
276    allow_http: bool,
277    grpc_loopback: bool,
278    http_loopback: bool,
279) -> Result<(), String> {
280    if !tls_enabled && allow_http && !(grpc_loopback && http_loopback) {
281        return Err(
282            "SNIP_SYNC_ALLOW_HTTP=true is permitted only when both gRPC and HTTP bind addresses are loopback; set TLS_ENABLED=true for non-loopback deployment"
283                .into(),
284        );
285    }
286    if !tls_enabled && !allow_http {
287        return Err(
288            "TLS termination is required for production. Set TLS_ENABLED=true when a reverse proxy terminates TLS, or set SNIP_SYNC_ALLOW_HTTP=true for loopback development"
289                .into(),
290        );
291    }
292    Ok(())
293}
294
295pub fn transport_environment() -> Result<TransportEnvironment, String> {
296    let config = Config::load().map_err(|e| e.to_string())?;
297    let tls_enabled = parse_bool_env(&|name| std::env::var(name).ok(), "TLS_ENABLED")
298        .map_err(|e| e.to_string())?
299        .unwrap_or(false);
300    let grpc_loopback = is_loopback_host(&config.grpc_host, config.grpc_port)?;
301    let http_loopback = is_loopback_host(&config.http_host, config.http_port)?;
302    let mut entries = Vec::new();
303    if tls_enabled {
304        entries.push(("TLS_ENABLED".into(), "true".into()));
305    } else {
306        validate_transport_policy(false, true, grpc_loopback, http_loopback)?;
307        entries.push(("SNIP_SYNC_ALLOW_HTTP".into(), "true".into()));
308    }
309    for name in [
310        "CONFIG_PATH",
311        "SNIP_SYNC_STATE_DIR",
312        "DATABASE_URL",
313        "PREMADE_DIR",
314    ] {
315        if let Ok(value) = std::env::var(name) {
316            if has_control_characters(&value) {
317                return Err(format!("{name} contains a control character"));
318            }
319            entries.push((name.into(), value));
320        }
321    }
322    Ok(TransportEnvironment { entries })
323}
324
325fn environment_lines_systemd(environment: &TransportEnvironment) -> Result<String, String> {
326    let mut rendered = String::new();
327    for (name, value) in &environment.entries {
328        rendered.push_str("Environment=");
329        rendered.push_str(&systemd_quote(&format!("{name}={value}"))?);
330        rendered.push('\n');
331    }
332    Ok(rendered)
333}
334
335pub fn render_systemd_unit(
336    executable: &Path,
337    account: &str,
338    environment: &TransportEnvironment,
339) -> Result<String, String> {
340    let executable = executable
341        .to_str()
342        .ok_or_else(|| "executable path is not valid UTF-8".to_string())?;
343    let exec_start = format!("{} serve", systemd_quote(executable)?);
344    if has_control_characters(account) || account.is_empty() {
345        return Err("systemd account is empty or contains a control character".into());
346    }
347    Ok(format!(
348        "# {OWNERSHIP_MARKER}\n[Unit]\nDescription=snip-sync gRPC server\nAfter=network.target\n\n[Service]\nType=simple\nUser={account}\nExecStart={exec_start}\n{}Restart=on-failure\nRestartSec=2\n\n[Install]\nWantedBy=multi-user.target\n",
349        environment_lines_systemd(environment)?
350    ))
351}
352
353pub fn render_launchd_plist(
354    executable: &Path,
355    account: &str,
356    environment: &TransportEnvironment,
357) -> Result<String, String> {
358    let executable = xml_escape(
359        executable
360            .to_str()
361            .ok_or_else(|| "executable path is not valid UTF-8".to_string())?,
362    )?;
363    let account = xml_escape(account)?;
364    let mut environment_xml = String::new();
365    for (name, value) in &environment.entries {
366        environment_xml.push_str(&format!(
367            "        <key>{}</key><string>{}</string>\n",
368            xml_escape(name)?,
369            xml_escape(value)?
370        ));
371    }
372    Ok(format!(
373        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- {OWNERSHIP_MARKER} -->\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n    <key>Label</key><string>{LAUNCHD_LABEL}</string>\n    <key>UserName</key><string>{account}</string>\n    <key>ProgramArguments</key>\n    <array><string>{executable}</string><string>serve</string></array>\n    <key>EnvironmentVariables</key>\n    <dict>\n{environment_xml}    </dict>\n    <key>KeepAlive</key><true/>\n    <key>ProcessType</key><string>Background</string>\n</dict>\n</plist>\n"
374    ))
375}
376
377fn cron_command(executable: &Path, environment: &TransportEnvironment) -> Result<String, String> {
378    let mut command = String::new();
379    for (name, value) in &environment.entries {
380        // Values are generated from booleans or explicitly supplied paths;
381        // shell_quote also rejects control characters.
382        let quoted = shell_quote(Path::new(value))?;
383        command.push_str(name);
384        command.push('=');
385        command.push_str(&quoted);
386        command.push(' ');
387    }
388    command.push_str(&shell_quote(executable)?);
389    command.push_str(" croncheck");
390    Ok(command)
391}
392
393pub fn render_cron_block(
394    executable: &Path,
395    environment: &TransportEnvironment,
396) -> Result<String, String> {
397    let command = cron_command(executable, environment)?;
398    Ok(format!(
399        "{CRON_BEGIN}\n@reboot {command}\n*/5 * * * * {command}\n{CRON_END}"
400    ))
401}
402
403pub fn render_task_commands(
404    executable: &Path,
405    environment: &TransportEnvironment,
406    administrator: bool,
407) -> Result<Vec<String>, String> {
408    let action = task_action(executable, environment)?;
409    let trigger = if administrator { "ONSTART" } else { "ONLOGON" };
410    let mut startup = format!(
411        "schtasks /Create /TN \"{TASK_STARTUP_NAME}\" /SC {trigger} /TR \"{}\" /F",
412        action.replace('"', "\\\"")
413    );
414    if administrator {
415        startup.push_str(" /RU SYSTEM /RL HIGHEST");
416    }
417    Ok(vec![
418        startup,
419        format!(
420            "schtasks /Create /TN \"{TASK_WATCHDOG_NAME}\" /SC MINUTE /MO 5 /TR \"{}\" /F",
421            action.replace('"', "\\\"")
422        ),
423    ])
424}
425
426fn task_action(executable: &Path, environment: &TransportEnvironment) -> Result<String, String> {
427    let executable = windows_quote(executable)?;
428    let mut command = String::from("cmd.exe /D /S /C \"");
429    for (name, value) in &environment.entries {
430        if has_control_characters(name) || has_control_characters(value) {
431            return Err("Task Scheduler environment contains a control character".into());
432        }
433        command.push_str("set \\\"");
434        command.push_str(name);
435        command.push('=');
436        command.push_str(value);
437        command.push_str("\\\"&&");
438    }
439    command.push_str(&executable);
440    command.push_str(" croncheck\"");
441    Ok(command)
442}
443
444fn account_name() -> String {
445    std::env::var("SUDO_USER")
446        .ok()
447        .filter(|value| !value.is_empty())
448        .or_else(|| std::env::var("USER").ok())
449        .or_else(|| std::env::var("USERNAME").ok())
450        .unwrap_or_else(|| "snip-sync".into())
451}
452
453fn require_non_root_service_account() -> Result<(), String> {
454    if is_root() && account_name() == "root" {
455        return Err(
456            "refusing to register a system service as root; invoke through sudo from the intended non-root account so SUDO_USER is preserved"
457                .into(),
458        );
459    }
460    Ok(())
461}
462
463fn is_root() -> bool {
464    #[cfg(unix)]
465    {
466        unsafe { libc::geteuid() == 0 }
467    }
468    #[cfg(not(unix))]
469    {
470        false
471    }
472}
473
474fn exact_elevated_command(method: StartupMethod, executable: &Path) -> Result<String, String> {
475    Ok(format!(
476        "sudo {} startup install --method {}",
477        shell_quote(executable)?,
478        method.as_str()
479    ))
480}
481
482fn require_root(method: StartupMethod, executable: &Path) -> Result<(), String> {
483    if !is_root() {
484        let command = exact_elevated_command(method, executable)?;
485        eprintln!("This startup method requires elevated privileges.");
486        eprintln!("Run exactly: {command}");
487        return Err("elevated privileges required".into());
488    }
489    Ok(())
490}
491
492fn require_root_for_uninstall(executable: &Path) -> Result<(), String> {
493    if !is_root() {
494        let command = format!("sudo {} startup uninstall", shell_quote(executable)?);
495        eprintln!("This startup removal requires elevated privileges.");
496        eprintln!("Run exactly: {command}");
497        return Err("elevated privileges required".into());
498    }
499    Ok(())
500}
501
502fn run_checked(program: &str, args: &[&str]) -> Result<Output, String> {
503    let output = Command::new(program)
504        .args(args)
505        .output()
506        .map_err(|e| format!("failed to execute {program}: {e}"))?;
507    if !output.status.success() {
508        return Err(format!(
509            "{program} {} failed: {}",
510            args.join(" "),
511            String::from_utf8_lossy(&output.stderr).trim()
512        ));
513    }
514    Ok(output)
515}
516
517fn run_allow_failure(program: &str, args: &[&str]) -> Result<(), String> {
518    Command::new(program)
519        .args(args)
520        .output()
521        .map(|_| ())
522        .map_err(|e| format!("failed to execute {program}: {e}"))
523}
524
525fn write_owned(path: &Path, content: &str) -> Result<(), String> {
526    if let Some(parent) = path.parent() {
527        fs::create_dir_all(parent)
528            .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
529    }
530    fs::write(path, content).map_err(|e| format!("failed to write {}: {e}", path.display()))
531}
532
533fn is_owned_file(path: &Path) -> bool {
534    fs::read_to_string(path)
535        .ok()
536        .is_some_and(|content| content.contains(OWNERSHIP_MARKER))
537}
538
539fn read_crontab() -> Result<String, String> {
540    let output = Command::new("crontab")
541        .arg("-l")
542        .output()
543        .map_err(|e| format!("crontab is unavailable: {e}"))?;
544    if output.status.success() {
545        return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
546    }
547    let stderr = String::from_utf8_lossy(&output.stderr);
548    if stderr.contains("no crontab") || stderr.contains("no crontab for") {
549        Ok(String::new())
550    } else {
551        Err(format!("crontab -l failed: {}", stderr.trim()))
552    }
553}
554
555fn replace_cron_block(existing: &str, replacement: Option<&str>) -> String {
556    let lines: Vec<&str> = existing.lines().collect();
557    let begin = lines.iter().position(|line| *line == CRON_BEGIN);
558    let end = begin.and_then(|begin| {
559        lines
560            .iter()
561            .enumerate()
562            .skip(begin + 1)
563            .find_map(|(index, line)| (*line == CRON_END).then_some(index))
564    });
565    let mut output = Vec::new();
566    match (begin, end) {
567        (Some(begin), Some(end)) => {
568            output.extend_from_slice(&lines[..begin]);
569            output.extend_from_slice(&lines[end + 1..]);
570        }
571        _ => output.extend(lines),
572    }
573    if let Some(replacement) = replacement {
574        while output.last().is_some_and(|line| line.is_empty()) {
575            output.pop();
576        }
577        if !output.is_empty() {
578            output.push("");
579        }
580        output.extend(replacement.lines());
581    }
582    let mut result = output.join("\n");
583    if !result.is_empty() {
584        result.push('\n');
585    }
586    result
587}
588
589fn write_crontab(content: &str) -> Result<(), String> {
590    let mut child = Command::new("crontab")
591        .arg("-")
592        .stdin(Stdio::piped())
593        .stdout(Stdio::null())
594        .stderr(Stdio::piped())
595        .spawn()
596        .map_err(|e| format!("failed to execute crontab: {e}"))?;
597    child
598        .stdin
599        .take()
600        .ok_or_else(|| "failed to open crontab stdin".to_string())?
601        .write_all(content.as_bytes())
602        .map_err(|e| format!("failed to write crontab: {e}"))?;
603    let output = child
604        .wait_with_output()
605        .map_err(|e| format!("failed waiting for crontab: {e}"))?;
606    if output.status.success() {
607        Ok(())
608    } else {
609        Err(format!(
610            "crontab install failed: {}",
611            String::from_utf8_lossy(&output.stderr).trim()
612        ))
613    }
614}
615
616fn persist_method(method: StartupMethod) -> Result<(), String> {
617    if let Some(parent) = startup_state_path().parent() {
618        fs::create_dir_all(parent).map_err(|e| format!("failed to create startup state: {e}"))?;
619    }
620    fs::write(startup_state_path(), method.as_str())
621        .map_err(|e| format!("failed to record startup method: {e}"))
622}
623
624fn installed_method() -> Option<StartupMethod> {
625    let value = fs::read_to_string(startup_state_path()).ok()?;
626    value.trim().parse().ok()
627}
628
629pub fn install(method_arg: StartupMethodArg, executable: &Path) -> Result<(), String> {
630    let method = resolve_method(method_arg)?;
631    if method == StartupMethod::Direct {
632        return Err("direct is an internal unmanaged state and cannot be installed".into());
633    }
634    if matches!(method, StartupMethod::Systemd | StartupMethod::Launchd) {
635        require_root(method, executable)?;
636    }
637    if method == StartupMethod::Cron && !command_available("crontab") {
638        return Err("cron startup requested but crontab is unavailable".into());
639    }
640    crate::bootstrap::ensure_layout()?;
641    crate::bootstrap::ensure_config_file()?;
642    let environment = transport_environment()?;
643    match method {
644        StartupMethod::Systemd => install_systemd(executable, &environment)?,
645        StartupMethod::Launchd => install_launchd(executable, &environment)?,
646        StartupMethod::Cron => install_cron(executable, &environment)?,
647        StartupMethod::TaskScheduler => install_task_scheduler(executable, &environment)?,
648        StartupMethod::Direct => unreachable!(),
649    }
650    persist_method(method)?;
651    println!("Installed snip-sync startup using {}.", method.as_str());
652    Ok(())
653}
654
655fn install_systemd(executable: &Path, environment: &TransportEnvironment) -> Result<(), String> {
656    if !cfg!(target_os = "linux") {
657        return Err("systemd startup installation is supported only on Linux".into());
658    }
659    require_non_root_service_account()?;
660    let unit = render_systemd_unit(executable, &account_name(), environment)?;
661    let path = systemd_unit_path();
662    write_owned(&path, &unit)?;
663    run_checked("systemctl", &["daemon-reload"])?;
664    run_checked("systemctl", &["enable", SYSTEMD_UNIT_NAME])?;
665    run_checked("systemctl", &["restart", SYSTEMD_UNIT_NAME])?;
666    let config = Config::load().map_err(|e| e.to_string())?;
667    wait_for_health(&config, Duration::from_secs(10))?;
668    println!("Unit: {}", path.display());
669    println!("Status: systemctl status {SYSTEMD_UNIT_NAME}");
670    Ok(())
671}
672
673fn install_launchd(executable: &Path, environment: &TransportEnvironment) -> Result<(), String> {
674    if !cfg!(target_os = "macos") {
675        return Err("launchd startup installation is supported only on macOS".into());
676    }
677    require_non_root_service_account()?;
678    let path = launchd_plist_path();
679    let plist = render_launchd_plist(executable, &account_name(), environment)?;
680    write_owned(&path, &plist)?;
681    let path_string = path
682        .to_str()
683        .ok_or_else(|| "launchd plist path is not valid UTF-8".to_string())?;
684    let target = format!("system/{LAUNCHD_LABEL}");
685    let _ = run_allow_failure("launchctl", &["bootout", &target]);
686    run_checked("launchctl", &["bootstrap", "system", path_string])?;
687    run_checked("launchctl", &["enable", &format!("system/{LAUNCHD_LABEL}")])?;
688    run_checked(
689        "launchctl",
690        &["kickstart", "-k", &format!("system/{LAUNCHD_LABEL}")],
691    )?;
692    let config = Config::load().map_err(|e| e.to_string())?;
693    wait_for_health(&config, Duration::from_secs(10))?;
694    println!("Plist: {}", path.display());
695    println!("Status: launchctl print system/{LAUNCHD_LABEL}");
696    Ok(())
697}
698
699fn install_cron(executable: &Path, environment: &TransportEnvironment) -> Result<(), String> {
700    let block = render_cron_block(executable, environment)?;
701    let existing = read_crontab()?;
702    write_crontab(&replace_cron_block(&existing, Some(&block)))
703}
704
705fn install_task_scheduler(
706    executable: &Path,
707    environment: &TransportEnvironment,
708) -> Result<(), String> {
709    if !cfg!(windows) {
710        return Err("Task Scheduler installation is supported only on Windows".into());
711    }
712    let administrator = is_windows_administrator();
713    let action = task_action(executable, environment)?;
714    let trigger = if administrator { "ONSTART" } else { "ONLOGON" };
715    let mut startup_args = vec![
716        "/Create".to_string(),
717        "/TN".to_string(),
718        TASK_STARTUP_NAME.to_string(),
719        "/SC".to_string(),
720        trigger.to_string(),
721        "/TR".to_string(),
722        action.clone(),
723        "/F".to_string(),
724    ];
725    if administrator {
726        startup_args.extend([
727            "/RU".to_string(),
728            "SYSTEM".to_string(),
729            "/RL".to_string(),
730            "HIGHEST".to_string(),
731        ]);
732    }
733    let watchdog_args = vec![
734        "/Create".to_string(),
735        "/TN".to_string(),
736        TASK_WATCHDOG_NAME.to_string(),
737        "/SC".to_string(),
738        "MINUTE".to_string(),
739        "/MO".to_string(),
740        "5".to_string(),
741        "/TR".to_string(),
742        action,
743        "/F".to_string(),
744    ];
745    for args in [startup_args, watchdog_args] {
746        run_checked(
747            "schtasks",
748            &args.iter().map(String::as_str).collect::<Vec<_>>(),
749        )?;
750    }
751    Ok(())
752}
753
754#[cfg(windows)]
755fn is_windows_administrator() -> bool {
756    Command::new("net")
757        .args(["session"])
758        .stdout(Stdio::null())
759        .stderr(Stdio::null())
760        .status()
761        .is_ok_and(|status| status.success())
762}
763
764#[cfg(not(windows))]
765fn is_windows_administrator() -> bool {
766    false
767}
768
769pub fn instructions(method_arg: StartupMethodArg, executable: &Path) -> Result<(), String> {
770    let method = resolve_method(method_arg)?;
771    let environment = transport_environment()?;
772    println!("Selected startup method: {}", method.as_str());
773    match method {
774        StartupMethod::Systemd => {
775            let path = systemd_unit_path();
776            println!("\nRun:\n  {}", exact_elevated_command(method, executable)?);
777            println!(
778                "\nFile: {}\n\n{}",
779                path.display(),
780                render_systemd_unit(executable, &account_name(), &environment)?
781            );
782        }
783        StartupMethod::Launchd => {
784            let path = launchd_plist_path();
785            println!("\nRun:\n  {}", exact_elevated_command(method, executable)?);
786            println!(
787                "\nFile: {}\n\n{}",
788                path.display(),
789                render_launchd_plist(executable, &account_name(), &environment)?
790            );
791        }
792        StartupMethod::Cron => {
793            println!("\nRun: crontab -e");
794            println!(
795                "\nAdd exactly:\n{}",
796                render_cron_block(executable, &environment)?
797            );
798        }
799        StartupMethod::TaskScheduler => {
800            println!("\nRun these commands in an elevated prompt when installing for all users:");
801            for command in render_task_commands(executable, &environment, true)? {
802                println!("{command}");
803            }
804            println!("\nNon-administrator fallback commands:");
805            for command in render_task_commands(executable, &environment, false)? {
806                println!("{command}");
807            }
808        }
809        StartupMethod::Direct => unreachable!(),
810    }
811    Ok(())
812}
813
814pub fn uninstall(executable: &Path) -> Result<(), String> {
815    let mut changed = false;
816    #[cfg(target_os = "linux")]
817    {
818        if is_owned_file(&systemd_unit_path()) {
819            require_root_for_uninstall(executable)?;
820            let _ = run_allow_failure("systemctl", &["disable", "--now", SYSTEMD_UNIT_NAME]);
821            fs::remove_file(systemd_unit_path())
822                .map_err(|e| format!("failed to remove systemd unit: {e}"))?;
823            let _ = run_allow_failure("systemctl", &["daemon-reload"]);
824            changed = true;
825        }
826    }
827    #[cfg(target_os = "macos")]
828    {
829        if is_owned_file(&launchd_plist_path()) {
830            require_root_for_uninstall(executable)?;
831            let _ = run_allow_failure(
832                "launchctl",
833                &["bootout", &format!("system/{LAUNCHD_LABEL}")],
834            );
835            fs::remove_file(launchd_plist_path())
836                .map_err(|e| format!("failed to remove launchd plist: {e}"))?;
837            changed = true;
838        }
839    }
840    #[cfg(any(unix, target_os = "linux", target_os = "macos"))]
841    if command_available("crontab") {
842        let existing = read_crontab()?;
843        let updated = replace_cron_block(&existing, None);
844        if updated != existing {
845            write_crontab(&updated)?;
846            changed = true;
847        }
848    }
849    #[cfg(windows)]
850    {
851        for name in [TASK_STARTUP_NAME, TASK_WATCHDOG_NAME] {
852            let _ = run_allow_failure("schtasks", &["/Delete", "/TN", name, "/F"]);
853            changed = true;
854        }
855    }
856    if startup_state_path().exists() {
857        let _ = fs::remove_file(startup_state_path());
858        changed = true;
859    }
860    if changed {
861        println!("Removed snip-sync-owned startup registration.");
862    } else {
863        println!("No snip-sync startup registration found.");
864    }
865    Ok(())
866}
867
868pub fn check_health(http_host: &str, http_port: u16) -> bool {
869    let address = match (http_host, http_port).to_socket_addrs() {
870        Ok(mut addresses) => match addresses.next() {
871            Some(address) => address,
872            None => return false,
873        },
874        Err(_) => return false,
875    };
876    let mut stream = match TcpStream::connect_timeout(&address, Duration::from_secs(2)) {
877        Ok(stream) => stream,
878        Err(_) => return false,
879    };
880    let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
881    let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
882    let request = format!("GET /health HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n");
883    if stream.write_all(request.as_bytes()).is_err() {
884        return false;
885    }
886    let mut response = [0u8; 4096];
887    let bytes_read = match stream.read(&mut response) {
888        Ok(bytes) => bytes,
889        Err(_) => return false,
890    };
891    let response = String::from_utf8_lossy(&response[..bytes_read]);
892    response.starts_with("HTTP/1.1 200") || response.starts_with("HTTP/1.0 200")
893}
894
895fn wait_for_health(config: &Config, timeout: Duration) -> Result<(), String> {
896    let deadline = Instant::now() + timeout;
897    while Instant::now() < deadline {
898        if check_health(&config.http_host, config.http_port) {
899            return Ok(());
900        }
901        std::thread::sleep(Duration::from_millis(250));
902    }
903    Err(format!(
904        "snip-sync did not become healthy at {}:{} within {} seconds",
905        config.http_host,
906        config.http_port,
907        timeout.as_secs()
908    ))
909}
910
911fn server_is_running() -> Result<bool, String> {
912    match crate::server_lock::ServerLock::try_acquire(&crate::paths::state_dir()) {
913        Ok(guard) => {
914            drop(guard);
915            Ok(false)
916        }
917        Err(crate::server_lock::ServerLockError::Busy { .. }) => Ok(true),
918        Err(error) => Err(error.to_string()),
919    }
920}
921
922/// Read-only lifecycle probe used by `update --dry-run`. It deliberately does
923/// not call `ServerLock::try_acquire`, because that API creates/publishes lock
924/// metadata when the server is absent.
925fn server_is_running_read_only() -> bool {
926    let path = crate::server_lock::server_lock_path(&crate::paths::state_dir());
927    let Some(owner) = crate::server_lock::read_owner(&path) else {
928        return false;
929    };
930    if !crate::process::is_running(owner.pid) {
931        return false;
932    }
933    owner.start_token.as_ref().is_none_or(|expected| {
934        crate::process::get_process_start_token(owner.pid).is_none_or(|actual| actual == *expected)
935    })
936}
937
938pub fn classify_update_lifecycle(
939    installed: Option<StartupMethod>,
940    running: bool,
941) -> UpdateLifecycle {
942    match (installed, running) {
943        (Some(method), true) => UpdateLifecycle::ManagedRunning(method),
944        (Some(method), false) => UpdateLifecycle::ManagedStopped(method),
945        (None, true) => UpdateLifecycle::DirectRunning,
946        (None, false) => UpdateLifecycle::NotRunning,
947    }
948}
949
950/// Capture the server state before an executable update. A stopped installed
951/// service is deliberately distinct from an absent service so an update never
952/// starts a server solely because it was requested.
953pub fn update_lifecycle() -> Result<UpdateLifecycle, String> {
954    Ok(classify_update_lifecycle(
955        installed_method(),
956        server_is_running_read_only(),
957    ))
958}
959
960fn restart_systemd() -> Result<(), String> {
961    run_checked("systemctl", &["restart", SYSTEMD_UNIT_NAME])?;
962    Ok(())
963}
964
965fn restart_launchd() -> Result<(), String> {
966    let target = format!("system/{LAUNCHD_LABEL}");
967    run_checked("launchctl", &["kickstart", "-k", &target])?;
968    Ok(())
969}
970
971fn spawn_server(executable: &Path) -> Result<(), String> {
972    Command::new(executable)
973        .arg("serve")
974        .stdin(Stdio::null())
975        .stdout(Stdio::null())
976        .stderr(Stdio::null())
977        .spawn()
978        .map(|_| ())
979        .map_err(|e| format!("failed to start detached server: {e}"))
980}
981
982/// Restart only a server that was running when the update began. Errors are
983/// intentionally returned after the binary replacement; callers can report a
984/// partial activation without rolling the verified binary back.
985pub fn restart_after_update(
986    executable: &Path,
987    lifecycle: UpdateLifecycle,
988    force: bool,
989) -> Result<(), String> {
990    let config = || Config::load().map_err(|e| e.to_string());
991    match lifecycle {
992        UpdateLifecycle::ManagedRunning(StartupMethod::Systemd) => {
993            restart_systemd()?;
994            wait_for_health(&config()?, Duration::from_secs(10))
995        }
996        UpdateLifecycle::ManagedRunning(StartupMethod::Launchd) => {
997            restart_launchd()?;
998            wait_for_health(&config()?, Duration::from_secs(10))
999        }
1000        UpdateLifecycle::ManagedRunning(StartupMethod::Cron | StartupMethod::TaskScheduler) => {
1001            let mut stop = Command::new(executable);
1002            stop.arg("stop");
1003            if force {
1004                stop.arg("--force");
1005            }
1006            let status = stop
1007                .status()
1008                .map_err(|e| format!("failed to stop server for managed restart: {e}"))?;
1009            if !status.success() {
1010                return Err("managed restart could not stop the running server".into());
1011            }
1012            spawn_croncheck(executable)?;
1013            wait_for_health(&config()?, Duration::from_secs(10))
1014        }
1015        UpdateLifecycle::DirectRunning | UpdateLifecycle::ManagedRunning(StartupMethod::Direct) => {
1016            let mut stop = Command::new(executable);
1017            stop.arg("stop");
1018            if force {
1019                stop.arg("--force");
1020            }
1021            let status = stop
1022                .status()
1023                .map_err(|e| format!("failed to stop server for restart: {e}"))?;
1024            if !status.success() {
1025                return Err("direct restart could not stop the running server".into());
1026            }
1027            spawn_server(executable)?;
1028            wait_for_health(&config()?, Duration::from_secs(10))
1029        }
1030        UpdateLifecycle::ManagedStopped(_) | UpdateLifecycle::NotRunning => Ok(()),
1031    }
1032}
1033
1034fn spawn_croncheck(executable: &Path) -> Result<(), String> {
1035    Command::new(executable)
1036        .arg("croncheck")
1037        .stdin(Stdio::null())
1038        .stdout(Stdio::null())
1039        .stderr(Stdio::null())
1040        .spawn()
1041        .map(|_| ())
1042        .map_err(|e| format!("failed to start detached croncheck: {e}"))
1043}
1044
1045/// Restart through an installed manager. `Ok(false)` means the caller should
1046/// use the existing unmanaged stop + foreground serve path.
1047pub fn restart_if_managed(executable: &Path, force: bool) -> Result<bool, String> {
1048    let Some(method) = installed_method() else {
1049        return Ok(false);
1050    };
1051    match method {
1052        StartupMethod::Systemd => {
1053            let state = Command::new("systemctl")
1054                .args(["is-active", "--quiet", SYSTEMD_UNIT_NAME])
1055                .status()
1056                .map_err(|e| format!("failed to inspect systemd service: {e}"))?;
1057            let action = if state.success() { "restart" } else { "start" };
1058            run_checked("systemctl", &[action, SYSTEMD_UNIT_NAME])?;
1059            let config = Config::load().map_err(|e| e.to_string())?;
1060            wait_for_health(&config, Duration::from_secs(10))?;
1061            Ok(true)
1062        }
1063        StartupMethod::Launchd => {
1064            let target = format!("system/{LAUNCHD_LABEL}");
1065            let loaded = Command::new("launchctl")
1066                .args(["print", &target])
1067                .status()
1068                .map_err(|e| format!("failed to inspect launchd job: {e}"))?
1069                .success();
1070            if loaded {
1071                run_checked("launchctl", &["kickstart", "-k", &target])?;
1072            } else {
1073                let path = launchd_plist_path();
1074                let path = path
1075                    .to_str()
1076                    .ok_or_else(|| "plist path is not UTF-8".to_string())?;
1077                run_checked("launchctl", &["bootstrap", "system", path])?;
1078            }
1079            let config = Config::load().map_err(|e| e.to_string())?;
1080            wait_for_health(&config, Duration::from_secs(10))?;
1081            Ok(true)
1082        }
1083        StartupMethod::Cron | StartupMethod::TaskScheduler => {
1084            if server_is_running()? {
1085                let mut stop = Command::new(executable);
1086                stop.arg("stop");
1087                if force {
1088                    stop.arg("--force");
1089                }
1090                let status = stop
1091                    .status()
1092                    .map_err(|e| format!("failed to run stop: {e}"))?;
1093                if !status.success() {
1094                    return Err("managed restart could not stop the running server".into());
1095                }
1096            }
1097            spawn_croncheck(executable)?;
1098            Ok(true)
1099        }
1100        StartupMethod::Direct => Ok(false),
1101    }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106    use super::*;
1107
1108    #[test]
1109    fn update_lifecycle_decision_table_preserves_stopped_state() {
1110        assert_eq!(
1111            classify_update_lifecycle(Some(StartupMethod::Systemd), true),
1112            UpdateLifecycle::ManagedRunning(StartupMethod::Systemd)
1113        );
1114        assert_eq!(
1115            classify_update_lifecycle(Some(StartupMethod::TaskScheduler), false),
1116            UpdateLifecycle::ManagedStopped(StartupMethod::TaskScheduler)
1117        );
1118        assert_eq!(
1119            classify_update_lifecycle(None, true),
1120            UpdateLifecycle::DirectRunning
1121        );
1122        assert_eq!(
1123            classify_update_lifecycle(None, false),
1124            UpdateLifecycle::NotRunning
1125        );
1126    }
1127
1128    fn loopback_env() -> TransportEnvironment {
1129        TransportEnvironment {
1130            entries: vec![("SNIP_SYNC_ALLOW_HTTP".into(), "true".into())],
1131        }
1132    }
1133
1134    #[test]
1135    fn systemd_requires_actual_runtime_markers() {
1136        assert!(!systemd_environment_is_running(false, Some("init"), false));
1137        assert!(systemd_environment_is_running(true, Some("init"), false));
1138        assert!(systemd_environment_is_running(
1139            false,
1140            Some("systemd"),
1141            false
1142        ));
1143        assert!(systemd_environment_is_running(false, Some("init"), true));
1144    }
1145
1146    fn systemd_environment_is_running(
1147        run_dir_exists: bool,
1148        pid_one_comm: Option<&str>,
1149        bounded_probe_succeeded: bool,
1150    ) -> bool {
1151        run_dir_exists || pid_one_comm == Some("systemd") || bounded_probe_succeeded
1152    }
1153
1154    #[test]
1155    fn shell_and_windows_quoting_rejects_controls() {
1156        assert_eq!(
1157            shell_quote(Path::new("/tmp/a'b")),
1158            Ok("'/tmp/a'\\''b'".into())
1159        );
1160        assert!(shell_quote(Path::new("/tmp/a\n")).is_err());
1161        assert!(windows_quote(Path::new("C:\\tmp\\a\n")).is_err());
1162    }
1163
1164    #[test]
1165    fn renders_exact_supervisor_records() {
1166        let executable = Path::new("/opt/snip-sync");
1167        let systemd = render_systemd_unit(executable, "alice", &loopback_env()).unwrap();
1168        assert!(systemd.contains("ExecStart=\"/opt/snip-sync\" serve"));
1169        assert!(systemd.contains("RestartSec=2"));
1170        assert!(
1171            render_launchd_plist(executable, "alice", &loopback_env())
1172                .unwrap()
1173                .contains("com.eggstack.snip-sync")
1174        );
1175        let cron = render_cron_block(executable, &loopback_env()).unwrap();
1176        assert!(cron.contains("@reboot SNIP_SYNC_ALLOW_HTTP='true' '/opt/snip-sync' croncheck"));
1177        assert!(!cron.contains(" serve"));
1178        let task = render_task_commands(executable, &loopback_env(), true).unwrap();
1179        assert!(task.iter().all(|line| line.contains("croncheck")));
1180    }
1181
1182    #[test]
1183    fn cron_replacement_is_idempotent_and_preserves_unrelated_entries() {
1184        let existing = "MAILTO=alice\n\n# old\n";
1185        let block = render_cron_block(Path::new("/tmp/snip-sync"), &loopback_env()).unwrap();
1186        let once = replace_cron_block(existing, Some(&block));
1187        let twice = replace_cron_block(&once, Some(&block));
1188        assert_eq!(once, twice);
1189        assert!(replace_cron_block(&twice, None).contains("MAILTO=alice"));
1190        assert!(!replace_cron_block(&twice, None).contains(CRON_BEGIN));
1191        let malformed = format!("MAILTO=alice\n{CRON_BEGIN}\n# unrelated trailing entry");
1192        assert!(replace_cron_block(&malformed, None).contains("# unrelated trailing entry"));
1193    }
1194
1195    #[test]
1196    fn transport_policy_only_allows_plaintext_loopback() {
1197        assert!(validate_transport_policy(false, true, true, true).is_ok());
1198        assert!(validate_transport_policy(true, false, false, false).is_ok());
1199        assert!(validate_transport_policy(false, true, false, true).is_err());
1200        assert!(validate_transport_policy(false, false, true, true).is_err());
1201    }
1202}