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