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
//! Small crate which helps with writing daemon applications in Rust.
//!
//! I am aware about [daemonize](https://crates.io/crates/daemonize) and
//! [daemonize-me](https://crates.io/crates/daemonize-me) crates, but needed some
//! extended functionality like locking PID file and searching for running daemon.
//!
//! Complete example:
//!
//! ```rust
//! use daemonizr::{Daemonizr, DaemonizrError, Group, Stderr, Stdout, User};
//! use std::{path::PathBuf, process::exit, thread::sleep, time::Duration};
//!
//! fn main() {
//!     match Daemonizr::new()
//!         .work_dir(PathBuf::from("/Users/alex/git/private/daemonizr"))
//!         .expect("invalid path")
//!         .as_user(User::by_name("alex").expect("invalid user"))
//!         .as_group(Group::by_name("staff").expect("invalid group"))
//!         .pidfile(PathBuf::from("dmnzr.pid"))
//!         .stdout(Stdout::Redirect(PathBuf::from("dmnzr.out")))
//!         .stderr(Stderr::Redirect(PathBuf::from("dmnzr.err")))
//!         .umask(0o027)
//!         .expect("invalid umask")
//!         .spawn()
//!     {
//!         Err(DaemonizrError::AlreadyRunning) => {
//!             /* search for the daemon's PID  */
//!             match Daemonizr::new()
//!                 .work_dir(PathBuf::from("/Users/alex/git/private/daemonizr"))
//!                 .unwrap()
//!                 .pidfile(PathBuf::from("dmnzr.pid"))
//!                 .search()
//!             {
//!                 Err(x) => eprintln!("error: {}", x),
//!                 Ok(pid) => {
//!                     eprintln!("another daemon with pid {} is already running", pid);
//!                     exit(1);
//!                 }
//!             };
//!         }
//!         Err(e) => eprintln!("DaemonizrError: {}", e),
//!         Ok(()) => { /* We are in daemon process now */ }
//!     };
//!
//!     /* actual daemon work goes here */
//!     println!("write something to stdout");
//!     eprintln!("write something to stderr");
//!     sleep(Duration::from_secs(60));
//!     println!("Daemon exits.")
//! }
//! ```
//! Hint:
//! > ⚠️ This crate will only work on POSIX compatible systems,
//! > where the "nix" and "libc" crates are available.
//!
use nix::{
    fcntl::{flock, open, OFlag},
    libc::{
        getgrgid, getgrnam, getpwnam, getpwuid, mode_t, STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO,
    },
    sys::stat::{umask, Mode},
    unistd::{close, dup, fork, geteuid, getpid, setgid, setsid, setuid, write, Gid, Uid},
};
use std::os::unix::io::RawFd;
use std::{
    env::{current_dir, set_current_dir},
    error::Error,
    ffi::CString,
    path::PathBuf,
};

/// Daemonizr holds context needed for spawning the daemon process.
///
/// It includes:
/// * working directory of the daemon;
/// * UID and GID to be set to after going daemon;
/// * umask which daemon uses after dropping the privileges;
/// * the PID file to use;
/// * setup for stdout/stderr files
///
#[derive(Debug)]
pub struct Daemonizr {
    work_dir: PathBuf,
    user: User,
    group: Group,
    umask: Mode,
    pidfile: PathBuf,
    stdout: Stdout,
    stderr: Stderr,
    fd_lock: RawFd,
}

/// Super
impl Daemonizr {
    /// Creates a new default Daemonizr context with following attributes:
    ///
    /// * current directory is used as working directory;
    /// * current user and his default group used for daemon;
    /// * the [umask()](https://man7.org/linux/man-pages/man2/umask.2.html) is set to 0 (means creation mode = 777);
    /// * PID file "daemonizr.pid" in current directory is used as PID file;
    /// * the stdout and stderr are both closed.
    ///
    pub fn new() -> Self {
        let work_dir = current_dir().expect("unable to get current working directory");
        let (user, group) = whoami().expect("unable to determine current user");
        let pidfile = work_dir.clone().join("daemonizr.pid");
        let umask = Mode::from_bits(0o027).expect("invalid bit mask: 0o027");
        Daemonizr {
            work_dir,
            user,
            group,
            umask,
            pidfile,
            stdout: Stdout::Close,
            stderr: Stderr::Close,
            fd_lock: -1 as RawFd,
        }
    }

    /// Path to working directory for the daemon, this path must be a directory,
    /// must exist AND be an absolute path.
    pub fn work_dir(mut self, work_dir: PathBuf) -> Result<Self, DaemonizrError> {
        if !work_dir.is_absolute() {
            return Err(DaemonizrError::WorkDirNotAbsolute(work_dir));
        }
        if !work_dir.exists() {
            return Err(DaemonizrError::WorkDirNotExists(work_dir));
        }
        if !work_dir.is_dir() {
            return Err(DaemonizrError::WorkDirNotDir(work_dir));
        }
        self.work_dir = work_dir;

        Ok(self)
    }

    /// User to be set after going daemon
    pub fn as_user(mut self, user: User) -> Self {
        self.user = user;
        self
    }

    /// Group to be set after going daemon
    pub fn as_group(mut self, group: Group) -> Self {
        self.group = group;
        self
    }

    /// Umask to use for daemon
    pub fn umask(mut self, umask: u16) -> Result<Self, DaemonizrError> {
        match Mode::from_bits(umask as mode_t) {
            Some(x) => {
                self.umask = x;
                Ok(self)
            }
            None => Err(DaemonizrError::InvalidUmask(umask)),
        }
    }

    /// Path for the pidfile. If path is a relative path, it is assumed
    /// to be relative to the working directory.
    pub fn pidfile(mut self, pidfile: PathBuf) -> Self {
        self.pidfile = if pidfile.is_relative() {
            self.work_dir.clone().join(pidfile)
        } else {
            pidfile
        };
        self
    }

    /// Set behaviour for standard output: close or redirect to the given path.
    pub fn stdout(mut self, s: Stdout) -> Self {
        self.stdout = match s {
            Stdout::Close => s,
            Stdout::Redirect(x) => {
                if x.is_absolute() {
                    Stdout::Redirect(x)
                } else {
                    Stdout::Redirect(self.work_dir.clone().join(x))
                }
            }
        };
        self
    }

    /// Set behaviour for standard error: close or redirect to the given path.
    pub fn stderr(mut self, s: Stderr) -> Self {
        self.stderr = match s {
            Stderr::Close => s,
            Stderr::Redirect(x) => {
                if x.is_absolute() {
                    Stderr::Redirect(x)
                } else {
                    Stderr::Redirect(self.work_dir.clone().join(x))
                }
            }
        };
        self
    }

    /// Perform the actual creation of a daemon process.
    /// In case of success, this function never returns - the parent process will exit with
    /// exit code 0 (success), the child (daemon) process will
    pub fn spawn(mut self) -> Result<(), DaemonizrError> {
        // fork daemon
        match unsafe { fork() } {
            Ok(nix::unistd::ForkResult::Parent { .. }) => std::process::exit(0),
            Ok(nix::unistd::ForkResult::Child) => {}
            Err(e) => return Err(DaemonizrError::ForkFailed(e.to_string())),
        }

        // setsuid() - obtain new process group
        if let Err(e) = setsid() {
            return Err(DaemonizrError::FailedToSetsid(e.to_string()));
        }

        // setuid()
        match self.user {
            User::Id(u) => {
                if let Err(e) = setuid(Uid::from_raw(u)) {
                    return Err(DaemonizrError::FailedToSetUser(u, e.to_string()));
                }
            }
        }

        // setgid()
        match self.group {
            Group::Id(g) => {
                if let Err(e) = setgid(Gid::from_raw(g)) {
                    return Err(DaemonizrError::FailedToSetGroup(g, e.to_string()));
                }
            }
        }

        // close stdin/stdout/stderr
        if let Err(_) = close(STDIN_FILENO) {} // 0 - stdin
        if let Err(_) = close(STDOUT_FILENO) {}; // 1 - stdout
        if let Err(_) = close(STDERR_FILENO) {}; // 2 - stderr

        // set umask
        umask(self.umask);

        // set working directory
        if let Err(e) = set_current_dir(&self.work_dir) {
            return Err(DaemonizrError::FailedSetWorkDir(
                (&self.work_dir.clone().display()).to_string(),
                e.to_string(),
            ));
        }

        // open stdin (always as /dev/null)
        let stdi = match open(
            &PathBuf::from("/dev/null"),
            OFlag::O_RDWR,
            Mode::from_bits(0o666).expect("invalid mode 0o666"),
        ) {
            Err(e) => {
                return Err(DaemonizrError::FailedToReopen(
                    "stdin".to_owned(),
                    e.to_string(),
                ))
            }
            Ok(x) => x,
        };

        // open stdout
        let stdo = match self.stdout {
            Stdout::Close => dup(stdi),
            Stdout::Redirect(f) => open(
                &f,
                OFlag::O_CREAT | OFlag::O_RDWR | OFlag::O_APPEND,
                Mode::from_bits(0o666).expect("invalid mode 0o666"),
            ),
        };

        if let Err(e) = stdo {
            return Err(DaemonizrError::FailedToReopen(
                "stdout".to_owned(),
                e.to_string(),
            ));
        }

        // open stderr
        let stde = match self.stderr {
            Stderr::Close => dup(stdi),
            Stderr::Redirect(f) => open(
                &f,
                OFlag::O_CREAT | OFlag::O_RDWR | OFlag::O_APPEND,
                Mode::from_bits(0o666).expect("invalid mode 0o666"),
            ),
        };

        if let Err(e) = stde {
            return Err(DaemonizrError::FailedToReopen(
                "stderr".to_owned(),
                e.to_string(),
            ));
        }

        // create pidfile
        self.fd_lock = match open(
            &self.pidfile,
            OFlag::O_CREAT | OFlag::O_RDWR,
            Mode::from_bits(0o666).expect("invalid mode 0o666"),
        ) {
            Err(e) => return Err(DaemonizrError::FailedCreatePidfile(e.to_string())),
            Ok(x) => x,
        };

        match flock(self.fd_lock, nix::fcntl::FlockArg::LockExclusiveNonblock) {
            Err(_) => return Err(DaemonizrError::AlreadyRunning),
            Ok(_) => {
                let pid = getpid();
                let pidb = format!("{}\n", pid.as_raw());
                if let Err(e) = write(self.fd_lock, pidb.as_bytes()) {
                    return Err(DaemonizrError::FailedToWritePidfile(e.to_string()));
                }
            }
        };

        Ok(())
    }

    /// Search for PID of an already spawned daemon. If one is present,
    /// its PID is returned, otherwise an error is returned.
    ///
    /// Hint: for search, you'll need to set at least absolute path with [`Self::pidfile()`],
    /// or, set absolute path using [`Self::work_dir()`] in conjuction with setting a relative
    /// path using [`Self::pidfile()`].
    pub fn search(self) -> Result<u32, DaemonizrError> {
        if !self.pidfile.exists() {
            return Err(DaemonizrError::NoDaemonFound);
        }
        let (pf_fd, pid) = match open(
            &self.pidfile,
            OFlag::O_RDONLY,
            Mode::from_bits(0o666).expect("invalid mode 0o666"),
        ) {
            Err(e) => return Err(DaemonizrError::FailedToOpenPidfile(e.to_string())),
            Ok(pf_fd) => {
                let mut buf: [u8; 10] = [32; 10];
                match nix::unistd::read(pf_fd, &mut buf as &mut [u8]) {
                    Err(e) => return Err(DaemonizrError::FailedToReadPidfile(e.to_string())),
                    Ok(u) => {
                        let s = String::from_utf8(buf.to_vec())
                            .expect("unable to convert PID to string")
                            .trim_end()
                            .to_string();
                        if u > 0 {
                            (
                                pf_fd,
                                u32::from_str_radix(&s, 10).expect("unable to parse PID to number"),
                            )
                        } else {
                            return Err(DaemonizrError::FailedToReadPidfile(
                                format!("invalid pid: {}", s).to_owned(),
                            ));
                        }
                    }
                }
            }
        };
        // now check that the pidfile is still locked, i.e. not stale
        match flock(pf_fd, nix::fcntl::FlockArg::LockExclusiveNonblock) {
            Err(_) => {}
            Ok(_) => {
                /* unexpected! */
                return Err(DaemonizrError::NoDaemonFound);
            }
        };
        Ok(pid)
    }
}

/// Determines behaviour for "stdout" file descriptor
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Stdout {
    /// stdout will be closed
    Close,
    /// stdout will be redirected to file
    Redirect(PathBuf),
}

/// Determines behaviour for "stderr" file descriptor
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Stderr {
    /// stderr will be closed
    Close,
    /// stderr will be redirected to file
    Redirect(PathBuf),
}

#[doc(hidden)]
/// Internal function to determine current user and group IDs
fn whoami() -> Result<(User, Group), DaemonizrError> {
    let uid = geteuid();
    let pwraw = unsafe { getpwuid(uid.as_raw()) };
    return if pwraw.is_null() {
        Err(DaemonizrError::NoUserOrGroup)
    } else {
        let gid = unsafe { (*pwraw).pw_gid };
        Ok((User::Id(uid.as_raw()), Group::Id(gid)))
    };
}

/// User object holds a valid user id (UID) to change to after child process has been daemonized.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum User {
    Id(u32),
}
/// Group object holds a valid group id (GID) to change to after child process has been daemonized.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Group {
    Id(u32),
}

impl User {
    /// Lookup User by given uid.
    pub fn by_uid(uid: u32) -> Result<User, DaemonizrError> {
        unsafe {
            let rawpw = getpwuid(uid);
            return if rawpw.is_null() {
                Err(DaemonizrError::InvalidUid(uid))
            } else {
                Ok(User::Id(uid))
            };
        }
    }

    /// Lookup User by given username.
    pub fn by_name(username: &str) -> Result<User, DaemonizrError> {
        unsafe {
            let cs = match CString::new(username) {
                Err(_) => return Err(DaemonizrError::ErrorCString),
                Ok(s) => s,
            };
            let rawpw = getpwnam(cs.as_ptr());
            return if rawpw.is_null() {
                Err(DaemonizrError::InvalidUsername(username.to_string()))
            } else {
                Ok(User::Id((*rawpw).pw_uid))
            };
        }
    }
}

impl Group {
    /// Lookup Group by given gid (group id).
    pub fn by_gid(gid: u32) -> Result<Group, DaemonizrError> {
        unsafe {
            let group = getgrgid(gid);
            return if group.is_null() {
                Err(DaemonizrError::InvalidGid(gid))
            } else {
                Ok(Group::Id((*group).gr_gid))
            };
        };
    }

    /// Lookup group by given group name.
    pub fn by_name(groupname: &str) -> Result<Group, DaemonizrError> {
        let cs = match CString::new(groupname) {
            Err(_) => return Err(DaemonizrError::ErrorCString),
            Ok(s) => s,
        };
        unsafe {
            let rawpw = getgrnam(cs.as_ptr());
            return if rawpw.is_null() {
                Err(DaemonizrError::InvalidGroupname(groupname.to_string()))
            } else {
                Ok(Group::Id((*rawpw).gr_gid))
            };
        }
    }
}

/// Error type reported by daemonizr.
#[derive(Debug)]
pub enum DaemonizrError {
    /// Provided working directory path is not an absolute path
    WorkDirNotAbsolute(PathBuf),
    /// Provided working directory path doesn't exist
    WorkDirNotExists(PathBuf),
    /// Provided working directory path is not a directory
    WorkDirNotDir(PathBuf),
    /// Provided UID is invalid
    InvalidUid(u32),
    /// Provided GID is invalid
    InvalidGid(u32),
    /// Provided umask is invalid
    InvalidUmask(u16),
    /// Provided username is invalid
    InvalidUsername(String),
    /// Provided groupname is invalid
    InvalidGroupname(String),
    /// Internal error while converting [CString]
    ErrorCString,
    /// Failed to determine current user / group
    NoUserOrGroup,
    /// failed to daemonize (fork) process
    ForkFailed(String),
    /// failed to set working directory
    FailedSetWorkDir(String, String),
    /// failed to set user to given uid
    FailedToSetUser(u32, String),
    /// failed to set user to given gid
    FailedToSetGroup(u32, String),
    /// failed to setsid() (obtain new process group)
    FailedToSetsid(String),
    /// failed to reopened given file stream
    FailedToReopen(String, String),
    /// failed to create pidfile
    FailedCreatePidfile(String),
    /// daemon already running (holding lock over pidfile)
    AlreadyRunning,
    /// failed to lock pidfile
    ErrorLockingPidfile(String),
    /// Error while writing pidfile
    FailedToWritePidfile(String),
    /// Error while writing pidfile
    FailedToReadPidfile(String),
    /// Error while writing pidfile
    FailedToOpenPidfile(String),
    /// No daemon found
    NoDaemonFound,
}

impl std::fmt::Display for DaemonizrError {
    /// [std::fmt::Display] trait implementation for DaemonizrError
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DaemonizrError::WorkDirNotAbsolute(m) => {
                write!(f, "working directory is not absolute: {}", m.display())
            }
            DaemonizrError::WorkDirNotExists(m) => {
                write!(f, "working directory does not exist: {}", m.display())
            }
            DaemonizrError::WorkDirNotDir(m) => {
                write!(f, "working directory is not a directory: {}", m.display())
            }
            DaemonizrError::InvalidUid(m) => write!(f, "invalid uid provided: {}", m),
            DaemonizrError::InvalidGid(m) => write!(f, "invalid gid provided: {}", m),
            DaemonizrError::InvalidUmask(u) => write!(f, "invalid umask provided: {}", u),
            DaemonizrError::InvalidUsername(s) => write!(f, "invalid username: {}", s),
            DaemonizrError::InvalidGroupname(s) => write!(f, "invalid groupname: {}", s),
            DaemonizrError::ErrorCString => write!(f, "invalid C string"),
            DaemonizrError::NoUserOrGroup => {
                write!(f, "unable to determine user or group of current user")
            }
            DaemonizrError::ForkFailed(e) => write!(f, "fork failed: {}", e),
            DaemonizrError::FailedSetWorkDir(d, e) => {
                write!(f, "failed to set current directory to {}: {}", d, e)
            }
            DaemonizrError::FailedToSetUser(u, e) => {
                write!(f, "failed to set user to UID {}: {}", u, e)
            }
            DaemonizrError::FailedToSetGroup(g, e) => {
                write!(f, "failed to set group to GID {}: {}", g, e)
            }
            DaemonizrError::FailedToSetsid(s) => write!(f, "failed to setsid(): {}", s),
            DaemonizrError::FailedToReopen(s, e) => write!(f, "failed to reopen {}: {}", s, e),
            DaemonizrError::FailedCreatePidfile(s) => write!(f, "failed to create pid file: {}", s),
            DaemonizrError::AlreadyRunning => {
                write!(f, "another daemon is already locking pidfile")
            }
            DaemonizrError::ErrorLockingPidfile(s) => write!(f, "error locking pidfile: {}", s),
            DaemonizrError::FailedToWritePidfile(s) => write!(f, "error writing pidfile: {}", s),
            DaemonizrError::FailedToOpenPidfile(s) => write!(f, "error opening pidfile: {}", s),
            DaemonizrError::FailedToReadPidfile(s) => write!(f, "error reading pidfile: {}", s),
            DaemonizrError::NoDaemonFound => write!(f, "no existing daemon was found"),
        }
    }
}

impl Error for DaemonizrError {
    /// [Error] trait implementation for DaemonizrError
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}