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 <linux/tcp.h>
37 #include <linux/tcp_diag.h>
39 int resolve_hosts = 0;
40 int resolve_services = 1;
41 int preferred_family = AF_UNSPEC;
55 static const char *TCP_PROTO = "tcp";
56 static const char *UDP_PROTO = "udp";
57 static const char *RAW_PROTO = "raw";
58 static const char *dg_proto = NULL;
73 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
74 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB))
75 #define ALL_DB ((1<<MAX_DB)-1)
93 #define SS_ALL ((1<<SS_MAX)-1)
105 struct filter default_filter = {
107 states: SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)),
108 families: (1<<AF_INET)|(1<<AF_INET6),
111 struct filter current_filter;
113 int generic_proc_open(char *env, char *name)
116 char *p = getenv(env);
118 p = getenv("PROC_ROOT") ? : "/proc";
119 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
122 return open(store, O_RDONLY);
125 int net_tcp_open(void)
127 return generic_proc_open("PROC_NET_TCP", "net/tcp");
130 int net_tcp6_open(void)
132 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
135 int net_udp_open(void)
137 return generic_proc_open("PROC_NET_UDP", "net/udp");
140 int net_udp6_open(void)
142 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
145 int net_raw_open(void)
147 return generic_proc_open("PROC_NET_RAW", "net/raw");
150 int net_raw6_open(void)
152 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
155 int net_unix_open(void)
157 return generic_proc_open("PROC_NET_UNIX", "net/unix");
160 int net_packet_open(void)
162 return generic_proc_open("PROC_NET_PACKET", "net/packet");
165 int net_netlink_open(void)
167 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
170 int slabinfo_open(void)
172 return generic_proc_open("PROC_SLABINFO", "slabinfo");
175 int net_sockstat_open(void)
177 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
180 int net_sockstat6_open(void)
182 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
185 int net_snmp_open(void)
187 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
190 int net_netstat_open(void)
192 return generic_proc_open("PROC_NET_NETSTAT", "net/netstat");
195 int ephemeral_ports_open(void)
197 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
200 int find_users(int ino, char *buf, int buflen)
214 sprintf(pattern, "socket:[%d]", ino);
215 pattern_len = strlen(pattern);
217 strncpy(name, getenv("PROC_ROOT") ? : "/proc/", sizeof(name)/2);
218 name[sizeof(name)/2] = 0;
219 if (strlen(name) == 0 ||
220 name[strlen(name)-1] != '/')
222 nameoff = strlen(name);
223 if ((dir = opendir(name)) == NULL)
226 while ((d = readdir(dir)) != NULL) {
234 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
237 sprintf(name+nameoff, "%d/fd/", pid);
239 if ((dir1 = opendir(name)) == NULL)
244 while ((d1 = readdir(dir1)) != NULL) {
248 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
251 sprintf(name+pos, "%d", fd);
252 n = readlink(name, lnk, sizeof(lnk)-1);
253 if (n != pattern_len ||
254 memcmp(lnk, pattern, n))
257 if (ptr-buf >= buflen-1)
260 if (process[0] == 0) {
263 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
264 getenv("PROC_ROOT") ? : "/proc", pid);
265 if ((fp = fopen(tmp, "r")) != NULL) {
266 fscanf(fp, "%*d (%[^)])", process);
271 snprintf(ptr, buflen-(ptr-buf), "(\"%s\",%d,%d),", process, pid, fd);
284 /* Get stats from slab */
295 struct slabstat slabstat;
297 static const char *slabstat_ids[] =
306 int get_slabstat(struct slabstat *s)
312 memset(s, 0, sizeof(*s));
314 if ((fp = fdopen(slabinfo_open(), "r")) == NULL)
317 cnt = sizeof(*s)/sizeof(int);
319 fgets(buf, sizeof(buf), fp);
320 while(fgets(buf, sizeof(buf), fp) != NULL) {
322 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
323 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
324 sscanf(buf, "%*s%d", ((int *)s) + i);
337 static const char *sstate_name[] = {
339 [TCP_ESTABLISHED] = "ESTAB",
340 [TCP_SYN_SENT] = "SYN-SENT",
341 [TCP_SYN_RECV] = "SYN-RECV",
342 [TCP_FIN_WAIT1] = "FIN-WAIT-1",
343 [TCP_FIN_WAIT2] = "FIN-WAIT-2",
344 [TCP_TIME_WAIT] = "TIME-WAIT",
345 [TCP_CLOSE] = "UNCONN",
346 [TCP_CLOSE_WAIT] = "CLOSE-WAIT",
347 [TCP_LAST_ACK] = "LAST-ACK",
348 [TCP_LISTEN] = "LISTEN",
349 [TCP_CLOSING] = "CLOSING",
352 static const char *sstate_namel[] = {
354 [TCP_ESTABLISHED] = "established",
355 [TCP_SYN_SENT] = "syn-sent",
356 [TCP_SYN_RECV] = "syn-recv",
357 [TCP_FIN_WAIT1] = "fin-wait-1",
358 [TCP_FIN_WAIT2] = "fin-wait-2",
359 [TCP_TIME_WAIT] = "time-wait",
360 [TCP_CLOSE] = "unconnected",
361 [TCP_CLOSE_WAIT] = "close-wait",
362 [TCP_LAST_ACK] = "last-ack",
363 [TCP_LISTEN] = "listening",
364 [TCP_CLOSING] = "closing",
382 unsigned long long sk;
383 int rto, ato, qack, cwnd, ssthresh;
386 static const char *tmr_name[] = {
395 const char *print_ms_timer(int timeout)
398 int secs, msecs, minutes;
404 msecs = timeout%1000;
408 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
415 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
418 sprintf(buf+strlen(buf), "%03dms", msecs);
422 const char *print_hz_timer(int timeout)
425 return print_ms_timer(((timeout*1000) + hz-1)/hz);
436 struct scache *rlist;
438 void init_service_resolver(void)
441 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
443 fgets(buf, sizeof(buf), fp);
444 while (fgets(buf, sizeof(buf), fp) != NULL) {
445 unsigned int progn, port;
446 char proto[128], prog[128];
447 if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
448 &port, prog+4) == 4) {
449 struct scache *c = malloc(sizeof(*c));
452 memcpy(prog, "rpc.", 4);
453 c->name = strdup(prog);
454 if (strcmp(proto, TCP_PROTO) == 0)
455 c->proto = TCP_PROTO;
456 else if (strcmp(proto, UDP_PROTO) == 0)
457 c->proto = UDP_PROTO;
468 static int ip_local_port_min, ip_local_port_max;
470 /* Even do not try default linux ephemeral port ranges:
471 * default /etc/services contains so much of useless crap
472 * wouldbe "allocated" to this area that resolution
473 * is really harmful. I shrug each time when seeing
474 * "socks" or "cfinger" in dumps.
476 static int is_ephemeral(int port)
478 if (!ip_local_port_min) {
479 FILE *f = fdopen(ephemeral_ports_open(), "r");
482 &ip_local_port_min, &ip_local_port_max);
485 ip_local_port_min = 1024;
486 ip_local_port_max = 4999;
490 return (port >= ip_local_port_min && port<= ip_local_port_max);
494 const char *__resolve_service(int port)
498 for (c = rlist; c; c = c->next) {
499 if (c->port == port && c->proto == dg_proto)
503 if (!is_ephemeral(port)) {
510 se = getservbyport(htons(port), dg_proto);
519 const char *resolve_service(int port)
521 static char buf[128];
522 static struct scache cache[256];
530 if (resolve_services) {
531 if (dg_proto == RAW_PROTO) {
532 return inet_proto_n2a(port, buf, sizeof(buf));
536 int hash = (port^(((unsigned long)dg_proto)>>2))&255;
538 for (c = &cache[hash]; c; c = c->next) {
539 if (c->port == port &&
540 c->proto == dg_proto) {
547 if ((res = __resolve_service(port)) != NULL) {
548 if ((c = malloc(sizeof(*c))) == NULL)
559 c->name = strdup(res);
560 c->next = cache[hash].next;
561 cache[hash].next = c;
569 sprintf(buf, "%u", port);
573 void formatted_print(const inet_prefix *a, int port)
576 const char *ap = buf;
579 est_len = addr_width;
581 if (a->family == AF_INET) {
582 if (a->data[0] == 0) {
586 ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
589 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
590 est_len = strlen(ap);
591 if (est_len <= addr_width)
592 est_len = addr_width;
594 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
596 printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
603 struct aafilter *next;
606 int inet2_addr_match(const inet_prefix *a, const inet_prefix *p, int plen)
608 if (!inet_addr_match(a, p, plen))
611 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
612 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
614 if (p->family == AF_INET && a->family == AF_INET6) {
615 if (a->data[0] == 0 && a->data[1] == 0 &&
616 a->data[2] == htonl(0xffff)) {
617 inet_prefix tmp = *a;
618 tmp.data[0] = a->data[3];
619 return inet_addr_match(&tmp, p, plen);
625 int unix_match(const inet_prefix *a, const inet_prefix *p)
627 char *addr, *pattern;
628 memcpy(&addr, a->data, sizeof(addr));
629 memcpy(&pattern, p->data, sizeof(pattern));
634 return !fnmatch(pattern, addr, 0);
637 int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
642 static int low, high=65535;
644 if (s->local.family == AF_UNIX) {
646 memcpy(&p, s->local.data, sizeof(p));
647 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
648 strspn(p+1, "0123456789abcdef") == 5);
650 if (s->local.family == AF_PACKET)
651 return s->lport == 0 && s->local.data == 0;
652 if (s->local.family == AF_NETLINK)
656 FILE *fp = fdopen(ephemeral_ports_open(), "r");
658 fscanf(fp, "%d%d", &low, &high);
662 return s->lport >= low && s->lport <= high;
666 struct aafilter *a = (void*)f->pred;
667 if (a->addr.family == AF_UNIX)
668 return unix_match(&s->remote, &a->addr);
669 if (a->port != -1 && a->port != s->rport)
671 if (a->addr.bitlen) {
673 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
675 } while ((a = a->next) != NULL);
682 struct aafilter *a = (void*)f->pred;
683 if (a->addr.family == AF_UNIX)
684 return unix_match(&s->local, &a->addr);
685 if (a->port != -1 && a->port != s->lport)
687 if (a->addr.bitlen) {
689 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
691 } while ((a = a->next) != NULL);
698 struct aafilter *a = (void*)f->pred;
699 return s->rport >= a->port;
703 struct aafilter *a = (void*)f->pred;
704 return s->rport <= a->port;
708 struct aafilter *a = (void*)f->pred;
709 return s->lport >= a->port;
713 struct aafilter *a = (void*)f->pred;
714 return s->lport <= a->port;
717 /* Yup. It is recursion. Sorry. */
719 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
721 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
723 return !run_ssfilter(f->pred, s);
729 /* Relocate external jumps by reloc. */
730 static void ssfilter_patch(char *a, int len, int reloc)
733 struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op*)a;
743 static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
748 if (!(*bytecode=malloc(4))) abort();
749 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_AUTO, 4, 8 };
755 struct aafilter *a = (void*)f->pred;
758 int code = (f->type == SSF_DCOND ? TCPDIAG_BC_D_COND : TCPDIAG_BC_S_COND);
761 for (b=a; b; b=b->next) {
762 len += 4 + sizeof(struct tcpdiag_hostcond);
763 if (a->addr.family == AF_INET6)
770 if (!(ptr = malloc(len))) abort();
772 for (b=a; b; b=b->next) {
773 struct tcpdiag_bc_op *op = (struct tcpdiag_bc_op *)ptr;
774 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
775 int oplen = alen + 4 + sizeof(struct tcpdiag_hostcond);
776 struct tcpdiag_hostcond *cond = (struct tcpdiag_hostcond*)(ptr+4);
778 *op = (struct tcpdiag_bc_op){ code, oplen, oplen+4 };
779 cond->family = a->addr.family;
780 cond->port = a->port;
781 cond->prefix_len = a->addr.bitlen;
782 memcpy(cond->addr, a->addr.data, alen);
785 op = (struct tcpdiag_bc_op *)ptr;
786 *op = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, len - (ptr-*bytecode)};
790 return ptr - *bytecode;
794 struct aafilter *x = (void*)f->pred;
795 if (!(*bytecode=malloc(8))) abort();
796 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_D_GE, 8, 12 };
797 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
802 struct aafilter *x = (void*)f->pred;
803 if (!(*bytecode=malloc(8))) abort();
804 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_D_LE, 8, 12 };
805 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
810 struct aafilter *x = (void*)f->pred;
811 if (!(*bytecode=malloc(8))) abort();
812 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_S_GE, 8, 12 };
813 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
818 struct aafilter *x = (void*)f->pred;
819 if (!(*bytecode=malloc(8))) abort();
820 ((struct tcpdiag_bc_op*)*bytecode)[0] = (struct tcpdiag_bc_op){ TCPDIAG_BC_S_LE, 8, 12 };
821 ((struct tcpdiag_bc_op*)*bytecode)[1] = (struct tcpdiag_bc_op){ 0, 0, x->port };
827 char *a1, *a2, *a, l1, l2;
828 l1 = ssfilter_bytecompile(f->pred, &a1);
829 l2 = ssfilter_bytecompile(f->post, &a2);
830 if (!(a = malloc(l1+l2))) abort();
832 memcpy(a+l1, a2, l2);
834 ssfilter_patch(a, l1, l2);
840 char *a1, *a2, *a, l1, l2;
841 l1 = ssfilter_bytecompile(f->pred, &a1);
842 l2 = ssfilter_bytecompile(f->post, &a2);
843 if (!(a = malloc(l1+l2+4))) abort();
845 memcpy(a+l1+4, a2, l2);
847 *(struct tcpdiag_bc_op*)(a+l1) = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, l2+4 };
854 l1 = ssfilter_bytecompile(f->pred, &a1);
855 if (!(a = malloc(l1+4))) abort();
858 *(struct tcpdiag_bc_op*)(a+l1) = (struct tcpdiag_bc_op){ TCPDIAG_BC_JMP, 4, 8 };
867 static int remember_he(struct aafilter *a, struct hostent *he)
869 char **ptr = he->h_addr_list;
873 if (he->h_addrtype == AF_INET)
875 else if (he->h_addrtype == AF_INET6)
881 struct aafilter *b = a;
882 if (a->addr.bitlen) {
883 if ((b = malloc(sizeof(*b))) == NULL)
889 memcpy(b->addr.data, *ptr, len);
890 b->addr.bytelen = len;
891 b->addr.bitlen = len*8;
892 b->addr.family = he->h_addrtype;
899 static int get_dns_host(struct aafilter *a, const char *addr, int fam)
910 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
912 cnt = remember_he(a, he);
913 if (fam == AF_UNSPEC) {
914 he = gethostbyname2(addr, AF_INET6);
916 cnt += remember_he(a, he);
921 static int xll_initted = 0;
923 static void xll_init(void)
925 struct rtnl_handle rth;
932 static const char *xll_index_to_name(int index)
936 return ll_index_to_name(index);
939 static int xll_name_to_index(const char *dev)
943 return ll_name_to_index(dev);
946 void *parse_hostcond(char *addr)
950 struct aafilter *res;
951 int fam = preferred_family;
953 memset(&a, 0, sizeof(a));
956 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
958 a.addr.family = AF_UNIX;
959 if (strncmp(addr, "unix:", 5) == 0)
962 a.addr.bitlen = 8*strlen(p);
963 memcpy(a.addr.data, &p, sizeof(p));
967 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
968 a.addr.family = AF_PACKET;
970 if (strncmp(addr, "link:", 5) == 0)
972 port = strchr(addr, ':');
975 if (port[1] && strcmp(port+1, "*")) {
976 if (get_integer(&a.port, port+1, 0)) {
977 if ((a.port = xll_name_to_index(port+1)) <= 0)
982 if (addr[0] && strcmp(addr, "*")) {
985 if (ll_proto_a2n(&tmp, addr))
987 a.addr.data[0] = ntohs(tmp);
992 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
993 a.addr.family = AF_NETLINK;
995 if (strncmp(addr, "netlink:", 8) == 0)
997 port = strchr(addr, ':');
1000 if (port[1] && strcmp(port+1, "*")) {
1001 if (get_integer(&a.port, port+1, 0)) {
1002 if (strcmp(port+1, "kernel") == 0)
1009 if (addr[0] && strcmp(addr, "*")) {
1011 if (get_u32(a.addr.data, addr, 0)) {
1012 if (strcmp(addr, "rtnl") == 0)
1014 else if (strcmp(addr, "fw") == 0)
1016 else if (strcmp(addr, "tcpdiag") == 0)
1025 if (strncmp(addr, "inet:", 5) == 0) {
1028 } else if (strncmp(addr, "inet6:", 6) == 0) {
1033 /* URL-like literal [] */
1034 if (addr[0] == '[') {
1036 if ((port = strchr(addr, ']')) == NULL)
1039 } else if (addr[0] == '*') {
1042 port = strrchr(strchr(addr, '/') ? : addr, ':');
1044 if (port && *port) {
1048 if (*port && *port != '*') {
1049 if (get_integer(&a.port, port, 0)) {
1050 struct servent *se1 = NULL;
1051 struct servent *se2 = NULL;
1052 if (current_filter.dbs&(1<<UDP_DB))
1053 se1 = getservbyname(port, UDP_PROTO);
1054 if (current_filter.dbs&(1<<TCP_DB))
1055 se2 = getservbyname(port, TCP_PROTO);
1056 if (se1 && se2 && se1->s_port != se2->s_port) {
1057 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1063 a.port = ntohs(se1->s_port);
1066 for (s = rlist; s; s = s->next) {
1067 if ((s->proto == UDP_PROTO &&
1068 (current_filter.dbs&(1<<UDP_DB))) ||
1069 (s->proto == TCP_PROTO &&
1070 (current_filter.dbs&(1<<TCP_DB)))) {
1071 if (s->name && strcmp(s->name, port) == 0) {
1072 if (a.port > 0 && a.port != s->port) {
1073 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1081 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1088 if (addr && *addr && *addr != '*') {
1089 if (get_prefix_1(&a.addr, addr, fam)) {
1090 if (get_dns_host(&a, addr, fam)) {
1091 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1098 res = malloc(sizeof(*res));
1100 memcpy(res, &a, sizeof(a));
1104 static int tcp_show_line(char *line, struct filter *f, int family)
1107 char *loc, *rem, *data;
1112 if ((p = strchr(line, ':')) == NULL)
1116 if ((p = strchr(loc, ':')) == NULL)
1121 if ((p = strchr(rem, ':')) == NULL)
1127 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1129 if (!(f->states & (1<<state)))
1133 s.local.family = s.remote.family = family;
1134 if (family == AF_INET) {
1135 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1136 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1137 s.local.bytelen = s.remote.bytelen = 4;
1139 sscanf(loc, "%08x%08x%08x%08x:%x",
1145 sscanf(rem, "%08x%08x%08x%08x:%x",
1151 s.local.bytelen = s.remote.bytelen = 16;
1154 if (f->f && run_ssfilter(f->f, &s) == 0)
1158 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %d %d %llx %d %d %d %d %d %[^\n]\n",
1159 &s.state, &s.wq, &s.rq,
1160 &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1161 &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1162 &s.cwnd, &s.ssthresh, opt);
1175 printf("%-*s ", netid_width, "tcp");
1177 printf("%-*s ", state_width, sstate_name[s.state]);
1179 printf("%-6d %-6d ", s.rq, s.wq);
1181 formatted_print(&s.local, s.lport);
1182 formatted_print(&s.remote, s.rport);
1188 printf(" timer:(%s,%s,%d)",
1190 print_hz_timer(s.timeout),
1191 s.timer != 1 ? s.probes : s.retrs);
1195 if (s.rto && s.rto != 3*get_hz())
1196 printf(" rto:%g", (double)s.rto/get_hz());
1198 printf(" ato:%g", (double)s.ato/get_hz());
1200 printf(" cwnd:%d", s.cwnd);
1201 if (s.ssthresh != -1)
1202 printf(" ssthresh:%d", s.ssthresh);
1204 printf(" qack:%d", s.qack/2);
1210 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1211 printf(" users:(%s)", ubuf);
1215 printf(" uid:%u", (unsigned)s.uid);
1216 printf(" ino:%u", (unsigned)s.ino);
1217 printf(" sk:%llx", s.sk);
1219 printf(" opt:\"%s\"", opt);
1226 static int generic_record_read(int fd, char *buf, int bufsize,
1227 int (*worker)(char*, struct filter *, int),
1228 struct filter *f, int fam)
1235 /* Load the first chunk and calculate record length from it. */
1236 n = read(fd, buf, bufsize);
1239 /* I _know_ that this is wrong, do not remind. :-)
1240 * But this works nowadays. */
1243 p = memchr(buf, '\n', n);
1244 if (p == NULL || (p-buf) >= n)
1245 goto outwrongformat;
1246 recsize = (p-buf)+1;
1250 while ((p+recsize) - buf <= n) {
1251 if (p[recsize-1] != '\n')
1252 goto outwrongformat;
1254 if (worker(p, f, fam) < 0)
1259 int remains = (buf+bufsize) - p;
1260 memcpy(buf, p, remains);
1262 n = read(fd, p, (buf+bufsize) - p);
1265 if (n < (buf+bufsize) - p) {
1269 goto outwrongformat;
1277 goto outwrongformat;
1290 static char *sprint_bw(char *buf, double bw)
1293 sprintf(buf,"%.1fM", bw / 1000000.);
1294 else if (bw > 1000.)
1295 sprintf(buf,"%.1fK", bw / 1000.);
1297 sprintf(buf, "%g", bw);
1302 static void tcp_show_info(const struct nlmsghdr *nlh, struct tcpdiagmsg *r)
1304 struct rtattr * tb[TCPDIAG_MAX+1];
1308 parse_rtattr(tb, TCPDIAG_MAX, (struct rtattr*)(r+1),
1309 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1311 if (tb[TCPDIAG_MEMINFO]) {
1312 const struct tcpdiag_meminfo *minfo
1313 = RTA_DATA(tb[TCPDIAG_MEMINFO]);
1314 printf(" mem:(r%u,w%u,f%u,t%u)",
1315 minfo->tcpdiag_rmem,
1316 minfo->tcpdiag_wmem,
1317 minfo->tcpdiag_fmem,
1318 minfo->tcpdiag_tmem);
1321 if (tb[TCPDIAG_INFO]) {
1322 struct tcp_info *info;
1323 int len = RTA_PAYLOAD(tb[TCPDIAG_INFO]);
1325 /* workaround for older kernels with less fields */
1326 if (len < sizeof(*info)) {
1327 info = alloca(sizeof(*info));
1328 memset(info, 0, sizeof(*info));
1329 memcpy(info, RTA_DATA(tb[TCPDIAG_INFO]), len);
1331 info = RTA_DATA(tb[TCPDIAG_INFO]);
1334 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1336 if (info->tcpi_options & TCPI_OPT_SACK)
1338 if (info->tcpi_options & TCPI_OPT_ECN)
1341 if (info->tcpi_options & TCPI_OPT_WSCALE)
1342 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1343 info->tcpi_rcv_wscale);
1344 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1345 printf(" rto:%g", (double)info->tcpi_rto/1000);
1347 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1348 (double)info->tcpi_rttvar/1000);
1350 printf(" ato:%g", (double)info->tcpi_ato/1000);
1351 if (info->tcpi_snd_cwnd != 2)
1352 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1353 if (info->tcpi_snd_ssthresh < 0xFFFF)
1354 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1356 rtt = (double) info->tcpi_rtt;
1357 if (tb[TCPDIAG_VEGASINFO]) {
1358 const struct tcpvegas_info *vinfo
1359 = RTA_DATA(tb[TCPDIAG_VEGASINFO]);
1361 if (vinfo->tcpv_enabled)
1364 if (vinfo->tcpv_rtt &&
1365 vinfo->tcpv_rtt != 0x7fffffff)
1366 rtt = vinfo->tcpv_rtt;
1369 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1370 printf(" send %sbps",
1371 sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1372 (double) info->tcpi_snd_mss * 8000000.
1376 if (info->tcpi_rcv_rtt)
1377 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1378 if (info->tcpi_rcv_space)
1379 printf(" rcv_space:%d", info->tcpi_rcv_space);
1384 int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
1386 struct tcpdiagmsg *r = NLMSG_DATA(nlh);
1389 s.state = r->tcpdiag_state;
1390 s.local.family = s.remote.family = r->tcpdiag_family;
1391 s.lport = ntohs(r->id.tcpdiag_sport);
1392 s.rport = ntohs(r->id.tcpdiag_dport);
1393 if (s.local.family == AF_INET) {
1394 s.local.bytelen = s.remote.bytelen = 4;
1396 s.local.bytelen = s.remote.bytelen = 16;
1398 memcpy(s.local.data, r->id.tcpdiag_src, s.local.bytelen);
1399 memcpy(s.remote.data, r->id.tcpdiag_dst, s.local.bytelen);
1401 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1405 printf("%-*s ", netid_width, "tcp");
1407 printf("%-*s ", state_width, sstate_name[s.state]);
1409 printf("%-6d %-6d ", r->tcpdiag_rqueue, r->tcpdiag_wqueue);
1411 formatted_print(&s.local, s.lport);
1412 formatted_print(&s.remote, s.rport);
1415 if (r->tcpdiag_timer) {
1416 if (r->tcpdiag_timer > 4)
1417 r->tcpdiag_timer = 5;
1418 printf(" timer:(%s,%s,%d)",
1419 tmr_name[r->tcpdiag_timer],
1420 print_ms_timer(r->tcpdiag_expires),
1421 r->tcpdiag_retrans);
1426 if (find_users(r->tcpdiag_inode, ubuf, sizeof(ubuf)) > 0)
1427 printf(" users:(%s)", ubuf);
1431 printf(" uid:%u", (unsigned)r->tcpdiag_uid);
1432 printf(" ino:%u", (unsigned)r->tcpdiag_inode);
1433 printf(" sk:%08x", r->id.tcpdiag_cookie[0]);
1434 if (r->id.tcpdiag_cookie[1] != 0)
1435 printf("%08x", r->id.tcpdiag_cookie[1]);
1437 if (show_mem || show_tcpinfo) {
1439 tcp_show_info(nlh, r);
1448 int tcp_show_netlink(struct filter *f, FILE *dump_fp)
1451 struct sockaddr_nl nladdr;
1453 struct nlmsghdr nlh;
1454 struct tcpdiagreq r;
1461 struct iovec iov[3];
1463 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TCPDIAG)) < 0)
1466 memset(&nladdr, 0, sizeof(nladdr));
1467 nladdr.nl_family = AF_NETLINK;
1469 req.nlh.nlmsg_len = sizeof(req);
1470 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
1471 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1472 req.nlh.nlmsg_pid = 0;
1473 req.nlh.nlmsg_seq = 123456;
1474 memset(&req.r, 0, sizeof(req.r));
1475 req.r.tcpdiag_family = AF_INET;
1476 req.r.tcpdiag_states = f->states;
1478 req.r.tcpdiag_ext |= (1<<(TCPDIAG_MEMINFO-1));
1481 req.r.tcpdiag_ext |= (1<<(TCPDIAG_INFO-1));
1482 req.r.tcpdiag_ext |= (1<<(TCPDIAG_VEGASINFO-1));
1485 iov[0] = (struct iovec){ &req, sizeof(req) };
1487 bclen = ssfilter_bytecompile(f->f, &bc);
1488 rta.rta_type = TCPDIAG_REQ_BYTECODE;
1489 rta.rta_len = RTA_LENGTH(bclen);
1490 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1491 iov[2] = (struct iovec){ bc, bclen };
1492 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1495 msg = (struct msghdr) {
1496 (void*)&nladdr, sizeof(nladdr),
1502 if (sendmsg(fd, &msg, 0) < 0)
1506 iov[0] = (struct iovec){ buf, sizeof(buf) };
1512 msg = (struct msghdr) {
1513 (void*)&nladdr, sizeof(nladdr),
1519 status = recvmsg(fd, &msg, 0);
1528 fprintf(stderr, "EOF on netlink\n");
1533 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1535 h = (struct nlmsghdr*)buf;
1536 while (NLMSG_OK(h, status)) {
1539 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1540 h->nlmsg_seq != 123456)
1543 if (h->nlmsg_type == NLMSG_DONE)
1545 if (h->nlmsg_type == NLMSG_ERROR) {
1546 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1547 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1548 fprintf(stderr, "ERROR truncated\n");
1550 errno = -err->error;
1551 perror("TCPDIAG answers");
1556 err = tcp_show_sock(h, NULL);
1562 h = NLMSG_NEXT(h, status);
1564 if (msg.msg_flags & MSG_TRUNC) {
1565 fprintf(stderr, "Message truncated\n");
1569 fprintf(stderr, "!!!Remnant of size %d\n", status);
1576 int tcp_show_netlink_file(struct filter *f)
1581 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1582 perror("fopen($TCPDIAG_FILE)");
1588 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1590 status = fread(buf, 1, sizeof(*h), fp);
1592 perror("Reading header from $TCPDIAG_FILE");
1595 if (status != sizeof(*h)) {
1596 perror("Unexpected EOF reading $TCPDIAG_FILE");
1600 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1603 perror("Reading $TCPDIAG_FILE");
1606 if (status + sizeof(*h) < h->nlmsg_len) {
1607 perror("Unexpected EOF reading $TCPDIAG_FILE");
1611 /* The only legal exit point */
1612 if (h->nlmsg_type == NLMSG_DONE)
1615 if (h->nlmsg_type == NLMSG_ERROR) {
1616 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1617 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1618 fprintf(stderr, "ERROR truncated\n");
1620 errno = -err->error;
1621 perror("TCPDIAG answered");
1626 err = tcp_show_sock(h, f);
1632 int tcp_show(struct filter *f)
1636 int bufsize = 64*1024;
1638 dg_proto = TCP_PROTO;
1640 if (getenv("TCPDIAG_FILE"))
1641 return tcp_show_netlink_file(f);
1643 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1644 && tcp_show_netlink(f, NULL) == 0)
1647 /* Sigh... We have to parse /proc/net/tcp... */
1649 /* Estimate amount of sockets and try to allocate
1650 * huge buffer to read all the table at one read.
1651 * Limit it by 16MB though. The assumption is: as soon as
1652 * kernel was able to hold information about N connections,
1653 * it is able to give us some memory for snapshot.
1656 int guess = slabstat.socks+slabstat.tcp_syns;
1657 if (f->states&(1<<SS_TIME_WAIT))
1658 guess += slabstat.tcp_tws;
1659 if (guess > (16*1024*1024)/128)
1660 guess = (16*1024*1024)/128;
1662 if (guess > bufsize)
1665 while (bufsize >= 64*1024) {
1666 if ((buf = malloc(bufsize)) != NULL)
1675 if (f->families & (1<<AF_INET)) {
1676 if ((fd = net_tcp_open()) < 0)
1678 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET))
1683 if ((f->families & (1<<AF_INET6)) &&
1684 (fd = net_tcp6_open()) >= 0) {
1685 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET6))
1695 int saved_errno = errno;
1700 errno = saved_errno;
1706 int dgram_show_line(char *line, struct filter *f, int family)
1709 char *loc, *rem, *data;
1714 if ((p = strchr(line, ':')) == NULL)
1718 if ((p = strchr(loc, ':')) == NULL)
1723 if ((p = strchr(rem, ':')) == NULL)
1729 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1731 if (!(f->states & (1<<state)))
1735 s.local.family = s.remote.family = family;
1736 if (family == AF_INET) {
1737 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1738 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1739 s.local.bytelen = s.remote.bytelen = 4;
1741 sscanf(loc, "%08x%08x%08x%08x:%x",
1747 sscanf(rem, "%08x%08x%08x%08x:%x",
1753 s.local.bytelen = s.remote.bytelen = 16;
1756 if (f->f && run_ssfilter(f->f, &s) == 0)
1760 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %d %d %llx %[^\n]\n",
1761 &s.state, &s.wq, &s.rq,
1763 &s.refcnt, &s.sk, opt);
1769 printf("%-*s ", netid_width, dg_proto);
1771 printf("%-*s ", state_width, sstate_name[s.state]);
1773 printf("%-6d %-6d ", s.rq, s.wq);
1775 formatted_print(&s.local, s.lport);
1776 formatted_print(&s.remote, s.rport);
1780 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1781 printf(" users:(%s)", ubuf);
1786 printf(" uid=%u", (unsigned)s.uid);
1787 printf(" ino=%u", (unsigned)s.ino);
1788 printf(" sk=%llx", s.sk);
1790 printf(" opt:\"%s\"", opt);
1798 int udp_show(struct filter *f)
1802 int bufsize = sizeof(buf);
1804 dg_proto = UDP_PROTO;
1806 if (f->families&(1<<AF_INET)) {
1807 if ((fd = net_udp_open()) < 0)
1809 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1814 if ((f->families&(1<<AF_INET6)) &&
1815 (fd = net_udp6_open()) >= 0) {
1816 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1824 int saved_errno = errno;
1827 errno = saved_errno;
1832 int raw_show(struct filter *f)
1836 int bufsize = sizeof(buf);
1838 dg_proto = RAW_PROTO;
1840 if (f->families&(1<<AF_INET)) {
1841 if ((fd = net_raw_open()) < 0)
1843 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1848 if ((f->families&(1<<AF_INET6)) &&
1849 (fd = net_raw6_open()) >= 0) {
1850 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1858 int saved_errno = errno;
1861 errno = saved_errno;
1869 struct unixstat *next;
1881 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
1882 SS_ESTABLISHED, SS_CLOSING };
1885 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
1887 void unix_list_free(struct unixstat *list)
1890 struct unixstat *s = list;
1898 void unix_list_print(struct unixstat *list, struct filter *f)
1903 for (s = list; s; s = s->next) {
1904 if (!(f->states & (1<<s->state)))
1906 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
1908 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
1914 for (p = list; p; p = p->next) {
1915 if (s->peer == p->ino)
1921 peer = p->name ? : "*";
1927 tst.local.family = AF_UNIX;
1928 tst.remote.family = AF_UNIX;
1929 memcpy(tst.local.data, &s->name, sizeof(s->name));
1930 if (strcmp(peer, "*") == 0)
1931 memset(tst.remote.data, 0, sizeof(peer));
1933 memcpy(tst.remote.data, &peer, sizeof(peer));
1934 if (run_ssfilter(f->f, &tst) == 0)
1939 printf("%-*s ", netid_width,
1940 s->type == SOCK_STREAM ? "u_str" : "u_dgr");
1942 printf("%-*s ", state_width, sstate_name[s->state]);
1943 printf("%-6d %-6d ", s->rq, s->wq);
1944 printf("%*s %-*d %*s %-*d",
1945 addr_width, s->name ? : "*", serv_width, s->ino,
1946 addr_width, peer, serv_width, s->peer);
1949 if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
1950 printf(" users:(%s)", ubuf);
1956 int unix_show(struct filter *f)
1963 struct unixstat *list = NULL;
1965 if ((fp = fdopen(net_unix_open(), "r")) == NULL)
1967 fgets(buf, sizeof(buf)-1, fp);
1969 if (memcmp(buf, "Peer", 4) == 0)
1973 while (fgets(buf, sizeof(buf)-1, fp)) {
1974 struct unixstat *u, **insp;
1977 if (!(u = malloc(sizeof(*u))))
1981 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
1982 &u->peer, &u->rq, &u->wq, &flags, &u->type,
1983 &u->state, &u->ino, name) < 8)
1986 if (flags&(1<<16)) {
1987 u->state = SS_LISTEN;
1989 u->state = unix_state_map[u->state-1];
1990 if (u->type == SOCK_DGRAM &&
1991 u->state == SS_CLOSE &&
1993 u->state = SS_ESTABLISHED;
2004 if (u->type < (*insp)->type ||
2005 (u->type == (*insp)->type &&
2006 u->ino < (*insp)->ino))
2008 insp = &(*insp)->next;
2014 if ((u->name = malloc(strlen(name)+1)) == NULL)
2016 strcpy(u->name, name);
2018 if (++cnt > MAX_UNIX_REMEMBER) {
2019 unix_list_print(list, f);
2020 unix_list_free(list);
2027 unix_list_print(list, f);
2028 unix_list_free(list);
2037 int packet_show(struct filter *f)
2048 unsigned long long sk;
2050 if (!(f->states & (1<<SS_CLOSE)))
2053 if ((fp = fdopen(net_packet_open(), "r")) == NULL)
2055 fgets(buf, sizeof(buf)-1, fp);
2057 while (fgets(buf, sizeof(buf)-1, fp)) {
2058 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2060 &type, &prot, &iface, &state,
2063 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2065 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2069 tst.local.family = AF_PACKET;
2070 tst.remote.family = AF_PACKET;
2073 tst.local.data[0] = prot;
2074 tst.remote.data[0] = 0;
2075 if (run_ssfilter(f->f, &tst) == 0)
2080 printf("%-*s ", netid_width,
2081 type == SOCK_RAW ? "p_raw" : "p_dgr");
2083 printf("%-*s ", state_width, "UNCONN");
2084 printf("%-6d %-6d ", rq, 0);
2086 printf("%*s:", addr_width, "*");
2089 printf("%*s:", addr_width,
2090 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2093 printf("%-*s ", serv_width, "*");
2095 printf("%-*s ", serv_width, xll_index_to_name(iface));
2098 addr_width, "", serv_width, "");
2102 if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2103 printf(" users:(%s)", ubuf);
2106 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2114 int netlink_show(struct filter *f)
2121 unsigned long long sk, cb;
2123 if (!(f->states & (1<<SS_CLOSE)))
2126 if ((fp = fdopen(net_netlink_open(), "r")) == NULL)
2128 fgets(buf, sizeof(buf)-1, fp);
2130 while (fgets(buf, sizeof(buf)-1, fp)) {
2131 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2133 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2137 tst.local.family = AF_NETLINK;
2138 tst.remote.family = AF_NETLINK;
2141 tst.local.data[0] = prot;
2142 tst.remote.data[0] = 0;
2143 if (run_ssfilter(f->f, &tst) == 0)
2148 printf("%-*s ", netid_width, "nl");
2150 printf("%-*s ", state_width, "UNCONN");
2151 printf("%-6d %-6d ", rq, wq);
2152 if (resolve_services && prot == 0)
2153 printf("%*s:", addr_width, "rtnl");
2154 else if (resolve_services && prot == 3)
2155 printf("%*s:", addr_width, "fw");
2156 else if (resolve_services && prot == 4)
2157 printf("%*s:", addr_width, "tcpdiag");
2159 printf("%*d:", addr_width, prot);
2161 printf("%-*s ", serv_width, "*");
2162 } else if (resolve_services) {
2166 printf("%-*s ", serv_width, "kernel");
2167 } else if (pid > 0) {
2170 sprintf(procname, "%s/%d/stat",
2171 getenv("PROC_ROOT") ? : "/proc", pid);
2172 if ((fp = fopen(procname, "r")) != NULL) {
2173 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2174 sprintf(procname+strlen(procname), "/%d", pid);
2175 printf("%-*s ", serv_width, procname);
2182 printf("%-*d ", serv_width, pid);
2184 printf("%-*d ", serv_width, pid);
2187 addr_width, "", serv_width, "");
2190 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2203 int get_snmp_int(char *proto, char *key, int *result)
2207 int protolen = strlen(proto);
2208 int keylen = strlen(key);
2212 if ((fp = fdopen(net_snmp_open(), "r")) == NULL)
2215 while (fgets(buf, sizeof(buf), fp) != NULL) {
2218 if (memcmp(buf, proto, protolen))
2220 while ((p = strchr(p, ' ')) != NULL) {
2223 if (memcmp(p, key, keylen) == 0 &&
2224 (p[keylen] == ' ' || p[keylen] == '\n'))
2227 if (fgets(buf, sizeof(buf), fp) == NULL)
2229 if (memcmp(buf, proto, protolen))
2232 while ((p = strchr(p, ' ')) != NULL) {
2235 sscanf(p, "%d", result);
2248 /* Get stats from sockstat */
2269 static void get_sockstat_line(char *line, struct sockstat *s)
2271 char id[256], rem[256];
2273 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2276 if (strcmp(id, "sockets:") == 0)
2277 sscanf(rem, "%*s%d", &s->socks);
2278 else if (strcmp(id, "UDP:") == 0)
2279 sscanf(rem, "%*s%d", &s->udp4);
2280 else if (strcmp(id, "UDP6:") == 0)
2281 sscanf(rem, "%*s%d", &s->udp6);
2282 else if (strcmp(id, "RAW:") == 0)
2283 sscanf(rem, "%*s%d", &s->raw4);
2284 else if (strcmp(id, "RAW6:") == 0)
2285 sscanf(rem, "%*s%d", &s->raw6);
2286 else if (strcmp(id, "TCP6:") == 0)
2287 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2288 else if (strcmp(id, "FRAG:") == 0)
2289 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2290 else if (strcmp(id, "FRAG6:") == 0)
2291 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2292 else if (strcmp(id, "TCP:") == 0)
2293 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2295 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2298 int get_sockstat(struct sockstat *s)
2303 memset(s, 0, sizeof(*s));
2305 if ((fp = fdopen(net_sockstat_open(), "r")) == NULL)
2307 while(fgets(buf, sizeof(buf), fp) != NULL)
2308 get_sockstat_line(buf, s);
2311 if ((fp = fdopen(net_sockstat6_open(), "r")) == NULL)
2313 while(fgets(buf, sizeof(buf), fp) != NULL)
2314 get_sockstat_line(buf, s);
2320 int print_summary(void)
2325 if (get_sockstat(&s) < 0)
2326 perror("ss: get_sockstat");
2327 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2328 perror("ss: get_snmpstat");
2330 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2332 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2333 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2335 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2338 s.tcp_tws, slabstat.tcp_tws,
2343 printf("Transport Total IP IPv6\n");
2344 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2345 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2346 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2347 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2348 printf("INET %-9d %-9d %-9d\n",
2349 s.raw4+s.udp4+s.tcp4_hashed+
2350 s.raw6+s.udp6+s.tcp6_hashed,
2351 s.raw4+s.udp4+s.tcp4_hashed,
2352 s.raw6+s.udp6+s.tcp6_hashed);
2353 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2361 static void usage(void) __attribute__((noreturn));
2363 static void usage(void)
2366 "Usage: ss [ OPTIONS ]\n"
2367 " ss [ OPTIONS ] [ FILTER ]\n"
2368 " -h, --help this message\n"
2369 " -V, --version output version information\n"
2370 " -n, --numeric don't resolve service names\n"
2371 " -r, --resolve resolve host names\n"
2372 " -a, --all display all sockets\n"
2373 " -l, --listening display listening sockets\n"
2374 " -o, --options show timer information\n"
2375 " -e, --extended show detailed socket information\n"
2376 " -m, --memory show socket memory usage\n"
2377 " -p, --processes show process using socket\n"
2378 " -i, --info show internal TCP information\n"
2379 " -s, --summary show socket usage summary\n"
2381 " -4, --ipv4 display only IP version 4 sockets\n"
2382 " -6, --ipv6 display only IP version 6 sockets\n"
2383 " -0, --packet display PACKET sockets\n"
2384 " -t, --tcp display only TCP sockets\n"
2385 " -u, --udp display only UDP sockets\n"
2386 " -w, --raw display only RAW sockets\n"
2387 " -x, --unix display only Unix domain sockets\n"
2388 " -f, --family=FAMILY display sockets of type FAMILY\n"
2390 " -A, --query=QUERY\n"
2391 " QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2393 " -F, --filter=FILE read filter information from FILE\n"
2394 " FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2400 int scan_state(const char *state)
2403 if (strcasecmp(state, "close") == 0 ||
2404 strcasecmp(state, "closed") == 0)
2405 return (1<<SS_CLOSE);
2406 if (strcasecmp(state, "syn-rcv") == 0)
2407 return (1<<SS_SYN_RECV);
2408 if (strcasecmp(state, "established") == 0)
2409 return (1<<SS_ESTABLISHED);
2410 if (strcasecmp(state, "all") == 0)
2412 if (strcasecmp(state, "connected") == 0)
2413 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2414 if (strcasecmp(state, "synchronized") == 0)
2415 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2416 if (strcasecmp(state, "bucket") == 0)
2417 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2418 if (strcasecmp(state, "big") == 0)
2419 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2420 for (i=0; i<SS_MAX; i++) {
2421 if (strcasecmp(state, sstate_namel[i]) == 0)
2427 static const struct option long_opts[] = {
2428 { "numeric", 0, 0, 'n' },
2429 { "resolve", 0, 0, 'r' },
2430 { "options", 0, 0, 'o' },
2431 { "extended", 0, 0, 'e' },
2432 { "memory", 0, 0, 'm' },
2433 { "info", 0, 0, 'i' },
2434 { "processes", 0, 0, 'p' },
2435 { "tcp", 0, 0, 't' },
2436 { "udp", 0, 0, 'u' },
2437 { "raw", 0, 0, 'w' },
2438 { "unix", 0, 0, 'x' },
2439 { "all", 0, 0, 'a' },
2440 { "listening", 0, 0, 'l' },
2441 { "ipv4", 0, 0, '4' },
2442 { "ipv6", 0, 0, '6' },
2443 { "packet", 0, 0, '0' },
2444 { "family", 1, 0, 'f' },
2445 { "socket", 1, 0, 'A' },
2446 { "summary", 0, 0, 's' },
2447 { "diag", 0, 0, 'D' },
2448 { "filter", 1, 0, 'F' },
2449 { "version", 0, 0, 'V' },
2450 { "help", 0, 0, 'h' },
2455 int main(int argc, char *argv[])
2461 const char *dump_tcpdiag = NULL;
2462 FILE *filter_fp = NULL;
2465 memset(¤t_filter, 0, sizeof(current_filter));
2467 current_filter.states = default_filter.states;
2469 while ((ch = getopt_long(argc, argv, "haletuwxnro460spf:miA:D:F:vV",
2470 long_opts, NULL)) != EOF) {
2473 resolve_services = 0;
2495 current_filter.dbs |= (1<<TCP_DB);
2499 current_filter.dbs |= (1<<UDP_DB);
2503 current_filter.dbs |= (1<<RAW_DB);
2507 current_filter.dbs |= UNIX_DBM;
2511 current_filter.states = SS_ALL;
2514 current_filter.states = (1<<SS_LISTEN);
2517 preferred_family = AF_INET;
2520 preferred_family = AF_INET6;
2523 preferred_family = AF_PACKET;
2526 if (strcmp(optarg, "inet") == 0)
2527 preferred_family = AF_INET;
2528 else if (strcmp(optarg, "inet6") == 0)
2529 preferred_family = AF_INET6;
2530 else if (strcmp(optarg, "link") == 0)
2531 preferred_family = AF_PACKET;
2532 else if (strcmp(optarg, "unix") == 0)
2533 preferred_family = AF_UNIX;
2534 else if (strcmp(optarg, "netlink") == 0)
2535 preferred_family = AF_NETLINK;
2536 else if (strcmp(optarg, "help") == 0)
2539 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2547 current_filter.dbs = 0;
2553 if ((p1 = strchr(p, ',')) != NULL)
2555 if (strcmp(p, "all") == 0) {
2556 current_filter.dbs = ALL_DB;
2557 } else if (strcmp(p, "inet") == 0) {
2558 current_filter.dbs |= (1<<TCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2559 } else if (strcmp(p, "udp") == 0) {
2560 current_filter.dbs |= (1<<UDP_DB);
2561 } else if (strcmp(p, "tcp") == 0) {
2562 current_filter.dbs |= (1<<TCP_DB);
2563 } else if (strcmp(p, "raw") == 0) {
2564 current_filter.dbs |= (1<<RAW_DB);
2565 } else if (strcmp(p, "unix") == 0) {
2566 current_filter.dbs |= UNIX_DBM;
2567 } else if (strcasecmp(p, "unix_stream") == 0 ||
2568 strcmp(p, "u_str") == 0) {
2569 current_filter.dbs |= (1<<UNIX_ST_DB);
2570 } else if (strcasecmp(p, "unix_dgram") == 0 ||
2571 strcmp(p, "u_dgr") == 0) {
2572 current_filter.dbs |= (1<<UNIX_DG_DB);
2573 } else if (strcmp(p, "packet") == 0) {
2574 current_filter.dbs |= PACKET_DBM;
2575 } else if (strcmp(p, "packet_raw") == 0 ||
2576 strcmp(p, "p_raw") == 0) {
2577 current_filter.dbs |= (1<<PACKET_R_DB);
2578 } else if (strcmp(p, "packet_dgram") == 0 ||
2579 strcmp(p, "p_dgr") == 0) {
2580 current_filter.dbs |= (1<<PACKET_DG_DB);
2581 } else if (strcmp(p, "netlink") == 0) {
2582 current_filter.dbs |= (1<<NETLINK_DB);
2584 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2595 dump_tcpdiag = optarg;
2599 fprintf(stderr, "More than one filter file\n");
2602 if (optarg[0] == '-')
2605 filter_fp = fopen(optarg, "r");
2607 perror("fopen filter file");
2613 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
2625 get_slabstat(&slabstat);
2629 if (do_default && argc == 0)
2634 current_filter.dbs = default_filter.dbs;
2636 if (preferred_family == AF_UNSPEC) {
2637 if (!(current_filter.dbs&~UNIX_DBM))
2638 preferred_family = AF_UNIX;
2639 else if (!(current_filter.dbs&~PACKET_DBM))
2640 preferred_family = AF_PACKET;
2641 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
2642 preferred_family = AF_NETLINK;
2645 if (preferred_family != AF_UNSPEC) {
2647 if (preferred_family == AF_INET ||
2648 preferred_family == AF_INET6) {
2651 mask2 = (1<<UDP_DB)|(1<<RAW_DB);
2652 } else if (preferred_family == AF_PACKET) {
2654 } else if (preferred_family == AF_UNIX) {
2656 } else if (preferred_family == AF_NETLINK) {
2657 mask2 = (1<<NETLINK_DB);
2663 current_filter.dbs = mask2;
2665 current_filter.dbs &= mask2;
2666 current_filter.families = (1<<preferred_family);
2669 current_filter.families = ~0;
2671 current_filter.families = default_filter.families;
2673 if (current_filter.dbs == 0) {
2674 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
2677 if (current_filter.families == 0) {
2678 fprintf(stderr, "ss: no families to show with such filter.\n");
2682 if (resolve_services && resolve_hosts &&
2683 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB))))
2684 init_service_resolver();
2686 /* Now parse filter... */
2687 if (argc == 0 && filter_fp) {
2688 if (ssfilter_parse(¤t_filter.f, 0, NULL, filter_fp))
2693 if (strcmp(*argv, "state") == 0) {
2696 current_filter.states = 0;
2697 current_filter.states |= scan_state(*argv);
2699 } else if (strcmp(*argv, "exclude") == 0 ||
2700 strcmp(*argv, "excl") == 0) {
2703 current_filter.states = SS_ALL;
2704 current_filter.states &= ~scan_state(*argv);
2707 if (ssfilter_parse(¤t_filter.f, argc, argv, filter_fp))
2714 if (current_filter.states == 0) {
2715 fprintf(stderr, "ss: no socket states to show with such filter.\n");
2720 FILE *dump_fp = stdout;
2721 if (!(current_filter.dbs & (1<<TCP_DB))) {
2722 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
2725 if (dump_tcpdiag[0] != '-') {
2726 dump_fp = fopen(dump_tcpdiag, "w");
2727 if (!dump_tcpdiag) {
2728 perror("fopen dump file");
2732 tcp_show_netlink(¤t_filter, dump_fp);
2738 if (current_filter.dbs&(current_filter.dbs-1))
2742 if (current_filter.states&(current_filter.states-1))
2746 if (isatty(STDOUT_FILENO)) {
2749 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
2751 screen_width = w.ws_col;
2755 addrp_width = screen_width;
2756 addrp_width -= netid_width+1;
2757 addrp_width -= state_width+1;
2760 if (addrp_width&1) {
2763 else if (state_width)
2770 serv_width = resolve_services ? 7 : 5;
2772 if (addrp_width < 15+serv_width+1)
2773 addrp_width = 15+serv_width+1;
2775 addr_width = addrp_width - serv_width - 1;
2778 printf("%-*s ", netid_width, "Netid");
2780 printf("%-*s ", state_width, "State");
2781 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
2783 printf("%*s:%-*s %*s:%-*s\n",
2784 addr_width, "Local Address", serv_width, "Port",
2785 addr_width, "Peer Address", serv_width, "Port");
2787 //printf("%08x %08x %08x\n", current_filter.dbs, current_filter.states, current_filter.families);
2790 if (current_filter.dbs & (1<<NETLINK_DB))
2791 netlink_show(¤t_filter);
2792 if (current_filter.dbs & PACKET_DBM)
2793 packet_show(¤t_filter);
2794 if (current_filter.dbs & UNIX_DBM)
2795 unix_show(¤t_filter);
2796 if (current_filter.dbs & (1<<RAW_DB))
2797 raw_show(¤t_filter);
2798 if (current_filter.dbs & (1<<UDP_DB))
2799 udp_show(¤t_filter);
2800 if (current_filter.dbs & (1<<TCP_DB))
2801 tcp_show(¤t_filter);