flowtop: Show counters by direction
[netsniff-ng.git] / flowtop.c
blob492d77a05f5a475316b84716ab7f0e1fc6156b93
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.
6 */
8 #define _LGPL_SOURCE
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <stdlib.h>
12 #include <signal.h>
13 #include <getopt.h>
14 #include <pthread.h>
15 #include <signal.h>
16 #include <netdb.h>
17 #include <ctype.h>
18 #include <netinet/in.h>
19 #include <curses.h>
20 #include <dirent.h>
21 #include <sys/stat.h>
22 #include <sys/fsuid.h>
23 #include <urcu.h>
24 #include <libgen.h>
25 #include <inttypes.h>
26 #include <poll.h>
27 #include <fcntl.h>
29 #include "die.h"
30 #include "xmalloc.h"
31 #include "conntrack.h"
32 #include "config.h"
33 #include "str.h"
34 #include "sig.h"
35 #include "lookup.h"
36 #include "geoip.h"
37 #include "built_in.h"
38 #include "locking.h"
39 #include "pkt_buff.h"
40 #include "screen.h"
41 #include "proc.h"
42 #include "sysctl.h"
44 struct flow_entry {
45 uint32_t flow_id, use, status;
46 uint8_t l3_proto, l4_proto;
47 uint32_t ip4_src_addr, ip4_dst_addr;
48 uint32_t ip6_src_addr[4], ip6_dst_addr[4];
49 uint16_t port_src, port_dst;
50 uint8_t tcp_state, tcp_flags, sctp_state, dccp_state;
51 uint64_t src_pkts, src_bytes;
52 uint64_t dst_pkts, dst_bytes;
53 uint64_t timestamp_start, timestamp_stop;
54 char country_src[128], country_dst[128];
55 char city_src[128], city_dst[128];
56 char rev_dns_src[256], rev_dns_dst[256];
57 char cmdline[256];
58 struct flow_entry *next;
59 int inode;
60 unsigned int procnum;
61 bool is_visible;
62 struct nf_conntrack *ct;
65 struct flow_list {
66 struct flow_entry *head;
67 struct spinlock lock;
70 #ifndef ATTR_TIMESTAMP_START
71 # define ATTR_TIMESTAMP_START 63
72 #endif
73 #ifndef ATTR_TIMESTAMP_STOP
74 # define ATTR_TIMESTAMP_STOP 64
75 #endif
77 #define SCROLL_MAX 1000
79 #define INCLUDE_IPV4 (1 << 0)
80 #define INCLUDE_IPV6 (1 << 1)
81 #define INCLUDE_UDP (1 << 2)
82 #define INCLUDE_TCP (1 << 3)
83 #define INCLUDE_DCCP (1 << 4)
84 #define INCLUDE_ICMP (1 << 5)
85 #define INCLUDE_SCTP (1 << 6)
87 static volatile bool is_flow_collecting;
88 static volatile sig_atomic_t sigint = 0;
89 static int what = INCLUDE_IPV4 | INCLUDE_IPV6 | INCLUDE_TCP, show_src = 0;
90 static struct flow_list flow_list;
91 static int nfct_acct_val = -1;
93 static const char *short_options = "vhTUsDIS46u";
94 static const struct option long_options[] = {
95 {"ipv4", no_argument, NULL, '4'},
96 {"ipv6", no_argument, NULL, '6'},
97 {"tcp", no_argument, NULL, 'T'},
98 {"udp", no_argument, NULL, 'U'},
99 {"dccp", no_argument, NULL, 'D'},
100 {"icmp", no_argument, NULL, 'I'},
101 {"sctp", no_argument, NULL, 'S'},
102 {"show-src", no_argument, NULL, 's'},
103 {"update", no_argument, NULL, 'u'},
104 {"version", no_argument, NULL, 'v'},
105 {"help", no_argument, NULL, 'h'},
106 {NULL, 0, NULL, 0}
109 static const char *copyright = "Please report bugs to <bugs@netsniff-ng.org>\n"
110 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
111 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
112 "Swiss federal institute of technology (ETH Zurich)\n"
113 "License: GNU GPL version 2.0\n"
114 "This is free software: you are free to change and redistribute it.\n"
115 "There is NO WARRANTY, to the extent permitted by law.";
117 static const char *const l3proto2str[AF_MAX] = {
118 [AF_INET] = "ipv4",
119 [AF_INET6] = "ipv6",
122 static const char *const l4proto2str[IPPROTO_MAX] = {
123 [IPPROTO_TCP] = "tcp",
124 [IPPROTO_UDP] = "udp",
125 [IPPROTO_UDPLITE] = "udplite",
126 [IPPROTO_ICMP] = "icmp",
127 [IPPROTO_ICMPV6] = "icmpv6",
128 [IPPROTO_SCTP] = "sctp",
129 [IPPROTO_GRE] = "gre",
130 [IPPROTO_DCCP] = "dccp",
131 [IPPROTO_IGMP] = "igmp",
132 [IPPROTO_IPIP] = "ipip",
133 [IPPROTO_EGP] = "egp",
134 [IPPROTO_PUP] = "pup",
135 [IPPROTO_IDP] = "idp",
136 [IPPROTO_RSVP] = "rsvp",
137 [IPPROTO_IPV6] = "ip6tun",
138 [IPPROTO_ESP] = "esp",
139 [IPPROTO_AH] = "ah",
140 [IPPROTO_PIM] = "pim",
141 [IPPROTO_COMP] = "comp",
144 static const char *const tcp_state2str[TCP_CONNTRACK_MAX] = {
145 [TCP_CONNTRACK_NONE] = "NOSTATE",
146 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
147 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
148 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
149 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
150 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
151 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
152 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
153 [TCP_CONNTRACK_CLOSE] = "CLOSE",
154 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
157 static const char *const dccp_state2str[DCCP_CONNTRACK_MAX] = {
158 [DCCP_CONNTRACK_NONE] = "NOSTATE",
159 [DCCP_CONNTRACK_REQUEST] = "REQUEST",
160 [DCCP_CONNTRACK_RESPOND] = "RESPOND",
161 [DCCP_CONNTRACK_PARTOPEN] = "PARTOPEN",
162 [DCCP_CONNTRACK_OPEN] = "OPEN",
163 [DCCP_CONNTRACK_CLOSEREQ] = "CLOSEREQ",
164 [DCCP_CONNTRACK_CLOSING] = "CLOSING",
165 [DCCP_CONNTRACK_TIMEWAIT] = "TIMEWAIT",
166 [DCCP_CONNTRACK_IGNORE] = "IGNORE",
167 [DCCP_CONNTRACK_INVALID] = "INVALID",
170 static const char *const sctp_state2str[SCTP_CONNTRACK_MAX] = {
171 [SCTP_CONNTRACK_NONE] = "NOSTATE",
172 [SCTP_CONNTRACK_CLOSED] = "CLOSED",
173 [SCTP_CONNTRACK_COOKIE_WAIT] = "COOKIE_WAIT",
174 [SCTP_CONNTRACK_COOKIE_ECHOED] = "COOKIE_ECHOED",
175 [SCTP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
176 [SCTP_CONNTRACK_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
177 [SCTP_CONNTRACK_SHUTDOWN_RECD] = "SHUTDOWN_RECD",
178 [SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = "SHUTDOWN_ACK_SENT",
181 static const struct nfct_filter_ipv4 filter_ipv4 = {
182 .addr = __constant_htonl(INADDR_LOOPBACK),
183 .mask = 0xffffffff,
186 static const struct nfct_filter_ipv6 filter_ipv6 = {
187 .addr = { 0x0, 0x0, 0x0, 0x1 },
188 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
191 static void signal_handler(int number)
193 switch (number) {
194 case SIGINT:
195 case SIGQUIT:
196 case SIGTERM:
197 sigint = 1;
198 break;
199 case SIGHUP:
200 default:
201 break;
205 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct);
206 static void flow_entry_get_extended(struct flow_entry *n);
208 static void help(void)
210 printf("flowtop %s, top-like netfilter TCP/UDP/SCTP/.. flow tracking\n",
211 VERSION_STRING);
212 puts("http://www.netsniff-ng.org\n\n"
213 "Usage: flowtop [options]\n"
214 "Options:\n"
215 " -4|--ipv4 Show only IPv4 flows (default)\n"
216 " -6|--ipv6 Show only IPv6 flows (default)\n"
217 " -T|--tcp Show only TCP flows (default)\n"
218 " -U|--udp Show only UDP flows\n"
219 " -D|--dccp Show only DCCP flows\n"
220 " -I|--icmp Show only ICMP/ICMPv6 flows\n"
221 " -S|--sctp Show only SCTP flows\n"
222 " -s|--show-src Also show source, not only dest\n"
223 " -u|--update Update GeoIP databases\n"
224 " -v|--version Print version and exit\n"
225 " -h|--help Print this help and exit\n\n"
226 "Examples:\n"
227 " flowtop\n"
228 " flowtop -46UTDISs\n\n"
229 "Note:\n"
230 " If netfilter is not running, you can activate it with e.g.:\n"
231 " iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
232 " iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n");
233 puts(copyright);
234 die();
237 static void version(void)
239 printf("flowtop %s, Git id: %s\n", VERSION_LONG, GITVERSION);
240 puts("top-like netfilter TCP/UDP/SCTP/.. flow tracking\n"
241 "http://www.netsniff-ng.org\n");
242 puts(copyright);
243 die();
246 static inline struct flow_entry *flow_entry_xalloc(void)
248 return xzmalloc(sizeof(struct flow_entry));
251 static inline void flow_entry_xfree(struct flow_entry *n)
253 if (n->ct)
254 nfct_destroy(n->ct);
256 xfree(n);
259 static inline void flow_list_init(struct flow_list *fl)
261 fl->head = NULL;
262 spinlock_init(&fl->lock);
265 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
267 struct flow_entry *n = flow_entry_xalloc();
269 n->ct = nfct_clone(ct);
271 flow_entry_from_ct(n, ct);
272 flow_entry_get_extended(n);
274 rcu_assign_pointer(n->next, fl->head);
275 rcu_assign_pointer(fl->head, n);
278 static struct flow_entry *flow_list_find_id(struct flow_list *fl,
279 uint32_t id)
281 struct flow_entry *n = rcu_dereference(fl->head);
283 while (n != NULL) {
284 if (n->flow_id == id)
285 return n;
287 n = rcu_dereference(n->next);
290 return NULL;
293 static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
294 uint32_t id)
296 struct flow_entry *prev = rcu_dereference(fl->head), *next;
298 if (prev->flow_id == id)
299 return NULL;
301 while ((next = rcu_dereference(prev->next)) != NULL) {
302 if (next->flow_id == id)
303 return prev;
305 prev = next;
308 return NULL;
311 static void flow_list_update_entry(struct flow_list *fl,
312 struct nf_conntrack *ct)
314 struct flow_entry *n;
316 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
317 if (n == NULL) {
318 flow_list_new_entry(fl, ct);
319 return;
322 flow_entry_from_ct(n, ct);
325 static void flow_list_destroy_entry(struct flow_list *fl,
326 struct nf_conntrack *ct)
328 struct flow_entry *n1, *n2;
329 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
331 n1 = flow_list_find_id(fl, id);
332 if (n1) {
333 n2 = flow_list_find_prev_id(fl, id);
334 if (n2) {
335 rcu_assign_pointer(n2->next, n1->next);
336 n1->next = NULL;
338 flow_entry_xfree(n1);
339 } else {
340 struct flow_entry *next = fl->head->next;
342 flow_entry_xfree(fl->head);
343 fl->head = next;
348 static void flow_list_destroy(struct flow_list *fl)
350 struct flow_entry *n;
352 while (fl->head != NULL) {
353 n = rcu_dereference(fl->head->next);
354 fl->head->next = NULL;
356 flow_entry_xfree(fl->head);
357 rcu_assign_pointer(fl->head, n);
360 synchronize_rcu();
361 spinlock_destroy(&fl->lock);
364 static int walk_process(unsigned int pid, struct flow_entry *n)
366 int ret;
367 DIR *dir;
368 struct dirent *ent;
369 char path[1024];
371 if (snprintf(path, sizeof(path), "/proc/%u/fd", pid) == -1)
372 panic("giant process name! %u\n", pid);
374 dir = opendir(path);
375 if (!dir)
376 return 0;
378 while ((ent = readdir(dir))) {
379 struct stat statbuf;
381 if (snprintf(path, sizeof(path), "/proc/%u/fd/%s",
382 pid, ent->d_name) < 0)
383 continue;
385 if (stat(path, &statbuf) < 0)
386 continue;
388 if (S_ISSOCK(statbuf.st_mode) && (ino_t) n->inode == statbuf.st_ino) {
389 ret = proc_get_cmdline(pid, n->cmdline, sizeof(n->cmdline));
390 if (ret < 0)
391 panic("Failed to get process cmdline: %s\n", strerror(errno));
393 n->procnum = pid;
394 closedir(dir);
395 return 1;
399 closedir(dir);
400 return 0;
403 static void walk_processes(struct flow_entry *n)
405 int ret;
406 DIR *dir;
407 struct dirent *ent;
409 /* n->inode must be set */
410 if (n->inode <= 0) {
411 n->cmdline[0] = '\0';
412 return;
415 dir = opendir("/proc");
416 if (!dir)
417 panic("Cannot open /proc: %s\n", strerror(errno));
419 while ((ent = readdir(dir))) {
420 const char *name = ent->d_name;
421 char *end;
422 unsigned int pid = strtoul(name, &end, 10);
424 /* not a PID */
425 if (pid == 0 && end == name)
426 continue;
428 ret = walk_process(pid, n);
429 if (ret > 0)
430 break;
433 closedir(dir);
436 static int get_port_inode(uint16_t port, int proto, bool is_ip6)
438 int ret = -ENOENT;
439 char path[128], buff[1024];
440 FILE *proc;
442 memset(path, 0, sizeof(path));
443 snprintf(path, sizeof(path), "/proc/net/%s%s",
444 l4proto2str[proto], is_ip6 ? "6" : "");
446 proc = fopen(path, "r");
447 if (!proc)
448 return -EIO;
450 memset(buff, 0, sizeof(buff));
452 while (fgets(buff, sizeof(buff), proc) != NULL) {
453 int inode = 0;
454 unsigned int lport = 0;
456 buff[sizeof(buff) - 1] = 0;
457 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
458 "%*X %*u %*u %u", &lport, &inode) == 2) {
459 if ((uint16_t) lport == port) {
460 ret = inode;
461 break;
465 memset(buff, 0, sizeof(buff));
468 fclose(proc);
469 return ret;
472 #define CP_NFCT(elem, attr, x) \
473 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
474 #define CP_NFCT_BUFF(elem, attr) do { \
475 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
476 if (buff != NULL) \
477 memcpy(n->elem, buff, sizeof(n->elem)); \
478 } while (0)
480 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
482 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
483 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
485 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
486 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
488 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
489 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
491 CP_NFCT(status, ATTR_STATUS, 32);
493 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
494 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
495 CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
496 CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
498 CP_NFCT(src_pkts, ATTR_ORIG_COUNTER_PACKETS, 64);
499 CP_NFCT(src_bytes, ATTR_ORIG_COUNTER_BYTES, 64);
501 CP_NFCT(dst_pkts, ATTR_REPL_COUNTER_PACKETS, 64);
502 CP_NFCT(dst_bytes, ATTR_REPL_COUNTER_BYTES, 64);
504 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
505 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
507 CP_NFCT(flow_id, ATTR_ID, 32);
508 CP_NFCT(use, ATTR_USE, 32);
510 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
511 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
513 n->port_src = ntohs(n->port_src);
514 n->port_dst = ntohs(n->port_dst);
516 n->ip4_src_addr = ntohl(n->ip4_src_addr);
517 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
520 enum flow_entry_direction {
521 flow_entry_src,
522 flow_entry_dst,
525 static inline bool flow_entry_get_extended_is_dns(struct flow_entry *n)
527 /* We don't want to analyze / display DNS itself, since we
528 * use it to resolve reverse dns.
530 return n->port_src == 53 || n->port_dst == 53;
533 #define SELFLD(dir,src_member,dst_member) \
534 (((dir) == flow_entry_src) ? n->src_member : n->dst_member)
536 static void flow_entry_get_sain4_obj(struct flow_entry *n,
537 enum flow_entry_direction dir,
538 struct sockaddr_in *sa)
540 memset(sa, 0, sizeof(*sa));
541 sa->sin_family = PF_INET;
542 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
545 static void flow_entry_get_sain6_obj(struct flow_entry *n,
546 enum flow_entry_direction dir,
547 struct sockaddr_in6 *sa)
549 memset(sa, 0, sizeof(*sa));
550 sa->sin6_family = PF_INET6;
552 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
553 sizeof(sa->sin6_addr));
556 static void
557 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
558 enum flow_entry_direction dir)
560 struct sockaddr_in sa4;
561 struct sockaddr_in6 sa6;
562 const char *city = NULL;
564 switch (n->l3_proto) {
565 default:
566 bug();
568 case AF_INET:
569 flow_entry_get_sain4_obj(n, dir, &sa4);
570 city = geoip4_city_name(&sa4);
571 break;
573 case AF_INET6:
574 flow_entry_get_sain6_obj(n, dir, &sa6);
575 city = geoip6_city_name(&sa6);
576 break;
579 build_bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
581 if (city) {
582 memcpy(SELFLD(dir, city_src, city_dst), city,
583 min(sizeof(n->city_src), strlen(city)));
584 } else {
585 memset(SELFLD(dir, city_src, city_dst), 0,
586 sizeof(n->city_src));
590 static void
591 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
592 enum flow_entry_direction dir)
594 struct sockaddr_in sa4;
595 struct sockaddr_in6 sa6;
596 const char *country = NULL;
598 switch (n->l3_proto) {
599 default:
600 bug();
602 case AF_INET:
603 flow_entry_get_sain4_obj(n, dir, &sa4);
604 country = geoip4_country_name(&sa4);
605 break;
607 case AF_INET6:
608 flow_entry_get_sain6_obj(n, dir, &sa6);
609 country = geoip6_country_name(&sa6);
610 break;
613 build_bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
615 if (country) {
616 memcpy(SELFLD(dir, country_src, country_dst), country,
617 min(sizeof(n->country_src), strlen(country)));
618 } else {
619 memset(SELFLD(dir, country_src, country_dst), 0,
620 sizeof(n->country_src));
624 static void flow_entry_get_extended_geo(struct flow_entry *n,
625 enum flow_entry_direction dir)
627 flow_entry_geo_city_lookup_generic(n, dir);
628 flow_entry_geo_country_lookup_generic(n, dir);
631 static void flow_entry_get_extended_revdns(struct flow_entry *n,
632 enum flow_entry_direction dir)
634 size_t sa_len;
635 struct sockaddr_in sa4;
636 struct sockaddr_in6 sa6;
637 struct sockaddr *sa;
638 struct hostent *hent;
640 switch (n->l3_proto) {
641 default:
642 bug();
644 case AF_INET:
645 flow_entry_get_sain4_obj(n, dir, &sa4);
646 sa = (struct sockaddr *) &sa4;
647 sa_len = sizeof(sa4);
648 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr), AF_INET);
649 break;
651 case AF_INET6:
652 flow_entry_get_sain6_obj(n, dir, &sa6);
653 sa = (struct sockaddr *) &sa6;
654 sa_len = sizeof(sa6);
655 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr), AF_INET6);
656 break;
659 build_bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
660 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
661 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
663 if (hent) {
664 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
665 memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
666 hent->h_name, min(sizeof(n->rev_dns_src),
667 strlen(hent->h_name)));
671 static void flow_entry_get_extended(struct flow_entry *n)
673 if (n->flow_id == 0 || flow_entry_get_extended_is_dns(n))
674 return;
676 flow_entry_get_extended_revdns(n, flow_entry_src);
677 flow_entry_get_extended_geo(n, flow_entry_src);
679 flow_entry_get_extended_revdns(n, flow_entry_dst);
680 flow_entry_get_extended_geo(n, flow_entry_dst);
682 /* Lookup application */
683 n->inode = get_port_inode(n->port_src, n->l4_proto,
684 n->l3_proto == AF_INET6);
685 if (n->inode > 0)
686 walk_processes(n);
689 static uint16_t presenter_get_port(uint16_t src, uint16_t dst, bool is_tcp)
691 if (src < dst && src < 1024) {
692 return src;
693 } else if (dst < src && dst < 1024) {
694 return dst;
695 } else {
696 const char *tmp1, *tmp2;
697 if (is_tcp) {
698 tmp1 = lookup_port_tcp(src);
699 tmp2 = lookup_port_tcp(dst);
700 } else {
701 tmp1 = lookup_port_udp(src);
702 tmp2 = lookup_port_udp(dst);
704 if (tmp1 && !tmp2) {
705 return src;
706 } else if (!tmp1 && tmp2) {
707 return dst;
708 } else {
709 if (src < dst)
710 return src;
711 else
712 return dst;
717 static char *bandw2str(double bytes, char *buf, size_t len)
719 if (bytes > 1000000000.)
720 snprintf(buf, len, "%.1fG", bytes / 1000000000.);
721 else if (bytes > 1000000.)
722 snprintf(buf, len, "%.1fM", bytes / 1000000.);
723 else if (bytes > 1000.)
724 snprintf(buf, len, "%.1fK", bytes / 1000.);
725 else
726 snprintf(buf, len, "%g", bytes);
728 return buf;
731 static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
732 unsigned int *line)
734 char tmp[128], *pname = NULL;
735 uint16_t port;
737 mvwprintw(screen, *line, 2, "");
739 /* PID, application name */
740 if (n->procnum > 0) {
741 slprintf(tmp, sizeof(tmp), "%s(%d)", basename(n->cmdline),
742 n->procnum);
744 printw("[");
745 attron(COLOR_PAIR(3));
746 printw("%s", tmp);
747 attroff(COLOR_PAIR(3));
748 printw("]:");
751 /* L3 protocol, L4 protocol, states */
752 printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
753 printw("[");
754 attron(COLOR_PAIR(3));
755 switch (n->l4_proto) {
756 case IPPROTO_TCP:
757 printw("%s", tcp_state2str[n->tcp_state]);
758 break;
759 case IPPROTO_SCTP:
760 printw("%s", sctp_state2str[n->sctp_state]);
761 break;
762 case IPPROTO_DCCP:
763 printw("%s", dccp_state2str[n->dccp_state]);
764 break;
765 case IPPROTO_UDP:
766 case IPPROTO_UDPLITE:
767 case IPPROTO_ICMP:
768 case IPPROTO_ICMPV6:
769 printw("NOSTATE");
770 break;
772 attroff(COLOR_PAIR(3));
773 printw("]");
775 /* Guess application port */
776 switch (n->l4_proto) {
777 case IPPROTO_TCP:
778 port = presenter_get_port(n->port_src, n->port_dst, true);
779 pname = lookup_port_tcp(port);
780 break;
781 case IPPROTO_UDP:
782 case IPPROTO_UDPLITE:
783 port = presenter_get_port(n->port_src, n->port_dst, false);
784 pname = lookup_port_udp(port);
785 break;
787 if (pname) {
788 attron(A_BOLD);
789 printw(":%s", pname);
790 attroff(A_BOLD);
793 /* Show source information: reverse DNS, port, country, city, counters */
794 if (show_src) {
795 attron(COLOR_PAIR(1));
796 mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
797 attroff(COLOR_PAIR(1));
799 printw(":%"PRIu16, n->port_src);
801 if (n->country_src[0]) {
802 printw(" (");
804 attron(COLOR_PAIR(4));
805 printw("%s", n->country_src);
806 attroff(COLOR_PAIR(4));
808 if (n->city_src[0])
809 printw(", %s", n->city_src);
811 printw(")");
814 if (n->src_pkts > 0 && n->src_bytes > 0) {
815 char bytes_str[64];
817 printw(" -> (%"PRIu64" pkts, %s bytes)", n->src_pkts,
818 bandw2str(n->src_bytes, bytes_str,
819 sizeof(bytes_str) - 1));
822 printw(" => ");
825 /* Show dest information: reverse DNS, port, country, city, counters */
826 attron(COLOR_PAIR(2));
827 mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
828 attroff(COLOR_PAIR(2));
830 printw(":%"PRIu16, n->port_dst);
832 if (n->country_dst[0]) {
833 printw(" (");
835 attron(COLOR_PAIR(4));
836 printw("%s", n->country_dst);
837 attroff(COLOR_PAIR(4));
839 if (n->city_dst[0])
840 printw(", %s", n->city_dst);
842 printw(")");
845 if (n->dst_pkts > 0 && n->dst_bytes > 0) {
846 char bytes_str[64];
848 printw(" -> (%"PRIu64" pkts, %s bytes)", n->dst_pkts,
849 bandw2str(n->dst_bytes, bytes_str,
850 sizeof(bytes_str) - 1));
854 static inline bool presenter_flow_wrong_state(struct flow_entry *n)
856 switch (n->l4_proto) {
857 case IPPROTO_TCP:
858 switch (n->tcp_state) {
859 case TCP_CONNTRACK_SYN_SENT:
860 case TCP_CONNTRACK_SYN_RECV:
861 case TCP_CONNTRACK_ESTABLISHED:
862 case TCP_CONNTRACK_FIN_WAIT:
863 case TCP_CONNTRACK_CLOSE_WAIT:
864 case TCP_CONNTRACK_LAST_ACK:
865 case TCP_CONNTRACK_TIME_WAIT:
866 case TCP_CONNTRACK_CLOSE:
867 case TCP_CONNTRACK_SYN_SENT2:
868 case TCP_CONNTRACK_NONE:
869 return false;
870 break;
872 break;
873 case IPPROTO_SCTP:
874 switch (n->sctp_state) {
875 case SCTP_CONNTRACK_NONE:
876 case SCTP_CONNTRACK_CLOSED:
877 case SCTP_CONNTRACK_COOKIE_WAIT:
878 case SCTP_CONNTRACK_COOKIE_ECHOED:
879 case SCTP_CONNTRACK_ESTABLISHED:
880 case SCTP_CONNTRACK_SHUTDOWN_SENT:
881 case SCTP_CONNTRACK_SHUTDOWN_RECD:
882 case SCTP_CONNTRACK_SHUTDOWN_ACK_SENT:
883 return false;
884 break;
886 break;
887 case IPPROTO_DCCP:
888 switch (n->dccp_state) {
889 case DCCP_CONNTRACK_NONE:
890 case DCCP_CONNTRACK_REQUEST:
891 case DCCP_CONNTRACK_RESPOND:
892 case DCCP_CONNTRACK_PARTOPEN:
893 case DCCP_CONNTRACK_OPEN:
894 case DCCP_CONNTRACK_CLOSEREQ:
895 case DCCP_CONNTRACK_CLOSING:
896 case DCCP_CONNTRACK_TIMEWAIT:
897 case DCCP_CONNTRACK_IGNORE:
898 case DCCP_CONNTRACK_INVALID:
899 return false;
900 break;
902 break;
903 case IPPROTO_UDP:
904 case IPPROTO_UDPLITE:
905 case IPPROTO_ICMP:
906 case IPPROTO_ICMPV6:
907 return false;
908 break;
911 return true;
914 static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
915 int skip_lines)
917 int maxy;
918 int skip_left = skip_lines;
919 unsigned int flows = 0;
920 unsigned int line = 3;
921 struct flow_entry *n;
923 curs_set(0);
925 maxy = getmaxy(screen);
926 maxy -= 6;
928 start_color();
929 init_pair(1, COLOR_RED, COLOR_BLACK);
930 init_pair(2, COLOR_BLUE, COLOR_BLACK);
931 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
932 init_pair(4, COLOR_GREEN, COLOR_BLACK);
934 wclear(screen);
935 clear();
937 rcu_read_lock();
939 n = rcu_dereference(fl->head);
940 if (!n)
941 mvwprintw(screen, line, 2, "(No active sessions! "
942 "Is netfilter running?)");
944 for (; n; n = rcu_dereference(n->next)) {
945 n->is_visible = false;
946 if (presenter_get_port(n->port_src, n->port_dst, false) == 53)
947 continue;
949 if (presenter_flow_wrong_state(n))
950 continue;
952 /* count only flows which might be showed */
953 flows++;
955 if (maxy <= 0)
956 continue;
958 if (skip_left > 0) {
959 skip_left--;
960 continue;
963 n->is_visible = true;
965 presenter_screen_do_line(screen, n, &line);
967 line++;
968 maxy -= (2 + 1 * show_src);
971 if (is_flow_collecting) {
972 mvwprintw(screen, 1, 2, "Collecting flows ...");
973 } else {
974 mvwprintw(screen, 1, 2,
975 "Kernel netfilter flows(%u) for %s%s%s%s%s%s"
976 "[+%d]", flows, what & INCLUDE_TCP ? "TCP, " : "",
977 what & INCLUDE_UDP ? "UDP, " : "",
978 what & INCLUDE_SCTP ? "SCTP, " : "",
979 what & INCLUDE_DCCP ? "DCCP, " : "",
980 what & INCLUDE_ICMP && what & INCLUDE_IPV4 ?
981 "ICMP, " : "",
982 what & INCLUDE_ICMP && what & INCLUDE_IPV6 ?
983 "ICMP6, " : "",
984 skip_lines);
987 rcu_read_unlock();
989 wrefresh(screen);
990 refresh();
993 static void presenter(void)
995 int skip_lines = 0;
996 WINDOW *screen;
998 lookup_init_ports(PORTS_TCP);
999 lookup_init_ports(PORTS_UDP);
1000 screen = screen_init(false);
1002 rcu_register_thread();
1003 while (!sigint) {
1004 switch (getch()) {
1005 case 'q':
1006 sigint = 1;
1007 break;
1008 case KEY_UP:
1009 case 'u':
1010 case 'k':
1011 skip_lines--;
1012 if (skip_lines < 0)
1013 skip_lines = 0;
1014 break;
1015 case KEY_DOWN:
1016 case 'd':
1017 case 'j':
1018 skip_lines++;
1019 if (skip_lines > SCROLL_MAX)
1020 skip_lines = SCROLL_MAX;
1021 break;
1022 default:
1023 fflush(stdin);
1024 break;
1027 presenter_screen_update(screen, &flow_list, skip_lines);
1028 usleep(200000);
1030 rcu_unregister_thread();
1032 screen_end();
1033 lookup_cleanup_ports(PORTS_UDP);
1034 lookup_cleanup_ports(PORTS_TCP);
1037 static int flow_event_cb(enum nf_conntrack_msg_type type,
1038 struct nf_conntrack *ct, void *data __maybe_unused)
1040 if (sigint)
1041 return NFCT_CB_STOP;
1043 synchronize_rcu();
1044 spinlock_lock(&flow_list.lock);
1046 switch (type) {
1047 case NFCT_T_NEW:
1048 flow_list_new_entry(&flow_list, ct);
1049 break;
1050 case NFCT_T_UPDATE:
1051 flow_list_update_entry(&flow_list, ct);
1052 break;
1053 case NFCT_T_DESTROY:
1054 flow_list_destroy_entry(&flow_list, ct);
1055 break;
1056 default:
1057 break;
1060 spinlock_unlock(&flow_list.lock);
1062 return NFCT_CB_CONTINUE;
1065 static void restore_sysctl(void *value)
1067 int int_val = *(int *)value;
1069 if (int_val == 0)
1070 sysctl_set_int("net/netfilter/nf_conntrack_acct", int_val);
1073 static void on_panic_handler(void *arg)
1075 restore_sysctl(arg);
1076 screen_end();
1079 static void conntrack_acct_enable(void)
1081 /* We can still work w/o traffic accounting so just warn about error */
1082 if (sysctl_get_int("net/netfilter/nf_conntrack_acct", &nfct_acct_val)) {
1083 fprintf(stderr, "Can't read net/netfilter/nf_conntrack_acct: %s\n",
1084 strerror(errno));
1087 if (nfct_acct_val == 1)
1088 return;
1090 if (sysctl_set_int("net/netfilter/nf_conntrack_acct", 1)) {
1091 fprintf(stderr, "Can't write net/netfilter/nf_conntrack_acct: %s\n",
1092 strerror(errno));
1096 static int flow_update_cb(enum nf_conntrack_msg_type type,
1097 struct nf_conntrack *ct, void *data __maybe_unused)
1099 struct flow_entry *n;
1101 if (type != NFCT_T_UPDATE)
1102 return NFCT_CB_CONTINUE;
1104 if (sigint)
1105 return NFCT_CB_STOP;
1107 n = flow_list_find_id(&flow_list, nfct_get_attr_u32(ct, ATTR_ID));
1108 if (!n)
1109 return NFCT_CB_CONTINUE;
1111 flow_entry_from_ct(n, ct);
1113 return NFCT_CB_CONTINUE;
1116 static void collector_refresh_flows(struct nfct_handle *handle)
1118 struct flow_entry *n;
1120 n = rcu_dereference(flow_list.head);
1121 for (; n; n = rcu_dereference(n->next)) {
1122 if (!n->is_visible)
1123 continue;
1125 nfct_query(handle, NFCT_Q_GET, n->ct);
1129 static void collector_create_filter(struct nfct_handle *nfct)
1131 struct nfct_filter *filter;
1132 int ret;
1134 filter = nfct_filter_create();
1135 if (!filter)
1136 panic("Cannot create a nfct filter: %s\n", strerror(errno));
1138 if (what & INCLUDE_UDP) {
1139 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1140 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
1142 if (what & INCLUDE_TCP)
1143 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1144 if (what & INCLUDE_DCCP)
1145 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1146 if (what & INCLUDE_SCTP)
1147 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1148 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1149 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1150 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1151 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1152 if (what & INCLUDE_IPV4) {
1153 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4, NFCT_FILTER_LOGIC_NEGATIVE);
1154 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1156 if (what & INCLUDE_IPV6) {
1157 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6, NFCT_FILTER_LOGIC_NEGATIVE);
1158 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1161 ret = nfct_filter_attach(nfct_fd(nfct), filter);
1162 if (ret < 0)
1163 panic("Cannot attach filter to handle: %s\n", strerror(errno));
1165 nfct_filter_destroy(filter);
1168 /* This hand-crafted filter looks ugly but it allows to do not
1169 * flush nfct connections & filter them by user specified filter.
1170 * May be it is better to replace this one by nfct_cmp. */
1171 static int flow_dump_cb(enum nf_conntrack_msg_type type,
1172 struct nf_conntrack *ct, void *data __maybe_unused)
1174 struct flow_entry fl;
1175 struct flow_entry *n = &fl;
1177 if (sigint)
1178 return NFCT_CB_STOP;
1180 synchronize_rcu();
1181 spinlock_lock(&flow_list.lock);
1183 if (!(what & ~(INCLUDE_IPV4 | INCLUDE_IPV6)))
1184 goto check_addr;
1186 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
1188 if (what & INCLUDE_UDP) {
1189 if (n->l4_proto == IPPROTO_UDP)
1190 goto check_addr;
1192 if (n->l4_proto == IPPROTO_UDPLITE)
1193 goto check_addr;
1196 if ((what & INCLUDE_TCP) && n->l4_proto == IPPROTO_TCP)
1197 goto check_addr;
1199 if ((what & INCLUDE_DCCP) && n->l4_proto == IPPROTO_DCCP)
1200 goto check_addr;
1202 if ((what & INCLUDE_SCTP) && n->l4_proto == IPPROTO_SCTP)
1203 goto check_addr;
1205 if ((what & INCLUDE_ICMP) && (what & INCLUDE_IPV4) &&
1206 n->l4_proto == IPPROTO_ICMP) {
1207 goto check_addr;
1210 if ((what & INCLUDE_ICMP) && (what & INCLUDE_IPV6) &&
1211 n->l4_proto == IPPROTO_ICMPV6) {
1212 goto check_addr;
1215 goto skip_flow;
1217 check_addr:
1218 /* filter loopback addresses */
1219 if (what & INCLUDE_IPV4) {
1220 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
1222 if (n->ip4_src_addr == filter_ipv4.addr)
1223 goto skip_flow;
1225 if (what & INCLUDE_IPV6) {
1226 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
1228 if (n->ip6_src_addr[0] == 0x0 &&
1229 n->ip6_src_addr[1] == 0x0 &&
1230 n->ip6_src_addr[2] == 0x0 &&
1231 n->ip6_src_addr[3] == 0x1)
1232 goto skip_flow;
1235 flow_list_new_entry(&flow_list, ct);
1237 skip_flow:
1238 spinlock_unlock(&flow_list.lock);
1239 return NFCT_CB_CONTINUE;
1242 static void collector_dump_flows(void)
1244 struct nfct_handle *nfct = nfct_open(CONNTRACK, 0);
1246 if (!nfct)
1247 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1249 nfct_callback_register(nfct, NFCT_T_ALL, flow_dump_cb, NULL);
1251 is_flow_collecting = true;
1252 if (what & INCLUDE_IPV4) {
1253 int family = AF_INET;
1254 nfct_query(nfct, NFCT_Q_DUMP, &family);
1256 if (what & INCLUDE_IPV6) {
1257 int family = AF_INET6;
1258 nfct_query(nfct, NFCT_Q_DUMP, &family);
1260 is_flow_collecting = false;
1262 nfct_close(nfct);
1265 static void *collector(void *null __maybe_unused)
1267 struct nfct_handle *ct_update;
1268 struct nfct_handle *ct_event;
1269 struct pollfd poll_fd[1];
1271 flow_list_init(&flow_list);
1273 ct_event = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1274 NF_NETLINK_CONNTRACK_UPDATE |
1275 NF_NETLINK_CONNTRACK_DESTROY);
1276 if (!ct_event)
1277 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1279 collector_create_filter(ct_event);
1281 nfct_callback_register(ct_event, NFCT_T_ALL, flow_event_cb, NULL);
1283 ct_update = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_UPDATE);
1284 if (!ct_update)
1285 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1287 nfct_callback_register(ct_update, NFCT_T_ALL, flow_update_cb, NULL);
1289 poll_fd[0].fd = nfct_fd(ct_event);
1290 poll_fd[0].events = POLLIN;
1292 if (fcntl(nfct_fd(ct_event), F_SETFL, O_NONBLOCK) == -1)
1293 panic("Cannot set non-blocking socket: fcntl(): %s\n",
1294 strerror(errno));
1296 if (fcntl(nfct_fd(ct_update), F_SETFL, O_NONBLOCK) == -1)
1297 panic("Cannot set non-blocking socket: fcntl(): %s\n",
1298 strerror(errno));
1300 rcu_register_thread();
1302 collector_dump_flows();
1304 while (!sigint) {
1305 int status;
1307 usleep(300000);
1309 collector_refresh_flows(ct_update);
1311 status = poll(poll_fd, 1, 0);
1312 if (status < 0) {
1313 if (errno == EAGAIN || errno == EINTR)
1314 continue;
1316 panic("Error while polling: %s\n", strerror(errno));
1317 } else if (status == 0) {
1318 continue;
1321 if (poll_fd[0].revents & POLLIN)
1322 nfct_catch(ct_event);
1325 rcu_unregister_thread();
1327 flow_list_destroy(&flow_list);
1328 nfct_close(ct_event);
1329 nfct_close(ct_update);
1331 pthread_exit(NULL);
1334 int main(int argc, char **argv)
1336 pthread_t tid;
1337 int ret, c, opt_index, what_cmd = 0;
1339 setfsuid(getuid());
1340 setfsgid(getgid());
1342 while ((c = getopt_long(argc, argv, short_options, long_options,
1343 &opt_index)) != EOF) {
1344 switch (c) {
1345 case '4':
1346 what_cmd |= INCLUDE_IPV4;
1347 break;
1348 case '6':
1349 what_cmd |= INCLUDE_IPV6;
1350 break;
1351 case 'T':
1352 what_cmd |= INCLUDE_TCP;
1353 break;
1354 case 'U':
1355 what_cmd |= INCLUDE_UDP;
1356 break;
1357 case 'D':
1358 what_cmd |= INCLUDE_DCCP;
1359 break;
1360 case 'I':
1361 what_cmd |= INCLUDE_ICMP;
1362 break;
1363 case 'S':
1364 what_cmd |= INCLUDE_SCTP;
1365 break;
1366 case 's':
1367 show_src = 1;
1368 break;
1369 case 'u':
1370 update_geoip();
1371 die();
1372 break;
1373 case 'h':
1374 help();
1375 break;
1376 case 'v':
1377 version();
1378 break;
1379 default:
1380 break;
1384 if (what_cmd > 0) {
1385 what = what_cmd;
1387 if (!(what & (INCLUDE_IPV4 | INCLUDE_IPV6)))
1388 what |= INCLUDE_IPV4 | INCLUDE_IPV6;
1391 rcu_init();
1393 register_signal(SIGINT, signal_handler);
1394 register_signal(SIGQUIT, signal_handler);
1395 register_signal(SIGTERM, signal_handler);
1396 register_signal(SIGHUP, signal_handler);
1398 panic_handler_add(on_panic_handler, &nfct_acct_val);
1400 conntrack_acct_enable();
1402 init_geoip(1);
1404 ret = pthread_create(&tid, NULL, collector, NULL);
1405 if (ret < 0)
1406 panic("Cannot create phthread!\n");
1408 presenter();
1410 destroy_geoip();
1412 restore_sysctl(&nfct_acct_val);
1414 return 0;