blivet 0.9.0

A correct, full-featured Unix daemon library and CLI for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Post-fork daemonization steps.
//!
//! Each function corresponds to one step in the daemonization sequence
//! orchestrated by [`daemonize_inner`](crate::daemonize_inner). They are
//! collected here rather than inlined because each is independently testable.

use std::os::fd::{AsFd, AsRawFd, OwnedFd};
use std::path::{Path, PathBuf};

use nix::fcntl::{open, Flock, FlockArg, OFlag};
use nix::sys::stat::Mode;
use nix::unistd::{self, Whence};

use crate::error::DaemonizeError;
use crate::unsafe_ops;
use crate::util::paths_same;

// ---- Plan/Execute types for redirect_output ----

/// Describes what to do with a single output stream (stdout or stderr).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StreamAction {
    /// Leave the stream as-is (already redirected to /dev/null).
    None,
    /// Open a file and redirect the target fd to it.
    OpenAndRedirect {
        path: PathBuf,
        flags: OFlag,
        target_fd: i32,
    },
    /// Dup an already-open fd to the target fd.
    DupFrom { source_fd: i32, target_fd: i32 },
}

/// Plan for redirecting stdout and stderr.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct OutputRedirectPlan {
    pub(crate) stdout: StreamAction,
    pub(crate) stderr: StreamAction,
}

/// Step 4: Set process umask.
///
/// `mode` is an octal permission value (validated `<= 0o7777` by
/// [`DaemonConfig::validate`](crate::DaemonConfig::validate)); the cast to
/// `mode_t` is therefore lossless.
pub(crate) fn set_umask(mode: u32) {
    nix::sys::stat::umask(Mode::from_bits_truncate(mode as libc::mode_t));
}

/// Step 5: Change working directory.
pub(crate) fn change_dir(path: &Path) -> Result<(), DaemonizeError> {
    nix::unistd::chdir(path)
        .map_err(|e| DaemonizeError::ChdirFailed(format!("{}: {e}", path.display())))
}

/// Step 6: Redirect standard streams to /dev/null.
///
/// Always redirects stdin. When `stdout_stderr` is true, also redirects
/// stdout and stderr. In foreground mode, stdout/stderr are left
/// inherited so output reaches the parent terminal or supervisor.
///
/// # Panics
///
/// Panics if /dev/null cannot be opened or dup2 fails.
pub(crate) fn redirect_to_devnull(stdout_stderr: bool) {
    let devnull =
        open(c"/dev/null", OFlag::O_RDWR, Mode::empty()).expect("failed to open /dev/null");
    unistd::dup2_stdin(&devnull).expect("failed to dup2 /dev/null to stdin");
    if stdout_stderr {
        unistd::dup2_stdout(&devnull).expect("failed to dup2 /dev/null to stdout");
        unistd::dup2_stderr(&devnull).expect("failed to dup2 /dev/null to stderr");
    }
    if devnull.as_raw_fd() <= 2 {
        // devnull IS one of the stdio fds — don't close it on drop.
        std::mem::forget(devnull);
    }
}

/// Step 7: Open and exclusively lock a lockfile.
pub(crate) fn open_and_lock(path: &Path) -> Result<Flock<OwnedFd>, DaemonizeError> {
    let fd = open(
        path,
        OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_CLOEXEC,
        Mode::from_bits_truncate(0o644),
    )
    .map_err(|e| DaemonizeError::LockfileError(format!("cannot open {}: {e}", path.display())))?;

    Flock::lock(fd, FlockArg::LockExclusiveNonblock).map_err(|(_fd, e)| {
        if e == nix::errno::Errno::EWOULDBLOCK {
            DaemonizeError::LockConflict(format!(
                "{} is already locked by another process",
                path.display()
            ))
        } else {
            DaemonizeError::LockfileError(format!("flock {}: {e}", path.display()))
        }
    })
}

/// Step 8: Write PID to pidfile.
///
/// If the pidfile is the same path as the lockfile, seeks to 0, truncates,
/// and writes to the already-locked fd. Otherwise opens, writes, and closes.
pub(crate) fn write_pidfile(
    pidfile_path: &Path,
    lockfile: Option<(&Path, &Flock<OwnedFd>)>,
) -> Result<(), DaemonizeError> {
    let pid = std::process::id();
    let content = format!("{pid}\n");

    // Check if pidfile is the same as lockfile
    let shared = match lockfile {
        Some((lp, flock)) if paths_same(pidfile_path, lp) => Some(flock),
        _ => None,
    };

    if let Some(flock) = shared {
        // Write to already-locked fd: seek, truncate, write
        nix::unistd::lseek(flock.as_fd(), 0, Whence::SeekSet)
            .map_err(|e| DaemonizeError::PidfileError(format!("seek: {e}")))?;
        nix::unistd::ftruncate(flock.as_fd(), 0)
            .map_err(|e| DaemonizeError::PidfileError(format!("truncate: {e}")))?;
        write_all_fd(flock.as_fd(), content.as_bytes())
            .map_err(|e| DaemonizeError::PidfileError(format!("write: {e}")))?;
    } else {
        // Open, write, close
        std::fs::write(pidfile_path, content.as_bytes()).map_err(|e| {
            DaemonizeError::PidfileError(format!("write {}: {e}", pidfile_path.display()))
        })?;
    }

    Ok(())
}

/// Step 10: Clear the signal mask.
///
/// # Panics
///
/// Panics if sigprocmask fails.
pub(crate) fn clear_signal_mask() {
    use nix::sys::signal::{SigSet, SigmaskHow};
    nix::sys::signal::sigprocmask(SigmaskHow::SIG_SETMASK, Some(&SigSet::empty()), None)
        .expect("sigprocmask failed");
}

/// Step 11: Set environment variables in insertion order.
///
/// Uses `std::env::set_var`, which is not thread-safe. Sound here because this
/// runs only inside the daemonization sequence: post-fork the child is
/// single-threaded by `fork` semantics, and in foreground mode the entry point
/// ([`daemonize`](crate::daemonize) /
/// [`daemonize_unchecked`](crate::daemonize_unchecked)) requires
/// single-threadedness. No other thread can touch `environ`.
#[allow(unsafe_code)]
pub(crate) fn set_env_vars(env: &[(String, String)]) {
    for (key, value) in env {
        // SAFETY: single-threaded per this fn's contract (post-fork child or
        // foreground entry gate), so the `setenv` cannot race.
        unsafe { std::env::set_var(key, value) };
    }
}

/// Build an [`OutputRedirectPlan`] describing how to redirect stdout/stderr.
///
/// This is pure logic with no side effects — it decides *what* to do based on
/// the configured paths and append flag, without touching any file descriptors.
pub(crate) fn plan_output_redirect(
    stdout: Option<&Path>,
    stderr: Option<&Path>,
    append: bool,
) -> OutputRedirectPlan {
    let mut flags = OFlag::O_WRONLY | OFlag::O_CREAT;
    if append {
        flags |= OFlag::O_APPEND;
    } else {
        flags |= OFlag::O_TRUNC;
    }

    let same_path = match (stdout, stderr) {
        (Some(out), Some(err)) => paths_same(out, err),
        _ => false,
    };

    let stdout_action = match stdout {
        Some(path) => StreamAction::OpenAndRedirect {
            path: path.to_path_buf(),
            flags,
            target_fd: 1,
        },
        None => StreamAction::None,
    };

    let stderr_action = if same_path {
        StreamAction::DupFrom {
            source_fd: 1,
            target_fd: 2,
        }
    } else {
        match stderr {
            Some(path) => StreamAction::OpenAndRedirect {
                path: path.to_path_buf(),
                flags,
                target_fd: 2,
            },
            None => StreamAction::None,
        }
    };

    OutputRedirectPlan {
        stdout: stdout_action,
        stderr: stderr_action,
    }
}

/// Duplicate `source` onto a stdio target fd (0=stdin, 1=stdout, 2=stderr).
fn dup2_stdio(source: impl AsFd, target_fd: i32) -> Result<(), nix::errno::Errno> {
    match target_fd {
        0 => unistd::dup2_stdin(source),
        1 => unistd::dup2_stdout(source),
        2 => unistd::dup2_stderr(source),
        _ => unreachable!("dup2_stdio called with non-stdio target: {target_fd}"),
    }
}

/// Execute a single [`StreamAction`], performing the actual fd operations.
fn execute_stream_action(action: &StreamAction) -> Result<(), DaemonizeError> {
    match action {
        StreamAction::None => Ok(()),
        StreamAction::OpenAndRedirect {
            path,
            flags,
            target_fd,
        } => {
            let mode = Mode::from_bits_truncate(0o644);
            let fd = open(path, *flags, mode).map_err(|e| {
                DaemonizeError::OutputFileError(format!("cannot open {}: {e}", path.display()))
            })?;
            if fd.as_raw_fd() != *target_fd {
                dup2_stdio(&fd, *target_fd).map_err(|e| {
                    DaemonizeError::OutputFileError(format!("dup2 fd {target_fd}: {e}"))
                })?;
                // fd drops here, closing the original descriptor.
            } else {
                // fd IS the target — don't close it on drop.
                std::mem::forget(fd);
            }
            Ok(())
        }
        StreamAction::DupFrom {
            source_fd,
            target_fd,
        } => {
            // source_fd is always a stdio fd set up by a prior action.
            match source_fd {
                0 => dup2_stdio(std::io::stdin(), *target_fd),
                1 => dup2_stdio(std::io::stdout(), *target_fd),
                2 => dup2_stdio(std::io::stderr(), *target_fd),
                _ => unreachable!("DupFrom with non-stdio source: {source_fd}"),
            }
            .map_err(|e| {
                DaemonizeError::OutputFileError(format!("dup2 fd {source_fd} -> {target_fd}: {e}"))
            })?;
            Ok(())
        }
    }
}

/// Execute an [`OutputRedirectPlan`], performing all fd operations.
pub(crate) fn execute_output_redirect(plan: &OutputRedirectPlan) -> Result<(), DaemonizeError> {
    execute_stream_action(&plan.stdout)?;
    execute_stream_action(&plan.stderr)?;
    Ok(())
}

/// Step 12: Redirect stdout/stderr to configured files.
///
/// Runs before the caller's split-phase privilege drop (R102), so files are
/// created with the original (often root) ownership;
/// [`chown_paths`](crate::DaemonContext::chown_paths) transfers them to the
/// target user afterward.
/// Same-path optimization: if stdout and stderr resolve to the same path,
/// open once for stdout and dup2 to stderr.
pub(crate) fn redirect_output(
    stdout: Option<&Path>,
    stderr: Option<&Path>,
    append: bool,
) -> Result<(), DaemonizeError> {
    let plan = plan_output_redirect(stdout, stderr, append);
    execute_output_redirect(&plan)
}

/// Write all bytes to a file descriptor, looping on partial writes.
fn write_all_fd(fd: impl AsFd, buf: &[u8]) -> Result<(), nix::errno::Errno> {
    let fd = fd.as_fd();
    let mut written = 0;
    while written < buf.len() {
        match nix::unistd::write(fd, &buf[written..]) {
            Ok(0) => return Err(nix::errno::Errno::EIO),
            Ok(n) => written += n,
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

/// Convert an `rlim_cur` value to the exclusive upper bound of the fd-close
/// range, saturating at `i32::MAX`.
///
/// A plain `as i32` cast wraps huge limits — `RLIM_INFINITY` becomes `-1`,
/// emptying the close range so *no* fds are closed. Saturating is lossless in
/// practice: fds are C ints, so no open fd can exceed `i32::MAX`.
///
/// `rlim_t` is unsigned on Linux/macOS/NetBSD but signed (`i64`) on FreeBSD,
/// so the conversion goes through `try_from`: any value outside `i32` range —
/// including a negative one, which no kernel should report — maps to
/// `i32::MAX`, erring toward closing everything rather than nothing.
pub(crate) fn clamp_max_fd(rlim_cur: libc::rlim_t) -> i32 {
    i32::try_from(rlim_cur).unwrap_or(i32::MAX)
}

/// Query the process fd limit via getrlimit.
///
/// # Panics
///
/// Panics if getrlimit fails.
pub(crate) fn get_max_fd() -> i32 {
    let limit = nix::sys::resource::getrlimit(nix::sys::resource::Resource::RLIMIT_NOFILE)
        .expect("getrlimit(RLIMIT_NOFILE) failed");
    clamp_max_fd(limit.0)
}

/// Return an iterator of fd numbers to close, filtering out skip_fds.
///
/// Pure logic — no side effects.
pub(crate) fn fds_to_close(max_fd: i32, skip_fds: &[i32]) -> impl Iterator<Item = i32> + '_ {
    (3..max_fd).filter(move |fd| !skip_fds.contains(fd))
}

/// Step 13: Close inherited file descriptors.
///
/// Iterates 3..rlim_cur, skipping fds in the skip list.
///
/// # Panics
///
/// Panics if getrlimit fails.
pub(crate) fn close_inherited_fds(skip_fds: &[i32]) {
    let max_fd = get_max_fd();
    for fd in fds_to_close(max_fd, skip_fds) {
        unsafe_ops::raw_close(fd);
    }
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use super::*;
    use serial_test::serial;

    /// Guard that saves file descriptors on creation and restores them on drop.
    ///
    /// Tests that redirect stdout/stderr (fd 1/2) corrupt the test harness
    /// because the harness writes results to those fds. This guard `dup`s the
    /// originals before the test body runs, then `dup2`s them back when dropped.
    struct SavedFds {
        saved: Vec<(i32, OwnedFd)>, // (original_fd, saved_copy)
    }

    impl SavedFds {
        fn new(fds: &[i32]) -> Self {
            let saved = fds
                .iter()
                .map(|&fd| {
                    let copy = match fd {
                        0 => unistd::dup(std::io::stdin()),
                        1 => unistd::dup(std::io::stdout()),
                        2 => unistd::dup(std::io::stderr()),
                        _ => panic!("SavedFds only supports stdio fds"),
                    }
                    .unwrap_or_else(|e| panic!("dup({fd}) failed: {e}"));
                    (fd, copy)
                })
                .collect();
            Self { saved }
        }

        /// Returns the raw fd numbers of the saved copies.
        ///
        /// Use this to build a skip list for `close_inherited_fds` so it
        /// doesn't close the backup copies we need for restoration.
        fn saved_fds(&self) -> Vec<i32> {
            self.saved
                .iter()
                .map(|(_, copy)| copy.as_raw_fd())
                .collect()
        }
    }

    impl Drop for SavedFds {
        fn drop(&mut self) {
            for (orig, copy) in self.saved.drain(..) {
                dup2_stdio(&copy, orig)
                    .unwrap_or_else(|e| panic!("dup2({} -> {orig}) failed: {e}", copy.as_raw_fd()));
                // copy is an OwnedFd — closed on drop
            }
        }
    }

    // --- Step 4: umask ---

    #[test]
    #[serial]
    fn set_umask_applies_and_can_be_read_back() {
        let old = nix::sys::stat::umask(Mode::from_bits_truncate(0o077));
        set_umask(0o022);
        let readback = nix::sys::stat::umask(old); // restore
        assert_eq!(readback, Mode::from_bits_truncate(0o022));
        nix::sys::stat::umask(old); // double-restore
    }

    // --- Step 5: chdir ---

    #[test]
    #[serial]
    fn change_dir_to_tempdir() {
        let original = std::env::current_dir().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let result = change_dir(tmp.path());
        assert!(result.is_ok());
        let cwd = std::env::current_dir().unwrap();
        assert_eq!(cwd, std::fs::canonicalize(tmp.path()).unwrap());
        std::env::set_current_dir(&original).unwrap();
    }

    #[test]
    #[serial]
    fn change_dir_nonexistent_fails() {
        let result = change_dir(Path::new("/nonexistent_daemonize_test_path"));
        assert!(matches!(result, Err(DaemonizeError::ChdirFailed(_))));
    }

    // --- Step 6: redirect to /dev/null ---

    // Covers: R7, R8
    #[test]
    #[serial]
    fn redirect_to_devnull_succeeds() {
        let _restore = SavedFds::new(&[0, 1, 2]);
        redirect_to_devnull(true);
    }

    // Covers: R7
    #[test]
    #[serial]
    fn redirect_to_devnull_foreground_preserves_stdout_stderr() {
        use nix::sys::stat::fstat;

        let _restore = SavedFds::new(&[0, 1, 2]);
        let stdout_before = fstat(std::io::stdout()).unwrap();
        let stderr_before = fstat(std::io::stderr()).unwrap();
        redirect_to_devnull(false);

        // stdin should be /dev/null
        let devnull = fstat(open(c"/dev/null", OFlag::O_RDONLY, Mode::empty()).unwrap()).unwrap();
        let stdin_after = fstat(std::io::stdin()).unwrap();
        assert_eq!(stdin_after.st_dev, devnull.st_dev);
        assert_eq!(stdin_after.st_ino, devnull.st_ino);

        // stdout and stderr should still point to the same files as before
        let stdout_after = fstat(std::io::stdout()).unwrap();
        let stderr_after = fstat(std::io::stderr()).unwrap();
        assert_eq!(stdout_before.st_dev, stdout_after.st_dev);
        assert_eq!(stdout_before.st_ino, stdout_after.st_ino);
        assert_eq!(stderr_before.st_dev, stderr_after.st_dev);
        assert_eq!(stderr_before.st_ino, stderr_after.st_ino);
    }

    // --- Step 7: open and lock ---

    // Covers: R96
    #[test]
    fn open_and_lock_creates_and_locks() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.lock");
        let flock = open_and_lock(&path).unwrap();
        assert!(path.exists());
        assert!(flock.as_raw_fd() >= 0);
    }

    #[test]
    fn open_and_lock_conflict() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.lock");
        let _first = open_and_lock(&path).unwrap();
        let second = open_and_lock(&path);
        assert!(matches!(second, Err(DaemonizeError::LockConflict(_))));
    }

    // --- Step 8: write pidfile ---

    #[test]
    fn write_pidfile_standalone() {
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("test.pid");
        let result = write_pidfile(&pidfile, None);
        assert!(result.is_ok());
        let contents = std::fs::read_to_string(&pidfile).unwrap();
        let pid: u32 = contents.trim().parse().unwrap();
        assert_eq!(pid, std::process::id());
    }

    #[test]
    fn write_pidfile_shared_with_lockfile() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shared.pid");
        let flock = open_and_lock(&path).unwrap();
        let result = write_pidfile(&path, Some((path.as_path(), &flock)));
        assert!(result.is_ok());
        let contents = std::fs::read_to_string(&path).unwrap();
        let pid: u32 = contents.trim().parse().unwrap();
        assert_eq!(pid, std::process::id());
    }

    // --- Step 9: signal disposition reset ---

    #[test]
    #[serial]
    #[allow(unsafe_code)]
    // Covers: R99
    fn reset_signal_dispositions_restores_default() {
        use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};

        // Install SIG_IGN handler for SIGUSR1
        let handler = SigAction::new(SigHandler::SigIgn, SaFlags::empty(), SigSet::empty());
        let old = unsafe { sigaction(Signal::SIGUSR1, &handler) }.unwrap();

        // Verify it's not SIG_DFL
        let current = unsafe { sigaction(Signal::SIGUSR1, &handler) }.unwrap();
        assert!(
            !matches!(current.handler(), SigHandler::SigDfl),
            "precondition: SIGUSR1 should not be SIG_DFL"
        );

        // Reset all dispositions
        crate::unsafe_ops::reset_signal_dispositions();

        // Read back SIGUSR1 disposition — should be SIG_DFL now
        let after_reset = unsafe { sigaction(Signal::SIGUSR1, &old) }.unwrap();
        assert!(
            matches!(after_reset.handler(), SigHandler::SigDfl),
            "SIGUSR1 should be SIG_DFL after reset"
        );

        // Restore original
        let _ = unsafe { sigaction(Signal::SIGUSR1, &old) };
    }

    // Covers: R127
    #[test]
    #[serial]
    #[allow(unsafe_code)]
    fn reset_signal_dispositions_preserves_sigpipe() {
        use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};

        // Read the harness's current SIGPIPE disposition so it can be
        // restored at the end (install-and-put-back is the only read API).
        let probe = SigAction::new(SigHandler::SigIgn, SaFlags::empty(), SigSet::empty());
        let original = unsafe { sigaction(Signal::SIGPIPE, &probe) }.unwrap();
        let _ = unsafe { sigaction(Signal::SIGPIPE, &original) };

        // SIG_IGN (what the Rust runtime installs) must survive the reset:
        // resetting it would turn every write to a closed pipe/socket into
        // silent process death instead of an EPIPE error.
        let ign = SigAction::new(SigHandler::SigIgn, SaFlags::empty(), SigSet::empty());
        unsafe { sigaction(Signal::SIGPIPE, &ign) }.unwrap();
        crate::unsafe_ops::reset_signal_dispositions();
        let after = unsafe { sigaction(Signal::SIGPIPE, &ign) }.unwrap();
        assert!(
            matches!(after.handler(), SigHandler::SigIgn),
            "SIGPIPE SIG_IGN must survive the disposition reset"
        );

        // The reset preserves the caller's choice, whatever it is — it does
        // not force SIG_IGN: an explicit SIG_DFL stays SIG_DFL.
        let dfl = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
        unsafe { sigaction(Signal::SIGPIPE, &dfl) }.unwrap();
        crate::unsafe_ops::reset_signal_dispositions();
        let after = unsafe { sigaction(Signal::SIGPIPE, &dfl) }.unwrap();
        assert!(
            matches!(after.handler(), SigHandler::SigDfl),
            "an explicit SIG_DFL must also be preserved, not overridden"
        );

        let _ = unsafe { sigaction(Signal::SIGPIPE, &original) };
    }

    // --- Step 10: clear signal mask ---

    #[test]
    #[serial]
    fn clear_signal_mask_empties() {
        use nix::sys::signal::{SigSet, SigmaskHow, Signal};
        // Block SIGUSR1
        let mut set = SigSet::empty();
        set.add(Signal::SIGUSR1);
        nix::sys::signal::sigprocmask(SigmaskHow::SIG_BLOCK, Some(&set), None).unwrap();

        clear_signal_mask();

        let mut current = SigSet::empty();
        nix::sys::signal::sigprocmask(SigmaskHow::SIG_SETMASK, None, Some(&mut current)).unwrap();
        assert!(!current.contains(Signal::SIGUSR1));
    }

    // --- Step 11: set env vars ---

    #[test]
    #[serial]
    #[allow(unsafe_code)]
    fn set_env_vars_applies() {
        let vars = vec![
            ("DAEMONIZE_TEST_A".into(), "1".into()),
            ("DAEMONIZE_TEST_B".into(), "2".into()),
        ];
        set_env_vars(&vars);
        assert_eq!(std::env::var("DAEMONIZE_TEST_A").unwrap(), "1");
        assert_eq!(std::env::var("DAEMONIZE_TEST_B").unwrap(), "2");
        // SAFETY: #[serial] guarantees no concurrent env access during this test.
        unsafe {
            std::env::remove_var("DAEMONIZE_TEST_A");
            std::env::remove_var("DAEMONIZE_TEST_B");
        }
    }

    #[test]
    #[serial]
    #[allow(unsafe_code)]
    fn set_env_vars_last_write_wins() {
        let vars = vec![
            ("DAEMONIZE_TEST_DUP".into(), "first".into()),
            ("DAEMONIZE_TEST_DUP".into(), "second".into()),
        ];
        set_env_vars(&vars);
        assert_eq!(std::env::var("DAEMONIZE_TEST_DUP").unwrap(), "second");
        // SAFETY: #[serial] guarantees no concurrent env access during this test.
        unsafe { std::env::remove_var("DAEMONIZE_TEST_DUP") };
    }

    // --- Step 12: redirect output (pure plan tests) ---

    #[test]
    fn plan_stdout_only_truncate() {
        let path = PathBuf::from("/tmp/out.log");
        let plan = plan_output_redirect(Some(&path), None, false);
        assert_eq!(
            plan.stdout,
            StreamAction::OpenAndRedirect {
                path: path.clone(),
                flags: OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_TRUNC,
                target_fd: 1,
            }
        );
        assert_eq!(plan.stderr, StreamAction::None);
    }

    #[test]
    fn plan_stderr_only() {
        let path = PathBuf::from("/tmp/err.log");
        let plan = plan_output_redirect(None, Some(&path), false);
        assert_eq!(plan.stdout, StreamAction::None);
        assert_eq!(
            plan.stderr,
            StreamAction::OpenAndRedirect {
                path: path.clone(),
                flags: OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_TRUNC,
                target_fd: 2,
            }
        );
    }

    #[test]
    fn plan_both_different_paths() {
        let out = PathBuf::from("/tmp/out.log");
        let err = PathBuf::from("/tmp/err.log");
        let plan = plan_output_redirect(Some(&out), Some(&err), false);
        assert!(matches!(
            plan.stdout,
            StreamAction::OpenAndRedirect { target_fd: 1, .. }
        ));
        assert!(matches!(
            plan.stderr,
            StreamAction::OpenAndRedirect { target_fd: 2, .. }
        ));
    }

    #[test]
    fn plan_both_same_path() {
        let path = PathBuf::from("/tmp/combined.log");
        let plan = plan_output_redirect(Some(&path), Some(&path), false);
        assert!(matches!(
            plan.stdout,
            StreamAction::OpenAndRedirect { target_fd: 1, .. }
        ));
        assert_eq!(
            plan.stderr,
            StreamAction::DupFrom {
                source_fd: 1,
                target_fd: 2,
            }
        );
    }

    #[test]
    fn plan_append_flag() {
        let path = PathBuf::from("/tmp/out.log");
        let plan = plan_output_redirect(Some(&path), None, true);
        if let StreamAction::OpenAndRedirect { flags, .. } = plan.stdout {
            assert!(flags.contains(OFlag::O_APPEND));
            assert!(!flags.contains(OFlag::O_TRUNC));
        } else {
            panic!("expected OpenAndRedirect");
        }
    }

    #[test]
    fn plan_truncate_flag() {
        let path = PathBuf::from("/tmp/out.log");
        let plan = plan_output_redirect(Some(&path), None, false);
        if let StreamAction::OpenAndRedirect { flags, .. } = plan.stdout {
            assert!(flags.contains(OFlag::O_TRUNC));
            assert!(!flags.contains(OFlag::O_APPEND));
        } else {
            panic!("expected OpenAndRedirect");
        }
    }

    #[test]
    fn plan_neither() {
        let plan = plan_output_redirect(None, None, false);
        assert_eq!(plan.stdout, StreamAction::None);
        assert_eq!(plan.stderr, StreamAction::None);
    }

    // --- Step 12: redirect output (executor smoke tests, serial) ---

    // Covers: R98
    #[test]
    #[serial]
    fn execute_redirect_creates_files() {
        let _restore = SavedFds::new(&[1, 2]);
        let dir = tempfile::tempdir().unwrap();
        let stdout_path = dir.path().join("stdout.log");
        let stderr_path = dir.path().join("stderr.log");
        let plan = plan_output_redirect(Some(&stdout_path), Some(&stderr_path), false);
        let result = execute_output_redirect(&plan);
        assert!(result.is_ok());
        assert!(stdout_path.exists());
        assert!(stderr_path.exists());
    }

    #[test]
    #[serial]
    fn execute_redirect_truncate_vs_append() {
        let _restore = SavedFds::new(&[1]);
        let dir = tempfile::tempdir().unwrap();
        let stdout_path = dir.path().join("stdout.log");

        // Truncate mode
        std::fs::write(&stdout_path, "old content\n").unwrap();
        redirect_output(Some(&stdout_path), None, false).unwrap();
        std::io::stdout().write_all(b"new content\n").unwrap();
        std::io::stdout().flush().unwrap();
        let content = std::fs::read_to_string(&stdout_path).unwrap();
        assert!(!content.contains("old content"), "should have truncated");
        assert!(content.contains("new content"));

        // Append mode
        redirect_output(Some(&stdout_path), None, true).unwrap();
        std::io::stdout().write_all(b"appended\n").unwrap();
        std::io::stdout().flush().unwrap();
        let content = std::fs::read_to_string(&stdout_path).unwrap();
        assert!(content.contains("new content"), "should preserve existing");
        assert!(content.contains("appended"));
    }

    #[test]
    #[serial]
    fn execute_redirect_dup_from() {
        let _restore = SavedFds::new(&[1, 2]);
        let dir = tempfile::tempdir().unwrap();
        let combined = dir.path().join("combined.log");
        let plan = plan_output_redirect(Some(&combined), Some(&combined), false);
        execute_output_redirect(&plan).unwrap();

        std::io::stdout().write_all(b"stdout\n").unwrap();
        std::io::stdout().flush().unwrap();
        std::io::stderr().write_all(b"stderr\n").unwrap();
        std::io::stderr().flush().unwrap();

        let content = std::fs::read_to_string(&combined).unwrap();
        assert!(content.contains("stdout"));
        assert!(content.contains("stderr"));
    }

    #[test]
    #[serial]
    fn execute_redirect_stderr_only() {
        let _restore = SavedFds::new(&[2]);
        let dir = tempfile::tempdir().unwrap();
        let stderr_path = dir.path().join("stderr.log");
        let plan = plan_output_redirect(None, Some(&stderr_path), false);
        execute_output_redirect(&plan).unwrap();
        assert!(stderr_path.exists());

        std::io::stderr().write_all(b"stderr content\n").unwrap();
        std::io::stderr().flush().unwrap();
        let content = std::fs::read_to_string(&stderr_path).unwrap();
        assert!(content.contains("stderr content"));
    }

    // --- Step 13: close inherited fds (pure plan tests) ---

    // Covers: R103
    #[test]
    fn clamp_max_fd_saturates_instead_of_wrapping() {
        // RLIM_INFINITY formerly wrapped to -1 via `as i32`, emptying the
        // close range so no fds were closed at all. The conversion must
        // saturate: closing up to i32::MAX covers every possible fd (fds are
        // C ints). rlim_t::MAX covers both the unsigned (u64::MAX, which IS
        // RLIM_INFINITY on Linux) and signed-FreeBSD (i64::MAX) cases.
        assert_eq!(clamp_max_fd(libc::rlim_t::MAX), i32::MAX);
        assert_eq!(clamp_max_fd(i32::MAX as libc::rlim_t + 1), i32::MAX);
        // Ordinary limits pass through unchanged.
        assert_eq!(clamp_max_fd(1024), 1024);
        assert_eq!(clamp_max_fd(0), 0);
    }

    // Covers: R104
    #[test]
    fn fds_to_close_skips_correctly() {
        let result: Vec<i32> = fds_to_close(10, &[4, 7]).collect();
        assert_eq!(result, vec![3, 5, 6, 8, 9]);
    }

    #[test]
    fn fds_to_close_empty_skip() {
        let result: Vec<i32> = fds_to_close(6, &[]).collect();
        assert_eq!(result, vec![3, 4, 5]);
    }

    #[test]
    fn fds_to_close_all_skipped() {
        let result: Vec<i32> = fds_to_close(6, &[3, 4, 5]).collect();
        assert!(result.is_empty());
    }

    #[test]
    fn fds_to_close_max_below_3() {
        let result: Vec<i32> = fds_to_close(2, &[]).collect();
        assert!(result.is_empty());
    }

    // --- Step 13: close inherited fds (executor smoke test, subprocess-isolated) ---
    //
    // close_inherited_fds closes every non-skipped descriptor process-wide. Run
    // in the shared test process it clobbers fds held by tests executing in
    // parallel (open lockfiles, ReadDir handles during tempdir cleanup),
    // producing spurious EBADF failures. #[serial] does not help: it only
    // orders against other #[serial] tests, not the parallel non-serial ones.
    // So this test runs #[ignore] and is spawned in isolation via
    // crate::test_support::run_in_subprocess.

    // Covers: R103, R104
    #[test]
    fn close_inherited_fds_preserves_skipped() {
        if std::env::var("CI").is_ok() {
            // Closing fds in-process triggers systemd's safe_close() EBADF
            // assertion on Ubuntu CI runners. Integration tests cover this path.
            return;
        }
        crate::test_support::run_in_subprocess(
            "steps::tests::close_inherited_fds_preserves_skipped_subprocess",
        );
    }

    #[test]
    #[ignore = "closes fds process-wide; only safe in an isolated subprocess"]
    fn close_inherited_fds_preserves_skipped_subprocess() {
        // Guard so this never runs as a stray `--include-ignored` in the shared
        // process; it executes only when spawned by run_in_subprocess.
        if !crate::test_support::is_subprocess() {
            return;
        }
        // Save stdout/stderr so the test harness can still report results
        // after we close all non-skipped fds (which includes harness-internal fds).
        let restore = SavedFds::new(&[1, 2]);
        let (rd, wr) = nix::unistd::pipe().unwrap();
        let mut skip = vec![rd.as_raw_fd(), wr.as_raw_fd()];
        // Also skip the SavedFds backup copies so they survive for restoration.
        skip.extend(restore.saved_fds());
        close_inherited_fds(&skip);
        // Our pipe fds should still be open
        assert!(nix::unistd::write(&wr, b"ok").is_ok());
    }

    #[test]
    fn write_pidfile_with_different_lockfile_path() {
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("test.pid");
        let lockfile_path = dir.path().join("test.lock");
        let flock = open_and_lock(&lockfile_path).unwrap();
        // lockfile_path differs from pidfile — should use std::fs::write path
        let result = write_pidfile(&pidfile, Some((lockfile_path.as_path(), &flock)));
        assert!(result.is_ok());
        let contents = std::fs::read_to_string(&pidfile).unwrap();
        let pid: u32 = contents.trim().parse().unwrap();
        assert_eq!(pid, std::process::id());
    }
}