trafgen: fix packet socket initialization with multiple CPUs
[netsniff-ng.git] / flowtop.c
blob0a3c514bc05a8b88140f6007624ee800518e6ea6
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 int flow_list_del_entry(struct flow_list *fl, const struct nf_conntrack *ct)
475 struct flow_entry *n;
477 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
478 if (n) {
479 if (n->proc) {
480 cds_list_del(&n->proc_head);
481 n->proc->flows_count--;
484 cds_list_del_rcu(&n->entry);
485 call_rcu(&n->rcu, flow_entry_xfree_rcu);
488 return NFCT_CB_CONTINUE;
491 static void flow_list_destroy(struct flow_list *fl)
493 struct flow_entry *n, *tmp;
495 cds_list_for_each_entry_safe(n, tmp, &fl->head, entry) {
496 cds_list_del_rcu(&n->entry);
497 call_rcu(&n->rcu, flow_entry_xfree_rcu);
501 static void proc_list_init(struct proc_list *proc_list)
503 CDS_INIT_LIST_HEAD(&proc_list->head);
506 static struct proc_entry *proc_list_new_entry(unsigned int pid)
508 struct proc_entry *proc;
510 cds_list_for_each_entry(proc, &proc_list.head, entry) {
511 if (proc->pid && proc->pid == pid)
512 return proc;
515 proc = xzmalloc(sizeof(*proc));
517 bug_on(gettimeofday(&proc->last_update, NULL));
518 CDS_INIT_LIST_HEAD(&proc->flows);
519 proc->pid = pid;
521 cds_list_add_tail(&proc->entry, &proc_list.head);
523 return proc;
526 static void proc_entry_xfree_rcu(struct rcu_head *head)
528 struct proc_entry *p = container_of(head, struct proc_entry, rcu);
530 xfree(p);
533 static void proc_list_destroy(struct proc_list *pl)
535 struct proc_entry *p, *tmp;
537 cds_list_for_each_entry_safe(p, tmp, &pl->head, entry) {
538 cds_list_del_rcu(&p->entry);
539 call_rcu(&p->rcu, proc_entry_xfree_rcu);
543 static void flow_entry_find_process(struct flow_entry *n)
545 struct proc_entry *p;
546 char cmdline[512];
547 pid_t pid;
548 int ret;
550 ret = proc_find_by_inode(n->inode, cmdline, sizeof(cmdline), &pid);
551 if (ret <= 0)
552 return;
554 p = proc_list_new_entry(pid);
556 if (snprintf(p->name, sizeof(p->name), "%s", basename(cmdline)) < 0)
557 p->name[0] = '\0';
559 p->stat.pkts_src += n->stat.pkts_src;
560 p->stat.pkts_dst += n->stat.pkts_dst;
561 p->stat.bytes_src += n->stat.bytes_src;
562 p->stat.bytes_dst += n->stat.bytes_dst;
563 p->flows_count++;
565 cds_list_add(&n->proc_head, &p->flows);
566 n->proc = p;
569 static int get_port_inode(uint16_t port, int proto, bool is_ip6)
571 int ret = -ENOENT;
572 char path[128], buff[1024];
573 FILE *proc;
575 memset(path, 0, sizeof(path));
576 snprintf(path, sizeof(path), "/proc/net/%s%s",
577 l4proto2str[proto], is_ip6 ? "6" : "");
579 proc = fopen(path, "r");
580 if (!proc)
581 return -EIO;
583 memset(buff, 0, sizeof(buff));
585 while (fgets(buff, sizeof(buff), proc) != NULL) {
586 int inode = 0;
587 unsigned int lport = 0;
589 buff[sizeof(buff) - 1] = 0;
590 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
591 "%*X %*u %*u %u", &lport, &inode) == 2) {
592 if ((uint16_t) lport == port) {
593 ret = inode;
594 break;
598 memset(buff, 0, sizeof(buff));
601 fclose(proc);
602 return ret;
605 #define CP_NFCT(elem, attr, x) \
606 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
607 #define CP_NFCT_BUFF(elem, attr) do { \
608 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
609 if (buff != NULL) \
610 memcpy(n->elem, buff, sizeof(n->elem)); \
611 } while (0)
613 static void flow_entry_from_ct(struct flow_entry *n, const struct nf_conntrack *ct)
615 uint64_t bytes_src = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_BYTES);
616 uint64_t bytes_dst = nfct_get_attr_u64(ct, ATTR_REPL_COUNTER_BYTES);
617 uint64_t pkts_src = nfct_get_attr_u64(ct, ATTR_ORIG_COUNTER_PACKETS);
618 uint64_t pkts_dst = nfct_get_attr_u64(ct, ATTR_REPL_COUNTER_PACKETS);
620 /* Update stats diff to the related process entry */
621 if (n->proc) {
622 n->proc->stat.pkts_src += pkts_src - n->stat.pkts_src;
623 n->proc->stat.pkts_dst += pkts_dst - n->stat.pkts_dst;
624 n->proc->stat.bytes_src += bytes_src - n->stat.bytes_src;
625 n->proc->stat.bytes_dst += bytes_dst - n->stat.bytes_dst;
628 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
629 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
631 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
632 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
634 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
635 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
637 CP_NFCT(status, ATTR_STATUS, 32);
639 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
640 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
641 CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
642 CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
644 CP_NFCT(stat.pkts_src, ATTR_ORIG_COUNTER_PACKETS, 64);
645 CP_NFCT(stat.bytes_src, ATTR_ORIG_COUNTER_BYTES, 64);
647 CP_NFCT(stat.pkts_dst, ATTR_REPL_COUNTER_PACKETS, 64);
648 CP_NFCT(stat.bytes_dst, ATTR_REPL_COUNTER_BYTES, 64);
650 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
651 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
653 CP_NFCT(flow_id, ATTR_ID, 32);
654 CP_NFCT(use, ATTR_USE, 32);
656 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
657 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
659 n->port_src = ntohs(n->port_src);
660 n->port_dst = ntohs(n->port_dst);
662 n->ip4_src_addr = ntohl(n->ip4_src_addr);
663 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
666 #define SELFLD(dir,src_member,dst_member) \
667 (((dir) == FLOW_DIR_SRC) ? n->src_member : n->dst_member)
669 static void flow_entry_get_sain4_obj(const struct flow_entry *n,
670 enum flow_direction dir,
671 struct sockaddr_in *sa)
673 memset(sa, 0, sizeof(*sa));
674 sa->sin_family = PF_INET;
675 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
678 static void flow_entry_get_sain6_obj(const struct flow_entry *n,
679 enum flow_direction dir,
680 struct sockaddr_in6 *sa)
682 memset(sa, 0, sizeof(*sa));
683 sa->sin6_family = PF_INET6;
685 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
686 sizeof(sa->sin6_addr));
689 static void
690 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
691 enum flow_direction dir)
693 struct sockaddr_in sa4;
694 struct sockaddr_in6 sa6;
695 char *city = NULL;
697 switch (n->l3_proto) {
698 default:
699 bug();
701 case AF_INET:
702 flow_entry_get_sain4_obj(n, dir, &sa4);
703 city = geoip4_city_name(&sa4);
704 break;
706 case AF_INET6:
707 flow_entry_get_sain6_obj(n, dir, &sa6);
708 city = geoip6_city_name(&sa6);
709 break;
712 build_bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
714 if (city)
715 strlcpy(SELFLD(dir, city_src, city_dst), city,
716 sizeof(n->city_src));
717 else
718 SELFLD(dir, city_src, city_dst)[0] = '\0';
720 free(city);
723 static void
724 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
725 enum flow_direction dir)
727 struct sockaddr_in sa4;
728 struct sockaddr_in6 sa6;
729 const char *country = NULL;
730 const char *country_code = NULL;
732 switch (n->l3_proto) {
733 default:
734 bug();
736 case AF_INET:
737 flow_entry_get_sain4_obj(n, dir, &sa4);
738 country = geoip4_country_name(&sa4);
739 country_code = geoip4_country_code3_name(&sa4);
740 break;
742 case AF_INET6:
743 flow_entry_get_sain6_obj(n, dir, &sa6);
744 country = geoip6_country_name(&sa6);
745 country_code = geoip6_country_code3_name(&sa6);
746 break;
749 build_bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
751 if (country)
752 strlcpy(SELFLD(dir, country_src, country_dst), country,
753 sizeof(n->country_src));
754 else
755 SELFLD(dir, country_src, country_dst)[0] = '\0';
757 build_bug_on(sizeof(n->country_code_src) != sizeof(n->country_code_dst));
759 if (country_code)
760 strlcpy(SELFLD(dir, country_code_src, country_code_dst),
761 country_code, sizeof(n->country_code_src));
762 else
763 SELFLD(dir, country_code_src, country_code_dst)[0] = '\0';
766 static void flow_entry_get_extended_geo(struct flow_entry *n,
767 enum flow_direction dir)
769 if (resolve_geoip) {
770 flow_entry_geo_city_lookup_generic(n, dir);
771 flow_entry_geo_country_lookup_generic(n, dir);
775 static void flow_entry_get_extended_revdns(struct flow_entry *n,
776 enum flow_direction dir)
778 size_t sa_len;
779 struct sockaddr_in sa4;
780 struct sockaddr_in6 sa6;
781 struct sockaddr *sa;
782 struct hostent *hent;
784 build_bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
786 switch (n->l3_proto) {
787 default:
788 bug();
790 case AF_INET:
791 flow_entry_get_sain4_obj(n, dir, &sa4);
793 if (!resolve_dns) {
794 inet_ntop(AF_INET, &sa4.sin_addr,
795 SELFLD(dir, rev_dns_src, rev_dns_dst),
796 sizeof(n->rev_dns_src));
797 return;
800 sa = (struct sockaddr *) &sa4;
801 sa_len = sizeof(sa4);
802 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr), AF_INET);
803 break;
805 case AF_INET6:
806 flow_entry_get_sain6_obj(n, dir, &sa6);
808 if (!resolve_dns) {
809 inet_ntop(AF_INET6, &sa6.sin6_addr,
810 SELFLD(dir, rev_dns_src, rev_dns_dst),
811 sizeof(n->rev_dns_src));
812 return;
815 sa = (struct sockaddr *) &sa6;
816 sa_len = sizeof(sa6);
817 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr), AF_INET6);
818 break;
821 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
822 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
824 if (hent)
825 strlcpy(SELFLD(dir, rev_dns_src, rev_dns_dst), hent->h_name,
826 sizeof(n->rev_dns_src));
829 static void flow_entry_get_extended(struct flow_entry *n)
831 if (n->flow_id == 0)
832 return;
834 flow_entry_get_extended_revdns(n, FLOW_DIR_SRC);
835 flow_entry_get_extended_geo(n, FLOW_DIR_SRC);
837 flow_entry_get_extended_revdns(n, FLOW_DIR_DST);
838 flow_entry_get_extended_geo(n, FLOW_DIR_DST);
840 /* Lookup application */
841 n->inode = get_port_inode(n->port_src, n->l4_proto,
842 n->l3_proto == AF_INET6);
843 if (n->inode > 0)
844 flow_entry_find_process(n);
847 static char *bandw2str(double bytes, char *buf, size_t len)
849 if (bytes <= 0) {
850 buf[0] = '\0';
851 return buf;
854 if (bytes > 1000000000.)
855 snprintf(buf, len, "%.1fGB", bytes / 1000000000.);
856 else if (bytes > 1000000.)
857 snprintf(buf, len, "%.1fMB", bytes / 1000000.);
858 else if (bytes > 1000.)
859 snprintf(buf, len, "%.1fkB", bytes / 1000.);
860 else
861 snprintf(buf, len, "%.0f", bytes);
863 return buf;
866 static char *rate2str(double rate, char *buf, size_t len)
868 const char * const unit_fmt[2][4] = {
869 { "%.1fGbit/s", "%.1fMbit/s", "%.1fkbit/s", "%.0fbit/s" },
870 { "%.1fGB/s", "%.1fMB/s", "%.1fkB/s", "%.0fB/s" }
873 if (rate <= 0) {
874 buf[0] = '\0';
875 return buf;
878 if (rate_type == RATE_BITS)
879 rate *= 8;
881 if (rate > 1000000000.)
882 snprintf(buf, len, unit_fmt[rate_type][0], rate / 1000000000.);
883 else if (rate > 1000000.)
884 snprintf(buf, len, unit_fmt[rate_type][1], rate / 1000000.);
885 else if (rate > 1000.)
886 snprintf(buf, len, unit_fmt[rate_type][2], rate / 1000.);
887 else
888 snprintf(buf, len, unit_fmt[rate_type][3], rate);
890 return buf;
893 static char *time2str(uint64_t tstamp, char *str, size_t len)
895 time_t now;
896 int v, s;
898 time(&now);
900 s = now - (tstamp ? (tstamp / NSEC_PER_SEC) : now);
901 if (s <= 0) {
902 str[0] = '\0';
903 return str;
906 v = s / (3600 * 24);
907 if (v > 0) {
908 slprintf(str, len, "%dd", v);
909 return str;
912 v = s / 3600;
913 if (v > 0) {
914 slprintf(str, len, "%dh", v);
915 return str;
918 v = s / 60;
919 if (v > 0) {
920 slprintf(str, len, "%dm", v);
921 return str;
924 slprintf(str, len, "%ds", s);
925 return str;
929 static const char *flow_state2str(const struct flow_entry *n)
931 switch (n->l4_proto) {
932 case IPPROTO_TCP:
933 return tcp_state2str[n->tcp_state];
934 case IPPROTO_SCTP:
935 return sctp_state2str[n->sctp_state];
936 case IPPROTO_DCCP:
937 return dccp_state2str[n->dccp_state];
939 case IPPROTO_UDP:
940 case IPPROTO_UDPLITE:
941 case IPPROTO_ICMP:
942 case IPPROTO_ICMPV6:
943 default:
944 return "";
948 static char *flow_port2str(const struct flow_entry *n, char *str, size_t len,
949 enum flow_direction dir)
951 const char *tmp = NULL;
952 uint16_t port = 0;
954 port = SELFLD(dir, port_src, port_dst);
955 tmp = NULL;
957 switch (n->l4_proto) {
958 case IPPROTO_TCP:
959 tmp = lookup_port_tcp(port);
960 break;
961 case IPPROTO_UDP:
962 case IPPROTO_UDPLITE:
963 tmp = lookup_port_udp(port);
964 break;
967 if (!tmp && port)
968 slprintf(str, len, "%d", port);
969 else
970 slprintf(str, len, "%s", tmp ? tmp : "");
972 return str;
975 static void print_flow_peer_info(const struct flow_entry *n, enum flow_direction dir)
977 int counters_color = COLOR(YELLOW, BLACK);
978 int src_color = COLOR(RED, BLACK);
979 int dst_color = COLOR(BLUE, BLACK);
980 int country_color = COLOR(GREEN, BLACK);
981 int addr_color = dst_color;
982 int port_color = A_BOLD;
983 char tmp[128];
985 if (show_src && dir == FLOW_DIR_SRC) {
986 country_color = src_color;
987 counters_color = src_color;
988 port_color |= src_color;
989 addr_color = src_color;
990 } else if (show_src && FLOW_DIR_DST) {
991 country_color = dst_color;
992 counters_color = dst_color;
993 port_color |= dst_color;
994 addr_color = dst_color;
997 ui_table_col_color_set(&flows_tbl, TBL_FLOW_ADDRESS, addr_color);
998 ui_table_col_color_set(&flows_tbl, TBL_FLOW_PORT, port_color);
999 ui_table_col_color_set(&flows_tbl, TBL_FLOW_GEO, country_color);
1000 ui_table_col_color_set(&flows_tbl, TBL_FLOW_BYTES, counters_color);
1001 ui_table_col_color_set(&flows_tbl, TBL_FLOW_RATE, counters_color);
1003 /* Reverse DNS/IP */
1004 ui_table_row_col_set(&flows_tbl, TBL_FLOW_ADDRESS,
1005 SELFLD(dir, rev_dns_src, rev_dns_dst));
1007 /* Application port */
1008 ui_table_row_col_set(&flows_tbl, TBL_FLOW_PORT,
1009 flow_port2str(n, tmp, sizeof(tmp), dir));
1011 /* GEO */
1012 ui_table_row_col_set(&flows_tbl, TBL_FLOW_GEO,
1013 SELFLD(dir, country_code_src, country_code_dst));
1015 /* Bytes */
1016 ui_table_row_col_set(&flows_tbl, TBL_FLOW_BYTES,
1017 bandw2str(SELFLD(dir, stat.bytes_src, stat.bytes_dst),
1018 tmp, sizeof(tmp) - 1));
1020 /* Rate bytes */
1021 ui_table_row_col_set(&flows_tbl, TBL_FLOW_RATE,
1022 rate2str(SELFLD(dir, stat.rate_bytes_src, stat.rate_bytes_dst),
1023 tmp, sizeof(tmp) - 1));
1026 static void draw_flow_entry(struct ui_table *tbl, const void *data)
1028 const struct flow_entry *n = data;
1029 char tmp[128];
1031 ui_table_row_add(tbl);
1033 /* Application */
1034 ui_table_row_col_set(tbl, TBL_FLOW_PROCESS, n->proc ? n->proc->name : "");
1036 /* PID */
1037 slprintf(tmp, sizeof(tmp), "%.d", n->proc ? n->proc->pid : 0);
1038 ui_table_row_col_set(tbl, TBL_FLOW_PID, tmp);
1040 /* L4 protocol */
1041 ui_table_row_col_set(tbl, TBL_FLOW_PROTO, l4proto2str[n->l4_proto]);
1043 /* L4 protocol state */
1044 ui_table_row_col_set(tbl, TBL_FLOW_STATE, flow_state2str(n));
1046 /* Time */
1047 time2str(n->timestamp_start, tmp, sizeof(tmp));
1048 ui_table_row_col_set(tbl, TBL_FLOW_TIME, tmp);
1050 print_flow_peer_info(n, show_src ? FLOW_DIR_SRC : FLOW_DIR_DST);
1052 ui_table_row_show(tbl);
1054 if (show_src) {
1055 ui_table_row_add(tbl);
1057 ui_table_row_col_set(tbl, TBL_FLOW_PROCESS, "");
1058 ui_table_row_col_set(tbl, TBL_FLOW_PID, "");
1059 ui_table_row_col_set(tbl, TBL_FLOW_PROTO, "");
1060 ui_table_row_col_set(tbl, TBL_FLOW_STATE, "");
1061 ui_table_row_col_set(tbl, TBL_FLOW_TIME, "");
1063 print_flow_peer_info(n, FLOW_DIR_DST);
1064 ui_table_row_show(tbl);
1068 static inline bool presenter_flow_wrong_state(struct flow_entry *n)
1070 switch (n->l4_proto) {
1071 case IPPROTO_TCP:
1072 switch (n->tcp_state) {
1073 case TCP_CONNTRACK_SYN_SENT:
1074 case TCP_CONNTRACK_SYN_RECV:
1075 case TCP_CONNTRACK_ESTABLISHED:
1076 case TCP_CONNTRACK_FIN_WAIT:
1077 case TCP_CONNTRACK_CLOSE_WAIT:
1078 case TCP_CONNTRACK_LAST_ACK:
1079 case TCP_CONNTRACK_TIME_WAIT:
1080 case TCP_CONNTRACK_CLOSE:
1081 case TCP_CONNTRACK_SYN_SENT2:
1082 case TCP_CONNTRACK_NONE:
1083 return false;
1084 break;
1086 break;
1087 case IPPROTO_SCTP:
1088 switch (n->sctp_state) {
1089 case SCTP_CONNTRACK_NONE:
1090 case SCTP_CONNTRACK_CLOSED:
1091 case SCTP_CONNTRACK_COOKIE_WAIT:
1092 case SCTP_CONNTRACK_COOKIE_ECHOED:
1093 case SCTP_CONNTRACK_ESTABLISHED:
1094 case SCTP_CONNTRACK_SHUTDOWN_SENT:
1095 case SCTP_CONNTRACK_SHUTDOWN_RECD:
1096 case SCTP_CONNTRACK_SHUTDOWN_ACK_SENT:
1097 return false;
1098 break;
1100 break;
1101 case IPPROTO_DCCP:
1102 switch (n->dccp_state) {
1103 case DCCP_CONNTRACK_NONE:
1104 case DCCP_CONNTRACK_REQUEST:
1105 case DCCP_CONNTRACK_RESPOND:
1106 case DCCP_CONNTRACK_PARTOPEN:
1107 case DCCP_CONNTRACK_OPEN:
1108 case DCCP_CONNTRACK_CLOSEREQ:
1109 case DCCP_CONNTRACK_CLOSING:
1110 case DCCP_CONNTRACK_TIMEWAIT:
1111 case DCCP_CONNTRACK_IGNORE:
1112 case DCCP_CONNTRACK_INVALID:
1113 return false;
1114 break;
1116 break;
1117 case IPPROTO_UDP:
1118 case IPPROTO_UDPLITE:
1119 case IPPROTO_ICMP:
1120 case IPPROTO_ICMPV6:
1121 return false;
1122 break;
1125 return true;
1128 static void draw_filter_status(struct ui_table *tbl, char *title)
1130 mvwprintw(screen, 1, 0, "%*s", COLS - 1, " ");
1131 mvwprintw(screen, 1, 2, "%s(%u) for ", title, ui_table_data_count(tbl));
1133 if (what & INCLUDE_IPV4)
1134 printw("IPv4,");
1135 if (what & INCLUDE_IPV6)
1136 printw("IPv6,");
1137 if (what & INCLUDE_TCP)
1138 printw("TCP,");
1139 if (what & INCLUDE_UDP)
1140 printw("UDP,");
1141 if (what & INCLUDE_SCTP)
1142 printw("SCTP,");
1143 if (what & INCLUDE_DCCP)
1144 printw("DCCP,");
1145 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1146 printw("ICMP,");
1147 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1148 printw("ICMP6,");
1149 if (show_active_only)
1150 printw("Active,");
1152 printw(" [+%d]", ui_table_scroll_height(tbl));
1154 if (is_flow_collecting)
1155 printw(" [Collecting flows ...]");
1159 static void draw_flows(WINDOW *screen, struct flow_list *fl)
1161 rcu_read_lock();
1163 if (cds_list_empty(&fl->head))
1164 mvwprintw(screen, 4, 2, "(No sessions! "
1165 "Is netfilter running?)");
1167 ui_table_data_bind(&flows_tbl);
1169 rcu_read_unlock();
1171 draw_filter_status(&flows_tbl, "Kernel netfilter flows");
1174 static void draw_proc_entry(struct ui_table *tbl, const void *data)
1176 const struct proc_entry *p = data;
1177 char tmp[128];
1179 ui_table_row_add(tbl);
1181 /* Application */
1182 ui_table_row_col_set(tbl, TBL_PROC_NAME, p->name);
1184 /* PID */
1185 slprintf(tmp, sizeof(tmp), "%.d", p->pid);
1186 ui_table_row_col_set(tbl, TBL_PROC_PID, tmp);
1188 /* Flows */
1189 slprintf(tmp, sizeof(tmp), "%.d", p->flows_count);
1190 ui_table_row_col_set(tbl, TBL_PROC_FLOWS, tmp);
1192 /* Bytes Src */
1193 bandw2str(p->stat.bytes_src, tmp, sizeof(tmp) - 1);
1194 ui_table_row_col_set(tbl, TBL_PROC_BYTES_SRC, tmp);
1196 /* Rate Src */
1197 rate2str(p->stat.rate_bytes_src, tmp, sizeof(tmp) - 1);
1198 ui_table_row_col_set(tbl, TBL_PROC_RATE_SRC, tmp);
1200 /* Bytes Dest */
1201 bandw2str(p->stat.bytes_dst, tmp, sizeof(tmp) - 1);
1202 ui_table_row_col_set(tbl, TBL_PROC_BYTES_DST, tmp);
1204 /* Rate Dest */
1205 rate2str(p->stat.rate_bytes_dst, tmp, sizeof(tmp) - 1);
1206 ui_table_row_col_set(tbl, TBL_PROC_RATE_DST, tmp);
1208 ui_table_row_show(tbl);
1211 static void draw_procs(WINDOW *screen, struct flow_list *fl)
1213 rcu_read_lock();
1215 ui_table_data_bind(&procs_tbl);
1217 rcu_read_unlock();
1219 draw_filter_status(&procs_tbl, "Processes");
1222 static void draw_help(void)
1224 int col = 0;
1225 int row = 1;
1226 int i;
1228 mvaddch(row, col, ACS_ULCORNER);
1229 mvaddch(rows - row - 1, col, ACS_LLCORNER);
1231 mvaddch(row, cols - 1, ACS_URCORNER);
1232 mvaddch(rows - row - 1, cols - 1, ACS_LRCORNER);
1234 for (i = 1; i < rows - row - 2; i++) {
1235 mvaddch(row + i, 0, ACS_VLINE);
1236 mvaddch(row + i, cols - 1, ACS_VLINE);
1238 for (i = 1; i < cols - col - 1; i++) {
1239 mvaddch(row, col + i, ACS_HLINE);
1240 mvaddch(rows - row - 1, col + i, ACS_HLINE);
1243 attron(A_BOLD);
1244 mvaddnstr(row, cols / 2 - 2, "| Help |", -1);
1246 attron(A_UNDERLINE);
1247 mvaddnstr(row + 2, col + 2, "Navigation", -1);
1248 attroff(A_BOLD | A_UNDERLINE);
1250 mvaddnstr(row + 4, col + 3, "TAB Go to next tab panel", -1);
1251 mvaddnstr(row + 5, col + 3, "Up, u, k Move up", -1);
1252 mvaddnstr(row + 6, col + 3, "Down, d, j Move down", -1);
1253 mvaddnstr(row + 7, col + 3, "Left,l Scroll left", -1);
1254 mvaddnstr(row + 8, col + 3, "Right,h Scroll right", -1);
1255 mvaddnstr(row + 9, col + 3, "? Toggle help window", -1);
1256 mvaddnstr(row + 10, col + 3, "q, Ctrl+C Quit", -1);
1258 attron(A_BOLD | A_UNDERLINE);
1259 mvaddnstr(row + 12, col + 2, "Display Settings", -1);
1260 attroff(A_BOLD | A_UNDERLINE);
1262 mvaddnstr(row + 14, col + 3, "b Toggle rate units (bits/bytes)", -1);
1263 mvaddnstr(row + 15, col + 3, "a Toggle display of active flows (rate > 0) only", -1);
1264 mvaddnstr(row + 16, col + 3, "s Toggle show source peer info", -1);
1266 mvaddnstr(row + 18, col + 3, "T Toggle display TCP flows", -1);
1267 mvaddnstr(row + 19, col + 3, "U Toggle display UDP flows", -1);
1268 mvaddnstr(row + 20, col + 3, "D Toggle display DCCP flows", -1);
1269 mvaddnstr(row + 21, col + 3, "I Toggle display ICMP flows", -1);
1270 mvaddnstr(row + 22, col + 3, "S Toggle display SCTP flows", -1);
1273 static void draw_header(WINDOW *screen)
1275 int i;
1277 attron(A_STANDOUT);
1279 for (i = 0; i < cols; i++)
1280 mvaddch(0, i, ' ');
1282 mvwprintw(screen, 0, 2, "flowtop %s", VERSION_LONG);
1283 attroff(A_STANDOUT);
1286 static void draw_footer(void)
1288 int i;
1290 attron(A_STANDOUT);
1292 for (i = 0; i < cols; i++)
1293 mvaddch(rows - 1, i, ' ');
1295 mvaddnstr(rows - 1, 1, "Press '?' for help", -1);
1296 addch(ACS_VLINE);
1297 attroff(A_STANDOUT);
1300 static void show_option_toggle(int opt)
1302 switch (opt) {
1303 case 'T':
1304 TOGGLE_FLAG(what, INCLUDE_TCP);
1305 break;
1306 case 'U':
1307 TOGGLE_FLAG(what, INCLUDE_UDP);
1308 break;
1309 case 'D':
1310 TOGGLE_FLAG(what, INCLUDE_DCCP);
1311 break;
1312 case 'I':
1313 TOGGLE_FLAG(what, INCLUDE_ICMP);
1314 break;
1315 case 'S':
1316 TOGGLE_FLAG(what, INCLUDE_SCTP);
1317 break;
1321 void * flows_iter(void *data)
1323 struct flow_entry *n = data;
1325 do {
1326 n = list_first_or_next(n, &flow_list.head, entry);
1327 } while (n && (!n->is_visible || presenter_flow_wrong_state(n)));
1329 return n;
1332 static void flows_table_init(struct ui_table *tbl)
1334 ui_table_init(tbl);
1336 ui_table_pos_set(tbl, 3, 0);
1337 ui_table_height_set(tbl, LINES - 3);
1339 ui_table_col_add(tbl, TBL_FLOW_PROCESS, "PROCESS", 13);
1340 ui_table_col_add(tbl, TBL_FLOW_PID, "PID", 7);
1341 ui_table_col_add(tbl, TBL_FLOW_PROTO, "PROTO", 6);
1342 ui_table_col_add(tbl, TBL_FLOW_STATE, "STATE", 11);
1343 ui_table_col_add(tbl, TBL_FLOW_TIME, "TIME", 4);
1344 ui_table_col_add(tbl, TBL_FLOW_ADDRESS, "ADDRESS", 50);
1345 ui_table_col_add(tbl, TBL_FLOW_PORT, "PORT", 8);
1346 ui_table_col_add(tbl, TBL_FLOW_GEO, "GEO", 3);
1347 ui_table_col_add(tbl, TBL_FLOW_BYTES, "BYTES", 10);
1348 ui_table_col_add(tbl, TBL_FLOW_RATE, "RATE", 10);
1350 ui_table_col_align_set(tbl, TBL_FLOW_TIME, UI_ALIGN_RIGHT);
1351 ui_table_col_align_set(tbl, TBL_FLOW_BYTES, UI_ALIGN_RIGHT);
1352 ui_table_col_align_set(tbl, TBL_FLOW_RATE, UI_ALIGN_RIGHT);
1354 ui_table_col_color_set(tbl, TBL_FLOW_PROCESS, COLOR(YELLOW, BLACK));
1355 ui_table_col_color_set(tbl, TBL_FLOW_PID, A_BOLD);
1356 ui_table_col_color_set(tbl, TBL_FLOW_STATE, COLOR(YELLOW, BLACK));
1358 ui_table_header_color_set(&flows_tbl, COLOR(BLACK, GREEN));
1360 ui_table_data_bind_set(tbl, draw_flow_entry);
1361 ui_table_data_iter_set(tbl, flows_iter);
1364 void * procs_iter(void *data)
1366 struct proc_entry *p = data;
1368 return list_first_or_next(p, &proc_list.head, entry);
1371 static void procs_table_init(struct ui_table *tbl)
1373 ui_table_init(tbl);
1375 ui_table_pos_set(tbl, 3, 0);
1376 ui_table_height_set(tbl, LINES - 3);
1378 ui_table_col_add(tbl, TBL_PROC_NAME, "NAME", 13);
1379 ui_table_col_add(tbl, TBL_PROC_PID, "PID", 7);
1380 ui_table_col_add(tbl, TBL_PROC_FLOWS, "FLOWS", 7);
1381 ui_table_col_add(tbl, TBL_PROC_BYTES_SRC, "BYTES_SRC", 10);
1382 ui_table_col_add(tbl, TBL_PROC_BYTES_DST, "BYTES_DST", 10);
1383 ui_table_col_add(tbl, TBL_PROC_RATE_SRC, "RATE_SRC", 14);
1384 ui_table_col_add(tbl, TBL_PROC_RATE_DST, "RATE_DST", 14);
1386 ui_table_col_align_set(tbl, TBL_PROC_BYTES_SRC, UI_ALIGN_RIGHT);
1387 ui_table_col_align_set(tbl, TBL_PROC_RATE_SRC, UI_ALIGN_RIGHT);
1388 ui_table_col_align_set(tbl, TBL_PROC_BYTES_DST, UI_ALIGN_RIGHT);
1389 ui_table_col_align_set(tbl, TBL_PROC_RATE_DST, UI_ALIGN_RIGHT);
1391 ui_table_col_color_set(tbl, TBL_PROC_NAME, COLOR(YELLOW, BLACK));
1392 ui_table_col_color_set(tbl, TBL_PROC_PID, A_BOLD);
1393 ui_table_col_color_set(tbl, TBL_PROC_FLOWS, COLOR(YELLOW, BLACK));
1394 ui_table_col_color_set(tbl, TBL_PROC_BYTES_SRC, COLOR(RED, BLACK));
1395 ui_table_col_color_set(tbl, TBL_PROC_RATE_SRC, COLOR(RED, BLACK));
1396 ui_table_col_color_set(tbl, TBL_PROC_BYTES_DST, COLOR(BLUE, BLACK));
1397 ui_table_col_color_set(tbl, TBL_PROC_RATE_DST, COLOR(BLUE, BLACK));
1399 ui_table_header_color_set(tbl, COLOR(BLACK, GREEN));
1401 ui_table_data_bind_set(tbl, draw_proc_entry);
1402 ui_table_data_iter_set(tbl, procs_iter);
1405 static void tab_main_on_open(struct ui_tab *tab, enum ui_tab_event_t evt, uint32_t id)
1407 if (evt != UI_TAB_EVT_OPEN)
1408 return;
1410 if (id == TAB_FLOWS) {
1411 draw_flows(screen, &flow_list);
1412 curr_tbl = &flows_tbl;
1413 } else if (id == TAB_PROCS) {
1414 draw_procs(screen, &flow_list);
1415 curr_tbl = &procs_tbl;
1419 static void presenter(void)
1421 bool show_help = false;
1422 struct ui_tab *tab_main;
1424 lookup_init(LT_PORTS_TCP);
1425 lookup_init(LT_PORTS_UDP);
1427 screen = screen_init(false);
1428 wclear(screen);
1429 halfdelay(1);
1431 start_color();
1432 INIT_COLOR(RED, BLACK);
1433 INIT_COLOR(BLUE, BLACK);
1434 INIT_COLOR(YELLOW, BLACK);
1435 INIT_COLOR(GREEN, BLACK);
1436 INIT_COLOR(BLACK, GREEN);
1438 flows_table_init(&flows_tbl);
1439 procs_table_init(&procs_tbl);
1441 tab_main = ui_tab_create();
1442 ui_tab_event_cb_set(tab_main, tab_main_on_open);
1443 ui_tab_pos_set(tab_main, 2, 0);
1444 ui_tab_active_color_set(tab_main, COLOR(BLACK, GREEN));
1445 ui_tab_entry_add(tab_main, TAB_FLOWS, "Flows");
1446 ui_tab_entry_add(tab_main, TAB_PROCS, "Process");
1448 rcu_register_thread();
1449 while (!sigint) {
1450 int ch;
1452 curs_set(0);
1453 getmaxyx(screen, rows, cols);
1455 ch = getch();
1456 switch (ch) {
1457 case 'q':
1458 sigint = 1;
1459 break;
1460 case KEY_UP:
1461 case 'u':
1462 case 'k':
1463 ui_table_event_send(curr_tbl, UI_EVT_SCROLL_UP);
1464 break;
1465 case KEY_DOWN:
1466 case 'd':
1467 case 'j':
1468 ui_table_event_send(curr_tbl, UI_EVT_SCROLL_DOWN);
1469 break;
1470 case KEY_LEFT:
1471 case 'h':
1472 ui_table_event_send(curr_tbl, UI_EVT_SCROLL_LEFT);
1473 break;
1474 case KEY_RIGHT:
1475 case 'l':
1476 ui_table_event_send(curr_tbl, UI_EVT_SCROLL_RIGHT);
1477 break;
1478 case 'b':
1479 if (rate_type == RATE_BYTES)
1480 rate_type = RATE_BITS;
1481 else
1482 rate_type = RATE_BYTES;
1483 break;
1484 case 'a':
1485 show_active_only = !show_active_only;
1486 break;
1487 case 's':
1488 show_src = !show_src;
1489 break;
1490 case '?':
1491 show_help = !show_help;
1492 wclear(screen);
1493 clear();
1494 break;
1495 case 'T':
1496 case 'U':
1497 case 'D':
1498 case 'I':
1499 case 'S':
1500 show_option_toggle(ch);
1501 do_reload_flows = true;
1502 break;
1503 case '\t':
1504 ui_tab_event_send(tab_main, UI_EVT_SELECT_NEXT);
1505 break;
1506 default:
1507 fflush(stdin);
1508 break;
1511 draw_header(screen);
1513 if (show_help)
1514 draw_help();
1515 else
1516 ui_tab_show(tab_main);
1518 draw_footer();
1520 rcu_unregister_thread();
1522 ui_table_uninit(&flows_tbl);
1523 ui_table_uninit(&procs_tbl);
1524 ui_tab_destroy(tab_main);
1526 screen_end();
1527 lookup_cleanup(LT_PORTS_UDP);
1528 lookup_cleanup(LT_PORTS_TCP);
1531 static void restore_sysctl(void *obj)
1533 struct sysctl_params_ctx *sysctl_ctx = obj;
1535 if (sysctl_ctx->nfct_acct == 0)
1536 sysctl_set_int("net/netfilter/nf_conntrack_acct",
1537 sysctl_ctx->nfct_acct);
1539 if (sysctl_ctx->nfct_tstamp == 0)
1540 sysctl_set_int("net/netfilter/nf_conntrack_timestamp",
1541 sysctl_ctx->nfct_tstamp);
1544 static void on_panic_handler(void *arg)
1546 restore_sysctl(arg);
1547 screen_end();
1550 static void conntrack_acct_enable(void)
1552 /* We can still work w/o traffic accounting so just warn about error */
1553 if (sysctl_get_int("net/netfilter/nf_conntrack_acct", &sysctl.nfct_acct)) {
1554 fprintf(stderr, "Can't read net/netfilter/nf_conntrack_acct: %s\n",
1555 strerror(errno));
1556 return;
1559 if (sysctl.nfct_acct == 1)
1560 return;
1562 if (sysctl_set_int("net/netfilter/nf_conntrack_acct", 1)) {
1563 fprintf(stderr, "Can't write net/netfilter/nf_conntrack_acct: %s\n",
1564 strerror(errno));
1568 static void conntrack_tstamp_enable(void)
1570 if (sysctl_get_int("net/netfilter/nf_conntrack_timestamp", &sysctl.nfct_tstamp)) {
1571 fprintf(stderr, "Can't read net/netfilter/nf_conntrack_timestamp: %s\n",
1572 strerror(errno));
1573 return;
1576 if (sysctl.nfct_tstamp == 1)
1577 return;
1579 if (sysctl_set_int("net/netfilter/nf_conntrack_timestamp", 1)) {
1580 fprintf(stderr, "Can't write net/netfilter/nf_conntrack_timestamp: %s\n",
1581 strerror(errno));
1585 static void flow_entry_filter(struct flow_entry *n)
1587 if (show_active_only && !n->stat.rate_bytes_src && !n->stat.rate_bytes_dst)
1588 n->is_visible = false;
1589 else
1590 n->is_visible = true;
1593 static int flow_list_update_entry(struct flow_list *fl, struct nf_conntrack *ct)
1595 struct flow_entry *n;
1597 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
1598 if (!n)
1599 return NFCT_CB_CONTINUE;
1601 flow_entry_calc_rate(n, ct);
1602 flow_entry_update_time(n);
1603 flow_entry_from_ct(n, ct);
1604 flow_entry_filter(n);
1606 return NFCT_CB_CONTINUE;
1609 static int flow_event_cb(enum nf_conntrack_msg_type type,
1610 struct nf_conntrack *ct, void *data __maybe_unused)
1612 if (sigint)
1613 return NFCT_CB_STOP;
1615 switch (type) {
1616 case NFCT_T_NEW:
1617 return flow_list_new_entry(&flow_list, ct);
1618 case NFCT_T_UPDATE:
1619 return flow_list_update_entry(&flow_list, ct);
1620 case NFCT_T_DESTROY:
1621 return flow_list_del_entry(&flow_list, ct);
1622 default:
1623 return NFCT_CB_CONTINUE;
1627 static void collector_refresh_procs(void)
1629 struct proc_entry *p, *tmp;
1631 cds_list_for_each_entry_safe(p, tmp, &proc_list.head, entry) {
1632 double sec = (double)time_after_us(&p->last_update) / USEC_PER_SEC;
1633 struct flow_entry *n;
1635 if (sec < 1)
1636 continue;
1638 bug_on(gettimeofday(&p->last_update, NULL));
1640 if (!p->flows_count && !proc_exists(p->pid)) {
1641 cds_list_del_rcu(&p->entry);
1642 call_rcu(&p->rcu, proc_entry_xfree_rcu);
1643 continue;
1646 p->stat.rate_bytes_src = 0;
1647 p->stat.rate_bytes_dst = 0;
1648 p->stat.rate_pkts_src = 0;
1649 p->stat.rate_pkts_dst = 0;
1651 cds_list_for_each_entry_rcu(n, &p->flows, proc_head) {
1652 p->stat.rate_bytes_src += n->stat.rate_bytes_src;
1653 p->stat.rate_bytes_dst += n->stat.rate_bytes_dst;
1654 p->stat.rate_pkts_src += n->stat.rate_pkts_src;
1655 p->stat.rate_pkts_dst += n->stat.rate_pkts_dst;
1660 static void collector_refresh_flows(struct nfct_handle *handle)
1662 struct flow_entry *n;
1664 cds_list_for_each_entry_rcu(n, &flow_list.head, entry) {
1665 nfct_query(handle, NFCT_Q_GET, n->ct);
1669 static void collector_create_filter(struct nfct_handle *nfct)
1671 struct nfct_filter *filter;
1672 int ret;
1674 filter = nfct_filter_create();
1675 if (!filter)
1676 panic("Cannot create a nfct filter: %s\n", strerror(errno));
1678 if (what & INCLUDE_UDP) {
1679 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1680 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
1682 if (what & INCLUDE_TCP)
1683 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1684 if (what & INCLUDE_DCCP)
1685 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1686 if (what & INCLUDE_SCTP)
1687 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1688 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1689 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1690 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1691 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1692 if (what & INCLUDE_IPV4) {
1693 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4, NFCT_FILTER_LOGIC_NEGATIVE);
1694 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1696 if (what & INCLUDE_IPV6) {
1697 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6, NFCT_FILTER_LOGIC_NEGATIVE);
1698 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1701 ret = nfct_filter_attach(nfct_fd(nfct), filter);
1702 if (ret < 0)
1703 panic("Cannot attach filter to handle: %s\n", strerror(errno));
1705 nfct_filter_destroy(filter);
1708 /* This hand-crafted filter looks ugly but it allows to do not
1709 * flush nfct connections & filter them by user specified filter.
1710 * May be it is better to replace this one by nfct_cmp. */
1711 static int flow_dump_cb(enum nf_conntrack_msg_type type __maybe_unused,
1712 struct nf_conntrack *ct, void *data __maybe_unused)
1714 struct flow_entry fl;
1715 struct flow_entry *n = &fl;
1717 if (sigint)
1718 return NFCT_CB_STOP;
1720 if (!(what & ~(INCLUDE_IPV4 | INCLUDE_IPV6)))
1721 goto check_addr;
1723 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
1725 if (what & INCLUDE_UDP) {
1726 if (n->l4_proto == IPPROTO_UDP)
1727 goto check_addr;
1729 if (n->l4_proto == IPPROTO_UDPLITE)
1730 goto check_addr;
1733 if ((what & INCLUDE_TCP) && n->l4_proto == IPPROTO_TCP)
1734 goto check_addr;
1736 if ((what & INCLUDE_DCCP) && n->l4_proto == IPPROTO_DCCP)
1737 goto check_addr;
1739 if ((what & INCLUDE_SCTP) && n->l4_proto == IPPROTO_SCTP)
1740 goto check_addr;
1742 if ((what & INCLUDE_ICMP) && (what & INCLUDE_IPV4) &&
1743 n->l4_proto == IPPROTO_ICMP) {
1744 goto check_addr;
1747 if ((what & INCLUDE_ICMP) && (what & INCLUDE_IPV6) &&
1748 n->l4_proto == IPPROTO_ICMPV6) {
1749 goto check_addr;
1752 goto skip_flow;
1754 check_addr:
1755 /* filter loopback addresses */
1756 if (what & INCLUDE_IPV4) {
1757 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
1759 if (n->ip4_src_addr == filter_ipv4.addr)
1760 goto skip_flow;
1762 if (what & INCLUDE_IPV6) {
1763 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
1765 if (n->ip6_src_addr[0] == 0x0 &&
1766 n->ip6_src_addr[1] == 0x0 &&
1767 n->ip6_src_addr[2] == 0x0 &&
1768 n->ip6_src_addr[3] == 0x1)
1769 goto skip_flow;
1772 return flow_list_new_entry(&flow_list, ct);
1774 skip_flow:
1775 return NFCT_CB_CONTINUE;
1778 static void collector_dump_flows(void)
1780 struct nfct_handle *nfct = nfct_open(CONNTRACK, 0);
1782 if (!nfct)
1783 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1785 nfct_callback_register(nfct, NFCT_T_ALL, flow_dump_cb, NULL);
1787 is_flow_collecting = true;
1788 if (what & INCLUDE_IPV4) {
1789 int family = AF_INET;
1790 nfct_query(nfct, NFCT_Q_DUMP, &family);
1792 if (what & INCLUDE_IPV6) {
1793 int family = AF_INET6;
1794 nfct_query(nfct, NFCT_Q_DUMP, &family);
1796 is_flow_collecting = false;
1798 nfct_close(nfct);
1801 static void *collector(void *null __maybe_unused)
1803 struct nfct_handle *ct_event;
1804 struct pollfd poll_fd[1];
1806 proc_list_init(&proc_list);
1807 flow_list_init(&flow_list);
1809 ct_event = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1810 NF_NETLINK_CONNTRACK_UPDATE |
1811 NF_NETLINK_CONNTRACK_DESTROY);
1812 if (!ct_event)
1813 panic("Cannot create a nfct handle: %s\n", strerror(errno));
1815 collector_create_filter(ct_event);
1817 nfct_callback_register(ct_event, NFCT_T_ALL, flow_event_cb, NULL);
1819 poll_fd[0].fd = nfct_fd(ct_event);
1820 poll_fd[0].events = POLLIN;
1822 if (fcntl(nfct_fd(ct_event), F_SETFL, O_NONBLOCK) == -1)
1823 panic("Cannot set non-blocking socket: fcntl(): %s\n",
1824 strerror(errno));
1826 rcu_register_thread();
1828 collector_dump_flows();
1830 while (!sigint) {
1831 int status;
1833 if (!do_reload_flows) {
1834 usleep(USEC_PER_SEC * interval);
1835 } else {
1836 do_reload_flows = false;
1838 flow_list_destroy(&flow_list);
1840 collector_create_filter(ct_event);
1841 collector_dump_flows();
1844 collector_refresh_procs();
1845 collector_refresh_flows(ct_event);
1847 status = poll(poll_fd, 1, 0);
1848 if (status < 0) {
1849 if (errno == EAGAIN || errno == EINTR)
1850 continue;
1852 panic("Error while polling: %s\n", strerror(errno));
1853 } else if (status != 0) {
1854 if (poll_fd[0].revents & POLLIN)
1855 nfct_catch(ct_event);
1859 flow_list_destroy(&flow_list);
1860 proc_list_destroy(&proc_list);
1862 rcu_unregister_thread();
1864 nfct_close(ct_event);
1866 pthread_exit(NULL);
1869 int main(int argc, char **argv)
1871 pthread_t tid;
1872 int ret, c, what_cmd = 0;
1874 setfsuid(getuid());
1875 setfsgid(getgid());
1877 while ((c = getopt_long(argc, argv, short_options, long_options,
1878 NULL)) != EOF) {
1879 switch (c) {
1880 case '4':
1881 what_cmd |= INCLUDE_IPV4;
1882 break;
1883 case '6':
1884 what_cmd |= INCLUDE_IPV6;
1885 break;
1886 case 'T':
1887 what_cmd |= INCLUDE_TCP;
1888 break;
1889 case 'U':
1890 what_cmd |= INCLUDE_UDP;
1891 break;
1892 case 'D':
1893 what_cmd |= INCLUDE_DCCP;
1894 break;
1895 case 'I':
1896 what_cmd |= INCLUDE_ICMP;
1897 break;
1898 case 'S':
1899 what_cmd |= INCLUDE_SCTP;
1900 break;
1901 case 's':
1902 show_src = true;
1903 break;
1904 case 'b':
1905 rate_type = RATE_BITS;
1906 break;
1907 case 'u':
1908 update_geoip();
1909 die();
1910 break;
1911 case 't':
1912 interval = strtoul(optarg, NULL, 10);
1913 break;
1914 case 'n':
1915 resolve_dns = false;
1916 break;
1917 case 'G':
1918 resolve_geoip = false;
1919 break;
1920 case 'h':
1921 help();
1922 break;
1923 case 'v':
1924 version();
1925 break;
1926 default:
1927 break;
1931 if (what_cmd > 0) {
1932 what = what_cmd;
1934 if (!(what & (INCLUDE_IPV4 | INCLUDE_IPV6)))
1935 what |= INCLUDE_IPV4 | INCLUDE_IPV6;
1938 rcu_init();
1940 register_signal(SIGINT, signal_handler);
1941 register_signal(SIGQUIT, signal_handler);
1942 register_signal(SIGTERM, signal_handler);
1943 register_signal(SIGHUP, signal_handler);
1945 panic_handler_add(on_panic_handler, &sysctl);
1947 conntrack_acct_enable();
1948 conntrack_tstamp_enable();
1950 if (resolve_geoip)
1951 init_geoip(1);
1953 ret = pthread_create(&tid, NULL, collector, NULL);
1954 if (ret < 0)
1955 panic("Cannot create phthread!\n");
1957 presenter();
1959 if (resolve_geoip)
1960 destroy_geoip();
1962 restore_sysctl(&sysctl);
1964 return 0;