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