flowtop: Fix use-after-free on filter reload
[netsniff-ng.git] / flowtop.c
blob256bd0503dcb97af07d4db214b2483e5d5a2922f
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 <sys/time.h>
21 #include <sys/fsuid.h>
22 #include <libgen.h>
23 #include <inttypes.h>
24 #include <poll.h>
25 #include <fcntl.h>
26 #include <arpa/inet.h>
28 #include <urcu.h>
29 #include <urcu/list.h>
30 #include <urcu/rculist.h>
32 #include "ui.h"
33 #include "die.h"
34 #include "xmalloc.h"
35 #include "conntrack.h"
36 #include "config.h"
37 #include "str.h"
38 #include "sig.h"
39 #include "lookup.h"
40 #include "geoip.h"
41 #include "built_in.h"
42 #include "pkt_buff.h"
43 #include "screen.h"
44 #include "proc.h"
45 #include "sysctl.h"
47 #ifndef NSEC_PER_SEC
48 #define NSEC_PER_SEC 1000000000L
49 #endif
51 #ifndef USEC_PER_SEC
52 #define USEC_PER_SEC 1000000L
53 #endif
55 struct flow_stat {
56 uint64_t pkts_src, bytes_src;
57 uint64_t pkts_dst, bytes_dst;
58 double rate_bytes_src;
59 double rate_bytes_dst;
60 double rate_pkts_src;
61 double rate_pkts_dst;
64 struct proc_entry {
65 struct cds_list_head entry;
66 struct cds_list_head flows;
67 struct rcu_head rcu;
69 struct timeval last_update;
70 struct flow_stat stat;
71 unsigned int pid;
72 char name[256];
73 int flows_count;
76 struct flow_entry {
77 struct cds_list_head proc_head;
78 struct cds_list_head entry;
79 struct rcu_head rcu;
81 uint32_t flow_id, use, status;
82 uint8_t l3_proto, l4_proto;
83 uint32_t ip4_src_addr, ip4_dst_addr;
84 uint32_t ip6_src_addr[4], ip6_dst_addr[4];
85 uint16_t port_src, port_dst;
86 uint8_t tcp_state, tcp_flags, sctp_state, dccp_state;
87 uint64_t timestamp_start, timestamp_stop;
88 char country_src[128], country_dst[128];
89 char country_code_src[4], country_code_dst[4];
90 char city_src[128], city_dst[128];
91 char rev_dns_src[256], rev_dns_dst[256];
92 struct proc_entry *proc;
93 int inode;
94 bool is_visible;
95 struct nf_conntrack *ct;
96 struct timeval last_update;
97 struct flow_stat stat;
100 struct flow_list {
101 struct cds_list_head head;
104 struct proc_list {
105 struct cds_list_head head;
108 enum flow_direction {
109 FLOW_DIR_SRC,
110 FLOW_DIR_DST,
113 #ifndef ATTR_TIMESTAMP_START
114 # define ATTR_TIMESTAMP_START 63
115 #endif
116 #ifndef ATTR_TIMESTAMP_STOP
117 # define ATTR_TIMESTAMP_STOP 64
118 #endif
120 #define INCLUDE_IPV4 (1 << 0)
121 #define INCLUDE_IPV6 (1 << 1)
122 #define INCLUDE_UDP (1 << 2)
123 #define INCLUDE_TCP (1 << 3)
124 #define INCLUDE_DCCP (1 << 4)
125 #define INCLUDE_ICMP (1 << 5)
126 #define INCLUDE_SCTP (1 << 6)
128 #define TOGGLE_FLAG(what, flag) \
129 do { \
130 if (what & flag) \
131 what &= ~flag; \
132 else \
133 what |= flag; \
134 } while (0)
136 struct sysctl_params_ctx {
137 int nfct_acct;
138 int nfct_tstamp;
141 enum rate_units {
142 RATE_BITS,
143 RATE_BYTES
146 static volatile bool do_reload_flows;
147 static volatile bool is_flow_collecting;
148 static volatile sig_atomic_t sigint = 0;
149 static int what = INCLUDE_IPV4 | INCLUDE_IPV6 | INCLUDE_TCP;
150 static struct proc_list proc_list;
151 static struct flow_list flow_list;
152 static struct sysctl_params_ctx sysctl = { -1, -1 };
154 static unsigned int cols, rows;
155 static WINDOW *screen;
157 static unsigned int interval = 1;
158 static bool show_src = false;
159 static bool resolve_dns = true;
160 static bool resolve_geoip = true;
161 static enum rate_units rate_type = RATE_BYTES;
162 static bool show_active_only = false;
164 enum tbl_flow_col {
165 TBL_FLOW_PROCESS,
166 TBL_FLOW_PID,
167 TBL_FLOW_PROTO,
168 TBL_FLOW_STATE,
169 TBL_FLOW_TIME,
170 TBL_FLOW_ADDRESS,
171 TBL_FLOW_PORT,
172 TBL_FLOW_GEO,
173 TBL_FLOW_BYTES,
174 TBL_FLOW_RATE,
177 enum tbl_proc_col {
178 TBL_PROC_NAME,
179 TBL_PROC_PID,
180 TBL_PROC_FLOWS,
181 TBL_PROC_BYTES_SRC,
182 TBL_PROC_RATE_SRC,
183 TBL_PROC_BYTES_DST,
184 TBL_PROC_RATE_DST,
187 static struct ui_table flows_tbl;
188 static struct ui_table procs_tbl;
189 static struct ui_table *curr_tbl;
191 enum tab_entry {
192 TAB_FLOWS,
193 TAB_PROCS,
196 #define list_first_or_next(__ptr, __head, __entry) \
197 ({ \
198 struct cds_list_head *h; \
199 if (!__ptr) \
200 h = rcu_dereference((__head)->next); \
201 else if (rcu_dereference(__ptr->__entry.next) == (__head)) \
202 return NULL; \
203 else \
204 h = rcu_dereference(__ptr->__entry.next); \
205 cds_list_entry(h, __typeof(* (__ptr)), __entry); \
208 static const char *short_options = "vhTUsDIS46ut:nGb";
209 static const struct option long_options[] = {
210 {"ipv4", no_argument, NULL, '4'},
211 {"ipv6", no_argument, NULL, '6'},
212 {"tcp", no_argument, NULL, 'T'},
213 {"udp", no_argument, NULL, 'U'},
214 {"dccp", no_argument, NULL, 'D'},
215 {"icmp", no_argument, NULL, 'I'},
216 {"sctp", no_argument, NULL, 'S'},
217 {"no-dns", no_argument, NULL, 'n'},
218 {"no-geoip", no_argument, NULL, 'G'},
219 {"show-src", no_argument, NULL, 's'},
220 {"bits", no_argument, NULL, 'b'},
221 {"update", no_argument, NULL, 'u'},
222 {"interval", required_argument, NULL, 't'},
223 {"version", no_argument, NULL, 'v'},
224 {"help", no_argument, NULL, 'h'},
225 {NULL, 0, NULL, 0}
228 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
229 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
230 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
231 "Swiss federal institute of technology (ETH Zurich)\n"
232 "License: GNU GPL version 2.0\n"
233 "This is free software: you are free to change and redistribute it.\n"
234 "There is NO WARRANTY, to the extent permitted by law.";
236 static const char *const l4proto2str[IPPROTO_MAX] = {
237 [IPPROTO_TCP] = "tcp",
238 [IPPROTO_UDP] = "udp",
239 [IPPROTO_UDPLITE] = "udplite",
240 [IPPROTO_ICMP] = "icmp",
241 [IPPROTO_ICMPV6] = "icmpv6",
242 [IPPROTO_SCTP] = "sctp",
243 [IPPROTO_GRE] = "gre",
244 [IPPROTO_DCCP] = "dccp",
245 [IPPROTO_IGMP] = "igmp",
246 [IPPROTO_IPIP] = "ipip",
247 [IPPROTO_EGP] = "egp",
248 [IPPROTO_PUP] = "pup",
249 [IPPROTO_IDP] = "idp",
250 [IPPROTO_RSVP] = "rsvp",
251 [IPPROTO_IPV6] = "ip6tun",
252 [IPPROTO_ESP] = "esp",
253 [IPPROTO_AH] = "ah",
254 [IPPROTO_PIM] = "pim",
255 [IPPROTO_COMP] = "comp",
258 static const char *const tcp_state2str[TCP_CONNTRACK_MAX] = {
259 [TCP_CONNTRACK_NONE] = "NONE",
260 [TCP_CONNTRACK_SYN_SENT] = "SYN-SENT",
261 [TCP_CONNTRACK_SYN_RECV] = "SYN-RECV",
262 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
263 [TCP_CONNTRACK_FIN_WAIT] = "FIN-WAIT",
264 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE-WAIT",
265 [TCP_CONNTRACK_LAST_ACK] = "LAST-ACK",
266 [TCP_CONNTRACK_TIME_WAIT] = "TIME-WAIT",
267 [TCP_CONNTRACK_CLOSE] = "CLOSE",
268 [TCP_CONNTRACK_SYN_SENT2] = "SYN-SENT2",
271 static const char *const dccp_state2str[DCCP_CONNTRACK_MAX] = {
272 [DCCP_CONNTRACK_NONE] = "NONE",
273 [DCCP_CONNTRACK_REQUEST] = "REQUEST",
274 [DCCP_CONNTRACK_RESPOND] = "RESPOND",
275 [DCCP_CONNTRACK_PARTOPEN] = "PARTOPEN",
276 [DCCP_CONNTRACK_OPEN] = "OPEN",
277 [DCCP_CONNTRACK_CLOSEREQ] = "CLOSE-REQ",
278 [DCCP_CONNTRACK_CLOSING] = "CLOSING",
279 [DCCP_CONNTRACK_TIMEWAIT] = "TIME-WAIT",
280 [DCCP_CONNTRACK_IGNORE] = "IGNORE",
281 [DCCP_CONNTRACK_INVALID] = "INVALID",
284 static const char *const sctp_state2str[SCTP_CONNTRACK_MAX] = {
285 [SCTP_CONNTRACK_NONE] = "NONE",
286 [SCTP_CONNTRACK_CLOSED] = "CLOSED",
287 [SCTP_CONNTRACK_COOKIE_WAIT] = "COOKIE-WAIT",
288 [SCTP_CONNTRACK_COOKIE_ECHOED] = "COOKIE-ECHO",
289 [SCTP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
290 [SCTP_CONNTRACK_SHUTDOWN_SENT] = "SHUTD-SENT",
291 [SCTP_CONNTRACK_SHUTDOWN_RECD] = "SHUTD-RCVD",
292 [SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = "SHUTD-ACK",
295 static const struct nfct_filter_ipv4 filter_ipv4 = {
296 .addr = __constant_htonl(INADDR_LOOPBACK),
297 .mask = 0xffffffff,
300 static const struct nfct_filter_ipv6 filter_ipv6 = {
301 .addr = { 0x0, 0x0, 0x0, 0x1 },
302 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
305 static int64_t time_after_us(struct timeval *tv)
307 struct timeval now;
309 bug_on(gettimeofday(&now, NULL));
311 now.tv_sec -= tv->tv_sec;
312 now.tv_usec -= tv->tv_usec;
314 return now.tv_sec * USEC_PER_SEC + now.tv_usec;
317 static void signal_handler(int number)
319 switch (number) {
320 case SIGINT:
321 case SIGQUIT:
322 case SIGTERM:
323 sigint = 1;
324 break;
325 case SIGHUP:
326 default:
327 break;
331 static void flow_entry_from_ct(struct flow_entry *n, const struct nf_conntrack *ct);
332 static void flow_entry_get_extended(struct flow_entry *n);
334 static void help(void)
336 printf("flowtop %s, top-like netfilter TCP/UDP/SCTP/.. flow tracking\n",
337 VERSION_STRING);
338 puts("http://www.netsniff-ng.org\n\n"
339 "Usage: flowtop [options]\n"
340 "Options:\n"
341 " -4|--ipv4 Show only IPv4 flows (default)\n"
342 " -6|--ipv6 Show only IPv6 flows (default)\n"
343 " -T|--tcp Show only TCP flows (default)\n"
344 " -U|--udp Show only UDP flows\n"
345 " -D|--dccp Show only DCCP flows\n"
346 " -I|--icmp Show only ICMP/ICMPv6 flows\n"
347 " -S|--sctp Show only SCTP flows\n"
348 " -n|--no-dns Don't perform hostname lookup\n"
349 " -G|--no-geoip Don't perform GeoIP lookup\n"
350 " -s|--show-src Also show source, not only dest\n"
351 " -b|--bits Show rates in bits/s instead of bytes/s\n"
352 " -u|--update Update GeoIP databases\n"
353 " -t|--interval <time> Refresh time in seconds (default 1s)\n"
354 " -v|--version Print version and exit\n"
355 " -h|--help Print this help and exit\n\n"
356 "Examples:\n"
357 " flowtop\n"
358 " flowtop -46UTDISs\n\n"
359 "Note:\n"
360 " If netfilter is not running, you can activate it with e.g.:\n"
361 " iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
362 " iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n");
363 puts(copyright);
364 die();
367 static void version(void)
369 printf("flowtop %s, Git id: %s\n", VERSION_LONG, GITVERSION);
370 puts("top-like netfilter TCP/UDP/SCTP/.. flow tracking\n"
371 "http://www.netsniff-ng.org\n");
372 puts(copyright);
373 die();
376 static void flow_entry_update_time(struct flow_entry *n)
378 bug_on(gettimeofday(&n->last_update, NULL));
381 #define CALC_RATE(fld) do { \
382 n->stat.rate_##fld = (((fld) > n->stat.fld) ? \
383 (((fld) - n->stat.fld) / sec) : 0); \
384 } while (0)
386 static void flow_entry_calc_rate(struct flow_entry *n, const struct nf_conntrack *ct)
388 uint64_t bytes_src = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_BYTES);
389 uint64_t bytes_dst = nfct_get_attr_u64(ct, ATTR_REPL_COUNTER_BYTES);
390 uint64_t pkts_src = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_PACKETS);
391 uint64_t pkts_dst = nfct_get_attr_u64(ct, ATTR_REPL_COUNTER_PACKETS);
392 double sec = (double)time_after_us(&n->last_update) / USEC_PER_SEC;
394 if (sec < 1)
395 return;
397 CALC_RATE(bytes_src);
398 CALC_RATE(bytes_dst);
399 CALC_RATE(pkts_src);
400 CALC_RATE(pkts_dst);
403 static inline struct flow_entry *flow_entry_xalloc(void)
405 return xzmalloc(sizeof(struct flow_entry));
408 static inline void flow_entry_xfree(struct flow_entry *n)
410 if (n->ct)
411 nfct_destroy(n->ct);
413 xfree(n);
416 static void flow_entry_xfree_rcu(struct rcu_head *head)
418 struct flow_entry *n = container_of(head, struct flow_entry, rcu);
420 flow_entry_xfree(n);
423 static inline void flow_list_init(struct flow_list *fl)
425 CDS_INIT_LIST_HEAD(&fl->head);
428 static inline bool nfct_is_dns(const struct nf_conntrack *ct)
430 uint16_t port_src = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_SRC);
431 uint16_t port_dst = nfct_get_attr_u16(ct, ATTR_ORIG_PORT_DST);
433 return ntohs(port_src) == 53 || ntohs(port_dst) == 53;
436 static int flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
438 struct flow_entry *n;
440 /* We don't want to analyze / display DNS itself, since we
441 * use it to resolve reverse dns.
443 if (nfct_is_dns(ct))
444 return NFCT_CB_CONTINUE;
446 n = flow_entry_xalloc();
448 n->ct = ct;
450 flow_entry_update_time(n);
451 flow_entry_from_ct(n, ct);
452 flow_entry_get_extended(n);
454 cds_list_add_rcu(&n->entry, &fl->head);
456 n->is_visible = true;
458 return NFCT_CB_STOLEN;
461 static struct flow_entry *flow_list_find_id(struct flow_list *fl, uint32_t id)
463 struct flow_entry *n;
465 cds_list_for_each_entry_rcu(n, &fl->head, entry) {
466 if (n->flow_id == id)
467 return n;
470 return NULL;
473 static void __flow_list_del_entry(struct flow_list *fl, struct flow_entry *n)
475 if (n->proc) {
476 cds_list_del_rcu(&n->proc_head);
477 n->proc->flows_count--;
480 cds_list_del_rcu(&n->entry);
481 call_rcu(&n->rcu, flow_entry_xfree_rcu);
484 static int flow_list_del_entry(struct flow_list *fl, const struct nf_conntrack *ct)
486 struct flow_entry *n;
488 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
489 if (n)
490 __flow_list_del_entry(fl, n);
492 return NFCT_CB_CONTINUE;
495 static void flow_list_destroy(struct flow_list *fl)
497 struct flow_entry *n, *tmp;
499 cds_list_for_each_entry_safe(n, tmp, &fl->head, entry)
500 __flow_list_del_entry(fl, n);
503 static void proc_list_init(struct proc_list *proc_list)
505 CDS_INIT_LIST_HEAD(&proc_list->head);
508 static struct proc_entry *proc_list_new_entry(unsigned int pid)
510 struct proc_entry *proc;
512 cds_list_for_each_entry(proc, &proc_list.head, entry) {
513 if (proc->pid && proc->pid == pid)
514 return proc;
517 proc = xzmalloc(sizeof(*proc));
519 bug_on(gettimeofday(&proc->last_update, NULL));
520 CDS_INIT_LIST_HEAD(&proc->flows);
521 proc->pid = pid;
523 cds_list_add_tail(&proc->entry, &proc_list.head);
525 return proc;
528 static void proc_entry_xfree_rcu(struct rcu_head *head)
530 struct proc_entry *p = container_of(head, struct proc_entry, rcu);
532 xfree(p);
535 static void proc_list_destroy(struct proc_list *pl)
537 struct proc_entry *p, *tmp;
539 cds_list_for_each_entry_safe(p, tmp, &pl->head, entry) {
540 cds_list_del_rcu(&p->entry);
541 call_rcu(&p->rcu, proc_entry_xfree_rcu);
545 static void flow_entry_find_process(struct flow_entry *n)
547 struct proc_entry *p;
548 char cmdline[512];
549 pid_t pid;
550 int ret;
552 ret = proc_find_by_inode(n->inode, cmdline, sizeof(cmdline), &pid);
553 if (ret <= 0)
554 return;
556 p = proc_list_new_entry(pid);
558 if (snprintf(p->name, sizeof(p->name), "%s", basename(cmdline)) < 0)
559 p->name[0] = '\0';
561 p->stat.pkts_src += n->stat.pkts_src;
562 p->stat.pkts_dst += n->stat.pkts_dst;
563 p->stat.bytes_src += n->stat.bytes_src;
564 p->stat.bytes_dst += n->stat.bytes_dst;
565 p->flows_count++;
567 cds_list_add_rcu(&n->proc_head, &p->flows);
568 n->proc = p;
571 static int get_port_inode(uint16_t port, int proto, bool is_ip6)
573 int ret = -ENOENT;
574 char path[128], buff[1024];
575 FILE *proc;
577 memset(path, 0, sizeof(path));
578 snprintf(path, sizeof(path), "/proc/net/%s%s",
579 l4proto2str[proto], is_ip6 ? "6" : "");
581 proc = fopen(path, "r");
582 if (!proc)
583 return -EIO;
585 memset(buff, 0, sizeof(buff));
587 while (fgets(buff, sizeof(buff), proc) != NULL) {
588 int inode = 0;
589 unsigned int lport = 0;
591 buff[sizeof(buff) - 1] = 0;
592 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
593 "%*X %*u %*u %u", &lport, &inode) == 2) {
594 if ((uint16_t) lport == port) {
595 ret = inode;
596 break;
600 memset(buff, 0, sizeof(buff));
603 fclose(proc);
604 return ret;
607 #define CP_NFCT(elem, attr, x) \
608 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
609 #define CP_NFCT_BUFF(elem, attr) do { \
610 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
611 if (buff != NULL) \
612 memcpy(n->elem, buff, sizeof(n->elem)); \
613 } while (0)
615 static void flow_entry_from_ct(struct flow_entry *n, const struct nf_conntrack *ct)
617 uint64_t bytes_src = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_BYTES);
618 uint64_t bytes_dst = nfct_get_attr_u64(ct, ATTR_REPL_COUNTER_BYTES);
619 uint64_t pkts_src = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_PACKETS);
620 uint64_t pkts_dst = nfct_get_attr_u64(ct, ATTR_REPL_COUNTER_PACKETS);
622 /* Update stats diff to the related process entry */
623 if (n->proc) {
624 n->proc->stat.pkts_src += pkts_src - n->stat.pkts_src;
625 n->proc->stat.pkts_dst += pkts_dst - n->stat.pkts_dst;
626 n->proc->stat.bytes_src += bytes_src - n->stat.bytes_src;
627 n->proc->stat.bytes_dst += bytes_dst - n->stat.bytes_dst;
630 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
631 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
633 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
634 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
636 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
637 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
639 CP_NFCT(status, ATTR_STATUS, 32);
641 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
642 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
643 CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
644 CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
646 CP_NFCT(stat.pkts_src, ATTR_ORIG_COUNTER_PACKETS, 64);
647 CP_NFCT(stat.bytes_src, ATTR_ORIG_COUNTER_BYTES, 64);
649 CP_NFCT(stat.pkts_dst, ATTR_REPL_COUNTER_PACKETS, 64);
650 CP_NFCT(stat.bytes_dst, ATTR_REPL_COUNTER_BYTES, 64);
652 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
653 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
655 CP_NFCT(flow_id, ATTR_ID, 32);
656 CP_NFCT(use, ATTR_USE, 32);
658 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
659 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
661 n->port_src = ntohs(n->port_src);
662 n->port_dst = ntohs(n->port_dst);
664 n->ip4_src_addr = ntohl(n->ip4_src_addr);
665 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
668 #define SELFLD(dir,src_member,dst_member) \
669 (((dir) == FLOW_DIR_SRC) ? n->src_member : n->dst_member)
671 static void flow_entry_get_sain4_obj(const struct flow_entry *n,
672 enum flow_direction dir,
673 struct sockaddr_in *sa)
675 memset(sa, 0, sizeof(*sa));
676 sa->sin_family = PF_INET;
677 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
680 static void flow_entry_get_sain6_obj(const struct flow_entry *n,
681 enum flow_direction dir,
682 struct sockaddr_in6 *sa)
684 memset(sa, 0, sizeof(*sa));
685 sa->sin6_family = PF_INET6;
687 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
688 sizeof(sa->sin6_addr));
691 static void
692 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
693 enum flow_direction dir)
695 struct sockaddr_in sa4;
696 struct sockaddr_in6 sa6;
697 char *city = NULL;
699 switch (n->l3_proto) {
700 default:
701 bug();
703 case AF_INET:
704 flow_entry_get_sain4_obj(n, dir, &sa4);
705 city = geoip4_city_name(&sa4);
706 break;
708 case AF_INET6:
709 flow_entry_get_sain6_obj(n, dir, &sa6);
710 city = geoip6_city_name(&sa6);
711 break;
714 build_bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
716 if (city)
717 strlcpy(SELFLD(dir, city_src, city_dst), city,
718 sizeof(n->city_src));
719 else
720 SELFLD(dir, city_src, city_dst)[0] = '\0';
722 free(city);
725 static void
726 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
727 enum flow_direction dir)
729 struct sockaddr_in sa4;
730 struct sockaddr_in6 sa6;
731 const char *country = NULL;
732 const char *country_code = NULL;
734 switch (n->l3_proto) {
735 default:
736 bug();
738 case AF_INET:
739 flow_entry_get_sain4_obj(n, dir, &sa4);
740 country = geoip4_country_name(&sa4);
741 country_code = geoip4_country_code3_name(&sa4);
742 break;
744 case AF_INET6:
745 flow_entry_get_sain6_obj(n, dir, &sa6);
746 country = geoip6_country_name(&sa6);
747 country_code = geoip6_country_code3_name(&sa6);
748 break;
751 build_bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
753 if (country)
754 strlcpy(SELFLD(dir, country_src, country_dst), country,
755 sizeof(n->country_src));
756 else
757 SELFLD(dir, country_src, country_dst)[0] = '\0';
759 build_bug_on(sizeof(n->country_code_src) != sizeof(n->country_code_dst));
761 if (country_code)
762 strlcpy(SELFLD(dir, country_code_src, country_code_dst),
763 country_code, sizeof(n->country_code_src));
764 else
765 SELFLD(dir, country_code_src, country_code_dst)[0] = '\0';
768 static void flow_entry_get_extended_geo(struct flow_entry *n,
769 enum flow_direction dir)
771 if (resolve_geoip) {
772 flow_entry_geo_city_lookup_generic(n, dir);
773 flow_entry_geo_country_lookup_generic(n, dir);
777 static void flow_entry_get_extended_revdns(struct flow_entry *n,
778 enum flow_direction dir)
780 size_t sa_len;
781 struct sockaddr_in sa4;
782 struct sockaddr_in6 sa6;
783 struct sockaddr *sa;
784 struct hostent *hent;
786 build_bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
788 switch (n->l3_proto) {
789 default:
790 bug();
792 case AF_INET:
793 flow_entry_get_sain4_obj(n, dir, &sa4);
795 if (!resolve_dns) {
796 inet_ntop(AF_INET, &sa4.sin_addr,
797 SELFLD(dir, rev_dns_src, rev_dns_dst),
798 sizeof(n->rev_dns_src));
799 return;
802 sa = (struct sockaddr *) &sa4;
803 sa_len = sizeof(sa4);
804 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr), AF_INET);
805 break;
807 case AF_INET6:
808 flow_entry_get_sain6_obj(n, dir, &sa6);
810 if (!resolve_dns) {
811 inet_ntop(AF_INET6, &sa6.sin6_addr,
812 SELFLD(dir, rev_dns_src, rev_dns_dst),
813 sizeof(n->rev_dns_src));
814 return;
817 sa = (struct sockaddr *) &sa6;
818 sa_len = sizeof(sa6);
819 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr), AF_INET6);
820 break;
823 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
824 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
826 if (hent)
827 strlcpy(SELFLD(dir, rev_dns_src, rev_dns_dst), hent->h_name,
828 sizeof(n->rev_dns_src));
831 static void flow_entry_get_extended(struct flow_entry *n)
833 if (n->flow_id == 0)
834 return;
836 flow_entry_get_extended_revdns(n, FLOW_DIR_SRC);
837 flow_entry_get_extended_geo(n, FLOW_DIR_SRC);
839 flow_entry_get_extended_revdns(n, FLOW_DIR_DST);
840 flow_entry_get_extended_geo(n, FLOW_DIR_DST);
842 /* Lookup application */
843 n->inode = get_port_inode(n->port_src, n->l4_proto,
844 n->l3_proto == AF_INET6);
845 if (n->inode > 0)
846 flow_entry_find_process(n);
849 static char *bandw2str(double bytes, char *buf, size_t len)
851 if (bytes <= 0) {
852 buf[0] = '\0';
853 return buf;
856 if (bytes > 1000000000.)
857 snprintf(buf, len, "%.1fGB", bytes / 1000000000.);
858 else if (bytes > 1000000.)
859 snprintf(buf, len, "%.1fMB", bytes / 1000000.);
860 else if (bytes > 1000.)
861 snprintf(buf, len, "%.1fkB", bytes / 1000.);
862 else
863 snprintf(buf, len, "%.0f", bytes);
865 return buf;
868 static char *rate2str(double rate, char *buf, size_t len)
870 const char * const unit_fmt[2][4] = {
871 { "%.1fGbit/s", "%.1fMbit/s", "%.1fkbit/s", "%.0fbit/s" },
872 { "%.1fGB/s", "%.1fMB/s", "%.1fkB/s", "%.0fB/s" }
875 if (rate <= 0) {
876 buf[0] = '\0';
877 return buf;
880 if (rate_type == RATE_BITS)
881 rate *= 8;
883 if (rate > 1000000000.)
884 snprintf(buf, len, unit_fmt[rate_type][0], rate / 1000000000.);
885 else if (rate > 1000000.)
886 snprintf(buf, len, unit_fmt[rate_type][1], rate / 1000000.);
887 else if (rate > 1000.)
888 snprintf(buf, len, unit_fmt[rate_type][2], rate / 1000.);
889 else
890 snprintf(buf, len, unit_fmt[rate_type][3], rate);
892 return buf;
895 static char *time2str(uint64_t tstamp, char *str, size_t len)
897 time_t now;
898 int v, s;
900 time(&now);
902 s = now - (tstamp ? (tstamp / NSEC_PER_SEC) : now);
903 if (s <= 0) {
904 str[0] = '\0';
905 return str;
908 v = s / (3600 * 24);
909 if (v > 0) {
910 slprintf(str, len, "%dd", v);
911 return str;
914 v = s / 3600;
915 if (v > 0) {
916 slprintf(str, len, "%dh", v);
917 return str;
920 v = s / 60;
921 if (v > 0) {
922 slprintf(str, len, "%dm", v);
923 return str;
926 slprintf(str, len, "%ds", s);
927 return str;
931 static const char *flow_state2str(const struct flow_entry *n)
933 switch (n->l4_proto) {
934 case IPPROTO_TCP:
935 return tcp_state2str[n->tcp_state];
936 case IPPROTO_SCTP:
937 return sctp_state2str[n->sctp_state];
938 case IPPROTO_DCCP:
939 return dccp_state2str[n->dccp_state];
941 case IPPROTO_UDP:
942 case IPPROTO_UDPLITE:
943 case IPPROTO_ICMP:
944 case IPPROTO_ICMPV6:
945 default:
946 return "";
950 static char *flow_port2str(const struct flow_entry *n, char *str, size_t len,
951 enum flow_direction dir)
953 const char *tmp = NULL;
954 uint16_t port = 0;
956 port = SELFLD(dir, port_src, port_dst);
957 tmp = NULL;
959 switch (n->l4_proto) {
960 case IPPROTO_TCP:
961 tmp = lookup_port_tcp(port);
962 break;
963 case IPPROTO_UDP:
964 case IPPROTO_UDPLITE:
965 tmp = lookup_port_udp(port);
966 break;
969 if (!tmp && port)
970 slprintf(str, len, "%d", port);
971 else
972 slprintf(str, len, "%s", tmp ? tmp : "");
974 return str;
977 static void print_flow_peer_info(const struct flow_entry *n, enum flow_direction dir)
979 int counters_color = COLOR(YELLOW, BLACK);
980 int src_color = COLOR(RED, BLACK);
981 int dst_color = COLOR(BLUE, BLACK);
982 int country_color = COLOR(GREEN, BLACK);
983 int addr_color = dst_color;
984 int port_color = A_BOLD;
985 char tmp[128];
987 if (show_src && dir == FLOW_DIR_SRC) {
988 country_color = src_color;
989 counters_color = src_color;
990 port_color |= src_color;
991 addr_color = src_color;
992 } else if (show_src && FLOW_DIR_DST) {
993 country_color = dst_color;
994 counters_color = dst_color;
995 port_color |= dst_color;
996 addr_color = dst_color;
999 ui_table_col_color_set(&flows_tbl, TBL_FLOW_ADDRESS, addr_color);
1000 ui_table_col_color_set(&flows_tbl, TBL_FLOW_PORT, port_color);
1001 ui_table_col_color_set(&flows_tbl, TBL_FLOW_GEO, country_color);
1002 ui_table_col_color_set(&flows_tbl, TBL_FLOW_BYTES, counters_color);
1003 ui_table_col_color_set(&flows_tbl, TBL_FLOW_RATE, counters_color);
1005 /* Reverse DNS/IP */
1006 ui_table_row_col_set(&flows_tbl, TBL_FLOW_ADDRESS,
1007 SELFLD(dir, rev_dns_src, rev_dns_dst));
1009 /* Application port */
1010 ui_table_row_col_set(&flows_tbl, TBL_FLOW_PORT,
1011 flow_port2str(n, tmp, sizeof(tmp), dir));
1013 /* GEO */
1014 ui_table_row_col_set(&flows_tbl, TBL_FLOW_GEO,
1015 SELFLD(dir, country_code_src, country_code_dst));
1017 /* Bytes */
1018 ui_table_row_col_set(&flows_tbl, TBL_FLOW_BYTES,
1019 bandw2str(SELFLD(dir, stat.bytes_src, stat.bytes_dst),
1020 tmp, sizeof(tmp) - 1));
1022 /* Rate bytes */
1023 ui_table_row_col_set(&flows_tbl, TBL_FLOW_RATE,
1024 rate2str(SELFLD(dir, stat.rate_bytes_src, stat.rate_bytes_dst),
1025 tmp, sizeof(tmp) - 1));
1028 static void draw_flow_entry(struct ui_table *tbl, const void *data)
1030 const struct flow_entry *n = data;
1031 char tmp[128];
1033 ui_table_row_add(tbl);
1035 /* Application */
1036 ui_table_row_col_set(tbl, TBL_FLOW_PROCESS, n->proc ? n->proc->name : "");
1038 /* PID */
1039 slprintf(tmp, sizeof(tmp), "%.d", n->proc ? n->proc->pid : 0);
1040 ui_table_row_col_set(tbl, TBL_FLOW_PID, tmp);
1042 /* L4 protocol */
1043 ui_table_row_col_set(tbl, TBL_FLOW_PROTO, l4proto2str[n->l4_proto]);
1045 /* L4 protocol state */
1046 ui_table_row_col_set(tbl, TBL_FLOW_STATE, flow_state2str(n));
1048 /* Time */
1049 time2str(n->timestamp_start, tmp, sizeof(tmp));
1050 ui_table_row_col_set(tbl, TBL_FLOW_TIME, tmp);
1052 print_flow_peer_info(n, show_src ? FLOW_DIR_SRC : FLOW_DIR_DST);
1054 ui_table_row_show(tbl);
1056 if (show_src) {
1057 ui_table_row_add(tbl);
1059 ui_table_row_col_set(tbl, TBL_FLOW_PROCESS, "");
1060 ui_table_row_col_set(tbl, TBL_FLOW_PID, "");
1061 ui_table_row_col_set(tbl, TBL_FLOW_PROTO, "");
1062 ui_table_row_col_set(tbl, TBL_FLOW_STATE, "");
1063 ui_table_row_col_set(tbl, TBL_FLOW_TIME, "");
1065 print_flow_peer_info(n, FLOW_DIR_DST);
1066 ui_table_row_show(tbl);
1070 static inline bool presenter_flow_wrong_state(struct flow_entry *n)
1072 switch (n->l4_proto) {
1073 case IPPROTO_TCP:
1074 switch (n->tcp_state) {
1075 case TCP_CONNTRACK_SYN_SENT:
1076 case TCP_CONNTRACK_SYN_RECV:
1077 case TCP_CONNTRACK_ESTABLISHED:
1078 case TCP_CONNTRACK_FIN_WAIT:
1079 case TCP_CONNTRACK_CLOSE_WAIT:
1080 case TCP_CONNTRACK_LAST_ACK:
1081 case TCP_CONNTRACK_TIME_WAIT:
1082 case TCP_CONNTRACK_CLOSE:
1083 case TCP_CONNTRACK_SYN_SENT2:
1084 case TCP_CONNTRACK_NONE:
1085 return false;
1086 break;
1088 break;
1089 case IPPROTO_SCTP:
1090 switch (n->sctp_state) {
1091 case SCTP_CONNTRACK_NONE:
1092 case SCTP_CONNTRACK_CLOSED:
1093 case SCTP_CONNTRACK_COOKIE_WAIT:
1094 case SCTP_CONNTRACK_COOKIE_ECHOED:
1095 case SCTP_CONNTRACK_ESTABLISHED:
1096 case SCTP_CONNTRACK_SHUTDOWN_SENT:
1097 case SCTP_CONNTRACK_SHUTDOWN_RECD:
1098 case SCTP_CONNTRACK_SHUTDOWN_ACK_SENT:
1099 return false;
1100 break;
1102 break;
1103 case IPPROTO_DCCP:
1104 switch (n->dccp_state) {
1105 case DCCP_CONNTRACK_NONE:
1106 case DCCP_CONNTRACK_REQUEST:
1107 case DCCP_CONNTRACK_RESPOND:
1108 case DCCP_CONNTRACK_PARTOPEN:
1109 case DCCP_CONNTRACK_OPEN:
1110 case DCCP_CONNTRACK_CLOSEREQ:
1111 case DCCP_CONNTRACK_CLOSING:
1112 case DCCP_CONNTRACK_TIMEWAIT:
1113 case DCCP_CONNTRACK_IGNORE:
1114 case DCCP_CONNTRACK_INVALID:
1115 return false;
1116 break;
1118 break;
1119 case IPPROTO_UDP:
1120 case IPPROTO_UDPLITE:
1121 case IPPROTO_ICMP:
1122 case IPPROTO_ICMPV6:
1123 return false;
1124 break;
1127 return true;
1130 static void draw_filter_status(struct ui_table *tbl, char *title)
1132 mvwprintw(screen, 1, 0, "%*s", COLS - 1, " ");
1133 mvwprintw(screen, 1, 2, "%s(%u) for ", title, ui_table_data_count(tbl));
1135 if (what & INCLUDE_IPV4)
1136 printw("IPv4,");
1137 if (what & INCLUDE_IPV6)
1138 printw("IPv6,");
1139 if (what & INCLUDE_TCP)
1140 printw("TCP,");
1141 if (what & INCLUDE_UDP)
1142 printw("UDP,");
1143 if (what & INCLUDE_SCTP)
1144 printw("SCTP,");
1145 if (what & INCLUDE_DCCP)
1146 printw("DCCP,");
1147 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1148 printw("ICMP,");
1149 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1150 printw("ICMP6,");
1151 if (show_active_only)
1152 printw("Active,");
1154 printw(" [+%d]", ui_table_scroll_height(tbl));
1156 if (is_flow_collecting)
1157 printw(" [Collecting flows ...]");
1161 static void draw_flows(WINDOW *screen, struct flow_list *fl)
1163 rcu_read_lock();
1165 if (cds_list_empty(&fl->head))
1166 mvwprintw(screen, 4, 2, "(No sessions! "
1167 "Is netfilter running?)");
1169 ui_table_data_bind(&flows_tbl);
1171 rcu_read_unlock();
1173 draw_filter_status(&flows_tbl, "Kernel netfilter flows");
1176 static void draw_proc_entry(struct ui_table *tbl, const void *data)
1178 const struct proc_entry *p = data;
1179 char tmp[128];
1181 ui_table_row_add(tbl);
1183 /* Application */
1184 ui_table_row_col_set(tbl, TBL_PROC_NAME, p->name);
1186 /* PID */
1187 slprintf(tmp, sizeof(tmp), "%.d", p->pid);
1188 ui_table_row_col_set(tbl, TBL_PROC_PID, tmp);
1190 /* Flows */
1191 slprintf(tmp, sizeof(tmp), "%.d", p->flows_count);
1192 ui_table_row_col_set(tbl, TBL_PROC_FLOWS, tmp);
1194 /* Bytes Src */
1195 bandw2str(p->stat.bytes_src, tmp, sizeof(tmp) - 1);
1196 ui_table_row_col_set(tbl, TBL_PROC_BYTES_SRC, tmp);
1198 /* Rate Src */
1199 rate2str(p->stat.rate_bytes_src, tmp, sizeof(tmp) - 1);
1200 ui_table_row_col_set(tbl, TBL_PROC_RATE_SRC, tmp);
1202 /* Bytes Dest */
1203 bandw2str(p->stat.bytes_dst, tmp, sizeof(tmp) - 1);
1204 ui_table_row_col_set(tbl, TBL_PROC_BYTES_DST, tmp);
1206 /* Rate Dest */
1207 rate2str(p->stat.rate_bytes_dst, tmp, sizeof(tmp) - 1);
1208 ui_table_row_col_set(tbl, TBL_PROC_RATE_DST, tmp);
1210 ui_table_row_show(tbl);
1213 static void draw_procs(WINDOW *screen, struct flow_list *fl)
1215 rcu_read_lock();
1217 ui_table_data_bind(&procs_tbl);
1219 rcu_read_unlock();
1221 draw_filter_status(&procs_tbl, "Processes");
1224 static void draw_help(void)
1226 int col = 0;
1227 int row = 1;
1228 int i;
1230 mvaddch(row, col, ACS_ULCORNER);
1231 mvaddch(rows - row - 1, col, ACS_LLCORNER);
1233 mvaddch(row, cols - 1, ACS_URCORNER);
1234 mvaddch(rows - row - 1, cols - 1, ACS_LRCORNER);
1236 for (i = 1; i < rows - row - 2; i++) {
1237 mvaddch(row + i, 0, ACS_VLINE);
1238 mvaddch(row + i, cols - 1, ACS_VLINE);
1240 for (i = 1; i < cols - col - 1; i++) {
1241 mvaddch(row, col + i, ACS_HLINE);
1242 mvaddch(rows - row - 1, col + i, ACS_HLINE);
1245 attron(A_BOLD);
1246 mvaddnstr(row, cols / 2 - 2, "| Help |", -1);
1248 attron(A_UNDERLINE);
1249 mvaddnstr(row + 2, col + 2, "Navigation", -1);
1250 attroff(A_BOLD | A_UNDERLINE);
1252 mvaddnstr(row + 4, col + 3, "TAB Go to next tab panel", -1);
1253 mvaddnstr(row + 5, col + 3, "Up, u, k Move up", -1);
1254 mvaddnstr(row + 6, col + 3, "Down, d, j Move down", -1);
1255 mvaddnstr(row + 7, col + 3, "Left,l Scroll left", -1);
1256 mvaddnstr(row + 8, col + 3, "Right,h Scroll right", -1);
1257 mvaddnstr(row + 9, col + 3, "? Toggle help window", -1);
1258 mvaddnstr(row + 10, col + 3, "q, Ctrl+C Quit", -1);
1260 attron(A_BOLD | A_UNDERLINE);
1261 mvaddnstr(row + 12, col + 2, "Display Settings", -1);
1262 attroff(A_BOLD | A_UNDERLINE);
1264 mvaddnstr(row + 14, col + 3, "b Toggle rate units (bits/bytes)", -1);
1265 mvaddnstr(row + 15, col + 3, "a Toggle display of active flows (rate > 0) only", -1);
1266 mvaddnstr(row + 16, col + 3, "s Toggle show source peer info", -1);
1268 mvaddnstr(row + 18, col + 3, "T Toggle display TCP flows", -1);
1269 mvaddnstr(row + 19, col + 3, "U Toggle display UDP flows", -1);
1270 mvaddnstr(row + 20, col + 3, "D Toggle display DCCP flows", -1);
1271 mvaddnstr(row + 21, col + 3, "I Toggle display ICMP flows", -1);
1272 mvaddnstr(row + 22, col + 3, "S Toggle display SCTP flows", -1);
1275 static void draw_header(WINDOW *screen)
1277 int i;
1279 attron(A_STANDOUT);
1281 for (i = 0; i < cols; i++)
1282 mvaddch(0, i, ' ');
1284 mvwprintw(screen, 0, 2, "flowtop %s", VERSION_LONG);
1285 attroff(A_STANDOUT);
1288 static void draw_footer(void)
1290 int i;
1292 attron(A_STANDOUT);
1294 for (i = 0; i < cols; i++)
1295 mvaddch(rows - 1, i, ' ');
1297 mvaddnstr(rows - 1, 1, "Press '?' for help", -1);
1298 addch(ACS_VLINE);
1299 attroff(A_STANDOUT);
1302 static void show_option_toggle(int opt)
1304 switch (opt) {
1305 case 'T':
1306 TOGGLE_FLAG(what, INCLUDE_TCP);
1307 break;
1308 case 'U':
1309 TOGGLE_FLAG(what, INCLUDE_UDP);
1310 break;
1311 case 'D':
1312 TOGGLE_FLAG(what, INCLUDE_DCCP);
1313 break;
1314 case 'I':
1315 TOGGLE_FLAG(what, INCLUDE_ICMP);
1316 break;
1317 case 'S':
1318 TOGGLE_FLAG(what, INCLUDE_SCTP);
1319 break;
1323 void * flows_iter(void *data)
1325 struct flow_entry *n = data;
1327 do {
1328 n = list_first_or_next(n, &flow_list.head, entry);
1329 } while (n && (!n->is_visible || presenter_flow_wrong_state(n)));
1331 return n;
1334 static void flows_table_init(struct ui_table *tbl)
1336 ui_table_init(tbl);
1338 ui_table_pos_set(tbl, 3, 0);
1339 ui_table_height_set(tbl, LINES - 3);
1341 ui_table_col_add(tbl, TBL_FLOW_PROCESS, "PROCESS", 13);
1342 ui_table_col_add(tbl, TBL_FLOW_PID, "PID", 7);
1343 ui_table_col_add(tbl, TBL_FLOW_PROTO, "PROTO", 6);
1344 ui_table_col_add(tbl, TBL_FLOW_STATE, "STATE", 11);
1345 ui_table_col_add(tbl, TBL_FLOW_TIME, "TIME", 4);
1346 ui_table_col_add(tbl, TBL_FLOW_ADDRESS, "ADDRESS", 50);
1347 ui_table_col_add(tbl, TBL_FLOW_PORT, "PORT", 8);
1348 ui_table_col_add(tbl, TBL_FLOW_GEO, "GEO", 3);
1349 ui_table_col_add(tbl, TBL_FLOW_BYTES, "BYTES", 10);
1350 ui_table_col_add(tbl, TBL_FLOW_RATE, "RATE", 10);
1352 ui_table_col_align_set(tbl, TBL_FLOW_TIME, UI_ALIGN_RIGHT);
1353 ui_table_col_align_set(tbl, TBL_FLOW_BYTES, UI_ALIGN_RIGHT);
1354 ui_table_col_align_set(tbl, TBL_FLOW_RATE, UI_ALIGN_RIGHT);
1356 ui_table_col_color_set(tbl, TBL_FLOW_PROCESS, COLOR(YELLOW, BLACK));
1357 ui_table_col_color_set(tbl, TBL_FLOW_PID, A_BOLD);
1358 ui_table_col_color_set(tbl, TBL_FLOW_STATE, COLOR(YELLOW, BLACK));
1360 ui_table_header_color_set(&flows_tbl, COLOR(BLACK, GREEN));
1362 ui_table_data_bind_set(tbl, draw_flow_entry);
1363 ui_table_data_iter_set(tbl, flows_iter);
1366 void * procs_iter(void *data)
1368 struct proc_entry *p = data;
1370 return list_first_or_next(p, &proc_list.head, entry);
1373 static void procs_table_init(struct ui_table *tbl)
1375 ui_table_init(tbl);
1377 ui_table_pos_set(tbl, 3, 0);
1378 ui_table_height_set(tbl, LINES - 3);
1380 ui_table_col_add(tbl, TBL_PROC_NAME, "NAME", 13);
1381 ui_table_col_add(tbl, TBL_PROC_PID, "PID", 7);
1382 ui_table_col_add(tbl, TBL_PROC_FLOWS, "FLOWS", 7);
1383 ui_table_col_add(tbl, TBL_PROC_BYTES_SRC, "BYTES_SRC", 10);
1384 ui_table_col_add(tbl, TBL_PROC_BYTES_DST, "BYTES_DST", 10);
1385 ui_table_col_add(tbl, TBL_PROC_RATE_SRC, "RATE_SRC", 14);
1386 ui_table_col_add(tbl, TBL_PROC_RATE_DST, "RATE_DST", 14);
1388 ui_table_col_align_set(tbl, TBL_PROC_BYTES_SRC, UI_ALIGN_RIGHT);
1389 ui_table_col_align_set(tbl, TBL_PROC_RATE_SRC, UI_ALIGN_RIGHT);
1390 ui_table_col_align_set(tbl, TBL_PROC_BYTES_DST, UI_ALIGN_RIGHT);
1391 ui_table_col_align_set(tbl, TBL_PROC_RATE_DST, UI_ALIGN_RIGHT);
1393 ui_table_col_color_set(tbl, TBL_PROC_NAME, COLOR(YELLOW, BLACK));
1394 ui_table_col_color_set(tbl, TBL_PROC_PID, A_BOLD);
1395 ui_table_col_color_set(tbl, TBL_PROC_FLOWS, COLOR(YELLOW, BLACK));
1396 ui_table_col_color_set(tbl, TBL_PROC_BYTES_SRC, COLOR(RED, BLACK));
1397 ui_table_col_color_set(tbl, TBL_PROC_RATE_SRC, COLOR(RED, BLACK));
1398 ui_table_col_color_set(tbl, TBL_PROC_BYTES_DST, COLOR(BLUE, BLACK));
1399 ui_table_col_color_set(tbl, TBL_PROC_RATE_DST, COLOR(BLUE, BLACK));
1401 ui_table_header_color_set(tbl, COLOR(BLACK, GREEN));
1403 ui_table_data_bind_set(tbl, draw_proc_entry);
1404 ui_table_data_iter_set(tbl, procs_iter);
1407 static void tab_main_on_open(struct ui_tab *tab, enum ui_tab_event_t evt, uint32_t id)
1409 if (evt != UI_TAB_EVT_OPEN)
1410 return;
1412 if (id == TAB_FLOWS) {
1413 draw_flows(screen, &flow_list);
1414 curr_tbl = &flows_tbl;
1415 } else if (id == TAB_PROCS) {
1416 draw_procs(screen, &flow_list);
1417 curr_tbl = &procs_tbl;
1421 static void presenter(void)
1423 bool show_help = false;
1424 struct ui_tab *tab_main;
1426 lookup_init(LT_PORTS_TCP);
1427 lookup_init(LT_PORTS_UDP);
1429 screen = screen_init(false);
1430 wclear(screen);
1431 halfdelay(1);
1433 start_color();
1434 INIT_COLOR(RED, BLACK);
1435 INIT_COLOR(BLUE, BLACK);
1436 INIT_COLOR(YELLOW, BLACK);
1437 INIT_COLOR(GREEN, BLACK);
1438 INIT_COLOR(BLACK, GREEN);
1440 flows_table_init(&flows_tbl);
1441 procs_table_init(&procs_tbl);
1443 tab_main = ui_tab_create();
1444 ui_tab_event_cb_set(tab_main, tab_main_on_open);
1445 ui_tab_pos_set(tab_main, 2, 0);
1446 ui_tab_active_color_set(tab_main, COLOR(BLACK, GREEN));
1447 ui_tab_entry_add(tab_main, TAB_FLOWS, "Flows");
1448 ui_tab_entry_add(tab_main, TAB_PROCS, "Processes");
1450 rcu_register_thread();
1451 while (!sigint) {
1452 int ch;
1454 curs_set(0);
1455 getmaxyx(screen, rows, cols);
1457 ch = getch();
1458 switch (ch) {
1459 case 'q':
1460 sigint = 1;
1461 break;
1462 case KEY_UP:
1463 case 'u':
1464 case 'k':
1465 ui_table_event_send(curr_tbl, UI_EVT_SCROLL_UP);
1466 break;
1467 case KEY_DOWN:
1468 case 'd':
1469 case 'j':
1470 ui_table_event_send(curr_tbl, UI_EVT_SCROLL_DOWN);
1471 break;
1472 case KEY_LEFT:
1473 case 'h':
1474 ui_table_event_send(curr_tbl, UI_EVT_SCROLL_LEFT);
1475 break;
1476 case KEY_RIGHT:
1477 case 'l':
1478 ui_table_event_send(curr_tbl, UI_EVT_SCROLL_RIGHT);
1479 break;
1480 case 'b':
1481 if (rate_type == RATE_BYTES)
1482 rate_type = RATE_BITS;
1483 else
1484 rate_type = RATE_BYTES;
1485 break;
1486 case 'a':
1487 show_active_only = !show_active_only;
1488 break;
1489 case 's':
1490 show_src = !show_src;
1491 break;
1492 case '?':
1493 show_help = !show_help;
1494 wclear(screen);
1495 clear();
1496 break;
1497 case 'T':
1498 case 'U':
1499 case 'D':
1500 case 'I':
1501 case 'S':
1502 show_option_toggle(ch);
1503 do_reload_flows = true;
1504 break;
1505 case '\t':
1506 ui_tab_event_send(tab_main, UI_EVT_SELECT_NEXT);
1507 break;
1508 default:
1509 fflush(stdin);
1510 break;
1513 draw_header(screen);
1515 if (show_help)
1516 draw_help();
1517 else
1518 ui_tab_show(tab_main);
1520 draw_footer();
1522 rcu_unregister_thread();
1524 ui_table_uninit(&flows_tbl);
1525 ui_table_uninit(&procs_tbl);
1526 ui_tab_destroy(tab_main);
1528 screen_end();
1529 lookup_cleanup(LT_PORTS_UDP);
1530 lookup_cleanup(LT_PORTS_TCP);
1533 static void restore_sysctl(void *obj)
1535 struct sysctl_params_ctx *sysctl_ctx = obj;
1537 if (sysctl_ctx->nfct_acct == 0)
1538 sysctl_set_int("net/netfilter/nf_conntrack_acct",
1539 sysctl_ctx->nfct_acct);
1541 if (sysctl_ctx->nfct_tstamp == 0)
1542 sysctl_set_int("net/netfilter/nf_conntrack_timestamp",
1543 sysctl_ctx->nfct_tstamp);
1546 static void on_panic_handler(void *arg)
1548 restore_sysctl(arg);
1549 screen_end();
1552 static void conntrack_acct_enable(void)
1554 /* We can still work w/o traffic accounting so just warn about error */
1555 if (sysctl_get_int("net/netfilter/nf_conntrack_acct", &sysctl.nfct_acct)) {
1556 fprintf(stderr, "Can't read net/netfilter/nf_conntrack_acct: %s\n",
1557 strerror(errno));
1558 return;
1561 if (sysctl.nfct_acct == 1)
1562 return;
1564 if (sysctl_set_int("net/netfilter/nf_conntrack_acct", 1)) {
1565 fprintf(stderr, "Can't write net/netfilter/nf_conntrack_acct: %s\n",
1566 strerror(errno));
1570 static void conntrack_tstamp_enable(void)
1572 if (sysctl_get_int("net/netfilter/nf_conntrack_timestamp", &sysctl.nfct_tstamp)) {
1573 fprintf(stderr, "Can't read net/netfilter/nf_conntrack_timestamp: %s\n",
1574 strerror(errno));
1575 return;
1578 if (sysctl.nfct_tstamp == 1)
1579 return;
1581 if (sysctl_set_int("net/netfilter/nf_conntrack_timestamp", 1)) {
1582 fprintf(stderr, "Can't write net/netfilter/nf_conntrack_timestamp: %s\n",
1583 strerror(errno));
1587 static void flow_entry_filter(struct flow_entry *n)
1589 if (show_active_only && !n->stat.rate_bytes_src && !n->stat.rate_bytes_dst)
1590 n->is_visible = false;
1591 else
1592 n->is_visible = true;
1595 static int flow_list_update_entry(struct flow_list *fl, struct nf_conntrack *ct)
1597 struct flow_entry *n;
1599 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
1600 if (!n)
1601 return NFCT_CB_CONTINUE;
1603 flow_entry_calc_rate(n, ct);
1604 flow_entry_update_time(n);
1605 flow_entry_from_ct(n, ct);
1606 flow_entry_filter(n);
1608 return NFCT_CB_CONTINUE;
1611 static int flow_event_cb(enum nf_conntrack_msg_type type,
1612 struct nf_conntrack *ct, void *data __maybe_unused)
1614 if (sigint)
1615 return NFCT_CB_STOP;
1617 switch (type) {
1618 case NFCT_T_NEW:
1619 return flow_list_new_entry(&flow_list, ct);
1620 case NFCT_T_UPDATE:
1621 return flow_list_update_entry(&flow_list, ct);
1622 case NFCT_T_DESTROY:
1623 return flow_list_del_entry(&flow_list, ct);
1624 default:
1625 return NFCT_CB_CONTINUE;
1629 static void collector_refresh_procs(void)
1631 struct proc_entry *p, *tmp;
1633 cds_list_for_each_entry_safe(p, tmp, &proc_list.head, entry) {
1634 double sec = (double)time_after_us(&p->last_update) / USEC_PER_SEC;
1635 struct flow_entry *n;
1637 if (sec < 1)
1638 continue;
1640 bug_on(gettimeofday(&p->last_update, NULL));
1642 if (!p->flows_count && !proc_exists(p->pid)) {
1643 cds_list_del_rcu(&p->entry);
1644 call_rcu(&p->rcu, proc_entry_xfree_rcu);
1645 continue;
1648 p->stat.rate_bytes_src = 0;
1649 p->stat.rate_bytes_dst = 0;
1650 p->stat.rate_pkts_src = 0;
1651 p->stat.rate_pkts_dst = 0;
1653 cds_list_for_each_entry_rcu(n, &p->flows, proc_head) {
1654 p->stat.rate_bytes_src += n->stat.rate_bytes_src;
1655 p->stat.rate_bytes_dst += n->stat.rate_bytes_dst;
1656 p->stat.rate_pkts_src += n->stat.rate_pkts_src;
1657 p->stat.rate_pkts_dst += n->stat.rate_pkts_dst;
1662 static void collector_refresh_flows(struct nfct_handle *handle)
1664 struct flow_entry *n;
1666 cds_list_for_each_entry_rcu(n, &flow_list.head, entry) {
1667 nfct_query(handle, NFCT_Q_GET, n->ct);
1671 static void collector_create_filter(struct nfct_handle *nfct)
1673 struct nfct_filter *filter;
1674 int ret;
1676 filter = nfct_filter_create();
1677 if (!filter)
1678 panic("Cannot create a nfct filter: %s\n", strerror(errno));
1680 if (what & INCLUDE_UDP) {
1681 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1682 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
1684 if (what & INCLUDE_TCP)
1685 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1686 if (what & INCLUDE_DCCP)
1687 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1688 if (what & INCLUDE_SCTP)
1689 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1690 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1691 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1692 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1693 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1694 if (what & INCLUDE_IPV4) {
1695 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4, NFCT_FILTER_LOGIC_NEGATIVE);
1696 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1698 if (what & INCLUDE_IPV6) {
1699 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6, NFCT_FILTER_LOGIC_NEGATIVE);
1700 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1703 ret = nfct_filter_attach(nfct_fd(nfct), filter);
1704 if (ret < 0)
1705 panic("Cannot attach filter to handle: %s\n", strerror(errno));
1707 nfct_filter_destroy(filter);
1710 /* This hand-crafted filter looks ugly but it allows to do not
1711 * flush nfct connections & filter them by user specified filter.
1712 * May be it is better to replace this one by nfct_cmp. */
1713 static int flow_dump_cb(enum nf_conntrack_msg_type type __maybe_unused,
1714 struct nf_conntrack *ct, void *data __maybe_unused)
1716 struct flow_entry fl;
1717 struct flow_entry *n = &fl;
1719 if (sigint)
1720 return NFCT_CB_STOP;
1722 if (!(what & ~(INCLUDE_IPV4 | INCLUDE_IPV6)))
1723 goto check_addr;
1725 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
1727 if (what & INCLUDE_UDP) {
1728 if (n->l4_proto == IPPROTO_UDP)
1729 goto check_addr;
1731 if (n->l4_proto == IPPROTO_UDPLITE)
1732 goto check_addr;
1735 if ((what & INCLUDE_TCP) && n->l4_proto == IPPROTO_TCP)
1736 goto check_addr;
1738 if ((what & INCLUDE_DCCP) && n->l4_proto == IPPROTO_DCCP)
1739 goto check_addr;
1741 if ((what & INCLUDE_SCTP) && n->l4_proto == IPPROTO_SCTP)
1742 goto check_addr;
1744 if ((what & INCLUDE_ICMP) && (what & INCLUDE_IPV4) &&
1745 n->l4_proto == IPPROTO_ICMP) {
1746 goto check_addr;
1749 if ((what & INCLUDE_ICMP) && (what & INCLUDE_IPV6) &&
1750 n->l4_proto == IPPROTO_ICMPV6) {
1751 goto check_addr;
1754 goto skip_flow;
1756 check_addr:
1757 /* filter loopback addresses */
1758 if (what & INCLUDE_IPV4) {
1759 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
1761 if (n->ip4_src_addr == filter_ipv4.addr)
1762 goto skip_flow;
1764 if (what & INCLUDE_IPV6) {
1765 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
1767 if (n->ip6_src_addr[0] == 0x0 &&
1768 n->ip6_src_addr[1] == 0x0 &&
1769 n->ip6_src_addr[2] == 0x0 &&
1770 n->ip6_src_addr[3] == 0x1)
1771 goto skip_flow;
1774 return flow_list_new_entry(&flow_list, ct);
1776 skip_flow:
1777 return NFCT_CB_CONTINUE;
1780 static void collector_dump_flows(void)
1782 struct nfct_handle *nfct = nfct_open(CONNTRACK, 0);
1784 if (!nfct)
1785 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1787 nfct_callback_register(nfct, NFCT_T_ALL, flow_dump_cb, NULL);
1789 is_flow_collecting = true;
1790 if (what & INCLUDE_IPV4) {
1791 int family = AF_INET;
1792 nfct_query(nfct, NFCT_Q_DUMP, &family);
1794 if (what & INCLUDE_IPV6) {
1795 int family = AF_INET6;
1796 nfct_query(nfct, NFCT_Q_DUMP, &family);
1798 is_flow_collecting = false;
1800 nfct_close(nfct);
1803 static void *collector(void *null __maybe_unused)
1805 struct nfct_handle *ct_event;
1806 struct pollfd poll_fd[1];
1808 proc_list_init(&proc_list);
1809 flow_list_init(&flow_list);
1811 ct_event = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1812 NF_NETLINK_CONNTRACK_UPDATE |
1813 NF_NETLINK_CONNTRACK_DESTROY);
1814 if (!ct_event)
1815 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1817 collector_create_filter(ct_event);
1819 nfct_callback_register(ct_event, NFCT_T_ALL, flow_event_cb, NULL);
1821 poll_fd[0].fd = nfct_fd(ct_event);
1822 poll_fd[0].events = POLLIN;
1824 if (fcntl(nfct_fd(ct_event), F_SETFL, O_NONBLOCK) == -1)
1825 panic("Cannot set non-blocking socket: fcntl(): %s\n",
1826 strerror(errno));
1828 rcu_register_thread();
1830 collector_dump_flows();
1832 while (!sigint) {
1833 int status;
1835 if (!do_reload_flows) {
1836 usleep(USEC_PER_SEC * interval);
1837 } else {
1838 do_reload_flows = false;
1840 flow_list_destroy(&flow_list);
1842 collector_create_filter(ct_event);
1843 collector_dump_flows();
1846 collector_refresh_procs();
1847 collector_refresh_flows(ct_event);
1849 status = poll(poll_fd, 1, 0);
1850 if (status < 0) {
1851 if (errno == EAGAIN || errno == EINTR)
1852 continue;
1854 panic("Error while polling: %s\n", strerror(errno));
1855 } else if (status != 0) {
1856 if (poll_fd[0].revents & POLLIN)
1857 nfct_catch(ct_event);
1861 flow_list_destroy(&flow_list);
1862 proc_list_destroy(&proc_list);
1864 rcu_unregister_thread();
1866 nfct_close(ct_event);
1868 pthread_exit(NULL);
1871 int main(int argc, char **argv)
1873 pthread_t tid;
1874 int ret, c, what_cmd = 0;
1876 setfsuid(getuid());
1877 setfsgid(getgid());
1879 while ((c = getopt_long(argc, argv, short_options, long_options,
1880 NULL)) != EOF) {
1881 switch (c) {
1882 case '4':
1883 what_cmd |= INCLUDE_IPV4;
1884 break;
1885 case '6':
1886 what_cmd |= INCLUDE_IPV6;
1887 break;
1888 case 'T':
1889 what_cmd |= INCLUDE_TCP;
1890 break;
1891 case 'U':
1892 what_cmd |= INCLUDE_UDP;
1893 break;
1894 case 'D':
1895 what_cmd |= INCLUDE_DCCP;
1896 break;
1897 case 'I':
1898 what_cmd |= INCLUDE_ICMP;
1899 break;
1900 case 'S':
1901 what_cmd |= INCLUDE_SCTP;
1902 break;
1903 case 's':
1904 show_src = true;
1905 break;
1906 case 'b':
1907 rate_type = RATE_BITS;
1908 break;
1909 case 'u':
1910 update_geoip();
1911 die();
1912 break;
1913 case 't':
1914 interval = strtoul(optarg, NULL, 10);
1915 break;
1916 case 'n':
1917 resolve_dns = false;
1918 break;
1919 case 'G':
1920 resolve_geoip = false;
1921 break;
1922 case 'h':
1923 help();
1924 break;
1925 case 'v':
1926 version();
1927 break;
1928 default:
1929 break;
1933 if (what_cmd > 0) {
1934 what = what_cmd;
1936 if (!(what & (INCLUDE_IPV4 | INCLUDE_IPV6)))
1937 what |= INCLUDE_IPV4 | INCLUDE_IPV6;
1940 rcu_init();
1942 register_signal(SIGINT, signal_handler);
1943 register_signal(SIGQUIT, signal_handler);
1944 register_signal(SIGTERM, signal_handler);
1945 register_signal(SIGHUP, signal_handler);
1947 panic_handler_add(on_panic_handler, &sysctl);
1949 conntrack_acct_enable();
1950 conntrack_tstamp_enable();
1952 if (resolve_geoip)
1953 init_geoip(1);
1955 ret = pthread_create(&tid, NULL, collector, NULL);
1956 if (ret < 0)
1957 panic("Cannot create phthread!\n");
1959 presenter();
1961 if (resolve_geoip)
1962 destroy_geoip();
1964 restore_sysctl(&sysctl);
1966 return 0;