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