Skip to main content

pitchfork_cli/
boot_manager.rs

1#[cfg(windows)]
2mod windows;
3
4// ─── Supported platforms (macOS, Linux, Windows) ──────────────────────────
5
6#[cfg(any(target_os = "macos", target_os = "linux", windows))]
7mod imp {
8    #[cfg(windows)]
9    use super::windows::WindowsLauncher as AutoLaunch;
10    use crate::{Result, env};
11    #[cfg(target_os = "linux")]
12    use auto_launcher::LinuxLaunchMode;
13    #[cfg(target_os = "macos")]
14    use auto_launcher::MacOSLaunchMode;
15    #[cfg(any(target_os = "macos", target_os = "linux"))]
16    use auto_launcher::{AutoLaunch, AutoLaunchBuilder};
17    use miette::IntoDiagnostic;
18
19    /// Arguments of the registered `pitchfork` command.
20    ///
21    /// A system registration made through sudo records the invoking user, since
22    /// launchd and systemd start the service without the sudo environment.
23    pub(crate) fn service_args(invoking_user: Option<&str>) -> Vec<String> {
24        let mut args: Vec<String> = ["supervisor", "run", "--boot"]
25            .into_iter()
26            .map(String::from)
27            .collect();
28        if let Some(user) = invoking_user {
29            args.push(env::INVOKING_USER_FLAG.to_string());
30            args.push(user.to_string());
31        }
32        args
33    }
34
35    #[cfg(any(target_os = "macos", target_os = "linux"))]
36    fn build_launcher(
37        app_path: &str,
38        args: &[String],
39        #[cfg(target_os = "macos")] macos_mode: MacOSLaunchMode,
40        #[cfg(target_os = "linux")] linux_mode: LinuxLaunchMode,
41    ) -> Result<AutoLaunch> {
42        let mut builder = AutoLaunchBuilder::new();
43        builder
44            .set_app_name("pitchfork")
45            .set_app_path(app_path)
46            .set_args(args);
47
48        #[cfg(target_os = "macos")]
49        builder.set_macos_launch_mode(macos_mode);
50
51        #[cfg(target_os = "linux")]
52        builder.set_linux_launch_mode(linux_mode);
53
54        builder.build().into_diagnostic()
55    }
56
57    pub struct BootManager {
58        /// Literal executable spelling selected for boot registration only.
59        app_path: String,
60        explicit_executable: bool,
61        /// User recorded in the system registration, if any.
62        invoking_user: Option<String>,
63        /// The launcher selected for writing registrations.
64        current: AutoLaunch,
65        /// The other level's launcher (used to detect cross-level registrations).
66        #[cfg(any(target_os = "macos", target_os = "linux"))]
67        other: AutoLaunch,
68        /// Legacy macOS LaunchAgentSystem entry (pre-1.0.3 used /Library/LaunchAgents/
69        /// instead of /Library/LaunchDaemons/ for root). Kept only for migration/cleanup.
70        #[cfg(target_os = "macos")]
71        legacy: AutoLaunch,
72    }
73
74    /// Where the system-level registration lives.
75    #[cfg(target_os = "macos")]
76    const SYSTEM_REGISTRATION: &str = "/Library/LaunchDaemons/pitchfork.plist";
77    #[cfg(target_os = "linux")]
78    const SYSTEM_REGISTRATION: &str = "/etc/systemd/system/pitchfork.service";
79
80    /// The invoking user recorded in the system-level registration, if the
81    /// registration exists, can be read, and records one.
82    #[cfg(any(target_os = "macos", target_os = "linux"))]
83    fn registered_system_invoking_user() -> Option<String> {
84        let contents = match std::fs::read(SYSTEM_REGISTRATION) {
85            Ok(contents) => contents,
86            Err(err) => {
87                if err.kind() != std::io::ErrorKind::NotFound {
88                    warn!("failed to read {SYSTEM_REGISTRATION}: {err}");
89                }
90                return None;
91            }
92        };
93        #[cfg(target_os = "macos")]
94        let argv = super::launchd_program_arguments(&contents);
95        #[cfg(target_os = "linux")]
96        let argv = super::systemd_exec_start(&String::from_utf8_lossy(&contents));
97        env::invoking_user_arg(argv?.into_iter().map(Into::into))
98    }
99
100    /// Write the launchd registration, then add the crash-restart keys that
101    /// `auto-launcher` does not emit (the macOS counterpart of systemd's
102    /// `Restart=on-failure`).
103    fn write_registration(launcher: &AutoLaunch) -> Result<()> {
104        // `enable` writes the plist anew, so a restart policy the user set on
105        // the registration is read first and put back afterwards.
106        #[cfg(target_os = "macos")]
107        let path = current_plist_path()?;
108        #[cfg(target_os = "macos")]
109        let previous = match std::fs::read(&path) {
110            Ok(previous) => Some(previous),
111            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
112            Err(e) => {
113                warn!("cannot read the existing launchd plist to keep its restart policy: {e}");
114                None
115            }
116        };
117        launcher.enable().into_diagnostic()?;
118        #[cfg(target_os = "macos")]
119        add_keep_alive(&path, previous.as_deref())?;
120        Ok(())
121    }
122
123    /// The launchd plist `auto-launcher` writes at the current privilege level.
124    #[cfg(target_os = "macos")]
125    fn current_plist_path() -> Result<std::path::PathBuf> {
126        if nix::unistd::Uid::effective().is_root() {
127            return Ok(SYSTEM_REGISTRATION.into());
128        }
129        let home =
130            dirs::home_dir().ok_or_else(|| miette::miette!("failed to find home directory"))?;
131        Ok(home.join("Library/LaunchAgents/pitchfork.plist"))
132    }
133
134    #[cfg(target_os = "macos")]
135    fn add_keep_alive(path: &std::path::Path, previous: Option<&[u8]>) -> Result<()> {
136        let mut contents = std::fs::read(path).into_diagnostic()?;
137        let mut changed = false;
138        if let Some(restored) =
139            previous.and_then(|p| super::launchd_with_restart_policy_of(&contents, p))
140        {
141            contents = restored;
142            changed = true;
143        }
144        if let Some(updated) = super::launchd_with_keep_alive(&contents) {
145            contents = updated;
146            changed = true;
147        }
148        if changed {
149            std::fs::write(path, contents).into_diagnostic()?;
150        }
151        Ok(())
152    }
153
154    impl BootManager {
155        /// Manager whose current-level registration records the user this
156        /// process acts on behalf of (see [`env::boot_service_invoking_user`]).
157        pub fn new() -> Result<Self> {
158            #[cfg(any(target_os = "macos", target_os = "linux"))]
159            return Self::with_invoking_user(env::boot_service_invoking_user()?);
160            #[cfg(windows)]
161            Self::with_invoking_user(None)
162        }
163
164        /// Manager whose current-level registration records `invoking_user`.
165        /// Only the current level's registration is ever written, and for root
166        /// that is the system registration.
167        fn with_invoking_user(invoking_user: Option<String>) -> Result<Self> {
168            let configured = crate::settings::settings().boot.executable.clone();
169            let explicit_executable = !configured.is_empty();
170            let app_path = if configured.is_empty() {
171                env::PITCHFORK_BIN.to_string_lossy().to_string()
172            } else {
173                configured
174            };
175
176            #[cfg(any(target_os = "macos", target_os = "linux"))]
177            let (current_args, other_args) =
178                (service_args(invoking_user.as_deref()), service_args(None));
179
180            #[cfg(target_os = "macos")]
181            let (current, other, legacy) = {
182                let is_root = nix::unistd::Uid::effective().is_root();
183                let (current_mode, other_mode) = if is_root {
184                    (
185                        MacOSLaunchMode::LaunchDaemonSystem,
186                        MacOSLaunchMode::LaunchAgentUser,
187                    )
188                } else {
189                    (
190                        MacOSLaunchMode::LaunchAgentUser,
191                        MacOSLaunchMode::LaunchDaemonSystem,
192                    )
193                };
194                (
195                    build_launcher(&app_path, &current_args, current_mode)?,
196                    build_launcher(&app_path, &other_args, other_mode)?,
197                    build_launcher(&app_path, &other_args, MacOSLaunchMode::LaunchAgentSystem)?,
198                )
199            };
200
201            #[cfg(target_os = "linux")]
202            let (current, other) = {
203                let is_root = nix::unistd::Uid::effective().is_root();
204                let (current_mode, other_mode) = if is_root {
205                    (LinuxLaunchMode::SystemdSystem, LinuxLaunchMode::SystemdUser)
206                } else {
207                    (LinuxLaunchMode::SystemdUser, LinuxLaunchMode::SystemdSystem)
208                };
209                (
210                    build_launcher(&app_path, &current_args, current_mode)?,
211                    build_launcher(&app_path, &other_args, other_mode)?,
212                )
213            };
214
215            // Windows uses one launcher, which handles both registry roots.
216            #[cfg(windows)]
217            let current = AutoLaunch::new(&app_path, &service_args(None));
218
219            #[cfg(target_os = "macos")]
220            return Ok(Self {
221                app_path,
222                explicit_executable,
223                invoking_user,
224                current,
225                other,
226                legacy,
227            });
228
229            #[cfg(not(target_os = "macos"))]
230            Ok(Self {
231                app_path,
232                explicit_executable,
233                invoking_user,
234                current,
235                #[cfg(target_os = "linux")]
236                other,
237            })
238        }
239
240        /// Validate only explicit choices, and only before registration work.
241        /// Status/disable must remain usable when an executable has disappeared.
242        fn validate_executable(&self) -> Result<()> {
243            if !self.explicit_executable {
244                return Ok(());
245            }
246            let invalid = |reason: &str| {
247                miette::miette!(
248                    "settings.boot.executable '{}': {reason}; set an absolute path to an \
249                     existing executable, or unset the setting to use the running binary",
250                    self.app_path
251                )
252            };
253            let path = std::path::Path::new(&self.app_path);
254            if !path.is_absolute() {
255                return Err(invalid(
256                    "path must be absolute (no PATH or tilde expansion)",
257                ));
258            }
259            if self.app_path.chars().any(char::is_control) {
260                return Err(invalid("path must not contain control characters"));
261            }
262            // auto-launcher's systemd format cannot quote an executable path.
263            #[cfg(target_os = "linux")]
264            if self.app_path.chars().any(char::is_whitespace) {
265                return Err(invalid(
266                    "boot registration does not support whitespace in paths on this platform",
267                ));
268            }
269            #[cfg(target_os = "linux")]
270            if self.app_path.contains(['\"', '\'', '\\', '%', '$']) {
271                return Err(invalid(
272                    "boot registration does not support quotes, backslashes, percent signs or dollar signs in systemd executable paths",
273                ));
274            }
275            let metadata = std::fs::metadata(path)
276                .map_err(|e| invalid(&format!("cannot access executable: {e}")))?;
277            if !metadata.is_file() {
278                return Err(invalid("path is not a regular file"));
279            }
280            #[cfg(unix)]
281            {
282                let path = std::ffi::CString::new(self.app_path.as_bytes())
283                    .map_err(|_| invalid("path contains a NUL byte"))?;
284                // SAFETY: path is a valid, NUL-terminated string. access only
285                // checks permissions; it does not run the configured program.
286                if unsafe { libc::access(path.as_ptr(), libc::X_OK) } != 0 {
287                    return Err(invalid("file is not executable by this user"));
288                }
289            }
290            Ok(())
291        }
292
293        /// User recorded in the registration written at the current level.
294        pub fn invoking_user(&self) -> Option<&str> {
295            self.invoking_user.as_deref()
296        }
297
298        /// Whether the system-level registration exists.
299        pub fn is_system_level_enabled(&self) -> Result<bool> {
300            #[cfg(any(target_os = "macos", target_os = "linux"))]
301            let system = if nix::unistd::Uid::effective().is_root() {
302                &self.current
303            } else {
304                &self.other
305            };
306            #[cfg(any(target_os = "macos", target_os = "linux"))]
307            return system.is_enabled().into_diagnostic();
308            #[cfg(windows)]
309            Ok(false)
310        }
311
312        /// The invoking user recorded in the existing system-level
313        /// registration. Readable without root.
314        pub fn system_invoking_user(&self) -> Option<String> {
315            #[cfg(any(target_os = "macos", target_os = "linux"))]
316            return registered_system_invoking_user();
317            #[cfg(windows)]
318            None
319        }
320
321        /// Whether the current-level registration already has the selected
322        /// boot executable and invoking user, so `enable` has nothing to change.
323        pub fn is_current_level_up_to_date(&self) -> Result<bool> {
324            self.validate_executable()?;
325            let registered = self.current.get_registered_app_path().into_diagnostic()?;
326            if registered.as_deref() != Some(self.app_path.as_str()) {
327                return Ok(false);
328            }
329            // Registrations written before crash-restart was added lack it.
330            #[cfg(target_os = "macos")]
331            {
332                let plist = std::fs::read(current_plist_path()?).into_diagnostic()?;
333                if super::launchd_with_keep_alive(&plist).is_some() {
334                    return Ok(false);
335                }
336            }
337            #[cfg(any(target_os = "macos", target_os = "linux"))]
338            if nix::unistd::Uid::effective().is_root() {
339                return Ok(registered_system_invoking_user() == self.invoking_user);
340            }
341            Ok(true)
342        }
343
344        /// Whether any registration (user- or system-level) exists.
345        pub fn is_enabled(&self) -> Result<bool> {
346            #[cfg(target_os = "macos")]
347            return Ok(self.current.is_enabled().into_diagnostic()?
348                || self.other.is_enabled().into_diagnostic()?
349                || self.legacy.is_enabled().into_diagnostic()?);
350
351            #[cfg(target_os = "linux")]
352            return Ok(self.current.is_enabled().into_diagnostic()?
353                || self.other.is_enabled().into_diagnostic()?);
354            #[cfg(windows)]
355            self.current.is_enabled().into_diagnostic()
356        }
357
358        /// Whether a registration at the *current* privilege level exists.
359        pub fn is_current_level_enabled(&self) -> Result<bool> {
360            self.current.is_enabled().into_diagnostic()
361        }
362
363        /// Whether a registration at the *other* privilege level exists.
364        /// Used to warn the user about cross-level mismatches.
365        /// On macOS, includes legacy entries for non-root callers (they are at a
366        /// different privilege level) but not for root callers (legacy is same level).
367        pub fn is_other_level_enabled(&self) -> Result<bool> {
368            #[cfg(target_os = "macos")]
369            return Ok(self.other.is_enabled().into_diagnostic()?
370                || (!nix::unistd::Uid::effective().is_root()
371                    && self.legacy.is_enabled().into_diagnostic()?));
372
373            #[cfg(target_os = "linux")]
374            return self.other.is_enabled().into_diagnostic();
375            #[cfg(windows)]
376            Ok(false)
377        }
378
379        /// Remove legacy macOS LaunchAgentSystem entry if present and caller is root.
380        /// Idempotent — safe to call on every enable path, including retries after
381        /// partial migration (new entry written but legacy removal failed).
382        ///
383        /// `migrated`: true when called after writing a new LaunchDaemonSystem entry
384        /// (full migration); false when just removing a stale leftover.
385        #[cfg(target_os = "macos")]
386        pub fn cleanup_legacy(&self, migrated: bool) -> Result<()> {
387            if nix::unistd::Uid::effective().is_root()
388                && self.legacy.is_enabled().into_diagnostic()?
389            {
390                self.legacy.disable().into_diagnostic()?;
391                if migrated {
392                    info!(
393                        "migrated legacy system-level launch entry from /Library/LaunchAgents/ to /Library/LaunchDaemons/"
394                    );
395                } else {
396                    info!("removed legacy system-level launch entry from /Library/LaunchAgents/");
397                }
398            }
399            Ok(())
400        }
401
402        /// Enable boot startup.
403        ///
404        /// On macOS and Linux, returns an error if a registration at the other
405        /// privilege level exists, preventing cross-level registrations.
406        /// On Windows, updates an existing registration in its original root;
407        /// only new registrations choose a root based on write access.
408        ///
409        /// On macOS, migrates any legacy LaunchAgentSystem entry (from pre-1.0.3)
410        /// to the correct LaunchDaemonSystem entry.
411        pub fn enable(&self) -> Result<()> {
412            self.validate_executable()?;
413            // For root, legacy will be migrated so only check non-legacy other level.
414            // For non-root, legacy cannot be migrated and is also a conflict.
415            #[cfg(target_os = "macos")]
416            let other_conflict = if nix::unistd::Uid::effective().is_root() {
417                self.other.is_enabled().into_diagnostic()?
418            } else {
419                self.is_other_level_enabled()?
420            };
421
422            #[cfg(target_os = "linux")]
423            let other_conflict = self.other.is_enabled().into_diagnostic()?;
424
425            #[cfg(windows)]
426            let other_conflict = false;
427
428            if other_conflict {
429                miette::bail!(
430                    "boot start is already registered at the other privilege level; \
431                    run `pitchfork boot disable` (with appropriate privileges) to remove \
432                    it first"
433                );
434            }
435
436            write_registration(&self.current)?;
437
438            #[cfg(target_os = "macos")]
439            self.cleanup_legacy(true)?;
440
441            Ok(())
442        }
443
444        /// Rewrite the existing registration, updating its binary path and
445        /// recorded invoking user. Windows preserves the existing registry root.
446        pub fn refresh(&self) -> Result<()> {
447            self.validate_executable()?;
448            write_registration(&self.current)?;
449
450            #[cfg(target_os = "macos")]
451            self.cleanup_legacy(false)?;
452
453            Ok(())
454        }
455
456        /// Remove registrations at *both* levels so cross-level leftovers are also
457        /// cleaned up. Also removes legacy macOS LaunchAgentSystem entries when
458        /// running as root. Returns Ok even if some entries could not be removed
459        /// due to insufficient privileges — callers should check is_enabled()
460        /// afterwards to detect incomplete cleanup.
461        pub fn disable(&self) -> Result<()> {
462            if self.current.is_enabled().into_diagnostic()? {
463                self.current.disable().into_diagnostic()?;
464            }
465            #[cfg(any(target_os = "macos", target_os = "linux"))]
466            if self.other.is_enabled().into_diagnostic()? {
467                self.other.disable().into_diagnostic()?;
468            }
469            #[cfg(target_os = "macos")]
470            if nix::unistd::Uid::effective().is_root()
471                && self.legacy.is_enabled().into_diagnostic()?
472            {
473                self.legacy.disable().into_diagnostic()?;
474            }
475            Ok(())
476        }
477
478        /// Check whether the registered boot binary path matches the selected
479        /// boot executable. If stale (binary moved after a package-manager upgrade),
480        /// re-register at the current privilege level so the next boot uses the
481        /// correct path.
482        ///
483        /// This is a no-op when boot start is not enabled, or when the registered
484        /// path already matches. Errors are logged and swallowed — this is a
485        /// best-effort self-heal that must not block supervisor startup.
486        #[cfg(any(target_os = "macos", target_os = "linux"))]
487        pub fn check_and_reregister_if_stale(&self) {
488            if let Err(e) = self.validate_executable() {
489                warn!("cannot repair boot registration: {e}");
490                return;
491            }
492            let current_bin = &self.app_path;
493
494            let registered = match self.current.get_registered_app_path() {
495                Ok(Some(path)) => path,
496                Ok(None) => return, // not registered, nothing to do
497                Err(e) => {
498                    warn!("failed to read registered boot path: {e}");
499                    return;
500                }
501            };
502
503            if registered == *current_bin {
504                return; // path matches, all good
505            }
506
507            info!(
508                "boot registration points to stale binary path '{registered}', \
509                re-registering with current path '{current_bin}'"
510            );
511
512            // Keep the invoking user the registration already records: this
513            // runs in whatever supervisor happens to start first, which must
514            // neither add a user to a root-shell registration nor drop one.
515            let preserved = if nix::unistd::Uid::effective().is_root() {
516                let registered = registered_system_invoking_user();
517                if registered == self.invoking_user {
518                    None
519                } else {
520                    match Self::with_invoking_user(registered) {
521                        Ok(manager) => Some(manager),
522                        Err(e) => {
523                            warn!("failed to prepare boot re-registration: {e}");
524                            return;
525                        }
526                    }
527                }
528            } else {
529                None
530            };
531            let launcher = preserved.as_ref().map_or(&self.current, |m| &m.current);
532
533            // Re-register by overwriting the existing registration file.
534            // Calling enable() directly (without disable first) ensures that
535            // if it fails, the stale registration is still present rather than
536            // missing entirely — a stale path is better than no path.
537            if let Err(e) = write_registration(launcher) {
538                warn!("failed to re-register boot start with current path: {e}");
539                return;
540            }
541
542            info!("boot registration updated to current binary path");
543        }
544
545        /// Repair a stale Windows boot path in its original registry root,
546        /// preserving Task Manager approval. Errors are logged without blocking
547        /// supervisor startup, and missing or current registrations are untouched.
548        #[cfg(windows)]
549        pub fn check_and_reregister_if_stale(&self) {
550            if let Err(e) = self.validate_executable() {
551                warn!("cannot repair boot registration: {e}");
552                return;
553            }
554            if let Err(e) = self.current.repair_if_stale() {
555                warn!("cannot repair boot registration: {e}");
556            }
557        }
558    }
559
560    #[cfg(all(test, target_os = "linux"))]
561    mod tests {
562        use super::BootManager;
563        use std::os::unix::fs::{PermissionsExt, symlink};
564
565        #[test]
566        fn refresh_preserves_executable_when_invoking_user_changes() {
567            // Root selects /etc regardless of HOME; never exercise that route.
568            assert!(
569                !nix::unistd::Uid::effective().is_root(),
570                "run this test as non-root"
571            );
572            if std::env::var_os("PITCHFORK_BOOT_METADATA_TEST_CHILD").is_none() {
573                let home = tempfile::tempdir().unwrap();
574                let bin = home.path().join("bin");
575                std::fs::create_dir(&bin).unwrap();
576                let systemctl = bin.join("systemctl");
577                std::fs::write(&systemctl, "#!/bin/sh\ncase \"$*\" in\n'--user daemon-reload'|'--user enable pitchfork.service') exit 0 ;;\n*) exit 99 ;;\nesac\n").unwrap();
578                std::fs::set_permissions(&systemctl, std::fs::Permissions::from_mode(0o755))
579                    .unwrap();
580                symlink(std::env::current_exe().unwrap(), bin.join("stable")).unwrap();
581                // Isolate settings/environment lazies from all other unit tests.
582                let output = std::process::Command::new(std::env::current_exe().unwrap())
583                    .args(["--exact", "boot_manager::imp::tests::refresh_preserves_executable_when_invoking_user_changes", "--nocapture"])
584                    .current_dir(home.path())
585                    .env("HOME", home.path())
586                    .env("PATH", &bin)
587                    .env("PITCHFORK_CONFIG_DIR", home.path())
588                    .env("PITCHFORK_BOOT_EXECUTABLE", bin.join("stable"))
589                    .env("PITCHFORK_BOOT_METADATA_TEST_CHILD", "1")
590                    .output().unwrap();
591                assert!(
592                    output.status.success(),
593                    "{}\n{}",
594                    String::from_utf8_lossy(&output.stdout),
595                    String::from_utf8_lossy(&output.stderr)
596                );
597                return;
598            }
599
600            // Use real BootManager registration with user-level fixture paths.
601            // This covers metadata writing, not root privilege routing or its
602            // automatic existing-account preservation branch.
603            let home = std::path::PathBuf::from(std::env::var_os("HOME").unwrap());
604            let stable = home.join("bin/stable");
605            let unit = home.join(".config/systemd/user/pitchfork.service");
606            for user in [Some("alice"), Some("bob"), None] {
607                let manager = BootManager::with_invoking_user(user.map(String::from)).unwrap();
608                manager.refresh().unwrap();
609                let contents = std::fs::read_to_string(&unit).unwrap();
610                let expected = match user {
611                    Some(user) => format!(
612                        "ExecStart={} supervisor run --boot --invoking-user {user}\n",
613                        stable.display()
614                    ),
615                    None => format!("ExecStart={} supervisor run --boot\n", stable.display()),
616                };
617                assert!(contents.contains(&expected), "{contents}");
618            }
619        }
620    }
621}
622
623// ─── Unsupported platforms ────────────────────────────────────────────────
624
625#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
626mod imp {
627    use crate::Result;
628
629    pub struct BootManager;
630
631    impl BootManager {
632        pub fn new() -> Result<Self> {
633            miette::bail!(
634                "boot management is not supported on this platform; \
635                only macOS, Linux, and Windows are supported"
636            );
637        }
638
639        pub fn is_enabled(&self) -> Result<bool> {
640            miette::bail!(
641                "boot management is not supported on this platform; \
642                only macOS, Linux, and Windows are supported"
643            );
644        }
645
646        pub fn is_current_level_enabled(&self) -> Result<bool> {
647            miette::bail!(
648                "boot management is not supported on this platform; \
649                only macOS, Linux, and Windows are supported"
650            );
651        }
652
653        pub fn is_other_level_enabled(&self) -> Result<bool> {
654            miette::bail!(
655                "boot management is not supported on this platform; \
656                only macOS, Linux, and Windows are supported"
657            );
658        }
659
660        pub fn enable(&self) -> Result<()> {
661            miette::bail!(
662                "boot management is not supported on this platform; \
663                only macOS, Linux, and Windows are supported"
664            );
665        }
666
667        pub fn refresh(&self) -> Result<()> {
668            miette::bail!(
669                "boot management is not supported on this platform; \
670                only macOS, Linux, and Windows are supported"
671            );
672        }
673
674        pub fn invoking_user(&self) -> Option<&str> {
675            None
676        }
677
678        pub fn is_system_level_enabled(&self) -> Result<bool> {
679            Ok(false)
680        }
681
682        pub fn system_invoking_user(&self) -> Option<String> {
683            None
684        }
685
686        pub fn is_current_level_up_to_date(&self) -> Result<bool> {
687            Ok(false)
688        }
689
690        pub fn disable(&self) -> Result<()> {
691            miette::bail!(
692                "boot management is not supported on this platform; \
693                only macOS, Linux, and Windows are supported"
694            );
695        }
696    }
697}
698
699pub use imp::BootManager;
700
701/// Command line of a systemd unit's `ExecStart=`, split as the unit was
702/// written: pitchfork's service arguments never need quoting.
703#[cfg(any(target_os = "linux", all(test, target_os = "macos")))]
704fn systemd_exec_start(unit: &str) -> Option<Vec<String>> {
705    unit.lines()
706        .find_map(|line| line.trim().strip_prefix("ExecStart="))
707        .map(|command| command.split_whitespace().map(String::from).collect())
708}
709
710/// `ProgramArguments` of a launchd plist.
711#[cfg(any(target_os = "macos", all(test, target_os = "linux")))]
712fn launchd_program_arguments(plist: &[u8]) -> Option<Vec<String>> {
713    let value = plist::Value::from_reader(std::io::Cursor::new(plist)).ok()?;
714    value
715        .as_dictionary()?
716        .get("ProgramArguments")?
717        .as_array()?
718        .iter()
719        .map(|arg| arg.as_string().map(String::from))
720        .collect()
721}
722
723/// The launchd keys that make up a registration's restart policy.
724#[cfg(any(target_os = "macos", all(test, target_os = "linux")))]
725const LAUNCHD_RESTART_KEYS: [&str; 2] = ["KeepAlive", "ThrottleInterval"];
726
727/// `plist` with the restart policy (`KeepAlive`, `ThrottleInterval`) of
728/// `previous`, the registration it replaces, or `None` when `previous` has
729/// none to carry over (or either cannot be parsed). Rewriting a registration,
730/// as repairing a stale executable path does, must not drop a policy the user
731/// set on it.
732#[cfg(any(target_os = "macos", all(test, target_os = "linux")))]
733fn launchd_with_restart_policy_of(plist: &[u8], previous: &[u8]) -> Option<Vec<u8>> {
734    let previous = plist::Value::from_reader(std::io::Cursor::new(previous)).ok()?;
735    let previous = previous.as_dictionary()?;
736    let mut value = plist::Value::from_reader(std::io::Cursor::new(plist)).ok()?;
737    let dict = value.as_dictionary_mut()?;
738    let mut changed = false;
739    for key in LAUNCHD_RESTART_KEYS {
740        if let Some(policy) = previous.get(key)
741            && dict.get(key) != Some(policy)
742        {
743            dict.insert(key.into(), policy.clone());
744            changed = true;
745        }
746    }
747    if !changed {
748        return None;
749    }
750    let mut out = Vec::new();
751    plist::to_writer_xml(&mut out, &value).ok()?;
752    Some(out)
753}
754
755/// `plist` with launchd's crash-restart keys added, or `None` when it already
756/// has a `KeepAlive` (or cannot be parsed). `SuccessfulExit = false` restarts
757/// the supervisor after a crash or SIGKILL but not after a clean exit, so
758/// `pitchfork supervisor stop` and `launchctl bootout` still stay stopped. The
759/// 10s throttle matches the systemd unit's `RestartSec=10`.
760///
761/// Only a plist with no `KeepAlive` at all gets them: one written before
762/// crash-restart was added. A `KeepAlive` of any other value, like a
763/// `ThrottleInterval` already there, is local launchd policy the user set on
764/// the registration, and is kept.
765#[cfg(any(target_os = "macos", all(test, target_os = "linux")))]
766fn launchd_with_keep_alive(plist: &[u8]) -> Option<Vec<u8>> {
767    let mut value = plist::Value::from_reader(std::io::Cursor::new(plist)).ok()?;
768    let dict = value.as_dictionary_mut()?;
769    if dict.contains_key("KeepAlive") {
770        return None;
771    }
772    let mut keep_alive = plist::Dictionary::new();
773    keep_alive.insert("SuccessfulExit".into(), plist::Value::Boolean(false));
774    dict.insert("KeepAlive".into(), plist::Value::Dictionary(keep_alive));
775    if !dict.contains_key("ThrottleInterval") {
776        dict.insert("ThrottleInterval".into(), plist::Value::Integer(10.into()));
777    }
778    let mut out = Vec::new();
779    plist::to_writer_xml(&mut out, &value).ok()?;
780    Some(out)
781}
782
783#[cfg(all(test, any(target_os = "macos", target_os = "linux")))]
784mod tests {
785    use super::imp::service_args;
786    use super::{
787        launchd_program_arguments, launchd_with_keep_alive, launchd_with_restart_policy_of,
788        systemd_exec_start,
789    };
790    use crate::env::invoking_user_arg;
791
792    fn argv(args: Option<Vec<String>>) -> Vec<std::ffi::OsString> {
793        args.unwrap().into_iter().map(Into::into).collect()
794    }
795
796    /// The system unit as `sudo pitchfork boot enable` writes it on Linux.
797    #[test]
798    fn invoking_user_is_read_back_from_systemd_unit() {
799        let unit = "[Unit]\nDescription=pitchfork\nAfter=multi-user.target\n\n\
800            [Service]\nType=simple\n\
801            ExecStart=/usr/local/bin/pitchfork supervisor run --boot --invoking-user alice\n\
802            Restart=on-failure\n";
803        let args = systemd_exec_start(unit);
804        assert_eq!(invoking_user_arg(argv(args)).as_deref(), Some("alice"));
805
806        let legacy = "[Service]\nExecStart=/usr/local/bin/pitchfork supervisor run --boot\n";
807        assert_eq!(invoking_user_arg(argv(systemd_exec_start(legacy))), None);
808        assert_eq!(systemd_exec_start("[Service]\n"), None);
809    }
810
811    /// The LaunchDaemon as `sudo pitchfork boot enable` writes it on macOS.
812    #[test]
813    fn invoking_user_is_read_back_from_launchd_plist() {
814        let plist = br#"<?xml version="1.0" encoding="UTF-8"?>
815<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
816<plist version="1.0">
817<dict>
818	<key>Label</key>
819	<string>pitchfork</string>
820	<key>ProgramArguments</key>
821	<array>
822		<string>/opt/homebrew/bin/pitchfork</string>
823		<string>supervisor</string>
824		<string>run</string>
825		<string>--boot</string>
826		<string>--invoking-user</string>
827		<string>alice</string>
828	</array>
829	<key>RunAtLoad</key>
830	<true/>
831	<key>SessionCreate</key>
832	<true/>
833</dict>
834</plist>"#;
835        let args = launchd_program_arguments(plist);
836        assert_eq!(invoking_user_arg(argv(args)).as_deref(), Some("alice"));
837        assert_eq!(launchd_program_arguments(b"not a plist"), None);
838    }
839
840    #[test]
841    fn service_args_without_invoking_user_keep_plain_boot_command() {
842        assert_eq!(service_args(None), ["supervisor", "run", "--boot"]);
843    }
844
845    #[test]
846    fn service_args_record_invoking_user() {
847        let args = service_args(Some("alice"));
848        assert_eq!(
849            args,
850            ["supervisor", "run", "--boot", "--invoking-user", "alice"]
851        );
852        // The service command line must yield the same user when the
853        // supervisor resolves paths from argv at startup.
854        let argv = std::iter::once("pitchfork".to_string())
855            .chain(args)
856            .map(std::ffi::OsString::from);
857        assert_eq!(
858            crate::env::invoking_user_arg(argv).as_deref(),
859            Some("alice")
860        );
861    }
862
863    #[test]
864    fn launchd_plist_gains_crash_restart_keys_once() {
865        let plist = br#"<?xml version="1.0" encoding="UTF-8"?>
866<plist version="1.0">
867<dict>
868    <key>Label</key><string>pitchfork</string>
869    <key>ProgramArguments</key><array><string>/bin/pitchfork</string><string>supervisor</string></array>
870    <key>RunAtLoad</key><true/>
871</dict>
872</plist>"#;
873        let updated = launchd_with_keep_alive(plist).unwrap();
874        let value = plist::Value::from_reader(std::io::Cursor::new(&updated)).unwrap();
875        let dict = value.as_dictionary().unwrap();
876        let keep_alive = dict.get("KeepAlive").unwrap().as_dictionary().unwrap();
877        assert_eq!(
878            keep_alive.get("SuccessfulExit").unwrap().as_boolean(),
879            Some(false)
880        );
881        assert_eq!(
882            dict.get("ThrottleInterval").unwrap().as_signed_integer(),
883            Some(10)
884        );
885        assert_eq!(dict.get("RunAtLoad").unwrap().as_boolean(), Some(true));
886        assert_eq!(launchd_program_arguments(&updated).unwrap().len(), 2);
887        assert_eq!(launchd_with_keep_alive(&updated), None);
888        assert_eq!(launchd_with_keep_alive(b"not a plist"), None);
889    }
890
891    /// A rewritten registration, as `auto-launcher` writes it, takes back
892    /// the restart policy of the one it replaces, and then needs no default.
893    #[test]
894    fn launchd_rewrite_keeps_the_previous_restart_policy() {
895        let rewritten = br#"<?xml version="1.0" encoding="UTF-8"?>
896<plist version="1.0">
897<dict>
898    <key>Label</key><string>pitchfork</string>
899    <key>ProgramArguments</key><array><string>/new/pitchfork</string></array>
900</dict>
901</plist>"#;
902        let previous = br#"<?xml version="1.0" encoding="UTF-8"?>
903<plist version="1.0">
904<dict>
905    <key>Label</key><string>pitchfork</string>
906    <key>ProgramArguments</key><array><string>/old/pitchfork</string></array>
907    <key>KeepAlive</key><true/>
908    <key>ThrottleInterval</key><integer>30</integer>
909</dict>
910</plist>"#;
911        let restored = launchd_with_restart_policy_of(rewritten, previous).unwrap();
912        let value = plist::Value::from_reader(std::io::Cursor::new(&restored)).unwrap();
913        let dict = value.as_dictionary().unwrap();
914        assert_eq!(dict.get("KeepAlive").unwrap().as_boolean(), Some(true));
915        assert_eq!(
916            dict.get("ThrottleInterval").unwrap().as_signed_integer(),
917            Some(30)
918        );
919        assert_eq!(
920            launchd_program_arguments(&restored).unwrap(),
921            vec!["/new/pitchfork".to_string()]
922        );
923        assert_eq!(launchd_with_keep_alive(&restored), None);
924
925        // A previous registration with no policy leaves the defaults to come.
926        let no_policy = br#"<?xml version="1.0" encoding="UTF-8"?>
927<plist version="1.0"><dict><key>Label</key><string>pitchfork</string></dict></plist>"#;
928        assert_eq!(launchd_with_restart_policy_of(rewritten, no_policy), None);
929        assert_eq!(
930            launchd_with_restart_policy_of(rewritten, b"not a plist"),
931            None
932        );
933        assert!(launchd_with_keep_alive(rewritten).is_some());
934    }
935
936    /// A `KeepAlive` the user set on the registration is their launchd
937    /// policy, not a registration from before crash-restart was added.
938    #[test]
939    fn launchd_plist_keeps_a_local_keep_alive_policy() {
940        let plist = br#"<?xml version="1.0" encoding="UTF-8"?>
941<plist version="1.0">
942<dict>
943    <key>Label</key><string>pitchfork</string>
944    <key>ProgramArguments</key><array><string>/bin/pitchfork</string><string>supervisor</string></array>
945    <key>KeepAlive</key><true/>
946    <key>ExitTimeOut</key><integer>240</integer>
947</dict>
948</plist>"#;
949        assert_eq!(launchd_with_keep_alive(plist), None);
950
951        // Without a KeepAlive, a ThrottleInterval already there is kept too.
952        let plist = br#"<?xml version="1.0" encoding="UTF-8"?>
953<plist version="1.0">
954<dict>
955    <key>Label</key><string>pitchfork</string>
956    <key>ThrottleInterval</key><integer>30</integer>
957</dict>
958</plist>"#;
959        let updated = launchd_with_keep_alive(plist).unwrap();
960        let value = plist::Value::from_reader(std::io::Cursor::new(&updated)).unwrap();
961        let dict = value.as_dictionary().unwrap();
962        assert!(dict.get("KeepAlive").unwrap().as_dictionary().is_some());
963        assert_eq!(
964            dict.get("ThrottleInterval").unwrap().as_signed_integer(),
965            Some(30)
966        );
967    }
968}