docs: add Jon as minor contributor
[netsniff-ng.git] / src / flowtop.c
blob729dce435d4e0b6a5ec88897d4843e19df97dbcd
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'.
18 #define _LGPL_SOURCE
19 #include <stdio.h>
20 #include <stdint.h>
21 #include <stdlib.h>
22 #include <signal.h>
23 #include <getopt.h>
24 #include <pthread.h>
25 #include <signal.h>
26 #include <netdb.h>
27 #include <ctype.h>
28 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
29 #include <libnetfilter_conntrack/libnetfilter_conntrack_tcp.h>
30 #include <GeoIP.h>
31 #include <GeoIPCity.h>
32 #include <netinet/in.h>
33 #include <curses.h>
34 #include <dirent.h>
35 #include <sys/stat.h>
36 #include <urcu.h>
37 #include <libgen.h>
39 #include "die.h"
40 #include "xmalloc.h"
41 #include "xio.h"
42 #include "xutils.h"
43 #include "built_in.h"
44 #include "locking.h"
45 #include "dissector_eth.h"
46 #include "pkt_buff.h"
48 #define INCLUDE_UDP (1 << 0)
49 #define INCLUDE_TCP (1 << 1)
51 #ifndef ATTR_TIMESTAMP_START
52 # define ATTR_TIMESTAMP_START 63
53 #endif
54 #ifndef ATTR_TIMESTAMP_STOP
55 # define ATTR_TIMESTAMP_STOP 64
56 #endif
58 #define SCROLL_MAX 1000
60 struct flow_entry {
61 uint32_t flow_id;
62 int first;
63 struct flow_entry *next;
64 uint32_t use;
65 uint32_t status;
66 uint8_t l3_proto;
67 uint8_t l4_proto;
68 uint32_t ip4_src_addr;
69 uint32_t ip4_dst_addr;
70 uint32_t ip6_src_addr[4];
71 uint32_t ip6_dst_addr[4];
72 uint16_t port_src;
73 uint16_t port_dst;
74 uint8_t tcp_state;
75 uint8_t tcp_flags;
76 uint64_t counter_pkts;
77 uint64_t counter_bytes;
78 uint64_t timestamp_start;
79 uint64_t timestamp_stop;
80 char country_src[128];
81 char city_src[128];
82 char rev_dns_src[256];
83 char country_dst[128];
84 char city_dst[128];
85 char rev_dns_dst[256];
86 int procnum;
87 int inode;
88 char cmdline[256];
91 struct flow_list {
92 struct flow_entry *head;
93 struct spinlock lock;
96 volatile sig_atomic_t sigint = 0;
98 static int what = INCLUDE_TCP;
100 static int show_src = 0;
102 static struct flow_list flow_list;
104 static GeoIP *gi_country = NULL;
105 static GeoIP *gi_city = NULL;
107 static char *path_city_db = NULL, *path_country_db = NULL;
109 static const char *short_options = "vhTULKs";
110 static const struct option long_options[] = {
111 {"tcp", no_argument, NULL, 'T'},
112 {"udp", no_argument, NULL, 'U'},
113 {"show-src", no_argument, NULL, 's'},
114 {"city-db", required_argument, NULL, 'L'},
115 {"country-db", required_argument, NULL, 'K'},
116 {"version", no_argument, NULL, 'v'},
117 {"help", no_argument, NULL, 'h'},
118 {NULL, 0, NULL, 0}
121 const char *const l3proto2str[AF_MAX] = {
122 [AF_INET] = "ipv4",
123 [AF_INET6] = "ipv6",
126 const char *const proto2str[IPPROTO_MAX] = {
127 [IPPROTO_TCP] = "tcp",
128 [IPPROTO_UDP] = "udp",
129 [IPPROTO_UDPLITE] = "udplite",
130 [IPPROTO_ICMP] = "icmp",
131 [IPPROTO_ICMPV6] = "icmpv6",
132 [IPPROTO_SCTP] = "sctp",
133 [IPPROTO_GRE] = "gre",
134 [IPPROTO_DCCP] = "dccp",
135 [IPPROTO_IGMP] = "igmp",
136 [IPPROTO_IPIP] = "ipip",
137 [IPPROTO_EGP] = "egp",
138 [IPPROTO_PUP] = "pup",
139 [IPPROTO_IDP] = "idp",
140 [IPPROTO_RSVP] = "rsvp",
141 [IPPROTO_IPV6] = "ip6tun",
142 [IPPROTO_ESP] = "esp",
143 [IPPROTO_AH] = "ah",
144 [IPPROTO_PIM] = "pim",
145 [IPPROTO_COMP] = "comp",
148 const char *const state2str[TCP_CONNTRACK_MAX] = {
149 [TCP_CONNTRACK_NONE] = "NOSTATE",
150 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
151 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
152 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
153 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
154 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
155 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
156 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
157 [TCP_CONNTRACK_CLOSE] = "CLOSE",
158 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
161 const uint8_t states[] = {
162 TCP_CONNTRACK_SYN_SENT,
163 TCP_CONNTRACK_SYN_RECV,
164 TCP_CONNTRACK_ESTABLISHED,
165 TCP_CONNTRACK_FIN_WAIT,
166 TCP_CONNTRACK_CLOSE_WAIT,
167 TCP_CONNTRACK_LAST_ACK,
168 TCP_CONNTRACK_TIME_WAIT,
169 TCP_CONNTRACK_CLOSE,
170 TCP_CONNTRACK_SYN_SENT2,
171 TCP_CONNTRACK_NONE,
174 static void signal_handler(int number)
176 switch (number) {
177 case SIGINT:
178 sigint = 1;
179 break;
180 case SIGHUP:
181 default:
182 break;
186 static void help(void)
188 printf("\n%s %s, top-like netfilter TCP/UDP flow tracking\n",
189 PROGNAME_STRING, VERSION_STRING);
190 puts("http://www.netsniff-ng.org\n\n"
191 "Usage: flowtop [options]\n"
192 "Options:\n"
193 " -T|--tcp Show only TCP flows (default)\n"
194 " -U|--udp Show only UDP flows\n"
195 " -s|--show-src Also show source, not only dest\n"
196 " --city-db <path> Specifiy path for geoip city database\n"
197 " --country-db <path> Specifiy path for geoip country database\n"
198 " -v|--version Print version\n"
199 " -h|--help Print this help\n\n"
200 "Examples:\n"
201 " flowtop\n"
202 " flowtop -s\n\n"
203 "Note:\n"
204 " If netfilter is not running, you can activate it with i.e.:\n"
205 " iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
206 " iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n\n"
207 "Please report bugs to <bugs@netsniff-ng.org>\n"
208 "Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
209 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
210 "License: GNU GPL version 2.0\n"
211 "This is free software: you are free to change and redistribute it.\n"
212 "There is NO WARRANTY, to the extent permitted by law.\n");
213 die();
216 static void version(void)
218 printf("\n%s %s, top-like netfilter TCP/UDP flow tracking\n",
219 PROGNAME_STRING, VERSION_STRING);
220 puts("http://www.netsniff-ng.org\n\n"
221 "Please report bugs to <bugs@netsniff-ng.org>\n"
222 "Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
223 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
224 "License: GNU GPL version 2.0\n"
225 "This is free software: you are free to change and redistribute it.\n"
226 "There is NO WARRANTY, to the extent permitted by law.\n");
227 die();
230 static void screen_init(WINDOW **screen)
232 (*screen) = initscr();
233 noecho();
234 cbreak();
235 keypad(stdscr, TRUE);
236 nodelay(*screen, TRUE);
237 refresh();
238 wrefresh(*screen);
241 static inline uint16_t get_port(uint16_t src, uint16_t dst)
243 char *tmp1, *tmp2;
245 src = ntohs(src);
246 dst = ntohs(dst);
248 /* XXX: Is there a better way to determine? */
249 if (src < dst && src < 1024) {
250 return src;
251 } else if (dst < src && dst < 1024) {
252 return dst;
253 } else {
254 tmp1 = lookup_port_tcp(src);
255 tmp2 = lookup_port_tcp(dst);
256 if (tmp1 && !tmp2) {
257 return src;
258 } else if (!tmp1 && tmp2) {
259 return dst;
260 } else {
261 if (src < dst)
262 return src;
263 else
264 return dst;
269 static void screen_update(WINDOW *screen, struct flow_list *fl, int skip_lines)
271 int i, line = 3;
272 int maxy;
273 struct flow_entry *n;
275 curs_set(0);
276 maxy = getmaxy(screen);
278 start_color();
279 init_pair(1, COLOR_RED, COLOR_BLACK);
280 init_pair(2, COLOR_BLUE, COLOR_BLACK);
281 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
282 init_pair(4, COLOR_GREEN, COLOR_BLACK);
284 clear();
286 rcu_read_lock();
288 mvwprintw(screen, 1, 2, "Kernel netfilter TCP/UDP flow statistics, [+%d]",
289 skip_lines);
291 if (rcu_dereference(fl->head) == NULL)
292 mvwprintw(screen, line, 2, "(No active sessions! Is netfilter running?)");
294 maxy -= 4;
295 /* Yes, that's lame :-P */
296 for (i = 0; i < sizeof(states); i++) {
297 n = rcu_dereference(fl->head);
299 while (n && maxy > 0) {
300 char tmp[128];
302 if (n->tcp_state != states[i] ||
303 (i != TCP_CONNTRACK_NONE &&
304 n->tcp_state == TCP_CONNTRACK_NONE) ||
305 /* Filter out DNS */
306 get_port(n->port_src, n->port_dst) == 53) {
307 n = rcu_dereference(n->next);
308 continue;
311 if (skip_lines > 0) {
312 n = rcu_dereference(n->next);
313 skip_lines--;
314 continue;
317 snprintf(tmp, sizeof(tmp), "%u/%s", n->procnum,
318 basename(n->cmdline));
319 tmp[sizeof(tmp) - 1] = 0;
321 mvwprintw(screen, line, 2, "[");
322 attron(COLOR_PAIR(3));
323 printw("%s", n->procnum > 0 ? tmp : "bridged(?)");
324 attroff(COLOR_PAIR(3));
325 printw("]:%s:%s[", l3proto2str[n->l3_proto],
326 proto2str[n->l4_proto]);
327 attron(COLOR_PAIR(3));
328 printw("%s", state2str[n->tcp_state]);
329 attroff(COLOR_PAIR(3));
330 printw("]:");
331 attron(A_BOLD);
332 if (n->tcp_state != TCP_CONNTRACK_NONE) {
333 printw("%s -> ", lookup_port_tcp(get_port(n->port_src,
334 n->port_dst)));
335 } else {
336 printw("%s -> ", lookup_port_udp(get_port(n->port_src,
337 n->port_dst)));
339 attroff(A_BOLD);
340 if (show_src) {
341 attron(COLOR_PAIR(1));
342 mvwprintw(screen, ++line, 8, "src: %s", n->rev_dns_src);
343 attroff(COLOR_PAIR(1));
344 printw(":%u (", ntohs(n->port_src));
345 attron(COLOR_PAIR(4));
346 printw("%s", (strlen(n->country_src) > 0 ?
347 n->country_src : "N/A"));
348 attroff(COLOR_PAIR(4));
349 printw(", %s) => ", (strlen(n->city_src) > 0 ?
350 n->city_src : "N/A"));
352 attron(COLOR_PAIR(2));
353 mvwprintw(screen, ++line, 8, "dst: %s", n->rev_dns_dst);
354 attroff(COLOR_PAIR(2));
355 printw(":%u (", ntohs(n->port_dst));
356 attron(COLOR_PAIR(4));
357 printw("%s", strlen(n->country_dst) > 0 ?
358 n->country_dst : "N/A");
359 attroff(COLOR_PAIR(4));
360 printw(", %s)", strlen(n->city_dst) > 0 ?
361 n->city_dst : "N/A");
363 line++;
364 maxy--;
365 n = rcu_dereference(n->next);
369 rcu_read_unlock();
371 wrefresh(screen);
372 refresh();
375 static void screen_end(void)
377 endwin();
380 static void presenter(void)
382 int skip_lines = 0;
383 WINDOW *screen = NULL;
385 dissector_init_ethernet(0);
386 screen_init(&screen);
387 rcu_register_thread();
389 while (!sigint) {
390 switch (getch()) {
391 case 'q':
392 sigint = 1;
393 break;
394 case KEY_UP:
395 case 'u':
396 case 'k':
397 skip_lines--;
398 if (skip_lines < 0)
399 skip_lines = 0;
400 break;
401 case KEY_DOWN:
402 case 'd':
403 case 'j':
404 skip_lines++;
405 if (skip_lines > SCROLL_MAX)
406 skip_lines = SCROLL_MAX;
407 break;
408 default:
409 fflush(stdin);
410 break;
413 screen_update(screen, &flow_list, skip_lines);
414 usleep(100000);
417 rcu_unregister_thread();
418 screen_end();
419 dissector_cleanup_ethernet();
422 static inline const char *make_n_a(const char *p)
424 return p ? : "N/A";
427 static void walk_process(char *process, struct flow_entry *n)
429 int rc;
430 DIR *dir;
431 struct dirent *ent;
432 char path[1024];
434 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
435 panic("giant process name! %s\n", process);
437 dir = opendir(path);
438 if (!dir)
439 return;
441 while ((ent = readdir(dir))) {
442 struct stat statbuf;
444 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
445 process, ent->d_name) < 0)
446 continue;
447 if (stat(path, &statbuf) < 0)
448 continue;
449 if (S_ISSOCK(statbuf.st_mode) && n->inode == statbuf.st_ino) {
450 memset(n->cmdline, 0, sizeof(n->cmdline));
451 snprintf(path, sizeof(path), "/proc/%s/exe", process);
452 rc = readlink(path, n->cmdline, sizeof(n->cmdline) - 1);
454 if (rc < 0)
455 panic("readlink error: %s\n", strerror(errno));
457 n->procnum = atoi(process);
461 closedir(dir);
464 /* Derived from ifpromisc, Fred N. van Kempen, GPL v2.0 */
465 /* n->inode must be set */
466 static void walk_processes(struct flow_entry *n)
468 DIR *dir;
469 struct dirent *ent;
471 if (n->inode <= 0) {
472 memset(n->cmdline, 0, sizeof(n->cmdline));
473 return;
476 dir = opendir("/proc");
477 if (!dir)
478 panic("Cannot open /proc!\n");
480 while ((ent = readdir(dir)))
481 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name))
482 walk_process(ent->d_name, n);
484 closedir(dir);
487 static int get_inode_from_local_port(int port, const char *proto, int ip6)
489 int ret = -ENOENT;
490 char path[128];
491 char buff[1024];
492 FILE *proc;
494 memset(path, 0, sizeof(path));
495 snprintf(path, sizeof(path), "/proc/net/%s%s", proto, ip6 ? "6" : "");
496 proc = fopen(path, "r");
497 if (!proc)
498 return -EIO;
499 memset(buff, 0, sizeof(buff));
500 while (fgets(buff, sizeof(buff), proc) != NULL) {
501 int lport = 0, inode = 0;
502 buff[sizeof(buff) - 1] = 0;
503 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
504 "%*X %*u %*u %u", &lport, &inode) == 2) {
505 if (lport == port) {
506 ret = inode;
507 break;
510 memset(buff, 0, sizeof(buff));
512 fclose(proc);
514 return ret;
517 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
519 n->flow_id = nfct_get_attr_u32(ct, ATTR_ID);
520 n->use = nfct_get_attr_u32(ct, ATTR_USE);
521 n->status = nfct_get_attr_u32(ct, ATTR_STATUS);
522 n->l3_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L3PROTO);
523 n->l4_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L4PROTO);
524 n->ip4_src_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_SRC);
525 n->ip4_dst_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_DST);
527 const uint8_t *ipv6_src = nfct_get_attr(ct, ATTR_ORIG_IPV6_SRC);
528 if (ipv6_src)
529 memcpy(n->ip6_src_addr, ipv6_src, sizeof(n->ip6_src_addr));
530 const uint8_t *ipv6_dst = nfct_get_attr(ct, ATTR_ORIG_IPV6_DST);
531 if (ipv6_dst)
532 memcpy(n->ip6_dst_addr, ipv6_dst, sizeof(n->ip6_dst_addr));
534 n->port_src = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_SRC);
535 n->port_dst = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_DST);
536 n->tcp_state = nfct_get_attr_u8(ct, ATTR_TCP_STATE);
537 n->tcp_flags = nfct_get_attr_u8(ct, ATTR_TCP_FLAGS_ORIG);
538 n->counter_pkts = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_PACKETS);
539 n->counter_bytes = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_BYTES);
540 n->timestamp_start = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_START);
541 n->timestamp_stop = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_STOP);
543 if (n->first) {
544 n->inode = get_inode_from_local_port(ntohs(n->port_src),
545 proto2str[n->l4_proto],
546 !!(ipv6_src));
547 if (n->inode > 0)
548 walk_processes(n);
550 /* if this really runs on a router, we try it once and then let it be */
551 n->first = 0;
554 /* TODO: IP4 + IP6 */
555 static void flow_entry_get_extended(struct flow_entry *n)
557 struct sockaddr_in sa;
558 struct hostent *hent;
559 GeoIPRecord *gir_src, *gir_dst;
561 if (n->flow_id == 0)
562 return;
563 if (ntohs(n->port_src) == 53 || ntohs(n->port_dst) == 53)
564 return;
566 memset(&sa, 0, sizeof(sa));
567 sa.sin_family = PF_INET; //XXX: IPv4
568 sa.sin_addr.s_addr = n->ip4_src_addr;
569 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_src,
570 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
572 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
573 if (hent) {
574 memset(n->rev_dns_src, 0, sizeof(n->rev_dns_src));
575 memcpy(n->rev_dns_src, hent->h_name,
576 min(sizeof(n->rev_dns_src), strlen(hent->h_name)));
579 gir_src = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_src_addr));
580 if (gir_src) {
581 const char *country =
582 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
583 ntohl(n->ip4_src_addr)));
584 const char *city = make_n_a(gir_src->city);
585 memcpy(n->country_src, country,
586 min(sizeof(n->country_src), strlen(country)));
587 memcpy(n->city_src, city,
588 min(sizeof(n->city_src), strlen(city)));
591 memset(&sa, 0, sizeof(sa));
592 sa.sin_family = PF_INET; //XXX: IPv4
593 sa.sin_addr.s_addr = n->ip4_dst_addr;
594 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_dst,
595 sizeof(n->rev_dns_dst), NULL, 0, NI_NUMERICHOST);
597 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
598 if (hent) {
599 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
600 memcpy(n->rev_dns_dst, hent->h_name,
601 min(sizeof(n->rev_dns_dst), strlen(hent->h_name)));
604 gir_dst = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_dst_addr));
605 if (gir_dst) {
606 const char *country =
607 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
608 ntohl(n->ip4_dst_addr)));
609 const char *city = make_n_a(gir_dst->city);
610 memcpy(n->country_dst, country,
611 min(sizeof(n->country_dst), strlen(country)));
612 memcpy(n->city_dst, city,
613 min(sizeof(n->city_dst), strlen(city)));
617 static void flow_list_init(struct flow_list *fl)
619 fl->head = NULL;
620 spinlock_init(&fl->lock);
623 static struct flow_entry *__flow_list_find_by_id(struct flow_list *fl, uint32_t id)
625 struct flow_entry *n = rcu_dereference(fl->head);
626 while (n != NULL) {
627 if (n->flow_id == id)
628 return n;
629 n = rcu_dereference(n->next);
631 return NULL;
634 static struct flow_entry *__flow_list_find_prev_by_id(struct flow_list *fl, uint32_t id)
636 struct flow_entry *n = rcu_dereference(fl->head);
637 if (n->flow_id == id)
638 return NULL;
639 while (rcu_dereference(n->next) != NULL) {
640 if (rcu_dereference(n->next)->flow_id == id)
641 return n;
642 n = rcu_dereference(n->next);
644 return NULL;
647 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
649 struct flow_entry *n = xzmalloc(sizeof(*n));
650 n->first = 1;
651 rcu_assign_pointer(n->next, fl->head);
652 rcu_assign_pointer(fl->head, n);
653 flow_entry_from_ct(n, ct);
654 flow_entry_get_extended(n);
657 static void flow_list_update_entry(struct flow_list *fl, struct nf_conntrack *ct)
659 int do_ext = 0;
660 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
661 struct flow_entry *n;
662 n = __flow_list_find_by_id(fl, id);
663 if (n == NULL) {
664 n = xzmalloc(sizeof(*n));
665 n->first = 1;
666 rcu_assign_pointer(n->next, fl->head);
667 rcu_assign_pointer(fl->head, n);
668 do_ext = 1;
670 flow_entry_from_ct(n, ct);
671 if (do_ext)
672 flow_entry_get_extended(n);
675 static void flow_list_destroy_entry(struct flow_list *fl, struct nf_conntrack *ct)
677 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
678 struct flow_entry *n1, *n2;
680 n1 = __flow_list_find_by_id(fl, id);
681 if (n1) {
682 n2 = __flow_list_find_prev_by_id(fl, id);
683 if (n2) {
684 rcu_assign_pointer(n2->next, n1->next);
685 rcu_assign_pointer(n1->next, NULL);
686 xfree(n1);
687 } else {
688 xfree(fl->head);
689 rcu_assign_pointer(fl->head, NULL);
694 static void flow_list_destroy(struct flow_list *fl)
696 struct flow_entry *n;
698 while (fl->head != NULL) {
699 n = rcu_dereference(fl->head->next);
700 rcu_assign_pointer(fl->head->next, NULL);
701 xfree(fl->head);
702 rcu_assign_pointer(fl->head, n);
705 synchronize_rcu();
706 spinlock_destroy(&fl->lock);
709 static int collector_cb(enum nf_conntrack_msg_type type,
710 struct nf_conntrack *ct,
711 void *data)
713 if (sigint)
714 return NFCT_CB_STOP;
716 synchronize_rcu();
718 spinlock_lock(&flow_list.lock);
719 switch (type) {
720 case NFCT_T_NEW:
721 flow_list_new_entry(&flow_list, ct);
722 break;
723 case NFCT_T_UPDATE:
724 flow_list_update_entry(&flow_list, ct);
725 break;
726 case NFCT_T_DESTROY:
727 flow_list_destroy_entry(&flow_list, ct);
728 break;
729 default:
730 break;
732 spinlock_unlock(&flow_list.lock);
734 return NFCT_CB_CONTINUE;
737 static int dummy_cb(enum nf_conntrack_msg_type type, struct nf_conntrack *ct,
738 void *data)
740 return NFCT_CB_STOP;
743 static void *collector(void *null)
745 int ret;
746 u_int32_t family = AF_INET;
747 struct nfct_handle *handle;
748 struct nfct_filter *filter;
750 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
751 if (!handle)
752 panic("Cannot create a nfct handle!\n");
754 /* Hack: inits ct */
755 nfct_callback_register(handle, NFCT_T_ALL, dummy_cb, NULL);
756 nfct_query(handle, NFCT_Q_DUMP, &family);
757 nfct_close(handle);
759 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
760 if (!handle)
761 panic("Cannot create a nfct handle!\n");
763 nfct_query(handle, NFCT_Q_FLUSH, &family);
765 filter = nfct_filter_create();
766 if (!filter)
767 panic("Cannot create a nfct filter!\n");
768 if (what & INCLUDE_UDP)
769 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
770 if (what & INCLUDE_TCP)
771 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
773 struct nfct_filter_ipv4 filter_ipv4 = {
774 .addr = ntohl(INADDR_LOOPBACK),
775 .mask = 0xffffffff,
778 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4,
779 NFCT_FILTER_LOGIC_NEGATIVE);
780 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
782 struct nfct_filter_ipv6 filter_ipv6 = {
783 .addr = { 0x0, 0x0, 0x0, 0x1 },
784 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
787 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6,
788 NFCT_FILTER_LOGIC_NEGATIVE);
789 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
791 ret = nfct_filter_attach(nfct_fd(handle), filter);
792 if (ret < 0)
793 panic("Cannot attach filter to handle!\n");
795 nfct_filter_destroy(filter);
797 if (path_country_db)
798 gi_country = GeoIP_open(path_country_db, GEOIP_MMAP_CACHE);
799 else
800 gi_country = GeoIP_open_type(GEOIP_COUNTRY_EDITION,
801 GEOIP_MMAP_CACHE);
803 if (path_city_db)
804 gi_city = GeoIP_open(path_city_db, GEOIP_MMAP_CACHE);
805 else
806 gi_city = GeoIP_open_type(GEOIP_CITY_EDITION_REV1,
807 GEOIP_MMAP_CACHE);
808 if (!gi_country || !gi_city)
809 panic("Cannot open GeoIP database!\n");
811 GeoIP_set_charset(gi_country, GEOIP_CHARSET_UTF8);
812 GeoIP_set_charset(gi_city, GEOIP_CHARSET_UTF8);
814 flow_list_init(&flow_list);
816 rcu_register_thread();
818 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
820 while (!sigint)
821 nfct_catch(handle);
823 rcu_unregister_thread();
825 flow_list_destroy(&flow_list);
827 GeoIP_delete(gi_city);
828 GeoIP_delete(gi_country);
830 nfct_close(handle);
832 if (path_city_db)
833 xfree(path_city_db);
834 if (path_country_db)
835 xfree(path_country_db);
837 pthread_exit(0);
840 int main(int argc, char **argv)
842 pthread_t tid;
843 int ret, c, opt_index, what_cmd = 0;
845 check_for_root_maybe_die();
847 while ((c = getopt_long(argc, argv, short_options, long_options,
848 &opt_index)) != EOF) {
849 switch (c) {
850 case 'T':
851 what_cmd |= INCLUDE_TCP;
852 break;
853 case 'U':
854 what_cmd |= INCLUDE_UDP;
855 break;
856 case 's':
857 show_src = 1;
858 break;
859 case 'L':
860 path_city_db = xstrdup(optarg);
861 break;
862 case 'K':
863 path_country_db = xstrdup(optarg);
864 break;
865 case 'h':
866 help();
867 break;
868 case 'v':
869 version();
870 break;
871 case '?':
872 switch (optopt) {
873 case 'L':
874 case 'K':
875 panic("Option -%c requires an argument!\n",
876 optopt);
877 default:
878 if (isprint(optopt))
879 whine("Unknown option character "
880 "`0x%X\'!\n", optopt);
881 die();
883 default:
884 break;
888 if (what_cmd > 0)
889 what = what_cmd;
891 rcu_init();
893 register_signal(SIGINT, signal_handler);
894 register_signal(SIGHUP, signal_handler);
896 ret = pthread_create(&tid, NULL, collector, NULL);
897 if (ret < 0)
898 panic("Cannot create phthread!\n");
900 presenter();
901 return 0;