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