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