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/sock_diag.h>
38 #include <linux/inet_diag.h>
39 #include <linux/unix_diag.h>
41 int resolve_hosts = 0;
42 int resolve_services = 1;
43 int preferred_family = AF_UNSPEC;
57 static const char *TCP_PROTO = "tcp";
58 static const char *UDP_PROTO = "udp";
59 static const char *RAW_PROTO = "raw";
60 static const char *dg_proto = NULL;
76 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
77 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB))
78 #define ALL_DB ((1<<MAX_DB)-1)
96 #define SS_ALL ((1<<SS_MAX)-1)
108 struct filter default_filter = {
110 .states = SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)),
111 .families= (1<<AF_INET)|(1<<AF_INET6),
114 struct filter current_filter;
116 static FILE *generic_proc_open(const char *env, const char *name)
118 const char *p = getenv(env);
122 p = getenv("PROC_ROOT") ? : "/proc";
123 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
127 return fopen(p, "r");
130 static FILE *net_tcp_open(void)
132 return generic_proc_open("PROC_NET_TCP", "net/tcp");
135 static FILE *net_tcp6_open(void)
137 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
140 static FILE *net_udp_open(void)
142 return generic_proc_open("PROC_NET_UDP", "net/udp");
145 static FILE *net_udp6_open(void)
147 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
150 static FILE *net_raw_open(void)
152 return generic_proc_open("PROC_NET_RAW", "net/raw");
155 static FILE *net_raw6_open(void)
157 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
160 static FILE *net_unix_open(void)
162 return generic_proc_open("PROC_NET_UNIX", "net/unix");
165 static FILE *net_packet_open(void)
167 return generic_proc_open("PROC_NET_PACKET", "net/packet");
170 static FILE *net_netlink_open(void)
172 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
175 static FILE *slabinfo_open(void)
177 return generic_proc_open("PROC_SLABINFO", "slabinfo");
180 static FILE *net_sockstat_open(void)
182 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
185 static FILE *net_sockstat6_open(void)
187 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
190 static FILE *net_snmp_open(void)
192 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
195 static FILE *ephemeral_ports_open(void)
197 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
201 struct user_ent *next;
208 #define USER_ENT_HASH_SIZE 256
209 struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE];
211 static int user_ent_hashfn(unsigned int ino)
213 int val = (ino >> 24) ^ (ino >> 16) ^ (ino >> 8) ^ ino;
215 return val & (USER_ENT_HASH_SIZE - 1);
218 static void user_ent_add(unsigned int ino, const char *process, int pid, int fd)
220 struct user_ent *p, **pp;
223 str_len = strlen(process) + 1;
224 p = malloc(sizeof(struct user_ent) + str_len);
231 strcpy(p->process, process);
233 pp = &user_ent_hash[user_ent_hashfn(ino)];
238 static void user_ent_hash_build(void)
240 const char *root = getenv("PROC_ROOT") ? : "/proc/";
247 if (strlen(name) == 0 || name[strlen(name)-1] != '/')
250 nameoff = strlen(name);
256 while ((d = readdir(dir)) != NULL) {
263 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
266 sprintf(name + nameoff, "%d/fd/", pid);
268 if ((dir1 = opendir(name)) == NULL)
273 while ((d1 = readdir(dir1)) != NULL) {
274 const char *pattern = "socket:[";
280 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
283 sprintf(name+pos, "%d", fd);
285 link_len = readlink(name, lnk, sizeof(lnk)-1);
288 lnk[link_len] = '\0';
290 if (strncmp(lnk, pattern, strlen(pattern)))
293 sscanf(lnk, "socket:[%u]", &ino);
295 if (process[0] == '\0') {
299 snprintf(tmp, sizeof(tmp), "%s/%d/stat", root, pid);
300 if ((fp = fopen(tmp, "r")) != NULL) {
301 fscanf(fp, "%*d (%[^)])", process);
306 user_ent_add(ino, process, pid, fd);
313 int find_users(unsigned ino, char *buf, int buflen)
322 p = user_ent_hash[user_ent_hashfn(ino)];
328 if (ptr - buf >= buflen - 1)
331 snprintf(ptr, buflen - (ptr - buf),
333 p->process, p->pid, p->fd);
347 /* Get stats from slab */
358 struct slabstat slabstat;
360 static const char *slabstat_ids[] =
369 int get_slabstat(struct slabstat *s)
375 memset(s, 0, sizeof(*s));
377 fp = slabinfo_open();
381 cnt = sizeof(*s)/sizeof(int);
383 fgets(buf, sizeof(buf), fp);
384 while(fgets(buf, sizeof(buf), fp) != NULL) {
386 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
387 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
388 sscanf(buf, "%*s%d", ((int *)s) + i);
401 static const char *sstate_name[] = {
403 [TCP_ESTABLISHED] = "ESTAB",
404 [TCP_SYN_SENT] = "SYN-SENT",
405 [TCP_SYN_RECV] = "SYN-RECV",
406 [TCP_FIN_WAIT1] = "FIN-WAIT-1",
407 [TCP_FIN_WAIT2] = "FIN-WAIT-2",
408 [TCP_TIME_WAIT] = "TIME-WAIT",
409 [TCP_CLOSE] = "UNCONN",
410 [TCP_CLOSE_WAIT] = "CLOSE-WAIT",
411 [TCP_LAST_ACK] = "LAST-ACK",
412 [TCP_LISTEN] = "LISTEN",
413 [TCP_CLOSING] = "CLOSING",
416 static const char *sstate_namel[] = {
418 [TCP_ESTABLISHED] = "established",
419 [TCP_SYN_SENT] = "syn-sent",
420 [TCP_SYN_RECV] = "syn-recv",
421 [TCP_FIN_WAIT1] = "fin-wait-1",
422 [TCP_FIN_WAIT2] = "fin-wait-2",
423 [TCP_TIME_WAIT] = "time-wait",
424 [TCP_CLOSE] = "unconnected",
425 [TCP_CLOSE_WAIT] = "close-wait",
426 [TCP_LAST_ACK] = "last-ack",
427 [TCP_LISTEN] = "listening",
428 [TCP_CLOSING] = "closing",
446 unsigned long long sk;
447 int rto, ato, qack, cwnd, ssthresh;
450 static const char *tmr_name[] = {
459 const char *print_ms_timer(int timeout)
462 int secs, msecs, minutes;
468 msecs = timeout%1000;
472 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
479 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
482 sprintf(buf+strlen(buf), "%03dms", msecs);
486 const char *print_hz_timer(int timeout)
488 int hz = get_user_hz();
489 return print_ms_timer(((timeout*1000) + hz-1)/hz);
500 struct scache *rlist;
502 void init_service_resolver(void)
505 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
507 fgets(buf, sizeof(buf), fp);
508 while (fgets(buf, sizeof(buf), fp) != NULL) {
509 unsigned int progn, port;
510 char proto[128], prog[128];
511 if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
512 &port, prog+4) == 4) {
513 struct scache *c = malloc(sizeof(*c));
516 memcpy(prog, "rpc.", 4);
517 c->name = strdup(prog);
518 if (strcmp(proto, TCP_PROTO) == 0)
519 c->proto = TCP_PROTO;
520 else if (strcmp(proto, UDP_PROTO) == 0)
521 c->proto = UDP_PROTO;
533 static int ip_local_port_min, ip_local_port_max;
535 /* Even do not try default linux ephemeral port ranges:
536 * default /etc/services contains so much of useless crap
537 * wouldbe "allocated" to this area that resolution
538 * is really harmful. I shrug each time when seeing
539 * "socks" or "cfinger" in dumps.
541 static int is_ephemeral(int port)
543 if (!ip_local_port_min) {
544 FILE *f = ephemeral_ports_open();
547 &ip_local_port_min, &ip_local_port_max);
550 ip_local_port_min = 1024;
551 ip_local_port_max = 4999;
555 return (port >= ip_local_port_min && port<= ip_local_port_max);
559 const char *__resolve_service(int port)
563 for (c = rlist; c; c = c->next) {
564 if (c->port == port && c->proto == dg_proto)
568 if (!is_ephemeral(port)) {
575 se = getservbyport(htons(port), dg_proto);
584 const char *resolve_service(int port)
586 static char buf[128];
587 static struct scache cache[256];
595 if (resolve_services) {
596 if (dg_proto == RAW_PROTO) {
597 return inet_proto_n2a(port, buf, sizeof(buf));
601 int hash = (port^(((unsigned long)dg_proto)>>2))&255;
603 for (c = &cache[hash]; c; c = c->next) {
604 if (c->port == port &&
605 c->proto == dg_proto) {
612 if ((res = __resolve_service(port)) != NULL) {
613 if ((c = malloc(sizeof(*c))) == NULL)
624 c->name = strdup(res);
625 c->next = cache[hash].next;
626 cache[hash].next = c;
634 sprintf(buf, "%u", port);
638 void formatted_print(const inet_prefix *a, int port)
641 const char *ap = buf;
644 est_len = addr_width;
646 if (a->family == AF_INET) {
647 if (a->data[0] == 0) {
651 ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
654 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
655 est_len = strlen(ap);
656 if (est_len <= addr_width)
657 est_len = addr_width;
659 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
661 printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
668 struct aafilter *next;
671 int inet2_addr_match(const inet_prefix *a, const inet_prefix *p, int plen)
673 if (!inet_addr_match(a, p, plen))
676 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
677 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
679 if (p->family == AF_INET && a->family == AF_INET6) {
680 if (a->data[0] == 0 && a->data[1] == 0 &&
681 a->data[2] == htonl(0xffff)) {
682 inet_prefix tmp = *a;
683 tmp.data[0] = a->data[3];
684 return inet_addr_match(&tmp, p, plen);
690 int unix_match(const inet_prefix *a, const inet_prefix *p)
692 char *addr, *pattern;
693 memcpy(&addr, a->data, sizeof(addr));
694 memcpy(&pattern, p->data, sizeof(pattern));
699 return !fnmatch(pattern, addr, 0);
702 int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
707 static int low, high=65535;
709 if (s->local.family == AF_UNIX) {
711 memcpy(&p, s->local.data, sizeof(p));
712 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
713 strspn(p+1, "0123456789abcdef") == 5);
715 if (s->local.family == AF_PACKET)
716 return s->lport == 0 && s->local.data == 0;
717 if (s->local.family == AF_NETLINK)
721 FILE *fp = ephemeral_ports_open();
723 fscanf(fp, "%d%d", &low, &high);
727 return s->lport >= low && s->lport <= high;
731 struct aafilter *a = (void*)f->pred;
732 if (a->addr.family == AF_UNIX)
733 return unix_match(&s->remote, &a->addr);
734 if (a->port != -1 && a->port != s->rport)
736 if (a->addr.bitlen) {
738 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
740 } while ((a = a->next) != NULL);
747 struct aafilter *a = (void*)f->pred;
748 if (a->addr.family == AF_UNIX)
749 return unix_match(&s->local, &a->addr);
750 if (a->port != -1 && a->port != s->lport)
752 if (a->addr.bitlen) {
754 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
756 } while ((a = a->next) != NULL);
763 struct aafilter *a = (void*)f->pred;
764 return s->rport >= a->port;
768 struct aafilter *a = (void*)f->pred;
769 return s->rport <= a->port;
773 struct aafilter *a = (void*)f->pred;
774 return s->lport >= a->port;
778 struct aafilter *a = (void*)f->pred;
779 return s->lport <= a->port;
782 /* Yup. It is recursion. Sorry. */
784 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
786 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
788 return !run_ssfilter(f->pred, s);
794 /* Relocate external jumps by reloc. */
795 static void ssfilter_patch(char *a, int len, int reloc)
798 struct inet_diag_bc_op *op = (struct inet_diag_bc_op*)a;
808 static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
813 if (!(*bytecode=malloc(4))) abort();
814 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
820 struct aafilter *a = (void*)f->pred;
823 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
826 for (b=a; b; b=b->next) {
827 len += 4 + sizeof(struct inet_diag_hostcond);
828 if (a->addr.family == AF_INET6)
835 if (!(ptr = malloc(len))) abort();
837 for (b=a; b; b=b->next) {
838 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
839 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
840 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
841 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond*)(ptr+4);
843 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
844 cond->family = a->addr.family;
845 cond->port = a->port;
846 cond->prefix_len = a->addr.bitlen;
847 memcpy(cond->addr, a->addr.data, alen);
850 op = (struct inet_diag_bc_op *)ptr;
851 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
855 return ptr - *bytecode;
859 struct aafilter *x = (void*)f->pred;
860 if (!(*bytecode=malloc(8))) abort();
861 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
862 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
867 struct aafilter *x = (void*)f->pred;
868 if (!(*bytecode=malloc(8))) abort();
869 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
870 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
875 struct aafilter *x = (void*)f->pred;
876 if (!(*bytecode=malloc(8))) abort();
877 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
878 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
883 struct aafilter *x = (void*)f->pred;
884 if (!(*bytecode=malloc(8))) abort();
885 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
886 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
892 char *a1, *a2, *a, l1, l2;
893 l1 = ssfilter_bytecompile(f->pred, &a1);
894 l2 = ssfilter_bytecompile(f->post, &a2);
895 if (!(a = malloc(l1+l2))) abort();
897 memcpy(a+l1, a2, l2);
899 ssfilter_patch(a, l1, l2);
905 char *a1, *a2, *a, l1, l2;
906 l1 = ssfilter_bytecompile(f->pred, &a1);
907 l2 = ssfilter_bytecompile(f->post, &a2);
908 if (!(a = malloc(l1+l2+4))) abort();
910 memcpy(a+l1+4, a2, l2);
912 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
919 l1 = ssfilter_bytecompile(f->pred, &a1);
920 if (!(a = malloc(l1+4))) abort();
923 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
932 static int remember_he(struct aafilter *a, struct hostent *he)
934 char **ptr = he->h_addr_list;
938 if (he->h_addrtype == AF_INET)
940 else if (he->h_addrtype == AF_INET6)
946 struct aafilter *b = a;
947 if (a->addr.bitlen) {
948 if ((b = malloc(sizeof(*b))) == NULL)
954 memcpy(b->addr.data, *ptr, len);
955 b->addr.bytelen = len;
956 b->addr.bitlen = len*8;
957 b->addr.family = he->h_addrtype;
964 static int get_dns_host(struct aafilter *a, const char *addr, int fam)
975 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
977 cnt = remember_he(a, he);
978 if (fam == AF_UNSPEC) {
979 he = gethostbyname2(addr, AF_INET6);
981 cnt += remember_he(a, he);
986 static int xll_initted = 0;
988 static void xll_init(void)
990 struct rtnl_handle rth;
997 static const char *xll_index_to_name(int index)
1001 return ll_index_to_name(index);
1004 static int xll_name_to_index(const char *dev)
1008 return ll_name_to_index(dev);
1011 void *parse_hostcond(char *addr)
1015 struct aafilter *res;
1016 int fam = preferred_family;
1018 memset(&a, 0, sizeof(a));
1021 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
1023 a.addr.family = AF_UNIX;
1024 if (strncmp(addr, "unix:", 5) == 0)
1027 a.addr.bitlen = 8*strlen(p);
1028 memcpy(a.addr.data, &p, sizeof(p));
1032 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
1033 a.addr.family = AF_PACKET;
1035 if (strncmp(addr, "link:", 5) == 0)
1037 port = strchr(addr, ':');
1040 if (port[1] && strcmp(port+1, "*")) {
1041 if (get_integer(&a.port, port+1, 0)) {
1042 if ((a.port = xll_name_to_index(port+1)) <= 0)
1047 if (addr[0] && strcmp(addr, "*")) {
1050 if (ll_proto_a2n(&tmp, addr))
1052 a.addr.data[0] = ntohs(tmp);
1057 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
1058 a.addr.family = AF_NETLINK;
1060 if (strncmp(addr, "netlink:", 8) == 0)
1062 port = strchr(addr, ':');
1065 if (port[1] && strcmp(port+1, "*")) {
1066 if (get_integer(&a.port, port+1, 0)) {
1067 if (strcmp(port+1, "kernel") == 0)
1074 if (addr[0] && strcmp(addr, "*")) {
1076 if (get_u32(a.addr.data, addr, 0)) {
1077 if (strcmp(addr, "rtnl") == 0)
1079 else if (strcmp(addr, "fw") == 0)
1081 else if (strcmp(addr, "tcpdiag") == 0)
1090 if (strncmp(addr, "inet:", 5) == 0) {
1093 } else if (strncmp(addr, "inet6:", 6) == 0) {
1098 /* URL-like literal [] */
1099 if (addr[0] == '[') {
1101 if ((port = strchr(addr, ']')) == NULL)
1104 } else if (addr[0] == '*') {
1107 port = strrchr(strchr(addr, '/') ? : addr, ':');
1109 if (port && *port) {
1113 if (*port && *port != '*') {
1114 if (get_integer(&a.port, port, 0)) {
1115 struct servent *se1 = NULL;
1116 struct servent *se2 = NULL;
1117 if (current_filter.dbs&(1<<UDP_DB))
1118 se1 = getservbyname(port, UDP_PROTO);
1119 if (current_filter.dbs&(1<<TCP_DB))
1120 se2 = getservbyname(port, TCP_PROTO);
1121 if (se1 && se2 && se1->s_port != se2->s_port) {
1122 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1128 a.port = ntohs(se1->s_port);
1131 for (s = rlist; s; s = s->next) {
1132 if ((s->proto == UDP_PROTO &&
1133 (current_filter.dbs&(1<<UDP_DB))) ||
1134 (s->proto == TCP_PROTO &&
1135 (current_filter.dbs&(1<<TCP_DB)))) {
1136 if (s->name && strcmp(s->name, port) == 0) {
1137 if (a.port > 0 && a.port != s->port) {
1138 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1146 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1153 if (addr && *addr && *addr != '*') {
1154 if (get_prefix_1(&a.addr, addr, fam)) {
1155 if (get_dns_host(&a, addr, fam)) {
1156 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1163 res = malloc(sizeof(*res));
1165 memcpy(res, &a, sizeof(a));
1169 static int tcp_show_line(char *line, const struct filter *f, int family)
1172 char *loc, *rem, *data;
1177 if ((p = strchr(line, ':')) == NULL)
1181 if ((p = strchr(loc, ':')) == NULL)
1186 if ((p = strchr(rem, ':')) == NULL)
1192 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1194 if (!(f->states & (1<<state)))
1198 s.local.family = s.remote.family = family;
1199 if (family == AF_INET) {
1200 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1201 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1202 s.local.bytelen = s.remote.bytelen = 4;
1204 sscanf(loc, "%08x%08x%08x%08x:%x",
1210 sscanf(rem, "%08x%08x%08x%08x:%x",
1216 s.local.bytelen = s.remote.bytelen = 16;
1219 if (f->f && run_ssfilter(f->f, &s) == 0)
1223 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
1224 &s.state, &s.wq, &s.rq,
1225 &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1226 &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1227 &s.cwnd, &s.ssthresh, opt);
1240 printf("%-*s ", netid_width, "tcp");
1242 printf("%-*s ", state_width, sstate_name[s.state]);
1244 printf("%-6d %-6d ", s.rq, s.wq);
1246 formatted_print(&s.local, s.lport);
1247 formatted_print(&s.remote, s.rport);
1253 printf(" timer:(%s,%s,%d)",
1255 print_hz_timer(s.timeout),
1256 s.timer != 1 ? s.probes : s.retrs);
1260 int hz = get_user_hz();
1261 if (s.rto && s.rto != 3*hz)
1262 printf(" rto:%g", (double)s.rto/hz);
1264 printf(" ato:%g", (double)s.ato/hz);
1266 printf(" cwnd:%d", s.cwnd);
1267 if (s.ssthresh != -1)
1268 printf(" ssthresh:%d", s.ssthresh);
1270 printf(" qack:%d", s.qack/2);
1276 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1277 printf(" users:(%s)", ubuf);
1281 printf(" uid:%u", (unsigned)s.uid);
1282 printf(" ino:%u", s.ino);
1283 printf(" sk:%llx", s.sk);
1285 printf(" opt:\"%s\"", opt);
1292 static int generic_record_read(FILE *fp,
1293 int (*worker)(char*, const struct filter *, int),
1294 const struct filter *f, int fam)
1299 if (fgets(line, sizeof(line), fp) == NULL)
1302 while (fgets(line, sizeof(line), fp) != NULL) {
1303 int n = strlen(line);
1304 if (n == 0 || line[n-1] != '\n') {
1310 if (worker(line, f, fam) < 0)
1315 return ferror(fp) ? -1 : 0;
1318 static char *sprint_bw(char *buf, double bw)
1321 sprintf(buf,"%.1fM", bw / 1000000.);
1322 else if (bw > 1000.)
1323 sprintf(buf,"%.1fK", bw / 1000.);
1325 sprintf(buf, "%g", bw);
1330 static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r)
1332 struct rtattr * tb[INET_DIAG_MAX+1];
1336 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr*)(r+1),
1337 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1339 if (tb[INET_DIAG_SKMEMINFO]) {
1340 const __u32 *skmeminfo = RTA_DATA(tb[INET_DIAG_SKMEMINFO]);
1341 printf(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u)",
1342 skmeminfo[SK_MEMINFO_RMEM_ALLOC],
1343 skmeminfo[SK_MEMINFO_RCVBUF],
1344 skmeminfo[SK_MEMINFO_WMEM_ALLOC],
1345 skmeminfo[SK_MEMINFO_SNDBUF],
1346 skmeminfo[SK_MEMINFO_FWD_ALLOC],
1347 skmeminfo[SK_MEMINFO_WMEM_QUEUED],
1348 skmeminfo[SK_MEMINFO_OPTMEM]);
1349 }else if (tb[INET_DIAG_MEMINFO]) {
1350 const struct inet_diag_meminfo *minfo
1351 = RTA_DATA(tb[INET_DIAG_MEMINFO]);
1352 printf(" mem:(r%u,w%u,f%u,t%u)",
1359 if (tb[INET_DIAG_INFO]) {
1360 struct tcp_info *info;
1361 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
1363 /* workaround for older kernels with less fields */
1364 if (len < sizeof(*info)) {
1365 info = alloca(sizeof(*info));
1366 memset(info, 0, sizeof(*info));
1367 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
1369 info = RTA_DATA(tb[INET_DIAG_INFO]);
1372 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1374 if (info->tcpi_options & TCPI_OPT_SACK)
1376 if (info->tcpi_options & TCPI_OPT_ECN)
1378 if (info->tcpi_options & TCPI_OPT_ECN_SEEN)
1382 if (tb[INET_DIAG_CONG])
1383 printf(" %s", rta_getattr_str(tb[INET_DIAG_CONG]));
1385 if (info->tcpi_options & TCPI_OPT_WSCALE)
1386 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1387 info->tcpi_rcv_wscale);
1388 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1389 printf(" rto:%g", (double)info->tcpi_rto/1000);
1391 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1392 (double)info->tcpi_rttvar/1000);
1394 printf(" ato:%g", (double)info->tcpi_ato/1000);
1395 if (info->tcpi_snd_cwnd != 2)
1396 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1397 if (info->tcpi_snd_ssthresh < 0xFFFF)
1398 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1400 rtt = (double) info->tcpi_rtt;
1401 if (tb[INET_DIAG_VEGASINFO]) {
1402 const struct tcpvegas_info *vinfo
1403 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
1405 if (vinfo->tcpv_enabled &&
1406 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
1407 rtt = vinfo->tcpv_rtt;
1410 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1411 printf(" send %sbps",
1412 sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1413 (double) info->tcpi_snd_mss * 8000000.
1417 if (info->tcpi_rcv_rtt)
1418 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1419 if (info->tcpi_rcv_space)
1420 printf(" rcv_space:%d", info->tcpi_rcv_space);
1425 static int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
1427 struct inet_diag_msg *r = NLMSG_DATA(nlh);
1430 s.state = r->idiag_state;
1431 s.local.family = s.remote.family = r->idiag_family;
1432 s.lport = ntohs(r->id.idiag_sport);
1433 s.rport = ntohs(r->id.idiag_dport);
1434 if (s.local.family == AF_INET) {
1435 s.local.bytelen = s.remote.bytelen = 4;
1437 s.local.bytelen = s.remote.bytelen = 16;
1439 memcpy(s.local.data, r->id.idiag_src, s.local.bytelen);
1440 memcpy(s.remote.data, r->id.idiag_dst, s.local.bytelen);
1442 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1446 printf("%-*s ", netid_width, "tcp");
1448 printf("%-*s ", state_width, sstate_name[s.state]);
1450 printf("%-6d %-6d ", r->idiag_rqueue, r->idiag_wqueue);
1452 formatted_print(&s.local, s.lport);
1453 formatted_print(&s.remote, s.rport);
1456 if (r->idiag_timer) {
1457 if (r->idiag_timer > 4)
1459 printf(" timer:(%s,%s,%d)",
1460 tmr_name[r->idiag_timer],
1461 print_ms_timer(r->idiag_expires),
1467 if (find_users(r->idiag_inode, ubuf, sizeof(ubuf)) > 0)
1468 printf(" users:(%s)", ubuf);
1472 printf(" uid:%u", (unsigned)r->idiag_uid);
1473 printf(" ino:%u", r->idiag_inode);
1475 if (r->id.idiag_cookie[1] != 0)
1476 printf("%08x", r->id.idiag_cookie[1]);
1477 printf("%08x", r->id.idiag_cookie[0]);
1479 if (show_mem || show_tcpinfo) {
1481 tcp_show_info(nlh, r);
1489 static int tcp_show_netlink(struct filter *f, FILE *dump_fp, int socktype)
1492 struct sockaddr_nl nladdr;
1494 struct nlmsghdr nlh;
1495 struct inet_diag_req r;
1502 struct iovec iov[3];
1504 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
1507 memset(&nladdr, 0, sizeof(nladdr));
1508 nladdr.nl_family = AF_NETLINK;
1510 req.nlh.nlmsg_len = sizeof(req);
1511 req.nlh.nlmsg_type = socktype;
1512 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1513 req.nlh.nlmsg_pid = 0;
1514 req.nlh.nlmsg_seq = 123456;
1515 memset(&req.r, 0, sizeof(req.r));
1516 req.r.idiag_family = AF_INET;
1517 req.r.idiag_states = f->states;
1519 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
1520 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
1524 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1525 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1526 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
1529 iov[0] = (struct iovec){
1531 .iov_len = sizeof(req)
1534 bclen = ssfilter_bytecompile(f->f, &bc);
1535 rta.rta_type = INET_DIAG_REQ_BYTECODE;
1536 rta.rta_len = RTA_LENGTH(bclen);
1537 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1538 iov[2] = (struct iovec){ bc, bclen };
1539 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1542 msg = (struct msghdr) {
1543 .msg_name = (void*)&nladdr,
1544 .msg_namelen = sizeof(nladdr),
1546 .msg_iovlen = f->f ? 3 : 1,
1549 if (sendmsg(fd, &msg, 0) < 0) {
1554 iov[0] = (struct iovec){
1556 .iov_len = sizeof(buf)
1563 msg = (struct msghdr) {
1564 (void*)&nladdr, sizeof(nladdr),
1570 status = recvmsg(fd, &msg, 0);
1579 fprintf(stderr, "EOF on netlink\n");
1585 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1587 h = (struct nlmsghdr*)buf;
1588 while (NLMSG_OK(h, status)) {
1590 struct inet_diag_msg *r = NLMSG_DATA(h);
1592 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1593 h->nlmsg_seq != 123456)
1596 if (h->nlmsg_type == NLMSG_DONE) {
1600 if (h->nlmsg_type == NLMSG_ERROR) {
1601 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1602 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1603 fprintf(stderr, "ERROR truncated\n");
1605 errno = -err->error;
1606 if (errno == EOPNOTSUPP) {
1610 perror("TCPDIAG answers");
1616 if (!(f->families & (1<<r->idiag_family))) {
1617 h = NLMSG_NEXT(h, status);
1620 err = tcp_show_sock(h, NULL);
1628 h = NLMSG_NEXT(h, status);
1630 if (msg.msg_flags & MSG_TRUNC) {
1631 fprintf(stderr, "Message truncated\n");
1635 fprintf(stderr, "!!!Remnant of size %d\n", status);
1643 static int tcp_show_netlink_file(struct filter *f)
1648 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1649 perror("fopen($TCPDIAG_FILE)");
1655 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1657 status = fread(buf, 1, sizeof(*h), fp);
1659 perror("Reading header from $TCPDIAG_FILE");
1662 if (status != sizeof(*h)) {
1663 perror("Unexpected EOF reading $TCPDIAG_FILE");
1667 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1670 perror("Reading $TCPDIAG_FILE");
1673 if (status + sizeof(*h) < h->nlmsg_len) {
1674 perror("Unexpected EOF reading $TCPDIAG_FILE");
1678 /* The only legal exit point */
1679 if (h->nlmsg_type == NLMSG_DONE)
1682 if (h->nlmsg_type == NLMSG_ERROR) {
1683 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1684 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1685 fprintf(stderr, "ERROR truncated\n");
1687 errno = -err->error;
1688 perror("TCPDIAG answered");
1693 err = tcp_show_sock(h, f);
1699 static int tcp_show(struct filter *f, int socktype)
1703 int bufsize = 64*1024;
1705 dg_proto = TCP_PROTO;
1707 if (getenv("TCPDIAG_FILE"))
1708 return tcp_show_netlink_file(f);
1710 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1711 && tcp_show_netlink(f, NULL, socktype) == 0)
1714 /* Sigh... We have to parse /proc/net/tcp... */
1717 /* Estimate amount of sockets and try to allocate
1718 * huge buffer to read all the table at one read.
1719 * Limit it by 16MB though. The assumption is: as soon as
1720 * kernel was able to hold information about N connections,
1721 * it is able to give us some memory for snapshot.
1724 int guess = slabstat.socks+slabstat.tcp_syns;
1725 if (f->states&(1<<SS_TIME_WAIT))
1726 guess += slabstat.tcp_tws;
1727 if (guess > (16*1024*1024)/128)
1728 guess = (16*1024*1024)/128;
1730 if (guess > bufsize)
1733 while (bufsize >= 64*1024) {
1734 if ((buf = malloc(bufsize)) != NULL)
1743 if (f->families & (1<<AF_INET)) {
1744 if ((fp = net_tcp_open()) == NULL)
1747 setbuffer(fp, buf, bufsize);
1748 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
1753 if ((f->families & (1<<AF_INET6)) &&
1754 (fp = net_tcp6_open()) != NULL) {
1755 setbuffer(fp, buf, bufsize);
1756 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
1766 int saved_errno = errno;
1771 errno = saved_errno;
1777 int dgram_show_line(char *line, const struct filter *f, int family)
1780 char *loc, *rem, *data;
1785 if ((p = strchr(line, ':')) == NULL)
1789 if ((p = strchr(loc, ':')) == NULL)
1794 if ((p = strchr(rem, ':')) == NULL)
1800 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1802 if (!(f->states & (1<<state)))
1806 s.local.family = s.remote.family = family;
1807 if (family == AF_INET) {
1808 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1809 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1810 s.local.bytelen = s.remote.bytelen = 4;
1812 sscanf(loc, "%08x%08x%08x%08x:%x",
1818 sscanf(rem, "%08x%08x%08x%08x:%x",
1824 s.local.bytelen = s.remote.bytelen = 16;
1827 if (f->f && run_ssfilter(f->f, &s) == 0)
1831 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
1832 &s.state, &s.wq, &s.rq,
1834 &s.refcnt, &s.sk, opt);
1840 printf("%-*s ", netid_width, dg_proto);
1842 printf("%-*s ", state_width, sstate_name[s.state]);
1844 printf("%-6d %-6d ", s.rq, s.wq);
1846 formatted_print(&s.local, s.lport);
1847 formatted_print(&s.remote, s.rport);
1851 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1852 printf(" users:(%s)", ubuf);
1857 printf(" uid=%u", (unsigned)s.uid);
1858 printf(" ino=%u", s.ino);
1859 printf(" sk=%llx", s.sk);
1861 printf(" opt:\"%s\"", opt);
1869 int udp_show(struct filter *f)
1873 dg_proto = UDP_PROTO;
1875 if (f->families&(1<<AF_INET)) {
1876 if ((fp = net_udp_open()) == NULL)
1878 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
1883 if ((f->families&(1<<AF_INET6)) &&
1884 (fp = net_udp6_open()) != NULL) {
1885 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
1893 int saved_errno = errno;
1896 errno = saved_errno;
1901 int raw_show(struct filter *f)
1905 dg_proto = RAW_PROTO;
1907 if (f->families&(1<<AF_INET)) {
1908 if ((fp = net_raw_open()) == NULL)
1910 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
1915 if ((f->families&(1<<AF_INET6)) &&
1916 (fp = net_raw6_open()) != NULL) {
1917 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
1925 int saved_errno = errno;
1928 errno = saved_errno;
1936 struct unixstat *next;
1948 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
1949 SS_ESTABLISHED, SS_CLOSING };
1952 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
1954 void unix_list_free(struct unixstat *list)
1957 struct unixstat *s = list;
1965 void unix_list_print(struct unixstat *list, struct filter *f)
1970 for (s = list; s; s = s->next) {
1971 if (!(f->states & (1<<s->state)))
1973 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
1975 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
1981 for (p = list; p; p = p->next) {
1982 if (s->peer == p->ino)
1988 peer = p->name ? : "*";
1994 tst.local.family = AF_UNIX;
1995 tst.remote.family = AF_UNIX;
1996 memcpy(tst.local.data, &s->name, sizeof(s->name));
1997 if (strcmp(peer, "*") == 0)
1998 memset(tst.remote.data, 0, sizeof(peer));
2000 memcpy(tst.remote.data, &peer, sizeof(peer));
2001 if (run_ssfilter(f->f, &tst) == 0)
2006 printf("%-*s ", netid_width,
2007 s->type == SOCK_STREAM ? "u_str" : "u_dgr");
2009 printf("%-*s ", state_width, sstate_name[s->state]);
2010 printf("%-6d %-6d ", s->rq, s->wq);
2011 printf("%*s %-*d %*s %-*d",
2012 addr_width, s->name ? : "*", serv_width, s->ino,
2013 addr_width, peer, serv_width, s->peer);
2016 if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
2017 printf(" users:(%s)", ubuf);
2023 static int unix_show_sock(struct nlmsghdr *nlh, struct filter *f)
2025 struct unix_diag_msg *r = NLMSG_DATA(nlh);
2026 struct rtattr *tb[UNIX_DIAG_MAX+1];
2031 parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr*)(r+1),
2032 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2035 printf("%-*s ", netid_width,
2036 r->udiag_type == SOCK_STREAM ? "u_str" : "u_dgr");
2038 printf("%-*s ", state_width, sstate_name[r->udiag_state]);
2040 if (tb[UNIX_DIAG_RQLEN])
2041 rqlen = *(int *)RTA_DATA(tb[UNIX_DIAG_RQLEN]);
2045 printf("%-6d %-6d ", rqlen, 0);
2047 if (tb[UNIX_DIAG_NAME]) {
2048 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
2050 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
2052 if (name[0] == '\0')
2057 if (tb[UNIX_DIAG_PEER])
2058 peer_ino = *(int *)RTA_DATA(tb[UNIX_DIAG_PEER]);
2062 printf("%*s %-*d %*s %-*d",
2064 serv_width, r->udiag_ino,
2065 addr_width, "*", /* FIXME */
2066 serv_width, peer_ino);
2070 if (find_users(r->udiag_ino, ubuf, sizeof(ubuf)) > 0)
2071 printf(" users:(%s)", ubuf);
2079 static int unix_show_netlink(struct filter *f, FILE *dump_fp)
2083 struct nlmsghdr nlh;
2084 struct unix_diag_req r;
2088 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
2091 memset(&req, 0, sizeof(req));
2092 req.nlh.nlmsg_len = sizeof(req);
2093 req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
2094 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
2095 req.nlh.nlmsg_seq = 123456;
2097 req.r.sdiag_family = AF_UNIX;
2098 req.r.udiag_states = f->states;
2099 req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
2101 if (send(fd, &req, sizeof(req), 0) < 0) {
2109 struct sockaddr_nl nladdr;
2110 socklen_t slen = sizeof(nladdr);
2112 status = recvfrom(fd, buf, sizeof(buf), 0,
2113 (struct sockaddr *) &nladdr, &slen);
2121 fprintf(stderr, "EOF on netlink\n");
2126 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
2128 h = (struct nlmsghdr*)buf;
2129 while (NLMSG_OK(h, status)) {
2132 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
2133 h->nlmsg_seq != 123456)
2136 if (h->nlmsg_type == NLMSG_DONE)
2139 if (h->nlmsg_type == NLMSG_ERROR) {
2140 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
2141 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2142 fprintf(stderr, "ERROR truncated\n");
2144 errno = -err->error;
2145 if (errno != ENOENT)
2146 fprintf(stderr, "UDIAG answers %d\n", errno);
2152 err = unix_show_sock(h, f);
2160 h = NLMSG_NEXT(h, status);
2164 fprintf(stderr, "!!!Remnant of size %zd\n", status);
2174 int unix_show(struct filter *f)
2181 struct unixstat *list = NULL;
2183 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
2184 && unix_show_netlink(f, NULL) == 0)
2187 if ((fp = net_unix_open()) == NULL)
2189 fgets(buf, sizeof(buf)-1, fp);
2191 if (memcmp(buf, "Peer", 4) == 0)
2195 while (fgets(buf, sizeof(buf)-1, fp)) {
2196 struct unixstat *u, **insp;
2199 if (!(u = malloc(sizeof(*u))))
2203 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
2204 &u->peer, &u->rq, &u->wq, &flags, &u->type,
2205 &u->state, &u->ino, name) < 8)
2208 if (flags&(1<<16)) {
2209 u->state = SS_LISTEN;
2211 u->state = unix_state_map[u->state-1];
2212 if (u->type == SOCK_DGRAM &&
2213 u->state == SS_CLOSE &&
2215 u->state = SS_ESTABLISHED;
2226 if (u->type < (*insp)->type ||
2227 (u->type == (*insp)->type &&
2228 u->ino < (*insp)->ino))
2230 insp = &(*insp)->next;
2236 if ((u->name = malloc(strlen(name)+1)) == NULL)
2238 strcpy(u->name, name);
2240 if (++cnt > MAX_UNIX_REMEMBER) {
2241 unix_list_print(list, f);
2242 unix_list_free(list);
2249 unix_list_print(list, f);
2250 unix_list_free(list);
2259 int packet_show(struct filter *f)
2270 unsigned long long sk;
2272 if (!(f->states & (1<<SS_CLOSE)))
2275 if ((fp = net_packet_open()) == NULL)
2277 fgets(buf, sizeof(buf)-1, fp);
2279 while (fgets(buf, sizeof(buf)-1, fp)) {
2280 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2282 &type, &prot, &iface, &state,
2285 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2287 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2291 tst.local.family = AF_PACKET;
2292 tst.remote.family = AF_PACKET;
2295 tst.local.data[0] = prot;
2296 tst.remote.data[0] = 0;
2297 if (run_ssfilter(f->f, &tst) == 0)
2302 printf("%-*s ", netid_width,
2303 type == SOCK_RAW ? "p_raw" : "p_dgr");
2305 printf("%-*s ", state_width, "UNCONN");
2306 printf("%-6d %-6d ", rq, 0);
2308 printf("%*s:", addr_width, "*");
2311 printf("%*s:", addr_width,
2312 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2315 printf("%-*s ", serv_width, "*");
2317 printf("%-*s ", serv_width, xll_index_to_name(iface));
2320 addr_width, "", serv_width, "");
2324 if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2325 printf(" users:(%s)", ubuf);
2328 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2336 int netlink_show(struct filter *f)
2343 unsigned long long sk, cb;
2345 if (!(f->states & (1<<SS_CLOSE)))
2348 if ((fp = net_netlink_open()) == NULL)
2350 fgets(buf, sizeof(buf)-1, fp);
2352 while (fgets(buf, sizeof(buf)-1, fp)) {
2353 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2355 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2359 tst.local.family = AF_NETLINK;
2360 tst.remote.family = AF_NETLINK;
2363 tst.local.data[0] = prot;
2364 tst.remote.data[0] = 0;
2365 if (run_ssfilter(f->f, &tst) == 0)
2370 printf("%-*s ", netid_width, "nl");
2372 printf("%-*s ", state_width, "UNCONN");
2373 printf("%-6d %-6d ", rq, wq);
2374 if (resolve_services && prot == 0)
2375 printf("%*s:", addr_width, "rtnl");
2376 else if (resolve_services && prot == 3)
2377 printf("%*s:", addr_width, "fw");
2378 else if (resolve_services && prot == 4)
2379 printf("%*s:", addr_width, "tcpdiag");
2381 printf("%*d:", addr_width, prot);
2383 printf("%-*s ", serv_width, "*");
2384 } else if (resolve_services) {
2388 printf("%-*s ", serv_width, "kernel");
2389 } else if (pid > 0) {
2392 sprintf(procname, "%s/%d/stat",
2393 getenv("PROC_ROOT") ? : "/proc", pid);
2394 if ((fp = fopen(procname, "r")) != NULL) {
2395 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2396 sprintf(procname+strlen(procname), "/%d", pid);
2397 printf("%-*s ", serv_width, procname);
2404 printf("%-*d ", serv_width, pid);
2406 printf("%-*d ", serv_width, pid);
2409 addr_width, "", serv_width, "");
2412 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2425 int get_snmp_int(char *proto, char *key, int *result)
2429 int protolen = strlen(proto);
2430 int keylen = strlen(key);
2434 if ((fp = net_snmp_open()) == NULL)
2437 while (fgets(buf, sizeof(buf), fp) != NULL) {
2440 if (memcmp(buf, proto, protolen))
2442 while ((p = strchr(p, ' ')) != NULL) {
2445 if (memcmp(p, key, keylen) == 0 &&
2446 (p[keylen] == ' ' || p[keylen] == '\n'))
2449 if (fgets(buf, sizeof(buf), fp) == NULL)
2451 if (memcmp(buf, proto, protolen))
2454 while ((p = strchr(p, ' ')) != NULL) {
2457 sscanf(p, "%d", result);
2470 /* Get stats from sockstat */
2491 static void get_sockstat_line(char *line, struct sockstat *s)
2493 char id[256], rem[256];
2495 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2498 if (strcmp(id, "sockets:") == 0)
2499 sscanf(rem, "%*s%d", &s->socks);
2500 else if (strcmp(id, "UDP:") == 0)
2501 sscanf(rem, "%*s%d", &s->udp4);
2502 else if (strcmp(id, "UDP6:") == 0)
2503 sscanf(rem, "%*s%d", &s->udp6);
2504 else if (strcmp(id, "RAW:") == 0)
2505 sscanf(rem, "%*s%d", &s->raw4);
2506 else if (strcmp(id, "RAW6:") == 0)
2507 sscanf(rem, "%*s%d", &s->raw6);
2508 else if (strcmp(id, "TCP6:") == 0)
2509 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2510 else if (strcmp(id, "FRAG:") == 0)
2511 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2512 else if (strcmp(id, "FRAG6:") == 0)
2513 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2514 else if (strcmp(id, "TCP:") == 0)
2515 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2517 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2520 int get_sockstat(struct sockstat *s)
2525 memset(s, 0, sizeof(*s));
2527 if ((fp = net_sockstat_open()) == NULL)
2529 while(fgets(buf, sizeof(buf), fp) != NULL)
2530 get_sockstat_line(buf, s);
2533 if ((fp = net_sockstat6_open()) == NULL)
2535 while(fgets(buf, sizeof(buf), fp) != NULL)
2536 get_sockstat_line(buf, s);
2542 int print_summary(void)
2547 if (get_sockstat(&s) < 0)
2548 perror("ss: get_sockstat");
2549 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2550 perror("ss: get_snmpstat");
2552 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2554 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2555 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2557 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2560 s.tcp_tws, slabstat.tcp_tws,
2565 printf("Transport Total IP IPv6\n");
2566 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2567 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2568 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2569 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2570 printf("INET %-9d %-9d %-9d\n",
2571 s.raw4+s.udp4+s.tcp4_hashed+
2572 s.raw6+s.udp6+s.tcp6_hashed,
2573 s.raw4+s.udp4+s.tcp4_hashed,
2574 s.raw6+s.udp6+s.tcp6_hashed);
2575 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2582 static void _usage(FILE *dest)
2585 "Usage: ss [ OPTIONS ]\n"
2586 " ss [ OPTIONS ] [ FILTER ]\n"
2587 " -h, --help this message\n"
2588 " -V, --version output version information\n"
2589 " -n, --numeric don't resolve service names\n"
2590 " -r, --resolve resolve host names\n"
2591 " -a, --all display all sockets\n"
2592 " -l, --listening display listening sockets\n"
2593 " -o, --options show timer information\n"
2594 " -e, --extended show detailed socket information\n"
2595 " -m, --memory show socket memory usage\n"
2596 " -p, --processes show process using socket\n"
2597 " -i, --info show internal TCP information\n"
2598 " -s, --summary show socket usage summary\n"
2600 " -4, --ipv4 display only IP version 4 sockets\n"
2601 " -6, --ipv6 display only IP version 6 sockets\n"
2602 " -0, --packet display PACKET sockets\n"
2603 " -t, --tcp display only TCP sockets\n"
2604 " -u, --udp display only UDP sockets\n"
2605 " -d, --dccp display only DCCP sockets\n"
2606 " -w, --raw display only RAW sockets\n"
2607 " -x, --unix display only Unix domain sockets\n"
2608 " -f, --family=FAMILY display sockets of type FAMILY\n"
2610 " -A, --query=QUERY, --socket=QUERY\n"
2611 " QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2613 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
2614 " -F, --filter=FILE read filter information from FILE\n"
2615 " FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2619 static void help(void) __attribute__((noreturn));
2620 static void help(void)
2626 static void usage(void) __attribute__((noreturn));
2627 static void usage(void)
2634 int scan_state(const char *state)
2637 if (strcasecmp(state, "close") == 0 ||
2638 strcasecmp(state, "closed") == 0)
2639 return (1<<SS_CLOSE);
2640 if (strcasecmp(state, "syn-rcv") == 0)
2641 return (1<<SS_SYN_RECV);
2642 if (strcasecmp(state, "established") == 0)
2643 return (1<<SS_ESTABLISHED);
2644 if (strcasecmp(state, "all") == 0)
2646 if (strcasecmp(state, "connected") == 0)
2647 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2648 if (strcasecmp(state, "synchronized") == 0)
2649 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2650 if (strcasecmp(state, "bucket") == 0)
2651 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2652 if (strcasecmp(state, "big") == 0)
2653 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2654 for (i=0; i<SS_MAX; i++) {
2655 if (strcasecmp(state, sstate_namel[i]) == 0)
2661 static const struct option long_opts[] = {
2662 { "numeric", 0, 0, 'n' },
2663 { "resolve", 0, 0, 'r' },
2664 { "options", 0, 0, 'o' },
2665 { "extended", 0, 0, 'e' },
2666 { "memory", 0, 0, 'm' },
2667 { "info", 0, 0, 'i' },
2668 { "processes", 0, 0, 'p' },
2669 { "dccp", 0, 0, 'd' },
2670 { "tcp", 0, 0, 't' },
2671 { "udp", 0, 0, 'u' },
2672 { "raw", 0, 0, 'w' },
2673 { "unix", 0, 0, 'x' },
2674 { "all", 0, 0, 'a' },
2675 { "listening", 0, 0, 'l' },
2676 { "ipv4", 0, 0, '4' },
2677 { "ipv6", 0, 0, '6' },
2678 { "packet", 0, 0, '0' },
2679 { "family", 1, 0, 'f' },
2680 { "socket", 1, 0, 'A' },
2681 { "query", 1, 0, 'A' },
2682 { "summary", 0, 0, 's' },
2683 { "diag", 1, 0, 'D' },
2684 { "filter", 1, 0, 'F' },
2685 { "version", 0, 0, 'V' },
2686 { "help", 0, 0, 'h' },
2691 int main(int argc, char *argv[])
2697 const char *dump_tcpdiag = NULL;
2698 FILE *filter_fp = NULL;
2701 memset(¤t_filter, 0, sizeof(current_filter));
2703 current_filter.states = default_filter.states;
2705 while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spf:miA:D:F:vV",
2706 long_opts, NULL)) != EOF) {
2709 resolve_services = 0;
2729 user_ent_hash_build();
2732 current_filter.dbs |= (1<<DCCP_DB);
2736 current_filter.dbs |= (1<<TCP_DB);
2740 current_filter.dbs |= (1<<UDP_DB);
2744 current_filter.dbs |= (1<<RAW_DB);
2748 current_filter.dbs |= UNIX_DBM;
2752 current_filter.states = SS_ALL;
2755 current_filter.states = (1<<SS_LISTEN) | (1<<SS_CLOSE);
2758 preferred_family = AF_INET;
2761 preferred_family = AF_INET6;
2764 preferred_family = AF_PACKET;
2767 if (strcmp(optarg, "inet") == 0)
2768 preferred_family = AF_INET;
2769 else if (strcmp(optarg, "inet6") == 0)
2770 preferred_family = AF_INET6;
2771 else if (strcmp(optarg, "link") == 0)
2772 preferred_family = AF_PACKET;
2773 else if (strcmp(optarg, "unix") == 0)
2774 preferred_family = AF_UNIX;
2775 else if (strcmp(optarg, "netlink") == 0)
2776 preferred_family = AF_NETLINK;
2777 else if (strcmp(optarg, "help") == 0)
2780 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2788 current_filter.dbs = 0;
2794 if ((p1 = strchr(p, ',')) != NULL)
2796 if (strcmp(p, "all") == 0) {
2797 current_filter.dbs = ALL_DB;
2798 } else if (strcmp(p, "inet") == 0) {
2799 current_filter.dbs |= (1<<TCP_DB)|(1<<DCCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2800 } else if (strcmp(p, "udp") == 0) {
2801 current_filter.dbs |= (1<<UDP_DB);
2802 } else if (strcmp(p, "dccp") == 0) {
2803 current_filter.dbs |= (1<<DCCP_DB);
2804 } else if (strcmp(p, "tcp") == 0) {
2805 current_filter.dbs |= (1<<TCP_DB);
2806 } else if (strcmp(p, "raw") == 0) {
2807 current_filter.dbs |= (1<<RAW_DB);
2808 } else if (strcmp(p, "unix") == 0) {
2809 current_filter.dbs |= UNIX_DBM;
2810 } else if (strcasecmp(p, "unix_stream") == 0 ||
2811 strcmp(p, "u_str") == 0) {
2812 current_filter.dbs |= (1<<UNIX_ST_DB);
2813 } else if (strcasecmp(p, "unix_dgram") == 0 ||
2814 strcmp(p, "u_dgr") == 0) {
2815 current_filter.dbs |= (1<<UNIX_DG_DB);
2816 } else if (strcmp(p, "packet") == 0) {
2817 current_filter.dbs |= PACKET_DBM;
2818 } else if (strcmp(p, "packet_raw") == 0 ||
2819 strcmp(p, "p_raw") == 0) {
2820 current_filter.dbs |= (1<<PACKET_R_DB);
2821 } else if (strcmp(p, "packet_dgram") == 0 ||
2822 strcmp(p, "p_dgr") == 0) {
2823 current_filter.dbs |= (1<<PACKET_DG_DB);
2824 } else if (strcmp(p, "netlink") == 0) {
2825 current_filter.dbs |= (1<<NETLINK_DB);
2827 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2838 dump_tcpdiag = optarg;
2842 fprintf(stderr, "More than one filter file\n");
2845 if (optarg[0] == '-')
2848 filter_fp = fopen(optarg, "r");
2850 perror("fopen filter file");
2856 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
2869 get_slabstat(&slabstat);
2873 if (do_default && argc == 0)
2878 current_filter.dbs = default_filter.dbs;
2880 if (preferred_family == AF_UNSPEC) {
2881 if (!(current_filter.dbs&~UNIX_DBM))
2882 preferred_family = AF_UNIX;
2883 else if (!(current_filter.dbs&~PACKET_DBM))
2884 preferred_family = AF_PACKET;
2885 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
2886 preferred_family = AF_NETLINK;
2889 if (preferred_family != AF_UNSPEC) {
2891 if (preferred_family == AF_INET ||
2892 preferred_family == AF_INET6) {
2893 mask2= current_filter.dbs;
2894 } else if (preferred_family == AF_PACKET) {
2896 } else if (preferred_family == AF_UNIX) {
2898 } else if (preferred_family == AF_NETLINK) {
2899 mask2 = (1<<NETLINK_DB);
2905 current_filter.dbs = mask2;
2907 current_filter.dbs &= mask2;
2908 current_filter.families = (1<<preferred_family);
2911 current_filter.families = ~0;
2913 current_filter.families = default_filter.families;
2915 if (current_filter.dbs == 0) {
2916 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
2919 if (current_filter.families == 0) {
2920 fprintf(stderr, "ss: no families to show with such filter.\n");
2924 if (resolve_services && resolve_hosts &&
2925 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
2926 init_service_resolver();
2928 /* Now parse filter... */
2929 if (argc == 0 && filter_fp) {
2930 if (ssfilter_parse(¤t_filter.f, 0, NULL, filter_fp))
2935 if (strcmp(*argv, "state") == 0) {
2938 current_filter.states = 0;
2939 current_filter.states |= scan_state(*argv);
2941 } else if (strcmp(*argv, "exclude") == 0 ||
2942 strcmp(*argv, "excl") == 0) {
2945 current_filter.states = SS_ALL;
2946 current_filter.states &= ~scan_state(*argv);
2949 if (ssfilter_parse(¤t_filter.f, argc, argv, filter_fp))
2956 if (current_filter.states == 0) {
2957 fprintf(stderr, "ss: no socket states to show with such filter.\n");
2962 FILE *dump_fp = stdout;
2963 if (!(current_filter.dbs & (1<<TCP_DB))) {
2964 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
2967 if (dump_tcpdiag[0] != '-') {
2968 dump_fp = fopen(dump_tcpdiag, "w");
2969 if (!dump_tcpdiag) {
2970 perror("fopen dump file");
2974 tcp_show_netlink(¤t_filter, dump_fp, TCPDIAG_GETSOCK);
2980 if (current_filter.dbs&(current_filter.dbs-1))
2984 if (current_filter.states&(current_filter.states-1))
2988 if (isatty(STDOUT_FILENO)) {
2991 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
2993 screen_width = w.ws_col;
2997 addrp_width = screen_width;
2998 addrp_width -= netid_width+1;
2999 addrp_width -= state_width+1;
3002 if (addrp_width&1) {
3005 else if (state_width)
3012 serv_width = resolve_services ? 7 : 5;
3014 if (addrp_width < 15+serv_width+1)
3015 addrp_width = 15+serv_width+1;
3017 addr_width = addrp_width - serv_width - 1;
3020 printf("%-*s ", netid_width, "Netid");
3022 printf("%-*s ", state_width, "State");
3023 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
3025 printf("%*s:%-*s %*s:%-*s\n",
3026 addr_width, "Local Address", serv_width, "Port",
3027 addr_width, "Peer Address", serv_width, "Port");
3031 if (current_filter.dbs & (1<<NETLINK_DB))
3032 netlink_show(¤t_filter);
3033 if (current_filter.dbs & PACKET_DBM)
3034 packet_show(¤t_filter);
3035 if (current_filter.dbs & UNIX_DBM)
3036 unix_show(¤t_filter);
3037 if (current_filter.dbs & (1<<RAW_DB))
3038 raw_show(¤t_filter);
3039 if (current_filter.dbs & (1<<UDP_DB))
3040 udp_show(¤t_filter);
3041 if (current_filter.dbs & (1<<TCP_DB))
3042 tcp_show(¤t_filter, TCPDIAG_GETSOCK);
3043 if (current_filter.dbs & (1<<DCCP_DB))
3044 tcp_show(¤t_filter, DCCPDIAG_GETSOCK);