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 <asm/byteorder.h>
37 #include <linux/tcp.h>
38 #include <linux/tcp_diag.h>
40 int resolve_hosts = 0;
41 int resolve_services = 1;
42 int preferred_family = AF_UNSPEC;
56 static const char *TCP_PROTO = "tcp";
57 static const char *UDP_PROTO = "udp";
58 static const char *RAW_PROTO = "raw";
59 static const char *dg_proto = NULL;
74 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
75 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB))
76 #define ALL_DB ((1<<MAX_DB)-1)
94 #define SS_ALL ((1<<SS_MAX)-1)
106 struct filter default_filter = {
108 states: SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)),
109 families: (1<<AF_INET)|(1<<AF_INET6),
112 struct filter current_filter;
114 int generic_proc_open(char *env, char *name)
117 char *p = getenv(env);
119 p = getenv("PROC_ROOT") ? : "/proc";
120 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
123 return open(store, O_RDONLY);
126 int net_tcp_open(void)
128 return generic_proc_open("PROC_NET_TCP", "net/tcp");
131 int net_tcp6_open(void)
133 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
136 int net_udp_open(void)
138 return generic_proc_open("PROC_NET_UDP", "net/udp");
141 int net_udp6_open(void)
143 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
146 int net_raw_open(void)
148 return generic_proc_open("PROC_NET_RAW", "net/raw");
151 int net_raw6_open(void)
153 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
156 int net_unix_open(void)
158 return generic_proc_open("PROC_NET_UNIX", "net/unix");
161 int net_packet_open(void)
163 return generic_proc_open("PROC_NET_PACKET", "net/packet");
166 int net_netlink_open(void)
168 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
171 int slabinfo_open(void)
173 return generic_proc_open("PROC_SLABINFO", "slabinfo");
176 int net_sockstat_open(void)
178 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
181 int net_sockstat6_open(void)
183 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
186 int net_snmp_open(void)
188 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
191 int net_netstat_open(void)
193 return generic_proc_open("PROC_NET_NETSTAT", "net/netstat");
196 int ephemeral_ports_open(void)
198 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
201 int find_users(int ino, char *buf, int buflen)
215 sprintf(pattern, "socket:[%d]", ino);
216 pattern_len = strlen(pattern);
218 strncpy(name, getenv("PROC_ROOT") ? : "/proc/", sizeof(name)/2);
219 name[sizeof(name)/2] = 0;
220 if (strlen(name) == 0 ||
221 name[strlen(name)-1] != '/')
223 nameoff = strlen(name);
224 if ((dir = opendir(name)) == NULL)
227 while ((d = readdir(dir)) != NULL) {
235 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
238 sprintf(name+nameoff, "%d/fd/", pid);
240 if ((dir1 = opendir(name)) == NULL)
245 while ((d1 = readdir(dir1)) != NULL) {
249 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
252 sprintf(name+pos, "%d", fd);
253 n = readlink(name, lnk, sizeof(lnk)-1);
254 if (n != pattern_len ||
255 memcmp(lnk, pattern, n))
258 if (ptr-buf >= buflen-1)
261 if (process[0] == 0) {
264 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
265 getenv("PROC_ROOT") ? : "/proc", pid);
266 if ((fp = fopen(tmp, "r")) != NULL) {
267 fscanf(fp, "%*d (%[^)])", process);
272 snprintf(ptr, buflen-(ptr-buf), "(\"%s\",%d,%d),", process, pid, fd);
285 /* Get stats from slab */
296 struct slabstat slabstat;
298 static const char *slabstat_ids[] =
307 int get_slabstat(struct slabstat *s)
313 memset(s, 0, sizeof(*s));
315 if ((fp = fdopen(slabinfo_open(), "r")) == NULL)
318 cnt = sizeof(*s)/sizeof(int);
320 fgets(buf, sizeof(buf), fp);
321 while(fgets(buf, sizeof(buf), fp) != NULL) {
323 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
324 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
325 sscanf(buf, "%*s%d", ((int *)s) + i);
338 static const char *sstate_name[] = {
340 [TCP_ESTABLISHED] = "ESTAB",
341 [TCP_SYN_SENT] = "SYN-SENT",
342 [TCP_SYN_RECV] = "SYN-RECV",
343 [TCP_FIN_WAIT1] = "FIN-WAIT-1",
344 [TCP_FIN_WAIT2] = "FIN-WAIT-2",
345 [TCP_TIME_WAIT] = "TIME-WAIT",
346 [TCP_CLOSE] = "UNCONN",
347 [TCP_CLOSE_WAIT] = "CLOSE-WAIT",
348 [TCP_LAST_ACK] = "LAST-ACK",
349 [TCP_LISTEN] = "LISTEN",
350 [TCP_CLOSING] = "CLOSING",
353 static const char *sstate_namel[] = {
355 [TCP_ESTABLISHED] = "established",
356 [TCP_SYN_SENT] = "syn-sent",
357 [TCP_SYN_RECV] = "syn-recv",
358 [TCP_FIN_WAIT1] = "fin-wait-1",
359 [TCP_FIN_WAIT2] = "fin-wait-2",
360 [TCP_TIME_WAIT] = "time-wait",
361 [TCP_CLOSE] = "unconnected",
362 [TCP_CLOSE_WAIT] = "close-wait",
363 [TCP_LAST_ACK] = "last-ack",
364 [TCP_LISTEN] = "listening",
365 [TCP_CLOSING] = "closing",
383 unsigned long long sk;
384 int rto, ato, qack, cwnd, ssthresh;
387 static const char *tmr_name[] = {
396 const char *print_ms_timer(int timeout)
399 int secs, msecs, minutes;
405 msecs = timeout%1000;
409 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
416 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
419 sprintf(buf+strlen(buf), "%03dms", msecs);
423 const char *print_hz_timer(int timeout)
426 return print_ms_timer(((timeout*1000) + hz-1)/hz);
437 struct scache *rlist;
439 void init_service_resolver(void)
442 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
444 fgets(buf, sizeof(buf), fp);
445 while (fgets(buf, sizeof(buf), fp) != NULL) {
446 unsigned int progn, port;
447 char proto[128], prog[128];
448 if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
449 &port, prog+4) == 4) {
450 struct scache *c = malloc(sizeof(*c));
453 memcpy(prog, "rpc.", 4);
454 c->name = strdup(prog);
455 if (strcmp(proto, TCP_PROTO) == 0)
456 c->proto = TCP_PROTO;
457 else if (strcmp(proto, UDP_PROTO) == 0)
458 c->proto = UDP_PROTO;
469 static int ip_local_port_min, ip_local_port_max;
471 /* Even do not try default linux ephemeral port ranges:
472 * default /etc/services contains so much of useless crap
473 * wouldbe "allocated" to this area that resolution
474 * is really harmful. I shrug each time when seeing
475 * "socks" or "cfinger" in dumps.
477 static int is_ephemeral(int port)
479 if (!ip_local_port_min) {
480 FILE *f = fdopen(ephemeral_ports_open(), "r");
483 &ip_local_port_min, &ip_local_port_max);
486 ip_local_port_min = 1024;
487 ip_local_port_max = 4999;
491 return (port >= ip_local_port_min && port<= ip_local_port_max);
495 const char *__resolve_service(int port)
499 for (c = rlist; c; c = c->next) {
500 if (c->port == port && c->proto == dg_proto)
504 if (!is_ephemeral(port)) {
511 se = getservbyport(htons(port), dg_proto);
520 const char *resolve_service(int port)
522 static char buf[128];
523 static struct scache cache[256];
531 if (resolve_services) {
532 if (dg_proto == RAW_PROTO) {
533 return inet_proto_n2a(port, buf, sizeof(buf));
537 int hash = (port^(((unsigned long)dg_proto)>>2))&255;
539 for (c = &cache[hash]; c; c = c->next) {
540 if (c->port == port &&
541 c->proto == dg_proto) {
548 if ((res = __resolve_service(port)) != NULL) {
549 if ((c = malloc(sizeof(*c))) == NULL)
560 c->name = strdup(res);
561 c->next = cache[hash].next;
562 cache[hash].next = c;
570 sprintf(buf, "%u", port);
574 void formatted_print(const inet_prefix *a, int port)
577 const char *ap = buf;
580 est_len = addr_width;
582 if (a->family == AF_INET) {
583 if (a->data[0] == 0) {
587 ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
590 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
591 est_len = strlen(ap);
592 if (est_len <= addr_width)
593 est_len = addr_width;
595 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
597 printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
604 struct aafilter *next;
607 int inet2_addr_match(const inet_prefix *a, const inet_prefix *p, int plen)
609 if (!inet_addr_match(a, p, plen))
612 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
613 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
615 if (p->family == AF_INET && a->family == AF_INET6) {
616 if (a->data[0] == 0 && a->data[1] == 0 &&
617 a->data[2] == htonl(0xffff)) {
618 inet_prefix tmp = *a;
619 tmp.data[0] = a->data[3];
620 return inet_addr_match(&tmp, p, plen);
626 int unix_match(const inet_prefix *a, const inet_prefix *p)
628 char *addr, *pattern;
629 memcpy(&addr, a->data, sizeof(addr));
630 memcpy(&pattern, p->data, sizeof(pattern));
635 return !fnmatch(pattern, addr, 0);
638 int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
643 static int low, high=65535;
645 if (s->local.family == AF_UNIX) {
647 memcpy(&p, s->local.data, sizeof(p));
648 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
649 strspn(p+1, "0123456789abcdef") == 5);
651 if (s->local.family == AF_PACKET)
652 return s->lport == 0 && s->local.data == 0;
653 if (s->local.family == AF_NETLINK)
657 FILE *fp = fdopen(ephemeral_ports_open(), "r");
659 fscanf(fp, "%d%d", &low, &high);
663 return s->lport >= low && s->lport <= high;
667 struct aafilter *a = (void*)f->pred;
668 if (a->addr.family == AF_UNIX)
669 return unix_match(&s->remote, &a->addr);
670 if (a->port != -1 && a->port != s->rport)
672 if (a->addr.bitlen) {
674 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
676 } while ((a = a->next) != NULL);
683 struct aafilter *a = (void*)f->pred;
684 if (a->addr.family == AF_UNIX)
685 return unix_match(&s->local, &a->addr);
686 if (a->port != -1 && a->port != s->lport)
688 if (a->addr.bitlen) {
690 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
692 } while ((a = a->next) != NULL);
699 struct aafilter *a = (void*)f->pred;
700 return s->rport >= a->port;
704 struct aafilter *a = (void*)f->pred;
705 return s->rport <= a->port;
709 struct aafilter *a = (void*)f->pred;
710 return s->lport >= a->port;
714 struct aafilter *a = (void*)f->pred;
715 return s->lport <= a->port;
718 /* Yup. It is recursion. Sorry. */
720 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
722 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
724 return !run_ssfilter(f->pred, s);
730 /* Relocate external jumps by reloc. */
731 void ssfilter_patch(char *a, int len, int reloc)
734 struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op*)a;
744 int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
749 if (!(*bytecode=malloc(4))) abort();
750 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_AUTO, 4, 8 };
756 struct aafilter *a = (void*)f->pred;
759 int code = (f->type == SSF_DCOND ? TCPDIAG_BC_D_COND : TCPDIAG_BC_S_COND);
762 for (b=a; b; b=b->next) {
763 len += 4 + sizeof(struct tcpdiag_hostcond);
764 if (a->addr.family == AF_INET6)
771 if (!(ptr = malloc(len))) abort();
773 for (b=a; b; b=b->next) {
774 struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op *)ptr;
775 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
776 int oplen = alen + 4 + sizeof(struct tcpdiag_hostcond);
777 struct tcpdiag_hostcond *cond = (struct tcpdiag_hostcond*)(ptr+4);
779 *op = (struct tcpdiag_bc_op){ code, oplen, oplen+4 };
780 cond->family = a->addr.family;
781 cond->port = a->port;
782 cond->prefix_len = a->addr.bitlen;
783 memcpy(cond->addr, a->addr.data, alen);
786 op = (struct tcpdiag_bc_op *)ptr;
787 *op = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, len - (ptr-*bytecode)};
791 return ptr - *bytecode;
795 struct aafilter *x = (void*)f->pred;
796 if (!(*bytecode=malloc(8))) abort();
797 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_D_GE, 8, 12 };
798 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
803 struct aafilter *x = (void*)f->pred;
804 if (!(*bytecode=malloc(8))) abort();
805 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_D_LE, 8, 12 };
806 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
811 struct aafilter *x = (void*)f->pred;
812 if (!(*bytecode=malloc(8))) abort();
813 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_S_GE, 8, 12 };
814 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
819 struct aafilter *x = (void*)f->pred;
820 if (!(*bytecode=malloc(8))) abort();
821 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_S_LE, 8, 12 };
822 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
828 char *a1, *a2, *a, l1, l2;
829 l1 = ssfilter_bytecompile(f->pred, &a1);
830 l2 = ssfilter_bytecompile(f->post, &a2);
831 if (!(a = malloc(l1+l2))) abort();
833 memcpy(a+l1, a2, l2);
835 ssfilter_patch(a, l1, l2);
841 char *a1, *a2, *a, l1, l2;
842 l1 = ssfilter_bytecompile(f->pred, &a1);
843 l2 = ssfilter_bytecompile(f->post, &a2);
844 if (!(a = malloc(l1+l2+4))) abort();
846 memcpy(a+l1+4, a2, l2);
848 *(struct tcpdiag_bc_op*)(a+l1) = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, l2+4 };
855 l1 = ssfilter_bytecompile(f->pred, &a1);
856 if (!(a = malloc(l1+4))) abort();
859 *(struct tcpdiag_bc_op*)(a+l1) = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, 8 };
868 int remember_he(struct aafilter *a, struct hostent *he)
870 char **ptr = he->h_addr_list;
874 if (he->h_addrtype == AF_INET)
876 else if (he->h_addrtype == AF_INET6)
882 struct aafilter *b = a;
883 if (a->addr.bitlen) {
884 if ((b = malloc(sizeof(*b))) == NULL)
890 memcpy(b->addr.data, *ptr, len);
891 b->addr.bytelen = len;
892 b->addr.bitlen = len*8;
893 b->addr.family = he->h_addrtype;
900 int get_dns_host(struct aafilter *a, char *addr, int fam)
911 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
913 cnt = remember_he(a, he);
914 if (fam == AF_UNSPEC) {
915 he = gethostbyname2(addr, AF_INET6);
917 cnt += remember_he(a, he);
926 struct rtnl_handle rth;
933 const char *xll_index_to_name(int index)
937 return ll_index_to_name(index);
940 int xll_name_to_index(char *dev)
944 return ll_name_to_index(dev);
947 void *parse_hostcond(char *addr)
951 struct aafilter *res;
952 int fam = preferred_family;
954 memset(&a, 0, sizeof(a));
957 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
959 a.addr.family = AF_UNIX;
960 if (strncmp(addr, "unix:", 5) == 0)
963 a.addr.bitlen = 8*strlen(p);
964 memcpy(a.addr.data, &p, sizeof(p));
968 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
969 a.addr.family = AF_PACKET;
971 if (strncmp(addr, "link:", 5) == 0)
973 port = strchr(addr, ':');
976 if (port[1] && strcmp(port+1, "*")) {
977 if (get_integer(&a.port, port+1, 0)) {
978 if ((a.port = xll_name_to_index(port+1)) <= 0)
983 if (addr[0] && strcmp(addr, "*")) {
986 if (ll_proto_a2n(&tmp, addr))
988 a.addr.data[0] = ntohs(tmp);
993 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
994 a.addr.family = AF_NETLINK;
996 if (strncmp(addr, "netlink:", 8) == 0)
998 port = strchr(addr, ':');
1001 if (port[1] && strcmp(port+1, "*")) {
1002 if (get_integer(&a.port, port+1, 0)) {
1003 if (strcmp(port+1, "kernel") == 0)
1010 if (addr[0] && strcmp(addr, "*")) {
1012 if (get_u32(a.addr.data, addr, 0)) {
1013 if (strcmp(addr, "rtnl") == 0)
1015 else if (strcmp(addr, "fw") == 0)
1017 else if (strcmp(addr, "tcpdiag") == 0)
1026 if (strncmp(addr, "inet:", 5) == 0) {
1029 } else if (strncmp(addr, "inet6:", 6) == 0) {
1034 /* URL-like literal [] */
1035 if (addr[0] == '[') {
1037 if ((port = strchr(addr, ']')) == NULL)
1040 } else if (addr[0] == '*') {
1043 port = strrchr(strchr(addr, '/') ? : addr, ':');
1045 if (port && *port) {
1049 if (*port && *port != '*') {
1050 if (get_integer(&a.port, port, 0)) {
1051 struct servent *se1 = NULL;
1052 struct servent *se2 = NULL;
1053 if (current_filter.dbs&(1<<UDP_DB))
1054 se1 = getservbyname(port, UDP_PROTO);
1055 if (current_filter.dbs&(1<<TCP_DB))
1056 se2 = getservbyname(port, TCP_PROTO);
1057 if (se1 && se2 && se1->s_port != se2->s_port) {
1058 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1064 a.port = ntohs(se1->s_port);
1067 for (s = rlist; s; s = s->next) {
1068 if ((s->proto == UDP_PROTO &&
1069 (current_filter.dbs&(1<<UDP_DB))) ||
1070 (s->proto == TCP_PROTO &&
1071 (current_filter.dbs&(1<<TCP_DB)))) {
1072 if (s->name && strcmp(s->name, port) == 0) {
1073 if (a.port > 0 && a.port != s->port) {
1074 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1082 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1089 if (addr && *addr && *addr != '*') {
1090 if (get_prefix_1(&a.addr, addr, fam)) {
1091 if (get_dns_host(&a, addr, fam)) {
1092 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1099 res = malloc(sizeof(*res));
1101 memcpy(res, &a, sizeof(a));
1105 int tcp_show_line(char *line, struct filter *f, int family)
1108 char *loc, *rem, *data;
1113 if ((p = strchr(line, ':')) == NULL)
1117 if ((p = strchr(loc, ':')) == NULL)
1122 if ((p = strchr(rem, ':')) == NULL)
1128 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1130 if (!(f->states & (1<<state)))
1134 s.local.family = s.remote.family = family;
1135 if (family == AF_INET) {
1136 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1137 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1138 s.local.bytelen = s.remote.bytelen = 4;
1140 sscanf(loc, "%08x%08x%08x%08x:%x",
1146 sscanf(rem, "%08x%08x%08x%08x:%x",
1152 s.local.bytelen = s.remote.bytelen = 16;
1155 if (f->f && run_ssfilter(f->f, &s) == 0)
1159 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %d %d %llx %d %d %d %d %d %[^\n]\n",
1160 &s.state, &s.wq, &s.rq,
1161 &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1162 &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1163 &s.cwnd, &s.ssthresh, opt);
1176 printf("%-*s ", netid_width, "tcp");
1178 printf("%-*s ", state_width, sstate_name[s.state]);
1180 printf("%-6d %-6d ", s.rq, s.wq);
1182 formatted_print(&s.local, s.lport);
1183 formatted_print(&s.remote, s.rport);
1189 printf(" timer:(%s,%s,%d)",
1191 print_hz_timer(s.timeout),
1192 s.timer != 1 ? s.probes : s.retrs);
1196 if (s.rto && s.rto != 3*get_hz())
1197 printf(" rto:%g", (double)s.rto/get_hz());
1199 printf(" ato:%g", (double)s.ato/get_hz());
1201 printf(" cwnd:%d", s.cwnd);
1202 if (s.ssthresh != -1)
1203 printf(" ssthresh:%d", s.ssthresh);
1205 printf(" qack:%d", s.qack/2);
1211 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1212 printf(" users:(%s)", ubuf);
1216 printf(" uid:%u", (unsigned)s.uid);
1217 printf(" ino:%u", (unsigned)s.ino);
1218 printf(" sk:%llx", s.sk);
1220 printf(" opt:\"%s\"", opt);
1227 int generic_record_read(int fd, char *buf, int bufsize,
1228 int (*worker)(char*, struct filter *, int),
1229 struct filter *f, int fam)
1236 /* Load the first chunk and calculate record length from it. */
1237 n = read(fd, buf, bufsize);
1240 /* I _know_ that this is wrong, do not remind. :-)
1241 * But this works nowadays. */
1244 p = memchr(buf, '\n', n);
1245 if (p == NULL || (p-buf) >= n)
1246 goto outwrongformat;
1247 recsize = (p-buf)+1;
1251 while ((p+recsize) - buf <= n) {
1252 if (p[recsize-1] != '\n')
1253 goto outwrongformat;
1255 if (worker(p, f, fam) < 0)
1260 int remains = (buf+bufsize) - p;
1261 memcpy(buf, p, remains);
1263 n = read(fd, p, (buf+bufsize) - p);
1266 if (n < (buf+bufsize) - p) {
1270 goto outwrongformat;
1278 goto outwrongformat;
1291 void tcp_show_info(struct nlmsghdr *nlh, struct tcpdiagmsg *r)
1293 struct rtattr * tb[TCPDIAG_MAX+1];
1295 memset(tb, 0, sizeof(tb));
1296 parse_rtattr(tb, TCPDIAG_MAX, (struct rtattr*)(r+1),
1297 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1299 if (tb[TCPDIAG_MEMINFO]) {
1300 const struct tcpdiag_meminfo *minfo
1301 = RTA_DATA(tb[TCPDIAG_MEMINFO]);
1302 printf(" mem:(r%u,w%u,f%u,t%u)",
1303 minfo->tcpdiag_rmem,
1304 minfo->tcpdiag_wmem,
1305 minfo->tcpdiag_fmem,
1306 minfo->tcpdiag_tmem);
1309 if (tb[TCPDIAG_INFO]) {
1310 struct tcp_info *info;
1311 int len = RTA_PAYLOAD(tb[TCPDIAG_INFO]);
1313 /* workaround for older kernels with less fields */
1314 if (len < sizeof(*info)) {
1315 info = alloca(sizeof(*info));
1316 memset(info, 0, sizeof(*info));
1317 memcpy(info, RTA_DATA(tb[TCPDIAG_INFO]), len);
1319 info = RTA_DATA(tb[TCPDIAG_INFO]);
1321 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1323 if (info->tcpi_options & TCPI_OPT_SACK)
1325 if (info->tcpi_options & TCPI_OPT_WSCALE)
1326 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1327 info->tcpi_rcv_wscale);
1328 if (info->tcpi_options & TCPI_OPT_ECN)
1330 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1331 printf(" rto:%g", (double)info->tcpi_rto/1000);
1333 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1334 (double)info->tcpi_rttvar/1000);
1336 printf(" ato:%g", (double)info->tcpi_ato/1000);
1337 if (info->tcpi_snd_cwnd != 2)
1338 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1339 if (info->tcpi_snd_ssthresh < 0xFFFF)
1340 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1342 #if LINUX_VERSION_CODE >= 0x20607
1343 if (info->tcpi_rcv_rtt)
1344 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1345 if (info->tcpi_rcv_space)
1346 printf(" rcv_space:%d", info->tcpi_rcv_space);
1348 if (tb[TCPDIAG_VEGASINFO]) {
1349 const struct tcpvegas_info *vinfo
1350 = RTA_DATA(tb[TCPDIAG_VEGASINFO]);
1352 if (vinfo->tcpv_enabled)
1355 if (vinfo->tcpv_rtt &&
1356 vinfo->tcpv_rtt != 0x7fffffff &&
1357 info->tcpi_snd_mss &&
1358 info->tcpi_snd_cwnd) {
1360 (double) info->tcpi_snd_cwnd *
1361 (double) info->tcpi_snd_mss *
1362 8000000. / (double) vinfo->tcpv_rtt);
1369 int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
1371 struct tcpdiagmsg *r = NLMSG_DATA(nlh);
1374 s.state = r->tcpdiag_state;
1375 s.local.family = s.remote.family = r->tcpdiag_family;
1376 s.lport = ntohs(r->id.tcpdiag_sport);
1377 s.rport = ntohs(r->id.tcpdiag_dport);
1378 if (s.local.family == AF_INET) {
1379 s.local.bytelen = s.remote.bytelen = 4;
1381 s.local.bytelen = s.remote.bytelen = 16;
1383 memcpy(s.local.data, r->id.tcpdiag_src, s.local.bytelen);
1384 memcpy(s.remote.data, r->id.tcpdiag_dst, s.local.bytelen);
1386 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1390 printf("%-*s ", netid_width, "tcp");
1392 printf("%-*s ", state_width, sstate_name[s.state]);
1394 printf("%-6d %-6d ", r->tcpdiag_rqueue, r->tcpdiag_wqueue);
1396 formatted_print(&s.local, s.lport);
1397 formatted_print(&s.remote, s.rport);
1400 if (r->tcpdiag_timer) {
1401 if (r->tcpdiag_timer > 4)
1402 r->tcpdiag_timer = 5;
1403 printf(" timer:(%s,%s,%d)",
1404 tmr_name[r->tcpdiag_timer],
1405 print_ms_timer(r->tcpdiag_expires),
1406 r->tcpdiag_retrans);
1411 if (find_users(r->tcpdiag_inode, ubuf, sizeof(ubuf)) > 0)
1412 printf(" users:(%s)", ubuf);
1416 printf(" uid:%u", (unsigned)r->tcpdiag_uid);
1417 printf(" ino:%u", (unsigned)r->tcpdiag_inode);
1418 printf(" sk:%08x", r->id.tcpdiag_cookie[0]);
1419 if (r->id.tcpdiag_cookie[1] != 0)
1420 printf("%08x", r->id.tcpdiag_cookie[1]);
1422 if (show_mem || show_tcpinfo) {
1424 tcp_show_info(nlh, r);
1433 int tcp_show_netlink(struct filter *f, FILE *dump_fp)
1436 struct sockaddr_nl nladdr;
1438 struct nlmsghdr nlh;
1439 struct tcpdiagreq r;
1446 struct iovec iov[3];
1448 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TCPDIAG)) < 0)
1451 memset(&nladdr, 0, sizeof(nladdr));
1452 nladdr.nl_family = AF_NETLINK;
1454 req.nlh.nlmsg_len = sizeof(req);
1455 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
1456 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1457 req.nlh.nlmsg_pid = 0;
1458 req.nlh.nlmsg_seq = 123456;
1459 memset(&req.r, 0, sizeof(req.r));
1460 req.r.tcpdiag_family = AF_INET;
1461 req.r.tcpdiag_states = f->states;
1463 req.r.tcpdiag_ext |= (1<<(TCPDIAG_MEMINFO-1));
1465 req.r.tcpdiag_ext |= (1<<(TCPDIAG_INFO-1));
1466 #ifdef TCPDIAG_VEGASINFO
1467 req.r.tcpdiag_ext |= (1<<(TCPDIAG_VEGASINFO-1));
1471 iov[0] = (struct iovec){ &req, sizeof(req) };
1473 bclen = ssfilter_bytecompile(f->f, &bc);
1474 rta.rta_type = TCPDIAG_REQ_BYTECODE;
1475 rta.rta_len = RTA_LENGTH(bclen);
1476 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1477 iov[2] = (struct iovec){ bc, bclen };
1478 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1481 msg = (struct msghdr) {
1482 (void*)&nladdr, sizeof(nladdr),
1488 if (sendmsg(fd, &msg, 0) < 0)
1492 iov[0] = (struct iovec){ buf, sizeof(buf) };
1498 msg = (struct msghdr) {
1499 (void*)&nladdr, sizeof(nladdr),
1505 status = recvmsg(fd, &msg, 0);
1514 fprintf(stderr, "EOF on netlink\n");
1519 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1521 h = (struct nlmsghdr*)buf;
1522 while (NLMSG_OK(h, status)) {
1525 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1526 h->nlmsg_seq != 123456)
1529 if (h->nlmsg_type == NLMSG_DONE)
1531 if (h->nlmsg_type == NLMSG_ERROR) {
1532 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1533 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1534 fprintf(stderr, "ERROR truncated\n");
1536 errno = -err->error;
1537 perror("TCPDIAG answers");
1542 err = tcp_show_sock(h, NULL);
1548 h = NLMSG_NEXT(h, status);
1550 if (msg.msg_flags & MSG_TRUNC) {
1551 fprintf(stderr, "Message truncated\n");
1555 fprintf(stderr, "!!!Remnant of size %d\n", status);
1562 int tcp_show_netlink_file(struct filter *f)
1567 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1568 perror("fopen($TCPDIAG_FILE)");
1574 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1576 status = fread(buf, 1, sizeof(*h), fp);
1578 perror("Reading header from $TCPDIAG_FILE");
1581 if (status != sizeof(*h)) {
1582 perror("Unexpected EOF reading $TCPDIAG_FILE");
1586 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1589 perror("Reading $TCPDIAG_FILE");
1592 if (status + sizeof(*h) < h->nlmsg_len) {
1593 perror("Unexpected EOF reading $TCPDIAG_FILE");
1597 /* The only legal exit point */
1598 if (h->nlmsg_type == NLMSG_DONE)
1601 if (h->nlmsg_type == NLMSG_ERROR) {
1602 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1603 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1604 fprintf(stderr, "ERROR truncated\n");
1606 errno = -err->error;
1607 perror("TCPDIAG answered");
1612 err = tcp_show_sock(h, f);
1618 int tcp_show(struct filter *f)
1622 int bufsize = 64*1024;
1624 dg_proto = TCP_PROTO;
1626 if (getenv("TCPDIAG_FILE"))
1627 return tcp_show_netlink_file(f);
1629 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1630 && tcp_show_netlink(f, NULL) == 0)
1633 /* Sigh... We have to parse /proc/net/tcp... */
1635 /* Estimate amount of sockets and try to allocate
1636 * huge buffer to read all the table at one read.
1637 * Limit it by 16MB though. The assumption is: as soon as
1638 * kernel was able to hold information about N connections,
1639 * it is able to give us some memory for snapshot.
1642 int guess = slabstat.socks+slabstat.tcp_syns;
1643 if (f->states&(1<<SS_TIME_WAIT))
1644 guess += slabstat.tcp_tws;
1645 if (guess > (16*1024*1024)/128)
1646 guess = (16*1024*1024)/128;
1648 if (guess > bufsize)
1651 while (bufsize >= 64*1024) {
1652 if ((buf = malloc(bufsize)) != NULL)
1661 if (f->families & (1<<AF_INET)) {
1662 if ((fd = net_tcp_open()) < 0)
1664 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET))
1669 if ((f->families & (1<<AF_INET6)) &&
1670 (fd = net_tcp6_open()) >= 0) {
1671 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET6))
1681 int saved_errno = errno;
1686 errno = saved_errno;
1692 int dgram_show_line(char *line, struct filter *f, int family)
1695 char *loc, *rem, *data;
1700 if ((p = strchr(line, ':')) == NULL)
1704 if ((p = strchr(loc, ':')) == NULL)
1709 if ((p = strchr(rem, ':')) == NULL)
1715 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1717 if (!(f->states & (1<<state)))
1721 s.local.family = s.remote.family = family;
1722 if (family == AF_INET) {
1723 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1724 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1725 s.local.bytelen = s.remote.bytelen = 4;
1727 sscanf(loc, "%08x%08x%08x%08x:%x",
1733 sscanf(rem, "%08x%08x%08x%08x:%x",
1739 s.local.bytelen = s.remote.bytelen = 16;
1742 if (f->f && run_ssfilter(f->f, &s) == 0)
1746 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %d %d %llx %[^\n]\n",
1747 &s.state, &s.wq, &s.rq,
1749 &s.refcnt, &s.sk, opt);
1755 printf("%-*s ", netid_width, dg_proto);
1757 printf("%-*s ", state_width, sstate_name[s.state]);
1759 printf("%-6d %-6d ", s.rq, s.wq);
1761 formatted_print(&s.local, s.lport);
1762 formatted_print(&s.remote, s.rport);
1766 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1767 printf(" users:(%s)", ubuf);
1772 printf(" uid=%u", (unsigned)s.uid);
1773 printf(" ino=%u", (unsigned)s.ino);
1774 printf(" sk=%llx", s.sk);
1776 printf(" opt:\"%s\"", opt);
1784 int udp_show(struct filter *f)
1788 int bufsize = sizeof(buf);
1790 dg_proto = UDP_PROTO;
1792 if (f->families&(1<<AF_INET)) {
1793 if ((fd = net_udp_open()) < 0)
1795 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1800 if ((f->families&(1<<AF_INET6)) &&
1801 (fd = net_udp6_open()) >= 0) {
1802 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1810 int saved_errno = errno;
1813 errno = saved_errno;
1818 int raw_show(struct filter *f)
1822 int bufsize = sizeof(buf);
1824 dg_proto = RAW_PROTO;
1826 if (f->families&(1<<AF_INET)) {
1827 if ((fd = net_raw_open()) < 0)
1829 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1834 if ((f->families&(1<<AF_INET6)) &&
1835 (fd = net_raw6_open()) >= 0) {
1836 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1844 int saved_errno = errno;
1847 errno = saved_errno;
1855 struct unixstat *next;
1867 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
1868 SS_ESTABLISHED, SS_CLOSING };
1871 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
1873 void unix_list_free(struct unixstat *list)
1876 struct unixstat *s = list;
1884 void unix_list_print(struct unixstat *list, struct filter *f)
1889 for (s = list; s; s = s->next) {
1890 if (!(f->states & (1<<s->state)))
1892 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
1894 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
1900 for (p = list; p; p = p->next) {
1901 if (s->peer == p->ino)
1907 peer = p->name ? : "*";
1913 tst.local.family = AF_UNIX;
1914 tst.remote.family = AF_UNIX;
1915 memcpy(tst.local.data, &s->name, sizeof(s->name));
1916 if (strcmp(peer, "*") == 0)
1917 memset(tst.remote.data, 0, sizeof(peer));
1919 memcpy(tst.remote.data, &peer, sizeof(peer));
1920 if (run_ssfilter(f->f, &tst) == 0)
1925 printf("%-*s ", netid_width,
1926 s->type == SOCK_STREAM ? "u_str" : "u_dgr");
1928 printf("%-*s ", state_width, sstate_name[s->state]);
1929 printf("%-6d %-6d ", s->rq, s->wq);
1930 printf("%*s %-*d %*s %-*d",
1931 addr_width, s->name ? : "*", serv_width, s->ino,
1932 addr_width, peer, serv_width, s->peer);
1935 if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
1936 printf(" users:(%s)", ubuf);
1942 int unix_show(struct filter *f)
1949 struct unixstat *list = NULL;
1951 if ((fp = fdopen(net_unix_open(), "r")) == NULL)
1953 fgets(buf, sizeof(buf)-1, fp);
1955 if (memcmp(buf, "Peer", 4) == 0)
1959 while (fgets(buf, sizeof(buf)-1, fp)) {
1960 struct unixstat *u, **insp;
1963 if (!(u = malloc(sizeof(*u))))
1967 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
1968 &u->peer, &u->rq, &u->wq, &flags, &u->type,
1969 &u->state, &u->ino, name) < 8)
1972 if (flags&(1<<16)) {
1973 u->state = SS_LISTEN;
1975 u->state = unix_state_map[u->state-1];
1976 if (u->type == SOCK_DGRAM &&
1977 u->state == SS_CLOSE &&
1979 u->state = SS_ESTABLISHED;
1990 if (u->type < (*insp)->type ||
1991 (u->type == (*insp)->type &&
1992 u->ino < (*insp)->ino))
1994 insp = &(*insp)->next;
2000 if ((u->name = malloc(strlen(name)+1)) == NULL)
2002 strcpy(u->name, name);
2004 if (++cnt > MAX_UNIX_REMEMBER) {
2005 unix_list_print(list, f);
2006 unix_list_free(list);
2013 unix_list_print(list, f);
2014 unix_list_free(list);
2023 int packet_show(struct filter *f)
2034 unsigned long long sk;
2036 if (!(f->states & (1<<SS_CLOSE)))
2039 if ((fp = fdopen(net_packet_open(), "r")) == NULL)
2041 fgets(buf, sizeof(buf)-1, fp);
2043 while (fgets(buf, sizeof(buf)-1, fp)) {
2044 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2046 &type, &prot, &iface, &state,
2049 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2051 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2055 tst.local.family = AF_PACKET;
2056 tst.remote.family = AF_PACKET;
2059 tst.local.data[0] = prot;
2060 tst.remote.data[0] = 0;
2061 if (run_ssfilter(f->f, &tst) == 0)
2066 printf("%-*s ", netid_width,
2067 type == SOCK_RAW ? "p_raw" : "p_dgr");
2069 printf("%-*s ", state_width, "UNCONN");
2070 printf("%-6d %-6d ", rq, 0);
2072 printf("%*s:", addr_width, "*");
2075 printf("%*s:", addr_width,
2076 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2079 printf("%-*s ", serv_width, "*");
2081 printf("%-*s ", serv_width, xll_index_to_name(iface));
2084 addr_width, "", serv_width, "");
2088 if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2089 printf(" users:(%s)", ubuf);
2092 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2100 int netlink_show(struct filter *f)
2107 unsigned long long sk, cb;
2109 if (!(f->states & (1<<SS_CLOSE)))
2112 if ((fp = fdopen(net_netlink_open(), "r")) == NULL)
2114 fgets(buf, sizeof(buf)-1, fp);
2116 while (fgets(buf, sizeof(buf)-1, fp)) {
2117 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2119 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2123 tst.local.family = AF_NETLINK;
2124 tst.remote.family = AF_NETLINK;
2127 tst.local.data[0] = prot;
2128 tst.remote.data[0] = 0;
2129 if (run_ssfilter(f->f, &tst) == 0)
2134 printf("%-*s ", netid_width, "nl");
2136 printf("%-*s ", state_width, "UNCONN");
2137 printf("%-6d %-6d ", rq, wq);
2138 if (resolve_services && prot == 0)
2139 printf("%*s:", addr_width, "rtnl");
2140 else if (resolve_services && prot == 3)
2141 printf("%*s:", addr_width, "fw");
2142 else if (resolve_services && prot == 4)
2143 printf("%*s:", addr_width, "tcpdiag");
2145 printf("%*d:", addr_width, prot);
2147 printf("%-*s ", serv_width, "*");
2148 } else if (resolve_services) {
2152 printf("%-*s ", serv_width, "kernel");
2153 } else if (pid > 0) {
2156 sprintf(procname, "%s/%d/stat",
2157 getenv("PROC_ROOT") ? : "/proc", pid);
2158 if ((fp = fopen(procname, "r")) != NULL) {
2159 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2160 sprintf(procname+strlen(procname), "/%d", pid);
2161 printf("%-*s ", serv_width, procname);
2168 printf("%-*d ", serv_width, pid);
2170 printf("%-*d ", serv_width, pid);
2173 addr_width, "", serv_width, "");
2176 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2189 int get_snmp_int(char *proto, char *key, int *result)
2193 int protolen = strlen(proto);
2194 int keylen = strlen(key);
2198 if ((fp = fdopen(net_snmp_open(), "r")) == NULL)
2201 while (fgets(buf, sizeof(buf), fp) != NULL) {
2204 if (memcmp(buf, proto, protolen))
2206 while ((p = strchr(p, ' ')) != NULL) {
2209 if (memcmp(p, key, keylen) == 0 &&
2210 (p[keylen] == ' ' || p[keylen] == '\n'))
2213 if (fgets(buf, sizeof(buf), fp) == NULL)
2215 if (memcmp(buf, proto, protolen))
2218 while ((p = strchr(p, ' ')) != NULL) {
2221 sscanf(p, "%d", result);
2234 /* Get stats from sockstat */
2255 static void get_sockstat_line(char *line, struct sockstat *s)
2257 char id[256], rem[256];
2259 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2262 if (strcmp(id, "sockets:") == 0)
2263 sscanf(rem, "%*s%d", &s->socks);
2264 else if (strcmp(id, "UDP:") == 0)
2265 sscanf(rem, "%*s%d", &s->udp4);
2266 else if (strcmp(id, "UDP6:") == 0)
2267 sscanf(rem, "%*s%d", &s->udp6);
2268 else if (strcmp(id, "RAW:") == 0)
2269 sscanf(rem, "%*s%d", &s->raw4);
2270 else if (strcmp(id, "RAW6:") == 0)
2271 sscanf(rem, "%*s%d", &s->raw6);
2272 else if (strcmp(id, "TCP6:") == 0)
2273 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2274 else if (strcmp(id, "FRAG:") == 0)
2275 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2276 else if (strcmp(id, "FRAG6:") == 0)
2277 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2278 else if (strcmp(id, "TCP:") == 0)
2279 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2281 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2284 int get_sockstat(struct sockstat *s)
2289 memset(s, 0, sizeof(*s));
2291 if ((fp = fdopen(net_sockstat_open(), "r")) == NULL)
2293 while(fgets(buf, sizeof(buf), fp) != NULL)
2294 get_sockstat_line(buf, s);
2297 if ((fp = fdopen(net_sockstat6_open(), "r")) == NULL)
2299 while(fgets(buf, sizeof(buf), fp) != NULL)
2300 get_sockstat_line(buf, s);
2306 int print_summary(void)
2311 if (get_sockstat(&s) < 0)
2312 perror("ss: get_sockstat");
2313 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2314 perror("ss: get_snmpstat");
2316 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2318 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2319 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2321 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2324 s.tcp_tws, slabstat.tcp_tws,
2329 printf("Transport Total IP IPv6\n");
2330 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2331 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2332 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2333 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2334 printf("INET %-9d %-9d %-9d\n",
2335 s.raw4+s.udp4+s.tcp4_hashed+
2336 s.raw6+s.udp6+s.tcp6_hashed,
2337 s.raw4+s.udp4+s.tcp4_hashed,
2338 s.raw6+s.udp6+s.tcp6_hashed);
2339 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2347 static void usage(void) __attribute__((noreturn));
2349 static void usage(void)
2352 "Usage: ss [ OPTIONS ]\n"
2353 " ss [ OPTIONS ] [ FILTER ]\n"
2354 " -h, --help this message\n"
2355 " -V, --version output version information\n"
2356 " -n, --numeric don't resolve service names\n"
2357 " -r, --resolve resolve host names\n"
2358 " -a, --all display all sockets\n"
2359 " -l, --listening display listening sockets\n"
2360 " -o, --options show timer information\n"
2361 " -e, --extended show detailed socket information\n"
2362 " -m, --memory show socket memory usage\n"
2363 " -p, --processes show process using socket\n"
2364 " -i, --info show internal TCP information\n"
2365 " -s, --summary show socket usage summary\n"
2367 " -4, --ipv4 display only IP version 4 sockets\n"
2368 " -6, --ipv6 display only IP version 6 sockets\n"
2369 " -0, --packet display PACKET sockets\n"
2370 " -t, --tcp display only TCP sockets\n"
2371 " -u, --udp display only UDP sockets\n"
2372 " -w, --raw display only RAW sockets\n"
2373 " -x, --unix display only Unix domain sockets\n"
2374 " -f, --family=FAMILY display sockets of type FAMILY\n"
2376 " -A, --query=QUERY\n"
2377 " QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2379 " -F, --filter=FILE read filter information from FILE\n"
2380 " FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2386 int scan_state(const char *state)
2389 if (strcasecmp(state, "close") == 0 ||
2390 strcasecmp(state, "closed") == 0)
2391 return (1<<SS_CLOSE);
2392 if (strcasecmp(state, "syn-rcv") == 0)
2393 return (1<<SS_SYN_RECV);
2394 if (matches(state, "established") == 0)
2395 return (1<<SS_ESTABLISHED);
2396 if (strcasecmp(state, "all") == 0)
2398 if (strcasecmp(state, "connected") == 0)
2399 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2400 if (matches(state, "synchronized") == 0)
2401 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2402 if (strcasecmp(state, "bucket") == 0)
2403 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2404 if (strcasecmp(state, "big") == 0)
2405 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2406 for (i=0; i<SS_MAX; i++) {
2407 if (matches(state, sstate_namel[i]) == 0)
2413 static const struct option long_opts[] = {
2414 { "numeric", 0, 0, 'n' },
2415 { "resolve", 0, 0, 'r' },
2416 { "options", 0, 0, 'o' },
2417 { "extended", 0, 0, 'e' },
2418 { "memory", 0, 0, 'm' },
2419 { "info", 0, 0, 'i' },
2420 { "processes", 0, 0, 'p' },
2421 { "tcp", 0, 0, 't' },
2422 { "udp", 0, 0, 'u' },
2423 { "raw", 0, 0, 'w' },
2424 { "unix", 0, 0, 'x' },
2425 { "all", 0, 0, 'a' },
2426 { "listening", 0, 0, 'l' },
2427 { "ipv4", 0, 0, '4' },
2428 { "ipv6", 0, 0, '6' },
2429 { "packet", 0, 0, '0' },
2430 { "family", 1, 0, 'f' },
2431 { "socket", 1, 0, 'A' },
2432 { "summaary", 0, 0, 's' },
2433 { "diag", 0, 0, 'D' },
2434 { "filter", 1, 0, 'F' },
2435 { "version", 0, 0, 'V' },
2436 { "help", 0, 0, 'h' },
2441 int main(int argc, char *argv[])
2447 const char *dump_tcpdiag = NULL;
2448 FILE *filter_fp = NULL;
2451 memset(¤t_filter, 0, sizeof(current_filter));
2453 current_filter.states = default_filter.states;
2455 while ((ch = getopt_long(argc, argv, "haletuwxnro460spf:miA:D:F:vV",
2456 long_opts, NULL)) != EOF) {
2459 resolve_services = 0;
2481 current_filter.dbs |= (1<<TCP_DB);
2485 current_filter.dbs |= (1<<UDP_DB);
2489 current_filter.dbs |= (1<<RAW_DB);
2493 current_filter.dbs |= UNIX_DBM;
2497 current_filter.states = SS_ALL;
2500 current_filter.states = (1<<SS_LISTEN);
2503 preferred_family = AF_INET;
2506 preferred_family = AF_INET6;
2509 preferred_family = AF_PACKET;
2512 if (strcmp(optarg, "inet") == 0)
2513 preferred_family = AF_INET;
2514 else if (strcmp(optarg, "inet6") == 0)
2515 preferred_family = AF_INET6;
2516 else if (strcmp(optarg, "link") == 0)
2517 preferred_family = AF_PACKET;
2518 else if (strcmp(optarg, "unix") == 0)
2519 preferred_family = AF_UNIX;
2520 else if (strcmp(optarg, "netlink") == 0)
2521 preferred_family = AF_NETLINK;
2522 else if (strcmp(optarg, "help") == 0)
2525 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2533 current_filter.dbs = 0;
2539 if ((p1 = strchr(p, ',')) != NULL)
2541 if (strcmp(p, "all") == 0) {
2542 current_filter.dbs = ALL_DB;
2543 } else if (strcmp(p, "inet") == 0) {
2544 current_filter.dbs |= (1<<TCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2545 } else if (strcmp(p, "udp") == 0) {
2546 current_filter.dbs |= (1<<UDP_DB);
2547 } else if (strcmp(p, "tcp") == 0) {
2548 current_filter.dbs |= (1<<TCP_DB);
2549 } else if (strcmp(p, "raw") == 0) {
2550 current_filter.dbs |= (1<<RAW_DB);
2551 } else if (strcmp(p, "unix") == 0) {
2552 current_filter.dbs |= UNIX_DBM;
2553 } else if (matches(p, "unix_stream") == 0 ||
2554 strcmp(p, "u_str") == 0) {
2555 current_filter.dbs |= (1<<UNIX_ST_DB);
2556 } else if (matches(p, "unix_dgram") == 0 ||
2557 strcmp(p, "u_dgr") == 0) {
2558 current_filter.dbs |= (1<<UNIX_DG_DB);
2559 } else if (strcmp(p, "packet") == 0) {
2560 current_filter.dbs |= PACKET_DBM;
2561 } else if (strcmp(p, "packet_raw") == 0 ||
2562 strcmp(p, "p_raw") == 0) {
2563 current_filter.dbs |= (1<<PACKET_R_DB);
2564 } else if (strcmp(p, "packet_dgram") == 0 ||
2565 strcmp(p, "p_dgr") == 0) {
2566 current_filter.dbs |= (1<<PACKET_DG_DB);
2567 } else if (strcmp(p, "netlink") == 0) {
2568 current_filter.dbs |= (1<<NETLINK_DB);
2570 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2581 dump_tcpdiag = optarg;
2585 fprintf(stderr, "More than one filter file\n");
2588 if (optarg[0] == '-')
2591 filter_fp = fopen(optarg, "r");
2593 perror("fopen filter file");
2599 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
2611 get_slabstat(&slabstat);
2615 if (do_default && argc == 0)
2620 current_filter.dbs = default_filter.dbs;
2622 if (preferred_family == AF_UNSPEC) {
2623 if (!(current_filter.dbs&~UNIX_DBM))
2624 preferred_family = AF_UNIX;
2625 else if (!(current_filter.dbs&~PACKET_DBM))
2626 preferred_family = AF_PACKET;
2627 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
2628 preferred_family = AF_NETLINK;
2631 if (preferred_family != AF_UNSPEC) {
2633 if (preferred_family == AF_INET ||
2634 preferred_family == AF_INET6) {
2637 mask2 = (1<<UDP_DB)|(1<<RAW_DB);
2638 } else if (preferred_family == AF_PACKET) {
2640 } else if (preferred_family == AF_UNIX) {
2642 } else if (preferred_family == AF_NETLINK) {
2643 mask2 = (1<<NETLINK_DB);
2649 current_filter.dbs = mask2;
2651 current_filter.dbs &= mask2;
2652 current_filter.families = (1<<preferred_family);
2655 current_filter.families = ~0;
2657 current_filter.families = default_filter.families;
2659 if (current_filter.dbs == 0) {
2660 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
2663 if (current_filter.families == 0) {
2664 fprintf(stderr, "ss: no families to show with such filter.\n");
2668 if (resolve_services && resolve_hosts &&
2669 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB))))
2670 init_service_resolver();
2672 /* Now parse filter... */
2673 if (argc == 0 && filter_fp) {
2674 if (ssfilter_parse(¤t_filter.f, 0, NULL, filter_fp))
2679 if (strcmp(*argv, "state") == 0) {
2682 current_filter.states = 0;
2683 current_filter.states |= scan_state(*argv);
2685 } else if (strcmp(*argv, "exclude") == 0 ||
2686 strcmp(*argv, "excl") == 0) {
2689 current_filter.states = SS_ALL;
2690 current_filter.states &= ~scan_state(*argv);
2693 if (ssfilter_parse(¤t_filter.f, argc, argv, filter_fp))
2700 if (current_filter.states == 0) {
2701 fprintf(stderr, "ss: no socket states to show with such filter.\n");
2706 FILE *dump_fp = stdout;
2707 if (!(current_filter.dbs & (1<<TCP_DB))) {
2708 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
2711 if (dump_tcpdiag[0] != '-') {
2712 dump_fp = fopen(dump_tcpdiag, "w");
2713 if (!dump_tcpdiag) {
2714 perror("fopen dump file");
2718 tcp_show_netlink(¤t_filter, dump_fp);
2724 if (current_filter.dbs&(current_filter.dbs-1))
2728 if (current_filter.states&(current_filter.states-1))
2732 if (isatty(STDOUT_FILENO)) {
2735 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
2737 screen_width = w.ws_col;
2741 addrp_width = screen_width;
2742 addrp_width -= netid_width+1;
2743 addrp_width -= state_width+1;
2746 if (addrp_width&1) {
2749 else if (state_width)
2756 serv_width = resolve_services ? 7 : 5;
2758 if (addrp_width < 15+serv_width+1)
2759 addrp_width = 15+serv_width+1;
2761 addr_width = addrp_width - serv_width - 1;
2764 printf("%-*s ", netid_width, "Netid");
2766 printf("%-*s ", state_width, "State");
2767 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
2769 printf("%*s:%-*s %*s:%-*s\n",
2770 addr_width, "Local Address", serv_width, "Port",
2771 addr_width, "Peer Address", serv_width, "Port");
2773 //printf("%08x %08x %08x\n", current_filter.dbs, current_filter.states, current_filter.families);
2776 if (current_filter.dbs & (1<<NETLINK_DB))
2777 netlink_show(¤t_filter);
2778 if (current_filter.dbs & PACKET_DBM)
2779 packet_show(¤t_filter);
2780 if (current_filter.dbs & UNIX_DBM)
2781 unix_show(¤t_filter);
2782 if (current_filter.dbs & (1<<RAW_DB))
2783 raw_show(¤t_filter);
2784 if (current_filter.dbs & (1<<UDP_DB))
2785 udp_show(¤t_filter);
2786 if (current_filter.dbs & (1<<TCP_DB))
2787 tcp_show(¤t_filter);