ifpps: also allow F10 to exit screen
[netsniff-ng.git] / src / flowtop.c
blob65b8cdf56fc69a7077982d87ab9994dbd4508fb8
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2011 - 2012 Daniel Borkmann.
5 * Copyright 2011 Emmanuel Roullit.
6 * Subject to the GPL, version 2.
8 * A tiny tool to provide top-like netfilter connection tracking information.
10 * The Dark Lord has Nine. But we have One, mightier than they: the White
11 * Rider. He has passed through the fire and the abyss, and they shall
12 * fear him. We will go where he leads.
14 * -- The Lord of the Rings, Aragorn,
15 * Chapter 'The White Rider'.
18 #define _LGPL_SOURCE
19 #include <stdio.h>
20 #include <stdint.h>
21 #include <stdlib.h>
22 #include <signal.h>
23 #include <getopt.h>
24 #include <pthread.h>
25 #include <signal.h>
26 #include <netdb.h>
27 #include <ctype.h>
28 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
29 #include <libnetfilter_conntrack/libnetfilter_conntrack_tcp.h>
30 #include <libnetfilter_conntrack/libnetfilter_conntrack_dccp.h>
31 #include <libnetfilter_conntrack/libnetfilter_conntrack_sctp.h>
32 #include <GeoIP.h>
33 #include <GeoIPCity.h>
34 #include <netinet/in.h>
35 #include <curses.h>
36 #include <dirent.h>
37 #include <sys/stat.h>
38 #include <urcu.h>
39 #include <libgen.h>
41 #include "die.h"
42 #include "xmalloc.h"
43 #include "xio.h"
44 #include "xutils.h"
45 #include "built_in.h"
46 #include "locking.h"
47 #include "dissector_eth.h"
48 #include "pkt_buff.h"
50 struct geo_ip_db {
51 GeoIP *gi4, *gi6;
52 char *path4, *path6;
55 struct flow_entry {
56 uint32_t flow_id, use, status;
57 uint8_t l3_proto, l4_proto;
58 uint32_t ip4_src_addr, ip4_dst_addr;
59 uint32_t ip6_src_addr[4], ip6_dst_addr[4];
60 uint16_t port_src, port_dst;
61 uint8_t tcp_state, tcp_flags, sctp_state, dccp_state;
62 uint64_t counter_pkts, counter_bytes;
63 uint64_t timestamp_start, timestamp_stop;
64 char country_src[128], country_dst[128];
65 char city_src[128], city_dst[128];
66 char rev_dns_src[256], rev_dns_dst[256];
67 char cmdline[256];
68 struct flow_entry *next;
69 int procnum, inode;
72 struct flow_list {
73 struct flow_entry *head;
74 struct spinlock lock;
77 #ifndef ATTR_TIMESTAMP_START
78 # define ATTR_TIMESTAMP_START 63
79 #endif
80 #ifndef ATTR_TIMESTAMP_STOP
81 # define ATTR_TIMESTAMP_STOP 64
82 #endif
84 #define SCROLL_MAX 1000
86 #define INCLUDE_IPV4 (1 << 0)
87 #define INCLUDE_IPV6 (1 << 1)
88 #define INCLUDE_UDP (1 << 2)
89 #define INCLUDE_TCP (1 << 3)
90 #define INCLUDE_DCCP (1 << 4)
91 #define INCLUDE_ICMP (1 << 5)
92 #define INCLUDE_SCTP (1 << 6)
94 volatile sig_atomic_t sigint = 0;
96 static int what = INCLUDE_IPV4 | INCLUDE_IPV6 | INCLUDE_TCP, show_src = 0;
98 struct geo_ip_db geo_country, geo_city;
100 static struct flow_list flow_list;
102 static const char *short_options = "vhTULKsOPDIS46";
103 static const struct option long_options[] = {
104 {"ipv4", no_argument, NULL, '4'},
105 {"ipv6", no_argument, NULL, '6'},
106 {"tcp", no_argument, NULL, 'T'},
107 {"udp", no_argument, NULL, 'U'},
108 {"dccp", no_argument, NULL, 'D'},
109 {"icmp", no_argument, NULL, 'I'},
110 {"sctp", no_argument, NULL, 'S'},
111 {"show-src", no_argument, NULL, 's'},
112 {"city-db4", required_argument, NULL, 'L'},
113 {"country-db4", required_argument, NULL, 'K'},
114 {"city-db6", required_argument, NULL, 'O'},
115 {"country-db6", required_argument, NULL, 'P'},
116 {"version", no_argument, NULL, 'v'},
117 {"help", no_argument, NULL, 'h'},
118 {NULL, 0, NULL, 0}
121 static const char *const l3proto2str[AF_MAX] = {
122 [AF_INET] = "ipv4",
123 [AF_INET6] = "ipv6",
126 static const char *const l4proto2str[IPPROTO_MAX] = {
127 [IPPROTO_TCP] = "tcp",
128 [IPPROTO_UDP] = "udp",
129 [IPPROTO_UDPLITE] = "udplite",
130 [IPPROTO_ICMP] = "icmp",
131 [IPPROTO_ICMPV6] = "icmpv6",
132 [IPPROTO_SCTP] = "sctp",
133 [IPPROTO_GRE] = "gre",
134 [IPPROTO_DCCP] = "dccp",
135 [IPPROTO_IGMP] = "igmp",
136 [IPPROTO_IPIP] = "ipip",
137 [IPPROTO_EGP] = "egp",
138 [IPPROTO_PUP] = "pup",
139 [IPPROTO_IDP] = "idp",
140 [IPPROTO_RSVP] = "rsvp",
141 [IPPROTO_IPV6] = "ip6tun",
142 [IPPROTO_ESP] = "esp",
143 [IPPROTO_AH] = "ah",
144 [IPPROTO_PIM] = "pim",
145 [IPPROTO_COMP] = "comp",
148 static const char *const tcp_state2str[TCP_CONNTRACK_MAX] = {
149 [TCP_CONNTRACK_NONE] = "NOSTATE",
150 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
151 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
152 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
153 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
154 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
155 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
156 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
157 [TCP_CONNTRACK_CLOSE] = "CLOSE",
158 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
161 static const uint8_t tcp_states[] = {
162 TCP_CONNTRACK_SYN_SENT,
163 TCP_CONNTRACK_SYN_RECV,
164 TCP_CONNTRACK_ESTABLISHED,
165 TCP_CONNTRACK_FIN_WAIT,
166 TCP_CONNTRACK_CLOSE_WAIT,
167 TCP_CONNTRACK_LAST_ACK,
168 TCP_CONNTRACK_TIME_WAIT,
169 TCP_CONNTRACK_CLOSE,
170 TCP_CONNTRACK_SYN_SENT2,
171 TCP_CONNTRACK_NONE,
174 static const char *const dccp_state2str[DCCP_CONNTRACK_MAX] = {
175 [DCCP_CONNTRACK_NONE] = "NOSTATE",
176 [DCCP_CONNTRACK_REQUEST] = "REQUEST",
177 [DCCP_CONNTRACK_RESPOND] = "RESPOND",
178 [DCCP_CONNTRACK_PARTOPEN] = "PARTOPEN",
179 [DCCP_CONNTRACK_OPEN] = "OPEN",
180 [DCCP_CONNTRACK_CLOSEREQ] = "CLOSEREQ",
181 [DCCP_CONNTRACK_CLOSING] = "CLOSING",
182 [DCCP_CONNTRACK_TIMEWAIT] = "TIMEWAIT",
183 [DCCP_CONNTRACK_IGNORE] = "IGNORE",
184 [DCCP_CONNTRACK_INVALID] = "INVALID",
187 static const uint8_t dccp_states[] = {
188 DCCP_CONNTRACK_NONE,
189 DCCP_CONNTRACK_REQUEST,
190 DCCP_CONNTRACK_RESPOND,
191 DCCP_CONNTRACK_PARTOPEN,
192 DCCP_CONNTRACK_OPEN,
193 DCCP_CONNTRACK_CLOSEREQ,
194 DCCP_CONNTRACK_CLOSING,
195 DCCP_CONNTRACK_TIMEWAIT,
196 DCCP_CONNTRACK_IGNORE,
197 DCCP_CONNTRACK_INVALID,
200 static const char *const sctp_state2str[SCTP_CONNTRACK_MAX] = {
201 [SCTP_CONNTRACK_NONE] = "NOSTATE",
202 [SCTP_CONNTRACK_CLOSED] = "CLOSED",
203 [SCTP_CONNTRACK_COOKIE_WAIT] = "COOKIE_WAIT",
204 [SCTP_CONNTRACK_COOKIE_ECHOED] = "COOKIE_ECHOED",
205 [SCTP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
206 [SCTP_CONNTRACK_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
207 [SCTP_CONNTRACK_SHUTDOWN_RECD] = "SHUTDOWN_RECD",
208 [SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = "SHUTDOWN_ACK_SENT",
211 static const uint8_t sctp_states[] = {
212 SCTP_CONNTRACK_NONE,
213 SCTP_CONNTRACK_CLOSED,
214 SCTP_CONNTRACK_COOKIE_WAIT,
215 SCTP_CONNTRACK_COOKIE_ECHOED,
216 SCTP_CONNTRACK_ESTABLISHED,
217 SCTP_CONNTRACK_SHUTDOWN_SENT,
218 SCTP_CONNTRACK_SHUTDOWN_RECD,
219 SCTP_CONNTRACK_SHUTDOWN_ACK_SENT,
222 static const struct nfct_filter_ipv4 filter_ipv4 = {
223 .addr = __constant_htonl(INADDR_LOOPBACK),
224 .mask = 0xffffffff,
227 static const struct nfct_filter_ipv6 filter_ipv6 = {
228 .addr = { 0x0, 0x0, 0x0, 0x1 },
229 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
232 static void signal_handler(int number)
234 switch (number) {
235 case SIGINT:
236 sigint = 1;
237 break;
238 case SIGHUP:
239 default:
240 break;
244 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct);
245 static void flow_entry_get_extended(struct flow_entry *n);
247 static void help(void)
249 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
250 VERSION_STRING);
251 puts("http://www.netsniff-ng.org\n\n"
252 "Usage: flowtop [options]\n"
253 "Options:\n"
254 " -4|--ipv4 Show only IPv4 flows (default)\n"
255 " -6|--ipv6 Show only IPv6 flows (default)\n"
256 " -T|--tcp Show only TCP flows (default)\n"
257 " -U|--udp Show only UDP flows\n"
258 " -D|--dccp Show only DCCP flows\n"
259 " -I|--icmp Show only ICMP/ICMPv6 flows\n"
260 " -S|--sctp Show only SCTP flows\n"
261 " -s|--show-src Also show source, not only dest\n"
262 " --city-db4 <path> Specifiy path for geoip4 city database\n"
263 " --country-db4 <path> Specifiy path for geoip4 country database\n"
264 " --city-db6 <path> Specifiy path for geoip6 city database\n"
265 " --country-db6 <path> Specifiy path for geoip6 country database\n"
266 " -v|--version Print version\n"
267 " -h|--help Print this help\n\n"
268 "Examples:\n"
269 " flowtop\n"
270 " flowtop -46UTDISs\n\n"
271 "Note:\n"
272 " If netfilter is not running, you can activate it with e.g.:\n"
273 " iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
274 " iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n\n"
275 "Please report bugs to <bugs@netsniff-ng.org>\n"
276 "Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
277 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
278 "License: GNU GPL version 2.0\n"
279 "This is free software: you are free to change and redistribute it.\n"
280 "There is NO WARRANTY, to the extent permitted by law.\n");
281 die();
284 static void version(void)
286 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
287 VERSION_STRING);
288 puts("http://www.netsniff-ng.org\n\n"
289 "Please report bugs to <bugs@netsniff-ng.org>\n"
290 "Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
291 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
292 "License: GNU GPL version 2.0\n"
293 "This is free software: you are free to change and redistribute it.\n"
294 "There is NO WARRANTY, to the extent permitted by law.\n");
295 die();
298 static inline struct flow_entry *flow_entry_xalloc(void)
300 return xzmalloc(sizeof(struct flow_entry));
303 static inline void flow_entry_xfree(struct flow_entry *n)
305 xfree(n);
308 static inline void flow_list_init(struct flow_list *fl)
310 fl->head = NULL;
311 spinlock_init(&fl->lock);
314 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
316 struct flow_entry *n = flow_entry_xalloc();
318 flow_entry_from_ct(n, ct);
319 flow_entry_get_extended(n);
321 rcu_assign_pointer(n->next, fl->head);
322 rcu_assign_pointer(fl->head, n);
325 static struct flow_entry *flow_list_find_id(struct flow_list *fl,
326 uint32_t id)
328 struct flow_entry *n = rcu_dereference(fl->head);
330 while (n != NULL) {
331 if (n->flow_id == id)
332 return n;
334 n = rcu_dereference(n->next);
337 return NULL;
340 static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
341 uint32_t id)
343 struct flow_entry *n = rcu_dereference(fl->head), *tmp;
345 if (n->flow_id == id)
346 return NULL;
348 while ((tmp = rcu_dereference(n->next)) != NULL) {
349 if (tmp->flow_id == id)
350 return n;
352 n = tmp;
355 return NULL;
358 static void flow_list_update_entry(struct flow_list *fl,
359 struct nf_conntrack *ct)
361 int do_ext = 0;
362 struct flow_entry *n;
364 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
365 if (n == NULL) {
366 n = flow_entry_xalloc();
367 do_ext = 1;
370 flow_entry_from_ct(n, ct);
371 if (do_ext) {
372 flow_entry_get_extended(n);
374 rcu_assign_pointer(n->next, fl->head);
375 rcu_assign_pointer(fl->head, n);
379 static void flow_list_destroy_entry(struct flow_list *fl,
380 struct nf_conntrack *ct)
382 struct flow_entry *n1, *n2;
383 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
385 n1 = flow_list_find_id(fl, id);
386 if (n1) {
387 n2 = flow_list_find_prev_id(fl, id);
388 if (n2) {
389 rcu_assign_pointer(n2->next, n1->next);
390 rcu_assign_pointer(n1->next, NULL);
392 flow_entry_xfree(n1);
393 } else {
394 flow_entry_xfree(fl->head);
396 rcu_assign_pointer(fl->head, NULL);
401 static void flow_list_destroy(struct flow_list *fl)
403 struct flow_entry *n;
405 while (fl->head != NULL) {
406 n = rcu_dereference(fl->head->next);
407 rcu_assign_pointer(fl->head->next, NULL);
409 flow_entry_xfree(fl->head);
410 rcu_assign_pointer(fl->head, n);
413 synchronize_rcu();
414 spinlock_destroy(&fl->lock);
417 static int walk_process(char *process, struct flow_entry *n)
419 int ret;
420 DIR *dir;
421 struct dirent *ent;
422 char path[1024];
424 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
425 panic("giant process name! %s\n", process);
427 dir = opendir(path);
428 if (!dir)
429 return 0;
431 while ((ent = readdir(dir))) {
432 struct stat statbuf;
434 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
435 process, ent->d_name) < 0)
436 continue;
438 if (stat(path, &statbuf) < 0)
439 continue;
441 if (S_ISSOCK(statbuf.st_mode) && n->inode == statbuf.st_ino) {
442 memset(n->cmdline, 0, sizeof(n->cmdline));
444 snprintf(path, sizeof(path), "/proc/%s/exe", process);
446 ret = readlink(path, n->cmdline,
447 sizeof(n->cmdline) - 1);
448 if (ret < 0)
449 panic("readlink error: %s\n", strerror(errno));
451 n->procnum = atoi(process);
452 return 1;
456 closedir(dir);
457 return 0;
460 static void walk_processes(struct flow_entry *n)
462 int ret;
463 DIR *dir;
464 struct dirent *ent;
466 /* n->inode must be set */
467 if (n->inode <= 0) {
468 memset(n->cmdline, 0, sizeof(n->cmdline));
469 return;
472 dir = opendir("/proc");
473 if (!dir)
474 panic("Cannot open /proc!\n");
476 while ((ent = readdir(dir))) {
477 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name)) {
478 ret = walk_process(ent->d_name, n);
479 if (ret > 0)
480 break;
484 closedir(dir);
487 static int get_port_inode(uint16_t port, int proto, int is_ip6)
489 int ret = -ENOENT;
490 char path[128], buff[1024];
491 FILE *proc;
493 memset(path, 0, sizeof(path));
494 snprintf(path, sizeof(path), "/proc/net/%s%s",
495 l4proto2str[proto], is_ip6 ? "6" : "");
497 proc = fopen(path, "r");
498 if (!proc)
499 return -EIO;
501 memset(buff, 0, sizeof(buff));
503 while (fgets(buff, sizeof(buff), proc) != NULL) {
504 int inode = 0;
505 unsigned int lport = 0;
507 buff[sizeof(buff) - 1] = 0;
508 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
509 "%*X %*u %*u %u", &lport, &inode) == 2) {
510 if ((uint16_t) lport == port) {
511 ret = inode;
512 break;
516 memset(buff, 0, sizeof(buff));
519 fclose(proc);
520 return ret;
523 #define CP_NFCT(elem, attr, x) \
524 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
525 #define CP_NFCT_BUFF(elem, attr) do { \
526 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
527 if (buff != NULL) \
528 memcpy(n->elem, buff, sizeof(n->elem)); \
529 } while (0)
531 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
533 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
534 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
536 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
537 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
539 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
540 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
542 CP_NFCT(status, ATTR_STATUS, 32);
544 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
545 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
546 CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
547 CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
549 CP_NFCT(counter_pkts, ATTR_ORIG_COUNTER_PACKETS, 64);
550 CP_NFCT(counter_bytes, ATTR_ORIG_COUNTER_BYTES, 64);
552 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
553 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
555 CP_NFCT(flow_id, ATTR_ID, 32);
556 CP_NFCT(use, ATTR_USE, 32);
558 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
559 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
561 n->port_src = ntohs(n->port_src);
562 n->port_dst = ntohs(n->port_dst);
564 n->ip4_src_addr = ntohl(n->ip4_src_addr);
565 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
568 enum flow_entry_direction {
569 flow_entry_src,
570 flow_entry_dst,
573 static inline int flow_entry_get_extended_is_dns(struct flow_entry *n)
575 /* We don't want to analyze / display DNS itself, since we
576 * use it to resolve reverse dns.
578 return n->port_src == 53 || n->port_dst == 53;
581 #define SELFLD(dir,src_member,dst_member) \
582 (((dir) == flow_entry_src) ? n->src_member : n->dst_member)
584 static struct sockaddr_in *
585 flow_entry_get_sain4_obj(struct flow_entry *n, enum flow_entry_direction dir,
586 struct sockaddr_in *sa)
588 memset(sa, 0, sizeof(*sa));
589 sa->sin_family = PF_INET;
590 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
592 return sa;
595 static struct sockaddr_in6 *
596 flow_entry_get_sain6_obj(struct flow_entry *n, enum flow_entry_direction dir,
597 struct sockaddr_in6 *sa)
599 memset(sa, 0, sizeof(*sa));
600 sa->sin6_family = PF_INET6;
602 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
603 sizeof(SELFLD(dir, ip6_src_addr, ip6_dst_addr)));
605 return sa;
608 static void
609 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
610 enum flow_entry_direction dir)
612 GeoIPRecord *gir = NULL;
613 struct sockaddr_in sa4;
614 struct sockaddr_in6 sa6;
615 const char *city = NULL;
617 switch (n->l3_proto) {
618 default:
619 bug();
621 case AF_INET:
622 flow_entry_get_sain4_obj(n, dir, &sa4);
623 gir = GeoIP_record_by_ipnum(geo_city.gi4,
624 ntohl(sa4.sin_addr.s_addr));
625 break;
627 case AF_INET6:
628 flow_entry_get_sain6_obj(n, dir, &sa6);
629 gir = GeoIP_record_by_ipnum_v6(geo_city.gi6, sa6.sin6_addr);
630 break;
633 if (gir != NULL)
634 city = gir->city;
636 bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
638 if (city) {
639 memcpy(SELFLD(dir, city_src, city_dst), city,
640 min(sizeof(n->city_src), strlen(city)));
641 } else {
642 memset(SELFLD(dir, city_src, city_dst), 0,
643 sizeof(n->city_src));
647 static void
648 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
649 enum flow_entry_direction dir)
651 struct sockaddr_in sa4;
652 struct sockaddr_in6 sa6;
653 inline const char *make_na(const char *p) { return p ? : "N/A"; }
654 const char *country = NULL;
656 switch (n->l3_proto) {
657 default:
658 bug();
660 case AF_INET:
661 flow_entry_get_sain4_obj(n, dir, &sa4);
662 country = GeoIP_country_name_by_ipnum(geo_country.gi4,
663 ntohl(sa4.sin_addr.s_addr));
664 break;
666 case AF_INET6:
667 flow_entry_get_sain6_obj(n, dir, &sa6);
668 country = GeoIP_country_name_by_ipnum_v6(geo_country.gi6,
669 sa6.sin6_addr);
670 break;
673 country = make_na(country);
675 bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
676 memcpy(SELFLD(dir, country_src, country_dst), country,
677 min(sizeof(n->country_src), strlen(country)));
680 static void flow_entry_get_extended_geo(struct flow_entry *n,
681 enum flow_entry_direction dir)
683 flow_entry_geo_city_lookup_generic(n, dir);
684 flow_entry_geo_country_lookup_generic(n, dir);
687 static void flow_entry_get_extended_revdns(struct flow_entry *n,
688 enum flow_entry_direction dir)
690 size_t sa_len;
691 struct sockaddr_in sa4;
692 struct sockaddr_in6 sa6;
693 struct sockaddr *sa;
694 struct hostent *hent;
696 switch (n->l3_proto) {
697 default:
698 bug();
700 case AF_INET:
701 flow_entry_get_sain4_obj(n, dir, &sa4);
702 sa = (struct sockaddr *) &sa4;
703 sa_len = sizeof(sa4);
704 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr),
705 AF_INET);
706 break;
708 case AF_INET6:
709 flow_entry_get_sain6_obj(n, dir, &sa6);
710 sa = (struct sockaddr *) &sa6;
711 sa_len = sizeof(sa6);
712 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr),
713 AF_INET6);
714 break;
717 bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
718 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
719 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
721 if (hent) {
722 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
723 memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
724 hent->h_name, min(sizeof(n->rev_dns_src),
725 strlen(hent->h_name)));
729 static void flow_entry_get_extended(struct flow_entry *n)
731 if (n->flow_id == 0 || flow_entry_get_extended_is_dns(n))
732 return;
734 flow_entry_get_extended_revdns(n, flow_entry_src);
735 flow_entry_get_extended_geo(n, flow_entry_src);
737 flow_entry_get_extended_revdns(n, flow_entry_dst);
738 flow_entry_get_extended_geo(n, flow_entry_dst);
740 /* Lookup application */
741 n->inode = get_port_inode(n->port_src, n->l4_proto,
742 n->l3_proto == AF_INET6);
743 if (n->inode > 0)
744 walk_processes(n);
747 static uint16_t presenter_get_port(uint16_t src, uint16_t dst, int tcp)
749 if (src < dst && src < 1024) {
750 return src;
751 } else if (dst < src && dst < 1024) {
752 return dst;
753 } else {
754 const char *tmp1, *tmp2;
755 if (tcp) {
756 tmp1 = lookup_port_tcp(src);
757 tmp2 = lookup_port_tcp(dst);
758 } else {
759 tmp1 = lookup_port_udp(src);
760 tmp2 = lookup_port_udp(dst);
762 if (tmp1 && !tmp2) {
763 return src;
764 } else if (!tmp1 && tmp2) {
765 return dst;
766 } else {
767 if (src < dst)
768 return src;
769 else
770 return dst;
775 static void presenter_screen_init(WINDOW **screen)
777 (*screen) = initscr();
778 noecho();
779 cbreak();
780 keypad(stdscr, TRUE);
781 nodelay(*screen, TRUE);
782 refresh();
783 wrefresh(*screen);
786 static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
787 unsigned int *line)
789 char tmp[128], *pname = NULL;
790 uint16_t port;
792 mvwprintw(screen, *line, 2, "");
794 /* PID, application name */
795 if (n->procnum > 0) {
796 slprintf(tmp, sizeof(tmp), "%s(%u)", basename(n->cmdline),
797 n->procnum);
799 printw("[");
800 attron(COLOR_PAIR(3));
801 printw("%s", tmp);
802 attroff(COLOR_PAIR(3));
803 printw("]:");
806 /* L3 protocol, L4 protocol, states */
807 printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
808 printw("[");
809 attron(COLOR_PAIR(3));
810 switch (n->l4_proto) {
811 case IPPROTO_TCP:
812 printw("%s", tcp_state2str[n->tcp_state]);
813 break;
814 case IPPROTO_SCTP:
815 printw("%s", sctp_state2str[n->sctp_state]);
816 break;
817 case IPPROTO_DCCP:
818 printw("%s", dccp_state2str[n->dccp_state]);
819 break;
820 case IPPROTO_UDP:
821 case IPPROTO_UDPLITE:
822 case IPPROTO_ICMP:
823 case IPPROTO_ICMPV6:
824 printw("NOSTATE");
825 break;
827 attroff(COLOR_PAIR(3));
828 printw("]");
830 /* Guess application port */
831 switch (n->l4_proto) {
832 case IPPROTO_TCP:
833 port = presenter_get_port(n->port_src, n->port_dst, 1);
834 pname = lookup_port_tcp(port);
835 break;
836 case IPPROTO_UDP:
837 case IPPROTO_UDPLITE:
838 port = presenter_get_port(n->port_src, n->port_dst, 0);
839 pname = lookup_port_udp(port);
840 break;
842 if (pname) {
843 attron(A_BOLD);
844 printw(":%s", pname);
845 attroff(A_BOLD);
847 printw(" ->");
849 /* Number packets, bytes */
850 if (n->counter_pkts > 0 && n->counter_bytes > 0)
851 printw(" (%llu pkts, %llu bytes) ->",
852 n->counter_pkts, n->counter_bytes);
854 /* Show source information: reverse DNS, port, country, city */
855 if (show_src) {
856 attron(COLOR_PAIR(1));
857 mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
858 attroff(COLOR_PAIR(1));
860 printw(":%u (", n->port_src);
862 attron(COLOR_PAIR(4));
863 printw("%s", n->country_src);
864 attroff(COLOR_PAIR(4));
866 if (n->city_src[0])
867 printw(", %s", n->city_src);
868 printw(") => ");
871 /* Show dest information: reverse DNS, port, country, city */
872 attron(COLOR_PAIR(2));
873 mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
874 attroff(COLOR_PAIR(2));
876 printw(":%u (", n->port_dst);
878 attron(COLOR_PAIR(4));
879 printw("%s", n->country_dst);
880 attroff(COLOR_PAIR(4));
882 if (n->city_dst[0])
883 printw(", %s", n->city_dst);
884 printw(")");
887 static inline int presenter_flow_wrong_state(struct flow_entry *n, int state)
889 int ret = 1;
891 switch (n->l4_proto) {
892 case IPPROTO_TCP:
893 if (n->tcp_state == state)
894 ret = 0;
895 break;
896 case IPPROTO_SCTP:
897 if (n->sctp_state == state)
898 ret = 0;
899 break;
900 case IPPROTO_DCCP:
901 if (n->dccp_state == state)
902 ret = 0;
903 break;
904 case IPPROTO_UDP:
905 case IPPROTO_UDPLITE:
906 case IPPROTO_ICMP:
907 case IPPROTO_ICMPV6:
908 ret = 0;
909 break;
912 return ret;
915 static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
916 int skip_lines)
918 int i, j, maxy;
919 unsigned int line = 3;
920 struct flow_entry *n;
921 uint8_t protocols[] = {
922 IPPROTO_TCP,
923 IPPROTO_DCCP,
924 IPPROTO_SCTP,
925 IPPROTO_UDP,
926 IPPROTO_UDPLITE,
927 IPPROTO_ICMP,
928 IPPROTO_ICMPV6,
930 size_t protocol_state_size[] = {
931 [IPPROTO_TCP] = array_size(tcp_states),
932 [IPPROTO_DCCP] = array_size(dccp_states),
933 [IPPROTO_SCTP] = array_size(sctp_states),
934 [IPPROTO_UDP] = 1,
935 [IPPROTO_UDPLITE] = 1,
936 [IPPROTO_ICMP] = 1,
937 [IPPROTO_ICMPV6] = 1,
940 curs_set(0);
942 maxy = getmaxy(screen);
943 maxy -= 6;
945 start_color();
946 init_pair(1, COLOR_RED, COLOR_BLACK);
947 init_pair(2, COLOR_BLUE, COLOR_BLACK);
948 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
949 init_pair(4, COLOR_GREEN, COLOR_BLACK);
951 wclear(screen);
952 clear();
954 mvwprintw(screen, 1, 2, "Kernel netfilter TCP/UDP "
955 "flow statistics, [+%d]", skip_lines);
957 rcu_read_lock();
959 if (rcu_dereference(fl->head) == NULL)
960 mvwprintw(screen, line, 2, "(No active sessions! "
961 "Is netfilter running?)");
963 for (i = 0; i < array_size(protocols); i++) {
964 for (j = 0; j < protocol_state_size[protocols[i]]; j++) {
965 n = rcu_dereference(fl->head);
966 while (n && maxy > 0) {
967 int skip_entry = 0;
969 if (n->l4_proto != protocols[i])
970 skip_entry = 1;
971 if (presenter_flow_wrong_state(n, j))
972 skip_entry = 1;
973 if (presenter_get_port(n->port_src,
974 n->port_dst, 0) == 53)
975 skip_entry = 1;
976 if (skip_entry) {
977 n = rcu_dereference(n->next);
978 continue;
980 if (skip_lines > 0) {
981 n = rcu_dereference(n->next);
982 skip_lines--;
983 continue;
986 presenter_screen_do_line(screen, n, &line);
988 line++;
989 maxy -= (2 + 1 * show_src);
990 n = rcu_dereference(n->next);
995 rcu_read_unlock();
997 wrefresh(screen);
998 refresh();
1001 static inline void presenter_screen_end(void)
1003 endwin();
1006 static void presenter(void)
1008 int skip_lines = 0;
1009 WINDOW *screen = NULL;
1011 dissector_init_ethernet(0);
1012 presenter_screen_init(&screen);
1014 rcu_register_thread();
1015 while (!sigint) {
1016 switch (getch()) {
1017 case 'q':
1018 sigint = 1;
1019 break;
1020 case KEY_UP:
1021 case 'u':
1022 case 'k':
1023 skip_lines--;
1024 if (skip_lines < 0)
1025 skip_lines = 0;
1026 break;
1027 case KEY_DOWN:
1028 case 'd':
1029 case 'j':
1030 skip_lines++;
1031 if (skip_lines > SCROLL_MAX)
1032 skip_lines = SCROLL_MAX;
1033 break;
1034 default:
1035 fflush(stdin);
1036 break;
1039 presenter_screen_update(screen, &flow_list, skip_lines);
1040 usleep(100000);
1042 rcu_unregister_thread();
1044 presenter_screen_end();
1045 dissector_cleanup_ethernet();
1048 static int collector_cb(enum nf_conntrack_msg_type type,
1049 struct nf_conntrack *ct, void *data)
1051 if (sigint)
1052 return NFCT_CB_STOP;
1054 synchronize_rcu();
1055 spinlock_lock(&flow_list.lock);
1057 switch (type) {
1058 case NFCT_T_NEW:
1059 flow_list_new_entry(&flow_list, ct);
1060 break;
1061 case NFCT_T_UPDATE:
1062 flow_list_update_entry(&flow_list, ct);
1063 break;
1064 case NFCT_T_DESTROY:
1065 flow_list_destroy_entry(&flow_list, ct);
1066 break;
1067 default:
1068 break;
1071 spinlock_unlock(&flow_list.lock);
1073 return NFCT_CB_CONTINUE;
1076 static inline GeoIP *collector_geoip_open(const char *path, int type)
1078 if (path != NULL)
1079 return GeoIP_open(path, GEOIP_MMAP_CACHE);
1080 else
1081 return GeoIP_open_type(type, GEOIP_MMAP_CACHE);
1084 static void collector_load_geoip(void)
1086 geo_country.gi4 = collector_geoip_open(geo_country.path4,
1087 GEOIP_COUNTRY_EDITION);
1088 if (geo_country.gi4 == NULL)
1089 panic("Cannot open GeoIP4 country database!\n");
1091 geo_country.gi6 = collector_geoip_open(geo_country.path6,
1092 GEOIP_COUNTRY_EDITION_V6);
1093 if (geo_country.gi6 == NULL)
1094 panic("Cannot open GeoIP6 country database!\n");
1096 geo_city.gi4 = collector_geoip_open(geo_city.path4,
1097 GEOIP_CITY_EDITION_REV1);
1098 if (geo_city.gi4 == NULL)
1099 panic("Cannot open GeoIP4 city database!\n");
1101 geo_city.gi6 = collector_geoip_open(geo_city.path6,
1102 GEOIP_CITY_EDITION_REV1_V6);
1103 if (geo_city.gi6 == NULL)
1104 panic("Cannot open GeoIP6 city database!\n");
1106 GeoIP_set_charset(geo_country.gi4, GEOIP_CHARSET_UTF8);
1107 GeoIP_set_charset(geo_country.gi6, GEOIP_CHARSET_UTF8);
1109 GeoIP_set_charset(geo_city.gi4, GEOIP_CHARSET_UTF8);
1110 GeoIP_set_charset(geo_city.gi6, GEOIP_CHARSET_UTF8);
1113 static void collector_destroy_geoip(void)
1115 GeoIP_delete(geo_country.gi4);
1116 GeoIP_delete(geo_country.gi6);
1118 GeoIP_delete(geo_city.gi4);
1119 GeoIP_delete(geo_city.gi6);
1122 static void inline collector_flush(struct nfct_handle *handle, uint8_t family)
1124 nfct_query(handle, NFCT_Q_FLUSH, &family);
1127 static void *collector(void *null)
1129 int ret;
1130 struct nfct_handle *handle;
1131 struct nfct_filter *filter;
1133 handle = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1134 NF_NETLINK_CONNTRACK_UPDATE |
1135 NF_NETLINK_CONNTRACK_DESTROY);
1136 if (!handle)
1137 panic("Cannot create a nfct handle!\n");
1139 collector_flush(handle, AF_INET);
1140 collector_flush(handle, AF_INET6);
1142 filter = nfct_filter_create();
1143 if (!filter)
1144 panic("Cannot create a nfct filter!\n");
1146 ret = nfct_filter_attach(nfct_fd(handle), filter);
1147 if (ret < 0)
1148 panic("Cannot attach filter to handle!\n");
1150 if (what & INCLUDE_UDP) {
1151 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1152 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
1154 if (what & INCLUDE_TCP)
1155 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1156 if (what & INCLUDE_DCCP)
1157 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1158 if (what & INCLUDE_SCTP)
1159 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1160 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1161 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1162 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1163 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1164 if (what & INCLUDE_IPV4) {
1165 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4,
1166 NFCT_FILTER_LOGIC_NEGATIVE);
1167 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1169 if (what & INCLUDE_IPV6) {
1170 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6,
1171 NFCT_FILTER_LOGIC_NEGATIVE);
1172 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1175 ret = nfct_filter_attach(nfct_fd(handle), filter);
1176 if (ret < 0)
1177 panic("Cannot attach filter to handle!\n");
1179 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
1181 nfct_filter_destroy(filter);
1183 collector_load_geoip();
1185 flow_list_init(&flow_list);
1187 rcu_register_thread();
1189 while (!sigint && ret >= 0)
1190 ret = nfct_catch(handle);
1192 rcu_unregister_thread();
1194 flow_list_destroy(&flow_list);
1196 collector_destroy_geoip();
1198 nfct_close(handle);
1200 pthread_exit(0);
1203 int main(int argc, char **argv)
1205 pthread_t tid;
1206 int ret, c, opt_index, what_cmd = 0;
1208 memset(&geo_country, 0, sizeof(geo_country));
1209 memset(&geo_city, 0, sizeof(geo_city));
1211 while ((c = getopt_long(argc, argv, short_options, long_options,
1212 &opt_index)) != EOF) {
1213 switch (c) {
1214 case '4':
1215 what_cmd |= INCLUDE_IPV4;
1216 break;
1217 case '6':
1218 what_cmd |= INCLUDE_IPV6;
1219 break;
1220 case 'T':
1221 what_cmd |= INCLUDE_TCP;
1222 break;
1223 case 'U':
1224 what_cmd |= INCLUDE_UDP;
1225 break;
1226 case 'D':
1227 what_cmd |= INCLUDE_DCCP;
1228 break;
1229 case 'I':
1230 what_cmd |= INCLUDE_ICMP;
1231 break;
1232 case 'S':
1233 what_cmd |= INCLUDE_SCTP;
1234 break;
1235 case 's':
1236 show_src = 1;
1237 break;
1238 case 'L':
1239 geo_city.path4 = xstrdup(optarg);
1240 break;
1241 case 'K':
1242 geo_country.path4 = xstrdup(optarg);
1243 break;
1244 case 'O':
1245 geo_city.path6 = xstrdup(optarg);
1246 break;
1247 case 'P':
1248 geo_country.path6 = xstrdup(optarg);
1249 break;
1250 case 'h':
1251 help();
1252 break;
1253 case 'v':
1254 version();
1255 break;
1256 case '?':
1257 switch (optopt) {
1258 case 'L':
1259 case 'K':
1260 case 'O':
1261 case 'P':
1262 panic("Option -%c requires an argument!\n",
1263 optopt);
1264 default:
1265 if (isprint(optopt))
1266 whine("Unknown option character "
1267 "`0x%X\'!\n", optopt);
1268 die();
1270 default:
1271 break;
1275 if (what_cmd > 0)
1276 what = what_cmd;
1278 rcu_init();
1280 register_signal(SIGINT, signal_handler);
1281 register_signal(SIGHUP, signal_handler);
1283 ret = pthread_create(&tid, NULL, collector, NULL);
1284 if (ret < 0)
1285 panic("Cannot create phthread!\n");
1287 presenter();
1289 free(geo_country.path4);
1290 free(geo_country.path6);
1292 free(geo_city.path4);
1293 free(geo_city.path6);
1295 return 0;