2 * copyright (c) 2001-2009 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)
18 #include "http.h" /* for http_base_url */
23 #include <arpa/inet.h> /* inet_aton() */
24 #include <netdb.h> /* struct addrinfo */
29 #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) );
112 /* Covers OpenBSD and FreeBSD. The macro __USE_GNU has
113 * taken care of GNU/Linux and GNU/kfreebsd. */
114 # define s6_addr32 __u6_addr.__u6_addr32
118 * This is the IPv6 hash function used by FreeBSD in the same file as above,
121 inline static uint32_t
122 ipv6_hash(const struct addr
*const a
)
124 const struct in6_addr
*const ip6
= &(a
->ip
.v6
);
125 return ( ip6
->s6_addr32
[0] ^ ip6
->s6_addr32
[1] ^
126 ip6
->s6_addr32
[2] ^ ip6
->s6_addr32
[3] );
129 /* ---------------------------------------------------------------------------
130 * hash_func collection
133 hash_func_host(const struct hashtable
*h _unused_
, const void *key
)
135 const struct addr
*a
= key
;
136 if (a
->family
== IPv4
)
137 return (ipv4_hash(a
));
139 assert(a
->family
== IPv6
);
140 return (ipv6_hash(a
));
144 #define CASTKEY(type) (*((const type *)key))
147 hash_func_short(const struct hashtable
*h
, const void *key
)
149 return (CASTKEY(uint16_t) * h
->coeff
);
153 hash_func_byte(const struct hashtable
*h
, const void *key
)
155 return (CASTKEY(uint8_t) * h
->coeff
);
158 /* ---------------------------------------------------------------------------
159 * key_func collection
163 key_func_host(const struct bucket
*b
)
165 return &(b
->u
.host
.addr
);
169 key_func_port_tcp(const struct bucket
*b
)
171 return &(b
->u
.port_tcp
.port
);
175 key_func_port_udp(const struct bucket
*b
)
177 return &(b
->u
.port_udp
.port
);
181 key_func_ip_proto(const struct bucket
*b
)
183 return &(b
->u
.ip_proto
.proto
);
186 /* ---------------------------------------------------------------------------
187 * find_func collection
191 find_func_host(const struct bucket
*b
, const void *key
)
193 return (addr_equal(key
, &(b
->u
.host
.addr
)));
197 find_func_port_tcp(const struct bucket
*b
, const void *key
)
199 return (b
->u
.port_tcp
.port
== CASTKEY(uint16_t));
203 find_func_port_udp(const struct bucket
*b
, const void *key
)
205 return (b
->u
.port_udp
.port
== CASTKEY(uint16_t));
209 find_func_ip_proto(const struct bucket
*b
, const void *key
)
211 return (b
->u
.ip_proto
.proto
== CASTKEY(uint8_t));
214 /* ---------------------------------------------------------------------------
215 * make_func collection
218 #define MAKE_BUCKET(name_bucket, name_content, type) struct { \
219 struct bucket *next; \
220 uint64_t in, out, total; \
221 union { struct type t; } u; } _custom_bucket; \
222 struct bucket *name_bucket = xcalloc(1, sizeof(_custom_bucket)); \
223 struct type *name_content = &(name_bucket->u.type); \
224 name_bucket->next = NULL; \
225 name_bucket->in = name_bucket->out = name_bucket->total = 0;
227 static struct bucket
*
228 make_func_host(const void *key
)
230 MAKE_BUCKET(b
, h
, host
);
231 h
->addr
= CASTKEY(struct addr
);
234 memset(&h
->mac_addr
, 0, sizeof(h
->mac_addr
));
242 free_func_host(struct bucket
*b
)
244 struct host
*h
= &(b
->u
.host
);
245 if (h
->dns
!= NULL
) free(h
->dns
);
246 hashtable_free(h
->ports_tcp
);
247 hashtable_free(h
->ports_udp
);
248 hashtable_free(h
->ip_protos
);
251 static struct bucket
*
252 make_func_port_tcp(const void *key
)
254 MAKE_BUCKET(b
, p
, port_tcp
);
255 p
->port
= CASTKEY(uint16_t);
260 static struct bucket
*
261 make_func_port_udp(const void *key
)
263 MAKE_BUCKET(b
, p
, port_udp
);
264 p
->port
= CASTKEY(uint16_t);
268 static struct bucket
*
269 make_func_ip_proto(const void *key
)
271 MAKE_BUCKET(b
, p
, ip_proto
);
272 p
->proto
= CASTKEY(uint8_t);
277 free_func_simple(struct bucket
*b _unused_
)
282 /* ---------------------------------------------------------------------------
283 * format_func collection (ordered by struct)
287 format_cols_host(struct str
*buf
)
289 /* FIXME: don't clobber parts of the query string
290 * specifically "full" and "start"
291 * when setting sort direction
297 " <th>Hostname</th>\n");
298 if (hosts_db_show_macs
) str_append(buf
,
299 " <th>MAC Address</th>\n");
301 " <th><a href=\"?sort=in\">In</a></th>\n"
302 " <th><a href=\"?sort=out\">Out</a></th>\n"
303 " <th><a href=\"?sort=total\">Total</a></th>\n");
304 if (opt_want_lastseen
) str_append(buf
,
305 " <th><a href=\"?sort=lastseen\">Last seen</a></th>\n");
311 format_row_host(struct str
*buf
, const struct bucket
*b
,
312 const char *css_class
)
314 const char *ip
= addr_to_str(&(b
->u
.host
.addr
));
317 "<tr class=\"%s\">\n"
318 " <td><a href=\"%shosts/%s/\">%s</a></td>\n"
321 http_base_url
, ip
, ip
,
322 (b
->u
.host
.dns
== NULL
) ? "" : b
->u
.host
.dns
);
324 if (hosts_db_show_macs
)
326 " <td><tt>%x:%x:%x:%x:%x:%x</tt></td>\n",
327 b
->u
.host
.mac_addr
[0],
328 b
->u
.host
.mac_addr
[1],
329 b
->u
.host
.mac_addr
[2],
330 b
->u
.host
.mac_addr
[3],
331 b
->u
.host
.mac_addr
[4],
332 b
->u
.host
.mac_addr
[5]);
335 " <td class=\"num\">%'qu</td>\n"
336 " <td class=\"num\">%'qu</td>\n"
337 " <td class=\"num\">%'qu</td>\n",
338 b
->in
, b
->out
, b
->total
);
340 if (opt_want_lastseen
) {
341 time_t last_t
= b
->u
.host
.last_seen
;
342 struct str
*lastseen
= NULL
;
345 lastseen
= length_of_time(now
- last_t
);
348 " <td class=\"num\">");
349 if (lastseen
== NULL
)
350 str_append(buf
, "(clock error)");
352 str_appendstr(buf
, lastseen
);
362 /* Only resolve hosts "on demand" */
363 if (b
->u
.host
.dns
== NULL
)
364 dns_queue(&(b
->u
.host
.addr
));
368 format_cols_port_tcp(struct str
*buf
)
374 " <th>Service</td>\n"
384 format_row_port_tcp(struct str
*buf
, const struct bucket
*b
,
385 const char *css_class
)
387 const struct port_tcp
*p
= &(b
->u
.port_tcp
);
390 "<tr class=\"%s\">\n"
391 " <td class=\"num\">%u</td>\n"
393 " <td class=\"num\">%'qu</td>\n"
394 " <td class=\"num\">%'qu</td>\n"
395 " <td class=\"num\">%'qu</td>\n"
396 " <td class=\"num\">%'qu</td>\n"
399 p
->port
, getservtcp(p
->port
), b
->in
, b
->out
, b
->total
, p
->syn
404 format_cols_port_udp(struct str
*buf
)
410 " <th>Service</td>\n"
419 format_row_port_udp(struct str
*buf
, const struct bucket
*b
,
420 const char *css_class
)
422 const struct port_udp
*p
= &(b
->u
.port_udp
);
425 "<tr class=\"%s\">\n"
426 " <td class=\"num\">%u</td>\n"
428 " <td class=\"num\">%'qu</td>\n"
429 " <td class=\"num\">%'qu</td>\n"
430 " <td class=\"num\">%'qu</td>\n"
433 p
->port
, getservudp(p
->port
), b
->in
, b
->out
, b
->total
438 format_cols_ip_proto(struct str
*buf
)
444 " <th>Protocol</td>\n"
453 format_row_ip_proto(struct str
*buf
, const struct bucket
*b
,
454 const char *css_class
)
456 const struct ip_proto
*p
= &(b
->u
.ip_proto
);
459 "<tr class=\"%s\">\n"
460 " <td class=\"num\">%u</td>\n"
462 " <td class=\"num\">%'qu</td>\n"
463 " <td class=\"num\">%'qu</td>\n"
464 " <td class=\"num\">%'qu</td>\n"
467 p
->proto
, getproto(p
->proto
),
468 b
->in
, b
->out
, b
->total
472 /* ---------------------------------------------------------------------------
473 * Initialise a hashtable.
475 static struct hashtable
*
476 hashtable_make(const uint8_t bits
,
477 const unsigned int count_max
,
478 const unsigned int count_keep
,
479 hash_func_t
*hash_func
,
480 free_func_t
*free_func
,
481 key_func_t
*key_func
,
482 find_func_t
*find_func
,
483 make_func_t
*make_func
,
484 format_cols_func_t
*format_cols_func
,
485 format_row_func_t
*format_row_func
)
487 struct hashtable
*hash
;
490 hash
= xmalloc(sizeof(*hash
));
492 hash
->count_max
= count_max
;
493 hash
->count_keep
= count_keep
;
494 hash
->size
= 1U << bits
;
495 hash
->mask
= hash
->size
- 1;
496 hash
->coeff
= coprime(hash
->size
);
497 hash
->hash_func
= hash_func
;
498 hash
->free_func
= free_func
;
499 hash
->key_func
= key_func
;
500 hash
->find_func
= find_func
;
501 hash
->make_func
= make_func
;
502 hash
->format_cols_func
= format_cols_func
;
503 hash
->format_row_func
= format_row_func
;
505 hash
->table
= xcalloc(hash
->size
, sizeof(*hash
->table
));
506 memset(&(hash
->stats
), 0, sizeof(hash
->stats
));
510 /* ---------------------------------------------------------------------------
511 * Initialise global hosts_db.
516 assert(hosts_db
== NULL
);
517 hosts_db
= hashtable_make(HOST_BITS
, opt_hosts_max
, opt_hosts_keep
,
518 hash_func_host
, free_func_host
, key_func_host
, find_func_host
,
519 make_func_host
, format_cols_host
, format_row_host
);
523 hashtable_rehash(struct hashtable
*h
, const uint8_t bits
)
525 struct bucket
**old_table
, **new_table
;
526 uint32_t i
, old_size
;
532 old_table
= h
->table
;
535 h
->size
= 1U << bits
;
536 h
->mask
= h
->size
- 1;
537 h
->coeff
= coprime(h
->size
);
538 new_table
= xcalloc(h
->size
, sizeof(*new_table
));
540 for (i
=0; i
<old_size
; i
++) {
541 struct bucket
*next
, *b
= old_table
[i
];
543 uint32_t pos
= h
->hash_func(h
, h
->key_func(b
)) & h
->mask
;
545 b
->next
= new_table
[pos
];
552 h
->table
= new_table
;
556 hashtable_insert(struct hashtable
*h
, struct bucket
*b
)
561 assert(b
->next
== NULL
);
563 /* Rehash on 80% occupancy */
564 if ((h
->count
> h
->size
) ||
565 ((h
->size
- h
->count
) < h
->size
/ 5))
566 hashtable_rehash(h
, h
->bits
+1);
568 pos
= h
->hash_func(h
, h
->key_func(b
)) & h
->mask
;
569 if (h
->table
[pos
] == NULL
)
572 /* Insert at top of chain. */
573 b
->next
= h
->table
[pos
];
580 /* Return bucket matching key, or NULL if no such entry. */
581 static struct bucket
*
582 hashtable_search(struct hashtable
*h
, const void *key
)
588 pos
= h
->hash_func(h
, key
) & h
->mask
;
591 if (h
->find_func(b
, key
))
599 typedef enum { NO_REDUCE
= 0, ALLOW_REDUCE
= 1 } reduce_bool
;
600 /* Search for a key. If it's not there, make and insert a bucket for it. */
601 static struct bucket
*
602 hashtable_find_or_insert(struct hashtable
*h
, const void *key
,
603 const reduce_bool allow_reduce
)
605 struct bucket
*b
= hashtable_search(h
, key
);
608 /* Not found, so insert after checking occupancy. */
609 if (allow_reduce
&& (h
->count
>= h
->count_max
))
611 b
= h
->make_func(key
);
612 hashtable_insert(h
, b
);
618 * Frees the hashtable and the buckets. The contents are assumed to be
619 * "simple" -- i.e. no "destructor" action is required beyond simply freeing
623 hashtable_free(struct hashtable
*h
)
629 for (i
=0; i
<h
->size
; i
++) {
630 struct bucket
*tmp
, *b
= h
->table
[i
];
642 /* ---------------------------------------------------------------------------
643 * Return existing host or insert a new one.
646 host_get(const struct addr
*const a
)
648 return (hashtable_find_or_insert(hosts_db
, a
, NO_REDUCE
));
651 /* ---------------------------------------------------------------------------
652 * Find host, returns NULL if not in DB.
655 host_find(const struct addr
*const a
)
657 return (hashtable_search(hosts_db
, a
));
660 /* ---------------------------------------------------------------------------
661 * Find host, returns NULL if not in DB.
663 static struct bucket
*
664 host_search(const char *ipstr
)
667 struct addrinfo hints
, *ai
;
669 memset(&hints
, 0, sizeof(hints
));
670 hints
.ai_family
= AF_UNSPEC
;
671 hints
.ai_flags
= AI_NUMERICHOST
;
673 if (getaddrinfo(ipstr
, NULL
, &hints
, &ai
))
674 return (NULL
); /* invalid addr */
676 if (ai
->ai_family
== AF_INET
) {
678 a
.ip
.v4
= ((const struct sockaddr_in
*)ai
->ai_addr
)->sin_addr
.s_addr
;
680 else if (ai
->ai_family
== AF_INET6
) {
683 ((struct sockaddr_in6
*)ai
->ai_addr
)->sin6_addr
.s6_addr
,
687 return (NULL
); /* unknown family */
691 verbosef("search(%s) turned into %s", ipstr
, addr_to_str(&a
));
692 return (hashtable_search(hosts_db
, &a
));
695 /* ---------------------------------------------------------------------------
696 * Reduce a hashtable to the top <keep> entries.
699 hashtable_reduce(struct hashtable
*ht
)
701 uint32_t i
, pos
, rmd
;
702 const struct bucket
**table
;
705 assert(ht
->count_keep
< ht
->count
);
707 /* Fill table with pointers to buckets in hashtable. */
708 table
= xcalloc(ht
->count
, sizeof(*table
));
709 for (pos
=0, i
=0; i
<ht
->size
; i
++) {
710 struct bucket
*b
= ht
->table
[i
];
716 assert(pos
== ht
->count
);
717 qsort_buckets(table
, ht
->count
, 0, ht
->count_keep
, TOTAL
);
718 cutoff
= table
[ht
->count_keep
]->total
;
721 /* Remove all elements with total <= cutoff. */
723 for (i
=0; i
<ht
->size
; i
++) {
724 struct bucket
*last
= NULL
, *next
, *b
= ht
->table
[i
];
727 if (b
->total
<= cutoff
) {
728 /* Remove this one. */
743 verbosef("hashtable_reduce: removed %u buckets, left %u",
745 hashtable_rehash(ht
, ht
->bits
); /* is this needed? */
748 /* Reduce hosts_db if needed. */
749 void hosts_db_reduce(void)
751 if (hosts_db
->count
>= hosts_db
->count_max
)
752 hashtable_reduce(hosts_db
);
755 /* ---------------------------------------------------------------------------
756 * Reset hosts_db to empty.
763 for (i
=0; i
<hosts_db
->size
; i
++) {
764 struct bucket
*next
, *b
= hosts_db
->table
[i
];
767 hosts_db
->free_func(b
);
771 hosts_db
->table
[i
] = NULL
;
773 verbosef("hosts_db reset to empty, freed %u hosts", hosts_db
->count
);
777 /* ---------------------------------------------------------------------------
778 * Deallocate hosts_db.
780 void hosts_db_free(void)
784 assert(hosts_db
!= NULL
);
785 for (i
=0; i
<hosts_db
->size
; i
++) {
786 struct bucket
*tmp
, *b
= hosts_db
->table
[i
];
790 hosts_db
->free_func(tmp
);
794 free(hosts_db
->table
);
799 /* ---------------------------------------------------------------------------
800 * Find or create a port_tcp inside a host.
803 host_get_port_tcp(struct bucket
*host
, const uint16_t port
)
805 struct host
*h
= &host
->u
.host
;
807 if (h
->ports_tcp
== NULL
)
808 h
->ports_tcp
= hashtable_make(PORT_BITS
, opt_ports_max
, opt_ports_keep
,
809 hash_func_short
, free_func_simple
, key_func_port_tcp
,
810 find_func_port_tcp
, make_func_port_tcp
,
811 format_cols_port_tcp
, format_row_port_tcp
);
812 return (hashtable_find_or_insert(h
->ports_tcp
, &port
, ALLOW_REDUCE
));
815 /* ---------------------------------------------------------------------------
816 * Find or create a port_udp inside a host.
819 host_get_port_udp(struct bucket
*host
, const uint16_t port
)
821 struct host
*h
= &host
->u
.host
;
823 if (h
->ports_udp
== NULL
)
824 h
->ports_udp
= hashtable_make(PORT_BITS
, opt_ports_max
, opt_ports_keep
,
825 hash_func_short
, free_func_simple
, key_func_port_udp
,
826 find_func_port_udp
, make_func_port_udp
,
827 format_cols_port_udp
, format_row_port_udp
);
828 return (hashtable_find_or_insert(h
->ports_udp
, &port
, ALLOW_REDUCE
));
831 /* ---------------------------------------------------------------------------
832 * Find or create an ip_proto inside a host.
835 host_get_ip_proto(struct bucket
*host
, const uint8_t proto
)
837 struct host
*h
= &host
->u
.host
;
838 static const unsigned int PROTOS_MAX
= 512, PROTOS_KEEP
= 256;
840 if (h
->ip_protos
== NULL
)
841 h
->ip_protos
= hashtable_make(PROTO_BITS
, PROTOS_MAX
, PROTOS_KEEP
,
842 hash_func_byte
, free_func_simple
, key_func_ip_proto
,
843 find_func_ip_proto
, make_func_ip_proto
,
844 format_cols_ip_proto
, format_row_ip_proto
);
845 return (hashtable_find_or_insert(h
->ip_protos
, &proto
, ALLOW_REDUCE
));
848 static struct str
*html_hosts_main(const char *qs
);
849 static struct str
*html_hosts_detail(const char *ip
);
851 /* ---------------------------------------------------------------------------
852 * Web interface: delegate the /hosts/ space.
855 html_hosts(const char *uri
, const char *query
)
857 unsigned int i
, num_elems
;
858 char **elem
= split('/', uri
, &num_elems
);
859 struct str
*buf
= NULL
;
861 assert(num_elems
>= 1);
862 assert(strcmp(elem
[0], "hosts") == 0);
866 buf
= html_hosts_main(query
);
867 else if (num_elems
== 2)
868 /* /hosts/<IP of host>/ */
869 buf
= html_hosts_detail(elem
[1]);
871 for (i
=0; i
<num_elems
; i
++)
874 return (buf
); /* FIXME: a NULL here becomes 404 Not Found, we might want
875 other codes to be possible */
878 /* ---------------------------------------------------------------------------
879 * Format hashtable into HTML.
882 format_table(struct str
*buf
, struct hashtable
*ht
, unsigned int start
,
883 const enum sort_dir sort
, const int full
)
885 const struct bucket
**table
;
886 unsigned int i
, pos
, end
;
889 if ((ht
== NULL
) || (ht
->count
== 0)) {
890 str_append(buf
, "<p>The table is empty.</p>\n");
894 /* Fill table with pointers to buckets in hashtable. */
895 table
= xcalloc(ht
->count
, sizeof(*table
));
896 for (pos
=0, i
=0; i
<ht
->size
; i
++) {
897 struct bucket
*b
= ht
->table
[i
];
903 assert(pos
== ht
->count
);
906 /* full report overrides start and end */
910 end
= min(ht
->count
, (uint32_t)start
+MAX_ENTRIES
);
912 str_appendf(buf
, "(%u-%u of %u)<br>\n", start
+1, end
, ht
->count
);
913 qsort_buckets(table
, ht
->count
, start
, end
, sort
);
914 ht
->format_cols_func(buf
);
916 for (i
=start
; i
<end
; i
++) {
917 ht
->format_row_func(buf
, table
[i
], alt
? "alt1" : "alt2");
918 alt
= !alt
; /* alternate class for table rows */
921 str_append(buf
, "</table>\n");
924 /* ---------------------------------------------------------------------------
925 * Web interface: sorted table of hosts.
928 html_hosts_main(const char *qs
)
930 struct str
*buf
= str_make();
931 char *qs_start
, *qs_sort
, *qs_full
, *ep
;
936 /* parse query string */
937 qs_start
= qs_get(qs
, "start");
938 qs_sort
= qs_get(qs
, "sort");
939 qs_full
= qs_get(qs
, "full");
940 if (qs_full
!= NULL
) {
946 if (qs_sort
== NULL
) sort
= TOTAL
;
947 else if (strcmp(qs_sort
, "total") == 0) sort
= TOTAL
;
948 else if (strcmp(qs_sort
, "in") == 0) sort
= IN
;
949 else if (strcmp(qs_sort
, "out") == 0) sort
= OUT
;
950 else if (strcmp(qs_sort
, "lastseen") == 0) sort
= LASTSEEN
;
952 str_append(buf
, "Error: invalid value for \"sort\".\n");
957 if (qs_start
== NULL
)
960 start
= (int)strtoul(qs_start
, &ep
, 10);
962 str_append(buf
, "Error: \"start\" is not a number.\n");
965 if ((errno
== ERANGE
) ||
966 (start
< 0) || (start
>= (int)hosts_db
->count
)) {
967 str_append(buf
, "Error: \"start\" is out of bounds.\n");
972 #define PREV "<<< prev page"
973 #define NEXT "next page >>>"
974 #define FULL "full table"
976 html_open(buf
, "Hosts", /*want_graph_js=*/0);
977 format_table(buf
, hosts_db
, start
, sort
, full
);
979 /* <prev | full | stats | next> */
981 if (sortstr
== NULL
) sortstr
= "total";
983 int prev
= start
- MAX_ENTRIES
;
986 str_appendf(buf
, "<a href=\"?start=%d&sort=%s\">" PREV
"</a>",
989 str_append(buf
, PREV
);
992 str_append(buf
, " | " FULL
);
994 str_appendf(buf
, " | <a href=\"?full=yes&sort=%s\">" FULL
"</a>",
997 if (start
+MAX_ENTRIES
< (int)hosts_db
->count
)
998 str_appendf(buf
, " | <a href=\"?start=%d&sort=%s\">" NEXT
"</a>",
999 start
+MAX_ENTRIES
, sortstr
);
1001 str_append(buf
, " | " NEXT
);
1003 str_append(buf
, "<br>\n");
1007 if (qs_start
!= NULL
) free(qs_start
);
1008 if (qs_sort
!= NULL
) free(qs_sort
);
1015 /* ---------------------------------------------------------------------------
1016 * Web interface: detailed view of a single host.
1019 html_hosts_detail(const char *ip
)
1022 struct str
*buf
, *ls_len
;
1024 const char *canonical
;
1027 h
= host_search(ip
);
1029 return (NULL
); /* no such host */
1031 canonical
= addr_to_str(&(h
->u
.host
.addr
));
1035 html_open(buf
, ip
, /*want_graph_js=*/0);
1036 if (strcmp(ip
, canonical
) != 0)
1037 str_appendf(buf
, "(canonically <b>%s</b>)\n", canonical
);
1040 "<b>Hostname:</b> %s<br>\n",
1041 (h
->u
.host
.dns
== NULL
)?"(resolving...)":h
->u
.host
.dns
);
1043 /* Resolve host "on demand" */
1044 if (h
->u
.host
.dns
== NULL
)
1045 dns_queue(&(h
->u
.host
.addr
));
1047 if (hosts_db_show_macs
)
1049 "<b>MAC Address:</b> "
1050 "<tt>%x:%x:%x:%x:%x:%x</tt><br>\n",
1051 h
->u
.host
.mac_addr
[0],
1052 h
->u
.host
.mac_addr
[1],
1053 h
->u
.host
.mac_addr
[2],
1054 h
->u
.host
.mac_addr
[3],
1055 h
->u
.host
.mac_addr
[4],
1056 h
->u
.host
.mac_addr
[5]);
1061 "<b>Last seen:</b> ");
1063 ls
= h
->u
.host
.last_seen
;
1064 if (strftime(ls_when
, sizeof(ls_when
),
1065 "%Y-%m-%d %H:%M:%S %Z%z", localtime(&ls
)) != 0)
1066 str_append(buf
, ls_when
);
1068 if (h
->u
.host
.last_seen
<= now
) {
1069 ls_len
= length_of_time(now
- h
->u
.host
.last_seen
);
1070 str_append(buf
, " (");
1071 str_appendstr(buf
, ls_len
);
1073 str_append(buf
, " ago)");
1075 str_append(buf
, " (in the future, possible clock problem)");
1081 " <b>In:</b> %'qu<br>\n"
1082 " <b>Out:</b> %'qu<br>\n"
1083 " <b>Total:</b> %'qu<br>\n"
1085 h
->in
, h
->out
, h
->total
);
1087 str_append(buf
, "<h3>TCP ports</h3>\n");
1088 format_table(buf
, h
->u
.host
.ports_tcp
, 0,TOTAL
,0);
1090 str_append(buf
, "<h3>UDP ports</h3>\n");
1091 format_table(buf
, h
->u
.host
.ports_udp
, 0,TOTAL
,0);
1093 str_append(buf
, "<h3>IP protocols</h3>\n");
1094 format_table(buf
, h
->u
.host
.ip_protos
, 0,TOTAL
,0);
1100 /* ---------------------------------------------------------------------------
1101 * Database import and export code:
1102 * Initially written and contributed by Ben Stewart.
1103 * copyright (c) 2007 Ben Stewart, Emil Mikulic.
1105 static int hosts_db_export_ip(const struct hashtable
*h
, const int fd
);
1106 static int hosts_db_export_tcp(const struct hashtable
*h
, const int fd
);
1107 static int hosts_db_export_udp(const struct hashtable
*h
, const int fd
);
1110 export_proto_ip
= 'P',
1111 export_proto_tcp
= 'T',
1112 export_proto_udp
= 'U';
1114 static const unsigned char
1115 export_tag_host_ver1
[] = {'H', 'S', 'T', 0x01},
1116 export_tag_host_ver2
[] = {'H', 'S', 'T', 0x02},
1117 export_tag_host_ver3
[] = {'H', 'S', 'T', 0x03};
1119 /* ---------------------------------------------------------------------------
1120 * Load a host's ip_proto table from a file.
1121 * Returns 0 on failure, 1 on success.
1124 hosts_db_import_ip(const int fd
, struct bucket
*host
)
1128 if (!expect8(fd
, export_proto_ip
)) return 0;
1129 if (!read8(fd
, &count
)) return 0;
1131 for (i
=0; i
<count
; i
++) {
1136 if (!read8(fd
, &proto
)) return 0;
1137 if (!read64(fd
, &in
)) return 0;
1138 if (!read64(fd
, &out
)) return 0;
1141 b
= host_get_ip_proto(host
, proto
);
1144 b
->total
= in
+ out
;
1145 assert(b
->u
.ip_proto
.proto
== proto
); /* should be done by make fn */
1150 /* ---------------------------------------------------------------------------
1151 * Load a host's port_tcp table from a file.
1152 * Returns 0 on failure, 1 on success.
1155 hosts_db_import_tcp(const int fd
, struct bucket
*host
)
1159 if (!expect8(fd
, export_proto_tcp
)) return 0;
1160 if (!read16(fd
, &count
)) return 0;
1162 for (i
=0; i
<count
; i
++) {
1165 uint64_t in
, out
, syn
;
1167 if (!read16(fd
, &port
)) return 0;
1168 if (!read64(fd
, &syn
)) return 0;
1169 if (!read64(fd
, &in
)) return 0;
1170 if (!read64(fd
, &out
)) return 0;
1173 b
= host_get_port_tcp(host
, port
);
1176 b
->total
= in
+ out
;
1177 assert(b
->u
.port_tcp
.port
== port
); /* done by make_func_port_tcp */
1178 b
->u
.port_tcp
.syn
= syn
;
1183 /* ---------------------------------------------------------------------------
1184 * Load a host's port_tcp table from a file.
1185 * Returns 0 on failure, 1 on success.
1188 hosts_db_import_udp(const int fd
, struct bucket
*host
)
1192 if (!expect8(fd
, export_proto_udp
)) return 0;
1193 if (!read16(fd
, &count
)) return 0;
1195 for (i
=0; i
<count
; i
++) {
1200 if (!read16(fd
, &port
)) return 0;
1201 if (!read64(fd
, &in
)) return 0;
1202 if (!read64(fd
, &out
)) return 0;
1205 b
= host_get_port_udp(host
, port
);
1208 b
->total
= in
+ out
;
1209 assert(b
->u
.port_udp
.port
== port
); /* done by make_func */
1214 /* ---------------------------------------------------------------------------
1215 * Load all hosts from a file.
1216 * Returns 0 on failure, 1 on success.
1219 hosts_db_import_host(const int fd
)
1221 struct bucket
*host
;
1223 uint8_t hostname_len
;
1225 unsigned int pos
= xtell(fd
);
1229 if (!readn(fd
, hdr
, sizeof(hdr
))) return 0;
1230 if (memcmp(hdr
, export_tag_host_ver3
, sizeof(hdr
)) == 0)
1232 else if (memcmp(hdr
, export_tag_host_ver2
, sizeof(hdr
)) == 0)
1234 else if (memcmp(hdr
, export_tag_host_ver1
, sizeof(hdr
)) == 0)
1237 warnx("bad host header: %02x%02x%02x%02x",
1238 hdr
[0], hdr
[1], hdr
[2], hdr
[3]);
1243 if (!readaddr(fd
, &a
))
1246 assert((ver
== 1) || (ver
== 2));
1247 if (!readaddr_ipv4(fd
, &a
))
1250 verbosef("at file pos %u, importing host %s", pos
, addr_to_str(&a
));
1251 host
= host_get(&a
);
1252 assert(addr_equal(&(host
->u
.host
.addr
), &a
));
1256 if (!read64(fd
, &t
)) return 0;
1257 host
->u
.host
.last_seen
= (time_t)t
;
1260 assert(sizeof(host
->u
.host
.mac_addr
) == 6);
1261 if (!readn(fd
, host
->u
.host
.mac_addr
, sizeof(host
->u
.host
.mac_addr
)))
1265 assert(host
->u
.host
.dns
== NULL
); /* make fn? */
1266 if (!read8(fd
, &hostname_len
)) return 0;
1267 if (hostname_len
> 0) {
1268 host
->u
.host
.dns
= xmalloc(hostname_len
+ 1);
1269 host
->u
.host
.dns
[0] = '\0';
1271 /* At this point, the hostname is attached to a host which is in our
1272 * hosts_db, so if we bail out due to an import error, this pointer
1273 * isn't lost and leaked, it can be cleaned up in hosts_db_{free,reset}
1276 if (!readn(fd
, host
->u
.host
.dns
, hostname_len
)) return 0;
1277 host
->u
.host
.dns
[hostname_len
] = '\0';
1280 if (!read64(fd
, &in
)) return 0;
1281 if (!read64(fd
, &out
)) return 0;
1285 host
->total
= in
+ out
;
1287 /* Host's port and proto subtables: */
1288 if (!hosts_db_import_ip(fd
, host
)) return 0;
1289 if (!hosts_db_import_tcp(fd
, host
)) return 0;
1290 if (!hosts_db_import_udp(fd
, host
)) return 0;
1294 /* ---------------------------------------------------------------------------
1295 * Database Import: Grab hosts_db from a file provided by the caller.
1297 * This function will retrieve the data sans the header. We expect the caller
1298 * to have validated the header of the hosts_db segment, and left the file
1299 * sitting at the start of the data.
1301 int hosts_db_import(const int fd
)
1303 uint32_t host_count
, i
;
1305 if (!read32(fd
, &host_count
)) return 0;
1307 for (i
=0; i
<host_count
; i
++)
1308 if (!hosts_db_import_host(fd
)) return 0;
1313 /* ---------------------------------------------------------------------------
1314 * Database Export: Dump hosts_db into a file provided by the caller.
1315 * The caller is responsible for writing out export_tag_hosts_ver1 first.
1317 int hosts_db_export(const int fd
)
1322 if (!write32(fd
, hosts_db
->count
)) return 0;
1324 for (i
= 0; i
<hosts_db
->size
; i
++)
1325 for (b
= hosts_db
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1326 /* For each host: */
1327 if (!writen(fd
, export_tag_host_ver3
, sizeof(export_tag_host_ver3
)))
1330 if (!writeaddr(fd
, &(b
->u
.host
.addr
))) return 0;
1332 if (!write64(fd
, (uint64_t)(b
->u
.host
.last_seen
))) return 0;
1334 assert(sizeof(b
->u
.host
.mac_addr
) == 6);
1335 if (!writen(fd
, b
->u
.host
.mac_addr
, sizeof(b
->u
.host
.mac_addr
)))
1339 if (b
->u
.host
.dns
== NULL
) {
1340 if (!write8(fd
, 0)) return 0;
1342 int dnslen
= strlen(b
->u
.host
.dns
);
1345 warnx("found a very long hostname: \"%s\"\n"
1346 "wasn't expecting one longer than 255 chars (this one is %d)",
1347 b
->u
.host
.dns
, dnslen
);
1351 if (!write8(fd
, (uint8_t)dnslen
)) return 0;
1352 if (!writen(fd
, b
->u
.host
.dns
, dnslen
)) return 0;
1355 if (!write64(fd
, b
->in
)) return 0;
1356 if (!write64(fd
, b
->out
)) return 0;
1358 if (!hosts_db_export_ip(b
->u
.host
.ip_protos
, fd
)) return 0;
1359 if (!hosts_db_export_tcp(b
->u
.host
.ports_tcp
, fd
)) return 0;
1360 if (!hosts_db_export_udp(b
->u
.host
.ports_udp
, fd
)) return 0;
1365 /* ---------------------------------------------------------------------------
1366 * Dump the ip_proto table of a host.
1369 hosts_db_export_ip(const struct hashtable
*h
, const int fd
)
1371 uint32_t i
, written
= 0;
1375 if (!write8(fd
, export_proto_ip
)) return 0;
1377 /* If no data, write a IP Proto count of 0 and we're done. */
1379 if (!write8(fd
, 0)) return 0;
1383 assert(h
->count
< 256);
1384 if (!write8(fd
, (uint8_t)h
->count
)) return 0;
1386 for (i
= 0; i
<h
->size
; i
++)
1387 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1388 /* For each ip_proto bucket: */
1390 if (!write8(fd
, b
->u
.ip_proto
.proto
)) return 0;
1391 if (!write64(fd
, b
->in
)) return 0;
1392 if (!write64(fd
, b
->out
)) return 0;
1395 assert(written
== h
->count
);
1399 /* ---------------------------------------------------------------------------
1400 * Dump the port_tcp table of a host.
1403 hosts_db_export_tcp(const struct hashtable
*h
, const int fd
)
1406 uint32_t i
, written
= 0;
1409 if (!write8(fd
, export_proto_tcp
)) return 0;
1411 /* If no data, write a count of 0 and we're done. */
1413 if (!write16(fd
, 0)) return 0;
1417 assert(h
->count
< 65536);
1418 if (!write16(fd
, (uint16_t)h
->count
)) return 0;
1420 for (i
= 0; i
<h
->size
; i
++)
1421 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1422 if (!write16(fd
, b
->u
.port_tcp
.port
)) return 0;
1423 if (!write64(fd
, b
->u
.port_tcp
.syn
)) return 0;
1424 if (!write64(fd
, b
->in
)) return 0;
1425 if (!write64(fd
, b
->out
)) return 0;
1428 assert(written
== h
->count
);
1432 /* ---------------------------------------------------------------------------
1433 * Dump the port_udp table of a host.
1436 hosts_db_export_udp(const struct hashtable
*h
, const int fd
)
1439 uint32_t i
, written
= 0;
1442 if (!write8(fd
, export_proto_udp
)) return 0;
1444 /* If no data, write a count of 0 and we're done. */
1446 if (!write16(fd
, 0)) return 0;
1450 assert(h
->count
< 65536);
1451 if (!write16(fd
, (uint16_t)h
->count
)) return 0;
1453 for (i
= 0; i
<h
->size
; i
++)
1454 for (b
= h
->table
[i
]; b
!= NULL
; b
= b
->next
) {
1455 if (!write16(fd
, b
->u
.port_udp
.port
)) return 0;
1456 if (!write64(fd
, b
->in
)) return 0;
1457 if (!write64(fd
, b
->out
)) return 0;
1460 assert(written
== h
->count
);
1464 /* vim:set ts=3 sw=3 tw=78 expandtab: */