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