daemonbase 0.1.5

A library for providing the foundation for daemon processes.
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
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
//! Process management.

#[cfg(unix)]
pub use self::unix::{Args, Config, GroupId, Process, UserId};

#[cfg(all(unix, feature = "tokio"))]
pub use self::unix::exit_signalled;

#[cfg(target_os = "linux")]
pub use self::linux::EnvSockets;

#[cfg(not(unix))]
pub use self::not_unix::{Args, Config, Process};

#[cfg(all(not(unix), feature = "tokio"))]
pub use self::not_unix::exit_signalled;

#[cfg(not(target_os = "linux"))]
pub use self::not_linux::EnvSockets;

//============ unix ==========================================================

/// Implementation for normal Unix-style systems.
///
#[cfg(unix)]
mod unix {
    use crate::config::{ConfigFile, ConfigPath};
    use crate::error::Failed;
    use log::error;
    use nix::fcntl::{Flock, FlockArg, OFlag, open};
    use nix::sys::stat::Mode;
    use nix::sys::stat::umask;
    use nix::unistd;
    use nix::unistd::{Gid, Group, Uid, User};
    use nix::unistd::{chroot, close, fork, getpid, setsid};
    use serde::{Deserialize, Serialize};
    use std::env::set_current_dir;
    use std::ffi::{CStr, CString};
    use std::fs::{File, OpenOptions};
    use std::io::Write;
    use std::os::unix::fs::OpenOptionsExt;
    use std::path::{Path, PathBuf, StripPrefixError};
    use std::str::FromStr;

    //-------- Process -------------------------------------------------------

    pub struct Process {
        /// All the configuration.
        config: Config,

        /// The pid file if requested.
        pid_file: Option<Flock<File>>,
    }

    impl Process {
        /// Creates the process from a config struct.
        pub fn from_config(config: Config) -> Self {
            Self {
                config,
                pid_file: None,
            }
        }

        /// Adjusts a path for use after dropping privileges.
        ///
        /// Since [`drop_privileges`][Self::drop_privileges] may change the
        /// file system root, all absolute paths will need to be adjusted if
        /// they should be used after it is called.
        ///
        /// The method returns an error if the path is outside of what’s
        /// accessible to the process after dropping privileges.
        pub fn adjust_path(
            &self,
            path: PathBuf,
        ) -> Result<PathBuf, StripPrefixError> {
            if let Some(chroot) = self.config.chroot.as_ref() {
                Ok(Path::new("/").join(path.strip_prefix(chroot)?))
            } else {
                Ok(path)
            }
        }

        /// Sets up the process as a daemon.
        ///
        /// If `background` is `true`, the daemon will be set up to run in
        /// the background which may involve forking.
        ///
        /// After the method returns, we will be running in the final process
        /// but still have the same privileges we were initially started with.
        /// This allows you to perform actions that require the original
        /// privileges in the forked process. Once you are done with that,
        /// call [`drop_privileges`][Self::drop_privileges] to conclude
        /// setting up the daemon.
        ///
        /// Because access to the standard streams may get lost during the
        /// method, it uses the logging facilities for any diagnostic output.
        /// You should therefore have set up your logging system prior to
        /// calling this method.
        pub fn setup_daemon(
            &mut self,
            background: bool,
        ) -> Result<(), Failed> {
            self.create_pid_file()?;

            if background {
                // Fork to detach from terminal.
                self.perform_fork()?;

                // Create a new session.
                if let Err(err) = setsid() {
                    error!("Fatal: failed to crates new session: {err}");
                    return Err(Failed);
                }

                // Fork again to stop being the session leader so we can’t
                // acquire a controlling terminal on SVR4.
                self.perform_fork()?;

                // Change the working directory to either what’s configured
                // or / (so we don’t block a file system from being umounted).
                self.change_working_dir(true)?;

                // Set umask to 0 -- the mask is used “inverted,” that is,
                // everything set in the mask is removed from the actual
                // mode of a created file. Setting it to 0 allows everything.
                umask(Mode::empty());

                // Redirect the three standard streams to /dev/null.
                self.redirect_stdio()?;
            } else {
                self.change_working_dir(false)?;
            }

            // chown_pid_file

            Ok(())
        }

        /// Drops privileges.
        ///
        /// If requested via the config, this method will drop all potentially
        /// elevated privileges. This may include losing root or system
        /// administrator permissions and change the file system root.
        pub fn drop_privileges(&mut self) -> Result<(), Failed> {
            if let Some(path) = self.config.chroot.as_ref() {
                if let Err(err) = chroot(path.as_path()) {
                    error!(
                        "Fatal: cannot chroot to '{}': {}'",
                        path.display(),
                        err
                    );
                    return Err(Failed);
                }
            }

            self.set_user_and_group()?;

            self.write_pid_file()?;

            Ok(())
        }

        /// Changes the user and group IDs.
        fn set_user_and_group(&self) -> Result<(), Failed> {
            // Unfortunately, this isn’t quite as portable as we want it to
            // be as most of the function we use are not available on some
            // platforms. Instead of copying the cfg attributes from the nix
            // crate, we define fallback functions and overwrite their symbol
            // if possible using a glob import.
            //
            // For setting uid and gid, we need to cascade: Use `setresuid`
            // if available, otherwise use `setreuid` if available, otherwise
            // use `setuid`; analogous for gid. We achieve this by having
            // the fallback call the next step which may itself be a fallback.

            /// Dummy fallback function for `nix::unistd::initgroups`.
            #[allow(dead_code)]
            fn initgroups(
                _user: &CStr,
                _group: Gid,
            ) -> Result<(), nix::errno::Errno> {
                Ok(())
            }

            /// Fallback function for `nix::unistd::setresgid`.
            #[allow(dead_code)]
            fn setresgid(
                rgid: Gid,
                egid: Gid,
                _sgid: Gid,
            ) -> Result<(), nix::errno::Errno> {
                use nix::libc::{c_int, gid_t};

                #[allow(dead_code)]
                unsafe fn setregid(rgid: gid_t, _egid: gid_t) -> c_int {
                    unsafe { nix::libc::setgid(rgid) }
                }

                {
                    #[allow(unused_imports)]
                    use nix::libc::*;

                    if unsafe { setregid(rgid.as_raw(), egid.as_raw()) } != 0
                    {
                        return Err(nix::errno::Errno::last());
                    }
                }

                Ok(())
            }

            /// Fallback function for `nix::unistd::setresuid`.
            #[allow(dead_code)]
            fn setresuid(
                ruid: Uid,
                euid: Uid,
                _suid: Uid,
            ) -> Result<(), nix::errno::Errno> {
                use nix::libc::{c_int, uid_t};

                #[allow(dead_code)]
                unsafe fn setreuid(ruid: uid_t, _euid: uid_t) -> c_int {
                    unsafe { nix::libc::setuid(ruid) }
                }

                {
                    #[allow(unused_imports)]
                    use nix::libc::*;

                    if unsafe { setreuid(ruid.as_raw(), euid.as_raw()) } != 0
                    {
                        return Err(nix::errno::Errno::last());
                    }
                }

                Ok(())
            }

            let Some(user) = self.config.user.as_ref() else {
                return Ok(());
            };

            // If we don’t have an explicit group, we use the user’s group.
            let gid = self
                .config
                .group
                .as_ref()
                .map(|g| g.gid)
                .unwrap_or_else(|| user.gid);

            // Let the system load the supplemental groups for the user.
            {
                #[allow(unused_imports)]
                use nix::unistd::*;

                initgroups(&user.c_name, gid).map_err(|err| {
                    error!(
                        "failed to initialize the group access list: {err}",
                    );
                    Failed
                })?;
            }

            // Set the group ID.
            {
                #[allow(unused_imports)]
                use nix::unistd::*;

                setresgid(gid, gid, gid).map_err(|err| {
                    error!("failed to set group ID: {err}");
                    Failed
                })?;
            }

            // Set the user ID.
            {
                #[allow(unused_imports)]
                use nix::unistd::*;

                setresuid(user.uid, user.uid, user.uid).map_err(|err| {
                    error!("failed to set user ID: {err}");
                    Failed
                })?;
            }

            Ok(())
        }

        /// Creates the pid file if requested.
        fn create_pid_file(&mut self) -> Result<(), Failed> {
            let path = match self.config.pid_file.as_ref() {
                Some(path) => path,
                None => return Ok(()),
            };

            let file = OpenOptions::new()
                .read(false)
                .write(true)
                .create(true)
                .truncate(true)
                .mode(0o666)
                .open(path);
            let file = match file {
                Ok(file) => file,
                Err(err) => {
                    error!(
                        "Fatal: failed to create PID file {}: {}",
                        path.display(),
                        err
                    );
                    return Err(Failed);
                }
            };
            let file =
                match Flock::lock(file, FlockArg::LockExclusiveNonblock) {
                    Ok(file) => file,
                    Err((_, err)) => {
                        error!(
                            "Fatal: cannot lock PID file {}: {}",
                            path.display(),
                            err
                        );
                        return Err(Failed);
                    }
                };
            self.pid_file = Some(file);
            Ok(())
        }

        /// Updates the pid in the pid file after forking.
        fn write_pid_file(&mut self) -> Result<(), Failed> {
            if let Some(pid_file) = self.pid_file.as_mut() {
                let pid = format!("{}", getpid());
                if let Err(err) = pid_file.write_all(pid.as_bytes()) {
                    error!("Fatal: failed to write PID to PID file: {err}");
                    return Err(Failed);
                }
            }
            Ok(())
        }

        /// Peforms a fork and exits the parent process.
        fn perform_fork(&self) -> Result<(), Failed> {
            match unsafe { fork() } {
                Ok(res) => {
                    if res.is_parent() {
                        std::process::exit(0)
                    }
                    Ok(())
                }
                Err(err) => {
                    error!("Fatal: failed to detach: {err}");
                    Err(Failed)
                }
            }
        }

        /// Changes the current working directory in necessary.
        fn change_working_dir(&self, background: bool) -> Result<(), Failed> {
            let mut path = self
                .config
                .working_dir
                .as_ref()
                .or(self.config.chroot.as_ref())
                .map(ConfigPath::as_path);
            if background {
                path = path.or(Some(Path::new("/")));
            }
            if let Some(path) = path {
                if let Err(err) = set_current_dir(path) {
                    error!(
                        "Fatal: failed to set working directory {}: {}",
                        path.display(),
                        err
                    );
                    return Err(Failed);
                }
            }

            Ok(())
        }

        /// Changes the stdio streams to /dev/null.
        fn redirect_stdio(&self) -> Result<(), Failed> {
            let dev_null =
                match open("/dev/null", OFlag::O_RDWR, Mode::empty()) {
                    Ok(fd) => fd,
                    Err(err) => {
                        error!("Fatal: failed to open /dev/null: {err}");
                        return Err(Failed);
                    }
                };

            if let Err(err) = unistd::dup2_stdin(&dev_null) {
                error!("Fatal: failed to redirect stdin to /dev/null: {err}");
                return Err(Failed);
            }
            if let Err(err) = unistd::dup2_stdout(&dev_null) {
                error!(
                    "Fatal: failed to redirect stdout to /dev/null: {err}"
                );
                return Err(Failed);
            }
            if let Err(err) = unistd::dup2_stderr(&dev_null) {
                error!(
                    "Fatal: failed to redirect stderr to /dev/null: {err}"
                );
                return Err(Failed);
            }

            if let Err(err) = close(dev_null) {
                error!("Fatal: failed to close /dev/null: {err}");
                return Err(Failed);
            }

            Ok(())
        }
    }

    //-------- Config --------------------------------------------------------

    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
    pub struct Config {
        /// The optional PID file for server mode.
        #[serde(rename = "pid-file")]
        pid_file: Option<ConfigPath>,

        /// The optional working directory for server mode.
        #[serde(rename = "working-dir")]
        working_dir: Option<ConfigPath>,

        /// The optional directory to chroot to in server mode.
        chroot: Option<ConfigPath>,

        /// The name of the user to change to in server mode.
        user: Option<UserId>,

        /// The name of the group to change to in server mode.
        group: Option<GroupId>,
    }

    impl Config {
        pub fn from_config_file(
            file: &mut ConfigFile,
        ) -> Result<Self, Failed> {
            Ok(Config {
                pid_file: file.take_path("pid-file")?,
                working_dir: file.take_path("working-dir")?,
                chroot: file.take_path("chroot")?,
                user: file.take_from_str("user")?,
                group: file.take_from_str("group")?,
            })
        }

        /// Creates the process from command line arguments only.
        pub fn from_args(args: Args) -> Self {
            Config {
                pid_file: args.pid_file,
                working_dir: args.working_dir,
                chroot: args.chroot,
                user: args.user,
                group: args.group,
            }
        }

        /// Applies the arguments to the process.
        pub fn apply_args(&mut self, args: Args) {
            if let Some(pid_file) = args.pid_file {
                self.pid_file = Some(pid_file)
            }
            if let Some(working_dir) = args.working_dir {
                self.working_dir = Some(working_dir)
            }
            if let Some(chroot) = args.chroot {
                self.chroot = Some(chroot)
            }
            if let Some(user) = args.user {
                self.user = Some(user)
            }
            if let Some(group) = args.group {
                self.group = Some(group)
            }
        }

        pub fn with_pid_file(mut self, v: ConfigPath) -> Self {
            self.pid_file = Some(v);
            self
        }

        pub fn with_working_dir(mut self, v: ConfigPath) -> Self {
            self.working_dir = Some(v);
            self
        }

        pub fn with_chroot(mut self, v: ConfigPath) -> Self {
            self.chroot = Some(v);
            self
        }

        pub fn with_user(mut self, v: &str) -> Result<Self, String> {
            self.user = Some(UserId::from_str(v)?);
            Ok(self)
        }

        pub fn with_user_id(mut self, user_id: UserId) -> Self {
            self.user = Some(user_id);
            self
        }

        pub fn with_group(mut self, v: &str) -> Result<Self, String> {
            self.group = Some(GroupId::from_str(v)?);
            Ok(self)
        }

        pub fn with_group_id(mut self, group_id: GroupId) -> Self {
            self.group = Some(group_id);
            self
        }
    }

    //-------- Args ----------------------------------------------------------

    #[derive(Clone, Debug, clap::Args)]
    #[group(id = "process-args")]
    pub struct Args {
        /// The file for keep the daemon process's PID in
        #[arg(long, value_name = "PATH")]
        pub pid_file: Option<ConfigPath>,

        /// The working directory of the daemon process
        #[arg(long, value_name = "PATH")]
        pub working_dir: Option<ConfigPath>,

        /// Root directory for the daemon process
        #[arg(long, value_name = "PATH")]
        pub chroot: Option<ConfigPath>,

        /// User for the daemon process
        #[arg(long, value_name = "UID")]
        pub user: Option<UserId>,

        /// Group for the daemon process
        #[arg(long, value_name = "GID")]
        pub group: Option<GroupId>,
    }

    impl Args {
        pub fn into_config(self) -> Config {
            Config::from_args(self)
        }
    }

    //-------- UserId --------------------------------------------------------

    /// A user ID in configuration.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(try_from = "String", into = "String", expecting = "a user name")]
    pub struct UserId {
        /// The user name.
        ///
        /// This is used for error reporting.
        name: String,

        /// The user name as a C string.
        ///
        /// This is used internally. We keep both the string and C string
        /// versions because conversion can cause errors, so it best happens
        /// already when creating an object.
        c_name: CString,

        /// The numerical user ID.
        uid: Uid,

        /// The numerical group ID of the user.
        gid: Gid,
    }

    impl TryFrom<String> for UserId {
        type Error = String;

        fn try_from(name: String) -> Result<Self, Self::Error> {
            let Ok(c_name) = CString::new(name.clone()) else {
                return Err(format!("invalid user name '{name}'"));
            };
            match User::from_name(&name) {
                Ok(Some(user)) => Ok(UserId {
                    name,
                    c_name,
                    gid: user.gid,
                    uid: user.uid,
                }),
                Ok(None) => Err(format!("unknown user '{name}'")),
                Err(err) => {
                    Err(format!("failed to resolve user '{name}': {err}"))
                }
            }
        }
    }

    impl FromStr for UserId {
        type Err = String;

        fn from_str(name: &str) -> Result<Self, Self::Err> {
            String::from(name).try_into()
        }
    }

    impl From<UserId> for String {
        fn from(user: UserId) -> Self {
            user.name
        }
    }

    //-------- GroupId -------------------------------------------------------

    /// A user ID in configuration.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(try_from = "String", into = "String", expecting = "a user name")]
    pub struct GroupId {
        /// The group name.
        name: String,

        /// The numerical group ID.
        gid: Gid,
    }

    impl TryFrom<String> for GroupId {
        type Error = String;

        fn try_from(name: String) -> Result<Self, Self::Error> {
            match Group::from_name(&name) {
                Ok(Some(group)) => Ok(GroupId {
                    gid: group.gid,
                    name,
                }),
                Ok(None) => Err(format!("unknown group '{name}'")),
                Err(err) => {
                    Err(format!("failed to resolve group '{name}': {err}"))
                }
            }
        }
    }

    impl FromStr for GroupId {
        type Err = String;

        fn from_str(name: &str) -> Result<Self, Self::Err> {
            String::from(name).try_into()
        }
    }

    impl From<GroupId> for String {
        fn from(user: GroupId) -> Self {
            user.name
        }
    }

    //------------ exit_signalled --------------------------------------------

    /// Returns when an exit signal was received.
    ///
    /// Returns when either a SIGINT or SIGTERM was received.
    ///
    #[cfg(feature = "tokio")]
    pub async fn exit_signalled() -> Result<(), std::io::Error> {
        use log::info;
        use tokio::signal::unix::{SignalKind, signal};

        let mut sigterm = signal(SignalKind::terminate())?;
        let mut sigint = signal(SignalKind::interrupt())?;

        tokio::select! {
            _ = sigterm.recv() => {
                info!("Received SIGTERM. Shutting down.");
            }
            _ = sigint.recv() => {
                info!("Received SIGINT. Shutting down.");
            }
        }
        Ok(())
    }
}

/// An error occurred while working with environment variable derived socket
/// file descriptors.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum EnvSocketsError {
    /// This instance of EnvSockets was already initialized from environment
    /// variables.
    AlreadyInitialized,

    /// The environment variables provided were for another PID than our own.
    NotForUs,

    /// The environment variables were not set.
    NotAvailable,

    /// The environment variables were malformed.
    Malformed,

    /// A provided file descsriptor was invalid.
    Unusable,
}

#[cfg(target_os = "linux")]
mod linux {
    use super::EnvSocketsError;
    use nix::fcntl::{FcntlArg, FdFlag, fcntl};
    use nix::sys::socket::{
        SockType, SockaddrStorage, getsockname, getsockopt,
    };
    use std::env::VarError;
    use std::net::{
        SocketAddr, SocketAddrV4, SocketAddrV6, TcpListener, UdpSocket,
    };
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};

    //-------- Constants -----------------------------------------------------

    /// The first file descriptor used by systemd.
    const SD_LISTEN_FDS_START: RawFd = 3;

    //-------- EnvSockets ----------------------------------------------------

    /// Accces to pre-bound sockets passed via environment variables.
    #[derive(Debug, Default)]
    pub struct EnvSockets {
        /// A flag indicating whether initialization from environment
        /// variables was already done or not.
        initialized: bool,

        /// An ordered collection of socket file descriptors along with their
        /// address and type.
        ///
        /// Preserves the order the sockets were provided to us.
        fds: Vec<SocketInfo>,
    }

    impl From<VarError> for EnvSocketsError {
        fn from(err: VarError) -> Self {
            match err {
                VarError::NotPresent => EnvSocketsError::NotAvailable,
                VarError::NotUnicode(_) => EnvSocketsError::Malformed,
            }
        }
    }

    impl From<nix::errno::Errno> for EnvSocketsError {
        fn from(_: nix::errno::Errno) -> Self {
            EnvSocketsError::Unusable
        }
    }

    impl EnvSockets {
        /// Create an empty instance.
        ///
        /// This is useful to have in case the call to
        /// [`Self::init_from_env()`] fails but you still want to use the
        /// [`EnvSockets`] instance as if [`Self::init_from_env()`] had
        /// succeeded.
        pub fn new() -> Self {
            Default::default()
        }

        /// Capture socket file descriptors from environment variables.
        ///
        /// Uses the following environment variables per [`sd_listen_fds()`]:
        /// - `LISTEN_PID`: Must match our own PID.
        /// - `LISTEN_FDS`: The number of FDs being passed to the application.
        ///
        /// The remaining FDs are numbered `SD_LISTEN_FDS_START
        /// + n` where `SD_LISTEN_FDS_START` is defined as `3` in
        /// `<systemd/sd-daemon.h>`.
        ///
        /// Only sockets of type `AF_INET` `UDP` and `AF_INET` `TCP`, whose
        /// address can be determined, will be captured by this function.
        /// Other socket file descriptors will be ignored.
        ///
        /// [`sd_listen_fds()`]: https://www.man7.org/linux/man-pages/man3/sd_listen_fds.3.html#NOTES
        pub fn init_from_env(
            &mut self,
            max_fds_to_process: Option<usize>,
        ) -> Result<(), EnvSocketsError> {
            if self.initialized {
                return Err(EnvSocketsError::AlreadyInitialized);
            }

            let own_pid = nix::unistd::Pid::this().as_raw().to_string();
            let var_pid = std::env::var("LISTEN_PID")?;

            log::debug!(
                "Checking systemd LISTEN_PID env var: our PID={own_pid}, \
                 LISTEN_PID={var_pid:?}"
            );

            if own_pid != var_pid {
                return Err(EnvSocketsError::NotForUs);
            }

            let var_fds = std::env::var("LISTEN_FDS")?;

            log::debug!(
                "Checking systemd LISTEN_FDS env var: \
                LISTEN_FDS={var_fds:?}"
            );
            let mut num_fds = var_fds
                .parse::<usize>()
                .map_err(|_| EnvSocketsError::Malformed)?;

            log::debug!(
                "Received {num_fds} socket file descriptors via the \
                 systemd LISTEN_FDS env var."
            );
            if let Some(max) = max_fds_to_process {
                num_fds = num_fds.clamp(0, max);
            }

            self.fds.reserve_exact(num_fds);

            // Here we do arithmetic with file descriptors, because
            // this is how the env var protocol for passing sockets is
            // defined as FDs are actually just integer values.
            for fd in
                SD_LISTEN_FDS_START..SD_LISTEN_FDS_START + (num_fds as RawFd)
            {
                let socket_info = SocketInfo::from_fd(fd)?;

                log::trace!(
                    "Received socket file descriptor {} via systemd \
                     LISTEN_FDS env var: type={}, address={}",
                    socket_info.fd.as_raw_fd(),
                    socket_info.socket_type,
                    socket_info.socket_addr
                );
                self.fds.push(socket_info);
            }

            Ok(())
        }

        /// Unset the `LISTEN_PID` and `LISTEN_FDS` environment variables.
        ///
        /// ## Safety
        ///
        /// This function is only safe to call in a single threaded context
        /// as it calls [`std::env::remove_var()`].
        pub fn clear_env() {
            log::trace!(
                "Unsetting systemd LISTEN_PID and LISTEN_FDS environment \
                variables."
            );
            unsafe {
                std::env::remove_var("LISTEN_PID");
                std::env::remove_var("LISTEN_FDS");
            }
        }

        /// Were socket descriptors passed to us via the environment?
        ///
        /// Returns false if not, true otherwise.
        pub fn is_empty(&self) -> bool {
            self.fds.is_empty()
        }

        /// Did the environment contain a UDP socket descriptor for
        /// the specified address?
        ///
        /// Returns true if so, false otherwise.
        pub fn has_udp(&self, addr: &SocketAddr) -> bool {
            self.fds.iter().any(|v| {
                v.socket_type == SocketType::Udp && v.socket_addr == *addr
            })
        }

        /// Did the environment contain a TCP socket descriptor for
        /// the specified local address?
        ///
        /// Returns true if so, false otherwise.
        pub fn has_tcp(&self, addr: &SocketAddr) -> bool {
            self.fds.iter().any(|v| {
                v.socket_type == SocketType::Tcp && v.socket_addr == *addr
            })
        }

        /// Returns a UDP socket that is bound to the specified local address,
        /// if it was supplied to us via the environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        ///
        /// Subsequent attempts to remove the same UDP socket, or any other
        /// non-existing socket, will return None.
        pub fn take_udp(
            &mut self,
            local_addr: &SocketAddr,
        ) -> Option<UdpSocket> {
            self.remove(SocketType::Udp, local_addr)
        }

        /// Returns the first remaining UDP socket from those received via the
        /// environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        pub fn pop_udp(&mut self) -> Option<UdpSocket> {
            self.pop(SocketType::Udp)
        }

        /// Returns a TCP listener that is bound to the specified local
        /// address, if it was supplied to us via the environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        ///
        /// Subsequent attempts to remove the same TCP socket, or any other
        /// non-existing socket, will return None.
        pub fn take_tcp(
            &mut self,
            local_addr: &SocketAddr,
        ) -> Option<TcpListener> {
            self.remove(SocketType::Tcp, local_addr)
        }

        /// Returns the first remaining TCP socket from those received via the
        /// environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        pub fn pop_tcp(&mut self) -> Option<TcpListener> {
            self.pop(SocketType::Tcp)
        }
    }

    //--- Private methods

    impl EnvSockets {
        /// Returns the socket with the specified type and addres, assuming it
        /// was supplied to us via the environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        ///
        /// Subsequent attempts to remove the same TCP socket, or any other
        /// non-existing socket, will return None.
        fn remove<T: std::fmt::Debug + From<OwnedFd>>(
            &mut self,
            ty: SocketType,
            addr: &SocketAddr,
        ) -> Option<T> {
            let res = self
                .fds
                .iter()
                .position(|v| v.socket_type == ty && v.socket_addr == *addr)
                .and_then(|idx| self.fds.remove(idx).finalize())?;
            log::trace!("EnvSockets::remove({ty}, {addr}) = {res:?}");
            Some(res)
        }

        /// Returns the first remaining socket of a given type from those
        /// received via the environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        fn pop<T: std::fmt::Debug + From<OwnedFd>>(
            &mut self,
            ty: SocketType,
        ) -> Option<T> {
            let res = self
                .fds
                .iter()
                .position(|v| v.socket_type == ty)
                .and_then(|idx| self.fds.remove(idx).finalize())?;
            log::trace!("daemonbase EnvSockets::pop({ty}) = {res:?}");
            Some(res)
        }
    }

    /// An internal data structure for storing information about sockets
    /// received via environment variables.
    #[derive(Debug)]
    struct SocketInfo {
        /// The type of socket.
        pub socket_type: SocketType,

        /// The address of the socket.
        pub socket_addr: SocketAddr,

        /// The underlying socket file descriptor.
        pub fd: OwnedFd,
    }

    impl SocketInfo {
        /// Creates a new [`SocketInfo`] instance.
        fn new(
            socket_type: SocketType,
            socket_addr: SocketAddr,
            fd: OwnedFd,
        ) -> Self {
            Self {
                socket_type,
                socket_addr,
                fd,
            }
        }

        /// Per [`sd_listen_fds()`] set the FD_CLOEXEC flag on the returned
        /// socket.
        ///
        /// Consumes self.
        ///
        /// Returns Some(T) if the FD_CLOEXEC flag could be set, None
        /// otherwise.
        fn finalize<T: From<OwnedFd>>(self) -> Option<T> {
            log::trace!(
                "Setting FD_CLOEXEC on systemd LISTEN_FDS received \
                 socket file descriptor {}",
                self.fd.as_raw_fd()
            );
            if let Err(err) =
                fcntl(&self.fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))
            {
                log::warn!(
                    "Setting FD_CLOEXEC on systemd LISTEN_FDS received \
                     socket file descriptor {} failed: {err}",
                    self.fd.as_raw_fd(),
                );
                return None;
            }
            Some(self.fd.into())
        }

        /// Wrap a socket file descriptor into a SocketInfo instance,
        /// if we support it.
        ///
        /// Supported file descriptors:
        ///   - Represent UDP or TCP sockets.
        ///   - Have an address.
        ///
        /// Returns Some(SocketInfo) on success, None otherwise.
        fn from_fd(fd: i32) -> Result<SocketInfo, nix::Error> {
            // If the fd is -1, converting it into an owned fd below will
            // panic. So let’s check already here.
            if fd == -1 {
                return Err(nix::Error::ENOTSOCK);
            }

            // [`getsockname()`]` will fail if the given argument is not "a
            // valid file descriptor" or does not "refer to a socket", so we
            // don't need to call fstat() to check that the FD is a socket,
            // we can let getsockname() take care of that for us.
            //
            // The conversion into a socket addr makes sure we only have an
            // IPv4 or an IPv6 socket.
            //
            // [`getsockname()`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsockname.html#tag_16_219_05
            let sock_addr =
                to_socket_addr(getsockname::<SockaddrStorage>(fd)?)?;

            // Safety: The conversion from a raw fd is safe if:
            //   - the fd is open and suitable for assuming ownership. The
            //     call to getsockname above should have failed if it isn’t.
            //   - the fd does not require any cleanup other than close.
            //     The call to getsockname above establishes that the fd is
            //     for a socket, so closing it is all that needs to be done.
            //   - the fd is not -1. We checked for that.
            let fd = unsafe { OwnedFd::from_raw_fd(fd) };

            let sock_opt =
                getsockopt(&fd, nix::sys::socket::sockopt::SockType)?;

            let socket_type = match sock_opt {
                SockType::Datagram => SocketType::Udp,
                SockType::Stream => SocketType::Tcp,
                _ => return Err(nix::Error::ENOTSOCK),
            };

            Ok(SocketInfo::new(socket_type, sock_addr, fd))
        }
    }

    /// The type of socket represented by a file descriptor.
    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
    pub enum SocketType {
        /// UDP.
        Udp,

        /// TCP.
        Tcp,
    }

    impl std::fmt::Display for SocketType {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                SocketType::Udp => write!(f, "UDP"),
                SocketType::Tcp => write!(f, "TCP"),
            }
        }
    }

    /// Convert a SockaddrStorage object into SocketAddr, if possible.
    fn to_socket_addr(
        sock_addr: SockaddrStorage,
    ) -> Result<SocketAddr, nix::Error> {
        if let Some(sock_addr) = sock_addr.as_sockaddr_in() {
            Ok(SocketAddrV4::new(sock_addr.ip(), sock_addr.port()).into())
        } else if let Some(sock_addr) = sock_addr.as_sockaddr_in6() {
            Ok(SocketAddrV6::new(
                sock_addr.ip(),
                sock_addr.port(),
                sock_addr.flowinfo(),
                sock_addr.scope_id(),
            )
            .into())
        } else {
            Err(nix::Error::ENOTSOCK)
        }
    }
}

//============ noop ==========================================================

/// ‘Empty’ implementation for systems we don’t really support.
///
#[cfg(not(unix))]
mod not_unix {
    use crate::config::{ConfigFile, ConfigPath};
    use crate::error::Failed;
    use serde::{Deserialize, Serialize};
    use std::path::{PathBuf, StripPrefixError};

    //-------- Process -------------------------------------------------------

    pub struct Process;

    impl Process {
        /// Creates the process from a config struct.
        pub fn from_config(config: Config) -> Self {
            let _ = config;
            Self
        }

        /// Adjusts a path for use after dropping privileges.
        ///
        /// Since [`drop_privileges`][Self::drop_privileges] may change the
        /// file system root, all absolute paths will need to be adjusted if
        /// they should be used after it is called.
        ///
        /// The method returns an error if the path is outside of what’s
        /// accessible to the process after dropping privileges.
        pub fn adjust_path(
            &self,
            path: PathBuf,
        ) -> Result<PathBuf, StripPrefixError> {
            Ok(path)
        }

        /// Sets up the process as a daemon.
        ///
        /// If `background` is `true`, the daemon will be set up to run in
        /// the background which may involve forking.
        ///
        /// After the method returns, we will be running in the final process
        /// but still have the same privileges we were initially started with.
        ///
        /// Because access to the standard streams may get lost during the
        /// method, it uses the logging facilities for any diagnostic output.
        /// You should therefore have set up your logging system prioir to
        /// calling this method.
        pub fn setup_daemon(
            &mut self,
            background: bool,
        ) -> Result<(), Failed> {
            let _ = background;
            Ok(())
        }

        /// Drops privileges.
        ///
        /// If requested via the config, this method will drop all potentially
        /// elevated privileges. This may include loosing root or system
        /// administrator permissions and change the file system root.
        pub fn drop_privileges(&mut self) -> Result<(), Failed> {
            Ok(())
        }
    }

    //-------- Config --------------------------------------------------------

    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
    pub struct Config;

    impl Config {
        /// Creates the proces from a config file.
        pub fn from_config_file(
            file: &mut ConfigFile,
        ) -> Result<Self, Failed> {
            let _ = file;
            Ok(Self)
        }

        /// Creates the process from command line arguments only.
        pub fn from_args(args: Args) -> Self {
            let _ = args;
            Self
        }

        /// Applies the arguments to the process.
        pub fn apply_args(&mut self, args: Args) {
            let _ = args;
        }

        pub fn with_pid_file(self, _: ConfigPath) -> Self {
            self
        }

        pub fn with_working_dir(self, _: ConfigPath) -> Self {
            self
        }

        pub fn with_chroot(self, _: ConfigPath) -> Self {
            self
        }

        pub fn with_user(self, _: &str) -> Result<Self, String> {
            Ok(self)
        }

        pub fn with_group(self, _: &str) -> Result<Self, String> {
            Ok(self)
        }
    }

    //-------- Args ----------------------------------------------------------

    #[derive(Clone, Debug, clap::Args)]
    #[group(id = "process-args")]
    pub struct Args;

    impl Args {
        pub fn into_config(&self) -> Config {
            Config
        }
    }

    //------------ exit_signalled --------------------------------------------

    /// Returns when an exit signal was received.
    ///
    /// This non-Unix implementation returns when the equivalent of a Ctrl+C is
    /// received.
    #[cfg(feature = "tokio")]
    pub async fn exit_signalled() -> Result<(), std::io::Error> {
        tokio::signal::ctrl_c().await
    }
}

#[cfg(not(target_os = "linux"))]
mod not_linux {
    use super::EnvSocketsError;
    use std::net::{SocketAddr, TcpListener, UdpSocket};

    //-------- EnvSockets ----------------------------------------------------

    /// Accces to pre-bound sockets passed via environment variables.
    #[derive(Debug, Default)]
    pub struct EnvSockets;

    impl EnvSockets {
        pub fn new() -> Self {
            Default::default()
        }

        /// Capture socket file descriptors from environment variables.
        pub fn init_from_env(
            &mut self,
            _max_fds_to_process: Option<usize>,
        ) -> Result<(), EnvSocketsError> {
            Ok(())
        }

        /// Were socket descriptors passed to us via the environment?
        ///
        /// Returns false if not, true otherwise.
        pub fn is_empty(&self) -> bool {
            true
        }

        /// Did the environment contain a UDP socket descriptor for
        /// the specified address?
        ///
        /// Returns true if so, false otherwise.
        pub fn has_udp(&self, _local_addr: &SocketAddr) -> bool {
            false
        }

        /// Did the environment contain a TCP socket descriptor for
        /// the specified address?
        ///
        /// Returns true if so, false otherwise.
        pub fn has_tcp(&self, _local_addr: &SocketAddr) -> bool {
            false
        }

        /// Returns a UDP socket that is bound to the specified local address,
        /// if it was supplied to us via the environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        ///
        /// Subsequent attempts to remove the same UDP socket, or any other
        /// non-existing socket, will return None.
        pub fn take_udp(&mut self, _addr: &SocketAddr) -> Option<UdpSocket> {
            None
        }

        /// Returns the first remaining UDP socket from those received via the
        /// environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        pub fn pop_udp(&mut self) -> Option<UdpSocket> {
            None
        }

        /// Returns a TCP listener that is bound to the specified local
        /// address, if it was supplied to us via the environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        ///
        /// Subsequent attempts to remove the same TCP socket, or any other
        /// non-existing socket, will return None.
        pub fn take_tcp(
            &mut self,
            _addr: &SocketAddr,
        ) -> Option<TcpListener> {
            None
        }

        /// Returns the first remaining TCP socket from those received via the
        /// environment.
        ///
        /// If found, removes the file descriptor from the collection, sets
        /// the FD_CLOEXEC flag on the file descriptor and returns it as the
        /// Rust type Some(UdpSocket).
        pub fn pop_tcp(&mut self) -> Option<TcpListener> {
            None
        }
    }
}