Imported Upstream version 3.0.715
[darkstat-debian] / darkstat.c
1 /* darkstat 3
2 * copyright (c) 2001-2011 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 "acct.h"
11 #include "cap.h"
12 #include "cdefs.h"
13 #include "config.h"
14 #include "conv.h"
15 #include "daylog.h"
16 #include "db.h"
17 #include "dns.h"
18 #include "err.h"
19 #include "http.h"
20 #include "hosts_db.h"
21 #include "localip.h"
22 #include "ncache.h"
23 #include "pidfile.h"
24
25 #include <assert.h>
26 #include <errno.h>
27 #include <inttypes.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, export_pending = 0;
48 static void sig_reset(int signum _unused_)
49 {
50 reset_pending = 1;
51 export_pending = 1;
52 }
53
54 static void sig_export(int signum _unused_) { export_pending = 1; }
55
56 /* --- Commandline parsing --- */
57 static unsigned long
58 parsenum(const char *str, unsigned long max /* 0 for no max */)
59 {
60 unsigned long n;
61 char *end;
62
63 errno = 0;
64 n = strtoul(str, &end, 10);
65 if (*end != '\0')
66 errx(1, "\"%s\" is not a valid number", str);
67 if (errno == ERANGE)
68 errx(1, "\"%s\" is out of range", str);
69 if ((max != 0) && (n > max))
70 errx(1, "\"%s\" is out of range (max %lu)", str, max);
71 return n;
72 }
73
74 const char *opt_interface = NULL;
75 static void cb_interface(const char *arg) { opt_interface = arg; }
76
77 const char *opt_capfile = NULL;
78 static void cb_capfile(const char *arg) { opt_capfile = arg; }
79
80 int opt_want_snaplen = -1;
81 static void cb_snaplen(const char *arg)
82 { opt_want_snaplen = (int)parsenum(arg, 0); }
83
84 int opt_want_pppoe = 0;
85 static void cb_pppoe(const char *arg _unused_) { opt_want_pppoe = 1; }
86
87 int opt_want_syslog = 0;
88 static void cb_syslog(const char *arg _unused_) { opt_want_syslog = 1; }
89
90 int opt_want_verbose = 0;
91 static void cb_verbose(const char *arg _unused_) { opt_want_verbose = 1; }
92
93 int opt_want_daemonize = 1;
94 static void cb_no_daemon(const char *arg _unused_) { opt_want_daemonize = 0; }
95
96 int opt_want_promisc = 1;
97 static void cb_no_promisc(const char *arg _unused_) { opt_want_promisc = 0; }
98
99 int opt_want_dns = 1;
100 static void cb_no_dns(const char *arg _unused_) { opt_want_dns = 0; }
101
102 int opt_want_macs = 1;
103 static void cb_no_macs(const char *arg _unused_) { opt_want_macs = 0; }
104
105 int opt_want_lastseen = 1;
106 static void cb_no_lastseen(const char *arg _unused_) { opt_want_lastseen = 0; }
107
108 unsigned short opt_bindport = 667;
109 static void cb_port(const char *arg)
110 { opt_bindport = (unsigned short)parsenum(arg, 65536); }
111
112 static void cb_bindaddr(const char *arg) { http_add_bindaddr(arg); }
113
114 const char *opt_filter = NULL;
115 static void cb_filter(const char *arg) { opt_filter = arg; }
116
117 static int is_localnet_specified = 0;
118 static void cb_local(const char *arg)
119 {
120 acct_init_localnet(arg);
121 is_localnet_specified = 1;
122 }
123
124 int opt_want_local_only = 0;
125 static void cb_local_only(const char *arg _unused_)
126 { opt_want_local_only = 1; }
127
128 const char *opt_chroot_dir = NULL;
129 static void cb_chroot(const char *arg) { opt_chroot_dir = arg; }
130
131 const char *opt_privdrop_user = NULL;
132 static void cb_user(const char *arg) { opt_privdrop_user = arg; }
133
134 const char *daylog_fn = NULL;
135 static void cb_daylog(const char *arg)
136 {
137 if (opt_chroot_dir == NULL)
138 errx(1, "the daylog file is relative to the chroot.\n"
139 "You must specify a --chroot dir before you can use --daylog.");
140 else
141 daylog_fn = arg;
142 }
143
144 const char *import_fn = NULL;
145 static void cb_import(const char *arg)
146 {
147 if (opt_chroot_dir == NULL)
148 errx(1, "the import file is relative to the chroot.\n"
149 "You must specify a --chroot dir before you can use --import.");
150 else
151 import_fn = arg;
152 }
153
154 const char *export_fn = NULL;
155 static void cb_export(const char *arg)
156 {
157 if ((opt_chroot_dir == NULL) && (opt_capfile == NULL))
158 errx(1, "the export file is relative to the chroot.\n"
159 "You must specify a --chroot dir before you can use --export.");
160 else
161 export_fn = arg;
162 }
163
164 static const char *pid_fn = NULL;
165 static void cb_pidfile(const char *arg)
166 {
167 if (opt_chroot_dir == NULL)
168 errx(1, "the pidfile is relative to the chroot.\n"
169 "You must specify a --chroot dir before you can use --pidfile.");
170 else
171 pid_fn = arg;
172 }
173
174 unsigned int opt_hosts_max = 1000;
175 static void cb_hosts_max(const char *arg)
176 { opt_hosts_max = parsenum(arg, 0); }
177
178 unsigned int opt_hosts_keep = 500;
179 static void cb_hosts_keep(const char *arg)
180 { opt_hosts_keep = parsenum(arg, 0); }
181
182 unsigned int opt_ports_max = 200;
183 static void cb_ports_max(const char *arg)
184 { opt_ports_max = parsenum(arg, 65536); }
185
186 unsigned int opt_ports_keep = 30;
187 static void cb_ports_keep(const char *arg)
188 { opt_ports_keep = parsenum(arg, 65536); }
189
190 unsigned int opt_highest_port = 65535;
191 static void cb_highest_port(const char *arg)
192 { opt_highest_port = parsenum(arg, 65535); }
193
194 int opt_wait_secs = -1;
195 static void cb_wait_secs(const char *arg)
196 { opt_wait_secs = (int)parsenum(arg, 0); }
197
198 int opt_want_hexdump = 0;
199 static void cb_hexdump(const char *arg _unused_)
200 { opt_want_hexdump = 1; }
201
202 int opt_want_help = 0;
203 static void cb_help(const char *arg _unused_)
204 { opt_want_help = 1; }
205 static void cb_version(const char *arg _unused_)
206 { opt_want_help = -1; }
207
208 /* --- */
209
210 struct cmdline_arg {
211 const char *name, *arg_name; /* NULL arg_name means unary */
212 void (*callback)(const char *arg);
213 int num_seen;
214 };
215
216 static struct cmdline_arg cmdline_args[] = {
217 {"-i", "interface", cb_interface, 0},
218 {"-r", "file", cb_capfile, 0},
219 {"-p", "port", cb_port, 0},
220 {"-b", "bindaddr", cb_bindaddr, -1},
221 {"-f", "filter", cb_filter, 0},
222 {"-l", "network/netmask", cb_local, 0},
223 {"--local-only", NULL, cb_local_only, 0},
224 {"--snaplen", "bytes", cb_snaplen, 0},
225 {"--pppoe", NULL, cb_pppoe, 0},
226 {"--syslog", NULL, cb_syslog, 0},
227 {"--verbose", NULL, cb_verbose, 0},
228 {"--no-daemon", NULL, cb_no_daemon, 0},
229 {"--no-promisc", NULL, cb_no_promisc, 0},
230 {"--no-dns", NULL, cb_no_dns, 0},
231 {"--no-macs", NULL, cb_no_macs, 0},
232 {"--no-lastseen", NULL, cb_no_lastseen, 0},
233 {"--chroot", "dir", cb_chroot, 0},
234 {"--user", "username", cb_user, 0},
235 {"--daylog", "filename", cb_daylog, 0},
236 {"--import", "filename", cb_import, 0},
237 {"--export", "filename", cb_export, 0},
238 {"--pidfile", "filename", cb_pidfile, 0},
239 {"--hosts-max", "count", cb_hosts_max, 0},
240 {"--hosts-keep", "count", cb_hosts_keep, 0},
241 {"--ports-max", "count", cb_ports_max, 0},
242 {"--ports-keep", "count", cb_ports_keep, 0},
243 {"--highest-port", "port", cb_highest_port, 0},
244 {"--wait", "secs", cb_wait_secs, 0},
245 {"--hexdump", NULL, cb_hexdump, 0},
246 {"--version", NULL, cb_version, 0},
247 {"--help", NULL, cb_help, 0},
248 {NULL, NULL, NULL, 0}
249 };
250
251 /*
252 * We autogenerate the usage statement from the cmdline_args data structure.
253 */
254 static void
255 usage(void)
256 {
257 static char intro[] = "usage: darkstat ";
258 char indent[sizeof(intro)];
259 struct cmdline_arg *arg;
260
261 printf(PACKAGE_STRING " (using %s)\n", pcap_lib_version());
262 if (opt_want_help == -1) return;
263
264 memset(indent, ' ', sizeof(indent));
265 indent[0] = indent[sizeof(indent) - 1] = 0;
266
267 printf("\n%s", intro);
268 for (arg = cmdline_args; arg->name != NULL; arg++) {
269 printf("%s[ %s%s%s ]\n",
270 indent,
271 arg->name,
272 arg->arg_name != NULL ? " " : "",
273 arg->arg_name != NULL ? arg->arg_name : "");
274 indent[0] = ' ';
275 }
276 printf("\n"
277 "Please refer to the darkstat(8) manual page for further\n"
278 "documentation and usage examples.\n");
279 }
280
281 static void
282 parse_sub_cmdline(const int argc, char * const *argv)
283 {
284 struct cmdline_arg *arg;
285
286 if (argc == 0) return;
287 for (arg = cmdline_args; arg->name != NULL; arg++)
288 if (strcmp(argv[0], arg->name) == 0) {
289 if ((arg->arg_name != NULL) && (argc == 1)) {
290 fprintf(stderr,
291 "error: argument \"%s\" requires parameter \"%s\"\n",
292 arg->name, arg->arg_name);
293 usage();
294 exit(EXIT_FAILURE);
295 }
296 if (arg->num_seen > 0) {
297 fprintf(stderr,
298 "error: already specified argument \"%s\"\n",
299 arg->name);
300 usage();
301 exit(EXIT_FAILURE);
302 }
303
304 if (arg->num_seen != -1) /* accept more than one */
305 arg->num_seen++;
306
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 if (opt_want_help) {
334 usage();
335 exit(EXIT_SUCCESS);
336 }
337
338 /* start syslogging as early as possible */
339 if (opt_want_syslog) openlog("darkstat", LOG_NDELAY | LOG_PID, LOG_DAEMON);
340
341 /* some default values */
342 if (opt_chroot_dir == NULL) opt_chroot_dir = CHROOT_DIR;
343 if (opt_privdrop_user == NULL) opt_privdrop_user = PRIVDROP_USER;
344
345 /* sanity check args */
346 if ((opt_interface == NULL) && (opt_capfile == NULL))
347 errx(1, "must specify either interface (-i) or capture file (-r)");
348
349 if ((opt_interface != NULL) && (opt_capfile != NULL))
350 errx(1, "can't specify both interface (-i) and capture file (-r)");
351
352 if ((opt_hosts_max != 0) && (opt_hosts_keep >= opt_hosts_max)) {
353 opt_hosts_keep = opt_hosts_max / 2;
354 warnx("reducing --hosts-keep to %u, to be under --hosts-max (%u)",
355 opt_hosts_keep, opt_hosts_max);
356 }
357 verbosef("max %u hosts, cutting down to %u when exceeded",
358 opt_hosts_max, opt_hosts_keep);
359
360 if ((opt_ports_max != 0) && (opt_ports_keep >= opt_ports_max)) {
361 opt_ports_keep = opt_ports_max / 2;
362 warnx("reducing --ports-keep to %u, to be under --ports-max (%u)",
363 opt_ports_keep, opt_ports_max);
364 }
365 verbosef("max %u ports per host, cutting down to %u when exceeded",
366 opt_ports_max, opt_ports_keep);
367
368 if (opt_want_hexdump && !opt_want_verbose) {
369 opt_want_verbose = 1;
370 verbosef("--hexdump implies --verbose");
371 }
372
373 if (opt_want_hexdump && opt_want_daemonize) {
374 opt_want_daemonize = 0;
375 verbosef("--hexdump implies --no-daemon");
376 }
377
378 if (opt_want_local_only && !is_localnet_specified)
379 verbosef("WARNING: --local-only without -l only matches the local host");
380 }
381
382 static void
383 run_from_capfile(void)
384 {
385 graph_init();
386 hosts_db_init();
387 cap_from_file(opt_capfile, opt_filter);
388 cap_stop();
389 if (export_fn != NULL) db_export(export_fn);
390 hosts_db_free();
391 graph_free();
392 #ifndef PRIu64
393 #warning "PRIu64 is not defined, using qu instead"
394 #define PRIu64 "qu"
395 #endif
396 verbosef("Total packets: %"PRIu64", bytes: %"PRIu64,
397 acct_total_packets, acct_total_bytes);
398 }
399
400 /* --- Program body --- */
401 int
402 main(int argc, char **argv)
403 {
404 test_64order();
405 parse_cmdline(argc-1, argv+1);
406
407 if (opt_capfile) {
408 /*
409 * This is very different from a regular run against a network
410 * interface.
411 */
412 run_from_capfile();
413 return 0;
414 }
415
416 /* must verbosef() before first fork to init lock */
417 verbosef("starting up");
418 if (pid_fn) pidfile_create(opt_chroot_dir, pid_fn, opt_privdrop_user);
419
420 if (opt_want_daemonize) {
421 verbosef("daemonizing to run in the background!");
422 daemonize_start();
423 verbosef("I am the main process");
424 }
425 if (pid_fn) pidfile_write_close();
426
427 /* do this first as it forks - minimize memory use */
428 if (opt_want_dns) dns_init(opt_privdrop_user);
429 cap_init(opt_interface, opt_filter, opt_want_promisc); /* needs root */
430 http_listen(opt_bindport);
431 ncache_init(); /* must do before chroot() */
432
433 privdrop(opt_chroot_dir, opt_privdrop_user);
434
435 /* Don't need root privs for these: */
436 now = time(NULL);
437 if (daylog_fn != NULL) daylog_init(daylog_fn);
438 graph_init();
439 hosts_db_init();
440 if (import_fn != NULL) db_import(import_fn);
441 localip_init(opt_interface);
442
443 if (signal(SIGTERM, sig_shutdown) == SIG_ERR)
444 errx(1, "signal(SIGTERM) failed");
445 if (signal(SIGINT, sig_shutdown) == SIG_ERR)
446 errx(1, "signal(SIGINT) failed");
447 if (signal(SIGUSR1, sig_reset) == SIG_ERR)
448 errx(1, "signal(SIGUSR1) failed");
449 if (signal(SIGUSR2, sig_export) == SIG_ERR)
450 errx(1, "signal(SIGUSR2) failed");
451
452 verbosef("entering main loop");
453 daemonize_finish();
454
455 while (running) {
456 int select_ret, max_fd = -1, use_timeout = 0;
457 struct timeval timeout;
458 fd_set rs, ws;
459
460 now = time(NULL);
461
462 if (export_pending) {
463 if (export_fn != NULL)
464 db_export(export_fn);
465 export_pending = 0;
466 }
467
468 if (reset_pending) {
469 if (export_pending)
470 continue; /* export before reset */
471 hosts_db_reset();
472 graph_reset();
473 reset_pending = 0;
474 }
475
476 FD_ZERO(&rs);
477 FD_ZERO(&ws);
478
479 cap_fd_set(&rs, &max_fd, &timeout, &use_timeout);
480 http_fd_set(&rs, &ws, &max_fd, &timeout, &use_timeout);
481
482 select_ret = select(max_fd+1, &rs, &ws, NULL,
483 (use_timeout) ? &timeout : NULL);
484
485 if ((select_ret == 0) && (!use_timeout))
486 errx(1, "select() erroneously timed out");
487
488 if (select_ret == -1) {
489 if (errno == EINTR)
490 continue;
491 else
492 err(1, "select()");
493 }
494 else {
495 graph_rotate();
496 cap_poll(&rs);
497 dns_poll();
498 http_poll(&rs, &ws);
499 }
500 }
501
502 verbosef("shutting down");
503 verbosef("pcap stats: %u packets received, %u packets dropped",
504 cap_pkts_recv, cap_pkts_drop);
505 http_stop();
506 cap_stop();
507 dns_stop();
508 if (export_fn != NULL) db_export(export_fn);
509 hosts_db_free();
510 graph_free();
511 if (daylog_fn != NULL) daylog_free();
512 ncache_free();
513 if (pid_fn) pidfile_unlink();
514 verbosef("shut down");
515 return (EXIT_SUCCESS);
516 }
517
518 /* vim:set ts=3 sw=3 tw=78 expandtab: */