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