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