forked from rzalamena/serverstatd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverstatd.c
361 lines (296 loc) · 8.15 KB
/
serverstatd.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
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
/*
* Copyright (c) 2016 Rafael Zalamena <rzalamena@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifdef LINUX_SUPPORT
/* Needed by setresgid() and setresuid() */
#define _GNU_SOURCE
#endif /* LINUX_SUPPORT */
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <err.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <grp.h>
#ifdef MACOSX_SUPPORT
#include <uuid/uuid.h>
#endif /* MACOSX_SUPPORT */
#include "serverstatd.h"
/* Global configuration structure shared between children. */
struct serverstatd_conf sc;
/* Child worker process declaration */
struct proc_ctx pcs[1] = {
{
.pc_name = "icmp probe",
.pc_func = icmp_handler,
.pc_pid = 0,
.pc_sp = { -1, -1 },
.pc_ev = NULL,
.pc_evout = NULL,
},
};
/* Main process signal handlers */
static void
main_term_handler(evutil_socket_t s, short ev, void *bula)
{
int n;
pid_t pid;
log_info("%s: received signal %d", __FUNCTION__, s);
for (n = 0; n < NOF(sizeof(pcs), sizeof(pcs[0])); n++) {
if (pcs[n].pc_pid == 0)
continue;
kill(pcs[n].pc_pid, SIGTERM);
}
do {
if ((pid = wait(NULL)) == -1 &&
errno != EINTR && errno != ECHILD)
fatal("wait");
} while (pid != -1 || (pid == -1 && errno == EINTR));
exit(0);
}
static void
main_hup_handler(evutil_socket_t s, short ev, void *bula)
{
log_info("%s: received signal %s", __FUNCTION__, s);
}
/* Main process dispatcher */
static void
main_dispatcher(evutil_socket_t sd, short ev, void *arg)
{
struct proc_ctx *pc = arg;
struct icmp_host *ih;
struct imsg imsg;
int n;
int sraw;
if (imsg_read(&pc->pc_ibuf) == -1 && errno != EAGAIN)
fatal("%s: imsg_read", __FUNCTION__);
while (1) {
if ((n = imsg_get(&pc->pc_ibuf, &imsg)) == -1)
break;
if (n == 0)
break;
switch (imsg.hdr.type) {
case IMSG_SOCKET_RAW:
log_debug("%s: new icmp socket", __FUNCTION__);
sraw = icmp_socket();
compose_to_child(&pcs[0], IMSG_SOCKET_RAW, sraw, NULL, 0);
break;
case IMSG_HOST_UP:
ih = imsg.data;
log_icmp_host_event(ih, IHS_UP);
break;
case IMSG_HOST_DOWN:
ih = imsg.data;
log_icmp_host_event(ih, IHS_DOWN);
break;
default:
log_debug("unhandled message type: %#08x",
imsg.hdr.type);
break;
}
}
}
/* Generic message sender dispatcher. */
static void
send_dispatcher(evutil_socket_t sd, short ev, void *arg)
{
struct proc_ctx *pc = arg;
if (imsg_flush(&pc->pc_ibuf) == -1)
log_warn("%s: imsg_flush", __FUNCTION__);
/* Reschedule if there is more writes pending. */
if (pc->pc_ibuf.w.queued)
event_add(pc->pc_evout, NULL);
}
/* Send a message from father to child. */
int
compose_to_child(struct proc_ctx *pc, uint32_t type, int fd, const void *data,
uint16_t datalen)
{
if (imsg_compose(&pc->pc_ibuf, type, 0, 0, fd, data, datalen) != 1)
return (-1);
event_add(pc->pc_evout, NULL);
return (0);
}
/* Send message from child to father. */
int
compose_to_father(struct proc_ctx *pc, uint32_t type, const void *data,
uint16_t datalen)
{
if (imsg_compose(&pc->pc_ibuf, type, 0, 0, -1, data, datalen) != 1)
return (-1);
event_add(pc->pc_evout, NULL);
return (0);
}
/* Initialize the pipe with a handler. */
void
pc_add(struct event_base *eb, struct proc_ctx *pc, int fd, event_callback_fn func)
{
pc->pc_eb = eb;
/* Attach read handler. */
pc->pc_ev = event_new(eb, fd, EV_READ | EV_PERSIST, func, pc);
event_add(pc->pc_ev, NULL);
/* Attach write handler. */
pc->pc_evout = event_new(eb, fd, EV_WRITE, send_dispatcher, pc);
/* Initiate imsg API. */
imsg_init(&pc->pc_ibuf, fd);
}
/* Generic function to spawn child processes. */
static int
launch_proc(struct proc_ctx *pc)
{
struct passwd *pw;
pid_t pid;
#ifdef MACOSX_SUPPORT
if (socketpair(PF_LOCAL, SOCK_STREAM, AF_UNSPEC, pc->pc_sp) == -1 ||
evutil_make_socket_closeonexec(pc->pc_sp[0]) == -1 ||
evutil_make_socket_closeonexec(pc->pc_sp[1]) == -1 ||
evutil_make_socket_nonblocking(pc->pc_sp[0]) == -1 ||
evutil_make_socket_nonblocking(pc->pc_sp[1]) == -1)
#else
if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC,
AF_UNSPEC, pc->pc_sp) == -1)
#endif /* MACOSX_SUPPORT */
fatal("%s: socketpair", pc->pc_name);
switch ((pid = fork())) {
case 0:
break;
case -1:
log_warn("Failed to spawn %s", pc->pc_name);
default:
close(pc->pc_sp[1]);
pc->pc_sp[1] = -1;
return (pc->pc_pid = pid);
}
close(pc->pc_sp[0]);
pc->pc_sp[0] = -1;
/* Load user details to drop privileges. */
if ((pw = getpwnam(sc.sc_user)) == NULL)
fatal("failed to get user");
/* Use user home as chroot, otherwise use definition. */
if (sc.sc_chroot[0] == 0) {
if (chroot(pw->pw_dir) != 0)
fatal("chroot");
} else {
if (chroot(sc.sc_chroot) != 0)
fatal("chroot");
}
/* Drop privileges. */
if (setgroups(1, &pw->pw_gid) ||
setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
fatal("failed to drop privileges");
pc->pc_func(pc);
_exit(0);
}
/* Initialize database, create tables and fill first infos. */
static void
db_initialize(void)
{
struct icmp_host *ih;
db_init(":memory:");
db_execute(" \
CREATE TABLE IF NOT EXISTS icmp_hosts ( \
id INTEGER PRIMARY KEY AUTOINCREMENT, \
name TEXT UNIQUE, \
address TEXT \
);");
db_execute("CREATE UNIQUE INDEX IF NOT EXISTS icmp_host_names ON icmp_hosts(name);");
db_execute(" \
CREATE TABLE IF NOT EXISTS icmp_host_events ( \
id INTEGER PRIMARY KEY AUTOINCREMENT, \
icmp_host_id INTEGER, \
event INTEGER);"
);
TAILQ_FOREACH(ih, &sc.sc_ihlist, ih_entry)
register_icmp_host(ih);
}
static void
usage(void)
{
extern const char *__progname;
fprintf(stderr, "%s: [-dfv]\n",
__progname);
exit(1);
}
int
main(int argc, char *argv[])
{
char *cfgfile = "/tmp/serverstatd.conf";
int foreground = 0;
int verbose = 0;
int c;
struct event_base *eb;
struct event *evsig_hup, *evsig_term, *evsig_int, *evsig_chld;
while ((c = getopt(argc, argv, "df:v")) != -1) {
switch (c) {
case 'd':
foreground = 1;
break;
case 'v':
verbose = 1;
break;
case 'f':
cfgfile = strdup(optarg);
break;
default:
usage();
/* NOTREACHED */
}
}
/* Check for root privileges. */
if (geteuid())
errx(1, "need root privileges");
/* Initialize log operation. */
log_init(foreground);
log_verbose(verbose);
/* Deal with configuration files. */
if (parse_config(cfgfile, &sc) != 0)
errx(1, "failed to read configuration");
/* Check the chroot dir. */
if (access(sc.sc_chroot, F_OK) != 0)
err(1, "could not open chroot directory");
/* Check for serverstatd user. */
if (getpwnam(sc.sc_user) == NULL)
errx(1, "unknown user %s", sc.sc_user);
#ifndef MACOSX_SUPPORT
if (foreground == 0)
if (daemon(1, 0) != 0)
fatal("daemonize");
#endif /* MACOSX_SUPPORT */
/* Launch children processes. */
launch_proc(&pcs[0]);
/* Register all events then go to main loop. */
eb = event_base_new();
signal(SIGPIPE, SIG_IGN);
evsig_chld = evsignal_new(eb, SIGCHLD, main_term_handler, NULL);
evsig_term = evsignal_new(eb, SIGTERM, main_term_handler, NULL);
evsig_int = evsignal_new(eb, SIGINT, main_term_handler, NULL);
evsig_hup = evsignal_new(eb, SIGHUP, main_hup_handler, NULL);
evsignal_add(evsig_chld, NULL);
evsignal_add(evsig_term, NULL);
evsignal_add(evsig_int, NULL);
evsignal_add(evsig_hup, NULL);
pc_add(eb, &pcs[0], pcs[0].pc_sp[0], main_dispatcher);
db_initialize();
log_info("started");
event_base_dispatch(eb);
/* NOTREACHED */
event_base_free(eb);
return (0);
}