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