2 * ss.c "sockstat", socket statistics
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
17 #include <sys/ioctl.h>
18 #include <sys/socket.h>
20 #include <netinet/in.h>
24 #include <arpa/inet.h>
33 #include "libnetlink.h"
36 #include <netinet/tcp.h>
37 #include <linux/inet_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;
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 static FILE *generic_proc_open(const char *env, const char *name)
116 const char *p = getenv(env);
120 p = getenv("PROC_ROOT") ? : "/proc";
121 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
125 return fopen(p, "r");
128 static FILE *net_tcp_open(void)
130 return generic_proc_open("PROC_NET_TCP", "net/tcp");
133 static FILE *net_tcp6_open(void)
135 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
138 static FILE *net_udp_open(void)
140 return generic_proc_open("PROC_NET_UDP", "net/udp");
143 static FILE *net_udp6_open(void)
145 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
148 static FILE *net_raw_open(void)
150 return generic_proc_open("PROC_NET_RAW", "net/raw");
153 static FILE *net_raw6_open(void)
155 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
158 static FILE *net_unix_open(void)
160 return generic_proc_open("PROC_NET_UNIX", "net/unix");
163 static FILE *net_packet_open(void)
165 return generic_proc_open("PROC_NET_PACKET", "net/packet");
168 static FILE *net_netlink_open(void)
170 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
173 static FILE *slabinfo_open(void)
175 return generic_proc_open("PROC_SLABINFO", "slabinfo");
178 static FILE *net_sockstat_open(void)
180 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
183 static FILE *net_sockstat6_open(void)
185 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
188 static FILE *net_snmp_open(void)
190 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
193 static FILE *ephemeral_ports_open(void)
195 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
199 struct user_ent *next;
206 #define USER_ENT_HASH_SIZE 256
207 struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE];
209 static int user_ent_hashfn(unsigned int ino)
211 int val = (ino >> 24) ^ (ino >> 16) ^ (ino >> 8) ^ ino;
213 return val & (USER_ENT_HASH_SIZE - 1);
216 static void user_ent_add(unsigned int ino, const char *process, int pid, int fd)
218 struct user_ent *p, **pp;
221 str_len = strlen(process) + 1;
222 p = malloc(sizeof(struct user_ent) + str_len);
229 strcpy(p->process, process);
231 pp = &user_ent_hash[user_ent_hashfn(ino)];
236 static void user_ent_hash_build(void)
238 const char *root = getenv("PROC_ROOT") ? : "/proc/";
245 if (strlen(name) == 0 || name[strlen(name)-1] != '/')
248 nameoff = strlen(name);
254 while ((d = readdir(dir)) != NULL) {
261 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
264 sprintf(name + nameoff, "%d/fd/", pid);
266 if ((dir1 = opendir(name)) == NULL)
271 while ((d1 = readdir(dir1)) != NULL) {
272 const char *pattern = "socket:[";
278 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
281 sprintf(name+pos, "%d", fd);
283 link_len = readlink(name, lnk, sizeof(lnk)-1);
286 lnk[link_len] = '\0';
288 if (strncmp(lnk, pattern, strlen(pattern)))
291 sscanf(lnk, "socket:[%u]", &ino);
293 if (process[0] == '\0') {
297 snprintf(tmp, sizeof(tmp), "%s/%d/stat", root, pid);
298 if ((fp = fopen(tmp, "r")) != NULL) {
299 fscanf(fp, "%*d (%[^)])", process);
304 user_ent_add(ino, process, pid, fd);
311 int find_users(unsigned ino, char *buf, int buflen)
320 p = user_ent_hash[user_ent_hashfn(ino)];
326 if (ptr - buf >= buflen - 1)
329 snprintf(ptr, buflen - (ptr - buf),
331 p->process, p->pid, p->fd);
345 /* Get stats from slab */
356 struct slabstat slabstat;
358 static const char *slabstat_ids[] =
367 int get_slabstat(struct slabstat *s)
373 memset(s, 0, sizeof(*s));
375 fp = slabinfo_open();
379 cnt = sizeof(*s)/sizeof(int);
381 fgets(buf, sizeof(buf), fp);
382 while(fgets(buf, sizeof(buf), fp) != NULL) {
384 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
385 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
386 sscanf(buf, "%*s%d", ((int *)s) + i);
399 static const char *sstate_name[] = {
401 [TCP_ESTABLISHED] = "ESTAB",
402 [TCP_SYN_SENT] = "SYN-SENT",
403 [TCP_SYN_RECV] = "SYN-RECV",
404 [TCP_FIN_WAIT1] = "FIN-WAIT-1",
405 [TCP_FIN_WAIT2] = "FIN-WAIT-2",
406 [TCP_TIME_WAIT] = "TIME-WAIT",
407 [TCP_CLOSE] = "UNCONN",
408 [TCP_CLOSE_WAIT] = "CLOSE-WAIT",
409 [TCP_LAST_ACK] = "LAST-ACK",
410 [TCP_LISTEN] = "LISTEN",
411 [TCP_CLOSING] = "CLOSING",
414 static const char *sstate_namel[] = {
416 [TCP_ESTABLISHED] = "established",
417 [TCP_SYN_SENT] = "syn-sent",
418 [TCP_SYN_RECV] = "syn-recv",
419 [TCP_FIN_WAIT1] = "fin-wait-1",
420 [TCP_FIN_WAIT2] = "fin-wait-2",
421 [TCP_TIME_WAIT] = "time-wait",
422 [TCP_CLOSE] = "unconnected",
423 [TCP_CLOSE_WAIT] = "close-wait",
424 [TCP_LAST_ACK] = "last-ack",
425 [TCP_LISTEN] = "listening",
426 [TCP_CLOSING] = "closing",
444 unsigned long long sk;
445 int rto, ato, qack, cwnd, ssthresh;
448 static const char *tmr_name[] = {
457 const char *print_ms_timer(int timeout)
460 int secs, msecs, minutes;
466 msecs = timeout%1000;
470 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
477 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
480 sprintf(buf+strlen(buf), "%03dms", msecs);
484 const char *print_hz_timer(int timeout)
486 int hz = get_user_hz();
487 return print_ms_timer(((timeout*1000) + hz-1)/hz);
498 struct scache *rlist;
500 void init_service_resolver(void)
503 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
505 fgets(buf, sizeof(buf), fp);
506 while (fgets(buf, sizeof(buf), fp) != NULL) {
507 unsigned int progn, port;
508 char proto[128], prog[128];
509 if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
510 &port, prog+4) == 4) {
511 struct scache *c = malloc(sizeof(*c));
514 memcpy(prog, "rpc.", 4);
515 c->name = strdup(prog);
516 if (strcmp(proto, TCP_PROTO) == 0)
517 c->proto = TCP_PROTO;
518 else if (strcmp(proto, UDP_PROTO) == 0)
519 c->proto = UDP_PROTO;
531 static int ip_local_port_min, ip_local_port_max;
533 /* Even do not try default linux ephemeral port ranges:
534 * default /etc/services contains so much of useless crap
535 * wouldbe "allocated" to this area that resolution
536 * is really harmful. I shrug each time when seeing
537 * "socks" or "cfinger" in dumps.
539 static int is_ephemeral(int port)
541 if (!ip_local_port_min) {
542 FILE *f = ephemeral_ports_open();
545 &ip_local_port_min, &ip_local_port_max);
548 ip_local_port_min = 1024;
549 ip_local_port_max = 4999;
553 return (port >= ip_local_port_min && port<= ip_local_port_max);
557 const char *__resolve_service(int port)
561 for (c = rlist; c; c = c->next) {
562 if (c->port == port && c->proto == dg_proto)
566 if (!is_ephemeral(port)) {
573 se = getservbyport(htons(port), dg_proto);
582 const char *resolve_service(int port)
584 static char buf[128];
585 static struct scache cache[256];
593 if (resolve_services) {
594 if (dg_proto == RAW_PROTO) {
595 return inet_proto_n2a(port, buf, sizeof(buf));
599 int hash = (port^(((unsigned long)dg_proto)>>2))&255;
601 for (c = &cache[hash]; c; c = c->next) {
602 if (c->port == port &&
603 c->proto == dg_proto) {
610 if ((res = __resolve_service(port)) != NULL) {
611 if ((c = malloc(sizeof(*c))) == NULL)
622 c->name = strdup(res);
623 c->next = cache[hash].next;
624 cache[hash].next = c;
632 sprintf(buf, "%u", port);
636 void formatted_print(const inet_prefix *a, int port)
639 const char *ap = buf;
642 est_len = addr_width;
644 if (a->family == AF_INET) {
645 if (a->data[0] == 0) {
649 ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
652 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
653 est_len = strlen(ap);
654 if (est_len <= addr_width)
655 est_len = addr_width;
657 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
659 printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
666 struct aafilter *next;
669 int inet2_addr_match(const inet_prefix *a, const inet_prefix *p, int plen)
671 if (!inet_addr_match(a, p, plen))
674 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
675 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
677 if (p->family == AF_INET && a->family == AF_INET6) {
678 if (a->data[0] == 0 && a->data[1] == 0 &&
679 a->data[2] == htonl(0xffff)) {
680 inet_prefix tmp = *a;
681 tmp.data[0] = a->data[3];
682 return inet_addr_match(&tmp, p, plen);
688 int unix_match(const inet_prefix *a, const inet_prefix *p)
690 char *addr, *pattern;
691 memcpy(&addr, a->data, sizeof(addr));
692 memcpy(&pattern, p->data, sizeof(pattern));
697 return !fnmatch(pattern, addr, 0);
700 int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
705 static int low, high=65535;
707 if (s->local.family == AF_UNIX) {
709 memcpy(&p, s->local.data, sizeof(p));
710 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
711 strspn(p+1, "0123456789abcdef") == 5);
713 if (s->local.family == AF_PACKET)
714 return s->lport == 0 && s->local.data == 0;
715 if (s->local.family == AF_NETLINK)
719 FILE *fp = ephemeral_ports_open();
721 fscanf(fp, "%d%d", &low, &high);
725 return s->lport >= low && s->lport <= high;
729 struct aafilter *a = (void*)f->pred;
730 if (a->addr.family == AF_UNIX)
731 return unix_match(&s->remote, &a->addr);
732 if (a->port != -1 && a->port != s->rport)
734 if (a->addr.bitlen) {
736 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
738 } while ((a = a->next) != NULL);
745 struct aafilter *a = (void*)f->pred;
746 if (a->addr.family == AF_UNIX)
747 return unix_match(&s->local, &a->addr);
748 if (a->port != -1 && a->port != s->lport)
750 if (a->addr.bitlen) {
752 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
754 } while ((a = a->next) != NULL);
761 struct aafilter *a = (void*)f->pred;
762 return s->rport >= a->port;
766 struct aafilter *a = (void*)f->pred;
767 return s->rport <= a->port;
771 struct aafilter *a = (void*)f->pred;
772 return s->lport >= a->port;
776 struct aafilter *a = (void*)f->pred;
777 return s->lport <= a->port;
780 /* Yup. It is recursion. Sorry. */
782 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
784 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
786 return !run_ssfilter(f->pred, s);
792 /* Relocate external jumps by reloc. */
793 static void ssfilter_patch(char *a, int len, int reloc)
796 struct inet_diag_bc_op *op = (struct inet_diag_bc_op*)a;
806 static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
811 if (!(*bytecode=malloc(4))) abort();
812 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
818 struct aafilter *a = (void*)f->pred;
821 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
824 for (b=a; b; b=b->next) {
825 len += 4 + sizeof(struct inet_diag_hostcond);
826 if (a->addr.family == AF_INET6)
833 if (!(ptr = malloc(len))) abort();
835 for (b=a; b; b=b->next) {
836 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
837 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
838 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
839 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond*)(ptr+4);
841 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
842 cond->family = a->addr.family;
843 cond->port = a->port;
844 cond->prefix_len = a->addr.bitlen;
845 memcpy(cond->addr, a->addr.data, alen);
848 op = (struct inet_diag_bc_op *)ptr;
849 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
853 return ptr - *bytecode;
857 struct aafilter *x = (void*)f->pred;
858 if (!(*bytecode=malloc(8))) abort();
859 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
860 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
865 struct aafilter *x = (void*)f->pred;
866 if (!(*bytecode=malloc(8))) abort();
867 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
868 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
873 struct aafilter *x = (void*)f->pred;
874 if (!(*bytecode=malloc(8))) abort();
875 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
876 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
881 struct aafilter *x = (void*)f->pred;
882 if (!(*bytecode=malloc(8))) abort();
883 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
884 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
890 char *a1, *a2, *a, l1, l2;
891 l1 = ssfilter_bytecompile(f->pred, &a1);
892 l2 = ssfilter_bytecompile(f->post, &a2);
893 if (!(a = malloc(l1+l2))) abort();
895 memcpy(a+l1, a2, l2);
897 ssfilter_patch(a, l1, l2);
903 char *a1, *a2, *a, l1, l2;
904 l1 = ssfilter_bytecompile(f->pred, &a1);
905 l2 = ssfilter_bytecompile(f->post, &a2);
906 if (!(a = malloc(l1+l2+4))) abort();
908 memcpy(a+l1+4, a2, l2);
910 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
917 l1 = ssfilter_bytecompile(f->pred, &a1);
918 if (!(a = malloc(l1+4))) abort();
921 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
930 static int remember_he(struct aafilter *a, struct hostent *he)
932 char **ptr = he->h_addr_list;
936 if (he->h_addrtype == AF_INET)
938 else if (he->h_addrtype == AF_INET6)
944 struct aafilter *b = a;
945 if (a->addr.bitlen) {
946 if ((b = malloc(sizeof(*b))) == NULL)
952 memcpy(b->addr.data, *ptr, len);
953 b->addr.bytelen = len;
954 b->addr.bitlen = len*8;
955 b->addr.family = he->h_addrtype;
962 static int get_dns_host(struct aafilter *a, const char *addr, int fam)
973 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
975 cnt = remember_he(a, he);
976 if (fam == AF_UNSPEC) {
977 he = gethostbyname2(addr, AF_INET6);
979 cnt += remember_he(a, he);
984 static int xll_initted = 0;
986 static void xll_init(void)
988 struct rtnl_handle rth;
995 static const char *xll_index_to_name(int index)
999 return ll_index_to_name(index);
1002 static int xll_name_to_index(const char *dev)
1006 return ll_name_to_index(dev);
1009 void *parse_hostcond(char *addr)
1013 struct aafilter *res;
1014 int fam = preferred_family;
1016 memset(&a, 0, sizeof(a));
1019 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
1021 a.addr.family = AF_UNIX;
1022 if (strncmp(addr, "unix:", 5) == 0)
1025 a.addr.bitlen = 8*strlen(p);
1026 memcpy(a.addr.data, &p, sizeof(p));
1030 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
1031 a.addr.family = AF_PACKET;
1033 if (strncmp(addr, "link:", 5) == 0)
1035 port = strchr(addr, ':');
1038 if (port[1] && strcmp(port+1, "*")) {
1039 if (get_integer(&a.port, port+1, 0)) {
1040 if ((a.port = xll_name_to_index(port+1)) <= 0)
1045 if (addr[0] && strcmp(addr, "*")) {
1048 if (ll_proto_a2n(&tmp, addr))
1050 a.addr.data[0] = ntohs(tmp);
1055 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
1056 a.addr.family = AF_NETLINK;
1058 if (strncmp(addr, "netlink:", 8) == 0)
1060 port = strchr(addr, ':');
1063 if (port[1] && strcmp(port+1, "*")) {
1064 if (get_integer(&a.port, port+1, 0)) {
1065 if (strcmp(port+1, "kernel") == 0)
1072 if (addr[0] && strcmp(addr, "*")) {
1074 if (get_u32(a.addr.data, addr, 0)) {
1075 if (strcmp(addr, "rtnl") == 0)
1077 else if (strcmp(addr, "fw") == 0)
1079 else if (strcmp(addr, "tcpdiag") == 0)
1088 if (strncmp(addr, "inet:", 5) == 0) {
1091 } else if (strncmp(addr, "inet6:", 6) == 0) {
1096 /* URL-like literal [] */
1097 if (addr[0] == '[') {
1099 if ((port = strchr(addr, ']')) == NULL)
1102 } else if (addr[0] == '*') {
1105 port = strrchr(strchr(addr, '/') ? : addr, ':');
1107 if (port && *port) {
1111 if (*port && *port != '*') {
1112 if (get_integer(&a.port, port, 0)) {
1113 struct servent *se1 = NULL;
1114 struct servent *se2 = NULL;
1115 if (current_filter.dbs&(1<<UDP_DB))
1116 se1 = getservbyname(port, UDP_PROTO);
1117 if (current_filter.dbs&(1<<TCP_DB))
1118 se2 = getservbyname(port, TCP_PROTO);
1119 if (se1 && se2 && se1->s_port != se2->s_port) {
1120 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1126 a.port = ntohs(se1->s_port);
1129 for (s = rlist; s; s = s->next) {
1130 if ((s->proto == UDP_PROTO &&
1131 (current_filter.dbs&(1<<UDP_DB))) ||
1132 (s->proto == TCP_PROTO &&
1133 (current_filter.dbs&(1<<TCP_DB)))) {
1134 if (s->name && strcmp(s->name, port) == 0) {
1135 if (a.port > 0 && a.port != s->port) {
1136 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1144 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1151 if (addr && *addr && *addr != '*') {
1152 if (get_prefix_1(&a.addr, addr, fam)) {
1153 if (get_dns_host(&a, addr, fam)) {
1154 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1161 res = malloc(sizeof(*res));
1163 memcpy(res, &a, sizeof(a));
1167 static int tcp_show_line(char *line, const struct filter *f, int family)
1170 char *loc, *rem, *data;
1175 if ((p = strchr(line, ':')) == NULL)
1179 if ((p = strchr(loc, ':')) == NULL)
1184 if ((p = strchr(rem, ':')) == NULL)
1190 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1192 if (!(f->states & (1<<state)))
1196 s.local.family = s.remote.family = family;
1197 if (family == AF_INET) {
1198 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1199 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1200 s.local.bytelen = s.remote.bytelen = 4;
1202 sscanf(loc, "%08x%08x%08x%08x:%x",
1208 sscanf(rem, "%08x%08x%08x%08x:%x",
1214 s.local.bytelen = s.remote.bytelen = 16;
1217 if (f->f && run_ssfilter(f->f, &s) == 0)
1221 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
1222 &s.state, &s.wq, &s.rq,
1223 &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1224 &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1225 &s.cwnd, &s.ssthresh, opt);
1238 printf("%-*s ", netid_width, "tcp");
1240 printf("%-*s ", state_width, sstate_name[s.state]);
1242 printf("%-6d %-6d ", s.rq, s.wq);
1244 formatted_print(&s.local, s.lport);
1245 formatted_print(&s.remote, s.rport);
1251 printf(" timer:(%s,%s,%d)",
1253 print_hz_timer(s.timeout),
1254 s.timer != 1 ? s.probes : s.retrs);
1258 int hz = get_user_hz();
1259 if (s.rto && s.rto != 3*hz)
1260 printf(" rto:%g", (double)s.rto/hz);
1262 printf(" ato:%g", (double)s.ato/hz);
1264 printf(" cwnd:%d", s.cwnd);
1265 if (s.ssthresh != -1)
1266 printf(" ssthresh:%d", s.ssthresh);
1268 printf(" qack:%d", s.qack/2);
1274 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1275 printf(" users:(%s)", ubuf);
1279 printf(" uid:%u", (unsigned)s.uid);
1280 printf(" ino:%u", s.ino);
1281 printf(" sk:%llx", s.sk);
1283 printf(" opt:\"%s\"", opt);
1290 static int generic_record_read(FILE *fp,
1291 int (*worker)(char*, const struct filter *, int),
1292 const struct filter *f, int fam)
1297 if (fgets(line, sizeof(line), fp) == NULL)
1300 while (fgets(line, sizeof(line), fp) != NULL) {
1301 int n = strlen(line);
1302 if (n == 0 || line[n-1] != '\n') {
1308 if (worker(line, f, fam) < 0)
1313 return ferror(fp) ? -1 : 0;
1316 static char *sprint_bw(char *buf, double bw)
1319 sprintf(buf,"%.1fM", bw / 1000000.);
1320 else if (bw > 1000.)
1321 sprintf(buf,"%.1fK", bw / 1000.);
1323 sprintf(buf, "%g", bw);
1328 static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r)
1330 struct rtattr * tb[INET_DIAG_MAX+1];
1334 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr*)(r+1),
1335 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1337 if (tb[INET_DIAG_MEMINFO]) {
1338 const struct inet_diag_meminfo *minfo
1339 = RTA_DATA(tb[INET_DIAG_MEMINFO]);
1340 printf(" mem:(r%u,w%u,f%u,t%u)",
1347 if (tb[INET_DIAG_INFO]) {
1348 struct tcp_info *info;
1349 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
1351 /* workaround for older kernels with less fields */
1352 if (len < sizeof(*info)) {
1353 info = alloca(sizeof(*info));
1354 memset(info, 0, sizeof(*info));
1355 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
1357 info = RTA_DATA(tb[INET_DIAG_INFO]);
1360 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1362 if (info->tcpi_options & TCPI_OPT_SACK)
1364 if (info->tcpi_options & TCPI_OPT_ECN)
1366 if (info->tcpi_options & TCPI_OPT_ECN_SEEN)
1370 if (tb[INET_DIAG_CONG])
1371 printf(" %s", (char *) RTA_DATA(tb[INET_DIAG_CONG]));
1373 if (info->tcpi_options & TCPI_OPT_WSCALE)
1374 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1375 info->tcpi_rcv_wscale);
1376 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1377 printf(" rto:%g", (double)info->tcpi_rto/1000);
1379 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1380 (double)info->tcpi_rttvar/1000);
1382 printf(" ato:%g", (double)info->tcpi_ato/1000);
1383 if (info->tcpi_snd_cwnd != 2)
1384 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1385 if (info->tcpi_snd_ssthresh < 0xFFFF)
1386 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1388 rtt = (double) info->tcpi_rtt;
1389 if (tb[INET_DIAG_VEGASINFO]) {
1390 const struct tcpvegas_info *vinfo
1391 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
1393 if (vinfo->tcpv_enabled &&
1394 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
1395 rtt = vinfo->tcpv_rtt;
1398 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1399 printf(" send %sbps",
1400 sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1401 (double) info->tcpi_snd_mss * 8000000.
1405 if (info->tcpi_rcv_rtt)
1406 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1407 if (info->tcpi_rcv_space)
1408 printf(" rcv_space:%d", info->tcpi_rcv_space);
1413 static int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
1415 struct inet_diag_msg *r = NLMSG_DATA(nlh);
1418 s.state = r->idiag_state;
1419 s.local.family = s.remote.family = r->idiag_family;
1420 s.lport = ntohs(r->id.idiag_sport);
1421 s.rport = ntohs(r->id.idiag_dport);
1422 if (s.local.family == AF_INET) {
1423 s.local.bytelen = s.remote.bytelen = 4;
1425 s.local.bytelen = s.remote.bytelen = 16;
1427 memcpy(s.local.data, r->id.idiag_src, s.local.bytelen);
1428 memcpy(s.remote.data, r->id.idiag_dst, s.local.bytelen);
1430 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1434 printf("%-*s ", netid_width, "tcp");
1436 printf("%-*s ", state_width, sstate_name[s.state]);
1438 printf("%-6d %-6d ", r->idiag_rqueue, r->idiag_wqueue);
1440 formatted_print(&s.local, s.lport);
1441 formatted_print(&s.remote, s.rport);
1444 if (r->idiag_timer) {
1445 if (r->idiag_timer > 4)
1447 printf(" timer:(%s,%s,%d)",
1448 tmr_name[r->idiag_timer],
1449 print_ms_timer(r->idiag_expires),
1455 if (find_users(r->idiag_inode, ubuf, sizeof(ubuf)) > 0)
1456 printf(" users:(%s)", ubuf);
1460 printf(" uid:%u", (unsigned)r->idiag_uid);
1461 printf(" ino:%u", r->idiag_inode);
1463 if (r->id.idiag_cookie[1] != 0)
1464 printf("%08x", r->id.idiag_cookie[1]);
1465 printf("%08x", r->id.idiag_cookie[0]);
1467 if (show_mem || show_tcpinfo) {
1469 tcp_show_info(nlh, r);
1477 static int tcp_show_netlink(struct filter *f, FILE *dump_fp, int socktype)
1480 struct sockaddr_nl nladdr;
1482 struct nlmsghdr nlh;
1483 struct inet_diag_req r;
1490 struct iovec iov[3];
1492 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
1495 memset(&nladdr, 0, sizeof(nladdr));
1496 nladdr.nl_family = AF_NETLINK;
1498 req.nlh.nlmsg_len = sizeof(req);
1499 req.nlh.nlmsg_type = socktype;
1500 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1501 req.nlh.nlmsg_pid = 0;
1502 req.nlh.nlmsg_seq = 123456;
1503 memset(&req.r, 0, sizeof(req.r));
1504 req.r.idiag_family = AF_INET;
1505 req.r.idiag_states = f->states;
1507 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
1510 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1511 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1512 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
1515 iov[0] = (struct iovec){
1517 .iov_len = sizeof(req)
1520 bclen = ssfilter_bytecompile(f->f, &bc);
1521 rta.rta_type = INET_DIAG_REQ_BYTECODE;
1522 rta.rta_len = RTA_LENGTH(bclen);
1523 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1524 iov[2] = (struct iovec){ bc, bclen };
1525 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1528 msg = (struct msghdr) {
1529 .msg_name = (void*)&nladdr,
1530 .msg_namelen = sizeof(nladdr),
1532 .msg_iovlen = f->f ? 3 : 1,
1535 if (sendmsg(fd, &msg, 0) < 0)
1538 iov[0] = (struct iovec){
1540 .iov_len = sizeof(buf)
1547 msg = (struct msghdr) {
1548 (void*)&nladdr, sizeof(nladdr),
1554 status = recvmsg(fd, &msg, 0);
1563 fprintf(stderr, "EOF on netlink\n");
1568 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1570 h = (struct nlmsghdr*)buf;
1571 while (NLMSG_OK(h, status)) {
1573 struct inet_diag_msg *r = NLMSG_DATA(h);
1575 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1576 h->nlmsg_seq != 123456)
1579 if (h->nlmsg_type == NLMSG_DONE)
1581 if (h->nlmsg_type == NLMSG_ERROR) {
1582 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1583 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1584 fprintf(stderr, "ERROR truncated\n");
1586 errno = -err->error;
1587 perror("TCPDIAG answers");
1592 if (!(f->families & (1<<r->idiag_family))) {
1593 h = NLMSG_NEXT(h, status);
1596 err = tcp_show_sock(h, NULL);
1602 h = NLMSG_NEXT(h, status);
1604 if (msg.msg_flags & MSG_TRUNC) {
1605 fprintf(stderr, "Message truncated\n");
1609 fprintf(stderr, "!!!Remnant of size %d\n", status);
1616 static int tcp_show_netlink_file(struct filter *f)
1621 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1622 perror("fopen($TCPDIAG_FILE)");
1628 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1630 status = fread(buf, 1, sizeof(*h), fp);
1632 perror("Reading header from $TCPDIAG_FILE");
1635 if (status != sizeof(*h)) {
1636 perror("Unexpected EOF reading $TCPDIAG_FILE");
1640 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1643 perror("Reading $TCPDIAG_FILE");
1646 if (status + sizeof(*h) < h->nlmsg_len) {
1647 perror("Unexpected EOF reading $TCPDIAG_FILE");
1651 /* The only legal exit point */
1652 if (h->nlmsg_type == NLMSG_DONE)
1655 if (h->nlmsg_type == NLMSG_ERROR) {
1656 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1657 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1658 fprintf(stderr, "ERROR truncated\n");
1660 errno = -err->error;
1661 perror("TCPDIAG answered");
1666 err = tcp_show_sock(h, f);
1672 static int tcp_show(struct filter *f, int socktype)
1676 int bufsize = 64*1024;
1678 dg_proto = TCP_PROTO;
1680 if (getenv("TCPDIAG_FILE"))
1681 return tcp_show_netlink_file(f);
1683 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1684 && tcp_show_netlink(f, NULL, socktype) == 0)
1687 /* Sigh... We have to parse /proc/net/tcp... */
1690 /* Estimate amount of sockets and try to allocate
1691 * huge buffer to read all the table at one read.
1692 * Limit it by 16MB though. The assumption is: as soon as
1693 * kernel was able to hold information about N connections,
1694 * it is able to give us some memory for snapshot.
1697 int guess = slabstat.socks+slabstat.tcp_syns;
1698 if (f->states&(1<<SS_TIME_WAIT))
1699 guess += slabstat.tcp_tws;
1700 if (guess > (16*1024*1024)/128)
1701 guess = (16*1024*1024)/128;
1703 if (guess > bufsize)
1706 while (bufsize >= 64*1024) {
1707 if ((buf = malloc(bufsize)) != NULL)
1716 if (f->families & (1<<AF_INET)) {
1717 if ((fp = net_tcp_open()) == NULL)
1720 setbuffer(fp, buf, bufsize);
1721 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
1726 if ((f->families & (1<<AF_INET6)) &&
1727 (fp = net_tcp6_open()) != NULL) {
1728 setbuffer(fp, buf, bufsize);
1729 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
1739 int saved_errno = errno;
1744 errno = saved_errno;
1750 int dgram_show_line(char *line, const struct filter *f, int family)
1753 char *loc, *rem, *data;
1758 if ((p = strchr(line, ':')) == NULL)
1762 if ((p = strchr(loc, ':')) == NULL)
1767 if ((p = strchr(rem, ':')) == NULL)
1773 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1775 if (!(f->states & (1<<state)))
1779 s.local.family = s.remote.family = family;
1780 if (family == AF_INET) {
1781 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1782 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1783 s.local.bytelen = s.remote.bytelen = 4;
1785 sscanf(loc, "%08x%08x%08x%08x:%x",
1791 sscanf(rem, "%08x%08x%08x%08x:%x",
1797 s.local.bytelen = s.remote.bytelen = 16;
1800 if (f->f && run_ssfilter(f->f, &s) == 0)
1804 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
1805 &s.state, &s.wq, &s.rq,
1807 &s.refcnt, &s.sk, opt);
1813 printf("%-*s ", netid_width, dg_proto);
1815 printf("%-*s ", state_width, sstate_name[s.state]);
1817 printf("%-6d %-6d ", s.rq, s.wq);
1819 formatted_print(&s.local, s.lport);
1820 formatted_print(&s.remote, s.rport);
1824 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1825 printf(" users:(%s)", ubuf);
1830 printf(" uid=%u", (unsigned)s.uid);
1831 printf(" ino=%u", s.ino);
1832 printf(" sk=%llx", s.sk);
1834 printf(" opt:\"%s\"", opt);
1842 int udp_show(struct filter *f)
1846 dg_proto = UDP_PROTO;
1848 if (f->families&(1<<AF_INET)) {
1849 if ((fp = net_udp_open()) == NULL)
1851 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
1856 if ((f->families&(1<<AF_INET6)) &&
1857 (fp = net_udp6_open()) != NULL) {
1858 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
1866 int saved_errno = errno;
1869 errno = saved_errno;
1874 int raw_show(struct filter *f)
1878 dg_proto = RAW_PROTO;
1880 if (f->families&(1<<AF_INET)) {
1881 if ((fp = net_raw_open()) == NULL)
1883 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
1888 if ((f->families&(1<<AF_INET6)) &&
1889 (fp = net_raw6_open()) != NULL) {
1890 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
1898 int saved_errno = errno;
1901 errno = saved_errno;
1909 struct unixstat *next;
1921 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
1922 SS_ESTABLISHED, SS_CLOSING };
1925 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
1927 void unix_list_free(struct unixstat *list)
1930 struct unixstat *s = list;
1938 void unix_list_print(struct unixstat *list, struct filter *f)
1943 for (s = list; s; s = s->next) {
1944 if (!(f->states & (1<<s->state)))
1946 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
1948 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
1954 for (p = list; p; p = p->next) {
1955 if (s->peer == p->ino)
1961 peer = p->name ? : "*";
1967 tst.local.family = AF_UNIX;
1968 tst.remote.family = AF_UNIX;
1969 memcpy(tst.local.data, &s->name, sizeof(s->name));
1970 if (strcmp(peer, "*") == 0)
1971 memset(tst.remote.data, 0, sizeof(peer));
1973 memcpy(tst.remote.data, &peer, sizeof(peer));
1974 if (run_ssfilter(f->f, &tst) == 0)
1979 printf("%-*s ", netid_width,
1980 s->type == SOCK_STREAM ? "u_str" : "u_dgr");
1982 printf("%-*s ", state_width, sstate_name[s->state]);
1983 printf("%-6d %-6d ", s->rq, s->wq);
1984 printf("%*s %-*d %*s %-*d",
1985 addr_width, s->name ? : "*", serv_width, s->ino,
1986 addr_width, peer, serv_width, s->peer);
1989 if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
1990 printf(" users:(%s)", ubuf);
1996 int unix_show(struct filter *f)
2003 struct unixstat *list = NULL;
2005 if ((fp = net_unix_open()) == NULL)
2007 fgets(buf, sizeof(buf)-1, fp);
2009 if (memcmp(buf, "Peer", 4) == 0)
2013 while (fgets(buf, sizeof(buf)-1, fp)) {
2014 struct unixstat *u, **insp;
2017 if (!(u = malloc(sizeof(*u))))
2021 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
2022 &u->peer, &u->rq, &u->wq, &flags, &u->type,
2023 &u->state, &u->ino, name) < 8)
2026 if (flags&(1<<16)) {
2027 u->state = SS_LISTEN;
2029 u->state = unix_state_map[u->state-1];
2030 if (u->type == SOCK_DGRAM &&
2031 u->state == SS_CLOSE &&
2033 u->state = SS_ESTABLISHED;
2044 if (u->type < (*insp)->type ||
2045 (u->type == (*insp)->type &&
2046 u->ino < (*insp)->ino))
2048 insp = &(*insp)->next;
2054 if ((u->name = malloc(strlen(name)+1)) == NULL)
2056 strcpy(u->name, name);
2058 if (++cnt > MAX_UNIX_REMEMBER) {
2059 unix_list_print(list, f);
2060 unix_list_free(list);
2067 unix_list_print(list, f);
2068 unix_list_free(list);
2077 int packet_show(struct filter *f)
2088 unsigned long long sk;
2090 if (!(f->states & (1<<SS_CLOSE)))
2093 if ((fp = net_packet_open()) == NULL)
2095 fgets(buf, sizeof(buf)-1, fp);
2097 while (fgets(buf, sizeof(buf)-1, fp)) {
2098 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2100 &type, &prot, &iface, &state,
2103 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2105 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2109 tst.local.family = AF_PACKET;
2110 tst.remote.family = AF_PACKET;
2113 tst.local.data[0] = prot;
2114 tst.remote.data[0] = 0;
2115 if (run_ssfilter(f->f, &tst) == 0)
2120 printf("%-*s ", netid_width,
2121 type == SOCK_RAW ? "p_raw" : "p_dgr");
2123 printf("%-*s ", state_width, "UNCONN");
2124 printf("%-6d %-6d ", rq, 0);
2126 printf("%*s:", addr_width, "*");
2129 printf("%*s:", addr_width,
2130 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2133 printf("%-*s ", serv_width, "*");
2135 printf("%-*s ", serv_width, xll_index_to_name(iface));
2138 addr_width, "", serv_width, "");
2142 if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2143 printf(" users:(%s)", ubuf);
2146 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2154 int netlink_show(struct filter *f)
2161 unsigned long long sk, cb;
2163 if (!(f->states & (1<<SS_CLOSE)))
2166 if ((fp = net_netlink_open()) == NULL)
2168 fgets(buf, sizeof(buf)-1, fp);
2170 while (fgets(buf, sizeof(buf)-1, fp)) {
2171 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2173 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2177 tst.local.family = AF_NETLINK;
2178 tst.remote.family = AF_NETLINK;
2181 tst.local.data[0] = prot;
2182 tst.remote.data[0] = 0;
2183 if (run_ssfilter(f->f, &tst) == 0)
2188 printf("%-*s ", netid_width, "nl");
2190 printf("%-*s ", state_width, "UNCONN");
2191 printf("%-6d %-6d ", rq, wq);
2192 if (resolve_services && prot == 0)
2193 printf("%*s:", addr_width, "rtnl");
2194 else if (resolve_services && prot == 3)
2195 printf("%*s:", addr_width, "fw");
2196 else if (resolve_services && prot == 4)
2197 printf("%*s:", addr_width, "tcpdiag");
2199 printf("%*d:", addr_width, prot);
2201 printf("%-*s ", serv_width, "*");
2202 } else if (resolve_services) {
2206 printf("%-*s ", serv_width, "kernel");
2207 } else if (pid > 0) {
2210 sprintf(procname, "%s/%d/stat",
2211 getenv("PROC_ROOT") ? : "/proc", pid);
2212 if ((fp = fopen(procname, "r")) != NULL) {
2213 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2214 sprintf(procname+strlen(procname), "/%d", pid);
2215 printf("%-*s ", serv_width, procname);
2222 printf("%-*d ", serv_width, pid);
2224 printf("%-*d ", serv_width, pid);
2227 addr_width, "", serv_width, "");
2230 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2243 int get_snmp_int(char *proto, char *key, int *result)
2247 int protolen = strlen(proto);
2248 int keylen = strlen(key);
2252 if ((fp = net_snmp_open()) == NULL)
2255 while (fgets(buf, sizeof(buf), fp) != NULL) {
2258 if (memcmp(buf, proto, protolen))
2260 while ((p = strchr(p, ' ')) != NULL) {
2263 if (memcmp(p, key, keylen) == 0 &&
2264 (p[keylen] == ' ' || p[keylen] == '\n'))
2267 if (fgets(buf, sizeof(buf), fp) == NULL)
2269 if (memcmp(buf, proto, protolen))
2272 while ((p = strchr(p, ' ')) != NULL) {
2275 sscanf(p, "%d", result);
2288 /* Get stats from sockstat */
2309 static void get_sockstat_line(char *line, struct sockstat *s)
2311 char id[256], rem[256];
2313 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2316 if (strcmp(id, "sockets:") == 0)
2317 sscanf(rem, "%*s%d", &s->socks);
2318 else if (strcmp(id, "UDP:") == 0)
2319 sscanf(rem, "%*s%d", &s->udp4);
2320 else if (strcmp(id, "UDP6:") == 0)
2321 sscanf(rem, "%*s%d", &s->udp6);
2322 else if (strcmp(id, "RAW:") == 0)
2323 sscanf(rem, "%*s%d", &s->raw4);
2324 else if (strcmp(id, "RAW6:") == 0)
2325 sscanf(rem, "%*s%d", &s->raw6);
2326 else if (strcmp(id, "TCP6:") == 0)
2327 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2328 else if (strcmp(id, "FRAG:") == 0)
2329 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2330 else if (strcmp(id, "FRAG6:") == 0)
2331 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2332 else if (strcmp(id, "TCP:") == 0)
2333 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2335 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2338 int get_sockstat(struct sockstat *s)
2343 memset(s, 0, sizeof(*s));
2345 if ((fp = net_sockstat_open()) == NULL)
2347 while(fgets(buf, sizeof(buf), fp) != NULL)
2348 get_sockstat_line(buf, s);
2351 if ((fp = net_sockstat6_open()) == NULL)
2353 while(fgets(buf, sizeof(buf), fp) != NULL)
2354 get_sockstat_line(buf, s);
2360 int print_summary(void)
2365 if (get_sockstat(&s) < 0)
2366 perror("ss: get_sockstat");
2367 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2368 perror("ss: get_snmpstat");
2370 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2372 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2373 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2375 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2378 s.tcp_tws, slabstat.tcp_tws,
2383 printf("Transport Total IP IPv6\n");
2384 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2385 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2386 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2387 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2388 printf("INET %-9d %-9d %-9d\n",
2389 s.raw4+s.udp4+s.tcp4_hashed+
2390 s.raw6+s.udp6+s.tcp6_hashed,
2391 s.raw4+s.udp4+s.tcp4_hashed,
2392 s.raw6+s.udp6+s.tcp6_hashed);
2393 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2400 static void _usage(FILE *dest)
2403 "Usage: ss [ OPTIONS ]\n"
2404 " ss [ OPTIONS ] [ FILTER ]\n"
2405 " -h, --help this message\n"
2406 " -V, --version output version information\n"
2407 " -n, --numeric don't resolve service names\n"
2408 " -r, --resolve resolve host names\n"
2409 " -a, --all display all sockets\n"
2410 " -l, --listening display listening sockets\n"
2411 " -o, --options show timer information\n"
2412 " -e, --extended show detailed socket information\n"
2413 " -m, --memory show socket memory usage\n"
2414 " -p, --processes show process using socket\n"
2415 " -i, --info show internal TCP information\n"
2416 " -s, --summary show socket usage summary\n"
2418 " -4, --ipv4 display only IP version 4 sockets\n"
2419 " -6, --ipv6 display only IP version 6 sockets\n"
2420 " -0, --packet display PACKET sockets\n"
2421 " -t, --tcp display only TCP sockets\n"
2422 " -u, --udp display only UDP sockets\n"
2423 " -d, --dccp display only DCCP sockets\n"
2424 " -w, --raw display only RAW sockets\n"
2425 " -x, --unix display only Unix domain sockets\n"
2426 " -f, --family=FAMILY display sockets of type FAMILY\n"
2428 " -A, --query=QUERY, --socket=QUERY\n"
2429 " QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2431 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
2432 " -F, --filter=FILE read filter information from FILE\n"
2433 " FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2437 static void help(void) __attribute__((noreturn));
2438 static void help(void)
2444 static void usage(void) __attribute__((noreturn));
2445 static void usage(void)
2452 int scan_state(const char *state)
2455 if (strcasecmp(state, "close") == 0 ||
2456 strcasecmp(state, "closed") == 0)
2457 return (1<<SS_CLOSE);
2458 if (strcasecmp(state, "syn-rcv") == 0)
2459 return (1<<SS_SYN_RECV);
2460 if (strcasecmp(state, "established") == 0)
2461 return (1<<SS_ESTABLISHED);
2462 if (strcasecmp(state, "all") == 0)
2464 if (strcasecmp(state, "connected") == 0)
2465 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2466 if (strcasecmp(state, "synchronized") == 0)
2467 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2468 if (strcasecmp(state, "bucket") == 0)
2469 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2470 if (strcasecmp(state, "big") == 0)
2471 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2472 for (i=0; i<SS_MAX; i++) {
2473 if (strcasecmp(state, sstate_namel[i]) == 0)
2479 static const struct option long_opts[] = {
2480 { "numeric", 0, 0, 'n' },
2481 { "resolve", 0, 0, 'r' },
2482 { "options", 0, 0, 'o' },
2483 { "extended", 0, 0, 'e' },
2484 { "memory", 0, 0, 'm' },
2485 { "info", 0, 0, 'i' },
2486 { "processes", 0, 0, 'p' },
2487 { "dccp", 0, 0, 'd' },
2488 { "tcp", 0, 0, 't' },
2489 { "udp", 0, 0, 'u' },
2490 { "raw", 0, 0, 'w' },
2491 { "unix", 0, 0, 'x' },
2492 { "all", 0, 0, 'a' },
2493 { "listening", 0, 0, 'l' },
2494 { "ipv4", 0, 0, '4' },
2495 { "ipv6", 0, 0, '6' },
2496 { "packet", 0, 0, '0' },
2497 { "family", 1, 0, 'f' },
2498 { "socket", 1, 0, 'A' },
2499 { "query", 1, 0, 'A' },
2500 { "summary", 0, 0, 's' },
2501 { "diag", 1, 0, 'D' },
2502 { "filter", 1, 0, 'F' },
2503 { "version", 0, 0, 'V' },
2504 { "help", 0, 0, 'h' },
2509 int main(int argc, char *argv[])
2515 const char *dump_tcpdiag = NULL;
2516 FILE *filter_fp = NULL;
2519 memset(¤t_filter, 0, sizeof(current_filter));
2521 current_filter.states = default_filter.states;
2523 while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spf:miA:D:F:vV",
2524 long_opts, NULL)) != EOF) {
2527 resolve_services = 0;
2547 user_ent_hash_build();
2550 current_filter.dbs |= (1<<DCCP_DB);
2554 current_filter.dbs |= (1<<TCP_DB);
2558 current_filter.dbs |= (1<<UDP_DB);
2562 current_filter.dbs |= (1<<RAW_DB);
2566 current_filter.dbs |= UNIX_DBM;
2570 current_filter.states = SS_ALL;
2573 current_filter.states = (1<<SS_LISTEN) | (1<<SS_CLOSE);
2576 preferred_family = AF_INET;
2579 preferred_family = AF_INET6;
2582 preferred_family = AF_PACKET;
2585 if (strcmp(optarg, "inet") == 0)
2586 preferred_family = AF_INET;
2587 else if (strcmp(optarg, "inet6") == 0)
2588 preferred_family = AF_INET6;
2589 else if (strcmp(optarg, "link") == 0)
2590 preferred_family = AF_PACKET;
2591 else if (strcmp(optarg, "unix") == 0)
2592 preferred_family = AF_UNIX;
2593 else if (strcmp(optarg, "netlink") == 0)
2594 preferred_family = AF_NETLINK;
2595 else if (strcmp(optarg, "help") == 0)
2598 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2606 current_filter.dbs = 0;
2612 if ((p1 = strchr(p, ',')) != NULL)
2614 if (strcmp(p, "all") == 0) {
2615 current_filter.dbs = ALL_DB;
2616 } else if (strcmp(p, "inet") == 0) {
2617 current_filter.dbs |= (1<<TCP_DB)|(1<<DCCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2618 } else if (strcmp(p, "udp") == 0) {
2619 current_filter.dbs |= (1<<UDP_DB);
2620 } else if (strcmp(p, "dccp") == 0) {
2621 current_filter.dbs |= (1<<DCCP_DB);
2622 } else if (strcmp(p, "tcp") == 0) {
2623 current_filter.dbs |= (1<<TCP_DB);
2624 } else if (strcmp(p, "raw") == 0) {
2625 current_filter.dbs |= (1<<RAW_DB);
2626 } else if (strcmp(p, "unix") == 0) {
2627 current_filter.dbs |= UNIX_DBM;
2628 } else if (strcasecmp(p, "unix_stream") == 0 ||
2629 strcmp(p, "u_str") == 0) {
2630 current_filter.dbs |= (1<<UNIX_ST_DB);
2631 } else if (strcasecmp(p, "unix_dgram") == 0 ||
2632 strcmp(p, "u_dgr") == 0) {
2633 current_filter.dbs |= (1<<UNIX_DG_DB);
2634 } else if (strcmp(p, "packet") == 0) {
2635 current_filter.dbs |= PACKET_DBM;
2636 } else if (strcmp(p, "packet_raw") == 0 ||
2637 strcmp(p, "p_raw") == 0) {
2638 current_filter.dbs |= (1<<PACKET_R_DB);
2639 } else if (strcmp(p, "packet_dgram") == 0 ||
2640 strcmp(p, "p_dgr") == 0) {
2641 current_filter.dbs |= (1<<PACKET_DG_DB);
2642 } else if (strcmp(p, "netlink") == 0) {
2643 current_filter.dbs |= (1<<NETLINK_DB);
2645 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2656 dump_tcpdiag = optarg;
2660 fprintf(stderr, "More than one filter file\n");
2663 if (optarg[0] == '-')
2666 filter_fp = fopen(optarg, "r");
2668 perror("fopen filter file");
2674 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
2687 get_slabstat(&slabstat);
2691 if (do_default && argc == 0)
2696 current_filter.dbs = default_filter.dbs;
2698 if (preferred_family == AF_UNSPEC) {
2699 if (!(current_filter.dbs&~UNIX_DBM))
2700 preferred_family = AF_UNIX;
2701 else if (!(current_filter.dbs&~PACKET_DBM))
2702 preferred_family = AF_PACKET;
2703 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
2704 preferred_family = AF_NETLINK;
2707 if (preferred_family != AF_UNSPEC) {
2709 if (preferred_family == AF_INET ||
2710 preferred_family == AF_INET6) {
2711 mask2= current_filter.dbs;
2712 } else if (preferred_family == AF_PACKET) {
2714 } else if (preferred_family == AF_UNIX) {
2716 } else if (preferred_family == AF_NETLINK) {
2717 mask2 = (1<<NETLINK_DB);
2723 current_filter.dbs = mask2;
2725 current_filter.dbs &= mask2;
2726 current_filter.families = (1<<preferred_family);
2729 current_filter.families = ~0;
2731 current_filter.families = default_filter.families;
2733 if (current_filter.dbs == 0) {
2734 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
2737 if (current_filter.families == 0) {
2738 fprintf(stderr, "ss: no families to show with such filter.\n");
2742 if (resolve_services && resolve_hosts &&
2743 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
2744 init_service_resolver();
2746 /* Now parse filter... */
2747 if (argc == 0 && filter_fp) {
2748 if (ssfilter_parse(¤t_filter.f, 0, NULL, filter_fp))
2753 if (strcmp(*argv, "state") == 0) {
2756 current_filter.states = 0;
2757 current_filter.states |= scan_state(*argv);
2759 } else if (strcmp(*argv, "exclude") == 0 ||
2760 strcmp(*argv, "excl") == 0) {
2763 current_filter.states = SS_ALL;
2764 current_filter.states &= ~scan_state(*argv);
2767 if (ssfilter_parse(¤t_filter.f, argc, argv, filter_fp))
2774 if (current_filter.states == 0) {
2775 fprintf(stderr, "ss: no socket states to show with such filter.\n");
2780 FILE *dump_fp = stdout;
2781 if (!(current_filter.dbs & (1<<TCP_DB))) {
2782 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
2785 if (dump_tcpdiag[0] != '-') {
2786 dump_fp = fopen(dump_tcpdiag, "w");
2787 if (!dump_tcpdiag) {
2788 perror("fopen dump file");
2792 tcp_show_netlink(¤t_filter, dump_fp, TCPDIAG_GETSOCK);
2798 if (current_filter.dbs&(current_filter.dbs-1))
2802 if (current_filter.states&(current_filter.states-1))
2806 if (isatty(STDOUT_FILENO)) {
2809 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
2811 screen_width = w.ws_col;
2815 addrp_width = screen_width;
2816 addrp_width -= netid_width+1;
2817 addrp_width -= state_width+1;
2820 if (addrp_width&1) {
2823 else if (state_width)
2830 serv_width = resolve_services ? 7 : 5;
2832 if (addrp_width < 15+serv_width+1)
2833 addrp_width = 15+serv_width+1;
2835 addr_width = addrp_width - serv_width - 1;
2838 printf("%-*s ", netid_width, "Netid");
2840 printf("%-*s ", state_width, "State");
2841 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
2843 printf("%*s:%-*s %*s:%-*s\n",
2844 addr_width, "Local Address", serv_width, "Port",
2845 addr_width, "Peer Address", serv_width, "Port");
2849 if (current_filter.dbs & (1<<NETLINK_DB))
2850 netlink_show(¤t_filter);
2851 if (current_filter.dbs & PACKET_DBM)
2852 packet_show(¤t_filter);
2853 if (current_filter.dbs & UNIX_DBM)
2854 unix_show(¤t_filter);
2855 if (current_filter.dbs & (1<<RAW_DB))
2856 raw_show(¤t_filter);
2857 if (current_filter.dbs & (1<<UDP_DB))
2858 udp_show(¤t_filter);
2859 if (current_filter.dbs & (1<<TCP_DB))
2860 tcp_show(¤t_filter, TCPDIAG_GETSOCK);
2861 if (current_filter.dbs & (1<<DCCP_DB))
2862 tcp_show(¤t_filter, DCCPDIAG_GETSOCK);