]> rtime.felk.cvut.cz Git - lisovros/iproute2_canprio.git/blob - misc/ss.c
Initial revision
[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 static 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 static 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 static 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 static int get_dns_host(struct aafilter *a, const 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 static int xll_initted = 0;
923
924 static 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 static 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 static int xll_name_to_index(const 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 static 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 static 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 static char *sprint_bw(char *buf, double bw)
1292 {
1293         if (bw > 1000000.) 
1294                 sprintf(buf,"%.1fM", bw / 1000000.);
1295         else if (bw > 1000.)
1296                 sprintf(buf,"%.1fK", bw / 1000.);
1297         else
1298                 sprintf(buf, "%g", bw);
1299
1300         return buf;
1301 }
1302
1303 static void tcp_show_info(const struct nlmsghdr *nlh, struct tcpdiagmsg *r)
1304 {
1305         struct rtattr * tb[TCPDIAG_MAX+1];
1306         char b1[64];
1307         double rtt = 0;
1308
1309         memset(tb, 0, sizeof(tb));
1310         parse_rtattr(tb, TCPDIAG_MAX, (struct rtattr*)(r+1),
1311                      nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1312
1313         if (tb[TCPDIAG_MEMINFO]) {
1314                 const struct tcpdiag_meminfo *minfo
1315                         = RTA_DATA(tb[TCPDIAG_MEMINFO]);
1316                 printf(" mem:(r%u,w%u,f%u,t%u)",
1317                        minfo->tcpdiag_rmem,
1318                        minfo->tcpdiag_wmem,
1319                        minfo->tcpdiag_fmem,
1320                        minfo->tcpdiag_tmem);
1321         }
1322
1323         if (tb[TCPDIAG_INFO]) {
1324                 struct tcp_info *info;
1325                 int len = RTA_PAYLOAD(tb[TCPDIAG_INFO]);
1326
1327                 /* workaround for older kernels with less fields */
1328                 if (len < sizeof(*info)) {
1329                         info = alloca(sizeof(*info));
1330                         memset(info, 0, sizeof(*info));
1331                         memcpy(info, RTA_DATA(tb[TCPDIAG_INFO]), len);
1332                 } else
1333                         info = RTA_DATA(tb[TCPDIAG_INFO]);
1334
1335                 if (show_options) {
1336                         if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1337                                 printf(" ts");
1338                         if (info->tcpi_options & TCPI_OPT_SACK)
1339                                 printf(" sack");
1340                         if (info->tcpi_options & TCPI_OPT_ECN)
1341                                 printf(" ecn");
1342                 }
1343                 if (info->tcpi_options & TCPI_OPT_WSCALE) 
1344                         printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1345                                info->tcpi_rcv_wscale);
1346                 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1347                         printf(" rto:%g", (double)info->tcpi_rto/1000);
1348                 if (info->tcpi_rtt)
1349                         printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1350                                (double)info->tcpi_rttvar/1000);
1351                 if (info->tcpi_ato)
1352                         printf(" ato:%g", (double)info->tcpi_ato/1000);
1353                 if (info->tcpi_snd_cwnd != 2)
1354                         printf(" cwnd:%d", info->tcpi_snd_cwnd);
1355                 if (info->tcpi_snd_ssthresh < 0xFFFF)
1356                         printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1357                 
1358                 rtt = (double) info->tcpi_rtt;
1359                 if (tb[TCPDIAG_VEGASINFO]) {
1360                         const struct tcpvegas_info *vinfo
1361                                 = RTA_DATA(tb[TCPDIAG_VEGASINFO]);
1362
1363                         if (vinfo->tcpv_enabled)
1364                                 printf(" vegas");
1365
1366                         if (vinfo->tcpv_rtt && 
1367                             vinfo->tcpv_rtt != 0x7fffffff)
1368                             rtt =  vinfo->tcpv_rtt;
1369                 }
1370
1371                 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1372                         printf(" send %sbps",
1373                                sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1374                                          (double) info->tcpi_snd_mss * 8000000.
1375                                          / rtt));
1376                 }
1377
1378                 if (info->tcpi_rcv_rtt)
1379                         printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1380                 if (info->tcpi_rcv_space)
1381                         printf(" rcv_space:%d", info->tcpi_rcv_space);
1382
1383         }
1384 }
1385
1386 int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
1387 {
1388         struct tcpdiagmsg *r = NLMSG_DATA(nlh);
1389         struct tcpstat s;
1390
1391         s.state = r->tcpdiag_state;
1392         s.local.family = s.remote.family = r->tcpdiag_family;
1393         s.lport = ntohs(r->id.tcpdiag_sport);
1394         s.rport = ntohs(r->id.tcpdiag_dport);
1395         if (s.local.family == AF_INET) {
1396                 s.local.bytelen = s.remote.bytelen = 4;
1397         } else {
1398                 s.local.bytelen = s.remote.bytelen = 16;
1399         }
1400         memcpy(s.local.data, r->id.tcpdiag_src, s.local.bytelen);
1401         memcpy(s.remote.data, r->id.tcpdiag_dst, s.local.bytelen);
1402
1403         if (f && f->f && run_ssfilter(f->f, &s) == 0)
1404                 return 0;
1405
1406         if (netid_width)
1407                 printf("%-*s ", netid_width, "tcp");
1408         if (state_width)
1409                 printf("%-*s ", state_width, sstate_name[s.state]);
1410
1411         printf("%-6d %-6d ", r->tcpdiag_rqueue, r->tcpdiag_wqueue);
1412
1413         formatted_print(&s.local, s.lport);
1414         formatted_print(&s.remote, s.rport);
1415
1416         if (show_options) {
1417                 if (r->tcpdiag_timer) {
1418                         if (r->tcpdiag_timer > 4)
1419                                 r->tcpdiag_timer = 5;
1420                         printf(" timer:(%s,%s,%d)",
1421                                tmr_name[r->tcpdiag_timer],
1422                                print_ms_timer(r->tcpdiag_expires),
1423                                r->tcpdiag_retrans);
1424                 }
1425         }
1426         if (show_users) {
1427                 char ubuf[4096];
1428                 if (find_users(r->tcpdiag_inode, ubuf, sizeof(ubuf)) > 0)
1429                         printf(" users:(%s)", ubuf);
1430         }
1431         if (show_details) {
1432                 if (r->tcpdiag_uid)
1433                         printf(" uid:%u", (unsigned)r->tcpdiag_uid);
1434                 printf(" ino:%u", (unsigned)r->tcpdiag_inode);
1435                 printf(" sk:%08x", r->id.tcpdiag_cookie[0]);
1436                 if (r->id.tcpdiag_cookie[1] != 0)
1437                         printf("%08x", r->id.tcpdiag_cookie[1]);
1438         }
1439         if (show_mem || show_tcpinfo) {
1440                 printf("\n\t");
1441                 tcp_show_info(nlh, r);
1442         }
1443
1444         printf("\n");
1445
1446         return 0;
1447
1448 }
1449
1450 int tcp_show_netlink(struct filter *f, FILE *dump_fp)
1451 {
1452         int fd;
1453         struct sockaddr_nl nladdr;
1454         struct {
1455                 struct nlmsghdr nlh;
1456                 struct tcpdiagreq r;
1457         } req;
1458         char    *bc = NULL;
1459         int     bclen;
1460         struct msghdr msg;
1461         struct rtattr rta;
1462         char    buf[8192];
1463         struct iovec iov[3];
1464
1465         if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TCPDIAG)) < 0)
1466                 return -1;
1467
1468         memset(&nladdr, 0, sizeof(nladdr));
1469         nladdr.nl_family = AF_NETLINK;
1470
1471         req.nlh.nlmsg_len = sizeof(req);
1472         req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
1473         req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1474         req.nlh.nlmsg_pid = 0;
1475         req.nlh.nlmsg_seq = 123456;
1476         memset(&req.r, 0, sizeof(req.r));
1477         req.r.tcpdiag_family = AF_INET;
1478         req.r.tcpdiag_states = f->states;
1479         if (show_mem)
1480                 req.r.tcpdiag_ext |= (1<<(TCPDIAG_MEMINFO-1)); 
1481
1482         if (show_tcpinfo) {
1483                 req.r.tcpdiag_ext |= (1<<(TCPDIAG_INFO-1));
1484                 req.r.tcpdiag_ext |= (1<<(TCPDIAG_VEGASINFO-1));
1485         }
1486
1487         iov[0] = (struct iovec){ &req, sizeof(req) };
1488         if (f->f) {
1489                 bclen = ssfilter_bytecompile(f->f, &bc);
1490                 rta.rta_type = TCPDIAG_REQ_BYTECODE;
1491                 rta.rta_len = RTA_LENGTH(bclen);
1492                 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1493                 iov[2] = (struct iovec){ bc, bclen };
1494                 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1495         }
1496
1497         msg = (struct msghdr) {
1498                 (void*)&nladdr, sizeof(nladdr),
1499                 iov,    f->f ? 3 : 1,
1500                 NULL,   0,
1501                 0
1502         };
1503
1504         if (sendmsg(fd, &msg, 0) < 0)
1505                 return -1;
1506
1507
1508         iov[0] = (struct iovec){ buf, sizeof(buf) };
1509
1510         while (1) {
1511                 int status;
1512                 struct nlmsghdr *h;
1513
1514                 msg = (struct msghdr) {
1515                         (void*)&nladdr, sizeof(nladdr),
1516                         iov,    1,
1517                         NULL,   0,
1518                         0
1519                 };
1520
1521                 status = recvmsg(fd, &msg, 0);
1522
1523                 if (status < 0) {
1524                         if (errno == EINTR)
1525                                 continue;
1526                         perror("OVERRUN");
1527                         continue;
1528                 }
1529                 if (status == 0) {
1530                         fprintf(stderr, "EOF on netlink\n");
1531                         return 0;
1532                 }
1533
1534                 if (dump_fp)
1535                         fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1536
1537                 h = (struct nlmsghdr*)buf;
1538                 while (NLMSG_OK(h, status)) {
1539                         int err;
1540
1541                         if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1542                             h->nlmsg_seq != 123456)
1543                                 goto skip_it;
1544
1545                         if (h->nlmsg_type == NLMSG_DONE)
1546                                 return 0;
1547                         if (h->nlmsg_type == NLMSG_ERROR) {
1548                                 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1549                                 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1550                                         fprintf(stderr, "ERROR truncated\n");
1551                                 } else {
1552                                         errno = -err->error;
1553                                         perror("TCPDIAG answers");
1554                                 }
1555                                 return 0;
1556                         }
1557                         if (!dump_fp) {
1558                                 err = tcp_show_sock(h, NULL);
1559                                 if (err < 0)
1560                                         return err;
1561                         }
1562
1563 skip_it:
1564                         h = NLMSG_NEXT(h, status);
1565                 }
1566                 if (msg.msg_flags & MSG_TRUNC) {
1567                         fprintf(stderr, "Message truncated\n");
1568                         continue;
1569                 }
1570                 if (status) {
1571                         fprintf(stderr, "!!!Remnant of size %d\n", status);
1572                         exit(1);
1573                 }
1574         }
1575         return 0;
1576 }
1577
1578 int tcp_show_netlink_file(struct filter *f)
1579 {
1580         FILE    *fp;
1581         char    buf[8192];
1582
1583         if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1584                 perror("fopen($TCPDIAG_FILE)");
1585                 return -1;
1586         }
1587
1588         while (1) {
1589                 int status, err;
1590                 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1591
1592                 status = fread(buf, 1, sizeof(*h), fp);
1593                 if (status < 0) {
1594                         perror("Reading header from $TCPDIAG_FILE");
1595                         return -1;
1596                 }
1597                 if (status != sizeof(*h)) {
1598                         perror("Unexpected EOF reading $TCPDIAG_FILE");
1599                         return -1;
1600                 }
1601
1602                 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1603
1604                 if (status < 0) {
1605                         perror("Reading $TCPDIAG_FILE");
1606                         return -1;
1607                 }
1608                 if (status + sizeof(*h) < h->nlmsg_len) {
1609                         perror("Unexpected EOF reading $TCPDIAG_FILE");
1610                         return -1;
1611                 }
1612
1613                 /* The only legal exit point */
1614                 if (h->nlmsg_type == NLMSG_DONE)
1615                         return 0;
1616
1617                 if (h->nlmsg_type == NLMSG_ERROR) {
1618                         struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1619                         if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1620                                 fprintf(stderr, "ERROR truncated\n");
1621                         } else {
1622                                 errno = -err->error;
1623                                 perror("TCPDIAG answered");
1624                         }
1625                         return -1;
1626                 }
1627
1628                 err = tcp_show_sock(h, f);
1629                 if (err < 0)
1630                         return err;
1631         }
1632 }
1633
1634 int tcp_show(struct filter *f)
1635 {
1636         int fd = -1;
1637         char *buf = NULL;
1638         int bufsize = 64*1024;
1639
1640         dg_proto = TCP_PROTO;
1641
1642         if (getenv("TCPDIAG_FILE"))
1643                 return tcp_show_netlink_file(f);
1644
1645         if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
1646             && tcp_show_netlink(f, NULL) == 0)
1647                 return 0;
1648
1649         /* Sigh... We have to parse /proc/net/tcp... */
1650
1651         /* Estimate amount of sockets and try to allocate
1652          * huge buffer to read all the table at one read.
1653          * Limit it by 16MB though. The assumption is: as soon as
1654          * kernel was able to hold information about N connections,
1655          * it is able to give us some memory for snapshot.
1656          */
1657         if (1) {
1658                 int guess = slabstat.socks+slabstat.tcp_syns;
1659                 if (f->states&(1<<SS_TIME_WAIT))
1660                         guess += slabstat.tcp_tws;
1661                 if (guess > (16*1024*1024)/128)
1662                         guess = (16*1024*1024)/128;
1663                 guess *= 128;
1664                 if (guess > bufsize)
1665                         bufsize = guess;
1666         }
1667         while (bufsize >= 64*1024) {
1668                 if ((buf = malloc(bufsize)) != NULL)
1669                         break;
1670                 bufsize /= 2;
1671         }
1672         if (buf == NULL) {
1673                 errno = ENOMEM;
1674                 return -1;
1675         }
1676
1677         if (f->families & (1<<AF_INET)) {
1678                 if ((fd = net_tcp_open()) < 0)
1679                         goto outerr;
1680                 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET))
1681                         goto outerr;
1682                 close(fd);
1683         }
1684
1685         if ((f->families & (1<<AF_INET6)) &&
1686             (fd = net_tcp6_open()) >= 0) {
1687                 if (generic_record_read(fd, buf, bufsize, tcp_show_line, f, AF_INET6))
1688                         goto outerr;
1689                 close(fd);
1690         }
1691
1692         free(buf);
1693         return 0;
1694
1695 outerr:
1696         do {
1697                 int saved_errno = errno;
1698                 if (buf)
1699                         free(buf);
1700                 if (fd >= 0)
1701                         close(fd);
1702                 errno = saved_errno;
1703                 return -1;
1704         } while (0);
1705 }
1706
1707
1708 int dgram_show_line(char *line, struct filter *f, int family)
1709 {
1710         struct tcpstat s;
1711         char *loc, *rem, *data;
1712         char opt[256];
1713         int n;
1714         char *p;
1715
1716         if ((p = strchr(line, ':')) == NULL)
1717                 return -1;
1718         loc = p+2;
1719
1720         if ((p = strchr(loc, ':')) == NULL)
1721                 return -1;
1722         p[5] = 0;
1723         rem = p+6;
1724
1725         if ((p = strchr(rem, ':')) == NULL)
1726                 return -1;
1727         p[5] = 0;
1728         data = p+6;
1729
1730         do {
1731                 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1732
1733                 if (!(f->states & (1<<state)))
1734                         return 0;
1735         } while (0);
1736
1737         s.local.family = s.remote.family = family;
1738         if (family == AF_INET) {
1739                 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1740                 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1741                 s.local.bytelen = s.remote.bytelen = 4;
1742         } else {
1743                 sscanf(loc, "%08x%08x%08x%08x:%x",
1744                        s.local.data,
1745                        s.local.data+1,
1746                        s.local.data+2,
1747                        s.local.data+3,
1748                        &s.lport);
1749                 sscanf(rem, "%08x%08x%08x%08x:%x",
1750                        s.remote.data,
1751                        s.remote.data+1,
1752                        s.remote.data+2,
1753                        s.remote.data+3,
1754                        &s.rport);
1755                 s.local.bytelen = s.remote.bytelen = 16;
1756         }
1757
1758         if (f->f && run_ssfilter(f->f, &s) == 0)
1759                 return 0;
1760
1761         opt[0] = 0;
1762         n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %d %d %llx %[^\n]\n",
1763                &s.state, &s.wq, &s.rq,
1764                &s.uid, &s.ino,
1765                &s.refcnt, &s.sk, opt);
1766
1767         if (n < 9)
1768                 opt[0] = 0;
1769
1770         if (netid_width)
1771                 printf("%-*s ", netid_width, dg_proto);
1772         if (state_width)
1773                 printf("%-*s ", state_width, sstate_name[s.state]);
1774
1775         printf("%-6d %-6d ", s.rq, s.wq);
1776
1777         formatted_print(&s.local, s.lport);
1778         formatted_print(&s.remote, s.rport);
1779
1780         if (show_users) {
1781                 char ubuf[4096];
1782                 if (find_users(s.ino, ubuf, sizeof(ubuf)) > 0)
1783                         printf(" users:(%s)", ubuf);
1784         }
1785
1786         if (show_details) {
1787                 if (s.uid)
1788                         printf(" uid=%u", (unsigned)s.uid);
1789                 printf(" ino=%u", (unsigned)s.ino);
1790                 printf(" sk=%llx", s.sk);
1791                 if (opt[0])
1792                         printf(" opt:\"%s\"", opt);
1793         }
1794         printf("\n");
1795
1796         return 0;
1797 }
1798
1799
1800 int udp_show(struct filter *f)
1801 {
1802         int fd = -1;
1803         char buf[8192];
1804         int  bufsize = sizeof(buf);
1805
1806         dg_proto = UDP_PROTO;
1807
1808         if (f->families&(1<<AF_INET)) {
1809                 if ((fd = net_udp_open()) < 0)
1810                         goto outerr;
1811                 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1812                         goto outerr;
1813                 close(fd);
1814         }
1815
1816         if ((f->families&(1<<AF_INET6)) &&
1817             (fd = net_udp6_open()) >= 0) {
1818                 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1819                         goto outerr;
1820                 close(fd);
1821         }
1822         return 0;
1823
1824 outerr:
1825         do {
1826                 int saved_errno = errno;
1827                 if (fd >= 0)
1828                         close(fd);
1829                 errno = saved_errno;
1830                 return -1;
1831         } while (0);
1832 }
1833
1834 int raw_show(struct filter *f)
1835 {
1836         int fd = -1;
1837         char buf[8192];
1838         int  bufsize = sizeof(buf);
1839
1840         dg_proto = RAW_PROTO;
1841
1842         if (f->families&(1<<AF_INET)) {
1843                 if ((fd = net_raw_open()) < 0)
1844                         goto outerr;
1845                 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET))
1846                         goto outerr;
1847                 close(fd);
1848         }
1849
1850         if ((f->families&(1<<AF_INET6)) &&
1851             (fd = net_raw6_open()) >= 0) {
1852                 if (generic_record_read(fd, buf, bufsize, dgram_show_line, f, AF_INET6))
1853                         goto outerr;
1854                 close(fd);
1855         }
1856         return 0;
1857
1858 outerr:
1859         do {
1860                 int saved_errno = errno;
1861                 if (fd >= 0)
1862                         close(fd);
1863                 errno = saved_errno;
1864                 return -1;
1865         } while (0);
1866 }
1867
1868
1869 struct unixstat
1870 {
1871         struct unixstat *next;
1872         int ino;
1873         int peer;
1874         int rq;
1875         int wq;
1876         int state;
1877         int type;
1878         char *name;
1879 };
1880
1881
1882
1883 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
1884                          SS_ESTABLISHED, SS_CLOSING };
1885
1886
1887 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
1888
1889 void unix_list_free(struct unixstat *list)
1890 {
1891         while (list) {
1892                 struct unixstat *s = list;
1893                 list = list->next;
1894                 if (s->name)
1895                         free(s->name);
1896                 free(s);
1897         }
1898 }
1899
1900 void unix_list_print(struct unixstat *list, struct filter *f)
1901 {
1902         struct unixstat *s;
1903         char *peer;
1904
1905         for (s = list; s; s = s->next) {
1906                 if (!(f->states & (1<<s->state)))
1907                         continue;
1908                 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
1909                         continue;
1910                 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
1911                         continue;
1912
1913                 peer = "*";
1914                 if (s->peer) {
1915                         struct unixstat *p;
1916                         for (p = list; p; p = p->next) {
1917                                 if (s->peer == p->ino)
1918                                         break;
1919                         }
1920                         if (!p) {
1921                                 peer = "?";
1922                         } else {
1923                                 peer = p->name ? : "*";
1924                         }
1925                 }
1926
1927                 if (f->f) {
1928                         struct tcpstat tst;
1929                         tst.local.family = AF_UNIX;
1930                         tst.remote.family = AF_UNIX;
1931                         memcpy(tst.local.data, &s->name, sizeof(s->name));
1932                         if (strcmp(peer, "*") == 0)
1933                                 memset(tst.remote.data, 0, sizeof(peer));
1934                         else
1935                                 memcpy(tst.remote.data, &peer, sizeof(peer));  
1936                         if (run_ssfilter(f->f, &tst) == 0)
1937                                 continue;
1938                 }
1939
1940                 if (netid_width)
1941                         printf("%-*s ", netid_width, 
1942                                s->type == SOCK_STREAM ? "u_str" : "u_dgr");
1943                 if (state_width)
1944                         printf("%-*s ", state_width, sstate_name[s->state]);
1945                 printf("%-6d %-6d ", s->rq, s->wq);
1946                 printf("%*s %-*d %*s %-*d",
1947                        addr_width, s->name ? : "*", serv_width, s->ino,
1948                        addr_width, peer, serv_width, s->peer);
1949                 if (show_users) {
1950                         char ubuf[4096];
1951                         if (find_users(s->ino, ubuf, sizeof(ubuf)) > 0)
1952                                 printf(" users:(%s)", ubuf);
1953                 }
1954                 printf("\n");
1955         }
1956 }
1957
1958 int unix_show(struct filter *f)
1959 {
1960         FILE *fp;
1961         char buf[256];
1962         char name[128];
1963         int  newformat = 0;
1964         int  cnt;
1965         struct unixstat *list = NULL;
1966
1967         if ((fp = fdopen(net_unix_open(), "r")) == NULL)
1968                 return -1;
1969         fgets(buf, sizeof(buf)-1, fp);
1970
1971         if (memcmp(buf, "Peer", 4) == 0) 
1972                 newformat = 1;
1973         cnt = 0;
1974
1975         while (fgets(buf, sizeof(buf)-1, fp)) {
1976                 struct unixstat *u, **insp;
1977                 int flags;
1978
1979                 if (!(u = malloc(sizeof(*u))))
1980                         break;
1981                 u->name = NULL;
1982
1983                 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
1984                            &u->peer, &u->rq, &u->wq, &flags, &u->type,
1985                            &u->state, &u->ino, name) < 8)
1986                         name[0] = 0;
1987
1988                 if (flags&(1<<16)) {
1989                         u->state = SS_LISTEN;
1990                 } else {
1991                         u->state = unix_state_map[u->state-1];
1992                         if (u->type == SOCK_DGRAM &&
1993                             u->state == SS_CLOSE &&
1994                             u->peer)
1995                                 u->state = SS_ESTABLISHED;
1996                 }
1997
1998                 if (!newformat) {
1999                         u->peer = 0;
2000                         u->rq = 0;
2001                         u->wq = 0;
2002                 }
2003
2004                 insp = &list;
2005                 while (*insp) {
2006                         if (u->type < (*insp)->type ||
2007                             (u->type == (*insp)->type &&
2008                              u->ino < (*insp)->ino))
2009                                 break;
2010                         insp = &(*insp)->next;
2011                 }
2012                 u->next = *insp;
2013                 *insp = u;
2014
2015                 if (name[0]) {
2016                         if ((u->name = malloc(strlen(name)+1)) == NULL)
2017                                 break;
2018                         strcpy(u->name, name);
2019                 }
2020                 if (++cnt > MAX_UNIX_REMEMBER) {
2021                         unix_list_print(list, f);
2022                         unix_list_free(list);
2023                         list = NULL;
2024                         cnt = 0;
2025                 }
2026         }
2027
2028         if (list) {
2029                 unix_list_print(list, f);
2030                 unix_list_free(list);
2031                 list = NULL;
2032                 cnt = 0;
2033         }
2034
2035         return 0;
2036 }
2037
2038
2039 int packet_show(struct filter *f)
2040 {
2041         FILE *fp;
2042         char buf[256];
2043         int type;
2044         int prot;
2045         int iface;
2046         int state;
2047         int rq;
2048         int uid;
2049         int ino;
2050         unsigned long long sk;
2051
2052         if (!(f->states & (1<<SS_CLOSE)))
2053                 return 0;
2054
2055         if ((fp = fdopen(net_packet_open(), "r")) == NULL)
2056                 return -1;
2057         fgets(buf, sizeof(buf)-1, fp);
2058
2059         while (fgets(buf, sizeof(buf)-1, fp)) {
2060                 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2061                        &sk,
2062                        &type, &prot, &iface, &state,
2063                        &rq, &uid, &ino);
2064
2065                 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2066                         continue;
2067                 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2068                         continue;
2069                 if (f->f) {
2070                         struct tcpstat tst;
2071                         tst.local.family = AF_PACKET;
2072                         tst.remote.family = AF_PACKET;
2073                         tst.rport = 0;
2074                         tst.lport = iface;
2075                         tst.local.data[0] = prot;
2076                         tst.remote.data[0] = 0;
2077                         if (run_ssfilter(f->f, &tst) == 0)
2078                                 continue;
2079                 }
2080
2081                 if (netid_width)
2082                         printf("%-*s ", netid_width, 
2083                                type == SOCK_RAW ? "p_raw" : "p_dgr");
2084                 if (state_width)
2085                         printf("%-*s ", state_width, "UNCONN");
2086                 printf("%-6d %-6d ", rq, 0);
2087                 if (prot == 3) {
2088                         printf("%*s:", addr_width, "*");
2089                 } else {
2090                         char tb[16];
2091                         printf("%*s:", addr_width, 
2092                                ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2093                 }
2094                 if (iface == 0) {
2095                         printf("%-*s ", serv_width, "*");
2096                 } else {
2097                         printf("%-*s ", serv_width, xll_index_to_name(iface));
2098                 }
2099                 printf("%*s*%-*s",
2100                        addr_width, "", serv_width, "");
2101
2102                 if (show_users) {
2103                         char ubuf[4096];
2104                         if (find_users(ino, ubuf, sizeof(ubuf)) > 0)
2105                                 printf(" users:(%s)", ubuf);
2106                 }
2107                 if (show_details) {
2108                         printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2109                 }
2110                 printf("\n");
2111         }
2112
2113         return 0;
2114 }
2115
2116 int netlink_show(struct filter *f)
2117 {
2118         FILE *fp;
2119         char buf[256];
2120         int prot, pid;
2121         unsigned groups;
2122         int rq, wq, rc;
2123         unsigned long long sk, cb;
2124
2125         if (!(f->states & (1<<SS_CLOSE)))
2126                 return 0;
2127
2128         if ((fp = fdopen(net_netlink_open(), "r")) == NULL)
2129                 return -1;
2130         fgets(buf, sizeof(buf)-1, fp);
2131
2132         while (fgets(buf, sizeof(buf)-1, fp)) {
2133                 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2134                        &sk,
2135                        &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2136
2137                 if (f->f) {
2138                         struct tcpstat tst;
2139                         tst.local.family = AF_NETLINK;
2140                         tst.remote.family = AF_NETLINK;
2141                         tst.rport = -1;
2142                         tst.lport = pid;
2143                         tst.local.data[0] = prot;
2144                         tst.remote.data[0] = 0;
2145                         if (run_ssfilter(f->f, &tst) == 0)
2146                                 continue;
2147                 }
2148
2149                 if (netid_width)
2150                         printf("%-*s ", netid_width, "nl"); 
2151                 if (state_width)
2152                         printf("%-*s ", state_width, "UNCONN");
2153                 printf("%-6d %-6d ", rq, wq);
2154                 if (resolve_services && prot == 0)
2155                         printf("%*s:", addr_width, "rtnl");
2156                 else if (resolve_services && prot == 3)
2157                         printf("%*s:", addr_width, "fw");
2158                 else if (resolve_services && prot == 4)
2159                         printf("%*s:", addr_width, "tcpdiag");
2160                 else
2161                         printf("%*d:", addr_width, prot);
2162                 if (pid == -1) {
2163                         printf("%-*s ", serv_width, "*");
2164                 } else if (resolve_services) {
2165                         int done = 0;
2166                         if (!pid) {
2167                                 done = 1;
2168                                 printf("%-*s ", serv_width, "kernel");
2169                         } else if (pid > 0) {
2170                                 char procname[64];
2171                                 FILE *fp;
2172                                 sprintf(procname, "%s/%d/stat",
2173                                         getenv("PROC_ROOT") ? : "/proc", pid);
2174                                 if ((fp = fopen(procname, "r")) != NULL) {
2175                                         if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2176                                                 sprintf(procname+strlen(procname), "/%d", pid);  
2177                                                 printf("%-*s ", serv_width, procname);
2178                                                 done = 1;
2179                                         }
2180                                         fclose(fp);
2181                                 }
2182                         }
2183                         if (!done)
2184                                 printf("%-*d ", serv_width, pid);
2185                 } else {
2186                         printf("%-*d ", serv_width, pid);
2187                 }
2188                 printf("%*s*%-*s",
2189                        addr_width, "", serv_width, "");
2190
2191                 if (show_details) {
2192                         printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2193                 }
2194                 printf("\n");
2195         }
2196
2197         return 0;
2198 }
2199
2200 struct snmpstat
2201 {
2202         int tcp_estab;
2203 };
2204
2205 int get_snmp_int(char *proto, char *key, int *result)
2206 {
2207         char buf[1024];
2208         FILE *fp;
2209         int protolen = strlen(proto);
2210         int keylen = strlen(key);
2211
2212         *result = 0;
2213
2214         if ((fp = fdopen(net_snmp_open(), "r")) == NULL)
2215                 return -1;
2216
2217         while (fgets(buf, sizeof(buf), fp) != NULL) {
2218                 char *p = buf;
2219                 int  pos = 0;
2220                 if (memcmp(buf, proto, protolen))
2221                         continue;
2222                 while ((p = strchr(p, ' ')) != NULL) {
2223                         pos++;
2224                         p++;
2225                         if (memcmp(p, key, keylen) == 0 &&
2226                             (p[keylen] == ' ' || p[keylen] == '\n'))
2227                                 break;
2228                 }
2229                 if (fgets(buf, sizeof(buf), fp) == NULL)
2230                         break;
2231                 if (memcmp(buf, proto, protolen))
2232                         break;
2233                 p = buf;
2234                 while ((p = strchr(p, ' ')) != NULL) {
2235                         p++;
2236                         if (--pos == 0) {
2237                                 sscanf(p, "%d", result);
2238                                 fclose(fp);
2239                                 return 0;
2240                         }
2241                 }
2242         }
2243
2244         fclose(fp);
2245         errno = ESRCH;
2246         return -1;
2247 }
2248
2249
2250 /* Get stats from sockstat */
2251
2252 struct sockstat
2253 {
2254         int socks;
2255         int tcp_mem;
2256         int tcp_total;
2257         int tcp_orphans;
2258         int tcp_tws;
2259         int tcp4_hashed;
2260         int udp4;
2261         int raw4;
2262         int frag4;
2263         int frag4_mem;
2264         int tcp6_hashed;
2265         int udp6;
2266         int raw6;
2267         int frag6;
2268         int frag6_mem;
2269 };
2270
2271 static void get_sockstat_line(char *line, struct sockstat *s)
2272 {
2273         char id[256], rem[256];
2274
2275         if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
2276                 return;
2277
2278         if (strcmp(id, "sockets:") == 0)
2279                 sscanf(rem, "%*s%d", &s->socks);
2280         else if (strcmp(id, "UDP:") == 0)
2281                 sscanf(rem, "%*s%d", &s->udp4);
2282         else if (strcmp(id, "UDP6:") == 0)
2283                 sscanf(rem, "%*s%d", &s->udp6);
2284         else if (strcmp(id, "RAW:") == 0)
2285                 sscanf(rem, "%*s%d", &s->raw4);
2286         else if (strcmp(id, "RAW6:") == 0)
2287                 sscanf(rem, "%*s%d", &s->raw6);
2288         else if (strcmp(id, "TCP6:") == 0)
2289                 sscanf(rem, "%*s%d", &s->tcp6_hashed);
2290         else if (strcmp(id, "FRAG:") == 0)
2291                 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
2292         else if (strcmp(id, "FRAG6:") == 0)
2293                 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
2294         else if (strcmp(id, "TCP:") == 0)
2295                 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
2296                        &s->tcp4_hashed,
2297                        &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
2298 }
2299
2300 int get_sockstat(struct sockstat *s)
2301 {
2302         char buf[256];
2303         FILE *fp;
2304
2305         memset(s, 0, sizeof(*s));
2306
2307         if ((fp = fdopen(net_sockstat_open(), "r")) == NULL)
2308                 return -1;
2309         while(fgets(buf, sizeof(buf), fp) != NULL)
2310                 get_sockstat_line(buf, s);
2311         fclose(fp);
2312
2313         if ((fp = fdopen(net_sockstat6_open(), "r")) == NULL)
2314                 return 0;
2315         while(fgets(buf, sizeof(buf), fp) != NULL)
2316                 get_sockstat_line(buf, s);
2317         fclose(fp);
2318
2319         return 0;
2320 }
2321
2322 int print_summary(void)
2323 {
2324         struct sockstat s;
2325         struct snmpstat sn;
2326
2327         if (get_sockstat(&s) < 0)
2328                 perror("ss: get_sockstat");
2329         if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
2330                 perror("ss: get_snmpstat");
2331
2332         printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
2333
2334         printf("TCP:   %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
2335                s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
2336                sn.tcp_estab,
2337                s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
2338                s.tcp_orphans,
2339                slabstat.tcp_syns,
2340                s.tcp_tws, slabstat.tcp_tws,
2341                slabstat.tcp_ports
2342                );
2343
2344         printf("\n");
2345         printf("Transport Total     IP        IPv6\n");
2346         printf("*         %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
2347         printf("RAW       %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
2348         printf("UDP       %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
2349         printf("TCP       %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
2350         printf("INET      %-9d %-9d %-9d\n", 
2351                s.raw4+s.udp4+s.tcp4_hashed+
2352                s.raw6+s.udp6+s.tcp6_hashed,
2353                s.raw4+s.udp4+s.tcp4_hashed,
2354                s.raw6+s.udp6+s.tcp6_hashed);
2355         printf("FRAG      %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
2356
2357         printf("\n");
2358
2359         return 0;
2360 }
2361
2362
2363 static void usage(void) __attribute__((noreturn));
2364
2365 static void usage(void)
2366 {
2367         fprintf(stderr,
2368 "Usage: ss [ OPTIONS ]\n"
2369 "       ss [ OPTIONS ] [ FILTER ]\n"
2370 "   -h, --help          this message\n"
2371 "   -V, --version       output version information\n"
2372 "   -n, --numeric       don't resolve service names\n"
2373 "   -r, --resolve       resolve host names\n"
2374 "   -a, --all           display all sockets\n"
2375 "   -l, --listening     display listening sockets\n"
2376 "   -o, --options       show timer information\n"
2377 "   -e, --extended      show detailed socket information\n"
2378 "   -m, --memory        show socket memory usage\n"
2379 "   -p, --processes     show process using socket\n"
2380 "   -i, --info          show internal TCP information\n"
2381 "   -s, --summary       show socket usage summary\n"
2382 "\n"
2383 "   -4, --ipv4          display only IP version 4 sockets\n"
2384 "   -6, --ipv6          display only IP version 6 sockets\n"
2385 "   -0, --packet        display PACKET sockets\n"
2386 "   -t, --tcp           display only TCP sockets\n"
2387 "   -u, --udp           display only UDP sockets\n"
2388 "   -w, --raw           display only RAW sockets\n"
2389 "   -x, --unix          display only Unix domain sockets\n"
2390 "   -f, --family=FAMILY display sockets of type FAMILY\n"
2391 "\n"
2392 "   -A, --query=QUERY\n"
2393 "       QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
2394 "\n"
2395 "   -F, --filter=FILE   read filter information from FILE\n"
2396 "       FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
2397                 );
2398         exit(-1);
2399 }
2400
2401
2402 int scan_state(const char *state)
2403 {
2404         int i;
2405         if (strcasecmp(state, "close") == 0 ||
2406             strcasecmp(state, "closed") == 0)
2407                 return (1<<SS_CLOSE);
2408         if (strcasecmp(state, "syn-rcv") == 0)
2409                 return (1<<SS_SYN_RECV);
2410         if (strcasecmp(state, "established") == 0)
2411                 return (1<<SS_ESTABLISHED);
2412         if (strcasecmp(state, "all") == 0)
2413                 return SS_ALL;
2414         if (strcasecmp(state, "connected") == 0)
2415                 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
2416         if (strcasecmp(state, "synchronized") == 0)
2417                 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
2418         if (strcasecmp(state, "bucket") == 0)
2419                 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
2420         if (strcasecmp(state, "big") == 0)
2421                 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
2422         for (i=0; i<SS_MAX; i++) {
2423                 if (strcasecmp(state, sstate_namel[i]) == 0)
2424                         return (1<<i);
2425         }
2426         return 0;
2427 }
2428
2429 static const struct option long_opts[] = {
2430         { "numeric", 0, 0, 'n' },
2431         { "resolve", 0, 0, 'r' },
2432         { "options", 0, 0, 'o' },
2433         { "extended", 0, 0, 'e' },
2434         { "memory", 0, 0, 'm' },
2435         { "info", 0, 0, 'i' },
2436         { "processes", 0, 0, 'p' },
2437         { "tcp", 0, 0, 't' },
2438         { "udp", 0, 0, 'u' },
2439         { "raw", 0, 0, 'w' },
2440         { "unix", 0, 0, 'x' },
2441         { "all", 0, 0, 'a' },
2442         { "listening", 0, 0, 'l' },
2443         { "ipv4", 0, 0, '4' },
2444         { "ipv6", 0, 0, '6' },
2445         { "packet", 0, 0, '0' },
2446         { "family", 1, 0, 'f' },
2447         { "socket", 1, 0, 'A' },
2448         { "summaary", 0, 0, 's' },
2449         { "diag", 0, 0, 'D' },
2450         { "filter", 1, 0, 'F' },
2451         { "version", 0, 0, 'V' },
2452         { "help", 0, 0, 'h' },
2453         { 0 }
2454         
2455 };
2456
2457 int main(int argc, char *argv[])
2458 {
2459         int do_default = 1;
2460         int saw_states = 0;
2461         int saw_query = 0;
2462         int do_summary = 0;
2463         const char *dump_tcpdiag = NULL;
2464         FILE *filter_fp = NULL;
2465         int ch;
2466
2467         memset(&current_filter, 0, sizeof(current_filter));
2468
2469         current_filter.states = default_filter.states;
2470
2471         while ((ch = getopt_long(argc, argv, "haletuwxnro460spf:miA:D:F:vV",
2472                                  long_opts, NULL)) != EOF) {
2473                 switch(ch) {
2474                 case 'n':
2475                         resolve_services = 0;
2476                         break;
2477                 case 'r':
2478                         resolve_hosts = 1;
2479                         break;
2480                 case 'o':
2481                         show_options = 1;
2482                         break;
2483                 case 'e':
2484                         show_options = 1;
2485                         show_details++;
2486                         break;
2487                 case 'm':
2488                         show_mem = 1;
2489                         break;
2490                 case 'i':
2491                         show_tcpinfo = 1;
2492                         break;
2493                 case 'p':
2494                         show_users++;
2495                         break;
2496                 case 't':
2497                         current_filter.dbs |= (1<<TCP_DB);
2498                         do_default = 0;
2499                         break;
2500                 case 'u':
2501                         current_filter.dbs |= (1<<UDP_DB);
2502                         do_default = 0;
2503                         break;
2504                 case 'w':
2505                         current_filter.dbs |= (1<<RAW_DB);
2506                         do_default = 0;
2507                         break;
2508                 case 'x':
2509                         current_filter.dbs |= UNIX_DBM;
2510                         do_default = 0;
2511                         break;
2512                 case 'a':
2513                         current_filter.states = SS_ALL;
2514                         break;
2515                 case 'l':
2516                         current_filter.states = (1<<SS_LISTEN);
2517                         break;
2518                 case '4':
2519                         preferred_family = AF_INET;
2520                         break;
2521                 case '6':
2522                         preferred_family = AF_INET6;
2523                         break;
2524                 case '0':
2525                         preferred_family = AF_PACKET;
2526                         break;
2527                 case 'f':
2528                         if (strcmp(optarg, "inet") == 0)
2529                                 preferred_family = AF_INET;
2530                         else if (strcmp(optarg, "inet6") == 0)
2531                                 preferred_family = AF_INET6;
2532                         else if (strcmp(optarg, "link") == 0)
2533                                 preferred_family = AF_PACKET;
2534                         else if (strcmp(optarg, "unix") == 0)
2535                                 preferred_family = AF_UNIX;
2536                         else if (strcmp(optarg, "netlink") == 0)
2537                                 preferred_family = AF_NETLINK;
2538                         else if (strcmp(optarg, "help") == 0)
2539                                 usage();
2540                         else {
2541                                 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
2542                                 usage();
2543                         }
2544                         break;
2545                 case 'A':
2546                 {
2547                         char *p, *p1;
2548                         if (!saw_query) {
2549                                 current_filter.dbs = 0;
2550                                 saw_query = 1;
2551                                 do_default = 0;
2552                         }
2553                         p = p1 = optarg;
2554                         do {
2555                                 if ((p1 = strchr(p, ',')) != NULL)
2556                                         *p1 = 0; 
2557                                 if (strcmp(p, "all") == 0) {
2558                                         current_filter.dbs = ALL_DB;
2559                                 } else if (strcmp(p, "inet") == 0) {
2560                                         current_filter.dbs |= (1<<TCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
2561                                 } else if (strcmp(p, "udp") == 0) {
2562                                         current_filter.dbs |= (1<<UDP_DB);
2563                                 } else if (strcmp(p, "tcp") == 0) {
2564                                         current_filter.dbs |= (1<<TCP_DB);
2565                                 } else if (strcmp(p, "raw") == 0) {
2566                                         current_filter.dbs |= (1<<RAW_DB);
2567                                 } else if (strcmp(p, "unix") == 0) {
2568                                         current_filter.dbs |= UNIX_DBM;
2569                                 } else if (strcasecmp(p, "unix_stream") == 0 ||
2570                                            strcmp(p, "u_str") == 0) {
2571                                         current_filter.dbs |= (1<<UNIX_ST_DB);
2572                                 } else if (strcasecmp(p, "unix_dgram") == 0 ||
2573                                            strcmp(p, "u_dgr") == 0) {
2574                                         current_filter.dbs |= (1<<UNIX_DG_DB);
2575                                 } else if (strcmp(p, "packet") == 0) {
2576                                         current_filter.dbs |= PACKET_DBM;
2577                                 } else if (strcmp(p, "packet_raw") == 0 ||
2578                                            strcmp(p, "p_raw") == 0) {
2579                                         current_filter.dbs |= (1<<PACKET_R_DB);
2580                                 } else if (strcmp(p, "packet_dgram") == 0 ||
2581                                            strcmp(p, "p_dgr") == 0) {
2582                                         current_filter.dbs |= (1<<PACKET_DG_DB);
2583                                 } else if (strcmp(p, "netlink") == 0) {
2584                                         current_filter.dbs |= (1<<NETLINK_DB);
2585                                 } else {
2586                                         fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
2587                                         usage();
2588                                 }
2589                                 p = p1 + 1;
2590                         } while (p1);
2591                         break;
2592                 }
2593                 case 's':
2594                         do_summary = 1;
2595                         break;
2596                 case 'D':
2597                         dump_tcpdiag = optarg;
2598                         break;
2599                 case 'F':
2600                         if (filter_fp) {
2601                                 fprintf(stderr, "More than one filter file\n");
2602                                 exit(-1);
2603                         }
2604                         if (optarg[0] == '-')
2605                                 filter_fp = stdin;
2606                         else
2607                                 filter_fp = fopen(optarg, "r");
2608                         if (!filter_fp) {
2609                                 perror("fopen filter file");
2610                                 exit(-1);
2611                         }
2612                         break;
2613                 case 'v':
2614                 case 'V':
2615                         printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
2616                         exit(0);
2617                 case 'h':
2618                 case '?':
2619                 default:
2620                         usage();
2621                 }
2622         }
2623
2624         argc -= optind;
2625         argv += optind;
2626
2627         get_slabstat(&slabstat);
2628
2629         if (do_summary) {
2630                 print_summary();
2631                 if (do_default && argc == 0)
2632                         exit(0);
2633         }
2634
2635         if (do_default)
2636                 current_filter.dbs = default_filter.dbs;
2637
2638         if (preferred_family == AF_UNSPEC) {
2639                 if (!(current_filter.dbs&~UNIX_DBM))
2640                         preferred_family = AF_UNIX;
2641                 else if (!(current_filter.dbs&~PACKET_DBM))
2642                         preferred_family = AF_PACKET;
2643                 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
2644                         preferred_family = AF_NETLINK;
2645         }
2646
2647         if (preferred_family != AF_UNSPEC) {
2648                 int mask2;
2649                 if (preferred_family == AF_INET ||
2650                     preferred_family == AF_INET6) {
2651                         mask2= (1<<TCP_DB);
2652                         if (!do_default)
2653                                 mask2 = (1<<UDP_DB)|(1<<RAW_DB);
2654                 } else if (preferred_family == AF_PACKET) {
2655                         mask2 = PACKET_DBM;
2656                 } else if (preferred_family == AF_UNIX) {
2657                         mask2 = UNIX_DBM;
2658                 } else if (preferred_family == AF_NETLINK) {
2659                         mask2 = (1<<NETLINK_DB);
2660                 } else {
2661                         mask2 = 0;
2662                 }
2663
2664                 if (do_default)
2665                         current_filter.dbs = mask2;
2666                 else
2667                         current_filter.dbs &= mask2;
2668                 current_filter.families = (1<<preferred_family);
2669         } else {
2670                 if (!do_default)
2671                         current_filter.families = ~0;
2672                 else
2673                         current_filter.families = default_filter.families;
2674         }
2675         if (current_filter.dbs == 0) {
2676                 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
2677                 exit(0);
2678         }
2679         if (current_filter.families == 0) {
2680                 fprintf(stderr, "ss: no families to show with such filter.\n");
2681                 exit(0);
2682         }
2683
2684         if (resolve_services && resolve_hosts &&
2685             (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB))))
2686                 init_service_resolver();
2687
2688         /* Now parse filter... */
2689         if (argc == 0 && filter_fp) {
2690                 if (ssfilter_parse(&current_filter.f, 0, NULL, filter_fp))
2691                         usage();
2692         }
2693
2694         while (argc > 0) {
2695                 if (strcmp(*argv, "state") == 0) {
2696                         NEXT_ARG();
2697                         if (!saw_states)
2698                                 current_filter.states = 0;
2699                         current_filter.states |= scan_state(*argv);
2700                         saw_states = 1;
2701                 } else if (strcmp(*argv, "exclude") == 0 ||
2702                            strcmp(*argv, "excl") == 0) {
2703                         NEXT_ARG();
2704                         if (!saw_states)
2705                                 current_filter.states = SS_ALL;
2706                         current_filter.states &= ~scan_state(*argv);
2707                         saw_states = 1;
2708                 } else {
2709                         if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
2710                                 usage();
2711                         break;
2712                 }
2713                 argc--; argv++;
2714         }
2715
2716         if (current_filter.states == 0) {
2717                 fprintf(stderr, "ss: no socket states to show with such filter.\n");
2718                 exit(0);
2719         }
2720
2721         if (dump_tcpdiag) {
2722                 FILE *dump_fp = stdout;
2723                 if (!(current_filter.dbs & (1<<TCP_DB))) {
2724                         fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
2725                         exit(0);
2726                 }
2727                 if (dump_tcpdiag[0] != '-') {
2728                         dump_fp = fopen(dump_tcpdiag, "w");
2729                         if (!dump_tcpdiag) {
2730                                 perror("fopen dump file");
2731                                 exit(-1);
2732                         }
2733                 }
2734                 tcp_show_netlink(&current_filter, dump_fp);
2735                 fflush(dump_fp);
2736                 exit(0);
2737         }
2738
2739         netid_width = 0;
2740         if (current_filter.dbs&(current_filter.dbs-1))
2741                 netid_width = 5;
2742
2743         state_width = 0;
2744         if (current_filter.states&(current_filter.states-1))
2745                 state_width = 10;
2746
2747         screen_width = 80;
2748         if (isatty(STDOUT_FILENO)) {
2749                 struct winsize w;
2750
2751                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
2752                         if (w.ws_col > 0)
2753                                 screen_width = w.ws_col;
2754                 }
2755         }
2756
2757         addrp_width = screen_width;
2758         addrp_width -= netid_width+1;
2759         addrp_width -= state_width+1;
2760         addrp_width -= 14;
2761
2762         if (addrp_width&1) {
2763                 if (netid_width)
2764                         netid_width++;
2765                 else if (state_width)
2766                         state_width++;
2767         }
2768
2769         addrp_width /= 2;
2770         addrp_width--;
2771
2772         serv_width = resolve_services ? 7 : 5;
2773
2774         if (addrp_width < 15+serv_width+1)
2775                 addrp_width = 15+serv_width+1;
2776
2777         addr_width = addrp_width - serv_width - 1; 
2778
2779         if (netid_width)
2780                 printf("%-*s ", netid_width, "Netid");
2781         if (state_width)
2782                 printf("%-*s ", state_width, "State");
2783         printf("%-6s %-6s ", "Recv-Q", "Send-Q");
2784
2785         printf("%*s:%-*s %*s:%-*s\n",
2786                addr_width, "Local Address", serv_width, "Port",
2787                addr_width, "Peer Address", serv_width, "Port");
2788
2789 //printf("%08x %08x %08x\n", current_filter.dbs, current_filter.states, current_filter.families);
2790         fflush(stdout);
2791
2792         if (current_filter.dbs & (1<<NETLINK_DB))
2793                 netlink_show(&current_filter);
2794         if (current_filter.dbs & PACKET_DBM)
2795                 packet_show(&current_filter);
2796         if (current_filter.dbs & UNIX_DBM)
2797                 unix_show(&current_filter);
2798         if (current_filter.dbs & (1<<RAW_DB))
2799                 raw_show(&current_filter);
2800         if (current_filter.dbs & (1<<UDP_DB))
2801                 udp_show(&current_filter);
2802         if (current_filter.dbs & (1<<TCP_DB))
2803                 tcp_show(&current_filter);
2804         return 0;
2805 }