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