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