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