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