2 * ss.c "sockstat", socket statistics
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
17 #include <sys/ioctl.h>
18 #include <sys/socket.h>
20 #include <netinet/in.h>
24 #include <arpa/inet.h>
33 #include "libnetlink.h"
36 #include <netinet/tcp.h>
37 #include <linux/inet_diag.h>
39 int resolve_hosts = 0;
40 int resolve_services = 1;
41 int preferred_family = AF_UNSPEC;
55 static const char *TCP_PROTO = "tcp";
56 static const char *UDP_PROTO = "udp";
57 static const char *RAW_PROTO = "raw";
58 static const char *dg_proto = NULL;
74 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
75 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB))
76 #define ALL_DB ((1<<MAX_DB)-1)
94 #define SS_ALL ((1<<SS_MAX)-1)
106 struct filter default_filter = {
108 .states = SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)),
109 .families= (1<<AF_INET)|(1<<AF_INET6),
112 struct filter current_filter;
114 static FILE *generic_proc_open(const char *env, const char *name)
116 const char *p = getenv(env);
120 p = getenv("PROC_ROOT") ? : "/proc";
121 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
125 return fopen(p, "r");
128 static FILE *net_tcp_open(void)
130 return generic_proc_open("PROC_NET_TCP", "net/tcp");
133 static FILE *net_tcp6_open(void)
135 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
138 static FILE *net_udp_open(void)
140 return generic_proc_open("PROC_NET_UDP", "net/udp");
143 static FILE *net_udp6_open(void)
145 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
148 static FILE *net_raw_open(void)
150 return generic_proc_open("PROC_NET_RAW", "net/raw");
153 static FILE *net_raw6_open(void)
155 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
158 static FILE *net_unix_open(void)
160 return generic_proc_open("PROC_NET_UNIX", "net/unix");
163 static FILE *net_packet_open(void)
165 return generic_proc_open("PROC_NET_PACKET", "net/packet");
168 static FILE *net_netlink_open(void)
170 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
173 static FILE *slabinfo_open(void)
175 return generic_proc_open("PROC_SLABINFO", "slabinfo");
178 static FILE *net_sockstat_open(void)
180 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
183 static FILE *net_sockstat6_open(void)
185 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
188 static FILE *net_snmp_open(void)
190 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
193 static FILE *ephemeral_ports_open(void)
195 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
198 int find_users(unsigned ino, char *buf, int buflen)
212 sprintf(pattern, "socket:[%u]", ino);
213 pattern_len = strlen(pattern);
215 strncpy(name, getenv("PROC_ROOT") ? : "/proc/", sizeof(name)/2);
216 name[sizeof(name)/2] = 0;
217 if (strlen(name) == 0 ||
218 name[strlen(name)-1] != '/')
220 nameoff = strlen(name);
221 if ((dir = opendir(name)) == NULL)
224 while ((d = readdir(dir)) != NULL) {
232 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
235 sprintf(name+nameoff, "%d/fd/", pid);
237 if ((dir1 = opendir(name)) == NULL)
242 while ((d1 = readdir(dir1)) != NULL) {
246 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
249 sprintf(name+pos, "%d", fd);
250 n = readlink(name, lnk, sizeof(lnk)-1);
251 if (n != pattern_len ||
252 memcmp(lnk, pattern, n))
255 if (ptr-buf >= buflen-1)
258 if (process[0] == 0) {
261 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
262 getenv("PROC_ROOT") ? : "/proc", pid);
263 if ((fp = fopen(tmp, "r")) != NULL) {
264 fscanf(fp, "%*d (%[^)])", process);
269 snprintf(ptr, buflen-(ptr-buf), "(\"%s\",%d,%d),", process, pid, fd);
282 /* Get stats from slab */
293 struct slabstat slabstat;
295 static const char *slabstat_ids[] =
304 int get_slabstat(struct slabstat *s)
310 memset(s, 0, sizeof(*s));
312 fp = slabinfo_open();
316 cnt = sizeof(*s)/sizeof(int);
318 fgets(buf, sizeof(buf), fp);
319 while(fgets(buf, sizeof(buf), fp) != NULL) {
321 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
322 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
323 sscanf(buf, "%*s%d", ((int *)s) + i);
336 static const char *sstate_name[] = {
338 [TCP_ESTABLISHED] = "ESTAB",
339 [TCP_SYN_SENT] = "SYN-SENT",
340 [TCP_SYN_RECV] = "SYN-RECV",
341 [TCP_FIN_WAIT1] = "FIN-WAIT-1",
342 [TCP_FIN_WAIT2] = "FIN-WAIT-2",
343 [TCP_TIME_WAIT] = "TIME-WAIT",
344 [TCP_CLOSE] = "UNCONN",
345 [TCP_CLOSE_WAIT] = "CLOSE-WAIT",
346 [TCP_LAST_ACK] = "LAST-ACK",
347 [TCP_LISTEN] = "LISTEN",
348 [TCP_CLOSING] = "CLOSING",
351 static const char *sstate_namel[] = {
353 [TCP_ESTABLISHED] = "established",
354 [TCP_SYN_SENT] = "syn-sent",
355 [TCP_SYN_RECV] = "syn-recv",
356 [TCP_FIN_WAIT1] = "fin-wait-1",
357 [TCP_FIN_WAIT2] = "fin-wait-2",
358 [TCP_TIME_WAIT] = "time-wait",
359 [TCP_CLOSE] = "unconnected",
360 [TCP_CLOSE_WAIT] = "close-wait",
361 [TCP_LAST_ACK] = "last-ack",
362 [TCP_LISTEN] = "listening",
363 [TCP_CLOSING] = "closing",
381 unsigned long long sk;
382 int rto, ato, qack, cwnd, ssthresh;
385 static const char *tmr_name[] = {
394 const char *print_ms_timer(int timeout)
397 int secs, msecs, minutes;
403 msecs = timeout%1000;
407 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
414 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
417 sprintf(buf+strlen(buf), "%03dms", msecs);
421 const char *print_hz_timer(int timeout)
423 int hz = get_user_hz();
424 return print_ms_timer(((timeout*1000) + hz-1)/hz);
435 struct scache *rlist;
437 void init_service_resolver(void)
440 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
442 fgets(buf, sizeof(buf), fp);
443 while (fgets(buf, sizeof(buf), fp) != NULL) {
444 unsigned int progn, port;
445 char proto[128], prog[128];
446 if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
447 &port, prog+4) == 4) {
448 struct scache *c = malloc(sizeof(*c));
451 memcpy(prog, "rpc.", 4);
452 c->name = strdup(prog);
453 if (strcmp(proto, TCP_PROTO) == 0)
454 c->proto = TCP_PROTO;
455 else if (strcmp(proto, UDP_PROTO) == 0)
456 c->proto = UDP_PROTO;
467 static int ip_local_port_min, ip_local_port_max;
469 /* Even do not try default linux ephemeral port ranges:
470 * default /etc/services contains so much of useless crap
471 * wouldbe "allocated" to this area that resolution
472 * is really harmful. I shrug each time when seeing
473 * "socks" or "cfinger" in dumps.
475 static int is_ephemeral(int port)
477 if (!ip_local_port_min) {
478 FILE *f = ephemeral_ports_open();
481 &ip_local_port_min, &ip_local_port_max);
484 ip_local_port_min = 1024;
485 ip_local_port_max = 4999;
489 return (port >= ip_local_port_min && port<= ip_local_port_max);
493 const char *__resolve_service(int port)
497 for (c = rlist; c; c = c->next) {
498 if (c->port == port && c->proto == dg_proto)
502 if (!is_ephemeral(port)) {
509 se = getservbyport(htons(port), dg_proto);
518 const char *resolve_service(int port)
520 static char buf[128];
521 static struct scache cache[256];
529 if (resolve_services) {
530 if (dg_proto == RAW_PROTO) {
531 return inet_proto_n2a(port, buf, sizeof(buf));
535 int hash = (port^(((unsigned long)dg_proto)>>2))&255;
537 for (c = &cache[hash]; c; c = c->next) {
538 if (c->port == port &&
539 c->proto == dg_proto) {
546 if ((res = __resolve_service(port)) != NULL) {
547 if ((c = malloc(sizeof(*c))) == NULL)
558 c->name = strdup(res);
559 c->next = cache[hash].next;
560 cache[hash].next = c;
568 sprintf(buf, "%u", port);
572 void formatted_print(const inet_prefix *a, int port)
575 const char *ap = buf;
578 est_len = addr_width;
580 if (a->family == AF_INET) {
581 if (a->data[0] == 0) {
585 ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
588 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
589 est_len = strlen(ap);
590 if (est_len <= addr_width)
591 est_len = addr_width;
593 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
595 printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
602 struct aafilter *next;
605 int inet2_addr_match(const inet_prefix *a, const inet_prefix *p, int plen)
607 if (!inet_addr_match(a, p, plen))
610 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
611 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
613 if (p->family == AF_INET && a->family == AF_INET6) {
614 if (a->data[0] == 0 && a->data[1] == 0 &&
615 a->data[2] == htonl(0xffff)) {
616 inet_prefix tmp = *a;
617 tmp.data[0] = a->data[3];
618 return inet_addr_match(&tmp, p, plen);
624 int unix_match(const inet_prefix *a, const inet_prefix *p)
626 char *addr, *pattern;
627 memcpy(&addr, a->data, sizeof(addr));
628 memcpy(&pattern, p->data, sizeof(pattern));
633 return !fnmatch(pattern, addr, 0);
636 int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
641 static int low, high=65535;
643 if (s->local.family == AF_UNIX) {
645 memcpy(&p, s->local.data, sizeof(p));
646 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
647 strspn(p+1, "0123456789abcdef") == 5);
649 if (s->local.family == AF_PACKET)
650 return s->lport == 0 && s->local.data == 0;
651 if (s->local.family == AF_NETLINK)
655 FILE *fp = ephemeral_ports_open();
657 fscanf(fp, "%d%d", &low, &high);
661 return s->lport >= low && s->lport <= high;
665 struct aafilter *a = (void*)f->pred;
666 if (a->addr.family == AF_UNIX)
667 return unix_match(&s->remote, &a->addr);
668 if (a->port != -1 && a->port != s->rport)
670 if (a->addr.bitlen) {
672 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
674 } while ((a = a->next) != NULL);
681 struct aafilter *a = (void*)f->pred;
682 if (a->addr.family == AF_UNIX)
683 return unix_match(&s->local, &a->addr);
684 if (a->port != -1 && a->port != s->lport)
686 if (a->addr.bitlen) {
688 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
690 } while ((a = a->next) != NULL);
697 struct aafilter *a = (void*)f->pred;
698 return s->rport >= a->port;
702 struct aafilter *a = (void*)f->pred;
703 return s->rport <= a->port;
707 struct aafilter *a = (void*)f->pred;
708 return s->lport >= a->port;
712 struct aafilter *a = (void*)f->pred;
713 return s->lport <= a->port;
716 /* Yup. It is recursion. Sorry. */
718 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
720 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
722 return !run_ssfilter(f->pred, s);
728 /* Relocate external jumps by reloc. */
729 static void ssfilter_patch(char *a, int len, int reloc)
732 struct inet_diag_bc_op *op = (struct inet_diag_bc_op*)a;
742 static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
747 if (!(*bytecode=malloc(4))) abort();
748 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
754 struct aafilter *a = (void*)f->pred;
757 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
760 for (b=a; b; b=b->next) {
761 len += 4 + sizeof(struct inet_diag_hostcond);
762 if (a->addr.family == AF_INET6)
769 if (!(ptr = malloc(len))) abort();
771 for (b=a; b; b=b->next) {
772 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
773 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
774 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
775 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond*)(ptr+4);
777 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
778 cond->family = a->addr.family;
779 cond->port = a->port;
780 cond->prefix_len = a->addr.bitlen;
781 memcpy(cond->addr, a->addr.data, alen);
784 op = (struct inet_diag_bc_op *)ptr;
785 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
789 return ptr - *bytecode;
793 struct aafilter *x = (void*)f->pred;
794 if (!(*bytecode=malloc(8))) abort();
795 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
796 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
801 struct aafilter *x = (void*)f->pred;
802 if (!(*bytecode=malloc(8))) abort();
803 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
804 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
809 struct aafilter *x = (void*)f->pred;
810 if (!(*bytecode=malloc(8))) abort();
811 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
812 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
817 struct aafilter *x = (void*)f->pred;
818 if (!(*bytecode=malloc(8))) abort();
819 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
820 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
826 char *a1, *a2, *a, l1, l2;
827 l1 = ssfilter_bytecompile(f->pred, &a1);
828 l2 = ssfilter_bytecompile(f->post, &a2);
829 if (!(a = malloc(l1+l2))) abort();
831 memcpy(a+l1, a2, l2);
833 ssfilter_patch(a, l1, l2);
839 char *a1, *a2, *a, l1, l2;
840 l1 = ssfilter_bytecompile(f->pred, &a1);
841 l2 = ssfilter_bytecompile(f->post, &a2);
842 if (!(a = malloc(l1+l2+4))) abort();
844 memcpy(a+l1+4, a2, l2);
846 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
853 l1 = ssfilter_bytecompile(f->pred, &a1);
854 if (!(a = malloc(l1+4))) abort();
857 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
866 static int remember_he(struct aafilter *a, struct hostent *he)
868 char **ptr = he->h_addr_list;
872 if (he->h_addrtype == AF_INET)
874 else if (he->h_addrtype == AF_INET6)
880 struct aafilter *b = a;
881 if (a->addr.bitlen) {
882 if ((b = malloc(sizeof(*b))) == NULL)
888 memcpy(b->addr.data, *ptr, len);
889 b->addr.bytelen = len;
890 b->addr.bitlen = len*8;
891 b->addr.family = he->h_addrtype;
898 static int get_dns_host(struct aafilter *a, const char *addr, int fam)
909 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
911 cnt = remember_he(a, he);
912 if (fam == AF_UNSPEC) {
913 he = gethostbyname2(addr, AF_INET6);
915 cnt += remember_he(a, he);
920 static int xll_initted = 0;
922 static void xll_init(void)
924 struct rtnl_handle rth;
931 static const char *xll_index_to_name(int index)
935 return ll_index_to_name(index);
938 static int xll_name_to_index(const char *dev)
942 return ll_name_to_index(dev);
945 void *parse_hostcond(char *addr)
949 struct aafilter *res;
950 int fam = preferred_family;
952 memset(&a, 0, sizeof(a));
955 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
957 a.addr.family = AF_UNIX;
958 if (strncmp(addr, "unix:", 5) == 0)
961 a.addr.bitlen = 8*strlen(p);
962 memcpy(a.addr.data, &p, sizeof(p));
966 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
967 a.addr.family = AF_PACKET;
969 if (strncmp(addr, "link:", 5) == 0)
971 port = strchr(addr, ':');
974 if (port[1] && strcmp(port+1, "*")) {
975 if (get_integer(&a.port, port+1, 0)) {
976 if ((a.port = xll_name_to_index(port+1)) <= 0)
981 if (addr[0] && strcmp(addr, "*")) {
984 if (ll_proto_a2n(&tmp, addr))
986 a.addr.data[0] = ntohs(tmp);
991 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
992 a.addr.family = AF_NETLINK;
994 if (strncmp(addr, "netlink:", 8) == 0)
996 port = strchr(addr, ':');
999 if (port[1] && strcmp(port+1, "*")) {
1000 if (get_integer(&a.port, port+1, 0)) {
1001 if (strcmp(port+1, "kernel") == 0)
1008 if (addr[0] && strcmp(addr, "*")) {
1010 if (get_u32(a.addr.data, addr, 0)) {
1011 if (strcmp(addr, "rtnl") == 0)
1013 else if (strcmp(addr, "fw") == 0)
1015 else if (strcmp(addr, "tcpdiag") == 0)
1024 if (strncmp(addr, "inet:", 5) == 0) {
1027 } else if (strncmp(addr, "inet6:", 6) == 0) {
1032 /* URL-like literal [] */
1033 if (addr[0] == '[') {
1035 if ((port = strchr(addr, ']')) == NULL)
1038 } else if (addr[0] == '*') {
1041 port = strrchr(strchr(addr, '/') ? : addr, ':');
1043 if (port && *port) {
1047 if (*port && *port != '*') {
1048 if (get_integer(&a.port, port, 0)) {
1049 struct servent *se1 = NULL;
1050 struct servent *se2 = NULL;
1051 if (current_filter.dbs&(1<<UDP_DB))
1052 se1 = getservbyname(port, UDP_PROTO);
1053 if (current_filter.dbs&(1<<TCP_DB))
1054 se2 = getservbyname(port, TCP_PROTO);
1055 if (se1 && se2 && se1->s_port != se2->s_port) {
1056 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1062 a.port = ntohs(se1->s_port);
1065 for (s = rlist; s; s = s->next) {
1066 if ((s->proto == UDP_PROTO &&
1067 (current_filter.dbs&(1<<UDP_DB))) ||
1068 (s->proto == TCP_PROTO &&
1069 (current_filter.dbs&(1<<TCP_DB)))) {
1070 if (s->name && strcmp(s->name, port) == 0) {
1071 if (a.port > 0 && a.port != s->port) {
1072 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1080 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1087 if (addr && *addr && *addr != '*') {
1088 if (get_prefix_1(&a.addr, addr, fam)) {
1089 if (get_dns_host(&a, addr, fam)) {
1090 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1097 res = malloc(sizeof(*res));
1099 memcpy(res, &a, sizeof(a));
1103 static int tcp_show_line(char *line, const struct filter *f, int family)
1106 char *loc, *rem, *data;
1111 if ((p = strchr(line, ':')) == NULL)
1115 if ((p = strchr(loc, ':')) == NULL)
1120 if ((p = strchr(rem, ':')) == NULL)
1126 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1128 if (!(f->states & (1<<state)))
1132 s.local.family = s.remote.family = family;
1133 if (family == AF_INET) {
1134 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1135 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1136 s.local.bytelen = s.remote.bytelen = 4;
1138 sscanf(loc, "%08x%08x%08x%08x:%x",
1144 sscanf(rem, "%08x%08x%08x%08x:%x",
1150 s.local.bytelen = s.remote.bytelen = 16;
1153 if (f->f && run_ssfilter(f->f, &s) == 0)
1157 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
1158 &s.state, &s.wq, &s.rq,
1159 &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1160 &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1161 &s.cwnd, &s.ssthresh, opt);
1174 printf("%-*s ", netid_width, "tcp");
1176 printf("%-*s ", state_width, sstate_name[s.state]);
1178 printf("%-6d %-6d ", s.rq, s.wq);
1180 formatted_print(&s.local, s.lport);
1181 formatted_print(&s.remote, s.rport);
1187 printf(" timer:(%s,%s,%d)",
1189 print_hz_timer(s.timeout),
1190 s.timer != 1 ? s.probes : s.retrs);
1194 int hz = get_user_hz();
1195 if (s.rto && s.rto != 3*hz)
1196 printf(" rto:%g", (double)s.rto/hz);
1198 printf(" ato:%g", (double)s.ato/hz);
1200 printf(" cwnd:%d", s.cwnd);
1201 if (s.ssthresh != -1)
1202 printf(" ssthresh:%d", s.ssthresh);
1204 printf(" qack:%d", s.qack/2);
1210 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1211 printf(" users:(%s)", ubuf);
1215 printf(" uid:%u", (unsigned)s.uid);
1216 printf(" ino:%u", s.ino);
1217 printf(" sk:%llx", s.sk);
1219 printf(" opt:\"%s\"", opt);
1226 static int generic_record_read(FILE *fp,
1227 int (*worker)(char*, const struct filter *, int),
1228 const struct filter *f, int fam)
1233 if (fgets(line, sizeof(line), fp) == NULL)
1236 while (fgets(line, sizeof(line), fp) != NULL) {
1237 int n = strlen(line);
1238 if (n == 0 || line[n-1] != '\n') {
1244 if (worker(line, f, fam) < 0)
1249 return ferror(fp) ? -1 : 0;
1252 static char *sprint_bw(char *buf, double bw)
1255 sprintf(buf,"%.1fM", bw / 1000000.);
1256 else if (bw > 1000.)
1257 sprintf(buf,"%.1fK", bw / 1000.);
1259 sprintf(buf, "%g", bw);
1264 static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r)
1266 struct rtattr * tb[INET_DIAG_MAX+1];
1270 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr*)(r+1),
1271 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1273 if (tb[INET_DIAG_MEMINFO]) {
1274 const struct inet_diag_meminfo *minfo
1275 = RTA_DATA(tb[INET_DIAG_MEMINFO]);
1276 printf(" mem:(r%u,w%u,f%u,t%u)",
1283 if (tb[INET_DIAG_INFO]) {
1284 struct tcp_info *info;
1285 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
1287 /* workaround for older kernels with less fields */
1288 if (len < sizeof(*info)) {
1289 info = alloca(sizeof(*info));
1290 memset(info, 0, sizeof(*info));
1291 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
1293 info = RTA_DATA(tb[INET_DIAG_INFO]);
1296 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1298 if (info->tcpi_options & TCPI_OPT_SACK)
1300 if (info->tcpi_options & TCPI_OPT_ECN)
1304 if (tb[INET_DIAG_CONG])
1305 printf(" %s", (char *) RTA_DATA(tb[INET_DIAG_CONG]));
1307 if (info->tcpi_options & TCPI_OPT_WSCALE)
1308 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1309 info->tcpi_rcv_wscale);
1310 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1311 printf(" rto:%g", (double)info->tcpi_rto/1000);
1313 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1314 (double)info->tcpi_rttvar/1000);
1316 printf(" ato:%g", (double)info->tcpi_ato/1000);
1317 if (info->tcpi_snd_cwnd != 2)
1318 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1319 if (info->tcpi_snd_ssthresh < 0xFFFF)
1320 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1322 rtt = (double) info->tcpi_rtt;
1323 if (tb[INET_DIAG_VEGASINFO]) {
1324 const struct tcpvegas_info *vinfo
1325 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
1327 if (vinfo->tcpv_enabled &&
1328 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
1329 rtt = vinfo->tcpv_rtt;
1332 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1333 printf(" send %sbps",
1334 sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1335 (double) info->tcpi_snd_mss * 8000000.
1339 if (info->tcpi_rcv_rtt)
1340 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1341 if (info->tcpi_rcv_space)
1342 printf(" rcv_space:%d", info->tcpi_rcv_space);
1347 static int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
1349 struct inet_diag_msg *r = NLMSG_DATA(nlh);
1352 s.state = r->idiag_state;
1353 s.local.family = s.remote.family = r->idiag_family;
1354 s.lport = ntohs(r->id.idiag_sport);
1355 s.rport = ntohs(r->id.idiag_dport);
1356 if (s.local.family == AF_INET) {
1357 s.local.bytelen = s.remote.bytelen = 4;
1359 s.local.bytelen = s.remote.bytelen = 16;
1361 memcpy(s.local.data, r->id.idiag_src, s.local.bytelen);
1362 memcpy(s.remote.data, r->id.idiag_dst, s.local.bytelen);
1364 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1368 printf("%-*s ", netid_width, "tcp");
1370 printf("%-*s ", state_width, sstate_name[s.state]);
1372 printf("%-6d %-6d ", r->idiag_rqueue, r->idiag_wqueue);
1374 formatted_print(&s.local, s.lport);
1375 formatted_print(&s.remote, s.rport);
1378 if (r->idiag_timer) {
1379 if (r->idiag_timer > 4)
1381 printf(" timer:(%s,%s,%d)",
1382 tmr_name[r->idiag_timer],
1383 print_ms_timer(r->idiag_expires),
1389 if (find_users(r->idiag_inode, ubuf, sizeof(ubuf)) > 0)
1390 printf(" users:(%s)", ubuf);
1394 printf(" uid:%u", (unsigned)r->idiag_uid);
1395 printf(" ino:%u", r->idiag_inode);
1397 if (r->id.idiag_cookie[1] != 0)
1398 printf("%08x", r->id.idiag_cookie[1]);
1399 printf("%08x", r->id.idiag_cookie[0]);
1401 if (show_mem || show_tcpinfo) {
1403 tcp_show_info(nlh, r);
1411 static int tcp_show_netlink(struct filter *f, FILE *dump_fp, int socktype)
1414 struct sockaddr_nl nladdr;
1416 struct nlmsghdr nlh;
1417 struct inet_diag_req r;
1424 struct iovec iov[3];
1426 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
1429 memset(&nladdr, 0, sizeof(nladdr));
1430 nladdr.nl_family = AF_NETLINK;
1432 req.nlh.nlmsg_len = sizeof(req);
1433 req.nlh.nlmsg_type = socktype;
1434 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1435 req.nlh.nlmsg_pid = 0;
1436 req.nlh.nlmsg_seq = 123456;
1437 memset(&req.r, 0, sizeof(req.r));
1438 req.r.idiag_family = AF_INET;
1439 req.r.idiag_states = f->states;
1441 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
1444 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1445 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1446 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
1449 iov[0] = (struct iovec){
1451 .iov_len = sizeof(req)
1454 bclen = ssfilter_bytecompile(f->f, &bc);
1455 rta.rta_type = INET_DIAG_REQ_BYTECODE;
1456 rta.rta_len = RTA_LENGTH(bclen);
1457 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1458 iov[2] = (struct iovec){ bc, bclen };
1459 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1462 msg = (struct msghdr) {
1463 .msg_name = (void*)&nladdr,
1464 .msg_namelen = sizeof(nladdr),
1466 .msg_iovlen = f->f ? 3 : 1,
1469 if (sendmsg(fd, &msg, 0) < 0)
1472 iov[0] = (struct iovec){
1474 .iov_len = sizeof(buf)
1481 msg = (struct msghdr) {
1482 (void*)&nladdr, sizeof(nladdr),
1488 status = recvmsg(fd, &msg, 0);
1497 fprintf(stderr, "EOF on netlink\n");
1502 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1504 h = (struct nlmsghdr*)buf;
1505 while (NLMSG_OK(h, status)) {
1507 struct inet_diag_msg *r = NLMSG_DATA(h);
1509 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1510 h->nlmsg_seq != 123456)
1513 if (h->nlmsg_type == NLMSG_DONE)
1515 if (h->nlmsg_type == NLMSG_ERROR) {
1516 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1517 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1518 fprintf(stderr, "ERROR truncated\n");
1520 errno = -err->error;
1521 perror("TCPDIAG answers");
1526 if (!(f->families & (1<<r->idiag_family))) {
1527 h = NLMSG_NEXT(h, status);
1530 err = tcp_show_sock(h, NULL);
1536 h = NLMSG_NEXT(h, status);
1538 if (msg.msg_flags & MSG_TRUNC) {
1539 fprintf(stderr, "Message truncated\n");
1543 fprintf(stderr, "!!!Remnant of size %d\n", status);
1550 static int tcp_show_netlink_file(struct filter *f)
1555 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1556 perror("fopen($TCPDIAG_FILE)");
1562 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1564 status = fread(buf, 1, sizeof(*h), fp);
1566 perror("Reading header from $TCPDIAG_FILE");
1569 if (status != sizeof(*h)) {
1570 perror("Unexpected EOF reading $TCPDIAG_FILE");
1574 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1577 perror("Reading $TCPDIAG_FILE");
1580 if (status + sizeof(*h) < h->nlmsg_len) {
1581 perror("Unexpected EOF reading $TCPDIAG_FILE");
1585 /* The only legal exit point */
1586 if (h->nlmsg_type == NLMSG_DONE)
1589 if (h->nlmsg_type == NLMSG_ERROR) {
1590 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1591 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1592 fprintf(stderr, "ERROR truncated\n");
1594 errno = -err->error;
1595 perror("TCPDIAG answered");
1600 err = tcp_show_sock(h, f);
1606 static int tcp_show(struct filter *f, int socktype)
1610 int bufsize = 64*1024;
1612 dg_proto = TCP_PROTO;
1614 if (getenv("TCPDIAG_FILE"))
1615 return tcp_show_netlink_file(f);
1617 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1618 && tcp_show_netlink(f, NULL, socktype) == 0)
1621 /* Sigh... We have to parse /proc/net/tcp... */
1624 /* Estimate amount of sockets and try to allocate
1625 * huge buffer to read all the table at one read.
1626 * Limit it by 16MB though. The assumption is: as soon as
1627 * kernel was able to hold information about N connections,
1628 * it is able to give us some memory for snapshot.
1631 int guess = slabstat.socks+slabstat.tcp_syns;
1632 if (f->states&(1<<SS_TIME_WAIT))
1633 guess += slabstat.tcp_tws;
1634 if (guess > (16*1024*1024)/128)
1635 guess = (16*1024*1024)/128;
1637 if (guess > bufsize)
1640 while (bufsize >= 64*1024) {
1641 if ((buf = malloc(bufsize)) != NULL)
1650 if (f->families & (1<<AF_INET)) {
1651 if ((fp = net_tcp_open()) == NULL)
1654 setbuffer(fp, buf, bufsize);
1655 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
1660 if ((f->families & (1<<AF_INET6)) &&
1661 (fp = net_tcp6_open()) != NULL) {
1662 setbuffer(fp, buf, bufsize);
1663 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
1673 int saved_errno = errno;
1678 errno = saved_errno;
1684 int dgram_show_line(char *line, const struct filter *f, int family)
1687 char *loc, *rem, *data;
1692 if ((p = strchr(line, ':')) == NULL)
1696 if ((p = strchr(loc, ':')) == NULL)
1701 if ((p = strchr(rem, ':')) == NULL)
1707 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1709 if (!(f->states & (1<<state)))
1713 s.local.family = s.remote.family = family;
1714 if (family == AF_INET) {
1715 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1716 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1717 s.local.bytelen = s.remote.bytelen = 4;
1719 sscanf(loc, "%08x%08x%08x%08x:%x",
1725 sscanf(rem, "%08x%08x%08x%08x:%x",
1731 s.local.bytelen = s.remote.bytelen = 16;
1734 if (f->f && run_ssfilter(f->f, &s) == 0)
1738 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
1739 &s.state, &s.wq, &s.rq,
1741 &s.refcnt, &s.sk, opt);
1747 printf("%-*s ", netid_width, dg_proto);
1749 printf("%-*s ", state_width, sstate_name[s.state]);
1751 printf("%-6d %-6d ", s.rq, s.wq);
1753 formatted_print(&s.local, s.lport);
1754 formatted_print(&s.remote, s.rport);
1758 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1759 printf(" users:(%s)", ubuf);
1764 printf(" uid=%u", (unsigned)s.uid);
1765 printf(" ino=%u", s.ino);
1766 printf(" sk=%llx", s.sk);
1768 printf(" opt:\"%s\"", opt);
1776 int udp_show(struct filter *f)
1780 dg_proto = UDP_PROTO;
1782 if (f->families&(1<<AF_INET)) {
1783 if ((fp = net_udp_open()) == NULL)
1785 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
1790 if ((f->families&(1<<AF_INET6)) &&
1791 (fp = net_udp6_open()) != NULL) {
1792 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
1800 int saved_errno = errno;
1803 errno = saved_errno;
1808 int raw_show(struct filter *f)
1812 dg_proto = RAW_PROTO;
1814 if (f->families&(1<<AF_INET)) {
1815 if ((fp = net_raw_open()) == NULL)
1817 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
1822 if ((f->families&(1<<AF_INET6)) &&
1823 (fp = net_raw6_open()) != NULL) {
1824 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
1832 int saved_errno = errno;
1835 errno = saved_errno;
1843 struct unixstat *next;
1855 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
1856 SS_ESTABLISHED, SS_CLOSING };
1859 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
1861 void unix_list_free(struct unixstat *list)
1864 struct unixstat *s = list;
1872 void unix_list_print(struct unixstat *list, struct filter *f)
1877 for (s = list; s; s = s->next) {
1878 if (!(f->states & (1<<s->state)))
1880 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
1882 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
1888 for (p = list; p; p = p->next) {
1889 if (s->peer == p->ino)
1895 peer = p->name ? : "*";
1901 tst.local.family = AF_UNIX;
1902 tst.remote.family = AF_UNIX;
1903 memcpy(tst.local.data, &s->name, sizeof(s->name));
1904 if (strcmp(peer, "*") == 0)
1905 memset(tst.remote.data, 0, sizeof(peer));
1907 memcpy(tst.remote.data, &peer, sizeof(peer));
1908 if (run_ssfilter(f->f, &tst) == 0)
1913 printf("%-*s ", netid_width,
1914 s->type == SOCK_STREAM ? "u_str" : "u_dgr");
1916 printf("%-*s ", state_width, sstate_name[s->state]);
1917 printf("%-6d %-6d ", s->rq, s->wq);
1918 printf("%*s %-*d %*s %-*d",
1919 addr_width, s->name ? : "*", serv_width, s->ino,
1920 addr_width, peer, serv_width, s->peer);
1923 if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
1924 printf(" users:(%s)", ubuf);
1930 int unix_show(struct filter *f)
1937 struct unixstat *list = NULL;
1939 if ((fp = net_unix_open()) == NULL)
1941 fgets(buf, sizeof(buf)-1, fp);
1943 if (memcmp(buf, "Peer", 4) == 0)
1947 while (fgets(buf, sizeof(buf)-1, fp)) {
1948 struct unixstat *u, **insp;
1951 if (!(u = malloc(sizeof(*u))))
1955 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
1956 &u->peer, &u->rq, &u->wq, &flags, &u->type,
1957 &u->state, &u->ino, name) < 8)
1960 if (flags&(1<<16)) {
1961 u->state = SS_LISTEN;
1963 u->state = unix_state_map[u->state-1];
1964 if (u->type == SOCK_DGRAM &&
1965 u->state == SS_CLOSE &&
1967 u->state = SS_ESTABLISHED;
1978 if (u->type < (*insp)->type ||
1979 (u->type == (*insp)->type &&
1980 u->ino < (*insp)->ino))
1982 insp = &(*insp)->next;
1988 if ((u->name = malloc(strlen(name)+1)) == NULL)
1990 strcpy(u->name, name);
1992 if (++cnt > MAX_UNIX_REMEMBER) {
1993 unix_list_print(list, f);
1994 unix_list_free(list);
2001 unix_list_print(list, f);
2002 unix_list_free(list);
2011 int packet_show(struct filter *f)
2022 unsigned long long sk;
2024 if (!(f->states & (1<<SS_CLOSE)))
2027 if ((fp = net_packet_open()) == NULL)
2029 fgets(buf, sizeof(buf)-1, fp);
2031 while (fgets(buf, sizeof(buf)-1, fp)) {
2032 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2034 &type, &prot, &iface, &state,
2037 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2039 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2043 tst.local.family = AF_PACKET;
2044 tst.remote.family = AF_PACKET;
2047 tst.local.data[0] = prot;
2048 tst.remote.data[0] = 0;
2049 if (run_ssfilter(f->f, &tst) == 0)
2054 printf("%-*s ", netid_width,
2055 type == SOCK_RAW ? "p_raw" : "p_dgr");
2057 printf("%-*s ", state_width, "UNCONN");
2058 printf("%-6d %-6d ", rq, 0);
2060 printf("%*s:", addr_width, "*");
2063 printf("%*s:", addr_width,
2064 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2067 printf("%-*s ", serv_width, "*");
2069 printf("%-*s ", serv_width, xll_index_to_name(iface));
2072 addr_width, "", serv_width, "");
2076 if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2077 printf(" users:(%s)", ubuf);
2080 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2088 int netlink_show(struct filter *f)
2095 unsigned long long sk, cb;
2097 if (!(f->states & (1<<SS_CLOSE)))
2100 if ((fp = net_netlink_open()) == NULL)
2102 fgets(buf, sizeof(buf)-1, fp);
2104 while (fgets(buf, sizeof(buf)-1, fp)) {
2105 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2107 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2111 tst.local.family = AF_NETLINK;
2112 tst.remote.family = AF_NETLINK;
2115 tst.local.data[0] = prot;
2116 tst.remote.data[0] = 0;
2117 if (run_ssfilter(f->f, &tst) == 0)
2122 printf("%-*s ", netid_width, "nl");
2124 printf("%-*s ", state_width, "UNCONN");
2125 printf("%-6d %-6d ", rq, wq);
2126 if (resolve_services && prot == 0)
2127 printf("%*s:", addr_width, "rtnl");
2128 else if (resolve_services && prot == 3)
2129 printf("%*s:", addr_width, "fw");
2130 else if (resolve_services && prot == 4)
2131 printf("%*s:", addr_width, "tcpdiag");
2133 printf("%*d:", addr_width, prot);
2135 printf("%-*s ", serv_width, "*");
2136 } else if (resolve_services) {
2140 printf("%-*s ", serv_width, "kernel");
2141 } else if (pid > 0) {
2144 sprintf(procname, "%s/%d/stat",
2145 getenv("PROC_ROOT") ? : "/proc", pid);
2146 if ((fp = fopen(procname, "r")) != NULL) {
2147 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2148 sprintf(procname+strlen(procname), "/%d", pid);
2149 printf("%-*s ", serv_width, procname);
2156 printf("%-*d ", serv_width, pid);
2158 printf("%-*d ", serv_width, pid);
2161 addr_width, "", serv_width, "");
2164 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2177 int get_snmp_int(char *proto, char *key, int *result)
2181 int protolen = strlen(proto);
2182 int keylen = strlen(key);
2186 if ((fp = net_snmp_open()) == NULL)
2189 while (fgets(buf, sizeof(buf), fp) != NULL) {
2192 if (memcmp(buf, proto, protolen))
2194 while ((p = strchr(p, ' ')) != NULL) {
2197 if (memcmp(p, key, keylen) == 0 &&
2198 (p[keylen] == ' ' || p[keylen] == '\n'))
2201 if (fgets(buf, sizeof(buf), fp) == NULL)
2203 if (memcmp(buf, proto, protolen))
2206 while ((p = strchr(p, ' ')) != NULL) {
2209 sscanf(p, "%d", result);
2222 /* Get stats from sockstat */
2243 static void get_sockstat_line(char *line, struct sockstat *s)
2245 char id[256], rem[256];
2247 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2250 if (strcmp(id, "sockets:") == 0)
2251 sscanf(rem, "%*s%d", &s->socks);
2252 else if (strcmp(id, "UDP:") == 0)
2253 sscanf(rem, "%*s%d", &s->udp4);
2254 else if (strcmp(id, "UDP6:") == 0)
2255 sscanf(rem, "%*s%d", &s->udp6);
2256 else if (strcmp(id, "RAW:") == 0)
2257 sscanf(rem, "%*s%d", &s->raw4);
2258 else if (strcmp(id, "RAW6:") == 0)
2259 sscanf(rem, "%*s%d", &s->raw6);
2260 else if (strcmp(id, "TCP6:") == 0)
2261 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2262 else if (strcmp(id, "FRAG:") == 0)
2263 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2264 else if (strcmp(id, "FRAG6:") == 0)
2265 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2266 else if (strcmp(id, "TCP:") == 0)
2267 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2269 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2272 int get_sockstat(struct sockstat *s)
2277 memset(s, 0, sizeof(*s));
2279 if ((fp = net_sockstat_open()) == NULL)
2281 while(fgets(buf, sizeof(buf), fp) != NULL)
2282 get_sockstat_line(buf, s);
2285 if ((fp = net_sockstat6_open()) == NULL)
2287 while(fgets(buf, sizeof(buf), fp) != NULL)
2288 get_sockstat_line(buf, s);
2294 int print_summary(void)
2299 if (get_sockstat(&s) < 0)
2300 perror("ss: get_sockstat");
2301 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2302 perror("ss: get_snmpstat");
2304 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2306 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2307 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2309 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2312 s.tcp_tws, slabstat.tcp_tws,
2317 printf("Transport Total IP IPv6\n");
2318 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2319 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2320 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2321 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2322 printf("INET %-9d %-9d %-9d\n",
2323 s.raw4+s.udp4+s.tcp4_hashed+
2324 s.raw6+s.udp6+s.tcp6_hashed,
2325 s.raw4+s.udp4+s.tcp4_hashed,
2326 s.raw6+s.udp6+s.tcp6_hashed);
2327 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2334 static void _usage(FILE *dest)
2337 "Usage: ss [ OPTIONS ]\n"
2338 " ss [ OPTIONS ] [ FILTER ]\n"
2339 " -h, --help this message\n"
2340 " -V, --version output version information\n"
2341 " -n, --numeric don't resolve service names\n"
2342 " -r, --resolve resolve host names\n"
2343 " -a, --all display all sockets\n"
2344 " -l, --listening display listening sockets\n"
2345 " -o, --options show timer information\n"
2346 " -e, --extended show detailed socket information\n"
2347 " -m, --memory show socket memory usage\n"
2348 " -p, --processes show process using socket\n"
2349 " -i, --info show internal TCP information\n"
2350 " -s, --summary show socket usage summary\n"
2352 " -4, --ipv4 display only IP version 4 sockets\n"
2353 " -6, --ipv6 display only IP version 6 sockets\n"
2354 " -0, --packet display PACKET sockets\n"
2355 " -t, --tcp display only TCP sockets\n"
2356 " -u, --udp display only UDP sockets\n"
2357 " -d, --dccp display only DCCP sockets\n"
2358 " -w, --raw display only RAW sockets\n"
2359 " -x, --unix display only Unix domain sockets\n"
2360 " -f, --family=FAMILY display sockets of type FAMILY\n"
2362 " -A, --query=QUERY\n"
2363 " QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2365 " -F, --filter=FILE read filter information from FILE\n"
2366 " FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2370 static void help(void) __attribute__((noreturn));
2371 static void help(void)
2377 static void usage(void) __attribute__((noreturn));
2378 static void usage(void)
2385 int scan_state(const char *state)
2388 if (strcasecmp(state, "close") == 0 ||
2389 strcasecmp(state, "closed") == 0)
2390 return (1<<SS_CLOSE);
2391 if (strcasecmp(state, "syn-rcv") == 0)
2392 return (1<<SS_SYN_RECV);
2393 if (strcasecmp(state, "established") == 0)
2394 return (1<<SS_ESTABLISHED);
2395 if (strcasecmp(state, "all") == 0)
2397 if (strcasecmp(state, "connected") == 0)
2398 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2399 if (strcasecmp(state, "synchronized") == 0)
2400 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2401 if (strcasecmp(state, "bucket") == 0)
2402 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2403 if (strcasecmp(state, "big") == 0)
2404 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2405 for (i=0; i<SS_MAX; i++) {
2406 if (strcasecmp(state, sstate_namel[i]) == 0)
2412 static const struct option long_opts[] = {
2413 { "numeric", 0, 0, 'n' },
2414 { "resolve", 0, 0, 'r' },
2415 { "options", 0, 0, 'o' },
2416 { "extended", 0, 0, 'e' },
2417 { "memory", 0, 0, 'm' },
2418 { "info", 0, 0, 'i' },
2419 { "processes", 0, 0, 'p' },
2420 { "dccp", 0, 0, 'd' },
2421 { "tcp", 0, 0, 't' },
2422 { "udp", 0, 0, 'u' },
2423 { "raw", 0, 0, 'w' },
2424 { "unix", 0, 0, 'x' },
2425 { "all", 0, 0, 'a' },
2426 { "listening", 0, 0, 'l' },
2427 { "ipv4", 0, 0, '4' },
2428 { "ipv6", 0, 0, '6' },
2429 { "packet", 0, 0, '0' },
2430 { "family", 1, 0, 'f' },
2431 { "socket", 1, 0, 'A' },
2432 { "summary", 0, 0, 's' },
2433 { "diag", 0, 0, 'D' },
2434 { "filter", 1, 0, 'F' },
2435 { "version", 0, 0, 'V' },
2436 { "help", 0, 0, 'h' },
2441 int main(int argc, char *argv[])
2447 const char *dump_tcpdiag = NULL;
2448 FILE *filter_fp = NULL;
2451 memset(¤t_filter, 0, sizeof(current_filter));
2453 current_filter.states = default_filter.states;
2455 while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spf:miA:D:F:vV",
2456 long_opts, NULL)) != EOF) {
2459 resolve_services = 0;
2481 current_filter.dbs |= (1<<DCCP_DB);
2485 current_filter.dbs |= (1<<TCP_DB);
2489 current_filter.dbs |= (1<<UDP_DB);
2493 current_filter.dbs |= (1<<RAW_DB);
2497 current_filter.dbs |= UNIX_DBM;
2501 current_filter.states = SS_ALL;
2504 current_filter.states = (1<<SS_LISTEN);
2507 preferred_family = AF_INET;
2510 preferred_family = AF_INET6;
2513 preferred_family = AF_PACKET;
2516 if (strcmp(optarg, "inet") == 0)
2517 preferred_family = AF_INET;
2518 else if (strcmp(optarg, "inet6") == 0)
2519 preferred_family = AF_INET6;
2520 else if (strcmp(optarg, "link") == 0)
2521 preferred_family = AF_PACKET;
2522 else if (strcmp(optarg, "unix") == 0)
2523 preferred_family = AF_UNIX;
2524 else if (strcmp(optarg, "netlink") == 0)
2525 preferred_family = AF_NETLINK;
2526 else if (strcmp(optarg, "help") == 0)
2529 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2537 current_filter.dbs = 0;
2543 if ((p1 = strchr(p, ',')) != NULL)
2545 if (strcmp(p, "all") == 0) {
2546 current_filter.dbs = ALL_DB;
2547 } else if (strcmp(p, "inet") == 0) {
2548 current_filter.dbs |= (1<<TCP_DB)|(1<<DCCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2549 } else if (strcmp(p, "udp") == 0) {
2550 current_filter.dbs |= (1<<UDP_DB);
2551 } else if (strcmp(p, "dccp") == 0) {
2552 current_filter.dbs |= (1<<DCCP_DB);
2553 } else if (strcmp(p, "tcp") == 0) {
2554 current_filter.dbs |= (1<<TCP_DB);
2555 } else if (strcmp(p, "raw") == 0) {
2556 current_filter.dbs |= (1<<RAW_DB);
2557 } else if (strcmp(p, "unix") == 0) {
2558 current_filter.dbs |= UNIX_DBM;
2559 } else if (strcasecmp(p, "unix_stream") == 0 ||
2560 strcmp(p, "u_str") == 0) {
2561 current_filter.dbs |= (1<<UNIX_ST_DB);
2562 } else if (strcasecmp(p, "unix_dgram") == 0 ||
2563 strcmp(p, "u_dgr") == 0) {
2564 current_filter.dbs |= (1<<UNIX_DG_DB);
2565 } else if (strcmp(p, "packet") == 0) {
2566 current_filter.dbs |= PACKET_DBM;
2567 } else if (strcmp(p, "packet_raw") == 0 ||
2568 strcmp(p, "p_raw") == 0) {
2569 current_filter.dbs |= (1<<PACKET_R_DB);
2570 } else if (strcmp(p, "packet_dgram") == 0 ||
2571 strcmp(p, "p_dgr") == 0) {
2572 current_filter.dbs |= (1<<PACKET_DG_DB);
2573 } else if (strcmp(p, "netlink") == 0) {
2574 current_filter.dbs |= (1<<NETLINK_DB);
2576 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2587 dump_tcpdiag = optarg;
2591 fprintf(stderr, "More than one filter file\n");
2594 if (optarg[0] == '-')
2597 filter_fp = fopen(optarg, "r");
2599 perror("fopen filter file");
2605 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
2618 get_slabstat(&slabstat);
2622 if (do_default && argc == 0)
2627 current_filter.dbs = default_filter.dbs;
2629 if (preferred_family == AF_UNSPEC) {
2630 if (!(current_filter.dbs&~UNIX_DBM))
2631 preferred_family = AF_UNIX;
2632 else if (!(current_filter.dbs&~PACKET_DBM))
2633 preferred_family = AF_PACKET;
2634 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
2635 preferred_family = AF_NETLINK;
2638 if (preferred_family != AF_UNSPEC) {
2640 if (preferred_family == AF_INET ||
2641 preferred_family == AF_INET6) {
2642 mask2= current_filter.dbs;
2643 } else if (preferred_family == AF_PACKET) {
2645 } else if (preferred_family == AF_UNIX) {
2647 } else if (preferred_family == AF_NETLINK) {
2648 mask2 = (1<<NETLINK_DB);
2654 current_filter.dbs = mask2;
2656 current_filter.dbs &= mask2;
2657 current_filter.families = (1<<preferred_family);
2660 current_filter.families = ~0;
2662 current_filter.families = default_filter.families;
2664 if (current_filter.dbs == 0) {
2665 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
2668 if (current_filter.families == 0) {
2669 fprintf(stderr, "ss: no families to show with such filter.\n");
2673 if (resolve_services && resolve_hosts &&
2674 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
2675 init_service_resolver();
2677 /* Now parse filter... */
2678 if (argc == 0 && filter_fp) {
2679 if (ssfilter_parse(¤t_filter.f, 0, NULL, filter_fp))
2684 if (strcmp(*argv, "state") == 0) {
2687 current_filter.states = 0;
2688 current_filter.states |= scan_state(*argv);
2690 } else if (strcmp(*argv, "exclude") == 0 ||
2691 strcmp(*argv, "excl") == 0) {
2694 current_filter.states = SS_ALL;
2695 current_filter.states &= ~scan_state(*argv);
2698 if (ssfilter_parse(¤t_filter.f, argc, argv, filter_fp))
2705 if (current_filter.states == 0) {
2706 fprintf(stderr, "ss: no socket states to show with such filter.\n");
2711 FILE *dump_fp = stdout;
2712 if (!(current_filter.dbs & (1<<TCP_DB))) {
2713 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
2716 if (dump_tcpdiag[0] != '-') {
2717 dump_fp = fopen(dump_tcpdiag, "w");
2718 if (!dump_tcpdiag) {
2719 perror("fopen dump file");
2723 tcp_show_netlink(¤t_filter, dump_fp, TCPDIAG_GETSOCK);
2729 if (current_filter.dbs&(current_filter.dbs-1))
2733 if (current_filter.states&(current_filter.states-1))
2737 if (isatty(STDOUT_FILENO)) {
2740 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
2742 screen_width = w.ws_col;
2746 addrp_width = screen_width;
2747 addrp_width -= netid_width+1;
2748 addrp_width -= state_width+1;
2751 if (addrp_width&1) {
2754 else if (state_width)
2761 serv_width = resolve_services ? 7 : 5;
2763 if (addrp_width < 15+serv_width+1)
2764 addrp_width = 15+serv_width+1;
2766 addr_width = addrp_width - serv_width - 1;
2769 printf("%-*s ", netid_width, "Netid");
2771 printf("%-*s ", state_width, "State");
2772 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
2774 printf("%*s:%-*s %*s:%-*s\n",
2775 addr_width, "Local Address", serv_width, "Port",
2776 addr_width, "Peer Address", serv_width, "Port");
2780 if (current_filter.dbs & (1<<NETLINK_DB))
2781 netlink_show(¤t_filter);
2782 if (current_filter.dbs & PACKET_DBM)
2783 packet_show(¤t_filter);
2784 if (current_filter.dbs & UNIX_DBM)
2785 unix_show(¤t_filter);
2786 if (current_filter.dbs & (1<<RAW_DB))
2787 raw_show(¤t_filter);
2788 if (current_filter.dbs & (1<<UDP_DB))
2789 udp_show(¤t_filter);
2790 if (current_filter.dbs & (1<<TCP_DB))
2791 tcp_show(¤t_filter, TCPDIAG_GETSOCK);
2792 if (current_filter.dbs & (1<<DCCP_DB))
2793 tcp_show(¤t_filter, DCCPDIAG_GETSOCK);