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