]> git.proxmox.com Git - mirror_iproute2.git/blob - misc/ss.c
Merge branch 'master' into net-next
[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 <fcntl.h>
16 #include <sys/ioctl.h>
17 #include <sys/socket.h>
18 #include <sys/uio.h>
19 #include <netinet/in.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <netdb.h>
23 #include <arpa/inet.h>
24 #include <dirent.h>
25 #include <fnmatch.h>
26 #include <getopt.h>
27 #include <stdbool.h>
28 #include <limits.h>
29 #include <stdarg.h>
30
31 #include "utils.h"
32 #include "rt_names.h"
33 #include "ll_map.h"
34 #include "libnetlink.h"
35 #include "namespace.h"
36 #include "SNAPSHOT.h"
37
38 #include <linux/tcp.h>
39 #include <linux/sock_diag.h>
40 #include <linux/inet_diag.h>
41 #include <linux/unix_diag.h>
42 #include <linux/netdevice.h> /* for MAX_ADDR_LEN */
43 #include <linux/filter.h>
44 #include <linux/packet_diag.h>
45 #include <linux/netlink_diag.h>
46 #include <linux/sctp.h>
47 #include <linux/vm_sockets_diag.h>
48
49 #define MAGIC_SEQ 123456
50 #define BUF_CHUNK (1024 * 1024)
51 #define LEN_ALIGN(x) (((x) + 1) & ~1)
52
53 #define DIAG_REQUEST(_req, _r) \
54 struct { \
55 struct nlmsghdr nlh; \
56 _r; \
57 } _req = { \
58 .nlh = { \
59 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
60 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
61 .nlmsg_seq = MAGIC_SEQ, \
62 .nlmsg_len = sizeof(_req), \
63 }, \
64 }
65
66 #if HAVE_SELINUX
67 #include <selinux/selinux.h>
68 #else
69 /* Stubs for SELinux functions */
70 static int is_selinux_enabled(void)
71 {
72 return -1;
73 }
74
75 static int getpidcon(pid_t pid, char **context)
76 {
77 *context = NULL;
78 return -1;
79 }
80
81 static int getfilecon(char *path, char **context)
82 {
83 *context = NULL;
84 return -1;
85 }
86
87 static int security_get_initial_context(char *name, char **context)
88 {
89 *context = NULL;
90 return -1;
91 }
92 #endif
93
94 int resolve_services = 1;
95 int preferred_family = AF_UNSPEC;
96 int show_options;
97 int show_details;
98 int show_users;
99 int show_mem;
100 int show_tcpinfo;
101 int show_bpf;
102 int show_proc_ctx;
103 int show_sock_ctx;
104 int show_header = 1;
105 int follow_events;
106 int sctp_ino;
107
108 enum col_id {
109 COL_NETID,
110 COL_STATE,
111 COL_RECVQ,
112 COL_SENDQ,
113 COL_ADDR,
114 COL_SERV,
115 COL_RADDR,
116 COL_RSERV,
117 COL_EXT,
118 COL_MAX
119 };
120
121 enum col_align {
122 ALIGN_LEFT,
123 ALIGN_CENTER,
124 ALIGN_RIGHT
125 };
126
127 struct column {
128 const enum col_align align;
129 const char *header;
130 const char *ldelim;
131 int disabled;
132 int width; /* Calculated, including additional layout spacing */
133 int max_len; /* Measured maximum field length in this column */
134 };
135
136 static struct column columns[] = {
137 { ALIGN_LEFT, "Netid", "", 0, 0, 0 },
138 { ALIGN_LEFT, "State", " ", 0, 0, 0 },
139 { ALIGN_LEFT, "Recv-Q", " ", 0, 0, 0 },
140 { ALIGN_LEFT, "Send-Q", " ", 0, 0, 0 },
141 { ALIGN_RIGHT, "Local Address:", " ", 0, 0, 0 },
142 { ALIGN_LEFT, "Port", "", 0, 0, 0 },
143 { ALIGN_RIGHT, "Peer Address:", " ", 0, 0, 0 },
144 { ALIGN_LEFT, "Port", "", 0, 0, 0 },
145 { ALIGN_LEFT, "", "", 0, 0, 0 },
146 };
147
148 static struct column *current_field = columns;
149
150 /* Output buffer: chained chunks of BUF_CHUNK bytes. Each field is written to
151 * the buffer as a variable size token. A token consists of a 16 bits length
152 * field, followed by a string which is not NULL-terminated.
153 *
154 * A new chunk is allocated and linked when the current chunk doesn't have
155 * enough room to store the current token as a whole.
156 */
157 struct buf_chunk {
158 struct buf_chunk *next; /* Next chained chunk */
159 char *end; /* Current end of content */
160 char data[0];
161 };
162
163 struct buf_token {
164 uint16_t len; /* Data length, excluding length descriptor */
165 char data[0];
166 };
167
168 static struct {
169 struct buf_token *cur; /* Position of current token in chunk */
170 struct buf_chunk *head; /* First chunk */
171 struct buf_chunk *tail; /* Current chunk */
172 } buffer;
173
174 static const char *TCP_PROTO = "tcp";
175 static const char *SCTP_PROTO = "sctp";
176 static const char *UDP_PROTO = "udp";
177 static const char *RAW_PROTO = "raw";
178 static const char *dg_proto;
179
180 enum {
181 TCP_DB,
182 DCCP_DB,
183 UDP_DB,
184 RAW_DB,
185 UNIX_DG_DB,
186 UNIX_ST_DB,
187 UNIX_SQ_DB,
188 PACKET_DG_DB,
189 PACKET_R_DB,
190 NETLINK_DB,
191 SCTP_DB,
192 VSOCK_ST_DB,
193 VSOCK_DG_DB,
194 MAX_DB
195 };
196
197 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
198 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
199 #define ALL_DB ((1<<MAX_DB)-1)
200 #define INET_L4_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<SCTP_DB))
201 #define INET_DBM (INET_L4_DBM | (1<<RAW_DB))
202 #define VSOCK_DBM ((1<<VSOCK_ST_DB)|(1<<VSOCK_DG_DB))
203
204 enum {
205 SS_UNKNOWN,
206 SS_ESTABLISHED,
207 SS_SYN_SENT,
208 SS_SYN_RECV,
209 SS_FIN_WAIT1,
210 SS_FIN_WAIT2,
211 SS_TIME_WAIT,
212 SS_CLOSE,
213 SS_CLOSE_WAIT,
214 SS_LAST_ACK,
215 SS_LISTEN,
216 SS_CLOSING,
217 SS_MAX
218 };
219
220 enum {
221 SCTP_STATE_CLOSED = 0,
222 SCTP_STATE_COOKIE_WAIT = 1,
223 SCTP_STATE_COOKIE_ECHOED = 2,
224 SCTP_STATE_ESTABLISHED = 3,
225 SCTP_STATE_SHUTDOWN_PENDING = 4,
226 SCTP_STATE_SHUTDOWN_SENT = 5,
227 SCTP_STATE_SHUTDOWN_RECEIVED = 6,
228 SCTP_STATE_SHUTDOWN_ACK_SENT = 7,
229 };
230
231 #define SS_ALL ((1 << SS_MAX) - 1)
232 #define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
233
234 #include "ssfilter.h"
235
236 struct filter {
237 int dbs;
238 int states;
239 uint64_t families;
240 struct ssfilter *f;
241 bool kill;
242 };
243
244 #define FAMILY_MASK(family) ((uint64_t)1 << (family))
245
246 static const struct filter default_dbs[MAX_DB] = {
247 [TCP_DB] = {
248 .states = SS_CONN,
249 .families = FAMILY_MASK(AF_INET) | FAMILY_MASK(AF_INET6),
250 },
251 [DCCP_DB] = {
252 .states = SS_CONN,
253 .families = FAMILY_MASK(AF_INET) | FAMILY_MASK(AF_INET6),
254 },
255 [UDP_DB] = {
256 .states = (1 << SS_ESTABLISHED),
257 .families = FAMILY_MASK(AF_INET) | FAMILY_MASK(AF_INET6),
258 },
259 [RAW_DB] = {
260 .states = (1 << SS_ESTABLISHED),
261 .families = FAMILY_MASK(AF_INET) | FAMILY_MASK(AF_INET6),
262 },
263 [UNIX_DG_DB] = {
264 .states = (1 << SS_CLOSE),
265 .families = FAMILY_MASK(AF_UNIX),
266 },
267 [UNIX_ST_DB] = {
268 .states = SS_CONN,
269 .families = FAMILY_MASK(AF_UNIX),
270 },
271 [UNIX_SQ_DB] = {
272 .states = SS_CONN,
273 .families = FAMILY_MASK(AF_UNIX),
274 },
275 [PACKET_DG_DB] = {
276 .states = (1 << SS_CLOSE),
277 .families = FAMILY_MASK(AF_PACKET),
278 },
279 [PACKET_R_DB] = {
280 .states = (1 << SS_CLOSE),
281 .families = FAMILY_MASK(AF_PACKET),
282 },
283 [NETLINK_DB] = {
284 .states = (1 << SS_CLOSE),
285 .families = FAMILY_MASK(AF_NETLINK),
286 },
287 [SCTP_DB] = {
288 .states = SS_CONN,
289 .families = FAMILY_MASK(AF_INET) | FAMILY_MASK(AF_INET6),
290 },
291 [VSOCK_ST_DB] = {
292 .states = SS_CONN,
293 .families = FAMILY_MASK(AF_VSOCK),
294 },
295 [VSOCK_DG_DB] = {
296 .states = SS_CONN,
297 .families = FAMILY_MASK(AF_VSOCK),
298 },
299 };
300
301 static const struct filter default_afs[AF_MAX] = {
302 [AF_INET] = {
303 .dbs = INET_DBM,
304 .states = SS_CONN,
305 },
306 [AF_INET6] = {
307 .dbs = INET_DBM,
308 .states = SS_CONN,
309 },
310 [AF_UNIX] = {
311 .dbs = UNIX_DBM,
312 .states = SS_CONN,
313 },
314 [AF_PACKET] = {
315 .dbs = PACKET_DBM,
316 .states = (1 << SS_CLOSE),
317 },
318 [AF_NETLINK] = {
319 .dbs = (1 << NETLINK_DB),
320 .states = (1 << SS_CLOSE),
321 },
322 [AF_VSOCK] = {
323 .dbs = VSOCK_DBM,
324 .states = SS_CONN,
325 },
326 };
327
328 static int do_default = 1;
329 static struct filter current_filter;
330
331 static void filter_db_set(struct filter *f, int db)
332 {
333 f->states |= default_dbs[db].states;
334 f->dbs |= 1 << db;
335 do_default = 0;
336 }
337
338 static void filter_af_set(struct filter *f, int af)
339 {
340 f->states |= default_afs[af].states;
341 f->families |= FAMILY_MASK(af);
342 do_default = 0;
343 preferred_family = af;
344 }
345
346 static int filter_af_get(struct filter *f, int af)
347 {
348 return !!(f->families & FAMILY_MASK(af));
349 }
350
351 static void filter_default_dbs(struct filter *f)
352 {
353 filter_db_set(f, UDP_DB);
354 filter_db_set(f, DCCP_DB);
355 filter_db_set(f, TCP_DB);
356 filter_db_set(f, RAW_DB);
357 filter_db_set(f, UNIX_ST_DB);
358 filter_db_set(f, UNIX_DG_DB);
359 filter_db_set(f, UNIX_SQ_DB);
360 filter_db_set(f, PACKET_R_DB);
361 filter_db_set(f, PACKET_DG_DB);
362 filter_db_set(f, NETLINK_DB);
363 filter_db_set(f, SCTP_DB);
364 filter_db_set(f, VSOCK_ST_DB);
365 filter_db_set(f, VSOCK_DG_DB);
366 }
367
368 static void filter_states_set(struct filter *f, int states)
369 {
370 if (states)
371 f->states = states;
372 }
373
374 static void filter_merge_defaults(struct filter *f)
375 {
376 int db;
377 int af;
378
379 for (db = 0; db < MAX_DB; db++) {
380 if (!(f->dbs & (1 << db)))
381 continue;
382
383 if (!(default_dbs[db].families & f->families))
384 f->families |= default_dbs[db].families;
385 }
386 for (af = 0; af < AF_MAX; af++) {
387 if (!(f->families & FAMILY_MASK(af)))
388 continue;
389
390 if (!(default_afs[af].dbs & f->dbs))
391 f->dbs |= default_afs[af].dbs;
392 }
393 }
394
395 static FILE *generic_proc_open(const char *env, const char *name)
396 {
397 const char *p = getenv(env);
398 char store[128];
399
400 if (!p) {
401 p = getenv("PROC_ROOT") ? : "/proc";
402 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
403 p = store;
404 }
405
406 return fopen(p, "r");
407 }
408 #define net_tcp_open() generic_proc_open("PROC_NET_TCP", "net/tcp")
409 #define net_tcp6_open() generic_proc_open("PROC_NET_TCP6", "net/tcp6")
410 #define net_udp_open() generic_proc_open("PROC_NET_UDP", "net/udp")
411 #define net_udp6_open() generic_proc_open("PROC_NET_UDP6", "net/udp6")
412 #define net_raw_open() generic_proc_open("PROC_NET_RAW", "net/raw")
413 #define net_raw6_open() generic_proc_open("PROC_NET_RAW6", "net/raw6")
414 #define net_unix_open() generic_proc_open("PROC_NET_UNIX", "net/unix")
415 #define net_packet_open() generic_proc_open("PROC_NET_PACKET", \
416 "net/packet")
417 #define net_netlink_open() generic_proc_open("PROC_NET_NETLINK", \
418 "net/netlink")
419 #define slabinfo_open() generic_proc_open("PROC_SLABINFO", "slabinfo")
420 #define net_sockstat_open() generic_proc_open("PROC_NET_SOCKSTAT", \
421 "net/sockstat")
422 #define net_sockstat6_open() generic_proc_open("PROC_NET_SOCKSTAT6", \
423 "net/sockstat6")
424 #define net_snmp_open() generic_proc_open("PROC_NET_SNMP", "net/snmp")
425 #define ephemeral_ports_open() generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", \
426 "sys/net/ipv4/ip_local_port_range")
427
428 struct user_ent {
429 struct user_ent *next;
430 unsigned int ino;
431 int pid;
432 int fd;
433 char *process;
434 char *process_ctx;
435 char *socket_ctx;
436 };
437
438 #define USER_ENT_HASH_SIZE 256
439 struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE];
440
441 static int user_ent_hashfn(unsigned int ino)
442 {
443 int val = (ino >> 24) ^ (ino >> 16) ^ (ino >> 8) ^ ino;
444
445 return val & (USER_ENT_HASH_SIZE - 1);
446 }
447
448 static void user_ent_add(unsigned int ino, char *process,
449 int pid, int fd,
450 char *proc_ctx,
451 char *sock_ctx)
452 {
453 struct user_ent *p, **pp;
454
455 p = malloc(sizeof(struct user_ent));
456 if (!p) {
457 fprintf(stderr, "ss: failed to malloc buffer\n");
458 abort();
459 }
460 p->next = NULL;
461 p->ino = ino;
462 p->pid = pid;
463 p->fd = fd;
464 p->process = strdup(process);
465 p->process_ctx = strdup(proc_ctx);
466 p->socket_ctx = strdup(sock_ctx);
467
468 pp = &user_ent_hash[user_ent_hashfn(ino)];
469 p->next = *pp;
470 *pp = p;
471 }
472
473 static void user_ent_destroy(void)
474 {
475 struct user_ent *p, *p_next;
476 int cnt = 0;
477
478 while (cnt != USER_ENT_HASH_SIZE) {
479 p = user_ent_hash[cnt];
480 while (p) {
481 free(p->process);
482 free(p->process_ctx);
483 free(p->socket_ctx);
484 p_next = p->next;
485 free(p);
486 p = p_next;
487 }
488 cnt++;
489 }
490 }
491
492 static void user_ent_hash_build(void)
493 {
494 const char *root = getenv("PROC_ROOT") ? : "/proc/";
495 struct dirent *d;
496 char name[1024];
497 int nameoff;
498 DIR *dir;
499 char *pid_context;
500 char *sock_context;
501 const char *no_ctx = "unavailable";
502 static int user_ent_hash_build_init;
503
504 /* If show_users & show_proc_ctx set only do this once */
505 if (user_ent_hash_build_init != 0)
506 return;
507
508 user_ent_hash_build_init = 1;
509
510 strlcpy(name, root, sizeof(name));
511
512 if (strlen(name) == 0 || name[strlen(name)-1] != '/')
513 strcat(name, "/");
514
515 nameoff = strlen(name);
516
517 dir = opendir(name);
518 if (!dir)
519 return;
520
521 while ((d = readdir(dir)) != NULL) {
522 struct dirent *d1;
523 char process[16];
524 char *p;
525 int pid, pos;
526 DIR *dir1;
527 char crap;
528
529 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
530 continue;
531
532 if (getpidcon(pid, &pid_context) != 0)
533 pid_context = strdup(no_ctx);
534
535 snprintf(name + nameoff, sizeof(name) - nameoff, "%d/fd/", pid);
536 pos = strlen(name);
537 if ((dir1 = opendir(name)) == NULL) {
538 free(pid_context);
539 continue;
540 }
541
542 process[0] = '\0';
543 p = process;
544
545 while ((d1 = readdir(dir1)) != NULL) {
546 const char *pattern = "socket:[";
547 unsigned int ino;
548 char lnk[64];
549 int fd;
550 ssize_t link_len;
551 char tmp[1024];
552
553 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
554 continue;
555
556 snprintf(name+pos, sizeof(name) - pos, "%d", fd);
557
558 link_len = readlink(name, lnk, sizeof(lnk)-1);
559 if (link_len == -1)
560 continue;
561 lnk[link_len] = '\0';
562
563 if (strncmp(lnk, pattern, strlen(pattern)))
564 continue;
565
566 sscanf(lnk, "socket:[%u]", &ino);
567
568 snprintf(tmp, sizeof(tmp), "%s/%d/fd/%s",
569 root, pid, d1->d_name);
570
571 if (getfilecon(tmp, &sock_context) <= 0)
572 sock_context = strdup(no_ctx);
573
574 if (*p == '\0') {
575 FILE *fp;
576
577 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
578 root, pid);
579 if ((fp = fopen(tmp, "r")) != NULL) {
580 if (fscanf(fp, "%*d (%[^)])", p) < 1)
581 ; /* ignore */
582 fclose(fp);
583 }
584 }
585 user_ent_add(ino, p, pid, fd,
586 pid_context, sock_context);
587 free(sock_context);
588 }
589 free(pid_context);
590 closedir(dir1);
591 }
592 closedir(dir);
593 }
594
595 enum entry_types {
596 USERS,
597 PROC_CTX,
598 PROC_SOCK_CTX
599 };
600
601 #define ENTRY_BUF_SIZE 512
602 static int find_entry(unsigned int ino, char **buf, int type)
603 {
604 struct user_ent *p;
605 int cnt = 0;
606 char *ptr;
607 char *new_buf;
608 int len, new_buf_len;
609 int buf_used = 0;
610 int buf_len = 0;
611
612 if (!ino)
613 return 0;
614
615 p = user_ent_hash[user_ent_hashfn(ino)];
616 ptr = *buf = NULL;
617 while (p) {
618 if (p->ino != ino)
619 goto next;
620
621 while (1) {
622 ptr = *buf + buf_used;
623 switch (type) {
624 case USERS:
625 len = snprintf(ptr, buf_len - buf_used,
626 "(\"%s\",pid=%d,fd=%d),",
627 p->process, p->pid, p->fd);
628 break;
629 case PROC_CTX:
630 len = snprintf(ptr, buf_len - buf_used,
631 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
632 p->process, p->pid,
633 p->process_ctx, p->fd);
634 break;
635 case PROC_SOCK_CTX:
636 len = snprintf(ptr, buf_len - buf_used,
637 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
638 p->process, p->pid,
639 p->process_ctx, p->fd,
640 p->socket_ctx);
641 break;
642 default:
643 fprintf(stderr, "ss: invalid type: %d\n", type);
644 abort();
645 }
646
647 if (len < 0 || len >= buf_len - buf_used) {
648 new_buf_len = buf_len + ENTRY_BUF_SIZE;
649 new_buf = realloc(*buf, new_buf_len);
650 if (!new_buf) {
651 fprintf(stderr, "ss: failed to malloc buffer\n");
652 abort();
653 }
654 *buf = new_buf;
655 buf_len = new_buf_len;
656 continue;
657 } else {
658 buf_used += len;
659 break;
660 }
661 }
662 cnt++;
663 next:
664 p = p->next;
665 }
666 if (buf_used) {
667 ptr = *buf + buf_used;
668 ptr[-1] = '\0';
669 }
670 return cnt;
671 }
672
673 /* Get stats from slab */
674
675 struct slabstat {
676 int socks;
677 int tcp_ports;
678 int tcp_tws;
679 int tcp_syns;
680 int skbs;
681 };
682
683 static struct slabstat slabstat;
684
685 static int get_slabstat(struct slabstat *s)
686 {
687 char buf[256];
688 FILE *fp;
689 int cnt;
690 static int slabstat_valid;
691 static const char * const slabstat_ids[] = {
692 "sock",
693 "tcp_bind_bucket",
694 "tcp_tw_bucket",
695 "tcp_open_request",
696 "skbuff_head_cache",
697 };
698
699 if (slabstat_valid)
700 return 0;
701
702 memset(s, 0, sizeof(*s));
703
704 fp = slabinfo_open();
705 if (!fp)
706 return -1;
707
708 cnt = sizeof(*s)/sizeof(int);
709
710 if (!fgets(buf, sizeof(buf), fp)) {
711 fclose(fp);
712 return -1;
713 }
714 while (fgets(buf, sizeof(buf), fp) != NULL) {
715 int i;
716
717 for (i = 0; i < ARRAY_SIZE(slabstat_ids); i++) {
718 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
719 sscanf(buf, "%*s%d", ((int *)s) + i);
720 cnt--;
721 break;
722 }
723 }
724 if (cnt <= 0)
725 break;
726 }
727
728 slabstat_valid = 1;
729
730 fclose(fp);
731 return 0;
732 }
733
734 static unsigned long long cookie_sk_get(const uint32_t *cookie)
735 {
736 return (((unsigned long long)cookie[1] << 31) << 1) | cookie[0];
737 }
738
739 static const char *sctp_sstate_name[] = {
740 [SCTP_STATE_CLOSED] = "CLOSED",
741 [SCTP_STATE_COOKIE_WAIT] = "COOKIE_WAIT",
742 [SCTP_STATE_COOKIE_ECHOED] = "COOKIE_ECHOED",
743 [SCTP_STATE_ESTABLISHED] = "ESTAB",
744 [SCTP_STATE_SHUTDOWN_PENDING] = "SHUTDOWN_PENDING",
745 [SCTP_STATE_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
746 [SCTP_STATE_SHUTDOWN_RECEIVED] = "SHUTDOWN_RECEIVED",
747 [SCTP_STATE_SHUTDOWN_ACK_SENT] = "ACK_SENT",
748 };
749
750 struct sockstat {
751 struct sockstat *next;
752 unsigned int type;
753 uint16_t prot;
754 uint16_t raw_prot;
755 inet_prefix local;
756 inet_prefix remote;
757 int lport;
758 int rport;
759 int state;
760 int rq, wq;
761 unsigned int ino;
762 unsigned int uid;
763 int refcnt;
764 unsigned int iface;
765 unsigned long long sk;
766 char *name;
767 char *peer_name;
768 __u32 mark;
769 };
770
771 struct dctcpstat {
772 unsigned int ce_state;
773 unsigned int alpha;
774 unsigned int ab_ecn;
775 unsigned int ab_tot;
776 bool enabled;
777 };
778
779 struct tcpstat {
780 struct sockstat ss;
781 unsigned int timer;
782 unsigned int timeout;
783 int probes;
784 char cong_alg[16];
785 double rto, ato, rtt, rttvar;
786 int qack, ssthresh, backoff;
787 double send_bps;
788 int snd_wscale;
789 int rcv_wscale;
790 int mss;
791 int rcv_mss;
792 int advmss;
793 unsigned int pmtu;
794 unsigned int cwnd;
795 unsigned int lastsnd;
796 unsigned int lastrcv;
797 unsigned int lastack;
798 double pacing_rate;
799 double pacing_rate_max;
800 double delivery_rate;
801 unsigned long long bytes_acked;
802 unsigned long long bytes_received;
803 unsigned int segs_out;
804 unsigned int segs_in;
805 unsigned int data_segs_out;
806 unsigned int data_segs_in;
807 unsigned int unacked;
808 unsigned int retrans;
809 unsigned int retrans_total;
810 unsigned int lost;
811 unsigned int sacked;
812 unsigned int fackets;
813 unsigned int reordering;
814 unsigned int not_sent;
815 double rcv_rtt;
816 double min_rtt;
817 int rcv_space;
818 unsigned int rcv_ssthresh;
819 unsigned long long busy_time;
820 unsigned long long rwnd_limited;
821 unsigned long long sndbuf_limited;
822 bool has_ts_opt;
823 bool has_sack_opt;
824 bool has_ecn_opt;
825 bool has_ecnseen_opt;
826 bool has_fastopen_opt;
827 bool has_wscale_opt;
828 bool app_limited;
829 struct dctcpstat *dctcp;
830 struct tcp_bbr_info *bbr_info;
831 };
832
833 /* SCTP assocs share the same inode number with their parent endpoint. So if we
834 * have seen the inode number before, it must be an assoc instead of the next
835 * endpoint. */
836 static bool is_sctp_assoc(struct sockstat *s, const char *sock_name)
837 {
838 if (strcmp(sock_name, "sctp"))
839 return false;
840 if (!sctp_ino || sctp_ino != s->ino)
841 return false;
842 return true;
843 }
844
845 static const char *unix_netid_name(int type)
846 {
847 switch (type) {
848 case SOCK_STREAM:
849 return "u_str";
850 case SOCK_SEQPACKET:
851 return "u_seq";
852 case SOCK_DGRAM:
853 default:
854 return "u_dgr";
855 }
856 }
857
858 static const char *proto_name(int protocol)
859 {
860 switch (protocol) {
861 case 0:
862 return "raw";
863 case IPPROTO_UDP:
864 return "udp";
865 case IPPROTO_TCP:
866 return "tcp";
867 case IPPROTO_SCTP:
868 return "sctp";
869 case IPPROTO_DCCP:
870 return "dccp";
871 case IPPROTO_ICMPV6:
872 return "icmp6";
873 }
874
875 return "???";
876 }
877
878 static const char *vsock_netid_name(int type)
879 {
880 switch (type) {
881 case SOCK_STREAM:
882 return "v_str";
883 case SOCK_DGRAM:
884 return "v_dgr";
885 default:
886 return "???";
887 }
888 }
889
890 /* Allocate and initialize a new buffer chunk */
891 static struct buf_chunk *buf_chunk_new(void)
892 {
893 struct buf_chunk *new = malloc(BUF_CHUNK);
894
895 if (!new)
896 abort();
897
898 new->next = NULL;
899
900 /* This is also the last block */
901 buffer.tail = new;
902
903 /* Next token will be stored at the beginning of chunk data area, and
904 * its initial length is zero.
905 */
906 buffer.cur = (struct buf_token *)new->data;
907 buffer.cur->len = 0;
908
909 new->end = buffer.cur->data;
910
911 return new;
912 }
913
914 /* Return available tail room in given chunk */
915 static int buf_chunk_avail(struct buf_chunk *chunk)
916 {
917 return BUF_CHUNK - offsetof(struct buf_chunk, data) -
918 (chunk->end - chunk->data);
919 }
920
921 /* Update end pointer and token length, link new chunk if we hit the end of the
922 * current one. Return -EAGAIN if we got a new chunk, caller has to print again.
923 */
924 static int buf_update(int len)
925 {
926 struct buf_chunk *chunk = buffer.tail;
927 struct buf_token *t = buffer.cur;
928
929 /* Claim success if new content fits in the current chunk, and anyway
930 * if this is the first token in the chunk: in the latter case,
931 * allocating a new chunk won't help, so we'll just cut the output.
932 */
933 if ((len < buf_chunk_avail(chunk) && len != -1 /* glibc < 2.0.6 */) ||
934 t == (struct buf_token *)chunk->data) {
935 len = min(len, buf_chunk_avail(chunk));
936
937 /* Total field length can't exceed 2^16 bytes, cut as needed */
938 len = min(len, USHRT_MAX - t->len);
939
940 chunk->end += len;
941 t->len += len;
942 return 0;
943 }
944
945 /* Content truncated, time to allocate more */
946 chunk->next = buf_chunk_new();
947
948 /* Copy current token over to new chunk, including length descriptor */
949 memcpy(chunk->next->data, t, sizeof(t->len) + t->len);
950 chunk->next->end += t->len;
951
952 /* Discard partially written field in old chunk */
953 chunk->end -= t->len + sizeof(t->len);
954
955 return -EAGAIN;
956 }
957
958 /* Append content to buffer as part of the current field */
959 static void out(const char *fmt, ...)
960 {
961 struct column *f = current_field;
962 va_list args;
963 char *pos;
964 int len;
965
966 if (f->disabled)
967 return;
968
969 if (!buffer.head)
970 buffer.head = buf_chunk_new();
971
972 again: /* Append to buffer: if we have a new chunk, print again */
973
974 pos = buffer.cur->data + buffer.cur->len;
975 va_start(args, fmt);
976
977 /* Limit to tail room. If we hit the limit, buf_update() will tell us */
978 len = vsnprintf(pos, buf_chunk_avail(buffer.tail), fmt, args);
979 va_end(args);
980
981 if (buf_update(len))
982 goto again;
983 }
984
985 static int print_left_spacing(struct column *f, int stored, int printed)
986 {
987 int s;
988
989 if (!f->width || f->align == ALIGN_LEFT)
990 return 0;
991
992 s = f->width - stored - printed;
993 if (f->align == ALIGN_CENTER)
994 /* If count of total spacing is odd, shift right by one */
995 s = (s + 1) / 2;
996
997 if (s > 0)
998 return printf("%*c", s, ' ');
999
1000 return 0;
1001 }
1002
1003 static void print_right_spacing(struct column *f, int printed)
1004 {
1005 int s;
1006
1007 if (!f->width || f->align == ALIGN_RIGHT)
1008 return;
1009
1010 s = f->width - printed;
1011 if (f->align == ALIGN_CENTER)
1012 s /= 2;
1013
1014 if (s > 0)
1015 printf("%*c", s, ' ');
1016 }
1017
1018 /* Done with field: update buffer pointer, start new token after current one */
1019 static void field_flush(struct column *f)
1020 {
1021 struct buf_chunk *chunk;
1022 unsigned int pad;
1023
1024 if (f->disabled)
1025 return;
1026
1027 chunk = buffer.tail;
1028 pad = buffer.cur->len % 2;
1029
1030 if (buffer.cur->len > f->max_len)
1031 f->max_len = buffer.cur->len;
1032
1033 /* We need a new chunk if we can't store the next length descriptor.
1034 * Mind the gap between end of previous token and next aligned position
1035 * for length descriptor.
1036 */
1037 if (buf_chunk_avail(chunk) - pad < sizeof(buffer.cur->len)) {
1038 chunk->end += pad;
1039 chunk->next = buf_chunk_new();
1040 return;
1041 }
1042
1043 buffer.cur = (struct buf_token *)(buffer.cur->data +
1044 LEN_ALIGN(buffer.cur->len));
1045 buffer.cur->len = 0;
1046 buffer.tail->end = buffer.cur->data;
1047 }
1048
1049 static int field_is_last(struct column *f)
1050 {
1051 return f - columns == COL_MAX - 1;
1052 }
1053
1054 static void field_next(void)
1055 {
1056 field_flush(current_field);
1057
1058 if (field_is_last(current_field))
1059 current_field = columns;
1060 else
1061 current_field++;
1062 }
1063
1064 /* Walk through fields and flush them until we reach the desired one */
1065 static void field_set(enum col_id id)
1066 {
1067 while (id != current_field - columns)
1068 field_next();
1069 }
1070
1071 /* Print header for all non-empty columns */
1072 static void print_header(void)
1073 {
1074 while (!field_is_last(current_field)) {
1075 if (!current_field->disabled)
1076 out(current_field->header);
1077 field_next();
1078 }
1079 }
1080
1081 /* Get the next available token in the buffer starting from the current token */
1082 static struct buf_token *buf_token_next(struct buf_token *cur)
1083 {
1084 struct buf_chunk *chunk = buffer.tail;
1085
1086 /* If we reached the end of chunk contents, get token from next chunk */
1087 if (cur->data + LEN_ALIGN(cur->len) == chunk->end) {
1088 buffer.tail = chunk = chunk->next;
1089 return chunk ? (struct buf_token *)chunk->data : NULL;
1090 }
1091
1092 return (struct buf_token *)(cur->data + LEN_ALIGN(cur->len));
1093 }
1094
1095 /* Free up all allocated buffer chunks */
1096 static void buf_free_all(void)
1097 {
1098 struct buf_chunk *tmp;
1099
1100 for (buffer.tail = buffer.head; buffer.tail; ) {
1101 tmp = buffer.tail;
1102 buffer.tail = buffer.tail->next;
1103 free(tmp);
1104 }
1105 buffer.head = NULL;
1106 }
1107
1108 /* Calculate column width from contents length. If columns don't fit on one
1109 * line, break them into the least possible amount of lines and keep them
1110 * aligned across lines. Available screen space is equally spread between fields
1111 * as additional spacing.
1112 */
1113 static void render_calc_width(int screen_width)
1114 {
1115 int first, len = 0, linecols = 0;
1116 struct column *c, *eol = columns - 1;
1117
1118 /* First pass: set width for each column to measured content length */
1119 for (first = 1, c = columns; c - columns < COL_MAX; c++) {
1120 if (c->disabled)
1121 continue;
1122
1123 if (!first && c->max_len)
1124 c->width = c->max_len + strlen(c->ldelim);
1125 else
1126 c->width = c->max_len;
1127
1128 /* But don't exceed screen size. If we exceed the screen size
1129 * for even a single field, it will just start on a line of its
1130 * own and then naturally wrap.
1131 */
1132 c->width = min(c->width, screen_width);
1133
1134 if (c->width)
1135 first = 0;
1136 }
1137
1138 /* Second pass: find out newlines and distribute available spacing */
1139 for (c = columns; c - columns < COL_MAX; c++) {
1140 int pad, spacing, rem, last;
1141 struct column *tmp;
1142
1143 if (!c->width)
1144 continue;
1145
1146 linecols++;
1147 len += c->width;
1148
1149 for (last = 1, tmp = c + 1; tmp - columns < COL_MAX; tmp++) {
1150 if (tmp->width) {
1151 last = 0;
1152 break;
1153 }
1154 }
1155
1156 if (!last && len < screen_width) {
1157 /* Columns fit on screen so far, nothing to do yet */
1158 continue;
1159 }
1160
1161 if (len == screen_width) {
1162 /* Exact fit, just start with new line */
1163 goto newline;
1164 }
1165
1166 if (len > screen_width) {
1167 /* Screen width exceeded: go back one column */
1168 len -= c->width;
1169 c--;
1170 linecols--;
1171 }
1172
1173 /* Distribute remaining space to columns on this line */
1174 pad = screen_width - len;
1175 spacing = pad / linecols;
1176 rem = pad % linecols;
1177 for (tmp = c; tmp > eol; tmp--) {
1178 if (!tmp->width)
1179 continue;
1180
1181 tmp->width += spacing;
1182 if (rem) {
1183 tmp->width++;
1184 rem--;
1185 }
1186 }
1187
1188 newline:
1189 /* Line break: reset line counters, mark end-of-line */
1190 eol = c;
1191 len = 0;
1192 linecols = 0;
1193 }
1194 }
1195
1196 /* Render buffered output with spacing and delimiters, then free up buffers */
1197 static void render(int screen_width)
1198 {
1199 struct buf_token *token = (struct buf_token *)buffer.head->data;
1200 int printed, line_started = 0;
1201 struct column *f;
1202
1203 /* Ensure end alignment of last token, it wasn't necessarily flushed */
1204 buffer.tail->end += buffer.cur->len % 2;
1205
1206 render_calc_width(screen_width);
1207
1208 /* Rewind and replay */
1209 buffer.tail = buffer.head;
1210
1211 f = columns;
1212 while (!f->width)
1213 f++;
1214
1215 while (token) {
1216 /* Print left delimiter only if we already started a line */
1217 if (line_started++)
1218 printed = printf("%s", current_field->ldelim);
1219 else
1220 printed = 0;
1221
1222 /* Print field content from token data with spacing */
1223 printed += print_left_spacing(f, token->len, printed);
1224 printed += fwrite(token->data, 1, token->len, stdout);
1225 print_right_spacing(f, printed);
1226
1227 /* Go to next non-empty field, deal with end-of-line */
1228 do {
1229 if (field_is_last(f)) {
1230 printf("\n");
1231 f = columns;
1232 line_started = 0;
1233 } else {
1234 f++;
1235 }
1236 } while (f->disabled);
1237
1238 token = buf_token_next(token);
1239 }
1240
1241 buf_free_all();
1242 }
1243
1244 static void sock_state_print(struct sockstat *s)
1245 {
1246 const char *sock_name;
1247 static const char * const sstate_name[] = {
1248 "UNKNOWN",
1249 [SS_ESTABLISHED] = "ESTAB",
1250 [SS_SYN_SENT] = "SYN-SENT",
1251 [SS_SYN_RECV] = "SYN-RECV",
1252 [SS_FIN_WAIT1] = "FIN-WAIT-1",
1253 [SS_FIN_WAIT2] = "FIN-WAIT-2",
1254 [SS_TIME_WAIT] = "TIME-WAIT",
1255 [SS_CLOSE] = "UNCONN",
1256 [SS_CLOSE_WAIT] = "CLOSE-WAIT",
1257 [SS_LAST_ACK] = "LAST-ACK",
1258 [SS_LISTEN] = "LISTEN",
1259 [SS_CLOSING] = "CLOSING",
1260 };
1261
1262 switch (s->local.family) {
1263 case AF_UNIX:
1264 sock_name = unix_netid_name(s->type);
1265 break;
1266 case AF_INET:
1267 case AF_INET6:
1268 sock_name = proto_name(s->type);
1269 break;
1270 case AF_PACKET:
1271 sock_name = s->type == SOCK_RAW ? "p_raw" : "p_dgr";
1272 break;
1273 case AF_NETLINK:
1274 sock_name = "nl";
1275 break;
1276 case AF_VSOCK:
1277 sock_name = vsock_netid_name(s->type);
1278 break;
1279 default:
1280 sock_name = "unknown";
1281 }
1282
1283 if (is_sctp_assoc(s, sock_name)) {
1284 field_set(COL_STATE); /* Empty Netid field */
1285 out("`- %s", sctp_sstate_name[s->state]);
1286 } else {
1287 field_set(COL_NETID);
1288 out("%s", sock_name);
1289 field_set(COL_STATE);
1290 out("%s", sstate_name[s->state]);
1291 }
1292
1293 field_set(COL_RECVQ);
1294 out("%-6d", s->rq);
1295 field_set(COL_SENDQ);
1296 out("%-6d", s->wq);
1297 field_set(COL_ADDR);
1298 }
1299
1300 static void sock_details_print(struct sockstat *s)
1301 {
1302 if (s->uid)
1303 out(" uid:%u", s->uid);
1304
1305 out(" ino:%u", s->ino);
1306 out(" sk:%llx", s->sk);
1307
1308 if (s->mark)
1309 out(" fwmark:0x%x", s->mark);
1310 }
1311
1312 static void sock_addr_print(const char *addr, char *delim, const char *port,
1313 const char *ifname)
1314 {
1315 if (ifname)
1316 out("%s" "%%" "%s%s", addr, ifname, delim);
1317 else
1318 out("%s%s", addr, delim);
1319
1320 field_next();
1321 out("%s", port);
1322 field_next();
1323 }
1324
1325 static const char *print_ms_timer(unsigned int timeout)
1326 {
1327 static char buf[64];
1328 int secs, msecs, minutes;
1329
1330 secs = timeout/1000;
1331 minutes = secs/60;
1332 secs = secs%60;
1333 msecs = timeout%1000;
1334 buf[0] = 0;
1335 if (minutes) {
1336 msecs = 0;
1337 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
1338 if (minutes > 9)
1339 secs = 0;
1340 }
1341 if (secs) {
1342 if (secs > 9)
1343 msecs = 0;
1344 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
1345 }
1346 if (msecs)
1347 sprintf(buf+strlen(buf), "%03dms", msecs);
1348 return buf;
1349 }
1350
1351 struct scache {
1352 struct scache *next;
1353 int port;
1354 char *name;
1355 const char *proto;
1356 };
1357
1358 struct scache *rlist;
1359
1360 static void init_service_resolver(void)
1361 {
1362 char buf[128];
1363 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
1364
1365 if (!fp)
1366 return;
1367
1368 if (!fgets(buf, sizeof(buf), fp)) {
1369 pclose(fp);
1370 return;
1371 }
1372 while (fgets(buf, sizeof(buf), fp) != NULL) {
1373 unsigned int progn, port;
1374 char proto[128], prog[128] = "rpc.";
1375 struct scache *c;
1376
1377 if (sscanf(buf, "%u %*d %s %u %s",
1378 &progn, proto, &port, prog+4) != 4)
1379 continue;
1380
1381 if (!(c = malloc(sizeof(*c))))
1382 continue;
1383
1384 c->port = port;
1385 c->name = strdup(prog);
1386 if (strcmp(proto, TCP_PROTO) == 0)
1387 c->proto = TCP_PROTO;
1388 else if (strcmp(proto, UDP_PROTO) == 0)
1389 c->proto = UDP_PROTO;
1390 else if (strcmp(proto, SCTP_PROTO) == 0)
1391 c->proto = SCTP_PROTO;
1392 else
1393 c->proto = NULL;
1394 c->next = rlist;
1395 rlist = c;
1396 }
1397 pclose(fp);
1398 }
1399
1400 /* Even do not try default linux ephemeral port ranges:
1401 * default /etc/services contains so much of useless crap
1402 * wouldbe "allocated" to this area that resolution
1403 * is really harmful. I shrug each time when seeing
1404 * "socks" or "cfinger" in dumps.
1405 */
1406 static int is_ephemeral(int port)
1407 {
1408 static int min = 0, max;
1409
1410 if (!min) {
1411 FILE *f = ephemeral_ports_open();
1412
1413 if (!f || fscanf(f, "%d %d", &min, &max) < 2) {
1414 min = 1024;
1415 max = 4999;
1416 }
1417 if (f)
1418 fclose(f);
1419 }
1420 return port >= min && port <= max;
1421 }
1422
1423
1424 static const char *__resolve_service(int port)
1425 {
1426 struct scache *c;
1427
1428 for (c = rlist; c; c = c->next) {
1429 if (c->port == port && c->proto == dg_proto)
1430 return c->name;
1431 }
1432
1433 if (!is_ephemeral(port)) {
1434 static int notfirst;
1435 struct servent *se;
1436
1437 if (!notfirst) {
1438 setservent(1);
1439 notfirst = 1;
1440 }
1441 se = getservbyport(htons(port), dg_proto);
1442 if (se)
1443 return se->s_name;
1444 }
1445
1446 return NULL;
1447 }
1448
1449 #define SCACHE_BUCKETS 1024
1450 static struct scache *cache_htab[SCACHE_BUCKETS];
1451
1452 static const char *resolve_service(int port)
1453 {
1454 static char buf[128];
1455 struct scache *c;
1456 const char *res;
1457 int hash;
1458
1459 if (port == 0) {
1460 buf[0] = '*';
1461 buf[1] = 0;
1462 return buf;
1463 }
1464
1465 if (!resolve_services)
1466 goto do_numeric;
1467
1468 if (dg_proto == RAW_PROTO)
1469 return inet_proto_n2a(port, buf, sizeof(buf));
1470
1471
1472 hash = (port^(((unsigned long)dg_proto)>>2)) % SCACHE_BUCKETS;
1473
1474 for (c = cache_htab[hash]; c; c = c->next) {
1475 if (c->port == port && c->proto == dg_proto)
1476 goto do_cache;
1477 }
1478
1479 c = malloc(sizeof(*c));
1480 if (!c)
1481 goto do_numeric;
1482 res = __resolve_service(port);
1483 c->port = port;
1484 c->name = res ? strdup(res) : NULL;
1485 c->proto = dg_proto;
1486 c->next = cache_htab[hash];
1487 cache_htab[hash] = c;
1488
1489 do_cache:
1490 if (c->name)
1491 return c->name;
1492
1493 do_numeric:
1494 sprintf(buf, "%u", port);
1495 return buf;
1496 }
1497
1498 static void inet_addr_print(const inet_prefix *a, int port,
1499 unsigned int ifindex, bool v6only)
1500 {
1501 char buf[1024];
1502 const char *ap = buf;
1503 const char *ifname = NULL;
1504
1505 if (a->family == AF_INET) {
1506 ap = format_host(AF_INET, 4, a->data);
1507 } else {
1508 if (!v6only &&
1509 !memcmp(a->data, &in6addr_any, sizeof(in6addr_any))) {
1510 buf[0] = '*';
1511 buf[1] = 0;
1512 } else {
1513 ap = format_host(a->family, 16, a->data);
1514
1515 /* Numeric IPv6 addresses should be bracketed */
1516 if (strchr(ap, ':')) {
1517 snprintf(buf, sizeof(buf),
1518 "[%s]", ap);
1519 ap = buf;
1520 }
1521 }
1522 }
1523
1524 if (ifindex)
1525 ifname = ll_index_to_name(ifindex);
1526
1527 sock_addr_print(ap, ":", resolve_service(port), ifname);
1528 }
1529
1530 struct aafilter {
1531 inet_prefix addr;
1532 int port;
1533 unsigned int iface;
1534 __u32 mark;
1535 __u32 mask;
1536 struct aafilter *next;
1537 };
1538
1539 static int inet2_addr_match(const inet_prefix *a, const inet_prefix *p,
1540 int plen)
1541 {
1542 if (!inet_addr_match(a, p, plen))
1543 return 0;
1544
1545 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1546 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1547 * sockets. Fair? */
1548 if (p->family == AF_INET && a->family == AF_INET6) {
1549 if (a->data[0] == 0 && a->data[1] == 0 &&
1550 a->data[2] == htonl(0xffff)) {
1551 inet_prefix tmp = *a;
1552
1553 tmp.data[0] = a->data[3];
1554 return inet_addr_match(&tmp, p, plen);
1555 }
1556 }
1557 return 1;
1558 }
1559
1560 static int unix_match(const inet_prefix *a, const inet_prefix *p)
1561 {
1562 char *addr, *pattern;
1563
1564 memcpy(&addr, a->data, sizeof(addr));
1565 memcpy(&pattern, p->data, sizeof(pattern));
1566 if (pattern == NULL)
1567 return 1;
1568 if (addr == NULL)
1569 addr = "";
1570 return !fnmatch(pattern, addr, 0);
1571 }
1572
1573 static int run_ssfilter(struct ssfilter *f, struct sockstat *s)
1574 {
1575 switch (f->type) {
1576 case SSF_S_AUTO:
1577 {
1578 if (s->local.family == AF_UNIX) {
1579 char *p;
1580
1581 memcpy(&p, s->local.data, sizeof(p));
1582 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
1583 strspn(p+1, "0123456789abcdef") == 5);
1584 }
1585 if (s->local.family == AF_PACKET)
1586 return s->lport == 0 && s->local.data[0] == 0;
1587 if (s->local.family == AF_NETLINK)
1588 return s->lport < 0;
1589 if (s->local.family == AF_VSOCK)
1590 return s->lport > 1023;
1591
1592 return is_ephemeral(s->lport);
1593 }
1594 case SSF_DCOND:
1595 {
1596 struct aafilter *a = (void *)f->pred;
1597
1598 if (a->addr.family == AF_UNIX)
1599 return unix_match(&s->remote, &a->addr);
1600 if (a->port != -1 && a->port != s->rport)
1601 return 0;
1602 if (a->addr.bitlen) {
1603 do {
1604 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
1605 return 1;
1606 } while ((a = a->next) != NULL);
1607 return 0;
1608 }
1609 return 1;
1610 }
1611 case SSF_SCOND:
1612 {
1613 struct aafilter *a = (void *)f->pred;
1614
1615 if (a->addr.family == AF_UNIX)
1616 return unix_match(&s->local, &a->addr);
1617 if (a->port != -1 && a->port != s->lport)
1618 return 0;
1619 if (a->addr.bitlen) {
1620 do {
1621 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
1622 return 1;
1623 } while ((a = a->next) != NULL);
1624 return 0;
1625 }
1626 return 1;
1627 }
1628 case SSF_D_GE:
1629 {
1630 struct aafilter *a = (void *)f->pred;
1631
1632 return s->rport >= a->port;
1633 }
1634 case SSF_D_LE:
1635 {
1636 struct aafilter *a = (void *)f->pred;
1637
1638 return s->rport <= a->port;
1639 }
1640 case SSF_S_GE:
1641 {
1642 struct aafilter *a = (void *)f->pred;
1643
1644 return s->lport >= a->port;
1645 }
1646 case SSF_S_LE:
1647 {
1648 struct aafilter *a = (void *)f->pred;
1649
1650 return s->lport <= a->port;
1651 }
1652 case SSF_DEVCOND:
1653 {
1654 struct aafilter *a = (void *)f->pred;
1655
1656 return s->iface == a->iface;
1657 }
1658 case SSF_MARKMASK:
1659 {
1660 struct aafilter *a = (void *)f->pred;
1661
1662 return (s->mark & a->mask) == a->mark;
1663 }
1664 /* Yup. It is recursion. Sorry. */
1665 case SSF_AND:
1666 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
1667 case SSF_OR:
1668 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
1669 case SSF_NOT:
1670 return !run_ssfilter(f->pred, s);
1671 default:
1672 abort();
1673 }
1674 }
1675
1676 /* Relocate external jumps by reloc. */
1677 static void ssfilter_patch(char *a, int len, int reloc)
1678 {
1679 while (len > 0) {
1680 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)a;
1681
1682 if (op->no == len+4)
1683 op->no += reloc;
1684 len -= op->yes;
1685 a += op->yes;
1686 }
1687 if (len < 0)
1688 abort();
1689 }
1690
1691 static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
1692 {
1693 switch (f->type) {
1694 case SSF_S_AUTO:
1695 {
1696 if (!(*bytecode = malloc(4))) abort();
1697 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
1698 return 4;
1699 }
1700 case SSF_DCOND:
1701 case SSF_SCOND:
1702 {
1703 struct aafilter *a = (void *)f->pred;
1704 struct aafilter *b;
1705 char *ptr;
1706 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
1707 int len = 0;
1708
1709 for (b = a; b; b = b->next) {
1710 len += 4 + sizeof(struct inet_diag_hostcond);
1711 if (a->addr.family == AF_INET6)
1712 len += 16;
1713 else
1714 len += 4;
1715 if (b->next)
1716 len += 4;
1717 }
1718 if (!(ptr = malloc(len))) abort();
1719 *bytecode = ptr;
1720 for (b = a; b; b = b->next) {
1721 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
1722 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
1723 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
1724 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond *)(ptr+4);
1725
1726 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
1727 cond->family = a->addr.family;
1728 cond->port = a->port;
1729 cond->prefix_len = a->addr.bitlen;
1730 memcpy(cond->addr, a->addr.data, alen);
1731 ptr += oplen;
1732 if (b->next) {
1733 op = (struct inet_diag_bc_op *)ptr;
1734 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
1735 ptr += 4;
1736 }
1737 }
1738 return ptr - *bytecode;
1739 }
1740 case SSF_D_GE:
1741 {
1742 struct aafilter *x = (void *)f->pred;
1743
1744 if (!(*bytecode = malloc(8))) abort();
1745 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
1746 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1747 return 8;
1748 }
1749 case SSF_D_LE:
1750 {
1751 struct aafilter *x = (void *)f->pred;
1752
1753 if (!(*bytecode = malloc(8))) abort();
1754 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
1755 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1756 return 8;
1757 }
1758 case SSF_S_GE:
1759 {
1760 struct aafilter *x = (void *)f->pred;
1761
1762 if (!(*bytecode = malloc(8))) abort();
1763 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
1764 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1765 return 8;
1766 }
1767 case SSF_S_LE:
1768 {
1769 struct aafilter *x = (void *)f->pred;
1770
1771 if (!(*bytecode = malloc(8))) abort();
1772 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
1773 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1774 return 8;
1775 }
1776
1777 case SSF_AND:
1778 {
1779 char *a1 = NULL, *a2 = NULL, *a;
1780 int l1, l2;
1781
1782 l1 = ssfilter_bytecompile(f->pred, &a1);
1783 l2 = ssfilter_bytecompile(f->post, &a2);
1784 if (!l1 || !l2) {
1785 free(a1);
1786 free(a2);
1787 return 0;
1788 }
1789 if (!(a = malloc(l1+l2))) abort();
1790 memcpy(a, a1, l1);
1791 memcpy(a+l1, a2, l2);
1792 free(a1); free(a2);
1793 ssfilter_patch(a, l1, l2);
1794 *bytecode = a;
1795 return l1+l2;
1796 }
1797 case SSF_OR:
1798 {
1799 char *a1 = NULL, *a2 = NULL, *a;
1800 int l1, l2;
1801
1802 l1 = ssfilter_bytecompile(f->pred, &a1);
1803 l2 = ssfilter_bytecompile(f->post, &a2);
1804 if (!l1 || !l2) {
1805 free(a1);
1806 free(a2);
1807 return 0;
1808 }
1809 if (!(a = malloc(l1+l2+4))) abort();
1810 memcpy(a, a1, l1);
1811 memcpy(a+l1+4, a2, l2);
1812 free(a1); free(a2);
1813 *(struct inet_diag_bc_op *)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
1814 *bytecode = a;
1815 return l1+l2+4;
1816 }
1817 case SSF_NOT:
1818 {
1819 char *a1 = NULL, *a;
1820 int l1;
1821
1822 l1 = ssfilter_bytecompile(f->pred, &a1);
1823 if (!l1) {
1824 free(a1);
1825 return 0;
1826 }
1827 if (!(a = malloc(l1+4))) abort();
1828 memcpy(a, a1, l1);
1829 free(a1);
1830 *(struct inet_diag_bc_op *)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
1831 *bytecode = a;
1832 return l1+4;
1833 }
1834 case SSF_DEVCOND:
1835 {
1836 /* bytecompile for SSF_DEVCOND not supported yet */
1837 return 0;
1838 }
1839 case SSF_MARKMASK:
1840 {
1841 struct aafilter *a = (void *)f->pred;
1842 struct instr {
1843 struct inet_diag_bc_op op;
1844 struct inet_diag_markcond cond;
1845 };
1846 int inslen = sizeof(struct instr);
1847
1848 if (!(*bytecode = malloc(inslen))) abort();
1849 ((struct instr *)*bytecode)[0] = (struct instr) {
1850 { INET_DIAG_BC_MARK_COND, inslen, inslen + 4 },
1851 { a->mark, a->mask},
1852 };
1853
1854 return inslen;
1855 }
1856 default:
1857 abort();
1858 }
1859 }
1860
1861 static int remember_he(struct aafilter *a, struct hostent *he)
1862 {
1863 char **ptr = he->h_addr_list;
1864 int cnt = 0;
1865 int len;
1866
1867 if (he->h_addrtype == AF_INET)
1868 len = 4;
1869 else if (he->h_addrtype == AF_INET6)
1870 len = 16;
1871 else
1872 return 0;
1873
1874 while (*ptr) {
1875 struct aafilter *b = a;
1876
1877 if (a->addr.bitlen) {
1878 if ((b = malloc(sizeof(*b))) == NULL)
1879 return cnt;
1880 *b = *a;
1881 a->next = b;
1882 }
1883 memcpy(b->addr.data, *ptr, len);
1884 b->addr.bytelen = len;
1885 b->addr.bitlen = len*8;
1886 b->addr.family = he->h_addrtype;
1887 ptr++;
1888 cnt++;
1889 }
1890 return cnt;
1891 }
1892
1893 static int get_dns_host(struct aafilter *a, const char *addr, int fam)
1894 {
1895 static int notfirst;
1896 int cnt = 0;
1897 struct hostent *he;
1898
1899 a->addr.bitlen = 0;
1900 if (!notfirst) {
1901 sethostent(1);
1902 notfirst = 1;
1903 }
1904 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
1905 if (he)
1906 cnt = remember_he(a, he);
1907 if (fam == AF_UNSPEC) {
1908 he = gethostbyname2(addr, AF_INET6);
1909 if (he)
1910 cnt += remember_he(a, he);
1911 }
1912 return !cnt;
1913 }
1914
1915 static int xll_initted;
1916
1917 static void xll_init(void)
1918 {
1919 struct rtnl_handle rth;
1920
1921 if (rtnl_open(&rth, 0) < 0)
1922 exit(1);
1923
1924 ll_init_map(&rth);
1925 rtnl_close(&rth);
1926 xll_initted = 1;
1927 }
1928
1929 static const char *xll_index_to_name(int index)
1930 {
1931 if (!xll_initted)
1932 xll_init();
1933 return ll_index_to_name(index);
1934 }
1935
1936 static int xll_name_to_index(const char *dev)
1937 {
1938 if (!xll_initted)
1939 xll_init();
1940 return ll_name_to_index(dev);
1941 }
1942
1943 void *parse_devcond(char *name)
1944 {
1945 struct aafilter a = { .iface = 0 };
1946 struct aafilter *res;
1947
1948 a.iface = xll_name_to_index(name);
1949 if (a.iface == 0) {
1950 char *end;
1951 unsigned long n;
1952
1953 n = strtoul(name, &end, 0);
1954 if (!end || end == name || *end || n > UINT_MAX)
1955 return NULL;
1956
1957 a.iface = n;
1958 }
1959
1960 res = malloc(sizeof(*res));
1961 *res = a;
1962
1963 return res;
1964 }
1965
1966 static void vsock_set_inet_prefix(inet_prefix *a, __u32 cid)
1967 {
1968 *a = (inet_prefix){
1969 .bytelen = sizeof(cid),
1970 .family = AF_VSOCK,
1971 };
1972 memcpy(a->data, &cid, sizeof(cid));
1973 }
1974
1975 void *parse_hostcond(char *addr, bool is_port)
1976 {
1977 char *port = NULL;
1978 struct aafilter a = { .port = -1 };
1979 struct aafilter *res;
1980 int fam = preferred_family;
1981 struct filter *f = &current_filter;
1982
1983 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
1984 char *p;
1985
1986 a.addr.family = AF_UNIX;
1987 if (strncmp(addr, "unix:", 5) == 0)
1988 addr += 5;
1989 p = strdup(addr);
1990 a.addr.bitlen = 8*strlen(p);
1991 memcpy(a.addr.data, &p, sizeof(p));
1992 fam = AF_UNIX;
1993 goto out;
1994 }
1995
1996 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
1997 a.addr.family = AF_PACKET;
1998 a.addr.bitlen = 0;
1999 if (strncmp(addr, "link:", 5) == 0)
2000 addr += 5;
2001 port = strchr(addr, ':');
2002 if (port) {
2003 *port = 0;
2004 if (port[1] && strcmp(port+1, "*")) {
2005 if (get_integer(&a.port, port+1, 0)) {
2006 if ((a.port = xll_name_to_index(port+1)) <= 0)
2007 return NULL;
2008 }
2009 }
2010 }
2011 if (addr[0] && strcmp(addr, "*")) {
2012 unsigned short tmp;
2013
2014 a.addr.bitlen = 32;
2015 if (ll_proto_a2n(&tmp, addr))
2016 return NULL;
2017 a.addr.data[0] = ntohs(tmp);
2018 }
2019 fam = AF_PACKET;
2020 goto out;
2021 }
2022
2023 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
2024 a.addr.family = AF_NETLINK;
2025 a.addr.bitlen = 0;
2026 if (strncmp(addr, "netlink:", 8) == 0)
2027 addr += 8;
2028 port = strchr(addr, ':');
2029 if (port) {
2030 *port = 0;
2031 if (port[1] && strcmp(port+1, "*")) {
2032 if (get_integer(&a.port, port+1, 0)) {
2033 if (strcmp(port+1, "kernel") == 0)
2034 a.port = 0;
2035 else
2036 return NULL;
2037 }
2038 }
2039 }
2040 if (addr[0] && strcmp(addr, "*")) {
2041 a.addr.bitlen = 32;
2042 if (nl_proto_a2n(&a.addr.data[0], addr) == -1)
2043 return NULL;
2044 }
2045 fam = AF_NETLINK;
2046 goto out;
2047 }
2048
2049 if (fam == AF_VSOCK || strncmp(addr, "vsock:", 6) == 0) {
2050 __u32 cid = ~(__u32)0;
2051
2052 a.addr.family = AF_VSOCK;
2053 if (strncmp(addr, "vsock:", 6) == 0)
2054 addr += 6;
2055
2056 if (is_port)
2057 port = addr;
2058 else {
2059 port = strchr(addr, ':');
2060 if (port) {
2061 *port = '\0';
2062 port++;
2063 }
2064 }
2065
2066 if (port && strcmp(port, "*") &&
2067 get_u32((__u32 *)&a.port, port, 0))
2068 return NULL;
2069
2070 if (addr[0] && strcmp(addr, "*")) {
2071 a.addr.bitlen = 32;
2072 if (get_u32(&cid, addr, 0))
2073 return NULL;
2074 }
2075 vsock_set_inet_prefix(&a.addr, cid);
2076 fam = AF_VSOCK;
2077 goto out;
2078 }
2079
2080 if (fam == AF_INET || !strncmp(addr, "inet:", 5)) {
2081 fam = AF_INET;
2082 if (!strncmp(addr, "inet:", 5))
2083 addr += 5;
2084 } else if (fam == AF_INET6 || !strncmp(addr, "inet6:", 6)) {
2085 fam = AF_INET6;
2086 if (!strncmp(addr, "inet6:", 6))
2087 addr += 6;
2088 }
2089
2090 /* URL-like literal [] */
2091 if (addr[0] == '[') {
2092 addr++;
2093 if ((port = strchr(addr, ']')) == NULL)
2094 return NULL;
2095 *port++ = 0;
2096 } else if (addr[0] == '*') {
2097 port = addr+1;
2098 } else {
2099 port = strrchr(strchr(addr, '/') ? : addr, ':');
2100 }
2101
2102 if (is_port)
2103 port = addr;
2104
2105 if (port && *port) {
2106 if (*port == ':')
2107 *port++ = 0;
2108
2109 if (*port && *port != '*') {
2110 if (get_integer(&a.port, port, 0)) {
2111 struct servent *se1 = NULL;
2112 struct servent *se2 = NULL;
2113
2114 if (current_filter.dbs&(1<<UDP_DB))
2115 se1 = getservbyname(port, UDP_PROTO);
2116 if (current_filter.dbs&(1<<TCP_DB))
2117 se2 = getservbyname(port, TCP_PROTO);
2118 if (se1 && se2 && se1->s_port != se2->s_port) {
2119 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
2120 return NULL;
2121 }
2122 if (!se1)
2123 se1 = se2;
2124 if (se1) {
2125 a.port = ntohs(se1->s_port);
2126 } else {
2127 struct scache *s;
2128
2129 for (s = rlist; s; s = s->next) {
2130 if ((s->proto == UDP_PROTO &&
2131 (current_filter.dbs&(1<<UDP_DB))) ||
2132 (s->proto == TCP_PROTO &&
2133 (current_filter.dbs&(1<<TCP_DB)))) {
2134 if (s->name && strcmp(s->name, port) == 0) {
2135 if (a.port > 0 && a.port != s->port) {
2136 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
2137 return NULL;
2138 }
2139 a.port = s->port;
2140 }
2141 }
2142 }
2143 if (a.port <= 0) {
2144 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
2145 return NULL;
2146 }
2147 }
2148 }
2149 }
2150 }
2151 if (!is_port && *addr && *addr != '*') {
2152 if (get_prefix_1(&a.addr, addr, fam)) {
2153 if (get_dns_host(&a, addr, fam)) {
2154 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
2155 return NULL;
2156 }
2157 }
2158 }
2159
2160 out:
2161 if (fam != AF_UNSPEC) {
2162 int states = f->states;
2163 f->families = 0;
2164 filter_af_set(f, fam);
2165 filter_states_set(f, states);
2166 }
2167
2168 res = malloc(sizeof(*res));
2169 if (res)
2170 memcpy(res, &a, sizeof(a));
2171 return res;
2172 }
2173
2174 void *parse_markmask(const char *markmask)
2175 {
2176 struct aafilter a, *res;
2177
2178 if (strchr(markmask, '/')) {
2179 if (sscanf(markmask, "%i/%i", &a.mark, &a.mask) != 2)
2180 return NULL;
2181 } else {
2182 a.mask = 0xffffffff;
2183 if (sscanf(markmask, "%i", &a.mark) != 1)
2184 return NULL;
2185 }
2186
2187 res = malloc(sizeof(*res));
2188 if (res)
2189 memcpy(res, &a, sizeof(a));
2190 return res;
2191 }
2192
2193 static void proc_ctx_print(struct sockstat *s)
2194 {
2195 char *buf;
2196
2197 if (show_proc_ctx || show_sock_ctx) {
2198 if (find_entry(s->ino, &buf,
2199 (show_proc_ctx & show_sock_ctx) ?
2200 PROC_SOCK_CTX : PROC_CTX) > 0) {
2201 out(" users:(%s)", buf);
2202 free(buf);
2203 }
2204 } else if (show_users) {
2205 if (find_entry(s->ino, &buf, USERS) > 0) {
2206 out(" users:(%s)", buf);
2207 free(buf);
2208 }
2209 }
2210 }
2211
2212 static void inet_stats_print(struct sockstat *s, bool v6only)
2213 {
2214 sock_state_print(s);
2215
2216 inet_addr_print(&s->local, s->lport, s->iface, v6only);
2217 inet_addr_print(&s->remote, s->rport, 0, v6only);
2218
2219 proc_ctx_print(s);
2220 }
2221
2222 static int proc_parse_inet_addr(char *loc, char *rem, int family, struct
2223 sockstat * s)
2224 {
2225 s->local.family = s->remote.family = family;
2226 if (family == AF_INET) {
2227 sscanf(loc, "%x:%x", s->local.data, (unsigned *)&s->lport);
2228 sscanf(rem, "%x:%x", s->remote.data, (unsigned *)&s->rport);
2229 s->local.bytelen = s->remote.bytelen = 4;
2230 return 0;
2231 } else {
2232 sscanf(loc, "%08x%08x%08x%08x:%x",
2233 s->local.data,
2234 s->local.data + 1,
2235 s->local.data + 2,
2236 s->local.data + 3,
2237 &s->lport);
2238 sscanf(rem, "%08x%08x%08x%08x:%x",
2239 s->remote.data,
2240 s->remote.data + 1,
2241 s->remote.data + 2,
2242 s->remote.data + 3,
2243 &s->rport);
2244 s->local.bytelen = s->remote.bytelen = 16;
2245 return 0;
2246 }
2247 return -1;
2248 }
2249
2250 static int proc_inet_split_line(char *line, char **loc, char **rem, char **data)
2251 {
2252 char *p;
2253
2254 if ((p = strchr(line, ':')) == NULL)
2255 return -1;
2256
2257 *loc = p+2;
2258 if ((p = strchr(*loc, ':')) == NULL)
2259 return -1;
2260
2261 p[5] = 0;
2262 *rem = p+6;
2263 if ((p = strchr(*rem, ':')) == NULL)
2264 return -1;
2265
2266 p[5] = 0;
2267 *data = p+6;
2268 return 0;
2269 }
2270
2271 static char *sprint_bw(char *buf, double bw)
2272 {
2273 if (bw > 1000000.)
2274 sprintf(buf, "%.1fM", bw / 1000000.);
2275 else if (bw > 1000.)
2276 sprintf(buf, "%.1fK", bw / 1000.);
2277 else
2278 sprintf(buf, "%g", bw);
2279
2280 return buf;
2281 }
2282
2283 static void sctp_stats_print(struct sctp_info *s)
2284 {
2285 if (s->sctpi_tag)
2286 out(" tag:%x", s->sctpi_tag);
2287 if (s->sctpi_state)
2288 out(" state:%s", sctp_sstate_name[s->sctpi_state]);
2289 if (s->sctpi_rwnd)
2290 out(" rwnd:%d", s->sctpi_rwnd);
2291 if (s->sctpi_unackdata)
2292 out(" unackdata:%d", s->sctpi_unackdata);
2293 if (s->sctpi_penddata)
2294 out(" penddata:%d", s->sctpi_penddata);
2295 if (s->sctpi_instrms)
2296 out(" instrms:%d", s->sctpi_instrms);
2297 if (s->sctpi_outstrms)
2298 out(" outstrms:%d", s->sctpi_outstrms);
2299 if (s->sctpi_inqueue)
2300 out(" inqueue:%d", s->sctpi_inqueue);
2301 if (s->sctpi_outqueue)
2302 out(" outqueue:%d", s->sctpi_outqueue);
2303 if (s->sctpi_overall_error)
2304 out(" overerr:%d", s->sctpi_overall_error);
2305 if (s->sctpi_max_burst)
2306 out(" maxburst:%d", s->sctpi_max_burst);
2307 if (s->sctpi_maxseg)
2308 out(" maxseg:%d", s->sctpi_maxseg);
2309 if (s->sctpi_peer_rwnd)
2310 out(" prwnd:%d", s->sctpi_peer_rwnd);
2311 if (s->sctpi_peer_tag)
2312 out(" ptag:%x", s->sctpi_peer_tag);
2313 if (s->sctpi_peer_capable)
2314 out(" pcapable:%d", s->sctpi_peer_capable);
2315 if (s->sctpi_peer_sack)
2316 out(" psack:%d", s->sctpi_peer_sack);
2317 if (s->sctpi_s_autoclose)
2318 out(" autoclose:%d", s->sctpi_s_autoclose);
2319 if (s->sctpi_s_adaptation_ind)
2320 out(" adapind:%d", s->sctpi_s_adaptation_ind);
2321 if (s->sctpi_s_pd_point)
2322 out(" pdpoint:%d", s->sctpi_s_pd_point);
2323 if (s->sctpi_s_nodelay)
2324 out(" nodealy:%d", s->sctpi_s_nodelay);
2325 if (s->sctpi_s_disable_fragments)
2326 out(" nofrag:%d", s->sctpi_s_disable_fragments);
2327 if (s->sctpi_s_v4mapped)
2328 out(" v4mapped:%d", s->sctpi_s_v4mapped);
2329 if (s->sctpi_s_frag_interleave)
2330 out(" fraginl:%d", s->sctpi_s_frag_interleave);
2331 }
2332
2333 static void tcp_stats_print(struct tcpstat *s)
2334 {
2335 char b1[64];
2336
2337 if (s->has_ts_opt)
2338 out(" ts");
2339 if (s->has_sack_opt)
2340 out(" sack");
2341 if (s->has_ecn_opt)
2342 out(" ecn");
2343 if (s->has_ecnseen_opt)
2344 out(" ecnseen");
2345 if (s->has_fastopen_opt)
2346 out(" fastopen");
2347 if (s->cong_alg[0])
2348 out(" %s", s->cong_alg);
2349 if (s->has_wscale_opt)
2350 out(" wscale:%d,%d", s->snd_wscale, s->rcv_wscale);
2351 if (s->rto)
2352 out(" rto:%g", s->rto);
2353 if (s->backoff)
2354 out(" backoff:%u", s->backoff);
2355 if (s->rtt)
2356 out(" rtt:%g/%g", s->rtt, s->rttvar);
2357 if (s->ato)
2358 out(" ato:%g", s->ato);
2359
2360 if (s->qack)
2361 out(" qack:%d", s->qack);
2362 if (s->qack & 1)
2363 out(" bidir");
2364
2365 if (s->mss)
2366 out(" mss:%d", s->mss);
2367 if (s->pmtu)
2368 out(" pmtu:%u", s->pmtu);
2369 if (s->rcv_mss)
2370 out(" rcvmss:%d", s->rcv_mss);
2371 if (s->advmss)
2372 out(" advmss:%d", s->advmss);
2373 if (s->cwnd)
2374 out(" cwnd:%u", s->cwnd);
2375 if (s->ssthresh)
2376 out(" ssthresh:%d", s->ssthresh);
2377
2378 if (s->bytes_acked)
2379 out(" bytes_acked:%llu", s->bytes_acked);
2380 if (s->bytes_received)
2381 out(" bytes_received:%llu", s->bytes_received);
2382 if (s->segs_out)
2383 out(" segs_out:%u", s->segs_out);
2384 if (s->segs_in)
2385 out(" segs_in:%u", s->segs_in);
2386 if (s->data_segs_out)
2387 out(" data_segs_out:%u", s->data_segs_out);
2388 if (s->data_segs_in)
2389 out(" data_segs_in:%u", s->data_segs_in);
2390
2391 if (s->dctcp && s->dctcp->enabled) {
2392 struct dctcpstat *dctcp = s->dctcp;
2393
2394 out(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
2395 dctcp->ce_state, dctcp->alpha, dctcp->ab_ecn,
2396 dctcp->ab_tot);
2397 } else if (s->dctcp) {
2398 out(" dctcp:fallback_mode");
2399 }
2400
2401 if (s->bbr_info) {
2402 __u64 bw;
2403
2404 bw = s->bbr_info->bbr_bw_hi;
2405 bw <<= 32;
2406 bw |= s->bbr_info->bbr_bw_lo;
2407
2408 out(" bbr:(bw:%sbps,mrtt:%g",
2409 sprint_bw(b1, bw * 8.0),
2410 (double)s->bbr_info->bbr_min_rtt / 1000.0);
2411 if (s->bbr_info->bbr_pacing_gain)
2412 out(",pacing_gain:%g",
2413 (double)s->bbr_info->bbr_pacing_gain / 256.0);
2414 if (s->bbr_info->bbr_cwnd_gain)
2415 out(",cwnd_gain:%g",
2416 (double)s->bbr_info->bbr_cwnd_gain / 256.0);
2417 out(")");
2418 }
2419
2420 if (s->send_bps)
2421 out(" send %sbps", sprint_bw(b1, s->send_bps));
2422 if (s->lastsnd)
2423 out(" lastsnd:%u", s->lastsnd);
2424 if (s->lastrcv)
2425 out(" lastrcv:%u", s->lastrcv);
2426 if (s->lastack)
2427 out(" lastack:%u", s->lastack);
2428
2429 if (s->pacing_rate) {
2430 out(" pacing_rate %sbps", sprint_bw(b1, s->pacing_rate));
2431 if (s->pacing_rate_max)
2432 out("/%sbps", sprint_bw(b1, s->pacing_rate_max));
2433 }
2434
2435 if (s->delivery_rate)
2436 out(" delivery_rate %sbps", sprint_bw(b1, s->delivery_rate));
2437 if (s->app_limited)
2438 out(" app_limited");
2439
2440 if (s->busy_time) {
2441 out(" busy:%llums", s->busy_time / 1000);
2442 if (s->rwnd_limited)
2443 out(" rwnd_limited:%llums(%.1f%%)",
2444 s->rwnd_limited / 1000,
2445 100.0 * s->rwnd_limited / s->busy_time);
2446 if (s->sndbuf_limited)
2447 out(" sndbuf_limited:%llums(%.1f%%)",
2448 s->sndbuf_limited / 1000,
2449 100.0 * s->sndbuf_limited / s->busy_time);
2450 }
2451
2452 if (s->unacked)
2453 out(" unacked:%u", s->unacked);
2454 if (s->retrans || s->retrans_total)
2455 out(" retrans:%u/%u", s->retrans, s->retrans_total);
2456 if (s->lost)
2457 out(" lost:%u", s->lost);
2458 if (s->sacked && s->ss.state != SS_LISTEN)
2459 out(" sacked:%u", s->sacked);
2460 if (s->fackets)
2461 out(" fackets:%u", s->fackets);
2462 if (s->reordering != 3)
2463 out(" reordering:%d", s->reordering);
2464 if (s->rcv_rtt)
2465 out(" rcv_rtt:%g", s->rcv_rtt);
2466 if (s->rcv_space)
2467 out(" rcv_space:%d", s->rcv_space);
2468 if (s->rcv_ssthresh)
2469 out(" rcv_ssthresh:%u", s->rcv_ssthresh);
2470 if (s->not_sent)
2471 out(" notsent:%u", s->not_sent);
2472 if (s->min_rtt)
2473 out(" minrtt:%g", s->min_rtt);
2474 }
2475
2476 static void tcp_timer_print(struct tcpstat *s)
2477 {
2478 static const char * const tmr_name[] = {
2479 "off",
2480 "on",
2481 "keepalive",
2482 "timewait",
2483 "persist",
2484 "unknown"
2485 };
2486
2487 if (s->timer) {
2488 if (s->timer > 4)
2489 s->timer = 5;
2490 out(" timer:(%s,%s,%d)",
2491 tmr_name[s->timer],
2492 print_ms_timer(s->timeout),
2493 s->retrans);
2494 }
2495 }
2496
2497 static void sctp_timer_print(struct tcpstat *s)
2498 {
2499 if (s->timer)
2500 out(" timer:(T3_RTX,%s,%d)",
2501 print_ms_timer(s->timeout), s->retrans);
2502 }
2503
2504 static int tcp_show_line(char *line, const struct filter *f, int family)
2505 {
2506 int rto = 0, ato = 0;
2507 struct tcpstat s = {};
2508 char *loc, *rem, *data;
2509 char opt[256];
2510 int n;
2511 int hz = get_user_hz();
2512
2513 if (proc_inet_split_line(line, &loc, &rem, &data))
2514 return -1;
2515
2516 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
2517
2518 if (!(f->states & (1 << state)))
2519 return 0;
2520
2521 proc_parse_inet_addr(loc, rem, family, &s.ss);
2522
2523 if (f->f && run_ssfilter(f->f, &s.ss) == 0)
2524 return 0;
2525
2526 opt[0] = 0;
2527 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2528 &s.ss.state, &s.ss.wq, &s.ss.rq,
2529 &s.timer, &s.timeout, &s.retrans, &s.ss.uid, &s.probes,
2530 &s.ss.ino, &s.ss.refcnt, &s.ss.sk, &rto, &ato, &s.qack, &s.cwnd,
2531 &s.ssthresh, opt);
2532
2533 if (n < 17)
2534 opt[0] = 0;
2535
2536 if (n < 12) {
2537 rto = 0;
2538 s.cwnd = 2;
2539 s.ssthresh = -1;
2540 ato = s.qack = 0;
2541 }
2542
2543 s.retrans = s.timer != 1 ? s.probes : s.retrans;
2544 s.timeout = (s.timeout * 1000 + hz - 1) / hz;
2545 s.ato = (double)ato / hz;
2546 s.qack /= 2;
2547 s.rto = (double)rto;
2548 s.ssthresh = s.ssthresh == -1 ? 0 : s.ssthresh;
2549 s.rto = s.rto != 3 * hz ? s.rto / hz : 0;
2550 s.ss.type = IPPROTO_TCP;
2551
2552 inet_stats_print(&s.ss, false);
2553
2554 if (show_options)
2555 tcp_timer_print(&s);
2556
2557 if (show_details) {
2558 sock_details_print(&s.ss);
2559 if (opt[0])
2560 out(" opt:\"%s\"", opt);
2561 }
2562
2563 if (show_tcpinfo)
2564 tcp_stats_print(&s);
2565
2566 return 0;
2567 }
2568
2569 static int generic_record_read(FILE *fp,
2570 int (*worker)(char*, const struct filter *, int),
2571 const struct filter *f, int fam)
2572 {
2573 char line[256];
2574
2575 /* skip header */
2576 if (fgets(line, sizeof(line), fp) == NULL)
2577 goto outerr;
2578
2579 while (fgets(line, sizeof(line), fp) != NULL) {
2580 int n = strlen(line);
2581
2582 if (n == 0 || line[n-1] != '\n') {
2583 errno = -EINVAL;
2584 return -1;
2585 }
2586 line[n-1] = 0;
2587
2588 if (worker(line, f, fam) < 0)
2589 return 0;
2590 }
2591 outerr:
2592
2593 return ferror(fp) ? -1 : 0;
2594 }
2595
2596 static void print_skmeminfo(struct rtattr *tb[], int attrtype)
2597 {
2598 const __u32 *skmeminfo;
2599
2600 if (!tb[attrtype]) {
2601 if (attrtype == INET_DIAG_SKMEMINFO) {
2602 if (!tb[INET_DIAG_MEMINFO])
2603 return;
2604
2605 const struct inet_diag_meminfo *minfo =
2606 RTA_DATA(tb[INET_DIAG_MEMINFO]);
2607
2608 out(" mem:(r%u,w%u,f%u,t%u)",
2609 minfo->idiag_rmem,
2610 minfo->idiag_wmem,
2611 minfo->idiag_fmem,
2612 minfo->idiag_tmem);
2613 }
2614 return;
2615 }
2616
2617 skmeminfo = RTA_DATA(tb[attrtype]);
2618
2619 out(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2620 skmeminfo[SK_MEMINFO_RMEM_ALLOC],
2621 skmeminfo[SK_MEMINFO_RCVBUF],
2622 skmeminfo[SK_MEMINFO_WMEM_ALLOC],
2623 skmeminfo[SK_MEMINFO_SNDBUF],
2624 skmeminfo[SK_MEMINFO_FWD_ALLOC],
2625 skmeminfo[SK_MEMINFO_WMEM_QUEUED],
2626 skmeminfo[SK_MEMINFO_OPTMEM]);
2627
2628 if (RTA_PAYLOAD(tb[attrtype]) >=
2629 (SK_MEMINFO_BACKLOG + 1) * sizeof(__u32))
2630 out(",bl%u", skmeminfo[SK_MEMINFO_BACKLOG]);
2631
2632 if (RTA_PAYLOAD(tb[attrtype]) >=
2633 (SK_MEMINFO_DROPS + 1) * sizeof(__u32))
2634 out(",d%u", skmeminfo[SK_MEMINFO_DROPS]);
2635
2636 out(")");
2637 }
2638
2639 static void print_md5sig(struct tcp_diag_md5sig *sig)
2640 {
2641 out("%s/%d=",
2642 format_host(sig->tcpm_family,
2643 sig->tcpm_family == AF_INET6 ? 16 : 4,
2644 &sig->tcpm_addr),
2645 sig->tcpm_prefixlen);
2646 print_escape_buf(sig->tcpm_key, sig->tcpm_keylen, " ,");
2647 }
2648
2649 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2650
2651 static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r,
2652 struct rtattr *tb[])
2653 {
2654 double rtt = 0;
2655 struct tcpstat s = {};
2656
2657 s.ss.state = r->idiag_state;
2658
2659 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
2660
2661 if (tb[INET_DIAG_INFO]) {
2662 struct tcp_info *info;
2663 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
2664
2665 /* workaround for older kernels with less fields */
2666 if (len < sizeof(*info)) {
2667 info = alloca(sizeof(*info));
2668 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
2669 memset((char *)info + len, 0, sizeof(*info) - len);
2670 } else
2671 info = RTA_DATA(tb[INET_DIAG_INFO]);
2672
2673 if (show_options) {
2674 s.has_ts_opt = TCPI_HAS_OPT(info, TCPI_OPT_TIMESTAMPS);
2675 s.has_sack_opt = TCPI_HAS_OPT(info, TCPI_OPT_SACK);
2676 s.has_ecn_opt = TCPI_HAS_OPT(info, TCPI_OPT_ECN);
2677 s.has_ecnseen_opt = TCPI_HAS_OPT(info, TCPI_OPT_ECN_SEEN);
2678 s.has_fastopen_opt = TCPI_HAS_OPT(info, TCPI_OPT_SYN_DATA);
2679 }
2680
2681 if (tb[INET_DIAG_CONG])
2682 strncpy(s.cong_alg,
2683 rta_getattr_str(tb[INET_DIAG_CONG]),
2684 sizeof(s.cong_alg) - 1);
2685
2686 if (TCPI_HAS_OPT(info, TCPI_OPT_WSCALE)) {
2687 s.has_wscale_opt = true;
2688 s.snd_wscale = info->tcpi_snd_wscale;
2689 s.rcv_wscale = info->tcpi_rcv_wscale;
2690 }
2691
2692 if (info->tcpi_rto && info->tcpi_rto != 3000000)
2693 s.rto = (double)info->tcpi_rto / 1000;
2694
2695 s.backoff = info->tcpi_backoff;
2696 s.rtt = (double)info->tcpi_rtt / 1000;
2697 s.rttvar = (double)info->tcpi_rttvar / 1000;
2698 s.ato = (double)info->tcpi_ato / 1000;
2699 s.mss = info->tcpi_snd_mss;
2700 s.rcv_mss = info->tcpi_rcv_mss;
2701 s.advmss = info->tcpi_advmss;
2702 s.rcv_space = info->tcpi_rcv_space;
2703 s.rcv_rtt = (double)info->tcpi_rcv_rtt / 1000;
2704 s.lastsnd = info->tcpi_last_data_sent;
2705 s.lastrcv = info->tcpi_last_data_recv;
2706 s.lastack = info->tcpi_last_ack_recv;
2707 s.unacked = info->tcpi_unacked;
2708 s.retrans = info->tcpi_retrans;
2709 s.retrans_total = info->tcpi_total_retrans;
2710 s.lost = info->tcpi_lost;
2711 s.sacked = info->tcpi_sacked;
2712 s.fackets = info->tcpi_fackets;
2713 s.reordering = info->tcpi_reordering;
2714 s.rcv_ssthresh = info->tcpi_rcv_ssthresh;
2715 s.cwnd = info->tcpi_snd_cwnd;
2716 s.pmtu = info->tcpi_pmtu;
2717
2718 if (info->tcpi_snd_ssthresh < 0xFFFF)
2719 s.ssthresh = info->tcpi_snd_ssthresh;
2720
2721 rtt = (double) info->tcpi_rtt;
2722 if (tb[INET_DIAG_VEGASINFO]) {
2723 const struct tcpvegas_info *vinfo
2724 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
2725
2726 if (vinfo->tcpv_enabled &&
2727 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
2728 rtt = vinfo->tcpv_rtt;
2729 }
2730
2731 if (tb[INET_DIAG_DCTCPINFO]) {
2732 struct dctcpstat *dctcp = malloc(sizeof(struct
2733 dctcpstat));
2734
2735 const struct tcp_dctcp_info *dinfo
2736 = RTA_DATA(tb[INET_DIAG_DCTCPINFO]);
2737
2738 dctcp->enabled = !!dinfo->dctcp_enabled;
2739 dctcp->ce_state = dinfo->dctcp_ce_state;
2740 dctcp->alpha = dinfo->dctcp_alpha;
2741 dctcp->ab_ecn = dinfo->dctcp_ab_ecn;
2742 dctcp->ab_tot = dinfo->dctcp_ab_tot;
2743 s.dctcp = dctcp;
2744 }
2745
2746 if (tb[INET_DIAG_BBRINFO]) {
2747 const void *bbr_info = RTA_DATA(tb[INET_DIAG_BBRINFO]);
2748 int len = min(RTA_PAYLOAD(tb[INET_DIAG_BBRINFO]),
2749 sizeof(*s.bbr_info));
2750
2751 s.bbr_info = calloc(1, sizeof(*s.bbr_info));
2752 if (s.bbr_info && bbr_info)
2753 memcpy(s.bbr_info, bbr_info, len);
2754 }
2755
2756 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
2757 s.send_bps = (double) info->tcpi_snd_cwnd *
2758 (double)info->tcpi_snd_mss * 8000000. / rtt;
2759 }
2760
2761 if (info->tcpi_pacing_rate &&
2762 info->tcpi_pacing_rate != ~0ULL) {
2763 s.pacing_rate = info->tcpi_pacing_rate * 8.;
2764
2765 if (info->tcpi_max_pacing_rate &&
2766 info->tcpi_max_pacing_rate != ~0ULL)
2767 s.pacing_rate_max = info->tcpi_max_pacing_rate * 8.;
2768 }
2769 s.bytes_acked = info->tcpi_bytes_acked;
2770 s.bytes_received = info->tcpi_bytes_received;
2771 s.segs_out = info->tcpi_segs_out;
2772 s.segs_in = info->tcpi_segs_in;
2773 s.data_segs_out = info->tcpi_data_segs_out;
2774 s.data_segs_in = info->tcpi_data_segs_in;
2775 s.not_sent = info->tcpi_notsent_bytes;
2776 if (info->tcpi_min_rtt && info->tcpi_min_rtt != ~0U)
2777 s.min_rtt = (double) info->tcpi_min_rtt / 1000;
2778 s.delivery_rate = info->tcpi_delivery_rate * 8.;
2779 s.app_limited = info->tcpi_delivery_rate_app_limited;
2780 s.busy_time = info->tcpi_busy_time;
2781 s.rwnd_limited = info->tcpi_rwnd_limited;
2782 s.sndbuf_limited = info->tcpi_sndbuf_limited;
2783 tcp_stats_print(&s);
2784 free(s.dctcp);
2785 free(s.bbr_info);
2786 }
2787 if (tb[INET_DIAG_MD5SIG]) {
2788 struct tcp_diag_md5sig *sig = RTA_DATA(tb[INET_DIAG_MD5SIG]);
2789 int len = RTA_PAYLOAD(tb[INET_DIAG_MD5SIG]);
2790
2791 out(" md5keys:");
2792 print_md5sig(sig++);
2793 for (len -= sizeof(*sig); len > 0; len -= sizeof(*sig)) {
2794 out(",");
2795 print_md5sig(sig++);
2796 }
2797 }
2798 }
2799
2800 static const char *format_host_sa(struct sockaddr_storage *sa)
2801 {
2802 union {
2803 struct sockaddr_in sin;
2804 struct sockaddr_in6 sin6;
2805 } *saddr = (void *)sa;
2806
2807 switch (sa->ss_family) {
2808 case AF_INET:
2809 return format_host(AF_INET, 4, &saddr->sin.sin_addr);
2810 case AF_INET6:
2811 return format_host(AF_INET6, 16, &saddr->sin6.sin6_addr);
2812 default:
2813 return "";
2814 }
2815 }
2816
2817 static void sctp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r,
2818 struct rtattr *tb[])
2819 {
2820 struct sockaddr_storage *sa;
2821 int len;
2822
2823 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
2824
2825 if (tb[INET_DIAG_LOCALS]) {
2826 len = RTA_PAYLOAD(tb[INET_DIAG_LOCALS]);
2827 sa = RTA_DATA(tb[INET_DIAG_LOCALS]);
2828
2829 out("locals:%s", format_host_sa(sa));
2830 for (sa++, len -= sizeof(*sa); len > 0; sa++, len -= sizeof(*sa))
2831 out(",%s", format_host_sa(sa));
2832
2833 }
2834 if (tb[INET_DIAG_PEERS]) {
2835 len = RTA_PAYLOAD(tb[INET_DIAG_PEERS]);
2836 sa = RTA_DATA(tb[INET_DIAG_PEERS]);
2837
2838 out(" peers:%s", format_host_sa(sa));
2839 for (sa++, len -= sizeof(*sa); len > 0; sa++, len -= sizeof(*sa))
2840 out(",%s", format_host_sa(sa));
2841 }
2842 if (tb[INET_DIAG_INFO]) {
2843 struct sctp_info *info;
2844 len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
2845
2846 /* workaround for older kernels with less fields */
2847 if (len < sizeof(*info)) {
2848 info = alloca(sizeof(*info));
2849 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
2850 memset((char *)info + len, 0, sizeof(*info) - len);
2851 } else
2852 info = RTA_DATA(tb[INET_DIAG_INFO]);
2853
2854 sctp_stats_print(info);
2855 }
2856 }
2857
2858 static void parse_diag_msg(struct nlmsghdr *nlh, struct sockstat *s)
2859 {
2860 struct rtattr *tb[INET_DIAG_MAX+1];
2861 struct inet_diag_msg *r = NLMSG_DATA(nlh);
2862
2863 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr *)(r+1),
2864 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2865
2866 s->state = r->idiag_state;
2867 s->local.family = s->remote.family = r->idiag_family;
2868 s->lport = ntohs(r->id.idiag_sport);
2869 s->rport = ntohs(r->id.idiag_dport);
2870 s->wq = r->idiag_wqueue;
2871 s->rq = r->idiag_rqueue;
2872 s->ino = r->idiag_inode;
2873 s->uid = r->idiag_uid;
2874 s->iface = r->id.idiag_if;
2875 s->sk = cookie_sk_get(&r->id.idiag_cookie[0]);
2876
2877 s->mark = 0;
2878 if (tb[INET_DIAG_MARK])
2879 s->mark = rta_getattr_u32(tb[INET_DIAG_MARK]);
2880 if (tb[INET_DIAG_PROTOCOL])
2881 s->raw_prot = rta_getattr_u8(tb[INET_DIAG_PROTOCOL]);
2882 else
2883 s->raw_prot = 0;
2884
2885 if (s->local.family == AF_INET)
2886 s->local.bytelen = s->remote.bytelen = 4;
2887 else
2888 s->local.bytelen = s->remote.bytelen = 16;
2889
2890 memcpy(s->local.data, r->id.idiag_src, s->local.bytelen);
2891 memcpy(s->remote.data, r->id.idiag_dst, s->local.bytelen);
2892 }
2893
2894 static int inet_show_sock(struct nlmsghdr *nlh,
2895 struct sockstat *s)
2896 {
2897 struct rtattr *tb[INET_DIAG_MAX+1];
2898 struct inet_diag_msg *r = NLMSG_DATA(nlh);
2899 unsigned char v6only = 0;
2900
2901 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr *)(r+1),
2902 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2903
2904 if (tb[INET_DIAG_PROTOCOL])
2905 s->type = rta_getattr_u8(tb[INET_DIAG_PROTOCOL]);
2906
2907 if (s->local.family == AF_INET6 && tb[INET_DIAG_SKV6ONLY])
2908 v6only = rta_getattr_u8(tb[INET_DIAG_SKV6ONLY]);
2909
2910 inet_stats_print(s, v6only);
2911
2912 if (show_options) {
2913 struct tcpstat t = {};
2914
2915 t.timer = r->idiag_timer;
2916 t.timeout = r->idiag_expires;
2917 t.retrans = r->idiag_retrans;
2918 if (s->type == IPPROTO_SCTP)
2919 sctp_timer_print(&t);
2920 else
2921 tcp_timer_print(&t);
2922 }
2923
2924 if (show_details) {
2925 sock_details_print(s);
2926 if (s->local.family == AF_INET6 && tb[INET_DIAG_SKV6ONLY])
2927 out(" v6only:%u", v6only);
2928
2929 if (tb[INET_DIAG_SHUTDOWN]) {
2930 unsigned char mask;
2931
2932 mask = rta_getattr_u8(tb[INET_DIAG_SHUTDOWN]);
2933 out(" %c-%c",
2934 mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2935 }
2936 }
2937
2938 if (show_mem || (show_tcpinfo && s->type != IPPROTO_UDP)) {
2939 out("\n\t");
2940 if (s->type == IPPROTO_SCTP)
2941 sctp_show_info(nlh, r, tb);
2942 else
2943 tcp_show_info(nlh, r, tb);
2944 }
2945 sctp_ino = s->ino;
2946
2947 return 0;
2948 }
2949
2950 static int tcpdiag_send(int fd, int protocol, struct filter *f)
2951 {
2952 struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
2953 struct {
2954 struct nlmsghdr nlh;
2955 struct inet_diag_req r;
2956 } req = {
2957 .nlh.nlmsg_len = sizeof(req),
2958 .nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST,
2959 .nlh.nlmsg_seq = MAGIC_SEQ,
2960 .r.idiag_family = AF_INET,
2961 .r.idiag_states = f->states,
2962 };
2963 char *bc = NULL;
2964 int bclen;
2965 struct msghdr msg;
2966 struct rtattr rta;
2967 struct iovec iov[3];
2968 int iovlen = 1;
2969
2970 if (protocol == IPPROTO_UDP)
2971 return -1;
2972
2973 if (protocol == IPPROTO_TCP)
2974 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
2975 else
2976 req.nlh.nlmsg_type = DCCPDIAG_GETSOCK;
2977 if (show_mem) {
2978 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
2979 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
2980 }
2981
2982 if (show_tcpinfo) {
2983 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
2984 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
2985 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
2986 }
2987
2988 iov[0] = (struct iovec){
2989 .iov_base = &req,
2990 .iov_len = sizeof(req)
2991 };
2992 if (f->f) {
2993 bclen = ssfilter_bytecompile(f->f, &bc);
2994 if (bclen) {
2995 rta.rta_type = INET_DIAG_REQ_BYTECODE;
2996 rta.rta_len = RTA_LENGTH(bclen);
2997 iov[1] = (struct iovec){ &rta, sizeof(rta) };
2998 iov[2] = (struct iovec){ bc, bclen };
2999 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
3000 iovlen = 3;
3001 }
3002 }
3003
3004 msg = (struct msghdr) {
3005 .msg_name = (void *)&nladdr,
3006 .msg_namelen = sizeof(nladdr),
3007 .msg_iov = iov,
3008 .msg_iovlen = iovlen,
3009 };
3010
3011 if (sendmsg(fd, &msg, 0) < 0) {
3012 close(fd);
3013 return -1;
3014 }
3015
3016 return 0;
3017 }
3018
3019 static int sockdiag_send(int family, int fd, int protocol, struct filter *f)
3020 {
3021 struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
3022 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
3023 char *bc = NULL;
3024 int bclen;
3025 struct msghdr msg;
3026 struct rtattr rta;
3027 struct iovec iov[3];
3028 int iovlen = 1;
3029
3030 if (family == PF_UNSPEC)
3031 return tcpdiag_send(fd, protocol, f);
3032
3033 memset(&req.r, 0, sizeof(req.r));
3034 req.r.sdiag_family = family;
3035 req.r.sdiag_protocol = protocol;
3036 req.r.idiag_states = f->states;
3037 if (show_mem) {
3038 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
3039 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
3040 }
3041
3042 if (show_tcpinfo) {
3043 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
3044 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
3045 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
3046 }
3047
3048 iov[0] = (struct iovec){
3049 .iov_base = &req,
3050 .iov_len = sizeof(req)
3051 };
3052 if (f->f) {
3053 bclen = ssfilter_bytecompile(f->f, &bc);
3054 if (bclen) {
3055 rta.rta_type = INET_DIAG_REQ_BYTECODE;
3056 rta.rta_len = RTA_LENGTH(bclen);
3057 iov[1] = (struct iovec){ &rta, sizeof(rta) };
3058 iov[2] = (struct iovec){ bc, bclen };
3059 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
3060 iovlen = 3;
3061 }
3062 }
3063
3064 msg = (struct msghdr) {
3065 .msg_name = (void *)&nladdr,
3066 .msg_namelen = sizeof(nladdr),
3067 .msg_iov = iov,
3068 .msg_iovlen = iovlen,
3069 };
3070
3071 if (sendmsg(fd, &msg, 0) < 0) {
3072 close(fd);
3073 return -1;
3074 }
3075
3076 return 0;
3077 }
3078
3079 struct inet_diag_arg {
3080 struct filter *f;
3081 int protocol;
3082 struct rtnl_handle *rth;
3083 };
3084
3085 static int kill_inet_sock(struct nlmsghdr *h, void *arg, struct sockstat *s)
3086 {
3087 struct inet_diag_msg *d = NLMSG_DATA(h);
3088 struct inet_diag_arg *diag_arg = arg;
3089 struct rtnl_handle *rth = diag_arg->rth;
3090
3091 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
3092
3093 req.nlh.nlmsg_type = SOCK_DESTROY;
3094 req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
3095 req.nlh.nlmsg_seq = ++rth->seq;
3096 req.r.sdiag_family = d->idiag_family;
3097 req.r.sdiag_protocol = diag_arg->protocol;
3098 req.r.id = d->id;
3099
3100 if (diag_arg->protocol == IPPROTO_RAW) {
3101 struct inet_diag_req_raw *raw = (void *)&req.r;
3102
3103 BUILD_BUG_ON(sizeof(req.r) != sizeof(*raw));
3104 raw->sdiag_raw_protocol = s->raw_prot;
3105 }
3106
3107 return rtnl_talk(rth, &req.nlh, NULL);
3108 }
3109
3110 static int show_one_inet_sock(const struct sockaddr_nl *addr,
3111 struct nlmsghdr *h, void *arg)
3112 {
3113 int err;
3114 struct inet_diag_arg *diag_arg = arg;
3115 struct inet_diag_msg *r = NLMSG_DATA(h);
3116 struct sockstat s = {};
3117
3118 if (!(diag_arg->f->families & FAMILY_MASK(r->idiag_family)))
3119 return 0;
3120
3121 parse_diag_msg(h, &s);
3122 s.type = diag_arg->protocol;
3123
3124 if (diag_arg->f->f && run_ssfilter(diag_arg->f->f, &s) == 0)
3125 return 0;
3126
3127 if (diag_arg->f->kill && kill_inet_sock(h, arg, &s) != 0) {
3128 if (errno == EOPNOTSUPP || errno == ENOENT) {
3129 /* Socket can't be closed, or is already closed. */
3130 return 0;
3131 } else {
3132 perror("SOCK_DESTROY answers");
3133 return -1;
3134 }
3135 }
3136
3137 err = inet_show_sock(h, &s);
3138 if (err < 0)
3139 return err;
3140
3141 return 0;
3142 }
3143
3144 static int inet_show_netlink(struct filter *f, FILE *dump_fp, int protocol)
3145 {
3146 int err = 0;
3147 struct rtnl_handle rth, rth2;
3148 int family = PF_INET;
3149 struct inet_diag_arg arg = { .f = f, .protocol = protocol };
3150
3151 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
3152 return -1;
3153
3154 if (f->kill) {
3155 if (rtnl_open_byproto(&rth2, 0, NETLINK_SOCK_DIAG)) {
3156 rtnl_close(&rth);
3157 return -1;
3158 }
3159 arg.rth = &rth2;
3160 }
3161
3162 rth.dump = MAGIC_SEQ;
3163 rth.dump_fp = dump_fp;
3164 if (preferred_family == PF_INET6)
3165 family = PF_INET6;
3166
3167 again:
3168 if ((err = sockdiag_send(family, rth.fd, protocol, f)))
3169 goto Exit;
3170
3171 if ((err = rtnl_dump_filter(&rth, show_one_inet_sock, &arg))) {
3172 if (family != PF_UNSPEC) {
3173 family = PF_UNSPEC;
3174 goto again;
3175 }
3176 goto Exit;
3177 }
3178 if (family == PF_INET && preferred_family != PF_INET) {
3179 family = PF_INET6;
3180 goto again;
3181 }
3182
3183 Exit:
3184 rtnl_close(&rth);
3185 if (arg.rth)
3186 rtnl_close(arg.rth);
3187 return err;
3188 }
3189
3190 static int tcp_show_netlink_file(struct filter *f)
3191 {
3192 FILE *fp;
3193 char buf[16384];
3194 int err = -1;
3195
3196 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
3197 perror("fopen($TCPDIAG_FILE)");
3198 return err;
3199 }
3200
3201 while (1) {
3202 int status, err2;
3203 struct nlmsghdr *h = (struct nlmsghdr *)buf;
3204 struct sockstat s = {};
3205
3206 status = fread(buf, 1, sizeof(*h), fp);
3207 if (status < 0) {
3208 perror("Reading header from $TCPDIAG_FILE");
3209 break;
3210 }
3211 if (status != sizeof(*h)) {
3212 perror("Unexpected EOF reading $TCPDIAG_FILE");
3213 break;
3214 }
3215
3216 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
3217
3218 if (status < 0) {
3219 perror("Reading $TCPDIAG_FILE");
3220 break;
3221 }
3222 if (status + sizeof(*h) < h->nlmsg_len) {
3223 perror("Unexpected EOF reading $TCPDIAG_FILE");
3224 break;
3225 }
3226
3227 /* The only legal exit point */
3228 if (h->nlmsg_type == NLMSG_DONE) {
3229 err = 0;
3230 break;
3231 }
3232
3233 if (h->nlmsg_type == NLMSG_ERROR) {
3234 struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(h);
3235
3236 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
3237 fprintf(stderr, "ERROR truncated\n");
3238 } else {
3239 errno = -err->error;
3240 perror("TCPDIAG answered");
3241 }
3242 break;
3243 }
3244
3245 parse_diag_msg(h, &s);
3246 s.type = IPPROTO_TCP;
3247
3248 if (f && f->f && run_ssfilter(f->f, &s) == 0)
3249 continue;
3250
3251 err2 = inet_show_sock(h, &s);
3252 if (err2 < 0) {
3253 err = err2;
3254 break;
3255 }
3256 }
3257
3258 fclose(fp);
3259 return err;
3260 }
3261
3262 static int tcp_show(struct filter *f)
3263 {
3264 FILE *fp = NULL;
3265 char *buf = NULL;
3266 int bufsize = 64*1024;
3267
3268 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
3269 return 0;
3270
3271 dg_proto = TCP_PROTO;
3272
3273 if (getenv("TCPDIAG_FILE"))
3274 return tcp_show_netlink_file(f);
3275
3276 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3277 && inet_show_netlink(f, NULL, IPPROTO_TCP) == 0)
3278 return 0;
3279
3280 /* Sigh... We have to parse /proc/net/tcp... */
3281
3282
3283 /* Estimate amount of sockets and try to allocate
3284 * huge buffer to read all the table at one read.
3285 * Limit it by 16MB though. The assumption is: as soon as
3286 * kernel was able to hold information about N connections,
3287 * it is able to give us some memory for snapshot.
3288 */
3289 if (1) {
3290 get_slabstat(&slabstat);
3291
3292 int guess = slabstat.socks+slabstat.tcp_syns;
3293
3294 if (f->states&(1<<SS_TIME_WAIT))
3295 guess += slabstat.tcp_tws;
3296 if (guess > (16*1024*1024)/128)
3297 guess = (16*1024*1024)/128;
3298 guess *= 128;
3299 if (guess > bufsize)
3300 bufsize = guess;
3301 }
3302 while (bufsize >= 64*1024) {
3303 if ((buf = malloc(bufsize)) != NULL)
3304 break;
3305 bufsize /= 2;
3306 }
3307 if (buf == NULL) {
3308 errno = ENOMEM;
3309 return -1;
3310 }
3311
3312 if (f->families & FAMILY_MASK(AF_INET)) {
3313 if ((fp = net_tcp_open()) == NULL)
3314 goto outerr;
3315
3316 setbuffer(fp, buf, bufsize);
3317 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
3318 goto outerr;
3319 fclose(fp);
3320 }
3321
3322 if ((f->families & FAMILY_MASK(AF_INET6)) &&
3323 (fp = net_tcp6_open()) != NULL) {
3324 setbuffer(fp, buf, bufsize);
3325 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
3326 goto outerr;
3327 fclose(fp);
3328 }
3329
3330 free(buf);
3331 return 0;
3332
3333 outerr:
3334 do {
3335 int saved_errno = errno;
3336
3337 free(buf);
3338 if (fp)
3339 fclose(fp);
3340 errno = saved_errno;
3341 return -1;
3342 } while (0);
3343 }
3344
3345 static int dccp_show(struct filter *f)
3346 {
3347 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
3348 return 0;
3349
3350 if (!getenv("PROC_NET_DCCP") && !getenv("PROC_ROOT")
3351 && inet_show_netlink(f, NULL, IPPROTO_DCCP) == 0)
3352 return 0;
3353
3354 return 0;
3355 }
3356
3357 static int sctp_show(struct filter *f)
3358 {
3359 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
3360 return 0;
3361
3362 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
3363 && inet_show_netlink(f, NULL, IPPROTO_SCTP) == 0)
3364 return 0;
3365
3366 return 0;
3367 }
3368
3369 static int dgram_show_line(char *line, const struct filter *f, int family)
3370 {
3371 struct sockstat s = {};
3372 char *loc, *rem, *data;
3373 char opt[256];
3374 int n;
3375
3376 if (proc_inet_split_line(line, &loc, &rem, &data))
3377 return -1;
3378
3379 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
3380
3381 if (!(f->states & (1 << state)))
3382 return 0;
3383
3384 proc_parse_inet_addr(loc, rem, family, &s);
3385
3386 if (f->f && run_ssfilter(f->f, &s) == 0)
3387 return 0;
3388
3389 opt[0] = 0;
3390 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
3391 &s.state, &s.wq, &s.rq,
3392 &s.uid, &s.ino,
3393 &s.refcnt, &s.sk, opt);
3394
3395 if (n < 9)
3396 opt[0] = 0;
3397
3398 s.type = dg_proto == UDP_PROTO ? IPPROTO_UDP : 0;
3399 inet_stats_print(&s, false);
3400
3401 if (show_details && opt[0])
3402 out(" opt:\"%s\"", opt);
3403
3404 return 0;
3405 }
3406
3407 static int udp_show(struct filter *f)
3408 {
3409 FILE *fp = NULL;
3410
3411 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
3412 return 0;
3413
3414 dg_proto = UDP_PROTO;
3415
3416 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
3417 && inet_show_netlink(f, NULL, IPPROTO_UDP) == 0)
3418 return 0;
3419
3420 if (f->families&FAMILY_MASK(AF_INET)) {
3421 if ((fp = net_udp_open()) == NULL)
3422 goto outerr;
3423 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
3424 goto outerr;
3425 fclose(fp);
3426 }
3427
3428 if ((f->families&FAMILY_MASK(AF_INET6)) &&
3429 (fp = net_udp6_open()) != NULL) {
3430 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
3431 goto outerr;
3432 fclose(fp);
3433 }
3434 return 0;
3435
3436 outerr:
3437 do {
3438 int saved_errno = errno;
3439
3440 if (fp)
3441 fclose(fp);
3442 errno = saved_errno;
3443 return -1;
3444 } while (0);
3445 }
3446
3447 static int raw_show(struct filter *f)
3448 {
3449 FILE *fp = NULL;
3450
3451 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
3452 return 0;
3453
3454 dg_proto = RAW_PROTO;
3455
3456 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
3457 inet_show_netlink(f, NULL, IPPROTO_RAW) == 0)
3458 return 0;
3459
3460 if (f->families&FAMILY_MASK(AF_INET)) {
3461 if ((fp = net_raw_open()) == NULL)
3462 goto outerr;
3463 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
3464 goto outerr;
3465 fclose(fp);
3466 }
3467
3468 if ((f->families&FAMILY_MASK(AF_INET6)) &&
3469 (fp = net_raw6_open()) != NULL) {
3470 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
3471 goto outerr;
3472 fclose(fp);
3473 }
3474 return 0;
3475
3476 outerr:
3477 do {
3478 int saved_errno = errno;
3479
3480 if (fp)
3481 fclose(fp);
3482 errno = saved_errno;
3483 return -1;
3484 } while (0);
3485 }
3486
3487 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
3488
3489 static void unix_list_drop_first(struct sockstat **list)
3490 {
3491 struct sockstat *s = *list;
3492
3493 (*list) = (*list)->next;
3494 free(s->name);
3495 free(s);
3496 }
3497
3498 static bool unix_type_skip(struct sockstat *s, struct filter *f)
3499 {
3500 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
3501 return true;
3502 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
3503 return true;
3504 if (s->type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
3505 return true;
3506 return false;
3507 }
3508
3509 static void unix_stats_print(struct sockstat *s, struct filter *f)
3510 {
3511 char port_name[30] = {};
3512
3513 sock_state_print(s);
3514
3515 sock_addr_print(s->name ?: "*", " ",
3516 int_to_str(s->lport, port_name), NULL);
3517 sock_addr_print(s->peer_name ?: "*", " ",
3518 int_to_str(s->rport, port_name), NULL);
3519
3520 proc_ctx_print(s);
3521 }
3522
3523 static int unix_show_sock(const struct sockaddr_nl *addr, struct nlmsghdr *nlh,
3524 void *arg)
3525 {
3526 struct filter *f = (struct filter *)arg;
3527 struct unix_diag_msg *r = NLMSG_DATA(nlh);
3528 struct rtattr *tb[UNIX_DIAG_MAX+1];
3529 char name[128];
3530 struct sockstat stat = { .name = "*", .peer_name = "*" };
3531
3532 parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr *)(r+1),
3533 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
3534
3535 stat.type = r->udiag_type;
3536 stat.state = r->udiag_state;
3537 stat.ino = stat.lport = r->udiag_ino;
3538 stat.local.family = stat.remote.family = AF_UNIX;
3539
3540 if (unix_type_skip(&stat, f))
3541 return 0;
3542
3543 if (tb[UNIX_DIAG_RQLEN]) {
3544 struct unix_diag_rqlen *rql = RTA_DATA(tb[UNIX_DIAG_RQLEN]);
3545
3546 stat.rq = rql->udiag_rqueue;
3547 stat.wq = rql->udiag_wqueue;
3548 }
3549 if (tb[UNIX_DIAG_NAME]) {
3550 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
3551
3552 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
3553 name[len] = '\0';
3554 if (name[0] == '\0') {
3555 int i;
3556 for (i = 0; i < len; i++)
3557 if (name[i] == '\0')
3558 name[i] = '@';
3559 }
3560 stat.name = &name[0];
3561 memcpy(stat.local.data, &stat.name, sizeof(stat.name));
3562 }
3563 if (tb[UNIX_DIAG_PEER])
3564 stat.rport = rta_getattr_u32(tb[UNIX_DIAG_PEER]);
3565
3566 if (f->f && run_ssfilter(f->f, &stat) == 0)
3567 return 0;
3568
3569 unix_stats_print(&stat, f);
3570
3571 if (show_mem)
3572 print_skmeminfo(tb, UNIX_DIAG_MEMINFO);
3573 if (show_details) {
3574 if (tb[UNIX_DIAG_SHUTDOWN]) {
3575 unsigned char mask;
3576
3577 mask = rta_getattr_u8(tb[UNIX_DIAG_SHUTDOWN]);
3578 out(" %c-%c",
3579 mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
3580 }
3581 }
3582
3583 return 0;
3584 }
3585
3586 static int handle_netlink_request(struct filter *f, struct nlmsghdr *req,
3587 size_t size, rtnl_filter_t show_one_sock)
3588 {
3589 int ret = -1;
3590 struct rtnl_handle rth;
3591
3592 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
3593 return -1;
3594
3595 rth.dump = MAGIC_SEQ;
3596
3597 if (rtnl_send(&rth, req, size) < 0)
3598 goto Exit;
3599
3600 if (rtnl_dump_filter(&rth, show_one_sock, f))
3601 goto Exit;
3602
3603 ret = 0;
3604 Exit:
3605 rtnl_close(&rth);
3606 return ret;
3607 }
3608
3609 static int unix_show_netlink(struct filter *f)
3610 {
3611 DIAG_REQUEST(req, struct unix_diag_req r);
3612
3613 req.r.sdiag_family = AF_UNIX;
3614 req.r.udiag_states = f->states;
3615 req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
3616 if (show_mem)
3617 req.r.udiag_show |= UDIAG_SHOW_MEMINFO;
3618
3619 return handle_netlink_request(f, &req.nlh, sizeof(req), unix_show_sock);
3620 }
3621
3622 static int unix_show(struct filter *f)
3623 {
3624 FILE *fp;
3625 char buf[256];
3626 char name[128];
3627 int newformat = 0;
3628 int cnt;
3629 struct sockstat *list = NULL;
3630 const int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
3631 SS_ESTABLISHED, SS_CLOSING };
3632
3633 if (!filter_af_get(f, AF_UNIX))
3634 return 0;
3635
3636 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3637 && unix_show_netlink(f) == 0)
3638 return 0;
3639
3640 if ((fp = net_unix_open()) == NULL)
3641 return -1;
3642 if (!fgets(buf, sizeof(buf), fp)) {
3643 fclose(fp);
3644 return -1;
3645 }
3646
3647 if (memcmp(buf, "Peer", 4) == 0)
3648 newformat = 1;
3649 cnt = 0;
3650
3651 while (fgets(buf, sizeof(buf), fp)) {
3652 struct sockstat *u, **insp;
3653 int flags;
3654
3655 if (!(u = calloc(1, sizeof(*u))))
3656 break;
3657
3658 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
3659 &u->rport, &u->rq, &u->wq, &flags, &u->type,
3660 &u->state, &u->ino, name) < 8)
3661 name[0] = 0;
3662
3663 u->lport = u->ino;
3664 u->local.family = u->remote.family = AF_UNIX;
3665
3666 if (flags & (1 << 16)) {
3667 u->state = SS_LISTEN;
3668 } else if (u->state > 0 &&
3669 u->state <= ARRAY_SIZE(unix_state_map)) {
3670 u->state = unix_state_map[u->state-1];
3671 if (u->type == SOCK_DGRAM && u->state == SS_CLOSE && u->rport)
3672 u->state = SS_ESTABLISHED;
3673 }
3674 if (unix_type_skip(u, f) ||
3675 !(f->states & (1 << u->state))) {
3676 free(u);
3677 continue;
3678 }
3679
3680 if (!newformat) {
3681 u->rport = 0;
3682 u->rq = 0;
3683 u->wq = 0;
3684 }
3685
3686 if (name[0]) {
3687 u->name = strdup(name);
3688 if (!u->name) {
3689 free(u);
3690 break;
3691 }
3692 }
3693
3694 if (u->rport) {
3695 struct sockstat *p;
3696
3697 for (p = list; p; p = p->next) {
3698 if (u->rport == p->lport)
3699 break;
3700 }
3701 if (!p)
3702 u->peer_name = "?";
3703 else
3704 u->peer_name = p->name ? : "*";
3705 }
3706
3707 if (f->f) {
3708 struct sockstat st = {
3709 .local.family = AF_UNIX,
3710 .remote.family = AF_UNIX,
3711 };
3712
3713 memcpy(st.local.data, &u->name, sizeof(u->name));
3714 /* when parsing the old format rport is set to 0 and
3715 * therefore peer_name remains NULL
3716 */
3717 if (u->peer_name && strcmp(u->peer_name, "*"))
3718 memcpy(st.remote.data, &u->peer_name,
3719 sizeof(u->peer_name));
3720 if (run_ssfilter(f->f, &st) == 0) {
3721 free(u->name);
3722 free(u);
3723 continue;
3724 }
3725 }
3726
3727 insp = &list;
3728 while (*insp) {
3729 if (u->type < (*insp)->type ||
3730 (u->type == (*insp)->type &&
3731 u->ino < (*insp)->ino))
3732 break;
3733 insp = &(*insp)->next;
3734 }
3735 u->next = *insp;
3736 *insp = u;
3737
3738 if (++cnt > MAX_UNIX_REMEMBER) {
3739 while (list) {
3740 unix_stats_print(list, f);
3741 unix_list_drop_first(&list);
3742 }
3743 cnt = 0;
3744 }
3745 }
3746 fclose(fp);
3747 while (list) {
3748 unix_stats_print(list, f);
3749 unix_list_drop_first(&list);
3750 }
3751
3752 return 0;
3753 }
3754
3755 static int packet_stats_print(struct sockstat *s, const struct filter *f)
3756 {
3757 const char *addr, *port;
3758 char ll_name[16];
3759
3760 s->local.family = s->remote.family = AF_PACKET;
3761
3762 if (f->f) {
3763 s->local.data[0] = s->prot;
3764 if (run_ssfilter(f->f, s) == 0)
3765 return 1;
3766 }
3767
3768 sock_state_print(s);
3769
3770 if (s->prot == 3)
3771 addr = "*";
3772 else
3773 addr = ll_proto_n2a(htons(s->prot), ll_name, sizeof(ll_name));
3774
3775 if (s->iface == 0)
3776 port = "*";
3777 else
3778 port = xll_index_to_name(s->iface);
3779
3780 sock_addr_print(addr, ":", port, NULL);
3781 sock_addr_print("", "*", "", NULL);
3782
3783 proc_ctx_print(s);
3784
3785 if (show_details)
3786 sock_details_print(s);
3787
3788 return 0;
3789 }
3790
3791 static void packet_show_ring(struct packet_diag_ring *ring)
3792 {
3793 out("blk_size:%d", ring->pdr_block_size);
3794 out(",blk_nr:%d", ring->pdr_block_nr);
3795 out(",frm_size:%d", ring->pdr_frame_size);
3796 out(",frm_nr:%d", ring->pdr_frame_nr);
3797 out(",tmo:%d", ring->pdr_retire_tmo);
3798 out(",features:0x%x", ring->pdr_features);
3799 }
3800
3801 static int packet_show_sock(const struct sockaddr_nl *addr,
3802 struct nlmsghdr *nlh, void *arg)
3803 {
3804 const struct filter *f = arg;
3805 struct packet_diag_msg *r = NLMSG_DATA(nlh);
3806 struct packet_diag_info *pinfo = NULL;
3807 struct packet_diag_ring *ring_rx = NULL, *ring_tx = NULL;
3808 struct rtattr *tb[PACKET_DIAG_MAX+1];
3809 struct sockstat stat = {};
3810 uint32_t fanout = 0;
3811 bool has_fanout = false;
3812
3813 parse_rtattr(tb, PACKET_DIAG_MAX, (struct rtattr *)(r+1),
3814 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
3815
3816 /* use /proc/net/packet if all info are not available */
3817 if (!tb[PACKET_DIAG_MEMINFO])
3818 return -1;
3819
3820 stat.type = r->pdiag_type;
3821 stat.prot = r->pdiag_num;
3822 stat.ino = r->pdiag_ino;
3823 stat.state = SS_CLOSE;
3824 stat.sk = cookie_sk_get(&r->pdiag_cookie[0]);
3825
3826 if (tb[PACKET_DIAG_MEMINFO]) {
3827 __u32 *skmeminfo = RTA_DATA(tb[PACKET_DIAG_MEMINFO]);
3828
3829 stat.rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
3830 }
3831
3832 if (tb[PACKET_DIAG_INFO]) {
3833 pinfo = RTA_DATA(tb[PACKET_DIAG_INFO]);
3834 stat.lport = stat.iface = pinfo->pdi_index;
3835 }
3836
3837 if (tb[PACKET_DIAG_UID])
3838 stat.uid = rta_getattr_u32(tb[PACKET_DIAG_UID]);
3839
3840 if (tb[PACKET_DIAG_RX_RING])
3841 ring_rx = RTA_DATA(tb[PACKET_DIAG_RX_RING]);
3842
3843 if (tb[PACKET_DIAG_TX_RING])
3844 ring_tx = RTA_DATA(tb[PACKET_DIAG_TX_RING]);
3845
3846 if (tb[PACKET_DIAG_FANOUT]) {
3847 has_fanout = true;
3848 fanout = rta_getattr_u32(tb[PACKET_DIAG_FANOUT]);
3849 }
3850
3851 if (packet_stats_print(&stat, f))
3852 return 0;
3853
3854 if (show_details) {
3855 if (pinfo) {
3856 out("\n\tver:%d", pinfo->pdi_version);
3857 out(" cpy_thresh:%d", pinfo->pdi_copy_thresh);
3858 out(" flags( ");
3859 if (pinfo->pdi_flags & PDI_RUNNING)
3860 out("running");
3861 if (pinfo->pdi_flags & PDI_AUXDATA)
3862 out(" auxdata");
3863 if (pinfo->pdi_flags & PDI_ORIGDEV)
3864 out(" origdev");
3865 if (pinfo->pdi_flags & PDI_VNETHDR)
3866 out(" vnethdr");
3867 if (pinfo->pdi_flags & PDI_LOSS)
3868 out(" loss");
3869 if (!pinfo->pdi_flags)
3870 out("0");
3871 out(" )");
3872 }
3873 if (ring_rx) {
3874 out("\n\tring_rx(");
3875 packet_show_ring(ring_rx);
3876 out(")");
3877 }
3878 if (ring_tx) {
3879 out("\n\tring_tx(");
3880 packet_show_ring(ring_tx);
3881 out(")");
3882 }
3883 if (has_fanout) {
3884 uint16_t type = (fanout >> 16) & 0xffff;
3885
3886 out("\n\tfanout(");
3887 out("id:%d,", fanout & 0xffff);
3888 out("type:");
3889
3890 if (type == 0)
3891 out("hash");
3892 else if (type == 1)
3893 out("lb");
3894 else if (type == 2)
3895 out("cpu");
3896 else if (type == 3)
3897 out("roll");
3898 else if (type == 4)
3899 out("random");
3900 else if (type == 5)
3901 out("qm");
3902 else
3903 out("0x%x", type);
3904
3905 out(")");
3906 }
3907 }
3908
3909 if (show_bpf && tb[PACKET_DIAG_FILTER]) {
3910 struct sock_filter *fil =
3911 RTA_DATA(tb[PACKET_DIAG_FILTER]);
3912 int num = RTA_PAYLOAD(tb[PACKET_DIAG_FILTER]) /
3913 sizeof(struct sock_filter);
3914
3915 out("\n\tbpf filter (%d): ", num);
3916 while (num) {
3917 out(" 0x%02x %u %u %u,",
3918 fil->code, fil->jt, fil->jf, fil->k);
3919 num--;
3920 fil++;
3921 }
3922 }
3923 return 0;
3924 }
3925
3926 static int packet_show_netlink(struct filter *f)
3927 {
3928 DIAG_REQUEST(req, struct packet_diag_req r);
3929
3930 req.r.sdiag_family = AF_PACKET;
3931 req.r.pdiag_show = PACKET_SHOW_INFO | PACKET_SHOW_MEMINFO |
3932 PACKET_SHOW_FILTER | PACKET_SHOW_RING_CFG | PACKET_SHOW_FANOUT;
3933
3934 return handle_netlink_request(f, &req.nlh, sizeof(req), packet_show_sock);
3935 }
3936
3937 static int packet_show_line(char *buf, const struct filter *f, int fam)
3938 {
3939 unsigned long long sk;
3940 struct sockstat stat = {};
3941 int type, prot, iface, state, rq, uid, ino;
3942
3943 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
3944 &sk,
3945 &type, &prot, &iface, &state,
3946 &rq, &uid, &ino);
3947
3948 if (stat.type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
3949 return 0;
3950 if (stat.type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
3951 return 0;
3952
3953 stat.type = type;
3954 stat.prot = prot;
3955 stat.lport = stat.iface = iface;
3956 stat.state = state;
3957 stat.rq = rq;
3958 stat.uid = uid;
3959 stat.ino = ino;
3960 stat.state = SS_CLOSE;
3961
3962 if (packet_stats_print(&stat, f))
3963 return 0;
3964
3965 return 0;
3966 }
3967
3968 static int packet_show(struct filter *f)
3969 {
3970 FILE *fp;
3971 int rc = 0;
3972
3973 if (!filter_af_get(f, AF_PACKET) || !(f->states & (1 << SS_CLOSE)))
3974 return 0;
3975
3976 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
3977 packet_show_netlink(f) == 0)
3978 return 0;
3979
3980 if ((fp = net_packet_open()) == NULL)
3981 return -1;
3982 if (generic_record_read(fp, packet_show_line, f, AF_PACKET))
3983 rc = -1;
3984
3985 fclose(fp);
3986 return rc;
3987 }
3988
3989 static int netlink_show_one(struct filter *f,
3990 int prot, int pid, unsigned int groups,
3991 int state, int dst_pid, unsigned int dst_group,
3992 int rq, int wq,
3993 unsigned long long sk, unsigned long long cb)
3994 {
3995 struct sockstat st = {
3996 .state = SS_CLOSE,
3997 .rq = rq,
3998 .wq = wq,
3999 .local.family = AF_NETLINK,
4000 .remote.family = AF_NETLINK,
4001 };
4002
4003 SPRINT_BUF(prot_buf) = {};
4004 const char *prot_name;
4005 char procname[64] = {};
4006
4007 if (f->f) {
4008 st.rport = -1;
4009 st.lport = pid;
4010 st.local.data[0] = prot;
4011 if (run_ssfilter(f->f, &st) == 0)
4012 return 1;
4013 }
4014
4015 sock_state_print(&st);
4016
4017 if (resolve_services)
4018 prot_name = nl_proto_n2a(prot, prot_buf, sizeof(prot_buf));
4019 else
4020 prot_name = int_to_str(prot, prot_buf);
4021
4022 if (pid == -1) {
4023 procname[0] = '*';
4024 } else if (resolve_services) {
4025 int done = 0;
4026
4027 if (!pid) {
4028 done = 1;
4029 strncpy(procname, "kernel", 6);
4030 } else if (pid > 0) {
4031 FILE *fp;
4032
4033 snprintf(procname, sizeof(procname), "%s/%d/stat",
4034 getenv("PROC_ROOT") ? : "/proc", pid);
4035 if ((fp = fopen(procname, "r")) != NULL) {
4036 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
4037 snprintf(procname+strlen(procname),
4038 sizeof(procname)-strlen(procname),
4039 "/%d", pid);
4040 done = 1;
4041 }
4042 fclose(fp);
4043 }
4044 }
4045 if (!done)
4046 int_to_str(pid, procname);
4047 } else {
4048 int_to_str(pid, procname);
4049 }
4050
4051 sock_addr_print(prot_name, ":", procname, NULL);
4052
4053 if (state == NETLINK_CONNECTED) {
4054 char dst_group_buf[30];
4055 char dst_pid_buf[30];
4056
4057 sock_addr_print(int_to_str(dst_group, dst_group_buf), ":",
4058 int_to_str(dst_pid, dst_pid_buf), NULL);
4059 } else {
4060 sock_addr_print("", "*", "", NULL);
4061 }
4062
4063 char *pid_context = NULL;
4064
4065 if (show_proc_ctx) {
4066 /* The pid value will either be:
4067 * 0 if destination kernel - show kernel initial context.
4068 * A valid process pid - use getpidcon.
4069 * A unique value allocated by the kernel or netlink user
4070 * to the process - show context as "not available".
4071 */
4072 if (!pid)
4073 security_get_initial_context("kernel", &pid_context);
4074 else if (pid > 0)
4075 getpidcon(pid, &pid_context);
4076
4077 out(" proc_ctx=%s", pid_context ? : "unavailable");
4078 free(pid_context);
4079 }
4080
4081 if (show_details) {
4082 out(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
4083 }
4084
4085 return 0;
4086 }
4087
4088 static int netlink_show_sock(const struct sockaddr_nl *addr,
4089 struct nlmsghdr *nlh, void *arg)
4090 {
4091 struct filter *f = (struct filter *)arg;
4092 struct netlink_diag_msg *r = NLMSG_DATA(nlh);
4093 struct rtattr *tb[NETLINK_DIAG_MAX+1];
4094 int rq = 0, wq = 0;
4095 unsigned long groups = 0;
4096
4097 parse_rtattr(tb, NETLINK_DIAG_MAX, (struct rtattr *)(r+1),
4098 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
4099
4100 if (tb[NETLINK_DIAG_GROUPS] && RTA_PAYLOAD(tb[NETLINK_DIAG_GROUPS]))
4101 groups = *(unsigned long *) RTA_DATA(tb[NETLINK_DIAG_GROUPS]);
4102
4103 if (tb[NETLINK_DIAG_MEMINFO]) {
4104 const __u32 *skmeminfo;
4105
4106 skmeminfo = RTA_DATA(tb[NETLINK_DIAG_MEMINFO]);
4107
4108 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
4109 wq = skmeminfo[SK_MEMINFO_WMEM_ALLOC];
4110 }
4111
4112 if (netlink_show_one(f, r->ndiag_protocol, r->ndiag_portid, groups,
4113 r->ndiag_state, r->ndiag_dst_portid, r->ndiag_dst_group,
4114 rq, wq, 0, 0)) {
4115 return 0;
4116 }
4117
4118 if (show_mem) {
4119 out("\t");
4120 print_skmeminfo(tb, NETLINK_DIAG_MEMINFO);
4121 }
4122
4123 return 0;
4124 }
4125
4126 static int netlink_show_netlink(struct filter *f)
4127 {
4128 DIAG_REQUEST(req, struct netlink_diag_req r);
4129
4130 req.r.sdiag_family = AF_NETLINK;
4131 req.r.sdiag_protocol = NDIAG_PROTO_ALL;
4132 req.r.ndiag_show = NDIAG_SHOW_GROUPS | NDIAG_SHOW_MEMINFO;
4133
4134 return handle_netlink_request(f, &req.nlh, sizeof(req), netlink_show_sock);
4135 }
4136
4137 static int netlink_show(struct filter *f)
4138 {
4139 FILE *fp;
4140 char buf[256];
4141 int prot, pid;
4142 unsigned int groups;
4143 int rq, wq, rc;
4144 unsigned long long sk, cb;
4145
4146 if (!filter_af_get(f, AF_NETLINK) || !(f->states & (1 << SS_CLOSE)))
4147 return 0;
4148
4149 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
4150 netlink_show_netlink(f) == 0)
4151 return 0;
4152
4153 if ((fp = net_netlink_open()) == NULL)
4154 return -1;
4155 if (!fgets(buf, sizeof(buf), fp)) {
4156 fclose(fp);
4157 return -1;
4158 }
4159
4160 while (fgets(buf, sizeof(buf), fp)) {
4161 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
4162 &sk,
4163 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
4164
4165 netlink_show_one(f, prot, pid, groups, 0, 0, 0, rq, wq, sk, cb);
4166 }
4167
4168 fclose(fp);
4169 return 0;
4170 }
4171
4172 static bool vsock_type_skip(struct sockstat *s, struct filter *f)
4173 {
4174 if (s->type == SOCK_STREAM && !(f->dbs & (1 << VSOCK_ST_DB)))
4175 return true;
4176 if (s->type == SOCK_DGRAM && !(f->dbs & (1 << VSOCK_DG_DB)))
4177 return true;
4178 return false;
4179 }
4180
4181 static void vsock_addr_print(inet_prefix *a, __u32 port)
4182 {
4183 char cid_str[sizeof("4294967295")];
4184 char port_str[sizeof("4294967295")];
4185 __u32 cid;
4186
4187 memcpy(&cid, a->data, sizeof(cid));
4188
4189 if (cid == ~(__u32)0)
4190 snprintf(cid_str, sizeof(cid_str), "*");
4191 else
4192 snprintf(cid_str, sizeof(cid_str), "%u", cid);
4193
4194 if (port == ~(__u32)0)
4195 snprintf(port_str, sizeof(port_str), "*");
4196 else
4197 snprintf(port_str, sizeof(port_str), "%u", port);
4198
4199 sock_addr_print(cid_str, ":", port_str, NULL);
4200 }
4201
4202 static void vsock_stats_print(struct sockstat *s, struct filter *f)
4203 {
4204 sock_state_print(s);
4205
4206 vsock_addr_print(&s->local, s->lport);
4207 vsock_addr_print(&s->remote, s->rport);
4208
4209 proc_ctx_print(s);
4210 }
4211
4212 static int vsock_show_sock(const struct sockaddr_nl *addr,
4213 struct nlmsghdr *nlh, void *arg)
4214 {
4215 struct filter *f = (struct filter *)arg;
4216 struct vsock_diag_msg *r = NLMSG_DATA(nlh);
4217 struct sockstat stat = {
4218 .type = r->vdiag_type,
4219 .lport = r->vdiag_src_port,
4220 .rport = r->vdiag_dst_port,
4221 .state = r->vdiag_state,
4222 .ino = r->vdiag_ino,
4223 };
4224
4225 vsock_set_inet_prefix(&stat.local, r->vdiag_src_cid);
4226 vsock_set_inet_prefix(&stat.remote, r->vdiag_dst_cid);
4227
4228 if (vsock_type_skip(&stat, f))
4229 return 0;
4230
4231 if (f->f && run_ssfilter(f->f, &stat) == 0)
4232 return 0;
4233
4234 vsock_stats_print(&stat, f);
4235
4236 return 0;
4237 }
4238
4239 static int vsock_show(struct filter *f)
4240 {
4241 DIAG_REQUEST(req, struct vsock_diag_req r);
4242
4243 if (!filter_af_get(f, AF_VSOCK))
4244 return 0;
4245
4246 req.r.sdiag_family = AF_VSOCK;
4247 req.r.vdiag_states = f->states;
4248
4249 return handle_netlink_request(f, &req.nlh, sizeof(req), vsock_show_sock);
4250 }
4251
4252 struct sock_diag_msg {
4253 __u8 sdiag_family;
4254 };
4255
4256 static int generic_show_sock(const struct sockaddr_nl *addr,
4257 struct nlmsghdr *nlh, void *arg)
4258 {
4259 struct sock_diag_msg *r = NLMSG_DATA(nlh);
4260 struct inet_diag_arg inet_arg = { .f = arg, .protocol = IPPROTO_MAX };
4261
4262 switch (r->sdiag_family) {
4263 case AF_INET:
4264 case AF_INET6:
4265 return show_one_inet_sock(addr, nlh, &inet_arg);
4266 case AF_UNIX:
4267 return unix_show_sock(addr, nlh, arg);
4268 case AF_PACKET:
4269 return packet_show_sock(addr, nlh, arg);
4270 case AF_NETLINK:
4271 return netlink_show_sock(addr, nlh, arg);
4272 case AF_VSOCK:
4273 return vsock_show_sock(addr, nlh, arg);
4274 default:
4275 return -1;
4276 }
4277 }
4278
4279 static int handle_follow_request(struct filter *f)
4280 {
4281 int ret = 0;
4282 int groups = 0;
4283 struct rtnl_handle rth;
4284
4285 if (f->families & FAMILY_MASK(AF_INET) && f->dbs & (1 << TCP_DB))
4286 groups |= 1 << (SKNLGRP_INET_TCP_DESTROY - 1);
4287 if (f->families & FAMILY_MASK(AF_INET) && f->dbs & (1 << UDP_DB))
4288 groups |= 1 << (SKNLGRP_INET_UDP_DESTROY - 1);
4289 if (f->families & FAMILY_MASK(AF_INET6) && f->dbs & (1 << TCP_DB))
4290 groups |= 1 << (SKNLGRP_INET6_TCP_DESTROY - 1);
4291 if (f->families & FAMILY_MASK(AF_INET6) && f->dbs & (1 << UDP_DB))
4292 groups |= 1 << (SKNLGRP_INET6_UDP_DESTROY - 1);
4293
4294 if (groups == 0)
4295 return -1;
4296
4297 if (rtnl_open_byproto(&rth, groups, NETLINK_SOCK_DIAG))
4298 return -1;
4299
4300 rth.dump = 0;
4301 rth.local.nl_pid = 0;
4302
4303 if (rtnl_dump_filter(&rth, generic_show_sock, f))
4304 ret = -1;
4305
4306 rtnl_close(&rth);
4307 return ret;
4308 }
4309
4310 static int get_snmp_int(char *proto, char *key, int *result)
4311 {
4312 char buf[1024];
4313 FILE *fp;
4314 int protolen = strlen(proto);
4315 int keylen = strlen(key);
4316
4317 *result = 0;
4318
4319 if ((fp = net_snmp_open()) == NULL)
4320 return -1;
4321
4322 while (fgets(buf, sizeof(buf), fp) != NULL) {
4323 char *p = buf;
4324 int pos = 0;
4325
4326 if (memcmp(buf, proto, protolen))
4327 continue;
4328 while ((p = strchr(p, ' ')) != NULL) {
4329 pos++;
4330 p++;
4331 if (memcmp(p, key, keylen) == 0 &&
4332 (p[keylen] == ' ' || p[keylen] == '\n'))
4333 break;
4334 }
4335 if (fgets(buf, sizeof(buf), fp) == NULL)
4336 break;
4337 if (memcmp(buf, proto, protolen))
4338 break;
4339 p = buf;
4340 while ((p = strchr(p, ' ')) != NULL) {
4341 p++;
4342 if (--pos == 0) {
4343 sscanf(p, "%d", result);
4344 fclose(fp);
4345 return 0;
4346 }
4347 }
4348 }
4349
4350 fclose(fp);
4351 errno = ESRCH;
4352 return -1;
4353 }
4354
4355
4356 /* Get stats from sockstat */
4357
4358 struct ssummary {
4359 int socks;
4360 int tcp_mem;
4361 int tcp_total;
4362 int tcp_orphans;
4363 int tcp_tws;
4364 int tcp4_hashed;
4365 int udp4;
4366 int raw4;
4367 int frag4;
4368 int frag4_mem;
4369 int tcp6_hashed;
4370 int udp6;
4371 int raw6;
4372 int frag6;
4373 int frag6_mem;
4374 };
4375
4376 static void get_sockstat_line(char *line, struct ssummary *s)
4377 {
4378 char id[256], rem[256];
4379
4380 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
4381 return;
4382
4383 if (strcmp(id, "sockets:") == 0)
4384 sscanf(rem, "%*s%d", &s->socks);
4385 else if (strcmp(id, "UDP:") == 0)
4386 sscanf(rem, "%*s%d", &s->udp4);
4387 else if (strcmp(id, "UDP6:") == 0)
4388 sscanf(rem, "%*s%d", &s->udp6);
4389 else if (strcmp(id, "RAW:") == 0)
4390 sscanf(rem, "%*s%d", &s->raw4);
4391 else if (strcmp(id, "RAW6:") == 0)
4392 sscanf(rem, "%*s%d", &s->raw6);
4393 else if (strcmp(id, "TCP6:") == 0)
4394 sscanf(rem, "%*s%d", &s->tcp6_hashed);
4395 else if (strcmp(id, "FRAG:") == 0)
4396 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
4397 else if (strcmp(id, "FRAG6:") == 0)
4398 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
4399 else if (strcmp(id, "TCP:") == 0)
4400 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
4401 &s->tcp4_hashed,
4402 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
4403 }
4404
4405 static int get_sockstat(struct ssummary *s)
4406 {
4407 char buf[256];
4408 FILE *fp;
4409
4410 memset(s, 0, sizeof(*s));
4411
4412 if ((fp = net_sockstat_open()) == NULL)
4413 return -1;
4414 while (fgets(buf, sizeof(buf), fp) != NULL)
4415 get_sockstat_line(buf, s);
4416 fclose(fp);
4417
4418 if ((fp = net_sockstat6_open()) == NULL)
4419 return 0;
4420 while (fgets(buf, sizeof(buf), fp) != NULL)
4421 get_sockstat_line(buf, s);
4422 fclose(fp);
4423
4424 return 0;
4425 }
4426
4427 static int print_summary(void)
4428 {
4429 struct ssummary s;
4430 int tcp_estab;
4431
4432 if (get_sockstat(&s) < 0)
4433 perror("ss: get_sockstat");
4434 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab) < 0)
4435 perror("ss: get_snmpstat");
4436
4437 get_slabstat(&slabstat);
4438
4439 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
4440
4441 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
4442 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
4443 tcp_estab,
4444 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
4445 s.tcp_orphans,
4446 slabstat.tcp_syns,
4447 s.tcp_tws, slabstat.tcp_tws,
4448 slabstat.tcp_ports
4449 );
4450
4451 printf("\n");
4452 printf("Transport Total IP IPv6\n");
4453 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
4454 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
4455 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
4456 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
4457 printf("INET %-9d %-9d %-9d\n",
4458 s.raw4+s.udp4+s.tcp4_hashed+
4459 s.raw6+s.udp6+s.tcp6_hashed,
4460 s.raw4+s.udp4+s.tcp4_hashed,
4461 s.raw6+s.udp6+s.tcp6_hashed);
4462 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
4463
4464 printf("\n");
4465
4466 return 0;
4467 }
4468
4469 static void _usage(FILE *dest)
4470 {
4471 fprintf(dest,
4472 "Usage: ss [ OPTIONS ]\n"
4473 " ss [ OPTIONS ] [ FILTER ]\n"
4474 " -h, --help this message\n"
4475 " -V, --version output version information\n"
4476 " -n, --numeric don't resolve service names\n"
4477 " -r, --resolve resolve host names\n"
4478 " -a, --all display all sockets\n"
4479 " -l, --listening display listening sockets\n"
4480 " -o, --options show timer information\n"
4481 " -e, --extended show detailed socket information\n"
4482 " -m, --memory show socket memory usage\n"
4483 " -p, --processes show process using socket\n"
4484 " -i, --info show internal TCP information\n"
4485 " -s, --summary show socket usage summary\n"
4486 " -b, --bpf show bpf filter socket information\n"
4487 " -E, --events continually display sockets as they are destroyed\n"
4488 " -Z, --context display process SELinux security contexts\n"
4489 " -z, --contexts display process and socket SELinux security contexts\n"
4490 " -N, --net switch to the specified network namespace name\n"
4491 "\n"
4492 " -4, --ipv4 display only IP version 4 sockets\n"
4493 " -6, --ipv6 display only IP version 6 sockets\n"
4494 " -0, --packet display PACKET sockets\n"
4495 " -t, --tcp display only TCP sockets\n"
4496 " -S, --sctp display only SCTP sockets\n"
4497 " -u, --udp display only UDP sockets\n"
4498 " -d, --dccp display only DCCP sockets\n"
4499 " -w, --raw display only RAW sockets\n"
4500 " -x, --unix display only Unix domain sockets\n"
4501 " --vsock display only vsock sockets\n"
4502 " -f, --family=FAMILY display sockets of type FAMILY\n"
4503 " FAMILY := {inet|inet6|link|unix|netlink|vsock|help}\n"
4504 "\n"
4505 " -K, --kill forcibly close sockets, display what was closed\n"
4506 " -H, --no-header Suppress header line\n"
4507 "\n"
4508 " -A, --query=QUERY, --socket=QUERY\n"
4509 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink|vsock_stream|vsock_dgram}[,QUERY]\n"
4510 "\n"
4511 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
4512 " -F, --filter=FILE read filter information from FILE\n"
4513 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
4514 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
4515 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listening|closing}\n"
4516 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4517 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4518 " bucket := {syn-recv|time-wait}\n"
4519 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listening|closing}\n"
4520 );
4521 }
4522
4523 static void help(void) __attribute__((noreturn));
4524 static void help(void)
4525 {
4526 _usage(stdout);
4527 exit(0);
4528 }
4529
4530 static void usage(void) __attribute__((noreturn));
4531 static void usage(void)
4532 {
4533 _usage(stderr);
4534 exit(-1);
4535 }
4536
4537
4538 static int scan_state(const char *state)
4539 {
4540 static const char * const sstate_namel[] = {
4541 "UNKNOWN",
4542 [SS_ESTABLISHED] = "established",
4543 [SS_SYN_SENT] = "syn-sent",
4544 [SS_SYN_RECV] = "syn-recv",
4545 [SS_FIN_WAIT1] = "fin-wait-1",
4546 [SS_FIN_WAIT2] = "fin-wait-2",
4547 [SS_TIME_WAIT] = "time-wait",
4548 [SS_CLOSE] = "unconnected",
4549 [SS_CLOSE_WAIT] = "close-wait",
4550 [SS_LAST_ACK] = "last-ack",
4551 [SS_LISTEN] = "listening",
4552 [SS_CLOSING] = "closing",
4553 };
4554 int i;
4555
4556 if (strcasecmp(state, "close") == 0 ||
4557 strcasecmp(state, "closed") == 0)
4558 return (1<<SS_CLOSE);
4559 if (strcasecmp(state, "syn-rcv") == 0)
4560 return (1<<SS_SYN_RECV);
4561 if (strcasecmp(state, "established") == 0)
4562 return (1<<SS_ESTABLISHED);
4563 if (strcasecmp(state, "all") == 0)
4564 return SS_ALL;
4565 if (strcasecmp(state, "connected") == 0)
4566 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
4567 if (strcasecmp(state, "synchronized") == 0)
4568 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
4569 if (strcasecmp(state, "bucket") == 0)
4570 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
4571 if (strcasecmp(state, "big") == 0)
4572 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
4573 for (i = 0; i < SS_MAX; i++) {
4574 if (strcasecmp(state, sstate_namel[i]) == 0)
4575 return (1<<i);
4576 }
4577
4578 fprintf(stderr, "ss: wrong state name: %s\n", state);
4579 exit(-1);
4580 }
4581
4582 /* Values 'v' and 'V' are already used so a non-character is used */
4583 #define OPT_VSOCK 256
4584
4585 static const struct option long_opts[] = {
4586 { "numeric", 0, 0, 'n' },
4587 { "resolve", 0, 0, 'r' },
4588 { "options", 0, 0, 'o' },
4589 { "extended", 0, 0, 'e' },
4590 { "memory", 0, 0, 'm' },
4591 { "info", 0, 0, 'i' },
4592 { "processes", 0, 0, 'p' },
4593 { "bpf", 0, 0, 'b' },
4594 { "events", 0, 0, 'E' },
4595 { "dccp", 0, 0, 'd' },
4596 { "tcp", 0, 0, 't' },
4597 { "sctp", 0, 0, 'S' },
4598 { "udp", 0, 0, 'u' },
4599 { "raw", 0, 0, 'w' },
4600 { "unix", 0, 0, 'x' },
4601 { "vsock", 0, 0, OPT_VSOCK },
4602 { "all", 0, 0, 'a' },
4603 { "listening", 0, 0, 'l' },
4604 { "ipv4", 0, 0, '4' },
4605 { "ipv6", 0, 0, '6' },
4606 { "packet", 0, 0, '0' },
4607 { "family", 1, 0, 'f' },
4608 { "socket", 1, 0, 'A' },
4609 { "query", 1, 0, 'A' },
4610 { "summary", 0, 0, 's' },
4611 { "diag", 1, 0, 'D' },
4612 { "filter", 1, 0, 'F' },
4613 { "version", 0, 0, 'V' },
4614 { "help", 0, 0, 'h' },
4615 { "context", 0, 0, 'Z' },
4616 { "contexts", 0, 0, 'z' },
4617 { "net", 1, 0, 'N' },
4618 { "kill", 0, 0, 'K' },
4619 { "no-header", 0, 0, 'H' },
4620 { 0 }
4621
4622 };
4623
4624 int main(int argc, char *argv[])
4625 {
4626 int saw_states = 0;
4627 int saw_query = 0;
4628 int do_summary = 0;
4629 const char *dump_tcpdiag = NULL;
4630 FILE *filter_fp = NULL;
4631 int ch;
4632 int state_filter = 0;
4633 int screen_width = 80;
4634
4635 while ((ch = getopt_long(argc, argv,
4636 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHS",
4637 long_opts, NULL)) != EOF) {
4638 switch (ch) {
4639 case 'n':
4640 resolve_services = 0;
4641 break;
4642 case 'r':
4643 resolve_hosts = 1;
4644 break;
4645 case 'o':
4646 show_options = 1;
4647 break;
4648 case 'e':
4649 show_options = 1;
4650 show_details++;
4651 break;
4652 case 'm':
4653 show_mem = 1;
4654 break;
4655 case 'i':
4656 show_tcpinfo = 1;
4657 break;
4658 case 'p':
4659 show_users++;
4660 user_ent_hash_build();
4661 break;
4662 case 'b':
4663 show_options = 1;
4664 show_bpf++;
4665 break;
4666 case 'E':
4667 follow_events = 1;
4668 break;
4669 case 'd':
4670 filter_db_set(&current_filter, DCCP_DB);
4671 break;
4672 case 't':
4673 filter_db_set(&current_filter, TCP_DB);
4674 break;
4675 case 'S':
4676 filter_db_set(&current_filter, SCTP_DB);
4677 break;
4678 case 'u':
4679 filter_db_set(&current_filter, UDP_DB);
4680 break;
4681 case 'w':
4682 filter_db_set(&current_filter, RAW_DB);
4683 break;
4684 case 'x':
4685 filter_af_set(&current_filter, AF_UNIX);
4686 break;
4687 case OPT_VSOCK:
4688 filter_af_set(&current_filter, AF_VSOCK);
4689 break;
4690 case 'a':
4691 state_filter = SS_ALL;
4692 break;
4693 case 'l':
4694 state_filter = (1 << SS_LISTEN) | (1 << SS_CLOSE);
4695 break;
4696 case '4':
4697 filter_af_set(&current_filter, AF_INET);
4698 break;
4699 case '6':
4700 filter_af_set(&current_filter, AF_INET6);
4701 break;
4702 case '0':
4703 filter_af_set(&current_filter, AF_PACKET);
4704 break;
4705 case 'f':
4706 if (strcmp(optarg, "inet") == 0)
4707 filter_af_set(&current_filter, AF_INET);
4708 else if (strcmp(optarg, "inet6") == 0)
4709 filter_af_set(&current_filter, AF_INET6);
4710 else if (strcmp(optarg, "link") == 0)
4711 filter_af_set(&current_filter, AF_PACKET);
4712 else if (strcmp(optarg, "unix") == 0)
4713 filter_af_set(&current_filter, AF_UNIX);
4714 else if (strcmp(optarg, "netlink") == 0)
4715 filter_af_set(&current_filter, AF_NETLINK);
4716 else if (strcmp(optarg, "vsock") == 0)
4717 filter_af_set(&current_filter, AF_VSOCK);
4718 else if (strcmp(optarg, "help") == 0)
4719 help();
4720 else {
4721 fprintf(stderr, "ss: \"%s\" is invalid family\n",
4722 optarg);
4723 usage();
4724 }
4725 break;
4726 case 'A':
4727 {
4728 char *p, *p1;
4729
4730 if (!saw_query) {
4731 current_filter.dbs = 0;
4732 state_filter = state_filter ?
4733 state_filter : SS_CONN;
4734 saw_query = 1;
4735 do_default = 0;
4736 }
4737 p = p1 = optarg;
4738 do {
4739 if ((p1 = strchr(p, ',')) != NULL)
4740 *p1 = 0;
4741 if (strcmp(p, "all") == 0) {
4742 filter_default_dbs(&current_filter);
4743 } else if (strcmp(p, "inet") == 0) {
4744 filter_db_set(&current_filter, UDP_DB);
4745 filter_db_set(&current_filter, DCCP_DB);
4746 filter_db_set(&current_filter, TCP_DB);
4747 filter_db_set(&current_filter, SCTP_DB);
4748 filter_db_set(&current_filter, RAW_DB);
4749 } else if (strcmp(p, "udp") == 0) {
4750 filter_db_set(&current_filter, UDP_DB);
4751 } else if (strcmp(p, "dccp") == 0) {
4752 filter_db_set(&current_filter, DCCP_DB);
4753 } else if (strcmp(p, "tcp") == 0) {
4754 filter_db_set(&current_filter, TCP_DB);
4755 } else if (strcmp(p, "sctp") == 0) {
4756 filter_db_set(&current_filter, SCTP_DB);
4757 } else if (strcmp(p, "raw") == 0) {
4758 filter_db_set(&current_filter, RAW_DB);
4759 } else if (strcmp(p, "unix") == 0) {
4760 filter_db_set(&current_filter, UNIX_ST_DB);
4761 filter_db_set(&current_filter, UNIX_DG_DB);
4762 filter_db_set(&current_filter, UNIX_SQ_DB);
4763 } else if (strcasecmp(p, "unix_stream") == 0 ||
4764 strcmp(p, "u_str") == 0) {
4765 filter_db_set(&current_filter, UNIX_ST_DB);
4766 } else if (strcasecmp(p, "unix_dgram") == 0 ||
4767 strcmp(p, "u_dgr") == 0) {
4768 filter_db_set(&current_filter, UNIX_DG_DB);
4769 } else if (strcasecmp(p, "unix_seqpacket") == 0 ||
4770 strcmp(p, "u_seq") == 0) {
4771 filter_db_set(&current_filter, UNIX_SQ_DB);
4772 } else if (strcmp(p, "packet") == 0) {
4773 filter_db_set(&current_filter, PACKET_R_DB);
4774 filter_db_set(&current_filter, PACKET_DG_DB);
4775 } else if (strcmp(p, "packet_raw") == 0 ||
4776 strcmp(p, "p_raw") == 0) {
4777 filter_db_set(&current_filter, PACKET_R_DB);
4778 } else if (strcmp(p, "packet_dgram") == 0 ||
4779 strcmp(p, "p_dgr") == 0) {
4780 filter_db_set(&current_filter, PACKET_DG_DB);
4781 } else if (strcmp(p, "netlink") == 0) {
4782 filter_db_set(&current_filter, NETLINK_DB);
4783 } else if (strcmp(p, "vsock") == 0) {
4784 filter_db_set(&current_filter, VSOCK_ST_DB);
4785 filter_db_set(&current_filter, VSOCK_DG_DB);
4786 } else if (strcmp(p, "vsock_stream") == 0 ||
4787 strcmp(p, "v_str") == 0) {
4788 filter_db_set(&current_filter, VSOCK_ST_DB);
4789 } else if (strcmp(p, "vsock_dgram") == 0 ||
4790 strcmp(p, "v_dgr") == 0) {
4791 filter_db_set(&current_filter, VSOCK_DG_DB);
4792 } else {
4793 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
4794 usage();
4795 }
4796 p = p1 + 1;
4797 } while (p1);
4798 break;
4799 }
4800 case 's':
4801 do_summary = 1;
4802 break;
4803 case 'D':
4804 dump_tcpdiag = optarg;
4805 break;
4806 case 'F':
4807 if (filter_fp) {
4808 fprintf(stderr, "More than one filter file\n");
4809 exit(-1);
4810 }
4811 if (optarg[0] == '-')
4812 filter_fp = stdin;
4813 else
4814 filter_fp = fopen(optarg, "r");
4815 if (!filter_fp) {
4816 perror("fopen filter file");
4817 exit(-1);
4818 }
4819 break;
4820 case 'v':
4821 case 'V':
4822 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
4823 exit(0);
4824 case 'z':
4825 show_sock_ctx++;
4826 /* fall through */
4827 case 'Z':
4828 if (is_selinux_enabled() <= 0) {
4829 fprintf(stderr, "ss: SELinux is not enabled.\n");
4830 exit(1);
4831 }
4832 show_proc_ctx++;
4833 user_ent_hash_build();
4834 break;
4835 case 'N':
4836 if (netns_switch(optarg))
4837 exit(1);
4838 break;
4839 case 'K':
4840 current_filter.kill = 1;
4841 break;
4842 case 'H':
4843 show_header = 0;
4844 break;
4845 case 'h':
4846 help();
4847 case '?':
4848 default:
4849 usage();
4850 }
4851 }
4852
4853 argc -= optind;
4854 argv += optind;
4855
4856 if (do_summary) {
4857 print_summary();
4858 if (do_default && argc == 0)
4859 exit(0);
4860 }
4861
4862 while (argc > 0) {
4863 if (strcmp(*argv, "state") == 0) {
4864 NEXT_ARG();
4865 if (!saw_states)
4866 state_filter = 0;
4867 state_filter |= scan_state(*argv);
4868 saw_states = 1;
4869 } else if (strcmp(*argv, "exclude") == 0 ||
4870 strcmp(*argv, "excl") == 0) {
4871 NEXT_ARG();
4872 if (!saw_states)
4873 state_filter = SS_ALL;
4874 state_filter &= ~scan_state(*argv);
4875 saw_states = 1;
4876 } else {
4877 break;
4878 }
4879 argc--; argv++;
4880 }
4881
4882 if (do_default) {
4883 state_filter = state_filter ? state_filter : SS_CONN;
4884 filter_default_dbs(&current_filter);
4885 }
4886
4887 filter_states_set(&current_filter, state_filter);
4888 filter_merge_defaults(&current_filter);
4889
4890 if (resolve_services && resolve_hosts &&
4891 (current_filter.dbs & (UNIX_DBM|INET_L4_DBM)))
4892 init_service_resolver();
4893
4894 if (current_filter.dbs == 0) {
4895 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
4896 exit(0);
4897 }
4898 if (current_filter.families == 0) {
4899 fprintf(stderr, "ss: no families to show with such filter.\n");
4900 exit(0);
4901 }
4902 if (current_filter.states == 0) {
4903 fprintf(stderr, "ss: no socket states to show with such filter.\n");
4904 exit(0);
4905 }
4906
4907 if (dump_tcpdiag) {
4908 FILE *dump_fp = stdout;
4909
4910 if (!(current_filter.dbs & (1<<TCP_DB))) {
4911 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
4912 exit(0);
4913 }
4914 if (dump_tcpdiag[0] != '-') {
4915 dump_fp = fopen(dump_tcpdiag, "w");
4916 if (!dump_tcpdiag) {
4917 perror("fopen dump file");
4918 exit(-1);
4919 }
4920 }
4921 inet_show_netlink(&current_filter, dump_fp, IPPROTO_TCP);
4922 fflush(dump_fp);
4923 exit(0);
4924 }
4925
4926 if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
4927 usage();
4928
4929 if (!(current_filter.dbs & (current_filter.dbs - 1)))
4930 columns[COL_NETID].disabled = 1;
4931
4932 if (!(current_filter.states & (current_filter.states - 1)))
4933 columns[COL_STATE].disabled = 1;
4934
4935 if (isatty(STDOUT_FILENO)) {
4936 struct winsize w;
4937
4938 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
4939 if (w.ws_col > 0)
4940 screen_width = w.ws_col;
4941 }
4942 }
4943
4944 if (show_header)
4945 print_header();
4946
4947 fflush(stdout);
4948
4949 if (follow_events)
4950 exit(handle_follow_request(&current_filter));
4951
4952 if (current_filter.dbs & (1<<NETLINK_DB))
4953 netlink_show(&current_filter);
4954 if (current_filter.dbs & PACKET_DBM)
4955 packet_show(&current_filter);
4956 if (current_filter.dbs & UNIX_DBM)
4957 unix_show(&current_filter);
4958 if (current_filter.dbs & (1<<RAW_DB))
4959 raw_show(&current_filter);
4960 if (current_filter.dbs & (1<<UDP_DB))
4961 udp_show(&current_filter);
4962 if (current_filter.dbs & (1<<TCP_DB))
4963 tcp_show(&current_filter);
4964 if (current_filter.dbs & (1<<DCCP_DB))
4965 dccp_show(&current_filter);
4966 if (current_filter.dbs & (1<<SCTP_DB))
4967 sctp_show(&current_filter);
4968 if (current_filter.dbs & VSOCK_DBM)
4969 vsock_show(&current_filter);
4970
4971 if (show_users || show_proc_ctx || show_sock_ctx)
4972 user_ent_destroy();
4973
4974 render(screen_width);
4975
4976 return 0;
4977 }