[armoring feature] apply the system hardening options.
[platform/upstream/iproute2.git] / misc / ss.c
1 /*
2  * ss.c         "sockstat", socket statistics
3  *
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.
8  *
9  * Authors:     Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10  */
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <syslog.h>
16 #include <fcntl.h>
17 #include <sys/ioctl.h>
18 #include <sys/socket.h>
19 #include <sys/uio.h>
20 #include <netinet/in.h>
21 #include <string.h>
22 #include <errno.h>
23 #include <netdb.h>
24 #include <arpa/inet.h>
25 #include <dirent.h>
26 #include <fnmatch.h>
27 #include <getopt.h>
28
29 #include "utils.h"
30 #include "rt_names.h"
31 #include "ll_map.h"
32 #include "libnetlink.h"
33 #include "SNAPSHOT.h"
34
35 #include <netinet/tcp.h>
36 #include <linux/sock_diag.h>
37 #include <linux/inet_diag.h>
38 #include <linux/unix_diag.h>
39
40 int resolve_hosts = 0;
41 int resolve_services = 1;
42 int preferred_family = AF_UNSPEC;
43 int show_options = 0;
44 int show_details = 0;
45 int show_users = 0;
46 int show_mem = 0;
47 int show_tcpinfo = 0;
48
49 int netid_width;
50 int state_width;
51 int addrp_width;
52 int addr_width;
53 int serv_width;
54 int screen_width;
55
56 static const char *TCP_PROTO = "tcp";
57 static const char *UDP_PROTO = "udp";
58 static const char *RAW_PROTO = "raw";
59 static const char *dg_proto = NULL;
60
61 enum
62 {
63         TCP_DB,
64         DCCP_DB,
65         UDP_DB,
66         RAW_DB,
67         UNIX_DG_DB,
68         UNIX_ST_DB,
69         PACKET_DG_DB,
70         PACKET_R_DB,
71         NETLINK_DB,
72         MAX_DB
73 };
74
75 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
76 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB))
77 #define ALL_DB ((1<<MAX_DB)-1)
78
79 enum {
80         SS_UNKNOWN,
81         SS_ESTABLISHED,
82         SS_SYN_SENT,
83         SS_SYN_RECV,
84         SS_FIN_WAIT1,
85         SS_FIN_WAIT2,
86         SS_TIME_WAIT,
87         SS_CLOSE,
88         SS_CLOSE_WAIT,
89         SS_LAST_ACK,
90         SS_LISTEN,
91         SS_CLOSING,
92         SS_MAX
93 };
94
95 #define SS_ALL ((1<<SS_MAX)-1)
96
97 #include "ssfilter.h"
98
99 struct filter
100 {
101         int dbs;
102         int states;
103         int families;
104         struct ssfilter *f;
105 };
106
107 struct filter default_filter = {
108         .dbs    =  ~0,
109         .states = SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)),
110         .families= (1<<AF_INET)|(1<<AF_INET6),
111 };
112
113 struct filter current_filter;
114
115 static FILE *generic_proc_open(const char *env, const char *name)
116 {
117         const char *p = getenv(env);
118         char store[128];
119
120         if (!p) {
121                 p = getenv("PROC_ROOT") ? : "/proc";
122                 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
123                 p = store;
124         }
125
126         return fopen(p, "r");
127 }
128
129 static FILE *net_tcp_open(void)
130 {
131         return generic_proc_open("PROC_NET_TCP", "net/tcp");
132 }
133
134 static FILE *net_tcp6_open(void)
135 {
136         return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
137 }
138
139 static FILE *net_udp_open(void)
140 {
141         return generic_proc_open("PROC_NET_UDP", "net/udp");
142 }
143
144 static FILE *net_udp6_open(void)
145 {
146         return generic_proc_open("PROC_NET_UDP6", "net/udp6");
147 }
148
149 static FILE *net_raw_open(void)
150 {
151         return generic_proc_open("PROC_NET_RAW", "net/raw");
152 }
153
154 static FILE *net_raw6_open(void)
155 {
156         return generic_proc_open("PROC_NET_RAW6", "net/raw6");
157 }
158
159 static FILE *net_unix_open(void)
160 {
161         return generic_proc_open("PROC_NET_UNIX", "net/unix");
162 }
163
164 static FILE *net_packet_open(void)
165 {
166         return generic_proc_open("PROC_NET_PACKET", "net/packet");
167 }
168
169 static FILE *net_netlink_open(void)
170 {
171         return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
172 }
173
174 static FILE *slabinfo_open(void)
175 {
176         return generic_proc_open("PROC_SLABINFO", "slabinfo");
177 }
178
179 static FILE *net_sockstat_open(void)
180 {
181         return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
182 }
183
184 static FILE *net_sockstat6_open(void)
185 {
186         return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
187 }
188
189 static FILE *net_snmp_open(void)
190 {
191         return generic_proc_open("PROC_NET_SNMP", "net/snmp");
192 }
193
194 static FILE *ephemeral_ports_open(void)
195 {
196         return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
197 }
198
199 struct user_ent {
200         struct user_ent *next;
201         unsigned int    ino;
202         int             pid;
203         int             fd;
204         char            process[0];
205 };
206
207 #define USER_ENT_HASH_SIZE      256
208 struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE];
209
210 static int user_ent_hashfn(unsigned int ino)
211 {
212         int val = (ino >> 24) ^ (ino >> 16) ^ (ino >> 8) ^ ino;
213
214         return val & (USER_ENT_HASH_SIZE - 1);
215 }
216
217 static void user_ent_add(unsigned int ino, const char *process, int pid, int fd)
218 {
219         struct user_ent *p, **pp;
220         int str_len;
221
222         str_len = strlen(process) + 1;
223         p = malloc(sizeof(struct user_ent) + str_len);
224         if (!p)
225                 abort();
226         p->next = NULL;
227         p->ino = ino;
228         p->pid = pid;
229         p->fd = fd;
230         strcpy(p->process, process);
231
232         pp = &user_ent_hash[user_ent_hashfn(ino)];
233         p->next = *pp;
234         *pp = p;
235 }
236
237 static void user_ent_hash_build(void)
238 {
239         const char *root = getenv("PROC_ROOT") ? : "/proc/";
240         struct dirent *d;
241         char name[1024];
242         int nameoff;
243         DIR *dir;
244
245         strcpy(name, root);
246         if (strlen(name) == 0 || name[strlen(name)-1] != '/')
247                 strcat(name, "/");
248
249         nameoff = strlen(name);
250
251         dir = opendir(name);
252         if (!dir)
253                 return;
254
255         while ((d = readdir(dir)) != NULL) {
256                 struct dirent *d1;
257                 char process[16];
258                 int pid, pos;
259                 DIR *dir1;
260                 char crap;
261
262                 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
263                         continue;
264
265                 sprintf(name + nameoff, "%d/fd/", pid);
266                 pos = strlen(name);
267                 if ((dir1 = opendir(name)) == NULL)
268                         continue;
269
270                 process[0] = '\0';
271
272                 while ((d1 = readdir(dir1)) != NULL) {
273                         const char *pattern = "socket:[";
274                         unsigned int ino;
275                         char lnk[64];
276                         int fd;
277                         ssize_t link_len;
278
279                         if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
280                                 continue;
281
282                         sprintf(name+pos, "%d", fd);
283
284                         link_len = readlink(name, lnk, sizeof(lnk)-1);
285                         if (link_len == -1)
286                                 continue;
287                         lnk[link_len] = '\0';
288
289                         if (strncmp(lnk, pattern, strlen(pattern)))
290                                 continue;
291
292                         sscanf(lnk, "socket:[%u]", &ino);
293
294                         if (process[0] == '\0') {
295                                 char tmp[1024];
296                                 FILE *fp;
297
298                                 snprintf(tmp, sizeof(tmp), "%s/%d/stat", root, pid);
299                                 if ((fp = fopen(tmp, "r")) != NULL) {
300                                         int ret = fscanf(fp, "%*d (%[^)])", process);
301                                         if (ret < 0)
302                                                 fprintf(stderr, "Error: failed to read from input file stream.\n");
303                                         fclose(fp);
304                                 }
305                         }
306
307                         user_ent_add(ino, process, pid, fd);
308                 }
309                 closedir(dir1);
310         }
311         closedir(dir);
312 }
313
314 static int find_users(unsigned ino, char *buf, int buflen)
315 {
316         struct user_ent *p;
317         int cnt = 0;
318         char *ptr;
319
320         if (!ino)
321                 return 0;
322
323         p = user_ent_hash[user_ent_hashfn(ino)];
324         ptr = buf;
325         while (p) {
326                 if (p->ino != ino)
327                         goto next;
328
329                 if (ptr - buf >= buflen - 1)
330                         break;
331
332                 snprintf(ptr, buflen - (ptr - buf),
333                          "(\"%s\",%d,%d),",
334                          p->process, p->pid, p->fd);
335                 ptr += strlen(ptr);
336                 cnt++;
337
338         next:
339                 p = p->next;
340         }
341
342         if (ptr != buf)
343                 ptr[-1] = '\0';
344
345         return cnt;
346 }
347
348 /* Get stats from slab */
349
350 struct slabstat
351 {
352         int socks;
353         int tcp_ports;
354         int tcp_tws;
355         int tcp_syns;
356         int skbs;
357 };
358
359 struct slabstat slabstat;
360
361 static const char *slabstat_ids[] =
362 {
363         "sock",
364         "tcp_bind_bucket",
365         "tcp_tw_bucket",
366         "tcp_open_request",
367         "skbuff_head_cache",
368 };
369
370 static int get_slabstat(struct slabstat *s)
371 {
372         char buf[256];
373         FILE *fp;
374         int cnt;
375
376         memset(s, 0, sizeof(*s));
377
378         fp = slabinfo_open();
379         if (!fp)
380                 return -1;
381
382         cnt = sizeof(*s)/sizeof(int);
383
384         if (fgets(buf, sizeof(buf), fp) == NULL)
385                 goto out;
386         while(fgets(buf, sizeof(buf), fp) != NULL) {
387                 int i;
388                 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
389                         if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
390                                 sscanf(buf, "%*s%d", ((int *)s) + i);
391                                 cnt--;
392                                 break;
393                         }
394                 }
395                 if (cnt <= 0)
396                         break;
397         }
398
399 out:
400         fclose(fp);
401         return 0;
402 }
403
404 static const char *sstate_name[] = {
405         "UNKNOWN",
406         [TCP_ESTABLISHED] = "ESTAB",
407         [TCP_SYN_SENT] = "SYN-SENT",
408         [TCP_SYN_RECV] = "SYN-RECV",
409         [TCP_FIN_WAIT1] = "FIN-WAIT-1",
410         [TCP_FIN_WAIT2] = "FIN-WAIT-2",
411         [TCP_TIME_WAIT] = "TIME-WAIT",
412         [TCP_CLOSE] = "UNCONN",
413         [TCP_CLOSE_WAIT] = "CLOSE-WAIT",
414         [TCP_LAST_ACK] = "LAST-ACK",
415         [TCP_LISTEN] =  "LISTEN",
416         [TCP_CLOSING] = "CLOSING",
417 };
418
419 static const char *sstate_namel[] = {
420         "UNKNOWN",
421         [TCP_ESTABLISHED] = "established",
422         [TCP_SYN_SENT] = "syn-sent",
423         [TCP_SYN_RECV] = "syn-recv",
424         [TCP_FIN_WAIT1] = "fin-wait-1",
425         [TCP_FIN_WAIT2] = "fin-wait-2",
426         [TCP_TIME_WAIT] = "time-wait",
427         [TCP_CLOSE] = "unconnected",
428         [TCP_CLOSE_WAIT] = "close-wait",
429         [TCP_LAST_ACK] = "last-ack",
430         [TCP_LISTEN] =  "listening",
431         [TCP_CLOSING] = "closing",
432 };
433
434 struct tcpstat
435 {
436         inet_prefix     local;
437         inet_prefix     remote;
438         int             lport;
439         int             rport;
440         int             state;
441         int             rq, wq;
442         int             timer;
443         int             timeout;
444         int             retrs;
445         unsigned        ino;
446         int             probes;
447         unsigned        uid;
448         int             refcnt;
449         unsigned long long sk;
450         int             rto, ato, qack, cwnd, ssthresh;
451 };
452
453 static const char *tmr_name[] = {
454         "off",
455         "on",
456         "keepalive",
457         "timewait",
458         "persist",
459         "unknown"
460 };
461
462 static const char *print_ms_timer(int timeout)
463 {
464         static char buf[64];
465         int secs, msecs, minutes;
466         if (timeout < 0)
467                 timeout = 0;
468         secs = timeout/1000;
469         minutes = secs/60;
470         secs = secs%60;
471         msecs = timeout%1000;
472         buf[0] = 0;
473         if (minutes) {
474                 msecs = 0;
475                 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
476                 if (minutes > 9)
477                         secs = 0;
478         }
479         if (secs) {
480                 if (secs > 9)
481                         msecs = 0;
482                 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
483         }
484         if (msecs)
485                 sprintf(buf+strlen(buf), "%03dms", msecs);
486         return buf;
487 }
488
489 static const char *print_hz_timer(int timeout)
490 {
491         int hz = get_user_hz();
492         return print_ms_timer(((timeout*1000) + hz-1)/hz);
493 }
494
495 struct scache
496 {
497         struct scache *next;
498         int port;
499         char *name;
500         const char *proto;
501 };
502
503 struct scache *rlist;
504
505 static void init_service_resolver(void)
506 {
507         char buf[128];
508         FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
509         if (fp) {
510                 if (fgets(buf, sizeof(buf), fp) == NULL)
511                         fprintf(stderr, "Error: failed to read from input file stream.\n");
512                 while (fgets(buf, sizeof(buf), fp) != NULL) {
513                         unsigned int progn, port;
514                         char proto[128], prog[128];
515                         if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
516                                    &port, prog+4) == 4) {
517                                 struct scache *c = malloc(sizeof(*c));
518                                 if (c) {
519                                         c->port = port;
520                                         memcpy(prog, "rpc.", 4);
521                                         c->name = strdup(prog);
522                                         if (strcmp(proto, TCP_PROTO) == 0)
523                                                 c->proto = TCP_PROTO;
524                                         else if (strcmp(proto, UDP_PROTO) == 0)
525                                                 c->proto = UDP_PROTO;
526                                         else
527                                                 c->proto = NULL;
528                                         c->next = rlist;
529                                         rlist = c;
530                                 }
531                         }
532                 }
533                 pclose(fp);
534         }
535 }
536
537 static int ip_local_port_min, ip_local_port_max;
538
539 /* Even do not try default linux ephemeral port ranges:
540  * default /etc/services contains so much of useless crap
541  * wouldbe "allocated" to this area that resolution
542  * is really harmful. I shrug each time when seeing
543  * "socks" or "cfinger" in dumps.
544  */
545 static int is_ephemeral(int port)
546 {
547         if (!ip_local_port_min) {
548                 FILE *f = ephemeral_ports_open();
549                 if (f) {
550                         int ret = fscanf(f, "%d %d",
551                                         &ip_local_port_min, &ip_local_port_max);
552                         if (ret < 0)
553                                 fprintf(stderr, "Error: failed to read from input file stream.\n");
554                         fclose(f);
555                 } else {
556                         ip_local_port_min = 1024;
557                         ip_local_port_max = 4999;
558                 }
559         }
560
561         return (port >= ip_local_port_min && port<= ip_local_port_max);
562 }
563
564
565 static const char *__resolve_service(int port)
566 {
567         struct scache *c;
568
569         for (c = rlist; c; c = c->next) {
570                 if (c->port == port && c->proto == dg_proto)
571                         return c->name;
572         }
573
574         if (!is_ephemeral(port)) {
575                 static int notfirst;
576                 struct servent *se;
577                 if (!notfirst) {
578                         setservent(1);
579                         notfirst = 1;
580                 }
581                 se = getservbyport(htons(port), dg_proto);
582                 if (se)
583                         return se->s_name;
584         }
585
586         return NULL;
587 }
588
589
590 static const char *resolve_service(int port)
591 {
592         static char buf[128];
593         static struct scache cache[256];
594
595         if (port == 0) {
596                 buf[0] = '*';
597                 buf[1] = 0;
598                 return buf;
599         }
600
601         if (resolve_services) {
602                 if (dg_proto == RAW_PROTO) {
603                         return inet_proto_n2a(port, buf, sizeof(buf));
604                 } else {
605                         struct scache *c;
606                         const char *res;
607                         int hash = (port^(((unsigned long)dg_proto)>>2))&255;
608
609                         for (c = &cache[hash]; c; c = c->next) {
610                                 if (c->port == port &&
611                                     c->proto == dg_proto) {
612                                         if (c->name)
613                                                 return c->name;
614                                         goto do_numeric;
615                                 }
616                         }
617
618                         if ((res = __resolve_service(port)) != NULL) {
619                                 if ((c = malloc(sizeof(*c))) == NULL)
620                                         goto do_numeric;
621                         } else {
622                                 c = &cache[hash];
623                                 if (c->name)
624                                         free(c->name);
625                         }
626                         c->port = port;
627                         c->name = NULL;
628                         c->proto = dg_proto;
629                         if (res) {
630                                 c->name = strdup(res);
631                                 c->next = cache[hash].next;
632                                 cache[hash].next = c;
633                         }
634                         if (c->name)
635                                 return c->name;
636                 }
637         }
638
639         do_numeric:
640         sprintf(buf, "%u", port);
641         return buf;
642 }
643
644 static void formatted_print(const inet_prefix *a, int port)
645 {
646         char buf[1024];
647         const char *ap = buf;
648         int est_len;
649
650         est_len = addr_width;
651
652         if (a->family == AF_INET) {
653                 if (a->data[0] == 0) {
654                         buf[0] = '*';
655                         buf[1] = 0;
656                 } else {
657                         ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
658                 }
659         } else {
660                 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
661                 est_len = strlen(ap);
662                 if (est_len <= addr_width)
663                         est_len = addr_width;
664                 else
665                         est_len = addr_width + ((est_len-addr_width+3)/4)*4;
666         }
667         printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
668 }
669
670 struct aafilter
671 {
672         inet_prefix     addr;
673         int             port;
674         struct aafilter *next;
675 };
676
677 static int inet2_addr_match(const inet_prefix *a, const inet_prefix *p,
678                             int plen)
679 {
680         if (!inet_addr_match(a, p, plen))
681                 return 0;
682
683         /* Cursed "v4 mapped" addresses: v4 mapped socket matches
684          * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
685          * sockets. Fair? */
686         if (p->family == AF_INET && a->family == AF_INET6) {
687                 if (a->data[0] == 0 && a->data[1] == 0 &&
688                     a->data[2] == htonl(0xffff)) {
689                         inet_prefix tmp = *a;
690                         tmp.data[0] = a->data[3];
691                         return inet_addr_match(&tmp, p, plen);
692                 }
693         }
694         return 1;
695 }
696
697 static int unix_match(const inet_prefix *a, const inet_prefix *p)
698 {
699         char *addr, *pattern;
700         memcpy(&addr, a->data, sizeof(addr));
701         memcpy(&pattern, p->data, sizeof(pattern));
702         if (pattern == NULL)
703                 return 1;
704         if (addr == NULL)
705                 addr = "";
706         return !fnmatch(pattern, addr, 0);
707 }
708
709 static int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
710 {
711         switch (f->type) {
712                 case SSF_S_AUTO:
713         {
714                 static int low, high=65535;
715
716                 if (s->local.family == AF_UNIX) {
717                         char *p;
718                         memcpy(&p, s->local.data, sizeof(p));
719                         return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
720                                              strspn(p+1, "0123456789abcdef") == 5);
721                 }
722                 if (s->local.family == AF_PACKET)
723                         return s->lport == 0 && s->local.data == 0;
724                 if (s->local.family == AF_NETLINK)
725                         return s->lport < 0;
726
727                 if (!low) {
728                         FILE *fp = ephemeral_ports_open();
729                         if (fp) {
730                                 int ret = fscanf(fp, "%d%d", &low, &high);
731                                 if (ret < 0)
732                                         fprintf(stderr, "Error: failed to read from input file stream.\n");
733                                 fclose(fp);
734                         }
735                 }
736                 return s->lport >= low && s->lport <= high;
737         }
738                 case SSF_DCOND:
739         {
740                 struct aafilter *a = (void*)f->pred;
741                 if (a->addr.family == AF_UNIX)
742                         return unix_match(&s->remote, &a->addr);
743                 if (a->port != -1 && a->port != s->rport)
744                         return 0;
745                 if (a->addr.bitlen) {
746                         do {
747                                 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
748                                         return 1;
749                         } while ((a = a->next) != NULL);
750                         return 0;
751                 }
752                 return 1;
753         }
754                 case SSF_SCOND:
755         {
756                 struct aafilter *a = (void*)f->pred;
757                 if (a->addr.family == AF_UNIX)
758                         return unix_match(&s->local, &a->addr);
759                 if (a->port != -1 && a->port != s->lport)
760                         return 0;
761                 if (a->addr.bitlen) {
762                         do {
763                                 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
764                                         return 1;
765                         } while ((a = a->next) != NULL);
766                         return 0;
767                 }
768                 return 1;
769         }
770                 case SSF_D_GE:
771         {
772                 struct aafilter *a = (void*)f->pred;
773                 return s->rport >= a->port;
774         }
775                 case SSF_D_LE:
776         {
777                 struct aafilter *a = (void*)f->pred;
778                 return s->rport <= a->port;
779         }
780                 case SSF_S_GE:
781         {
782                 struct aafilter *a = (void*)f->pred;
783                 return s->lport >= a->port;
784         }
785                 case SSF_S_LE:
786         {
787                 struct aafilter *a = (void*)f->pred;
788                 return s->lport <= a->port;
789         }
790
791                 /* Yup. It is recursion. Sorry. */
792                 case SSF_AND:
793                 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
794                 case SSF_OR:
795                 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
796                 case SSF_NOT:
797                 return !run_ssfilter(f->pred, s);
798                 default:
799                 abort();
800         }
801 }
802
803 /* Relocate external jumps by reloc. */
804 static void ssfilter_patch(char *a, int len, int reloc)
805 {
806         while (len > 0) {
807                 struct inet_diag_bc_op *op = (struct inet_diag_bc_op*)a;
808                 if (op->no == len+4)
809                         op->no += reloc;
810                 len -= op->yes;
811                 a += op->yes;
812         }
813         if (len < 0)
814                 abort();
815 }
816
817 static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
818 {
819         switch (f->type) {
820                 case SSF_S_AUTO:
821         {
822                 if (!(*bytecode=malloc(4))) abort();
823                 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
824                 return 4;
825         }
826                 case SSF_DCOND:
827                 case SSF_SCOND:
828         {
829                 struct aafilter *a = (void*)f->pred;
830                 struct aafilter *b;
831                 char *ptr;
832                 int  code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
833                 int len = 0;
834
835                 for (b=a; b; b=b->next) {
836                         len += 4 + sizeof(struct inet_diag_hostcond);
837                         if (a->addr.family == AF_INET6)
838                                 len += 16;
839                         else
840                                 len += 4;
841                         if (b->next)
842                                 len += 4;
843                 }
844                 if (!(ptr = malloc(len))) abort();
845                 *bytecode = ptr;
846                 for (b=a; b; b=b->next) {
847                         struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
848                         int alen = (a->addr.family == AF_INET6 ? 16 : 4);
849                         int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
850                         struct inet_diag_hostcond *cond = (struct inet_diag_hostcond*)(ptr+4);
851
852                         *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
853                         cond->family = a->addr.family;
854                         cond->port = a->port;
855                         cond->prefix_len = a->addr.bitlen;
856                         memcpy(cond->addr, a->addr.data, alen);
857                         ptr += oplen;
858                         if (b->next) {
859                                 op = (struct inet_diag_bc_op *)ptr;
860                                 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
861                                 ptr += 4;
862                         }
863                 }
864                 return ptr - *bytecode;
865         }
866                 case SSF_D_GE:
867         {
868                 struct aafilter *x = (void*)f->pred;
869                 if (!(*bytecode=malloc(8))) abort();
870                 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
871                 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
872                 return 8;
873         }
874                 case SSF_D_LE:
875         {
876                 struct aafilter *x = (void*)f->pred;
877                 if (!(*bytecode=malloc(8))) abort();
878                 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
879                 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
880                 return 8;
881         }
882                 case SSF_S_GE:
883         {
884                 struct aafilter *x = (void*)f->pred;
885                 if (!(*bytecode=malloc(8))) abort();
886                 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
887                 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
888                 return 8;
889         }
890                 case SSF_S_LE:
891         {
892                 struct aafilter *x = (void*)f->pred;
893                 if (!(*bytecode=malloc(8))) abort();
894                 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
895                 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
896                 return 8;
897         }
898
899                 case SSF_AND:
900         {
901                 char *a1, *a2, *a, l1, l2;
902                 l1 = ssfilter_bytecompile(f->pred, &a1);
903                 l2 = ssfilter_bytecompile(f->post, &a2);
904                 if (!(a = malloc(l1+l2))) abort();
905                 memcpy(a, a1, l1);
906                 memcpy(a+l1, a2, l2);
907                 free(a1); free(a2);
908                 ssfilter_patch(a, l1, l2);
909                 *bytecode = a;
910                 return l1+l2;
911         }
912                 case SSF_OR:
913         {
914                 char *a1, *a2, *a, l1, l2;
915                 l1 = ssfilter_bytecompile(f->pred, &a1);
916                 l2 = ssfilter_bytecompile(f->post, &a2);
917                 if (!(a = malloc(l1+l2+4))) abort();
918                 memcpy(a, a1, l1);
919                 memcpy(a+l1+4, a2, l2);
920                 free(a1); free(a2);
921                 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
922                 *bytecode = a;
923                 return l1+l2+4;
924         }
925                 case SSF_NOT:
926         {
927                 char *a1, *a, l1;
928                 l1 = ssfilter_bytecompile(f->pred, &a1);
929                 if (!(a = malloc(l1+4))) abort();
930                 memcpy(a, a1, l1);
931                 free(a1);
932                 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
933                 *bytecode = a;
934                 return l1+4;
935         }
936                 default:
937                 abort();
938         }
939 }
940
941 static int remember_he(struct aafilter *a, struct hostent *he)
942 {
943         char **ptr = he->h_addr_list;
944         int cnt = 0;
945         int len;
946
947         if (he->h_addrtype == AF_INET)
948                 len = 4;
949         else if (he->h_addrtype == AF_INET6)
950                 len = 16;
951         else
952                 return 0;
953
954         while (*ptr) {
955                 struct aafilter *b = a;
956                 if (a->addr.bitlen) {
957                         if ((b = malloc(sizeof(*b))) == NULL)
958                                 return cnt;
959                         *b = *a;
960                         b->next = a->next;
961                         a->next = b;
962                 }
963                 memcpy(b->addr.data, *ptr, len);
964                 b->addr.bytelen = len;
965                 b->addr.bitlen = len*8;
966                 b->addr.family = he->h_addrtype;
967                 ptr++;
968                 cnt++;
969         }
970         return cnt;
971 }
972
973 static int get_dns_host(struct aafilter *a, const char *addr, int fam)
974 {
975         static int notfirst;
976         int cnt = 0;
977         struct hostent *he;
978
979         a->addr.bitlen = 0;
980         if (!notfirst) {
981                 sethostent(1);
982                 notfirst = 1;
983         }
984         he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
985         if (he)
986                 cnt = remember_he(a, he);
987         if (fam == AF_UNSPEC) {
988                 he = gethostbyname2(addr, AF_INET6);
989                 if (he)
990                         cnt += remember_he(a, he);
991         }
992         return !cnt;
993 }
994
995 static int xll_initted = 0;
996
997 static void xll_init(void)
998 {
999         struct rtnl_handle rth;
1000         rtnl_open(&rth, 0);
1001         ll_init_map(&rth);
1002         rtnl_close(&rth);
1003         xll_initted = 1;
1004 }
1005
1006 static const char *xll_index_to_name(int index)
1007 {
1008         if (!xll_initted)
1009                 xll_init();
1010         return ll_index_to_name(index);
1011 }
1012
1013 static int xll_name_to_index(const char *dev)
1014 {
1015         if (!xll_initted)
1016                 xll_init();
1017         return ll_name_to_index(dev);
1018 }
1019
1020 void *parse_hostcond(char *addr)
1021 {
1022         char *port = NULL;
1023         struct aafilter a;
1024         struct aafilter *res;
1025         int fam = preferred_family;
1026
1027         memset(&a, 0, sizeof(a));
1028         a.port = -1;
1029
1030         if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
1031                 char *p;
1032                 a.addr.family = AF_UNIX;
1033                 if (strncmp(addr, "unix:", 5) == 0)
1034                         addr+=5;
1035                 p = strdup(addr);
1036                 a.addr.bitlen = 8*strlen(p);
1037                 memcpy(a.addr.data, &p, sizeof(p));
1038                 goto out;
1039         }
1040
1041         if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
1042                 a.addr.family = AF_PACKET;
1043                 a.addr.bitlen = 0;
1044                 if (strncmp(addr, "link:", 5) == 0)
1045                         addr+=5;
1046                 port = strchr(addr, ':');
1047                 if (port) {
1048                         *port = 0;
1049                         if (port[1] && strcmp(port+1, "*")) {
1050                                 if (get_integer(&a.port, port+1, 0)) {
1051                                         if ((a.port = xll_name_to_index(port+1)) <= 0)
1052                                                 return NULL;
1053                                 }
1054                         }
1055                 }
1056                 if (addr[0] && strcmp(addr, "*")) {
1057                         unsigned short tmp;
1058                         a.addr.bitlen = 32;
1059                         if (ll_proto_a2n(&tmp, addr))
1060                                 return NULL;
1061                         a.addr.data[0] = ntohs(tmp);
1062                 }
1063                 goto out;
1064         }
1065
1066         if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
1067                 a.addr.family = AF_NETLINK;
1068                 a.addr.bitlen = 0;
1069                 if (strncmp(addr, "netlink:", 8) == 0)
1070                         addr+=8;
1071                 port = strchr(addr, ':');
1072                 if (port) {
1073                         *port = 0;
1074                         if (port[1] && strcmp(port+1, "*")) {
1075                                 if (get_integer(&a.port, port+1, 0)) {
1076                                         if (strcmp(port+1, "kernel") == 0)
1077                                                 a.port = 0;
1078                                         else
1079                                                 return NULL;
1080                                 }
1081                         }
1082                 }
1083                 if (addr[0] && strcmp(addr, "*")) {
1084                         a.addr.bitlen = 32;
1085                         if (get_u32(a.addr.data, addr, 0)) {
1086                                 if (strcmp(addr, "rtnl") == 0)
1087                                         a.addr.data[0] = 0;
1088                                 else if (strcmp(addr, "fw") == 0)
1089                                         a.addr.data[0] = 3;
1090                                 else if (strcmp(addr, "tcpdiag") == 0)
1091                                         a.addr.data[0] = 4;
1092                                 else
1093                                         return NULL;
1094                         }
1095                 }
1096                 goto out;
1097         }
1098
1099         if (strncmp(addr, "inet:", 5) == 0) {
1100                 addr += 5;
1101                 fam = AF_INET;
1102         } else if (strncmp(addr, "inet6:", 6) == 0) {
1103                 addr += 6;
1104                 fam = AF_INET6;
1105         }
1106
1107         /* URL-like literal [] */
1108         if (addr[0] == '[') {
1109                 addr++;
1110                 if ((port = strchr(addr, ']')) == NULL)
1111                         return NULL;
1112                 *port++ = 0;
1113         } else if (addr[0] == '*') {
1114                 port = addr+1;
1115         } else {
1116                 port = strrchr(strchr(addr, '/') ? : addr, ':');
1117         }
1118         if (port && *port) {
1119                 if (*port != ':')
1120                         return NULL;
1121                 *port++ = 0;
1122                 if (*port && *port != '*') {
1123                         if (get_integer(&a.port, port, 0)) {
1124                                 struct servent *se1 = NULL;
1125                                 struct servent *se2 = NULL;
1126                                 if (current_filter.dbs&(1<<UDP_DB))
1127                                         se1 = getservbyname(port, UDP_PROTO);
1128                                 if (current_filter.dbs&(1<<TCP_DB))
1129                                         se2 = getservbyname(port, TCP_PROTO);
1130                                 if (se1 && se2 && se1->s_port != se2->s_port) {
1131                                         fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1132                                         return NULL;
1133                                 }
1134                                 if (!se1)
1135                                         se1 = se2;
1136                                 if (se1) {
1137                                         a.port = ntohs(se1->s_port);
1138                                 } else {
1139                                         struct scache *s;
1140                                         for (s = rlist; s; s = s->next) {
1141                                                 if ((s->proto == UDP_PROTO &&
1142                                                      (current_filter.dbs&(1<<UDP_DB))) ||
1143                                                     (s->proto == TCP_PROTO &&
1144                                                      (current_filter.dbs&(1<<TCP_DB)))) {
1145                                                         if (s->name && strcmp(s->name, port) == 0) {
1146                                                                 if (a.port > 0 && a.port != s->port) {
1147                                                                         fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1148                                                                         return NULL;
1149                                                                 }
1150                                                                 a.port = s->port;
1151                                                         }
1152                                                 }
1153                                         }
1154                                         if (a.port <= 0) {
1155                                                 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1156                                                 return NULL;
1157                                         }
1158                                 }
1159                         }
1160                 }
1161         }
1162         if (addr && *addr && *addr != '*') {
1163                 if (get_prefix_1(&a.addr, addr, fam)) {
1164                         if (get_dns_host(&a, addr, fam)) {
1165                                 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1166                                 return NULL;
1167                         }
1168                 }
1169         }
1170
1171         out:
1172         res = malloc(sizeof(*res));
1173         if (res)
1174                 memcpy(res, &a, sizeof(a));
1175         return res;
1176 }
1177
1178 static int tcp_show_line(char *line, const struct filter *f, int family)
1179 {
1180         struct tcpstat s;
1181         char *loc, *rem, *data;
1182         char opt[256];
1183         int n;
1184         char *p;
1185
1186         if ((p = strchr(line, ':')) == NULL)
1187                 return -1;
1188         loc = p+2;
1189
1190         if ((p = strchr(loc, ':')) == NULL)
1191                 return -1;
1192         p[5] = 0;
1193         rem = p+6;
1194
1195         if ((p = strchr(rem, ':')) == NULL)
1196                 return -1;
1197         p[5] = 0;
1198         data = p+6;
1199
1200         do {
1201                 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1202
1203                 if (!(f->states & (1<<state)))
1204                         return 0;
1205         } while (0);
1206
1207         s.local.family = s.remote.family = family;
1208         if (family == AF_INET) {
1209                 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1210                 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1211                 s.local.bytelen = s.remote.bytelen = 4;
1212         } else {
1213                 sscanf(loc, "%08x%08x%08x%08x:%x",
1214                        s.local.data,
1215                        s.local.data+1,
1216                        s.local.data+2,
1217                        s.local.data+3,
1218                        &s.lport);
1219                 sscanf(rem, "%08x%08x%08x%08x:%x",
1220                        s.remote.data,
1221                        s.remote.data+1,
1222                        s.remote.data+2,
1223                        s.remote.data+3,
1224                        &s.rport);
1225                 s.local.bytelen = s.remote.bytelen = 16;
1226         }
1227
1228         if (f->f && run_ssfilter(f->f, &s) == 0)
1229                 return 0;
1230
1231         opt[0] = 0;
1232         n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
1233                    &s.state, &s.wq, &s.rq,
1234                    &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1235                    &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1236                    &s.cwnd, &s.ssthresh, opt);
1237
1238         if (n < 17)
1239                 opt[0] = 0;
1240
1241         if (n < 12) {
1242                 s.rto = 0;
1243                 s.cwnd = 2;
1244                 s.ssthresh = -1;
1245                 s.ato = s.qack = 0;
1246         }
1247
1248         if (netid_width)
1249                 printf("%-*s ", netid_width, "tcp");
1250         if (state_width)
1251                 printf("%-*s ", state_width, sstate_name[s.state]);
1252
1253         printf("%-6d %-6d ", s.rq, s.wq);
1254
1255         formatted_print(&s.local, s.lport);
1256         formatted_print(&s.remote, s.rport);
1257
1258         if (show_options) {
1259                 if (s.timer) {
1260                         if (s.timer > 4)
1261                                 s.timer = 5;
1262                         printf(" timer:(%s,%s,%d)",
1263                                tmr_name[s.timer],
1264                                print_hz_timer(s.timeout),
1265                                s.timer != 1 ? s.probes : s.retrs);
1266                 }
1267         }
1268         if (show_tcpinfo) {
1269                 int hz = get_user_hz();
1270                 if (s.rto && s.rto != 3*hz)
1271                         printf(" rto:%g", (double)s.rto/hz);
1272                 if (s.ato)
1273                         printf(" ato:%g", (double)s.ato/hz);
1274                 if (s.cwnd != 2)
1275                         printf(" cwnd:%d", s.cwnd);
1276                 if (s.ssthresh != -1)
1277                         printf(" ssthresh:%d", s.ssthresh);
1278                 if (s.qack/2)
1279                         printf(" qack:%d", s.qack/2);
1280                 if (s.qack&1)
1281                         printf(" bidir");
1282         }
1283         if (show_users) {
1284                 char ubuf[4096];
1285                 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1286                         printf(" users:(%s)", ubuf);
1287         }
1288         if (show_details) {
1289                 if (s.uid)
1290                         printf(" uid:%u", (unsigned)s.uid);
1291                 printf(" ino:%u", s.ino);
1292                 printf(" sk:%llx", s.sk);
1293                 if (opt[0])
1294                         printf(" opt:\"%s\"", opt);
1295         }
1296         printf("\n");
1297
1298         return 0;
1299 }
1300
1301 static int generic_record_read(FILE *fp,
1302                                int (*worker)(char*, const struct filter *, int),
1303                                const struct filter *f, int fam)
1304 {
1305         char line[256];
1306
1307         /* skip header */
1308         if (fgets(line, sizeof(line), fp) == NULL)
1309                 goto outerr;
1310
1311         while (fgets(line, sizeof(line), fp) != NULL) {
1312                 int n = strlen(line);
1313                 if (n == 0 || line[n-1] != '\n') {
1314                         errno = -EINVAL;
1315                         return -1;
1316                 }
1317                 line[n-1] = 0;
1318
1319                 if (worker(line, f, fam) < 0)
1320                         return 0;
1321         }
1322 outerr:
1323
1324         return ferror(fp) ? -1 : 0;
1325 }
1326
1327 static char *sprint_bw(char *buf, double bw)
1328 {
1329         if (bw > 1000000.)
1330                 sprintf(buf,"%.1fM", bw / 1000000.);
1331         else if (bw > 1000.)
1332                 sprintf(buf,"%.1fK", bw / 1000.);
1333         else
1334                 sprintf(buf, "%g", bw);
1335
1336         return buf;
1337 }
1338
1339 static void print_skmeminfo(struct rtattr *tb[], int attrtype)
1340 {
1341         const __u32 *skmeminfo;
1342         if (!tb[attrtype])
1343                 return;
1344         skmeminfo = RTA_DATA(tb[attrtype]);
1345
1346         printf(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
1347                skmeminfo[SK_MEMINFO_RMEM_ALLOC],
1348                skmeminfo[SK_MEMINFO_RCVBUF],
1349                skmeminfo[SK_MEMINFO_WMEM_ALLOC],
1350                skmeminfo[SK_MEMINFO_SNDBUF],
1351                skmeminfo[SK_MEMINFO_FWD_ALLOC],
1352                skmeminfo[SK_MEMINFO_WMEM_QUEUED],
1353                skmeminfo[SK_MEMINFO_OPTMEM]);
1354
1355         if (RTA_PAYLOAD(tb[attrtype]) >=
1356                 (SK_MEMINFO_BACKLOG + 1) * sizeof(__u32))
1357                 printf(",bl%u", skmeminfo[SK_MEMINFO_BACKLOG]);
1358
1359         printf(")");
1360 }
1361
1362 static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r)
1363 {
1364         struct rtattr * tb[INET_DIAG_MAX+1];
1365         char b1[64];
1366         double rtt = 0;
1367
1368         parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr*)(r+1),
1369                      nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1370
1371         if (tb[INET_DIAG_SKMEMINFO]) {
1372                 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
1373         } else if (tb[INET_DIAG_MEMINFO]) {
1374                 const struct inet_diag_meminfo *minfo
1375                         = RTA_DATA(tb[INET_DIAG_MEMINFO]);
1376                 printf(" mem:(r%u,w%u,f%u,t%u)",
1377                        minfo->idiag_rmem,
1378                        minfo->idiag_wmem,
1379                        minfo->idiag_fmem,
1380                        minfo->idiag_tmem);
1381         }
1382
1383         if (tb[INET_DIAG_INFO]) {
1384                 struct tcp_info *info;
1385                 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
1386
1387                 /* workaround for older kernels with less fields */
1388                 if (len < sizeof(*info)) {
1389                         info = alloca(sizeof(*info));
1390                         memset(info, 0, sizeof(*info));
1391                         memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
1392                 } else
1393                         info = RTA_DATA(tb[INET_DIAG_INFO]);
1394
1395                 if (show_options) {
1396                         if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1397                                 printf(" ts");
1398                         if (info->tcpi_options & TCPI_OPT_SACK)
1399                                 printf(" sack");
1400                         if (info->tcpi_options & TCPI_OPT_ECN)
1401                                 printf(" ecn");
1402                         if (info->tcpi_options & TCPI_OPT_ECN_SEEN)
1403                                 printf(" ecnseen");
1404                 }
1405
1406                 if (tb[INET_DIAG_CONG])
1407                         printf(" %s", rta_getattr_str(tb[INET_DIAG_CONG]));
1408
1409                 if (info->tcpi_options & TCPI_OPT_WSCALE)
1410                         printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1411                                info->tcpi_rcv_wscale);
1412                 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1413                         printf(" rto:%g", (double)info->tcpi_rto/1000);
1414                 if (info->tcpi_rtt)
1415                         printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1416                                (double)info->tcpi_rttvar/1000);
1417                 if (info->tcpi_ato)
1418                         printf(" ato:%g", (double)info->tcpi_ato/1000);
1419                 if (info->tcpi_snd_mss)
1420                         printf(" mss:%d", info->tcpi_snd_mss);
1421                 if (info->tcpi_snd_cwnd != 2)
1422                         printf(" cwnd:%d", info->tcpi_snd_cwnd);
1423                 if (info->tcpi_snd_ssthresh < 0xFFFF)
1424                         printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1425
1426                 rtt = (double) info->tcpi_rtt;
1427                 if (tb[INET_DIAG_VEGASINFO]) {
1428                         const struct tcpvegas_info *vinfo
1429                                 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
1430
1431                         if (vinfo->tcpv_enabled &&
1432                             vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
1433                                 rtt =  vinfo->tcpv_rtt;
1434                 }
1435
1436                 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1437                         printf(" send %sbps",
1438                                sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1439                                          (double) info->tcpi_snd_mss * 8000000.
1440                                          / rtt));
1441                 }
1442
1443                 if (info->tcpi_rcv_rtt)
1444                         printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1445                 if (info->tcpi_rcv_space)
1446                         printf(" rcv_space:%d", info->tcpi_rcv_space);
1447
1448         }
1449 }
1450
1451 static int inet_show_sock(struct nlmsghdr *nlh, struct filter *f)
1452 {
1453         struct inet_diag_msg *r = NLMSG_DATA(nlh);
1454         struct tcpstat s;
1455
1456         s.state = r->idiag_state;
1457         s.local.family = s.remote.family = r->idiag_family;
1458         s.lport = ntohs(r->id.idiag_sport);
1459         s.rport = ntohs(r->id.idiag_dport);
1460         if (s.local.family == AF_INET) {
1461                 s.local.bytelen = s.remote.bytelen = 4;
1462         } else {
1463                 s.local.bytelen = s.remote.bytelen = 16;
1464         }
1465         memcpy(s.local.data, r->id.idiag_src, s.local.bytelen);
1466         memcpy(s.remote.data, r->id.idiag_dst, s.local.bytelen);
1467
1468         if (f && f->f && run_ssfilter(f->f, &s) == 0)
1469                 return 0;
1470
1471         if (netid_width)
1472                 printf("%-*s ", netid_width, "tcp");
1473         if (state_width)
1474                 printf("%-*s ", state_width, sstate_name[s.state]);
1475
1476         printf("%-6d %-6d ", r->idiag_rqueue, r->idiag_wqueue);
1477
1478         formatted_print(&s.local, s.lport);
1479         formatted_print(&s.remote, s.rport);
1480
1481         if (show_options) {
1482                 if (r->idiag_timer) {
1483                         if (r->idiag_timer > 4)
1484                                 r->idiag_timer = 5;
1485                         printf(" timer:(%s,%s,%d)",
1486                                tmr_name[r->idiag_timer],
1487                                print_ms_timer(r->idiag_expires),
1488                                r->idiag_retrans);
1489                 }
1490         }
1491         if (show_users) {
1492                 char ubuf[4096];
1493                 if (find_users(r->idiag_inode, ubuf, sizeof(ubuf)) > 0)
1494                         printf(" users:(%s)", ubuf);
1495         }
1496         if (show_details) {
1497                 if (r->idiag_uid)
1498                         printf(" uid:%u", (unsigned)r->idiag_uid);
1499                 printf(" ino:%u", r->idiag_inode);
1500                 printf(" sk:");
1501                 if (r->id.idiag_cookie[1] != 0)
1502                         printf("%08x", r->id.idiag_cookie[1]);
1503                 printf("%08x", r->id.idiag_cookie[0]);
1504         }
1505         if (show_mem || show_tcpinfo) {
1506                 printf("\n\t");
1507                 tcp_show_info(nlh, r);
1508         }
1509
1510         printf("\n");
1511
1512         return 0;
1513 }
1514
1515 static int tcpdiag_send(int fd, int protocol, struct filter *f)
1516 {
1517         struct sockaddr_nl nladdr;
1518         struct {
1519                 struct nlmsghdr nlh;
1520                 struct inet_diag_req r;
1521         } req;
1522         char    *bc = NULL;
1523         int     bclen;
1524         struct msghdr msg;
1525         struct rtattr rta;
1526         struct iovec iov[3];
1527
1528         if (protocol == IPPROTO_UDP)
1529                 return -1;
1530
1531         memset(&nladdr, 0, sizeof(nladdr));
1532         nladdr.nl_family = AF_NETLINK;
1533
1534         req.nlh.nlmsg_len = sizeof(req);
1535         if (protocol == IPPROTO_TCP)
1536                 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
1537         else
1538                 req.nlh.nlmsg_type = DCCPDIAG_GETSOCK;
1539         req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1540         req.nlh.nlmsg_pid = 0;
1541         req.nlh.nlmsg_seq = 123456;
1542         memset(&req.r, 0, sizeof(req.r));
1543         req.r.idiag_family = AF_INET;
1544         req.r.idiag_states = f->states;
1545         if (show_mem) {
1546                 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
1547                 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
1548         }
1549
1550         if (show_tcpinfo) {
1551                 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1552                 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1553                 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
1554         }
1555
1556         iov[0] = (struct iovec){
1557                 .iov_base = &req,
1558                 .iov_len = sizeof(req)
1559         };
1560         if (f->f) {
1561                 bclen = ssfilter_bytecompile(f->f, &bc);
1562                 rta.rta_type = INET_DIAG_REQ_BYTECODE;
1563                 rta.rta_len = RTA_LENGTH(bclen);
1564                 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1565                 iov[2] = (struct iovec){ bc, bclen };
1566                 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1567         }
1568
1569         msg = (struct msghdr) {
1570                 .msg_name = (void*)&nladdr,
1571                 .msg_namelen = sizeof(nladdr),
1572                 .msg_iov = iov,
1573                 .msg_iovlen = f->f ? 3 : 1,
1574         };
1575
1576         if (sendmsg(fd, &msg, 0) < 0) {
1577                 close(fd);
1578                 return -1;
1579         }
1580
1581         return 0;
1582 }
1583
1584 static int sockdiag_send(int family, int fd, int protocol, struct filter *f)
1585 {
1586         struct sockaddr_nl nladdr;
1587         struct {
1588                 struct nlmsghdr nlh;
1589                 struct inet_diag_req_v2 r;
1590         } req;
1591         char    *bc = NULL;
1592         int     bclen;
1593         struct msghdr msg;
1594         struct rtattr rta;
1595         struct iovec iov[3];
1596
1597         if (family == PF_UNSPEC)
1598                 return tcpdiag_send(fd, protocol, f);
1599
1600         memset(&nladdr, 0, sizeof(nladdr));
1601         nladdr.nl_family = AF_NETLINK;
1602
1603         req.nlh.nlmsg_len = sizeof(req);
1604         req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
1605         req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1606         req.nlh.nlmsg_pid = 0;
1607         req.nlh.nlmsg_seq = 123456;
1608         memset(&req.r, 0, sizeof(req.r));
1609         req.r.sdiag_family = family;
1610         req.r.sdiag_protocol = protocol;
1611         req.r.idiag_states = f->states;
1612         if (show_mem) {
1613                 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
1614                 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
1615         }
1616
1617         if (show_tcpinfo) {
1618                 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1619                 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1620                 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
1621         }
1622
1623         iov[0] = (struct iovec){
1624                 .iov_base = &req,
1625                 .iov_len = sizeof(req)
1626         };
1627         if (f->f) {
1628                 bclen = ssfilter_bytecompile(f->f, &bc);
1629                 rta.rta_type = INET_DIAG_REQ_BYTECODE;
1630                 rta.rta_len = RTA_LENGTH(bclen);
1631                 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1632                 iov[2] = (struct iovec){ bc, bclen };
1633                 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1634         }
1635
1636         msg = (struct msghdr) {
1637                 .msg_name = (void*)&nladdr,
1638                 .msg_namelen = sizeof(nladdr),
1639                 .msg_iov = iov,
1640                 .msg_iovlen = f->f ? 3 : 1,
1641         };
1642
1643         if (sendmsg(fd, &msg, 0) < 0) {
1644                 close(fd);
1645                 return -1;
1646         }
1647
1648         return 0;
1649 }
1650
1651 static int inet_show_netlink(struct filter *f, FILE *dump_fp, int protocol)
1652 {
1653         int fd, family;
1654         struct sockaddr_nl nladdr;
1655         struct msghdr msg;
1656         char    buf[8192];
1657         struct iovec iov[3];
1658
1659         if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
1660                 return -1;
1661
1662         family = PF_INET;
1663 again:
1664         if (sockdiag_send(family, fd, protocol, f))
1665                 return -1;
1666
1667         memset(&nladdr, 0, sizeof(nladdr));
1668         nladdr.nl_family = AF_NETLINK;
1669
1670         iov[0] = (struct iovec){
1671                 .iov_base = buf,
1672                 .iov_len = sizeof(buf)
1673         };
1674
1675         while (1) {
1676                 int status;
1677                 struct nlmsghdr *h;
1678
1679                 msg = (struct msghdr) {
1680                         (void*)&nladdr, sizeof(nladdr),
1681                         iov,    1,
1682                         NULL,   0,
1683                         0
1684                 };
1685
1686                 status = recvmsg(fd, &msg, 0);
1687
1688                 if (status < 0) {
1689                         if (errno == EINTR)
1690                                 continue;
1691                         perror("OVERRUN");
1692                         continue;
1693                 }
1694                 if (status == 0) {
1695                         fprintf(stderr, "EOF on netlink\n");
1696                         close(fd);
1697                         return 0;
1698                 }
1699
1700                 if (dump_fp)
1701                         fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1702
1703                 h = (struct nlmsghdr*)buf;
1704                 while (NLMSG_OK(h, status)) {
1705                         int err;
1706                         struct inet_diag_msg *r = NLMSG_DATA(h);
1707
1708                         if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1709                             h->nlmsg_seq != 123456)
1710                                 goto skip_it;
1711
1712                         if (h->nlmsg_type == NLMSG_DONE)
1713                                 goto done;
1714
1715                         if (h->nlmsg_type == NLMSG_ERROR) {
1716                                 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1717                                 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1718                                         fprintf(stderr, "ERROR truncated\n");
1719                                 } else {
1720                                         if (family != PF_UNSPEC) {
1721                                                 family = PF_UNSPEC;
1722                                                 goto again;
1723                                         }
1724
1725                                         errno = -err->error;
1726                                         if (errno == EOPNOTSUPP) {
1727                                                 close(fd);
1728                                                 return -1;
1729                                         }
1730                                         perror("TCPDIAG answers");
1731                                 }
1732
1733                                 goto done;
1734                         }
1735                         if (!dump_fp) {
1736                                 if (!(f->families & (1<<r->idiag_family))) {
1737                                         h = NLMSG_NEXT(h, status);
1738                                         continue;
1739                                 }
1740                                 err = inet_show_sock(h, NULL);
1741                                 if (err < 0) {
1742                                         close(fd);
1743                                         return err;
1744                                 }
1745                         }
1746
1747 skip_it:
1748                         h = NLMSG_NEXT(h, status);
1749                 }
1750                 if (msg.msg_flags & MSG_TRUNC) {
1751                         fprintf(stderr, "Message truncated\n");
1752                         continue;
1753                 }
1754                 if (status) {
1755                         fprintf(stderr, "!!!Remnant of size %d\n", status);
1756                         exit(1);
1757                 }
1758         }
1759 done:
1760         if (family == PF_INET) {
1761                 family = PF_INET6;
1762                 goto again;
1763         }
1764
1765         close(fd);
1766         return 0;
1767 }
1768
1769 static int tcp_show_netlink_file(struct filter *f)
1770 {
1771         FILE    *fp;
1772         char    buf[8192];
1773
1774         if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1775                 perror("fopen($TCPDIAG_FILE)");
1776                 return -1;
1777         }
1778
1779         while (1) {
1780                 int status, err;
1781                 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1782
1783                 status = fread(buf, 1, sizeof(*h), fp);
1784                 if (status < 0) {
1785                         perror("Reading header from $TCPDIAG_FILE");
1786                         return -1;
1787                 }
1788                 if (status != sizeof(*h)) {
1789                         perror("Unexpected EOF reading $TCPDIAG_FILE");
1790                         return -1;
1791                 }
1792
1793                 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1794
1795                 if (status < 0) {
1796                         perror("Reading $TCPDIAG_FILE");
1797                         return -1;
1798                 }
1799                 if (status + sizeof(*h) < h->nlmsg_len) {
1800                         perror("Unexpected EOF reading $TCPDIAG_FILE");
1801                         return -1;
1802                 }
1803
1804                 /* The only legal exit point */
1805                 if (h->nlmsg_type == NLMSG_DONE)
1806                         return 0;
1807
1808                 if (h->nlmsg_type == NLMSG_ERROR) {
1809                         struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1810                         if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1811                                 fprintf(stderr, "ERROR truncated\n");
1812                         } else {
1813                                 errno = -err->error;
1814                                 perror("TCPDIAG answered");
1815                         }
1816                         return -1;
1817                 }
1818
1819                 err = inet_show_sock(h, f);
1820                 if (err < 0)
1821                         return err;
1822         }
1823 }
1824
1825 static int tcp_show(struct filter *f, int socktype)
1826 {
1827         FILE *fp = NULL;
1828         char *buf = NULL;
1829         int bufsize = 64*1024;
1830
1831         dg_proto = TCP_PROTO;
1832
1833         if (getenv("TCPDIAG_FILE"))
1834                 return tcp_show_netlink_file(f);
1835
1836         if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1837             && inet_show_netlink(f, NULL, socktype) == 0)
1838                 return 0;
1839
1840         /* Sigh... We have to parse /proc/net/tcp... */
1841
1842
1843         /* Estimate amount of sockets and try to allocate
1844          * huge buffer to read all the table at one read.
1845          * Limit it by 16MB though. The assumption is: as soon as
1846          * kernel was able to hold information about N connections,
1847          * it is able to give us some memory for snapshot.
1848          */
1849         if (1) {
1850                 int guess = slabstat.socks+slabstat.tcp_syns;
1851                 if (f->states&(1<<SS_TIME_WAIT))
1852                         guess += slabstat.tcp_tws;
1853                 if (guess > (16*1024*1024)/128)
1854                         guess = (16*1024*1024)/128;
1855                 guess *= 128;
1856                 if (guess > bufsize)
1857                         bufsize = guess;
1858         }
1859         while (bufsize >= 64*1024) {
1860                 if ((buf = malloc(bufsize)) != NULL)
1861                         break;
1862                 bufsize /= 2;
1863         }
1864         if (buf == NULL) {
1865                 errno = ENOMEM;
1866                 return -1;
1867         }
1868
1869         if (f->families & (1<<AF_INET)) {
1870                 if ((fp = net_tcp_open()) == NULL)
1871                         goto outerr;
1872
1873                 setbuffer(fp, buf, bufsize);
1874                 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
1875                         goto outerr;
1876                 fclose(fp);
1877         }
1878
1879         if ((f->families & (1<<AF_INET6)) &&
1880             (fp = net_tcp6_open()) != NULL) {
1881                 setbuffer(fp, buf, bufsize);
1882                 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
1883                         goto outerr;
1884                 fclose(fp);
1885         }
1886
1887         free(buf);
1888         return 0;
1889
1890 outerr:
1891         do {
1892                 int saved_errno = errno;
1893                 if (buf)
1894                         free(buf);
1895                 if (fp)
1896                         fclose(fp);
1897                 errno = saved_errno;
1898                 return -1;
1899         } while (0);
1900 }
1901
1902
1903 static int dgram_show_line(char *line, const struct filter *f, int family)
1904 {
1905         struct tcpstat s;
1906         char *loc, *rem, *data;
1907         char opt[256];
1908         int n;
1909         char *p;
1910
1911         if ((p = strchr(line, ':')) == NULL)
1912                 return -1;
1913         loc = p+2;
1914
1915         if ((p = strchr(loc, ':')) == NULL)
1916                 return -1;
1917         p[5] = 0;
1918         rem = p+6;
1919
1920         if ((p = strchr(rem, ':')) == NULL)
1921                 return -1;
1922         p[5] = 0;
1923         data = p+6;
1924
1925         do {
1926                 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1927
1928                 if (!(f->states & (1<<state)))
1929                         return 0;
1930         } while (0);
1931
1932         s.local.family = s.remote.family = family;
1933         if (family == AF_INET) {
1934                 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1935                 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1936                 s.local.bytelen = s.remote.bytelen = 4;
1937         } else {
1938                 sscanf(loc, "%08x%08x%08x%08x:%x",
1939                        s.local.data,
1940                        s.local.data+1,
1941                        s.local.data+2,
1942                        s.local.data+3,
1943                        &s.lport);
1944                 sscanf(rem, "%08x%08x%08x%08x:%x",
1945                        s.remote.data,
1946                        s.remote.data+1,
1947                        s.remote.data+2,
1948                        s.remote.data+3,
1949                        &s.rport);
1950                 s.local.bytelen = s.remote.bytelen = 16;
1951         }
1952
1953         if (f->f && run_ssfilter(f->f, &s) == 0)
1954                 return 0;
1955
1956         opt[0] = 0;
1957         n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
1958                &s.state, &s.wq, &s.rq,
1959                &s.uid, &s.ino,
1960                &s.refcnt, &s.sk, opt);
1961
1962         if (n < 9)
1963                 opt[0] = 0;
1964
1965         if (netid_width)
1966                 printf("%-*s ", netid_width, dg_proto);
1967         if (state_width)
1968                 printf("%-*s ", state_width, sstate_name[s.state]);
1969
1970         printf("%-6d %-6d ", s.rq, s.wq);
1971
1972         formatted_print(&s.local, s.lport);
1973         formatted_print(&s.remote, s.rport);
1974
1975         if (show_users) {
1976                 char ubuf[4096];
1977                 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1978                         printf(" users:(%s)", ubuf);
1979         }
1980
1981         if (show_details) {
1982                 if (s.uid)
1983                         printf(" uid=%u", (unsigned)s.uid);
1984                 printf(" ino=%u", s.ino);
1985                 printf(" sk=%llx", s.sk);
1986                 if (opt[0])
1987                         printf(" opt:\"%s\"", opt);
1988         }
1989         printf("\n");
1990
1991         return 0;
1992 }
1993
1994
1995 static int udp_show(struct filter *f)
1996 {
1997         FILE *fp = NULL;
1998
1999         if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
2000             && inet_show_netlink(f, NULL, IPPROTO_UDP) == 0)
2001                 return 0;
2002
2003         dg_proto = UDP_PROTO;
2004
2005         if (f->families&(1<<AF_INET)) {
2006                 if ((fp = net_udp_open()) == NULL)
2007                         goto outerr;
2008                 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
2009                         goto outerr;
2010                 fclose(fp);
2011         }
2012
2013         if ((f->families&(1<<AF_INET6)) &&
2014             (fp = net_udp6_open()) != NULL) {
2015                 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
2016                         goto outerr;
2017                 fclose(fp);
2018         }
2019         return 0;
2020
2021 outerr:
2022         do {
2023                 int saved_errno = errno;
2024                 if (fp)
2025                         fclose(fp);
2026                 errno = saved_errno;
2027                 return -1;
2028         } while (0);
2029 }
2030
2031 static int raw_show(struct filter *f)
2032 {
2033         FILE *fp = NULL;
2034
2035         dg_proto = RAW_PROTO;
2036
2037         if (f->families&(1<<AF_INET)) {
2038                 if ((fp = net_raw_open()) == NULL)
2039                         goto outerr;
2040                 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
2041                         goto outerr;
2042                 fclose(fp);
2043         }
2044
2045         if ((f->families&(1<<AF_INET6)) &&
2046             (fp = net_raw6_open()) != NULL) {
2047                 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
2048                         goto outerr;
2049                 fclose(fp);
2050         }
2051         return 0;
2052
2053 outerr:
2054         do {
2055                 int saved_errno = errno;
2056                 if (fp)
2057                         fclose(fp);
2058                 errno = saved_errno;
2059                 return -1;
2060         } while (0);
2061 }
2062
2063
2064 struct unixstat
2065 {
2066         struct unixstat *next;
2067         int ino;
2068         int peer;
2069         int rq;
2070         int wq;
2071         int state;
2072         int type;
2073         char *name;
2074 };
2075
2076
2077
2078 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
2079                          SS_ESTABLISHED, SS_CLOSING };
2080
2081
2082 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
2083
2084 static void unix_list_free(struct unixstat *list)
2085 {
2086         while (list) {
2087                 struct unixstat *s = list;
2088                 list = list->next;
2089                 if (s->name)
2090                         free(s->name);
2091                 free(s);
2092         }
2093 }
2094
2095 static void unix_list_print(struct unixstat *list, struct filter *f)
2096 {
2097         struct unixstat *s;
2098         char *peer;
2099
2100         for (s = list; s; s = s->next) {
2101                 if (!(f->states & (1<<s->state)))
2102                         continue;
2103                 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2104                         continue;
2105                 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2106                         continue;
2107
2108                 peer = "*";
2109                 if (s->peer) {
2110                         struct unixstat *p;
2111                         for (p = list; p; p = p->next) {
2112                                 if (s->peer == p->ino)
2113                                         break;
2114                         }
2115                         if (!p) {
2116                                 peer = "?";
2117                         } else {
2118                                 peer = p->name ? : "*";
2119                         }
2120                 }
2121
2122                 if (f->f) {
2123                         struct tcpstat tst;
2124                         tst.local.family = AF_UNIX;
2125                         tst.remote.family = AF_UNIX;
2126                         memcpy(tst.local.data, &s->name, sizeof(s->name));
2127                         if (strcmp(peer, "*") == 0)
2128                                 memset(tst.remote.data, 0, sizeof(peer));
2129                         else
2130                                 memcpy(tst.remote.data, &peer, sizeof(peer));
2131                         if (run_ssfilter(f->f, &tst) == 0)
2132                                 continue;
2133                 }
2134
2135                 if (netid_width)
2136                         printf("%-*s ", netid_width,
2137                                s->type == SOCK_STREAM ? "u_str" : "u_dgr");
2138                 if (state_width)
2139                         printf("%-*s ", state_width, sstate_name[s->state]);
2140                 printf("%-6d %-6d ", s->rq, s->wq);
2141                 printf("%*s %-*d %*s %-*d",
2142                        addr_width, s->name ? : "*", serv_width, s->ino,
2143                        addr_width, peer, serv_width, s->peer);
2144                 if (show_users) {
2145                         char ubuf[4096];
2146                         if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
2147                                 printf(" users:(%s)", ubuf);
2148                 }
2149                 printf("\n");
2150         }
2151 }
2152
2153 static int unix_show_sock(struct nlmsghdr *nlh, struct filter *f)
2154 {
2155         struct unix_diag_msg *r = NLMSG_DATA(nlh);
2156         struct rtattr *tb[UNIX_DIAG_MAX+1];
2157         char name[128];
2158         int peer_ino;
2159         __u32 rqlen, wqlen;
2160
2161         parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr*)(r+1),
2162                      nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2163
2164         if (netid_width)
2165                 printf("%-*s ", netid_width,
2166                                 r->udiag_type == SOCK_STREAM ? "u_str" : "u_dgr");
2167         if (state_width)
2168                 printf("%-*s ", state_width, sstate_name[r->udiag_state]);
2169
2170         if (tb[UNIX_DIAG_RQLEN]) {
2171                 struct unix_diag_rqlen *rql = RTA_DATA(tb[UNIX_DIAG_RQLEN]);
2172                 rqlen = rql->udiag_rqueue;
2173                 wqlen = rql->udiag_wqueue;
2174         } else {
2175                 rqlen = 0;
2176                 wqlen = 0;
2177         }
2178
2179         printf("%-6u %-6u ", rqlen, wqlen);
2180
2181         if (tb[UNIX_DIAG_NAME]) {
2182                 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
2183
2184                 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
2185                 name[len] = '\0';
2186                 if (name[0] == '\0')
2187                         name[0] = '@';
2188         } else
2189                 sprintf(name, "*");
2190
2191         if (tb[UNIX_DIAG_PEER])
2192                 peer_ino = rta_getattr_u32(tb[UNIX_DIAG_PEER]);
2193         else
2194                 peer_ino = 0;
2195
2196         printf("%*s %-*d %*s %-*d",
2197                         addr_width, name,
2198                         serv_width, r->udiag_ino,
2199                         addr_width, "*", /* FIXME */
2200                         serv_width, peer_ino);
2201
2202         if (show_users) {
2203                 char ubuf[4096];
2204                 if (find_users(r->udiag_ino, ubuf, sizeof(ubuf)) > 0)
2205                         printf(" users:(%s)", ubuf);
2206         }
2207
2208         if (show_mem) {
2209                 printf("\n\t");
2210                 print_skmeminfo(tb, UNIX_DIAG_MEMINFO);
2211         }
2212
2213         printf("\n");
2214
2215         return 0;
2216 }
2217
2218 static int unix_show_netlink(struct filter *f, FILE *dump_fp)
2219 {
2220         int fd;
2221         struct {
2222                 struct nlmsghdr nlh;
2223                 struct unix_diag_req r;
2224         } req;
2225         char    buf[8192];
2226
2227         if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
2228                 return -1;
2229
2230         memset(&req, 0, sizeof(req));
2231         req.nlh.nlmsg_len = sizeof(req);
2232         req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
2233         req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
2234         req.nlh.nlmsg_seq = 123456;
2235
2236         req.r.sdiag_family = AF_UNIX;
2237         req.r.udiag_states = f->states;
2238         req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
2239         if (show_mem)
2240                 req.r.udiag_show |= UDIAG_SHOW_MEMINFO;
2241
2242         if (send(fd, &req, sizeof(req), 0) < 0) {
2243                 close(fd);
2244                 return -1;
2245         }
2246
2247         while (1) {
2248                 ssize_t status;
2249                 struct nlmsghdr *h;
2250                 struct sockaddr_nl nladdr;
2251                 socklen_t slen = sizeof(nladdr);
2252
2253                 status = recvfrom(fd, buf, sizeof(buf), 0,
2254                                   (struct sockaddr *) &nladdr, &slen);
2255                 if (status < 0) {
2256                         if (errno == EINTR)
2257                                 continue;
2258                         perror("OVERRUN");
2259                         continue;
2260                 }
2261                 if (status == 0) {
2262                         fprintf(stderr, "EOF on netlink\n");
2263                         goto close_it;
2264                 }
2265
2266                 if (dump_fp)
2267                         fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
2268
2269                 h = (struct nlmsghdr*)buf;
2270                 while (NLMSG_OK(h, status)) {
2271                         int err;
2272
2273                         if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
2274                             h->nlmsg_seq != 123456)
2275                                 goto skip_it;
2276
2277                         if (h->nlmsg_type == NLMSG_DONE)
2278                                 goto close_it;
2279
2280                         if (h->nlmsg_type == NLMSG_ERROR) {
2281                                 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
2282                                 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2283                                         fprintf(stderr, "ERROR truncated\n");
2284                                 } else {
2285                                         errno = -err->error;
2286                                         if (errno != ENOENT)
2287                                                 fprintf(stderr, "UDIAG answers %d\n", errno);
2288                                 }
2289                                 close(fd);
2290                                 return -1;
2291                         }
2292                         if (!dump_fp) {
2293                                 err = unix_show_sock(h, f);
2294                                 if (err < 0) {
2295                                         close(fd);
2296                                         return err;
2297                                 }
2298                         }
2299
2300 skip_it:
2301                         h = NLMSG_NEXT(h, status);
2302                 }
2303
2304                 if (status) {
2305                         fprintf(stderr, "!!!Remnant of size %zd\n", status);
2306                         exit(1);
2307                 }
2308         }
2309
2310 close_it:
2311         close(fd);
2312         return 0;
2313 }
2314
2315 static int unix_show(struct filter *f)
2316 {
2317         FILE *fp;
2318         char buf[256];
2319         char name[128];
2320         int  newformat = 0;
2321         int  cnt;
2322         struct unixstat *list = NULL;
2323
2324         if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
2325             && unix_show_netlink(f, NULL) == 0)
2326                 return 0;
2327
2328         if ((fp = net_unix_open()) == NULL)
2329                 return -1;
2330         if (fgets(buf, sizeof(buf)-1, fp) == NULL)
2331                 return -1;
2332
2333         if (memcmp(buf, "Peer", 4) == 0)
2334                 newformat = 1;
2335         cnt = 0;
2336
2337         while (fgets(buf, sizeof(buf)-1, fp)) {
2338                 struct unixstat *u, **insp;
2339                 int flags;
2340
2341                 if (!(u = malloc(sizeof(*u))))
2342                         break;
2343                 u->name = NULL;
2344
2345                 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
2346                            &u->peer, &u->rq, &u->wq, &flags, &u->type,
2347                            &u->state, &u->ino, name) < 8)
2348                         name[0] = 0;
2349
2350                 if (flags&(1<<16)) {
2351                         u->state = SS_LISTEN;
2352                 } else {
2353                         u->state = unix_state_map[u->state-1];
2354                         if (u->type == SOCK_DGRAM &&
2355                             u->state == SS_CLOSE &&
2356                             u->peer)
2357                                 u->state = SS_ESTABLISHED;
2358                 }
2359
2360                 if (!newformat) {
2361                         u->peer = 0;
2362                         u->rq = 0;
2363                         u->wq = 0;
2364                 }
2365
2366                 insp = &list;
2367                 while (*insp) {
2368                         if (u->type < (*insp)->type ||
2369                             (u->type == (*insp)->type &&
2370                              u->ino < (*insp)->ino))
2371                                 break;
2372                         insp = &(*insp)->next;
2373                 }
2374                 u->next = *insp;
2375                 *insp = u;
2376
2377                 if (name[0]) {
2378                         if ((u->name = malloc(strlen(name)+1)) == NULL)
2379                                 break;
2380                         strcpy(u->name, name);
2381                 }
2382                 if (++cnt > MAX_UNIX_REMEMBER) {
2383                         unix_list_print(list, f);
2384                         unix_list_free(list);
2385                         list = NULL;
2386                         cnt = 0;
2387                 }
2388         }
2389         fclose(fp);
2390         if (list) {
2391                 unix_list_print(list, f);
2392                 unix_list_free(list);
2393                 list = NULL;
2394                 cnt = 0;
2395         }
2396
2397         return 0;
2398 }
2399
2400
2401 static int packet_show(struct filter *f)
2402 {
2403         FILE *fp;
2404         char buf[256];
2405         int type;
2406         int prot;
2407         int iface;
2408         int state;
2409         int rq;
2410         int uid;
2411         int ino;
2412         unsigned long long sk;
2413
2414         if (!(f->states & (1<<SS_CLOSE)))
2415                 return 0;
2416
2417         if ((fp = net_packet_open()) == NULL)
2418                 return -1;
2419         if (fgets(buf, sizeof(buf)-1, fp) == NULL)
2420                 fprintf(stderr, "Error: failed to read from input file stream.\n");
2421
2422         while (fgets(buf, sizeof(buf)-1, fp)) {
2423                 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2424                        &sk,
2425                        &type, &prot, &iface, &state,
2426                        &rq, &uid, &ino);
2427
2428                 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2429                         continue;
2430                 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2431                         continue;
2432                 if (f->f) {
2433                         struct tcpstat tst;
2434                         tst.local.family = AF_PACKET;
2435                         tst.remote.family = AF_PACKET;
2436                         tst.rport = 0;
2437                         tst.lport = iface;
2438                         tst.local.data[0] = prot;
2439                         tst.remote.data[0] = 0;
2440                         if (run_ssfilter(f->f, &tst) == 0)
2441                                 continue;
2442                 }
2443
2444                 if (netid_width)
2445                         printf("%-*s ", netid_width,
2446                                type == SOCK_RAW ? "p_raw" : "p_dgr");
2447                 if (state_width)
2448                         printf("%-*s ", state_width, "UNCONN");
2449                 printf("%-6d %-6d ", rq, 0);
2450                 if (prot == 3) {
2451                         printf("%*s:", addr_width, "*");
2452                 } else {
2453                         char tb[16];
2454                         printf("%*s:", addr_width,
2455                                ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2456                 }
2457                 if (iface == 0) {
2458                         printf("%-*s ", serv_width, "*");
2459                 } else {
2460                         printf("%-*s ", serv_width, xll_index_to_name(iface));
2461                 }
2462                 printf("%*s*%-*s",
2463                        addr_width, "", serv_width, "");
2464
2465                 if (show_users) {
2466                         char ubuf[4096];
2467                         if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2468                                 printf(" users:(%s)", ubuf);
2469                 }
2470                 if (show_details) {
2471                         printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2472                 }
2473                 printf("\n");
2474         }
2475
2476         return 0;
2477 }
2478
2479 static int netlink_show(struct filter *f)
2480 {
2481         FILE *fp;
2482         char buf[256];
2483         int prot, pid;
2484         unsigned groups;
2485         int rq, wq, rc;
2486         unsigned long long sk, cb;
2487
2488         if (!(f->states & (1<<SS_CLOSE)))
2489                 return 0;
2490
2491         if ((fp = net_netlink_open()) == NULL)
2492                 return -1;
2493         if (fgets(buf, sizeof(buf)-1, fp) == NULL)
2494                 fprintf(stderr, "Error: failed to read from input file stream.\n");
2495
2496         while (fgets(buf, sizeof(buf)-1, fp)) {
2497                 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2498                        &sk,
2499                        &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2500
2501                 if (f->f) {
2502                         struct tcpstat tst;
2503                         tst.local.family = AF_NETLINK;
2504                         tst.remote.family = AF_NETLINK;
2505                         tst.rport = -1;
2506                         tst.lport = pid;
2507                         tst.local.data[0] = prot;
2508                         tst.remote.data[0] = 0;
2509                         if (run_ssfilter(f->f, &tst) == 0)
2510                                 continue;
2511                 }
2512
2513                 if (netid_width)
2514                         printf("%-*s ", netid_width, "nl");
2515                 if (state_width)
2516                         printf("%-*s ", state_width, "UNCONN");
2517                 printf("%-6d %-6d ", rq, wq);
2518                 if (resolve_services && prot == 0)
2519                         printf("%*s:", addr_width, "rtnl");
2520                 else if (resolve_services && prot == 3)
2521                         printf("%*s:", addr_width, "fw");
2522                 else if (resolve_services && prot == 4)
2523                         printf("%*s:", addr_width, "tcpdiag");
2524                 else
2525                         printf("%*d:", addr_width, prot);
2526                 if (pid == -1) {
2527                         printf("%-*s ", serv_width, "*");
2528                 } else if (resolve_services) {
2529                         int done = 0;
2530                         if (!pid) {
2531                                 done = 1;
2532                                 printf("%-*s ", serv_width, "kernel");
2533                         } else if (pid > 0) {
2534                                 char procname[64];
2535                                 FILE *fp;
2536                                 sprintf(procname, "%s/%d/stat",
2537                                         getenv("PROC_ROOT") ? : "/proc", pid);
2538                                 if ((fp = fopen(procname, "r")) != NULL) {
2539                                         if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2540                                                 sprintf(procname+strlen(procname), "/%d", pid);
2541                                                 printf("%-*s ", serv_width, procname);
2542                                                 done = 1;
2543                                         }
2544                                         fclose(fp);
2545                                 }
2546                         }
2547                         if (!done)
2548                                 printf("%-*d ", serv_width, pid);
2549                 } else {
2550                         printf("%-*d ", serv_width, pid);
2551                 }
2552                 printf("%*s*%-*s",
2553                        addr_width, "", serv_width, "");
2554
2555                 if (show_details) {
2556                         printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2557                 }
2558                 printf("\n");
2559         }
2560
2561         return 0;
2562 }
2563
2564 struct snmpstat
2565 {
2566         int tcp_estab;
2567 };
2568
2569 static int get_snmp_int(char *proto, char *key, int *result)
2570 {
2571         char buf[1024];
2572         FILE *fp;
2573         int protolen = strlen(proto);
2574         int keylen = strlen(key);
2575
2576         *result = 0;
2577
2578         if ((fp = net_snmp_open()) == NULL)
2579                 return -1;
2580
2581         while (fgets(buf, sizeof(buf), fp) != NULL) {
2582                 char *p = buf;
2583                 int  pos = 0;
2584                 if (memcmp(buf, proto, protolen))
2585                         continue;
2586                 while ((p = strchr(p, ' ')) != NULL) {
2587                         pos++;
2588                         p++;
2589                         if (memcmp(p, key, keylen) == 0 &&
2590                             (p[keylen] == ' ' || p[keylen] == '\n'))
2591                                 break;
2592                 }
2593                 if (fgets(buf, sizeof(buf), fp) == NULL)
2594                         break;
2595                 if (memcmp(buf, proto, protolen))
2596                         break;
2597                 p = buf;
2598                 while ((p = strchr(p, ' ')) != NULL) {
2599                         p++;
2600                         if (--pos == 0) {
2601                                 sscanf(p, "%d", result);
2602                                 fclose(fp);
2603                                 return 0;
2604                         }
2605                 }
2606         }
2607
2608         fclose(fp);
2609         errno = ESRCH;
2610         return -1;
2611 }
2612
2613
2614 /* Get stats from sockstat */
2615
2616 struct sockstat
2617 {
2618         int socks;
2619         int tcp_mem;
2620         int tcp_total;
2621         int tcp_orphans;
2622         int tcp_tws;
2623         int tcp4_hashed;
2624         int udp4;
2625         int raw4;
2626         int frag4;
2627         int frag4_mem;
2628         int tcp6_hashed;
2629         int udp6;
2630         int raw6;
2631         int frag6;
2632         int frag6_mem;
2633 };
2634
2635 static void get_sockstat_line(char *line, struct sockstat *s)
2636 {
2637         char id[256], rem[256];
2638
2639         if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2640                 return;
2641
2642         if (strcmp(id, "sockets:") == 0)
2643                 sscanf(rem, "%*s%d", &s->socks);
2644         else if (strcmp(id, "UDP:") == 0)
2645                 sscanf(rem, "%*s%d", &s->udp4);
2646         else if (strcmp(id, "UDP6:") == 0)
2647                 sscanf(rem, "%*s%d", &s->udp6);
2648         else if (strcmp(id, "RAW:") == 0)
2649                 sscanf(rem, "%*s%d", &s->raw4);
2650         else if (strcmp(id, "RAW6:") == 0)
2651                 sscanf(rem, "%*s%d", &s->raw6);
2652         else if (strcmp(id, "TCP6:") == 0)
2653                 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2654         else if (strcmp(id, "FRAG:") == 0)
2655                 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2656         else if (strcmp(id, "FRAG6:") == 0)
2657                 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2658         else if (strcmp(id, "TCP:") == 0)
2659                 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2660                        &s->tcp4_hashed,
2661                        &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2662 }
2663
2664 static int get_sockstat(struct sockstat *s)
2665 {
2666         char buf[256];
2667         FILE *fp;
2668
2669         memset(s, 0, sizeof(*s));
2670
2671         if ((fp = net_sockstat_open()) == NULL)
2672                 return -1;
2673         while(fgets(buf, sizeof(buf), fp) != NULL)
2674                 get_sockstat_line(buf, s);
2675         fclose(fp);
2676
2677         if ((fp = net_sockstat6_open()) == NULL)
2678                 return 0;
2679         while(fgets(buf, sizeof(buf), fp) != NULL)
2680                 get_sockstat_line(buf, s);
2681         fclose(fp);
2682
2683         return 0;
2684 }
2685
2686 static int print_summary(void)
2687 {
2688         struct sockstat s;
2689         struct snmpstat sn;
2690
2691         if (get_sockstat(&s) < 0)
2692                 perror("ss: get_sockstat");
2693         if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2694                 perror("ss: get_snmpstat");
2695
2696         printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2697
2698         printf("TCP:   %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2699                s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2700                sn.tcp_estab,
2701                s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2702                s.tcp_orphans,
2703                slabstat.tcp_syns,
2704                s.tcp_tws, slabstat.tcp_tws,
2705                slabstat.tcp_ports
2706                );
2707
2708         printf("\n");
2709         printf("Transport Total     IP        IPv6\n");
2710         printf("*         %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2711         printf("RAW       %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2712         printf("UDP       %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2713         printf("TCP       %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2714         printf("INET      %-9d %-9d %-9d\n",
2715                s.raw4+s.udp4+s.tcp4_hashed+
2716                s.raw6+s.udp6+s.tcp6_hashed,
2717                s.raw4+s.udp4+s.tcp4_hashed,
2718                s.raw6+s.udp6+s.tcp6_hashed);
2719         printf("FRAG      %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2720
2721         printf("\n");
2722
2723         return 0;
2724 }
2725
2726 static void _usage(FILE *dest)
2727 {
2728         fprintf(dest,
2729 "Usage: ss [ OPTIONS ]\n"
2730 "       ss [ OPTIONS ] [ FILTER ]\n"
2731 "   -h, --help          this message\n"
2732 "   -V, --version       output version information\n"
2733 "   -n, --numeric       don't resolve service names\n"
2734 "   -r, --resolve       resolve host names\n"
2735 "   -a, --all           display all sockets\n"
2736 "   -l, --listening     display listening sockets\n"
2737 "   -o, --options       show timer information\n"
2738 "   -e, --extended      show detailed socket information\n"
2739 "   -m, --memory        show socket memory usage\n"
2740 "   -p, --processes     show process using socket\n"
2741 "   -i, --info          show internal TCP information\n"
2742 "   -s, --summary       show socket usage summary\n"
2743 "\n"
2744 "   -4, --ipv4          display only IP version 4 sockets\n"
2745 "   -6, --ipv6          display only IP version 6 sockets\n"
2746 "   -0, --packet        display PACKET sockets\n"
2747 "   -t, --tcp           display only TCP sockets\n"
2748 "   -u, --udp           display only UDP sockets\n"
2749 "   -d, --dccp          display only DCCP sockets\n"
2750 "   -w, --raw           display only RAW sockets\n"
2751 "   -x, --unix          display only Unix domain sockets\n"
2752 "   -f, --family=FAMILY display sockets of type FAMILY\n"
2753 "\n"
2754 "   -A, --query=QUERY, --socket=QUERY\n"
2755 "       QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2756 "\n"
2757 "   -D, --diag=FILE     Dump raw information about TCP sockets to FILE\n"
2758 "   -F, --filter=FILE   read filter information from FILE\n"
2759 "       FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2760                 );
2761 }
2762
2763 static void help(void) __attribute__((noreturn));
2764 static void help(void)
2765 {
2766         _usage(stdout);
2767         exit(0);
2768 }
2769
2770 static void usage(void) __attribute__((noreturn));
2771 static void usage(void)
2772 {
2773         _usage(stderr);
2774         exit(-1);
2775 }
2776
2777
2778 static int scan_state(const char *state)
2779 {
2780         int i;
2781         if (strcasecmp(state, "close") == 0 ||
2782             strcasecmp(state, "closed") == 0)
2783                 return (1<<SS_CLOSE);
2784         if (strcasecmp(state, "syn-rcv") == 0)
2785                 return (1<<SS_SYN_RECV);
2786         if (strcasecmp(state, "established") == 0)
2787                 return (1<<SS_ESTABLISHED);
2788         if (strcasecmp(state, "all") == 0)
2789                 return SS_ALL;
2790         if (strcasecmp(state, "connected") == 0)
2791                 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2792         if (strcasecmp(state, "synchronized") == 0)
2793                 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2794         if (strcasecmp(state, "bucket") == 0)
2795                 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2796         if (strcasecmp(state, "big") == 0)
2797                 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2798         for (i=0; i<SS_MAX; i++) {
2799                 if (strcasecmp(state, sstate_namel[i]) == 0)
2800                         return (1<<i);
2801         }
2802         return 0;
2803 }
2804
2805 static const struct option long_opts[] = {
2806         { "numeric", 0, 0, 'n' },
2807         { "resolve", 0, 0, 'r' },
2808         { "options", 0, 0, 'o' },
2809         { "extended", 0, 0, 'e' },
2810         { "memory", 0, 0, 'm' },
2811         { "info", 0, 0, 'i' },
2812         { "processes", 0, 0, 'p' },
2813         { "dccp", 0, 0, 'd' },
2814         { "tcp", 0, 0, 't' },
2815         { "udp", 0, 0, 'u' },
2816         { "raw", 0, 0, 'w' },
2817         { "unix", 0, 0, 'x' },
2818         { "all", 0, 0, 'a' },
2819         { "listening", 0, 0, 'l' },
2820         { "ipv4", 0, 0, '4' },
2821         { "ipv6", 0, 0, '6' },
2822         { "packet", 0, 0, '0' },
2823         { "family", 1, 0, 'f' },
2824         { "socket", 1, 0, 'A' },
2825         { "query", 1, 0, 'A' },
2826         { "summary", 0, 0, 's' },
2827         { "diag", 1, 0, 'D' },
2828         { "filter", 1, 0, 'F' },
2829         { "version", 0, 0, 'V' },
2830         { "help", 0, 0, 'h' },
2831         { 0 }
2832
2833 };
2834
2835 int main(int argc, char *argv[])
2836 {
2837         int do_default = 1;
2838         int saw_states = 0;
2839         int saw_query = 0;
2840         int do_summary = 0;
2841         const char *dump_tcpdiag = NULL;
2842         FILE *filter_fp = NULL;
2843         int ch;
2844
2845         memset(&current_filter, 0, sizeof(current_filter));
2846
2847         current_filter.states = default_filter.states;
2848
2849         while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spf:miA:D:F:vV",
2850                                  long_opts, NULL)) != EOF) {
2851                 switch(ch) {
2852                 case 'n':
2853                         resolve_services = 0;
2854                         break;
2855                 case 'r':
2856                         resolve_hosts = 1;
2857                         break;
2858                 case 'o':
2859                         show_options = 1;
2860                         break;
2861                 case 'e':
2862                         show_options = 1;
2863                         show_details++;
2864                         break;
2865                 case 'm':
2866                         show_mem = 1;
2867                         break;
2868                 case 'i':
2869                         show_tcpinfo = 1;
2870                         break;
2871                 case 'p':
2872                         show_users++;
2873                         user_ent_hash_build();
2874                         break;
2875                 case 'd':
2876                         current_filter.dbs |= (1<<DCCP_DB);
2877                         do_default = 0;
2878                         break;
2879                 case 't':
2880                         current_filter.dbs |= (1<<TCP_DB);
2881                         do_default = 0;
2882                         break;
2883                 case 'u':
2884                         current_filter.dbs |= (1<<UDP_DB);
2885                         do_default = 0;
2886                         break;
2887                 case 'w':
2888                         current_filter.dbs |= (1<<RAW_DB);
2889                         do_default = 0;
2890                         break;
2891                 case 'x':
2892                         current_filter.dbs |= UNIX_DBM;
2893                         do_default = 0;
2894                         break;
2895                 case 'a':
2896                         current_filter.states = SS_ALL;
2897                         break;
2898                 case 'l':
2899                         current_filter.states = (1<<SS_LISTEN) | (1<<SS_CLOSE);
2900                         break;
2901                 case '4':
2902                         preferred_family = AF_INET;
2903                         break;
2904                 case '6':
2905                         preferred_family = AF_INET6;
2906                         break;
2907                 case '0':
2908                         preferred_family = AF_PACKET;
2909                         break;
2910                 case 'f':
2911                         if (strcmp(optarg, "inet") == 0)
2912                                 preferred_family = AF_INET;
2913                         else if (strcmp(optarg, "inet6") == 0)
2914                                 preferred_family = AF_INET6;
2915                         else if (strcmp(optarg, "link") == 0)
2916                                 preferred_family = AF_PACKET;
2917                         else if (strcmp(optarg, "unix") == 0)
2918                                 preferred_family = AF_UNIX;
2919                         else if (strcmp(optarg, "netlink") == 0)
2920                                 preferred_family = AF_NETLINK;
2921                         else if (strcmp(optarg, "help") == 0)
2922                                 help();
2923                         else {
2924                                 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2925                                 usage();
2926                         }
2927                         break;
2928                 case 'A':
2929                 {
2930                         char *p, *p1;
2931                         if (!saw_query) {
2932                                 current_filter.dbs = 0;
2933                                 saw_query = 1;
2934                                 do_default = 0;
2935                         }
2936                         p = p1 = optarg;
2937                         do {
2938                                 if ((p1 = strchr(p, ',')) != NULL)
2939                                         *p1 = 0;
2940                                 if (strcmp(p, "all") == 0) {
2941                                         current_filter.dbs = ALL_DB;
2942                                 } else if (strcmp(p, "inet") == 0) {
2943                                         current_filter.dbs |= (1<<TCP_DB)|(1<<DCCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2944                                 } else if (strcmp(p, "udp") == 0) {
2945                                         current_filter.dbs |= (1<<UDP_DB);
2946                                 } else if (strcmp(p, "dccp") == 0) {
2947                                         current_filter.dbs |= (1<<DCCP_DB);
2948                                 } else if (strcmp(p, "tcp") == 0) {
2949                                         current_filter.dbs |= (1<<TCP_DB);
2950                                 } else if (strcmp(p, "raw") == 0) {
2951                                         current_filter.dbs |= (1<<RAW_DB);
2952                                 } else if (strcmp(p, "unix") == 0) {
2953                                         current_filter.dbs |= UNIX_DBM;
2954                                 } else if (strcasecmp(p, "unix_stream") == 0 ||
2955                                            strcmp(p, "u_str") == 0) {
2956                                         current_filter.dbs |= (1<<UNIX_ST_DB);
2957                                 } else if (strcasecmp(p, "unix_dgram") == 0 ||
2958                                            strcmp(p, "u_dgr") == 0) {
2959                                         current_filter.dbs |= (1<<UNIX_DG_DB);
2960                                 } else if (strcmp(p, "packet") == 0) {
2961                                         current_filter.dbs |= PACKET_DBM;
2962                                 } else if (strcmp(p, "packet_raw") == 0 ||
2963                                            strcmp(p, "p_raw") == 0) {
2964                                         current_filter.dbs |= (1<<PACKET_R_DB);
2965                                 } else if (strcmp(p, "packet_dgram") == 0 ||
2966                                            strcmp(p, "p_dgr") == 0) {
2967                                         current_filter.dbs |= (1<<PACKET_DG_DB);
2968                                 } else if (strcmp(p, "netlink") == 0) {
2969                                         current_filter.dbs |= (1<<NETLINK_DB);
2970                                 } else {
2971                                         fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2972                                         usage();
2973                                 }
2974                                 p = p1 + 1;
2975                         } while (p1);
2976                         break;
2977                 }
2978                 case 's':
2979                         do_summary = 1;
2980                         break;
2981                 case 'D':
2982                         dump_tcpdiag = optarg;
2983                         break;
2984                 case 'F':
2985                         if (filter_fp) {
2986                                 fprintf(stderr, "More than one filter file\n");
2987                                 exit(-1);
2988                         }
2989                         if (optarg[0] == '-')
2990                                 filter_fp = stdin;
2991                         else
2992                                 filter_fp = fopen(optarg, "r");
2993                         if (!filter_fp) {
2994                                 perror("fopen filter file");
2995                                 exit(-1);
2996                         }
2997                         break;
2998                 case 'v':
2999                 case 'V':
3000                         printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
3001                         exit(0);
3002                 case 'h':
3003                 case '?':
3004                         help();
3005                 default:
3006                         usage();
3007                 }
3008         }
3009
3010         argc -= optind;
3011         argv += optind;
3012
3013         get_slabstat(&slabstat);
3014
3015         if (do_summary) {
3016                 print_summary();
3017                 if (do_default && argc == 0)
3018                         exit(0);
3019         }
3020
3021         if (do_default)
3022                 current_filter.dbs = default_filter.dbs;
3023
3024         if (preferred_family == AF_UNSPEC) {
3025                 if (!(current_filter.dbs&~UNIX_DBM))
3026                         preferred_family = AF_UNIX;
3027                 else if (!(current_filter.dbs&~PACKET_DBM))
3028                         preferred_family = AF_PACKET;
3029                 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
3030                         preferred_family = AF_NETLINK;
3031         }
3032
3033         if (preferred_family != AF_UNSPEC) {
3034                 int mask2;
3035                 if (preferred_family == AF_INET ||
3036                     preferred_family == AF_INET6) {
3037                         mask2= current_filter.dbs;
3038                 } else if (preferred_family == AF_PACKET) {
3039                         mask2 = PACKET_DBM;
3040                 } else if (preferred_family == AF_UNIX) {
3041                         mask2 = UNIX_DBM;
3042                 } else if (preferred_family == AF_NETLINK) {
3043                         mask2 = (1<<NETLINK_DB);
3044                 } else {
3045                         mask2 = 0;
3046                 }
3047
3048                 if (do_default)
3049                         current_filter.dbs = mask2;
3050                 else
3051                         current_filter.dbs &= mask2;
3052                 current_filter.families = (1<<preferred_family);
3053         } else {
3054                 if (!do_default)
3055                         current_filter.families = ~0;
3056                 else
3057                         current_filter.families = default_filter.families;
3058         }
3059         if (current_filter.dbs == 0) {
3060                 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
3061                 exit(0);
3062         }
3063         if (current_filter.families == 0) {
3064                 fprintf(stderr, "ss: no families to show with such filter.\n");
3065                 exit(0);
3066         }
3067
3068         if (resolve_services && resolve_hosts &&
3069             (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
3070                 init_service_resolver();
3071
3072         /* Now parse filter... */
3073         if (argc == 0 && filter_fp) {
3074                 if (ssfilter_parse(&current_filter.f, 0, NULL, filter_fp))
3075                         usage();
3076         }
3077
3078         while (argc > 0) {
3079                 if (strcmp(*argv, "state") == 0) {
3080                         NEXT_ARG();
3081                         if (!saw_states)
3082                                 current_filter.states = 0;
3083                         current_filter.states |= scan_state(*argv);
3084                         saw_states = 1;
3085                 } else if (strcmp(*argv, "exclude") == 0 ||
3086                            strcmp(*argv, "excl") == 0) {
3087                         NEXT_ARG();
3088                         if (!saw_states)
3089                                 current_filter.states = SS_ALL;
3090                         current_filter.states &= ~scan_state(*argv);
3091                         saw_states = 1;
3092                 } else {
3093                         if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
3094                                 usage();
3095                         break;
3096                 }
3097                 argc--; argv++;
3098         }
3099
3100         if (current_filter.states == 0) {
3101                 fprintf(stderr, "ss: no socket states to show with such filter.\n");
3102                 exit(0);
3103         }
3104
3105         if (dump_tcpdiag) {
3106                 FILE *dump_fp = stdout;
3107                 if (!(current_filter.dbs & (1<<TCP_DB))) {
3108                         fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
3109                         exit(0);
3110                 }
3111                 if (dump_tcpdiag[0] != '-') {
3112                         dump_fp = fopen(dump_tcpdiag, "w");
3113                         if (!dump_tcpdiag) {
3114                                 perror("fopen dump file");
3115                                 exit(-1);
3116                         }
3117                 }
3118                 inet_show_netlink(&current_filter, dump_fp, IPPROTO_TCP);
3119                 fflush(dump_fp);
3120                 exit(0);
3121         }
3122
3123         netid_width = 0;
3124         if (current_filter.dbs&(current_filter.dbs-1))
3125                 netid_width = 5;
3126
3127         state_width = 0;
3128         if (current_filter.states&(current_filter.states-1))
3129                 state_width = 10;
3130
3131         screen_width = 80;
3132         if (isatty(STDOUT_FILENO)) {
3133                 struct winsize w;
3134
3135                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
3136                         if (w.ws_col > 0)
3137                                 screen_width = w.ws_col;
3138                 }
3139         }
3140
3141         addrp_width = screen_width;
3142         addrp_width -= netid_width+1;
3143         addrp_width -= state_width+1;
3144         addrp_width -= 14;
3145
3146         if (addrp_width&1) {
3147                 if (netid_width)
3148                         netid_width++;
3149                 else if (state_width)
3150                         state_width++;
3151         }
3152
3153         addrp_width /= 2;
3154         addrp_width--;
3155
3156         serv_width = resolve_services ? 7 : 5;
3157
3158         if (addrp_width < 15+serv_width+1)
3159                 addrp_width = 15+serv_width+1;
3160
3161         addr_width = addrp_width - serv_width - 1;
3162
3163         if (netid_width)
3164                 printf("%-*s ", netid_width, "Netid");
3165         if (state_width)
3166                 printf("%-*s ", state_width, "State");
3167         printf("%-6s %-6s ", "Recv-Q", "Send-Q");
3168
3169         printf("%*s:%-*s %*s:%-*s\n",
3170                addr_width, "Local Address", serv_width, "Port",
3171                addr_width, "Peer Address", serv_width, "Port");
3172
3173         fflush(stdout);
3174
3175         if (current_filter.dbs & (1<<NETLINK_DB))
3176                 netlink_show(&current_filter);
3177         if (current_filter.dbs & PACKET_DBM)
3178                 packet_show(&current_filter);
3179         if (current_filter.dbs & UNIX_DBM)
3180                 unix_show(&current_filter);
3181         if (current_filter.dbs & (1<<RAW_DB))
3182                 raw_show(&current_filter);
3183         if (current_filter.dbs & (1<<UDP_DB))
3184                 udp_show(&current_filter);
3185         if (current_filter.dbs & (1<<TCP_DB))
3186                 tcp_show(&current_filter, IPPROTO_TCP);
3187         if (current_filter.dbs & (1<<DCCP_DB))
3188                 tcp_show(&current_filter, IPPROTO_DCCP);
3189         return 0;
3190 }