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
use std::ffi::{CString, OsStr, OsString};
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::exit;
use nix::sys::stat::{Mode, umask};
#[cfg(not(target_os = "macos"))]
use nix::unistd::{
chdir, chown, fork, ForkResult, getpid, Gid, initgroups, Pid, setgid, setsid,
setuid, Uid,
};
#[cfg(target_os = "macos")]
use nix::unistd::{
chdir, chown, close, dup2, fork, ForkResult, getpid, Gid, Pid, setgid, setsid, setuid, Uid,
};
use crate::{DaemonError, Result};
use crate::ffi::{PasswdRecord, set_proc_name};
use crate::group::Group;
use crate::stdio::{redirect_stdio, Stdio};
use crate::user::User;
pub struct Daemon {
pub chdir: PathBuf,
pub pid_file: Option<PathBuf>,
pub chown_pid_file: bool,
pub user: Option<User>,
pub group: Option<Group>,
pub umask: u16,
pub stdin: Stdio,
pub stdout: Stdio,
pub stderr: Stdio,
pub name: Option<OsString>,
}
impl Daemon {
pub fn new() -> Self {
Daemon {
chdir: Path::new("/").to_owned(),
pid_file: None,
chown_pid_file: false,
user: None,
group: None,
umask: 0o027,
stdin: Stdio::devnull(),
stdout: Stdio::devnull(),
stderr: Stdio::devnull(),
name: None,
}
}
pub fn pid_file<T: AsRef<Path>>(mut self, path: T, chmod: Option<bool>) -> Self {
self.pid_file = Some(path.as_ref().to_owned());
self.chown_pid_file = chmod.unwrap_or(false);
self
}
pub fn work_dir<T: AsRef<Path>>(mut self, path: T) -> Self {
self.chdir = path.as_ref().to_owned();
self
}
pub fn user<T: Into<User>>(mut self, user: T) -> Self {
self.user = Some(user.into());
self
}
pub fn group<T: Into<Group>>(mut self, group: T) -> Self {
self.group = Some(group.into());
self
}
pub fn umask(mut self, mask: u16) -> Self {
self.umask = mask;
self
}
pub fn stdin<T: Into<Stdio>>(mut self, stdio: T) -> Self {
self.stdin = stdio.into();
self
}
pub fn stdout<T: Into<Stdio>>(mut self, stdio: T) -> Self {
self.stdout = stdio.into();
self
}
pub fn stderr<T: Into<Stdio>>(mut self, stdio: T) -> Self {
self.stderr = stdio.into();
self
}
pub fn name(mut self, name: &OsStr) -> Self {
self.name = Some(OsString::from(name));
self
}
pub fn start(self) -> Result<()> {
let pid: Pid;
let has_pid_file = self.pid_file.is_some();
let pid_file_path = match self.pid_file {
Some(path) => path.clone(),
None => Path::new("").to_path_buf(),
};
redirect_stdio(&self.stdin, &self.stdout, &self.stderr)?;
if self.chown_pid_file && (self.user.is_none() || self.group.is_none()) {
return Err(DaemonError::InvalidUserGroupPair);
} else if (self.user.is_some() || self.group.is_some())
&& (self.user.is_none() || self.group.is_none())
{
return Err(DaemonError::InvalidUserGroupPair);
}
unsafe {
match fork() {
Ok(ForkResult::Parent { child: _ }) => exit(0),
Ok(ForkResult::Child) => (),
Err(_) => return Err(DaemonError::Fork),
}
}
if let Some(proc_name) = &self.name {
match set_proc_name(proc_name.as_ref()) {
Ok(()) => (),
Err(e) => return Err(e)
}
}
let umask_mode = match Mode::from_bits(self.umask as _) {
Some(mode) => mode,
None => return Err(DaemonError::InvalidUmaskBits),
};
umask(umask_mode);
if let Err(_) = setsid() {
return Err(DaemonError::SetSid);
};
if let Err(_) = chdir::<Path>(self.chdir.as_path()) {
return Err(DaemonError::ChDir);
};
pid = getpid();
if has_pid_file {
let pid_file = &pid_file_path;
match File::create(pid_file) {
Ok(mut fp) => {
if let Err(_) = fp.write_all(pid.to_string().as_ref()) {
return Err(DaemonError::WritePid);
}
}
Err(_) => return Err(DaemonError::WritePid),
};
}
if self.user.is_some() && self.group.is_some() {
let user = match self.user.unwrap() {
User::Id(id) => Uid::from_raw(id),
};
let uname = match PasswdRecord::get_record_by_id(user.as_raw()) {
Ok(record) => record.pw_name,
Err(_) => return Err(DaemonError::InvalidUser),
};
let gr = match self.group.unwrap() {
Group::Id(id) => Gid::from_raw(id),
};
if self.chown_pid_file && has_pid_file {
match chown(&pid_file_path, Some(user), Some(gr)) {
Ok(_) => (),
Err(_) => return Err(DaemonError::ChownPid),
};
}
match setgid(gr) {
Ok(_) => (),
Err(_) => return Err(DaemonError::SetGid),
};
#[cfg(not(target_os = "macos"))]
{
let u_cstr = match CString::new(uname) {
Ok(cstr) => cstr,
Err(_) => return Err(DaemonError::SetGid),
};
match initgroups(&u_cstr, gr) {
Ok(_) => (),
Err(_) => return Err(DaemonError::InitGroups),
};
}
match setuid(user) {
Ok(_) => (),
Err(_) => return Err(DaemonError::SetUid),
}
}
let chdir_path = self.chdir.to_owned();
match chdir::<Path>(chdir_path.as_ref()) {
Ok(_) => (),
Err(_) => return Err(DaemonError::ChDir),
};
Ok(())
}
}