]> git.proxmox.com Git - mirror_iproute2.git/blob - misc/ss.c
d3c4fa6597ba62d9a106a56fcc4b753e49f37b75
[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 <dirent.h>
26 #include <fnmatch.h>
27 #include <getopt.h>
28
29 #include "utils.h"
30 #include "rt_names.h"
31 #include "ll_map.h"
32 #include "libnetlink.h"
33 #include "SNAPSHOT.h"
34
35 #include <linux/tcp.h>
36 #include <linux/sock_diag.h>
37 #include <linux/inet_diag.h>
38 #include <linux/unix_diag.h>
39 #include <linux/netdevice.h> /* for MAX_ADDR_LEN */
40 #include <linux/filter.h>
41 #include <linux/packet_diag.h>
42 #include <linux/netlink_diag.h>
43
44 #if HAVE_SELINUX
45 #include <selinux/selinux.h>
46 #else
47 /* Stubs for SELinux functions */
48 static int is_selinux_enabled(void)
49 {
50 return -1;
51 }
52
53 static int getpidcon(pid_t pid, char **context)
54 {
55 *context = NULL;
56 return -1;
57 }
58
59 static int getfilecon(char *path, char **context)
60 {
61 *context = NULL;
62 return -1;
63 }
64
65 static int security_get_initial_context(char *name, char **context)
66 {
67 *context = NULL;
68 return -1;
69 }
70 #endif
71
72 int resolve_hosts = 0;
73 int resolve_services = 1;
74 int preferred_family = AF_UNSPEC;
75 int show_options = 0;
76 int show_details = 0;
77 int show_users = 0;
78 int show_mem = 0;
79 int show_tcpinfo = 0;
80 int show_bpf = 0;
81 int show_proc_ctx = 0;
82 int show_sock_ctx = 0;
83 /* If show_users & show_proc_ctx only do user_ent_hash_build() once */
84 int user_ent_hash_build_init = 0;
85
86 int netid_width;
87 int state_width;
88 int addrp_width;
89 int addr_width;
90 int serv_width;
91 int screen_width;
92
93 static const char *TCP_PROTO = "tcp";
94 static const char *UDP_PROTO = "udp";
95 static const char *RAW_PROTO = "raw";
96 static const char *dg_proto = NULL;
97
98 enum
99 {
100 TCP_DB,
101 DCCP_DB,
102 UDP_DB,
103 RAW_DB,
104 UNIX_DG_DB,
105 UNIX_ST_DB,
106 UNIX_SQ_DB,
107 PACKET_DG_DB,
108 PACKET_R_DB,
109 NETLINK_DB,
110 MAX_DB
111 };
112
113 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
114 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
115 #define ALL_DB ((1<<MAX_DB)-1)
116
117 enum {
118 SS_UNKNOWN,
119 SS_ESTABLISHED,
120 SS_SYN_SENT,
121 SS_SYN_RECV,
122 SS_FIN_WAIT1,
123 SS_FIN_WAIT2,
124 SS_TIME_WAIT,
125 SS_CLOSE,
126 SS_CLOSE_WAIT,
127 SS_LAST_ACK,
128 SS_LISTEN,
129 SS_CLOSING,
130 SS_MAX
131 };
132
133 #define SS_ALL ((1<<SS_MAX)-1)
134
135 #include "ssfilter.h"
136
137 struct filter
138 {
139 int dbs;
140 int states;
141 int families;
142 struct ssfilter *f;
143 };
144
145 struct filter default_filter = {
146 .dbs = ~0,
147 .states = SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)),
148 .families= (1<<AF_INET)|(1<<AF_INET6),
149 };
150
151 struct filter current_filter;
152
153 static FILE *generic_proc_open(const char *env, const char *name)
154 {
155 const char *p = getenv(env);
156 char store[128];
157
158 if (!p) {
159 p = getenv("PROC_ROOT") ? : "/proc";
160 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
161 p = store;
162 }
163
164 return fopen(p, "r");
165 }
166
167 static FILE *net_tcp_open(void)
168 {
169 return generic_proc_open("PROC_NET_TCP", "net/tcp");
170 }
171
172 static FILE *net_tcp6_open(void)
173 {
174 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
175 }
176
177 static FILE *net_udp_open(void)
178 {
179 return generic_proc_open("PROC_NET_UDP", "net/udp");
180 }
181
182 static FILE *net_udp6_open(void)
183 {
184 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
185 }
186
187 static FILE *net_raw_open(void)
188 {
189 return generic_proc_open("PROC_NET_RAW", "net/raw");
190 }
191
192 static FILE *net_raw6_open(void)
193 {
194 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
195 }
196
197 static FILE *net_unix_open(void)
198 {
199 return generic_proc_open("PROC_NET_UNIX", "net/unix");
200 }
201
202 static FILE *net_packet_open(void)
203 {
204 return generic_proc_open("PROC_NET_PACKET", "net/packet");
205 }
206
207 static FILE *net_netlink_open(void)
208 {
209 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
210 }
211
212 static FILE *slabinfo_open(void)
213 {
214 return generic_proc_open("PROC_SLABINFO", "slabinfo");
215 }
216
217 static FILE *net_sockstat_open(void)
218 {
219 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
220 }
221
222 static FILE *net_sockstat6_open(void)
223 {
224 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
225 }
226
227 static FILE *net_snmp_open(void)
228 {
229 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
230 }
231
232 static FILE *ephemeral_ports_open(void)
233 {
234 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
235 }
236
237 struct user_ent {
238 struct user_ent *next;
239 unsigned int ino;
240 int pid;
241 int fd;
242 char *process;
243 char *process_ctx;
244 char *socket_ctx;
245 };
246
247 #define USER_ENT_HASH_SIZE 256
248 struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE];
249
250 static int user_ent_hashfn(unsigned int ino)
251 {
252 int val = (ino >> 24) ^ (ino >> 16) ^ (ino >> 8) ^ ino;
253
254 return val & (USER_ENT_HASH_SIZE - 1);
255 }
256
257 static void user_ent_add(unsigned int ino, char *process,
258 int pid, int fd,
259 char *proc_ctx,
260 char *sock_ctx)
261 {
262 struct user_ent *p, **pp;
263
264 p = malloc(sizeof(struct user_ent));
265 if (!p) {
266 fprintf(stderr, "ss: failed to malloc buffer\n");
267 abort();
268 }
269 p->next = NULL;
270 p->ino = ino;
271 p->pid = pid;
272 p->fd = fd;
273 p->process = strdup(process);
274 p->process_ctx = strdup(proc_ctx);
275 p->socket_ctx = strdup(sock_ctx);
276
277 pp = &user_ent_hash[user_ent_hashfn(ino)];
278 p->next = *pp;
279 *pp = p;
280 }
281
282 static void user_ent_destroy(void)
283 {
284 struct user_ent *p, *p_next;
285 int cnt = 0;
286
287 while (cnt != USER_ENT_HASH_SIZE) {
288 p = user_ent_hash[cnt];
289 while (p) {
290 free(p->process);
291 free(p->process_ctx);
292 free(p->socket_ctx);
293 p_next = p->next;
294 free(p);
295 p = p_next;
296 }
297 cnt++;
298 }
299 }
300
301 static void user_ent_hash_build(void)
302 {
303 const char *root = getenv("PROC_ROOT") ? : "/proc/";
304 struct dirent *d;
305 char name[1024];
306 int nameoff;
307 DIR *dir;
308 char *pid_context;
309 char *sock_context;
310 const char *no_ctx = "unavailable";
311
312 /* If show_users & show_proc_ctx set only do this once */
313 if (user_ent_hash_build_init != 0)
314 return;
315
316 user_ent_hash_build_init = 1;
317
318 strcpy(name, root);
319 if (strlen(name) == 0 || name[strlen(name)-1] != '/')
320 strcat(name, "/");
321
322 nameoff = strlen(name);
323
324 dir = opendir(name);
325 if (!dir)
326 return;
327
328 while ((d = readdir(dir)) != NULL) {
329 struct dirent *d1;
330 char process[16];
331 char *p;
332 int pid, pos;
333 DIR *dir1;
334 char crap;
335
336 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
337 continue;
338
339 if (getpidcon(pid, &pid_context) != 0)
340 pid_context = strdup(no_ctx);
341
342 sprintf(name + nameoff, "%d/fd/", pid);
343 pos = strlen(name);
344 if ((dir1 = opendir(name)) == NULL)
345 continue;
346
347 process[0] = '\0';
348 p = process;
349
350 while ((d1 = readdir(dir1)) != NULL) {
351 const char *pattern = "socket:[";
352 unsigned int ino;
353 char lnk[64];
354 int fd;
355 ssize_t link_len;
356 char tmp[1024];
357
358 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
359 continue;
360
361 sprintf(name+pos, "%d", fd);
362
363 link_len = readlink(name, lnk, sizeof(lnk)-1);
364 if (link_len == -1)
365 continue;
366 lnk[link_len] = '\0';
367
368 if (strncmp(lnk, pattern, strlen(pattern)))
369 continue;
370
371 sscanf(lnk, "socket:[%u]", &ino);
372
373 snprintf(tmp, sizeof(tmp), "%s/%d/fd/%s",
374 root, pid, d1->d_name);
375
376 if (getfilecon(tmp, &sock_context) <= 0)
377 sock_context = strdup(no_ctx);
378
379 if (*p == '\0') {
380 FILE *fp;
381
382 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
383 root, pid);
384 if ((fp = fopen(tmp, "r")) != NULL) {
385 fscanf(fp, "%*d (%[^)])", p);
386 fclose(fp);
387 }
388 }
389 user_ent_add(ino, p, pid, fd,
390 pid_context, sock_context);
391 free(sock_context);
392 }
393 free(pid_context);
394 closedir(dir1);
395 }
396 closedir(dir);
397 }
398
399 enum entry_types {
400 USERS,
401 PROC_CTX,
402 PROC_SOCK_CTX
403 };
404
405 #define ENTRY_BUF_SIZE 512
406 static int find_entry(unsigned ino, char **buf, int type)
407 {
408 struct user_ent *p;
409 int cnt = 0;
410 char *ptr;
411 char **new_buf = buf;
412 int len, new_buf_len;
413 int buf_used = 0;
414 int buf_len = 0;
415
416 if (!ino)
417 return 0;
418
419 p = user_ent_hash[user_ent_hashfn(ino)];
420 ptr = *buf = NULL;
421 while (p) {
422 if (p->ino != ino)
423 goto next;
424
425 while (1) {
426 ptr = *buf + buf_used;
427 switch (type) {
428 case USERS:
429 len = snprintf(ptr, buf_len - buf_used,
430 "(\"%s\",pid=%d,fd=%d),",
431 p->process, p->pid, p->fd);
432 break;
433 case PROC_CTX:
434 len = snprintf(ptr, buf_len - buf_used,
435 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
436 p->process, p->pid,
437 p->process_ctx, p->fd);
438 break;
439 case PROC_SOCK_CTX:
440 len = snprintf(ptr, buf_len - buf_used,
441 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
442 p->process, p->pid,
443 p->process_ctx, p->fd,
444 p->socket_ctx);
445 break;
446 default:
447 fprintf(stderr, "ss: invalid type: %d\n", type);
448 abort();
449 }
450
451 if (len < 0 || len >= buf_len - buf_used) {
452 new_buf_len = buf_len + ENTRY_BUF_SIZE;
453 *new_buf = realloc(*buf, new_buf_len);
454 if (!new_buf) {
455 fprintf(stderr, "ss: failed to malloc buffer\n");
456 abort();
457 }
458 **buf = **new_buf;
459 buf_len = new_buf_len;
460 continue;
461 } else {
462 buf_used += len;
463 break;
464 }
465 }
466 cnt++;
467 next:
468 p = p->next;
469 }
470 if (buf_used) {
471 ptr = *buf + buf_used;
472 ptr[-1] = '\0';
473 }
474 return cnt;
475 }
476
477 /* Get stats from slab */
478
479 struct slabstat
480 {
481 int socks;
482 int tcp_ports;
483 int tcp_tws;
484 int tcp_syns;
485 int skbs;
486 };
487
488 struct slabstat slabstat;
489
490 static const char *slabstat_ids[] =
491 {
492 "sock",
493 "tcp_bind_bucket",
494 "tcp_tw_bucket",
495 "tcp_open_request",
496 "skbuff_head_cache",
497 };
498
499 static int get_slabstat(struct slabstat *s)
500 {
501 char buf[256];
502 FILE *fp;
503 int cnt;
504
505 memset(s, 0, sizeof(*s));
506
507 fp = slabinfo_open();
508 if (!fp)
509 return -1;
510
511 cnt = sizeof(*s)/sizeof(int);
512
513 fgets(buf, sizeof(buf), fp);
514 while(fgets(buf, sizeof(buf), fp) != NULL) {
515 int i;
516 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
517 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
518 sscanf(buf, "%*s%d", ((int *)s) + i);
519 cnt--;
520 break;
521 }
522 }
523 if (cnt <= 0)
524 break;
525 }
526
527 fclose(fp);
528 return 0;
529 }
530
531 static const char *sstate_name[] = {
532 "UNKNOWN",
533 [SS_ESTABLISHED] = "ESTAB",
534 [SS_SYN_SENT] = "SYN-SENT",
535 [SS_SYN_RECV] = "SYN-RECV",
536 [SS_FIN_WAIT1] = "FIN-WAIT-1",
537 [SS_FIN_WAIT2] = "FIN-WAIT-2",
538 [SS_TIME_WAIT] = "TIME-WAIT",
539 [SS_CLOSE] = "UNCONN",
540 [SS_CLOSE_WAIT] = "CLOSE-WAIT",
541 [SS_LAST_ACK] = "LAST-ACK",
542 [SS_LISTEN] = "LISTEN",
543 [SS_CLOSING] = "CLOSING",
544 };
545
546 static const char *sstate_namel[] = {
547 "UNKNOWN",
548 [SS_ESTABLISHED] = "established",
549 [SS_SYN_SENT] = "syn-sent",
550 [SS_SYN_RECV] = "syn-recv",
551 [SS_FIN_WAIT1] = "fin-wait-1",
552 [SS_FIN_WAIT2] = "fin-wait-2",
553 [SS_TIME_WAIT] = "time-wait",
554 [SS_CLOSE] = "unconnected",
555 [SS_CLOSE_WAIT] = "close-wait",
556 [SS_LAST_ACK] = "last-ack",
557 [SS_LISTEN] = "listening",
558 [SS_CLOSING] = "closing",
559 };
560
561 struct tcpstat
562 {
563 inet_prefix local;
564 inet_prefix remote;
565 int lport;
566 int rport;
567 int state;
568 int rq, wq;
569 int timer;
570 int timeout;
571 int retrs;
572 unsigned ino;
573 int probes;
574 unsigned uid;
575 int refcnt;
576 unsigned long long sk;
577 int rto, ato, qack, cwnd, ssthresh;
578 };
579
580 static const char *tmr_name[] = {
581 "off",
582 "on",
583 "keepalive",
584 "timewait",
585 "persist",
586 "unknown"
587 };
588
589 static const char *print_ms_timer(int timeout)
590 {
591 static char buf[64];
592 int secs, msecs, minutes;
593 if (timeout < 0)
594 timeout = 0;
595 secs = timeout/1000;
596 minutes = secs/60;
597 secs = secs%60;
598 msecs = timeout%1000;
599 buf[0] = 0;
600 if (minutes) {
601 msecs = 0;
602 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
603 if (minutes > 9)
604 secs = 0;
605 }
606 if (secs) {
607 if (secs > 9)
608 msecs = 0;
609 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
610 }
611 if (msecs)
612 sprintf(buf+strlen(buf), "%03dms", msecs);
613 return buf;
614 }
615
616 static const char *print_hz_timer(int timeout)
617 {
618 int hz = get_user_hz();
619 return print_ms_timer(((timeout*1000) + hz-1)/hz);
620 }
621
622 struct scache
623 {
624 struct scache *next;
625 int port;
626 char *name;
627 const char *proto;
628 };
629
630 struct scache *rlist;
631
632 static void init_service_resolver(void)
633 {
634 char buf[128];
635 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
636 if (fp) {
637 fgets(buf, sizeof(buf), fp);
638 while (fgets(buf, sizeof(buf), fp) != NULL) {
639 unsigned int progn, port;
640 char proto[128], prog[128];
641 if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
642 &port, prog+4) == 4) {
643 struct scache *c = malloc(sizeof(*c));
644 if (c) {
645 c->port = port;
646 memcpy(prog, "rpc.", 4);
647 c->name = strdup(prog);
648 if (strcmp(proto, TCP_PROTO) == 0)
649 c->proto = TCP_PROTO;
650 else if (strcmp(proto, UDP_PROTO) == 0)
651 c->proto = UDP_PROTO;
652 else
653 c->proto = NULL;
654 c->next = rlist;
655 rlist = c;
656 }
657 }
658 }
659 pclose(fp);
660 }
661 }
662
663 static int ip_local_port_min, ip_local_port_max;
664
665 /* Even do not try default linux ephemeral port ranges:
666 * default /etc/services contains so much of useless crap
667 * wouldbe "allocated" to this area that resolution
668 * is really harmful. I shrug each time when seeing
669 * "socks" or "cfinger" in dumps.
670 */
671 static int is_ephemeral(int port)
672 {
673 if (!ip_local_port_min) {
674 FILE *f = ephemeral_ports_open();
675 if (f) {
676 fscanf(f, "%d %d",
677 &ip_local_port_min, &ip_local_port_max);
678 fclose(f);
679 } else {
680 ip_local_port_min = 1024;
681 ip_local_port_max = 4999;
682 }
683 }
684
685 return (port >= ip_local_port_min && port<= ip_local_port_max);
686 }
687
688
689 static const char *__resolve_service(int port)
690 {
691 struct scache *c;
692
693 for (c = rlist; c; c = c->next) {
694 if (c->port == port && c->proto == dg_proto)
695 return c->name;
696 }
697
698 if (!is_ephemeral(port)) {
699 static int notfirst;
700 struct servent *se;
701 if (!notfirst) {
702 setservent(1);
703 notfirst = 1;
704 }
705 se = getservbyport(htons(port), dg_proto);
706 if (se)
707 return se->s_name;
708 }
709
710 return NULL;
711 }
712
713
714 static const char *resolve_service(int port)
715 {
716 static char buf[128];
717 static struct scache cache[256];
718
719 if (port == 0) {
720 buf[0] = '*';
721 buf[1] = 0;
722 return buf;
723 }
724
725 if (resolve_services) {
726 if (dg_proto == RAW_PROTO) {
727 return inet_proto_n2a(port, buf, sizeof(buf));
728 } else {
729 struct scache *c;
730 const char *res;
731 int hash = (port^(((unsigned long)dg_proto)>>2))&255;
732
733 for (c = &cache[hash]; c; c = c->next) {
734 if (c->port == port &&
735 c->proto == dg_proto) {
736 if (c->name)
737 return c->name;
738 goto do_numeric;
739 }
740 }
741
742 if ((res = __resolve_service(port)) != NULL) {
743 if ((c = malloc(sizeof(*c))) == NULL)
744 goto do_numeric;
745 } else {
746 c = &cache[hash];
747 if (c->name)
748 free(c->name);
749 }
750 c->port = port;
751 c->name = NULL;
752 c->proto = dg_proto;
753 if (res) {
754 c->name = strdup(res);
755 c->next = cache[hash].next;
756 cache[hash].next = c;
757 }
758 if (c->name)
759 return c->name;
760 }
761 }
762
763 do_numeric:
764 sprintf(buf, "%u", port);
765 return buf;
766 }
767
768 static void formatted_print(const inet_prefix *a, int port, unsigned int ifindex)
769 {
770 char buf[1024];
771 const char *ap = buf;
772 int est_len;
773
774 est_len = addr_width;
775
776 if (a->family == AF_INET) {
777 if (a->data[0] == 0) {
778 buf[0] = '*';
779 buf[1] = 0;
780 } else {
781 ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
782 }
783 } else {
784 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
785 est_len = strlen(ap);
786 if (est_len <= addr_width)
787 est_len = addr_width;
788 else
789 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
790 }
791 if (ifindex) {
792 const char *ifname = ll_index_to_name(ifindex);
793 const int len = strlen(ifname) + 1; /* +1 for percent char */
794
795 printf("%*s%%%s:%-*s ", est_len - len, ap, ifname, serv_width,
796 resolve_service(port));
797 } else
798 printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
799 }
800
801 struct aafilter
802 {
803 inet_prefix addr;
804 int port;
805 struct aafilter *next;
806 };
807
808 static int inet2_addr_match(const inet_prefix *a, const inet_prefix *p,
809 int plen)
810 {
811 if (!inet_addr_match(a, p, plen))
812 return 0;
813
814 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
815 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
816 * sockets. Fair? */
817 if (p->family == AF_INET && a->family == AF_INET6) {
818 if (a->data[0] == 0 && a->data[1] == 0 &&
819 a->data[2] == htonl(0xffff)) {
820 inet_prefix tmp = *a;
821 tmp.data[0] = a->data[3];
822 return inet_addr_match(&tmp, p, plen);
823 }
824 }
825 return 1;
826 }
827
828 static int unix_match(const inet_prefix *a, const inet_prefix *p)
829 {
830 char *addr, *pattern;
831 memcpy(&addr, a->data, sizeof(addr));
832 memcpy(&pattern, p->data, sizeof(pattern));
833 if (pattern == NULL)
834 return 1;
835 if (addr == NULL)
836 addr = "";
837 return !fnmatch(pattern, addr, 0);
838 }
839
840 static int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
841 {
842 switch (f->type) {
843 case SSF_S_AUTO:
844 {
845 static int low, high=65535;
846
847 if (s->local.family == AF_UNIX) {
848 char *p;
849 memcpy(&p, s->local.data, sizeof(p));
850 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
851 strspn(p+1, "0123456789abcdef") == 5);
852 }
853 if (s->local.family == AF_PACKET)
854 return s->lport == 0 && s->local.data == 0;
855 if (s->local.family == AF_NETLINK)
856 return s->lport < 0;
857
858 if (!low) {
859 FILE *fp = ephemeral_ports_open();
860 if (fp) {
861 fscanf(fp, "%d%d", &low, &high);
862 fclose(fp);
863 }
864 }
865 return s->lport >= low && s->lport <= high;
866 }
867 case SSF_DCOND:
868 {
869 struct aafilter *a = (void*)f->pred;
870 if (a->addr.family == AF_UNIX)
871 return unix_match(&s->remote, &a->addr);
872 if (a->port != -1 && a->port != s->rport)
873 return 0;
874 if (a->addr.bitlen) {
875 do {
876 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
877 return 1;
878 } while ((a = a->next) != NULL);
879 return 0;
880 }
881 return 1;
882 }
883 case SSF_SCOND:
884 {
885 struct aafilter *a = (void*)f->pred;
886 if (a->addr.family == AF_UNIX)
887 return unix_match(&s->local, &a->addr);
888 if (a->port != -1 && a->port != s->lport)
889 return 0;
890 if (a->addr.bitlen) {
891 do {
892 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
893 return 1;
894 } while ((a = a->next) != NULL);
895 return 0;
896 }
897 return 1;
898 }
899 case SSF_D_GE:
900 {
901 struct aafilter *a = (void*)f->pred;
902 return s->rport >= a->port;
903 }
904 case SSF_D_LE:
905 {
906 struct aafilter *a = (void*)f->pred;
907 return s->rport <= a->port;
908 }
909 case SSF_S_GE:
910 {
911 struct aafilter *a = (void*)f->pred;
912 return s->lport >= a->port;
913 }
914 case SSF_S_LE:
915 {
916 struct aafilter *a = (void*)f->pred;
917 return s->lport <= a->port;
918 }
919
920 /* Yup. It is recursion. Sorry. */
921 case SSF_AND:
922 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
923 case SSF_OR:
924 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
925 case SSF_NOT:
926 return !run_ssfilter(f->pred, s);
927 default:
928 abort();
929 }
930 }
931
932 /* Relocate external jumps by reloc. */
933 static void ssfilter_patch(char *a, int len, int reloc)
934 {
935 while (len > 0) {
936 struct inet_diag_bc_op *op = (struct inet_diag_bc_op*)a;
937 if (op->no == len+4)
938 op->no += reloc;
939 len -= op->yes;
940 a += op->yes;
941 }
942 if (len < 0)
943 abort();
944 }
945
946 static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
947 {
948 switch (f->type) {
949 case SSF_S_AUTO:
950 {
951 if (!(*bytecode=malloc(4))) abort();
952 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
953 return 4;
954 }
955 case SSF_DCOND:
956 case SSF_SCOND:
957 {
958 struct aafilter *a = (void*)f->pred;
959 struct aafilter *b;
960 char *ptr;
961 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
962 int len = 0;
963
964 for (b=a; b; b=b->next) {
965 len += 4 + sizeof(struct inet_diag_hostcond);
966 if (a->addr.family == AF_INET6)
967 len += 16;
968 else
969 len += 4;
970 if (b->next)
971 len += 4;
972 }
973 if (!(ptr = malloc(len))) abort();
974 *bytecode = ptr;
975 for (b=a; b; b=b->next) {
976 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
977 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
978 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
979 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond*)(ptr+4);
980
981 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
982 cond->family = a->addr.family;
983 cond->port = a->port;
984 cond->prefix_len = a->addr.bitlen;
985 memcpy(cond->addr, a->addr.data, alen);
986 ptr += oplen;
987 if (b->next) {
988 op = (struct inet_diag_bc_op *)ptr;
989 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
990 ptr += 4;
991 }
992 }
993 return ptr - *bytecode;
994 }
995 case SSF_D_GE:
996 {
997 struct aafilter *x = (void*)f->pred;
998 if (!(*bytecode=malloc(8))) abort();
999 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
1000 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1001 return 8;
1002 }
1003 case SSF_D_LE:
1004 {
1005 struct aafilter *x = (void*)f->pred;
1006 if (!(*bytecode=malloc(8))) abort();
1007 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
1008 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1009 return 8;
1010 }
1011 case SSF_S_GE:
1012 {
1013 struct aafilter *x = (void*)f->pred;
1014 if (!(*bytecode=malloc(8))) abort();
1015 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
1016 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1017 return 8;
1018 }
1019 case SSF_S_LE:
1020 {
1021 struct aafilter *x = (void*)f->pred;
1022 if (!(*bytecode=malloc(8))) abort();
1023 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
1024 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1025 return 8;
1026 }
1027
1028 case SSF_AND:
1029 {
1030 char *a1, *a2, *a;
1031 int l1, l2;
1032 l1 = ssfilter_bytecompile(f->pred, &a1);
1033 l2 = ssfilter_bytecompile(f->post, &a2);
1034 if (!(a = malloc(l1+l2))) abort();
1035 memcpy(a, a1, l1);
1036 memcpy(a+l1, a2, l2);
1037 free(a1); free(a2);
1038 ssfilter_patch(a, l1, l2);
1039 *bytecode = a;
1040 return l1+l2;
1041 }
1042 case SSF_OR:
1043 {
1044 char *a1, *a2, *a;
1045 int l1, l2;
1046 l1 = ssfilter_bytecompile(f->pred, &a1);
1047 l2 = ssfilter_bytecompile(f->post, &a2);
1048 if (!(a = malloc(l1+l2+4))) abort();
1049 memcpy(a, a1, l1);
1050 memcpy(a+l1+4, a2, l2);
1051 free(a1); free(a2);
1052 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
1053 *bytecode = a;
1054 return l1+l2+4;
1055 }
1056 case SSF_NOT:
1057 {
1058 char *a1, *a;
1059 int l1;
1060 l1 = ssfilter_bytecompile(f->pred, &a1);
1061 if (!(a = malloc(l1+4))) abort();
1062 memcpy(a, a1, l1);
1063 free(a1);
1064 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
1065 *bytecode = a;
1066 return l1+4;
1067 }
1068 default:
1069 abort();
1070 }
1071 }
1072
1073 static int remember_he(struct aafilter *a, struct hostent *he)
1074 {
1075 char **ptr = he->h_addr_list;
1076 int cnt = 0;
1077 int len;
1078
1079 if (he->h_addrtype == AF_INET)
1080 len = 4;
1081 else if (he->h_addrtype == AF_INET6)
1082 len = 16;
1083 else
1084 return 0;
1085
1086 while (*ptr) {
1087 struct aafilter *b = a;
1088 if (a->addr.bitlen) {
1089 if ((b = malloc(sizeof(*b))) == NULL)
1090 return cnt;
1091 *b = *a;
1092 b->next = a->next;
1093 a->next = b;
1094 }
1095 memcpy(b->addr.data, *ptr, len);
1096 b->addr.bytelen = len;
1097 b->addr.bitlen = len*8;
1098 b->addr.family = he->h_addrtype;
1099 ptr++;
1100 cnt++;
1101 }
1102 return cnt;
1103 }
1104
1105 static int get_dns_host(struct aafilter *a, const char *addr, int fam)
1106 {
1107 static int notfirst;
1108 int cnt = 0;
1109 struct hostent *he;
1110
1111 a->addr.bitlen = 0;
1112 if (!notfirst) {
1113 sethostent(1);
1114 notfirst = 1;
1115 }
1116 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
1117 if (he)
1118 cnt = remember_he(a, he);
1119 if (fam == AF_UNSPEC) {
1120 he = gethostbyname2(addr, AF_INET6);
1121 if (he)
1122 cnt += remember_he(a, he);
1123 }
1124 return !cnt;
1125 }
1126
1127 static int xll_initted = 0;
1128
1129 static void xll_init(void)
1130 {
1131 struct rtnl_handle rth;
1132 if (rtnl_open(&rth, 0) < 0)
1133 exit(1);
1134
1135 ll_init_map(&rth);
1136 rtnl_close(&rth);
1137 xll_initted = 1;
1138 }
1139
1140 static const char *xll_index_to_name(int index)
1141 {
1142 if (!xll_initted)
1143 xll_init();
1144 return ll_index_to_name(index);
1145 }
1146
1147 static int xll_name_to_index(const char *dev)
1148 {
1149 if (!xll_initted)
1150 xll_init();
1151 return ll_name_to_index(dev);
1152 }
1153
1154 void *parse_hostcond(char *addr)
1155 {
1156 char *port = NULL;
1157 struct aafilter a;
1158 struct aafilter *res;
1159 int fam = preferred_family;
1160
1161 memset(&a, 0, sizeof(a));
1162 a.port = -1;
1163
1164 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
1165 char *p;
1166 a.addr.family = AF_UNIX;
1167 if (strncmp(addr, "unix:", 5) == 0)
1168 addr+=5;
1169 p = strdup(addr);
1170 a.addr.bitlen = 8*strlen(p);
1171 memcpy(a.addr.data, &p, sizeof(p));
1172 goto out;
1173 }
1174
1175 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
1176 a.addr.family = AF_PACKET;
1177 a.addr.bitlen = 0;
1178 if (strncmp(addr, "link:", 5) == 0)
1179 addr+=5;
1180 port = strchr(addr, ':');
1181 if (port) {
1182 *port = 0;
1183 if (port[1] && strcmp(port+1, "*")) {
1184 if (get_integer(&a.port, port+1, 0)) {
1185 if ((a.port = xll_name_to_index(port+1)) <= 0)
1186 return NULL;
1187 }
1188 }
1189 }
1190 if (addr[0] && strcmp(addr, "*")) {
1191 unsigned short tmp;
1192 a.addr.bitlen = 32;
1193 if (ll_proto_a2n(&tmp, addr))
1194 return NULL;
1195 a.addr.data[0] = ntohs(tmp);
1196 }
1197 goto out;
1198 }
1199
1200 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
1201 a.addr.family = AF_NETLINK;
1202 a.addr.bitlen = 0;
1203 if (strncmp(addr, "netlink:", 8) == 0)
1204 addr+=8;
1205 port = strchr(addr, ':');
1206 if (port) {
1207 *port = 0;
1208 if (port[1] && strcmp(port+1, "*")) {
1209 if (get_integer(&a.port, port+1, 0)) {
1210 if (strcmp(port+1, "kernel") == 0)
1211 a.port = 0;
1212 else
1213 return NULL;
1214 }
1215 }
1216 }
1217 if (addr[0] && strcmp(addr, "*")) {
1218 a.addr.bitlen = 32;
1219 if (get_u32(a.addr.data, addr, 0)) {
1220 if (strcmp(addr, "rtnl") == 0)
1221 a.addr.data[0] = 0;
1222 else if (strcmp(addr, "fw") == 0)
1223 a.addr.data[0] = 3;
1224 else if (strcmp(addr, "tcpdiag") == 0)
1225 a.addr.data[0] = 4;
1226 else
1227 return NULL;
1228 }
1229 }
1230 goto out;
1231 }
1232
1233 if (strncmp(addr, "inet:", 5) == 0) {
1234 addr += 5;
1235 fam = AF_INET;
1236 } else if (strncmp(addr, "inet6:", 6) == 0) {
1237 addr += 6;
1238 fam = AF_INET6;
1239 }
1240
1241 /* URL-like literal [] */
1242 if (addr[0] == '[') {
1243 addr++;
1244 if ((port = strchr(addr, ']')) == NULL)
1245 return NULL;
1246 *port++ = 0;
1247 } else if (addr[0] == '*') {
1248 port = addr+1;
1249 } else {
1250 port = strrchr(strchr(addr, '/') ? : addr, ':');
1251 }
1252 if (port && *port) {
1253 if (*port != ':')
1254 return NULL;
1255 *port++ = 0;
1256 if (*port && *port != '*') {
1257 if (get_integer(&a.port, port, 0)) {
1258 struct servent *se1 = NULL;
1259 struct servent *se2 = NULL;
1260 if (current_filter.dbs&(1<<UDP_DB))
1261 se1 = getservbyname(port, UDP_PROTO);
1262 if (current_filter.dbs&(1<<TCP_DB))
1263 se2 = getservbyname(port, TCP_PROTO);
1264 if (se1 && se2 && se1->s_port != se2->s_port) {
1265 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1266 return NULL;
1267 }
1268 if (!se1)
1269 se1 = se2;
1270 if (se1) {
1271 a.port = ntohs(se1->s_port);
1272 } else {
1273 struct scache *s;
1274 for (s = rlist; s; s = s->next) {
1275 if ((s->proto == UDP_PROTO &&
1276 (current_filter.dbs&(1<<UDP_DB))) ||
1277 (s->proto == TCP_PROTO &&
1278 (current_filter.dbs&(1<<TCP_DB)))) {
1279 if (s->name && strcmp(s->name, port) == 0) {
1280 if (a.port > 0 && a.port != s->port) {
1281 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1282 return NULL;
1283 }
1284 a.port = s->port;
1285 }
1286 }
1287 }
1288 if (a.port <= 0) {
1289 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1290 return NULL;
1291 }
1292 }
1293 }
1294 }
1295 }
1296 if (addr && *addr && *addr != '*') {
1297 if (get_prefix_1(&a.addr, addr, fam)) {
1298 if (get_dns_host(&a, addr, fam)) {
1299 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1300 return NULL;
1301 }
1302 }
1303 }
1304
1305 out:
1306 res = malloc(sizeof(*res));
1307 if (res)
1308 memcpy(res, &a, sizeof(a));
1309 return res;
1310 }
1311
1312 static int tcp_show_line(char *line, const struct filter *f, int family)
1313 {
1314 struct tcpstat s;
1315 char *loc, *rem, *data;
1316 char opt[256];
1317 int n;
1318 char *p;
1319
1320 if ((p = strchr(line, ':')) == NULL)
1321 return -1;
1322 loc = p+2;
1323
1324 if ((p = strchr(loc, ':')) == NULL)
1325 return -1;
1326 p[5] = 0;
1327 rem = p+6;
1328
1329 if ((p = strchr(rem, ':')) == NULL)
1330 return -1;
1331 p[5] = 0;
1332 data = p+6;
1333
1334 do {
1335 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1336
1337 if (!(f->states & (1<<state)))
1338 return 0;
1339 } while (0);
1340
1341 s.local.family = s.remote.family = family;
1342 if (family == AF_INET) {
1343 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1344 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1345 s.local.bytelen = s.remote.bytelen = 4;
1346 } else {
1347 sscanf(loc, "%08x%08x%08x%08x:%x",
1348 s.local.data,
1349 s.local.data+1,
1350 s.local.data+2,
1351 s.local.data+3,
1352 &s.lport);
1353 sscanf(rem, "%08x%08x%08x%08x:%x",
1354 s.remote.data,
1355 s.remote.data+1,
1356 s.remote.data+2,
1357 s.remote.data+3,
1358 &s.rport);
1359 s.local.bytelen = s.remote.bytelen = 16;
1360 }
1361
1362 if (f->f && run_ssfilter(f->f, &s) == 0)
1363 return 0;
1364
1365 opt[0] = 0;
1366 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
1367 &s.state, &s.wq, &s.rq,
1368 &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1369 &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1370 &s.cwnd, &s.ssthresh, opt);
1371
1372 if (n < 17)
1373 opt[0] = 0;
1374
1375 if (n < 12) {
1376 s.rto = 0;
1377 s.cwnd = 2;
1378 s.ssthresh = -1;
1379 s.ato = s.qack = 0;
1380 }
1381
1382 if (netid_width)
1383 printf("%-*s ", netid_width, "tcp");
1384 if (state_width)
1385 printf("%-*s ", state_width, sstate_name[s.state]);
1386
1387 printf("%-6d %-6d ", s.rq, s.wq);
1388
1389 formatted_print(&s.local, s.lport, 0);
1390 formatted_print(&s.remote, s.rport, 0);
1391
1392 if (show_options) {
1393 if (s.timer) {
1394 if (s.timer > 4)
1395 s.timer = 5;
1396 printf(" timer:(%s,%s,%d)",
1397 tmr_name[s.timer],
1398 print_hz_timer(s.timeout),
1399 s.timer != 1 ? s.probes : s.retrs);
1400 }
1401 }
1402 if (show_tcpinfo) {
1403 int hz = get_user_hz();
1404 if (s.rto && s.rto != 3*hz)
1405 printf(" rto:%g", (double)s.rto/hz);
1406 if (s.ato)
1407 printf(" ato:%g", (double)s.ato/hz);
1408 if (s.cwnd != 2)
1409 printf(" cwnd:%d", s.cwnd);
1410 if (s.ssthresh != -1)
1411 printf(" ssthresh:%d", s.ssthresh);
1412 if (s.qack/2)
1413 printf(" qack:%d", s.qack/2);
1414 if (s.qack&1)
1415 printf(" bidir");
1416 }
1417 char *buf = NULL;
1418 if (show_proc_ctx || show_sock_ctx) {
1419 if (find_entry(s.ino, &buf,
1420 (show_proc_ctx & show_sock_ctx) ?
1421 PROC_SOCK_CTX : PROC_CTX) > 0) {
1422 printf(" users:(%s)", buf);
1423 free(buf);
1424 }
1425 } else if (show_users) {
1426 if (find_entry(s.ino, &buf, USERS) > 0) {
1427 printf(" users:(%s)", buf);
1428 free(buf);
1429 }
1430 }
1431
1432 if (show_details) {
1433 if (s.uid)
1434 printf(" uid:%u", (unsigned)s.uid);
1435 printf(" ino:%u", s.ino);
1436 printf(" sk:%llx", s.sk);
1437 if (opt[0])
1438 printf(" opt:\"%s\"", opt);
1439 }
1440 printf("\n");
1441
1442 return 0;
1443 }
1444
1445 static int generic_record_read(FILE *fp,
1446 int (*worker)(char*, const struct filter *, int),
1447 const struct filter *f, int fam)
1448 {
1449 char line[256];
1450
1451 /* skip header */
1452 if (fgets(line, sizeof(line), fp) == NULL)
1453 goto outerr;
1454
1455 while (fgets(line, sizeof(line), fp) != NULL) {
1456 int n = strlen(line);
1457 if (n == 0 || line[n-1] != '\n') {
1458 errno = -EINVAL;
1459 return -1;
1460 }
1461 line[n-1] = 0;
1462
1463 if (worker(line, f, fam) < 0)
1464 return 0;
1465 }
1466 outerr:
1467
1468 return ferror(fp) ? -1 : 0;
1469 }
1470
1471 static char *sprint_bw(char *buf, double bw)
1472 {
1473 if (bw > 1000000.)
1474 sprintf(buf,"%.1fM", bw / 1000000.);
1475 else if (bw > 1000.)
1476 sprintf(buf,"%.1fK", bw / 1000.);
1477 else
1478 sprintf(buf, "%g", bw);
1479
1480 return buf;
1481 }
1482
1483 static void print_skmeminfo(struct rtattr *tb[], int attrtype)
1484 {
1485 const __u32 *skmeminfo;
1486 if (!tb[attrtype])
1487 return;
1488 skmeminfo = RTA_DATA(tb[attrtype]);
1489
1490 printf(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
1491 skmeminfo[SK_MEMINFO_RMEM_ALLOC],
1492 skmeminfo[SK_MEMINFO_RCVBUF],
1493 skmeminfo[SK_MEMINFO_WMEM_ALLOC],
1494 skmeminfo[SK_MEMINFO_SNDBUF],
1495 skmeminfo[SK_MEMINFO_FWD_ALLOC],
1496 skmeminfo[SK_MEMINFO_WMEM_QUEUED],
1497 skmeminfo[SK_MEMINFO_OPTMEM]);
1498
1499 if (RTA_PAYLOAD(tb[attrtype]) >=
1500 (SK_MEMINFO_BACKLOG + 1) * sizeof(__u32))
1501 printf(",bl%u", skmeminfo[SK_MEMINFO_BACKLOG]);
1502
1503 printf(")");
1504 }
1505
1506 static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r,
1507 struct rtattr *tb[])
1508 {
1509 char b1[64];
1510 double rtt = 0;
1511
1512 if (tb[INET_DIAG_SKMEMINFO]) {
1513 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
1514 } else if (tb[INET_DIAG_MEMINFO]) {
1515 const struct inet_diag_meminfo *minfo
1516 = RTA_DATA(tb[INET_DIAG_MEMINFO]);
1517 printf(" mem:(r%u,w%u,f%u,t%u)",
1518 minfo->idiag_rmem,
1519 minfo->idiag_wmem,
1520 minfo->idiag_fmem,
1521 minfo->idiag_tmem);
1522 }
1523
1524 if (tb[INET_DIAG_INFO]) {
1525 struct tcp_info *info;
1526 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
1527
1528 /* workaround for older kernels with less fields */
1529 if (len < sizeof(*info)) {
1530 info = alloca(sizeof(*info));
1531 memset(info, 0, sizeof(*info));
1532 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
1533 } else
1534 info = RTA_DATA(tb[INET_DIAG_INFO]);
1535
1536 if (show_options) {
1537 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1538 printf(" ts");
1539 if (info->tcpi_options & TCPI_OPT_SACK)
1540 printf(" sack");
1541 if (info->tcpi_options & TCPI_OPT_ECN)
1542 printf(" ecn");
1543 if (info->tcpi_options & TCPI_OPT_ECN_SEEN)
1544 printf(" ecnseen");
1545 if (info->tcpi_options & TCPI_OPT_SYN_DATA)
1546 printf(" fastopen");
1547 }
1548
1549 if (tb[INET_DIAG_CONG])
1550 printf(" %s", rta_getattr_str(tb[INET_DIAG_CONG]));
1551
1552 if (info->tcpi_options & TCPI_OPT_WSCALE)
1553 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1554 info->tcpi_rcv_wscale);
1555 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1556 printf(" rto:%g", (double)info->tcpi_rto/1000);
1557 if (info->tcpi_backoff)
1558 printf(" backoff:%u", info->tcpi_backoff);
1559 if (info->tcpi_rtt)
1560 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1561 (double)info->tcpi_rttvar/1000);
1562 if (info->tcpi_ato)
1563 printf(" ato:%g", (double)info->tcpi_ato/1000);
1564 if (info->tcpi_snd_mss)
1565 printf(" mss:%d", info->tcpi_snd_mss);
1566 if (info->tcpi_snd_cwnd != 2)
1567 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1568 if (info->tcpi_snd_ssthresh < 0xFFFF)
1569 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
1570
1571 rtt = (double) info->tcpi_rtt;
1572 if (tb[INET_DIAG_VEGASINFO]) {
1573 const struct tcpvegas_info *vinfo
1574 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
1575
1576 if (vinfo->tcpv_enabled &&
1577 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
1578 rtt = vinfo->tcpv_rtt;
1579 }
1580
1581 if (tb[INET_DIAG_DCTCPINFO]) {
1582 const struct tcp_dctcp_info *dinfo
1583 = RTA_DATA(tb[INET_DIAG_DCTCPINFO]);
1584
1585 if (dinfo->dctcp_enabled) {
1586 printf(" ce_state %u alpha %u ab_ecn %u ab_tot %u",
1587 dinfo->dctcp_ce_state, dinfo->dctcp_alpha,
1588 dinfo->dctcp_ab_ecn, dinfo->dctcp_ab_tot);
1589 } else {
1590 printf(" fallback_mode");
1591 }
1592 }
1593
1594 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1595 printf(" send %sbps",
1596 sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1597 (double) info->tcpi_snd_mss * 8000000.
1598 / rtt));
1599 }
1600
1601 if (info->tcpi_last_data_sent)
1602 printf(" lastsnd:%u", info->tcpi_last_data_sent);
1603
1604 if (info->tcpi_last_data_recv)
1605 printf(" lastrcv:%u", info->tcpi_last_data_recv);
1606
1607 if (info->tcpi_last_ack_recv)
1608 printf(" lastack:%u", info->tcpi_last_ack_recv);
1609
1610 if (info->tcpi_pacing_rate &&
1611 info->tcpi_pacing_rate != ~0ULL) {
1612 printf(" pacing_rate %sbps",
1613 sprint_bw(b1, info->tcpi_pacing_rate * 8.));
1614
1615 if (info->tcpi_max_pacing_rate &&
1616 info->tcpi_max_pacing_rate != ~0ULL)
1617 printf("/%sbps",
1618 sprint_bw(b1, info->tcpi_max_pacing_rate * 8.));
1619 }
1620 if (info->tcpi_unacked)
1621 printf(" unacked:%u", info->tcpi_unacked);
1622 if (info->tcpi_retrans || info->tcpi_total_retrans)
1623 printf(" retrans:%u/%u", info->tcpi_retrans,
1624 info->tcpi_total_retrans);
1625 if (info->tcpi_lost)
1626 printf(" lost:%u", info->tcpi_lost);
1627 if (info->tcpi_sacked && r->idiag_state != SS_LISTEN)
1628 printf(" sacked:%u", info->tcpi_sacked);
1629 if (info->tcpi_fackets)
1630 printf(" fackets:%u", info->tcpi_fackets);
1631 if (info->tcpi_reordering != 3)
1632 printf(" reordering:%d", info->tcpi_reordering);
1633 if (info->tcpi_rcv_rtt)
1634 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1635 if (info->tcpi_rcv_space)
1636 printf(" rcv_space:%d", info->tcpi_rcv_space);
1637
1638 }
1639 }
1640
1641 static char *proto_name(int protocol)
1642 {
1643 switch (protocol) {
1644 case IPPROTO_UDP:
1645 return "udp";
1646 case IPPROTO_TCP:
1647 return "tcp";
1648 case IPPROTO_DCCP:
1649 return "dccp";
1650 }
1651
1652 return "???";
1653 }
1654
1655 static int inet_show_sock(struct nlmsghdr *nlh, struct filter *f, int protocol)
1656 {
1657 struct rtattr * tb[INET_DIAG_MAX+1];
1658 struct inet_diag_msg *r = NLMSG_DATA(nlh);
1659 struct tcpstat s;
1660
1661 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr*)(r+1),
1662 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1663
1664 s.state = r->idiag_state;
1665 s.local.family = s.remote.family = r->idiag_family;
1666 s.lport = ntohs(r->id.idiag_sport);
1667 s.rport = ntohs(r->id.idiag_dport);
1668 if (s.local.family == AF_INET) {
1669 s.local.bytelen = s.remote.bytelen = 4;
1670 } else {
1671 s.local.bytelen = s.remote.bytelen = 16;
1672 }
1673 memcpy(s.local.data, r->id.idiag_src, s.local.bytelen);
1674 memcpy(s.remote.data, r->id.idiag_dst, s.local.bytelen);
1675
1676 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1677 return 0;
1678
1679 if (netid_width)
1680 printf("%-*s ", netid_width, proto_name(protocol));
1681 if (state_width)
1682 printf("%-*s ", state_width, sstate_name[s.state]);
1683
1684 printf("%-6d %-6d ", r->idiag_rqueue, r->idiag_wqueue);
1685
1686 formatted_print(&s.local, s.lport, r->id.idiag_if);
1687 formatted_print(&s.remote, s.rport, 0);
1688
1689 if (show_options) {
1690 if (r->idiag_timer) {
1691 if (r->idiag_timer > 4)
1692 r->idiag_timer = 5;
1693 printf(" timer:(%s,%s,%d)",
1694 tmr_name[r->idiag_timer],
1695 print_ms_timer(r->idiag_expires),
1696 r->idiag_retrans);
1697 }
1698 }
1699 char *buf = NULL;
1700
1701 if (show_proc_ctx || show_sock_ctx) {
1702 if (find_entry(r->idiag_inode, &buf,
1703 (show_proc_ctx & show_sock_ctx) ?
1704 PROC_SOCK_CTX : PROC_CTX) > 0) {
1705 printf(" users:(%s)", buf);
1706 free(buf);
1707 }
1708 } else if (show_users) {
1709 if (find_entry(r->idiag_inode, &buf, USERS) > 0) {
1710 printf(" users:(%s)", buf);
1711 free(buf);
1712 }
1713 }
1714
1715 if (show_details) {
1716 if (r->idiag_uid)
1717 printf(" uid:%u", (unsigned)r->idiag_uid);
1718 printf(" ino:%u", r->idiag_inode);
1719 printf(" sk:");
1720 if (r->id.idiag_cookie[1] != 0)
1721 printf("%08x", r->id.idiag_cookie[1]);
1722 printf("%08x", r->id.idiag_cookie[0]);
1723 if (tb[INET_DIAG_SHUTDOWN]) {
1724 unsigned char mask;
1725 mask = *(__u8 *)RTA_DATA(tb[INET_DIAG_SHUTDOWN]);
1726 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
1727 }
1728 }
1729 if (show_mem || show_tcpinfo) {
1730 printf("\n\t");
1731 tcp_show_info(nlh, r, tb);
1732 }
1733
1734 printf("\n");
1735
1736 return 0;
1737 }
1738
1739 static int tcpdiag_send(int fd, int protocol, struct filter *f)
1740 {
1741 struct sockaddr_nl nladdr;
1742 struct {
1743 struct nlmsghdr nlh;
1744 struct inet_diag_req r;
1745 } req;
1746 char *bc = NULL;
1747 int bclen;
1748 struct msghdr msg;
1749 struct rtattr rta;
1750 struct iovec iov[3];
1751
1752 if (protocol == IPPROTO_UDP)
1753 return -1;
1754
1755 memset(&nladdr, 0, sizeof(nladdr));
1756 nladdr.nl_family = AF_NETLINK;
1757
1758 req.nlh.nlmsg_len = sizeof(req);
1759 if (protocol == IPPROTO_TCP)
1760 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
1761 else
1762 req.nlh.nlmsg_type = DCCPDIAG_GETSOCK;
1763 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1764 req.nlh.nlmsg_pid = 0;
1765 req.nlh.nlmsg_seq = 123456;
1766 memset(&req.r, 0, sizeof(req.r));
1767 req.r.idiag_family = AF_INET;
1768 req.r.idiag_states = f->states;
1769 if (show_mem) {
1770 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
1771 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
1772 }
1773
1774 if (show_tcpinfo) {
1775 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1776 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1777 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
1778 }
1779
1780 iov[0] = (struct iovec){
1781 .iov_base = &req,
1782 .iov_len = sizeof(req)
1783 };
1784 if (f->f) {
1785 bclen = ssfilter_bytecompile(f->f, &bc);
1786 rta.rta_type = INET_DIAG_REQ_BYTECODE;
1787 rta.rta_len = RTA_LENGTH(bclen);
1788 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1789 iov[2] = (struct iovec){ bc, bclen };
1790 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1791 }
1792
1793 msg = (struct msghdr) {
1794 .msg_name = (void*)&nladdr,
1795 .msg_namelen = sizeof(nladdr),
1796 .msg_iov = iov,
1797 .msg_iovlen = f->f ? 3 : 1,
1798 };
1799
1800 if (sendmsg(fd, &msg, 0) < 0) {
1801 close(fd);
1802 return -1;
1803 }
1804
1805 return 0;
1806 }
1807
1808 static int sockdiag_send(int family, int fd, int protocol, struct filter *f)
1809 {
1810 struct sockaddr_nl nladdr;
1811 struct {
1812 struct nlmsghdr nlh;
1813 struct inet_diag_req_v2 r;
1814 } req;
1815 char *bc = NULL;
1816 int bclen;
1817 struct msghdr msg;
1818 struct rtattr rta;
1819 struct iovec iov[3];
1820
1821 if (family == PF_UNSPEC)
1822 return tcpdiag_send(fd, protocol, f);
1823
1824 memset(&nladdr, 0, sizeof(nladdr));
1825 nladdr.nl_family = AF_NETLINK;
1826
1827 req.nlh.nlmsg_len = sizeof(req);
1828 req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
1829 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1830 req.nlh.nlmsg_pid = 0;
1831 req.nlh.nlmsg_seq = 123456;
1832 memset(&req.r, 0, sizeof(req.r));
1833 req.r.sdiag_family = family;
1834 req.r.sdiag_protocol = protocol;
1835 req.r.idiag_states = f->states;
1836 if (show_mem) {
1837 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
1838 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
1839 }
1840
1841 if (show_tcpinfo) {
1842 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1843 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1844 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
1845 }
1846
1847 iov[0] = (struct iovec){
1848 .iov_base = &req,
1849 .iov_len = sizeof(req)
1850 };
1851 if (f->f) {
1852 bclen = ssfilter_bytecompile(f->f, &bc);
1853 rta.rta_type = INET_DIAG_REQ_BYTECODE;
1854 rta.rta_len = RTA_LENGTH(bclen);
1855 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1856 iov[2] = (struct iovec){ bc, bclen };
1857 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1858 }
1859
1860 msg = (struct msghdr) {
1861 .msg_name = (void*)&nladdr,
1862 .msg_namelen = sizeof(nladdr),
1863 .msg_iov = iov,
1864 .msg_iovlen = f->f ? 3 : 1,
1865 };
1866
1867 if (sendmsg(fd, &msg, 0) < 0) {
1868 close(fd);
1869 return -1;
1870 }
1871
1872 return 0;
1873 }
1874
1875 static int inet_show_netlink(struct filter *f, FILE *dump_fp, int protocol)
1876 {
1877 int fd, family;
1878 struct sockaddr_nl nladdr;
1879 struct msghdr msg;
1880 char buf[8192];
1881 struct iovec iov[3];
1882
1883 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
1884 return -1;
1885
1886 family = PF_INET;
1887 again:
1888 if (sockdiag_send(family, fd, protocol, f))
1889 return -1;
1890
1891 memset(&nladdr, 0, sizeof(nladdr));
1892 nladdr.nl_family = AF_NETLINK;
1893
1894 iov[0] = (struct iovec){
1895 .iov_base = buf,
1896 .iov_len = sizeof(buf)
1897 };
1898
1899 while (1) {
1900 int status;
1901 struct nlmsghdr *h;
1902
1903 msg = (struct msghdr) {
1904 (void*)&nladdr, sizeof(nladdr),
1905 iov, 1,
1906 NULL, 0,
1907 0
1908 };
1909
1910 status = recvmsg(fd, &msg, 0);
1911
1912 if (status < 0) {
1913 if (errno == EINTR)
1914 continue;
1915 perror("OVERRUN");
1916 continue;
1917 }
1918 if (status == 0) {
1919 fprintf(stderr, "EOF on netlink\n");
1920 close(fd);
1921 return 0;
1922 }
1923
1924 if (dump_fp)
1925 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1926
1927 h = (struct nlmsghdr*)buf;
1928 while (NLMSG_OK(h, status)) {
1929 int err;
1930 struct inet_diag_msg *r = NLMSG_DATA(h);
1931
1932 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
1933 h->nlmsg_seq != 123456)
1934 goto skip_it;
1935
1936 if (h->nlmsg_type == NLMSG_DONE)
1937 goto done;
1938
1939 if (h->nlmsg_type == NLMSG_ERROR) {
1940 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1941 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1942 fprintf(stderr, "ERROR truncated\n");
1943 } else {
1944 if (family != PF_UNSPEC) {
1945 family = PF_UNSPEC;
1946 goto again;
1947 }
1948
1949 errno = -err->error;
1950 if (errno == EOPNOTSUPP) {
1951 close(fd);
1952 return -1;
1953 }
1954 perror("TCPDIAG answers");
1955 }
1956
1957 goto done;
1958 }
1959 if (!dump_fp) {
1960 if (!(f->families & (1<<r->idiag_family))) {
1961 h = NLMSG_NEXT(h, status);
1962 continue;
1963 }
1964 err = inet_show_sock(h, NULL, protocol);
1965 if (err < 0) {
1966 close(fd);
1967 return err;
1968 }
1969 }
1970
1971 skip_it:
1972 h = NLMSG_NEXT(h, status);
1973 }
1974 if (msg.msg_flags & MSG_TRUNC) {
1975 fprintf(stderr, "Message truncated\n");
1976 continue;
1977 }
1978 if (status) {
1979 fprintf(stderr, "!!!Remnant of size %d\n", status);
1980 exit(1);
1981 }
1982 }
1983 done:
1984 if (family == PF_INET) {
1985 family = PF_INET6;
1986 goto again;
1987 }
1988
1989 close(fd);
1990 return 0;
1991 }
1992
1993 static int tcp_show_netlink_file(struct filter *f)
1994 {
1995 FILE *fp;
1996 char buf[8192];
1997
1998 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1999 perror("fopen($TCPDIAG_FILE)");
2000 return -1;
2001 }
2002
2003 while (1) {
2004 int status, err;
2005 struct nlmsghdr *h = (struct nlmsghdr*)buf;
2006
2007 status = fread(buf, 1, sizeof(*h), fp);
2008 if (status < 0) {
2009 perror("Reading header from $TCPDIAG_FILE");
2010 return -1;
2011 }
2012 if (status != sizeof(*h)) {
2013 perror("Unexpected EOF reading $TCPDIAG_FILE");
2014 return -1;
2015 }
2016
2017 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
2018
2019 if (status < 0) {
2020 perror("Reading $TCPDIAG_FILE");
2021 return -1;
2022 }
2023 if (status + sizeof(*h) < h->nlmsg_len) {
2024 perror("Unexpected EOF reading $TCPDIAG_FILE");
2025 return -1;
2026 }
2027
2028 /* The only legal exit point */
2029 if (h->nlmsg_type == NLMSG_DONE)
2030 return 0;
2031
2032 if (h->nlmsg_type == NLMSG_ERROR) {
2033 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
2034 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2035 fprintf(stderr, "ERROR truncated\n");
2036 } else {
2037 errno = -err->error;
2038 perror("TCPDIAG answered");
2039 }
2040 return -1;
2041 }
2042
2043 err = inet_show_sock(h, f, IPPROTO_TCP);
2044 if (err < 0)
2045 return err;
2046 }
2047 }
2048
2049 static int tcp_show(struct filter *f, int socktype)
2050 {
2051 FILE *fp = NULL;
2052 char *buf = NULL;
2053 int bufsize = 64*1024;
2054
2055 dg_proto = TCP_PROTO;
2056
2057 if (getenv("TCPDIAG_FILE"))
2058 return tcp_show_netlink_file(f);
2059
2060 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
2061 && inet_show_netlink(f, NULL, socktype) == 0)
2062 return 0;
2063
2064 /* Sigh... We have to parse /proc/net/tcp... */
2065
2066
2067 /* Estimate amount of sockets and try to allocate
2068 * huge buffer to read all the table at one read.
2069 * Limit it by 16MB though. The assumption is: as soon as
2070 * kernel was able to hold information about N connections,
2071 * it is able to give us some memory for snapshot.
2072 */
2073 if (1) {
2074 int guess = slabstat.socks+slabstat.tcp_syns;
2075 if (f->states&(1<<SS_TIME_WAIT))
2076 guess += slabstat.tcp_tws;
2077 if (guess > (16*1024*1024)/128)
2078 guess = (16*1024*1024)/128;
2079 guess *= 128;
2080 if (guess > bufsize)
2081 bufsize = guess;
2082 }
2083 while (bufsize >= 64*1024) {
2084 if ((buf = malloc(bufsize)) != NULL)
2085 break;
2086 bufsize /= 2;
2087 }
2088 if (buf == NULL) {
2089 errno = ENOMEM;
2090 return -1;
2091 }
2092
2093 if (f->families & (1<<AF_INET)) {
2094 if ((fp = net_tcp_open()) == NULL)
2095 goto outerr;
2096
2097 setbuffer(fp, buf, bufsize);
2098 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
2099 goto outerr;
2100 fclose(fp);
2101 }
2102
2103 if ((f->families & (1<<AF_INET6)) &&
2104 (fp = net_tcp6_open()) != NULL) {
2105 setbuffer(fp, buf, bufsize);
2106 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
2107 goto outerr;
2108 fclose(fp);
2109 }
2110
2111 free(buf);
2112 return 0;
2113
2114 outerr:
2115 do {
2116 int saved_errno = errno;
2117 if (buf)
2118 free(buf);
2119 if (fp)
2120 fclose(fp);
2121 errno = saved_errno;
2122 return -1;
2123 } while (0);
2124 }
2125
2126
2127 static int dgram_show_line(char *line, const struct filter *f, int family)
2128 {
2129 struct tcpstat s;
2130 char *loc, *rem, *data;
2131 char opt[256];
2132 int n;
2133 char *p;
2134
2135 if ((p = strchr(line, ':')) == NULL)
2136 return -1;
2137 loc = p+2;
2138
2139 if ((p = strchr(loc, ':')) == NULL)
2140 return -1;
2141 p[5] = 0;
2142 rem = p+6;
2143
2144 if ((p = strchr(rem, ':')) == NULL)
2145 return -1;
2146 p[5] = 0;
2147 data = p+6;
2148
2149 do {
2150 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
2151
2152 if (!(f->states & (1<<state)))
2153 return 0;
2154 } while (0);
2155
2156 s.local.family = s.remote.family = family;
2157 if (family == AF_INET) {
2158 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
2159 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
2160 s.local.bytelen = s.remote.bytelen = 4;
2161 } else {
2162 sscanf(loc, "%08x%08x%08x%08x:%x",
2163 s.local.data,
2164 s.local.data+1,
2165 s.local.data+2,
2166 s.local.data+3,
2167 &s.lport);
2168 sscanf(rem, "%08x%08x%08x%08x:%x",
2169 s.remote.data,
2170 s.remote.data+1,
2171 s.remote.data+2,
2172 s.remote.data+3,
2173 &s.rport);
2174 s.local.bytelen = s.remote.bytelen = 16;
2175 }
2176
2177 if (f->f && run_ssfilter(f->f, &s) == 0)
2178 return 0;
2179
2180 opt[0] = 0;
2181 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
2182 &s.state, &s.wq, &s.rq,
2183 &s.uid, &s.ino,
2184 &s.refcnt, &s.sk, opt);
2185
2186 if (n < 9)
2187 opt[0] = 0;
2188
2189 if (netid_width)
2190 printf("%-*s ", netid_width, dg_proto);
2191 if (state_width)
2192 printf("%-*s ", state_width, sstate_name[s.state]);
2193
2194 printf("%-6d %-6d ", s.rq, s.wq);
2195
2196 formatted_print(&s.local, s.lport, 0);
2197 formatted_print(&s.remote, s.rport, 0);
2198
2199 char *buf = NULL;
2200
2201 if (show_proc_ctx || show_sock_ctx) {
2202 if (find_entry(s.ino, &buf,
2203 (show_proc_ctx & show_sock_ctx) ?
2204 PROC_SOCK_CTX : PROC_CTX) > 0) {
2205 printf(" users:(%s)", buf);
2206 free(buf);
2207 }
2208 } else if (show_users) {
2209 if (find_entry(s.ino, &buf, USERS) > 0) {
2210 printf(" users:(%s)", buf);
2211 free(buf);
2212 }
2213 }
2214
2215 if (show_details) {
2216 if (s.uid)
2217 printf(" uid=%u", (unsigned)s.uid);
2218 printf(" ino=%u", s.ino);
2219 printf(" sk=%llx", s.sk);
2220 if (opt[0])
2221 printf(" opt:\"%s\"", opt);
2222 }
2223 printf("\n");
2224
2225 return 0;
2226 }
2227
2228
2229 static int udp_show(struct filter *f)
2230 {
2231 FILE *fp = NULL;
2232
2233 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
2234 && inet_show_netlink(f, NULL, IPPROTO_UDP) == 0)
2235 return 0;
2236
2237 dg_proto = UDP_PROTO;
2238
2239 if (f->families&(1<<AF_INET)) {
2240 if ((fp = net_udp_open()) == NULL)
2241 goto outerr;
2242 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
2243 goto outerr;
2244 fclose(fp);
2245 }
2246
2247 if ((f->families&(1<<AF_INET6)) &&
2248 (fp = net_udp6_open()) != NULL) {
2249 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
2250 goto outerr;
2251 fclose(fp);
2252 }
2253 return 0;
2254
2255 outerr:
2256 do {
2257 int saved_errno = errno;
2258 if (fp)
2259 fclose(fp);
2260 errno = saved_errno;
2261 return -1;
2262 } while (0);
2263 }
2264
2265 static int raw_show(struct filter *f)
2266 {
2267 FILE *fp = NULL;
2268
2269 dg_proto = RAW_PROTO;
2270
2271 if (f->families&(1<<AF_INET)) {
2272 if ((fp = net_raw_open()) == NULL)
2273 goto outerr;
2274 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
2275 goto outerr;
2276 fclose(fp);
2277 }
2278
2279 if ((f->families&(1<<AF_INET6)) &&
2280 (fp = net_raw6_open()) != NULL) {
2281 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
2282 goto outerr;
2283 fclose(fp);
2284 }
2285 return 0;
2286
2287 outerr:
2288 do {
2289 int saved_errno = errno;
2290 if (fp)
2291 fclose(fp);
2292 errno = saved_errno;
2293 return -1;
2294 } while (0);
2295 }
2296
2297
2298 struct unixstat
2299 {
2300 struct unixstat *next;
2301 int ino;
2302 int peer;
2303 int rq;
2304 int wq;
2305 int state;
2306 int type;
2307 char *name;
2308 };
2309
2310
2311
2312 int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
2313 SS_ESTABLISHED, SS_CLOSING };
2314
2315
2316 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
2317
2318 static void unix_list_free(struct unixstat *list)
2319 {
2320 while (list) {
2321 struct unixstat *s = list;
2322 list = list->next;
2323 if (s->name)
2324 free(s->name);
2325 free(s);
2326 }
2327 }
2328
2329 static const char *unix_netid_name(int type)
2330 {
2331 const char *netid;
2332
2333 switch (type) {
2334 case SOCK_STREAM:
2335 netid = "u_str";
2336 break;
2337 case SOCK_SEQPACKET:
2338 netid = "u_seq";
2339 break;
2340 case SOCK_DGRAM:
2341 default:
2342 netid = "u_dgr";
2343 break;
2344 }
2345 return netid;
2346 }
2347
2348 static void unix_list_print(struct unixstat *list, struct filter *f)
2349 {
2350 struct unixstat *s;
2351 char *peer;
2352
2353 for (s = list; s; s = s->next) {
2354 if (!(f->states & (1<<s->state)))
2355 continue;
2356 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2357 continue;
2358 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2359 continue;
2360 if (s->type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2361 continue;
2362
2363 peer = "*";
2364 if (s->peer) {
2365 struct unixstat *p;
2366 for (p = list; p; p = p->next) {
2367 if (s->peer == p->ino)
2368 break;
2369 }
2370 if (!p) {
2371 peer = "?";
2372 } else {
2373 peer = p->name ? : "*";
2374 }
2375 }
2376
2377 if (f->f) {
2378 struct tcpstat tst;
2379 tst.local.family = AF_UNIX;
2380 tst.remote.family = AF_UNIX;
2381 memcpy(tst.local.data, &s->name, sizeof(s->name));
2382 if (strcmp(peer, "*") == 0)
2383 memset(tst.remote.data, 0, sizeof(peer));
2384 else
2385 memcpy(tst.remote.data, &peer, sizeof(peer));
2386 if (run_ssfilter(f->f, &tst) == 0)
2387 continue;
2388 }
2389
2390 if (netid_width)
2391 printf("%-*s ", netid_width,
2392 unix_netid_name(s->type));
2393 if (state_width)
2394 printf("%-*s ", state_width, sstate_name[s->state]);
2395 printf("%-6d %-6d ", s->rq, s->wq);
2396 printf("%*s %-*d %*s %-*d",
2397 addr_width, s->name ? : "*", serv_width, s->ino,
2398 addr_width, peer, serv_width, s->peer);
2399 char *buf = NULL;
2400
2401 if (show_proc_ctx || show_sock_ctx) {
2402 if (find_entry(s->ino, &buf,
2403 (show_proc_ctx & show_sock_ctx) ?
2404 PROC_SOCK_CTX : PROC_CTX) > 0) {
2405 printf(" users:(%s)", buf);
2406 free(buf);
2407 }
2408 } else if (show_users) {
2409 if (find_entry(s->ino, &buf, USERS) > 0) {
2410 printf(" users:(%s)", buf);
2411 free(buf);
2412 }
2413 }
2414 printf("\n");
2415 }
2416 }
2417
2418 static int unix_show_sock(struct nlmsghdr *nlh, struct filter *f)
2419 {
2420 struct unix_diag_msg *r = NLMSG_DATA(nlh);
2421 struct rtattr *tb[UNIX_DIAG_MAX+1];
2422 char name[128];
2423 int peer_ino;
2424 __u32 rqlen, wqlen;
2425
2426 parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr*)(r+1),
2427 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2428
2429 if (r->udiag_type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2430 return 0;
2431 if (r->udiag_type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2432 return 0;
2433 if (r->udiag_type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2434 return 0;
2435
2436 if (netid_width)
2437 printf("%-*s ", netid_width,
2438 unix_netid_name(r->udiag_type));
2439 if (state_width)
2440 printf("%-*s ", state_width, sstate_name[r->udiag_state]);
2441
2442 if (tb[UNIX_DIAG_RQLEN]) {
2443 struct unix_diag_rqlen *rql = RTA_DATA(tb[UNIX_DIAG_RQLEN]);
2444 rqlen = rql->udiag_rqueue;
2445 wqlen = rql->udiag_wqueue;
2446 } else {
2447 rqlen = 0;
2448 wqlen = 0;
2449 }
2450
2451 printf("%-6u %-6u ", rqlen, wqlen);
2452
2453 if (tb[UNIX_DIAG_NAME]) {
2454 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
2455
2456 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
2457 name[len] = '\0';
2458 if (name[0] == '\0')
2459 name[0] = '@';
2460 } else
2461 sprintf(name, "*");
2462
2463 if (tb[UNIX_DIAG_PEER])
2464 peer_ino = rta_getattr_u32(tb[UNIX_DIAG_PEER]);
2465 else
2466 peer_ino = 0;
2467
2468 printf("%*s %-*d %*s %-*d",
2469 addr_width, name,
2470 serv_width, r->udiag_ino,
2471 addr_width, "*", /* FIXME */
2472 serv_width, peer_ino);
2473
2474 char *buf = NULL;
2475
2476 if (show_proc_ctx || show_sock_ctx) {
2477 if (find_entry(r->udiag_ino, &buf,
2478 (show_proc_ctx & show_sock_ctx) ?
2479 PROC_SOCK_CTX : PROC_CTX) > 0) {
2480 printf(" users:(%s)", buf);
2481 free(buf);
2482 }
2483 } else if (show_users) {
2484 if (find_entry(r->udiag_ino, &buf, USERS) > 0) {
2485 printf(" users:(%s)", buf);
2486 free(buf);
2487 }
2488 }
2489
2490 if (show_mem) {
2491 printf("\n\t");
2492 print_skmeminfo(tb, UNIX_DIAG_MEMINFO);
2493 }
2494
2495 if (show_details) {
2496 if (tb[UNIX_DIAG_SHUTDOWN]) {
2497 unsigned char mask;
2498 mask = *(__u8 *)RTA_DATA(tb[UNIX_DIAG_SHUTDOWN]);
2499 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2500 }
2501 }
2502
2503 printf("\n");
2504
2505 return 0;
2506 }
2507
2508 static int handle_netlink_request(struct filter *f, FILE *dump_fp,
2509 struct nlmsghdr *req, size_t size,
2510 int (* show_one_sock)(struct nlmsghdr *nlh, struct filter *f))
2511 {
2512 int fd;
2513 char buf[8192];
2514
2515 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
2516 return -1;
2517
2518 if (send(fd, req, size, 0) < 0) {
2519 close(fd);
2520 return -1;
2521 }
2522
2523 while (1) {
2524 ssize_t status;
2525 struct nlmsghdr *h;
2526 struct sockaddr_nl nladdr;
2527 socklen_t slen = sizeof(nladdr);
2528
2529 status = recvfrom(fd, buf, sizeof(buf), 0,
2530 (struct sockaddr *) &nladdr, &slen);
2531 if (status < 0) {
2532 if (errno == EINTR)
2533 continue;
2534 perror("OVERRUN");
2535 continue;
2536 }
2537 if (status == 0) {
2538 fprintf(stderr, "EOF on netlink\n");
2539 goto close_it;
2540 }
2541
2542 if (dump_fp)
2543 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
2544
2545 h = (struct nlmsghdr*)buf;
2546 while (NLMSG_OK(h, status)) {
2547 int err;
2548
2549 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
2550 h->nlmsg_seq != 123456)
2551 goto skip_it;
2552
2553 if (h->nlmsg_type == NLMSG_DONE)
2554 goto close_it;
2555
2556 if (h->nlmsg_type == NLMSG_ERROR) {
2557 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
2558 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2559 fprintf(stderr, "ERROR truncated\n");
2560 } else {
2561 errno = -err->error;
2562 if (errno != ENOENT)
2563 fprintf(stderr, "DIAG answers %d\n", errno);
2564 }
2565 close(fd);
2566 return -1;
2567 }
2568 if (!dump_fp) {
2569 err = show_one_sock(h, f);
2570 if (err < 0) {
2571 close(fd);
2572 return err;
2573 }
2574 }
2575
2576 skip_it:
2577 h = NLMSG_NEXT(h, status);
2578 }
2579
2580 if (status) {
2581 fprintf(stderr, "!!!Remnant of size %zd\n", status);
2582 exit(1);
2583 }
2584 }
2585
2586 close_it:
2587 close(fd);
2588 return 0;
2589 }
2590
2591 static int unix_show_netlink(struct filter *f, FILE *dump_fp)
2592 {
2593 struct {
2594 struct nlmsghdr nlh;
2595 struct unix_diag_req r;
2596 } req;
2597
2598 memset(&req, 0, sizeof(req));
2599 req.nlh.nlmsg_len = sizeof(req);
2600 req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
2601 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
2602 req.nlh.nlmsg_seq = 123456;
2603
2604 req.r.sdiag_family = AF_UNIX;
2605 req.r.udiag_states = f->states;
2606 req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
2607 if (show_mem)
2608 req.r.udiag_show |= UDIAG_SHOW_MEMINFO;
2609
2610 return handle_netlink_request(f, dump_fp, &req.nlh,
2611 sizeof(req), unix_show_sock);
2612 }
2613
2614 static int unix_show(struct filter *f)
2615 {
2616 FILE *fp;
2617 char buf[256];
2618 char name[128];
2619 int newformat = 0;
2620 int cnt;
2621 struct unixstat *list = NULL;
2622
2623 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
2624 && unix_show_netlink(f, NULL) == 0)
2625 return 0;
2626
2627 if ((fp = net_unix_open()) == NULL)
2628 return -1;
2629 fgets(buf, sizeof(buf)-1, fp);
2630
2631 if (memcmp(buf, "Peer", 4) == 0)
2632 newformat = 1;
2633 cnt = 0;
2634
2635 while (fgets(buf, sizeof(buf)-1, fp)) {
2636 struct unixstat *u, **insp;
2637 int flags;
2638
2639 if (!(u = malloc(sizeof(*u))))
2640 break;
2641 u->name = NULL;
2642
2643 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
2644 &u->peer, &u->rq, &u->wq, &flags, &u->type,
2645 &u->state, &u->ino, name) < 8)
2646 name[0] = 0;
2647
2648 if (flags&(1<<16)) {
2649 u->state = SS_LISTEN;
2650 } else {
2651 u->state = unix_state_map[u->state-1];
2652 if (u->type == SOCK_DGRAM &&
2653 u->state == SS_CLOSE &&
2654 u->peer)
2655 u->state = SS_ESTABLISHED;
2656 }
2657
2658 if (!newformat) {
2659 u->peer = 0;
2660 u->rq = 0;
2661 u->wq = 0;
2662 }
2663
2664 insp = &list;
2665 while (*insp) {
2666 if (u->type < (*insp)->type ||
2667 (u->type == (*insp)->type &&
2668 u->ino < (*insp)->ino))
2669 break;
2670 insp = &(*insp)->next;
2671 }
2672 u->next = *insp;
2673 *insp = u;
2674
2675 if (name[0]) {
2676 if ((u->name = malloc(strlen(name)+1)) == NULL)
2677 break;
2678 strcpy(u->name, name);
2679 }
2680 if (++cnt > MAX_UNIX_REMEMBER) {
2681 unix_list_print(list, f);
2682 unix_list_free(list);
2683 list = NULL;
2684 cnt = 0;
2685 }
2686 }
2687 fclose(fp);
2688 if (list) {
2689 unix_list_print(list, f);
2690 unix_list_free(list);
2691 list = NULL;
2692 cnt = 0;
2693 }
2694
2695 return 0;
2696 }
2697
2698 static int packet_show_sock(struct nlmsghdr *nlh, struct filter *f)
2699 {
2700 struct packet_diag_msg *r = NLMSG_DATA(nlh);
2701 struct rtattr *tb[PACKET_DIAG_MAX+1];
2702 __u32 rq;
2703
2704 parse_rtattr(tb, PACKET_DIAG_MAX, (struct rtattr*)(r+1),
2705 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2706
2707 /* use /proc/net/packet if all info are not available */
2708 if (!tb[PACKET_DIAG_MEMINFO])
2709 return -1;
2710
2711 if (netid_width)
2712 printf("%-*s ", netid_width,
2713 r->pdiag_type == SOCK_RAW ? "p_raw" : "p_dgr");
2714 if (state_width)
2715 printf("%-*s ", state_width, "UNCONN");
2716
2717 if (tb[PACKET_DIAG_MEMINFO]) {
2718 __u32 *skmeminfo = RTA_DATA(tb[PACKET_DIAG_MEMINFO]);
2719
2720 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
2721 } else
2722 rq = 0;
2723 printf("%-6d %-6d ", rq, 0);
2724
2725 if (r->pdiag_num == 3) {
2726 printf("%*s:", addr_width, "*");
2727 } else {
2728 char tb2[16];
2729 printf("%*s:", addr_width,
2730 ll_proto_n2a(htons(r->pdiag_num), tb2, sizeof(tb2)));
2731 }
2732 if (tb[PACKET_DIAG_INFO]) {
2733 struct packet_diag_info *pinfo = RTA_DATA(tb[PACKET_DIAG_INFO]);
2734
2735 if (pinfo->pdi_index == 0)
2736 printf("%-*s ", serv_width, "*");
2737 else
2738 printf("%-*s ", serv_width, xll_index_to_name(pinfo->pdi_index));
2739 } else
2740 printf("%-*s ", serv_width, "*");
2741
2742 printf("%*s*%-*s",
2743 addr_width, "", serv_width, "");
2744
2745 char *buf = NULL;
2746
2747 if (show_proc_ctx || show_sock_ctx) {
2748 if (find_entry(r->pdiag_ino, &buf,
2749 (show_proc_ctx & show_sock_ctx) ?
2750 PROC_SOCK_CTX : PROC_CTX) > 0) {
2751 printf(" users:(%s)", buf);
2752 free(buf);
2753 }
2754 } else if (show_users) {
2755 if (find_entry(r->pdiag_ino, &buf, USERS) > 0) {
2756 printf(" users:(%s)", buf);
2757 free(buf);
2758 }
2759 }
2760
2761 if (show_details) {
2762 __u32 uid = 0;
2763
2764 if (tb[PACKET_DIAG_UID])
2765 uid = *(__u32 *)RTA_DATA(tb[PACKET_DIAG_UID]);
2766
2767 printf(" ino=%u uid=%u sk=", r->pdiag_ino, uid);
2768 if (r->pdiag_cookie[1] != 0)
2769 printf("%08x", r->pdiag_cookie[1]);
2770 printf("%08x", r->pdiag_cookie[0]);
2771 }
2772
2773 if (show_bpf && tb[PACKET_DIAG_FILTER]) {
2774 struct sock_filter *fil =
2775 RTA_DATA(tb[PACKET_DIAG_FILTER]);
2776 int num = RTA_PAYLOAD(tb[PACKET_DIAG_FILTER]) /
2777 sizeof(struct sock_filter);
2778
2779 printf("\n\tbpf filter (%d): ", num);
2780 while (num) {
2781 printf(" 0x%02x %u %u %u,",
2782 fil->code, fil->jt, fil->jf, fil->k);
2783 num--;
2784 fil++;
2785 }
2786 }
2787 printf("\n");
2788 return 0;
2789 }
2790
2791 static int packet_show_netlink(struct filter *f, FILE *dump_fp)
2792 {
2793 int fd;
2794 struct {
2795 struct nlmsghdr nlh;
2796 struct packet_diag_req r;
2797 } req;
2798 char buf[8192];
2799
2800 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
2801 return -1;
2802
2803 memset(&req, 0, sizeof(req));
2804 req.nlh.nlmsg_len = sizeof(req);
2805 req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
2806 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
2807 req.nlh.nlmsg_seq = 123456;
2808
2809 req.r.sdiag_family = AF_PACKET;
2810 req.r.pdiag_show = PACKET_SHOW_INFO | PACKET_SHOW_MEMINFO | PACKET_SHOW_FILTER;
2811
2812 if (send(fd, &req, sizeof(req), 0) < 0) {
2813 close(fd);
2814 return -1;
2815 }
2816
2817 while (1) {
2818 ssize_t status;
2819 struct nlmsghdr *h;
2820 struct sockaddr_nl nladdr;
2821 socklen_t slen = sizeof(nladdr);
2822
2823 status = recvfrom(fd, buf, sizeof(buf), 0,
2824 (struct sockaddr *) &nladdr, &slen);
2825 if (status < 0) {
2826 if (errno == EINTR)
2827 continue;
2828 perror("OVERRUN");
2829 continue;
2830 }
2831 if (status == 0) {
2832 fprintf(stderr, "EOF on netlink\n");
2833 goto close_it;
2834 }
2835
2836 if (dump_fp)
2837 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
2838
2839 h = (struct nlmsghdr*)buf;
2840 while (NLMSG_OK(h, status)) {
2841 int err;
2842
2843 if (h->nlmsg_seq != 123456)
2844 goto skip_it;
2845
2846 if (h->nlmsg_type == NLMSG_DONE)
2847 goto close_it;
2848
2849 if (h->nlmsg_type == NLMSG_ERROR) {
2850 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
2851 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2852 fprintf(stderr, "ERROR truncated\n");
2853 } else {
2854 errno = -err->error;
2855 if (errno != ENOENT)
2856 fprintf(stderr, "UDIAG answers %d\n", errno);
2857 }
2858 close(fd);
2859 return -1;
2860 }
2861 if (!dump_fp) {
2862 err = packet_show_sock(h, f);
2863 if (err < 0) {
2864 close(fd);
2865 return err;
2866 }
2867 }
2868
2869 skip_it:
2870 h = NLMSG_NEXT(h, status);
2871 }
2872
2873 if (status) {
2874 fprintf(stderr, "!!!Remnant of size %zd\n", status);
2875 exit(1);
2876 }
2877 }
2878
2879 close_it:
2880 close(fd);
2881 return 0;
2882 }
2883
2884
2885 static int packet_show(struct filter *f)
2886 {
2887 FILE *fp;
2888 char buf[256];
2889 int type;
2890 int prot;
2891 int iface;
2892 int state;
2893 int rq;
2894 int uid;
2895 int ino;
2896 unsigned long long sk;
2897
2898 if (!(f->states & (1<<SS_CLOSE)))
2899 return 0;
2900
2901 if (packet_show_netlink(f, NULL) == 0)
2902 return 0;
2903
2904 if ((fp = net_packet_open()) == NULL)
2905 return -1;
2906 fgets(buf, sizeof(buf)-1, fp);
2907
2908 while (fgets(buf, sizeof(buf)-1, fp)) {
2909 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2910 &sk,
2911 &type, &prot, &iface, &state,
2912 &rq, &uid, &ino);
2913
2914 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2915 continue;
2916 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2917 continue;
2918 if (f->f) {
2919 struct tcpstat tst;
2920 tst.local.family = AF_PACKET;
2921 tst.remote.family = AF_PACKET;
2922 tst.rport = 0;
2923 tst.lport = iface;
2924 tst.local.data[0] = prot;
2925 tst.remote.data[0] = 0;
2926 if (run_ssfilter(f->f, &tst) == 0)
2927 continue;
2928 }
2929
2930 if (netid_width)
2931 printf("%-*s ", netid_width,
2932 type == SOCK_RAW ? "p_raw" : "p_dgr");
2933 if (state_width)
2934 printf("%-*s ", state_width, "UNCONN");
2935 printf("%-6d %-6d ", rq, 0);
2936 if (prot == 3) {
2937 printf("%*s:", addr_width, "*");
2938 } else {
2939 char tb[16];
2940 printf("%*s:", addr_width,
2941 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2942 }
2943 if (iface == 0) {
2944 printf("%-*s ", serv_width, "*");
2945 } else {
2946 printf("%-*s ", serv_width, xll_index_to_name(iface));
2947 }
2948 printf("%*s*%-*s",
2949 addr_width, "", serv_width, "");
2950
2951 char *buf = NULL;
2952
2953 if (show_proc_ctx || show_sock_ctx) {
2954 if (find_entry(ino, &buf,
2955 (show_proc_ctx & show_sock_ctx) ?
2956 PROC_SOCK_CTX : PROC_CTX) > 0) {
2957 printf(" users:(%s)", buf);
2958 free(buf);
2959 }
2960 } else if (show_users) {
2961 if (find_entry(ino, &buf, USERS) > 0) {
2962 printf(" users:(%s)", buf);
2963 free(buf);
2964 }
2965 }
2966
2967 if (show_details) {
2968 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2969 }
2970 printf("\n");
2971 }
2972
2973 return 0;
2974 }
2975
2976 static void netlink_show_one(struct filter *f,
2977 int prot, int pid, unsigned groups,
2978 int state, int dst_pid, unsigned dst_group,
2979 int rq, int wq,
2980 unsigned long long sk, unsigned long long cb)
2981 {
2982 if (f->f) {
2983 struct tcpstat tst;
2984 tst.local.family = AF_NETLINK;
2985 tst.remote.family = AF_NETLINK;
2986 tst.rport = -1;
2987 tst.lport = pid;
2988 tst.local.data[0] = prot;
2989 tst.remote.data[0] = 0;
2990 if (run_ssfilter(f->f, &tst) == 0)
2991 return;
2992 }
2993
2994 if (netid_width)
2995 printf("%-*s ", netid_width, "nl");
2996 if (state_width)
2997 printf("%-*s ", state_width, "UNCONN");
2998 printf("%-6d %-6d ", rq, wq);
2999 if (resolve_services && prot == 0)
3000 printf("%*s:", addr_width, "rtnl");
3001 else if (resolve_services && prot == 3)
3002 printf("%*s:", addr_width, "fw");
3003 else if (resolve_services && prot == 4)
3004 printf("%*s:", addr_width, "tcpdiag");
3005 else
3006 printf("%*d:", addr_width, prot);
3007 if (pid == -1) {
3008 printf("%-*s ", serv_width, "*");
3009 } else if (resolve_services) {
3010 int done = 0;
3011 if (!pid) {
3012 done = 1;
3013 printf("%-*s ", serv_width, "kernel");
3014 } else if (pid > 0) {
3015 char procname[64];
3016 FILE *fp;
3017 sprintf(procname, "%s/%d/stat",
3018 getenv("PROC_ROOT") ? : "/proc", pid);
3019 if ((fp = fopen(procname, "r")) != NULL) {
3020 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
3021 sprintf(procname+strlen(procname), "/%d", pid);
3022 printf("%-*s ", serv_width, procname);
3023 done = 1;
3024 }
3025 fclose(fp);
3026 }
3027 }
3028 if (!done)
3029 printf("%-*d ", serv_width, pid);
3030 } else {
3031 printf("%-*d ", serv_width, pid);
3032 }
3033
3034 if (state == NETLINK_CONNECTED) {
3035 printf("%*d:%-*d",
3036 addr_width, dst_group, serv_width, dst_pid);
3037 } else {
3038 printf("%*s*%-*s",
3039 addr_width, "", serv_width, "");
3040 }
3041
3042 char *pid_context = NULL;
3043 if (show_proc_ctx) {
3044 /* The pid value will either be:
3045 * 0 if destination kernel - show kernel initial context.
3046 * A valid process pid - use getpidcon.
3047 * A unique value allocated by the kernel or netlink user
3048 * to the process - show context as "not available".
3049 */
3050 if (!pid)
3051 security_get_initial_context("kernel", &pid_context);
3052 else if (pid > 0)
3053 getpidcon(pid, &pid_context);
3054
3055 if (pid_context != NULL) {
3056 printf("proc_ctx=%-*s ", serv_width, pid_context);
3057 free(pid_context);
3058 } else {
3059 printf("proc_ctx=%-*s ", serv_width, "unavailable");
3060 }
3061 }
3062
3063 if (show_details) {
3064 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
3065 }
3066 printf("\n");
3067
3068 return;
3069 }
3070
3071 static int netlink_show_sock(struct nlmsghdr *nlh, struct filter *f)
3072 {
3073 struct netlink_diag_msg *r = NLMSG_DATA(nlh);
3074 struct rtattr *tb[NETLINK_DIAG_MAX+1];
3075 int rq = 0, wq = 0;
3076 unsigned long groups = 0;
3077
3078 parse_rtattr(tb, NETLINK_DIAG_MAX, (struct rtattr*)(r+1),
3079 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
3080
3081 if (tb[NETLINK_DIAG_GROUPS] && RTA_PAYLOAD(tb[NETLINK_DIAG_GROUPS]))
3082 groups = *(unsigned long *) RTA_DATA(tb[NETLINK_DIAG_GROUPS]);
3083
3084 if (tb[NETLINK_DIAG_MEMINFO]) {
3085 const __u32 *skmeminfo;
3086 skmeminfo = RTA_DATA(tb[NETLINK_DIAG_MEMINFO]);
3087
3088 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
3089 wq = skmeminfo[SK_MEMINFO_WMEM_ALLOC];
3090 }
3091
3092 netlink_show_one(f, r->ndiag_protocol, r->ndiag_portid, groups,
3093 r->ndiag_state, r->ndiag_dst_portid, r->ndiag_dst_group,
3094 rq, wq, 0, 0);
3095
3096 if (show_mem) {
3097 printf("\t");
3098 print_skmeminfo(tb, NETLINK_DIAG_MEMINFO);
3099 printf("\n");
3100 }
3101
3102 return 0;
3103 }
3104
3105 static int netlink_show_netlink(struct filter *f, FILE *dump_fp)
3106 {
3107 struct {
3108 struct nlmsghdr nlh;
3109 struct netlink_diag_req r;
3110 } req;
3111
3112 memset(&req, 0, sizeof(req));
3113 req.nlh.nlmsg_len = sizeof(req);
3114 req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
3115 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
3116 req.nlh.nlmsg_seq = 123456;
3117
3118 req.r.sdiag_family = AF_NETLINK;
3119 req.r.sdiag_protocol = NDIAG_PROTO_ALL;
3120 req.r.ndiag_show = NDIAG_SHOW_GROUPS | NDIAG_SHOW_MEMINFO;
3121
3122 return handle_netlink_request(f, dump_fp, &req.nlh,
3123 sizeof(req), netlink_show_sock);
3124 }
3125
3126 static int netlink_show(struct filter *f)
3127 {
3128 FILE *fp;
3129 char buf[256];
3130 int prot, pid;
3131 unsigned groups;
3132 int rq, wq, rc;
3133 unsigned long long sk, cb;
3134
3135 if (!(f->states & (1<<SS_CLOSE)))
3136 return 0;
3137
3138 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
3139 netlink_show_netlink(f, NULL) == 0)
3140 return 0;
3141
3142 if ((fp = net_netlink_open()) == NULL)
3143 return -1;
3144 fgets(buf, sizeof(buf)-1, fp);
3145
3146 while (fgets(buf, sizeof(buf)-1, fp)) {
3147 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
3148 &sk,
3149 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
3150
3151 netlink_show_one(f, prot, pid, groups, 0, 0, 0, rq, wq, sk, cb);
3152 }
3153
3154 return 0;
3155 }
3156
3157 struct snmpstat
3158 {
3159 int tcp_estab;
3160 };
3161
3162 static int get_snmp_int(char *proto, char *key, int *result)
3163 {
3164 char buf[1024];
3165 FILE *fp;
3166 int protolen = strlen(proto);
3167 int keylen = strlen(key);
3168
3169 *result = 0;
3170
3171 if ((fp = net_snmp_open()) == NULL)
3172 return -1;
3173
3174 while (fgets(buf, sizeof(buf), fp) != NULL) {
3175 char *p = buf;
3176 int pos = 0;
3177 if (memcmp(buf, proto, protolen))
3178 continue;
3179 while ((p = strchr(p, ' ')) != NULL) {
3180 pos++;
3181 p++;
3182 if (memcmp(p, key, keylen) == 0 &&
3183 (p[keylen] == ' ' || p[keylen] == '\n'))
3184 break;
3185 }
3186 if (fgets(buf, sizeof(buf), fp) == NULL)
3187 break;
3188 if (memcmp(buf, proto, protolen))
3189 break;
3190 p = buf;
3191 while ((p = strchr(p, ' ')) != NULL) {
3192 p++;
3193 if (--pos == 0) {
3194 sscanf(p, "%d", result);
3195 fclose(fp);
3196 return 0;
3197 }
3198 }
3199 }
3200
3201 fclose(fp);
3202 errno = ESRCH;
3203 return -1;
3204 }
3205
3206
3207 /* Get stats from sockstat */
3208
3209 struct sockstat
3210 {
3211 int socks;
3212 int tcp_mem;
3213 int tcp_total;
3214 int tcp_orphans;
3215 int tcp_tws;
3216 int tcp4_hashed;
3217 int udp4;
3218 int raw4;
3219 int frag4;
3220 int frag4_mem;
3221 int tcp6_hashed;
3222 int udp6;
3223 int raw6;
3224 int frag6;
3225 int frag6_mem;
3226 };
3227
3228 static void get_sockstat_line(char *line, struct sockstat *s)
3229 {
3230 char id[256], rem[256];
3231
3232 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
3233 return;
3234
3235 if (strcmp(id, "sockets:") == 0)
3236 sscanf(rem, "%*s%d", &s->socks);
3237 else if (strcmp(id, "UDP:") == 0)
3238 sscanf(rem, "%*s%d", &s->udp4);
3239 else if (strcmp(id, "UDP6:") == 0)
3240 sscanf(rem, "%*s%d", &s->udp6);
3241 else if (strcmp(id, "RAW:") == 0)
3242 sscanf(rem, "%*s%d", &s->raw4);
3243 else if (strcmp(id, "RAW6:") == 0)
3244 sscanf(rem, "%*s%d", &s->raw6);
3245 else if (strcmp(id, "TCP6:") == 0)
3246 sscanf(rem, "%*s%d", &s->tcp6_hashed);
3247 else if (strcmp(id, "FRAG:") == 0)
3248 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
3249 else if (strcmp(id, "FRAG6:") == 0)
3250 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
3251 else if (strcmp(id, "TCP:") == 0)
3252 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
3253 &s->tcp4_hashed,
3254 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
3255 }
3256
3257 static int get_sockstat(struct sockstat *s)
3258 {
3259 char buf[256];
3260 FILE *fp;
3261
3262 memset(s, 0, sizeof(*s));
3263
3264 if ((fp = net_sockstat_open()) == NULL)
3265 return -1;
3266 while(fgets(buf, sizeof(buf), fp) != NULL)
3267 get_sockstat_line(buf, s);
3268 fclose(fp);
3269
3270 if ((fp = net_sockstat6_open()) == NULL)
3271 return 0;
3272 while(fgets(buf, sizeof(buf), fp) != NULL)
3273 get_sockstat_line(buf, s);
3274 fclose(fp);
3275
3276 return 0;
3277 }
3278
3279 static int print_summary(void)
3280 {
3281 struct sockstat s;
3282 struct snmpstat sn;
3283
3284 if (get_sockstat(&s) < 0)
3285 perror("ss: get_sockstat");
3286 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
3287 perror("ss: get_snmpstat");
3288
3289 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
3290
3291 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
3292 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
3293 sn.tcp_estab,
3294 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
3295 s.tcp_orphans,
3296 slabstat.tcp_syns,
3297 s.tcp_tws, slabstat.tcp_tws,
3298 slabstat.tcp_ports
3299 );
3300
3301 printf("\n");
3302 printf("Transport Total IP IPv6\n");
3303 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
3304 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
3305 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
3306 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
3307 printf("INET %-9d %-9d %-9d\n",
3308 s.raw4+s.udp4+s.tcp4_hashed+
3309 s.raw6+s.udp6+s.tcp6_hashed,
3310 s.raw4+s.udp4+s.tcp4_hashed,
3311 s.raw6+s.udp6+s.tcp6_hashed);
3312 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
3313
3314 printf("\n");
3315
3316 return 0;
3317 }
3318
3319 static void _usage(FILE *dest)
3320 {
3321 fprintf(dest,
3322 "Usage: ss [ OPTIONS ]\n"
3323 " ss [ OPTIONS ] [ FILTER ]\n"
3324 " -h, --help this message\n"
3325 " -V, --version output version information\n"
3326 " -n, --numeric don't resolve service names\n"
3327 " -r, --resolve resolve host names\n"
3328 " -a, --all display all sockets\n"
3329 " -l, --listening display listening sockets\n"
3330 " -o, --options show timer information\n"
3331 " -e, --extended show detailed socket information\n"
3332 " -m, --memory show socket memory usage\n"
3333 " -p, --processes show process using socket\n"
3334 " -i, --info show internal TCP information\n"
3335 " -s, --summary show socket usage summary\n"
3336 " -b, --bpf show bpf filter socket information\n"
3337 " -Z, --context display process SELinux security contexts\n"
3338 " -z, --contexts display process and socket SELinux security contexts\n"
3339 "\n"
3340 " -4, --ipv4 display only IP version 4 sockets\n"
3341 " -6, --ipv6 display only IP version 6 sockets\n"
3342 " -0, --packet display PACKET sockets\n"
3343 " -t, --tcp display only TCP sockets\n"
3344 " -u, --udp display only UDP sockets\n"
3345 " -d, --dccp display only DCCP sockets\n"
3346 " -w, --raw display only RAW sockets\n"
3347 " -x, --unix display only Unix domain sockets\n"
3348 " -f, --family=FAMILY display sockets of type FAMILY\n"
3349 "\n"
3350 " -A, --query=QUERY, --socket=QUERY\n"
3351 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink}[,QUERY]\n"
3352 "\n"
3353 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
3354 " -F, --filter=FILE read filter information from FILE\n"
3355 " FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
3356 );
3357 }
3358
3359 static void help(void) __attribute__((noreturn));
3360 static void help(void)
3361 {
3362 _usage(stdout);
3363 exit(0);
3364 }
3365
3366 static void usage(void) __attribute__((noreturn));
3367 static void usage(void)
3368 {
3369 _usage(stderr);
3370 exit(-1);
3371 }
3372
3373
3374 static int scan_state(const char *state)
3375 {
3376 int i;
3377 if (strcasecmp(state, "close") == 0 ||
3378 strcasecmp(state, "closed") == 0)
3379 return (1<<SS_CLOSE);
3380 if (strcasecmp(state, "syn-rcv") == 0)
3381 return (1<<SS_SYN_RECV);
3382 if (strcasecmp(state, "established") == 0)
3383 return (1<<SS_ESTABLISHED);
3384 if (strcasecmp(state, "all") == 0)
3385 return SS_ALL;
3386 if (strcasecmp(state, "connected") == 0)
3387 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
3388 if (strcasecmp(state, "synchronized") == 0)
3389 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
3390 if (strcasecmp(state, "bucket") == 0)
3391 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
3392 if (strcasecmp(state, "big") == 0)
3393 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
3394 for (i=0; i<SS_MAX; i++) {
3395 if (strcasecmp(state, sstate_namel[i]) == 0)
3396 return (1<<i);
3397 }
3398 return 0;
3399 }
3400
3401 static const struct option long_opts[] = {
3402 { "numeric", 0, 0, 'n' },
3403 { "resolve", 0, 0, 'r' },
3404 { "options", 0, 0, 'o' },
3405 { "extended", 0, 0, 'e' },
3406 { "memory", 0, 0, 'm' },
3407 { "info", 0, 0, 'i' },
3408 { "processes", 0, 0, 'p' },
3409 { "bpf", 0, 0, 'b' },
3410 { "dccp", 0, 0, 'd' },
3411 { "tcp", 0, 0, 't' },
3412 { "udp", 0, 0, 'u' },
3413 { "raw", 0, 0, 'w' },
3414 { "unix", 0, 0, 'x' },
3415 { "all", 0, 0, 'a' },
3416 { "listening", 0, 0, 'l' },
3417 { "ipv4", 0, 0, '4' },
3418 { "ipv6", 0, 0, '6' },
3419 { "packet", 0, 0, '0' },
3420 { "family", 1, 0, 'f' },
3421 { "socket", 1, 0, 'A' },
3422 { "query", 1, 0, 'A' },
3423 { "summary", 0, 0, 's' },
3424 { "diag", 1, 0, 'D' },
3425 { "filter", 1, 0, 'F' },
3426 { "version", 0, 0, 'V' },
3427 { "help", 0, 0, 'h' },
3428 { "context", 0, 0, 'Z' },
3429 { "contexts", 0, 0, 'z' },
3430 { 0 }
3431
3432 };
3433
3434 int main(int argc, char *argv[])
3435 {
3436 int do_default = 1;
3437 int saw_states = 0;
3438 int saw_query = 0;
3439 int do_summary = 0;
3440 const char *dump_tcpdiag = NULL;
3441 FILE *filter_fp = NULL;
3442 int ch;
3443
3444 memset(&current_filter, 0, sizeof(current_filter));
3445
3446 current_filter.states = default_filter.states;
3447
3448 while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spbf:miA:D:F:vVzZ",
3449 long_opts, NULL)) != EOF) {
3450 switch(ch) {
3451 case 'n':
3452 resolve_services = 0;
3453 break;
3454 case 'r':
3455 resolve_hosts = 1;
3456 break;
3457 case 'o':
3458 show_options = 1;
3459 break;
3460 case 'e':
3461 show_options = 1;
3462 show_details++;
3463 break;
3464 case 'm':
3465 show_mem = 1;
3466 break;
3467 case 'i':
3468 show_tcpinfo = 1;
3469 break;
3470 case 'p':
3471 show_users++;
3472 user_ent_hash_build();
3473 break;
3474 case 'b':
3475 show_options = 1;
3476 show_bpf++;
3477 break;
3478 case 'd':
3479 current_filter.dbs |= (1<<DCCP_DB);
3480 do_default = 0;
3481 break;
3482 case 't':
3483 current_filter.dbs |= (1<<TCP_DB);
3484 do_default = 0;
3485 break;
3486 case 'u':
3487 current_filter.dbs |= (1<<UDP_DB);
3488 do_default = 0;
3489 break;
3490 case 'w':
3491 current_filter.dbs |= (1<<RAW_DB);
3492 do_default = 0;
3493 break;
3494 case 'x':
3495 current_filter.dbs |= UNIX_DBM;
3496 do_default = 0;
3497 break;
3498 case 'a':
3499 current_filter.states = SS_ALL;
3500 break;
3501 case 'l':
3502 current_filter.states = (1<<SS_LISTEN) | (1<<SS_CLOSE);
3503 break;
3504 case '4':
3505 preferred_family = AF_INET;
3506 break;
3507 case '6':
3508 preferred_family = AF_INET6;
3509 break;
3510 case '0':
3511 preferred_family = AF_PACKET;
3512 break;
3513 case 'f':
3514 if (strcmp(optarg, "inet") == 0)
3515 preferred_family = AF_INET;
3516 else if (strcmp(optarg, "inet6") == 0)
3517 preferred_family = AF_INET6;
3518 else if (strcmp(optarg, "link") == 0)
3519 preferred_family = AF_PACKET;
3520 else if (strcmp(optarg, "unix") == 0)
3521 preferred_family = AF_UNIX;
3522 else if (strcmp(optarg, "netlink") == 0)
3523 preferred_family = AF_NETLINK;
3524 else if (strcmp(optarg, "help") == 0)
3525 help();
3526 else {
3527 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
3528 usage();
3529 }
3530 break;
3531 case 'A':
3532 {
3533 char *p, *p1;
3534 if (!saw_query) {
3535 current_filter.dbs = 0;
3536 saw_query = 1;
3537 do_default = 0;
3538 }
3539 p = p1 = optarg;
3540 do {
3541 if ((p1 = strchr(p, ',')) != NULL)
3542 *p1 = 0;
3543 if (strcmp(p, "all") == 0) {
3544 current_filter.dbs = ALL_DB;
3545 } else if (strcmp(p, "inet") == 0) {
3546 current_filter.dbs |= (1<<TCP_DB)|(1<<DCCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
3547 } else if (strcmp(p, "udp") == 0) {
3548 current_filter.dbs |= (1<<UDP_DB);
3549 } else if (strcmp(p, "dccp") == 0) {
3550 current_filter.dbs |= (1<<DCCP_DB);
3551 } else if (strcmp(p, "tcp") == 0) {
3552 current_filter.dbs |= (1<<TCP_DB);
3553 } else if (strcmp(p, "raw") == 0) {
3554 current_filter.dbs |= (1<<RAW_DB);
3555 } else if (strcmp(p, "unix") == 0) {
3556 current_filter.dbs |= UNIX_DBM;
3557 } else if (strcasecmp(p, "unix_stream") == 0 ||
3558 strcmp(p, "u_str") == 0) {
3559 current_filter.dbs |= (1<<UNIX_ST_DB);
3560 } else if (strcasecmp(p, "unix_dgram") == 0 ||
3561 strcmp(p, "u_dgr") == 0) {
3562 current_filter.dbs |= (1<<UNIX_DG_DB);
3563 } else if (strcasecmp(p, "unix_seqpacket") == 0 ||
3564 strcmp(p, "u_seq") == 0) {
3565 current_filter.dbs |= (1<<UNIX_SQ_DB);
3566 } else if (strcmp(p, "packet") == 0) {
3567 current_filter.dbs |= PACKET_DBM;
3568 } else if (strcmp(p, "packet_raw") == 0 ||
3569 strcmp(p, "p_raw") == 0) {
3570 current_filter.dbs |= (1<<PACKET_R_DB);
3571 } else if (strcmp(p, "packet_dgram") == 0 ||
3572 strcmp(p, "p_dgr") == 0) {
3573 current_filter.dbs |= (1<<PACKET_DG_DB);
3574 } else if (strcmp(p, "netlink") == 0) {
3575 current_filter.dbs |= (1<<NETLINK_DB);
3576 } else {
3577 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
3578 usage();
3579 }
3580 p = p1 + 1;
3581 } while (p1);
3582 break;
3583 }
3584 case 's':
3585 do_summary = 1;
3586 break;
3587 case 'D':
3588 dump_tcpdiag = optarg;
3589 break;
3590 case 'F':
3591 if (filter_fp) {
3592 fprintf(stderr, "More than one filter file\n");
3593 exit(-1);
3594 }
3595 if (optarg[0] == '-')
3596 filter_fp = stdin;
3597 else
3598 filter_fp = fopen(optarg, "r");
3599 if (!filter_fp) {
3600 perror("fopen filter file");
3601 exit(-1);
3602 }
3603 break;
3604 case 'v':
3605 case 'V':
3606 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
3607 exit(0);
3608 case 'z':
3609 show_sock_ctx++;
3610 case 'Z':
3611 if (is_selinux_enabled() <= 0) {
3612 fprintf(stderr, "ss: SELinux is not enabled.\n");
3613 exit(1);
3614 }
3615 show_proc_ctx++;
3616 user_ent_hash_build();
3617 break;
3618 case 'h':
3619 case '?':
3620 help();
3621 default:
3622 usage();
3623 }
3624 }
3625
3626 argc -= optind;
3627 argv += optind;
3628
3629 get_slabstat(&slabstat);
3630
3631 if (do_summary) {
3632 print_summary();
3633 if (do_default && argc == 0)
3634 exit(0);
3635 }
3636
3637 if (do_default)
3638 current_filter.dbs = default_filter.dbs;
3639
3640 if (preferred_family == AF_UNSPEC) {
3641 if (!(current_filter.dbs&~UNIX_DBM))
3642 preferred_family = AF_UNIX;
3643 else if (!(current_filter.dbs&~PACKET_DBM))
3644 preferred_family = AF_PACKET;
3645 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
3646 preferred_family = AF_NETLINK;
3647 }
3648
3649 if (preferred_family != AF_UNSPEC) {
3650 int mask2;
3651 if (preferred_family == AF_INET ||
3652 preferred_family == AF_INET6) {
3653 mask2= current_filter.dbs;
3654 } else if (preferred_family == AF_PACKET) {
3655 mask2 = PACKET_DBM;
3656 } else if (preferred_family == AF_UNIX) {
3657 mask2 = UNIX_DBM;
3658 } else if (preferred_family == AF_NETLINK) {
3659 mask2 = (1<<NETLINK_DB);
3660 } else {
3661 mask2 = 0;
3662 }
3663
3664 if (do_default)
3665 current_filter.dbs = mask2;
3666 else
3667 current_filter.dbs &= mask2;
3668 current_filter.families = (1<<preferred_family);
3669 } else {
3670 if (!do_default)
3671 current_filter.families = ~0;
3672 else
3673 current_filter.families = default_filter.families;
3674 }
3675 if (current_filter.dbs == 0) {
3676 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
3677 exit(0);
3678 }
3679 if (current_filter.families == 0) {
3680 fprintf(stderr, "ss: no families to show with such filter.\n");
3681 exit(0);
3682 }
3683
3684 if (resolve_services && resolve_hosts &&
3685 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
3686 init_service_resolver();
3687
3688 /* Now parse filter... */
3689 if (argc == 0 && filter_fp) {
3690 if (ssfilter_parse(&current_filter.f, 0, NULL, filter_fp))
3691 usage();
3692 }
3693
3694 while (argc > 0) {
3695 if (strcmp(*argv, "state") == 0) {
3696 NEXT_ARG();
3697 if (!saw_states)
3698 current_filter.states = 0;
3699 current_filter.states |= scan_state(*argv);
3700 saw_states = 1;
3701 } else if (strcmp(*argv, "exclude") == 0 ||
3702 strcmp(*argv, "excl") == 0) {
3703 NEXT_ARG();
3704 if (!saw_states)
3705 current_filter.states = SS_ALL;
3706 current_filter.states &= ~scan_state(*argv);
3707 saw_states = 1;
3708 } else {
3709 if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
3710 usage();
3711 break;
3712 }
3713 argc--; argv++;
3714 }
3715
3716 if (current_filter.states == 0) {
3717 fprintf(stderr, "ss: no socket states to show with such filter.\n");
3718 exit(0);
3719 }
3720
3721 if (dump_tcpdiag) {
3722 FILE *dump_fp = stdout;
3723 if (!(current_filter.dbs & (1<<TCP_DB))) {
3724 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
3725 exit(0);
3726 }
3727 if (dump_tcpdiag[0] != '-') {
3728 dump_fp = fopen(dump_tcpdiag, "w");
3729 if (!dump_tcpdiag) {
3730 perror("fopen dump file");
3731 exit(-1);
3732 }
3733 }
3734 inet_show_netlink(&current_filter, dump_fp, IPPROTO_TCP);
3735 fflush(dump_fp);
3736 exit(0);
3737 }
3738
3739 netid_width = 0;
3740 if (current_filter.dbs&(current_filter.dbs-1))
3741 netid_width = 5;
3742
3743 state_width = 0;
3744 if (current_filter.states&(current_filter.states-1))
3745 state_width = 10;
3746
3747 screen_width = 80;
3748 if (isatty(STDOUT_FILENO)) {
3749 struct winsize w;
3750
3751 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
3752 if (w.ws_col > 0)
3753 screen_width = w.ws_col;
3754 }
3755 }
3756
3757 addrp_width = screen_width;
3758 addrp_width -= netid_width+1;
3759 addrp_width -= state_width+1;
3760 addrp_width -= 14;
3761
3762 if (addrp_width&1) {
3763 if (netid_width)
3764 netid_width++;
3765 else if (state_width)
3766 state_width++;
3767 }
3768
3769 addrp_width /= 2;
3770 addrp_width--;
3771
3772 serv_width = resolve_services ? 7 : 5;
3773
3774 if (addrp_width < 15+serv_width+1)
3775 addrp_width = 15+serv_width+1;
3776
3777 addr_width = addrp_width - serv_width - 1;
3778
3779 if (netid_width)
3780 printf("%-*s ", netid_width, "Netid");
3781 if (state_width)
3782 printf("%-*s ", state_width, "State");
3783 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
3784
3785 printf("%*s:%-*s %*s:%-*s\n",
3786 addr_width, "Local Address", serv_width, "Port",
3787 addr_width, "Peer Address", serv_width, "Port");
3788
3789 fflush(stdout);
3790
3791 if (current_filter.dbs & (1<<NETLINK_DB))
3792 netlink_show(&current_filter);
3793 if (current_filter.dbs & PACKET_DBM)
3794 packet_show(&current_filter);
3795 if (current_filter.dbs & UNIX_DBM)
3796 unix_show(&current_filter);
3797 if (current_filter.dbs & (1<<RAW_DB))
3798 raw_show(&current_filter);
3799 if (current_filter.dbs & (1<<UDP_DB))
3800 udp_show(&current_filter);
3801 if (current_filter.dbs & (1<<TCP_DB))
3802 tcp_show(&current_filter, IPPROTO_TCP);
3803 if (current_filter.dbs & (1<<DCCP_DB))
3804 tcp_show(&current_filter, IPPROTO_DCCP);
3805
3806 if (show_users || show_proc_ctx || show_sock_ctx)
3807 user_ent_destroy();
3808
3809 return 0;
3810 }