2 * copyright (c) 2001-2011 Emil Mikulic.
4 * hosts_db.c: database of hosts, ports, protocols.
6 * You may use, modify and redistribute this file under the terms of the
7 * GNU General Public License version 2. (see COPYING.GPL)
23 #include <netdb.h> /* struct addrinfo */
28 #include <string.h> /* memset(), strcmp() */
31 int hosts_db_show_macs
= 0;
33 /* FIXME: specify somewhere more sane/tunable */
34 #define MAX_ENTRIES 30 /* in an HTML table rendered from a hashtable */
36 typedef uint32_t (hash_func_t
)(const struct hashtable
*, const void *);
37 typedef void (free_func_t
)(struct bucket
*);
38 typedef const void * (key_func_t
)(const struct bucket
*);
39 typedef int (find_func_t
)(const struct bucket
*, const void *);
40 typedef struct bucket
* (make_func_t
)(const void *);
41 typedef void (format_cols_func_t
)(struct str
*);
42 typedef void (format_row_func_t
)(struct str
*, const struct bucket
*,
46 uint8_t bits
; /* size of hashtable in bits */
48 uint32_t count
, count_max
, count_keep
; /* items in table */
49 uint32_t coeff
; /* coefficient for Fibonacci hashing */
50 struct bucket
**table
;
53 uint64_t inserts
, searches
, deletions
, rehashes
;
56 hash_func_t
*hash_func
;
57 /* returns hash value of given key (passed as void*) */
59 free_func_t
*free_func
;
60 /* free of bucket payload */
63 /* returns pointer to key of bucket (to pass to hash_func) */
65 find_func_t
*find_func
;
66 /* returns true if given bucket matches key (passed as void*) */
68 make_func_t
*make_func
;
69 /* returns bucket containing new record with key (passed as void*) */
71 format_cols_func_t
*format_cols_func
;
72 /* append table columns to str */
74 format_row_func_t
*format_row_func
;
75 /* format record and append to str */
78 static void hashtable_reduce(struct hashtable
*ht
);
79 static void hashtable_free(struct hashtable
*h
);
81 #define HOST_BITS 1 /* initial size of hosts table */
82 #define PORT_BITS 1 /* initial size of ports tables */
83 #define PROTO_BITS 1 /* initial size of proto table */
85 /* We only use one hosts_db hashtable and this is it. */
86 static struct hashtable
*hosts_db
= NULL
;
88 /* phi^-1 (reciprocal of golden ratio) = (sqrt(5) - 1) / 2 */
89 static const double phi_1
=
90 0.61803398874989490252573887119069695472717285156250;
92 /* Co-prime of u, using phi^-1 */
93 inline static uint32_t
94 coprime(const uint32_t u
)
96 return ( (uint32_t)( (double)(u
) * phi_1
) | 1U );
100 * This is the "recommended" IPv4 hash function, as seen in FreeBSD's
101 * src/sys/netinet/tcp_hostcache.c 1.1
103 inline static uint32_t
104 ipv4_hash(const struct addr
*const a
)
106 uint32_t ip
= a
->ip
.v4
;
107 return ( (ip
) ^ ((ip
) >> 7) ^ ((ip
) >> 17) );
113 * http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/netinet/in.h#130
115 # define s6_addr32 _S6_un._S6_u32
117 /* Covers OpenBSD and FreeBSD. The macro __USE_GNU has
118 * taken care of GNU/Linux and GNU/kfreebsd. */
119 # define s6_addr32 __u6_addr.__u6_addr32
124 * This is the IPv6 hash function used by FreeBSD in the same file as above,
127 inline static uint32_t
128 ipv6_hash(const struct addr
*const a
)
130 const struct in6_addr
*const ip6
= &(a
->ip
.v6
);
131 return ( ip6
->s6_addr32
[0] ^ ip6
->s6_addr32
[1] ^
132 ip6
->s6_addr32
[2] ^ ip6
->s6_addr32
[3] );
135 /* ---------------------------------------------------------------------------
136 * hash_func collection
139 hash_func_host(const struct hashtable
*h _unused_
, const void *key
)
141 const struct addr
*a
= key
;
142 if (a
->family
== IPv4
)
143 return (ipv4_hash(a
));
145 assert(a
->family
== IPv6
);
146 return (ipv6_hash(a
));
150 #define CASTKEY(type) (*((const type *)key))
153 hash_func_short(const struct hashtable
*h
, const void *key
)
155 return (CASTKEY(uint16_t) * h
->coeff
);
159 hash_func_byte(const struct hashtable
*h
, const void *key
)
161 return (CASTKEY(uint8_t) * h
->coeff
);
164 /* ---------------------------------------------------------------------------
165 * key_func collection
169 key_func_host(const struct bucket
*b
)
171 return &(b
->u
.host
.addr
);
175 key_func_port_tcp(const struct bucket
*b
)
177 return &(b
->u
.port_tcp
.port
);
181 key_func_port_udp(const struct bucket
*b
)
183 return &(b
->u
.port_udp
.port
);
187 key_func_ip_proto(const struct bucket
*b
)
189 return &(b
->u
.ip_proto
.proto
);
192 /* ---------------------------------------------------------------------------
193 * find_func collection
197 find_func_host(const struct bucket
*b
, const void *key
)
199 return (addr_equal(key
, &(b
->u
.host
.addr
)));
203 find_func_port_tcp(const struct bucket
*b
, const void *key
)
205 return (b
->u
.port_tcp
.port
== CASTKEY(uint16_t));
209 find_func_port_udp(const struct bucket
*b
, const void *key
)
211 return (b
->u
.port_udp
.port
== CASTKEY(uint16_t));
215 find_func_ip_proto(const struct bucket
*b
, const void *key
)
217 return (b
->u
.ip_proto
.proto
== CASTKEY(uint8_t));
220 /* ---------------------------------------------------------------------------
221 * make_func collection
224 #define MAKE_BUCKET(name_bucket, name_content, type) struct { \
225 struct bucket *next; \
226 uint64_t in, out, total; \
227 union { struct type t; } u; } _custom_bucket; \
228 struct bucket *name_bucket = xcalloc(1, sizeof(_custom_bucket)); \
229 struct type *name_content = &(name_bucket->u.type); \
230 name_bucket->next = NULL; \
231 name_bucket->in = name_bucket->out = name_bucket->total = 0;
233 static struct bucket
*
234 make_func_host(const void *key
)
236 MAKE_BUCKET(b
, h
, host
);
237 h
->addr
= CASTKEY(struct addr
);
240 memset(&h
->mac_addr
, 0, sizeof(h
->mac_addr
));
248 free_func_host(struct bucket
*b
)
250 struct host
*h
= &(b
->u
.host
);
251 if (h
->dns
!= NULL
) free(h
->dns
);
252 hashtable_free(h
->ports_tcp
);
253 hashtable_free(h
->ports_udp
);
254 hashtable_free(h
->ip_protos
);
257 static struct bucket
*
258 make_func_port_tcp(const void *key
)
260 MAKE_BUCKET(b
, p
, port_tcp
);
261 p
->port
= CASTKEY(uint16_t);
266 static struct bucket
*
267 make_func_port_udp(const void *key
)
269 MAKE_BUCKET(b
, p
, port_udp
);
270 p
->port
= CASTKEY(uint16_t);
274 static struct bucket
*
275 make_func_ip_proto(const void *key
)
277 MAKE_BUCKET(b
, p
, ip_proto
);
278 p
->proto
= CASTKEY(uint8_t);
283 free_func_simple(struct bucket
*b _unused_
)
288 /* ---------------------------------------------------------------------------
289 * format_func collection (ordered by struct)
293 format_cols_host(struct str
*buf
)
295 /* FIXME: don't clobber parts of the query string
296 * specifically "full" and "start"
297 * when setting sort direction
303 " <th>Hostname</th>\n");
304 if (hosts_db_show_macs
) str_append(buf
,
305 " <th>MAC Address</th>\n");
307 " <th><a href=\"?sort=in\">In</a></th>\n"
308 " <th><a href=\"?sort=out\">Out</a></th>\n"
309 " <th><a href=\"?sort=total\">Total</a></th>\n");
310 if (opt_want_lastseen
) str_append(buf
,
311 " <th><a href=\"?sort=lastseen\">Last seen</a></th>\n");
317 format_row_host(struct str
*buf
, const struct bucket
*b
,
318 const char *css_class
)
320 const char *ip
= addr_to_str(&(b
->u
.host
.addr
));
323 "<tr class=\"%s\">\n"
324 " <td><a href=\"./%s/\">%s</a></td>\n"
328 (b
->u
.host
.dns
== NULL
) ? "" : b
->u
.host
.dns
);
330 if (hosts_db_show_macs
)
332 " <td><tt>%x:%x:%x:%x:%x:%x</tt></td>\n",
333 b
->u
.host
.mac_addr
[0],
334 b
->u
.host
.mac_addr
[1],
335 b
->u
.host
.mac_addr
[2],
336 b
->u
.host
.mac_addr
[3],
337 b
->u
.host
.mac_addr
[4],
338 b
->u
.host
.mac_addr
[5]);
341 " <td class=\"num\">%'qu</td>\n"
342 " <td class=\"num\">%'qu</td>\n"
343 " <td class=\"num\">%'qu</td>\n",
344 b
->in
, b
->out
, b
->total
);
346 if (opt_want_lastseen
) {
347 time_t last_t
= b
->u
.host
.lastseen
;
348 struct str
*last_str
= NULL
;
350 if ((now
>= last_t
) && (last_t
> 0))
351 last_str
= length_of_time(now
- last_t
);
354 " <td class=\"num\">");
355 if (last_str
== NULL
) {
357 str_append(buf
, "(never)");
359 str_append(buf
, "(clock error)");
361 str_appendstr(buf
, last_str
);
371 /* Only resolve hosts "on demand" */
372 if (b
->u
.host
.dns
== NULL
)
373 dns_queue(&(b
->u
.host
.addr
));
377 format_cols_port_tcp(struct str
*buf
)
383 " <th>Service</td>\n"
393 format_row_port_tcp(struct str
*buf
, const struct bucket
*b
,
394 const char *css_class
)
396 const struct port_tcp
*p
= &(b
->u
.port_tcp
);
399 "<tr class=\"%s\">\n"
400 " <td class=\"num\">%u</td>\n"
402 " <td class=\"num\">%'qu</td>\n"
403 " <td class=\"num\">%'qu</td>\n"
404 " <td class=\"num\">%'qu</td>\n"
405 " <td class=\"num\">%'qu</td>\n"
408 p
->port
, getservtcp(p
->port
), b
->in
, b
->out
, b
->total
, p
->syn
413 format_cols_port_udp(struct str
*buf
)
419 " <th>Service</td>\n"
428 format_row_port_udp(struct str
*buf
, const struct bucket
*b
,
429 const char *css_class
)
431 const struct port_udp
*p
= &(b
->u
.port_udp
);
434 "<tr class=\"%s\">\n"
435 " <td class=\"num\">%u</td>\n"
437 " <td class=\"num\">%'qu</td>\n"
438 " <td class=\"num\">%'qu</td>\n"
439 " <td class=\"num\">%'qu</td>\n"
442 p
->port
, getservudp(p
->port
), b
->in
, b
->out
, b
->total
447 format_cols_ip_proto(struct str
*buf
)
453 " <th>Protocol</td>\n"
462 format_row_ip_proto(struct str
*buf
, const struct bucket
*b
,
463 const char *css_class
)
465 const struct ip_proto
*p
= &(b
->u
.ip_proto
);
468 "<tr class=\"%s\">\n"
469 " <td class=\"num\">%u</td>\n"
471 " <td class=\"num\">%'qu</td>\n"
472 " <td class=\"num\">%'qu</td>\n"
473 " <td class=\"num\">%'qu</td>\n"
476 p
->proto
, getproto(p
->proto
),
477 b
->in
, b
->out
, b
->total
481 /* ---------------------------------------------------------------------------
482 * Initialise a hashtable.
484 static struct hashtable
*
485 hashtable_make(const uint8_t bits
,
486 const unsigned int count_max
,
487 const unsigned int count_keep
,
488 hash_func_t
*hash_func
,
489 free_func_t
*free_func
,
490 key_func_t
*key_func
,
491 find_func_t
*find_func
,
492 make_func_t
*make_func
,
493 format_cols_func_t
*format_cols_func
,
494 format_row_func_t
*format_row_func
)
496 struct hashtable
*hash
;
499 hash
= xmalloc(sizeof(*hash
));
501 hash
->count_max
= count_max
;
502 hash
->count_keep
= count_keep
;
503 hash
->size
= 1U << bits
;
504 hash
->mask
= hash
->size
- 1;
505 hash
->coeff
= coprime(hash
->size
);
506 hash
->hash_func
= hash_func
;
507 hash
->free_func
= free_func
;
508 hash
->key_func
= key_func
;
509 hash
->find_func
= find_func
;
510 hash
->make_func
= make_func
;
511 hash
->format_cols_func
= format_cols_func
;
512 hash
->format_row_func
= format_row_func
;
514 hash
->table
= xcalloc(hash
->size
, sizeof(*hash
->table
));
515 memset(&(hash
->stats
), 0, sizeof(hash
->stats
));
519 /* ---------------------------------------------------------------------------
520 * Initialise global hosts_db.
525 assert(hosts_db
== NULL
);
526 hosts_db
= hashtable_make(HOST_BITS
, opt_hosts_max
, opt_hosts_keep
,
527 hash_func_host
, free_func_host
, key_func_host
, find_func_host
,
528 make_func_host
, format_cols_host
, format_row_host
);
532 hashtable_rehash(struct hashtable
*h
, const uint8_t bits
)
534 struct bucket
**old_table
, **new_table
;
535 uint32_t i
, old_size
;
541 old_table
= h
->table
;
544 h
->size
= 1U << bits
;
545 h
->mask
= h
->size
- 1;
546 h
->coeff
= coprime(h
->size
);
547 new_table
= xcalloc(h
->size
, sizeof(*new_table
));
549 for (i
=0; i
<old_size
; i
++) {
550 struct bucket
*next
, *b
= old_table
[i
];
552 uint32_t pos
= h
->hash_func(h
, h
->key_func(b
)) & h
->mask
;
554 b
->next
= new_table
[pos
];
561 h
->table
= new_table
;
565 hashtable_insert(struct hashtable
*h
, struct bucket
*b
)
570 assert(b
->next
== NULL
);
572 /* Rehash on 80% occupancy */
573 if ((h
->count
> h
->size
) ||
574 ((h
->size
- h
->count
) < h
->size
/ 5))
575 hashtable_rehash(h
, h
->bits
+1);
577 pos
= h
->hash_func(h
, h
->key_func(b
)) & h
->mask
;
578 if (h
->table
[pos
] == NULL
)
581 /* Insert at top of chain. */
582 b
->next
= h
->table
[pos
];
589 /* Return bucket matching key, or NULL if no such entry. */
590 static struct bucket
*
591 hashtable_search(struct hashtable
*h
, const void *key
)
597 pos
= h
->hash_func(h
, key
) & h
->mask
;
600 if (h
->find_func(b
, key
))
608 typedef enum { NO_REDUCE
= 0, ALLOW_REDUCE
= 1 } reduce_bool
;
609 /* Search for a key. If it's not there, make and insert a bucket for it. */
610 static struct bucket
*
611 hashtable_find_or_insert(struct hashtable
*h
, const void *key
,
612 const reduce_bool allow_reduce
)
614 struct bucket
*b
= hashtable_search(h
, key
);
617 /* Not found, so insert after checking occupancy. */
618 if (allow_reduce
&& (h
->count
>= h
->count_max
))
620 b
= h
->make_func(key
);
621 hashtable_insert(h
, b
);
627 * Frees the hashtable and the buckets. The contents are assumed to be
628 * "simple" -- i.e. no "destructor" action is required beyond simply freeing
632 hashtable_free(struct hashtable
*h
)
638 for (i
=0; i
<h
->size
; i
++) {
639 struct bucket
*tmp
, *b
= h
->table
[i
];
651 /* ---------------------------------------------------------------------------
652 * Return existing host or insert a new one.
655 host_get(const struct addr
*const a
)
657 return (hashtable_find_or_insert(hosts_db
, a
, NO_REDUCE
));
660 /* ---------------------------------------------------------------------------
661 * Find host, returns NULL if not in DB.
664 host_find(const struct addr
*const a
)
666 return (hashtable_search(hosts_db
, a
));
669 /* ---------------------------------------------------------------------------
670 * Find host, returns NULL if not in DB.
672 static struct bucket
*
673 host_search(const char *ipstr
)
676 struct addrinfo hints
, *ai
;
678 memset(&hints
, 0, sizeof(hints
));
679 hints
.ai_family
= AF_UNSPEC
;
680 hints
.ai_flags
= AI_NUMERICHOST
;
682 if (getaddrinfo(ipstr
, NULL
, &hints
, &ai
))
683 return (NULL
); /* invalid addr */
685 if (ai
->ai_family
== AF_INET
) {
687 a
.ip
.v4
= ((const struct sockaddr_in
*)ai
->ai_addr
)->sin_addr
.s_addr
;
689 else if (ai
->ai_family
== AF_INET6
) {
692 ((struct sockaddr_in6
*)ai
->ai_addr
)->sin6_addr
.s6_addr
,
696 return (NULL
); /* unknown family */
700 verbosef("search(%s) turned into %s", ipstr
, addr_to_str(&a
));
701 return (hashtable_search(hosts_db
, &a
));
704 /* ---------------------------------------------------------------------------
705 * Reduce a hashtable to the top <keep> entries.
708 hashtable_reduce(struct hashtable
*ht
)
710 uint32_t i
, pos
, rmd
;
711 const struct bucket
**table
;
714 assert(ht
->count_keep
< ht
->count
);
716 /* Fill table with pointers to buckets in hashtable. */
717 table
= xcalloc(ht
->count
, sizeof(*table
));
718 for (pos
=0, i
=0; i
<ht
->size
; i
++) {
719 struct bucket
*b
= ht
->table
[i
];
725 assert(pos
== ht
->count
);
726 qsort_buckets(table
, ht
->count
, 0, ht
->count_keep
, TOTAL
);
727 cutoff
= table
[ht
->count_keep
]->total
;
730 /* Remove all elements with total <= cutoff. */
732 for (i
=0; i
<ht
->size
; i
++) {
733 struct bucket
*last
= NULL
, *next
, *b
= ht
->table
[i
];
736 if (b
->total
<= cutoff
) {
737 /* Remove this one. */
752 verbosef("hashtable_reduce: removed %u buckets, left %u",
754 hashtable_rehash(ht
, ht
->bits
); /* is this needed? */
757 /* Reduce hosts_db if needed. */
758 void hosts_db_reduce(void)
760 if (hosts_db
->count
>= hosts_db
->count_max
)
761 hashtable_reduce(hosts_db
);
764 /* ---------------------------------------------------------------------------
765 * Reset hosts_db to empty.
772 for (i
=0; i
<hosts_db
->size
; i
++) {
773 struct bucket
*next
, *b
= hosts_db
->table
[i
];
776 hosts_db
->free_func(b
);
780 hosts_db
->table
[i
] = NULL
;
782 verbosef("hosts_db reset to empty, freed %u hosts", hosts_db
->count
);
786 /* ---------------------------------------------------------------------------
787 * Deallocate hosts_db.
789 void hosts_db_free(void)
793 assert(hosts_db
!= NULL
);
794 for (i
=0; i
<hosts_db
->size
; i
++) {
795 struct bucket
*tmp
, *b
= hosts_db
->table
[i
];
799 hosts_db
->free_func(tmp
);
803 free(hosts_db
->table
);
808 /* ---------------------------------------------------------------------------
809 * Find or create a port_tcp inside a host.
812 host_get_port_tcp(struct bucket
*host
, const uint16_t port
)
814 struct host
*h
= &host
->u
.host
;
816 if (h
->ports_tcp
== NULL
)
817 h
->ports_tcp
= hashtable_make(PORT_BITS
, opt_ports_max
, opt_ports_keep
,
818 hash_func_short
, free_func_simple
, key_func_port_tcp
,
819 find_func_port_tcp
, make_func_port_tcp
,
820 format_cols_port_tcp
, format_row_port_tcp
);
821 return (hashtable_find_or_insert(h
->ports_tcp
, &port
, ALLOW_REDUCE
));
824 /* ---------------------------------------------------------------------------
825 * Find or create a port_udp inside a host.
828 host_get_port_udp(struct bucket
*host
, const uint16_t port
)
830 struct host
*h
= &host
->u
.host
;
832 if (h
->ports_udp
== NULL
)
833 h
->ports_udp
= hashtable_make(PORT_BITS
, opt_ports_max
, opt_ports_keep
,
834 hash_func_short
, free_func_simple
, key_func_port_udp
,
835 find_func_port_udp
, make_func_port_udp
,
836 format_cols_port_udp
, format_row_port_udp
);
837 return (hashtable_find_or_insert(h
->ports_udp
, &port
, ALLOW_REDUCE
));
840 /* ---------------------------------------------------------------------------
841 * Find or create an ip_proto inside a host.
844 host_get_ip_proto(struct bucket
*host
, const uint8_t proto
)
846 struct host
*h
= &host
->u
.host
;
847 static const unsigned int PROTOS_MAX
= 512, PROTOS_KEEP
= 256;
849 if (h
->ip_protos
== NULL
)
850 h
->ip_protos
= hashtable_make(PROTO_BITS
, PROTOS_MAX
, PROTOS_KEEP
,
851 hash_func_byte
, free_func_simple
, key_func_ip_proto
,
852 find_func_ip_proto
, make_func_ip_proto
,
853 format_cols_ip_proto
, format_row_ip_proto
);
854 return (hashtable_find_or_insert(h
->ip_protos
, &proto
, ALLOW_REDUCE
));
857 static struct str
*html_hosts_main(const char *qs
);
858 static struct str
*html_hosts_detail(const char *ip
);
860 /* ---------------------------------------------------------------------------
861 * Web interface: delegate the /hosts/ space.
864 html_hosts(const char *uri
, const char *query
)
866 unsigned int i
, num_elems
;
867 char **elem
= split('/', uri
, &num_elems
);
868 struct str
*buf
= NULL
;
870 assert(num_elems
>= 1);
871 assert(strcmp(elem
[0], "hosts") == 0);
875 buf
= html_hosts_main(query
);
876 else if (num_elems
== 2)
877 /* /hosts/<IP of host>/ */
878 buf
= html_hosts_detail(elem
[1]);
880 for (i
=0; i
<num_elems
; i
++)
883 return (buf
); /* FIXME: a NULL here becomes 404 Not Found, we might want
884 other codes to be possible */
887 /* ---------------------------------------------------------------------------
888 * Format hashtable into HTML.
891 format_table(struct str
*buf
, struct hashtable
*ht
, unsigned int start
,
892 const enum sort_dir sort
, const int full
)
894 const struct bucket
**table
;
895 unsigned int i
, pos
, end
;
898 if ((ht
== NULL
) || (ht
->count
== 0)) {
899 str_append(buf
, "<p>The table is empty.</p>\n");
903 /* Fill table with pointers to buckets in hashtable. */
904 table
= xcalloc(ht
->count
, sizeof(*table
));
905 for (pos
=0, i
=0; i
<ht
->size
; i
++) {
906 struct bucket
*b
= ht
->table
[i
];
912 assert(pos
== ht
->count
);
915 /* full report overrides start and end */
919 end
= MIN(ht
->count
, (uint32_t)start
+MAX_ENTRIES
);
921 str_appendf(buf
, "(%u-%u of %u)<br>\n", start
+1, end
, ht
->count
);
922 qsort_buckets(table
, ht
->count
, start
, end
, sort
);
923 ht
->format_cols_func(buf
);
925 for (i
=start
; i
<end
; i
++) {
926 ht
->format_row_func(buf
, table
[i
], alt
? "alt1" : "alt2");
927 alt
= !alt
; /* alternate class for table rows */
930 str_append(buf
, "</table>\n");
933 /* ---------------------------------------------------------------------------
934 * Web interface: sorted table of hosts.
937 html_hosts_main(const char *qs
)
939 struct str
*buf
= str_make();
940 char *qs_start
, *qs_sort
, *qs_full
, *ep
;
945 /* parse query string */
946 qs_start
= qs_get(qs
, "start");
947 qs_sort
= qs_get(qs
, "sort");
948 qs_full
= qs_get(qs
, "full");
949 if (qs_full
!= NULL
) {
955 if (qs_sort
== NULL
) sort
= TOTAL
;
956 else if (strcmp(qs_sort
, "total") == 0) sort
= TOTAL
;
957 else if (strcmp(qs_sort
, "in") == 0) sort
= IN
;
958 else if (strcmp(qs_sort
, "out") == 0) sort
= OUT
;
959 else if (strcmp(qs_sort
, "lastseen") == 0) sort
= LASTSEEN
;
961 str_append(buf
, "Error: invalid value for \"sort\".\n");
966 if (qs_start
== NULL
)
969 start
= (int)strtoul(qs_start
, &ep
, 10);
971 str_append(buf
, "Error: \"start\" is not a number.\n");
974 if ((errno
== ERANGE
) ||
975 (start
< 0) || (start
>= (int)hosts_db
->count
)) {
976 str_append(buf
, "Error: \"start\" is out of bounds.\n");
981 #define PREV "<<< prev page"
982 #define NEXT "next page >>>"
983 #define FULL "full table"
985 html_open(buf
, "Hosts", /*path_depth=*/1, /*want_graph_js=*/0);
986 format_table(buf
, hosts_db
, start
, sort
, full
);
988 /* <prev | full | stats | next> */
990 if (sortstr
== NULL
) sortstr
= "total";
992 int prev
= start
- MAX_ENTRIES
;
995 str_appendf(buf
, "<a href=\"?start=%d&sort=%s\">" PREV
"</a>",
998 str_append(buf
, PREV
);
1001 str_append(buf
, " | " FULL
);
1003 str_appendf(buf
, " | <a href=\"?full=yes&sort=%s\">" FULL
"</a>",
1006 if (start
+MAX_ENTRIES
< (int)hosts_db
->count
)
1007 str_appendf(buf
, " | <a href=\"?start=%d&sort=%s\">" NEXT
"</a>",
1008 start
+MAX_ENTRIES
, sortstr
);
1010 str_append(buf
, " | " NEXT
);
1012 str_append(buf
, "<br>\n");
1016 if (qs_start
!= NULL
) free(qs_start
);
1017 if (qs_sort
!= NULL
) free(qs_sort
);
1024 /* ---------------------------------------------------------------------------
1025 * Web interface: detailed view of a single host.
1028 html_hosts_detail(const char *ip
)
1031 struct str
*buf
, *ls_len
;
1033 const char *canonical
;
1036 h
= host_search(ip
);
1038 return (NULL
); /* no such host */
1040 canonical
= addr_to_str(&(h
->u
.host
.addr
));
1044 html_open(buf
, ip
, /*path_depth=*/2, /*want_graph_js=*/0);
1045 if (strcmp(ip
, canonical
) != 0)
1046 str_appendf(buf
, "(canonically <b>%s</b>)\n", canonical
);
1049 "<b>Hostname:</b> %s<br>\n",
1050 (h
->u
.host
.dns
== NULL
)?"(resolving...)":h
->u
.host
.dns
);
1052 /* Resolve host "on demand" */
1053 if (h
->u
.host
.dns
== NULL
)
1054 dns_queue(&(h
->u
.host
.addr
));
1056 if (hosts_db_show_macs
)
1058 "<b>MAC Address:</b> "
1059 "<tt>%x:%x:%x:%x:%x:%x</tt><br>\n",
1060 h
->u
.host
.mac_addr
[0],
1061 h
->u
.host
.mac_addr
[1],
1062 h
->u
.host
.mac_addr
[2],
1063 h
->u
.host
.mac_addr
[3],
1064 h
->u
.host
.mac_addr
[4],
1065 h
->u
.host
.mac_addr
[5]);
1070 "<b>Last seen:</b> ");
1072 ls
= h
->u
.host
.lastseen
;
1073 if (strftime(ls_when
, sizeof(ls_when
),
1074 "%Y-%m-%d %H:%M:%S %Z%z", localtime(&ls
)) != 0)
1075 str_append(buf
, ls_when
);
1077 if (h
->u
.host
.lastseen
<= now
) {
1078 ls_len
= length_of_time(now
- h
->u
.host
.lastseen
);
1079 str_append(buf
, " (");
1080 str_appendstr(buf
, ls_len
);
1082 str_append(buf
, " ago)");
1084 str_append(buf
, " (in the future, possible clock problem)");
1090 " <b>In:</b> %'qu<br>\n"
1091 " <b>Out:</b> %'qu<br>\n"
1092 " <b>Total:</b> %'qu<br>\n"
1094 h
->in
, h
->out
, h
->total
);
1096 str_append(buf
, "<h3>TCP ports</h3>\n");
1097 format_table(buf
, h
->u
.host
.ports_tcp
, 0,TOTAL
,0);
1099 str_append(buf
, "<h3>UDP ports</h3>\n");
1100 format_table(buf
, h
->u
.host
.ports_udp
, 0,TOTAL
,0);
1102 str_append(buf
, "<h3>IP protocols</h3>\n");
1103 format_table(buf
, h
->u
.host
.ip_protos
, 0,TOTAL
,0);
1109 /* ---------------------------------------------------------------------------
1110 * Database import and export code:
1111 * Initially written and contributed by Ben Stewart.
1112 * copyright (c) 2007-2011 Ben Stewart, Emil Mikulic.
1114 static int hosts_db_export_ip(const struct hashtable
*h
, const int fd
);
1115 static int hosts_db_export_tcp(const struct hashtable
*h
, const int fd
);
1116 static int hosts_db_export_udp(const struct hashtable
*h
, const int fd
);
1119 export_proto_ip
= 'P',
1120 export_proto_tcp
= 'T',
1121 export_proto_udp
= 'U';
1123 static const unsigned char
1124 export_tag_host_ver1
[] = {'H', 'S', 'T', 0x01},
1125 export_tag_host_ver2
[] = {'H', 'S', 'T', 0x02},
1126 export_tag_host_ver3
[] = {'H', 'S', 'T', 0x03};
1128 /* ---------------------------------------------------------------------------
1129 * Load a host's ip_proto table from a file.
1130 * Returns 0 on failure, 1 on success.
1133 hosts_db_import_ip(const int fd
, struct bucket
*host
)
1137 if (!expect8(fd
, export_proto_ip
)) return 0;
1138 if (!read8(fd
, &count
)) return 0;
1140 for (i
=0; i
<count
; i
++) {
1145 if (!read8(fd
, &proto
)) return 0;
1146 if (!read64(fd
, &in
)) return 0;
1147 if (!read64(fd
, &out
)) return 0;
1150 b
= host_get_ip_proto(host
, proto
);
1153 b
->total
= in
+ out
;
1154 assert(b
->u
.ip_proto
.proto
== proto
); /* should be done by make fn */
1159 /* ---------------------------------------------------------------------------
1160 * Load a host's port_tcp table from a file.
1161 * Returns 0 on failure, 1 on success.
1164 hosts_db_import_tcp(const int fd
, struct bucket
*host
)
1168 if (!expect8(fd
, export_proto_tcp
)) return 0;
1169 if (!read16(fd
, &count
)) return 0;
1171 for (i
=0; i
<count
; i
++) {
1174 uint64_t in
, out
, syn
;
1176 if (!read16(fd
, &port
)) return 0;
1177 if (!read64(fd
, &syn
)) return 0;
1178 if (!read64(fd
, &in
)) return 0;
1179 if (!read64(fd
, &out
)) return 0;
1182 b
= host_get_port_tcp(host
, port
);
1185 b
->total
= in
+ out
;
1186 assert(b
->u
.port_tcp
.port
== port
); /* done by make_func_port_tcp */
1187 b
->u
.port_tcp
.syn
= syn
;
1192 /* ---------------------------------------------------------------------------
1193 * Load a host's port_tcp table from a file.
1194 * Returns 0 on failure, 1 on success.
1197 hosts_db_import_udp(const int fd
, struct bucket
*host
)
1201 if (!expect8(fd
, export_proto_udp
)) return 0;
1202 if (!read16(fd
, &count
)) return 0;
1204 for (i
=0; i
<count
; i
++) {
1209 if (!read16(fd
, &port
)) return 0;
1210 if (!read64(fd
, &in
)) return 0;
1211 if (!read64(fd
, &out
)) return 0;
1214 b
= host_get_port_udp(host
, port
);
1217 b
->total
= in
+ out
;
1218 assert(b
->u
.port_udp
.port
== port
); /* done by make_func */
1223 /* ---------------------------------------------------------------------------
1224 * Load all hosts from a file.
1225 * Returns 0 on failure, 1 on success.
1228 hosts_db_import_host(const int fd
)
1230 struct bucket
*host
;
1232 uint8_t hostname_len
;
1234 unsigned int pos
= xtell(fd
);
1238 if (!readn(fd
, hdr
, sizeof(hdr
))) return 0;
1239 if (memcmp(hdr
, export_tag_host_ver3
, sizeof(hdr
)) == 0)
1241 else if (memcmp(hdr
, export_tag_host_ver2
, sizeof(hdr
)) == 0)
1243 else if (memcmp(hdr
, export_tag_host_ver1
, sizeof(hdr
)) == 0)
1246 warnx("bad host header: %02x%02x%02x%02x",
1247 hdr
[0], hdr
[1], hdr
[2], hdr
[3]);
1252 if (!readaddr(fd
, &a
))
1255 assert((ver
== 1) || (ver
== 2));
1256 if (!readaddr_ipv4(fd
, &a
))
1259 verbosef("at file pos %u, importing host %s", pos
, addr_to_str(&a
));
1260 host
= host_get(&a
);
1261 assert(addr_equal(&(host
->u
.host
.addr
), &a
));
1265 if (!read64(fd
, &t
)) return 0;
1266 host
->u
.host
.lastseen
= (time_t)t
;
1269 assert(sizeof(host
->u
.host
.mac_addr
) == 6);
1270 if (!readn(fd
, host
->u
.host
.mac_addr
, sizeof(host
->u
.host
.mac_addr
)))
1274 assert(host
->u
.host
.dns
== NULL
); /* make fn? */
1275 if (!read8(fd
, &hostname_len
)) return 0;
1276 if (hostname_len
> 0) {
1277 host
->u
.host
.dns
= xmalloc(hostname_len
+ 1);
1278 host
->u
.host
.dns
[0] = '\0';
1280 /* At this point, the hostname is attached to a host which is in our
1281 * hosts_db, so if we bail out due to an import error, this pointer
1282 * isn't lost and leaked, it can be cleaned up in hosts_db_{free,reset}
1285 if (!readn(fd
, host
->u
.host
.dns
, hostname_len
)) return 0;
1286 host
->u
.host
.dns
[hostname_len
] = '\0';
1289 if (!read64(fd
, &in
)) return 0;
1290 if (!read64(fd
, &out
)) return 0;
1294 host
->total
= in
+ out
;
1296 /* Host's port and proto subtables: */
1297 if (!hosts_db_import_ip(fd
, host
)) return 0;
1298 if (!hosts_db_import_tcp(fd
, host
)) return 0;
1299 if (!hosts_db_import_udp(fd
, host
)) return 0;
1303 /* ---------------------------------------------------------------------------
1304 * Database Import: Grab hosts_db from a file provided by the caller.
1306 * This function will retrieve the data sans the header. We expect the caller
1307 * to have validated the header of the hosts_db segment, and left the file
1308 * sitting at the start of the data.
1310 int hosts_db_import(const int fd
)
1312 uint32_t host_count
, i
;
1314 if (!read32(fd
, &host_count
)) return 0;
1316 for (i
=0; i
<host_count
; i
++)
1317 if (!hosts_db_import_host(fd
)) return 0;
1322 /* ---------------------------------------------------------------------------
1323 * Database Export: Dump hosts_db into a file provided by the caller.
1324 * The caller is responsible for writing out export_tag_hosts_ver1 first.
1326 int hosts_db_export(const int fd
)
1331 if (!write32(fd
, hosts_db
->count
)) return 0;
1333 for (i
= 0; i
<hosts_db
->size
; i
++)
1334 for (b
= hosts_db
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1335 /* For each host: */
1336 if (!writen(fd
, export_tag_host_ver3
, sizeof(export_tag_host_ver3
)))
1339 if (!writeaddr(fd
, &(b
->u
.host
.addr
))) return 0;
1341 if (!write64(fd
, (uint64_t)(b
->u
.host
.lastseen
))) return 0;
1343 assert(sizeof(b
->u
.host
.mac_addr
) == 6);
1344 if (!writen(fd
, b
->u
.host
.mac_addr
, sizeof(b
->u
.host
.mac_addr
)))
1348 if (b
->u
.host
.dns
== NULL
) {
1349 if (!write8(fd
, 0)) return 0;
1351 int dnslen
= strlen(b
->u
.host
.dns
);
1354 warnx("found a very long hostname: \"%s\"\n"
1355 "wasn't expecting one longer than 255 chars (this one is %d)",
1356 b
->u
.host
.dns
, dnslen
);
1360 if (!write8(fd
, (uint8_t)dnslen
)) return 0;
1361 if (!writen(fd
, b
->u
.host
.dns
, dnslen
)) return 0;
1364 if (!write64(fd
, b
->in
)) return 0;
1365 if (!write64(fd
, b
->out
)) return 0;
1367 if (!hosts_db_export_ip(b
->u
.host
.ip_protos
, fd
)) return 0;
1368 if (!hosts_db_export_tcp(b
->u
.host
.ports_tcp
, fd
)) return 0;
1369 if (!hosts_db_export_udp(b
->u
.host
.ports_udp
, fd
)) return 0;
1374 /* ---------------------------------------------------------------------------
1375 * Dump the ip_proto table of a host.
1378 hosts_db_export_ip(const struct hashtable
*h
, const int fd
)
1380 uint32_t i
, written
= 0;
1384 if (!write8(fd
, export_proto_ip
)) return 0;
1386 /* If no data, write a IP Proto count of 0 and we're done. */
1388 if (!write8(fd
, 0)) return 0;
1392 assert(h
->count
< 256);
1393 if (!write8(fd
, (uint8_t)h
->count
)) return 0;
1395 for (i
= 0; i
<h
->size
; i
++)
1396 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1397 /* For each ip_proto bucket: */
1399 if (!write8(fd
, b
->u
.ip_proto
.proto
)) return 0;
1400 if (!write64(fd
, b
->in
)) return 0;
1401 if (!write64(fd
, b
->out
)) return 0;
1404 assert(written
== h
->count
);
1408 /* ---------------------------------------------------------------------------
1409 * Dump the port_tcp table of a host.
1412 hosts_db_export_tcp(const struct hashtable
*h
, const int fd
)
1415 uint32_t i
, written
= 0;
1418 if (!write8(fd
, export_proto_tcp
)) return 0;
1420 /* If no data, write a count of 0 and we're done. */
1422 if (!write16(fd
, 0)) return 0;
1426 assert(h
->count
< 65536);
1427 if (!write16(fd
, (uint16_t)h
->count
)) return 0;
1429 for (i
= 0; i
<h
->size
; i
++)
1430 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1431 if (!write16(fd
, b
->u
.port_tcp
.port
)) return 0;
1432 if (!write64(fd
, b
->u
.port_tcp
.syn
)) return 0;
1433 if (!write64(fd
, b
->in
)) return 0;
1434 if (!write64(fd
, b
->out
)) return 0;
1437 assert(written
== h
->count
);
1441 /* ---------------------------------------------------------------------------
1442 * Dump the port_udp table of a host.
1445 hosts_db_export_udp(const struct hashtable
*h
, const int fd
)
1448 uint32_t i
, written
= 0;
1451 if (!write8(fd
, export_proto_udp
)) return 0;
1453 /* If no data, write a count of 0 and we're done. */
1455 if (!write16(fd
, 0)) return 0;
1459 assert(h
->count
< 65536);
1460 if (!write16(fd
, (uint16_t)h
->count
)) return 0;
1462 for (i
= 0; i
<h
->size
; i
++)
1463 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1464 if (!write16(fd
, b
->u
.port_udp
.port
)) return 0;
1465 if (!write64(fd
, b
->in
)) return 0;
1466 if (!write64(fd
, b
->out
)) return 0;
1469 assert(written
== h
->count
);
1473 /* vim:set ts=3 sw=3 tw=78 expandtab: */