2 * copyright (c) 2001-2014 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() */
32 int hosts_db_show_macs
= 0;
34 /* FIXME: specify somewhere more sane/tunable */
35 #define MAX_ENTRIES 30 /* in an HTML table rendered from a hashtable */
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
*,
47 uint8_t bits
; /* size of hashtable in bits */
49 uint32_t count
, count_max
, count_keep
; /* items in table */
50 uint32_t coeff
; /* coefficient for Fibonacci hashing */
51 struct bucket
**table
;
54 uint64_t inserts
, searches
, deletions
, rehashes
;
57 hash_func_t
*hash_func
;
58 /* returns hash value of given key (passed as void*) */
60 free_func_t
*free_func
;
61 /* free of bucket payload */
64 /* returns pointer to key of bucket (to pass to hash_func) */
66 find_func_t
*find_func
;
67 /* returns true if given bucket matches key (passed as void*) */
69 make_func_t
*make_func
;
70 /* returns bucket containing new record with key (passed as void*) */
72 format_cols_func_t
*format_cols_func
;
73 /* append table columns to str */
75 format_row_func_t
*format_row_func
;
76 /* format record and append to str */
79 static void hashtable_reduce(struct hashtable
*ht
);
80 static void hashtable_free(struct hashtable
*h
);
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 */
86 /* We only use one hosts_db hashtable and this is it. */
87 static struct hashtable
*hosts_db
= NULL
;
89 /* phi^-1 (reciprocal of golden ratio) = (sqrt(5) - 1) / 2 */
90 static const double phi_1
=
91 0.61803398874989490252573887119069695472717285156250;
93 /* Co-prime of u, using phi^-1 */
94 inline static uint32_t
95 coprime(const uint32_t u
)
97 return ( (uint32_t)( (double)(u
) * phi_1
) | 1U );
101 * This is the "recommended" IPv4 hash function, as seen in FreeBSD's
102 * src/sys/netinet/tcp_hostcache.c 1.1
104 inline static uint32_t
105 ipv4_hash(const struct addr
*const a
)
107 uint32_t ip
= a
->ip
.v4
;
108 return ( (ip
) ^ ((ip
) >> 7) ^ ((ip
) >> 17) );
114 * http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/netinet/in.h#130
116 # define s6_addr32 _S6_un._S6_u32
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
125 * This is the IPv6 hash function used by FreeBSD in the same file as above,
128 inline static uint32_t
129 ipv6_hash(const struct addr
*const a
)
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] );
136 /* ---------------------------------------------------------------------------
137 * hash_func collection
140 hash_func_host(const struct hashtable
*h _unused_
, const void *key
)
142 const struct addr
*a
= key
;
143 if (a
->family
== IPv4
)
144 return (ipv4_hash(a
));
146 assert(a
->family
== IPv6
);
147 return (ipv6_hash(a
));
151 #define CASTKEY(type) (*((const type *)key))
154 hash_func_short(const struct hashtable
*h
, const void *key
)
156 return (CASTKEY(uint16_t) * h
->coeff
);
160 hash_func_byte(const struct hashtable
*h
, const void *key
)
162 return (CASTKEY(uint8_t) * h
->coeff
);
165 /* ---------------------------------------------------------------------------
166 * key_func collection
170 key_func_host(const struct bucket
*b
)
172 return &(b
->u
.host
.addr
);
176 key_func_port_tcp(const struct bucket
*b
)
178 return &(b
->u
.port_tcp
.port
);
182 key_func_port_udp(const struct bucket
*b
)
184 return &(b
->u
.port_udp
.port
);
188 key_func_ip_proto(const struct bucket
*b
)
190 return &(b
->u
.ip_proto
.proto
);
193 /* ---------------------------------------------------------------------------
194 * find_func collection
198 find_func_host(const struct bucket
*b
, const void *key
)
200 return (addr_equal(key
, &(b
->u
.host
.addr
)));
204 find_func_port_tcp(const struct bucket
*b
, const void *key
)
206 return (b
->u
.port_tcp
.port
== CASTKEY(uint16_t));
210 find_func_port_udp(const struct bucket
*b
, const void *key
)
212 return (b
->u
.port_udp
.port
== CASTKEY(uint16_t));
216 find_func_ip_proto(const struct bucket
*b
, const void *key
)
218 return (b
->u
.ip_proto
.proto
== CASTKEY(uint8_t));
221 /* ---------------------------------------------------------------------------
222 * make_func collection
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;
234 static struct bucket
*
235 make_func_host(const void *key
)
237 MAKE_BUCKET(b
, h
, host
);
238 h
->addr
= CASTKEY(struct addr
);
240 h
->last_seen_mono
= 0;
241 memset(&h
->mac_addr
, 0, sizeof(h
->mac_addr
));
249 free_func_host(struct bucket
*b
)
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
);
258 static struct bucket
*
259 make_func_port_tcp(const void *key
)
261 MAKE_BUCKET(b
, p
, port_tcp
);
262 p
->port
= CASTKEY(uint16_t);
267 static struct bucket
*
268 make_func_port_udp(const void *key
)
270 MAKE_BUCKET(b
, p
, port_udp
);
271 p
->port
= CASTKEY(uint16_t);
275 static struct bucket
*
276 make_func_ip_proto(const void *key
)
278 MAKE_BUCKET(b
, p
, ip_proto
);
279 p
->proto
= CASTKEY(uint8_t);
284 free_func_simple(struct bucket
*b _unused_
)
289 /* ---------------------------------------------------------------------------
290 * format_func collection (ordered by struct)
294 format_cols_host(struct str
*buf
)
296 /* FIXME: don't clobber parts of the query string
297 * specifically "full" and "start"
298 * when setting sort direction
304 " <th>Hostname</th>\n");
305 if (hosts_db_show_macs
) str_append(buf
,
306 " <th>MAC Address</th>\n");
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");
318 format_row_host(struct str
*buf
, const struct bucket
*b
,
319 const char *css_class
)
321 const char *ip
= addr_to_str(&(b
->u
.host
.addr
));
324 "<tr class=\"%s\">\n"
325 " <td><a href=\"./%s/\">%s</a></td>\n"
329 (b
->u
.host
.dns
== NULL
) ? "" : b
->u
.host
.dns
);
331 if (hosts_db_show_macs
)
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]);
342 " <td class=\"num\">%'qu</td>\n"
343 " <td class=\"num\">%'qu</td>\n"
344 " <td class=\"num\">%'qu</td>\n",
349 if (opt_want_lastseen
) {
350 time_t last
= b
->u
.host
.last_seen_mono
;
351 struct str
*last_str
= NULL
;
353 if ((now_mono() >= last
) && (last
> 0))
354 last_str
= length_of_time(now_mono() - last
);
356 str_append(buf
, " <td class=\"num\">");
357 if (last_str
== NULL
) {
359 str_append(buf
, "(never)");
361 str_appendf(buf
, "(clock error: now = %qu, last = %qu)",
365 str_appendstr(buf
, last_str
);
368 str_append(buf
, "</td>");
371 str_appendf(buf
, "</tr>\n");
373 /* Only resolve hosts "on demand" */
374 if (b
->u
.host
.dns
== NULL
)
375 dns_queue(&(b
->u
.host
.addr
));
379 format_cols_port_tcp(struct str
*buf
)
385 " <th>Service</td>\n"
395 format_row_port_tcp(struct str
*buf
, const struct bucket
*b
,
396 const char *css_class
)
398 const struct port_tcp
*p
= &(b
->u
.port_tcp
);
401 "<tr class=\"%s\">\n"
402 " <td class=\"num\">%u</td>\n"
404 " <td class=\"num\">%'qu</td>\n"
405 " <td class=\"num\">%'qu</td>\n"
406 " <td class=\"num\">%'qu</td>\n"
407 " <td class=\"num\">%'qu</td>\n"
420 format_cols_port_udp(struct str
*buf
)
426 " <th>Service</td>\n"
435 format_row_port_udp(struct str
*buf
, const struct bucket
*b
,
436 const char *css_class
)
438 const struct port_udp
*p
= &(b
->u
.port_udp
);
441 "<tr class=\"%s\">\n"
442 " <td class=\"num\">%u</td>\n"
444 " <td class=\"num\">%'qu</td>\n"
445 " <td class=\"num\">%'qu</td>\n"
446 " <td class=\"num\">%'qu</td>\n"
458 format_cols_ip_proto(struct str
*buf
)
464 " <th>Protocol</td>\n"
473 format_row_ip_proto(struct str
*buf
, const struct bucket
*b
,
474 const char *css_class
)
476 const struct ip_proto
*p
= &(b
->u
.ip_proto
);
479 "<tr class=\"%s\">\n"
480 " <td class=\"num\">%u</td>\n"
482 " <td class=\"num\">%'qu</td>\n"
483 " <td class=\"num\">%'qu</td>\n"
484 " <td class=\"num\">%'qu</td>\n"
495 /* ---------------------------------------------------------------------------
496 * Initialise a hashtable.
498 static struct hashtable
*
499 hashtable_make(const uint8_t bits
,
500 const unsigned int count_max
,
501 const unsigned int count_keep
,
502 hash_func_t
*hash_func
,
503 free_func_t
*free_func
,
504 key_func_t
*key_func
,
505 find_func_t
*find_func
,
506 make_func_t
*make_func
,
507 format_cols_func_t
*format_cols_func
,
508 format_row_func_t
*format_row_func
)
510 struct hashtable
*hash
;
513 hash
= xmalloc(sizeof(*hash
));
515 hash
->count_max
= count_max
;
516 hash
->count_keep
= count_keep
;
517 hash
->size
= 1U << bits
;
518 hash
->mask
= hash
->size
- 1;
519 hash
->coeff
= coprime(hash
->size
);
520 hash
->hash_func
= hash_func
;
521 hash
->free_func
= free_func
;
522 hash
->key_func
= key_func
;
523 hash
->find_func
= find_func
;
524 hash
->make_func
= make_func
;
525 hash
->format_cols_func
= format_cols_func
;
526 hash
->format_row_func
= format_row_func
;
528 hash
->table
= xcalloc(hash
->size
, sizeof(*hash
->table
));
529 memset(&(hash
->stats
), 0, sizeof(hash
->stats
));
533 /* ---------------------------------------------------------------------------
534 * Initialise global hosts_db.
539 assert(hosts_db
== NULL
);
540 hosts_db
= hashtable_make(HOST_BITS
, opt_hosts_max
, opt_hosts_keep
,
541 hash_func_host
, free_func_host
, key_func_host
, find_func_host
,
542 make_func_host
, format_cols_host
, format_row_host
);
546 hashtable_rehash(struct hashtable
*h
, const uint8_t bits
)
548 struct bucket
**old_table
, **new_table
;
549 uint32_t i
, old_size
;
555 old_table
= h
->table
;
558 h
->size
= 1U << bits
;
559 h
->mask
= h
->size
- 1;
560 h
->coeff
= coprime(h
->size
);
561 new_table
= xcalloc(h
->size
, sizeof(*new_table
));
563 for (i
=0; i
<old_size
; i
++) {
564 struct bucket
*next
, *b
= old_table
[i
];
566 uint32_t pos
= h
->hash_func(h
, h
->key_func(b
)) & h
->mask
;
568 b
->next
= new_table
[pos
];
575 h
->table
= new_table
;
579 hashtable_insert(struct hashtable
*h
, struct bucket
*b
)
584 assert(b
->next
== NULL
);
586 /* Rehash on 80% occupancy */
587 if ((h
->count
> h
->size
) ||
588 ((h
->size
- h
->count
) < h
->size
/ 5))
589 hashtable_rehash(h
, h
->bits
+1);
591 pos
= h
->hash_func(h
, h
->key_func(b
)) & h
->mask
;
592 if (h
->table
[pos
] == NULL
)
595 /* Insert at top of chain. */
596 b
->next
= h
->table
[pos
];
603 /* Return bucket matching key, or NULL if no such entry. */
604 static struct bucket
*
605 hashtable_search(struct hashtable
*h
, const void *key
)
611 pos
= h
->hash_func(h
, key
) & h
->mask
;
614 if (h
->find_func(b
, key
))
622 typedef enum { NO_REDUCE
= 0, ALLOW_REDUCE
= 1 } reduce_bool
;
623 /* Search for a key. If it's not there, make and insert a bucket for it. */
624 static struct bucket
*
625 hashtable_find_or_insert(struct hashtable
*h
, const void *key
,
626 const reduce_bool allow_reduce
)
628 struct bucket
*b
= hashtable_search(h
, key
);
631 /* Not found, so insert after checking occupancy. */
632 if (allow_reduce
&& (h
->count
>= h
->count_max
))
634 b
= h
->make_func(key
);
635 hashtable_insert(h
, b
);
641 * Frees the hashtable and the buckets. The contents are assumed to be
642 * "simple" -- i.e. no "destructor" action is required beyond simply freeing
646 hashtable_free(struct hashtable
*h
)
652 for (i
=0; i
<h
->size
; i
++) {
653 struct bucket
*tmp
, *b
= h
->table
[i
];
665 /* ---------------------------------------------------------------------------
666 * Return existing host or insert a new one.
669 host_get(const struct addr
*const a
)
671 return (hashtable_find_or_insert(hosts_db
, a
, NO_REDUCE
));
674 /* ---------------------------------------------------------------------------
675 * Find host, returns NULL if not in DB.
678 host_find(const struct addr
*const a
)
680 return (hashtable_search(hosts_db
, a
));
683 /* ---------------------------------------------------------------------------
684 * Find host, returns NULL if not in DB.
686 static struct bucket
*
687 host_search(const char *ipstr
)
690 struct addrinfo hints
, *ai
;
692 memset(&hints
, 0, sizeof(hints
));
693 hints
.ai_family
= AF_UNSPEC
;
694 hints
.ai_flags
= AI_NUMERICHOST
;
696 if (getaddrinfo(ipstr
, NULL
, &hints
, &ai
))
697 return (NULL
); /* invalid addr */
699 if (ai
->ai_family
== AF_INET
) {
701 a
.ip
.v4
= ((const struct sockaddr_in
*)ai
->ai_addr
)->sin_addr
.s_addr
;
703 else if (ai
->ai_family
== AF_INET6
) {
706 ((struct sockaddr_in6
*)ai
->ai_addr
)->sin6_addr
.s6_addr
,
710 return (NULL
); /* unknown family */
714 verbosef("search(%s) turned into %s", ipstr
, addr_to_str(&a
));
715 return (hashtable_search(hosts_db
, &a
));
718 /* ---------------------------------------------------------------------------
719 * Reduce a hashtable to the top <keep> entries.
722 hashtable_reduce(struct hashtable
*ht
)
724 uint32_t i
, pos
, rmd
;
725 const struct bucket
**table
;
728 assert(ht
->count_keep
< ht
->count
);
730 /* Fill table with pointers to buckets in hashtable. */
731 table
= xcalloc(ht
->count
, sizeof(*table
));
732 for (pos
=0, i
=0; i
<ht
->size
; i
++) {
733 struct bucket
*b
= ht
->table
[i
];
739 assert(pos
== ht
->count
);
740 qsort_buckets(table
, ht
->count
, 0, ht
->count_keep
, TOTAL
);
741 cutoff
= table
[ht
->count_keep
]->total
;
744 /* Remove all elements with total <= cutoff. */
746 for (i
=0; i
<ht
->size
; i
++) {
747 struct bucket
*last
= NULL
, *next
, *b
= ht
->table
[i
];
750 if (b
->total
<= cutoff
) {
751 /* Remove this one. */
766 verbosef("hashtable_reduce: removed %u buckets, left %u",
768 hashtable_rehash(ht
, ht
->bits
); /* is this needed? */
771 /* Reduce hosts_db if needed. */
772 void hosts_db_reduce(void)
774 if (hosts_db
->count
>= hosts_db
->count_max
)
775 hashtable_reduce(hosts_db
);
778 /* ---------------------------------------------------------------------------
779 * Reset hosts_db to empty.
786 for (i
=0; i
<hosts_db
->size
; i
++) {
787 struct bucket
*next
, *b
= hosts_db
->table
[i
];
790 hosts_db
->free_func(b
);
794 hosts_db
->table
[i
] = NULL
;
796 verbosef("hosts_db reset to empty, freed %u hosts", hosts_db
->count
);
800 /* ---------------------------------------------------------------------------
801 * Deallocate hosts_db.
803 void hosts_db_free(void)
807 assert(hosts_db
!= NULL
);
808 for (i
=0; i
<hosts_db
->size
; i
++) {
809 struct bucket
*tmp
, *b
= hosts_db
->table
[i
];
813 hosts_db
->free_func(tmp
);
817 free(hosts_db
->table
);
822 /* ---------------------------------------------------------------------------
823 * Find or create a port_tcp inside a host.
826 host_get_port_tcp(struct bucket
*host
, const uint16_t port
)
828 struct host
*h
= &host
->u
.host
;
830 if (h
->ports_tcp
== NULL
)
831 h
->ports_tcp
= hashtable_make(PORT_BITS
, opt_ports_max
, opt_ports_keep
,
832 hash_func_short
, free_func_simple
, key_func_port_tcp
,
833 find_func_port_tcp
, make_func_port_tcp
,
834 format_cols_port_tcp
, format_row_port_tcp
);
835 return (hashtable_find_or_insert(h
->ports_tcp
, &port
, ALLOW_REDUCE
));
838 /* ---------------------------------------------------------------------------
839 * Find or create a port_udp inside a host.
842 host_get_port_udp(struct bucket
*host
, const uint16_t port
)
844 struct host
*h
= &host
->u
.host
;
846 if (h
->ports_udp
== NULL
)
847 h
->ports_udp
= hashtable_make(PORT_BITS
, opt_ports_max
, opt_ports_keep
,
848 hash_func_short
, free_func_simple
, key_func_port_udp
,
849 find_func_port_udp
, make_func_port_udp
,
850 format_cols_port_udp
, format_row_port_udp
);
851 return (hashtable_find_or_insert(h
->ports_udp
, &port
, ALLOW_REDUCE
));
854 /* ---------------------------------------------------------------------------
855 * Find or create an ip_proto inside a host.
858 host_get_ip_proto(struct bucket
*host
, const uint8_t proto
)
860 struct host
*h
= &host
->u
.host
;
861 static const unsigned int PROTOS_MAX
= 512, PROTOS_KEEP
= 256;
863 if (h
->ip_protos
== NULL
)
864 h
->ip_protos
= hashtable_make(PROTO_BITS
, PROTOS_MAX
, PROTOS_KEEP
,
865 hash_func_byte
, free_func_simple
, key_func_ip_proto
,
866 find_func_ip_proto
, make_func_ip_proto
,
867 format_cols_ip_proto
, format_row_ip_proto
);
868 return (hashtable_find_or_insert(h
->ip_protos
, &proto
, ALLOW_REDUCE
));
871 static struct str
*html_hosts_main(const char *qs
);
872 static struct str
*html_hosts_detail(const char *ip
);
874 /* ---------------------------------------------------------------------------
875 * Web interface: delegate the /hosts/ space.
878 html_hosts(const char *uri
, const char *query
)
880 unsigned int i
, num_elems
;
881 char **elem
= split('/', uri
, &num_elems
);
882 struct str
*buf
= NULL
;
884 assert(num_elems
>= 1);
885 assert(strcmp(elem
[0], "hosts") == 0);
889 buf
= html_hosts_main(query
);
890 else if (num_elems
== 2)
891 /* /hosts/<IP of host>/ */
892 buf
= html_hosts_detail(elem
[1]);
894 for (i
=0; i
<num_elems
; i
++)
897 return (buf
); /* FIXME: a NULL here becomes 404 Not Found, we might want
898 other codes to be possible */
901 /* ---------------------------------------------------------------------------
902 * Format hashtable into HTML.
905 format_table(struct str
*buf
, struct hashtable
*ht
, unsigned int start
,
906 const enum sort_dir sort
, const int full
)
908 const struct bucket
**table
;
909 unsigned int i
, pos
, end
;
912 if ((ht
== NULL
) || (ht
->count
== 0)) {
913 str_append(buf
, "<p>The table is empty.</p>\n");
917 /* Fill table with pointers to buckets in hashtable. */
918 table
= xcalloc(ht
->count
, sizeof(*table
));
919 for (pos
=0, i
=0; i
<ht
->size
; i
++) {
920 struct bucket
*b
= ht
->table
[i
];
926 assert(pos
== ht
->count
);
929 /* full report overrides start and end */
933 end
= MIN(ht
->count
, (uint32_t)start
+MAX_ENTRIES
);
935 str_appendf(buf
, "(%u-%u of %u)<br>\n", start
+1, end
, ht
->count
);
936 qsort_buckets(table
, ht
->count
, start
, end
, sort
);
937 ht
->format_cols_func(buf
);
939 for (i
=start
; i
<end
; i
++) {
940 ht
->format_row_func(buf
, table
[i
], alt
? "alt1" : "alt2");
941 alt
= !alt
; /* alternate class for table rows */
944 str_append(buf
, "</table>\n");
947 /* ---------------------------------------------------------------------------
948 * Web interface: sorted table of hosts.
951 html_hosts_main(const char *qs
)
953 struct str
*buf
= str_make();
954 char *qs_start
, *qs_sort
, *qs_full
, *ep
;
959 /* parse query string */
960 qs_start
= qs_get(qs
, "start");
961 qs_sort
= qs_get(qs
, "sort");
962 qs_full
= qs_get(qs
, "full");
963 if (qs_full
!= NULL
) {
969 if (qs_sort
== NULL
) sort
= TOTAL
;
970 else if (strcmp(qs_sort
, "total") == 0) sort
= TOTAL
;
971 else if (strcmp(qs_sort
, "in") == 0) sort
= IN
;
972 else if (strcmp(qs_sort
, "out") == 0) sort
= OUT
;
973 else if (strcmp(qs_sort
, "lastseen") == 0) sort
= LASTSEEN
;
975 str_append(buf
, "Error: invalid value for \"sort\".\n");
980 if (qs_start
== NULL
)
983 start
= (int)strtoul(qs_start
, &ep
, 10);
985 str_append(buf
, "Error: \"start\" is not a number.\n");
988 if ((errno
== ERANGE
) ||
989 (start
< 0) || (start
>= (int)hosts_db
->count
)) {
990 str_append(buf
, "Error: \"start\" is out of bounds.\n");
995 #define PREV "<<< prev page"
996 #define NEXT "next page >>>"
997 #define FULL "full table"
999 html_open(buf
, "Hosts", /*path_depth=*/1, /*want_graph_js=*/0);
1000 format_table(buf
, hosts_db
, start
, sort
, full
);
1002 /* <prev | full | stats | next> */
1004 if (sortstr
== NULL
) sortstr
= "total";
1006 int prev
= start
- MAX_ENTRIES
;
1009 str_appendf(buf
, "<a href=\"?start=%d&sort=%s\">" PREV
"</a>",
1012 str_append(buf
, PREV
);
1015 str_append(buf
, " | " FULL
);
1017 str_appendf(buf
, " | <a href=\"?full=yes&sort=%s\">" FULL
"</a>",
1020 if (start
+MAX_ENTRIES
< (int)hosts_db
->count
)
1021 str_appendf(buf
, " | <a href=\"?start=%d&sort=%s\">" NEXT
"</a>",
1022 start
+MAX_ENTRIES
, sortstr
);
1024 str_append(buf
, " | " NEXT
);
1026 str_append(buf
, "<br>\n");
1030 if (qs_start
!= NULL
) free(qs_start
);
1031 if (qs_sort
!= NULL
) free(qs_sort
);
1038 /* ---------------------------------------------------------------------------
1039 * Web interface: detailed view of a single host.
1041 static struct str
*html_hosts_detail(const char *ip
) {
1043 struct str
*buf
, *ls_len
;
1045 const char *canonical
;
1046 time_t last_seen_real
;
1048 h
= host_search(ip
);
1050 return (NULL
); /* no such host */
1052 canonical
= addr_to_str(&(h
->u
.host
.addr
));
1056 html_open(buf
, ip
, /*path_depth=*/2, /*want_graph_js=*/0);
1057 if (strcmp(ip
, canonical
) != 0)
1058 str_appendf(buf
, "(canonically <b>%s</b>)\n", canonical
);
1061 "<b>Hostname:</b> %s<br>\n",
1062 (h
->u
.host
.dns
== NULL
)?"(resolving...)":h
->u
.host
.dns
);
1064 /* Resolve host "on demand" */
1065 if (h
->u
.host
.dns
== NULL
)
1066 dns_queue(&(h
->u
.host
.addr
));
1068 if (hosts_db_show_macs
)
1070 "<b>MAC Address:</b> "
1071 "<tt>%x:%x:%x:%x:%x:%x</tt><br>\n",
1072 h
->u
.host
.mac_addr
[0],
1073 h
->u
.host
.mac_addr
[1],
1074 h
->u
.host
.mac_addr
[2],
1075 h
->u
.host
.mac_addr
[3],
1076 h
->u
.host
.mac_addr
[4],
1077 h
->u
.host
.mac_addr
[5]);
1082 "<b>Last seen:</b> ");
1084 last_seen_real
= mono_to_real(h
->u
.host
.last_seen_mono
);
1085 if (strftime(ls_when
, sizeof(ls_when
),
1086 "%Y-%m-%d %H:%M:%S %Z%z", localtime(&last_seen_real
)) != 0)
1087 str_append(buf
, ls_when
);
1089 if (h
->u
.host
.last_seen_mono
<= now_mono()) {
1090 ls_len
= length_of_time(now_mono() - h
->u
.host
.last_seen_mono
);
1091 str_append(buf
, " (");
1092 str_appendstr(buf
, ls_len
);
1094 str_append(buf
, " ago)");
1096 str_append(buf
, " (in the future, possible clock problem)");
1102 " <b>In:</b> %'qu<br>\n"
1103 " <b>Out:</b> %'qu<br>\n"
1104 " <b>Total:</b> %'qu<br>\n"
1110 str_append(buf
, "<h3>TCP ports</h3>\n");
1111 format_table(buf
, h
->u
.host
.ports_tcp
, 0,TOTAL
,0);
1113 str_append(buf
, "<h3>UDP ports</h3>\n");
1114 format_table(buf
, h
->u
.host
.ports_udp
, 0,TOTAL
,0);
1116 str_append(buf
, "<h3>IP protocols</h3>\n");
1117 format_table(buf
, h
->u
.host
.ip_protos
, 0,TOTAL
,0);
1123 /* ---------------------------------------------------------------------------
1124 * Database import and export code:
1125 * Initially written and contributed by Ben Stewart.
1126 * copyright (c) 2007-2011 Ben Stewart, Emil Mikulic.
1128 static int hosts_db_export_ip(const struct hashtable
*h
, const int fd
);
1129 static int hosts_db_export_tcp(const struct hashtable
*h
, const int fd
);
1130 static int hosts_db_export_udp(const struct hashtable
*h
, const int fd
);
1133 export_proto_ip
= 'P',
1134 export_proto_tcp
= 'T',
1135 export_proto_udp
= 'U';
1137 static const unsigned char
1138 export_tag_host_ver1
[] = {'H', 'S', 'T', 0x01},
1139 export_tag_host_ver2
[] = {'H', 'S', 'T', 0x02},
1140 export_tag_host_ver3
[] = {'H', 'S', 'T', 0x03};
1142 /* ---------------------------------------------------------------------------
1143 * Load a host's ip_proto table from a file.
1144 * Returns 0 on failure, 1 on success.
1147 hosts_db_import_ip(const int fd
, struct bucket
*host
)
1151 if (!expect8(fd
, export_proto_ip
)) return 0;
1152 if (!read8(fd
, &count
)) return 0;
1154 for (i
=0; i
<count
; i
++) {
1159 if (!read8(fd
, &proto
)) return 0;
1160 if (!read64(fd
, &in
)) return 0;
1161 if (!read64(fd
, &out
)) return 0;
1164 b
= host_get_ip_proto(host
, proto
);
1167 b
->total
= in
+ out
;
1168 assert(b
->u
.ip_proto
.proto
== proto
); /* should be done by make fn */
1173 /* ---------------------------------------------------------------------------
1174 * Load a host's port_tcp table from a file.
1175 * Returns 0 on failure, 1 on success.
1178 hosts_db_import_tcp(const int fd
, struct bucket
*host
)
1182 if (!expect8(fd
, export_proto_tcp
)) return 0;
1183 if (!read16(fd
, &count
)) return 0;
1185 for (i
=0; i
<count
; i
++) {
1188 uint64_t in
, out
, syn
;
1190 if (!read16(fd
, &port
)) return 0;
1191 if (!read64(fd
, &syn
)) return 0;
1192 if (!read64(fd
, &in
)) return 0;
1193 if (!read64(fd
, &out
)) return 0;
1196 b
= host_get_port_tcp(host
, port
);
1199 b
->total
= in
+ out
;
1200 assert(b
->u
.port_tcp
.port
== port
); /* done by make_func_port_tcp */
1201 b
->u
.port_tcp
.syn
= syn
;
1206 /* ---------------------------------------------------------------------------
1207 * Load a host's port_tcp table from a file.
1208 * Returns 0 on failure, 1 on success.
1211 hosts_db_import_udp(const int fd
, struct bucket
*host
)
1215 if (!expect8(fd
, export_proto_udp
)) return 0;
1216 if (!read16(fd
, &count
)) return 0;
1218 for (i
=0; i
<count
; i
++) {
1223 if (!read16(fd
, &port
)) return 0;
1224 if (!read64(fd
, &in
)) return 0;
1225 if (!read64(fd
, &out
)) return 0;
1228 b
= host_get_port_udp(host
, port
);
1231 b
->total
= in
+ out
;
1232 assert(b
->u
.port_udp
.port
== port
); /* done by make_func */
1237 /* ---------------------------------------------------------------------------
1238 * Load all hosts from a file.
1239 * Returns 0 on failure, 1 on success.
1242 hosts_db_import_host(const int fd
)
1244 struct bucket
*host
;
1246 uint8_t hostname_len
;
1248 unsigned int pos
= xtell(fd
);
1252 if (!readn(fd
, hdr
, sizeof(hdr
))) return 0;
1253 if (memcmp(hdr
, export_tag_host_ver3
, sizeof(hdr
)) == 0)
1255 else if (memcmp(hdr
, export_tag_host_ver2
, sizeof(hdr
)) == 0)
1257 else if (memcmp(hdr
, export_tag_host_ver1
, sizeof(hdr
)) == 0)
1260 warnx("bad host header: %02x%02x%02x%02x",
1261 hdr
[0], hdr
[1], hdr
[2], hdr
[3]);
1266 if (!readaddr(fd
, &a
))
1269 assert((ver
== 1) || (ver
== 2));
1270 if (!readaddr_ipv4(fd
, &a
))
1273 verbosef("at file pos %u, importing host %s", pos
, addr_to_str(&a
));
1274 host
= host_get(&a
);
1275 assert(addr_equal(&(host
->u
.host
.addr
), &a
));
1279 if (!read64(fd
, &t
)) return 0;
1280 host
->u
.host
.last_seen_mono
= real_to_mono(t
);
1283 assert(sizeof(host
->u
.host
.mac_addr
) == 6);
1284 if (!readn(fd
, host
->u
.host
.mac_addr
, sizeof(host
->u
.host
.mac_addr
)))
1288 assert(host
->u
.host
.dns
== NULL
); /* make fn? */
1289 if (!read8(fd
, &hostname_len
)) return 0;
1290 if (hostname_len
> 0) {
1291 host
->u
.host
.dns
= xmalloc(hostname_len
+ 1);
1292 host
->u
.host
.dns
[0] = '\0';
1294 /* At this point, the hostname is attached to a host which is in our
1295 * hosts_db, so if we bail out due to an import error, this pointer
1296 * isn't lost and leaked, it can be cleaned up in hosts_db_{free,reset}
1299 if (!readn(fd
, host
->u
.host
.dns
, hostname_len
)) return 0;
1300 host
->u
.host
.dns
[hostname_len
] = '\0';
1303 if (!read64(fd
, &in
)) return 0;
1304 if (!read64(fd
, &out
)) return 0;
1308 host
->total
= in
+ out
;
1310 /* Host's port and proto subtables: */
1311 if (!hosts_db_import_ip(fd
, host
)) return 0;
1312 if (!hosts_db_import_tcp(fd
, host
)) return 0;
1313 if (!hosts_db_import_udp(fd
, host
)) return 0;
1317 /* ---------------------------------------------------------------------------
1318 * Database Import: Grab hosts_db from a file provided by the caller.
1320 * This function will retrieve the data sans the header. We expect the caller
1321 * to have validated the header of the hosts_db segment, and left the file
1322 * sitting at the start of the data.
1324 int hosts_db_import(const int fd
)
1326 uint32_t host_count
, i
;
1328 if (!read32(fd
, &host_count
)) return 0;
1330 for (i
=0; i
<host_count
; i
++)
1331 if (!hosts_db_import_host(fd
)) return 0;
1336 /* ---------------------------------------------------------------------------
1337 * Database Export: Dump hosts_db into a file provided by the caller.
1338 * The caller is responsible for writing out export_tag_hosts_ver1 first.
1340 int hosts_db_export(const int fd
)
1345 if (!write32(fd
, hosts_db
->count
)) return 0;
1347 for (i
= 0; i
<hosts_db
->size
; i
++)
1348 for (b
= hosts_db
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1349 /* For each host: */
1350 if (!writen(fd
, export_tag_host_ver3
, sizeof(export_tag_host_ver3
)))
1353 if (!writeaddr(fd
, &(b
->u
.host
.addr
)))
1356 if (!write64(fd
, (uint64_t)mono_to_real(b
->u
.host
.last_seen_mono
)))
1359 assert(sizeof(b
->u
.host
.mac_addr
) == 6);
1360 if (!writen(fd
, b
->u
.host
.mac_addr
, sizeof(b
->u
.host
.mac_addr
)))
1364 if (b
->u
.host
.dns
== NULL
) {
1365 if (!write8(fd
, 0)) return 0;
1367 int dnslen
= strlen(b
->u
.host
.dns
);
1370 warnx("found a very long hostname: \"%s\"\n"
1371 "wasn't expecting one longer than 255 chars (this one is %d)",
1372 b
->u
.host
.dns
, dnslen
);
1376 if (!write8(fd
, (uint8_t)dnslen
)) return 0;
1377 if (!writen(fd
, b
->u
.host
.dns
, dnslen
)) return 0;
1380 if (!write64(fd
, b
->in
)) return 0;
1381 if (!write64(fd
, b
->out
)) return 0;
1383 if (!hosts_db_export_ip(b
->u
.host
.ip_protos
, fd
)) return 0;
1384 if (!hosts_db_export_tcp(b
->u
.host
.ports_tcp
, fd
)) return 0;
1385 if (!hosts_db_export_udp(b
->u
.host
.ports_udp
, fd
)) return 0;
1390 /* ---------------------------------------------------------------------------
1391 * Dump the ip_proto table of a host.
1394 hosts_db_export_ip(const struct hashtable
*h
, const int fd
)
1396 uint32_t i
, written
= 0;
1400 if (!write8(fd
, export_proto_ip
)) return 0;
1402 /* If no data, write a IP Proto count of 0 and we're done. */
1404 if (!write8(fd
, 0)) return 0;
1408 assert(h
->count
< 256);
1409 if (!write8(fd
, (uint8_t)h
->count
)) return 0;
1411 for (i
= 0; i
<h
->size
; i
++)
1412 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1413 /* For each ip_proto bucket: */
1415 if (!write8(fd
, b
->u
.ip_proto
.proto
)) return 0;
1416 if (!write64(fd
, b
->in
)) return 0;
1417 if (!write64(fd
, b
->out
)) return 0;
1420 assert(written
== h
->count
);
1424 /* ---------------------------------------------------------------------------
1425 * Dump the port_tcp table of a host.
1428 hosts_db_export_tcp(const struct hashtable
*h
, const int fd
)
1431 uint32_t i
, written
= 0;
1434 if (!write8(fd
, export_proto_tcp
)) return 0;
1436 /* If no data, write a count of 0 and we're done. */
1438 if (!write16(fd
, 0)) return 0;
1442 assert(h
->count
< 65536);
1443 if (!write16(fd
, (uint16_t)h
->count
)) return 0;
1445 for (i
= 0; i
<h
->size
; i
++)
1446 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1447 if (!write16(fd
, b
->u
.port_tcp
.port
)) return 0;
1448 if (!write64(fd
, b
->u
.port_tcp
.syn
)) return 0;
1449 if (!write64(fd
, b
->in
)) return 0;
1450 if (!write64(fd
, b
->out
)) return 0;
1453 assert(written
== h
->count
);
1457 /* ---------------------------------------------------------------------------
1458 * Dump the port_udp table of a host.
1461 hosts_db_export_udp(const struct hashtable
*h
, const int fd
)
1464 uint32_t i
, written
= 0;
1467 if (!write8(fd
, export_proto_udp
)) return 0;
1469 /* If no data, write a count of 0 and we're done. */
1471 if (!write16(fd
, 0)) return 0;
1475 assert(h
->count
< 65536);
1476 if (!write16(fd
, (uint16_t)h
->count
)) return 0;
1478 for (i
= 0; i
<h
->size
; i
++)
1479 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1480 if (!write16(fd
, b
->u
.port_udp
.port
)) return 0;
1481 if (!write64(fd
, b
->in
)) return 0;
1482 if (!write64(fd
, b
->out
)) return 0;
1485 assert(written
== h
->count
);
1489 /* vim:set ts=3 sw=3 tw=78 expandtab: */