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>
32 #include "libnetlink.h"
35 #include <asm/byteorder.h>
36 #include <linux/tcp.h>
37 #include <linux/tcp_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;
73 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
74 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB))
75 #define ALL_DB ((1<<MAX_DB)-1)
93 #define SS_ALL ((1<<SS_MAX)-1)
105 struct filter default_filter = {
107 states: SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)),
108 families: (1<<AF_INET)|(1<<AF_INET6),
111 struct filter current_filter;
113 int generic_proc_open(char *env, char *name)
116 char *p = getenv(env);
118 p = getenv("PROC_ROOT") ? : "/proc";
119 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
122 return open(store, O_RDONLY);
125 int net_tcp_open(void)
127 return generic_proc_open("PROC_NET_TCP", "net/tcp");
130 int net_tcp6_open(void)
132 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
135 int net_udp_open(void)
137 return generic_proc_open("PROC_NET_UDP", "net/udp");
140 int net_udp6_open(void)
142 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
145 int net_raw_open(void)
147 return generic_proc_open("PROC_NET_RAW", "net/raw");
150 int net_raw6_open(void)
152 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
155 int net_unix_open(void)
157 return generic_proc_open("PROC_NET_UNIX", "net/unix");
160 int net_packet_open(void)
162 return generic_proc_open("PROC_NET_PACKET", "net/packet");
165 int net_netlink_open(void)
167 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
170 int slabinfo_open(void)
172 return generic_proc_open("PROC_SLABINFO", "slabinfo");
175 int net_sockstat_open(void)
177 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
180 int net_sockstat6_open(void)
182 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
185 int net_snmp_open(void)
187 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
190 int net_netstat_open(void)
192 return generic_proc_open("PROC_NET_NETSTAT", "net/netstat");
195 int ephemeral_ports_open(void)
197 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
200 int find_users(int ino, char *buf, int buflen)
214 sprintf(pattern, "socket:[%d]", ino);
215 pattern_len = strlen(pattern);
217 strncpy(name, getenv("PROC_ROOT") ? : "/proc/", sizeof(name)/2);
218 name[sizeof(name)/2] = 0;
219 if (strlen(name) == 0 ||
220 name[strlen(name)-1] != '/')
222 nameoff = strlen(name);
223 if ((dir = opendir(name)) == NULL)
226 while ((d = readdir(dir)) != NULL) {
234 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
237 sprintf(name+nameoff, "%d/fd/", pid);
239 if ((dir1 = opendir(name)) == NULL)
244 while ((d1 = readdir(dir1)) != NULL) {
248 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
251 sprintf(name+pos, "%d", fd);
252 n = readlink(name, lnk, sizeof(lnk)-1);
253 if (n != pattern_len ||
254 memcmp(lnk, pattern, n))
257 if (ptr-buf >= buflen-1)
260 if (process[0] == 0) {
263 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
264 getenv("PROC_ROOT") ? : "/proc", pid);
265 if ((fp = fopen(tmp, "r")) != NULL) {
266 fscanf(fp, "%*d (%[^)])", process);
271 snprintf(ptr, buflen-(ptr-buf), "(\"%s\",%d,%d),", process, pid, fd);
284 /* Get stats from slab */
295 struct slabstat slabstat;
297 static const char *slabstat_ids[] =
306 int get_slabstat(struct slabstat *s)
312 memset(s, 0, sizeof(*s));
314 if ((fp = fdopen(slabinfo_open(), "r")) == NULL)
317 cnt = sizeof(*s)/sizeof(int);
319 fgets(buf, sizeof(buf), fp);
320 while(fgets(buf, sizeof(buf), fp) != NULL) {
322 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
323 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
324 sscanf(buf, "%*s%d", ((int *)s) + i);
337 static const char *sstate_name[] = {
339 [TCP_ESTABLISHED] = "ESTAB",
340 [TCP_SYN_SENT] = "SYN-SENT",
341 [TCP_SYN_RECV] = "SYN-RECV",
342 [TCP_FIN_WAIT1] = "FIN-WAIT-1",
343 [TCP_FIN_WAIT2] = "FIN-WAIT-2",
344 [TCP_TIME_WAIT] = "TIME-WAIT",
345 [TCP_CLOSE] = "UNCONN",
346 [TCP_CLOSE_WAIT] = "CLOSE-WAIT",
347 [TCP_LAST_ACK] = "LAST-ACK",
348 [TCP_LISTEN] = "LISTEN",
349 [TCP_CLOSING] = "CLOSING",
352 static const char *sstate_namel[] = {
354 [TCP_ESTABLISHED] = "established",
355 [TCP_SYN_SENT] = "syn-sent",
356 [TCP_SYN_RECV] = "syn-recv",
357 [TCP_FIN_WAIT1] = "fin-wait-1",
358 [TCP_FIN_WAIT2] = "fin-wait-2",
359 [TCP_TIME_WAIT] = "time-wait",
360 [TCP_CLOSE] = "unconnected",
361 [TCP_CLOSE_WAIT] = "close-wait",
362 [TCP_LAST_ACK] = "last-ack",
363 [TCP_LISTEN] = "listening",
364 [TCP_CLOSING] = "closing",
382 unsigned long long sk;
383 int rto, ato, qack, cwnd, ssthresh;
386 static const char *tmr_name[] = {
395 const char *print_ms_timer(int timeout)
398 int secs, msecs, minutes;
404 msecs = timeout%1000;
408 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
415 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
418 sprintf(buf+strlen(buf), "%03dms", msecs);
422 const char *print_hz_timer(int timeout)
425 return print_ms_timer(((timeout*1000) + hz-1)/hz);
436 struct scache *rlist;
438 void init_service_resolver(void)
441 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
443 fgets(buf, sizeof(buf), fp);
444 while (fgets(buf, sizeof(buf), fp) != NULL) {
445 unsigned int progn, port;
446 char proto[128], prog[128];
447 if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
448 &port, prog+4) == 4) {
449 struct scache *c = malloc(sizeof(*c));
452 memcpy(prog, "rpc.", 4);
453 c->name = strdup(prog);
454 if (strcmp(proto, TCP_PROTO) == 0)
455 c->proto = TCP_PROTO;
456 else if (strcmp(proto, UDP_PROTO) == 0)
457 c->proto = UDP_PROTO;
468 const char *__resolve_service(int port)
472 for (c = rlist; c; c = c->next) {
473 if (c->port == port && c->proto == dg_proto)
477 /* Even do not try default linux ephemeral port ranges:
478 * default /etc/services contains so much of useless crap
479 * wouldbe "allocated" to this area that resolution
480 * is really harmful. I shrug each time when seeing
481 * "socks" or "cfinger" in dumps.
483 if (port < 32768 && (port < 1024 || port > 4999)) {
490 se = getservbyport(htons(port), dg_proto);
499 const char *resolve_service(int port)
501 static char buf[128];
502 static struct scache cache[256];
510 if (resolve_services) {
511 if (dg_proto == RAW_PROTO) {
512 return inet_proto_n2a(port, buf, sizeof(buf));
516 int hash = (port^(((unsigned long)dg_proto)>>2))&255;
518 for (c = &cache[hash]; c; c = c->next) {
519 if (c->port == port &&
520 c->proto == dg_proto) {
527 if ((res = __resolve_service(port)) != NULL) {
528 if ((c = malloc(sizeof(*c))) == NULL)
539 c->name = strdup(res);
540 c->next = cache[hash].next;
541 cache[hash].next = c;
549 sprintf(buf, "%u", port);
553 void formatted_print(const inet_prefix *a, int port)
556 const char *ap = buf;
559 est_len = addr_width;
561 if (a->family == AF_INET) {
562 if (a->data[0] == 0) {
566 ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
569 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
570 est_len = strlen(ap);
571 if (est_len <= addr_width)
572 est_len = addr_width;
574 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
576 printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
583 struct aafilter *next;
586 int inet2_addr_match(const inet_prefix *a, const inet_prefix *p, int plen)
588 if (!inet_addr_match(a, p, plen))
591 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
592 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
594 if (p->family == AF_INET && a->family == AF_INET6) {
595 if (a->data[0] == 0 && a->data[1] == 0 &&
596 a->data[2] == htonl(0xffff)) {
597 inet_prefix tmp = *a;
598 tmp.data[0] = a->data[3];
599 return inet_addr_match(&tmp, p, plen);
605 int unix_match(const inet_prefix *a, const inet_prefix *p)
607 char *addr, *pattern;
608 memcpy(&addr, a->data, sizeof(addr));
609 memcpy(&pattern, p->data, sizeof(pattern));
614 return !fnmatch(pattern, addr, 0);
617 int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
622 static int low, high=65535;
624 if (s->local.family == AF_UNIX) {
626 memcpy(&p, s->local.data, sizeof(p));
627 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
628 strspn(p+1, "0123456789abcdef") == 5);
630 if (s->local.family == AF_PACKET)
631 return s->lport == 0 && s->local.data == 0;
632 if (s->local.family == AF_NETLINK)
636 FILE *fp = fdopen(ephemeral_ports_open(), "r");
638 fscanf(fp, "%d%d", &low, &high);
642 return s->lport >= low && s->lport <= high;
646 struct aafilter *a = (void*)f->pred;
647 if (a->addr.family == AF_UNIX)
648 return unix_match(&s->remote, &a->addr);
649 if (a->port != -1 && a->port != s->rport)
651 if (a->addr.bitlen) {
653 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
655 } while ((a = a->next) != NULL);
662 struct aafilter *a = (void*)f->pred;
663 if (a->addr.family == AF_UNIX)
664 return unix_match(&s->local, &a->addr);
665 if (a->port != -1 && a->port != s->lport)
667 if (a->addr.bitlen) {
669 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
671 } while ((a = a->next) != NULL);
678 struct aafilter *a = (void*)f->pred;
679 return s->rport >= a->port;
683 struct aafilter *a = (void*)f->pred;
684 return s->rport <= a->port;
688 struct aafilter *a = (void*)f->pred;
689 return s->lport >= a->port;
693 struct aafilter *a = (void*)f->pred;
694 return s->lport <= a->port;
697 /* Yup. It is recursion. Sorry. */
699 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
701 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
703 return !run_ssfilter(f->pred, s);
709 /* Relocate external jumps by reloc. */
710 void ssfilter_patch(char *a, int len, int reloc)
713 struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op*)a;
723 int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
728 if (!(*bytecode=malloc(4))) abort();
729 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_AUTO, 4, 8 };
735 struct aafilter *a = (void*)f->pred;
738 int code = (f->type == SSF_DCOND ? TCPDIAG_BC_D_COND : TCPDIAG_BC_S_COND);
741 for (b=a; b; b=b->next) {
742 len += 4 + sizeof(struct tcpdiag_hostcond);
743 if (a->addr.family == AF_INET6)
750 if (!(ptr = malloc(len))) abort();
752 for (b=a; b; b=b->next) {
753 struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op *)ptr;
754 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
755 int oplen = alen + 4 + sizeof(struct tcpdiag_hostcond);
756 struct tcpdiag_hostcond *cond = (struct tcpdiag_hostcond*)(ptr+4);
758 *op = (struct tcpdiag_bc_op){ code, oplen, oplen+4 };
759 cond->family = a->addr.family;
760 cond->port = a->port;
761 cond->prefix_len = a->addr.bitlen;
762 memcpy(cond->addr, a->addr.data, alen);
765 op = (struct tcpdiag_bc_op *)ptr;
766 *op = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, len - (ptr-*bytecode)};
770 return ptr - *bytecode;
774 struct aafilter *x = (void*)f->pred;
775 if (!(*bytecode=malloc(8))) abort();
776 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_D_GE, 8, 12 };
777 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
782 struct aafilter *x = (void*)f->pred;
783 if (!(*bytecode=malloc(8))) abort();
784 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_D_LE, 8, 12 };
785 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
790 struct aafilter *x = (void*)f->pred;
791 if (!(*bytecode=malloc(8))) abort();
792 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_S_GE, 8, 12 };
793 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
798 struct aafilter *x = (void*)f->pred;
799 if (!(*bytecode=malloc(8))) abort();
800 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_S_LE, 8, 12 };
801 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
807 char *a1, *a2, *a, l1, l2;
808 l1 = ssfilter_bytecompile(f->pred, &a1);
809 l2 = ssfilter_bytecompile(f->post, &a2);
810 if (!(a = malloc(l1+l2))) abort();
812 memcpy(a+l1, a2, l2);
814 ssfilter_patch(a, l1, l2);
820 char *a1, *a2, *a, l1, l2;
821 l1 = ssfilter_bytecompile(f->pred, &a1);
822 l2 = ssfilter_bytecompile(f->post, &a2);
823 if (!(a = malloc(l1+l2+4))) abort();
825 memcpy(a+l1+4, a2, l2);
827 *(struct tcpdiag_bc_op*)(a+l1) = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, l2+4 };
834 l1 = ssfilter_bytecompile(f->pred, &a1);
835 if (!(a = malloc(l1+4))) abort();
838 *(struct tcpdiag_bc_op*)(a+l1) = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, 8 };
847 int remember_he(struct aafilter *a, struct hostent *he)
849 char **ptr = he->h_addr_list;
853 if (he->h_addrtype == AF_INET)
855 else if (he->h_addrtype == AF_INET6)
861 struct aafilter *b = a;
862 if (a->addr.bitlen) {
863 if ((b = malloc(sizeof(*b))) == NULL)
869 memcpy(b->addr.data, *ptr, len);
870 b->addr.bytelen = len;
871 b->addr.bitlen = len*8;
872 b->addr.family = he->h_addrtype;
879 int get_dns_host(struct aafilter *a, char *addr, int fam)
890 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
892 cnt = remember_he(a, he);
893 if (fam == AF_UNSPEC) {
894 he = gethostbyname2(addr, AF_INET6);
896 cnt += remember_he(a, he);
905 struct rtnl_handle rth;
912 const char *xll_index_to_name(int index)
916 return ll_index_to_name(index);
919 int xll_name_to_index(char *dev)
923 return ll_name_to_index(dev);
926 void *parse_hostcond(char *addr)
930 struct aafilter *res;
931 int fam = preferred_family;
933 memset(&a, 0, sizeof(a));
936 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
938 a.addr.family = AF_UNIX;
939 if (strncmp(addr, "unix:", 5) == 0)
942 a.addr.bitlen = 8*strlen(p);
943 memcpy(a.addr.data, &p, sizeof(p));
947 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
948 a.addr.family = AF_PACKET;
950 if (strncmp(addr, "link:", 5) == 0)
952 port = strchr(addr, ':');
955 if (port[1] && strcmp(port+1, "*")) {
956 if (get_integer(&a.port, port+1, 0)) {
957 if ((a.port = xll_name_to_index(port+1)) <= 0)
962 if (addr[0] && strcmp(addr, "*")) {
965 if (ll_proto_a2n(&tmp, addr))
967 a.addr.data[0] = ntohs(tmp);
972 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
973 a.addr.family = AF_NETLINK;
975 if (strncmp(addr, "netlink:", 8) == 0)
977 port = strchr(addr, ':');
980 if (port[1] && strcmp(port+1, "*")) {
981 if (get_integer(&a.port, port+1, 0)) {
982 if (strcmp(port+1, "kernel") == 0)
989 if (addr[0] && strcmp(addr, "*")) {
991 if (get_u32(a.addr.data, addr, 0)) {
992 if (strcmp(addr, "rtnl") == 0)
994 else if (strcmp(addr, "fw") == 0)
996 else if (strcmp(addr, "tcpdiag") == 0)
1005 if (strncmp(addr, "inet:", 5) == 0) {
1008 } else if (strncmp(addr, "inet6:", 6) == 0) {
1013 /* URL-like literal [] */
1014 if (addr[0] == '[') {
1016 if ((port = strchr(addr, ']')) == NULL)
1019 } else if (addr[0] == '*') {
1022 port = strrchr(strchr(addr, '/') ? : addr, ':');
1024 if (port && *port) {
1028 if (*port && *port != '*') {
1029 if (get_integer(&a.port, port, 0)) {
1030 struct servent *se1 = NULL;
1031 struct servent *se2 = NULL;
1032 if (current_filter.dbs&(1<<UDP_DB))
1033 se1 = getservbyname(port, UDP_PROTO);
1034 if (current_filter.dbs&(1<<TCP_DB))
1035 se2 = getservbyname(port, TCP_PROTO);
1036 if (se1 && se2 && se1->s_port != se2->s_port) {
1037 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1043 a.port = ntohs(se1->s_port);
1046 for (s = rlist; s; s = s->next) {
1047 if ((s->proto == UDP_PROTO &&
1048 (current_filter.dbs&(1<<UDP_DB))) ||
1049 (s->proto == TCP_PROTO &&
1050 (current_filter.dbs&(1<<TCP_DB)))) {
1051 if (s->name && strcmp(s->name, port) == 0) {
1052 if (a.port > 0 && a.port != s->port) {
1053 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1061 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1068 if (addr && *addr && *addr != '*') {
1069 if (get_prefix_1(&a.addr, addr, fam)) {
1070 if (get_dns_host(&a, addr, fam)) {
1071 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1078 res = malloc(sizeof(*res));
1080 memcpy(res, &a, sizeof(a));
1084 int tcp_show_line(char *line, struct filter *f, int family)
1087 char *loc, *rem, *data;
1092 if ((p = strchr(line, ':')) == NULL)
1096 if ((p = strchr(loc, ':')) == NULL)
1101 if ((p = strchr(rem, ':')) == NULL)
1107 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1109 if (!(f->states & (1<<state)))
1113 s.local.family = s.remote.family = family;
1114 if (family == AF_INET) {
1115 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1116 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1117 s.local.bytelen = s.remote.bytelen = 4;
1119 sscanf(loc, "%08x%08x%08x%08x:%x",
1125 sscanf(rem, "%08x%08x%08x%08x:%x",
1131 s.local.bytelen = s.remote.bytelen = 16;
1134 if (f->f && run_ssfilter(f->f, &s) == 0)
1138 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %d %d %llx %d %d %d %d %d %[^\n]\n",
1139 &s.state, &s.wq, &s.rq,
1140 &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1141 &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1142 &s.cwnd, &s.ssthresh, opt);
1155 printf("%-*s ", netid_width, "tcp");
1157 printf("%-*s ", state_width, sstate_name[s.state]);
1159 printf("%-6d %-6d ", s.rq, s.wq);
1161 formatted_print(&s.local, s.lport);
1162 formatted_print(&s.remote, s.rport);
1168 printf(" timer:(%s,%s,%d)",
1170 print_hz_timer(s.timeout),
1171 s.timer != 1 ? s.probes : s.retrs);
1175 if (s.rto && s.rto != 3*get_hz())
1176 printf(" rto:%g", (double)s.rto/get_hz());
1178 printf(" ato:%g", (double)s.ato/get_hz());
1180 printf(" cwnd:%d", s.cwnd);
1181 if (s.ssthresh != -1)
1182 printf(" ssthresh:%d", s.ssthresh);
1184 printf(" qack:%d", s.qack/2);
1190 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1191 printf(" users:(%s)", ubuf);
1195 printf(" uid:%u", (unsigned)s.uid);
1196 printf(" ino:%u", (unsigned)s.ino);
1197 printf(" sk:%llx", s.sk);
1199 printf(" opt:\"%s\"", opt);
1206 int generic_record_read(int fd, char *buf, int bufsize,
1207 int (*worker)(char*, struct filter *, int),
1208 struct filter *f, int fam)
1215 /* Load the first chunk and calculate record length from it. */
1216 n = read(fd, buf, bufsize);
1219 /* I _know_ that this is wrong, do not remind. :-)
1220 * But this works nowadays. */
1223 p = memchr(buf, '\n', n);
1224 if (p == NULL || (p-buf) >= n)
1225 goto outwrongformat;
1226 recsize = (p-buf)+1;
1230 while ((p+recsize) - buf <= n) {
1231 if (p[recsize-1] != '\n')
1232 goto outwrongformat;
1234 if (worker(p, f, fam) < 0)
1239 int remains = (buf+bufsize) - p;
1240 memcpy(buf, p, remains);
1242 n = read(fd, p, (buf+bufsize) - p);
1245 if (n < (buf+bufsize) - p) {
1249 goto outwrongformat;
1257 goto outwrongformat;
1270 void tcp_show_info(struct nlmsghdr *nlh, struct tcpdiagmsg *r)
1272 struct rtattr * tb[TCPDIAG_MAX+1];
1274 memset(tb, 0, sizeof(tb));
1275 parse_rtattr(tb, TCPDIAG_MAX, (struct rtattr*)(r+1),
1276 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1278 if (tb[TCPDIAG_MEMINFO]) {
1279 const struct tcpdiag_meminfo *minfo
1280 = RTA_DATA(tb[TCPDIAG_MEMINFO]);
1281 printf(" mem:(r%u,w%u,f%u,t%u)",
1282 minfo->tcpdiag_rmem,
1283 minfo->tcpdiag_wmem,
1284 minfo->tcpdiag_fmem,
1285 minfo->tcpdiag_tmem);
1288 if (tb[TCPDIAG_INFO]) {
1289 struct tcp_info *info;
1290 int len = RTA_PAYLOAD(tb[TCPDIAG_INFO]);
1292 /* workaround for older kernels with less fields */
1293 if (len < sizeof(*info)) {
1294 info = alloca(sizeof(*info));
1295 memset(info, 0, sizeof(*info));
1296 memcpy(info, RTA_DATA(tb[TCPDIAG_INFO]), len);
1298 info = RTA_DATA(tb[TCPDIAG_INFO]);
1300 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1302 if (info->tcpi_options & TCPI_OPT_SACK)
1304 if (info->tcpi_options & TCPI_OPT_WSCALE)
1305 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1306 info->tcpi_rcv_wscale);
1307 if (info->tcpi_options & TCPI_OPT_ECN)
1309 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1310 printf(" rto:%g", (double)info->tcpi_rto/1000);
1312 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1313 (double)info->tcpi_rttvar/1000);
1315 printf(" ato:%g", (double)info->tcpi_ato/1000);
1316 if (info->tcpi_snd_cwnd != 2)
1317 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1318 if (info->tcpi_snd_ssthresh < 0xFFFF)
1319 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1321 #if LINUX_VERSION_CODE >= 0x20607
1322 if (info->tcpi_rcv_rtt)
1323 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1324 if (info->tcpi_rcv_space)
1325 printf(" rcv_space:%d", info->tcpi_rcv_space);
1327 if (tb[TCPDIAG_VEGASINFO]) {
1328 const struct tcpvegas_info *vinfo
1329 = RTA_DATA(tb[TCPDIAG_VEGASINFO]);
1331 if (vinfo->tcpv_enabled)
1334 if (vinfo->tcpv_rtt &&
1335 vinfo->tcpv_rtt != 0x7fffffff &&
1336 info->tcpi_snd_mss &&
1337 info->tcpi_snd_cwnd) {
1339 (double) info->tcpi_snd_cwnd *
1340 (double) info->tcpi_snd_mss *
1341 8000000. / (double) vinfo->tcpv_rtt);
1348 int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
1350 struct tcpdiagmsg *r = NLMSG_DATA(nlh);
1353 s.state = r->tcpdiag_state;
1354 s.local.family = s.remote.family = r->tcpdiag_family;
1355 s.lport = ntohs(r->id.tcpdiag_sport);
1356 s.rport = ntohs(r->id.tcpdiag_dport);
1357 if (s.local.family == AF_INET) {
1358 s.local.bytelen = s.remote.bytelen = 4;
1360 s.local.bytelen = s.remote.bytelen = 16;
1362 memcpy(s.local.data, r->id.tcpdiag_src, s.local.bytelen);
1363 memcpy(s.remote.data, r->id.tcpdiag_dst, s.local.bytelen);
1365 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1369 printf("%-*s ", netid_width, "tcp");
1371 printf("%-*s ", state_width, sstate_name[s.state]);
1373 printf("%-6d %-6d ", r->tcpdiag_rqueue, r->tcpdiag_wqueue);
1375 formatted_print(&s.local, s.lport);
1376 formatted_print(&s.remote, s.rport);
1379 if (r->tcpdiag_timer) {
1380 if (r->tcpdiag_timer > 4)
1381 r->tcpdiag_timer = 5;
1382 printf(" timer:(%s,%s,%d)",
1383 tmr_name[r->tcpdiag_timer],
1384 print_ms_timer(r->tcpdiag_expires),
1385 r->tcpdiag_retrans);
1390 if (find_users(r->tcpdiag_inode, ubuf, sizeof(ubuf)) > 0)
1391 printf(" users:(%s)", ubuf);
1395 printf(" uid:%u", (unsigned)r->tcpdiag_uid);
1396 printf(" ino:%u", (unsigned)r->tcpdiag_inode);
1397 printf(" sk:%08x", r->id.tcpdiag_cookie[0]);
1398 if (r->id.tcpdiag_cookie[1] != 0)
1399 printf("%08x", r->id.tcpdiag_cookie[1]);
1401 if (show_mem || show_tcpinfo) {
1403 tcp_show_info(nlh, r);
1412 int tcp_show_netlink(struct filter *f, FILE *dump_fp)
1415 struct sockaddr_nl nladdr;
1417 struct nlmsghdr nlh;
1418 struct tcpdiagreq r;
1425 struct iovec iov[3];
1427 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TCPDIAG)) < 0)
1430 memset(&nladdr, 0, sizeof(nladdr));
1431 nladdr.nl_family = AF_NETLINK;
1433 req.nlh.nlmsg_len = sizeof(req);
1434 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
1435 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1436 req.nlh.nlmsg_pid = 0;
1437 req.nlh.nlmsg_seq = 123456;
1438 memset(&req.r, 0, sizeof(req.r));
1439 req.r.tcpdiag_family = AF_INET;
1440 req.r.tcpdiag_states = f->states;
1442 req.r.tcpdiag_ext |= (1<<(TCPDIAG_MEMINFO-1));
1444 req.r.tcpdiag_ext |= (1<<(TCPDIAG_INFO-1));
1445 #ifdef TCPDIAG_VEGASINFO
1446 req.r.tcpdiag_ext |= (1<<(TCPDIAG_VEGASINFO-1));
1450 iov[0] = (struct iovec){ &req, sizeof(req) };
1452 bclen = ssfilter_bytecompile(f->f, &bc);
1453 rta.rta_type = TCPDIAG_REQ_BYTECODE;
1454 rta.rta_len = RTA_LENGTH(bclen);
1455 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1456 iov[2] = (struct iovec){ bc, bclen };
1457 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1460 msg = (struct msghdr) {
1461 (void*)&nladdr, sizeof(nladdr),
1467 if (sendmsg(fd, &msg, 0) < 0)
1471 iov[0] = (struct iovec){ buf, sizeof(buf) };
1477 msg = (struct msghdr) {
1478 (void*)&nladdr, sizeof(nladdr),
1484 status = recvmsg(fd, &msg, 0);
1493 fprintf(stderr, "EOF on netlink\n");
1498 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1500 h = (struct nlmsghdr*)buf;
1501 while (NLMSG_OK(h, status)) {
1504 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1505 h->nlmsg_seq != 123456)
1508 if (h->nlmsg_type == NLMSG_DONE)
1510 if (h->nlmsg_type == NLMSG_ERROR) {
1511 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1512 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1513 fprintf(stderr, "ERROR truncated\n");
1515 errno = -err->error;
1516 perror("TCPDIAG answers");
1521 err = tcp_show_sock(h, NULL);
1527 h = NLMSG_NEXT(h, status);
1529 if (msg.msg_flags & MSG_TRUNC) {
1530 fprintf(stderr, "Message truncated\n");
1534 fprintf(stderr, "!!!Remnant of size %d\n", status);
1541 int tcp_show_netlink_file(struct filter *f)
1546 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1547 perror("fopen($TCPDIAG_FILE)");
1553 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1555 status = fread(buf, 1, sizeof(*h), fp);
1557 perror("Reading header from $TCPDIAG_FILE");
1560 if (status != sizeof(*h)) {
1561 perror("Unexpected EOF reading $TCPDIAG_FILE");
1565 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1568 perror("Reading $TCPDIAG_FILE");
1571 if (status + sizeof(*h) < h->nlmsg_len) {
1572 perror("Unexpected EOF reading $TCPDIAG_FILE");
1576 /* The only legal exit point */
1577 if (h->nlmsg_type == NLMSG_DONE)
1580 if (h->nlmsg_type == NLMSG_ERROR) {
1581 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1582 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1583 fprintf(stderr, "ERROR truncated\n");
1585 errno = -err->error;
1586 perror("TCPDIAG answered");
1591 err = tcp_show_sock(h, f);
1597 int tcp_show(struct filter *f)
1601 int bufsize = 64*1024;
1603 dg_proto = TCP_PROTO;
1605 if (getenv("TCPDIAG_FILE"))
1606 return tcp_show_netlink_file(f);
1608 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1609 && tcp_show_netlink(f, NULL) == 0)
1612 /* Sigh... We have to parse /proc/net/tcp... */
1614 /* Estimate amount of sockets and try to allocate
1615 * huge buffer to read all the table at one read.
1616 * Limit it by 16MB though. The assumption is: as soon as
1617 * kernel was able to hold information about N connections,
1618 * it is able to give us some memory for snapshot.
1621 int guess = slabstat.socks+slabstat.tcp_syns;
1622 if (f->states&(1<<SS_TIME_WAIT))
1623 guess += slabstat.tcp_tws;
1624 if (guess > (16*1024*1024)/128)
1625 guess = (16*1024*1024)/128;
1627 if (guess > bufsize)
1630 while (bufsize >= 64*1024) {
1631 if ((buf = malloc(bufsize)) != NULL)
1640 if (f->families & (1<<AF_INET)) {
1641 if ((fd = net_tcp_open()) < 0)
1643 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET))
1648 if ((f->families & (1<<AF_INET6)) &&
1649 (fd = net_tcp6_open()) >= 0) {
1650 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET6))
1660 int saved_errno = errno;
1665 errno = saved_errno;
1671 int dgram_show_line(char *line, struct filter *f, int family)
1674 char *loc, *rem, *data;
1679 if ((p = strchr(line, ':')) == NULL)
1683 if ((p = strchr(loc, ':')) == NULL)
1688 if ((p = strchr(rem, ':')) == NULL)
1694 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1696 if (!(f->states & (1<<state)))
1700 s.local.family = s.remote.family = family;
1701 if (family == AF_INET) {
1702 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1703 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1704 s.local.bytelen = s.remote.bytelen = 4;
1706 sscanf(loc, "%08x%08x%08x%08x:%x",
1712 sscanf(rem, "%08x%08x%08x%08x:%x",
1718 s.local.bytelen = s.remote.bytelen = 16;
1721 if (f->f && run_ssfilter(f->f, &s) == 0)
1725 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %d %d %llx %[^\n]\n",
1726 &s.state, &s.wq, &s.rq,
1728 &s.refcnt, &s.sk, opt);
1734 printf("%-*s ", netid_width, dg_proto);
1736 printf("%-*s ", state_width, sstate_name[s.state]);
1738 printf("%-6d %-6d ", s.rq, s.wq);
1740 formatted_print(&s.local, s.lport);
1741 formatted_print(&s.remote, s.rport);
1745 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1746 printf(" users:(%s)", ubuf);
1751 printf(" uid=%u", (unsigned)s.uid);
1752 printf(" ino=%u", (unsigned)s.ino);
1753 printf(" sk=%llx", s.sk);
1755 printf(" opt:\"%s\"", opt);
1763 int udp_show(struct filter *f)
1767 int bufsize = sizeof(buf);
1769 dg_proto = UDP_PROTO;
1771 if (f->families&(1<<AF_INET)) {
1772 if ((fd = net_udp_open()) < 0)
1774 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1779 if ((f->families&(1<<AF_INET6)) &&
1780 (fd = net_udp6_open()) >= 0) {
1781 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1789 int saved_errno = errno;
1792 errno = saved_errno;
1797 int raw_show(struct filter *f)
1801 int bufsize = sizeof(buf);
1803 dg_proto = RAW_PROTO;
1805 if (f->families&(1<<AF_INET)) {
1806 if ((fd = net_raw_open()) < 0)
1808 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1813 if ((f->families&(1<<AF_INET6)) &&
1814 (fd = net_raw6_open()) >= 0) {
1815 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1823 int saved_errno = errno;
1826 errno = saved_errno;
1834 struct unixstat *next;
1846 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
1847 SS_ESTABLISHED, SS_CLOSING };
1850 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
1852 void unix_list_free(struct unixstat *list)
1855 struct unixstat *s = list;
1863 void unix_list_print(struct unixstat *list, struct filter *f)
1868 for (s = list; s; s = s->next) {
1869 if (!(f->states & (1<<s->state)))
1871 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
1873 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
1879 for (p = list; p; p = p->next) {
1880 if (s->peer == p->ino)
1886 peer = p->name ? : "*";
1892 tst.local.family = AF_UNIX;
1893 tst.remote.family = AF_UNIX;
1894 memcpy(tst.local.data, &s->name, sizeof(s->name));
1895 if (strcmp(peer, "*") == 0)
1896 memset(tst.remote.data, 0, sizeof(peer));
1898 memcpy(tst.remote.data, &peer, sizeof(peer));
1899 if (run_ssfilter(f->f, &tst) == 0)
1904 printf("%-*s ", netid_width,
1905 s->type == SOCK_STREAM ? "u_str" : "u_dgr");
1907 printf("%-*s ", state_width, sstate_name[s->state]);
1908 printf("%-6d %-6d ", s->rq, s->wq);
1909 printf("%*s %-*d %*s %-*d",
1910 addr_width, s->name ? : "*", serv_width, s->ino,
1911 addr_width, peer, serv_width, s->peer);
1914 if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
1915 printf(" users:(%s)", ubuf);
1921 int unix_show(struct filter *f)
1928 struct unixstat *list = NULL;
1930 if ((fp = fdopen(net_unix_open(), "r")) == NULL)
1932 fgets(buf, sizeof(buf)-1, fp);
1934 if (memcmp(buf, "Peer", 4) == 0)
1938 while (fgets(buf, sizeof(buf)-1, fp)) {
1939 struct unixstat *u, **insp;
1942 if (!(u = malloc(sizeof(*u))))
1946 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
1947 &u->peer, &u->rq, &u->wq, &flags, &u->type,
1948 &u->state, &u->ino, name) < 8)
1951 if (flags&(1<<16)) {
1952 u->state = SS_LISTEN;
1954 u->state = unix_state_map[u->state-1];
1955 if (u->type == SOCK_DGRAM &&
1956 u->state == SS_CLOSE &&
1958 u->state = SS_ESTABLISHED;
1969 if (u->type < (*insp)->type ||
1970 (u->type == (*insp)->type &&
1971 u->ino < (*insp)->ino))
1973 insp = &(*insp)->next;
1979 if ((u->name = malloc(strlen(name)+1)) == NULL)
1981 strcpy(u->name, name);
1983 if (++cnt > MAX_UNIX_REMEMBER) {
1984 unix_list_print(list, f);
1985 unix_list_free(list);
1992 unix_list_print(list, f);
1993 unix_list_free(list);
2002 int packet_show(struct filter *f)
2013 unsigned long long sk;
2015 if (!(f->states & (1<<SS_CLOSE)))
2018 if ((fp = fdopen(net_packet_open(), "r")) == NULL)
2020 fgets(buf, sizeof(buf)-1, fp);
2022 while (fgets(buf, sizeof(buf)-1, fp)) {
2023 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2025 &type, &prot, &iface, &state,
2028 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2030 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2034 tst.local.family = AF_PACKET;
2035 tst.remote.family = AF_PACKET;
2038 tst.local.data[0] = prot;
2039 tst.remote.data[0] = 0;
2040 if (run_ssfilter(f->f, &tst) == 0)
2045 printf("%-*s ", netid_width,
2046 type == SOCK_RAW ? "p_raw" : "p_dgr");
2048 printf("%-*s ", state_width, "UNCONN");
2049 printf("%-6d %-6d ", rq, 0);
2051 printf("%*s:", addr_width, "*");
2054 printf("%*s:", addr_width,
2055 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2058 printf("%-*s ", serv_width, "*");
2060 printf("%-*s ", serv_width, xll_index_to_name(iface));
2063 addr_width, "", serv_width, "");
2067 if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2068 printf(" users:(%s)", ubuf);
2071 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2079 int netlink_show(struct filter *f)
2086 unsigned long long sk, cb;
2088 if (!(f->states & (1<<SS_CLOSE)))
2091 if ((fp = fdopen(net_netlink_open(), "r")) == NULL)
2093 fgets(buf, sizeof(buf)-1, fp);
2095 while (fgets(buf, sizeof(buf)-1, fp)) {
2096 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2098 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2102 tst.local.family = AF_NETLINK;
2103 tst.remote.family = AF_NETLINK;
2106 tst.local.data[0] = prot;
2107 tst.remote.data[0] = 0;
2108 if (run_ssfilter(f->f, &tst) == 0)
2113 printf("%-*s ", netid_width, "nl");
2115 printf("%-*s ", state_width, "UNCONN");
2116 printf("%-6d %-6d ", rq, wq);
2117 if (resolve_services && prot == 0)
2118 printf("%*s:", addr_width, "rtnl");
2119 else if (resolve_services && prot == 3)
2120 printf("%*s:", addr_width, "fw");
2121 else if (resolve_services && prot == 4)
2122 printf("%*s:", addr_width, "tcpdiag");
2124 printf("%*d:", addr_width, prot);
2126 printf("%-*s ", serv_width, "*");
2127 } else if (resolve_services) {
2131 printf("%-*s ", serv_width, "kernel");
2132 } else if (pid > 0) {
2135 sprintf(procname, "%s/%d/stat",
2136 getenv("PROC_ROOT") ? : "/proc", pid);
2137 if ((fp = fopen(procname, "r")) != NULL) {
2138 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2139 sprintf(procname+strlen(procname), "/%d", pid);
2140 printf("%-*s ", serv_width, procname);
2147 printf("%-*d ", serv_width, pid);
2149 printf("%-*d ", serv_width, pid);
2152 addr_width, "", serv_width, "");
2155 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2168 int get_snmp_int(char *proto, char *key, int *result)
2172 int protolen = strlen(proto);
2173 int keylen = strlen(key);
2177 if ((fp = fdopen(net_snmp_open(), "r")) == NULL)
2180 while (fgets(buf, sizeof(buf), fp) != NULL) {
2183 if (memcmp(buf, proto, protolen))
2185 while ((p = strchr(p, ' ')) != NULL) {
2188 if (memcmp(p, key, keylen) == 0 &&
2189 (p[keylen] == ' ' || p[keylen] == '\n'))
2192 if (fgets(buf, sizeof(buf), fp) == NULL)
2194 if (memcmp(buf, proto, protolen))
2197 while ((p = strchr(p, ' ')) != NULL) {
2200 sscanf(p, "%d", result);
2213 /* Get stats from sockstat */
2234 static void get_sockstat_line(char *line, struct sockstat *s)
2236 char id[256], rem[256];
2238 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2241 if (strcmp(id, "sockets:") == 0)
2242 sscanf(rem, "%*s%d", &s->socks);
2243 else if (strcmp(id, "UDP:") == 0)
2244 sscanf(rem, "%*s%d", &s->udp4);
2245 else if (strcmp(id, "UDP6:") == 0)
2246 sscanf(rem, "%*s%d", &s->udp6);
2247 else if (strcmp(id, "RAW:") == 0)
2248 sscanf(rem, "%*s%d", &s->raw4);
2249 else if (strcmp(id, "RAW6:") == 0)
2250 sscanf(rem, "%*s%d", &s->raw6);
2251 else if (strcmp(id, "TCP6:") == 0)
2252 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2253 else if (strcmp(id, "FRAG:") == 0)
2254 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2255 else if (strcmp(id, "FRAG6:") == 0)
2256 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2257 else if (strcmp(id, "TCP:") == 0)
2258 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2260 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2263 int get_sockstat(struct sockstat *s)
2268 memset(s, 0, sizeof(*s));
2270 if ((fp = fdopen(net_sockstat_open(), "r")) == NULL)
2272 while(fgets(buf, sizeof(buf), fp) != NULL)
2273 get_sockstat_line(buf, s);
2276 if ((fp = fdopen(net_sockstat6_open(), "r")) == NULL)
2278 while(fgets(buf, sizeof(buf), fp) != NULL)
2279 get_sockstat_line(buf, s);
2285 int print_summary(void)
2290 if (get_sockstat(&s) < 0)
2291 perror("ss: get_sockstat");
2292 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2293 perror("ss: get_snmpstat");
2295 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2297 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2298 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2300 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2303 s.tcp_tws, slabstat.tcp_tws,
2308 printf("Transport Total IP IPv6\n");
2309 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2310 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2311 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2312 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2313 printf("INET %-9d %-9d %-9d\n",
2314 s.raw4+s.udp4+s.tcp4_hashed+
2315 s.raw6+s.udp6+s.tcp6_hashed,
2316 s.raw4+s.udp4+s.tcp4_hashed,
2317 s.raw6+s.udp6+s.tcp6_hashed);
2318 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2326 static void usage(void) __attribute__((noreturn));
2328 static void usage(void)
2331 "Usage: ss [ OPTIONS ]\n"
2332 " ss [ OPTIONS ] [ FILTER ]\n"
2333 "where OPTIONS := { -h[elp] | -V[ersion] | -n[umeric] | -r[esolve] |\n"
2334 " -a[ll] -l[istening] -o[ptions] -e[xtended] -p[rocesses]\n"
2335 " -A QUERY -i[nfo] } -s[ummary]\n"
2336 " -f[amily] { inet | inet6 | link | unix } }\n"
2337 " QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2338 " FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2344 int scan_state(const char *state)
2347 if (strcasecmp(state, "close") == 0 ||
2348 strcasecmp(state, "closed") == 0)
2349 return (1<<SS_CLOSE);
2350 if (strcasecmp(state, "syn-rcv") == 0)
2351 return (1<<SS_SYN_RECV);
2352 if (matches(state, "established") == 0)
2353 return (1<<SS_ESTABLISHED);
2354 if (strcasecmp(state, "all") == 0)
2356 if (strcasecmp(state, "connected") == 0)
2357 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2358 if (matches(state, "synchronized") == 0)
2359 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2360 if (strcasecmp(state, "bucket") == 0)
2361 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2362 if (strcasecmp(state, "big") == 0)
2363 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2364 for (i=0; i<SS_MAX; i++) {
2365 if (matches(state, sstate_namel[i]) == 0)
2371 int main(int argc, char *argv[])
2377 const char *dump_tcpdiag = NULL;
2378 FILE *filter_fp = NULL;
2381 memset(¤t_filter, 0, sizeof(current_filter));
2383 current_filter.states = default_filter.states;
2385 while ((ch = getopt(argc, argv, "h?aletuwxnro460spf:miA:D:F:vV")) != EOF) {
2388 resolve_services = 0;
2410 current_filter.dbs |= (1<<TCP_DB);
2414 current_filter.dbs |= (1<<UDP_DB);
2418 current_filter.dbs |= (1<<RAW_DB);
2422 current_filter.dbs |= UNIX_DBM;
2426 current_filter.states = SS_ALL;
2429 current_filter.states = (1<<SS_LISTEN);
2432 preferred_family = AF_INET;
2435 preferred_family = AF_INET6;
2438 preferred_family = AF_PACKET;
2441 if (strcmp(optarg, "inet") == 0)
2442 preferred_family = AF_INET;
2443 else if (strcmp(optarg, "inet6") == 0)
2444 preferred_family = AF_INET6;
2445 else if (strcmp(optarg, "link") == 0)
2446 preferred_family = AF_PACKET;
2447 else if (strcmp(optarg, "unix") == 0)
2448 preferred_family = AF_UNIX;
2449 else if (strcmp(optarg, "netlink") == 0)
2450 preferred_family = AF_NETLINK;
2451 else if (strcmp(optarg, "help") == 0)
2454 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2462 current_filter.dbs = 0;
2468 if ((p1 = strchr(p, ',')) != NULL)
2470 if (strcmp(p, "all") == 0) {
2471 current_filter.dbs = ALL_DB;
2472 } else if (strcmp(p, "inet") == 0) {
2473 current_filter.dbs |= (1<<TCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2474 } else if (strcmp(p, "udp") == 0) {
2475 current_filter.dbs |= (1<<UDP_DB);
2476 } else if (strcmp(p, "tcp") == 0) {
2477 current_filter.dbs |= (1<<TCP_DB);
2478 } else if (strcmp(p, "raw") == 0) {
2479 current_filter.dbs |= (1<<RAW_DB);
2480 } else if (strcmp(p, "unix") == 0) {
2481 current_filter.dbs |= UNIX_DBM;
2482 } else if (matches(p, "unix_stream") == 0 ||
2483 strcmp(p, "u_str") == 0) {
2484 current_filter.dbs |= (1<<UNIX_ST_DB);
2485 } else if (matches(p, "unix_dgram") == 0 ||
2486 strcmp(p, "u_dgr") == 0) {
2487 current_filter.dbs |= (1<<UNIX_DG_DB);
2488 } else if (strcmp(p, "packet") == 0) {
2489 current_filter.dbs |= PACKET_DBM;
2490 } else if (strcmp(p, "packet_raw") == 0 ||
2491 strcmp(p, "p_raw") == 0) {
2492 current_filter.dbs |= (1<<PACKET_R_DB);
2493 } else if (strcmp(p, "packet_dgram") == 0 ||
2494 strcmp(p, "p_dgr") == 0) {
2495 current_filter.dbs |= (1<<PACKET_DG_DB);
2496 } else if (strcmp(p, "netlink") == 0) {
2497 current_filter.dbs |= (1<<NETLINK_DB);
2499 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2510 dump_tcpdiag = optarg;
2514 fprintf(stderr, "More than one filter file\n");
2517 if (optarg[0] == '-')
2520 filter_fp = fopen(optarg, "r");
2522 perror("fopen filter file");
2528 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
2540 get_slabstat(&slabstat);
2544 if (do_default && argc == 0)
2549 current_filter.dbs = default_filter.dbs;
2551 if (preferred_family == AF_UNSPEC) {
2552 if (!(current_filter.dbs&~UNIX_DBM))
2553 preferred_family = AF_UNIX;
2554 else if (!(current_filter.dbs&~PACKET_DBM))
2555 preferred_family = AF_PACKET;
2556 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
2557 preferred_family = AF_NETLINK;
2560 if (preferred_family != AF_UNSPEC) {
2562 if (preferred_family == AF_INET ||
2563 preferred_family == AF_INET6) {
2566 mask2 = (1<<UDP_DB)|(1<<RAW_DB);
2567 } else if (preferred_family == AF_PACKET) {
2569 } else if (preferred_family == AF_UNIX) {
2571 } else if (preferred_family == AF_NETLINK) {
2572 mask2 = (1<<NETLINK_DB);
2578 current_filter.dbs = mask2;
2580 current_filter.dbs &= mask2;
2581 current_filter.families = (1<<preferred_family);
2584 current_filter.families = ~0;
2586 current_filter.families = default_filter.families;
2588 if (current_filter.dbs == 0) {
2589 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
2592 if (current_filter.families == 0) {
2593 fprintf(stderr, "ss: no families to show with such filter.\n");
2597 if (resolve_services && resolve_hosts &&
2598 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB))))
2599 init_service_resolver();
2601 /* Now parse filter... */
2602 if (argc == 0 && filter_fp) {
2603 if (ssfilter_parse(¤t_filter.f, 0, NULL, filter_fp))
2608 if (strcmp(*argv, "state") == 0) {
2611 current_filter.states = 0;
2612 current_filter.states |= scan_state(*argv);
2614 } else if (strcmp(*argv, "exclude") == 0 ||
2615 strcmp(*argv, "excl") == 0) {
2618 current_filter.states = SS_ALL;
2619 current_filter.states &= ~scan_state(*argv);
2622 if (ssfilter_parse(¤t_filter.f, argc, argv, filter_fp))
2629 if (current_filter.states == 0) {
2630 fprintf(stderr, "ss: no socket states to show with such filter.\n");
2635 FILE *dump_fp = stdout;
2636 if (!(current_filter.dbs & (1<<TCP_DB))) {
2637 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
2640 if (dump_tcpdiag[0] != '-') {
2641 dump_fp = fopen(dump_tcpdiag, "w");
2642 if (!dump_tcpdiag) {
2643 perror("fopen dump file");
2647 tcp_show_netlink(¤t_filter, dump_fp);
2653 if (current_filter.dbs&(current_filter.dbs-1))
2657 if (current_filter.states&(current_filter.states-1))
2661 if (isatty(STDOUT_FILENO)) {
2664 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
2666 screen_width = w.ws_col;
2670 addrp_width = screen_width;
2671 addrp_width -= netid_width+1;
2672 addrp_width -= state_width+1;
2675 if (addrp_width&1) {
2678 else if (state_width)
2685 serv_width = resolve_services ? 7 : 5;
2687 if (addrp_width < 15+serv_width+1)
2688 addrp_width = 15+serv_width+1;
2690 addr_width = addrp_width - serv_width - 1;
2693 printf("%-*s ", netid_width, "Netid");
2695 printf("%-*s ", state_width, "State");
2696 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
2698 printf("%*s:%-*s %*s:%-*s\n",
2699 addr_width, "Local Address", serv_width, "Port",
2700 addr_width, "Peer Address", serv_width, "Port");
2702 //printf("%08x %08x %08x\n", current_filter.dbs, current_filter.states, current_filter.families);
2705 if (current_filter.dbs & (1<<NETLINK_DB))
2706 netlink_show(¤t_filter);
2707 if (current_filter.dbs & PACKET_DBM)
2708 packet_show(¤t_filter);
2709 if (current_filter.dbs & UNIX_DBM)
2710 unix_show(¤t_filter);
2711 if (current_filter.dbs & (1<<RAW_DB))
2712 raw_show(¤t_filter);
2713 if (current_filter.dbs & (1<<UDP_DB))
2714 udp_show(¤t_filter);
2715 if (current_filter.dbs & (1<<TCP_DB))
2716 tcp_show(¤t_filter);