flowtop: better readability on smaller-sized terminals
[netsniff-ng.git] / src / flowtop.c
blob4c922ad68f18de31071d4fbda786fd892d658670
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2011 Daniel Borkmann.
5 * Copyright 2011 Emmanuel Roullit.
6 * Subject to the GPL, version 2.
8 * A tiny tool to provide top-like netfilter connection tracking information.
10 * The Dark Lord has Nine. But we have One, mightier than they: the White
11 * Rider. He has passed through the fire and the abyss, and they shall
12 * fear him. We will go where he leads.
14 * -- The Lord of the Rings, Aragorn,
15 * Chapter 'The White Rider'.
19 * Debian: apt-get install libnetfilter-conntrack3 libnetfilter-conntrack-dev
20 * liburcu0 liburcu-dev
22 * Start conntrack (if not yet running):
23 * iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT
24 * iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT
29 =head1 NAME
31 flowtop - provide top-like netfilter connection tracking information
33 =head1 SYNOPSIS
35 flowtop [--city-db <path>][--country-db <path>]
36 [-T|--tcp][-U|--udp][-v|--version][-h|--help]
38 =head1 DESCRIPTION
40 flowtop is a tiny tool to print human-readable
41 netfilter connection tracking information.
43 =head1 EXAMPLES
45 =over
47 =item flowtop
49 Show only TCP flows
51 =item flowtop --udp
53 Show only UDP flows
55 =item flowtop --city-db /usr/share/GeoIP/GeoIPCity.dat
57 Use the specified GeoIP city database
59 =item flowtop --country-db /usr/share/GeoIP/GeoIP.dat
61 Use the specified GeoIP country database
63 =back
65 =head1 OPTIONS
67 =over
69 =item -T|--tcp
71 Only show TCP flows (default)
73 =item -U|--udp
75 Only show UDP flows
77 =item -s|--show-src
79 Also include flow source in top output
81 =item --city-db
83 Path to GeoIP city database
85 =item --country-db
87 Path to GeoIP country database
89 =item -v|--version
91 Print version.
93 =item -h|--help
95 Print help text and lists all options.
97 =back
99 =head1 AUTHOR
101 Written by Daniel Borkmann <daniel@netsniff-ng.org>
103 =head1 DOCUMENTATION
105 Documentation by Emmanuel Roullit <emmanuel@netsniff-ng.org>
107 =head1 BUGS
109 Please report bugs to <bugs@netsniff-ng.org>
111 =cut
115 #define _LGPL_SOURCE
116 #include <stdio.h>
117 #include <stdint.h>
118 #include <stdlib.h>
119 #include <signal.h>
120 #include <getopt.h>
121 #include <pthread.h>
122 #include <signal.h>
123 #include <netdb.h>
124 #include <ctype.h>
125 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
126 #include <libnetfilter_conntrack/libnetfilter_conntrack_tcp.h>
127 #include <GeoIP.h>
128 #include <GeoIPCity.h>
129 #include <netinet/in.h>
130 #include <curses.h>
131 #include <dirent.h>
132 #include <sys/stat.h>
133 #include <urcu.h>
134 #include <libgen.h>
136 #include "die.h"
137 #include "xmalloc.h"
138 #include "xio.h"
139 #include "xsys.h"
140 #include "built_in.h"
141 #include "locking.h"
142 #include "dissector_eth.h"
144 #define INCLUDE_UDP (1 << 0)
145 #define INCLUDE_TCP (1 << 1)
147 #ifndef ATTR_TIMESTAMP_START
148 # define ATTR_TIMESTAMP_START 63
149 #endif
150 #ifndef ATTR_TIMESTAMP_STOP
151 # define ATTR_TIMESTAMP_STOP 64
152 #endif
154 #define SCROLL_MAX 1000
156 struct flow_entry {
157 uint32_t flow_id;
158 int first;
159 struct flow_entry *next;
160 uint32_t use;
161 uint32_t status;
162 uint8_t l3_proto;
163 uint8_t l4_proto;
164 uint32_t ip4_src_addr;
165 uint32_t ip4_dst_addr;
166 uint32_t ip6_src_addr[4];
167 uint32_t ip6_dst_addr[4];
168 uint16_t port_src;
169 uint16_t port_dst;
170 uint8_t tcp_state;
171 uint8_t tcp_flags;
172 uint64_t counter_pkts;
173 uint64_t counter_bytes;
174 uint64_t timestamp_start;
175 uint64_t timestamp_stop;
176 char country_src[128];
177 char city_src[128];
178 char rev_dns_src[256];
179 char country_dst[128];
180 char city_dst[128];
181 char rev_dns_dst[256];
182 int procnum;
183 int inode;
184 char cmdline[256];
187 struct flow_list {
188 struct flow_entry *head;
189 struct spinlock lock;
192 volatile sig_atomic_t sigint = 0;
194 static int what = INCLUDE_TCP;
196 static int show_src = 0;
198 static struct flow_list flow_list;
200 static GeoIP *gi_country = NULL;
201 static GeoIP *gi_city = NULL;
203 static char *path_city_db = NULL, *path_country_db = NULL;
205 static const char *short_options = "vhTULKs";
207 static struct option long_options[] = {
208 {"tcp", no_argument, 0, 'T'},
209 {"udp", no_argument, 0, 'U'},
210 {"show-src", no_argument, 0, 's'},
211 {"city-db", required_argument, 0, 'L'},
212 {"country-db", required_argument, 0, 'K'},
213 {"version", no_argument, 0, 'v'},
214 {"help", no_argument, 0, 'h'},
215 {0, 0, 0, 0}
218 const char *const l3proto2str[AF_MAX] = {
219 [AF_INET] = "ipv4",
220 [AF_INET6] = "ipv6",
223 const char *const proto2str[IPPROTO_MAX] = {
224 [IPPROTO_TCP] = "tcp",
225 [IPPROTO_UDP] = "udp",
226 [IPPROTO_UDPLITE] = "udplite",
227 [IPPROTO_ICMP] = "icmp",
228 [IPPROTO_ICMPV6] = "icmpv6",
229 [IPPROTO_SCTP] = "sctp",
230 [IPPROTO_GRE] = "gre",
231 [IPPROTO_DCCP] = "dccp",
232 [IPPROTO_IGMP] = "igmp",
233 [IPPROTO_IPIP] = "ipip",
234 [IPPROTO_EGP] = "egp",
235 [IPPROTO_PUP] = "pup",
236 [IPPROTO_IDP] = "idp",
237 [IPPROTO_RSVP] = "rsvp",
238 [IPPROTO_IPV6] = "ip6tun",
239 [IPPROTO_ESP] = "esp",
240 [IPPROTO_AH] = "ah",
241 [IPPROTO_PIM] = "pim",
242 [IPPROTO_COMP] = "comp",
245 const char *const state2str[TCP_CONNTRACK_MAX] = {
246 [TCP_CONNTRACK_NONE] = "NOSTATE",
247 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
248 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
249 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
250 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
251 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
252 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
253 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
254 [TCP_CONNTRACK_CLOSE] = "CLOSE",
255 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
258 const uint8_t states[] = {
259 TCP_CONNTRACK_SYN_SENT,
260 TCP_CONNTRACK_SYN_RECV,
261 TCP_CONNTRACK_ESTABLISHED,
262 TCP_CONNTRACK_FIN_WAIT,
263 TCP_CONNTRACK_CLOSE_WAIT,
264 TCP_CONNTRACK_LAST_ACK,
265 TCP_CONNTRACK_TIME_WAIT,
266 TCP_CONNTRACK_CLOSE,
267 TCP_CONNTRACK_SYN_SENT2,
268 TCP_CONNTRACK_NONE,
271 static void signal_handler(int number)
273 switch (number) {
274 case SIGINT:
275 sigint = 1;
276 break;
277 case SIGHUP:
278 default:
279 break;
283 static void help(void)
285 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
286 VERSION_STRING);
287 printf("http://www.netsniff-ng.org\n\n");
288 printf("Usage: flowtop [options]\n");
289 printf("Options:\n");
290 printf(" -T|--tcp Show only TCP flows (default)\n");
291 printf(" -U|--udp Show only UDP flows\n");
292 printf(" -s|--show-src Also show source, not only dest\n");
293 printf(" --city-db <path> Specifiy path for geoip city database\n");
294 printf(" --country-db <path> Specifiy path for geoip country database\n");
295 printf(" -v|--version Print version\n");
296 printf(" -h|--help Print this help\n");
297 printf("\n");
298 printf("Examples:\n");
299 printf(" flowtop\n");
300 printf(" flowtop -s\n\n");
301 printf("Note:\n");
302 printf(" If netfilter is not running, you can activate it with i.e.:\n");
303 printf(" iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n");
304 printf(" iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n");
305 printf("\n");
306 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
307 printf("Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n");
308 printf("Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n");
309 printf("License: GNU GPL version 2\n");
310 printf("This is free software: you are free to change and redistribute it.\n");
311 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
312 die();
315 static void version(void)
317 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
318 VERSION_STRING);
319 printf("http://www.netsniff-ng.org\n\n");
320 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
321 printf("Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n");
322 printf("Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n");
323 printf("License: GNU GPL version 2\n");
324 printf("This is free software: you are free to change and redistribute it.\n");
325 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
326 die();
329 static void screen_init(WINDOW **screen)
331 (*screen) = initscr();
332 noecho();
333 cbreak();
334 keypad(stdscr, TRUE);
335 nodelay(*screen, TRUE);
336 refresh();
337 wrefresh(*screen);
340 static inline uint16_t get_port(uint16_t src, uint16_t dst)
342 char *tmp1, *tmp2;
344 src = ntohs(src);
345 dst = ntohs(dst);
347 /* XXX: Is there a better way to determine? */
348 if (src < dst && src < 1024) {
349 return src;
350 } else if (dst < src && dst < 1024) {
351 return dst;
352 } else {
353 tmp1 = lookup_port_tcp(src);
354 tmp2 = lookup_port_tcp(dst);
355 if (tmp1 && !tmp2) {
356 return src;
357 } else if (!tmp1 && tmp2) {
358 return dst;
359 } else {
360 if (src < dst)
361 return src;
362 else
363 return dst;
368 static void screen_update(WINDOW *screen, struct flow_list *fl, int skip_lines)
370 int i, line = 3;
371 int maxx, maxy;
372 struct flow_entry *n;
374 curs_set(0);
375 getmaxyx(screen, maxy, maxx);
377 start_color();
378 init_pair(1, COLOR_RED, COLOR_BLACK);
379 init_pair(2, COLOR_BLUE, COLOR_BLACK);
380 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
381 init_pair(4, COLOR_GREEN, COLOR_BLACK);
383 clear();
385 rcu_read_lock();
387 mvwprintw(screen, 1, 2, "Kernel netfilter TCP/UDP flow statistics, [+%d]",
388 skip_lines);
390 if (rcu_dereference(fl->head) == NULL)
391 mvwprintw(screen, line, 2, "(No active sessions! Is netfilter running?)");
393 maxy -= 4;
394 /* Yes, that's lame :-P */
395 for (i = 0; i < sizeof(states); i++) {
396 n = rcu_dereference(fl->head);
398 while (n && maxy > 0) {
399 char tmp[128];
401 if (n->tcp_state != states[i] ||
402 (i != TCP_CONNTRACK_NONE &&
403 n->tcp_state == TCP_CONNTRACK_NONE) ||
404 /* Filter out DNS */
405 get_port(n->port_src, n->port_dst) == 53) {
406 n = rcu_dereference(n->next);
407 continue;
410 if (skip_lines > 0) {
411 n = rcu_dereference(n->next);
412 skip_lines--;
413 continue;
416 snprintf(tmp, sizeof(tmp), "%u/%s", n->procnum,
417 basename(n->cmdline));
418 tmp[sizeof(tmp) - 1] = 0;
420 mvwprintw(screen, line, 2, "[");
421 attron(COLOR_PAIR(3));
422 printw("%s", n->procnum > 0 ? tmp : "bridged(?)");
423 attroff(COLOR_PAIR(3));
424 printw("]:%s:%s[", l3proto2str[n->l3_proto],
425 proto2str[n->l4_proto]);
426 attron(COLOR_PAIR(3));
427 printw("%s", state2str[n->tcp_state]);
428 attroff(COLOR_PAIR(3));
429 printw("]:");
430 attron(A_BOLD);
431 if (n->tcp_state != TCP_CONNTRACK_NONE) {
432 printw("%s -> ", lookup_port_tcp(get_port(n->port_src,
433 n->port_dst)));
434 } else {
435 printw("%s -> ", lookup_port_udp(get_port(n->port_src,
436 n->port_dst)));
438 attroff(A_BOLD);
439 if (show_src) {
440 attron(COLOR_PAIR(1));
441 mvwprintw(screen, ++line, 8, "src: %s", n->rev_dns_src);
442 attroff(COLOR_PAIR(1));
443 printw(":%u (", ntohs(n->port_src));
444 attron(COLOR_PAIR(4));
445 printw("%s", (strlen(n->country_src) > 0 ?
446 n->country_src : "N/A"));
447 attroff(COLOR_PAIR(4));
448 printw(", %s) => ", (strlen(n->city_src) > 0 ?
449 n->city_src : "N/A"));
451 attron(COLOR_PAIR(2));
452 mvwprintw(screen, ++line, 8, "dst: %s", n->rev_dns_dst);
453 attroff(COLOR_PAIR(2));
454 printw(":%u (", ntohs(n->port_dst));
455 attron(COLOR_PAIR(4));
456 printw("%s", strlen(n->country_dst) > 0 ?
457 n->country_dst : "N/A");
458 attroff(COLOR_PAIR(4));
459 printw(", %s)", strlen(n->city_dst) > 0 ?
460 n->city_dst : "N/A");
462 line++;
463 maxy--;
464 n = rcu_dereference(n->next);
468 rcu_read_unlock();
470 wrefresh(screen);
471 refresh();
474 static void screen_end(void)
476 endwin();
479 static void presenter(void)
481 int skip_lines = 0;
482 WINDOW *screen = NULL;
484 dissector_init_ethernet(0);
485 screen_init(&screen);
486 rcu_register_thread();
488 while (!sigint) {
489 switch (getch()) {
490 case 'q':
491 sigint = 1;
492 break;
493 case KEY_UP:
494 case 'u':
495 case 'k':
496 skip_lines--;
497 if (skip_lines < 0)
498 skip_lines = 0;
499 break;
500 case KEY_DOWN:
501 case 'd':
502 case 'j':
503 skip_lines++;
504 if (skip_lines > SCROLL_MAX)
505 skip_lines = SCROLL_MAX;
506 break;
507 default:
508 fflush(stdin);
509 break;
512 screen_update(screen, &flow_list, skip_lines);
513 usleep(100000);
516 rcu_unregister_thread();
517 screen_end();
518 dissector_cleanup_ethernet();
521 static inline const char *make_n_a(const char *p)
523 return p ? : "N/A";
526 static void walk_process(char *process, struct flow_entry *n)
528 int rc;
529 DIR *dir;
530 struct dirent *ent;
531 char path[1024];
533 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
534 panic("giant process name! %s\n", process);
536 dir = opendir(path);
537 if (!dir)
538 return;
540 while ((ent = readdir(dir))) {
541 struct stat statbuf;
543 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
544 process, ent->d_name) < 0)
545 continue;
546 if (stat(path, &statbuf) < 0)
547 continue;
548 if (S_ISSOCK(statbuf.st_mode) && n->inode == statbuf.st_ino) {
549 memset(n->cmdline, 0, sizeof(n->cmdline));
550 snprintf(path, sizeof(path), "/proc/%s/exe", process);
551 rc = readlink(path, n->cmdline, sizeof(n->cmdline) - 1);
553 if (rc < 0)
554 panic("readlink error: %s\n", strerror(errno));
556 n->procnum = atoi(process);
560 closedir(dir);
563 /* Derived from ifpromisc, Fred N. van Kempen, GPL v2.0 */
564 /* n->inode must be set */
565 static void walk_processes(struct flow_entry *n)
567 DIR *dir;
568 struct dirent *ent;
570 if (n->inode <= 0) {
571 memset(n->cmdline, 0, sizeof(n->cmdline));
572 return;
575 dir = opendir("/proc");
576 if (!dir)
577 panic("Cannot open /proc!\n");
579 while ((ent = readdir(dir)))
580 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name))
581 walk_process(ent->d_name, n);
583 closedir(dir);
586 static int get_inode_from_local_port(int port, const char *proto, int ip6)
588 int ret = -ENOENT;
589 char path[128];
590 char buff[1024];
591 FILE *proc;
593 memset(path, 0, sizeof(path));
594 snprintf(path, sizeof(path), "/proc/net/%s%s", proto, ip6 ? "6" : "");
595 proc = fopen(path, "r");
596 if (!proc)
597 return -EIO;
598 memset(buff, 0, sizeof(buff));
599 while (fgets(buff, sizeof(buff), proc) != NULL) {
600 int lport = 0, inode = 0;
601 buff[sizeof(buff) - 1] = 0;
602 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
603 "%*X %*u %*u %u", &lport, &inode) == 2) {
604 if (lport == port) {
605 ret = inode;
606 break;
609 memset(buff, 0, sizeof(buff));
611 fclose(proc);
613 return ret;
616 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
618 n->flow_id = nfct_get_attr_u32(ct, ATTR_ID);
619 n->use = nfct_get_attr_u32(ct, ATTR_USE);
620 n->status = nfct_get_attr_u32(ct, ATTR_STATUS);
621 n->l3_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L3PROTO);
622 n->l4_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L4PROTO);
623 n->ip4_src_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_SRC);
624 n->ip4_dst_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_DST);
626 const uint8_t *ipv6_src = nfct_get_attr(ct, ATTR_ORIG_IPV6_SRC);
627 if (ipv6_src)
628 memcpy(n->ip6_src_addr, ipv6_src, sizeof(n->ip6_src_addr));
629 const uint8_t *ipv6_dst = nfct_get_attr(ct, ATTR_ORIG_IPV6_DST);
630 if (ipv6_dst)
631 memcpy(n->ip6_dst_addr, ipv6_dst, sizeof(n->ip6_dst_addr));
633 n->port_src = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_SRC);
634 n->port_dst = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_DST);
635 n->tcp_state = nfct_get_attr_u8(ct, ATTR_TCP_STATE);
636 n->tcp_flags = nfct_get_attr_u8(ct, ATTR_TCP_FLAGS_ORIG);
637 n->counter_pkts = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_PACKETS);
638 n->counter_bytes = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_BYTES);
639 n->timestamp_start = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_START);
640 n->timestamp_stop = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_STOP);
642 if (n->first) {
643 n->inode = get_inode_from_local_port(ntohs(n->port_src),
644 proto2str[n->l4_proto],
645 !!(ipv6_src));
646 if (n->inode > 0)
647 walk_processes(n);
649 /* if this really runs on a router, we try it once and then let it be */
650 n->first = 0;
653 /* TODO: IP4 + IP6 */
654 static void flow_entry_get_extended(struct flow_entry *n)
656 struct sockaddr_in sa;
657 struct hostent *hent;
658 GeoIPRecord *gir_src, *gir_dst;
660 if (n->flow_id == 0)
661 return;
662 if (ntohs(n->port_src) == 53 || ntohs(n->port_dst) == 53)
663 return;
665 memset(&sa, 0, sizeof(sa));
666 sa.sin_family = PF_INET; //XXX: IPv4
667 sa.sin_addr.s_addr = n->ip4_src_addr;
668 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_src,
669 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
671 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
672 if (hent) {
673 memset(n->rev_dns_src, 0, sizeof(n->rev_dns_src));
674 memcpy(n->rev_dns_src, hent->h_name,
675 min(sizeof(n->rev_dns_src), strlen(hent->h_name)));
678 gir_src = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_src_addr));
679 if (gir_src) {
680 const char *country =
681 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
682 ntohl(n->ip4_src_addr)));
683 const char *city = make_n_a(gir_src->city);
684 memcpy(n->country_src, country,
685 min(sizeof(n->country_src), strlen(country)));
686 memcpy(n->city_src, city,
687 min(sizeof(n->city_src), strlen(city)));
690 memset(&sa, 0, sizeof(sa));
691 sa.sin_family = PF_INET; //XXX: IPv4
692 sa.sin_addr.s_addr = n->ip4_dst_addr;
693 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_dst,
694 sizeof(n->rev_dns_dst), NULL, 0, NI_NUMERICHOST);
696 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
697 if (hent) {
698 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
699 memcpy(n->rev_dns_dst, hent->h_name,
700 min(sizeof(n->rev_dns_dst), strlen(hent->h_name)));
703 gir_dst = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_dst_addr));
704 if (gir_dst) {
705 const char *country =
706 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
707 ntohl(n->ip4_dst_addr)));
708 const char *city = make_n_a(gir_dst->city);
709 memcpy(n->country_dst, country,
710 min(sizeof(n->country_dst), strlen(country)));
711 memcpy(n->city_dst, city,
712 min(sizeof(n->city_dst), strlen(city)));
716 static void flow_list_init(struct flow_list *fl)
718 fl->head = NULL;
719 spinlock_init(&fl->lock);
722 static struct flow_entry *__flow_list_find_by_id(struct flow_list *fl, uint32_t id)
724 struct flow_entry *n = rcu_dereference(fl->head);
725 while (n != NULL) {
726 if (n->flow_id == id)
727 return n;
728 n = rcu_dereference(n->next);
730 return NULL;
733 static struct flow_entry *__flow_list_find_prev_by_id(struct flow_list *fl, uint32_t id)
735 struct flow_entry *n = rcu_dereference(fl->head);
736 if (n->flow_id == id)
737 return NULL;
738 while (rcu_dereference(n->next) != NULL) {
739 if (rcu_dereference(n->next)->flow_id == id)
740 return n;
741 n = rcu_dereference(n->next);
743 return NULL;
746 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
748 struct flow_entry *n = xzmalloc(sizeof(*n));
749 n->first = 1;
750 rcu_assign_pointer(n->next, fl->head);
751 rcu_assign_pointer(fl->head, n);
752 flow_entry_from_ct(n, ct);
753 flow_entry_get_extended(n);
756 static void flow_list_update_entry(struct flow_list *fl, struct nf_conntrack *ct)
758 int do_ext = 0;
759 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
760 struct flow_entry *n;
761 n = __flow_list_find_by_id(fl, id);
762 if (n == NULL) {
763 n = xzmalloc(sizeof(*n));
764 n->first = 1;
765 rcu_assign_pointer(n->next, fl->head);
766 rcu_assign_pointer(fl->head, n);
767 do_ext = 1;
769 flow_entry_from_ct(n, ct);
770 if (do_ext)
771 flow_entry_get_extended(n);
774 static void flow_list_destroy_entry(struct flow_list *fl, struct nf_conntrack *ct)
776 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
777 struct flow_entry *n1, *n2;
779 n1 = __flow_list_find_by_id(fl, id);
780 if (n1) {
781 n2 = __flow_list_find_prev_by_id(fl, id);
782 if (n2) {
783 rcu_assign_pointer(n2->next, n1->next);
784 rcu_assign_pointer(n1->next, NULL);
785 xfree(n1);
786 } else {
787 xfree(fl->head);
788 rcu_assign_pointer(fl->head, NULL);
793 static void flow_list_destroy(struct flow_list *fl)
795 struct flow_entry *n;
797 while (fl->head != NULL) {
798 n = rcu_dereference(fl->head->next);
799 rcu_assign_pointer(fl->head->next, NULL);
800 xfree(fl->head);
801 rcu_assign_pointer(fl->head, n);
804 synchronize_rcu();
805 spinlock_destroy(&fl->lock);
808 static int collector_cb(enum nf_conntrack_msg_type type,
809 struct nf_conntrack *ct,
810 void *data)
812 if (sigint)
813 return NFCT_CB_STOP;
815 synchronize_rcu();
817 spinlock_lock(&flow_list.lock);
818 switch (type) {
819 case NFCT_T_NEW:
820 flow_list_new_entry(&flow_list, ct);
821 break;
822 case NFCT_T_UPDATE:
823 flow_list_update_entry(&flow_list, ct);
824 break;
825 case NFCT_T_DESTROY:
826 flow_list_destroy_entry(&flow_list, ct);
827 break;
828 default:
829 break;
831 spinlock_unlock(&flow_list.lock);
833 return NFCT_CB_CONTINUE;
836 static int dummy_cb(enum nf_conntrack_msg_type type, struct nf_conntrack *ct,
837 void *data)
839 return NFCT_CB_STOP;
842 static void *collector(void *null)
844 int ret;
845 u_int32_t family = AF_INET;
846 struct nfct_handle *handle;
847 struct nfct_filter *filter;
849 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
850 if (!handle)
851 panic("Cannot create a nfct handle!\n");
853 /* Hack: inits ct */
854 nfct_callback_register(handle, NFCT_T_ALL, dummy_cb, NULL);
855 nfct_query(handle, NFCT_Q_DUMP, &family);
856 nfct_close(handle);
858 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
859 if (!handle)
860 panic("Cannot create a nfct handle!\n");
862 nfct_query(handle, NFCT_Q_FLUSH, &family);
864 filter = nfct_filter_create();
865 if (!filter)
866 panic("Cannot create a nfct filter!\n");
867 if (what & INCLUDE_UDP)
868 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
869 if (what & INCLUDE_TCP)
870 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
872 struct nfct_filter_ipv4 filter_ipv4 = {
873 .addr = ntohl(INADDR_LOOPBACK),
874 .mask = 0xffffffff,
877 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4,
878 NFCT_FILTER_LOGIC_NEGATIVE);
879 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
881 struct nfct_filter_ipv6 filter_ipv6 = {
882 .addr = { 0x0, 0x0, 0x0, 0x1 },
883 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
886 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6,
887 NFCT_FILTER_LOGIC_NEGATIVE);
888 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
890 ret = nfct_filter_attach(nfct_fd(handle), filter);
891 if (ret < 0)
892 panic("Cannot attach filter to handle!\n");
894 nfct_filter_destroy(filter);
896 if (path_country_db)
897 gi_country = GeoIP_open(path_country_db, GEOIP_MMAP_CACHE);
898 else
899 gi_country = GeoIP_open_type(GEOIP_COUNTRY_EDITION,
900 GEOIP_MMAP_CACHE);
902 if (path_city_db)
903 gi_city = GeoIP_open(path_city_db, GEOIP_MMAP_CACHE);
904 else
905 gi_city = GeoIP_open_type(GEOIP_CITY_EDITION_REV1,
906 GEOIP_MMAP_CACHE);
907 if (!gi_country || !gi_city)
908 panic("Cannot open GeoIP database!\n");
910 GeoIP_set_charset(gi_country, GEOIP_CHARSET_UTF8);
911 GeoIP_set_charset(gi_city, GEOIP_CHARSET_UTF8);
913 flow_list_init(&flow_list);
915 rcu_register_thread();
917 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
919 while (!sigint)
920 nfct_catch(handle);
922 rcu_unregister_thread();
924 flow_list_destroy(&flow_list);
926 GeoIP_delete(gi_city);
927 GeoIP_delete(gi_country);
929 nfct_close(handle);
931 if (path_city_db)
932 xfree(path_city_db);
933 if (path_country_db)
934 xfree(path_country_db);
936 pthread_exit(0);
939 int main(int argc, char **argv)
941 pthread_t tid;
942 int ret, c, opt_index, what_cmd = 0;
944 check_for_root_maybe_die();
946 while ((c = getopt_long(argc, argv, short_options, long_options,
947 &opt_index)) != EOF) {
948 switch (c) {
949 case 'T':
950 what_cmd |= INCLUDE_TCP;
951 break;
952 case 'U':
953 what_cmd |= INCLUDE_UDP;
954 break;
955 case 's':
956 show_src = 1;
957 break;
958 case 'L':
959 path_city_db = xstrdup(optarg);
960 break;
961 case 'K':
962 path_country_db = xstrdup(optarg);
963 break;
964 case 'h':
965 help();
966 break;
967 case 'v':
968 version();
969 break;
970 case '?':
971 switch (optopt) {
972 case 'L':
973 case 'K':
974 panic("Option -%c requires an argument!\n",
975 optopt);
976 default:
977 if (isprint(optopt))
978 whine("Unknown option character "
979 "`0x%X\'!\n", optopt);
980 die();
982 default:
983 break;
987 if (what_cmd > 0)
988 what = what_cmd;
990 rcu_init();
992 register_signal(SIGINT, signal_handler);
993 register_signal(SIGHUP, signal_handler);
995 ret = pthread_create(&tid, NULL, collector, NULL);
996 if (ret < 0)
997 panic("Cannot create phthread!\n");
999 presenter();
1000 return 0;