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
#![doc(test(attr(deny(warnings))))]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
use std::env;
use std::fs::OpenOptions;
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::AsRawFd;
use std::path::{Path, PathBuf};
use std::process;
use err_context::prelude::*;
use log::{debug, trace, warn};
use nix::sys::stat::{self, Mode};
use nix::unistd::{self, ForkResult, Gid, Uid};
use serde::{Deserialize, Serialize};
use spirit::error::log_errors;
use spirit::fragment::driver::OnceDriver;
use spirit::fragment::Installer;
use spirit::AnyError;
use structdoc::StructDoc;
#[cfg(feature = "cfg-help")]
use structopt::StructOpt;
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct Daemonize {
daemonize: bool,
pid_file: Option<PathBuf>,
}
impl Daemonize {
pub fn daemonize(&self) -> Result<(), AnyError> {
if self.daemonize {
trace!("Redirecting stdio");
let devnull = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open("/dev/null")
.context("Failed to open /dev/null")?;
for fd in &[0, 1, 2] {
unistd::dup2(devnull.as_raw_fd(), *fd)
.with_context(|_| format!("Failed to redirect FD {}", fd))?;
}
trace!("Doing double fork");
if let ForkResult::Parent { .. } = unistd::fork().context("Failed to fork")? {
process::exit(0);
}
unistd::setsid()?;
if let ForkResult::Parent { .. } = unistd::fork().context("Failed to fork")? {
process::exit(0);
}
} else {
trace!("Not going to background");
}
if let Some(file) = self.pid_file.as_ref() {
let mut f = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o644)
.open(file)
.with_context(|_| format!("Failed to write PID file {}", file.display()))?;
writeln!(f, "{}", unistd::getpid())?;
}
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "cfg-help", derive(StructDoc))]
#[serde(untagged)]
#[non_exhaustive]
pub enum SecId {
Name(String),
Id(u32),
#[serde(skip)]
Nothing,
}
impl SecId {
fn is_nothing(&self) -> bool {
self == &SecId::Nothing
}
}
impl Default for SecId {
fn default() -> Self {
SecId::Nothing
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "cfg-help", derive(StructDoc))]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct Daemon {
#[serde(default, skip_serializing_if = "SecId::is_nothing")]
pub user: SecId,
#[serde(default, skip_serializing_if = "SecId::is_nothing")]
pub group: SecId,
#[serde(skip_serializing_if = "Option::is_none")]
pub pid_file: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub workdir: Option<PathBuf>,
#[serde(default)]
pub daemonize: bool,
}
impl Daemon {
pub fn prepare(&self) -> Result<Daemonize, AnyError> {
debug!("Preparing to daemonize with {:?}", self);
stat::umask(Mode::empty());
let workdir = self
.workdir
.as_ref()
.map(|pb| pb as &Path)
.unwrap_or_else(|| Path::new("/"));
trace!("Changing working directory to {:?}", workdir);
env::set_current_dir(workdir)
.with_context(|_| format!("Failed to switch to workdir {}", workdir.display()))?;
match self.group {
SecId::Id(id) => {
unistd::setgid(Gid::from_raw(id)).context("Failed to change the group")?
}
SecId::Name(ref name) => privdrop::PrivDrop::default()
.group(&name)
.apply()
.context("Failed to change the group")?,
SecId::Nothing => (),
}
match self.user {
SecId::Id(id) => {
unistd::setuid(Uid::from_raw(id)).context("Failed to change the user")?
}
SecId::Name(ref name) => privdrop::PrivDrop::default()
.user(&name)
.apply()
.context("Failed to change the user")?,
SecId::Nothing => (),
}
if let Some(file) = self.pid_file.as_ref() {
let _ = OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.mode(0o644)
.open(file)
.with_context(|_| format!("Writing the PID file {}", file.display()))?;
}
Ok(Daemonize {
daemonize: self.daemonize,
pid_file: self.pid_file.clone(),
})
}
pub fn daemonize(&self) -> Result<(), AnyError> {
self.prepare()?.daemonize()?;
Ok(())
}
}
#[derive(Copy, Clone, Debug, Default)]
pub struct DaemonizeInstaller;
impl<O, C> Installer<Daemonize, O, C> for DaemonizeInstaller {
type UninstallHandle = ();
fn install(&mut self, daemonize: Daemonize, _: &str) {
if log_errors(module_path!(), || daemonize.daemonize()).is_err() {
process::abort();
}
}
}
spirit::simple_fragment! {
impl Fragment for Daemon {
type Driver = OnceDriver<Self>;
type Resource = Daemonize;
type Installer = DaemonizeInstaller;
fn create(&self, _: &'static str) -> Result<Daemonize, AnyError> {
self.prepare()
}
}
}
impl From<UserDaemon> for Daemon {
fn from(ud: UserDaemon) -> Daemon {
Daemon {
pid_file: ud.pid_file,
workdir: ud.workdir,
daemonize: ud.daemonize,
..Daemon::default()
}
}
}
#[cfg_attr(not(doc), allow(missing_docs))]
#[cfg_attr(
doc,
doc = r#"
Command line options fragment.
This adds the `-d` (`--daemonize`) and `-f` (`--foreground`) flag to command line. These
override whatever is written in configuration (if merged together with the configuration).
This can be used to transform the [`Daemon`] before daemonization.
The [`Pipeline`] here can be used to automatically handle both configuration and command line.
See the [crate example][index.html#examples].
Flatten this into the top-level `StructOpt` structure.
[`Pipeline`]: spirit::Pipeline
"#
)]
#[derive(Clone, Debug, StructOpt)]
#[non_exhaustive]
pub struct Opts {
#[structopt(short, long)]
pub daemonize: bool,
#[structopt(short, long)]
pub foreground: bool,
}
impl Opts {
pub fn daemonize(&self) -> bool {
self.daemonize && !self.foreground
}
pub fn transform(&self, daemon: Daemon) -> Daemon {
Daemon {
daemonize: self.daemonize(),
..daemon
}
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "cfg-help", derive(StructDoc))]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct UserDaemon {
#[serde(skip_serializing_if = "Option::is_none")]
pub pid_file: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub workdir: Option<PathBuf>,
#[serde(default)]
pub daemonize: bool,
}
impl UserDaemon {
pub fn into_daemon(self) -> Daemon {
self.into()
}
}
spirit::simple_fragment! {
impl Fragment for UserDaemon {
type Driver = OnceDriver<Self>;
type Resource = Daemonize;
type Installer = DaemonizeInstaller;
fn create(&self, _: &'static str) -> Result<Daemonize, AnyError> {
Daemon::from(self.clone()).prepare()
}
}
}