mausezahn: Don't use ternary operator to decide which function to call
[netsniff-ng.git] / flowtop.c
blobce43d93960c94d30ef0937d4a1561aef19651d1e
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2011 - 2013 Daniel Borkmann.
4 * Copyright 2011 Emmanuel Roullit.
5 * Subject to the GPL, version 2.
6 */
8 #define _LGPL_SOURCE
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <stdlib.h>
12 #include <signal.h>
13 #include <getopt.h>
14 #include <pthread.h>
15 #include <signal.h>
16 #include <netdb.h>
17 #include <ctype.h>
18 #include <netinet/in.h>
19 #include <curses.h>
20 #include <dirent.h>
21 #include <sys/stat.h>
22 #include <sys/fsuid.h>
23 #include <urcu.h>
24 #include <libgen.h>
25 #include <inttypes.h>
27 #include "die.h"
28 #include "xmalloc.h"
29 #include "conntrack.h"
30 #include "ioops.h"
31 #include "config.h"
32 #include "str.h"
33 #include "sig.h"
34 #include "geoip.h"
35 #include "built_in.h"
36 #include "locking.h"
37 #include "dissector_eth.h"
38 #include "pkt_buff.h"
39 #include "screen.h"
41 struct flow_entry {
42 uint32_t flow_id, use, status;
43 uint8_t l3_proto, l4_proto;
44 uint32_t ip4_src_addr, ip4_dst_addr;
45 uint32_t ip6_src_addr[4], ip6_dst_addr[4];
46 uint16_t port_src, port_dst;
47 uint8_t tcp_state, tcp_flags, sctp_state, dccp_state;
48 uint64_t counter_pkts, counter_bytes;
49 uint64_t timestamp_start, timestamp_stop;
50 char country_src[128], country_dst[128];
51 char city_src[128], city_dst[128];
52 char rev_dns_src[256], rev_dns_dst[256];
53 char cmdline[256];
54 struct flow_entry *next;
55 int procnum, inode;
58 struct flow_list {
59 struct flow_entry *head;
60 struct spinlock lock;
63 #ifndef ATTR_TIMESTAMP_START
64 # define ATTR_TIMESTAMP_START 63
65 #endif
66 #ifndef ATTR_TIMESTAMP_STOP
67 # define ATTR_TIMESTAMP_STOP 64
68 #endif
70 #define SCROLL_MAX 1000
72 #define INCLUDE_IPV4 (1 << 0)
73 #define INCLUDE_IPV6 (1 << 1)
74 #define INCLUDE_UDP (1 << 2)
75 #define INCLUDE_TCP (1 << 3)
76 #define INCLUDE_DCCP (1 << 4)
77 #define INCLUDE_ICMP (1 << 5)
78 #define INCLUDE_SCTP (1 << 6)
80 static volatile sig_atomic_t sigint = 0;
81 static int what = INCLUDE_IPV4 | INCLUDE_IPV6 | INCLUDE_TCP, show_src = 0;
82 static struct flow_list flow_list;
84 static const char *short_options = "vhTUsDIS46u";
85 static const struct option long_options[] = {
86 {"ipv4", no_argument, NULL, '4'},
87 {"ipv6", no_argument, NULL, '6'},
88 {"tcp", no_argument, NULL, 'T'},
89 {"udp", no_argument, NULL, 'U'},
90 {"dccp", no_argument, NULL, 'D'},
91 {"icmp", no_argument, NULL, 'I'},
92 {"sctp", no_argument, NULL, 'S'},
93 {"show-src", no_argument, NULL, 's'},
94 {"update", no_argument, NULL, 'u'},
95 {"version", no_argument, NULL, 'v'},
96 {"help", no_argument, NULL, 'h'},
97 {NULL, 0, NULL, 0}
100 static const char *const l3proto2str[AF_MAX] = {
101 [AF_INET] = "ipv4",
102 [AF_INET6] = "ipv6",
105 static const char *const l4proto2str[IPPROTO_MAX] = {
106 [IPPROTO_TCP] = "tcp",
107 [IPPROTO_UDP] = "udp",
108 [IPPROTO_UDPLITE] = "udplite",
109 [IPPROTO_ICMP] = "icmp",
110 [IPPROTO_ICMPV6] = "icmpv6",
111 [IPPROTO_SCTP] = "sctp",
112 [IPPROTO_GRE] = "gre",
113 [IPPROTO_DCCP] = "dccp",
114 [IPPROTO_IGMP] = "igmp",
115 [IPPROTO_IPIP] = "ipip",
116 [IPPROTO_EGP] = "egp",
117 [IPPROTO_PUP] = "pup",
118 [IPPROTO_IDP] = "idp",
119 [IPPROTO_RSVP] = "rsvp",
120 [IPPROTO_IPV6] = "ip6tun",
121 [IPPROTO_ESP] = "esp",
122 [IPPROTO_AH] = "ah",
123 [IPPROTO_PIM] = "pim",
124 [IPPROTO_COMP] = "comp",
127 static const char *const tcp_state2str[TCP_CONNTRACK_MAX] = {
128 [TCP_CONNTRACK_NONE] = "NOSTATE",
129 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
130 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
131 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
132 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
133 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
134 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
135 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
136 [TCP_CONNTRACK_CLOSE] = "CLOSE",
137 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
140 static const uint8_t tcp_states[] = {
141 TCP_CONNTRACK_SYN_SENT,
142 TCP_CONNTRACK_SYN_RECV,
143 TCP_CONNTRACK_ESTABLISHED,
144 TCP_CONNTRACK_FIN_WAIT,
145 TCP_CONNTRACK_CLOSE_WAIT,
146 TCP_CONNTRACK_LAST_ACK,
147 TCP_CONNTRACK_TIME_WAIT,
148 TCP_CONNTRACK_CLOSE,
149 TCP_CONNTRACK_SYN_SENT2,
150 TCP_CONNTRACK_NONE,
153 static const char *const dccp_state2str[DCCP_CONNTRACK_MAX] = {
154 [DCCP_CONNTRACK_NONE] = "NOSTATE",
155 [DCCP_CONNTRACK_REQUEST] = "REQUEST",
156 [DCCP_CONNTRACK_RESPOND] = "RESPOND",
157 [DCCP_CONNTRACK_PARTOPEN] = "PARTOPEN",
158 [DCCP_CONNTRACK_OPEN] = "OPEN",
159 [DCCP_CONNTRACK_CLOSEREQ] = "CLOSEREQ",
160 [DCCP_CONNTRACK_CLOSING] = "CLOSING",
161 [DCCP_CONNTRACK_TIMEWAIT] = "TIMEWAIT",
162 [DCCP_CONNTRACK_IGNORE] = "IGNORE",
163 [DCCP_CONNTRACK_INVALID] = "INVALID",
166 static const uint8_t dccp_states[] = {
167 DCCP_CONNTRACK_NONE,
168 DCCP_CONNTRACK_REQUEST,
169 DCCP_CONNTRACK_RESPOND,
170 DCCP_CONNTRACK_PARTOPEN,
171 DCCP_CONNTRACK_OPEN,
172 DCCP_CONNTRACK_CLOSEREQ,
173 DCCP_CONNTRACK_CLOSING,
174 DCCP_CONNTRACK_TIMEWAIT,
175 DCCP_CONNTRACK_IGNORE,
176 DCCP_CONNTRACK_INVALID,
179 static const char *const sctp_state2str[SCTP_CONNTRACK_MAX] = {
180 [SCTP_CONNTRACK_NONE] = "NOSTATE",
181 [SCTP_CONNTRACK_CLOSED] = "CLOSED",
182 [SCTP_CONNTRACK_COOKIE_WAIT] = "COOKIE_WAIT",
183 [SCTP_CONNTRACK_COOKIE_ECHOED] = "COOKIE_ECHOED",
184 [SCTP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
185 [SCTP_CONNTRACK_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
186 [SCTP_CONNTRACK_SHUTDOWN_RECD] = "SHUTDOWN_RECD",
187 [SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = "SHUTDOWN_ACK_SENT",
190 static const uint8_t sctp_states[] = {
191 SCTP_CONNTRACK_NONE,
192 SCTP_CONNTRACK_CLOSED,
193 SCTP_CONNTRACK_COOKIE_WAIT,
194 SCTP_CONNTRACK_COOKIE_ECHOED,
195 SCTP_CONNTRACK_ESTABLISHED,
196 SCTP_CONNTRACK_SHUTDOWN_SENT,
197 SCTP_CONNTRACK_SHUTDOWN_RECD,
198 SCTP_CONNTRACK_SHUTDOWN_ACK_SENT,
201 static const struct nfct_filter_ipv4 filter_ipv4 = {
202 .addr = __constant_htonl(INADDR_LOOPBACK),
203 .mask = 0xffffffff,
206 static const struct nfct_filter_ipv6 filter_ipv6 = {
207 .addr = { 0x0, 0x0, 0x0, 0x1 },
208 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
211 static void signal_handler(int number)
213 switch (number) {
214 case SIGINT:
215 case SIGQUIT:
216 case SIGTERM:
217 sigint = 1;
218 break;
219 case SIGHUP:
220 default:
221 break;
225 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct);
226 static void flow_entry_get_extended(struct flow_entry *n);
228 static void help(void)
230 printf("\nflowtop %s, top-like netfilter TCP/UDP/SCTP/.. flow tracking\n",
231 VERSION_STRING);
232 puts("http://www.netsniff-ng.org\n\n"
233 "Usage: flowtop [options]\n"
234 "Options:\n"
235 " -4|--ipv4 Show only IPv4 flows (default)\n"
236 " -6|--ipv6 Show only IPv6 flows (default)\n"
237 " -T|--tcp Show only TCP flows (default)\n"
238 " -U|--udp Show only UDP flows\n"
239 " -D|--dccp Show only DCCP flows\n"
240 " -I|--icmp Show only ICMP/ICMPv6 flows\n"
241 " -S|--sctp Show only SCTP flows\n"
242 " -s|--show-src Also show source, not only dest\n"
243 " -u|--update Update GeoIP databases\n"
244 " -v|--version Print version and exit\n"
245 " -h|--help Print this help and exit\n\n"
246 "Examples:\n"
247 " flowtop\n"
248 " flowtop -46UTDISs\n\n"
249 "Note:\n"
250 " If netfilter is not running, you can activate it with e.g.:\n"
251 " iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
252 " iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n\n"
253 "Please report bugs to <bugs@netsniff-ng.org>\n"
254 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
255 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
256 "Swiss federal institute of technology (ETH Zurich)\n"
257 "License: GNU GPL version 2.0\n"
258 "This is free software: you are free to change and redistribute it.\n"
259 "There is NO WARRANTY, to the extent permitted by law.\n");
260 die();
263 static void version(void)
265 printf("\nflowtop %s, Git id: %s\n", VERSION_LONG, GITVERSION);
266 puts("top-like netfilter TCP/UDP/SCTP/.. flow tracking\n"
267 "http://www.netsniff-ng.org\n\n"
268 "Please report bugs to <bugs@netsniff-ng.org>\n"
269 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
270 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
271 "Swiss federal institute of technology (ETH Zurich)\n"
272 "License: GNU GPL version 2.0\n"
273 "This is free software: you are free to change and redistribute it.\n"
274 "There is NO WARRANTY, to the extent permitted by law.\n");
275 die();
278 static inline struct flow_entry *flow_entry_xalloc(void)
280 return xzmalloc(sizeof(struct flow_entry));
283 static inline void flow_entry_xfree(struct flow_entry *n)
285 xfree(n);
288 static inline void flow_list_init(struct flow_list *fl)
290 fl->head = NULL;
291 spinlock_init(&fl->lock);
294 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
296 struct flow_entry *n = flow_entry_xalloc();
298 flow_entry_from_ct(n, ct);
299 flow_entry_get_extended(n);
301 rcu_assign_pointer(n->next, fl->head);
302 rcu_assign_pointer(fl->head, n);
305 static struct flow_entry *flow_list_find_id(struct flow_list *fl,
306 uint32_t id)
308 struct flow_entry *n = rcu_dereference(fl->head);
310 while (n != NULL) {
311 if (n->flow_id == id)
312 return n;
314 n = rcu_dereference(n->next);
317 return NULL;
320 static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
321 uint32_t id)
323 struct flow_entry *n = rcu_dereference(fl->head), *tmp;
325 if (n->flow_id == id)
326 return NULL;
328 while ((tmp = rcu_dereference(n->next)) != NULL) {
329 if (tmp->flow_id == id)
330 return n;
332 n = tmp;
335 return NULL;
338 static void flow_list_update_entry(struct flow_list *fl,
339 struct nf_conntrack *ct)
341 int do_ext = 0;
342 struct flow_entry *n;
344 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
345 if (n == NULL) {
346 n = flow_entry_xalloc();
347 do_ext = 1;
350 flow_entry_from_ct(n, ct);
351 if (do_ext) {
352 flow_entry_get_extended(n);
354 rcu_assign_pointer(n->next, fl->head);
355 rcu_assign_pointer(fl->head, n);
359 static void flow_list_destroy_entry(struct flow_list *fl,
360 struct nf_conntrack *ct)
362 struct flow_entry *n1, *n2;
363 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
365 n1 = flow_list_find_id(fl, id);
366 if (n1) {
367 n2 = flow_list_find_prev_id(fl, id);
368 if (n2) {
369 rcu_assign_pointer(n2->next, n1->next);
370 n1->next = NULL;
372 flow_entry_xfree(n1);
373 } else {
374 flow_entry_xfree(fl->head);
375 fl->head = NULL;
380 static void flow_list_destroy(struct flow_list *fl)
382 struct flow_entry *n;
384 while (fl->head != NULL) {
385 n = rcu_dereference(fl->head->next);
386 fl->head->next = NULL;
388 flow_entry_xfree(fl->head);
389 rcu_assign_pointer(fl->head, n);
392 synchronize_rcu();
393 spinlock_destroy(&fl->lock);
396 static int walk_process(const char *process, struct flow_entry *n)
398 int ret;
399 DIR *dir;
400 struct dirent *ent;
401 char path[1024];
403 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
404 panic("giant process name! %s\n", process);
406 dir = opendir(path);
407 if (!dir)
408 return 0;
410 while ((ent = readdir(dir))) {
411 struct stat statbuf;
413 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
414 process, ent->d_name) < 0)
415 continue;
417 if (stat(path, &statbuf) < 0)
418 continue;
420 if (S_ISSOCK(statbuf.st_mode) && (ino_t) n->inode == statbuf.st_ino) {
421 memset(n->cmdline, 0, sizeof(n->cmdline));
423 snprintf(path, sizeof(path), "/proc/%s/exe", process);
425 ret = readlink(path, n->cmdline,
426 sizeof(n->cmdline) - 1);
427 if (ret < 0)
428 panic("readlink error: %s\n", strerror(errno));
430 n->procnum = atoi(process);
431 closedir(dir);
432 return 1;
436 closedir(dir);
437 return 0;
440 static void walk_processes(struct flow_entry *n)
442 int ret;
443 DIR *dir;
444 struct dirent *ent;
446 /* n->inode must be set */
447 if (n->inode <= 0) {
448 memset(n->cmdline, 0, sizeof(n->cmdline));
449 return;
452 dir = opendir("/proc");
453 if (!dir)
454 panic("Cannot open /proc!\n");
456 while ((ent = readdir(dir))) {
457 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name)) {
458 ret = walk_process(ent->d_name, n);
459 if (ret > 0)
460 break;
464 closedir(dir);
467 static int get_port_inode(uint16_t port, int proto, int is_ip6)
469 int ret = -ENOENT;
470 char path[128], buff[1024];
471 FILE *proc;
473 memset(path, 0, sizeof(path));
474 snprintf(path, sizeof(path), "/proc/net/%s%s",
475 l4proto2str[proto], is_ip6 ? "6" : "");
477 proc = fopen(path, "r");
478 if (!proc)
479 return -EIO;
481 memset(buff, 0, sizeof(buff));
483 while (fgets(buff, sizeof(buff), proc) != NULL) {
484 int inode = 0;
485 unsigned int lport = 0;
487 buff[sizeof(buff) - 1] = 0;
488 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
489 "%*X %*u %*u %u", &lport, &inode) == 2) {
490 if ((uint16_t) lport == port) {
491 ret = inode;
492 break;
496 memset(buff, 0, sizeof(buff));
499 fclose(proc);
500 return ret;
503 #define CP_NFCT(elem, attr, x) \
504 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
505 #define CP_NFCT_BUFF(elem, attr) do { \
506 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
507 if (buff != NULL) \
508 memcpy(n->elem, buff, sizeof(n->elem)); \
509 } while (0)
511 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
513 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
514 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
516 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
517 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
519 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
520 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
522 CP_NFCT(status, ATTR_STATUS, 32);
524 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
525 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
526 CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
527 CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
529 CP_NFCT(counter_pkts, ATTR_ORIG_COUNTER_PACKETS, 64);
530 CP_NFCT(counter_bytes, ATTR_ORIG_COUNTER_BYTES, 64);
532 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
533 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
535 CP_NFCT(flow_id, ATTR_ID, 32);
536 CP_NFCT(use, ATTR_USE, 32);
538 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
539 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
541 n->port_src = ntohs(n->port_src);
542 n->port_dst = ntohs(n->port_dst);
544 n->ip4_src_addr = ntohl(n->ip4_src_addr);
545 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
548 enum flow_entry_direction {
549 flow_entry_src,
550 flow_entry_dst,
553 static inline int flow_entry_get_extended_is_dns(struct flow_entry *n)
555 /* We don't want to analyze / display DNS itself, since we
556 * use it to resolve reverse dns.
558 return n->port_src == 53 || n->port_dst == 53;
561 #define SELFLD(dir,src_member,dst_member) \
562 (((dir) == flow_entry_src) ? n->src_member : n->dst_member)
564 static void flow_entry_get_sain4_obj(struct flow_entry *n,
565 enum flow_entry_direction dir,
566 struct sockaddr_in *sa)
568 memset(sa, 0, sizeof(*sa));
569 sa->sin_family = PF_INET;
570 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
573 static void flow_entry_get_sain6_obj(struct flow_entry *n,
574 enum flow_entry_direction dir,
575 struct sockaddr_in6 *sa)
577 memset(sa, 0, sizeof(*sa));
578 sa->sin6_family = PF_INET6;
580 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
581 sizeof(sa->sin6_addr));
584 static void
585 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
586 enum flow_entry_direction dir)
588 struct sockaddr_in sa4;
589 struct sockaddr_in6 sa6;
590 const char *city = NULL;
592 switch (n->l3_proto) {
593 default:
594 bug();
596 case AF_INET:
597 flow_entry_get_sain4_obj(n, dir, &sa4);
598 city = geoip4_city_name(&sa4);
599 break;
601 case AF_INET6:
602 flow_entry_get_sain6_obj(n, dir, &sa6);
603 city = geoip6_city_name(&sa6);
604 break;
607 bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
609 if (city) {
610 memcpy(SELFLD(dir, city_src, city_dst), city,
611 min(sizeof(n->city_src), strlen(city)));
612 } else {
613 memset(SELFLD(dir, city_src, city_dst), 0,
614 sizeof(n->city_src));
618 static void
619 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
620 enum flow_entry_direction dir)
622 struct sockaddr_in sa4;
623 struct sockaddr_in6 sa6;
624 const char *country = NULL;
626 switch (n->l3_proto) {
627 default:
628 bug();
630 case AF_INET:
631 flow_entry_get_sain4_obj(n, dir, &sa4);
632 country = geoip4_country_name(&sa4);
633 break;
635 case AF_INET6:
636 flow_entry_get_sain6_obj(n, dir, &sa6);
637 country = geoip6_country_name(&sa6);
638 break;
641 bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
643 if (country) {
644 memcpy(SELFLD(dir, country_src, country_dst), country,
645 min(sizeof(n->country_src), strlen(country)));
646 } else {
647 memset(SELFLD(dir, country_src, country_dst), 0,
648 sizeof(n->country_src));
652 static void flow_entry_get_extended_geo(struct flow_entry *n,
653 enum flow_entry_direction dir)
655 flow_entry_geo_city_lookup_generic(n, dir);
656 flow_entry_geo_country_lookup_generic(n, dir);
659 static void flow_entry_get_extended_revdns(struct flow_entry *n,
660 enum flow_entry_direction dir)
662 size_t sa_len;
663 struct sockaddr_in sa4;
664 struct sockaddr_in6 sa6;
665 struct sockaddr *sa;
666 struct hostent *hent;
668 switch (n->l3_proto) {
669 default:
670 bug();
672 case AF_INET:
673 flow_entry_get_sain4_obj(n, dir, &sa4);
674 sa = (struct sockaddr *) &sa4;
675 sa_len = sizeof(sa4);
676 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr), AF_INET);
677 break;
679 case AF_INET6:
680 flow_entry_get_sain6_obj(n, dir, &sa6);
681 sa = (struct sockaddr *) &sa6;
682 sa_len = sizeof(sa6);
683 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr), AF_INET6);
684 break;
687 bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
688 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
689 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
691 if (hent) {
692 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
693 memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
694 hent->h_name, min(sizeof(n->rev_dns_src),
695 strlen(hent->h_name)));
699 static void flow_entry_get_extended(struct flow_entry *n)
701 if (n->flow_id == 0 || flow_entry_get_extended_is_dns(n))
702 return;
704 flow_entry_get_extended_revdns(n, flow_entry_src);
705 flow_entry_get_extended_geo(n, flow_entry_src);
707 flow_entry_get_extended_revdns(n, flow_entry_dst);
708 flow_entry_get_extended_geo(n, flow_entry_dst);
710 /* Lookup application */
711 n->inode = get_port_inode(n->port_src, n->l4_proto,
712 n->l3_proto == AF_INET6);
713 if (n->inode > 0)
714 walk_processes(n);
717 static uint16_t presenter_get_port(uint16_t src, uint16_t dst, int tcp)
719 if (src < dst && src < 1024) {
720 return src;
721 } else if (dst < src && dst < 1024) {
722 return dst;
723 } else {
724 const char *tmp1, *tmp2;
725 if (tcp) {
726 tmp1 = lookup_port_tcp(src);
727 tmp2 = lookup_port_tcp(dst);
728 } else {
729 tmp1 = lookup_port_udp(src);
730 tmp2 = lookup_port_udp(dst);
732 if (tmp1 && !tmp2) {
733 return src;
734 } else if (!tmp1 && tmp2) {
735 return dst;
736 } else {
737 if (src < dst)
738 return src;
739 else
740 return dst;
745 static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
746 unsigned int *line)
748 char tmp[128], *pname = NULL;
749 uint16_t port;
751 mvwprintw(screen, *line, 2, "");
753 /* PID, application name */
754 if (n->procnum > 0) {
755 slprintf(tmp, sizeof(tmp), "%s(%d)", basename(n->cmdline),
756 n->procnum);
758 printw("[");
759 attron(COLOR_PAIR(3));
760 printw("%s", tmp);
761 attroff(COLOR_PAIR(3));
762 printw("]:");
765 /* L3 protocol, L4 protocol, states */
766 printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
767 printw("[");
768 attron(COLOR_PAIR(3));
769 switch (n->l4_proto) {
770 case IPPROTO_TCP:
771 printw("%s", tcp_state2str[n->tcp_state]);
772 break;
773 case IPPROTO_SCTP:
774 printw("%s", sctp_state2str[n->sctp_state]);
775 break;
776 case IPPROTO_DCCP:
777 printw("%s", dccp_state2str[n->dccp_state]);
778 break;
779 case IPPROTO_UDP:
780 case IPPROTO_UDPLITE:
781 case IPPROTO_ICMP:
782 case IPPROTO_ICMPV6:
783 printw("NOSTATE");
784 break;
786 attroff(COLOR_PAIR(3));
787 printw("]");
789 /* Guess application port */
790 switch (n->l4_proto) {
791 case IPPROTO_TCP:
792 port = presenter_get_port(n->port_src, n->port_dst, 1);
793 pname = lookup_port_tcp(port);
794 break;
795 case IPPROTO_UDP:
796 case IPPROTO_UDPLITE:
797 port = presenter_get_port(n->port_src, n->port_dst, 0);
798 pname = lookup_port_udp(port);
799 break;
801 if (pname) {
802 attron(A_BOLD);
803 printw(":%s", pname);
804 attroff(A_BOLD);
806 printw(" ->");
808 /* Number packets, bytes */
809 if (n->counter_pkts > 0 && n->counter_bytes > 0)
810 printw(" (%"PRIu64" pkts, %"PRIu64" bytes) ->",
811 n->counter_pkts, n->counter_bytes);
813 /* Show source information: reverse DNS, port, country, city */
814 if (show_src) {
815 attron(COLOR_PAIR(1));
816 mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
817 attroff(COLOR_PAIR(1));
819 printw(":%"PRIu16, n->port_src);
821 if (n->country_src[0]) {
822 printw(" (");
824 attron(COLOR_PAIR(4));
825 printw("%s", n->country_src);
826 attroff(COLOR_PAIR(4));
828 if (n->city_src[0])
829 printw(", %s", n->city_src);
831 printw(")");
834 printw(" => ");
837 /* Show dest information: reverse DNS, port, country, city */
838 attron(COLOR_PAIR(2));
839 mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
840 attroff(COLOR_PAIR(2));
842 printw(":%"PRIu16, n->port_dst);
844 if (n->country_dst[0]) {
845 printw(" (");
847 attron(COLOR_PAIR(4));
848 printw("%s", n->country_dst);
849 attroff(COLOR_PAIR(4));
851 if (n->city_dst[0])
852 printw(", %s", n->city_dst);
854 printw(")");
858 static inline int presenter_flow_wrong_state(struct flow_entry *n, int state)
860 int ret = 1;
862 switch (n->l4_proto) {
863 case IPPROTO_TCP:
864 if (n->tcp_state == state)
865 ret = 0;
866 break;
867 case IPPROTO_SCTP:
868 if (n->sctp_state == state)
869 ret = 0;
870 break;
871 case IPPROTO_DCCP:
872 if (n->dccp_state == state)
873 ret = 0;
874 break;
875 case IPPROTO_UDP:
876 case IPPROTO_UDPLITE:
877 case IPPROTO_ICMP:
878 case IPPROTO_ICMPV6:
879 ret = 0;
880 break;
883 return ret;
886 static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
887 int skip_lines)
889 int maxy;
890 size_t i, j;
891 unsigned int line = 3;
892 struct flow_entry *n;
893 uint8_t protocols[] = {
894 IPPROTO_TCP,
895 IPPROTO_DCCP,
896 IPPROTO_SCTP,
897 IPPROTO_UDP,
898 IPPROTO_UDPLITE,
899 IPPROTO_ICMP,
900 IPPROTO_ICMPV6,
902 size_t protocol_state_size[] = {
903 [IPPROTO_TCP] = array_size(tcp_states),
904 [IPPROTO_DCCP] = array_size(dccp_states),
905 [IPPROTO_SCTP] = array_size(sctp_states),
906 [IPPROTO_UDP] = 1,
907 [IPPROTO_UDPLITE] = 1,
908 [IPPROTO_ICMP] = 1,
909 [IPPROTO_ICMPV6] = 1,
912 curs_set(0);
914 maxy = getmaxy(screen);
915 maxy -= 6;
917 start_color();
918 init_pair(1, COLOR_RED, COLOR_BLACK);
919 init_pair(2, COLOR_BLUE, COLOR_BLACK);
920 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
921 init_pair(4, COLOR_GREEN, COLOR_BLACK);
923 wclear(screen);
924 clear();
926 mvwprintw(screen, 1, 2, "Kernel netfilter flows for %s%s%s%s%s%s"
927 "[+%d]", what & INCLUDE_TCP ? "TCP, " : "" ,
928 what & INCLUDE_UDP ? "UDP, " : "",
929 what & INCLUDE_SCTP ? "SCTP, " : "",
930 what & INCLUDE_DCCP ? "DCCP, " : "",
931 what & INCLUDE_ICMP && what & INCLUDE_IPV4 ? "ICMP, " : "",
932 what & INCLUDE_ICMP && what & INCLUDE_IPV6 ? "ICMP6, " : "",
933 skip_lines);
935 rcu_read_lock();
937 if (rcu_dereference(fl->head) == NULL)
938 mvwprintw(screen, line, 2, "(No active sessions! "
939 "Is netfilter running?)");
941 for (i = 0; i < array_size(protocols); i++) {
942 for (j = 0; j < protocol_state_size[protocols[i]]; j++) {
943 n = rcu_dereference(fl->head);
944 while (n && maxy > 0) {
945 int skip_entry = 0;
947 if (n->l4_proto != protocols[i])
948 skip_entry = 1;
949 if (presenter_flow_wrong_state(n, j))
950 skip_entry = 1;
951 if (presenter_get_port(n->port_src,
952 n->port_dst, 0) == 53)
953 skip_entry = 1;
954 if (skip_entry) {
955 n = rcu_dereference(n->next);
956 continue;
958 if (skip_lines > 0) {
959 n = rcu_dereference(n->next);
960 skip_lines--;
961 continue;
964 presenter_screen_do_line(screen, n, &line);
966 line++;
967 maxy -= (2 + 1 * show_src);
968 n = rcu_dereference(n->next);
973 rcu_read_unlock();
975 wrefresh(screen);
976 refresh();
979 static void presenter(void)
981 int skip_lines = 0;
982 WINDOW *screen;
984 dissector_init_ethernet(0);
985 screen = screen_init(false);
987 rcu_register_thread();
988 while (!sigint) {
989 switch (getch()) {
990 case 'q':
991 sigint = 1;
992 break;
993 case KEY_UP:
994 case 'u':
995 case 'k':
996 skip_lines--;
997 if (skip_lines < 0)
998 skip_lines = 0;
999 break;
1000 case KEY_DOWN:
1001 case 'd':
1002 case 'j':
1003 skip_lines++;
1004 if (skip_lines > SCROLL_MAX)
1005 skip_lines = SCROLL_MAX;
1006 break;
1007 default:
1008 fflush(stdin);
1009 break;
1012 presenter_screen_update(screen, &flow_list, skip_lines);
1013 usleep(100000);
1015 rcu_unregister_thread();
1017 screen_end();
1018 dissector_cleanup_ethernet();
1021 static int collector_cb(enum nf_conntrack_msg_type type,
1022 struct nf_conntrack *ct, void *data __maybe_unused)
1024 if (sigint)
1025 return NFCT_CB_STOP;
1027 synchronize_rcu();
1028 spinlock_lock(&flow_list.lock);
1030 switch (type) {
1031 case NFCT_T_NEW:
1032 flow_list_new_entry(&flow_list, ct);
1033 break;
1034 case NFCT_T_UPDATE:
1035 flow_list_update_entry(&flow_list, ct);
1036 break;
1037 case NFCT_T_DESTROY:
1038 flow_list_destroy_entry(&flow_list, ct);
1039 break;
1040 default:
1041 break;
1044 spinlock_unlock(&flow_list.lock);
1046 return NFCT_CB_CONTINUE;
1049 static inline void collector_flush(struct nfct_handle *handle, uint8_t family)
1051 nfct_query(handle, NFCT_Q_FLUSH, &family);
1054 static void *collector(void *null __maybe_unused)
1056 int ret;
1057 struct nfct_handle *handle;
1058 struct nfct_filter *filter;
1060 handle = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1061 NF_NETLINK_CONNTRACK_UPDATE |
1062 NF_NETLINK_CONNTRACK_DESTROY);
1063 if (!handle)
1064 panic("Cannot create a nfct handle!\n");
1066 collector_flush(handle, AF_INET);
1067 collector_flush(handle, AF_INET6);
1069 filter = nfct_filter_create();
1070 if (!filter)
1071 panic("Cannot create a nfct filter!\n");
1073 ret = nfct_filter_attach(nfct_fd(handle), filter);
1074 if (ret < 0)
1075 panic("Cannot attach filter to handle!\n");
1077 if (what & INCLUDE_UDP) {
1078 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1079 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
1081 if (what & INCLUDE_TCP)
1082 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1083 if (what & INCLUDE_DCCP)
1084 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1085 if (what & INCLUDE_SCTP)
1086 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1087 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1088 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1089 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1090 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1091 if (what & INCLUDE_IPV4) {
1092 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4, NFCT_FILTER_LOGIC_NEGATIVE);
1093 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1095 if (what & INCLUDE_IPV6) {
1096 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6, NFCT_FILTER_LOGIC_NEGATIVE);
1097 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1100 ret = nfct_filter_attach(nfct_fd(handle), filter);
1101 if (ret < 0)
1102 panic("Cannot attach filter to handle!\n");
1104 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
1105 nfct_filter_destroy(filter);
1106 flow_list_init(&flow_list);
1108 rcu_register_thread();
1110 while (!sigint && ret >= 0)
1111 ret = nfct_catch(handle);
1113 rcu_unregister_thread();
1115 flow_list_destroy(&flow_list);
1116 nfct_close(handle);
1118 pthread_exit(NULL);
1121 int main(int argc, char **argv)
1123 pthread_t tid;
1124 int ret, c, opt_index, what_cmd = 0;
1126 setfsuid(getuid());
1127 setfsgid(getgid());
1129 while ((c = getopt_long(argc, argv, short_options, long_options,
1130 &opt_index)) != EOF) {
1131 switch (c) {
1132 case '4':
1133 what_cmd |= INCLUDE_IPV4;
1134 break;
1135 case '6':
1136 what_cmd |= INCLUDE_IPV6;
1137 break;
1138 case 'T':
1139 what_cmd |= INCLUDE_TCP;
1140 break;
1141 case 'U':
1142 what_cmd |= INCLUDE_UDP;
1143 break;
1144 case 'D':
1145 what_cmd |= INCLUDE_DCCP;
1146 break;
1147 case 'I':
1148 what_cmd |= INCLUDE_ICMP;
1149 break;
1150 case 'S':
1151 what_cmd |= INCLUDE_SCTP;
1152 break;
1153 case 's':
1154 show_src = 1;
1155 break;
1156 case 'u':
1157 update_geoip();
1158 die();
1159 break;
1160 case 'h':
1161 help();
1162 break;
1163 case 'v':
1164 version();
1165 break;
1166 default:
1167 break;
1171 if (what_cmd > 0)
1172 what = what_cmd;
1174 rcu_init();
1176 register_signal(SIGINT, signal_handler);
1177 register_signal(SIGQUIT, signal_handler);
1178 register_signal(SIGTERM, signal_handler);
1179 register_signal(SIGHUP, signal_handler);
1181 init_geoip(1);
1183 ret = pthread_create(&tid, NULL, collector, NULL);
1184 if (ret < 0)
1185 panic("Cannot create phthread!\n");
1187 presenter();
1189 destroy_geoip();
1191 return 0;