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