docs: add todo's from Sibir's repo
[netsniff-ng.git] / src / flowtop.c
blobb9aafe0a518d84d954749e884acaa7eb07666053
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("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
189 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("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
219 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 wclear(screen);
285 clear();
287 rcu_read_lock();
289 mvwprintw(screen, 1, 2, "Kernel netfilter TCP/UDP flow statistics, [+%d]",
290 skip_lines);
292 if (rcu_dereference(fl->head) == NULL)
293 mvwprintw(screen, line, 2, "(No active sessions! Is netfilter running?)");
295 maxy -= 4;
296 /* Yes, that's lame :-P */
297 for (i = 0; i < sizeof(states); i++) {
298 n = rcu_dereference(fl->head);
300 while (n && maxy > 0) {
301 char tmp[128];
303 if (n->tcp_state != states[i] ||
304 (i != TCP_CONNTRACK_NONE &&
305 n->tcp_state == TCP_CONNTRACK_NONE) ||
306 /* Filter out DNS */
307 get_port(n->port_src, n->port_dst) == 53) {
308 n = rcu_dereference(n->next);
309 continue;
312 if (skip_lines > 0) {
313 n = rcu_dereference(n->next);
314 skip_lines--;
315 continue;
318 snprintf(tmp, sizeof(tmp), "%u/%s", n->procnum,
319 basename(n->cmdline));
320 tmp[sizeof(tmp) - 1] = 0;
322 mvwprintw(screen, line, 2, "[");
323 attron(COLOR_PAIR(3));
324 printw("%s", n->procnum > 0 ? tmp : "bridged(?)");
325 attroff(COLOR_PAIR(3));
326 printw("]:%s:%s[", l3proto2str[n->l3_proto],
327 proto2str[n->l4_proto]);
328 attron(COLOR_PAIR(3));
329 printw("%s", state2str[n->tcp_state]);
330 attroff(COLOR_PAIR(3));
331 printw("]:");
332 attron(A_BOLD);
333 if (n->tcp_state != TCP_CONNTRACK_NONE) {
334 printw("%s -> ", lookup_port_tcp(get_port(n->port_src,
335 n->port_dst)));
336 } else {
337 printw("%s -> ", lookup_port_udp(get_port(n->port_src,
338 n->port_dst)));
340 attroff(A_BOLD);
341 if (show_src) {
342 attron(COLOR_PAIR(1));
343 mvwprintw(screen, ++line, 8, "src: %s", n->rev_dns_src);
344 attroff(COLOR_PAIR(1));
345 printw(":%u (", ntohs(n->port_src));
346 attron(COLOR_PAIR(4));
347 printw("%s", (strlen(n->country_src) > 0 ?
348 n->country_src : "N/A"));
349 attroff(COLOR_PAIR(4));
350 printw(", %s) => ", (strlen(n->city_src) > 0 ?
351 n->city_src : "N/A"));
353 attron(COLOR_PAIR(2));
354 mvwprintw(screen, ++line, 8, "dst: %s", n->rev_dns_dst);
355 attroff(COLOR_PAIR(2));
356 printw(":%u (", ntohs(n->port_dst));
357 attron(COLOR_PAIR(4));
358 printw("%s", strlen(n->country_dst) > 0 ?
359 n->country_dst : "N/A");
360 attroff(COLOR_PAIR(4));
361 printw(", %s)", strlen(n->city_dst) > 0 ?
362 n->city_dst : "N/A");
364 line++;
365 maxy--;
366 n = rcu_dereference(n->next);
370 rcu_read_unlock();
372 wrefresh(screen);
373 refresh();
376 static void screen_end(void)
378 endwin();
381 static void presenter(void)
383 int skip_lines = 0;
384 WINDOW *screen = NULL;
386 dissector_init_ethernet(0);
387 screen_init(&screen);
388 rcu_register_thread();
390 while (!sigint) {
391 switch (getch()) {
392 case 'q':
393 sigint = 1;
394 break;
395 case KEY_UP:
396 case 'u':
397 case 'k':
398 skip_lines--;
399 if (skip_lines < 0)
400 skip_lines = 0;
401 break;
402 case KEY_DOWN:
403 case 'd':
404 case 'j':
405 skip_lines++;
406 if (skip_lines > SCROLL_MAX)
407 skip_lines = SCROLL_MAX;
408 break;
409 default:
410 fflush(stdin);
411 break;
414 screen_update(screen, &flow_list, skip_lines);
415 usleep(100000);
418 rcu_unregister_thread();
419 screen_end();
420 dissector_cleanup_ethernet();
423 static inline const char *make_n_a(const char *p)
425 return p ? : "N/A";
428 static void walk_process(char *process, struct flow_entry *n)
430 int rc;
431 DIR *dir;
432 struct dirent *ent;
433 char path[1024];
435 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
436 panic("giant process name! %s\n", process);
438 dir = opendir(path);
439 if (!dir)
440 return;
442 while ((ent = readdir(dir))) {
443 struct stat statbuf;
445 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
446 process, ent->d_name) < 0)
447 continue;
448 if (stat(path, &statbuf) < 0)
449 continue;
450 if (S_ISSOCK(statbuf.st_mode) && n->inode == statbuf.st_ino) {
451 memset(n->cmdline, 0, sizeof(n->cmdline));
452 snprintf(path, sizeof(path), "/proc/%s/exe", process);
453 rc = readlink(path, n->cmdline, sizeof(n->cmdline) - 1);
455 if (rc < 0)
456 panic("readlink error: %s\n", strerror(errno));
458 n->procnum = atoi(process);
462 closedir(dir);
465 /* Derived from ifpromisc, Fred N. van Kempen, GPL v2.0 */
466 /* n->inode must be set */
467 static void walk_processes(struct flow_entry *n)
469 DIR *dir;
470 struct dirent *ent;
472 if (n->inode <= 0) {
473 memset(n->cmdline, 0, sizeof(n->cmdline));
474 return;
477 dir = opendir("/proc");
478 if (!dir)
479 panic("Cannot open /proc!\n");
481 while ((ent = readdir(dir)))
482 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name))
483 walk_process(ent->d_name, n);
485 closedir(dir);
488 static int get_inode_from_local_port(int port, const char *proto, int ip6)
490 int ret = -ENOENT;
491 char path[128];
492 char buff[1024];
493 FILE *proc;
495 memset(path, 0, sizeof(path));
496 snprintf(path, sizeof(path), "/proc/net/%s%s", proto, ip6 ? "6" : "");
497 proc = fopen(path, "r");
498 if (!proc)
499 return -EIO;
500 memset(buff, 0, sizeof(buff));
501 while (fgets(buff, sizeof(buff), proc) != NULL) {
502 int lport = 0, inode = 0;
503 buff[sizeof(buff) - 1] = 0;
504 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
505 "%*X %*u %*u %u", &lport, &inode) == 2) {
506 if (lport == port) {
507 ret = inode;
508 break;
511 memset(buff, 0, sizeof(buff));
513 fclose(proc);
515 return ret;
518 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
520 const uint8_t *ipv6_src;
521 const uint8_t *ipv6_dst;
523 n->flow_id = nfct_get_attr_u32(ct, ATTR_ID);
524 n->use = nfct_get_attr_u32(ct, ATTR_USE);
525 n->status = nfct_get_attr_u32(ct, ATTR_STATUS);
526 n->l3_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L3PROTO);
527 n->l4_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L4PROTO);
528 n->ip4_src_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_SRC);
529 n->ip4_dst_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_DST);
531 ipv6_src = nfct_get_attr(ct, ATTR_ORIG_IPV6_SRC);
532 if (ipv6_src)
533 memcpy(n->ip6_src_addr, ipv6_src, sizeof(n->ip6_src_addr));
534 ipv6_dst = nfct_get_attr(ct, ATTR_ORIG_IPV6_DST);
535 if (ipv6_dst)
536 memcpy(n->ip6_dst_addr, ipv6_dst, sizeof(n->ip6_dst_addr));
538 n->port_src = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_SRC);
539 n->port_dst = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_DST);
540 n->tcp_state = nfct_get_attr_u8(ct, ATTR_TCP_STATE);
541 n->tcp_flags = nfct_get_attr_u8(ct, ATTR_TCP_FLAGS_ORIG);
542 n->counter_pkts = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_PACKETS);
543 n->counter_bytes = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_BYTES);
544 n->timestamp_start = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_START);
545 n->timestamp_stop = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_STOP);
547 if (n->first) {
548 n->inode = get_inode_from_local_port(ntohs(n->port_src),
549 proto2str[n->l4_proto],
550 !!(ipv6_src));
551 if (n->inode > 0)
552 walk_processes(n);
554 /* if this really runs on a router, we try it once and then let it be */
555 n->first = 0;
558 /* TODO: IP4 + IP6 */
559 static void flow_entry_get_extended(struct flow_entry *n)
561 struct sockaddr_in sa;
562 struct hostent *hent;
563 GeoIPRecord *gir_src, *gir_dst;
565 if (n->flow_id == 0)
566 return;
567 if (ntohs(n->port_src) == 53 || ntohs(n->port_dst) == 53)
568 return;
570 memset(&sa, 0, sizeof(sa));
571 sa.sin_family = PF_INET; //XXX: IPv4
572 sa.sin_addr.s_addr = n->ip4_src_addr;
573 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_src,
574 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
576 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
577 if (hent) {
578 memset(n->rev_dns_src, 0, sizeof(n->rev_dns_src));
579 memcpy(n->rev_dns_src, hent->h_name,
580 min(sizeof(n->rev_dns_src), strlen(hent->h_name)));
583 gir_src = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_src_addr));
584 if (gir_src) {
585 const char *country =
586 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
587 ntohl(n->ip4_src_addr)));
588 const char *city = make_n_a(gir_src->city);
589 memcpy(n->country_src, country,
590 min(sizeof(n->country_src), strlen(country)));
591 memcpy(n->city_src, city,
592 min(sizeof(n->city_src), strlen(city)));
595 memset(&sa, 0, sizeof(sa));
596 sa.sin_family = PF_INET; //XXX: IPv4
597 sa.sin_addr.s_addr = n->ip4_dst_addr;
598 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_dst,
599 sizeof(n->rev_dns_dst), NULL, 0, NI_NUMERICHOST);
601 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
602 if (hent) {
603 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
604 memcpy(n->rev_dns_dst, hent->h_name,
605 min(sizeof(n->rev_dns_dst), strlen(hent->h_name)));
608 gir_dst = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_dst_addr));
609 if (gir_dst) {
610 const char *country =
611 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
612 ntohl(n->ip4_dst_addr)));
613 const char *city = make_n_a(gir_dst->city);
614 memcpy(n->country_dst, country,
615 min(sizeof(n->country_dst), strlen(country)));
616 memcpy(n->city_dst, city,
617 min(sizeof(n->city_dst), strlen(city)));
621 static void flow_list_init(struct flow_list *fl)
623 fl->head = NULL;
624 spinlock_init(&fl->lock);
627 static struct flow_entry *__flow_list_find_by_id(struct flow_list *fl, uint32_t id)
629 struct flow_entry *n = rcu_dereference(fl->head);
630 while (n != NULL) {
631 if (n->flow_id == id)
632 return n;
633 n = rcu_dereference(n->next);
635 return NULL;
638 static struct flow_entry *__flow_list_find_prev_by_id(struct flow_list *fl, uint32_t id)
640 struct flow_entry *n = rcu_dereference(fl->head);
641 if (n->flow_id == id)
642 return NULL;
643 while (rcu_dereference(n->next) != NULL) {
644 if (rcu_dereference(n->next)->flow_id == id)
645 return n;
646 n = rcu_dereference(n->next);
648 return NULL;
651 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
653 struct flow_entry *n = xzmalloc(sizeof(*n));
654 n->first = 1;
655 rcu_assign_pointer(n->next, fl->head);
656 rcu_assign_pointer(fl->head, n);
657 flow_entry_from_ct(n, ct);
658 flow_entry_get_extended(n);
661 static void flow_list_update_entry(struct flow_list *fl, struct nf_conntrack *ct)
663 int do_ext = 0;
664 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
665 struct flow_entry *n;
666 n = __flow_list_find_by_id(fl, id);
667 if (n == NULL) {
668 n = xzmalloc(sizeof(*n));
669 n->first = 1;
670 rcu_assign_pointer(n->next, fl->head);
671 rcu_assign_pointer(fl->head, n);
672 do_ext = 1;
674 flow_entry_from_ct(n, ct);
675 if (do_ext)
676 flow_entry_get_extended(n);
679 static void flow_list_destroy_entry(struct flow_list *fl, struct nf_conntrack *ct)
681 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
682 struct flow_entry *n1, *n2;
684 n1 = __flow_list_find_by_id(fl, id);
685 if (n1) {
686 n2 = __flow_list_find_prev_by_id(fl, id);
687 if (n2) {
688 rcu_assign_pointer(n2->next, n1->next);
689 rcu_assign_pointer(n1->next, NULL);
690 xfree(n1);
691 } else {
692 xfree(fl->head);
693 rcu_assign_pointer(fl->head, NULL);
698 static void flow_list_destroy(struct flow_list *fl)
700 struct flow_entry *n;
702 while (fl->head != NULL) {
703 n = rcu_dereference(fl->head->next);
704 rcu_assign_pointer(fl->head->next, NULL);
705 xfree(fl->head);
706 rcu_assign_pointer(fl->head, n);
709 synchronize_rcu();
710 spinlock_destroy(&fl->lock);
713 static int collector_cb(enum nf_conntrack_msg_type type,
714 struct nf_conntrack *ct,
715 void *data)
717 if (sigint)
718 return NFCT_CB_STOP;
720 synchronize_rcu();
722 spinlock_lock(&flow_list.lock);
723 switch (type) {
724 case NFCT_T_NEW:
725 flow_list_new_entry(&flow_list, ct);
726 break;
727 case NFCT_T_UPDATE:
728 flow_list_update_entry(&flow_list, ct);
729 break;
730 case NFCT_T_DESTROY:
731 flow_list_destroy_entry(&flow_list, ct);
732 break;
733 default:
734 break;
736 spinlock_unlock(&flow_list.lock);
738 return NFCT_CB_CONTINUE;
741 static int dummy_cb(enum nf_conntrack_msg_type type, struct nf_conntrack *ct,
742 void *data)
744 return NFCT_CB_STOP;
747 static void *collector(void *null)
749 int ret;
750 u_int32_t family = AF_INET;
751 struct nfct_handle *handle;
752 struct nfct_filter *filter;
753 struct nfct_filter_ipv4 filter_ipv4 = {
754 .addr = ntohl(INADDR_LOOPBACK),
755 .mask = 0xffffffff,
757 struct nfct_filter_ipv6 filter_ipv6 = {
758 .addr = { 0x0, 0x0, 0x0, 0x1 },
759 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
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 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4,
786 NFCT_FILTER_LOGIC_NEGATIVE);
787 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
789 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6,
790 NFCT_FILTER_LOGIC_NEGATIVE);
791 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
793 ret = nfct_filter_attach(nfct_fd(handle), filter);
794 if (ret < 0)
795 panic("Cannot attach filter to handle!\n");
797 nfct_filter_destroy(filter);
799 if (path_country_db)
800 gi_country = GeoIP_open(path_country_db, GEOIP_MMAP_CACHE);
801 else
802 gi_country = GeoIP_open_type(GEOIP_COUNTRY_EDITION,
803 GEOIP_MMAP_CACHE);
805 if (path_city_db)
806 gi_city = GeoIP_open(path_city_db, GEOIP_MMAP_CACHE);
807 else
808 gi_city = GeoIP_open_type(GEOIP_CITY_EDITION_REV1,
809 GEOIP_MMAP_CACHE);
810 if (!gi_country || !gi_city)
811 panic("Cannot open GeoIP database!\n");
813 GeoIP_set_charset(gi_country, GEOIP_CHARSET_UTF8);
814 GeoIP_set_charset(gi_city, GEOIP_CHARSET_UTF8);
816 flow_list_init(&flow_list);
818 rcu_register_thread();
820 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
822 while (!sigint)
823 nfct_catch(handle);
825 rcu_unregister_thread();
827 flow_list_destroy(&flow_list);
829 GeoIP_delete(gi_city);
830 GeoIP_delete(gi_country);
832 nfct_close(handle);
834 if (path_city_db)
835 xfree(path_city_db);
836 if (path_country_db)
837 xfree(path_country_db);
839 pthread_exit(0);
842 int main(int argc, char **argv)
844 pthread_t tid;
845 int ret, c, opt_index, what_cmd = 0;
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;