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