Remove an unnecessary define.
[darkstat] / hosts_db.c
1 /* darkstat 3
2 * copyright (c) 2001-2011 Emil Mikulic.
3 *
4 * hosts_db.c: database of hosts, ports, protocols.
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 "cdefs.h"
11 #include "conv.h"
12 #include "decode.h"
13 #include "dns.h"
14 #include "err.h"
15 #include "hosts_db.h"
16 #include "db.h"
17 #include "html.h"
18 #include "ncache.h"
19 #include "now.h"
20 #include "opt.h"
21 #include "str.h"
22
23 #include <arpa/inet.h> /* inet_aton() */
24 #include <netdb.h> /* struct addrinfo */
25 #include <assert.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h> /* memset(), strcmp() */
30 #include <unistd.h>
31
32 int hosts_db_show_macs = 0;
33
34 /* FIXME: specify somewhere more sane/tunable */
35 #define MAX_ENTRIES 30 /* in an HTML table rendered from a hashtable */
36
37 typedef uint32_t (hash_func_t)(const struct hashtable *, const void *);
38 typedef void (free_func_t)(struct bucket *);
39 typedef const void * (key_func_t)(const struct bucket *);
40 typedef int (find_func_t)(const struct bucket *, const void *);
41 typedef struct bucket * (make_func_t)(const void *);
42 typedef void (format_cols_func_t)(struct str *);
43 typedef void (format_row_func_t)(struct str *, const struct bucket *,
44 const char *);
45
46 struct hashtable {
47 uint8_t bits; /* size of hashtable in bits */
48 uint32_t size, mask;
49 uint32_t count, count_max, count_keep; /* items in table */
50 uint32_t coeff; /* coefficient for Fibonacci hashing */
51 struct bucket **table;
52
53 struct {
54 uint64_t inserts, searches, deletions, rehashes;
55 } stats;
56
57 hash_func_t *hash_func;
58 /* returns hash value of given key (passed as void*) */
59
60 free_func_t *free_func;
61 /* free of bucket payload */
62
63 key_func_t *key_func;
64 /* returns pointer to key of bucket (to pass to hash_func) */
65
66 find_func_t *find_func;
67 /* returns true if given bucket matches key (passed as void*) */
68
69 make_func_t *make_func;
70 /* returns bucket containing new record with key (passed as void*) */
71
72 format_cols_func_t *format_cols_func;
73 /* append table columns to str */
74
75 format_row_func_t *format_row_func;
76 /* format record and append to str */
77 };
78
79 static void hashtable_reduce(struct hashtable *ht);
80 static void hashtable_free(struct hashtable *h);
81
82 #define HOST_BITS 1 /* initial size of hosts table */
83 #define PORT_BITS 1 /* initial size of ports tables */
84 #define PROTO_BITS 1 /* initial size of proto table */
85
86 /* We only use one hosts_db hashtable and this is it. */
87 static struct hashtable *hosts_db = NULL;
88
89 /* phi^-1 (reciprocal of golden ratio) = (sqrt(5) - 1) / 2 */
90 static const double phi_1 =
91 0.61803398874989490252573887119069695472717285156250;
92
93 /* Co-prime of u, using phi^-1 */
94 inline static uint32_t
95 coprime(const uint32_t u)
96 {
97 return ( (uint32_t)( (double)(u) * phi_1 ) | 1U );
98 }
99
100 /*
101 * This is the "recommended" IPv4 hash function, as seen in FreeBSD's
102 * src/sys/netinet/tcp_hostcache.c 1.1
103 */
104 inline static uint32_t
105 ipv4_hash(const struct addr *const a)
106 {
107 uint32_t ip = a->ip.v4;
108 return ( (ip) ^ ((ip) >> 7) ^ ((ip) >> 17) );
109 }
110
111 #ifndef s6_addr32
112 # ifdef sun
113 /*
114 * http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/netinet/in.h#130
115 */
116 # define s6_addr32 _S6_un._S6_u32
117 # else
118 /* Covers OpenBSD and FreeBSD. The macro __USE_GNU has
119 * taken care of GNU/Linux and GNU/kfreebsd. */
120 # define s6_addr32 __u6_addr.__u6_addr32
121 # endif
122 #endif
123
124 /*
125 * This is the IPv6 hash function used by FreeBSD in the same file as above,
126 * svn rev 122922.
127 */
128 inline static uint32_t
129 ipv6_hash(const struct addr *const a)
130 {
131 const struct in6_addr *const ip6 = &(a->ip.v6);
132 return ( ip6->s6_addr32[0] ^ ip6->s6_addr32[1] ^
133 ip6->s6_addr32[2] ^ ip6->s6_addr32[3] );
134 }
135
136 /* ---------------------------------------------------------------------------
137 * hash_func collection
138 */
139 static uint32_t
140 hash_func_host(const struct hashtable *h _unused_, const void *key)
141 {
142 const struct addr *a = key;
143 if (a->family == IPv4)
144 return (ipv4_hash(a));
145 else {
146 assert(a->family == IPv6);
147 return (ipv6_hash(a));
148 }
149 }
150
151 #define CASTKEY(type) (*((const type *)key))
152
153 static uint32_t
154 hash_func_short(const struct hashtable *h, const void *key)
155 {
156 return (CASTKEY(uint16_t) * h->coeff);
157 }
158
159 static uint32_t
160 hash_func_byte(const struct hashtable *h, const void *key)
161 {
162 return (CASTKEY(uint8_t) * h->coeff);
163 }
164
165 /* ---------------------------------------------------------------------------
166 * key_func collection
167 */
168
169 static const void *
170 key_func_host(const struct bucket *b)
171 {
172 return &(b->u.host.addr);
173 }
174
175 static const void *
176 key_func_port_tcp(const struct bucket *b)
177 {
178 return &(b->u.port_tcp.port);
179 }
180
181 static const void *
182 key_func_port_udp(const struct bucket *b)
183 {
184 return &(b->u.port_udp.port);
185 }
186
187 static const void *
188 key_func_ip_proto(const struct bucket *b)
189 {
190 return &(b->u.ip_proto.proto);
191 }
192
193 /* ---------------------------------------------------------------------------
194 * find_func collection
195 */
196
197 static int
198 find_func_host(const struct bucket *b, const void *key)
199 {
200 return (addr_equal(key, &(b->u.host.addr)));
201 }
202
203 static int
204 find_func_port_tcp(const struct bucket *b, const void *key)
205 {
206 return (b->u.port_tcp.port == CASTKEY(uint16_t));
207 }
208
209 static int
210 find_func_port_udp(const struct bucket *b, const void *key)
211 {
212 return (b->u.port_udp.port == CASTKEY(uint16_t));
213 }
214
215 static int
216 find_func_ip_proto(const struct bucket *b, const void *key)
217 {
218 return (b->u.ip_proto.proto == CASTKEY(uint8_t));
219 }
220
221 /* ---------------------------------------------------------------------------
222 * make_func collection
223 */
224
225 #define MAKE_BUCKET(name_bucket, name_content, type) struct { \
226 struct bucket *next; \
227 uint64_t in, out, total; \
228 union { struct type t; } u; } _custom_bucket; \
229 struct bucket *name_bucket = xcalloc(1, sizeof(_custom_bucket)); \
230 struct type *name_content = &(name_bucket->u.type); \
231 name_bucket->next = NULL; \
232 name_bucket->in = name_bucket->out = name_bucket->total = 0;
233
234 static struct bucket *
235 make_func_host(const void *key)
236 {
237 MAKE_BUCKET(b, h, host);
238 h->addr = CASTKEY(struct addr);
239 h->dns = NULL;
240 h->lastseen = 0;
241 memset(&h->mac_addr, 0, sizeof(h->mac_addr));
242 h->ports_tcp = NULL;
243 h->ports_udp = NULL;
244 h->ip_protos = NULL;
245 return (b);
246 }
247
248 static void
249 free_func_host(struct bucket *b)
250 {
251 struct host *h = &(b->u.host);
252 if (h->dns != NULL) free(h->dns);
253 hashtable_free(h->ports_tcp);
254 hashtable_free(h->ports_udp);
255 hashtable_free(h->ip_protos);
256 }
257
258 static struct bucket *
259 make_func_port_tcp(const void *key)
260 {
261 MAKE_BUCKET(b, p, port_tcp);
262 p->port = CASTKEY(uint16_t);
263 p->syn = 0;
264 return (b);
265 }
266
267 static struct bucket *
268 make_func_port_udp(const void *key)
269 {
270 MAKE_BUCKET(b, p, port_udp);
271 p->port = CASTKEY(uint16_t);
272 return (b);
273 }
274
275 static struct bucket *
276 make_func_ip_proto(const void *key)
277 {
278 MAKE_BUCKET(b, p, ip_proto);
279 p->proto = CASTKEY(uint8_t);
280 return (b);
281 }
282
283 static void
284 free_func_simple(struct bucket *b _unused_)
285 {
286 /* nop */
287 }
288
289 /* ---------------------------------------------------------------------------
290 * format_func collection (ordered by struct)
291 */
292
293 static void
294 format_cols_host(struct str *buf)
295 {
296 /* FIXME: don't clobber parts of the query string
297 * specifically "full" and "start"
298 * when setting sort direction
299 */
300 str_append(buf,
301 "<table>\n"
302 "<tr>\n"
303 " <th>IP</th>\n"
304 " <th>Hostname</th>\n");
305 if (hosts_db_show_macs) str_append(buf,
306 " <th>MAC Address</th>\n");
307 str_append(buf,
308 " <th><a href=\"?sort=in\">In</a></th>\n"
309 " <th><a href=\"?sort=out\">Out</a></th>\n"
310 " <th><a href=\"?sort=total\">Total</a></th>\n");
311 if (opt_want_lastseen) str_append(buf,
312 " <th><a href=\"?sort=lastseen\">Last seen</a></th>\n");
313 str_append(buf,
314 "</tr>\n");
315 }
316
317 static void
318 format_row_host(struct str *buf, const struct bucket *b,
319 const char *css_class)
320 {
321 const char *ip = addr_to_str(&(b->u.host.addr));
322
323 str_appendf(buf,
324 "<tr class=\"%s\">\n"
325 " <td><a href=\"./%s/\">%s</a></td>\n"
326 " <td>%s</td>\n",
327 css_class,
328 ip, ip,
329 (b->u.host.dns == NULL) ? "" : b->u.host.dns);
330
331 if (hosts_db_show_macs)
332 str_appendf(buf,
333 " <td><tt>%x:%x:%x:%x:%x:%x</tt></td>\n",
334 b->u.host.mac_addr[0],
335 b->u.host.mac_addr[1],
336 b->u.host.mac_addr[2],
337 b->u.host.mac_addr[3],
338 b->u.host.mac_addr[4],
339 b->u.host.mac_addr[5]);
340
341 str_appendf(buf,
342 " <td class=\"num\">%'qu</td>\n"
343 " <td class=\"num\">%'qu</td>\n"
344 " <td class=\"num\">%'qu</td>\n",
345 b->in, b->out, b->total);
346
347 if (opt_want_lastseen) {
348 time_t last_t = b->u.host.lastseen;
349 struct str *last_str = NULL;
350
351 if ((now >= last_t) && (last_t > 0))
352 last_str = length_of_time(now - last_t);
353
354 str_append(buf,
355 " <td class=\"num\">");
356 if (last_str == NULL) {
357 if (last_t == 0)
358 str_append(buf, "(never)");
359 else
360 str_append(buf, "(clock error)");
361 } else {
362 str_appendstr(buf, last_str);
363 str_free(last_str);
364 }
365 str_append(buf,
366 "</td>");
367 }
368
369 str_appendf(buf,
370 "</tr>\n");
371
372 /* Only resolve hosts "on demand" */
373 if (b->u.host.dns == NULL)
374 dns_queue(&(b->u.host.addr));
375 }
376
377 static void
378 format_cols_port_tcp(struct str *buf)
379 {
380 str_append(buf,
381 "<table>\n"
382 "<tr>\n"
383 " <th>Port</td>\n"
384 " <th>Service</td>\n"
385 " <th>In</td>\n"
386 " <th>Out</td>\n"
387 " <th>Total</td>\n"
388 " <th>SYNs</td>\n"
389 "</tr>\n"
390 );
391 }
392
393 static void
394 format_row_port_tcp(struct str *buf, const struct bucket *b,
395 const char *css_class)
396 {
397 const struct port_tcp *p = &(b->u.port_tcp);
398
399 str_appendf(buf,
400 "<tr class=\"%s\">\n"
401 " <td class=\"num\">%u</td>\n"
402 " <td>%s</td>\n"
403 " <td class=\"num\">%'qu</td>\n"
404 " <td class=\"num\">%'qu</td>\n"
405 " <td class=\"num\">%'qu</td>\n"
406 " <td class=\"num\">%'qu</td>\n"
407 "</tr>\n",
408 css_class,
409 p->port, getservtcp(p->port), b->in, b->out, b->total, p->syn
410 );
411 }
412
413 static void
414 format_cols_port_udp(struct str *buf)
415 {
416 str_append(buf,
417 "<table>\n"
418 "<tr>\n"
419 " <th>Port</td>\n"
420 " <th>Service</td>\n"
421 " <th>In</td>\n"
422 " <th>Out</td>\n"
423 " <th>Total</td>\n"
424 "</tr>\n"
425 );
426 }
427
428 static void
429 format_row_port_udp(struct str *buf, const struct bucket *b,
430 const char *css_class)
431 {
432 const struct port_udp *p = &(b->u.port_udp);
433
434 str_appendf(buf,
435 "<tr class=\"%s\">\n"
436 " <td class=\"num\">%u</td>\n"
437 " <td>%s</td>\n"
438 " <td class=\"num\">%'qu</td>\n"
439 " <td class=\"num\">%'qu</td>\n"
440 " <td class=\"num\">%'qu</td>\n"
441 "</tr>\n",
442 css_class,
443 p->port, getservudp(p->port), b->in, b->out, b->total
444 );
445 }
446
447 static void
448 format_cols_ip_proto(struct str *buf)
449 {
450 str_append(buf,
451 "<table>\n"
452 "<tr>\n"
453 " <th>#</td>\n"
454 " <th>Protocol</td>\n"
455 " <th>In</td>\n"
456 " <th>Out</td>\n"
457 " <th>Total</td>\n"
458 "</tr>\n"
459 );
460 }
461
462 static void
463 format_row_ip_proto(struct str *buf, const struct bucket *b,
464 const char *css_class)
465 {
466 const struct ip_proto *p = &(b->u.ip_proto);
467
468 str_appendf(buf,
469 "<tr class=\"%s\">\n"
470 " <td class=\"num\">%u</td>\n"
471 " <td>%s</td>\n"
472 " <td class=\"num\">%'qu</td>\n"
473 " <td class=\"num\">%'qu</td>\n"
474 " <td class=\"num\">%'qu</td>\n"
475 "</tr>\n",
476 css_class,
477 p->proto, getproto(p->proto),
478 b->in, b->out, b->total
479 );
480 }
481
482 /* ---------------------------------------------------------------------------
483 * Initialise a hashtable.
484 */
485 static struct hashtable *
486 hashtable_make(const uint8_t bits,
487 const unsigned int count_max,
488 const unsigned int count_keep,
489 hash_func_t *hash_func,
490 free_func_t *free_func,
491 key_func_t *key_func,
492 find_func_t *find_func,
493 make_func_t *make_func,
494 format_cols_func_t *format_cols_func,
495 format_row_func_t *format_row_func)
496 {
497 struct hashtable *hash;
498 assert(bits > 0);
499
500 hash = xmalloc(sizeof(*hash));
501 hash->bits = bits;
502 hash->count_max = count_max;
503 hash->count_keep = count_keep;
504 hash->size = 1U << bits;
505 hash->mask = hash->size - 1;
506 hash->coeff = coprime(hash->size);
507 hash->hash_func = hash_func;
508 hash->free_func = free_func;
509 hash->key_func = key_func;
510 hash->find_func = find_func;
511 hash->make_func = make_func;
512 hash->format_cols_func = format_cols_func;
513 hash->format_row_func = format_row_func;
514 hash->count = 0;
515 hash->table = xcalloc(hash->size, sizeof(*hash->table));
516 memset(&(hash->stats), 0, sizeof(hash->stats));
517 return (hash);
518 }
519
520 /* ---------------------------------------------------------------------------
521 * Initialise global hosts_db.
522 */
523 void
524 hosts_db_init(void)
525 {
526 assert(hosts_db == NULL);
527 hosts_db = hashtable_make(HOST_BITS, opt_hosts_max, opt_hosts_keep,
528 hash_func_host, free_func_host, key_func_host, find_func_host,
529 make_func_host, format_cols_host, format_row_host);
530 }
531
532 static void
533 hashtable_rehash(struct hashtable *h, const uint8_t bits)
534 {
535 struct bucket **old_table, **new_table;
536 uint32_t i, old_size;
537 assert(h != NULL);
538 assert(bits > 0);
539
540 h->stats.rehashes++;
541 old_size = h->size;
542 old_table = h->table;
543
544 h->bits = bits;
545 h->size = 1U << bits;
546 h->mask = h->size - 1;
547 h->coeff = coprime(h->size);
548 new_table = xcalloc(h->size, sizeof(*new_table));
549
550 for (i=0; i<old_size; i++) {
551 struct bucket *next, *b = old_table[i];
552 while (b != NULL) {
553 uint32_t pos = h->hash_func(h, h->key_func(b)) & h->mask;
554 next = b->next;
555 b->next = new_table[pos];
556 new_table[pos] = b;
557 b = next;
558 }
559 }
560
561 free(h->table);
562 h->table = new_table;
563 }
564
565 static void
566 hashtable_insert(struct hashtable *h, struct bucket *b)
567 {
568 uint32_t pos;
569 assert(h != NULL);
570 assert(b != NULL);
571 assert(b->next == NULL);
572
573 /* Rehash on 80% occupancy */
574 if ((h->count > h->size) ||
575 ((h->size - h->count) < h->size / 5))
576 hashtable_rehash(h, h->bits+1);
577
578 pos = h->hash_func(h, h->key_func(b)) & h->mask;
579 if (h->table[pos] == NULL)
580 h->table[pos] = b;
581 else {
582 /* Insert at top of chain. */
583 b->next = h->table[pos];
584 h->table[pos] = b;
585 }
586 h->count++;
587 h->stats.inserts++;
588 }
589
590 /* Return bucket matching key, or NULL if no such entry. */
591 static struct bucket *
592 hashtable_search(struct hashtable *h, const void *key)
593 {
594 uint32_t pos;
595 struct bucket *b;
596
597 h->stats.searches++;
598 pos = h->hash_func(h, key) & h->mask;
599 b = h->table[pos];
600 while (b != NULL) {
601 if (h->find_func(b, key))
602 return (b);
603 else
604 b = b->next;
605 }
606 return (NULL);
607 }
608
609 typedef enum { NO_REDUCE = 0, ALLOW_REDUCE = 1 } reduce_bool;
610 /* Search for a key. If it's not there, make and insert a bucket for it. */
611 static struct bucket *
612 hashtable_find_or_insert(struct hashtable *h, const void *key,
613 const reduce_bool allow_reduce)
614 {
615 struct bucket *b = hashtable_search(h, key);
616
617 if (b == NULL) {
618 /* Not found, so insert after checking occupancy. */
619 if (allow_reduce && (h->count >= h->count_max))
620 hashtable_reduce(h);
621 b = h->make_func(key);
622 hashtable_insert(h, b);
623 }
624 return (b);
625 }
626
627 /*
628 * Frees the hashtable and the buckets. The contents are assumed to be
629 * "simple" -- i.e. no "destructor" action is required beyond simply freeing
630 * the bucket.
631 */
632 static void
633 hashtable_free(struct hashtable *h)
634 {
635 uint32_t i;
636
637 if (h == NULL)
638 return;
639 for (i=0; i<h->size; i++) {
640 struct bucket *tmp, *b = h->table[i];
641 while (b != NULL) {
642 tmp = b;
643 b = b->next;
644 h->free_func(tmp);
645 free(tmp);
646 }
647 }
648 free(h->table);
649 free(h);
650 }
651
652 /* ---------------------------------------------------------------------------
653 * Return existing host or insert a new one.
654 */
655 struct bucket *
656 host_get(const struct addr *const a)
657 {
658 return (hashtable_find_or_insert(hosts_db, a, NO_REDUCE));
659 }
660
661 /* ---------------------------------------------------------------------------
662 * Find host, returns NULL if not in DB.
663 */
664 struct bucket *
665 host_find(const struct addr *const a)
666 {
667 return (hashtable_search(hosts_db, a));
668 }
669
670 /* ---------------------------------------------------------------------------
671 * Find host, returns NULL if not in DB.
672 */
673 static struct bucket *
674 host_search(const char *ipstr)
675 {
676 struct addr a;
677 struct addrinfo hints, *ai;
678
679 memset(&hints, 0, sizeof(hints));
680 hints.ai_family = AF_UNSPEC;
681 hints.ai_flags = AI_NUMERICHOST;
682
683 if (getaddrinfo(ipstr, NULL, &hints, &ai))
684 return (NULL); /* invalid addr */
685
686 if (ai->ai_family == AF_INET) {
687 a.family = IPv4;
688 a.ip.v4 = ((const struct sockaddr_in *)ai->ai_addr)->sin_addr.s_addr;
689 }
690 else if (ai->ai_family == AF_INET6) {
691 a.family = IPv6;
692 memcpy(&(a.ip.v6),
693 ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr.s6_addr,
694 sizeof(a.ip.v6));
695 } else {
696 freeaddrinfo(ai);
697 return (NULL); /* unknown family */
698 }
699 freeaddrinfo(ai);
700
701 verbosef("search(%s) turned into %s", ipstr, addr_to_str(&a));
702 return (hashtable_search(hosts_db, &a));
703 }
704
705 /* ---------------------------------------------------------------------------
706 * Reduce a hashtable to the top <keep> entries.
707 */
708 static void
709 hashtable_reduce(struct hashtable *ht)
710 {
711 uint32_t i, pos, rmd;
712 const struct bucket **table;
713 uint64_t cutoff;
714
715 assert(ht->count_keep < ht->count);
716
717 /* Fill table with pointers to buckets in hashtable. */
718 table = xcalloc(ht->count, sizeof(*table));
719 for (pos=0, i=0; i<ht->size; i++) {
720 struct bucket *b = ht->table[i];
721 while (b != NULL) {
722 table[pos++] = b;
723 b = b->next;
724 }
725 }
726 assert(pos == ht->count);
727 qsort_buckets(table, ht->count, 0, ht->count_keep, TOTAL);
728 cutoff = table[ht->count_keep]->total;
729 free(table);
730
731 /* Remove all elements with total <= cutoff. */
732 rmd = 0;
733 for (i=0; i<ht->size; i++) {
734 struct bucket *last = NULL, *next, *b = ht->table[i];
735 while (b != NULL) {
736 next = b->next;
737 if (b->total <= cutoff) {
738 /* Remove this one. */
739 ht->free_func(b);
740 free(b);
741 if (last == NULL)
742 ht->table[i] = next;
743 else
744 last->next = next;
745 rmd++;
746 ht->count--;
747 } else {
748 last = b;
749 }
750 b = next;
751 }
752 }
753 verbosef("hashtable_reduce: removed %u buckets, left %u",
754 rmd, ht->count);
755 hashtable_rehash(ht, ht->bits); /* is this needed? */
756 }
757
758 /* Reduce hosts_db if needed. */
759 void hosts_db_reduce(void)
760 {
761 if (hosts_db->count >= hosts_db->count_max)
762 hashtable_reduce(hosts_db);
763 }
764
765 /* ---------------------------------------------------------------------------
766 * Reset hosts_db to empty.
767 */
768 void
769 hosts_db_reset(void)
770 {
771 unsigned int i;
772
773 for (i=0; i<hosts_db->size; i++) {
774 struct bucket *next, *b = hosts_db->table[i];
775 while (b != NULL) {
776 next = b->next;
777 hosts_db->free_func(b);
778 free(b);
779 b = next;
780 }
781 hosts_db->table[i] = NULL;
782 }
783 verbosef("hosts_db reset to empty, freed %u hosts", hosts_db->count);
784 hosts_db->count = 0;
785 }
786
787 /* ---------------------------------------------------------------------------
788 * Deallocate hosts_db.
789 */
790 void hosts_db_free(void)
791 {
792 uint32_t i;
793
794 assert(hosts_db != NULL);
795 for (i=0; i<hosts_db->size; i++) {
796 struct bucket *tmp, *b = hosts_db->table[i];
797 while (b != NULL) {
798 tmp = b;
799 b = b->next;
800 hosts_db->free_func(tmp);
801 free(tmp);
802 }
803 }
804 free(hosts_db->table);
805 free(hosts_db);
806 hosts_db = NULL;
807 }
808
809 /* ---------------------------------------------------------------------------
810 * Find or create a port_tcp inside a host.
811 */
812 struct bucket *
813 host_get_port_tcp(struct bucket *host, const uint16_t port)
814 {
815 struct host *h = &host->u.host;
816 assert(h != NULL);
817 if (h->ports_tcp == NULL)
818 h->ports_tcp = hashtable_make(PORT_BITS, opt_ports_max, opt_ports_keep,
819 hash_func_short, free_func_simple, key_func_port_tcp,
820 find_func_port_tcp, make_func_port_tcp,
821 format_cols_port_tcp, format_row_port_tcp);
822 return (hashtable_find_or_insert(h->ports_tcp, &port, ALLOW_REDUCE));
823 }
824
825 /* ---------------------------------------------------------------------------
826 * Find or create a port_udp inside a host.
827 */
828 struct bucket *
829 host_get_port_udp(struct bucket *host, const uint16_t port)
830 {
831 struct host *h = &host->u.host;
832 assert(h != NULL);
833 if (h->ports_udp == NULL)
834 h->ports_udp = hashtable_make(PORT_BITS, opt_ports_max, opt_ports_keep,
835 hash_func_short, free_func_simple, key_func_port_udp,
836 find_func_port_udp, make_func_port_udp,
837 format_cols_port_udp, format_row_port_udp);
838 return (hashtable_find_or_insert(h->ports_udp, &port, ALLOW_REDUCE));
839 }
840
841 /* ---------------------------------------------------------------------------
842 * Find or create an ip_proto inside a host.
843 */
844 struct bucket *
845 host_get_ip_proto(struct bucket *host, const uint8_t proto)
846 {
847 struct host *h = &host->u.host;
848 static const unsigned int PROTOS_MAX = 512, PROTOS_KEEP = 256;
849 assert(h != NULL);
850 if (h->ip_protos == NULL)
851 h->ip_protos = hashtable_make(PROTO_BITS, PROTOS_MAX, PROTOS_KEEP,
852 hash_func_byte, free_func_simple, key_func_ip_proto,
853 find_func_ip_proto, make_func_ip_proto,
854 format_cols_ip_proto, format_row_ip_proto);
855 return (hashtable_find_or_insert(h->ip_protos, &proto, ALLOW_REDUCE));
856 }
857
858 static struct str *html_hosts_main(const char *qs);
859 static struct str *html_hosts_detail(const char *ip);
860
861 /* ---------------------------------------------------------------------------
862 * Web interface: delegate the /hosts/ space.
863 */
864 struct str *
865 html_hosts(const char *uri, const char *query)
866 {
867 unsigned int i, num_elems;
868 char **elem = split('/', uri, &num_elems);
869 struct str *buf = NULL;
870
871 assert(num_elems >= 1);
872 assert(strcmp(elem[0], "hosts") == 0);
873
874 if (num_elems == 1)
875 /* /hosts/ */
876 buf = html_hosts_main(query);
877 else if (num_elems == 2)
878 /* /hosts/<IP of host>/ */
879 buf = html_hosts_detail(elem[1]);
880
881 for (i=0; i<num_elems; i++)
882 free(elem[i]);
883 free(elem);
884 return (buf); /* FIXME: a NULL here becomes 404 Not Found, we might want
885 other codes to be possible */
886 }
887
888 /* ---------------------------------------------------------------------------
889 * Format hashtable into HTML.
890 */
891 static void
892 format_table(struct str *buf, struct hashtable *ht, unsigned int start,
893 const enum sort_dir sort, const int full)
894 {
895 const struct bucket **table;
896 unsigned int i, pos, end;
897 int alt = 0;
898
899 if ((ht == NULL) || (ht->count == 0)) {
900 str_append(buf, "<p>The table is empty.</p>\n");
901 return;
902 }
903
904 /* Fill table with pointers to buckets in hashtable. */
905 table = xcalloc(ht->count, sizeof(*table));
906 for (pos=0, i=0; i<ht->size; i++) {
907 struct bucket *b = ht->table[i];
908 while (b != NULL) {
909 table[pos++] = b;
910 b = b->next;
911 }
912 }
913 assert(pos == ht->count);
914
915 if (full) {
916 /* full report overrides start and end */
917 start = 0;
918 end = ht->count;
919 } else
920 end = MIN(ht->count, (uint32_t)start+MAX_ENTRIES);
921
922 str_appendf(buf, "(%u-%u of %u)<br>\n", start+1, end, ht->count);
923 qsort_buckets(table, ht->count, start, end, sort);
924 ht->format_cols_func(buf);
925
926 for (i=start; i<end; i++) {
927 ht->format_row_func(buf, table[i], alt ? "alt1" : "alt2");
928 alt = !alt; /* alternate class for table rows */
929 }
930 free(table);
931 str_append(buf, "</table>\n");
932 }
933
934 /* ---------------------------------------------------------------------------
935 * Web interface: sorted table of hosts.
936 */
937 static struct str *
938 html_hosts_main(const char *qs)
939 {
940 struct str *buf = str_make();
941 char *qs_start, *qs_sort, *qs_full, *ep;
942 const char *sortstr;
943 int start, full = 0;
944 enum sort_dir sort;
945
946 /* parse query string */
947 qs_start = qs_get(qs, "start");
948 qs_sort = qs_get(qs, "sort");
949 qs_full = qs_get(qs, "full");
950 if (qs_full != NULL) {
951 full = 1;
952 free(qs_full);
953 }
954
955 /* validate sort */
956 if (qs_sort == NULL) sort = TOTAL;
957 else if (strcmp(qs_sort, "total") == 0) sort = TOTAL;
958 else if (strcmp(qs_sort, "in") == 0) sort = IN;
959 else if (strcmp(qs_sort, "out") == 0) sort = OUT;
960 else if (strcmp(qs_sort, "lastseen") == 0) sort = LASTSEEN;
961 else {
962 str_append(buf, "Error: invalid value for \"sort\".\n");
963 goto done;
964 }
965
966 /* parse start */
967 if (qs_start == NULL)
968 start = 0;
969 else {
970 start = (int)strtoul(qs_start, &ep, 10);
971 if (*ep != '\0') {
972 str_append(buf, "Error: \"start\" is not a number.\n");
973 goto done;
974 }
975 if ((errno == ERANGE) ||
976 (start < 0) || (start >= (int)hosts_db->count)) {
977 str_append(buf, "Error: \"start\" is out of bounds.\n");
978 goto done;
979 }
980 }
981
982 #define PREV "&lt;&lt;&lt; prev page"
983 #define NEXT "next page &gt;&gt;&gt;"
984 #define FULL "full table"
985
986 html_open(buf, "Hosts", /*path_depth=*/1, /*want_graph_js=*/0);
987 format_table(buf, hosts_db, start, sort, full);
988
989 /* <prev | full | stats | next> */
990 sortstr = qs_sort;
991 if (sortstr == NULL) sortstr = "total";
992 if (start > 0) {
993 int prev = start - MAX_ENTRIES;
994 if (prev < 0)
995 prev = 0;
996 str_appendf(buf, "<a href=\"?start=%d&sort=%s\">" PREV "</a>",
997 prev, sortstr);
998 } else
999 str_append(buf, PREV);
1000
1001 if (full)
1002 str_append(buf, " | " FULL);
1003 else
1004 str_appendf(buf, " | <a href=\"?full=yes&sort=%s\">" FULL "</a>",
1005 sortstr);
1006
1007 if (start+MAX_ENTRIES < (int)hosts_db->count)
1008 str_appendf(buf, " | <a href=\"?start=%d&sort=%s\">" NEXT "</a>",
1009 start+MAX_ENTRIES, sortstr);
1010 else
1011 str_append(buf, " | " NEXT);
1012
1013 str_append(buf, "<br>\n");
1014
1015 html_close(buf);
1016 done:
1017 if (qs_start != NULL) free(qs_start);
1018 if (qs_sort != NULL) free(qs_sort);
1019 return buf;
1020 #undef PREV
1021 #undef NEXT
1022 #undef FULL
1023 }
1024
1025 /* ---------------------------------------------------------------------------
1026 * Web interface: detailed view of a single host.
1027 */
1028 static struct str *
1029 html_hosts_detail(const char *ip)
1030 {
1031 struct bucket *h;
1032 struct str *buf, *ls_len;
1033 char ls_when[100];
1034 const char *canonical;
1035 time_t ls;
1036
1037 h = host_search(ip);
1038 if (h == NULL)
1039 return (NULL); /* no such host */
1040
1041 canonical = addr_to_str(&(h->u.host.addr));
1042
1043 /* Overview. */
1044 buf = str_make();
1045 html_open(buf, ip, /*path_depth=*/2, /*want_graph_js=*/0);
1046 if (strcmp(ip, canonical) != 0)
1047 str_appendf(buf, "(canonically <b>%s</b>)\n", canonical);
1048 str_appendf(buf,
1049 "<p>\n"
1050 "<b>Hostname:</b> %s<br>\n",
1051 (h->u.host.dns == NULL)?"(resolving...)":h->u.host.dns);
1052
1053 /* Resolve host "on demand" */
1054 if (h->u.host.dns == NULL)
1055 dns_queue(&(h->u.host.addr));
1056
1057 if (hosts_db_show_macs)
1058 str_appendf(buf,
1059 "<b>MAC Address:</b> "
1060 "<tt>%x:%x:%x:%x:%x:%x</tt><br>\n",
1061 h->u.host.mac_addr[0],
1062 h->u.host.mac_addr[1],
1063 h->u.host.mac_addr[2],
1064 h->u.host.mac_addr[3],
1065 h->u.host.mac_addr[4],
1066 h->u.host.mac_addr[5]);
1067
1068 str_append(buf,
1069 "</p>\n"
1070 "<p>\n"
1071 "<b>Last seen:</b> ");
1072
1073 ls = h->u.host.lastseen;
1074 if (strftime(ls_when, sizeof(ls_when),
1075 "%Y-%m-%d %H:%M:%S %Z%z", localtime(&ls)) != 0)
1076 str_append(buf, ls_when);
1077
1078 if (h->u.host.lastseen <= now) {
1079 ls_len = length_of_time(now - h->u.host.lastseen);
1080 str_append(buf, " (");
1081 str_appendstr(buf, ls_len);
1082 str_free(ls_len);
1083 str_append(buf, " ago)");
1084 } else {
1085 str_append(buf, " (in the future, possible clock problem)");
1086 }
1087
1088 str_appendf(buf,
1089 "</p>\n"
1090 "<p>\n"
1091 " <b>In:</b> %'qu<br>\n"
1092 " <b>Out:</b> %'qu<br>\n"
1093 " <b>Total:</b> %'qu<br>\n"
1094 "</p>\n",
1095 h->in, h->out, h->total);
1096
1097 str_append(buf, "<h3>TCP ports</h3>\n");
1098 format_table(buf, h->u.host.ports_tcp, 0,TOTAL,0);
1099
1100 str_append(buf, "<h3>UDP ports</h3>\n");
1101 format_table(buf, h->u.host.ports_udp, 0,TOTAL,0);
1102
1103 str_append(buf, "<h3>IP protocols</h3>\n");
1104 format_table(buf, h->u.host.ip_protos, 0,TOTAL,0);
1105
1106 html_close(buf);
1107 return (buf);
1108 }
1109
1110 /* ---------------------------------------------------------------------------
1111 * Database import and export code:
1112 * Initially written and contributed by Ben Stewart.
1113 * copyright (c) 2007-2011 Ben Stewart, Emil Mikulic.
1114 */
1115 static int hosts_db_export_ip(const struct hashtable *h, const int fd);
1116 static int hosts_db_export_tcp(const struct hashtable *h, const int fd);
1117 static int hosts_db_export_udp(const struct hashtable *h, const int fd);
1118
1119 static const char
1120 export_proto_ip = 'P',
1121 export_proto_tcp = 'T',
1122 export_proto_udp = 'U';
1123
1124 static const unsigned char
1125 export_tag_host_ver1[] = {'H', 'S', 'T', 0x01},
1126 export_tag_host_ver2[] = {'H', 'S', 'T', 0x02},
1127 export_tag_host_ver3[] = {'H', 'S', 'T', 0x03};
1128
1129 /* ---------------------------------------------------------------------------
1130 * Load a host's ip_proto table from a file.
1131 * Returns 0 on failure, 1 on success.
1132 */
1133 static int
1134 hosts_db_import_ip(const int fd, struct bucket *host)
1135 {
1136 uint8_t count, i;
1137
1138 if (!expect8(fd, export_proto_ip)) return 0;
1139 if (!read8(fd, &count)) return 0;
1140
1141 for (i=0; i<count; i++) {
1142 struct bucket *b;
1143 uint8_t proto;
1144 uint64_t in, out;
1145
1146 if (!read8(fd, &proto)) return 0;
1147 if (!read64(fd, &in)) return 0;
1148 if (!read64(fd, &out)) return 0;
1149
1150 /* Store data */
1151 b = host_get_ip_proto(host, proto);
1152 b->in = in;
1153 b->out = out;
1154 b->total = in + out;
1155 assert(b->u.ip_proto.proto == proto); /* should be done by make fn */
1156 }
1157 return 1;
1158 }
1159
1160 /* ---------------------------------------------------------------------------
1161 * Load a host's port_tcp table from a file.
1162 * Returns 0 on failure, 1 on success.
1163 */
1164 static int
1165 hosts_db_import_tcp(const int fd, struct bucket *host)
1166 {
1167 uint16_t count, i;
1168
1169 if (!expect8(fd, export_proto_tcp)) return 0;
1170 if (!read16(fd, &count)) return 0;
1171
1172 for (i=0; i<count; i++) {
1173 struct bucket *b;
1174 uint16_t port;
1175 uint64_t in, out, syn;
1176
1177 if (!read16(fd, &port)) return 0;
1178 if (!read64(fd, &syn)) return 0;
1179 if (!read64(fd, &in)) return 0;
1180 if (!read64(fd, &out)) return 0;
1181
1182 /* Store data */
1183 b = host_get_port_tcp(host, port);
1184 b->in = in;
1185 b->out = out;
1186 b->total = in + out;
1187 assert(b->u.port_tcp.port == port); /* done by make_func_port_tcp */
1188 b->u.port_tcp.syn = syn;
1189 }
1190 return 1;
1191 }
1192
1193 /* ---------------------------------------------------------------------------
1194 * Load a host's port_tcp table from a file.
1195 * Returns 0 on failure, 1 on success.
1196 */
1197 static int
1198 hosts_db_import_udp(const int fd, struct bucket *host)
1199 {
1200 uint16_t count, i;
1201
1202 if (!expect8(fd, export_proto_udp)) return 0;
1203 if (!read16(fd, &count)) return 0;
1204
1205 for (i=0; i<count; i++) {
1206 struct bucket *b;
1207 uint16_t port;
1208 uint64_t in, out;
1209
1210 if (!read16(fd, &port)) return 0;
1211 if (!read64(fd, &in)) return 0;
1212 if (!read64(fd, &out)) return 0;
1213
1214 /* Store data */
1215 b = host_get_port_udp(host, port);
1216 b->in = in;
1217 b->out = out;
1218 b->total = in + out;
1219 assert(b->u.port_udp.port == port); /* done by make_func */
1220 }
1221 return 1;
1222 }
1223
1224 /* ---------------------------------------------------------------------------
1225 * Load all hosts from a file.
1226 * Returns 0 on failure, 1 on success.
1227 */
1228 static int
1229 hosts_db_import_host(const int fd)
1230 {
1231 struct bucket *host;
1232 struct addr a;
1233 uint8_t hostname_len;
1234 uint64_t in, out;
1235 unsigned int pos = xtell(fd);
1236 char hdr[4];
1237 int ver = 0;
1238
1239 if (!readn(fd, hdr, sizeof(hdr))) return 0;
1240 if (memcmp(hdr, export_tag_host_ver3, sizeof(hdr)) == 0)
1241 ver = 3;
1242 else if (memcmp(hdr, export_tag_host_ver2, sizeof(hdr)) == 0)
1243 ver = 2;
1244 else if (memcmp(hdr, export_tag_host_ver1, sizeof(hdr)) == 0)
1245 ver = 1;
1246 else {
1247 warnx("bad host header: %02x%02x%02x%02x",
1248 hdr[0], hdr[1], hdr[2], hdr[3]);
1249 return 0;
1250 }
1251
1252 if (ver == 3) {
1253 if (!readaddr(fd, &a))
1254 return 0;
1255 } else {
1256 assert((ver == 1) || (ver == 2));
1257 if (!readaddr_ipv4(fd, &a))
1258 return 0;
1259 }
1260 verbosef("at file pos %u, importing host %s", pos, addr_to_str(&a));
1261 host = host_get(&a);
1262 assert(addr_equal(&(host->u.host.addr), &a));
1263
1264 if (ver > 1) {
1265 uint64_t t;
1266 if (!read64(fd, &t)) return 0;
1267 host->u.host.lastseen = (time_t)t;
1268 }
1269
1270 assert(sizeof(host->u.host.mac_addr) == 6);
1271 if (!readn(fd, host->u.host.mac_addr, sizeof(host->u.host.mac_addr)))
1272 return 0;
1273
1274 /* HOSTNAME */
1275 assert(host->u.host.dns == NULL); /* make fn? */
1276 if (!read8(fd, &hostname_len)) return 0;
1277 if (hostname_len > 0) {
1278 host->u.host.dns = xmalloc(hostname_len + 1);
1279 host->u.host.dns[0] = '\0';
1280
1281 /* At this point, the hostname is attached to a host which is in our
1282 * hosts_db, so if we bail out due to an import error, this pointer
1283 * isn't lost and leaked, it can be cleaned up in hosts_db_{free,reset}
1284 */
1285
1286 if (!readn(fd, host->u.host.dns, hostname_len)) return 0;
1287 host->u.host.dns[hostname_len] = '\0';
1288 }
1289
1290 if (!read64(fd, &in)) return 0;
1291 if (!read64(fd, &out)) return 0;
1292
1293 host->in = in;
1294 host->out = out;
1295 host->total = in + out;
1296
1297 /* Host's port and proto subtables: */
1298 if (!hosts_db_import_ip(fd, host)) return 0;
1299 if (!hosts_db_import_tcp(fd, host)) return 0;
1300 if (!hosts_db_import_udp(fd, host)) return 0;
1301 return 1;
1302 }
1303
1304 /* ---------------------------------------------------------------------------
1305 * Database Import: Grab hosts_db from a file provided by the caller.
1306 *
1307 * This function will retrieve the data sans the header. We expect the caller
1308 * to have validated the header of the hosts_db segment, and left the file
1309 * sitting at the start of the data.
1310 */
1311 int hosts_db_import(const int fd)
1312 {
1313 uint32_t host_count, i;
1314
1315 if (!read32(fd, &host_count)) return 0;
1316
1317 for (i=0; i<host_count; i++)
1318 if (!hosts_db_import_host(fd)) return 0;
1319
1320 return 1;
1321 }
1322
1323 /* ---------------------------------------------------------------------------
1324 * Database Export: Dump hosts_db into a file provided by the caller.
1325 * The caller is responsible for writing out export_tag_hosts_ver1 first.
1326 */
1327 int hosts_db_export(const int fd)
1328 {
1329 uint32_t i;
1330 struct bucket *b;
1331
1332 if (!write32(fd, hosts_db->count)) return 0;
1333
1334 for (i = 0; i<hosts_db->size; i++)
1335 for (b = hosts_db->table[i]; b != NULL; b = b->next) {
1336 /* For each host: */
1337 if (!writen(fd, export_tag_host_ver3, sizeof(export_tag_host_ver3)))
1338 return 0;
1339
1340 if (!writeaddr(fd, &(b->u.host.addr))) return 0;
1341
1342 if (!write64(fd, (uint64_t)(b->u.host.lastseen))) return 0;
1343
1344 assert(sizeof(b->u.host.mac_addr) == 6);
1345 if (!writen(fd, b->u.host.mac_addr, sizeof(b->u.host.mac_addr)))
1346 return 0;
1347
1348 /* HOSTNAME */
1349 if (b->u.host.dns == NULL) {
1350 if (!write8(fd, 0)) return 0;
1351 } else {
1352 int dnslen = strlen(b->u.host.dns);
1353
1354 if (dnslen > 255) {
1355 warnx("found a very long hostname: \"%s\"\n"
1356 "wasn't expecting one longer than 255 chars (this one is %d)",
1357 b->u.host.dns, dnslen);
1358 dnslen = 255;
1359 }
1360
1361 if (!write8(fd, (uint8_t)dnslen)) return 0;
1362 if (!writen(fd, b->u.host.dns, dnslen)) return 0;
1363 }
1364
1365 if (!write64(fd, b->in)) return 0;
1366 if (!write64(fd, b->out)) return 0;
1367
1368 if (!hosts_db_export_ip(b->u.host.ip_protos, fd)) return 0;
1369 if (!hosts_db_export_tcp(b->u.host.ports_tcp, fd)) return 0;
1370 if (!hosts_db_export_udp(b->u.host.ports_udp, fd)) return 0;
1371 }
1372 return 1;
1373 }
1374
1375 /* ---------------------------------------------------------------------------
1376 * Dump the ip_proto table of a host.
1377 */
1378 static int
1379 hosts_db_export_ip(const struct hashtable *h, const int fd)
1380 {
1381 uint32_t i, written = 0;
1382 struct bucket *b;
1383
1384 /* IP DATA */
1385 if (!write8(fd, export_proto_ip)) return 0;
1386
1387 /* If no data, write a IP Proto count of 0 and we're done. */
1388 if (h == NULL) {
1389 if (!write8(fd, 0)) return 0;
1390 return 1;
1391 }
1392
1393 assert(h->count < 256);
1394 if (!write8(fd, (uint8_t)h->count)) return 0;
1395
1396 for (i = 0; i<h->size; i++)
1397 for (b = h->table[i]; b != NULL; b = b->next) {
1398 /* For each ip_proto bucket: */
1399
1400 if (!write8(fd, b->u.ip_proto.proto)) return 0;
1401 if (!write64(fd, b->in)) return 0;
1402 if (!write64(fd, b->out)) return 0;
1403 written++;
1404 }
1405 assert(written == h->count);
1406 return 1;
1407 }
1408
1409 /* ---------------------------------------------------------------------------
1410 * Dump the port_tcp table of a host.
1411 */
1412 static int
1413 hosts_db_export_tcp(const struct hashtable *h, const int fd)
1414 {
1415 struct bucket *b;
1416 uint32_t i, written = 0;
1417
1418 /* TCP DATA */
1419 if (!write8(fd, export_proto_tcp)) return 0;
1420
1421 /* If no data, write a count of 0 and we're done. */
1422 if (h == NULL) {
1423 if (!write16(fd, 0)) return 0;
1424 return 1;
1425 }
1426
1427 assert(h->count < 65536);
1428 if (!write16(fd, (uint16_t)h->count)) return 0;
1429
1430 for (i = 0; i<h->size; i++)
1431 for (b = h->table[i]; b != NULL; b = b->next) {
1432 if (!write16(fd, b->u.port_tcp.port)) return 0;
1433 if (!write64(fd, b->u.port_tcp.syn)) return 0;
1434 if (!write64(fd, b->in)) return 0;
1435 if (!write64(fd, b->out)) return 0;
1436 written++;
1437 }
1438 assert(written == h->count);
1439 return 1;
1440 }
1441
1442 /* ---------------------------------------------------------------------------
1443 * Dump the port_udp table of a host.
1444 */
1445 static int
1446 hosts_db_export_udp(const struct hashtable *h, const int fd)
1447 {
1448 struct bucket *b;
1449 uint32_t i, written = 0;
1450
1451 /* UDP DATA */
1452 if (!write8(fd, export_proto_udp)) return 0;
1453
1454 /* If no data, write a count of 0 and we're done. */
1455 if (h == NULL) {
1456 if (!write16(fd, 0)) return 0;
1457 return 1;
1458 }
1459
1460 assert(h->count < 65536);
1461 if (!write16(fd, (uint16_t)h->count)) return 0;
1462
1463 for (i = 0; i<h->size; i++)
1464 for (b = h->table[i]; b != NULL; b = b->next) {
1465 if (!write16(fd, b->u.port_udp.port)) return 0;
1466 if (!write64(fd, b->in)) return 0;
1467 if (!write64(fd, b->out)) return 0;
1468 written++;
1469 }
1470 assert(written == h->count);
1471 return 1;
1472 }
1473
1474 /* vim:set ts=3 sw=3 tw=78 expandtab: */