examples: bpf: different labeling
[netsniff-ng.git] / src / flowtop.c
blob68786e45b579100de5b59a9c9da237642c552da1
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 const uint8_t *ipv6_src;
520 const uint8_t *ipv6_dst;
522 n->flow_id = nfct_get_attr_u32(ct, ATTR_ID);
523 n->use = nfct_get_attr_u32(ct, ATTR_USE);
524 n->status = nfct_get_attr_u32(ct, ATTR_STATUS);
525 n->l3_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L3PROTO);
526 n->l4_proto = nfct_get_attr_u8(ct, ATTR_ORIG_L4PROTO);
527 n->ip4_src_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_SRC);
528 n->ip4_dst_addr = nfct_get_attr_u32(ct, ATTR_ORIG_IPV4_DST);
530 ipv6_src = nfct_get_attr(ct, ATTR_ORIG_IPV6_SRC);
531 if (ipv6_src)
532 memcpy(n->ip6_src_addr, ipv6_src, sizeof(n->ip6_src_addr));
533 ipv6_dst = nfct_get_attr(ct, ATTR_ORIG_IPV6_DST);
534 if (ipv6_dst)
535 memcpy(n->ip6_dst_addr, ipv6_dst, sizeof(n->ip6_dst_addr));
537 n->port_src = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_SRC);
538 n->port_dst = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_DST);
539 n->tcp_state = nfct_get_attr_u8(ct, ATTR_TCP_STATE);
540 n->tcp_flags = nfct_get_attr_u8(ct, ATTR_TCP_FLAGS_ORIG);
541 n->counter_pkts = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_PACKETS);
542 n->counter_bytes = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_BYTES);
543 n->timestamp_start = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_START);
544 n->timestamp_stop = nfct_get_attr_u64(ct, ATTR_TIMESTAMP_STOP);
546 if (n->first) {
547 n->inode = get_inode_from_local_port(ntohs(n->port_src),
548 proto2str[n->l4_proto],
549 !!(ipv6_src));
550 if (n->inode > 0)
551 walk_processes(n);
553 /* if this really runs on a router, we try it once and then let it be */
554 n->first = 0;
557 /* TODO: IP4 + IP6 */
558 static void flow_entry_get_extended(struct flow_entry *n)
560 struct sockaddr_in sa;
561 struct hostent *hent;
562 GeoIPRecord *gir_src, *gir_dst;
564 if (n->flow_id == 0)
565 return;
566 if (ntohs(n->port_src) == 53 || ntohs(n->port_dst) == 53)
567 return;
569 memset(&sa, 0, sizeof(sa));
570 sa.sin_family = PF_INET; //XXX: IPv4
571 sa.sin_addr.s_addr = n->ip4_src_addr;
572 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_src,
573 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
575 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
576 if (hent) {
577 memset(n->rev_dns_src, 0, sizeof(n->rev_dns_src));
578 memcpy(n->rev_dns_src, hent->h_name,
579 min(sizeof(n->rev_dns_src), strlen(hent->h_name)));
582 gir_src = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_src_addr));
583 if (gir_src) {
584 const char *country =
585 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
586 ntohl(n->ip4_src_addr)));
587 const char *city = make_n_a(gir_src->city);
588 memcpy(n->country_src, country,
589 min(sizeof(n->country_src), strlen(country)));
590 memcpy(n->city_src, city,
591 min(sizeof(n->city_src), strlen(city)));
594 memset(&sa, 0, sizeof(sa));
595 sa.sin_family = PF_INET; //XXX: IPv4
596 sa.sin_addr.s_addr = n->ip4_dst_addr;
597 getnameinfo((struct sockaddr *) &sa, sizeof(sa), n->rev_dns_dst,
598 sizeof(n->rev_dns_dst), NULL, 0, NI_NUMERICHOST);
600 hent = gethostbyaddr(&sa.sin_addr, sizeof(sa.sin_addr), PF_INET);
601 if (hent) {
602 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
603 memcpy(n->rev_dns_dst, hent->h_name,
604 min(sizeof(n->rev_dns_dst), strlen(hent->h_name)));
607 gir_dst = GeoIP_record_by_ipnum(gi_city, ntohl(n->ip4_dst_addr));
608 if (gir_dst) {
609 const char *country =
610 make_n_a(GeoIP_country_name_by_ipnum(gi_country,
611 ntohl(n->ip4_dst_addr)));
612 const char *city = make_n_a(gir_dst->city);
613 memcpy(n->country_dst, country,
614 min(sizeof(n->country_dst), strlen(country)));
615 memcpy(n->city_dst, city,
616 min(sizeof(n->city_dst), strlen(city)));
620 static void flow_list_init(struct flow_list *fl)
622 fl->head = NULL;
623 spinlock_init(&fl->lock);
626 static struct flow_entry *__flow_list_find_by_id(struct flow_list *fl, uint32_t id)
628 struct flow_entry *n = rcu_dereference(fl->head);
629 while (n != NULL) {
630 if (n->flow_id == id)
631 return n;
632 n = rcu_dereference(n->next);
634 return NULL;
637 static struct flow_entry *__flow_list_find_prev_by_id(struct flow_list *fl, uint32_t id)
639 struct flow_entry *n = rcu_dereference(fl->head);
640 if (n->flow_id == id)
641 return NULL;
642 while (rcu_dereference(n->next) != NULL) {
643 if (rcu_dereference(n->next)->flow_id == id)
644 return n;
645 n = rcu_dereference(n->next);
647 return NULL;
650 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
652 struct flow_entry *n = xzmalloc(sizeof(*n));
653 n->first = 1;
654 rcu_assign_pointer(n->next, fl->head);
655 rcu_assign_pointer(fl->head, n);
656 flow_entry_from_ct(n, ct);
657 flow_entry_get_extended(n);
660 static void flow_list_update_entry(struct flow_list *fl, struct nf_conntrack *ct)
662 int do_ext = 0;
663 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
664 struct flow_entry *n;
665 n = __flow_list_find_by_id(fl, id);
666 if (n == NULL) {
667 n = xzmalloc(sizeof(*n));
668 n->first = 1;
669 rcu_assign_pointer(n->next, fl->head);
670 rcu_assign_pointer(fl->head, n);
671 do_ext = 1;
673 flow_entry_from_ct(n, ct);
674 if (do_ext)
675 flow_entry_get_extended(n);
678 static void flow_list_destroy_entry(struct flow_list *fl, struct nf_conntrack *ct)
680 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
681 struct flow_entry *n1, *n2;
683 n1 = __flow_list_find_by_id(fl, id);
684 if (n1) {
685 n2 = __flow_list_find_prev_by_id(fl, id);
686 if (n2) {
687 rcu_assign_pointer(n2->next, n1->next);
688 rcu_assign_pointer(n1->next, NULL);
689 xfree(n1);
690 } else {
691 xfree(fl->head);
692 rcu_assign_pointer(fl->head, NULL);
697 static void flow_list_destroy(struct flow_list *fl)
699 struct flow_entry *n;
701 while (fl->head != NULL) {
702 n = rcu_dereference(fl->head->next);
703 rcu_assign_pointer(fl->head->next, NULL);
704 xfree(fl->head);
705 rcu_assign_pointer(fl->head, n);
708 synchronize_rcu();
709 spinlock_destroy(&fl->lock);
712 static int collector_cb(enum nf_conntrack_msg_type type,
713 struct nf_conntrack *ct,
714 void *data)
716 if (sigint)
717 return NFCT_CB_STOP;
719 synchronize_rcu();
721 spinlock_lock(&flow_list.lock);
722 switch (type) {
723 case NFCT_T_NEW:
724 flow_list_new_entry(&flow_list, ct);
725 break;
726 case NFCT_T_UPDATE:
727 flow_list_update_entry(&flow_list, ct);
728 break;
729 case NFCT_T_DESTROY:
730 flow_list_destroy_entry(&flow_list, ct);
731 break;
732 default:
733 break;
735 spinlock_unlock(&flow_list.lock);
737 return NFCT_CB_CONTINUE;
740 static int dummy_cb(enum nf_conntrack_msg_type type, struct nf_conntrack *ct,
741 void *data)
743 return NFCT_CB_STOP;
746 static void *collector(void *null)
748 int ret;
749 u_int32_t family = AF_INET;
750 struct nfct_handle *handle;
751 struct nfct_filter *filter;
752 struct nfct_filter_ipv4 filter_ipv4 = {
753 .addr = ntohl(INADDR_LOOPBACK),
754 .mask = 0xffffffff,
756 struct nfct_filter_ipv6 filter_ipv6 = {
757 .addr = { 0x0, 0x0, 0x0, 0x1 },
758 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
761 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
762 if (!handle)
763 panic("Cannot create a nfct handle!\n");
765 /* Hack: inits ct */
766 nfct_callback_register(handle, NFCT_T_ALL, dummy_cb, NULL);
767 nfct_query(handle, NFCT_Q_DUMP, &family);
768 nfct_close(handle);
770 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
771 if (!handle)
772 panic("Cannot create a nfct handle!\n");
774 nfct_query(handle, NFCT_Q_FLUSH, &family);
776 filter = nfct_filter_create();
777 if (!filter)
778 panic("Cannot create a nfct filter!\n");
779 if (what & INCLUDE_UDP)
780 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
781 if (what & INCLUDE_TCP)
782 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
784 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4,
785 NFCT_FILTER_LOGIC_NEGATIVE);
786 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
788 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6,
789 NFCT_FILTER_LOGIC_NEGATIVE);
790 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
792 ret = nfct_filter_attach(nfct_fd(handle), filter);
793 if (ret < 0)
794 panic("Cannot attach filter to handle!\n");
796 nfct_filter_destroy(filter);
798 if (path_country_db)
799 gi_country = GeoIP_open(path_country_db, GEOIP_MMAP_CACHE);
800 else
801 gi_country = GeoIP_open_type(GEOIP_COUNTRY_EDITION,
802 GEOIP_MMAP_CACHE);
804 if (path_city_db)
805 gi_city = GeoIP_open(path_city_db, GEOIP_MMAP_CACHE);
806 else
807 gi_city = GeoIP_open_type(GEOIP_CITY_EDITION_REV1,
808 GEOIP_MMAP_CACHE);
809 if (!gi_country || !gi_city)
810 panic("Cannot open GeoIP database!\n");
812 GeoIP_set_charset(gi_country, GEOIP_CHARSET_UTF8);
813 GeoIP_set_charset(gi_city, GEOIP_CHARSET_UTF8);
815 flow_list_init(&flow_list);
817 rcu_register_thread();
819 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
821 while (!sigint)
822 nfct_catch(handle);
824 rcu_unregister_thread();
826 flow_list_destroy(&flow_list);
828 GeoIP_delete(gi_city);
829 GeoIP_delete(gi_country);
831 nfct_close(handle);
833 if (path_city_db)
834 xfree(path_city_db);
835 if (path_country_db)
836 xfree(path_country_db);
838 pthread_exit(0);
841 int main(int argc, char **argv)
843 pthread_t tid;
844 int ret, c, opt_index, what_cmd = 0;
846 while ((c = getopt_long(argc, argv, short_options, long_options,
847 &opt_index)) != EOF) {
848 switch (c) {
849 case 'T':
850 what_cmd |= INCLUDE_TCP;
851 break;
852 case 'U':
853 what_cmd |= INCLUDE_UDP;
854 break;
855 case 's':
856 show_src = 1;
857 break;
858 case 'L':
859 path_city_db = xstrdup(optarg);
860 break;
861 case 'K':
862 path_country_db = xstrdup(optarg);
863 break;
864 case 'h':
865 help();
866 break;
867 case 'v':
868 version();
869 break;
870 case '?':
871 switch (optopt) {
872 case 'L':
873 case 'K':
874 panic("Option -%c requires an argument!\n",
875 optopt);
876 default:
877 if (isprint(optopt))
878 whine("Unknown option character "
879 "`0x%X\'!\n", optopt);
880 die();
882 default:
883 break;
887 if (what_cmd > 0)
888 what = what_cmd;
890 rcu_init();
892 register_signal(SIGINT, signal_handler);
893 register_signal(SIGHUP, signal_handler);
895 ret = pthread_create(&tid, NULL, collector, NULL);
896 if (ret < 0)
897 panic("Cannot create phthread!\n");
899 presenter();
900 return 0;