-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
daemon.c
87 lines (74 loc) · 1.44 KB
/
daemon.c
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
#include <stddef.h>
#include <signal.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include "daemon.h"
#include "globals.h"
#include "log.h"
static void signal_handler(int signal)
{
my_log(LOG_DAEMON | LOG_INFO, "Got signal %d, shutting down", signal);
globals.terminate = 1;
}
void set_signals(void)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
struct sigaction sa;
sa.sa_handler = signal_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, NULL);
#pragma clang diagnostic pop
}
#ifndef MINIMALISTIC_BUILD
static int find_account(uid_t* uid, gid_t* gid)
{
struct passwd* pwd;
pwd = getpwnam("nobody");
if (!pwd) {
pwd = getpwnam("daemon");
}
if (pwd) {
*uid = pwd->pw_uid;
*gid = pwd->pw_gid;
return 0;
}
return -1;
}
#endif
int drop_privs(struct globals_t* g)
{
#ifndef MINIMALISTIC_BUILD
if (0 == geteuid()) {
if (!g->uid_set || !g->gid_set) {
uid_t uid;
gid_t gid;
if (-1 == find_account(&uid, &gid)) {
return DP_NO_UNPRIV_ACCOUNT;
}
if (!g->uid_set) {
g->uid_set = 1;
g->uid = uid;
}
if (!g->gid_set) {
g->gid_set = 1;
g->gid = gid;
}
}
if (
setgroups(0, NULL)
|| setgid(g->gid)
|| setuid(g->uid)
) {
return DP_GENERAL_FAILURE;
}
}
#endif
return 0;
}