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