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