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