Making the webserver IPv6 capable.
[darkstat] / darkstat.c
1 /* darkstat 3
2 * copyright (c) 2001-2010 Emil Mikulic.
3 *
4 * darkstat.c: signals, cmdline parsing, program body.
5 *
6 * You may use, modify and redistribute this file under the terms of the
7 * GNU General Public License version 2. (see COPYING.GPL)
8 */
9
10 #include "darkstat.h"
11 #include "acct.h"
12 #include "cap.h"
13 #include "conv.h"
14 #include "daylog.h"
15 #include "db.h"
16 #include "dns.h"
17 #include "http.h"
18 #include "hosts_db.h"
19 #include "localip.h"
20 #include "ncache.h"
21 #include "pidfile.h"
22
23 #include "err.h"
24 #include <arpa/inet.h>
25 #include <netdb.h>
26 #include <assert.h>
27 #include <errno.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <syslog.h>
33 #include <unistd.h>
34 #include <pcap.h>
35
36 #include "now.h"
37 time_t now;
38
39 #ifndef INADDR_NONE
40 # define INADDR_NONE (-1) /* Solaris */
41 #endif
42
43 /* --- Signal handling --- */
44 static volatile int running = 1;
45 static void sig_shutdown(int signum _unused_) { running = 0; }
46
47 static volatile int reset_pending = 0;
48 static void sig_reset(int signum _unused_) { reset_pending = 1; }
49
50 /* --- Commandline parsing --- */
51 static unsigned long
52 parsenum(const char *str, unsigned long max /* 0 for no max */)
53 {
54 unsigned long n;
55 char *end;
56
57 errno = 0;
58 n = strtoul(str, &end, 10);
59 if (*end != '\0')
60 errx(1, "\"%s\" is not a valid number", str);
61 if (errno == ERANGE)
62 errx(1, "\"%s\" is out of range", str);
63 if ((max != 0) && (n > max))
64 errx(1, "\"%s\" is out of range (max %lu)", str, max);
65 return n;
66 }
67
68 const char *interface = NULL;
69 static void cb_interface(const char *arg) { interface = arg; }
70
71 const char *capfile = NULL;
72 static void cb_capfile(const char *arg) { capfile = arg; }
73
74 int want_snaplen = -1;
75 static void cb_snaplen(const char *arg) { want_snaplen = parsenum(arg, 0); }
76
77 int want_pppoe = 0;
78 static void cb_pppoe(const char *arg _unused_) { want_pppoe = 1; }
79
80 static void cb_syslog(const char *arg _unused_) { want_syslog = 1; }
81
82 static void cb_verbose(const char *arg _unused_) { want_verbose = 1; }
83
84 int want_daemonize = 1;
85 static void cb_no_daemon(const char *arg _unused_) { want_daemonize = 0; }
86
87 int want_promisc = 1;
88 static void cb_no_promisc(const char *arg _unused_) { want_promisc = 0; }
89
90 int want_dns = 1;
91 static void cb_no_dns(const char *arg _unused_) { want_dns = 0; }
92
93 int want_macs = 1;
94 static void cb_no_macs(const char *arg _unused_) { want_macs = 0; }
95
96 int want_lastseen = 1;
97 static void cb_no_lastseen(const char *arg _unused_) { want_lastseen = 0; }
98
99 unsigned short bindport = 667;
100 static void cb_port(const char *arg) { bindport = parsenum(arg, 65536); }
101
102 char * bindaddr = NULL;
103 static void cb_bindaddr(const char *arg)
104 {
105 struct addrinfo hints, *ai;
106
107 memset(&hints, '\0', sizeof(hints));
108 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
109 hints.ai_family = AF_UNSPEC;
110 hints.ai_socktype = SOCK_STREAM;
111
112 if (getaddrinfo(arg, NULL, &hints, &ai))
113 errx(1, "malformed address \"%s\"", arg);
114
115 freeaddrinfo(ai);
116 bindaddr = strdup(arg);
117 }
118
119 const char *filter = NULL;
120 static void cb_filter(const char *arg) { filter = arg; }
121
122 static void cb_local(const char *arg) { acct_init_localnet(arg); }
123
124 const char *chroot_dir = NULL;
125 static void cb_chroot(const char *arg) { chroot_dir = arg; }
126
127 const char *privdrop_user = NULL;
128 static void cb_user(const char *arg) { privdrop_user = arg; }
129
130 const char *daylog_fn = NULL;
131 static void cb_daylog(const char *arg)
132 {
133 if (chroot_dir == NULL)
134 errx(1, "the daylog file is relative to the chroot.\n"
135 "You must specify a --chroot dir before you can use --daylog.");
136 else
137 daylog_fn = arg;
138 }
139
140 const char *import_fn = NULL;
141 static void cb_import(const char *arg)
142 {
143 if (chroot_dir == NULL)
144 errx(1, "the import file is relative to the chroot.\n"
145 "You must specify a --chroot dir before you can use --import.");
146 else
147 import_fn = arg;
148 }
149
150 const char *export_fn = NULL;
151 static void cb_export(const char *arg)
152 {
153 if ((chroot_dir == NULL) && (capfile == NULL))
154 errx(1, "the export file is relative to the chroot.\n"
155 "You must specify a --chroot dir before you can use --export.");
156 else
157 export_fn = arg;
158 }
159
160 static const char *pid_fn = NULL;
161 static void cb_pidfile(const char *arg)
162 {
163 if (chroot_dir == NULL)
164 errx(1, "the pidfile is relative to the chroot.\n"
165 "You must specify a --chroot dir before you can use --pidfile.");
166 else
167 pid_fn = arg;
168 }
169
170 unsigned int hosts_max = 1000;
171 static void cb_hosts_max(const char *arg)
172 { hosts_max = parsenum(arg, 0); }
173
174 unsigned int hosts_keep = 500;
175 static void cb_hosts_keep(const char *arg)
176 { hosts_keep = parsenum(arg, 0); }
177
178 unsigned int ports_max = 200;
179 static void cb_ports_max(const char *arg)
180 { ports_max = parsenum(arg, 65536); }
181
182 unsigned int ports_keep = 30;
183 static void cb_ports_keep(const char *arg)
184 { ports_keep = parsenum(arg, 65536); }
185
186 unsigned int highest_port = 65535;
187 static void cb_highest_port(const char *arg)
188 { highest_port = parsenum(arg, 65535); }
189
190 int wait_secs = -1;
191 static void cb_wait_secs(const char *arg)
192 { wait_secs = parsenum(arg, 0); }
193
194 int want_hexdump = 0;
195 static void cb_hexdump(const char *arg _unused_) { want_hexdump = 1; }
196
197 /* --- */
198
199 struct cmdline_arg {
200 const char *name, *arg_name; /* NULL arg_name means unary */
201 void (*callback)(const char *arg);
202 int num_seen;
203 };
204
205 static struct cmdline_arg cmdline_args[] = {
206 {"-i", "interface", cb_interface, 0},
207 {"-r", "file", cb_capfile, 0},
208 {"--snaplen", "bytes", cb_snaplen, 0},
209 {"--pppoe", NULL, cb_pppoe, 0},
210 {"--syslog", NULL, cb_syslog, 0},
211 {"--verbose", NULL, cb_verbose, 0},
212 {"--no-daemon", NULL, cb_no_daemon, 0},
213 {"--no-promisc", NULL, cb_no_promisc, 0},
214 {"--no-dns", NULL, cb_no_dns, 0},
215 {"--no-macs", NULL, cb_no_macs, 0},
216 {"--no-lastseen", NULL, cb_no_lastseen, 0},
217 {"-p", "port", cb_port, 0},
218 {"-b", "bindaddr", cb_bindaddr, 0},
219 {"-f", "filter", cb_filter, 0},
220 {"-l", "network/netmask", cb_local, 0},
221 {"--chroot", "dir", cb_chroot, 0},
222 {"--user", "username", cb_user, 0},
223 {"--daylog", "filename", cb_daylog, 0},
224 {"--import", "filename", cb_import, 0},
225 {"--export", "filename", cb_export, 0},
226 {"--pidfile", "filename", cb_pidfile, 0},
227 {"--hosts-max", "count", cb_hosts_max, 0},
228 {"--hosts-keep", "count", cb_hosts_keep, 0},
229 {"--ports-max", "count", cb_ports_max, 0},
230 {"--ports-keep", "count", cb_ports_keep, 0},
231 {"--highest-port", "port", cb_highest_port, 0},
232 {"--wait", "secs", cb_wait_secs, 0},
233 {"--hexdump", NULL, cb_hexdump, 0},
234 {NULL, NULL, NULL, 0}
235 };
236
237 static void
238 pad(const int width)
239 {
240 int i;
241 for (i=0; i<width; i++) printf(" ");
242 }
243
244 /*
245 * We autogenerate the usage statement from the cmdline_args data structure.
246 */
247 static void
248 usage(void)
249 {
250 int width, first;
251 struct cmdline_arg *arg;
252
253 printf(PACKAGE_STRING " (built with libpcap %d.%d)\n\n",
254 PCAP_VERSION_MAJOR, PCAP_VERSION_MINOR);
255
256 width = printf("usage: darkstat ");
257 first = 1;
258
259 for (arg = cmdline_args; arg->name != NULL; arg++) {
260 if (first) first = 0; else pad(width);
261 printf("[ %s", arg->name);
262 if (arg->arg_name != NULL) printf(" %s", arg->arg_name);
263 printf(" ]\n");
264 }
265 printf("\n"
266 "Please refer to the darkstat(8) manual page for further\n"
267 "documentation and usage examples.\n");
268 }
269
270 static void
271 parse_sub_cmdline(const int argc, char * const *argv)
272 {
273 struct cmdline_arg *arg;
274
275 if (argc == 0) return;
276 for (arg = cmdline_args; arg->name != NULL; arg++)
277 if (strcmp(argv[0], arg->name) == 0) {
278 if ((arg->arg_name != NULL) && (argc == 1)) {
279 fprintf(stderr,
280 "error: argument \"%s\" requires parameter \"%s\"\n",
281 arg->name, arg->arg_name);
282 usage();
283 exit(EXIT_FAILURE);
284 }
285 if (arg->num_seen > 0) {
286 fprintf(stderr,
287 "error: already specified argument \"%s\"\n",
288 arg->name);
289 usage();
290 exit(EXIT_FAILURE);
291 }
292
293 arg->num_seen++;
294 if (arg->arg_name == NULL) {
295 arg->callback(NULL);
296 parse_sub_cmdline(argc-1, argv+1);
297 } else {
298 arg->callback(argv[1]);
299 parse_sub_cmdline(argc-2, argv+2);
300 }
301 return;
302 }
303
304 fprintf(stderr, "error: illegal argument: \"%s\"\n", argv[0]);
305 usage();
306 exit(EXIT_FAILURE);
307 }
308
309 static void
310 parse_cmdline(const int argc, char * const *argv)
311 {
312 if (argc < 1) {
313 /* Not enough args. */
314 usage();
315 exit(EXIT_FAILURE);
316 }
317
318 parse_sub_cmdline(argc, argv);
319
320 /* start syslogging as early as possible */
321 if (want_syslog) openlog("darkstat", LOG_NDELAY | LOG_PID, LOG_DAEMON);
322
323 /* some default values */
324 if (chroot_dir == NULL) chroot_dir = CHROOT_DIR;
325 if (privdrop_user == NULL) privdrop_user = PRIVDROP_USER;
326
327 /* sanity check args */
328 if ((interface == NULL) && (capfile == NULL))
329 errx(1, "must specify either interface (-i) or capture file (-r)");
330
331 if ((interface != NULL) && (capfile != NULL))
332 errx(1, "can't specify both interface (-i) and capture file (-r)");
333
334 if ((hosts_max != 0) && (hosts_keep >= hosts_max)) {
335 hosts_keep = hosts_max / 2;
336 warnx("reducing --hosts-keep to %u, to be under --hosts-max (%u)",
337 hosts_keep, hosts_max);
338 }
339 verbosef("max %u hosts, cutting down to %u when exceeded",
340 hosts_max, hosts_keep);
341
342 if ((ports_max != 0) && (ports_keep >= ports_max)) {
343 ports_keep = ports_max / 2;
344 warnx("reducing --ports-keep to %u, to be under --ports-max (%u)",
345 ports_keep, ports_max);
346 }
347 verbosef("max %u ports per host, cutting down to %u when exceeded",
348 ports_max, ports_keep);
349
350 if (want_hexdump && !want_verbose) {
351 want_verbose = 1;
352 verbosef("--hexdump implies --verbose");
353 }
354
355 if (want_hexdump && want_daemonize) {
356 want_daemonize = 0;
357 verbosef("--hexdump implies --no-daemon");
358 }
359 }
360
361 static void
362 run_from_capfile(void)
363 {
364 graph_init();
365 hosts_db_init();
366 cap_from_file(capfile, filter);
367 cap_stop();
368 if (export_fn != NULL) db_export(export_fn);
369 hosts_db_free();
370 graph_free();
371 verbosef("Total packets: %qu, bytes: %qu", total_packets, total_bytes);
372 }
373
374 /* --- Program body --- */
375 int
376 main(int argc, char **argv)
377 {
378 test_64order();
379 parse_cmdline(argc-1, argv+1);
380
381 if (capfile) {
382 /*
383 * This is very different from a regular run against a network
384 * interface.
385 */
386 run_from_capfile();
387 return 0;
388 }
389
390 /* must verbosef() before first fork to init lock */
391 verbosef("starting up");
392 if (pid_fn) pidfile_create(chroot_dir, pid_fn, privdrop_user);
393
394 if (want_daemonize) {
395 verbosef("daemonizing to run in the background!");
396 daemonize_start();
397 verbosef("I am the main process");
398 }
399 if (pid_fn) pidfile_write_close();
400
401 /* do this first as it forks - minimize memory use */
402 if (want_dns) dns_init(privdrop_user);
403 cap_init(interface, filter, want_promisc); /* needs root */
404 http_init(bindaddr, bindport, /*maxconn=*/ -1); /* low ports need root */
405 ncache_init(); /* must do before chroot() */
406
407 privdrop(chroot_dir, privdrop_user);
408
409 /* Don't need root privs for these: */
410 now = time(NULL);
411 if (daylog_fn != NULL) daylog_init(daylog_fn);
412 graph_init();
413 hosts_db_init();
414 if (import_fn != NULL) db_import(import_fn);
415 localip_init(interface);
416
417 if (signal(SIGTERM, sig_shutdown) == SIG_ERR)
418 errx(1, "signal(SIGTERM) failed");
419 if (signal(SIGINT, sig_shutdown) == SIG_ERR)
420 errx(1, "signal(SIGINT) failed");
421 if (signal(SIGUSR1, sig_reset) == SIG_ERR)
422 errx(1, "signal(SIGUSR1) failed");
423
424 verbosef("entering main loop");
425 daemonize_finish();
426
427 while (running) {
428 int select_ret, max_fd = -1, use_timeout = 0;
429 struct timeval timeout;
430 fd_set rs, ws;
431
432 now = time(NULL);
433
434 if (reset_pending) {
435 if (export_fn != NULL) db_export(export_fn); /* FIXME: USR2? */
436 hosts_db_reset();
437 graph_reset();
438 reset_pending = 0;
439 }
440
441 FD_ZERO(&rs);
442 FD_ZERO(&ws);
443
444 cap_fd_set(&rs, &max_fd, &timeout, &use_timeout);
445 http_fd_set(&rs, &ws, &max_fd, &timeout, &use_timeout);
446
447 select_ret = select(max_fd+1, &rs, &ws, NULL,
448 (use_timeout) ? &timeout : NULL);
449
450 if ((select_ret == 0) && (!use_timeout))
451 errx(1, "select() erroneously timed out");
452
453 if (select_ret == -1) {
454 if (errno == EINTR)
455 continue;
456 else
457 err(1, "select()");
458 }
459 else {
460 graph_rotate();
461 cap_poll(&rs);
462 dns_poll();
463 http_poll(&rs, &ws);
464 }
465 }
466
467 verbosef("shutting down");
468 verbosef("pcap stats: %u packets received, %u packets dropped",
469 pkts_recv, pkts_drop);
470 cap_stop();
471 dns_stop();
472 if (export_fn != NULL) db_export(export_fn);
473 hosts_db_free();
474 graph_free();
475 if (daylog_fn != NULL) daylog_free();
476 ncache_free();
477 if (pid_fn) pidfile_unlink();
478 verbosef("shut down");
479 return (EXIT_SUCCESS);
480 }
481
482 /* vim:set ts=3 sw=3 tw=78 expandtab: */