1 // Copyright 2021-2022 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
5 #![allow(unused_imports)]
7 #![allow(unused_macros)]
9 use std::convert::TryInto;
10 use std::ffi::{c_int, CStr};
12 use std::os::unix::io::RawFd;
15 use std::thread::panicking;
22 use nix::sys::stat::*;
23 use nix::sys::signal::*;
25 use nix::sys::wait::*;
27 use hippotat::prelude as prelude;
30 pub struct Daemoniser {
31 drop_bomb: Option<()>,
32 intermediate_pid: Pid,
37 fn crashv(ms: &[IoSlice<'_>]) -> ! {
39 let _ = writev(2, ms);
44 macro_rules! crashv { { $( $m:expr ),* $(,)? } => {
51 let ms = ms.map(|m| IoSlice::new(m.as_bytes()));
57 macro_rules! cstr { { $b:tt } => {
58 CStr::from_bytes_with_nul($b)
59 .unwrap_or_else(|_| crashm("cstr not nul terminated?! bug!"))
62 fn crashm(m: &str) -> ! {
65 fn crashe(m: &str, e: Errno) -> ! {
66 crashv!(m, ": ", e.desc())
70 impl<T> nix::Result<T> {
71 fn context(self, m: &str) -> T {
74 Err(e) => crashe(m, e),
79 const ITOA_BUFL: usize = 12;
80 fn c_itoa(value: c_int, buf: &mut [u8; ITOA_BUFL]) -> &str {
82 *buf = [b'.'; ITOA_BUFL];
83 libc::snprintf({ let buf: *mut u8 = buf.as_mut_ptr(); buf as *mut i8 },
85 cstr!(b"%x\0").as_ptr(),
88 let s = buf.splitn(2, |&c| c == b'\0').next()
89 .unwrap_or_else(|| crashm("splitn no next"));
90 str::from_utf8(s).unwrap_or_else(|_| crashm("non-utf-8 from snprintf!"))
93 unsafe fn mdup2(oldfd: RawFd, newfd: RawFd, what: &str) {
94 match dup2(oldfd, newfd) {
95 Ok(got) if got == newfd => { },
96 Ok(_) => crashm("dup2 gave wrong return value"),
97 Err(e) => crashv!("dup2 ", what, ": ", e.desc()),
101 unsafe fn write_status(st_wfd: RawFd, estatus: u8) {
102 match write(st_wfd, slice::from_ref(&estatus)) {
104 Ok(_) => crashm("write child startup exit status: short write"),
105 Err(e) => crashe("write child startup exit status", e),
109 unsafe fn parent(st_rfd: RawFd) -> ! {
110 let mut exitstatus = 0u8;
112 match read(st_rfd, slice::from_mut(&mut exitstatus)) {
113 Ok(0) => crashm("startup/daemonisation failed"),
114 Ok(1) => libc::_exit(exitstatus.into()),
115 Ok(_) => crashm("read startup: excess read!"),
116 Err(e) if e == Errno::EINTR => continue,
117 Err(e) => crashe("read startup signal pipe", e),
122 unsafe fn intermediate(child: Pid, st_wfd: RawFd) -> ! {
123 let mut wstatus: c_int = 0;
125 let r = libc::waitpid(child.as_raw(), &mut wstatus, 0);
126 if r == -1 { crashe("await child startup status",
127 nix::errno::from_i32(errno())) }
128 if r != child.as_raw() { crashm("await child startup status: wrong pid") }
130 let cooked = WaitStatus::from_raw(child, wstatus)
131 .context("await child startup status: convert wait status");
133 WaitStatus::Exited(_, estatus) => {
134 let estatus: u8 = estatus.try_into()
135 .unwrap_or_else(|_| crashm(
136 "await child startup status: exit status out of range!"));
137 write_status(st_wfd, estatus);
141 WaitStatus::Signaled(_, signal, coredump) => {
142 crashv!("startup failed: died due to signal: ", signal.as_str(),
143 if coredump { " (core dumped)" } else { "" });
147 crashv!("child startup exit status was strange! 0x",
148 c_itoa(wstatus, &mut default()))
154 pub fn phase1() -> Self {
156 let null_fd = open(cstr!(b"/dev/null\0"), OFlag::O_RDWR, Mode::empty())
157 .context("open /dev/null");
158 mdup2(null_fd, 0, "null onto stdin");
160 let (st_rfd, st_wfd) = pipe().context("pipe");
162 match fork().context("fork (1)") {
163 ForkResult::Child => { }
164 ForkResult::Parent { child: _ } => {
165 close(st_wfd).context("close st_wfd pipe");
170 close(st_rfd).context("close st_rfd pipe");
171 setsid().context("setsid");
172 let intermediate_pid = Pid::this();
174 match fork().context("fork (2)") {
175 ForkResult::Child => { }
176 ForkResult::Parent { child } => {
177 intermediate(child, st_wfd)
190 pub fn complete(mut self) {
192 mdup2(self.null_fd, 1, "null over stdin");
194 if Pid::parent() != self.intermediate_pid {
196 "startup complete, but our parent is no longer the intermediate?");
198 kill(self.intermediate_pid, Some(Signal::SIGKILL))
199 .context("kill intermediate (after startup complete)");
201 write_status(self.st_wfd, 0);
202 mdup2(self.null_fd, 2, "null over stderrr");
204 self.drop_bomb.take();
209 impl Drop for Daemoniser {
211 if let Some(()) = self.drop_bomb.take() {
213 // We will crash in due course, having printed some messages
214 // to stderr, presumably.
217 panic!("Daemonizer object dropped unexpectedly, startup failed");