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