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