Merge pull request #59 from electronjoe/graceful-SIGTERM-handling
[netsniff-ng-old.git] / flowtop.c
blob4fe71dc5cd0da0577249b8555b6776358c8ba0ba
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2011 - 2013 Daniel Borkmann.
4 * Copyright 2011 Emmanuel Roullit.
5 * Subject to the GPL, version 2.
7 * The Dark Lord has Nine. But we have One, mightier than they: the White
8 * Rider. He has passed through the fire and the abyss, and they shall
9 * fear him. We will go where he leads.
11 * -- The Lord of the Rings, Aragorn,
12 * Chapter 'The White Rider'.
15 #define _LGPL_SOURCE
16 #include <stdio.h>
17 #include <stdint.h>
18 #include <stdlib.h>
19 #include <signal.h>
20 #include <getopt.h>
21 #include <pthread.h>
22 #include <signal.h>
23 #include <netdb.h>
24 #include <ctype.h>
25 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
26 #include <libnetfilter_conntrack/libnetfilter_conntrack_tcp.h>
27 #include <libnetfilter_conntrack/libnetfilter_conntrack_dccp.h>
28 #include <libnetfilter_conntrack/libnetfilter_conntrack_sctp.h>
29 #include <netinet/in.h>
30 #include <curses.h>
31 #include <dirent.h>
32 #include <sys/stat.h>
33 #include <sys/fsuid.h>
34 #include <urcu.h>
35 #include <libgen.h>
37 #include "die.h"
38 #include "xmalloc.h"
39 #include "xio.h"
40 #include "geoip.h"
41 #include "xutils.h"
42 #include "built_in.h"
43 #include "locking.h"
44 #include "dissector_eth.h"
45 #include "pkt_buff.h"
47 struct flow_entry {
48 uint32_t flow_id, use, status;
49 uint8_t l3_proto, l4_proto;
50 uint32_t ip4_src_addr, ip4_dst_addr;
51 uint32_t ip6_src_addr[4], ip6_dst_addr[4];
52 uint16_t port_src, port_dst;
53 uint8_t tcp_state, tcp_flags, sctp_state, dccp_state;
54 uint64_t counter_pkts, counter_bytes;
55 uint64_t timestamp_start, timestamp_stop;
56 char country_src[128], country_dst[128];
57 char city_src[128], city_dst[128];
58 char rev_dns_src[256], rev_dns_dst[256];
59 char cmdline[256];
60 struct flow_entry *next;
61 int procnum, inode;
64 struct flow_list {
65 struct flow_entry *head;
66 struct spinlock lock;
69 #ifndef ATTR_TIMESTAMP_START
70 # define ATTR_TIMESTAMP_START 63
71 #endif
72 #ifndef ATTR_TIMESTAMP_STOP
73 # define ATTR_TIMESTAMP_STOP 64
74 #endif
76 #define SCROLL_MAX 1000
78 #define INCLUDE_IPV4 (1 << 0)
79 #define INCLUDE_IPV6 (1 << 1)
80 #define INCLUDE_UDP (1 << 2)
81 #define INCLUDE_TCP (1 << 3)
82 #define INCLUDE_DCCP (1 << 4)
83 #define INCLUDE_ICMP (1 << 5)
84 #define INCLUDE_SCTP (1 << 6)
86 volatile sig_atomic_t sigint = 0;
88 static int what = INCLUDE_IPV4 | INCLUDE_IPV6 | INCLUDE_TCP, show_src = 0;
90 static struct flow_list flow_list;
92 static const char *short_options = "vhTUsDIS46u";
93 static const struct option long_options[] = {
94 {"ipv4", no_argument, NULL, '4'},
95 {"ipv6", no_argument, NULL, '6'},
96 {"tcp", no_argument, NULL, 'T'},
97 {"udp", no_argument, NULL, 'U'},
98 {"dccp", no_argument, NULL, 'D'},
99 {"icmp", no_argument, NULL, 'I'},
100 {"sctp", no_argument, NULL, 'S'},
101 {"show-src", no_argument, NULL, 's'},
102 {"update", no_argument, NULL, 'u'},
103 {"version", no_argument, NULL, 'v'},
104 {"help", no_argument, NULL, 'h'},
105 {NULL, 0, NULL, 0}
108 static const char *const l3proto2str[AF_MAX] = {
109 [AF_INET] = "ipv4",
110 [AF_INET6] = "ipv6",
113 static const char *const l4proto2str[IPPROTO_MAX] = {
114 [IPPROTO_TCP] = "tcp",
115 [IPPROTO_UDP] = "udp",
116 [IPPROTO_UDPLITE] = "udplite",
117 [IPPROTO_ICMP] = "icmp",
118 [IPPROTO_ICMPV6] = "icmpv6",
119 [IPPROTO_SCTP] = "sctp",
120 [IPPROTO_GRE] = "gre",
121 [IPPROTO_DCCP] = "dccp",
122 [IPPROTO_IGMP] = "igmp",
123 [IPPROTO_IPIP] = "ipip",
124 [IPPROTO_EGP] = "egp",
125 [IPPROTO_PUP] = "pup",
126 [IPPROTO_IDP] = "idp",
127 [IPPROTO_RSVP] = "rsvp",
128 [IPPROTO_IPV6] = "ip6tun",
129 [IPPROTO_ESP] = "esp",
130 [IPPROTO_AH] = "ah",
131 [IPPROTO_PIM] = "pim",
132 [IPPROTO_COMP] = "comp",
135 static const char *const tcp_state2str[TCP_CONNTRACK_MAX] = {
136 [TCP_CONNTRACK_NONE] = "NOSTATE",
137 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
138 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
139 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
140 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
141 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
142 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
143 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
144 [TCP_CONNTRACK_CLOSE] = "CLOSE",
145 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
148 static const uint8_t tcp_states[] = {
149 TCP_CONNTRACK_SYN_SENT,
150 TCP_CONNTRACK_SYN_RECV,
151 TCP_CONNTRACK_ESTABLISHED,
152 TCP_CONNTRACK_FIN_WAIT,
153 TCP_CONNTRACK_CLOSE_WAIT,
154 TCP_CONNTRACK_LAST_ACK,
155 TCP_CONNTRACK_TIME_WAIT,
156 TCP_CONNTRACK_CLOSE,
157 TCP_CONNTRACK_SYN_SENT2,
158 TCP_CONNTRACK_NONE,
161 static const char *const dccp_state2str[DCCP_CONNTRACK_MAX] = {
162 [DCCP_CONNTRACK_NONE] = "NOSTATE",
163 [DCCP_CONNTRACK_REQUEST] = "REQUEST",
164 [DCCP_CONNTRACK_RESPOND] = "RESPOND",
165 [DCCP_CONNTRACK_PARTOPEN] = "PARTOPEN",
166 [DCCP_CONNTRACK_OPEN] = "OPEN",
167 [DCCP_CONNTRACK_CLOSEREQ] = "CLOSEREQ",
168 [DCCP_CONNTRACK_CLOSING] = "CLOSING",
169 [DCCP_CONNTRACK_TIMEWAIT] = "TIMEWAIT",
170 [DCCP_CONNTRACK_IGNORE] = "IGNORE",
171 [DCCP_CONNTRACK_INVALID] = "INVALID",
174 static const uint8_t dccp_states[] = {
175 DCCP_CONNTRACK_NONE,
176 DCCP_CONNTRACK_REQUEST,
177 DCCP_CONNTRACK_RESPOND,
178 DCCP_CONNTRACK_PARTOPEN,
179 DCCP_CONNTRACK_OPEN,
180 DCCP_CONNTRACK_CLOSEREQ,
181 DCCP_CONNTRACK_CLOSING,
182 DCCP_CONNTRACK_TIMEWAIT,
183 DCCP_CONNTRACK_IGNORE,
184 DCCP_CONNTRACK_INVALID,
187 static const char *const sctp_state2str[SCTP_CONNTRACK_MAX] = {
188 [SCTP_CONNTRACK_NONE] = "NOSTATE",
189 [SCTP_CONNTRACK_CLOSED] = "CLOSED",
190 [SCTP_CONNTRACK_COOKIE_WAIT] = "COOKIE_WAIT",
191 [SCTP_CONNTRACK_COOKIE_ECHOED] = "COOKIE_ECHOED",
192 [SCTP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
193 [SCTP_CONNTRACK_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
194 [SCTP_CONNTRACK_SHUTDOWN_RECD] = "SHUTDOWN_RECD",
195 [SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = "SHUTDOWN_ACK_SENT",
198 static const uint8_t sctp_states[] = {
199 SCTP_CONNTRACK_NONE,
200 SCTP_CONNTRACK_CLOSED,
201 SCTP_CONNTRACK_COOKIE_WAIT,
202 SCTP_CONNTRACK_COOKIE_ECHOED,
203 SCTP_CONNTRACK_ESTABLISHED,
204 SCTP_CONNTRACK_SHUTDOWN_SENT,
205 SCTP_CONNTRACK_SHUTDOWN_RECD,
206 SCTP_CONNTRACK_SHUTDOWN_ACK_SENT,
209 static const struct nfct_filter_ipv4 filter_ipv4 = {
210 .addr = __constant_htonl(INADDR_LOOPBACK),
211 .mask = 0xffffffff,
214 static const struct nfct_filter_ipv6 filter_ipv6 = {
215 .addr = { 0x0, 0x0, 0x0, 0x1 },
216 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
219 static void signal_handler(int number)
221 switch (number) {
222 case SIGINT:
223 sigint = 1;
224 break;
225 case SIGHUP:
226 default:
227 break;
231 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct);
232 static void flow_entry_get_extended(struct flow_entry *n);
234 static void help(void)
236 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
237 VERSION_STRING);
238 puts("http://www.netsniff-ng.org\n\n"
239 "Usage: flowtop [options]\n"
240 "Options:\n"
241 " -4|--ipv4 Show only IPv4 flows (default)\n"
242 " -6|--ipv6 Show only IPv6 flows (default)\n"
243 " -T|--tcp Show only TCP flows (default)\n"
244 " -U|--udp Show only UDP flows\n"
245 " -D|--dccp Show only DCCP flows\n"
246 " -I|--icmp Show only ICMP/ICMPv6 flows\n"
247 " -S|--sctp Show only SCTP flows\n"
248 " -s|--show-src Also show source, not only dest\n"
249 " -u|--update Update GeoIP databases\n"
250 " -v|--version Print version\n"
251 " -h|--help Print this help\n\n"
252 "Examples:\n"
253 " flowtop\n"
254 " flowtop -46UTDISs\n\n"
255 "Note:\n"
256 " If netfilter is not running, you can activate it with e.g.:\n"
257 " iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
258 " iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n\n"
259 "Please report bugs to <bugs@netsniff-ng.org>\n"
260 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
261 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
262 "Swiss federal institute of technology (ETH Zurich)\n"
263 "License: GNU GPL version 2.0\n"
264 "This is free software: you are free to change and redistribute it.\n"
265 "There is NO WARRANTY, to the extent permitted by law.\n");
266 die();
269 static void version(void)
271 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
272 VERSION_STRING);
273 puts("http://www.netsniff-ng.org\n\n"
274 "Please report bugs to <bugs@netsniff-ng.org>\n"
275 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
276 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
277 "Swiss federal institute of technology (ETH Zurich)\n"
278 "License: GNU GPL version 2.0\n"
279 "This is free software: you are free to change and redistribute it.\n"
280 "There is NO WARRANTY, to the extent permitted by law.\n");
281 die();
284 static inline struct flow_entry *flow_entry_xalloc(void)
286 return xzmalloc(sizeof(struct flow_entry));
289 static inline void flow_entry_xfree(struct flow_entry *n)
291 xfree(n);
294 static inline void flow_list_init(struct flow_list *fl)
296 fl->head = NULL;
297 spinlock_init(&fl->lock);
300 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
302 struct flow_entry *n = flow_entry_xalloc();
304 flow_entry_from_ct(n, ct);
305 flow_entry_get_extended(n);
307 rcu_assign_pointer(n->next, fl->head);
308 rcu_assign_pointer(fl->head, n);
311 static struct flow_entry *flow_list_find_id(struct flow_list *fl,
312 uint32_t id)
314 struct flow_entry *n = rcu_dereference(fl->head);
316 while (n != NULL) {
317 if (n->flow_id == id)
318 return n;
320 n = rcu_dereference(n->next);
323 return NULL;
326 static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
327 uint32_t id)
329 struct flow_entry *n = rcu_dereference(fl->head), *tmp;
331 if (n->flow_id == id)
332 return NULL;
334 while ((tmp = rcu_dereference(n->next)) != NULL) {
335 if (tmp->flow_id == id)
336 return n;
338 n = tmp;
341 return NULL;
344 static void flow_list_update_entry(struct flow_list *fl,
345 struct nf_conntrack *ct)
347 int do_ext = 0;
348 struct flow_entry *n;
350 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
351 if (n == NULL) {
352 n = flow_entry_xalloc();
353 do_ext = 1;
356 flow_entry_from_ct(n, ct);
357 if (do_ext) {
358 flow_entry_get_extended(n);
360 rcu_assign_pointer(n->next, fl->head);
361 rcu_assign_pointer(fl->head, n);
365 static void flow_list_destroy_entry(struct flow_list *fl,
366 struct nf_conntrack *ct)
368 struct flow_entry *n1, *n2;
369 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
371 n1 = flow_list_find_id(fl, id);
372 if (n1) {
373 n2 = flow_list_find_prev_id(fl, id);
374 if (n2) {
375 rcu_assign_pointer(n2->next, n1->next);
376 rcu_assign_pointer(n1->next, NULL);
378 flow_entry_xfree(n1);
379 } else {
380 flow_entry_xfree(fl->head);
382 rcu_assign_pointer(fl->head, NULL);
387 static void flow_list_destroy(struct flow_list *fl)
389 struct flow_entry *n;
391 while (fl->head != NULL) {
392 n = rcu_dereference(fl->head->next);
393 rcu_assign_pointer(fl->head->next, NULL);
395 flow_entry_xfree(fl->head);
396 rcu_assign_pointer(fl->head, n);
399 synchronize_rcu();
400 spinlock_destroy(&fl->lock);
403 static int walk_process(char *process, struct flow_entry *n)
405 int ret;
406 DIR *dir;
407 struct dirent *ent;
408 char path[1024];
410 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
411 panic("giant process name! %s\n", process);
413 dir = opendir(path);
414 if (!dir)
415 return 0;
417 while ((ent = readdir(dir))) {
418 struct stat statbuf;
420 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
421 process, ent->d_name) < 0)
422 continue;
424 if (stat(path, &statbuf) < 0)
425 continue;
427 if (S_ISSOCK(statbuf.st_mode) && n->inode == statbuf.st_ino) {
428 memset(n->cmdline, 0, sizeof(n->cmdline));
430 snprintf(path, sizeof(path), "/proc/%s/exe", process);
432 ret = readlink(path, n->cmdline,
433 sizeof(n->cmdline) - 1);
434 if (ret < 0)
435 panic("readlink error: %s\n", strerror(errno));
437 n->procnum = atoi(process);
438 return 1;
442 closedir(dir);
443 return 0;
446 static void walk_processes(struct flow_entry *n)
448 int ret;
449 DIR *dir;
450 struct dirent *ent;
452 /* n->inode must be set */
453 if (n->inode <= 0) {
454 memset(n->cmdline, 0, sizeof(n->cmdline));
455 return;
458 dir = opendir("/proc");
459 if (!dir)
460 panic("Cannot open /proc!\n");
462 while ((ent = readdir(dir))) {
463 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name)) {
464 ret = walk_process(ent->d_name, n);
465 if (ret > 0)
466 break;
470 closedir(dir);
473 static int get_port_inode(uint16_t port, int proto, int is_ip6)
475 int ret = -ENOENT;
476 char path[128], buff[1024];
477 FILE *proc;
479 memset(path, 0, sizeof(path));
480 snprintf(path, sizeof(path), "/proc/net/%s%s",
481 l4proto2str[proto], is_ip6 ? "6" : "");
483 proc = fopen(path, "r");
484 if (!proc)
485 return -EIO;
487 memset(buff, 0, sizeof(buff));
489 while (fgets(buff, sizeof(buff), proc) != NULL) {
490 int inode = 0;
491 unsigned int lport = 0;
493 buff[sizeof(buff) - 1] = 0;
494 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
495 "%*X %*u %*u %u", &lport, &inode) == 2) {
496 if ((uint16_t) lport == port) {
497 ret = inode;
498 break;
502 memset(buff, 0, sizeof(buff));
505 fclose(proc);
506 return ret;
509 #define CP_NFCT(elem, attr, x) \
510 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
511 #define CP_NFCT_BUFF(elem, attr) do { \
512 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
513 if (buff != NULL) \
514 memcpy(n->elem, buff, sizeof(n->elem)); \
515 } while (0)
517 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
519 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
520 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
522 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
523 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
525 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
526 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
528 CP_NFCT(status, ATTR_STATUS, 32);
530 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
531 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
532 CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
533 CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
535 CP_NFCT(counter_pkts, ATTR_ORIG_COUNTER_PACKETS, 64);
536 CP_NFCT(counter_bytes, ATTR_ORIG_COUNTER_BYTES, 64);
538 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
539 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
541 CP_NFCT(flow_id, ATTR_ID, 32);
542 CP_NFCT(use, ATTR_USE, 32);
544 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
545 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
547 n->port_src = ntohs(n->port_src);
548 n->port_dst = ntohs(n->port_dst);
550 n->ip4_src_addr = ntohl(n->ip4_src_addr);
551 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
554 enum flow_entry_direction {
555 flow_entry_src,
556 flow_entry_dst,
559 static inline int flow_entry_get_extended_is_dns(struct flow_entry *n)
561 /* We don't want to analyze / display DNS itself, since we
562 * use it to resolve reverse dns.
564 return n->port_src == 53 || n->port_dst == 53;
567 #define SELFLD(dir,src_member,dst_member) \
568 (((dir) == flow_entry_src) ? n->src_member : n->dst_member)
570 static struct sockaddr_in *
571 flow_entry_get_sain4_obj(struct flow_entry *n, enum flow_entry_direction dir,
572 struct sockaddr_in *sa)
574 memset(sa, 0, sizeof(*sa));
575 sa->sin_family = PF_INET;
576 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
578 return sa;
581 static struct sockaddr_in6 *
582 flow_entry_get_sain6_obj(struct flow_entry *n, enum flow_entry_direction dir,
583 struct sockaddr_in6 *sa)
585 memset(sa, 0, sizeof(*sa));
586 sa->sin6_family = PF_INET6;
588 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
589 sizeof(SELFLD(dir, ip6_src_addr, ip6_dst_addr)));
591 return sa;
594 static void
595 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
596 enum flow_entry_direction dir)
598 struct sockaddr_in sa4;
599 struct sockaddr_in6 sa6;
600 const char *city = NULL;
602 switch (n->l3_proto) {
603 default:
604 bug();
606 case AF_INET:
607 flow_entry_get_sain4_obj(n, dir, &sa4);
608 city = geoip4_city_name(sa4);
609 break;
611 case AF_INET6:
612 flow_entry_get_sain6_obj(n, dir, &sa6);
613 city = geoip6_city_name(sa6);
614 break;
617 bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
619 if (city) {
620 memcpy(SELFLD(dir, city_src, city_dst), city,
621 min(sizeof(n->city_src), strlen(city)));
622 } else {
623 memset(SELFLD(dir, city_src, city_dst), 0,
624 sizeof(n->city_src));
628 static void
629 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
630 enum flow_entry_direction dir)
632 struct sockaddr_in sa4;
633 struct sockaddr_in6 sa6;
634 inline const char *make_na(const char *p) { return p ? : "N/A"; }
635 const char *country = NULL;
637 switch (n->l3_proto) {
638 default:
639 bug();
641 case AF_INET:
642 flow_entry_get_sain4_obj(n, dir, &sa4);
643 country = geoip4_country_name(sa4);
644 break;
646 case AF_INET6:
647 flow_entry_get_sain6_obj(n, dir, &sa6);
648 country = geoip6_country_name(sa6);
649 break;
652 country = make_na(country);
654 bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
656 memcpy(SELFLD(dir, country_src, country_dst), country,
657 min(sizeof(n->country_src), strlen(country)));
660 static void flow_entry_get_extended_geo(struct flow_entry *n,
661 enum flow_entry_direction dir)
663 flow_entry_geo_city_lookup_generic(n, dir);
664 flow_entry_geo_country_lookup_generic(n, dir);
667 static void flow_entry_get_extended_revdns(struct flow_entry *n,
668 enum flow_entry_direction dir)
670 size_t sa_len;
671 struct sockaddr_in sa4;
672 struct sockaddr_in6 sa6;
673 struct sockaddr *sa;
674 struct hostent *hent;
676 switch (n->l3_proto) {
677 default:
678 bug();
680 case AF_INET:
681 flow_entry_get_sain4_obj(n, dir, &sa4);
682 sa = (struct sockaddr *) &sa4;
683 sa_len = sizeof(sa4);
684 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr), AF_INET);
685 break;
687 case AF_INET6:
688 flow_entry_get_sain6_obj(n, dir, &sa6);
689 sa = (struct sockaddr *) &sa6;
690 sa_len = sizeof(sa6);
691 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr), AF_INET6);
692 break;
695 bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
696 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
697 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
699 if (hent) {
700 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
701 memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
702 hent->h_name, min(sizeof(n->rev_dns_src),
703 strlen(hent->h_name)));
707 static void flow_entry_get_extended(struct flow_entry *n)
709 if (n->flow_id == 0 || flow_entry_get_extended_is_dns(n))
710 return;
712 flow_entry_get_extended_revdns(n, flow_entry_src);
713 flow_entry_get_extended_geo(n, flow_entry_src);
715 flow_entry_get_extended_revdns(n, flow_entry_dst);
716 flow_entry_get_extended_geo(n, flow_entry_dst);
718 /* Lookup application */
719 n->inode = get_port_inode(n->port_src, n->l4_proto,
720 n->l3_proto == AF_INET6);
721 if (n->inode > 0)
722 walk_processes(n);
725 static uint16_t presenter_get_port(uint16_t src, uint16_t dst, int tcp)
727 if (src < dst && src < 1024) {
728 return src;
729 } else if (dst < src && dst < 1024) {
730 return dst;
731 } else {
732 const char *tmp1, *tmp2;
733 if (tcp) {
734 tmp1 = lookup_port_tcp(src);
735 tmp2 = lookup_port_tcp(dst);
736 } else {
737 tmp1 = lookup_port_udp(src);
738 tmp2 = lookup_port_udp(dst);
740 if (tmp1 && !tmp2) {
741 return src;
742 } else if (!tmp1 && tmp2) {
743 return dst;
744 } else {
745 if (src < dst)
746 return src;
747 else
748 return dst;
753 static void presenter_screen_init(WINDOW **screen)
755 (*screen) = initscr();
756 noecho();
757 cbreak();
758 keypad(stdscr, TRUE);
759 nodelay(*screen, TRUE);
760 refresh();
761 wrefresh(*screen);
764 static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
765 unsigned int *line)
767 char tmp[128], *pname = NULL;
768 uint16_t port;
770 mvwprintw(screen, *line, 2, "");
772 /* PID, application name */
773 if (n->procnum > 0) {
774 slprintf(tmp, sizeof(tmp), "%s(%u)", basename(n->cmdline),
775 n->procnum);
777 printw("[");
778 attron(COLOR_PAIR(3));
779 printw("%s", tmp);
780 attroff(COLOR_PAIR(3));
781 printw("]:");
784 /* L3 protocol, L4 protocol, states */
785 printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
786 printw("[");
787 attron(COLOR_PAIR(3));
788 switch (n->l4_proto) {
789 case IPPROTO_TCP:
790 printw("%s", tcp_state2str[n->tcp_state]);
791 break;
792 case IPPROTO_SCTP:
793 printw("%s", sctp_state2str[n->sctp_state]);
794 break;
795 case IPPROTO_DCCP:
796 printw("%s", dccp_state2str[n->dccp_state]);
797 break;
798 case IPPROTO_UDP:
799 case IPPROTO_UDPLITE:
800 case IPPROTO_ICMP:
801 case IPPROTO_ICMPV6:
802 printw("NOSTATE");
803 break;
805 attroff(COLOR_PAIR(3));
806 printw("]");
808 /* Guess application port */
809 switch (n->l4_proto) {
810 case IPPROTO_TCP:
811 port = presenter_get_port(n->port_src, n->port_dst, 1);
812 pname = lookup_port_tcp(port);
813 break;
814 case IPPROTO_UDP:
815 case IPPROTO_UDPLITE:
816 port = presenter_get_port(n->port_src, n->port_dst, 0);
817 pname = lookup_port_udp(port);
818 break;
820 if (pname) {
821 attron(A_BOLD);
822 printw(":%s", pname);
823 attroff(A_BOLD);
825 printw(" ->");
827 /* Number packets, bytes */
828 if (n->counter_pkts > 0 && n->counter_bytes > 0)
829 printw(" (%llu pkts, %llu bytes) ->",
830 n->counter_pkts, n->counter_bytes);
832 /* Show source information: reverse DNS, port, country, city */
833 if (show_src) {
834 attron(COLOR_PAIR(1));
835 mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
836 attroff(COLOR_PAIR(1));
838 printw(":%u (", n->port_src);
840 attron(COLOR_PAIR(4));
841 printw("%s", n->country_src);
842 attroff(COLOR_PAIR(4));
844 if (n->city_src[0])
845 printw(", %s", n->city_src);
846 printw(") => ");
849 /* Show dest information: reverse DNS, port, country, city */
850 attron(COLOR_PAIR(2));
851 mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
852 attroff(COLOR_PAIR(2));
854 printw(":%u (", n->port_dst);
856 attron(COLOR_PAIR(4));
857 printw("%s", n->country_dst);
858 attroff(COLOR_PAIR(4));
860 if (n->city_dst[0])
861 printw(", %s", n->city_dst);
862 printw(")");
865 static inline int presenter_flow_wrong_state(struct flow_entry *n, int state)
867 int ret = 1;
869 switch (n->l4_proto) {
870 case IPPROTO_TCP:
871 if (n->tcp_state == state)
872 ret = 0;
873 break;
874 case IPPROTO_SCTP:
875 if (n->sctp_state == state)
876 ret = 0;
877 break;
878 case IPPROTO_DCCP:
879 if (n->dccp_state == state)
880 ret = 0;
881 break;
882 case IPPROTO_UDP:
883 case IPPROTO_UDPLITE:
884 case IPPROTO_ICMP:
885 case IPPROTO_ICMPV6:
886 ret = 0;
887 break;
890 return ret;
893 static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
894 int skip_lines)
896 int i, j, maxy;
897 unsigned int line = 3;
898 struct flow_entry *n;
899 uint8_t protocols[] = {
900 IPPROTO_TCP,
901 IPPROTO_DCCP,
902 IPPROTO_SCTP,
903 IPPROTO_UDP,
904 IPPROTO_UDPLITE,
905 IPPROTO_ICMP,
906 IPPROTO_ICMPV6,
908 size_t protocol_state_size[] = {
909 [IPPROTO_TCP] = array_size(tcp_states),
910 [IPPROTO_DCCP] = array_size(dccp_states),
911 [IPPROTO_SCTP] = array_size(sctp_states),
912 [IPPROTO_UDP] = 1,
913 [IPPROTO_UDPLITE] = 1,
914 [IPPROTO_ICMP] = 1,
915 [IPPROTO_ICMPV6] = 1,
918 curs_set(0);
920 maxy = getmaxy(screen);
921 maxy -= 6;
923 start_color();
924 init_pair(1, COLOR_RED, COLOR_BLACK);
925 init_pair(2, COLOR_BLUE, COLOR_BLACK);
926 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
927 init_pair(4, COLOR_GREEN, COLOR_BLACK);
929 wclear(screen);
930 clear();
932 mvwprintw(screen, 1, 2, "Kernel netfilter TCP/UDP "
933 "flow statistics, [+%d]", skip_lines);
935 rcu_read_lock();
937 if (rcu_dereference(fl->head) == NULL)
938 mvwprintw(screen, line, 2, "(No active sessions! "
939 "Is netfilter running?)");
941 for (i = 0; i < array_size(protocols); i++) {
942 for (j = 0; j < protocol_state_size[protocols[i]]; j++) {
943 n = rcu_dereference(fl->head);
944 while (n && maxy > 0) {
945 int skip_entry = 0;
947 if (n->l4_proto != protocols[i])
948 skip_entry = 1;
949 if (presenter_flow_wrong_state(n, j))
950 skip_entry = 1;
951 if (presenter_get_port(n->port_src,
952 n->port_dst, 0) == 53)
953 skip_entry = 1;
954 if (skip_entry) {
955 n = rcu_dereference(n->next);
956 continue;
958 if (skip_lines > 0) {
959 n = rcu_dereference(n->next);
960 skip_lines--;
961 continue;
964 presenter_screen_do_line(screen, n, &line);
966 line++;
967 maxy -= (2 + 1 * show_src);
968 n = rcu_dereference(n->next);
973 rcu_read_unlock();
975 wrefresh(screen);
976 refresh();
979 static inline void presenter_screen_end(void)
981 endwin();
984 static void presenter(void)
986 int skip_lines = 0;
987 WINDOW *screen = NULL;
989 dissector_init_ethernet(0);
990 presenter_screen_init(&screen);
992 rcu_register_thread();
993 while (!sigint) {
994 switch (getch()) {
995 case 'q':
996 sigint = 1;
997 break;
998 case KEY_UP:
999 case 'u':
1000 case 'k':
1001 skip_lines--;
1002 if (skip_lines < 0)
1003 skip_lines = 0;
1004 break;
1005 case KEY_DOWN:
1006 case 'd':
1007 case 'j':
1008 skip_lines++;
1009 if (skip_lines > SCROLL_MAX)
1010 skip_lines = SCROLL_MAX;
1011 break;
1012 default:
1013 fflush(stdin);
1014 break;
1017 presenter_screen_update(screen, &flow_list, skip_lines);
1018 usleep(100000);
1020 rcu_unregister_thread();
1022 presenter_screen_end();
1023 dissector_cleanup_ethernet();
1026 static int collector_cb(enum nf_conntrack_msg_type type,
1027 struct nf_conntrack *ct, void *data)
1029 if (sigint)
1030 return NFCT_CB_STOP;
1032 synchronize_rcu();
1033 spinlock_lock(&flow_list.lock);
1035 switch (type) {
1036 case NFCT_T_NEW:
1037 flow_list_new_entry(&flow_list, ct);
1038 break;
1039 case NFCT_T_UPDATE:
1040 flow_list_update_entry(&flow_list, ct);
1041 break;
1042 case NFCT_T_DESTROY:
1043 flow_list_destroy_entry(&flow_list, ct);
1044 break;
1045 default:
1046 break;
1049 spinlock_unlock(&flow_list.lock);
1051 return NFCT_CB_CONTINUE;
1054 static inline void collector_flush(struct nfct_handle *handle, uint8_t family)
1056 nfct_query(handle, NFCT_Q_FLUSH, &family);
1059 static void *collector(void *null)
1061 int ret;
1062 struct nfct_handle *handle;
1063 struct nfct_filter *filter;
1065 handle = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1066 NF_NETLINK_CONNTRACK_UPDATE |
1067 NF_NETLINK_CONNTRACK_DESTROY);
1068 if (!handle)
1069 panic("Cannot create a nfct handle!\n");
1071 collector_flush(handle, AF_INET);
1072 collector_flush(handle, AF_INET6);
1074 filter = nfct_filter_create();
1075 if (!filter)
1076 panic("Cannot create a nfct filter!\n");
1078 ret = nfct_filter_attach(nfct_fd(handle), filter);
1079 if (ret < 0)
1080 panic("Cannot attach filter to handle!\n");
1082 if (what & INCLUDE_UDP) {
1083 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1084 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
1086 if (what & INCLUDE_TCP)
1087 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1088 if (what & INCLUDE_DCCP)
1089 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1090 if (what & INCLUDE_SCTP)
1091 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1092 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1093 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1094 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1095 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1096 if (what & INCLUDE_IPV4) {
1097 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4, NFCT_FILTER_LOGIC_NEGATIVE);
1098 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1100 if (what & INCLUDE_IPV6) {
1101 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6, NFCT_FILTER_LOGIC_NEGATIVE);
1102 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1105 ret = nfct_filter_attach(nfct_fd(handle), filter);
1106 if (ret < 0)
1107 panic("Cannot attach filter to handle!\n");
1109 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
1110 nfct_filter_destroy(filter);
1111 flow_list_init(&flow_list);
1113 rcu_register_thread();
1115 while (!sigint && ret >= 0)
1116 ret = nfct_catch(handle);
1118 rcu_unregister_thread();
1120 flow_list_destroy(&flow_list);
1121 nfct_close(handle);
1123 pthread_exit(0);
1126 int main(int argc, char **argv)
1128 pthread_t tid;
1129 int ret, c, opt_index, what_cmd = 0;
1131 setfsuid(getuid());
1132 setfsgid(getgid());
1134 while ((c = getopt_long(argc, argv, short_options, long_options,
1135 &opt_index)) != EOF) {
1136 switch (c) {
1137 case '4':
1138 what_cmd |= INCLUDE_IPV4;
1139 break;
1140 case '6':
1141 what_cmd |= INCLUDE_IPV6;
1142 break;
1143 case 'T':
1144 what_cmd |= INCLUDE_TCP;
1145 break;
1146 case 'U':
1147 what_cmd |= INCLUDE_UDP;
1148 break;
1149 case 'D':
1150 what_cmd |= INCLUDE_DCCP;
1151 break;
1152 case 'I':
1153 what_cmd |= INCLUDE_ICMP;
1154 break;
1155 case 'S':
1156 what_cmd |= INCLUDE_SCTP;
1157 break;
1158 case 's':
1159 show_src = 1;
1160 break;
1161 case 'u':
1162 update_geoip();
1163 die();
1164 break;
1165 case 'h':
1166 help();
1167 break;
1168 case 'v':
1169 version();
1170 break;
1171 default:
1172 break;
1176 if (what_cmd > 0)
1177 what = what_cmd;
1179 rcu_init();
1181 register_signal(SIGINT, signal_handler);
1182 register_signal(SIGHUP, signal_handler);
1184 init_geoip(1);
1186 ret = pthread_create(&tid, NULL, collector, NULL);
1187 if (ret < 0)
1188 panic("Cannot create phthread!\n");
1190 presenter();
1192 destroy_geoip();
1194 return 0;