0f0f9deee93ce0f5d96b213b26874b41bd588808
[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 const char *privdrop_user = NULL;
138 static void cb_user(const char *arg) { privdrop_user = arg; }
139
140 const char *daylog_fn = NULL;
141 static void cb_daylog(const char *arg)
142 {
143 if (chroot_dir == NULL)
144 errx(1, "the daylog file is relative to the chroot.\n"
145 "You must specify a --chroot dir before you can use --daylog.");
146 else
147 daylog_fn = arg;
148 }
149
150 const char *import_fn = NULL;
151 static void cb_import(const char *arg)
152 {
153 if (chroot_dir == NULL)
154 errx(1, "the import file is relative to the chroot.\n"
155 "You must specify a --chroot dir before you can use --import.");
156 else
157 import_fn = arg;
158 }
159
160 const char *export_fn = NULL;
161 static void cb_export(const char *arg)
162 {
163 if ((chroot_dir == NULL) && (capfile == NULL))
164 errx(1, "the export file is relative to the chroot.\n"
165 "You must specify a --chroot dir before you can use --export.");
166 else
167 export_fn = arg;
168 }
169
170 static const char *pid_fn = NULL;
171 static void cb_pidfile(const char *arg)
172 {
173 if (chroot_dir == NULL)
174 errx(1, "the pidfile is relative to the chroot.\n"
175 "You must specify a --chroot dir before you can use --pidfile.");
176 else
177 pid_fn = arg;
178 }
179
180 unsigned int hosts_max = 1000;
181 static void cb_hosts_max(const char *arg)
182 { hosts_max = parsenum(arg, 0); }
183
184 unsigned int hosts_keep = 500;
185 static void cb_hosts_keep(const char *arg)
186 { hosts_keep = parsenum(arg, 0); }
187
188 unsigned int ports_max = 200;
189 static void cb_ports_max(const char *arg)
190 { ports_max = parsenum(arg, 65536); }
191
192 unsigned int ports_keep = 30;
193 static void cb_ports_keep(const char *arg)
194 { ports_keep = parsenum(arg, 65536); }
195
196 unsigned int highest_port = 65535;
197 static void cb_highest_port(const char *arg)
198 { highest_port = parsenum(arg, 65535); }
199
200 int wait_secs = -1;
201 static void cb_wait_secs(const char *arg)
202 { wait_secs = parsenum(arg, 0); }
203
204 int want_hexdump = 0;
205 static void cb_hexdump(const char *arg _unused_) { want_hexdump = 1; }
206
207 /* --- */
208
209 struct cmdline_arg {
210 const char *name, *arg_name; /* NULL arg_name means unary */
211 void (*callback)(const char *arg);
212 int num_seen;
213 };
214
215 static struct cmdline_arg cmdline_args[] = {
216 {"-i", "interface", cb_interface, 0},
217 {"-r", "file", cb_capfile, 0},
218 {"--snaplen", "bytes", cb_snaplen, 0},
219 {"--pppoe", NULL, cb_pppoe, 0},
220 {"--syslog", NULL, cb_syslog, 0},
221 {"--verbose", NULL, cb_verbose, 0},
222 {"--no-daemon", NULL, cb_no_daemon, 0},
223 {"--no-promisc", NULL, cb_no_promisc, 0},
224 {"--no-dns", NULL, cb_no_dns, 0},
225 {"--no-macs", NULL, cb_no_macs, 0},
226 {"--no-lastseen", NULL, cb_no_lastseen, 0},
227 {"-p", "port", cb_port, 0},
228 {"-b", "bindaddr", cb_bindaddr, 0},
229 {"-f", "filter", cb_filter, 0},
230 {"-l", "network/netmask", cb_local, 0},
231 {"--chroot", "dir", cb_chroot, 0},
232 {"--user", "username", cb_user, 0},
233 {"--daylog", "filename", cb_daylog, 0},
234 {"--import", "filename", cb_import, 0},
235 {"--export", "filename", cb_export, 0},
236 {"--pidfile", "filename", cb_pidfile, 0},
237 {"--hosts-max", "count", cb_hosts_max, 0},
238 {"--hosts-keep", "count", cb_hosts_keep, 0},
239 {"--ports-max", "count", cb_ports_max, 0},
240 {"--ports-keep", "count", cb_ports_keep, 0},
241 {"--highest-port", "port", cb_highest_port, 0},
242 {"--wait", "secs", cb_wait_secs, 0},
243 {"--hexdump", NULL, cb_hexdump, 0},
244 {NULL, NULL, NULL, 0}
245 };
246
247 static void
248 pad(const int width)
249 {
250 int i;
251 for (i=0; i<width; i++) printf(" ");
252 }
253
254 /*
255 * We autogenerate the usage statement from the cmdline_args data structure.
256 */
257 static void
258 usage(void)
259 {
260 int width, first;
261 struct cmdline_arg *arg;
262
263 printf(PACKAGE_STRING " (built with libpcap %d.%d)\n\n",
264 PCAP_VERSION_MAJOR, PCAP_VERSION_MINOR);
265
266 width = printf("usage: darkstat ");
267 first = 1;
268
269 for (arg = cmdline_args; arg->name != NULL; arg++) {
270 if (first) first = 0; else pad(width);
271 printf("[ %s", arg->name);
272 if (arg->arg_name != NULL) printf(" %s", arg->arg_name);
273 printf(" ]\n");
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
281 parse_sub_cmdline(const int argc, char * const *argv)
282 {
283 struct cmdline_arg *arg;
284
285 if (argc == 0) return;
286 for (arg = cmdline_args; arg->name != NULL; arg++)
287 if (strcmp(argv[0], arg->name) == 0) {
288 if ((arg->arg_name != NULL) && (argc == 1)) {
289 fprintf(stderr,
290 "error: argument \"%s\" requires parameter \"%s\"\n",
291 arg->name, arg->arg_name);
292 usage();
293 exit(EXIT_FAILURE);
294 }
295 if (arg->num_seen > 0) {
296 fprintf(stderr,
297 "error: already specified argument \"%s\"\n",
298 arg->name);
299 usage();
300 exit(EXIT_FAILURE);
301 }
302
303 arg->num_seen++;
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
320 parse_cmdline(const int argc, char * const *argv)
321 {
322 if (argc < 1) {
323 /* Not enough args. */
324 usage();
325 exit(EXIT_FAILURE);
326 }
327
328 parse_sub_cmdline(argc, argv);
329
330 /* start syslogging as early as possible */
331 if (want_syslog) openlog("darkstat", LOG_NDELAY | LOG_PID, LOG_DAEMON);
332
333 /* some default values */
334 if (chroot_dir == NULL) chroot_dir = CHROOT_DIR;
335 if (privdrop_user == NULL) privdrop_user = PRIVDROP_USER;
336
337 /* sanity check args */
338 if ((interface == NULL) && (capfile == NULL))
339 errx(1, "must specify either interface (-i) or capture file (-r)");
340
341 if ((interface != NULL) && (capfile != NULL))
342 errx(1, "can't specify both interface (-i) and capture file (-r)");
343
344 if ((hosts_max != 0) && (hosts_keep >= hosts_max)) {
345 hosts_keep = hosts_max / 2;
346 warnx("reducing --hosts-keep to %u, to be under --hosts-max (%u)",
347 hosts_keep, hosts_max);
348 }
349 verbosef("max %u hosts, cutting down to %u when exceeded",
350 hosts_max, hosts_keep);
351
352 if ((ports_max != 0) && (ports_keep >= ports_max)) {
353 ports_keep = ports_max / 2;
354 warnx("reducing --ports-keep to %u, to be under --ports-max (%u)",
355 ports_keep, ports_max);
356 }
357 verbosef("max %u ports per host, cutting down to %u when exceeded",
358 ports_max, ports_keep);
359
360 if (want_hexdump && !want_verbose) {
361 want_verbose = 1;
362 verbosef("--hexdump implies --verbose");
363 }
364
365 if (want_hexdump && want_daemonize) {
366 want_daemonize = 0;
367 verbosef("--hexdump implies --no-daemon");
368 }
369 }
370
371 static void
372 run_from_capfile(void)
373 {
374 graph_init();
375 hosts_db_init();
376 cap_from_file(capfile, filter);
377 cap_stop();
378 if (export_fn != NULL) db_export(export_fn);
379 hosts_db_free();
380 graph_free();
381 verbosef("Total packets: %qu, bytes: %qu", total_packets, total_bytes);
382 }
383
384 /* --- Program body --- */
385 int
386 main(int argc, char **argv)
387 {
388 test_64order();
389 parse_cmdline(argc-1, argv+1);
390
391 if (capfile) {
392 /*
393 * This is very different from a regular run against a network
394 * interface.
395 */
396 run_from_capfile();
397 return 0;
398 }
399
400 /* must verbosef() before first fork to init lock */
401 verbosef("starting up");
402 if (pid_fn) pidfile_create(chroot_dir, pid_fn, privdrop_user);
403
404 if (want_daemonize) {
405 verbosef("daemonizing to run in the background!");
406 daemonize_start();
407 verbosef("I am the main process");
408 }
409 if (pid_fn) pidfile_write_close();
410
411 /* do this first as it forks - minimize memory use */
412 if (want_dns) dns_init(privdrop_user);
413 cap_init(interface, filter, want_promisc); /* needs root */
414 http_init(bindaddr, bindport, /*maxconn=*/ -1); /* low ports need root */
415 ncache_init(); /* must do before chroot() */
416
417 privdrop(chroot_dir, privdrop_user);
418
419 /* Don't need root privs for these: */
420 now = time(NULL);
421 if (daylog_fn != NULL) daylog_init(daylog_fn);
422 graph_init();
423 hosts_db_init();
424 if (import_fn != NULL) db_import(import_fn);
425 localip_init(interface);
426
427 if (signal(SIGTERM, sig_shutdown) == SIG_ERR)
428 errx(1, "signal(SIGTERM) failed");
429 if (signal(SIGINT, sig_shutdown) == SIG_ERR)
430 errx(1, "signal(SIGINT) failed");
431 if (signal(SIGUSR1, sig_reset) == SIG_ERR)
432 errx(1, "signal(SIGUSR1) failed");
433 if (signal(SIGUSR2, sig_export) == SIG_ERR)
434 errx(1, "signal(SIGUSR2) failed");
435
436 verbosef("entering main loop");
437 daemonize_finish();
438
439 while (running) {
440 int select_ret, max_fd = -1, use_timeout = 0;
441 struct timeval timeout;
442 fd_set rs, ws;
443
444 now = time(NULL);
445
446 if (export_pending) {
447 if (export_fn != NULL)
448 db_export(export_fn);
449 export_pending = 0;
450 }
451
452 if (reset_pending) {
453 hosts_db_reset();
454 graph_reset();
455 reset_pending = 0;
456 }
457
458 FD_ZERO(&rs);
459 FD_ZERO(&ws);
460
461 cap_fd_set(&rs, &max_fd, &timeout, &use_timeout);
462 http_fd_set(&rs, &ws, &max_fd, &timeout, &use_timeout);
463
464 select_ret = select(max_fd+1, &rs, &ws, NULL,
465 (use_timeout) ? &timeout : NULL);
466
467 if ((select_ret == 0) && (!use_timeout))
468 errx(1, "select() erroneously timed out");
469
470 if (select_ret == -1) {
471 if (errno == EINTR)
472 continue;
473 else
474 err(1, "select()");
475 }
476 else {
477 graph_rotate();
478 cap_poll(&rs);
479 dns_poll();
480 http_poll(&rs, &ws);
481 }
482 }
483
484 verbosef("shutting down");
485 verbosef("pcap stats: %u packets received, %u packets dropped",
486 pkts_recv, pkts_drop);
487 cap_stop();
488 dns_stop();
489 if (export_fn != NULL) db_export(export_fn);
490 hosts_db_free();
491 graph_free();
492 if (daylog_fn != NULL) daylog_free();
493 ncache_free();
494 if (pid_fn) pidfile_unlink();
495 verbosef("shut down");
496 return (EXIT_SUCCESS);
497 }
498
499 /* vim:set ts=3 sw=3 tw=78 expandtab: */