flowtop: Change tcp param to 'bool is_tcp' in presenter_get_port(..)
[netsniff-ng.git] / flowtop.c
blob314be80ce9af1fa9366f11b670e86b1b9157e796
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 counter_pkts, counter_bytes;
52 uint64_t timestamp_start, timestamp_stop;
53 char country_src[128], country_dst[128];
54 char city_src[128], city_dst[128];
55 char rev_dns_src[256], rev_dns_dst[256];
56 char cmdline[256];
57 struct flow_entry *next;
58 int inode;
59 unsigned int procnum;
60 bool is_visible;
61 struct nf_conntrack *ct;
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 static volatile sig_atomic_t sigint = 0;
87 static int what = INCLUDE_IPV4 | INCLUDE_IPV6 | INCLUDE_TCP, show_src = 0;
88 static struct flow_list flow_list;
89 static int nfct_acct_val = -1;
91 static const char *short_options = "vhTUsDIS46u";
92 static const struct option long_options[] = {
93 {"ipv4", no_argument, NULL, '4'},
94 {"ipv6", no_argument, NULL, '6'},
95 {"tcp", no_argument, NULL, 'T'},
96 {"udp", no_argument, NULL, 'U'},
97 {"dccp", no_argument, NULL, 'D'},
98 {"icmp", no_argument, NULL, 'I'},
99 {"sctp", no_argument, NULL, 'S'},
100 {"show-src", no_argument, NULL, 's'},
101 {"update", no_argument, NULL, 'u'},
102 {"version", no_argument, NULL, 'v'},
103 {"help", no_argument, NULL, 'h'},
104 {NULL, 0, NULL, 0}
107 static const char *copyright = "Please report bugs to <bugs@netsniff-ng.org>\n"
108 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
109 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
110 "Swiss federal institute of technology (ETH Zurich)\n"
111 "License: GNU GPL version 2.0\n"
112 "This is free software: you are free to change and redistribute it.\n"
113 "There is NO WARRANTY, to the extent permitted by law.";
115 static const char *const l3proto2str[AF_MAX] = {
116 [AF_INET] = "ipv4",
117 [AF_INET6] = "ipv6",
120 static const char *const l4proto2str[IPPROTO_MAX] = {
121 [IPPROTO_TCP] = "tcp",
122 [IPPROTO_UDP] = "udp",
123 [IPPROTO_UDPLITE] = "udplite",
124 [IPPROTO_ICMP] = "icmp",
125 [IPPROTO_ICMPV6] = "icmpv6",
126 [IPPROTO_SCTP] = "sctp",
127 [IPPROTO_GRE] = "gre",
128 [IPPROTO_DCCP] = "dccp",
129 [IPPROTO_IGMP] = "igmp",
130 [IPPROTO_IPIP] = "ipip",
131 [IPPROTO_EGP] = "egp",
132 [IPPROTO_PUP] = "pup",
133 [IPPROTO_IDP] = "idp",
134 [IPPROTO_RSVP] = "rsvp",
135 [IPPROTO_IPV6] = "ip6tun",
136 [IPPROTO_ESP] = "esp",
137 [IPPROTO_AH] = "ah",
138 [IPPROTO_PIM] = "pim",
139 [IPPROTO_COMP] = "comp",
142 static const char *const tcp_state2str[TCP_CONNTRACK_MAX] = {
143 [TCP_CONNTRACK_NONE] = "NOSTATE",
144 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
145 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
146 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
147 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
148 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
149 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
150 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
151 [TCP_CONNTRACK_CLOSE] = "CLOSE",
152 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
155 static const char *const dccp_state2str[DCCP_CONNTRACK_MAX] = {
156 [DCCP_CONNTRACK_NONE] = "NOSTATE",
157 [DCCP_CONNTRACK_REQUEST] = "REQUEST",
158 [DCCP_CONNTRACK_RESPOND] = "RESPOND",
159 [DCCP_CONNTRACK_PARTOPEN] = "PARTOPEN",
160 [DCCP_CONNTRACK_OPEN] = "OPEN",
161 [DCCP_CONNTRACK_CLOSEREQ] = "CLOSEREQ",
162 [DCCP_CONNTRACK_CLOSING] = "CLOSING",
163 [DCCP_CONNTRACK_TIMEWAIT] = "TIMEWAIT",
164 [DCCP_CONNTRACK_IGNORE] = "IGNORE",
165 [DCCP_CONNTRACK_INVALID] = "INVALID",
168 static const char *const sctp_state2str[SCTP_CONNTRACK_MAX] = {
169 [SCTP_CONNTRACK_NONE] = "NOSTATE",
170 [SCTP_CONNTRACK_CLOSED] = "CLOSED",
171 [SCTP_CONNTRACK_COOKIE_WAIT] = "COOKIE_WAIT",
172 [SCTP_CONNTRACK_COOKIE_ECHOED] = "COOKIE_ECHOED",
173 [SCTP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
174 [SCTP_CONNTRACK_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
175 [SCTP_CONNTRACK_SHUTDOWN_RECD] = "SHUTDOWN_RECD",
176 [SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = "SHUTDOWN_ACK_SENT",
179 static const struct nfct_filter_ipv4 filter_ipv4 = {
180 .addr = __constant_htonl(INADDR_LOOPBACK),
181 .mask = 0xffffffff,
184 static const struct nfct_filter_ipv6 filter_ipv6 = {
185 .addr = { 0x0, 0x0, 0x0, 0x1 },
186 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
189 static void signal_handler(int number)
191 switch (number) {
192 case SIGINT:
193 case SIGQUIT:
194 case SIGTERM:
195 sigint = 1;
196 break;
197 case SIGHUP:
198 default:
199 break;
203 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct);
204 static void flow_entry_get_extended(struct flow_entry *n);
206 static void help(void)
208 printf("flowtop %s, top-like netfilter TCP/UDP/SCTP/.. flow tracking\n",
209 VERSION_STRING);
210 puts("http://www.netsniff-ng.org\n\n"
211 "Usage: flowtop [options]\n"
212 "Options:\n"
213 " -4|--ipv4 Show only IPv4 flows (default)\n"
214 " -6|--ipv6 Show only IPv6 flows (default)\n"
215 " -T|--tcp Show only TCP flows (default)\n"
216 " -U|--udp Show only UDP flows\n"
217 " -D|--dccp Show only DCCP flows\n"
218 " -I|--icmp Show only ICMP/ICMPv6 flows\n"
219 " -S|--sctp Show only SCTP flows\n"
220 " -s|--show-src Also show source, not only dest\n"
221 " -u|--update Update GeoIP databases\n"
222 " -v|--version Print version and exit\n"
223 " -h|--help Print this help and exit\n\n"
224 "Examples:\n"
225 " flowtop\n"
226 " flowtop -46UTDISs\n\n"
227 "Note:\n"
228 " If netfilter is not running, you can activate it with e.g.:\n"
229 " iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
230 " iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n");
231 puts(copyright);
232 die();
235 static void version(void)
237 printf("flowtop %s, Git id: %s\n", VERSION_LONG, GITVERSION);
238 puts("top-like netfilter TCP/UDP/SCTP/.. flow tracking\n"
239 "http://www.netsniff-ng.org\n");
240 puts(copyright);
241 die();
244 static inline struct flow_entry *flow_entry_xalloc(void)
246 return xzmalloc(sizeof(struct flow_entry));
249 static inline void flow_entry_xfree(struct flow_entry *n)
251 if (n->ct)
252 nfct_destroy(n->ct);
254 xfree(n);
257 static inline void flow_list_init(struct flow_list *fl)
259 fl->head = NULL;
260 spinlock_init(&fl->lock);
263 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
265 struct flow_entry *n = flow_entry_xalloc();
267 n->ct = nfct_clone(ct);
269 flow_entry_from_ct(n, ct);
270 flow_entry_get_extended(n);
272 rcu_assign_pointer(n->next, fl->head);
273 rcu_assign_pointer(fl->head, n);
276 static struct flow_entry *flow_list_find_id(struct flow_list *fl,
277 uint32_t id)
279 struct flow_entry *n = rcu_dereference(fl->head);
281 while (n != NULL) {
282 if (n->flow_id == id)
283 return n;
285 n = rcu_dereference(n->next);
288 return NULL;
291 static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
292 uint32_t id)
294 struct flow_entry *n = rcu_dereference(fl->head), *tmp;
296 if (n->flow_id == id)
297 return NULL;
299 while ((tmp = rcu_dereference(n->next)) != NULL) {
300 if (tmp->flow_id == id)
301 return n;
303 n = tmp;
306 return NULL;
309 static void flow_list_update_entry(struct flow_list *fl,
310 struct nf_conntrack *ct)
312 struct flow_entry *n;
314 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
315 if (n == NULL) {
316 flow_list_new_entry(fl, ct);
317 return;
320 flow_entry_from_ct(n, ct);
323 static void flow_list_destroy_entry(struct flow_list *fl,
324 struct nf_conntrack *ct)
326 struct flow_entry *n1, *n2;
327 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
329 n1 = flow_list_find_id(fl, id);
330 if (n1) {
331 n2 = flow_list_find_prev_id(fl, id);
332 if (n2) {
333 rcu_assign_pointer(n2->next, n1->next);
334 n1->next = NULL;
336 flow_entry_xfree(n1);
337 } else {
338 struct flow_entry *next = fl->head->next;
340 flow_entry_xfree(fl->head);
341 fl->head = next;
346 static void flow_list_destroy(struct flow_list *fl)
348 struct flow_entry *n;
350 while (fl->head != NULL) {
351 n = rcu_dereference(fl->head->next);
352 fl->head->next = NULL;
354 flow_entry_xfree(fl->head);
355 rcu_assign_pointer(fl->head, n);
358 synchronize_rcu();
359 spinlock_destroy(&fl->lock);
362 static int walk_process(unsigned int pid, struct flow_entry *n)
364 int ret;
365 DIR *dir;
366 struct dirent *ent;
367 char path[1024];
369 if (snprintf(path, sizeof(path), "/proc/%u/fd", pid) == -1)
370 panic("giant process name! %u\n", pid);
372 dir = opendir(path);
373 if (!dir)
374 return 0;
376 while ((ent = readdir(dir))) {
377 struct stat statbuf;
379 if (snprintf(path, sizeof(path), "/proc/%u/fd/%s",
380 pid, ent->d_name) < 0)
381 continue;
383 if (stat(path, &statbuf) < 0)
384 continue;
386 if (S_ISSOCK(statbuf.st_mode) && (ino_t) n->inode == statbuf.st_ino) {
387 ret = proc_get_cmdline(pid, n->cmdline, sizeof(n->cmdline));
388 if (ret < 0)
389 panic("Failed to get process cmdline: %s\n", strerror(errno));
391 n->procnum = pid;
392 closedir(dir);
393 return 1;
397 closedir(dir);
398 return 0;
401 static void walk_processes(struct flow_entry *n)
403 int ret;
404 DIR *dir;
405 struct dirent *ent;
407 /* n->inode must be set */
408 if (n->inode <= 0) {
409 n->cmdline[0] = '\0';
410 return;
413 dir = opendir("/proc");
414 if (!dir)
415 panic("Cannot open /proc: %s\n", strerror(errno));
417 while ((ent = readdir(dir))) {
418 const char *name = ent->d_name;
419 char *end;
420 unsigned int pid = strtoul(name, &end, 10);
422 /* not a PID */
423 if (pid == 0 && end == name)
424 continue;
426 ret = walk_process(pid, n);
427 if (ret > 0)
428 break;
431 closedir(dir);
434 static int get_port_inode(uint16_t port, int proto, bool is_ip6)
436 int ret = -ENOENT;
437 char path[128], buff[1024];
438 FILE *proc;
440 memset(path, 0, sizeof(path));
441 snprintf(path, sizeof(path), "/proc/net/%s%s",
442 l4proto2str[proto], is_ip6 ? "6" : "");
444 proc = fopen(path, "r");
445 if (!proc)
446 return -EIO;
448 memset(buff, 0, sizeof(buff));
450 while (fgets(buff, sizeof(buff), proc) != NULL) {
451 int inode = 0;
452 unsigned int lport = 0;
454 buff[sizeof(buff) - 1] = 0;
455 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
456 "%*X %*u %*u %u", &lport, &inode) == 2) {
457 if ((uint16_t) lport == port) {
458 ret = inode;
459 break;
463 memset(buff, 0, sizeof(buff));
466 fclose(proc);
467 return ret;
470 #define CP_NFCT(elem, attr, x) \
471 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
472 #define CP_NFCT_BUFF(elem, attr) do { \
473 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
474 if (buff != NULL) \
475 memcpy(n->elem, buff, sizeof(n->elem)); \
476 } while (0)
478 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
480 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
481 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
483 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
484 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
486 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
487 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
489 CP_NFCT(status, ATTR_STATUS, 32);
491 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
492 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
493 CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
494 CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
496 CP_NFCT(counter_pkts, ATTR_ORIG_COUNTER_PACKETS, 64);
497 CP_NFCT(counter_bytes, ATTR_ORIG_COUNTER_BYTES, 64);
499 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
500 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
502 CP_NFCT(flow_id, ATTR_ID, 32);
503 CP_NFCT(use, ATTR_USE, 32);
505 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
506 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
508 n->port_src = ntohs(n->port_src);
509 n->port_dst = ntohs(n->port_dst);
511 n->ip4_src_addr = ntohl(n->ip4_src_addr);
512 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
515 enum flow_entry_direction {
516 flow_entry_src,
517 flow_entry_dst,
520 static inline bool flow_entry_get_extended_is_dns(struct flow_entry *n)
522 /* We don't want to analyze / display DNS itself, since we
523 * use it to resolve reverse dns.
525 return n->port_src == 53 || n->port_dst == 53;
528 #define SELFLD(dir,src_member,dst_member) \
529 (((dir) == flow_entry_src) ? n->src_member : n->dst_member)
531 static void flow_entry_get_sain4_obj(struct flow_entry *n,
532 enum flow_entry_direction dir,
533 struct sockaddr_in *sa)
535 memset(sa, 0, sizeof(*sa));
536 sa->sin_family = PF_INET;
537 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
540 static void flow_entry_get_sain6_obj(struct flow_entry *n,
541 enum flow_entry_direction dir,
542 struct sockaddr_in6 *sa)
544 memset(sa, 0, sizeof(*sa));
545 sa->sin6_family = PF_INET6;
547 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
548 sizeof(sa->sin6_addr));
551 static void
552 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
553 enum flow_entry_direction dir)
555 struct sockaddr_in sa4;
556 struct sockaddr_in6 sa6;
557 const char *city = NULL;
559 switch (n->l3_proto) {
560 default:
561 bug();
563 case AF_INET:
564 flow_entry_get_sain4_obj(n, dir, &sa4);
565 city = geoip4_city_name(&sa4);
566 break;
568 case AF_INET6:
569 flow_entry_get_sain6_obj(n, dir, &sa6);
570 city = geoip6_city_name(&sa6);
571 break;
574 bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
576 if (city) {
577 memcpy(SELFLD(dir, city_src, city_dst), city,
578 min(sizeof(n->city_src), strlen(city)));
579 } else {
580 memset(SELFLD(dir, city_src, city_dst), 0,
581 sizeof(n->city_src));
585 static void
586 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
587 enum flow_entry_direction dir)
589 struct sockaddr_in sa4;
590 struct sockaddr_in6 sa6;
591 const char *country = NULL;
593 switch (n->l3_proto) {
594 default:
595 bug();
597 case AF_INET:
598 flow_entry_get_sain4_obj(n, dir, &sa4);
599 country = geoip4_country_name(&sa4);
600 break;
602 case AF_INET6:
603 flow_entry_get_sain6_obj(n, dir, &sa6);
604 country = geoip6_country_name(&sa6);
605 break;
608 bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
610 if (country) {
611 memcpy(SELFLD(dir, country_src, country_dst), country,
612 min(sizeof(n->country_src), strlen(country)));
613 } else {
614 memset(SELFLD(dir, country_src, country_dst), 0,
615 sizeof(n->country_src));
619 static void flow_entry_get_extended_geo(struct flow_entry *n,
620 enum flow_entry_direction dir)
622 flow_entry_geo_city_lookup_generic(n, dir);
623 flow_entry_geo_country_lookup_generic(n, dir);
626 static void flow_entry_get_extended_revdns(struct flow_entry *n,
627 enum flow_entry_direction dir)
629 size_t sa_len;
630 struct sockaddr_in sa4;
631 struct sockaddr_in6 sa6;
632 struct sockaddr *sa;
633 struct hostent *hent;
635 switch (n->l3_proto) {
636 default:
637 bug();
639 case AF_INET:
640 flow_entry_get_sain4_obj(n, dir, &sa4);
641 sa = (struct sockaddr *) &sa4;
642 sa_len = sizeof(sa4);
643 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr), AF_INET);
644 break;
646 case AF_INET6:
647 flow_entry_get_sain6_obj(n, dir, &sa6);
648 sa = (struct sockaddr *) &sa6;
649 sa_len = sizeof(sa6);
650 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr), AF_INET6);
651 break;
654 bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
655 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
656 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
658 if (hent) {
659 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
660 memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
661 hent->h_name, min(sizeof(n->rev_dns_src),
662 strlen(hent->h_name)));
666 static void flow_entry_get_extended(struct flow_entry *n)
668 if (n->flow_id == 0 || flow_entry_get_extended_is_dns(n))
669 return;
671 flow_entry_get_extended_revdns(n, flow_entry_src);
672 flow_entry_get_extended_geo(n, flow_entry_src);
674 flow_entry_get_extended_revdns(n, flow_entry_dst);
675 flow_entry_get_extended_geo(n, flow_entry_dst);
677 /* Lookup application */
678 n->inode = get_port_inode(n->port_src, n->l4_proto,
679 n->l3_proto == AF_INET6);
680 if (n->inode > 0)
681 walk_processes(n);
684 static uint16_t presenter_get_port(uint16_t src, uint16_t dst, bool is_tcp)
686 if (src < dst && src < 1024) {
687 return src;
688 } else if (dst < src && dst < 1024) {
689 return dst;
690 } else {
691 const char *tmp1, *tmp2;
692 if (is_tcp) {
693 tmp1 = lookup_port_tcp(src);
694 tmp2 = lookup_port_tcp(dst);
695 } else {
696 tmp1 = lookup_port_udp(src);
697 tmp2 = lookup_port_udp(dst);
699 if (tmp1 && !tmp2) {
700 return src;
701 } else if (!tmp1 && tmp2) {
702 return dst;
703 } else {
704 if (src < dst)
705 return src;
706 else
707 return dst;
712 static char *bandw2str(double bytes, char *buf, size_t len)
714 if (bytes > 1000000000.)
715 snprintf(buf, len, "%.1fG", bytes / 1000000000.);
716 if (bytes > 1000000.)
717 snprintf(buf, len, "%.1fM", bytes / 1000000.);
718 else if (bytes > 1000.)
719 snprintf(buf, len, "%.1fK", bytes / 1000.);
720 else
721 snprintf(buf, len, "%g", bytes);
723 return buf;
726 static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
727 unsigned int *line)
729 char tmp[128], *pname = NULL;
730 uint16_t port;
732 mvwprintw(screen, *line, 2, "");
734 /* PID, application name */
735 if (n->procnum > 0) {
736 slprintf(tmp, sizeof(tmp), "%s(%d)", basename(n->cmdline),
737 n->procnum);
739 printw("[");
740 attron(COLOR_PAIR(3));
741 printw("%s", tmp);
742 attroff(COLOR_PAIR(3));
743 printw("]:");
746 /* L3 protocol, L4 protocol, states */
747 printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
748 printw("[");
749 attron(COLOR_PAIR(3));
750 switch (n->l4_proto) {
751 case IPPROTO_TCP:
752 printw("%s", tcp_state2str[n->tcp_state]);
753 break;
754 case IPPROTO_SCTP:
755 printw("%s", sctp_state2str[n->sctp_state]);
756 break;
757 case IPPROTO_DCCP:
758 printw("%s", dccp_state2str[n->dccp_state]);
759 break;
760 case IPPROTO_UDP:
761 case IPPROTO_UDPLITE:
762 case IPPROTO_ICMP:
763 case IPPROTO_ICMPV6:
764 printw("NOSTATE");
765 break;
767 attroff(COLOR_PAIR(3));
768 printw("]");
770 /* Guess application port */
771 switch (n->l4_proto) {
772 case IPPROTO_TCP:
773 port = presenter_get_port(n->port_src, n->port_dst, true);
774 pname = lookup_port_tcp(port);
775 break;
776 case IPPROTO_UDP:
777 case IPPROTO_UDPLITE:
778 port = presenter_get_port(n->port_src, n->port_dst, false);
779 pname = lookup_port_udp(port);
780 break;
782 if (pname) {
783 attron(A_BOLD);
784 printw(":%s", pname);
785 attroff(A_BOLD);
787 printw(" ->");
789 /* Number packets, bytes */
790 if (n->counter_pkts > 0 && n->counter_bytes > 0) {
791 char bytes_str[64];
793 printw(" (%"PRIu64" pkts, %s bytes) ->", n->counter_pkts,
794 bandw2str(n->counter_bytes, bytes_str,
795 sizeof(bytes_str) - 1));
798 /* Show source information: reverse DNS, port, country, city */
799 if (show_src) {
800 attron(COLOR_PAIR(1));
801 mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
802 attroff(COLOR_PAIR(1));
804 printw(":%"PRIu16, n->port_src);
806 if (n->country_src[0]) {
807 printw(" (");
809 attron(COLOR_PAIR(4));
810 printw("%s", n->country_src);
811 attroff(COLOR_PAIR(4));
813 if (n->city_src[0])
814 printw(", %s", n->city_src);
816 printw(")");
819 printw(" => ");
822 /* Show dest information: reverse DNS, port, country, city */
823 attron(COLOR_PAIR(2));
824 mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
825 attroff(COLOR_PAIR(2));
827 printw(":%"PRIu16, n->port_dst);
829 if (n->country_dst[0]) {
830 printw(" (");
832 attron(COLOR_PAIR(4));
833 printw("%s", n->country_dst);
834 attroff(COLOR_PAIR(4));
836 if (n->city_dst[0])
837 printw(", %s", n->city_dst);
839 printw(")");
843 static inline bool presenter_flow_wrong_state(struct flow_entry *n)
845 switch (n->l4_proto) {
846 case IPPROTO_TCP:
847 switch (n->tcp_state) {
848 case TCP_CONNTRACK_SYN_SENT:
849 case TCP_CONNTRACK_SYN_RECV:
850 case TCP_CONNTRACK_ESTABLISHED:
851 case TCP_CONNTRACK_FIN_WAIT:
852 case TCP_CONNTRACK_CLOSE_WAIT:
853 case TCP_CONNTRACK_LAST_ACK:
854 case TCP_CONNTRACK_TIME_WAIT:
855 case TCP_CONNTRACK_CLOSE:
856 case TCP_CONNTRACK_SYN_SENT2:
857 case TCP_CONNTRACK_NONE:
858 return false;
859 break;
861 break;
862 case IPPROTO_SCTP:
863 switch (n->sctp_state) {
864 case SCTP_CONNTRACK_NONE:
865 case SCTP_CONNTRACK_CLOSED:
866 case SCTP_CONNTRACK_COOKIE_WAIT:
867 case SCTP_CONNTRACK_COOKIE_ECHOED:
868 case SCTP_CONNTRACK_ESTABLISHED:
869 case SCTP_CONNTRACK_SHUTDOWN_SENT:
870 case SCTP_CONNTRACK_SHUTDOWN_RECD:
871 case SCTP_CONNTRACK_SHUTDOWN_ACK_SENT:
872 return false;
873 break;
875 break;
876 case IPPROTO_DCCP:
877 switch (n->dccp_state) {
878 case DCCP_CONNTRACK_NONE:
879 case DCCP_CONNTRACK_REQUEST:
880 case DCCP_CONNTRACK_RESPOND:
881 case DCCP_CONNTRACK_PARTOPEN:
882 case DCCP_CONNTRACK_OPEN:
883 case DCCP_CONNTRACK_CLOSEREQ:
884 case DCCP_CONNTRACK_CLOSING:
885 case DCCP_CONNTRACK_TIMEWAIT:
886 case DCCP_CONNTRACK_IGNORE:
887 case DCCP_CONNTRACK_INVALID:
888 return false;
889 break;
891 break;
892 case IPPROTO_UDP:
893 case IPPROTO_UDPLITE:
894 case IPPROTO_ICMP:
895 case IPPROTO_ICMPV6:
896 return false;
897 break;
900 return true;
903 static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
904 int skip_lines)
906 int maxy;
907 int skip_left = skip_lines;
908 unsigned int flows = 0;
909 unsigned int line = 3;
910 struct flow_entry *n;
912 curs_set(0);
914 maxy = getmaxy(screen);
915 maxy -= 6;
917 start_color();
918 init_pair(1, COLOR_RED, COLOR_BLACK);
919 init_pair(2, COLOR_BLUE, COLOR_BLACK);
920 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
921 init_pair(4, COLOR_GREEN, COLOR_BLACK);
923 wclear(screen);
924 clear();
926 rcu_read_lock();
928 n = rcu_dereference(fl->head);
929 if (!n)
930 mvwprintw(screen, line, 2, "(No active sessions! "
931 "Is netfilter running?)");
933 for (; n; n = rcu_dereference(n->next)) {
934 n->is_visible = false;
935 if (presenter_get_port(n->port_src, n->port_dst, false) == 53)
936 continue;
938 if (presenter_flow_wrong_state(n))
939 continue;
941 /* count only flows which might be showed */
942 flows++;
944 if (maxy <= 0)
945 continue;
947 if (skip_left > 0) {
948 skip_left--;
949 continue;
952 n->is_visible = true;
954 presenter_screen_do_line(screen, n, &line);
956 line++;
957 maxy -= (2 + 1 * show_src);
960 mvwprintw(screen, 1, 2, "Kernel netfilter flows(%u) for %s%s%s%s%s%s"
961 "[+%d]", flows, what & INCLUDE_TCP ? "TCP, " : "" ,
962 what & INCLUDE_UDP ? "UDP, " : "",
963 what & INCLUDE_SCTP ? "SCTP, " : "",
964 what & INCLUDE_DCCP ? "DCCP, " : "",
965 what & INCLUDE_ICMP && what & INCLUDE_IPV4 ? "ICMP, " : "",
966 what & INCLUDE_ICMP && what & INCLUDE_IPV6 ? "ICMP6, " : "",
967 skip_lines);
969 rcu_read_unlock();
971 wrefresh(screen);
972 refresh();
975 static void presenter(void)
977 int skip_lines = 0;
978 WINDOW *screen;
980 lookup_init_ports(PORTS_TCP);
981 lookup_init_ports(PORTS_UDP);
982 screen = screen_init(false);
984 rcu_register_thread();
985 while (!sigint) {
986 switch (getch()) {
987 case 'q':
988 sigint = 1;
989 break;
990 case KEY_UP:
991 case 'u':
992 case 'k':
993 skip_lines--;
994 if (skip_lines < 0)
995 skip_lines = 0;
996 break;
997 case KEY_DOWN:
998 case 'd':
999 case 'j':
1000 skip_lines++;
1001 if (skip_lines > SCROLL_MAX)
1002 skip_lines = SCROLL_MAX;
1003 break;
1004 default:
1005 fflush(stdin);
1006 break;
1009 presenter_screen_update(screen, &flow_list, skip_lines);
1010 usleep(200000);
1012 rcu_unregister_thread();
1014 screen_end();
1015 lookup_cleanup_ports(PORTS_UDP);
1016 lookup_cleanup_ports(PORTS_TCP);
1019 static int collector_cb(enum nf_conntrack_msg_type type,
1020 struct nf_conntrack *ct, void *data __maybe_unused)
1022 if (sigint)
1023 return NFCT_CB_STOP;
1025 synchronize_rcu();
1026 spinlock_lock(&flow_list.lock);
1028 switch (type) {
1029 case NFCT_T_NEW:
1030 flow_list_new_entry(&flow_list, ct);
1031 break;
1032 case NFCT_T_UPDATE:
1033 flow_list_update_entry(&flow_list, ct);
1034 break;
1035 case NFCT_T_DESTROY:
1036 flow_list_destroy_entry(&flow_list, ct);
1037 break;
1038 default:
1039 break;
1042 spinlock_unlock(&flow_list.lock);
1044 return NFCT_CB_CONTINUE;
1047 static inline void collector_flush(struct nfct_handle *handle, uint8_t family)
1049 nfct_query(handle, NFCT_Q_FLUSH, &family);
1052 static void restore_sysctl(void *value)
1054 int int_val = *(int *)value;
1056 if (int_val == 0)
1057 sysctl_set_int("net/netfilter/nf_conntrack_acct", int_val);
1060 static void on_panic_handler(void *arg)
1062 restore_sysctl(arg);
1063 screen_end();
1066 static void conntrack_acct_enable(void)
1068 /* We can still work w/o traffic accounting so just warn about error */
1069 if (sysctl_get_int("net/netfilter/nf_conntrack_acct", &nfct_acct_val)) {
1070 fprintf(stderr, "Can't read net/netfilter/nf_conntrack_acct: %s\n",
1071 strerror(errno));
1074 if (nfct_acct_val == 1)
1075 return;
1077 if (sysctl_set_int("net/netfilter/nf_conntrack_acct", 1)) {
1078 fprintf(stderr, "Can't write net/netfilter/nf_conntrack_acct: %s\n",
1079 strerror(errno));
1083 static int dump_cb(enum nf_conntrack_msg_type type,
1084 struct nf_conntrack *ct, void *data __maybe_unused)
1086 struct flow_entry *n;
1088 if (type != NFCT_T_UPDATE)
1089 return NFCT_CB_CONTINUE;
1091 if (sigint)
1092 return NFCT_CB_STOP;
1094 n = flow_list_find_id(&flow_list, nfct_get_attr_u32(ct, ATTR_ID));
1095 if (!n)
1096 return NFCT_CB_CONTINUE;
1098 flow_entry_from_ct(n, ct);
1100 return NFCT_CB_CONTINUE;
1103 static void collector_refresh_flows(struct nfct_handle *handle)
1105 struct flow_entry *n;
1107 n = rcu_dereference(flow_list.head);
1108 for (; n; n = rcu_dereference(n->next)) {
1109 if (!n->is_visible)
1110 continue;
1112 nfct_query(handle, NFCT_Q_GET, n->ct);
1116 static void *collector(void *null __maybe_unused)
1118 struct nfct_handle *ct_event;
1119 struct nfct_handle *ct_dump;
1120 struct nfct_filter *filter;
1121 struct pollfd poll_fd[1];
1122 int ret;
1124 ct_event = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1125 NF_NETLINK_CONNTRACK_UPDATE |
1126 NF_NETLINK_CONNTRACK_DESTROY);
1127 if (!ct_event)
1128 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1130 collector_flush(ct_event, AF_INET);
1131 collector_flush(ct_event, AF_INET6);
1133 filter = nfct_filter_create();
1134 if (!filter)
1135 panic("Cannot create a nfct filter: %s\n", strerror(errno));
1137 ret = nfct_filter_attach(nfct_fd(ct_event), filter);
1138 if (ret < 0)
1139 panic("Cannot attach filter to handle: %s\n", strerror(errno));
1141 if (what & INCLUDE_UDP) {
1142 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1143 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
1145 if (what & INCLUDE_TCP)
1146 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1147 if (what & INCLUDE_DCCP)
1148 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1149 if (what & INCLUDE_SCTP)
1150 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1151 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1152 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1153 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1154 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1155 if (what & INCLUDE_IPV4) {
1156 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4, NFCT_FILTER_LOGIC_NEGATIVE);
1157 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1159 if (what & INCLUDE_IPV6) {
1160 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6, NFCT_FILTER_LOGIC_NEGATIVE);
1161 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1164 ret = nfct_filter_attach(nfct_fd(ct_event), filter);
1165 if (ret < 0)
1166 panic("Cannot attach filter to handle: %s\n", strerror(errno));
1168 nfct_filter_destroy(filter);
1170 nfct_callback_register(ct_event, NFCT_T_ALL, collector_cb, NULL);
1171 flow_list_init(&flow_list);
1173 ct_dump = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_UPDATE);
1174 if (!ct_dump)
1175 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1177 nfct_callback_register(ct_dump, NFCT_T_ALL, dump_cb, NULL);
1179 poll_fd[0].fd = nfct_fd(ct_event);
1180 poll_fd[0].events = POLLIN;
1182 if (fcntl(nfct_fd(ct_event), F_SETFL, O_NONBLOCK) == -1)
1183 panic("Cannot set non-blocking socket: fcntl(): %s\n",
1184 strerror(errno));
1186 if (fcntl(nfct_fd(ct_dump), F_SETFL, O_NONBLOCK) == -1)
1187 panic("Cannot set non-blocking socket: fcntl(): %s\n",
1188 strerror(errno));
1190 rcu_register_thread();
1192 while (!sigint && ret >= 0) {
1193 int status;
1195 usleep(300000);
1197 collector_refresh_flows(ct_dump);
1199 status = poll(poll_fd, 1, 0);
1200 if (status < 0) {
1201 if (errno == EAGAIN || errno == EINTR)
1202 continue;
1204 panic("Error while polling: %s\n", strerror(errno));
1205 } else if (status == 0) {
1206 continue;
1209 if (poll_fd[0].revents & POLLIN)
1210 nfct_catch(ct_event);
1213 rcu_unregister_thread();
1215 flow_list_destroy(&flow_list);
1216 nfct_close(ct_event);
1217 nfct_close(ct_dump);
1219 pthread_exit(NULL);
1222 int main(int argc, char **argv)
1224 pthread_t tid;
1225 int ret, c, opt_index, what_cmd = 0;
1227 setfsuid(getuid());
1228 setfsgid(getgid());
1230 while ((c = getopt_long(argc, argv, short_options, long_options,
1231 &opt_index)) != EOF) {
1232 switch (c) {
1233 case '4':
1234 what_cmd |= INCLUDE_IPV4;
1235 break;
1236 case '6':
1237 what_cmd |= INCLUDE_IPV6;
1238 break;
1239 case 'T':
1240 what_cmd |= INCLUDE_TCP;
1241 break;
1242 case 'U':
1243 what_cmd |= INCLUDE_UDP;
1244 break;
1245 case 'D':
1246 what_cmd |= INCLUDE_DCCP;
1247 break;
1248 case 'I':
1249 what_cmd |= INCLUDE_ICMP;
1250 break;
1251 case 'S':
1252 what_cmd |= INCLUDE_SCTP;
1253 break;
1254 case 's':
1255 show_src = 1;
1256 break;
1257 case 'u':
1258 update_geoip();
1259 die();
1260 break;
1261 case 'h':
1262 help();
1263 break;
1264 case 'v':
1265 version();
1266 break;
1267 default:
1268 break;
1272 if (what_cmd > 0)
1273 what = what_cmd;
1275 rcu_init();
1277 register_signal(SIGINT, signal_handler);
1278 register_signal(SIGQUIT, signal_handler);
1279 register_signal(SIGTERM, signal_handler);
1280 register_signal(SIGHUP, signal_handler);
1282 panic_handler_add(on_panic_handler, &nfct_acct_val);
1284 conntrack_acct_enable();
1286 init_geoip(1);
1288 ret = pthread_create(&tid, NULL, collector, NULL);
1289 if (ret < 0)
1290 panic("Cannot create phthread!\n");
1292 presenter();
1294 destroy_geoip();
1296 restore_sysctl(&nfct_acct_val);
1298 return 0;