doc: new fedora/rhel maintainer
[netsniff-ng.git] / src / flowtop.c
blob9adf8dbebecf7813242483549843c4f6fdcd08e6
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
27 #define _LGPL_SOURCE
28 #include <stdio.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <signal.h>
32 #include <getopt.h>
33 #include <pthread.h>
34 #include <signal.h>
35 #include <netdb.h>
36 #include <ctype.h>
37 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
38 #include <libnetfilter_conntrack/libnetfilter_conntrack_tcp.h>
39 #include <GeoIP.h>
40 #include <GeoIPCity.h>
41 #include <netinet/in.h>
42 #include <curses.h>
43 #include <dirent.h>
44 #include <sys/stat.h>
45 #include <urcu.h>
46 #include <libgen.h>
48 #include "die.h"
49 #include "xmalloc.h"
50 #include "xio.h"
51 #include "xutils.h"
52 #include "built_in.h"
53 #include "locking.h"
54 #include "dissector_eth.h"
55 #include "pkt_buff.h"
57 #define INCLUDE_UDP (1 << 0)
58 #define INCLUDE_TCP (1 << 1)
60 #ifndef ATTR_TIMESTAMP_START
61 # define ATTR_TIMESTAMP_START 63
62 #endif
63 #ifndef ATTR_TIMESTAMP_STOP
64 # define ATTR_TIMESTAMP_STOP 64
65 #endif
67 #define SCROLL_MAX 1000
69 struct flow_entry {
70 uint32_t flow_id;
71 int first;
72 struct flow_entry *next;
73 uint32_t use;
74 uint32_t status;
75 uint8_t l3_proto;
76 uint8_t l4_proto;
77 uint32_t ip4_src_addr;
78 uint32_t ip4_dst_addr;
79 uint32_t ip6_src_addr[4];
80 uint32_t ip6_dst_addr[4];
81 uint16_t port_src;
82 uint16_t port_dst;
83 uint8_t tcp_state;
84 uint8_t tcp_flags;
85 uint64_t counter_pkts;
86 uint64_t counter_bytes;
87 uint64_t timestamp_start;
88 uint64_t timestamp_stop;
89 char country_src[128];
90 char city_src[128];
91 char rev_dns_src[256];
92 char country_dst[128];
93 char city_dst[128];
94 char rev_dns_dst[256];
95 int procnum;
96 int inode;
97 char cmdline[256];
100 struct flow_list {
101 struct flow_entry *head;
102 struct spinlock lock;
105 volatile sig_atomic_t sigint = 0;
107 static int what = INCLUDE_TCP;
109 static int show_src = 0;
111 static struct flow_list flow_list;
113 static GeoIP *gi_country = NULL;
114 static GeoIP *gi_city = NULL;
116 static char *path_city_db = NULL, *path_country_db = NULL;
118 static const char *short_options = "vhTULKs";
120 static struct option long_options[] = {
121 {"tcp", no_argument, 0, 'T'},
122 {"udp", no_argument, 0, 'U'},
123 {"show-src", no_argument, 0, 's'},
124 {"city-db", required_argument, 0, 'L'},
125 {"country-db", required_argument, 0, 'K'},
126 {"version", no_argument, 0, 'v'},
127 {"help", no_argument, 0, 'h'},
128 {0, 0, 0, 0}
131 const char *const l3proto2str[AF_MAX] = {
132 [AF_INET] = "ipv4",
133 [AF_INET6] = "ipv6",
136 const char *const proto2str[IPPROTO_MAX] = {
137 [IPPROTO_TCP] = "tcp",
138 [IPPROTO_UDP] = "udp",
139 [IPPROTO_UDPLITE] = "udplite",
140 [IPPROTO_ICMP] = "icmp",
141 [IPPROTO_ICMPV6] = "icmpv6",
142 [IPPROTO_SCTP] = "sctp",
143 [IPPROTO_GRE] = "gre",
144 [IPPROTO_DCCP] = "dccp",
145 [IPPROTO_IGMP] = "igmp",
146 [IPPROTO_IPIP] = "ipip",
147 [IPPROTO_EGP] = "egp",
148 [IPPROTO_PUP] = "pup",
149 [IPPROTO_IDP] = "idp",
150 [IPPROTO_RSVP] = "rsvp",
151 [IPPROTO_IPV6] = "ip6tun",
152 [IPPROTO_ESP] = "esp",
153 [IPPROTO_AH] = "ah",
154 [IPPROTO_PIM] = "pim",
155 [IPPROTO_COMP] = "comp",
158 const char *const state2str[TCP_CONNTRACK_MAX] = {
159 [TCP_CONNTRACK_NONE] = "NOSTATE",
160 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
161 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
162 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
163 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
164 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
165 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
166 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
167 [TCP_CONNTRACK_CLOSE] = "CLOSE",
168 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
171 const uint8_t states[] = {
172 TCP_CONNTRACK_SYN_SENT,
173 TCP_CONNTRACK_SYN_RECV,
174 TCP_CONNTRACK_ESTABLISHED,
175 TCP_CONNTRACK_FIN_WAIT,
176 TCP_CONNTRACK_CLOSE_WAIT,
177 TCP_CONNTRACK_LAST_ACK,
178 TCP_CONNTRACK_TIME_WAIT,
179 TCP_CONNTRACK_CLOSE,
180 TCP_CONNTRACK_SYN_SENT2,
181 TCP_CONNTRACK_NONE,
184 static void signal_handler(int number)
186 switch (number) {
187 case SIGINT:
188 sigint = 1;
189 break;
190 case SIGHUP:
191 default:
192 break;
196 static void help(void)
198 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
199 VERSION_STRING);
200 printf("http://www.netsniff-ng.org\n\n");
201 printf("Usage: flowtop [options]\n");
202 printf("Options:\n");
203 printf(" -T|--tcp Show only TCP flows (default)\n");
204 printf(" -U|--udp Show only UDP flows\n");
205 printf(" -s|--show-src Also show source, not only dest\n");
206 printf(" --city-db <path> Specifiy path for geoip city database\n");
207 printf(" --country-db <path> Specifiy path for geoip country database\n");
208 printf(" -v|--version Print version\n");
209 printf(" -h|--help Print this help\n");
210 printf("\n");
211 printf("Examples:\n");
212 printf(" flowtop\n");
213 printf(" flowtop -s\n\n");
214 printf("Note:\n");
215 printf(" If netfilter is not running, you can activate it with i.e.:\n");
216 printf(" iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n");
217 printf(" iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n");
218 printf("\n");
219 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
220 printf("Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n");
221 printf("Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n");
222 printf("License: GNU GPL version 2\n");
223 printf("This is free software: you are free to change and redistribute it.\n");
224 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
225 die();
228 static void version(void)
230 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
231 VERSION_STRING);
232 printf("http://www.netsniff-ng.org\n\n");
233 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
234 printf("Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n");
235 printf("Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n");
236 printf("License: GNU GPL version 2\n");
237 printf("This is free software: you are free to change and redistribute it.\n");
238 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
239 die();
242 static void screen_init(WINDOW **screen)
244 (*screen) = initscr();
245 noecho();
246 cbreak();
247 keypad(stdscr, TRUE);
248 nodelay(*screen, TRUE);
249 refresh();
250 wrefresh(*screen);
253 static inline uint16_t get_port(uint16_t src, uint16_t dst)
255 char *tmp1, *tmp2;
257 src = ntohs(src);
258 dst = ntohs(dst);
260 /* XXX: Is there a better way to determine? */
261 if (src < dst && src < 1024) {
262 return src;
263 } else if (dst < src && dst < 1024) {
264 return dst;
265 } else {
266 tmp1 = lookup_port_tcp(src);
267 tmp2 = lookup_port_tcp(dst);
268 if (tmp1 && !tmp2) {
269 return src;
270 } else if (!tmp1 && tmp2) {
271 return dst;
272 } else {
273 if (src < dst)
274 return src;
275 else
276 return dst;
281 static void screen_update(WINDOW *screen, struct flow_list *fl, int skip_lines)
283 int i, line = 3;
284 int maxy;
285 struct flow_entry *n;
287 curs_set(0);
288 maxy = getmaxy(screen);
290 start_color();
291 init_pair(1, COLOR_RED, COLOR_BLACK);
292 init_pair(2, COLOR_BLUE, COLOR_BLACK);
293 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
294 init_pair(4, COLOR_GREEN, COLOR_BLACK);
296 clear();
298 rcu_read_lock();
300 mvwprintw(screen, 1, 2, "Kernel netfilter TCP/UDP flow statistics, [+%d]",
301 skip_lines);
303 if (rcu_dereference(fl->head) == NULL)
304 mvwprintw(screen, line, 2, "(No active sessions! Is netfilter running?)");
306 maxy -= 4;
307 /* Yes, that's lame :-P */
308 for (i = 0; i < sizeof(states); i++) {
309 n = rcu_dereference(fl->head);
311 while (n && maxy > 0) {
312 char tmp[128];
314 if (n->tcp_state != states[i] ||
315 (i != TCP_CONNTRACK_NONE &&
316 n->tcp_state == TCP_CONNTRACK_NONE) ||
317 /* Filter out DNS */
318 get_port(n->port_src, n->port_dst) == 53) {
319 n = rcu_dereference(n->next);
320 continue;
323 if (skip_lines > 0) {
324 n = rcu_dereference(n->next);
325 skip_lines--;
326 continue;
329 snprintf(tmp, sizeof(tmp), "%u/%s", n->procnum,
330 basename(n->cmdline));
331 tmp[sizeof(tmp) - 1] = 0;
333 mvwprintw(screen, line, 2, "[");
334 attron(COLOR_PAIR(3));
335 printw("%s", n->procnum > 0 ? tmp : "bridged(?)");
336 attroff(COLOR_PAIR(3));
337 printw("]:%s:%s[", l3proto2str[n->l3_proto],
338 proto2str[n->l4_proto]);
339 attron(COLOR_PAIR(3));
340 printw("%s", state2str[n->tcp_state]);
341 attroff(COLOR_PAIR(3));
342 printw("]:");
343 attron(A_BOLD);
344 if (n->tcp_state != TCP_CONNTRACK_NONE) {
345 printw("%s -> ", lookup_port_tcp(get_port(n->port_src,
346 n->port_dst)));
347 } else {
348 printw("%s -> ", lookup_port_udp(get_port(n->port_src,
349 n->port_dst)));
351 attroff(A_BOLD);
352 if (show_src) {
353 attron(COLOR_PAIR(1));
354 mvwprintw(screen, ++line, 8, "src: %s", n->rev_dns_src);
355 attroff(COLOR_PAIR(1));
356 printw(":%u (", ntohs(n->port_src));
357 attron(COLOR_PAIR(4));
358 printw("%s", (strlen(n->country_src) > 0 ?
359 n->country_src : "N/A"));
360 attroff(COLOR_PAIR(4));
361 printw(", %s) => ", (strlen(n->city_src) > 0 ?
362 n->city_src : "N/A"));
364 attron(COLOR_PAIR(2));
365 mvwprintw(screen, ++line, 8, "dst: %s", n->rev_dns_dst);
366 attroff(COLOR_PAIR(2));
367 printw(":%u (", ntohs(n->port_dst));
368 attron(COLOR_PAIR(4));
369 printw("%s", strlen(n->country_dst) > 0 ?
370 n->country_dst : "N/A");
371 attroff(COLOR_PAIR(4));
372 printw(", %s)", strlen(n->city_dst) > 0 ?
373 n->city_dst : "N/A");
375 line++;
376 maxy--;
377 n = rcu_dereference(n->next);
381 rcu_read_unlock();
383 wrefresh(screen);
384 refresh();
387 static void screen_end(void)
389 endwin();
392 static void presenter(void)
394 int skip_lines = 0;
395 WINDOW *screen = NULL;
397 dissector_init_ethernet(0);
398 screen_init(&screen);
399 rcu_register_thread();
401 while (!sigint) {
402 switch (getch()) {
403 case 'q':
404 sigint = 1;
405 break;
406 case KEY_UP:
407 case 'u':
408 case 'k':
409 skip_lines--;
410 if (skip_lines < 0)
411 skip_lines = 0;
412 break;
413 case KEY_DOWN:
414 case 'd':
415 case 'j':
416 skip_lines++;
417 if (skip_lines > SCROLL_MAX)
418 skip_lines = SCROLL_MAX;
419 break;
420 default:
421 fflush(stdin);
422 break;
425 screen_update(screen, &flow_list, skip_lines);
426 usleep(100000);
429 rcu_unregister_thread();
430 screen_end();
431 dissector_cleanup_ethernet();
434 static inline const char *make_n_a(const char *p)
436 return p ? : "N/A";
439 static void walk_process(char *process, struct flow_entry *n)
441 int rc;
442 DIR *dir;
443 struct dirent *ent;
444 char path[1024];
446 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
447 panic("giant process name! %s\n", process);
449 dir = opendir(path);
450 if (!dir)
451 return;
453 while ((ent = readdir(dir))) {
454 struct stat statbuf;
456 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
457 process, ent->d_name) < 0)
458 continue;
459 if (stat(path, &statbuf) < 0)
460 continue;
461 if (S_ISSOCK(statbuf.st_mode) && n->inode == statbuf.st_ino) {
462 memset(n->cmdline, 0, sizeof(n->cmdline));
463 snprintf(path, sizeof(path), "/proc/%s/exe", process);
464 rc = readlink(path, n->cmdline, sizeof(n->cmdline) - 1);
466 if (rc < 0)
467 panic("readlink error: %s\n", strerror(errno));
469 n->procnum = atoi(process);
473 closedir(dir);
476 /* Derived from ifpromisc, Fred N. van Kempen, GPL v2.0 */
477 /* n->inode must be set */
478 static void walk_processes(struct flow_entry *n)
480 DIR *dir;
481 struct dirent *ent;
483 if (n->inode <= 0) {
484 memset(n->cmdline, 0, sizeof(n->cmdline));
485 return;
488 dir = opendir("/proc");
489 if (!dir)
490 panic("Cannot open /proc!\n");
492 while ((ent = readdir(dir)))
493 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name))
494 walk_process(ent->d_name, n);
496 closedir(dir);
499 static int get_inode_from_local_port(int port, const char *proto, int ip6)
501 int ret = -ENOENT;
502 char path[128];
503 char buff[1024];
504 FILE *proc;
506 memset(path, 0, sizeof(path));
507 snprintf(path, sizeof(path), "/proc/net/%s%s", proto, ip6 ? "6" : "");
508 proc = fopen(path, "r");
509 if (!proc)
510 return -EIO;
511 memset(buff, 0, sizeof(buff));
512 while (fgets(buff, sizeof(buff), proc) != NULL) {
513 int lport = 0, inode = 0;
514 buff[sizeof(buff) - 1] = 0;
515 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
516 "%*X %*u %*u %u", &lport, &inode) == 2) {
517 if (lport == port) {
518 ret = inode;
519 break;
522 memset(buff, 0, sizeof(buff));
524 fclose(proc);
526 return ret;
529 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
531 n->flow_id = nfct_get_attr_u32(ct, ATTR_ID);
532 n->use = nfct_get_attr_u32(ct, ATTR_USE);
533 n->status = nfct_get_attr_u32(ct, ATTR_STATUS);
534 n->l3_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L3PROTO);
535 n->l4_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L4PROTO);
536 n->ip4_src_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_SRC);
537 n->ip4_dst_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_DST);
539 const uint8_t *ipv6_src = nfct_get_attr(ct, ATTR_ORIG_IPV6_SRC);
540 if (ipv6_src)
541 memcpy(n->ip6_src_addr, ipv6_src, sizeof(n->ip6_src_addr));
542 const uint8_t *ipv6_dst = nfct_get_attr(ct, ATTR_ORIG_IPV6_DST);
543 if (ipv6_dst)
544 memcpy(n->ip6_dst_addr, ipv6_dst, sizeof(n->ip6_dst_addr));
546 n->port_src = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_SRC);
547 n->port_dst = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_DST);
548 n->tcp_state = nfct_get_attr_u8(ct, ATTR_TCP_STATE);
549 n->tcp_flags = nfct_get_attr_u8(ct, ATTR_TCP_FLAGS_ORIG);
550 n->counter_pkts = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_PACKETS);
551 n->counter_bytes = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_BYTES);
552 n->timestamp_start = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_START);
553 n->timestamp_stop = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_STOP);
555 if (n->first) {
556 n->inode = get_inode_from_local_port(ntohs(n->port_src),
557 proto2str[n->l4_proto],
558 !!(ipv6_src));
559 if (n->inode > 0)
560 walk_processes(n);
562 /* if this really runs on a router, we try it once and then let it be */
563 n->first = 0;
566 /* TODO: IP4 + IP6 */
567 static void flow_entry_get_extended(struct flow_entry *n)
569 struct sockaddr_in sa;
570 struct hostent *hent;
571 GeoIPRecord *gir_src, *gir_dst;
573 if (n->flow_id == 0)
574 return;
575 if (ntohs(n->port_src) == 53 || ntohs(n->port_dst) == 53)
576 return;
578 memset(&sa, 0, sizeof(sa));
579 sa.sin_family = PF_INET; //XXX: IPv4
580 sa.sin_addr.s_addr = n->ip4_src_addr;
581 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_src,
582 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
584 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
585 if (hent) {
586 memset(n->rev_dns_src, 0, sizeof(n->rev_dns_src));
587 memcpy(n->rev_dns_src, hent->h_name,
588 min(sizeof(n->rev_dns_src), strlen(hent->h_name)));
591 gir_src = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_src_addr));
592 if (gir_src) {
593 const char *country =
594 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
595 ntohl(n->ip4_src_addr)));
596 const char *city = make_n_a(gir_src->city);
597 memcpy(n->country_src, country,
598 min(sizeof(n->country_src), strlen(country)));
599 memcpy(n->city_src, city,
600 min(sizeof(n->city_src), strlen(city)));
603 memset(&sa, 0, sizeof(sa));
604 sa.sin_family = PF_INET; //XXX: IPv4
605 sa.sin_addr.s_addr = n->ip4_dst_addr;
606 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_dst,
607 sizeof(n->rev_dns_dst), NULL, 0, NI_NUMERICHOST);
609 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
610 if (hent) {
611 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
612 memcpy(n->rev_dns_dst, hent->h_name,
613 min(sizeof(n->rev_dns_dst), strlen(hent->h_name)));
616 gir_dst = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_dst_addr));
617 if (gir_dst) {
618 const char *country =
619 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
620 ntohl(n->ip4_dst_addr)));
621 const char *city = make_n_a(gir_dst->city);
622 memcpy(n->country_dst, country,
623 min(sizeof(n->country_dst), strlen(country)));
624 memcpy(n->city_dst, city,
625 min(sizeof(n->city_dst), strlen(city)));
629 static void flow_list_init(struct flow_list *fl)
631 fl->head = NULL;
632 spinlock_init(&fl->lock);
635 static struct flow_entry *__flow_list_find_by_id(struct flow_list *fl, uint32_t id)
637 struct flow_entry *n = rcu_dereference(fl->head);
638 while (n != NULL) {
639 if (n->flow_id == id)
640 return n;
641 n = rcu_dereference(n->next);
643 return NULL;
646 static struct flow_entry *__flow_list_find_prev_by_id(struct flow_list *fl, uint32_t id)
648 struct flow_entry *n = rcu_dereference(fl->head);
649 if (n->flow_id == id)
650 return NULL;
651 while (rcu_dereference(n->next) != NULL) {
652 if (rcu_dereference(n->next)->flow_id == id)
653 return n;
654 n = rcu_dereference(n->next);
656 return NULL;
659 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
661 struct flow_entry *n = xzmalloc(sizeof(*n));
662 n->first = 1;
663 rcu_assign_pointer(n->next, fl->head);
664 rcu_assign_pointer(fl->head, n);
665 flow_entry_from_ct(n, ct);
666 flow_entry_get_extended(n);
669 static void flow_list_update_entry(struct flow_list *fl, struct nf_conntrack *ct)
671 int do_ext = 0;
672 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
673 struct flow_entry *n;
674 n = __flow_list_find_by_id(fl, id);
675 if (n == NULL) {
676 n = xzmalloc(sizeof(*n));
677 n->first = 1;
678 rcu_assign_pointer(n->next, fl->head);
679 rcu_assign_pointer(fl->head, n);
680 do_ext = 1;
682 flow_entry_from_ct(n, ct);
683 if (do_ext)
684 flow_entry_get_extended(n);
687 static void flow_list_destroy_entry(struct flow_list *fl, struct nf_conntrack *ct)
689 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
690 struct flow_entry *n1, *n2;
692 n1 = __flow_list_find_by_id(fl, id);
693 if (n1) {
694 n2 = __flow_list_find_prev_by_id(fl, id);
695 if (n2) {
696 rcu_assign_pointer(n2->next, n1->next);
697 rcu_assign_pointer(n1->next, NULL);
698 xfree(n1);
699 } else {
700 xfree(fl->head);
701 rcu_assign_pointer(fl->head, NULL);
706 static void flow_list_destroy(struct flow_list *fl)
708 struct flow_entry *n;
710 while (fl->head != NULL) {
711 n = rcu_dereference(fl->head->next);
712 rcu_assign_pointer(fl->head->next, NULL);
713 xfree(fl->head);
714 rcu_assign_pointer(fl->head, n);
717 synchronize_rcu();
718 spinlock_destroy(&fl->lock);
721 static int collector_cb(enum nf_conntrack_msg_type type,
722 struct nf_conntrack *ct,
723 void *data)
725 if (sigint)
726 return NFCT_CB_STOP;
728 synchronize_rcu();
730 spinlock_lock(&flow_list.lock);
731 switch (type) {
732 case NFCT_T_NEW:
733 flow_list_new_entry(&flow_list, ct);
734 break;
735 case NFCT_T_UPDATE:
736 flow_list_update_entry(&flow_list, ct);
737 break;
738 case NFCT_T_DESTROY:
739 flow_list_destroy_entry(&flow_list, ct);
740 break;
741 default:
742 break;
744 spinlock_unlock(&flow_list.lock);
746 return NFCT_CB_CONTINUE;
749 static int dummy_cb(enum nf_conntrack_msg_type type, struct nf_conntrack *ct,
750 void *data)
752 return NFCT_CB_STOP;
755 static void *collector(void *null)
757 int ret;
758 u_int32_t family = AF_INET;
759 struct nfct_handle *handle;
760 struct nfct_filter *filter;
762 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
763 if (!handle)
764 panic("Cannot create a nfct handle!\n");
766 /* Hack: inits ct */
767 nfct_callback_register(handle, NFCT_T_ALL, dummy_cb, NULL);
768 nfct_query(handle, NFCT_Q_DUMP, &family);
769 nfct_close(handle);
771 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
772 if (!handle)
773 panic("Cannot create a nfct handle!\n");
775 nfct_query(handle, NFCT_Q_FLUSH, &family);
777 filter = nfct_filter_create();
778 if (!filter)
779 panic("Cannot create a nfct filter!\n");
780 if (what & INCLUDE_UDP)
781 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
782 if (what & INCLUDE_TCP)
783 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
785 struct nfct_filter_ipv4 filter_ipv4 = {
786 .addr = ntohl(INADDR_LOOPBACK),
787 .mask = 0xffffffff,
790 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4,
791 NFCT_FILTER_LOGIC_NEGATIVE);
792 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
794 struct nfct_filter_ipv6 filter_ipv6 = {
795 .addr = { 0x0, 0x0, 0x0, 0x1 },
796 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
799 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6,
800 NFCT_FILTER_LOGIC_NEGATIVE);
801 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
803 ret = nfct_filter_attach(nfct_fd(handle), filter);
804 if (ret < 0)
805 panic("Cannot attach filter to handle!\n");
807 nfct_filter_destroy(filter);
809 if (path_country_db)
810 gi_country = GeoIP_open(path_country_db, GEOIP_MMAP_CACHE);
811 else
812 gi_country = GeoIP_open_type(GEOIP_COUNTRY_EDITION,
813 GEOIP_MMAP_CACHE);
815 if (path_city_db)
816 gi_city = GeoIP_open(path_city_db, GEOIP_MMAP_CACHE);
817 else
818 gi_city = GeoIP_open_type(GEOIP_CITY_EDITION_REV1,
819 GEOIP_MMAP_CACHE);
820 if (!gi_country || !gi_city)
821 panic("Cannot open GeoIP database!\n");
823 GeoIP_set_charset(gi_country, GEOIP_CHARSET_UTF8);
824 GeoIP_set_charset(gi_city, GEOIP_CHARSET_UTF8);
826 flow_list_init(&flow_list);
828 rcu_register_thread();
830 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
832 while (!sigint)
833 nfct_catch(handle);
835 rcu_unregister_thread();
837 flow_list_destroy(&flow_list);
839 GeoIP_delete(gi_city);
840 GeoIP_delete(gi_country);
842 nfct_close(handle);
844 if (path_city_db)
845 xfree(path_city_db);
846 if (path_country_db)
847 xfree(path_country_db);
849 pthread_exit(0);
852 int main(int argc, char **argv)
854 pthread_t tid;
855 int ret, c, opt_index, what_cmd = 0;
857 check_for_root_maybe_die();
859 while ((c = getopt_long(argc, argv, short_options, long_options,
860 &opt_index)) != EOF) {
861 switch (c) {
862 case 'T':
863 what_cmd |= INCLUDE_TCP;
864 break;
865 case 'U':
866 what_cmd |= INCLUDE_UDP;
867 break;
868 case 's':
869 show_src = 1;
870 break;
871 case 'L':
872 path_city_db = xstrdup(optarg);
873 break;
874 case 'K':
875 path_country_db = xstrdup(optarg);
876 break;
877 case 'h':
878 help();
879 break;
880 case 'v':
881 version();
882 break;
883 case '?':
884 switch (optopt) {
885 case 'L':
886 case 'K':
887 panic("Option -%c requires an argument!\n",
888 optopt);
889 default:
890 if (isprint(optopt))
891 whine("Unknown option character "
892 "`0x%X\'!\n", optopt);
893 die();
895 default:
896 break;
900 if (what_cmd > 0)
901 what = what_cmd;
903 rcu_init();
905 register_signal(SIGINT, signal_handler);
906 register_signal(SIGHUP, signal_handler);
908 ret = pthread_create(&tid, NULL, collector, NULL);
909 if (ret < 0)
910 panic("Cannot create phthread!\n");
912 presenter();
913 return 0;