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