blivet 0.13.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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
//! A correct, full-featured Unix daemon library and CLI for Rust.
//!
//! A [blivet] is the "impossible fork" optical illusion, also known as the
//! devil's fork. Daemons are created by forking — and this crate
//! performs the impossible double-fork to do it correctly.
//!
//! This crate provides a library and CLI tool for daemonizing processes on Unix
//! systems. It performs a double-fork, resets signal dispositions and
//! mask, and uses a notification pipe so the parent can wait for daemon
//! readiness. Privilege dropping is split-phase: `daemonize()` returns a
//! context while still privileged, and the caller explicitly calls
//! `drop_privileges()` when ready.
//!
//! [blivet]: https://en.wikipedia.org/wiki/Impossible_trident
//!
//! # Example
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use blivet::{DaemonConfig, daemonize};
//!
//! let mut config = DaemonConfig::new();
//! config.pidfile("/var/run/foo.pid").chdir("/tmp");
//!
//! let mut ctx = daemonize(&config)?;
//! // ... application initialization ...
//! ctx.notify_parent()?;
//! // daemon process continues here
//! # Ok(())
//! # }
//! ```
//!
//! # Choosing an entry point
//!
//! There are two entry points:
//!
//! - [`daemonize`] is the safe default: it verifies the process is
//!   single-threaded for you, so no `unsafe` is needed. It is available on
//!   **Linux, macOS, FreeBSD, NetBSD, and OpenBSD**, each using the kernel's
//!   own thread count (`/proc/self/status` on Linux, `proc_pidinfo` on macOS,
//!   `sysctl` on the BSDs). On any other target it is a `#[deprecated]` stub
//!   that never daemonizes — a hard compile error under `-D warnings` /
//!   `#![deny(deprecated)]`; use [`daemonize_unchecked`] there.
//! - [`daemonize_unchecked`] is `unsafe` and available on all Unix platforms:
//!   you must guarantee the process is single-threaded at the call site (see
//!   [Threads and async runtimes](#threads-and-async-runtimes)).
//!
//! Most callers want [`daemonize`]:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let config = blivet::DaemonConfig::new();
//! let mut ctx = blivet::daemonize(&config)?;
//! # ctx.notify_parent()?;
//! # Ok(())
//! # }
//! ```
//!
//! To also compile on an exotic target without thread-count support, gate the
//! call so the deprecated stub is never built:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let config = blivet::DaemonConfig::new();
//! #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd",
//!           target_os = "netbsd", target_os = "openbsd"))]
//! let mut ctx = blivet::daemonize(&config)?;
//! #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd",
//!               target_os = "netbsd", target_os = "openbsd")))]
//! // SAFETY: no threads spawned before this point.
//! let mut ctx = unsafe { blivet::daemonize_unchecked(&config)? };
//! # ctx.notify_parent()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Threads and async runtimes
//!
//! Daemonizing forks, and forking a multithreaded process is unsound:
//! mutexes held by other threads stay locked forever in the child. A second
//! thread-unsafe step follows:
//! [`drop_privileges`](DaemonContext::drop_privileges) calls `setenv`
//! (`USER`/`HOME`/`LOGNAME`) when switching users. The single-threaded window
//! therefore runs from the fork through the last `setenv` — i.e. through
//! `drop_privileges()`:
//!
//! ```text
//! [single-threaded required]
//!   daemonize() / daemonize_unchecked() <- forks here
//!   drop_privileges()                    <- last unsafe step: setenv (USER/HOME/LOGNAME)
//! [now safe to spawn threads / start tokio / accept connections]
//!   notify_parent()                      <- thread-safe; writes one byte to the pipe
//! ```
//!
//! Both guards check for you and panic if violated: [`daemonize`] at the fork,
//! [`drop_privileges`](DaemonContext::drop_privileges) at its `setenv` (when a
//! user is configured). [`daemonize_unchecked`] and
//! [`drop_privileges_unchecked`](DaemonContext::drop_privileges_unchecked) are
//! the `unsafe` opt-outs.
//!
//! Spawn threads, start an async runtime, or begin a thread-per-connection
//! accept loop **after** `drop_privileges()` returns — or after [`daemonize`]
//! returns if you don't switch users.
//! [`notify_parent`](DaemonContext::notify_parent) itself is thread-safe.
//!
//! # Output and the working directory
//!
//! Two `daemonize(1)`-standard defaults bite the unwary: stdout/stderr go to
//! `/dev/null` (a `println!` vanishes), and the working directory becomes `/`
//! (relative paths resolve against `/` and usually fail). Use absolute paths;
//! see [`stdout`](DaemonConfig::stdout) / [`stderr`](DaemonConfig::stderr) /
//! [`chdir`](DaemonConfig::chdir) to change them.
//!
//! # Signals
//!
//! Daemonization resets every signal disposition to its default and clears
//! the signal mask — with one exception: **SIGPIPE is preserved**. The Rust
//! runtime ignores SIGPIPE so writes to a closed pipe or socket return
//! [`ErrorKind::BrokenPipe`](std::io::ErrorKind::BrokenPipe) instead of
//! killing the process, and that guarantee survives [`daemonize`]. (The
//! `daemonize` CLI restores the default disposition just before `exec`, so
//! spawned programs still start with conventional signal state.)
//!
//! # Pidfile cleanup on signals
//!
//! `Drop` **does not run** when a signal kills the process (how daemons are
//! normally stopped), so the auto-cleanup from
//! [`cleanup_on_drop`](DaemonConfig::cleanup_on_drop) leaves a stale pidfile.
//! Call [`cleanup_on_term_signals`](DaemonContext::cleanup_on_term_signals)
//! once, or run your own shutdown loop and let the context drop — see
//! `examples/echo_server.rs`.
//!
//! # Exit codes
//!
//! [`DaemonizeError::exit_code`] maps each error to a `sysexits.h` code — see
//! its docs for the full table — but `fn main() -> Result<(), E>` ignores it
//! and exits **1**. To surface the codes, call `exit_code()` yourself. To
//! report a failure from your own init code (e.g. a socket bind) with a chosen
//! code, use [`report_error_msg`](DaemonContext::report_error_msg) or the
//! [`DaemonizeError::Application`] variant.
//!
//! # Split-phase design
//!
//! Many daemons need root during startup — bind a privileged port, write a
//! pidfile to `/var/run`, open root-owned logs — but should run unprivileged
//! afterward. Rather than fold privilege dropping into the daemonize call,
//! `daemonize()` returns a [`DaemonContext`] still running as root; you do the
//! privileged work, then call
//! [`drop_privileges()`](DaemonContext::drop_privileges) (which first chowns
//! the pidfile/lockfile/logs to the target user — opt out with
//! [`chown_paths`](DaemonConfig::chown_paths)), then
//! [`notify_parent()`](DaemonContext::notify_parent). Full ordering control:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use blivet::{DaemonConfig, daemonize};
//!
//! let mut config = DaemonConfig::new();
//! config.pidfile("/var/run/foo.pid").user("nobody").group("nogroup");
//!
//! let mut ctx = daemonize(&config)?;
//!
//! // 1. Privileged work while still root:
//! //    bind sockets, chroot, set resource limits, etc.
//! let _listener = std::net::TcpListener::bind("0.0.0.0:80")?;
//!
//! // 2. Drop to unprivileged user (chowns pidfile/logs first, while still root)
//! ctx.drop_privileges()?;
//!
//! // 3. Tell the parent we're ready
//! ctx.notify_parent()?;
//!
//! // Daemon continues as "nobody" with the socket still open
//! # Ok(())
//! # }
//! ```

#![deny(unsafe_code)]

mod config;
mod context;
mod error;
pub(crate) mod forker;
mod identity;
pub(crate) mod unsafe_ops;

mod notify;
mod steps;
mod thread_count;
pub(crate) mod util;

#[cfg(test)]
mod test_support;

#[cfg(test)]
mod doc_sync;

/// Compile-checks every `rust` code block in the README as a doctest, so a
/// stale snippet fails `cargo test` instead of misleading readers. Blocks
/// that daemonize are marked `no_run`; fragments that cannot stand alone are
/// marked `ignore`. Does not affect the docs.rs front page.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_doctests {}

pub use config::DaemonConfig;
pub use context::DaemonContext;
pub use error::DaemonizeError;

use std::io::Read;
use std::os::fd::{AsRawFd, OwnedFd};

use nix::unistd::ForkResult;

use forker::{Forker, RealForker};
use notify::NotifyPipe;

/// Daemonize the current process without verifying the thread count.
///
/// Prefer the safe [`daemonize`], which verifies the single-threaded
/// requirement for you on the mainstream Unixes. Reach for this `unsafe`
/// variant only on targets where [`daemonize`] is unavailable, or when you
/// must manage the single-threaded contract yourself.
///
/// # Safety
///
/// No other threads may be running when this function is called.
/// Forking a multithreaded process leaves mutexes held by other
/// threads permanently locked in the child, causing deadlocks or
/// undefined behavior. Call before spawning threads, async runtimes,
/// or libraries with background threads. See [Threads and async
/// runtimes](crate#threads-and-async-runtimes) for the full lifecycle.
///
/// # Errors
///
/// Returns `DaemonizeError` on validation failure or any syscall error
/// during the daemonization sequence. Pre-fork errors are returned
/// directly; post-fork errors are reported via the notification pipe.
/// In foreground mode every error is returned directly — the library
/// never exits the caller's process.
///
/// # Panics
///
/// Panics if `/dev/null` cannot be opened, `dup2` to a standard fd fails,
/// `sigprocmask` fails, `getrlimit` fails, or other OS-level invariants
/// are violated (indicating a fundamentally broken environment).
#[allow(unsafe_code)]
pub unsafe fn daemonize_unchecked(config: &DaemonConfig) -> Result<DaemonContext, DaemonizeError> {
    config.validate()?;
    // SAFETY: this `unsafe fn`'s own contract requires single-threadedness.
    unsafe { daemonize_inner(config, &mut RealForker) }
}

// The OSes where `daemonize` can verify the thread count natively are
// listed explicitly in each `cfg` below (function-like macros do not expand
// inside `cfg` attributes): linux, macos, freebsd, netbsd, openbsd. The count
// itself lives in the `thread_count` module.

/// Returns the panic message if `count` is not exactly one thread, else `None`.
///
/// The checked entry points require *exactly* one thread (R45): forking — or
/// calling `setenv` during `drop_privileges` — in a multi-threaded process is
/// unsound. Any count other than 1 is a violation — including an anomalous `0`,
/// which a healthy process can never report and so signals an unreliable
/// thread-count query. Failing closed keeps the safety guard from
/// green-lighting on a count it cannot trust. `caller` names the operation in
/// the panic message.
#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd"
))]
pub(crate) fn single_threaded_violation(caller: &str, count: usize) -> Option<String> {
    (count != 1).then(|| {
        format!(
            "{caller}: {count} threads running (expected 1). \
             Call {caller} before spawning threads, async runtimes, \
             or libraries with background threads."
        )
    })
}

/// Reads the current thread count and panics unless it is exactly 1, naming
/// `caller` in the message.
///
/// The imperative shell around [`single_threaded_violation`], shared by the
/// checked entry points that must run single-threaded: [`daemonize`] (before
/// the fork) and
/// [`DaemonContext::drop_privileges`](crate::DaemonContext::drop_privileges)
/// (before its `setenv`).
#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd"
))]
pub(crate) fn assert_single_threaded(caller: &str) {
    let count = thread_count::count().unwrap_or_else(|_| {
        panic!("{caller}: cannot determine thread count to verify single-threadedness")
    });
    if let Some(msg) = single_threaded_violation(caller, count) {
        panic!("{msg}");
    }
}

/// Daemonize the current process, verifying it is single-threaded first.
///
/// Counts the threads in the current process and panics unless exactly one is
/// running, then calls [`daemonize_unchecked`]. This upholds the
/// single-threaded contract for you, so no `unsafe` block is needed, and is the
/// recommended entry point.
///
/// # Platform support
///
/// Available on **Linux, macOS, FreeBSD, NetBSD, and OpenBSD**, each using the
/// kernel's own thread count (`/proc/self/status` on Linux, `proc_pidinfo` on
/// macOS, `sysctl` on the BSDs). On any other target it is a `#[deprecated]`
/// stub that never daemonizes — calling it warns with guidance (and is a hard
/// compile error under `-D warnings` / `#![deny(deprecated)]`), and panics if
/// invoked anyway; call [`daemonize_unchecked`] yourself there inside an
/// `unsafe` block.
///
/// # Errors
///
/// As [`daemonize_unchecked`]: `DaemonizeError` on validation failure or any
/// syscall error during the daemonization sequence.
///
/// # Panics
///
/// Panics if the thread count is anything other than exactly 1, or if the
/// thread count cannot be determined.
#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd"
))]
pub fn daemonize(config: &DaemonConfig) -> Result<DaemonContext, DaemonizeError> {
    assert_single_threaded("daemonize");
    #[allow(unsafe_code)]
    unsafe {
        daemonize_unchecked(config)
    }
}

/// Stub for targets where the thread count cannot be queried, so there is no
/// safe wrapper to offer.
///
/// Rather than omit the symbol entirely (which yields a bare "cannot find
/// function `daemonize`" error that hides *why*), this stub is provided
/// and marked `#[deprecated]`: using it warns with guidance by default, and is
/// a hard compile error under `-D warnings` / `#![deny(deprecated)]`.
///
/// It never performs an unchecked daemonization. Call
/// `unsafe { `[`daemonize_unchecked`]`(&config) }` directly on this platform,
/// ensuring the process is single-threaded first.
///
/// # Panics
///
/// Always panics: the operation is unsupported on this target.
#[cfg(not(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd"
)))]
#[deprecated(note = "daemonize cannot verify the thread count on this target. \
            Call `unsafe { daemonize_unchecked(&config) }` and ensure the process \
            is single-threaded yourself.")]
pub fn daemonize(_config: &DaemonConfig) -> Result<DaemonContext, DaemonizeError> {
    panic!(
        "daemonize is unsupported on this target (cannot query the thread \
         count); call `unsafe {{ daemonize_unchecked(&config) }}` and ensure the \
         process is single-threaded yourself"
    )
}

/// Internal daemonization logic, generic over the Forker trait for testability.
///
/// # Safety
///
/// With a real `Forker` this performs `fork`; the process must be
/// single-threaded at the call, since forking with other threads running is
/// undefined behavior. The checked [`daemonize`] establishes this, and the
/// public [`daemonize_unchecked`] forwards the contract to its caller. (The
/// test `NullForker` does not fork, so test calls are sound.)
#[allow(unsafe_code)]
pub(crate) unsafe fn daemonize_inner(
    config: &DaemonConfig,
    forker: &mut impl Forker,
) -> Result<DaemonContext, DaemonizeError> {
    let foreground = config.foreground;

    // Steps 1–3: Fork sequence (skipped in foreground mode)
    let mut pipe_wr = if foreground {
        None
    } else {
        // Step 1: Create notification pipe and first fork
        let pipe = forker.create_notification_pipe();
        let (pipe_rd, mut pipe_wr) = match pipe {
            Some((rd, wr)) => (Some(rd), Some(NotifyPipe::new(wr))),
            None => (None, None),
        };

        // SAFETY: daemonize_unchecked() is unsafe and requires the caller to
        // ensure the process is single-threaded. The checked daemonize()
        // verifies this via the kernel thread count before calling
        // daemonize_inner().
        let first_fork = unsafe { forker.fork() };
        let first_fork = match first_fork {
            Ok(result) => result,
            Err(e) => {
                // No child exists yet; the error returns to the caller
                // directly, so close the write end silently rather than let
                // the NotifyPipe Drop safety net write into a pipe whose only
                // reader is this same process.
                if let Some(pipe) = pipe_wr {
                    pipe.close();
                }
                return Err(e);
            }
        };
        match first_fork {
            ForkResult::Parent { .. } => {
                // Parent: close the write end *silently* (it only reads) then
                // read and exit. A plain drop would trip the NotifyPipe Drop
                // safety net and make the parent read its own failure bytes.
                if let Some(pipe) = pipe_wr {
                    pipe.close();
                }
                if let Some(rd) = pipe_rd {
                    parent_pipe_reader(rd, forker);
                }
                // If no pipe (NullForker), just exit
                forker.exit(0);
            }
            ForkResult::Child => {
                // Child: close read end, continue
                drop(pipe_rd);
            }
        }

        // Step 2: setsid
        if let Err(e) = forker.setsid() {
            signal_error_to_parent(&mut pipe_wr, &e);
            forker.exit(e.exit_code() as i32);
        }

        // Step 3: Second fork
        // SAFETY: same as above — single-threaded post-fork child.
        match unsafe { forker.fork() } {
            Ok(ForkResult::Parent { .. }) => {
                // Intermediate child exits silently: the grandchild daemon is
                // the sole writer, so close the write-end copy without tripping
                // the NotifyPipe Drop safety net.
                if let Some(pipe) = pipe_wr {
                    pipe.close();
                }
                forker.exit(0);
            }
            Ok(ForkResult::Child) => {
                // Grandchild continues
            }
            Err(e) => {
                signal_error_to_parent(&mut pipe_wr, &e);
                forker.exit(e.exit_code() as i32);
            }
        }

        pipe_wr
    };

    // Steps 4–14 run in the final daemon process and report failures as a
    // single Result. In foreground mode no fork happened, so errors simply
    // propagate to the caller. In daemon mode the child cannot return to the
    // original caller, so funnel any error through one place: notify the
    // parent and exit. `pipe_wr` stays available so the error path can still
    // signal it.
    match run_post_fork(config, &mut pipe_wr) {
        Ok(ctx) => Ok(ctx),
        Err(e) if foreground => Err(e),
        Err(e) => {
            signal_error_to_parent(&mut pipe_wr, &e);
            forker.exit(e.exit_code() as i32);
        }
    }
}

/// Steps 4–14: apply the configuration in the final daemon process.
///
/// Forker-free and fallible: every step returns its error rather than touching
/// the notification pipe, leaving the single error-to-parent seam in
/// [`daemonize_inner`]. On success the notification pipe write end is moved into
/// the returned [`DaemonContext`]; `pipe_wr` is left `None`.
fn run_post_fork(
    config: &DaemonConfig,
    pipe_wr: &mut Option<NotifyPipe>,
) -> Result<DaemonContext, DaemonizeError> {
    // Step 4: Set umask
    steps::set_umask(config.umask);

    // Step 5: chdir
    steps::change_dir(&config.chdir)?;

    // Step 6: Redirect stdin to /dev/null (always); redirect stdout/stderr
    // to /dev/null only when not in foreground mode (foreground leaves them
    // inherited so output reaches the terminal or supervisor).
    steps::redirect_to_devnull(!config.foreground)?;

    // Step 7: Open and lock lockfile (explicit path, or the pidfile itself
    // unless derivation was opted out)
    let lockfile_path = config.effective_lockfile().map(std::path::PathBuf::as_path);
    let lockfile = match lockfile_path {
        Some(path) => Some(steps::open_and_lock(path)?),
        None => None,
    };

    // Step 8: Write pidfile
    if let Some(ref pidfile_path) = config.pidfile {
        steps::write_pidfile(pidfile_path, lockfile_path.zip(lockfile.as_ref()))?;
    }

    // Step 9: Reset signal dispositions
    unsafe_ops::reset_signal_dispositions()?;

    // Step 10: Clear signal mask
    steps::clear_signal_mask()?;

    // Step 11: Set environment variables
    steps::set_env_vars(&config.env);

    // Step 12: Redirect stdout/stderr to configured files
    if config.stdout.is_some() || config.stderr.is_some() {
        steps::redirect_output(
            config.stdout.as_deref(),
            config.stderr.as_deref(),
            config.append,
        )?;
    }

    // Step 13: Close inherited fds (if enabled)
    if config.close_fds {
        let mut skip_fds: Vec<i32> = Vec::new();
        if let Some(ref flock) = lockfile {
            skip_fds.push(flock.as_raw_fd());
        }
        if let Some(ref wr) = pipe_wr {
            skip_fds.push(wr.as_fd().as_raw_fd());
        }
        steps::close_inherited_fds(&skip_fds)?;
    }

    // Step 14: Return DaemonContext (clones the config-derived fields it needs)
    Ok(DaemonContext::new(config, lockfile, pipe_wr.take()))
}

/// Parent-side pipe reader. Reads from the pipe and exits accordingly.
fn parent_pipe_reader(rd: OwnedFd, forker: &impl Forker) -> ! {
    let mut file = std::fs::File::from(rd);
    let mut buf = Vec::new();
    let _ = file.read_to_end(&mut buf);

    match notify::decode(&buf) {
        notify::Outcome::Success => forker.exit(0),
        notify::Outcome::Failure { code, message } => {
            eprintln!("{message}");
            forker.exit(code);
        }
    }
}

/// Report a daemonization error to the parent via the notification pipe
/// (best-effort), consuming the write end if present. Used by the fork-sequence
/// and post-fork error paths that abort with `forker.exit` immediately after.
fn signal_error_to_parent(pipe_wr: &mut Option<NotifyPipe>, err: &DaemonizeError) {
    if let Some(pipe) = pipe_wr.take() {
        pipe.signal_error(err);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::forker::null_forker::NullForker;
    use crate::test_support::{is_subprocess, run_in_subprocess};
    use std::panic::catch_unwind;

    #[test]
    fn both_forks_child_succeeds() {
        run_in_subprocess("tests::both_forks_child_succeeds_subprocess");
    }

    // Covers: R45
    #[cfg(any(
        target_os = "linux",
        target_os = "macos",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd"
    ))]
    #[test]
    fn single_threaded_violation_accepts_only_exactly_one() {
        assert!(
            single_threaded_violation("daemonize", 1).is_none(),
            "exactly one thread is the single-threaded case"
        );
        assert!(
            single_threaded_violation("daemonize", 0).is_some(),
            "an anomalous 0 must fail closed, not green-light a fork"
        );
        let msg =
            single_threaded_violation("drop_privileges", 2).expect("2 threads is a violation");
        assert!(
            msg.contains("drop_privileges: 2 threads running (expected 1)"),
            "message should name the caller, count, and expectation, got: {msg}"
        );
    }

    /// Test wrapper: `daemonize_inner` driven by the non-forking `NullForker`.
    ///
    /// `NullForker::fork` returns a configured result without actually forking,
    /// so the `unsafe fn`'s single-threaded contract is vacuously satisfied —
    /// keeping the call sites free of per-test `unsafe` blocks.
    #[allow(unsafe_code)]
    fn run_inner(
        config: &DaemonConfig,
        forker: &mut NullForker,
    ) -> Result<DaemonContext, DaemonizeError> {
        // SAFETY: NullForker does not fork.
        unsafe { daemonize_inner(config, forker) }
    }

    #[test]
    #[ignore]
    fn both_forks_child_succeeds_subprocess() {
        if !is_subprocess() {
            return;
        }
        let mut config = DaemonConfig::new();
        config.close_fds(false); // Don't close fds in test subprocess (systemd aborts on EBADF)
        let mut forker = NullForker::both_child();
        let result = run_inner(&config, &mut forker);
        assert!(result.is_ok());
    }

    #[test]
    fn first_fork_parent_exits() {
        let config = DaemonConfig::new();
        let mut forker = NullForker::first_parent();
        let result = catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_inner(&config, &mut forker)
        }));
        assert!(result.is_err()); // exit panics in NullForker
    }

    // Covers: R137
    #[test]
    fn first_fork_parent_closes_pipe_silently() {
        // The parent's write-end copy must be *closed*, not dropped: NotifyPipe's
        // Drop safety net writes failure bytes, and a parent that drops would
        // read its own bytes and report a failure for a healthy start. With the
        // write end closed silently, the reader sees EOF -> success -> exit(0).
        let config = DaemonConfig::new();
        let mut forker = NullForker::first_parent().with_pipe();
        let result = catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_inner(&config, &mut forker)
        }));
        let panic_msg = result
            .expect_err("parent exits after reading the pipe")
            .downcast_ref::<String>()
            .cloned()
            .unwrap();
        assert!(
            panic_msg.contains("NullForker::exit(0)"),
            "parent must read EOF = success from its own silently-closed write \
             end, got: {panic_msg}"
        );
    }

    // Covers: R137
    #[test]
    fn second_fork_intermediate_closes_pipe_silently() {
        // The intermediate child's write-end copy must also close without
        // writing: the grandchild daemon is the sole writer on the pipe.
        let config = DaemonConfig::new();
        let mut forker = NullForker::second_parent().with_pipe();
        let result = catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_inner(&config, &mut forker)
        }));
        assert!(result.is_err(), "intermediate child exits");

        let rd = forker
            .take_pipe_reader()
            .expect("with_pipe stores a reader for the test");
        let mut buf = Vec::new();
        std::fs::File::from(rd).read_to_end(&mut buf).unwrap();
        assert_eq!(
            buf,
            Vec::<u8>::new(),
            "intermediate child must close the pipe without writing; the \
             daemon is the sole writer"
        );
    }

    #[test]
    fn second_fork_parent_exits() {
        let config = DaemonConfig::new();
        let mut forker = NullForker::second_parent();
        let result = catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_inner(&config, &mut forker)
        }));
        assert!(result.is_err());
    }

    // Covers: R57
    #[test]
    fn first_fork_fails_returns_error() {
        let config = DaemonConfig::new();
        let mut forker = NullForker::first_fork_fails();
        let result = run_inner(&config, &mut forker);
        assert!(matches!(result, Err(DaemonizeError::ForkFailed(_))));
    }

    #[test]
    fn first_fork_failure_closes_pipe_silently() {
        // The error goes back to the caller directly — nothing should reach
        // the pipe, whose only reader is this same process. A plain drop would
        // fire the NotifyPipe Drop safety net into it.
        let config = DaemonConfig::new();
        let mut forker = NullForker::first_fork_fails().with_pipe();
        let result = run_inner(&config, &mut forker);
        assert!(matches!(result, Err(DaemonizeError::ForkFailed(_))));

        let rd = forker
            .take_pipe_reader()
            .expect("with_pipe stores a reader");
        let mut buf = Vec::new();
        std::fs::File::from(rd).read_to_end(&mut buf).unwrap();
        assert_eq!(
            buf,
            Vec::<u8>::new(),
            "a pre-fork failure must leave the pipe unwritten"
        );
    }

    #[test]
    fn setsid_fails_exits() {
        let config = DaemonConfig::new();
        let mut forker = NullForker::setsid_fails();
        let result = catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_inner(&config, &mut forker)
        }));
        assert!(result.is_err());
    }

    // Covers: R58
    #[test]
    fn second_fork_fails_exits() {
        let config = DaemonConfig::new();
        let mut forker = NullForker::second_fork_fails();
        let result = catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_inner(&config, &mut forker)
        }));
        assert!(result.is_err());
    }

    #[test]
    fn exit_panic_contains_code() {
        let config = DaemonConfig::new();
        let mut forker = NullForker::first_parent();
        let result = catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_inner(&config, &mut forker)
        }));
        let panic_msg = result
            .unwrap_err()
            .downcast_ref::<String>()
            .cloned()
            .unwrap();
        assert!(
            panic_msg.contains("NullForker::exit(0)"),
            "panic message should contain exit code, got: {panic_msg}"
        );
    }

    // A post-fork step failing in daemon mode must funnel through the
    // notify-parent-and-exit arm (lib.rs), not return the error to the caller —
    // the child has no caller to return to. Distinct from a fork failure, which
    // returns before run_post_fork. Kills the mutant that swaps the foreground
    // and daemon match arms: with the arms swapped, this would return Err
    // instead of exiting.
    #[test]
    #[serial_test::serial]
    fn daemon_post_fork_failure_exits_not_returns() {
        // Step 4 sets the process umask from the config before chdir fails;
        // the guard restores the harness's umask even if an assertion panics.
        let _umask = test_support::UmaskGuard::set(nix::sys::stat::Mode::empty());
        // Daemon mode (foreground stays false); chdir to a nonexistent path
        // fails at step 5, before any stdio redirection touches this process.
        let mut config = DaemonConfig::new();
        config.chdir("/nonexistent_daemonize_postfork_failure");
        let mut forker = NullForker::both_child();
        let result = catch_unwind(std::panic::AssertUnwindSafe(|| {
            run_inner(&config, &mut forker)
        }));

        let panic_msg = result
            .expect_err("daemon-mode post-fork failure must exit (panic), not return")
            .downcast_ref::<String>()
            .cloned()
            .unwrap();
        assert!(
            panic_msg.contains("NullForker::exit(71)"),
            "must exit with ChdirFailed's EX_OSERR code 71, got: {panic_msg}"
        );
    }

    #[test]
    fn signal_error_to_parent_noop_with_none() {
        signal_error_to_parent(&mut None, &DaemonizeError::ForkFailed("test".into()));
    }

    #[test]
    fn signal_error_to_parent_writes_protocol() {
        let (rd, wr) = nix::unistd::pipe().unwrap();
        let mut pipe_wr = Some(NotifyPipe::new(wr));
        let err = DaemonizeError::ForkFailed("test error".into());
        signal_error_to_parent(&mut pipe_wr, &err);
        assert!(pipe_wr.is_none(), "write end consumed after signalling");

        let mut file = std::fs::File::from(rd);
        let mut buf = Vec::new();
        file.read_to_end(&mut buf).unwrap();

        assert_eq!(buf[0], 71); // EX_OSERR
        assert_eq!(
            std::str::from_utf8(&buf[1..]).unwrap(),
            "fork failed: test error"
        );
    }

    // Covers: R66, R68
    #[test]
    fn foreground_mode_skips_fork() {
        run_in_subprocess("tests::foreground_mode_skips_fork_subprocess");
    }

    #[test]
    #[ignore]
    fn foreground_mode_skips_fork_subprocess() {
        if !is_subprocess() {
            return;
        }
        let mut config = DaemonConfig::new();
        config.foreground(true).close_fds(false);
        let mut forker = NullForker::new(vec![], Ok(()));
        let result = run_inner(&config, &mut forker);
        let ctx = result.expect("foreground daemonize_inner should succeed");
        assert!(ctx.lockfile_fd().is_none());
    }

    // The three SystemError-producing steps cannot be made to fail from inside
    // a test process (that needs a missing /dev/null or a seccomp filter), so
    // each propagation test flips a steps::failpoints flag and asserts the
    // error surfaces from daemonize_inner instead of being swallowed — killing
    // mutants like `let _ = steps::clear_signal_mask();` in run_post_fork.
    // Subprocess-isolated: the flags are process-global, and run_post_fork
    // mutates umask/cwd/stdin for real on the way to the failing step.

    // Covers: R95
    #[test]
    fn devnull_failure_propagates() {
        run_in_subprocess("tests::devnull_failure_propagates_subprocess");
    }

    #[test]
    #[ignore]
    fn devnull_failure_propagates_subprocess() {
        if !is_subprocess() {
            return;
        }
        steps::failpoints::DEVNULL_OPEN_FAILS.store(true, std::sync::atomic::Ordering::Relaxed);
        let mut config = DaemonConfig::new();
        config.foreground(true).close_fds(false);
        let mut forker = NullForker::new(vec![], Ok(()));
        match run_inner(&config, &mut forker) {
            Err(DaemonizeError::SystemError(msg)) => {
                assert!(
                    msg.contains("/dev/null"),
                    "message names the syscall: {msg}"
                );
            }
            other => panic!("expected SystemError to propagate, got {other:?}"),
        }
    }

    // Covers: R134
    #[test]
    fn sigaction_failure_propagates() {
        run_in_subprocess("tests::sigaction_failure_propagates_subprocess");
    }

    #[test]
    #[ignore]
    fn sigaction_failure_propagates_subprocess() {
        if !is_subprocess() {
            return;
        }
        steps::failpoints::SIGACTION_FAILS.store(true, std::sync::atomic::Ordering::Relaxed);
        let mut config = DaemonConfig::new();
        config.foreground(true).close_fds(false);
        let mut forker = NullForker::new(vec![], Ok(()));
        match run_inner(&config, &mut forker) {
            Err(DaemonizeError::SystemError(msg)) => {
                assert!(
                    msg.contains("sigaction"),
                    "message names the syscall: {msg}"
                );
            }
            other => panic!("expected SystemError to propagate, got {other:?}"),
        }
    }

    // Covers: R134
    #[test]
    fn sigprocmask_failure_propagates() {
        run_in_subprocess("tests::sigprocmask_failure_propagates_subprocess");
    }

    #[test]
    #[ignore]
    fn sigprocmask_failure_propagates_subprocess() {
        if !is_subprocess() {
            return;
        }
        steps::failpoints::SIGPROCMASK_FAILS.store(true, std::sync::atomic::Ordering::Relaxed);
        let mut config = DaemonConfig::new();
        config.foreground(true).close_fds(false);
        let mut forker = NullForker::new(vec![], Ok(()));
        match run_inner(&config, &mut forker) {
            Err(DaemonizeError::SystemError(msg)) => {
                assert!(
                    msg.contains("sigprocmask"),
                    "message names the syscall: {msg}"
                );
            }
            other => panic!("expected SystemError to propagate, got {other:?}"),
        }
    }

    // Covers: R105
    #[test]
    fn getrlimit_failure_propagates() {
        run_in_subprocess("tests::getrlimit_failure_propagates_subprocess");
    }

    #[test]
    #[ignore]
    fn getrlimit_failure_propagates_subprocess() {
        if !is_subprocess() {
            return;
        }
        // Force the brute-force fallback (the fd listing normally short-circuits
        // it on Linux/macOS), then fail its getrlimit. get_max_fd errors before
        // any fd is closed, so the subprocess's descriptors survive.
        steps::failpoints::FD_LISTING_UNAVAILABLE.store(true, std::sync::atomic::Ordering::Relaxed);
        steps::failpoints::GETRLIMIT_FAILS.store(true, std::sync::atomic::Ordering::Relaxed);
        let mut config = DaemonConfig::new();
        config.foreground(true).close_fds(true);
        let mut forker = NullForker::new(vec![], Ok(()));
        match run_inner(&config, &mut forker) {
            Err(DaemonizeError::SystemError(msg)) => {
                assert!(
                    msg.contains("getrlimit"),
                    "message names the syscall: {msg}"
                );
            }
            other => panic!("expected SystemError to propagate, got {other:?}"),
        }
    }

    // Covers: R131
    #[test]
    fn pidfile_only_holds_derived_lock() {
        run_in_subprocess("tests::pidfile_only_holds_derived_lock_subprocess");
    }

    #[test]
    #[ignore]
    fn pidfile_only_holds_derived_lock_subprocess() {
        if !is_subprocess() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("app.pid");
        let mut config = DaemonConfig::new();
        config.foreground(true).close_fds(false).pidfile(&pidfile);
        let mut forker = NullForker::new(vec![], Ok(()));
        let ctx = run_inner(&config, &mut forker).expect("daemonize should succeed");
        let lock_fd = ctx
            .lockfile_fd()
            .expect("a lone pidfile should be flock'd by default");
        // The held lock must be on the pidfile itself, not some other file.
        let lock_stat = nix::sys::stat::fstat(lock_fd).unwrap();
        let pidfile_stat = nix::sys::stat::stat(&pidfile).unwrap();
        assert_eq!(
            (lock_stat.st_dev, lock_stat.st_ino),
            (pidfile_stat.st_dev, pidfile_stat.st_ino),
            "derived lock fd should refer to the pidfile"
        );
        // A second acquisition of the same path must conflict.
        let second = steps::open_and_lock(&pidfile);
        assert!(matches!(second, Err(DaemonizeError::LockConflict { .. })));
    }

    // Covers: R134
    #[test]
    fn foreground_lock_conflict_returns_err() {
        run_in_subprocess("tests::foreground_lock_conflict_returns_err_subprocess");
    }

    #[test]
    #[ignore]
    fn foreground_lock_conflict_returns_err_subprocess() {
        if !is_subprocess() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("app.pid");
        let _held = steps::open_and_lock(&pidfile).expect("first lock should succeed");
        let mut config = DaemonConfig::new();
        config.foreground(true).close_fds(false).pidfile(&pidfile);
        let mut forker = NullForker::new(vec![], Ok(()));
        let result = run_inner(&config, &mut forker);
        assert!(
            matches!(result, Err(DaemonizeError::LockConflict { .. })),
            "foreground mode should surface setup errors as Err, not exit"
        );
    }

    // Covers: R67
    #[test]
    fn foreground_mode_notify_parent_noop() {
        run_in_subprocess("tests::foreground_mode_notify_parent_noop_subprocess");
    }

    #[test]
    #[ignore]
    fn foreground_mode_notify_parent_noop_subprocess() {
        if !is_subprocess() {
            return;
        }
        let mut config = DaemonConfig::new();
        config.foreground(true).close_fds(false);
        let mut forker = NullForker::new(vec![], Ok(()));
        let mut ctx = run_inner(&config, &mut forker).unwrap();
        assert!(ctx.notify_parent().is_ok());
    }

    // Covers: R69
    #[test]
    fn close_fds_false_preserves_fds() {
        run_in_subprocess("tests::close_fds_false_preserves_fds_subprocess");
    }

    #[test]
    #[ignore]
    fn close_fds_false_preserves_fds_subprocess() {
        if !is_subprocess() {
            return;
        }
        let (rd, wr) = nix::unistd::pipe().unwrap();

        let mut config = DaemonConfig::new();
        config.close_fds(false);
        let mut forker = NullForker::both_child();
        let _ctx = run_inner(&config, &mut forker).unwrap();

        assert!(
            nix::unistd::write(&wr, b"alive").is_ok(),
            "write fd should still be open with close_fds=false"
        );
        let mut buf = [0u8; 5];
        assert!(
            nix::unistd::read(&rd, &mut buf).is_ok(),
            "read fd should still be open with close_fds=false"
        );
    }

    // Covers: R120
    #[test]
    fn context_carries_config_fields() {
        run_in_subprocess("tests::context_carries_config_fields_subprocess");
    }

    #[test]
    #[ignore]
    fn context_carries_config_fields_subprocess() {
        if !is_subprocess() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("test.pid");
        let stdout = dir.path().join("out.log");

        let mut config = DaemonConfig::new();
        config
            .pidfile(&pidfile)
            .stdout(&stdout)
            .user("nobody")
            .group("nogroup")
            .foreground(true)
            .close_fds(false);

        let mut forker = NullForker::new(vec![], Ok(()));
        let ctx = run_inner(&config, &mut forker).unwrap();

        let debug = format!("{:?}", ctx);
        assert!(
            debug.contains("test.pid"),
            "context should contain pidfile path"
        );
        assert!(
            debug.contains("out.log"),
            "context should contain stdout path"
        );
        assert!(debug.contains("nobody"), "context should contain user");
        assert!(debug.contains("nogroup"), "context should contain group");
    }
}