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 static void ssfilter_patch(char *a, int len, int reloc)
734 struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op*)a;
744 static 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 static 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 static int get_dns_host(struct aafilter *a, const 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);
922 static int xll_initted = 0;
924 static void xll_init(void)
926 struct rtnl_handle rth;
933 static const char *xll_index_to_name(int index)
937 return ll_index_to_name(index);
940 static int xll_name_to_index(const 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 static 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 static 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 static char *sprint_bw(char *buf, double bw)
1294 sprintf(buf,"%.1fM", bw / 1000000.);
1295 else if (bw > 1000.)
1296 sprintf(buf,"%.1fK", bw / 1000.);
1298 sprintf(buf, "%g", bw);
1303 static void tcp_show_info(const struct nlmsghdr *nlh, struct tcpdiagmsg *r)
1305 struct rtattr * tb[TCPDIAG_MAX+1];
1309 memset(tb, 0, sizeof(tb));
1310 parse_rtattr(tb, TCPDIAG_MAX, (struct rtattr*)(r+1),
1311 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1313 if (tb[TCPDIAG_MEMINFO]) {
1314 const struct tcpdiag_meminfo *minfo
1315 = RTA_DATA(tb[TCPDIAG_MEMINFO]);
1316 printf(" mem:(r%u,w%u,f%u,t%u)",
1317 minfo->tcpdiag_rmem,
1318 minfo->tcpdiag_wmem,
1319 minfo->tcpdiag_fmem,
1320 minfo->tcpdiag_tmem);
1323 if (tb[TCPDIAG_INFO]) {
1324 struct tcp_info *info;
1325 int len = RTA_PAYLOAD(tb[TCPDIAG_INFO]);
1327 /* workaround for older kernels with less fields */
1328 if (len < sizeof(*info)) {
1329 info = alloca(sizeof(*info));
1330 memset(info, 0, sizeof(*info));
1331 memcpy(info, RTA_DATA(tb[TCPDIAG_INFO]), len);
1333 info = RTA_DATA(tb[TCPDIAG_INFO]);
1336 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1338 if (info->tcpi_options & TCPI_OPT_SACK)
1340 if (info->tcpi_options & TCPI_OPT_ECN)
1343 if (info->tcpi_options & TCPI_OPT_WSCALE)
1344 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1345 info->tcpi_rcv_wscale);
1346 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1347 printf(" rto:%g", (double)info->tcpi_rto/1000);
1349 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1350 (double)info->tcpi_rttvar/1000);
1352 printf(" ato:%g", (double)info->tcpi_ato/1000);
1353 if (info->tcpi_snd_cwnd != 2)
1354 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1355 if (info->tcpi_snd_ssthresh < 0xFFFF)
1356 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1358 rtt = (double) info->tcpi_rtt;
1359 if (tb[TCPDIAG_VEGASINFO]) {
1360 const struct tcpvegas_info *vinfo
1361 = RTA_DATA(tb[TCPDIAG_VEGASINFO]);
1363 if (vinfo->tcpv_enabled)
1366 if (vinfo->tcpv_rtt &&
1367 vinfo->tcpv_rtt != 0x7fffffff)
1368 rtt = vinfo->tcpv_rtt;
1371 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1372 printf(" send %sbps",
1373 sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1374 (double) info->tcpi_snd_mss * 8000000.
1378 if (info->tcpi_rcv_rtt)
1379 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1380 if (info->tcpi_rcv_space)
1381 printf(" rcv_space:%d", info->tcpi_rcv_space);
1386 int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
1388 struct tcpdiagmsg *r = NLMSG_DATA(nlh);
1391 s.state = r->tcpdiag_state;
1392 s.local.family = s.remote.family = r->tcpdiag_family;
1393 s.lport = ntohs(r->id.tcpdiag_sport);
1394 s.rport = ntohs(r->id.tcpdiag_dport);
1395 if (s.local.family == AF_INET) {
1396 s.local.bytelen = s.remote.bytelen = 4;
1398 s.local.bytelen = s.remote.bytelen = 16;
1400 memcpy(s.local.data, r->id.tcpdiag_src, s.local.bytelen);
1401 memcpy(s.remote.data, r->id.tcpdiag_dst, s.local.bytelen);
1403 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1407 printf("%-*s ", netid_width, "tcp");
1409 printf("%-*s ", state_width, sstate_name[s.state]);
1411 printf("%-6d %-6d ", r->tcpdiag_rqueue, r->tcpdiag_wqueue);
1413 formatted_print(&s.local, s.lport);
1414 formatted_print(&s.remote, s.rport);
1417 if (r->tcpdiag_timer) {
1418 if (r->tcpdiag_timer > 4)
1419 r->tcpdiag_timer = 5;
1420 printf(" timer:(%s,%s,%d)",
1421 tmr_name[r->tcpdiag_timer],
1422 print_ms_timer(r->tcpdiag_expires),
1423 r->tcpdiag_retrans);
1428 if (find_users(r->tcpdiag_inode, ubuf, sizeof(ubuf)) > 0)
1429 printf(" users:(%s)", ubuf);
1433 printf(" uid:%u", (unsigned)r->tcpdiag_uid);
1434 printf(" ino:%u", (unsigned)r->tcpdiag_inode);
1435 printf(" sk:%08x", r->id.tcpdiag_cookie[0]);
1436 if (r->id.tcpdiag_cookie[1] != 0)
1437 printf("%08x", r->id.tcpdiag_cookie[1]);
1439 if (show_mem || show_tcpinfo) {
1441 tcp_show_info(nlh, r);
1450 int tcp_show_netlink(struct filter *f, FILE *dump_fp)
1453 struct sockaddr_nl nladdr;
1455 struct nlmsghdr nlh;
1456 struct tcpdiagreq r;
1463 struct iovec iov[3];
1465 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TCPDIAG)) < 0)
1468 memset(&nladdr, 0, sizeof(nladdr));
1469 nladdr.nl_family = AF_NETLINK;
1471 req.nlh.nlmsg_len = sizeof(req);
1472 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
1473 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1474 req.nlh.nlmsg_pid = 0;
1475 req.nlh.nlmsg_seq = 123456;
1476 memset(&req.r, 0, sizeof(req.r));
1477 req.r.tcpdiag_family = AF_INET;
1478 req.r.tcpdiag_states = f->states;
1480 req.r.tcpdiag_ext |= (1<<(TCPDIAG_MEMINFO-1));
1483 req.r.tcpdiag_ext |= (1<<(TCPDIAG_INFO-1));
1484 req.r.tcpdiag_ext |= (1<<(TCPDIAG_VEGASINFO-1));
1487 iov[0] = (struct iovec){ &req, sizeof(req) };
1489 bclen = ssfilter_bytecompile(f->f, &bc);
1490 rta.rta_type = TCPDIAG_REQ_BYTECODE;
1491 rta.rta_len = RTA_LENGTH(bclen);
1492 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1493 iov[2] = (struct iovec){ bc, bclen };
1494 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1497 msg = (struct msghdr) {
1498 (void*)&nladdr, sizeof(nladdr),
1504 if (sendmsg(fd, &msg, 0) < 0)
1508 iov[0] = (struct iovec){ buf, sizeof(buf) };
1514 msg = (struct msghdr) {
1515 (void*)&nladdr, sizeof(nladdr),
1521 status = recvmsg(fd, &msg, 0);
1530 fprintf(stderr, "EOF on netlink\n");
1535 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1537 h = (struct nlmsghdr*)buf;
1538 while (NLMSG_OK(h, status)) {
1541 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1542 h->nlmsg_seq != 123456)
1545 if (h->nlmsg_type == NLMSG_DONE)
1547 if (h->nlmsg_type == NLMSG_ERROR) {
1548 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1549 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1550 fprintf(stderr, "ERROR truncated\n");
1552 errno = -err->error;
1553 perror("TCPDIAG answers");
1558 err = tcp_show_sock(h, NULL);
1564 h = NLMSG_NEXT(h, status);
1566 if (msg.msg_flags & MSG_TRUNC) {
1567 fprintf(stderr, "Message truncated\n");
1571 fprintf(stderr, "!!!Remnant of size %d\n", status);
1578 int tcp_show_netlink_file(struct filter *f)
1583 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1584 perror("fopen($TCPDIAG_FILE)");
1590 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1592 status = fread(buf, 1, sizeof(*h), fp);
1594 perror("Reading header from $TCPDIAG_FILE");
1597 if (status != sizeof(*h)) {
1598 perror("Unexpected EOF reading $TCPDIAG_FILE");
1602 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1605 perror("Reading $TCPDIAG_FILE");
1608 if (status + sizeof(*h) < h->nlmsg_len) {
1609 perror("Unexpected EOF reading $TCPDIAG_FILE");
1613 /* The only legal exit point */
1614 if (h->nlmsg_type == NLMSG_DONE)
1617 if (h->nlmsg_type == NLMSG_ERROR) {
1618 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1619 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1620 fprintf(stderr, "ERROR truncated\n");
1622 errno = -err->error;
1623 perror("TCPDIAG answered");
1628 err = tcp_show_sock(h, f);
1634 int tcp_show(struct filter *f)
1638 int bufsize = 64*1024;
1640 dg_proto = TCP_PROTO;
1642 if (getenv("TCPDIAG_FILE"))
1643 return tcp_show_netlink_file(f);
1645 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1646 && tcp_show_netlink(f, NULL) == 0)
1649 /* Sigh... We have to parse /proc/net/tcp... */
1651 /* Estimate amount of sockets and try to allocate
1652 * huge buffer to read all the table at one read.
1653 * Limit it by 16MB though. The assumption is: as soon as
1654 * kernel was able to hold information about N connections,
1655 * it is able to give us some memory for snapshot.
1658 int guess = slabstat.socks+slabstat.tcp_syns;
1659 if (f->states&(1<<SS_TIME_WAIT))
1660 guess += slabstat.tcp_tws;
1661 if (guess > (16*1024*1024)/128)
1662 guess = (16*1024*1024)/128;
1664 if (guess > bufsize)
1667 while (bufsize >= 64*1024) {
1668 if ((buf = malloc(bufsize)) != NULL)
1677 if (f->families & (1<<AF_INET)) {
1678 if ((fd = net_tcp_open()) < 0)
1680 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET))
1685 if ((f->families & (1<<AF_INET6)) &&
1686 (fd = net_tcp6_open()) >= 0) {
1687 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET6))
1697 int saved_errno = errno;
1702 errno = saved_errno;
1708 int dgram_show_line(char *line, struct filter *f, int family)
1711 char *loc, *rem, *data;
1716 if ((p = strchr(line, ':')) == NULL)
1720 if ((p = strchr(loc, ':')) == NULL)
1725 if ((p = strchr(rem, ':')) == NULL)
1731 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1733 if (!(f->states & (1<<state)))
1737 s.local.family = s.remote.family = family;
1738 if (family == AF_INET) {
1739 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1740 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1741 s.local.bytelen = s.remote.bytelen = 4;
1743 sscanf(loc, "%08x%08x%08x%08x:%x",
1749 sscanf(rem, "%08x%08x%08x%08x:%x",
1755 s.local.bytelen = s.remote.bytelen = 16;
1758 if (f->f && run_ssfilter(f->f, &s) == 0)
1762 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %d %d %llx %[^\n]\n",
1763 &s.state, &s.wq, &s.rq,
1765 &s.refcnt, &s.sk, opt);
1771 printf("%-*s ", netid_width, dg_proto);
1773 printf("%-*s ", state_width, sstate_name[s.state]);
1775 printf("%-6d %-6d ", s.rq, s.wq);
1777 formatted_print(&s.local, s.lport);
1778 formatted_print(&s.remote, s.rport);
1782 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1783 printf(" users:(%s)", ubuf);
1788 printf(" uid=%u", (unsigned)s.uid);
1789 printf(" ino=%u", (unsigned)s.ino);
1790 printf(" sk=%llx", s.sk);
1792 printf(" opt:\"%s\"", opt);
1800 int udp_show(struct filter *f)
1804 int bufsize = sizeof(buf);
1806 dg_proto = UDP_PROTO;
1808 if (f->families&(1<<AF_INET)) {
1809 if ((fd = net_udp_open()) < 0)
1811 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1816 if ((f->families&(1<<AF_INET6)) &&
1817 (fd = net_udp6_open()) >= 0) {
1818 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1826 int saved_errno = errno;
1829 errno = saved_errno;
1834 int raw_show(struct filter *f)
1838 int bufsize = sizeof(buf);
1840 dg_proto = RAW_PROTO;
1842 if (f->families&(1<<AF_INET)) {
1843 if ((fd = net_raw_open()) < 0)
1845 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1850 if ((f->families&(1<<AF_INET6)) &&
1851 (fd = net_raw6_open()) >= 0) {
1852 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1860 int saved_errno = errno;
1863 errno = saved_errno;
1871 struct unixstat *next;
1883 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
1884 SS_ESTABLISHED, SS_CLOSING };
1887 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
1889 void unix_list_free(struct unixstat *list)
1892 struct unixstat *s = list;
1900 void unix_list_print(struct unixstat *list, struct filter *f)
1905 for (s = list; s; s = s->next) {
1906 if (!(f->states & (1<<s->state)))
1908 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
1910 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
1916 for (p = list; p; p = p->next) {
1917 if (s->peer == p->ino)
1923 peer = p->name ? : "*";
1929 tst.local.family = AF_UNIX;
1930 tst.remote.family = AF_UNIX;
1931 memcpy(tst.local.data, &s->name, sizeof(s->name));
1932 if (strcmp(peer, "*") == 0)
1933 memset(tst.remote.data, 0, sizeof(peer));
1935 memcpy(tst.remote.data, &peer, sizeof(peer));
1936 if (run_ssfilter(f->f, &tst) == 0)
1941 printf("%-*s ", netid_width,
1942 s->type == SOCK_STREAM ? "u_str" : "u_dgr");
1944 printf("%-*s ", state_width, sstate_name[s->state]);
1945 printf("%-6d %-6d ", s->rq, s->wq);
1946 printf("%*s %-*d %*s %-*d",
1947 addr_width, s->name ? : "*", serv_width, s->ino,
1948 addr_width, peer, serv_width, s->peer);
1951 if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
1952 printf(" users:(%s)", ubuf);
1958 int unix_show(struct filter *f)
1965 struct unixstat *list = NULL;
1967 if ((fp = fdopen(net_unix_open(), "r")) == NULL)
1969 fgets(buf, sizeof(buf)-1, fp);
1971 if (memcmp(buf, "Peer", 4) == 0)
1975 while (fgets(buf, sizeof(buf)-1, fp)) {
1976 struct unixstat *u, **insp;
1979 if (!(u = malloc(sizeof(*u))))
1983 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
1984 &u->peer, &u->rq, &u->wq, &flags, &u->type,
1985 &u->state, &u->ino, name) < 8)
1988 if (flags&(1<<16)) {
1989 u->state = SS_LISTEN;
1991 u->state = unix_state_map[u->state-1];
1992 if (u->type == SOCK_DGRAM &&
1993 u->state == SS_CLOSE &&
1995 u->state = SS_ESTABLISHED;
2006 if (u->type < (*insp)->type ||
2007 (u->type == (*insp)->type &&
2008 u->ino < (*insp)->ino))
2010 insp = &(*insp)->next;
2016 if ((u->name = malloc(strlen(name)+1)) == NULL)
2018 strcpy(u->name, name);
2020 if (++cnt > MAX_UNIX_REMEMBER) {
2021 unix_list_print(list, f);
2022 unix_list_free(list);
2029 unix_list_print(list, f);
2030 unix_list_free(list);
2039 int packet_show(struct filter *f)
2050 unsigned long long sk;
2052 if (!(f->states & (1<<SS_CLOSE)))
2055 if ((fp = fdopen(net_packet_open(), "r")) == NULL)
2057 fgets(buf, sizeof(buf)-1, fp);
2059 while (fgets(buf, sizeof(buf)-1, fp)) {
2060 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2062 &type, &prot, &iface, &state,
2065 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2067 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2071 tst.local.family = AF_PACKET;
2072 tst.remote.family = AF_PACKET;
2075 tst.local.data[0] = prot;
2076 tst.remote.data[0] = 0;
2077 if (run_ssfilter(f->f, &tst) == 0)
2082 printf("%-*s ", netid_width,
2083 type == SOCK_RAW ? "p_raw" : "p_dgr");
2085 printf("%-*s ", state_width, "UNCONN");
2086 printf("%-6d %-6d ", rq, 0);
2088 printf("%*s:", addr_width, "*");
2091 printf("%*s:", addr_width,
2092 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2095 printf("%-*s ", serv_width, "*");
2097 printf("%-*s ", serv_width, xll_index_to_name(iface));
2100 addr_width, "", serv_width, "");
2104 if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2105 printf(" users:(%s)", ubuf);
2108 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2116 int netlink_show(struct filter *f)
2123 unsigned long long sk, cb;
2125 if (!(f->states & (1<<SS_CLOSE)))
2128 if ((fp = fdopen(net_netlink_open(), "r")) == NULL)
2130 fgets(buf, sizeof(buf)-1, fp);
2132 while (fgets(buf, sizeof(buf)-1, fp)) {
2133 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2135 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2139 tst.local.family = AF_NETLINK;
2140 tst.remote.family = AF_NETLINK;
2143 tst.local.data[0] = prot;
2144 tst.remote.data[0] = 0;
2145 if (run_ssfilter(f->f, &tst) == 0)
2150 printf("%-*s ", netid_width, "nl");
2152 printf("%-*s ", state_width, "UNCONN");
2153 printf("%-6d %-6d ", rq, wq);
2154 if (resolve_services && prot == 0)
2155 printf("%*s:", addr_width, "rtnl");
2156 else if (resolve_services && prot == 3)
2157 printf("%*s:", addr_width, "fw");
2158 else if (resolve_services && prot == 4)
2159 printf("%*s:", addr_width, "tcpdiag");
2161 printf("%*d:", addr_width, prot);
2163 printf("%-*s ", serv_width, "*");
2164 } else if (resolve_services) {
2168 printf("%-*s ", serv_width, "kernel");
2169 } else if (pid > 0) {
2172 sprintf(procname, "%s/%d/stat",
2173 getenv("PROC_ROOT") ? : "/proc", pid);
2174 if ((fp = fopen(procname, "r")) != NULL) {
2175 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2176 sprintf(procname+strlen(procname), "/%d", pid);
2177 printf("%-*s ", serv_width, procname);
2184 printf("%-*d ", serv_width, pid);
2186 printf("%-*d ", serv_width, pid);
2189 addr_width, "", serv_width, "");
2192 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2205 int get_snmp_int(char *proto, char *key, int *result)
2209 int protolen = strlen(proto);
2210 int keylen = strlen(key);
2214 if ((fp = fdopen(net_snmp_open(), "r")) == NULL)
2217 while (fgets(buf, sizeof(buf), fp) != NULL) {
2220 if (memcmp(buf, proto, protolen))
2222 while ((p = strchr(p, ' ')) != NULL) {
2225 if (memcmp(p, key, keylen) == 0 &&
2226 (p[keylen] == ' ' || p[keylen] == '\n'))
2229 if (fgets(buf, sizeof(buf), fp) == NULL)
2231 if (memcmp(buf, proto, protolen))
2234 while ((p = strchr(p, ' ')) != NULL) {
2237 sscanf(p, "%d", result);
2250 /* Get stats from sockstat */
2271 static void get_sockstat_line(char *line, struct sockstat *s)
2273 char id[256], rem[256];
2275 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2278 if (strcmp(id, "sockets:") == 0)
2279 sscanf(rem, "%*s%d", &s->socks);
2280 else if (strcmp(id, "UDP:") == 0)
2281 sscanf(rem, "%*s%d", &s->udp4);
2282 else if (strcmp(id, "UDP6:") == 0)
2283 sscanf(rem, "%*s%d", &s->udp6);
2284 else if (strcmp(id, "RAW:") == 0)
2285 sscanf(rem, "%*s%d", &s->raw4);
2286 else if (strcmp(id, "RAW6:") == 0)
2287 sscanf(rem, "%*s%d", &s->raw6);
2288 else if (strcmp(id, "TCP6:") == 0)
2289 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2290 else if (strcmp(id, "FRAG:") == 0)
2291 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2292 else if (strcmp(id, "FRAG6:") == 0)
2293 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2294 else if (strcmp(id, "TCP:") == 0)
2295 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2297 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2300 int get_sockstat(struct sockstat *s)
2305 memset(s, 0, sizeof(*s));
2307 if ((fp = fdopen(net_sockstat_open(), "r")) == NULL)
2309 while(fgets(buf, sizeof(buf), fp) != NULL)
2310 get_sockstat_line(buf, s);
2313 if ((fp = fdopen(net_sockstat6_open(), "r")) == NULL)
2315 while(fgets(buf, sizeof(buf), fp) != NULL)
2316 get_sockstat_line(buf, s);
2322 int print_summary(void)
2327 if (get_sockstat(&s) < 0)
2328 perror("ss: get_sockstat");
2329 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2330 perror("ss: get_snmpstat");
2332 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2334 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2335 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2337 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2340 s.tcp_tws, slabstat.tcp_tws,
2345 printf("Transport Total IP IPv6\n");
2346 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2347 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2348 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2349 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2350 printf("INET %-9d %-9d %-9d\n",
2351 s.raw4+s.udp4+s.tcp4_hashed+
2352 s.raw6+s.udp6+s.tcp6_hashed,
2353 s.raw4+s.udp4+s.tcp4_hashed,
2354 s.raw6+s.udp6+s.tcp6_hashed);
2355 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2363 static void usage(void) __attribute__((noreturn));
2365 static void usage(void)
2368 "Usage: ss [ OPTIONS ]\n"
2369 " ss [ OPTIONS ] [ FILTER ]\n"
2370 " -h, --help this message\n"
2371 " -V, --version output version information\n"
2372 " -n, --numeric don't resolve service names\n"
2373 " -r, --resolve resolve host names\n"
2374 " -a, --all display all sockets\n"
2375 " -l, --listening display listening sockets\n"
2376 " -o, --options show timer information\n"
2377 " -e, --extended show detailed socket information\n"
2378 " -m, --memory show socket memory usage\n"
2379 " -p, --processes show process using socket\n"
2380 " -i, --info show internal TCP information\n"
2381 " -s, --summary show socket usage summary\n"
2383 " -4, --ipv4 display only IP version 4 sockets\n"
2384 " -6, --ipv6 display only IP version 6 sockets\n"
2385 " -0, --packet display PACKET sockets\n"
2386 " -t, --tcp display only TCP sockets\n"
2387 " -u, --udp display only UDP sockets\n"
2388 " -w, --raw display only RAW sockets\n"
2389 " -x, --unix display only Unix domain sockets\n"
2390 " -f, --family=FAMILY display sockets of type FAMILY\n"
2392 " -A, --query=QUERY\n"
2393 " QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2395 " -F, --filter=FILE read filter information from FILE\n"
2396 " FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2402 int scan_state(const char *state)
2405 if (strcasecmp(state, "close") == 0 ||
2406 strcasecmp(state, "closed") == 0)
2407 return (1<<SS_CLOSE);
2408 if (strcasecmp(state, "syn-rcv") == 0)
2409 return (1<<SS_SYN_RECV);
2410 if (strcasecmp(state, "established") == 0)
2411 return (1<<SS_ESTABLISHED);
2412 if (strcasecmp(state, "all") == 0)
2414 if (strcasecmp(state, "connected") == 0)
2415 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2416 if (strcasecmp(state, "synchronized") == 0)
2417 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2418 if (strcasecmp(state, "bucket") == 0)
2419 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2420 if (strcasecmp(state, "big") == 0)
2421 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2422 for (i=0; i<SS_MAX; i++) {
2423 if (strcasecmp(state, sstate_namel[i]) == 0)
2429 static const struct option long_opts[] = {
2430 { "numeric", 0, 0, 'n' },
2431 { "resolve", 0, 0, 'r' },
2432 { "options", 0, 0, 'o' },
2433 { "extended", 0, 0, 'e' },
2434 { "memory", 0, 0, 'm' },
2435 { "info", 0, 0, 'i' },
2436 { "processes", 0, 0, 'p' },
2437 { "tcp", 0, 0, 't' },
2438 { "udp", 0, 0, 'u' },
2439 { "raw", 0, 0, 'w' },
2440 { "unix", 0, 0, 'x' },
2441 { "all", 0, 0, 'a' },
2442 { "listening", 0, 0, 'l' },
2443 { "ipv4", 0, 0, '4' },
2444 { "ipv6", 0, 0, '6' },
2445 { "packet", 0, 0, '0' },
2446 { "family", 1, 0, 'f' },
2447 { "socket", 1, 0, 'A' },
2448 { "summaary", 0, 0, 's' },
2449 { "diag", 0, 0, 'D' },
2450 { "filter", 1, 0, 'F' },
2451 { "version", 0, 0, 'V' },
2452 { "help", 0, 0, 'h' },
2457 int main(int argc, char *argv[])
2463 const char *dump_tcpdiag = NULL;
2464 FILE *filter_fp = NULL;
2467 memset(¤t_filter, 0, sizeof(current_filter));
2469 current_filter.states = default_filter.states;
2471 while ((ch = getopt_long(argc, argv, "haletuwxnro460spf:miA:D:F:vV",
2472 long_opts, NULL)) != EOF) {
2475 resolve_services = 0;
2497 current_filter.dbs |= (1<<TCP_DB);
2501 current_filter.dbs |= (1<<UDP_DB);
2505 current_filter.dbs |= (1<<RAW_DB);
2509 current_filter.dbs |= UNIX_DBM;
2513 current_filter.states = SS_ALL;
2516 current_filter.states = (1<<SS_LISTEN);
2519 preferred_family = AF_INET;
2522 preferred_family = AF_INET6;
2525 preferred_family = AF_PACKET;
2528 if (strcmp(optarg, "inet") == 0)
2529 preferred_family = AF_INET;
2530 else if (strcmp(optarg, "inet6") == 0)
2531 preferred_family = AF_INET6;
2532 else if (strcmp(optarg, "link") == 0)
2533 preferred_family = AF_PACKET;
2534 else if (strcmp(optarg, "unix") == 0)
2535 preferred_family = AF_UNIX;
2536 else if (strcmp(optarg, "netlink") == 0)
2537 preferred_family = AF_NETLINK;
2538 else if (strcmp(optarg, "help") == 0)
2541 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2549 current_filter.dbs = 0;
2555 if ((p1 = strchr(p, ',')) != NULL)
2557 if (strcmp(p, "all") == 0) {
2558 current_filter.dbs = ALL_DB;
2559 } else if (strcmp(p, "inet") == 0) {
2560 current_filter.dbs |= (1<<TCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2561 } else if (strcmp(p, "udp") == 0) {
2562 current_filter.dbs |= (1<<UDP_DB);
2563 } else if (strcmp(p, "tcp") == 0) {
2564 current_filter.dbs |= (1<<TCP_DB);
2565 } else if (strcmp(p, "raw") == 0) {
2566 current_filter.dbs |= (1<<RAW_DB);
2567 } else if (strcmp(p, "unix") == 0) {
2568 current_filter.dbs |= UNIX_DBM;
2569 } else if (strcasecmp(p, "unix_stream") == 0 ||
2570 strcmp(p, "u_str") == 0) {
2571 current_filter.dbs |= (1<<UNIX_ST_DB);
2572 } else if (strcasecmp(p, "unix_dgram") == 0 ||
2573 strcmp(p, "u_dgr") == 0) {
2574 current_filter.dbs |= (1<<UNIX_DG_DB);
2575 } else if (strcmp(p, "packet") == 0) {
2576 current_filter.dbs |= PACKET_DBM;
2577 } else if (strcmp(p, "packet_raw") == 0 ||
2578 strcmp(p, "p_raw") == 0) {
2579 current_filter.dbs |= (1<<PACKET_R_DB);
2580 } else if (strcmp(p, "packet_dgram") == 0 ||
2581 strcmp(p, "p_dgr") == 0) {
2582 current_filter.dbs |= (1<<PACKET_DG_DB);
2583 } else if (strcmp(p, "netlink") == 0) {
2584 current_filter.dbs |= (1<<NETLINK_DB);
2586 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2597 dump_tcpdiag = optarg;
2601 fprintf(stderr, "More than one filter file\n");
2604 if (optarg[0] == '-')
2607 filter_fp = fopen(optarg, "r");
2609 perror("fopen filter file");
2615 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
2627 get_slabstat(&slabstat);
2631 if (do_default && argc == 0)
2636 current_filter.dbs = default_filter.dbs;
2638 if (preferred_family == AF_UNSPEC) {
2639 if (!(current_filter.dbs&~UNIX_DBM))
2640 preferred_family = AF_UNIX;
2641 else if (!(current_filter.dbs&~PACKET_DBM))
2642 preferred_family = AF_PACKET;
2643 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
2644 preferred_family = AF_NETLINK;
2647 if (preferred_family != AF_UNSPEC) {
2649 if (preferred_family == AF_INET ||
2650 preferred_family == AF_INET6) {
2653 mask2 = (1<<UDP_DB)|(1<<RAW_DB);
2654 } else if (preferred_family == AF_PACKET) {
2656 } else if (preferred_family == AF_UNIX) {
2658 } else if (preferred_family == AF_NETLINK) {
2659 mask2 = (1<<NETLINK_DB);
2665 current_filter.dbs = mask2;
2667 current_filter.dbs &= mask2;
2668 current_filter.families = (1<<preferred_family);
2671 current_filter.families = ~0;
2673 current_filter.families = default_filter.families;
2675 if (current_filter.dbs == 0) {
2676 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
2679 if (current_filter.families == 0) {
2680 fprintf(stderr, "ss: no families to show with such filter.\n");
2684 if (resolve_services && resolve_hosts &&
2685 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB))))
2686 init_service_resolver();
2688 /* Now parse filter... */
2689 if (argc == 0 && filter_fp) {
2690 if (ssfilter_parse(¤t_filter.f, 0, NULL, filter_fp))
2695 if (strcmp(*argv, "state") == 0) {
2698 current_filter.states = 0;
2699 current_filter.states |= scan_state(*argv);
2701 } else if (strcmp(*argv, "exclude") == 0 ||
2702 strcmp(*argv, "excl") == 0) {
2705 current_filter.states = SS_ALL;
2706 current_filter.states &= ~scan_state(*argv);
2709 if (ssfilter_parse(¤t_filter.f, argc, argv, filter_fp))
2716 if (current_filter.states == 0) {
2717 fprintf(stderr, "ss: no socket states to show with such filter.\n");
2722 FILE *dump_fp = stdout;
2723 if (!(current_filter.dbs & (1<<TCP_DB))) {
2724 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
2727 if (dump_tcpdiag[0] != '-') {
2728 dump_fp = fopen(dump_tcpdiag, "w");
2729 if (!dump_tcpdiag) {
2730 perror("fopen dump file");
2734 tcp_show_netlink(¤t_filter, dump_fp);
2740 if (current_filter.dbs&(current_filter.dbs-1))
2744 if (current_filter.states&(current_filter.states-1))
2748 if (isatty(STDOUT_FILENO)) {
2751 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
2753 screen_width = w.ws_col;
2757 addrp_width = screen_width;
2758 addrp_width -= netid_width+1;
2759 addrp_width -= state_width+1;
2762 if (addrp_width&1) {
2765 else if (state_width)
2772 serv_width = resolve_services ? 7 : 5;
2774 if (addrp_width < 15+serv_width+1)
2775 addrp_width = 15+serv_width+1;
2777 addr_width = addrp_width - serv_width - 1;
2780 printf("%-*s ", netid_width, "Netid");
2782 printf("%-*s ", state_width, "State");
2783 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
2785 printf("%*s:%-*s %*s:%-*s\n",
2786 addr_width, "Local Address", serv_width, "Port",
2787 addr_width, "Peer Address", serv_width, "Port");
2789 //printf("%08x %08x %08x\n", current_filter.dbs, current_filter.states, current_filter.families);
2792 if (current_filter.dbs & (1<<NETLINK_DB))
2793 netlink_show(¤t_filter);
2794 if (current_filter.dbs & PACKET_DBM)
2795 packet_show(¤t_filter);
2796 if (current_filter.dbs & UNIX_DBM)
2797 unix_show(¤t_filter);
2798 if (current_filter.dbs & (1<<RAW_DB))
2799 raw_show(¤t_filter);
2800 if (current_filter.dbs & (1<<UDP_DB))
2801 udp_show(¤t_filter);
2802 if (current_filter.dbs & (1<<TCP_DB))
2803 tcp_show(¤t_filter);