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