netsniff-ng: proto_ipv4: Fix typo in comment
[netsniff-ng-new.git] / flowtop.c
blobd98859024e791bb74ad703342861e2e0b82bb3cc
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 pkts_src, bytes_src;
52 uint64_t pkts_dst, bytes_dst;
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 inline bool nfct_is_dns(struct nf_conntrack *ct)
267 uint16_t port_src = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_SRC);
268 uint16_t port_dst = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_DST);
270 return ntohs(port_src) == 53 || ntohs(port_dst) == 53;
273 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
275 struct flow_entry *n;
277 /* We don't want to analyze / display DNS itself, since we
278 * use it to resolve reverse dns.
280 if (nfct_is_dns(ct))
281 return;
283 n = flow_entry_xalloc();
285 n->ct = nfct_clone(ct);
287 flow_entry_from_ct(n, ct);
288 flow_entry_get_extended(n);
290 rcu_assign_pointer(n->next, fl->head);
291 rcu_assign_pointer(fl->head, n);
294 static struct flow_entry *flow_list_find_id(struct flow_list *fl,
295 uint32_t id)
297 struct flow_entry *n = rcu_dereference(fl->head);
299 while (n != NULL) {
300 if (n->flow_id == id)
301 return n;
303 n = rcu_dereference(n->next);
306 return NULL;
309 static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
310 uint32_t id)
312 struct flow_entry *prev = rcu_dereference(fl->head), *next;
314 if (prev->flow_id == id)
315 return NULL;
317 while ((next = rcu_dereference(prev->next)) != NULL) {
318 if (next->flow_id == id)
319 return prev;
321 prev = next;
324 return NULL;
327 static void flow_list_update_entry(struct flow_list *fl,
328 struct nf_conntrack *ct)
330 struct flow_entry *n;
332 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
333 if (n == NULL) {
334 flow_list_new_entry(fl, ct);
335 return;
338 flow_entry_from_ct(n, ct);
341 static void flow_list_destroy_entry(struct flow_list *fl,
342 struct nf_conntrack *ct)
344 struct flow_entry *n1, *n2;
345 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
347 n1 = flow_list_find_id(fl, id);
348 if (n1) {
349 n2 = flow_list_find_prev_id(fl, id);
350 if (n2) {
351 rcu_assign_pointer(n2->next, n1->next);
352 n1->next = NULL;
354 flow_entry_xfree(n1);
355 } else {
356 struct flow_entry *next = fl->head->next;
358 flow_entry_xfree(fl->head);
359 fl->head = next;
364 static void flow_list_destroy(struct flow_list *fl)
366 struct flow_entry *n;
368 while (fl->head != NULL) {
369 n = rcu_dereference(fl->head->next);
370 fl->head->next = NULL;
372 flow_entry_xfree(fl->head);
373 rcu_assign_pointer(fl->head, n);
376 synchronize_rcu();
377 spinlock_destroy(&fl->lock);
380 static int walk_process(unsigned int pid, struct flow_entry *n)
382 int ret;
383 DIR *dir;
384 struct dirent *ent;
385 char path[1024];
387 if (snprintf(path, sizeof(path), "/proc/%u/fd", pid) == -1)
388 panic("giant process name! %u\n", pid);
390 dir = opendir(path);
391 if (!dir)
392 return 0;
394 while ((ent = readdir(dir))) {
395 struct stat statbuf;
397 if (snprintf(path, sizeof(path), "/proc/%u/fd/%s",
398 pid, ent->d_name) < 0)
399 continue;
401 if (stat(path, &statbuf) < 0)
402 continue;
404 if (S_ISSOCK(statbuf.st_mode) && (ino_t) n->inode == statbuf.st_ino) {
405 ret = proc_get_cmdline(pid, n->cmdline, sizeof(n->cmdline));
406 if (ret < 0)
407 panic("Failed to get process cmdline: %s\n", strerror(errno));
409 n->procnum = pid;
410 closedir(dir);
411 return 1;
415 closedir(dir);
416 return 0;
419 static void walk_processes(struct flow_entry *n)
421 int ret;
422 DIR *dir;
423 struct dirent *ent;
425 /* n->inode must be set */
426 if (n->inode <= 0) {
427 n->cmdline[0] = '\0';
428 return;
431 dir = opendir("/proc");
432 if (!dir)
433 panic("Cannot open /proc: %s\n", strerror(errno));
435 while ((ent = readdir(dir))) {
436 const char *name = ent->d_name;
437 char *end;
438 unsigned int pid = strtoul(name, &end, 10);
440 /* not a PID */
441 if (pid == 0 && end == name)
442 continue;
444 ret = walk_process(pid, n);
445 if (ret > 0)
446 break;
449 closedir(dir);
452 static int get_port_inode(uint16_t port, int proto, bool is_ip6)
454 int ret = -ENOENT;
455 char path[128], buff[1024];
456 FILE *proc;
458 memset(path, 0, sizeof(path));
459 snprintf(path, sizeof(path), "/proc/net/%s%s",
460 l4proto2str[proto], is_ip6 ? "6" : "");
462 proc = fopen(path, "r");
463 if (!proc)
464 return -EIO;
466 memset(buff, 0, sizeof(buff));
468 while (fgets(buff, sizeof(buff), proc) != NULL) {
469 int inode = 0;
470 unsigned int lport = 0;
472 buff[sizeof(buff) - 1] = 0;
473 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
474 "%*X %*u %*u %u", &lport, &inode) == 2) {
475 if ((uint16_t) lport == port) {
476 ret = inode;
477 break;
481 memset(buff, 0, sizeof(buff));
484 fclose(proc);
485 return ret;
488 #define CP_NFCT(elem, attr, x) \
489 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
490 #define CP_NFCT_BUFF(elem, attr) do { \
491 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
492 if (buff != NULL) \
493 memcpy(n->elem, buff, sizeof(n->elem)); \
494 } while (0)
496 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
498 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
499 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
501 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
502 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
504 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
505 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
507 CP_NFCT(status, ATTR_STATUS, 32);
509 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
510 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
511 CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
512 CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
514 CP_NFCT(pkts_src, ATTR_ORIG_COUNTER_PACKETS, 64);
515 CP_NFCT(bytes_src, ATTR_ORIG_COUNTER_BYTES, 64);
517 CP_NFCT(pkts_dst, ATTR_REPL_COUNTER_PACKETS, 64);
518 CP_NFCT(bytes_dst, ATTR_REPL_COUNTER_BYTES, 64);
520 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
521 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
523 CP_NFCT(flow_id, ATTR_ID, 32);
524 CP_NFCT(use, ATTR_USE, 32);
526 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
527 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
529 n->port_src = ntohs(n->port_src);
530 n->port_dst = ntohs(n->port_dst);
532 n->ip4_src_addr = ntohl(n->ip4_src_addr);
533 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
536 enum flow_entry_direction {
537 flow_entry_src,
538 flow_entry_dst,
541 #define SELFLD(dir,src_member,dst_member) \
542 (((dir) == flow_entry_src) ? n->src_member : n->dst_member)
544 static void flow_entry_get_sain4_obj(struct flow_entry *n,
545 enum flow_entry_direction dir,
546 struct sockaddr_in *sa)
548 memset(sa, 0, sizeof(*sa));
549 sa->sin_family = PF_INET;
550 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
553 static void flow_entry_get_sain6_obj(struct flow_entry *n,
554 enum flow_entry_direction dir,
555 struct sockaddr_in6 *sa)
557 memset(sa, 0, sizeof(*sa));
558 sa->sin6_family = PF_INET6;
560 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
561 sizeof(sa->sin6_addr));
564 static void
565 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
566 enum flow_entry_direction dir)
568 struct sockaddr_in sa4;
569 struct sockaddr_in6 sa6;
570 const char *city = NULL;
572 switch (n->l3_proto) {
573 default:
574 bug();
576 case AF_INET:
577 flow_entry_get_sain4_obj(n, dir, &sa4);
578 city = geoip4_city_name(&sa4);
579 break;
581 case AF_INET6:
582 flow_entry_get_sain6_obj(n, dir, &sa6);
583 city = geoip6_city_name(&sa6);
584 break;
587 build_bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
589 if (city) {
590 memcpy(SELFLD(dir, city_src, city_dst), city,
591 min(sizeof(n->city_src), strlen(city)));
592 } else {
593 memset(SELFLD(dir, city_src, city_dst), 0,
594 sizeof(n->city_src));
598 static void
599 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
600 enum flow_entry_direction dir)
602 struct sockaddr_in sa4;
603 struct sockaddr_in6 sa6;
604 const char *country = NULL;
606 switch (n->l3_proto) {
607 default:
608 bug();
610 case AF_INET:
611 flow_entry_get_sain4_obj(n, dir, &sa4);
612 country = geoip4_country_name(&sa4);
613 break;
615 case AF_INET6:
616 flow_entry_get_sain6_obj(n, dir, &sa6);
617 country = geoip6_country_name(&sa6);
618 break;
621 build_bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
623 if (country) {
624 memcpy(SELFLD(dir, country_src, country_dst), country,
625 min(sizeof(n->country_src), strlen(country)));
626 } else {
627 memset(SELFLD(dir, country_src, country_dst), 0,
628 sizeof(n->country_src));
632 static void flow_entry_get_extended_geo(struct flow_entry *n,
633 enum flow_entry_direction dir)
635 flow_entry_geo_city_lookup_generic(n, dir);
636 flow_entry_geo_country_lookup_generic(n, dir);
639 static void flow_entry_get_extended_revdns(struct flow_entry *n,
640 enum flow_entry_direction dir)
642 size_t sa_len;
643 struct sockaddr_in sa4;
644 struct sockaddr_in6 sa6;
645 struct sockaddr *sa;
646 struct hostent *hent;
648 switch (n->l3_proto) {
649 default:
650 bug();
652 case AF_INET:
653 flow_entry_get_sain4_obj(n, dir, &sa4);
654 sa = (struct sockaddr *) &sa4;
655 sa_len = sizeof(sa4);
656 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr), AF_INET);
657 break;
659 case AF_INET6:
660 flow_entry_get_sain6_obj(n, dir, &sa6);
661 sa = (struct sockaddr *) &sa6;
662 sa_len = sizeof(sa6);
663 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr), AF_INET6);
664 break;
667 build_bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
668 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
669 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
671 if (hent) {
672 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
673 memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
674 hent->h_name, min(sizeof(n->rev_dns_src),
675 strlen(hent->h_name)));
679 static void flow_entry_get_extended(struct flow_entry *n)
681 if (n->flow_id == 0)
682 return;
684 if (show_src) {
685 flow_entry_get_extended_revdns(n, flow_entry_src);
686 flow_entry_get_extended_geo(n, flow_entry_src);
689 flow_entry_get_extended_revdns(n, flow_entry_dst);
690 flow_entry_get_extended_geo(n, flow_entry_dst);
692 /* Lookup application */
693 n->inode = get_port_inode(n->port_src, n->l4_proto,
694 n->l3_proto == AF_INET6);
695 if (n->inode > 0)
696 walk_processes(n);
699 static uint16_t presenter_get_port(uint16_t src, uint16_t dst, bool is_tcp)
701 if (src < dst && src < 1024) {
702 return src;
703 } else if (dst < src && dst < 1024) {
704 return dst;
705 } else {
706 const char *tmp1, *tmp2;
707 if (is_tcp) {
708 tmp1 = lookup_port_tcp(src);
709 tmp2 = lookup_port_tcp(dst);
710 } else {
711 tmp1 = lookup_port_udp(src);
712 tmp2 = lookup_port_udp(dst);
714 if (tmp1 && !tmp2) {
715 return src;
716 } else if (!tmp1 && tmp2) {
717 return dst;
718 } else {
719 if (src < dst)
720 return src;
721 else
722 return dst;
727 static char *bandw2str(double bytes, char *buf, size_t len)
729 if (bytes > 1000000000.)
730 snprintf(buf, len, "%.1fG", bytes / 1000000000.);
731 else if (bytes > 1000000.)
732 snprintf(buf, len, "%.1fM", bytes / 1000000.);
733 else if (bytes > 1000.)
734 snprintf(buf, len, "%.1fK", bytes / 1000.);
735 else
736 snprintf(buf, len, "%g", bytes);
738 return buf;
741 static void presenter_print_counters(uint64_t bytes, uint64_t pkts, int color)
743 char bytes_str[64];
745 printw(" -> (");
746 attron(COLOR_PAIR(color));
747 printw("%"PRIu64" pkts, ", pkts);
748 printw("%s bytes", bandw2str(bytes, bytes_str, sizeof(bytes_str) - 1));
749 attroff(COLOR_PAIR(color));
750 printw(")");
753 static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
754 unsigned int *line)
756 char tmp[128], *pname = NULL;
757 uint16_t port;
759 mvwprintw(screen, *line, 2, "");
761 /* PID, application name */
762 if (n->procnum > 0) {
763 slprintf(tmp, sizeof(tmp), "%s(%d)", basename(n->cmdline),
764 n->procnum);
766 printw("[");
767 attron(COLOR_PAIR(3));
768 printw("%s", tmp);
769 attroff(COLOR_PAIR(3));
770 printw("]:");
773 /* L3 protocol, L4 protocol, states */
774 printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
775 printw("[");
776 attron(COLOR_PAIR(3));
777 switch (n->l4_proto) {
778 case IPPROTO_TCP:
779 printw("%s", tcp_state2str[n->tcp_state]);
780 break;
781 case IPPROTO_SCTP:
782 printw("%s", sctp_state2str[n->sctp_state]);
783 break;
784 case IPPROTO_DCCP:
785 printw("%s", dccp_state2str[n->dccp_state]);
786 break;
787 case IPPROTO_UDP:
788 case IPPROTO_UDPLITE:
789 case IPPROTO_ICMP:
790 case IPPROTO_ICMPV6:
791 printw("NOSTATE");
792 break;
794 attroff(COLOR_PAIR(3));
795 printw("]");
797 /* Guess application port */
798 switch (n->l4_proto) {
799 case IPPROTO_TCP:
800 port = presenter_get_port(n->port_src, n->port_dst, true);
801 pname = lookup_port_tcp(port);
802 break;
803 case IPPROTO_UDP:
804 case IPPROTO_UDPLITE:
805 port = presenter_get_port(n->port_src, n->port_dst, false);
806 pname = lookup_port_udp(port);
807 break;
809 if (pname) {
810 attron(A_BOLD);
811 printw(":%s", pname);
812 attroff(A_BOLD);
815 /* Show source information: reverse DNS, port, country, city, counters */
816 if (show_src) {
817 attron(COLOR_PAIR(1));
818 mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
819 attroff(COLOR_PAIR(1));
821 printw(":%"PRIu16, n->port_src);
823 if (n->country_src[0]) {
824 printw(" (");
826 attron(COLOR_PAIR(4));
827 printw("%s", n->country_src);
828 attroff(COLOR_PAIR(4));
830 if (n->city_src[0])
831 printw(", %s", n->city_src);
833 printw(")");
836 if (n->pkts_src > 0 && n->bytes_src > 0)
837 presenter_print_counters(n->bytes_src, n->pkts_src, 1);
839 printw(" => ");
842 /* Show dest information: reverse DNS, port, country, city, counters */
843 attron(COLOR_PAIR(2));
844 mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
845 attroff(COLOR_PAIR(2));
847 printw(":%"PRIu16, n->port_dst);
849 if (n->country_dst[0]) {
850 printw(" (");
852 attron(COLOR_PAIR(4));
853 printw("%s", n->country_dst);
854 attroff(COLOR_PAIR(4));
856 if (n->city_dst[0])
857 printw(", %s", n->city_dst);
859 printw(")");
862 if (n->pkts_dst > 0 && n->bytes_dst > 0)
863 presenter_print_counters(n->bytes_dst, n->pkts_dst, 2);
866 static inline bool presenter_flow_wrong_state(struct flow_entry *n)
868 switch (n->l4_proto) {
869 case IPPROTO_TCP:
870 switch (n->tcp_state) {
871 case TCP_CONNTRACK_SYN_SENT:
872 case TCP_CONNTRACK_SYN_RECV:
873 case TCP_CONNTRACK_ESTABLISHED:
874 case TCP_CONNTRACK_FIN_WAIT:
875 case TCP_CONNTRACK_CLOSE_WAIT:
876 case TCP_CONNTRACK_LAST_ACK:
877 case TCP_CONNTRACK_TIME_WAIT:
878 case TCP_CONNTRACK_CLOSE:
879 case TCP_CONNTRACK_SYN_SENT2:
880 case TCP_CONNTRACK_NONE:
881 return false;
882 break;
884 break;
885 case IPPROTO_SCTP:
886 switch (n->sctp_state) {
887 case SCTP_CONNTRACK_NONE:
888 case SCTP_CONNTRACK_CLOSED:
889 case SCTP_CONNTRACK_COOKIE_WAIT:
890 case SCTP_CONNTRACK_COOKIE_ECHOED:
891 case SCTP_CONNTRACK_ESTABLISHED:
892 case SCTP_CONNTRACK_SHUTDOWN_SENT:
893 case SCTP_CONNTRACK_SHUTDOWN_RECD:
894 case SCTP_CONNTRACK_SHUTDOWN_ACK_SENT:
895 return false;
896 break;
898 break;
899 case IPPROTO_DCCP:
900 switch (n->dccp_state) {
901 case DCCP_CONNTRACK_NONE:
902 case DCCP_CONNTRACK_REQUEST:
903 case DCCP_CONNTRACK_RESPOND:
904 case DCCP_CONNTRACK_PARTOPEN:
905 case DCCP_CONNTRACK_OPEN:
906 case DCCP_CONNTRACK_CLOSEREQ:
907 case DCCP_CONNTRACK_CLOSING:
908 case DCCP_CONNTRACK_TIMEWAIT:
909 case DCCP_CONNTRACK_IGNORE:
910 case DCCP_CONNTRACK_INVALID:
911 return false;
912 break;
914 break;
915 case IPPROTO_UDP:
916 case IPPROTO_UDPLITE:
917 case IPPROTO_ICMP:
918 case IPPROTO_ICMPV6:
919 return false;
920 break;
923 return true;
926 static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
927 int skip_lines)
929 int maxy;
930 int skip_left = skip_lines;
931 unsigned int flows = 0;
932 unsigned int line = 3;
933 struct flow_entry *n;
935 curs_set(0);
937 maxy = getmaxy(screen);
938 maxy -= 6;
940 start_color();
941 init_pair(1, COLOR_RED, COLOR_BLACK);
942 init_pair(2, COLOR_BLUE, COLOR_BLACK);
943 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
944 init_pair(4, COLOR_GREEN, COLOR_BLACK);
946 wclear(screen);
947 clear();
949 rcu_read_lock();
951 n = rcu_dereference(fl->head);
952 if (!n)
953 mvwprintw(screen, line, 2, "(No active sessions! "
954 "Is netfilter running?)");
956 for (; n; n = rcu_dereference(n->next)) {
957 n->is_visible = false;
959 if (presenter_flow_wrong_state(n))
960 continue;
962 /* count only flows which might be showed */
963 flows++;
965 if (maxy <= 0)
966 continue;
968 if (skip_left > 0) {
969 skip_left--;
970 continue;
973 n->is_visible = true;
975 presenter_screen_do_line(screen, n, &line);
977 line++;
978 maxy -= (2 + 1 * show_src);
981 mvwprintw(screen, 1, 2,
982 "Kernel netfilter flows(%u) for %s%s%s%s%s%s"
983 "[+%d]", flows, what & INCLUDE_TCP ? "TCP, " : "",
984 what & INCLUDE_UDP ? "UDP, " : "",
985 what & INCLUDE_SCTP ? "SCTP, " : "",
986 what & INCLUDE_DCCP ? "DCCP, " : "",
987 what & INCLUDE_ICMP && what & INCLUDE_IPV4 ? "ICMP, " : "",
988 what & INCLUDE_ICMP && what & INCLUDE_IPV6 ? "ICMP6, " : "",
989 skip_lines);
991 if (is_flow_collecting)
992 printw(" [Collecting flows ...]");
994 rcu_read_unlock();
996 wrefresh(screen);
997 refresh();
1000 static void presenter(void)
1002 int skip_lines = 0;
1003 WINDOW *screen;
1005 lookup_init_ports(PORTS_TCP);
1006 lookup_init_ports(PORTS_UDP);
1007 screen = screen_init(false);
1009 rcu_register_thread();
1010 while (!sigint) {
1011 switch (getch()) {
1012 case 'q':
1013 sigint = 1;
1014 break;
1015 case KEY_UP:
1016 case 'u':
1017 case 'k':
1018 skip_lines--;
1019 if (skip_lines < 0)
1020 skip_lines = 0;
1021 break;
1022 case KEY_DOWN:
1023 case 'd':
1024 case 'j':
1025 skip_lines++;
1026 if (skip_lines > SCROLL_MAX)
1027 skip_lines = SCROLL_MAX;
1028 break;
1029 default:
1030 fflush(stdin);
1031 break;
1034 presenter_screen_update(screen, &flow_list, skip_lines);
1035 usleep(200000);
1037 rcu_unregister_thread();
1039 screen_end();
1040 lookup_cleanup_ports(PORTS_UDP);
1041 lookup_cleanup_ports(PORTS_TCP);
1044 static int flow_event_cb(enum nf_conntrack_msg_type type,
1045 struct nf_conntrack *ct, void *data __maybe_unused)
1047 if (sigint)
1048 return NFCT_CB_STOP;
1050 synchronize_rcu();
1051 spinlock_lock(&flow_list.lock);
1053 switch (type) {
1054 case NFCT_T_NEW:
1055 flow_list_new_entry(&flow_list, ct);
1056 break;
1057 case NFCT_T_UPDATE:
1058 flow_list_update_entry(&flow_list, ct);
1059 break;
1060 case NFCT_T_DESTROY:
1061 flow_list_destroy_entry(&flow_list, ct);
1062 break;
1063 default:
1064 break;
1067 spinlock_unlock(&flow_list.lock);
1069 return NFCT_CB_CONTINUE;
1072 static void restore_sysctl(void *value)
1074 int int_val = *(int *)value;
1076 if (int_val == 0)
1077 sysctl_set_int("net/netfilter/nf_conntrack_acct", int_val);
1080 static void on_panic_handler(void *arg)
1082 restore_sysctl(arg);
1083 screen_end();
1086 static void conntrack_acct_enable(void)
1088 /* We can still work w/o traffic accounting so just warn about error */
1089 if (sysctl_get_int("net/netfilter/nf_conntrack_acct", &nfct_acct_val)) {
1090 fprintf(stderr, "Can't read net/netfilter/nf_conntrack_acct: %s\n",
1091 strerror(errno));
1094 if (nfct_acct_val == 1)
1095 return;
1097 if (sysctl_set_int("net/netfilter/nf_conntrack_acct", 1)) {
1098 fprintf(stderr, "Can't write net/netfilter/nf_conntrack_acct: %s\n",
1099 strerror(errno));
1103 static int flow_update_cb(enum nf_conntrack_msg_type type,
1104 struct nf_conntrack *ct, void *data __maybe_unused)
1106 struct flow_entry *n;
1108 if (type != NFCT_T_UPDATE)
1109 return NFCT_CB_CONTINUE;
1111 if (sigint)
1112 return NFCT_CB_STOP;
1114 n = flow_list_find_id(&flow_list, nfct_get_attr_u32(ct, ATTR_ID));
1115 if (!n)
1116 return NFCT_CB_CONTINUE;
1118 flow_entry_from_ct(n, ct);
1120 return NFCT_CB_CONTINUE;
1123 static void collector_refresh_flows(struct nfct_handle *handle)
1125 struct flow_entry *n;
1127 n = rcu_dereference(flow_list.head);
1128 for (; n; n = rcu_dereference(n->next)) {
1129 if (!n->is_visible)
1130 continue;
1132 nfct_query(handle, NFCT_Q_GET, n->ct);
1136 static void collector_create_filter(struct nfct_handle *nfct)
1138 struct nfct_filter *filter;
1139 int ret;
1141 filter = nfct_filter_create();
1142 if (!filter)
1143 panic("Cannot create a nfct filter: %s\n", strerror(errno));
1145 if (what & INCLUDE_UDP) {
1146 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1147 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
1149 if (what & INCLUDE_TCP)
1150 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1151 if (what & INCLUDE_DCCP)
1152 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1153 if (what & INCLUDE_SCTP)
1154 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1155 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1156 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1157 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1158 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1159 if (what & INCLUDE_IPV4) {
1160 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4, NFCT_FILTER_LOGIC_NEGATIVE);
1161 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1163 if (what & INCLUDE_IPV6) {
1164 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6, NFCT_FILTER_LOGIC_NEGATIVE);
1165 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1168 ret = nfct_filter_attach(nfct_fd(nfct), filter);
1169 if (ret < 0)
1170 panic("Cannot attach filter to handle: %s\n", strerror(errno));
1172 nfct_filter_destroy(filter);
1175 /* This hand-crafted filter looks ugly but it allows to do not
1176 * flush nfct connections & filter them by user specified filter.
1177 * May be it is better to replace this one by nfct_cmp. */
1178 static int flow_dump_cb(enum nf_conntrack_msg_type type,
1179 struct nf_conntrack *ct, void *data __maybe_unused)
1181 struct flow_entry fl;
1182 struct flow_entry *n = &fl;
1184 if (sigint)
1185 return NFCT_CB_STOP;
1187 synchronize_rcu();
1188 spinlock_lock(&flow_list.lock);
1190 if (!(what & ~(INCLUDE_IPV4 | INCLUDE_IPV6)))
1191 goto check_addr;
1193 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
1195 if (what & INCLUDE_UDP) {
1196 if (n->l4_proto == IPPROTO_UDP)
1197 goto check_addr;
1199 if (n->l4_proto == IPPROTO_UDPLITE)
1200 goto check_addr;
1203 if ((what & INCLUDE_TCP) && n->l4_proto == IPPROTO_TCP)
1204 goto check_addr;
1206 if ((what & INCLUDE_DCCP) && n->l4_proto == IPPROTO_DCCP)
1207 goto check_addr;
1209 if ((what & INCLUDE_SCTP) && n->l4_proto == IPPROTO_SCTP)
1210 goto check_addr;
1212 if ((what & INCLUDE_ICMP) && (what & INCLUDE_IPV4) &&
1213 n->l4_proto == IPPROTO_ICMP) {
1214 goto check_addr;
1217 if ((what & INCLUDE_ICMP) && (what & INCLUDE_IPV6) &&
1218 n->l4_proto == IPPROTO_ICMPV6) {
1219 goto check_addr;
1222 goto skip_flow;
1224 check_addr:
1225 /* filter loopback addresses */
1226 if (what & INCLUDE_IPV4) {
1227 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
1229 if (n->ip4_src_addr == filter_ipv4.addr)
1230 goto skip_flow;
1232 if (what & INCLUDE_IPV6) {
1233 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
1235 if (n->ip6_src_addr[0] == 0x0 &&
1236 n->ip6_src_addr[1] == 0x0 &&
1237 n->ip6_src_addr[2] == 0x0 &&
1238 n->ip6_src_addr[3] == 0x1)
1239 goto skip_flow;
1242 flow_list_new_entry(&flow_list, ct);
1244 skip_flow:
1245 spinlock_unlock(&flow_list.lock);
1246 return NFCT_CB_CONTINUE;
1249 static void collector_dump_flows(void)
1251 struct nfct_handle *nfct = nfct_open(CONNTRACK, 0);
1253 if (!nfct)
1254 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1256 nfct_callback_register(nfct, NFCT_T_ALL, flow_dump_cb, NULL);
1258 is_flow_collecting = true;
1259 if (what & INCLUDE_IPV4) {
1260 int family = AF_INET;
1261 nfct_query(nfct, NFCT_Q_DUMP, &family);
1263 if (what & INCLUDE_IPV6) {
1264 int family = AF_INET6;
1265 nfct_query(nfct, NFCT_Q_DUMP, &family);
1267 is_flow_collecting = false;
1269 nfct_close(nfct);
1272 static void *collector(void *null __maybe_unused)
1274 struct nfct_handle *ct_update;
1275 struct nfct_handle *ct_event;
1276 struct pollfd poll_fd[1];
1278 flow_list_init(&flow_list);
1280 ct_event = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1281 NF_NETLINK_CONNTRACK_UPDATE |
1282 NF_NETLINK_CONNTRACK_DESTROY);
1283 if (!ct_event)
1284 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1286 collector_create_filter(ct_event);
1288 nfct_callback_register(ct_event, NFCT_T_ALL, flow_event_cb, NULL);
1290 ct_update = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_UPDATE);
1291 if (!ct_update)
1292 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1294 nfct_callback_register(ct_update, NFCT_T_ALL, flow_update_cb, NULL);
1296 poll_fd[0].fd = nfct_fd(ct_event);
1297 poll_fd[0].events = POLLIN;
1299 if (fcntl(nfct_fd(ct_event), F_SETFL, O_NONBLOCK) == -1)
1300 panic("Cannot set non-blocking socket: fcntl(): %s\n",
1301 strerror(errno));
1303 if (fcntl(nfct_fd(ct_update), F_SETFL, O_NONBLOCK) == -1)
1304 panic("Cannot set non-blocking socket: fcntl(): %s\n",
1305 strerror(errno));
1307 rcu_register_thread();
1309 collector_dump_flows();
1311 while (!sigint) {
1312 int status;
1314 usleep(300000);
1316 collector_refresh_flows(ct_update);
1318 status = poll(poll_fd, 1, 0);
1319 if (status < 0) {
1320 if (errno == EAGAIN || errno == EINTR)
1321 continue;
1323 panic("Error while polling: %s\n", strerror(errno));
1324 } else if (status == 0) {
1325 continue;
1328 if (poll_fd[0].revents & POLLIN)
1329 nfct_catch(ct_event);
1332 rcu_unregister_thread();
1334 flow_list_destroy(&flow_list);
1335 nfct_close(ct_event);
1336 nfct_close(ct_update);
1338 pthread_exit(NULL);
1341 int main(int argc, char **argv)
1343 pthread_t tid;
1344 int ret, c, opt_index, what_cmd = 0;
1346 setfsuid(getuid());
1347 setfsgid(getgid());
1349 while ((c = getopt_long(argc, argv, short_options, long_options,
1350 &opt_index)) != EOF) {
1351 switch (c) {
1352 case '4':
1353 what_cmd |= INCLUDE_IPV4;
1354 break;
1355 case '6':
1356 what_cmd |= INCLUDE_IPV6;
1357 break;
1358 case 'T':
1359 what_cmd |= INCLUDE_TCP;
1360 break;
1361 case 'U':
1362 what_cmd |= INCLUDE_UDP;
1363 break;
1364 case 'D':
1365 what_cmd |= INCLUDE_DCCP;
1366 break;
1367 case 'I':
1368 what_cmd |= INCLUDE_ICMP;
1369 break;
1370 case 'S':
1371 what_cmd |= INCLUDE_SCTP;
1372 break;
1373 case 's':
1374 show_src = 1;
1375 break;
1376 case 'u':
1377 update_geoip();
1378 die();
1379 break;
1380 case 'h':
1381 help();
1382 break;
1383 case 'v':
1384 version();
1385 break;
1386 default:
1387 break;
1391 if (what_cmd > 0) {
1392 what = what_cmd;
1394 if (!(what & (INCLUDE_IPV4 | INCLUDE_IPV6)))
1395 what |= INCLUDE_IPV4 | INCLUDE_IPV6;
1398 rcu_init();
1400 register_signal(SIGINT, signal_handler);
1401 register_signal(SIGQUIT, signal_handler);
1402 register_signal(SIGTERM, signal_handler);
1403 register_signal(SIGHUP, signal_handler);
1405 panic_handler_add(on_panic_handler, &nfct_acct_val);
1407 conntrack_acct_enable();
1409 init_geoip(1);
1411 ret = pthread_create(&tid, NULL, collector, NULL);
1412 if (ret < 0)
1413 panic("Cannot create phthread!\n");
1415 presenter();
1417 destroy_geoip();
1419 restore_sysctl(&nfct_acct_val);
1421 return 0;