]> git.proxmox.com Git - mirror_iproute2.git/blame - misc/ss.c
ip route: restore_handler should check tb[RTA_PREFSRC] for local networks
[mirror_iproute2.git] / misc / ss.c
CommitLineData
b9de3ecf 1/*
aba5acdf
SH
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 <syslog.h>
16#include <fcntl.h>
17#include <sys/ioctl.h>
18#include <sys/socket.h>
19#include <sys/uio.h>
20#include <netinet/in.h>
21#include <string.h>
22#include <errno.h>
23#include <netdb.h>
24#include <arpa/inet.h>
aba5acdf
SH
25#include <dirent.h>
26#include <fnmatch.h>
ab61159a 27#include <getopt.h>
bf4ceee6 28#include <stdbool.h>
aba5acdf
SH
29
30#include "utils.h"
31#include "rt_names.h"
32#include "ll_map.h"
33#include "libnetlink.h"
95ce04bc 34#include "namespace.h"
aba5acdf
SH
35#include "SNAPSHOT.h"
36
9cb1eccf 37#include <linux/tcp.h>
f6062360 38#include <linux/sock_diag.h>
351efcde 39#include <linux/inet_diag.h>
dfbaa90d 40#include <linux/unix_diag.h>
372c30d2
ND
41#include <linux/netdevice.h> /* for MAX_ADDR_LEN */
42#include <linux/filter.h>
43#include <linux/packet_diag.h>
ecb928c8 44#include <linux/netlink_diag.h>
aba5acdf 45
8a4025f6 46#define MAGIC_SEQ 123456
47
5fb421d4 48#define DIAG_REQUEST(_req, _r) \
49 struct { \
50 struct nlmsghdr nlh; \
51 _r; \
52 } _req = { \
53 .nlh = { \
54 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
55 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
8a4025f6 56 .nlmsg_seq = MAGIC_SEQ, \
5fb421d4 57 .nlmsg_len = sizeof(_req), \
58 }, \
59 }
60
116ac927
RH
61#if HAVE_SELINUX
62#include <selinux/selinux.h>
63#else
64/* Stubs for SELinux functions */
65static int is_selinux_enabled(void)
66{
67 return -1;
68}
69
70static int getpidcon(pid_t pid, char **context)
71{
72 *context = NULL;
73 return -1;
74}
75
76static int getfilecon(char *path, char **context)
77{
78 *context = NULL;
79 return -1;
80}
81
82static int security_get_initial_context(char *name, char **context)
83{
84 *context = NULL;
85 return -1;
86}
87#endif
88
acd1e437 89int resolve_hosts;
aba5acdf
SH
90int resolve_services = 1;
91int preferred_family = AF_UNSPEC;
acd1e437
SH
92int show_options;
93int show_details;
94int show_users;
95int show_mem;
96int show_tcpinfo;
97int show_bpf;
98int show_proc_ctx;
99int show_sock_ctx;
7a4559f6 100int show_header = 1;
116ac927 101/* If show_users & show_proc_ctx only do user_ent_hash_build() once */
acd1e437
SH
102int user_ent_hash_build_init;
103int follow_events;
aba5acdf
SH
104
105int netid_width;
106int state_width;
107int addrp_width;
108int addr_width;
109int serv_width;
110int screen_width;
111
112static const char *TCP_PROTO = "tcp";
113static const char *UDP_PROTO = "udp";
114static const char *RAW_PROTO = "raw";
acd1e437 115static const char *dg_proto;
aba5acdf 116
acd1e437 117enum {
aba5acdf 118 TCP_DB,
351efcde 119 DCCP_DB,
aba5acdf
SH
120 UDP_DB,
121 RAW_DB,
122 UNIX_DG_DB,
123 UNIX_ST_DB,
30b669d7 124 UNIX_SQ_DB,
aba5acdf
SH
125 PACKET_DG_DB,
126 PACKET_R_DB,
127 NETLINK_DB,
128 MAX_DB
129};
130
131#define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
30b669d7 132#define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
aba5acdf 133#define ALL_DB ((1<<MAX_DB)-1)
9db7bf15 134#define INET_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<RAW_DB))
aba5acdf
SH
135
136enum {
7d105b56
SH
137 SS_UNKNOWN,
138 SS_ESTABLISHED,
139 SS_SYN_SENT,
140 SS_SYN_RECV,
141 SS_FIN_WAIT1,
142 SS_FIN_WAIT2,
143 SS_TIME_WAIT,
144 SS_CLOSE,
145 SS_CLOSE_WAIT,
146 SS_LAST_ACK,
147 SS_LISTEN,
148 SS_CLOSING,
149 SS_MAX
aba5acdf
SH
150};
151
9db7bf15
VK
152#define SS_ALL ((1 << SS_MAX) - 1)
153#define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
aba5acdf
SH
154
155#include "ssfilter.h"
156
acd1e437 157struct filter {
aba5acdf
SH
158 int dbs;
159 int states;
160 int families;
161 struct ssfilter *f;
fb2594c1 162 bool kill;
aba5acdf
SH
163};
164
9db7bf15
VK
165static const struct filter default_dbs[MAX_DB] = {
166 [TCP_DB] = {
167 .states = SS_CONN,
168 .families = (1 << AF_INET) | (1 << AF_INET6),
169 },
170 [DCCP_DB] = {
171 .states = SS_CONN,
172 .families = (1 << AF_INET) | (1 << AF_INET6),
173 },
174 [UDP_DB] = {
f42a4574 175 .states = (1 << SS_ESTABLISHED),
9db7bf15
VK
176 .families = (1 << AF_INET) | (1 << AF_INET6),
177 },
178 [RAW_DB] = {
f42a4574 179 .states = (1 << SS_ESTABLISHED),
9db7bf15
VK
180 .families = (1 << AF_INET) | (1 << AF_INET6),
181 },
182 [UNIX_DG_DB] = {
183 .states = (1 << SS_CLOSE),
184 .families = (1 << AF_UNIX),
185 },
186 [UNIX_ST_DB] = {
187 .states = SS_CONN,
188 .families = (1 << AF_UNIX),
189 },
190 [UNIX_SQ_DB] = {
191 .states = SS_CONN,
192 .families = (1 << AF_UNIX),
193 },
194 [PACKET_DG_DB] = {
195 .states = (1 << SS_CLOSE),
196 .families = (1 << AF_PACKET),
197 },
198 [PACKET_R_DB] = {
199 .states = (1 << SS_CLOSE),
200 .families = (1 << AF_PACKET),
201 },
202 [NETLINK_DB] = {
203 .states = (1 << SS_CLOSE),
204 .families = (1 << AF_NETLINK),
205 },
aba5acdf
SH
206};
207
9db7bf15
VK
208static const struct filter default_afs[AF_MAX] = {
209 [AF_INET] = {
210 .dbs = INET_DBM,
211 .states = SS_CONN,
212 },
213 [AF_INET6] = {
214 .dbs = INET_DBM,
215 .states = SS_CONN,
216 },
217 [AF_UNIX] = {
218 .dbs = UNIX_DBM,
219 .states = SS_CONN,
220 },
221 [AF_PACKET] = {
222 .dbs = PACKET_DBM,
223 .states = (1 << SS_CLOSE),
224 },
225 [AF_NETLINK] = {
226 .dbs = (1 << NETLINK_DB),
227 .states = (1 << SS_CLOSE),
228 },
229};
230
231static int do_default = 1;
232static struct filter current_filter;
233
234static void filter_db_set(struct filter *f, int db)
235{
236 f->states |= default_dbs[db].states;
9db7bf15
VK
237 f->dbs |= 1 << db;
238 do_default = 0;
239}
240
241static void filter_af_set(struct filter *f, int af)
242{
1527a17e
VK
243 f->states |= default_afs[af].states;
244 f->families |= 1 << af;
245 do_default = 0;
246 preferred_family = af;
9db7bf15
VK
247}
248
249static int filter_af_get(struct filter *f, int af)
250{
251 return f->families & (1 << af);
252}
253
254static void filter_default_dbs(struct filter *f)
255{
256 filter_db_set(f, UDP_DB);
257 filter_db_set(f, DCCP_DB);
258 filter_db_set(f, TCP_DB);
259 filter_db_set(f, RAW_DB);
260 filter_db_set(f, UNIX_ST_DB);
261 filter_db_set(f, UNIX_DG_DB);
262 filter_db_set(f, UNIX_SQ_DB);
263 filter_db_set(f, PACKET_R_DB);
264 filter_db_set(f, PACKET_DG_DB);
265 filter_db_set(f, NETLINK_DB);
266}
267
57ff5a10 268static void filter_states_set(struct filter *f, int states)
9db7bf15 269{
57ff5a10 270 if (states)
9d320e1e 271 f->states = states;
57ff5a10 272}
9db7bf15 273
57ff5a10
VK
274static void filter_merge_defaults(struct filter *f)
275{
276 int db;
277 int af;
9db7bf15 278
57ff5a10
VK
279 for (db = 0; db < MAX_DB; db++) {
280 if (!(f->dbs & (1 << db)))
281 continue;
9db7bf15 282
57ff5a10
VK
283 if (!(default_dbs[db].families & f->families))
284 f->families |= default_dbs[db].families;
285 }
286 for (af = 0; af < AF_MAX; af++) {
287 if (!(f->families & (1 << af)))
288 continue;
289
290 if (!(default_afs[af].dbs & f->dbs))
291 f->dbs |= default_afs[af].dbs;
292 }
9db7bf15 293}
aba5acdf 294
ab01dbbb 295static FILE *generic_proc_open(const char *env, const char *name)
aba5acdf 296{
ab01dbbb 297 const char *p = getenv(env);
aba5acdf 298 char store[128];
ab01dbbb 299
aba5acdf
SH
300 if (!p) {
301 p = getenv("PROC_ROOT") ? : "/proc";
302 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
303 p = store;
304 }
ab01dbbb
SH
305
306 return fopen(p, "r");
aba5acdf
SH
307}
308
ab01dbbb 309static FILE *net_tcp_open(void)
aba5acdf
SH
310{
311 return generic_proc_open("PROC_NET_TCP", "net/tcp");
312}
313
ab01dbbb 314static FILE *net_tcp6_open(void)
aba5acdf
SH
315{
316 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
317}
318
ab01dbbb 319static FILE *net_udp_open(void)
aba5acdf
SH
320{
321 return generic_proc_open("PROC_NET_UDP", "net/udp");
322}
323
ab01dbbb 324static FILE *net_udp6_open(void)
aba5acdf
SH
325{
326 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
327}
328
ab01dbbb 329static FILE *net_raw_open(void)
aba5acdf
SH
330{
331 return generic_proc_open("PROC_NET_RAW", "net/raw");
332}
333
ab01dbbb 334static FILE *net_raw6_open(void)
aba5acdf
SH
335{
336 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
337}
338
ab01dbbb 339static FILE *net_unix_open(void)
aba5acdf
SH
340{
341 return generic_proc_open("PROC_NET_UNIX", "net/unix");
342}
343
ab01dbbb 344static FILE *net_packet_open(void)
aba5acdf
SH
345{
346 return generic_proc_open("PROC_NET_PACKET", "net/packet");
347}
348
ab01dbbb 349static FILE *net_netlink_open(void)
aba5acdf
SH
350{
351 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
352}
353
ab01dbbb 354static FILE *slabinfo_open(void)
aba5acdf
SH
355{
356 return generic_proc_open("PROC_SLABINFO", "slabinfo");
357}
358
ab01dbbb 359static FILE *net_sockstat_open(void)
aba5acdf
SH
360{
361 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
362}
363
ab01dbbb 364static FILE *net_sockstat6_open(void)
aba5acdf
SH
365{
366 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
367}
368
ab01dbbb 369static FILE *net_snmp_open(void)
aba5acdf
SH
370{
371 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
372}
373
ab01dbbb 374static FILE *ephemeral_ports_open(void)
aba5acdf
SH
375{
376 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
377}
378
fbc0f876
SF
379struct user_ent {
380 struct user_ent *next;
381 unsigned int ino;
382 int pid;
383 int fd;
116ac927
RH
384 char *process;
385 char *process_ctx;
386 char *socket_ctx;
fbc0f876
SF
387};
388
389#define USER_ENT_HASH_SIZE 256
390struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE];
391
392static int user_ent_hashfn(unsigned int ino)
aba5acdf 393{
fbc0f876 394 int val = (ino >> 24) ^ (ino >> 16) ^ (ino >> 8) ^ ino;
aba5acdf 395
fbc0f876
SF
396 return val & (USER_ENT_HASH_SIZE - 1);
397}
398
116ac927
RH
399static void user_ent_add(unsigned int ino, char *process,
400 int pid, int fd,
401 char *proc_ctx,
402 char *sock_ctx)
fbc0f876
SF
403{
404 struct user_ent *p, **pp;
aba5acdf 405
116ac927
RH
406 p = malloc(sizeof(struct user_ent));
407 if (!p) {
408 fprintf(stderr, "ss: failed to malloc buffer\n");
fbc0f876 409 abort();
116ac927 410 }
fbc0f876
SF
411 p->next = NULL;
412 p->ino = ino;
413 p->pid = pid;
414 p->fd = fd;
116ac927
RH
415 p->process = strdup(process);
416 p->process_ctx = strdup(proc_ctx);
417 p->socket_ctx = strdup(sock_ctx);
fbc0f876
SF
418
419 pp = &user_ent_hash[user_ent_hashfn(ino)];
420 p->next = *pp;
421 *pp = p;
422}
aba5acdf 423
116ac927
RH
424static void user_ent_destroy(void)
425{
426 struct user_ent *p, *p_next;
427 int cnt = 0;
428
429 while (cnt != USER_ENT_HASH_SIZE) {
430 p = user_ent_hash[cnt];
431 while (p) {
432 free(p->process);
433 free(p->process_ctx);
434 free(p->socket_ctx);
435 p_next = p->next;
436 free(p);
437 p = p_next;
438 }
439 cnt++;
440 }
441}
442
fbc0f876
SF
443static void user_ent_hash_build(void)
444{
445 const char *root = getenv("PROC_ROOT") ? : "/proc/";
446 struct dirent *d;
447 char name[1024];
448 int nameoff;
449 DIR *dir;
116ac927
RH
450 char *pid_context;
451 char *sock_context;
452 const char *no_ctx = "unavailable";
453
454 /* If show_users & show_proc_ctx set only do this once */
455 if (user_ent_hash_build_init != 0)
456 return;
457
458 user_ent_hash_build_init = 1;
fbc0f876 459
0ee9052f 460 strncpy(name, root, sizeof(name)-1);
461 name[sizeof(name)-1] = 0;
462
fbc0f876 463 if (strlen(name) == 0 || name[strlen(name)-1] != '/')
aba5acdf 464 strcat(name, "/");
fbc0f876 465
aba5acdf 466 nameoff = strlen(name);
fbc0f876
SF
467
468 dir = opendir(name);
469 if (!dir)
470 return;
aba5acdf
SH
471
472 while ((d = readdir(dir)) != NULL) {
aba5acdf 473 struct dirent *d1;
aba5acdf 474 char process[16];
116ac927 475 char *p;
fbc0f876
SF
476 int pid, pos;
477 DIR *dir1;
478 char crap;
aba5acdf
SH
479
480 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
481 continue;
482
116ac927
RH
483 if (getpidcon(pid, &pid_context) != 0)
484 pid_context = strdup(no_ctx);
485
0ee9052f 486 snprintf(name + nameoff, sizeof(name) - nameoff, "%d/fd/", pid);
aba5acdf 487 pos = strlen(name);
a02371fb
PS
488 if ((dir1 = opendir(name)) == NULL) {
489 free(pid_context);
aba5acdf 490 continue;
a02371fb 491 }
aba5acdf 492
fbc0f876 493 process[0] = '\0';
116ac927 494 p = process;
aba5acdf
SH
495
496 while ((d1 = readdir(dir1)) != NULL) {
fbc0f876
SF
497 const char *pattern = "socket:[";
498 unsigned int ino;
aba5acdf 499 char lnk[64];
18445b3e 500 int fd;
788731b3 501 ssize_t link_len;
116ac927 502 char tmp[1024];
aba5acdf
SH
503
504 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
505 continue;
506
0ee9052f 507 snprintf(name+pos, sizeof(name) - pos, "%d", fd);
788731b3
TJ
508
509 link_len = readlink(name, lnk, sizeof(lnk)-1);
510 if (link_len == -1)
511 continue;
512 lnk[link_len] = '\0';
513
514 if (strncmp(lnk, pattern, strlen(pattern)))
aba5acdf
SH
515 continue;
516
fbc0f876 517 sscanf(lnk, "socket:[%u]", &ino);
aba5acdf 518
116ac927
RH
519 snprintf(tmp, sizeof(tmp), "%s/%d/fd/%s",
520 root, pid, d1->d_name);
521
522 if (getfilecon(tmp, &sock_context) <= 0)
523 sock_context = strdup(no_ctx);
524
525 if (*p == '\0') {
aba5acdf 526 FILE *fp;
fbc0f876 527
116ac927
RH
528 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
529 root, pid);
aba5acdf 530 if ((fp = fopen(tmp, "r")) != NULL) {
d572ed4d
PS
531 if (fscanf(fp, "%*d (%[^)])", p) < 1)
532 ; /* ignore */
aba5acdf
SH
533 fclose(fp);
534 }
535 }
116ac927
RH
536 user_ent_add(ino, p, pid, fd,
537 pid_context, sock_context);
538 free(sock_context);
aba5acdf 539 }
116ac927 540 free(pid_context);
aba5acdf
SH
541 closedir(dir1);
542 }
543 closedir(dir);
fbc0f876
SF
544}
545
116ac927
RH
546enum entry_types {
547 USERS,
548 PROC_CTX,
549 PROC_SOCK_CTX
550};
551
552#define ENTRY_BUF_SIZE 512
acd1e437 553static int find_entry(unsigned int ino, char **buf, int type)
fbc0f876
SF
554{
555 struct user_ent *p;
556 int cnt = 0;
557 char *ptr;
532ca40a 558 char *new_buf;
116ac927
RH
559 int len, new_buf_len;
560 int buf_used = 0;
561 int buf_len = 0;
fbc0f876
SF
562
563 if (!ino)
564 return 0;
565
566 p = user_ent_hash[user_ent_hashfn(ino)];
116ac927 567 ptr = *buf = NULL;
fbc0f876
SF
568 while (p) {
569 if (p->ino != ino)
570 goto next;
571
116ac927
RH
572 while (1) {
573 ptr = *buf + buf_used;
574 switch (type) {
575 case USERS:
576 len = snprintf(ptr, buf_len - buf_used,
577 "(\"%s\",pid=%d,fd=%d),",
578 p->process, p->pid, p->fd);
579 break;
580 case PROC_CTX:
581 len = snprintf(ptr, buf_len - buf_used,
582 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
583 p->process, p->pid,
584 p->process_ctx, p->fd);
585 break;
586 case PROC_SOCK_CTX:
587 len = snprintf(ptr, buf_len - buf_used,
588 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
589 p->process, p->pid,
590 p->process_ctx, p->fd,
591 p->socket_ctx);
592 break;
593 default:
594 fprintf(stderr, "ss: invalid type: %d\n", type);
595 abort();
596 }
fbc0f876 597
116ac927
RH
598 if (len < 0 || len >= buf_len - buf_used) {
599 new_buf_len = buf_len + ENTRY_BUF_SIZE;
532ca40a 600 new_buf = realloc(*buf, new_buf_len);
116ac927
RH
601 if (!new_buf) {
602 fprintf(stderr, "ss: failed to malloc buffer\n");
603 abort();
604 }
532ca40a 605 *buf = new_buf;
116ac927
RH
606 buf_len = new_buf_len;
607 continue;
608 } else {
609 buf_used += len;
610 break;
611 }
612 }
fbc0f876 613 cnt++;
116ac927 614next:
fbc0f876
SF
615 p = p->next;
616 }
116ac927
RH
617 if (buf_used) {
618 ptr = *buf + buf_used;
fbc0f876 619 ptr[-1] = '\0';
116ac927 620 }
aba5acdf
SH
621 return cnt;
622}
623
aba5acdf
SH
624/* Get stats from slab */
625
acd1e437 626struct slabstat {
aba5acdf
SH
627 int socks;
628 int tcp_ports;
629 int tcp_tws;
630 int tcp_syns;
631 int skbs;
632};
633
a221d621 634static struct slabstat slabstat;
aba5acdf 635
acd1e437
SH
636static const char *slabstat_ids[] = {
637
aba5acdf
SH
638 "sock",
639 "tcp_bind_bucket",
640 "tcp_tw_bucket",
641 "tcp_open_request",
642 "skbuff_head_cache",
643};
644
d1f28cf1 645static int get_slabstat(struct slabstat *s)
aba5acdf
SH
646{
647 char buf[256];
648 FILE *fp;
649 int cnt;
a221d621
BL
650 static int slabstat_valid;
651
652 if (slabstat_valid)
653 return 0;
aba5acdf
SH
654
655 memset(s, 0, sizeof(*s));
656
ab01dbbb
SH
657 fp = slabinfo_open();
658 if (!fp)
aba5acdf
SH
659 return -1;
660
661 cnt = sizeof(*s)/sizeof(int);
662
d572ed4d
PS
663 if (!fgets(buf, sizeof(buf), fp)) {
664 fclose(fp);
665 return -1;
666 }
acd1e437 667 while (fgets(buf, sizeof(buf), fp) != NULL) {
aba5acdf 668 int i;
acd1e437 669
62000e51 670 for (i = 0; i < ARRAY_SIZE(slabstat_ids); i++) {
aba5acdf
SH
671 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
672 sscanf(buf, "%*s%d", ((int *)s) + i);
673 cnt--;
674 break;
675 }
676 }
677 if (cnt <= 0)
678 break;
679 }
680
a221d621
BL
681 slabstat_valid = 1;
682
aba5acdf
SH
683 fclose(fp);
684 return 0;
685}
686
2e7e805d 687static unsigned long long cookie_sk_get(const uint32_t *cookie)
f1b39e1b 688{
2e7e805d 689 return (((unsigned long long)cookie[1] << 31) << 1) | cookie[0];
f1b39e1b
VK
690}
691
7d105b56
SH
692static const char *sstate_name[] = {
693 "UNKNOWN",
9cb1eccf
ED
694 [SS_ESTABLISHED] = "ESTAB",
695 [SS_SYN_SENT] = "SYN-SENT",
696 [SS_SYN_RECV] = "SYN-RECV",
697 [SS_FIN_WAIT1] = "FIN-WAIT-1",
698 [SS_FIN_WAIT2] = "FIN-WAIT-2",
699 [SS_TIME_WAIT] = "TIME-WAIT",
700 [SS_CLOSE] = "UNCONN",
701 [SS_CLOSE_WAIT] = "CLOSE-WAIT",
702 [SS_LAST_ACK] = "LAST-ACK",
acd1e437 703 [SS_LISTEN] = "LISTEN",
9cb1eccf 704 [SS_CLOSING] = "CLOSING",
aba5acdf
SH
705};
706
7d105b56
SH
707static const char *sstate_namel[] = {
708 "UNKNOWN",
9cb1eccf
ED
709 [SS_ESTABLISHED] = "established",
710 [SS_SYN_SENT] = "syn-sent",
711 [SS_SYN_RECV] = "syn-recv",
712 [SS_FIN_WAIT1] = "fin-wait-1",
713 [SS_FIN_WAIT2] = "fin-wait-2",
714 [SS_TIME_WAIT] = "time-wait",
715 [SS_CLOSE] = "unconnected",
716 [SS_CLOSE_WAIT] = "close-wait",
717 [SS_LAST_ACK] = "last-ack",
acd1e437 718 [SS_LISTEN] = "listening",
9cb1eccf 719 [SS_CLOSING] = "closing",
aba5acdf
SH
720};
721
acd1e437 722struct sockstat {
ec4d0d8a
VK
723 struct sockstat *next;
724 unsigned int type;
89f634f9 725 uint16_t prot;
8250bc9f
VK
726 inet_prefix local;
727 inet_prefix remote;
728 int lport;
729 int rport;
730 int state;
731 int rq, wq;
acd1e437
SH
732 unsigned int ino;
733 unsigned int uid;
8250bc9f
VK
734 int refcnt;
735 unsigned int iface;
736 unsigned long long sk;
99bb68ff
VK
737 char *name;
738 char *peer_name;
055840f2
VK
739};
740
acd1e437 741struct dctcpstat {
055840f2
VK
742 unsigned int ce_state;
743 unsigned int alpha;
744 unsigned int ab_ecn;
745 unsigned int ab_tot;
746 bool enabled;
747};
748
acd1e437 749struct tcpstat {
055840f2 750 struct sockstat ss;
8250bc9f
VK
751 int timer;
752 int timeout;
753 int probes;
d2055ea5 754 char cong_alg[16];
8250bc9f
VK
755 double rto, ato, rtt, rttvar;
756 int qack, cwnd, ssthresh, backoff;
757 double send_bps;
758 int snd_wscale;
759 int rcv_wscale;
760 int mss;
761 unsigned int lastsnd;
762 unsigned int lastrcv;
763 unsigned int lastack;
764 double pacing_rate;
765 double pacing_rate_max;
1a4dda71
ED
766 unsigned long long bytes_acked;
767 unsigned long long bytes_received;
ecb435ea
CG
768 unsigned int segs_out;
769 unsigned int segs_in;
414aeec9
MKL
770 unsigned int data_segs_out;
771 unsigned int data_segs_in;
8250bc9f
VK
772 unsigned int unacked;
773 unsigned int retrans;
774 unsigned int retrans_total;
775 unsigned int lost;
776 unsigned int sacked;
777 unsigned int fackets;
778 unsigned int reordering;
9e99e495 779 unsigned int not_sent;
8250bc9f 780 double rcv_rtt;
9e99e495 781 double min_rtt;
8250bc9f
VK
782 int rcv_space;
783 bool has_ts_opt;
784 bool has_sack_opt;
785 bool has_ecn_opt;
786 bool has_ecnseen_opt;
787 bool has_fastopen_opt;
788 bool has_wscale_opt;
789 struct dctcpstat *dctcp;
aba5acdf
SH
790};
791
2d791bc8
VK
792static void sock_state_print(struct sockstat *s, const char *sock_name)
793{
794 if (netid_width)
795 printf("%-*s ", netid_width, sock_name);
796 if (state_width)
797 printf("%-*s ", state_width, sstate_name[s->state]);
798
799 printf("%-6d %-6d ", s->rq, s->wq);
800}
801
f1b39e1b
VK
802static void sock_details_print(struct sockstat *s)
803{
804 if (s->uid)
805 printf(" uid:%u", s->uid);
806
807 printf(" ino:%u", s->ino);
808 printf(" sk:%llx", s->sk);
809}
810
b217df10
VK
811static void sock_addr_print_width(int addr_len, const char *addr, char *delim,
812 int port_len, const char *port, const char *ifname)
813{
814 if (ifname) {
815 printf("%*s%%%s%s%-*s ", addr_len, addr, ifname, delim,
816 port_len, port);
acd1e437 817 } else {
b217df10
VK
818 printf("%*s%s%-*s ", addr_len, addr, delim, port_len, port);
819 }
820}
821
822static void sock_addr_print(const char *addr, char *delim, const char *port,
823 const char *ifname)
824{
825 sock_addr_print_width(addr_width, addr, delim, serv_width, port, ifname);
826}
827
7d105b56 828static const char *tmr_name[] = {
aba5acdf
SH
829 "off",
830 "on",
831 "keepalive",
832 "timewait",
833 "persist",
834 "unknown"
835};
836
d1f28cf1 837static const char *print_ms_timer(int timeout)
aba5acdf
SH
838{
839 static char buf[64];
840 int secs, msecs, minutes;
acd1e437 841
aba5acdf
SH
842 if (timeout < 0)
843 timeout = 0;
844 secs = timeout/1000;
845 minutes = secs/60;
846 secs = secs%60;
847 msecs = timeout%1000;
848 buf[0] = 0;
849 if (minutes) {
850 msecs = 0;
851 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
852 if (minutes > 9)
853 secs = 0;
854 }
855 if (secs) {
856 if (secs > 9)
857 msecs = 0;
858 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
859 }
860 if (msecs)
861 sprintf(buf+strlen(buf), "%03dms", msecs);
862 return buf;
e7113c61 863}
aba5acdf 864
22588a0e 865struct scache {
aba5acdf
SH
866 struct scache *next;
867 int port;
868 char *name;
869 const char *proto;
870};
871
872struct scache *rlist;
873
d1f28cf1 874static void init_service_resolver(void)
aba5acdf
SH
875{
876 char buf[128];
877 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
596307ea
PS
878
879 if (!fp)
880 return;
881
882 if (!fgets(buf, sizeof(buf), fp)) {
2bcc3c16 883 pclose(fp);
596307ea
PS
884 return;
885 }
886 while (fgets(buf, sizeof(buf), fp) != NULL) {
887 unsigned int progn, port;
888 char proto[128], prog[128] = "rpc.";
889 struct scache *c;
890
891 if (sscanf(buf, "%u %*d %s %u %s",
acd1e437 892 &progn, proto, &port, prog+4) != 4)
596307ea
PS
893 continue;
894
895 if (!(c = malloc(sizeof(*c))))
896 continue;
897
898 c->port = port;
899 c->name = strdup(prog);
900 if (strcmp(proto, TCP_PROTO) == 0)
901 c->proto = TCP_PROTO;
902 else if (strcmp(proto, UDP_PROTO) == 0)
903 c->proto = UDP_PROTO;
904 else
905 c->proto = NULL;
906 c->next = rlist;
907 rlist = c;
aba5acdf 908 }
596307ea 909 pclose(fp);
aba5acdf
SH
910}
911
ab61159a
SH
912/* Even do not try default linux ephemeral port ranges:
913 * default /etc/services contains so much of useless crap
914 * wouldbe "allocated" to this area that resolution
915 * is really harmful. I shrug each time when seeing
916 * "socks" or "cfinger" in dumps.
917 */
918static int is_ephemeral(int port)
919{
acd1e437 920 static int min = 0, max;
c29d3792
PS
921
922 if (!min) {
ab01dbbb 923 FILE *f = ephemeral_ports_open();
acd1e437 924
c29d3792
PS
925 if (!f || fscanf(f, "%d %d", &min, &max) < 2) {
926 min = 1024;
927 max = 4999;
ab61159a 928 }
c29d3792
PS
929 if (f)
930 fclose(f);
ab61159a 931 }
c29d3792 932 return port >= min && port <= max;
ab61159a
SH
933}
934
935
d1f28cf1 936static const char *__resolve_service(int port)
aba5acdf
SH
937{
938 struct scache *c;
939
940 for (c = rlist; c; c = c->next) {
941 if (c->port == port && c->proto == dg_proto)
942 return c->name;
943 }
944
ab61159a 945 if (!is_ephemeral(port)) {
aba5acdf
SH
946 static int notfirst;
947 struct servent *se;
acd1e437 948
aba5acdf
SH
949 if (!notfirst) {
950 setservent(1);
951 notfirst = 1;
ae665a52 952 }
aba5acdf
SH
953 se = getservbyport(htons(port), dg_proto);
954 if (se)
955 return se->s_name;
956 }
957
958 return NULL;
959}
960
22588a0e
ED
961#define SCACHE_BUCKETS 1024
962static struct scache *cache_htab[SCACHE_BUCKETS];
aba5acdf 963
d1f28cf1 964static const char *resolve_service(int port)
aba5acdf
SH
965{
966 static char buf[128];
22588a0e
ED
967 struct scache *c;
968 const char *res;
969 int hash;
aba5acdf
SH
970
971 if (port == 0) {
972 buf[0] = '*';
973 buf[1] = 0;
974 return buf;
975 }
976
22588a0e
ED
977 if (!resolve_services)
978 goto do_numeric;
aba5acdf 979
22588a0e
ED
980 if (dg_proto == RAW_PROTO)
981 return inet_proto_n2a(port, buf, sizeof(buf));
982
983
984 hash = (port^(((unsigned long)dg_proto)>>2)) % SCACHE_BUCKETS;
985
986 for (c = cache_htab[hash]; c; c = c->next) {
987 if (c->port == port && c->proto == dg_proto)
988 goto do_cache;
aba5acdf
SH
989 }
990
22588a0e
ED
991 c = malloc(sizeof(*c));
992 if (!c)
993 goto do_numeric;
994 res = __resolve_service(port);
995 c->port = port;
996 c->name = res ? strdup(res) : NULL;
997 c->proto = dg_proto;
998 c->next = cache_htab[hash];
999 cache_htab[hash] = c;
1000
1001do_cache:
1002 if (c->name)
1003 return c->name;
1004
1005do_numeric:
aba5acdf
SH
1006 sprintf(buf, "%u", port);
1007 return buf;
1008}
1009
b217df10 1010static void inet_addr_print(const inet_prefix *a, int port, unsigned int ifindex)
aba5acdf
SH
1011{
1012 char buf[1024];
1013 const char *ap = buf;
b217df10
VK
1014 int est_len = addr_width;
1015 const char *ifname = NULL;
aba5acdf
SH
1016
1017 if (a->family == AF_INET) {
1018 if (a->data[0] == 0) {
1019 buf[0] = '*';
1020 buf[1] = 0;
1021 } else {
a418e451 1022 ap = format_host(AF_INET, 4, a->data);
aba5acdf
SH
1023 }
1024 } else {
a418e451 1025 ap = format_host(a->family, 16, a->data);
aba5acdf
SH
1026 est_len = strlen(ap);
1027 if (est_len <= addr_width)
1028 est_len = addr_width;
1029 else
1030 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
1031 }
b217df10 1032
7c8a3cfb 1033 if (ifindex) {
b217df10
VK
1034 ifname = ll_index_to_name(ifindex);
1035 est_len -= strlen(ifname) + 1; /* +1 for percent char */
4fcfb6bc
MS
1036 if (est_len < 0)
1037 est_len = 0;
b217df10 1038 }
7c8a3cfb 1039
b217df10
VK
1040 sock_addr_print_width(est_len, ap, ":", serv_width, resolve_service(port),
1041 ifname);
aba5acdf
SH
1042}
1043
acd1e437 1044struct aafilter {
aba5acdf
SH
1045 inet_prefix addr;
1046 int port;
2d293212 1047 unsigned int iface;
aba5acdf
SH
1048 struct aafilter *next;
1049};
1050
d1f28cf1
SH
1051static int inet2_addr_match(const inet_prefix *a, const inet_prefix *p,
1052 int plen)
aba5acdf
SH
1053{
1054 if (!inet_addr_match(a, p, plen))
1055 return 0;
7d105b56 1056
aba5acdf
SH
1057 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1058 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1059 * sockets. Fair? */
1060 if (p->family == AF_INET && a->family == AF_INET6) {
1061 if (a->data[0] == 0 && a->data[1] == 0 &&
1062 a->data[2] == htonl(0xffff)) {
1063 inet_prefix tmp = *a;
acd1e437 1064
aba5acdf
SH
1065 tmp.data[0] = a->data[3];
1066 return inet_addr_match(&tmp, p, plen);
1067 }
1068 }
1069 return 1;
1070}
1071
d1f28cf1 1072static int unix_match(const inet_prefix *a, const inet_prefix *p)
aba5acdf 1073{
99bb68ff 1074 char *addr, *pattern;
acd1e437 1075
99bb68ff
VK
1076 memcpy(&addr, a->data, sizeof(addr));
1077 memcpy(&pattern, p->data, sizeof(pattern));
aba5acdf
SH
1078 if (pattern == NULL)
1079 return 1;
1080 if (addr == NULL)
1081 addr = "";
1082 return !fnmatch(pattern, addr, 0);
1083}
1084
055840f2 1085static int run_ssfilter(struct ssfilter *f, struct sockstat *s)
aba5acdf
SH
1086{
1087 switch (f->type) {
1088 case SSF_S_AUTO:
1089 {
aba5acdf 1090 if (s->local.family == AF_UNIX) {
99bb68ff 1091 char *p;
acd1e437 1092
99bb68ff 1093 memcpy(&p, s->local.data, sizeof(p));
aba5acdf 1094 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
ae665a52 1095 strspn(p+1, "0123456789abcdef") == 5);
aba5acdf
SH
1096 }
1097 if (s->local.family == AF_PACKET)
bbd303d1 1098 return s->lport == 0 && s->local.data[0] == 0;
aba5acdf
SH
1099 if (s->local.family == AF_NETLINK)
1100 return s->lport < 0;
1101
c29d3792 1102 return is_ephemeral(s->lport);
aba5acdf
SH
1103 }
1104 case SSF_DCOND:
1105 {
acd1e437
SH
1106 struct aafilter *a = (void *)f->pred;
1107
aba5acdf
SH
1108 if (a->addr.family == AF_UNIX)
1109 return unix_match(&s->remote, &a->addr);
1110 if (a->port != -1 && a->port != s->rport)
1111 return 0;
1112 if (a->addr.bitlen) {
1113 do {
1114 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
1115 return 1;
1116 } while ((a = a->next) != NULL);
1117 return 0;
1118 }
1119 return 1;
1120 }
1121 case SSF_SCOND:
1122 {
acd1e437
SH
1123 struct aafilter *a = (void *)f->pred;
1124
aba5acdf
SH
1125 if (a->addr.family == AF_UNIX)
1126 return unix_match(&s->local, &a->addr);
1127 if (a->port != -1 && a->port != s->lport)
1128 return 0;
1129 if (a->addr.bitlen) {
1130 do {
1131 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
1132 return 1;
ae665a52 1133 } while ((a = a->next) != NULL);
aba5acdf
SH
1134 return 0;
1135 }
1136 return 1;
1137 }
1138 case SSF_D_GE:
1139 {
acd1e437
SH
1140 struct aafilter *a = (void *)f->pred;
1141
aba5acdf
SH
1142 return s->rport >= a->port;
1143 }
1144 case SSF_D_LE:
1145 {
acd1e437
SH
1146 struct aafilter *a = (void *)f->pred;
1147
aba5acdf
SH
1148 return s->rport <= a->port;
1149 }
1150 case SSF_S_GE:
1151 {
acd1e437
SH
1152 struct aafilter *a = (void *)f->pred;
1153
aba5acdf
SH
1154 return s->lport >= a->port;
1155 }
1156 case SSF_S_LE:
1157 {
acd1e437
SH
1158 struct aafilter *a = (void *)f->pred;
1159
aba5acdf
SH
1160 return s->lport <= a->port;
1161 }
2d293212
DA
1162 case SSF_DEVCOND:
1163 {
1164 struct aafilter *a = (void *)f->pred;
aba5acdf 1165
2d293212
DA
1166 return s->iface == a->iface;
1167 }
aba5acdf
SH
1168 /* Yup. It is recursion. Sorry. */
1169 case SSF_AND:
1170 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
1171 case SSF_OR:
1172 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
1173 case SSF_NOT:
1174 return !run_ssfilter(f->pred, s);
1175 default:
1176 abort();
1177 }
1178}
1179
ae665a52 1180/* Relocate external jumps by reloc. */
b4b0b7d5 1181static void ssfilter_patch(char *a, int len, int reloc)
aba5acdf
SH
1182{
1183 while (len > 0) {
acd1e437
SH
1184 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)a;
1185
aba5acdf
SH
1186 if (op->no == len+4)
1187 op->no += reloc;
1188 len -= op->yes;
1189 a += op->yes;
1190 }
1191 if (len < 0)
1192 abort();
1193}
1194
b4b0b7d5 1195static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
aba5acdf
SH
1196{
1197 switch (f->type) {
1198 case SSF_S_AUTO:
1199 {
acd1e437
SH
1200 if (!(*bytecode = malloc(4))) abort();
1201 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
df39de8d 1202 return 4;
aba5acdf
SH
1203 }
1204 case SSF_DCOND:
1205 case SSF_SCOND:
1206 {
acd1e437 1207 struct aafilter *a = (void *)f->pred;
aba5acdf
SH
1208 struct aafilter *b;
1209 char *ptr;
351efcde 1210 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
aba5acdf
SH
1211 int len = 0;
1212
acd1e437 1213 for (b = a; b; b = b->next) {
351efcde 1214 len += 4 + sizeof(struct inet_diag_hostcond);
aba5acdf
SH
1215 if (a->addr.family == AF_INET6)
1216 len += 16;
1217 else
1218 len += 4;
1219 if (b->next)
1220 len += 4;
1221 }
1222 if (!(ptr = malloc(len))) abort();
1223 *bytecode = ptr;
acd1e437 1224 for (b = a; b; b = b->next) {
351efcde 1225 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
aba5acdf 1226 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
351efcde 1227 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
acd1e437 1228 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond *)(ptr+4);
aba5acdf 1229
351efcde 1230 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
aba5acdf
SH
1231 cond->family = a->addr.family;
1232 cond->port = a->port;
1233 cond->prefix_len = a->addr.bitlen;
1234 memcpy(cond->addr, a->addr.data, alen);
1235 ptr += oplen;
1236 if (b->next) {
351efcde
SH
1237 op = (struct inet_diag_bc_op *)ptr;
1238 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
aba5acdf
SH
1239 ptr += 4;
1240 }
1241 }
1242 return ptr - *bytecode;
1243 }
1244 case SSF_D_GE:
1245 {
acd1e437
SH
1246 struct aafilter *x = (void *)f->pred;
1247
1248 if (!(*bytecode = malloc(8))) abort();
1249 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
1250 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1251 return 8;
1252 }
1253 case SSF_D_LE:
1254 {
acd1e437
SH
1255 struct aafilter *x = (void *)f->pred;
1256
1257 if (!(*bytecode = malloc(8))) abort();
1258 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
1259 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1260 return 8;
1261 }
1262 case SSF_S_GE:
1263 {
acd1e437
SH
1264 struct aafilter *x = (void *)f->pred;
1265
1266 if (!(*bytecode = malloc(8))) abort();
1267 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
1268 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1269 return 8;
1270 }
1271 case SSF_S_LE:
1272 {
acd1e437
SH
1273 struct aafilter *x = (void *)f->pred;
1274
1275 if (!(*bytecode = malloc(8))) abort();
1276 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
1277 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1278 return 8;
1279 }
1280
1281 case SSF_AND:
1282 {
376fb868 1283 char *a1 = NULL, *a2 = NULL, *a;
2a4fa1c3 1284 int l1, l2;
acd1e437 1285
aba5acdf
SH
1286 l1 = ssfilter_bytecompile(f->pred, &a1);
1287 l2 = ssfilter_bytecompile(f->post, &a2);
376fb868
DA
1288 if (!l1 || !l2) {
1289 free(a1);
1290 free(a2);
1291 return 0;
1292 }
aba5acdf
SH
1293 if (!(a = malloc(l1+l2))) abort();
1294 memcpy(a, a1, l1);
1295 memcpy(a+l1, a2, l2);
1296 free(a1); free(a2);
1297 ssfilter_patch(a, l1, l2);
1298 *bytecode = a;
1299 return l1+l2;
1300 }
1301 case SSF_OR:
1302 {
376fb868 1303 char *a1 = NULL, *a2 = NULL, *a;
2a4fa1c3 1304 int l1, l2;
acd1e437 1305
aba5acdf
SH
1306 l1 = ssfilter_bytecompile(f->pred, &a1);
1307 l2 = ssfilter_bytecompile(f->post, &a2);
376fb868
DA
1308 if (!l1 || !l2) {
1309 free(a1);
1310 free(a2);
1311 return 0;
1312 }
aba5acdf
SH
1313 if (!(a = malloc(l1+l2+4))) abort();
1314 memcpy(a, a1, l1);
1315 memcpy(a+l1+4, a2, l2);
1316 free(a1); free(a2);
acd1e437 1317 *(struct inet_diag_bc_op *)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
aba5acdf
SH
1318 *bytecode = a;
1319 return l1+l2+4;
1320 }
1321 case SSF_NOT:
1322 {
376fb868 1323 char *a1 = NULL, *a;
2a4fa1c3 1324 int l1;
acd1e437 1325
aba5acdf 1326 l1 = ssfilter_bytecompile(f->pred, &a1);
376fb868
DA
1327 if (!l1) {
1328 free(a1);
1329 return 0;
1330 }
aba5acdf
SH
1331 if (!(a = malloc(l1+4))) abort();
1332 memcpy(a, a1, l1);
1333 free(a1);
acd1e437 1334 *(struct inet_diag_bc_op *)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
aba5acdf
SH
1335 *bytecode = a;
1336 return l1+4;
2d293212
DA
1337 }
1338 case SSF_DEVCOND:
1339 {
1340 /* bytecompile for SSF_DEVCOND not supported yet */
1341 return 0;
aba5acdf
SH
1342 }
1343 default:
1344 abort();
1345 }
1346}
1347
b4b0b7d5 1348static int remember_he(struct aafilter *a, struct hostent *he)
aba5acdf 1349{
ae665a52 1350 char **ptr = he->h_addr_list;
aba5acdf
SH
1351 int cnt = 0;
1352 int len;
1353
1354 if (he->h_addrtype == AF_INET)
1355 len = 4;
1356 else if (he->h_addrtype == AF_INET6)
1357 len = 16;
1358 else
1359 return 0;
1360
1361 while (*ptr) {
1362 struct aafilter *b = a;
acd1e437 1363
aba5acdf
SH
1364 if (a->addr.bitlen) {
1365 if ((b = malloc(sizeof(*b))) == NULL)
1366 return cnt;
1367 *b = *a;
1368 b->next = a->next;
1369 a->next = b;
1370 }
1371 memcpy(b->addr.data, *ptr, len);
1372 b->addr.bytelen = len;
1373 b->addr.bitlen = len*8;
1374 b->addr.family = he->h_addrtype;
1375 ptr++;
1376 cnt++;
1377 }
1378 return cnt;
1379}
1380
b4b0b7d5 1381static int get_dns_host(struct aafilter *a, const char *addr, int fam)
aba5acdf
SH
1382{
1383 static int notfirst;
1384 int cnt = 0;
1385 struct hostent *he;
1386
1387 a->addr.bitlen = 0;
1388 if (!notfirst) {
1389 sethostent(1);
1390 notfirst = 1;
1391 }
1392 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
1393 if (he)
1394 cnt = remember_he(a, he);
1395 if (fam == AF_UNSPEC) {
1396 he = gethostbyname2(addr, AF_INET6);
1397 if (he)
1398 cnt += remember_he(a, he);
1399 }
1400 return !cnt;
1401}
1402
acd1e437 1403static int xll_initted;
aba5acdf 1404
b4b0b7d5 1405static void xll_init(void)
aba5acdf
SH
1406{
1407 struct rtnl_handle rth;
acd1e437 1408
d2468da0
SH
1409 if (rtnl_open(&rth, 0) < 0)
1410 exit(1);
1411
aba5acdf
SH
1412 ll_init_map(&rth);
1413 rtnl_close(&rth);
1414 xll_initted = 1;
1415}
1416
b4b0b7d5 1417static const char *xll_index_to_name(int index)
aba5acdf
SH
1418{
1419 if (!xll_initted)
1420 xll_init();
1421 return ll_index_to_name(index);
1422}
1423
b4b0b7d5 1424static int xll_name_to_index(const char *dev)
aba5acdf
SH
1425{
1426 if (!xll_initted)
1427 xll_init();
1428 return ll_name_to_index(dev);
1429}
1430
2d293212
DA
1431void *parse_devcond(char *name)
1432{
1433 struct aafilter a = { .iface = 0 };
1434 struct aafilter *res;
1435
1436 a.iface = xll_name_to_index(name);
1437 if (a.iface == 0) {
1438 char *end;
930d3f28 1439 unsigned long n;
2d293212 1440
930d3f28
DA
1441 n = strtoul(name, &end, 0);
1442 if (!end || end == name || *end || n > UINT_MAX)
2d293212 1443 return NULL;
930d3f28
DA
1444
1445 a.iface = n;
2d293212
DA
1446 }
1447
1448 res = malloc(sizeof(*res));
1449 *res = a;
1450
1451 return res;
1452}
1453
7871f7db 1454void *parse_hostcond(char *addr, bool is_port)
aba5acdf
SH
1455{
1456 char *port = NULL;
1527a17e 1457 struct aafilter a = { .port = -1 };
aba5acdf 1458 struct aafilter *res;
1527a17e 1459 int fam = preferred_family;
9db7bf15 1460 struct filter *f = &current_filter;
aba5acdf 1461
1527a17e 1462 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
aba5acdf 1463 char *p;
acd1e437 1464
aba5acdf
SH
1465 a.addr.family = AF_UNIX;
1466 if (strncmp(addr, "unix:", 5) == 0)
acd1e437 1467 addr += 5;
aba5acdf
SH
1468 p = strdup(addr);
1469 a.addr.bitlen = 8*strlen(p);
99bb68ff 1470 memcpy(a.addr.data, &p, sizeof(p));
9db7bf15 1471 fam = AF_UNIX;
aba5acdf
SH
1472 goto out;
1473 }
1474
1527a17e 1475 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
aba5acdf
SH
1476 a.addr.family = AF_PACKET;
1477 a.addr.bitlen = 0;
1478 if (strncmp(addr, "link:", 5) == 0)
acd1e437 1479 addr += 5;
aba5acdf
SH
1480 port = strchr(addr, ':');
1481 if (port) {
1482 *port = 0;
1483 if (port[1] && strcmp(port+1, "*")) {
1484 if (get_integer(&a.port, port+1, 0)) {
1485 if ((a.port = xll_name_to_index(port+1)) <= 0)
1486 return NULL;
1487 }
1488 }
1489 }
1490 if (addr[0] && strcmp(addr, "*")) {
1491 unsigned short tmp;
acd1e437 1492
aba5acdf
SH
1493 a.addr.bitlen = 32;
1494 if (ll_proto_a2n(&tmp, addr))
1495 return NULL;
1496 a.addr.data[0] = ntohs(tmp);
1497 }
9db7bf15 1498 fam = AF_PACKET;
aba5acdf
SH
1499 goto out;
1500 }
1501
1527a17e 1502 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
aba5acdf
SH
1503 a.addr.family = AF_NETLINK;
1504 a.addr.bitlen = 0;
1505 if (strncmp(addr, "netlink:", 8) == 0)
acd1e437 1506 addr += 8;
aba5acdf
SH
1507 port = strchr(addr, ':');
1508 if (port) {
1509 *port = 0;
1510 if (port[1] && strcmp(port+1, "*")) {
1511 if (get_integer(&a.port, port+1, 0)) {
1512 if (strcmp(port+1, "kernel") == 0)
1513 a.port = 0;
1514 else
1515 return NULL;
1516 }
1517 }
1518 }
1519 if (addr[0] && strcmp(addr, "*")) {
1520 a.addr.bitlen = 32;
b00daf6a 1521 if (nl_proto_a2n(&a.addr.data[0], addr) == -1)
1522 return NULL;
aba5acdf 1523 }
9db7bf15 1524 fam = AF_NETLINK;
aba5acdf
SH
1525 goto out;
1526 }
1527
1527a17e 1528 if (fam == AF_INET || !strncmp(addr, "inet:", 5)) {
aba5acdf 1529 fam = AF_INET;
1527a17e
VK
1530 if (!strncmp(addr, "inet:", 5))
1531 addr += 5;
1532 } else if (fam == AF_INET6 || !strncmp(addr, "inet6:", 6)) {
aba5acdf 1533 fam = AF_INET6;
1527a17e
VK
1534 if (!strncmp(addr, "inet6:", 6))
1535 addr += 6;
aba5acdf
SH
1536 }
1537
1538 /* URL-like literal [] */
1539 if (addr[0] == '[') {
1540 addr++;
1541 if ((port = strchr(addr, ']')) == NULL)
1542 return NULL;
1543 *port++ = 0;
1544 } else if (addr[0] == '*') {
1545 port = addr+1;
1546 } else {
1547 port = strrchr(strchr(addr, '/') ? : addr, ':');
1548 }
7871f7db
VK
1549
1550 if (is_port)
1551 port = addr;
1552
aba5acdf 1553 if (port && *port) {
7871f7db
VK
1554 if (*port == ':')
1555 *port++ = 0;
1556
aba5acdf
SH
1557 if (*port && *port != '*') {
1558 if (get_integer(&a.port, port, 0)) {
1559 struct servent *se1 = NULL;
1560 struct servent *se2 = NULL;
acd1e437 1561
aba5acdf
SH
1562 if (current_filter.dbs&(1<<UDP_DB))
1563 se1 = getservbyname(port, UDP_PROTO);
1564 if (current_filter.dbs&(1<<TCP_DB))
1565 se2 = getservbyname(port, TCP_PROTO);
1566 if (se1 && se2 && se1->s_port != se2->s_port) {
1567 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1568 return NULL;
1569 }
1570 if (!se1)
1571 se1 = se2;
1572 if (se1) {
1573 a.port = ntohs(se1->s_port);
1574 } else {
1575 struct scache *s;
acd1e437 1576
aba5acdf
SH
1577 for (s = rlist; s; s = s->next) {
1578 if ((s->proto == UDP_PROTO &&
1579 (current_filter.dbs&(1<<UDP_DB))) ||
1580 (s->proto == TCP_PROTO &&
1581 (current_filter.dbs&(1<<TCP_DB)))) {
1582 if (s->name && strcmp(s->name, port) == 0) {
1583 if (a.port > 0 && a.port != s->port) {
1584 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1585 return NULL;
1586 }
1587 a.port = s->port;
1588 }
1589 }
1590 }
1591 if (a.port <= 0) {
1592 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1593 return NULL;
1594 }
1595 }
1596 }
1597 }
1598 }
7871f7db 1599 if (!is_port && addr && *addr && *addr != '*') {
aba5acdf
SH
1600 if (get_prefix_1(&a.addr, addr, fam)) {
1601 if (get_dns_host(&a, addr, fam)) {
1602 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1603 return NULL;
1604 }
1605 }
1606 }
1607
9db7bf15 1608out:
1527a17e 1609 if (fam != AF_UNSPEC) {
e56a959e 1610 int states = f->states;
1527a17e 1611 f->families = 0;
9db7bf15 1612 filter_af_set(f, fam);
e56a959e 1613 filter_states_set(f, states);
1527a17e 1614 }
9db7bf15 1615
aba5acdf
SH
1616 res = malloc(sizeof(*res));
1617 if (res)
1618 memcpy(res, &a, sizeof(a));
1619 return res;
1620}
1621
8250bc9f
VK
1622static char *proto_name(int protocol)
1623{
1624 switch (protocol) {
235c4453
NA
1625 case 0:
1626 return "raw";
8250bc9f
VK
1627 case IPPROTO_UDP:
1628 return "udp";
1629 case IPPROTO_TCP:
1630 return "tcp";
1631 case IPPROTO_DCCP:
1632 return "dccp";
1633 }
1634
1635 return "???";
1636}
1637
055840f2 1638static void inet_stats_print(struct sockstat *s, int protocol)
8250bc9f
VK
1639{
1640 char *buf = NULL;
1641
2d791bc8 1642 sock_state_print(s, proto_name(protocol));
8250bc9f 1643
b217df10
VK
1644 inet_addr_print(&s->local, s->lport, s->iface);
1645 inet_addr_print(&s->remote, s->rport, 0);
8250bc9f 1646
8250bc9f
VK
1647 if (show_proc_ctx || show_sock_ctx) {
1648 if (find_entry(s->ino, &buf,
1649 (show_proc_ctx & show_sock_ctx) ?
1650 PROC_SOCK_CTX : PROC_CTX) > 0) {
1651 printf(" users:(%s)", buf);
1652 free(buf);
1653 }
1654 } else if (show_users) {
1655 if (find_entry(s->ino, &buf, USERS) > 0) {
1656 printf(" users:(%s)", buf);
1657 free(buf);
1658 }
1659 }
1660}
1661
055840f2 1662static int proc_parse_inet_addr(char *loc, char *rem, int family, struct
acd1e437 1663 sockstat * s)
8250bc9f
VK
1664{
1665 s->local.family = s->remote.family = family;
1666 if (family == AF_INET) {
acd1e437
SH
1667 sscanf(loc, "%x:%x", s->local.data, (unsigned *)&s->lport);
1668 sscanf(rem, "%x:%x", s->remote.data, (unsigned *)&s->rport);
8250bc9f
VK
1669 s->local.bytelen = s->remote.bytelen = 4;
1670 return 0;
1671 } else {
1672 sscanf(loc, "%08x%08x%08x%08x:%x",
1673 s->local.data,
1674 s->local.data + 1,
1675 s->local.data + 2,
1676 s->local.data + 3,
1677 &s->lport);
1678 sscanf(rem, "%08x%08x%08x%08x:%x",
1679 s->remote.data,
1680 s->remote.data + 1,
1681 s->remote.data + 2,
1682 s->remote.data + 3,
1683 &s->rport);
1684 s->local.bytelen = s->remote.bytelen = 16;
1685 return 0;
1686 }
1687 return -1;
1688}
1689
1690static int proc_inet_split_line(char *line, char **loc, char **rem, char **data)
aba5acdf 1691{
aba5acdf 1692 char *p;
ae665a52 1693
aba5acdf
SH
1694 if ((p = strchr(line, ':')) == NULL)
1695 return -1;
ae665a52 1696
8250bc9f
VK
1697 *loc = p+2;
1698 if ((p = strchr(*loc, ':')) == NULL)
aba5acdf 1699 return -1;
ae665a52 1700
8250bc9f
VK
1701 p[5] = 0;
1702 *rem = p+6;
1703 if ((p = strchr(*rem, ':')) == NULL)
aba5acdf 1704 return -1;
8250bc9f 1705
aba5acdf 1706 p[5] = 0;
8250bc9f
VK
1707 *data = p+6;
1708 return 0;
1709}
ae665a52 1710
8250bc9f
VK
1711static char *sprint_bw(char *buf, double bw)
1712{
1713 if (bw > 1000000.)
acd1e437 1714 sprintf(buf, "%.1fM", bw / 1000000.);
8250bc9f 1715 else if (bw > 1000.)
acd1e437 1716 sprintf(buf, "%.1fK", bw / 1000.);
8250bc9f
VK
1717 else
1718 sprintf(buf, "%g", bw);
aba5acdf 1719
8250bc9f
VK
1720 return buf;
1721}
ae665a52 1722
8250bc9f
VK
1723static void tcp_stats_print(struct tcpstat *s)
1724{
1725 char b1[64];
1726
1727 if (s->has_ts_opt)
1728 printf(" ts");
1729 if (s->has_sack_opt)
1730 printf(" sack");
1731 if (s->has_ecn_opt)
1732 printf(" ecn");
1733 if (s->has_ecnseen_opt)
1734 printf(" ecnseen");
1735 if (s->has_fastopen_opt)
1736 printf(" fastopen");
d2055ea5 1737 if (s->cong_alg[0])
8250bc9f
VK
1738 printf(" %s", s->cong_alg);
1739 if (s->has_wscale_opt)
1740 printf(" wscale:%d,%d", s->snd_wscale, s->rcv_wscale);
1741 if (s->rto)
1742 printf(" rto:%g", s->rto);
1743 if (s->backoff)
1744 printf(" backoff:%u", s->backoff);
1745 if (s->rtt)
1746 printf(" rtt:%g/%g", s->rtt, s->rttvar);
1747 if (s->ato)
1748 printf(" ato:%g", s->ato);
1749
1750 if (s->qack)
1751 printf(" qack:%d", s->qack);
1752 if (s->qack & 1)
1753 printf(" bidir");
1754
1755 if (s->mss)
1756 printf(" mss:%d", s->mss);
3bf5445c 1757 if (s->cwnd)
8250bc9f
VK
1758 printf(" cwnd:%d", s->cwnd);
1759 if (s->ssthresh)
1760 printf(" ssthresh:%d", s->ssthresh);
1761
1a4dda71
ED
1762 if (s->bytes_acked)
1763 printf(" bytes_acked:%llu", s->bytes_acked);
1764 if (s->bytes_received)
1765 printf(" bytes_received:%llu", s->bytes_received);
ecb435ea
CG
1766 if (s->segs_out)
1767 printf(" segs_out:%u", s->segs_out);
1768 if (s->segs_in)
1769 printf(" segs_in:%u", s->segs_in);
414aeec9
MKL
1770 if (s->data_segs_out)
1771 printf(" data_segs_out:%u", s->data_segs_out);
1772 if (s->data_segs_in)
1773 printf(" data_segs_in:%u", s->data_segs_in);
1a4dda71 1774
8250bc9f
VK
1775 if (s->dctcp && s->dctcp->enabled) {
1776 struct dctcpstat *dctcp = s->dctcp;
1777
3bf5445c 1778 printf(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
8250bc9f
VK
1779 dctcp->ce_state, dctcp->alpha, dctcp->ab_ecn,
1780 dctcp->ab_tot);
1781 } else if (s->dctcp) {
3bf5445c 1782 printf(" dctcp:fallback_mode");
8250bc9f
VK
1783 }
1784
1785 if (s->send_bps)
1786 printf(" send %sbps", sprint_bw(b1, s->send_bps));
1787 if (s->lastsnd)
1788 printf(" lastsnd:%u", s->lastsnd);
1789 if (s->lastrcv)
1790 printf(" lastrcv:%u", s->lastrcv);
1791 if (s->lastack)
1792 printf(" lastack:%u", s->lastack);
1793
1794 if (s->pacing_rate) {
1795 printf(" pacing_rate %sbps", sprint_bw(b1, s->pacing_rate));
1796 if (s->pacing_rate_max)
1797 printf("/%sbps", sprint_bw(b1,
1798 s->pacing_rate_max));
1799 }
1800
1801 if (s->unacked)
1802 printf(" unacked:%u", s->unacked);
1803 if (s->retrans || s->retrans_total)
1804 printf(" retrans:%u/%u", s->retrans, s->retrans_total);
1805 if (s->lost)
1806 printf(" lost:%u", s->lost);
055840f2 1807 if (s->sacked && s->ss.state != SS_LISTEN)
8250bc9f
VK
1808 printf(" sacked:%u", s->sacked);
1809 if (s->fackets)
1810 printf(" fackets:%u", s->fackets);
1811 if (s->reordering != 3)
1812 printf(" reordering:%d", s->reordering);
1813 if (s->rcv_rtt)
1814 printf(" rcv_rtt:%g", s->rcv_rtt);
1815 if (s->rcv_space)
1816 printf(" rcv_space:%d", s->rcv_space);
9e99e495
SH
1817 if (s->not_sent)
1818 printf(" notsent:%u", s->not_sent);
1819 if (s->min_rtt)
1820 printf(" minrtt:%g", s->min_rtt);
8250bc9f
VK
1821}
1822
055840f2
VK
1823static void tcp_timer_print(struct tcpstat *s)
1824{
1825 if (s->timer) {
1826 if (s->timer > 4)
1827 s->timer = 5;
1828 printf(" timer:(%s,%s,%d)",
1829 tmr_name[s->timer],
1830 print_ms_timer(s->timeout),
1831 s->retrans);
1832 }
1833}
1834
8250bc9f
VK
1835static int tcp_show_line(char *line, const struct filter *f, int family)
1836{
1837 int rto = 0, ato = 0;
1838 struct tcpstat s = {};
1839 char *loc, *rem, *data;
1840 char opt[256];
1841 int n;
1842 int hz = get_user_hz();
1843
1844 if (proc_inet_split_line(line, &loc, &rem, &data))
1845 return -1;
1846
1847 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
acd1e437 1848
8250bc9f
VK
1849 if (!(f->states & (1 << state)))
1850 return 0;
1851
055840f2 1852 proc_parse_inet_addr(loc, rem, family, &s.ss);
ae665a52 1853
055840f2 1854 if (f->f && run_ssfilter(f->f, &s.ss) == 0)
aba5acdf 1855 return 0;
ae665a52 1856
aba5acdf 1857 opt[0] = 0;
e7113c61 1858 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
055840f2
VK
1859 &s.ss.state, &s.ss.wq, &s.ss.rq,
1860 &s.timer, &s.timeout, &s.retrans, &s.ss.uid, &s.probes,
1861 &s.ss.ino, &s.ss.refcnt, &s.ss.sk, &rto, &ato, &s.qack, &s.cwnd,
1862 &s.ssthresh, opt);
ae665a52 1863
aba5acdf
SH
1864 if (n < 17)
1865 opt[0] = 0;
ae665a52 1866
aba5acdf 1867 if (n < 12) {
8250bc9f 1868 rto = 0;
aba5acdf
SH
1869 s.cwnd = 2;
1870 s.ssthresh = -1;
8250bc9f 1871 ato = s.qack = 0;
aba5acdf 1872 }
ae665a52 1873
8250bc9f
VK
1874 s.retrans = s.timer != 1 ? s.probes : s.retrans;
1875 s.timeout = (s.timeout * 1000 + hz - 1) / hz;
1876 s.ato = (double)ato / hz;
1877 s.qack /= 2;
1878 s.rto = (double)rto;
1879 s.ssthresh = s.ssthresh == -1 ? 0 : s.ssthresh;
1880 s.rto = s.rto != 3 * hz ? s.rto / hz : 0;
ae665a52 1881
055840f2
VK
1882 inet_stats_print(&s.ss, IPPROTO_TCP);
1883
1884 if (show_options)
1885 tcp_timer_print(&s);
116ac927 1886
aba5acdf 1887 if (show_details) {
f1b39e1b 1888 sock_details_print(&s.ss);
aba5acdf
SH
1889 if (opt[0])
1890 printf(" opt:\"%s\"", opt);
1891 }
aba5acdf 1892
8250bc9f
VK
1893 if (show_tcpinfo)
1894 tcp_stats_print(&s);
1895
1896 printf("\n");
aba5acdf
SH
1897 return 0;
1898}
1899
ab01dbbb
SH
1900static int generic_record_read(FILE *fp,
1901 int (*worker)(char*, const struct filter *, int),
1902 const struct filter *f, int fam)
aba5acdf 1903{
ab01dbbb 1904 char line[256];
aba5acdf 1905
ab01dbbb
SH
1906 /* skip header */
1907 if (fgets(line, sizeof(line), fp) == NULL)
aba5acdf 1908 goto outerr;
ab01dbbb
SH
1909
1910 while (fgets(line, sizeof(line), fp) != NULL) {
1911 int n = strlen(line);
acd1e437 1912
ab01dbbb
SH
1913 if (n == 0 || line[n-1] != '\n') {
1914 errno = -EINVAL;
1915 return -1;
aba5acdf 1916 }
ab01dbbb 1917 line[n-1] = 0;
aba5acdf 1918
ab01dbbb
SH
1919 if (worker(line, f, fam) < 0)
1920 return 0;
1921 }
aba5acdf 1922outerr:
ab01dbbb
SH
1923
1924 return ferror(fp) ? -1 : 0;
aba5acdf 1925}
ae665a52 1926
51ff9f24
HFS
1927static void print_skmeminfo(struct rtattr *tb[], int attrtype)
1928{
1929 const __u32 *skmeminfo;
db08bdb8
VK
1930
1931 if (!tb[attrtype]) {
1932 if (attrtype == INET_DIAG_SKMEMINFO) {
1933 if (!tb[INET_DIAG_MEMINFO])
1934 return;
1935
1936 const struct inet_diag_meminfo *minfo =
1937 RTA_DATA(tb[INET_DIAG_MEMINFO]);
1938
1939 printf(" mem:(r%u,w%u,f%u,t%u)",
1940 minfo->idiag_rmem,
1941 minfo->idiag_wmem,
1942 minfo->idiag_fmem,
1943 minfo->idiag_tmem);
1944 }
51ff9f24 1945 return;
db08bdb8
VK
1946 }
1947
51ff9f24
HFS
1948 skmeminfo = RTA_DATA(tb[attrtype]);
1949
1950 printf(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
1951 skmeminfo[SK_MEMINFO_RMEM_ALLOC],
1952 skmeminfo[SK_MEMINFO_RCVBUF],
1953 skmeminfo[SK_MEMINFO_WMEM_ALLOC],
1954 skmeminfo[SK_MEMINFO_SNDBUF],
1955 skmeminfo[SK_MEMINFO_FWD_ALLOC],
1956 skmeminfo[SK_MEMINFO_WMEM_QUEUED],
1957 skmeminfo[SK_MEMINFO_OPTMEM]);
1958
1959 if (RTA_PAYLOAD(tb[attrtype]) >=
1960 (SK_MEMINFO_BACKLOG + 1) * sizeof(__u32))
1961 printf(",bl%u", skmeminfo[SK_MEMINFO_BACKLOG]);
1962
6df9c7a0
ED
1963 if (RTA_PAYLOAD(tb[attrtype]) >=
1964 (SK_MEMINFO_DROPS + 1) * sizeof(__u32))
1965 printf(",d%u", skmeminfo[SK_MEMINFO_DROPS]);
1966
51ff9f24
HFS
1967 printf(")");
1968}
1969
8250bc9f
VK
1970#define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
1971
5b816047
PE
1972static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r,
1973 struct rtattr *tb[])
7d105b56 1974{
b4b0b7d5 1975 double rtt = 0;
8250bc9f 1976 struct tcpstat s = {};
7d105b56 1977
055840f2
VK
1978 s.ss.state = r->idiag_state;
1979
db08bdb8 1980 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
7d105b56 1981
351efcde 1982 if (tb[INET_DIAG_INFO]) {
05e18118 1983 struct tcp_info *info;
351efcde 1984 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
05e18118
SH
1985
1986 /* workaround for older kernels with less fields */
1987 if (len < sizeof(*info)) {
1988 info = alloca(sizeof(*info));
351efcde 1989 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
656e8fdd 1990 memset((char *)info + len, 0, sizeof(*info) - len);
05e18118 1991 } else
351efcde 1992 info = RTA_DATA(tb[INET_DIAG_INFO]);
05e18118 1993
b4b0b7d5 1994 if (show_options) {
8250bc9f
VK
1995 s.has_ts_opt = TCPI_HAS_OPT(info, TCPI_OPT_TIMESTAMPS);
1996 s.has_sack_opt = TCPI_HAS_OPT(info, TCPI_OPT_SACK);
1997 s.has_ecn_opt = TCPI_HAS_OPT(info, TCPI_OPT_ECN);
1998 s.has_ecnseen_opt = TCPI_HAS_OPT(info, TCPI_OPT_ECN_SEEN);
1999 s.has_fastopen_opt = TCPI_HAS_OPT(info, TCPI_OPT_SYN_DATA);
b4b0b7d5 2000 }
52d5ac3f 2001
d2055ea5
ED
2002 if (tb[INET_DIAG_CONG])
2003 strncpy(s.cong_alg,
2004 rta_getattr_str(tb[INET_DIAG_CONG]),
2005 sizeof(s.cong_alg) - 1);
8250bc9f
VK
2006
2007 if (TCPI_HAS_OPT(info, TCPI_OPT_WSCALE)) {
2008 s.has_wscale_opt = true;
2009 s.snd_wscale = info->tcpi_snd_wscale;
2010 s.rcv_wscale = info->tcpi_rcv_wscale;
2011 }
ea8fc104 2012
7d105b56 2013 if (info->tcpi_rto && info->tcpi_rto != 3000000)
8250bc9f
VK
2014 s.rto = (double)info->tcpi_rto / 1000;
2015
2016 s.backoff = info->tcpi_backoff;
2017 s.rtt = (double)info->tcpi_rtt / 1000;
2018 s.rttvar = (double)info->tcpi_rttvar / 1000;
11ba90fc 2019 s.ato = (double)info->tcpi_ato / 1000;
8250bc9f
VK
2020 s.mss = info->tcpi_snd_mss;
2021 s.rcv_space = info->tcpi_rcv_space;
2022 s.rcv_rtt = (double)info->tcpi_rcv_rtt / 1000;
2023 s.lastsnd = info->tcpi_last_data_sent;
2024 s.lastrcv = info->tcpi_last_data_recv;
2025 s.lastack = info->tcpi_last_ack_recv;
2026 s.unacked = info->tcpi_unacked;
2027 s.retrans = info->tcpi_retrans;
2028 s.retrans_total = info->tcpi_total_retrans;
2029 s.lost = info->tcpi_lost;
2030 s.sacked = info->tcpi_sacked;
2031 s.reordering = info->tcpi_reordering;
2032 s.rcv_space = info->tcpi_rcv_space;
2033 s.cwnd = info->tcpi_snd_cwnd;
2034
7d105b56 2035 if (info->tcpi_snd_ssthresh < 0xFFFF)
8250bc9f 2036 s.ssthresh = info->tcpi_snd_ssthresh;
52d5ac3f 2037
b4b0b7d5 2038 rtt = (double) info->tcpi_rtt;
351efcde 2039 if (tb[INET_DIAG_VEGASINFO]) {
05e18118 2040 const struct tcpvegas_info *vinfo
351efcde 2041 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
7d105b56 2042
ae665a52 2043 if (vinfo->tcpv_enabled &&
8250bc9f 2044 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
ea8fc104 2045 rtt = vinfo->tcpv_rtt;
b4b0b7d5
SH
2046 }
2047
907e1aca 2048 if (tb[INET_DIAG_DCTCPINFO]) {
8250bc9f
VK
2049 struct dctcpstat *dctcp = malloc(sizeof(struct
2050 dctcpstat));
2051
907e1aca
DB
2052 const struct tcp_dctcp_info *dinfo
2053 = RTA_DATA(tb[INET_DIAG_DCTCPINFO]);
2054
8250bc9f
VK
2055 dctcp->enabled = !!dinfo->dctcp_enabled;
2056 dctcp->ce_state = dinfo->dctcp_ce_state;
2057 dctcp->alpha = dinfo->dctcp_alpha;
2058 dctcp->ab_ecn = dinfo->dctcp_ab_ecn;
2059 dctcp->ab_tot = dinfo->dctcp_ab_tot;
2060 s.dctcp = dctcp;
907e1aca
DB
2061 }
2062
b4b0b7d5 2063 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
8250bc9f
VK
2064 s.send_bps = (double) info->tcpi_snd_cwnd *
2065 (double)info->tcpi_snd_mss * 8000000. / rtt;
7d105b56 2066 }
b4b0b7d5 2067
eb6028b2 2068 if (info->tcpi_pacing_rate &&
8250bc9f
VK
2069 info->tcpi_pacing_rate != ~0ULL) {
2070 s.pacing_rate = info->tcpi_pacing_rate * 8.;
eb6028b2
ED
2071
2072 if (info->tcpi_max_pacing_rate &&
8250bc9f
VK
2073 info->tcpi_max_pacing_rate != ~0ULL)
2074 s.pacing_rate_max = info->tcpi_max_pacing_rate * 8.;
eb6028b2 2075 }
1a4dda71
ED
2076 s.bytes_acked = info->tcpi_bytes_acked;
2077 s.bytes_received = info->tcpi_bytes_received;
ecb435ea
CG
2078 s.segs_out = info->tcpi_segs_out;
2079 s.segs_in = info->tcpi_segs_in;
414aeec9
MKL
2080 s.data_segs_out = info->tcpi_data_segs_out;
2081 s.data_segs_in = info->tcpi_data_segs_in;
9e99e495 2082 s.not_sent = info->tcpi_notsent_bytes;
d9ba887e
ED
2083 if (info->tcpi_min_rtt && info->tcpi_min_rtt != ~0U)
2084 s.min_rtt = (double) info->tcpi_min_rtt / 1000;
8250bc9f 2085 tcp_stats_print(&s);
92de1c2c 2086 free(s.dctcp);
77a8ca81 2087 }
77a8ca81
PE
2088}
2089
82d73ea0 2090static void parse_diag_msg(struct nlmsghdr *nlh, struct sockstat *s)
aba5acdf 2091{
acd1e437 2092 struct rtattr *tb[INET_DIAG_MAX+1];
351efcde 2093 struct inet_diag_msg *r = NLMSG_DATA(nlh);
aba5acdf 2094
acd1e437 2095 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr *)(r+1),
5b816047
PE
2096 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2097
82d73ea0
DA
2098 s->state = r->idiag_state;
2099 s->local.family = s->remote.family = r->idiag_family;
2100 s->lport = ntohs(r->id.idiag_sport);
2101 s->rport = ntohs(r->id.idiag_dport);
2102 s->wq = r->idiag_wqueue;
2103 s->rq = r->idiag_rqueue;
2104 s->ino = r->idiag_inode;
2105 s->uid = r->idiag_uid;
2106 s->iface = r->id.idiag_if;
2107 s->sk = cookie_sk_get(&r->id.idiag_cookie[0]);
2108
2109 if (s->local.family == AF_INET)
2110 s->local.bytelen = s->remote.bytelen = 4;
2111 else
2112 s->local.bytelen = s->remote.bytelen = 16;
8250bc9f 2113
82d73ea0
DA
2114 memcpy(s->local.data, r->id.idiag_src, s->local.bytelen);
2115 memcpy(s->remote.data, r->id.idiag_dst, s->local.bytelen);
2116}
aba5acdf 2117
82d73ea0
DA
2118static int inet_show_sock(struct nlmsghdr *nlh,
2119 struct sockstat *s,
2120 int protocol)
2121{
2122 struct rtattr *tb[INET_DIAG_MAX+1];
2123 struct inet_diag_msg *r = NLMSG_DATA(nlh);
2124
2125 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr *)(r+1),
2126 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
aba5acdf 2127
6885e3bf
CG
2128 if (tb[INET_DIAG_PROTOCOL])
2129 protocol = *(__u8 *)RTA_DATA(tb[INET_DIAG_PROTOCOL]);
2130
82d73ea0 2131 inet_stats_print(s, protocol);
116ac927 2132
055840f2
VK
2133 if (show_options) {
2134 struct tcpstat t = {};
2135
2136 t.timer = r->idiag_timer;
2137 t.timeout = r->idiag_expires;
2138 t.retrans = r->idiag_retrans;
2139 tcp_timer_print(&t);
2140 }
2141
aba5acdf 2142 if (show_details) {
82d73ea0
DA
2143 sock_details_print(s);
2144 if (s->local.family == AF_INET6 && tb[INET_DIAG_SKV6ONLY]) {
f32dc746 2145 unsigned char v6only;
acd1e437 2146
f32dc746
PS
2147 v6only = *(__u8 *)RTA_DATA(tb[INET_DIAG_SKV6ONLY]);
2148 printf(" v6only:%u", v6only);
2149 }
5b816047
PE
2150 if (tb[INET_DIAG_SHUTDOWN]) {
2151 unsigned char mask;
acd1e437 2152
5b816047
PE
2153 mask = *(__u8 *)RTA_DATA(tb[INET_DIAG_SHUTDOWN]);
2154 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2155 }
aba5acdf 2156 }
8250bc9f 2157
aba5acdf 2158 if (show_mem || show_tcpinfo) {
7d105b56 2159 printf("\n\t");
5b816047 2160 tcp_show_info(nlh, r, tb);
aba5acdf 2161 }
7d105b56 2162
aba5acdf 2163 printf("\n");
aba5acdf 2164 return 0;
aba5acdf
SH
2165}
2166
746a695f 2167static int tcpdiag_send(int fd, int protocol, struct filter *f)
aba5acdf 2168{
d17b136f 2169 struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
aba5acdf
SH
2170 struct {
2171 struct nlmsghdr nlh;
351efcde 2172 struct inet_diag_req r;
d17b136f
PS
2173 } req = {
2174 .nlh.nlmsg_len = sizeof(req),
2175 .nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST,
2176 .nlh.nlmsg_seq = MAGIC_SEQ,
2177 .r.idiag_family = AF_INET,
2178 .r.idiag_states = f->states,
2179 };
aba5acdf
SH
2180 char *bc = NULL;
2181 int bclen;
2182 struct msghdr msg;
2183 struct rtattr rta;
aba5acdf 2184 struct iovec iov[3];
376fb868 2185 int iovlen = 1;
aba5acdf 2186
346f8ca8
PE
2187 if (protocol == IPPROTO_UDP)
2188 return -1;
2189
3fe5b534
PE
2190 if (protocol == IPPROTO_TCP)
2191 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
2192 else
2193 req.nlh.nlmsg_type = DCCPDIAG_GETSOCK;
910b0397 2194 if (show_mem) {
ae665a52 2195 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
910b0397
SW
2196 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
2197 }
b4b0b7d5 2198
7d105b56 2199 if (show_tcpinfo) {
351efcde
SH
2200 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
2201 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
2202 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
7d105b56 2203 }
aba5acdf 2204
ae665a52
SH
2205 iov[0] = (struct iovec){
2206 .iov_base = &req,
2207 .iov_len = sizeof(req)
ea8fc104 2208 };
aba5acdf
SH
2209 if (f->f) {
2210 bclen = ssfilter_bytecompile(f->f, &bc);
376fb868
DA
2211 if (bclen) {
2212 rta.rta_type = INET_DIAG_REQ_BYTECODE;
2213 rta.rta_len = RTA_LENGTH(bclen);
2214 iov[1] = (struct iovec){ &rta, sizeof(rta) };
2215 iov[2] = (struct iovec){ bc, bclen };
2216 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
2217 iovlen = 3;
2218 }
aba5acdf
SH
2219 }
2220
2221 msg = (struct msghdr) {
acd1e437 2222 .msg_name = (void *)&nladdr,
ea8fc104 2223 .msg_namelen = sizeof(nladdr),
ae665a52 2224 .msg_iov = iov,
376fb868 2225 .msg_iovlen = iovlen,
aba5acdf
SH
2226 };
2227
930a75f9
ED
2228 if (sendmsg(fd, &msg, 0) < 0) {
2229 close(fd);
aba5acdf 2230 return -1;
930a75f9 2231 }
aba5acdf 2232
746a695f
PE
2233 return 0;
2234}
2235
886d19d6
PE
2236static int sockdiag_send(int family, int fd, int protocol, struct filter *f)
2237{
d17b136f 2238 struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
5fb421d4 2239 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
886d19d6
PE
2240 char *bc = NULL;
2241 int bclen;
2242 struct msghdr msg;
2243 struct rtattr rta;
2244 struct iovec iov[3];
376fb868 2245 int iovlen = 1;
886d19d6
PE
2246
2247 if (family == PF_UNSPEC)
2248 return tcpdiag_send(fd, protocol, f);
2249
886d19d6
PE
2250 memset(&req.r, 0, sizeof(req.r));
2251 req.r.sdiag_family = family;
2252 req.r.sdiag_protocol = protocol;
2253 req.r.idiag_states = f->states;
2254 if (show_mem) {
2255 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
2256 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
2257 }
2258
2259 if (show_tcpinfo) {
2260 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
2261 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
2262 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
2263 }
2264
2265 iov[0] = (struct iovec){
2266 .iov_base = &req,
2267 .iov_len = sizeof(req)
2268 };
2269 if (f->f) {
2270 bclen = ssfilter_bytecompile(f->f, &bc);
376fb868
DA
2271 if (bclen) {
2272 rta.rta_type = INET_DIAG_REQ_BYTECODE;
2273 rta.rta_len = RTA_LENGTH(bclen);
2274 iov[1] = (struct iovec){ &rta, sizeof(rta) };
2275 iov[2] = (struct iovec){ bc, bclen };
2276 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
2277 iovlen = 3;
2278 }
886d19d6
PE
2279 }
2280
2281 msg = (struct msghdr) {
acd1e437 2282 .msg_name = (void *)&nladdr,
886d19d6
PE
2283 .msg_namelen = sizeof(nladdr),
2284 .msg_iov = iov,
376fb868 2285 .msg_iovlen = iovlen,
886d19d6
PE
2286 };
2287
2288 if (sendmsg(fd, &msg, 0) < 0) {
2289 close(fd);
2290 return -1;
2291 }
2292
2293 return 0;
2294}
2295
486ccd99
VK
2296struct inet_diag_arg {
2297 struct filter *f;
2298 int protocol;
fb2594c1 2299 struct rtnl_handle *rth;
486ccd99 2300};
aba5acdf 2301
b38e7409 2302static int kill_inet_sock(struct nlmsghdr *h, void *arg)
fb2594c1
LC
2303{
2304 struct inet_diag_msg *d = NLMSG_DATA(h);
2305 struct inet_diag_arg *diag_arg = arg;
2306 struct rtnl_handle *rth = diag_arg->rth;
acd1e437 2307
fb2594c1
LC
2308 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
2309
2310 req.nlh.nlmsg_type = SOCK_DESTROY;
2311 req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2312 req.nlh.nlmsg_seq = ++rth->seq;
2313 req.r.sdiag_family = d->idiag_family;
2314 req.r.sdiag_protocol = diag_arg->protocol;
2315 req.r.id = d->id;
2316
2317 return rtnl_talk(rth, &req.nlh, NULL, 0);
2318}
2319
486ccd99
VK
2320static int show_one_inet_sock(const struct sockaddr_nl *addr,
2321 struct nlmsghdr *h, void *arg)
2322{
2323 int err;
2324 struct inet_diag_arg *diag_arg = arg;
2325 struct inet_diag_msg *r = NLMSG_DATA(h);
82d73ea0 2326 struct sockstat s = {};
aba5acdf 2327
486ccd99
VK
2328 if (!(diag_arg->f->families & (1 << r->idiag_family)))
2329 return 0;
82d73ea0
DA
2330
2331 parse_diag_msg(h, &s);
2332
2333 if (diag_arg->f->f && run_ssfilter(diag_arg->f->f, &s) == 0)
2334 return 0;
2335
b38e7409 2336 if (diag_arg->f->kill && kill_inet_sock(h, arg) != 0) {
fb2594c1
LC
2337 if (errno == EOPNOTSUPP || errno == ENOENT) {
2338 /* Socket can't be closed, or is already closed. */
2339 return 0;
2340 } else {
2341 perror("SOCK_DESTROY answers");
2342 return -1;
2343 }
2344 }
82d73ea0
DA
2345
2346 err = inet_show_sock(h, &s, diag_arg->protocol);
2347 if (err < 0)
486ccd99 2348 return err;
aba5acdf 2349
486ccd99
VK
2350 return 0;
2351}
886d19d6 2352
486ccd99
VK
2353static int inet_show_netlink(struct filter *f, FILE *dump_fp, int protocol)
2354{
2355 int err = 0;
fb2594c1 2356 struct rtnl_handle rth, rth2;
486ccd99
VK
2357 int family = PF_INET;
2358 struct inet_diag_arg arg = { .f = f, .protocol = protocol };
886d19d6 2359
486ccd99
VK
2360 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
2361 return -1;
fb2594c1
LC
2362
2363 if (f->kill) {
2364 if (rtnl_open_byproto(&rth2, 0, NETLINK_SOCK_DIAG)) {
2365 rtnl_close(&rth);
2366 return -1;
2367 }
2368 arg.rth = &rth2;
2369 }
2370
486ccd99
VK
2371 rth.dump = MAGIC_SEQ;
2372 rth.dump_fp = dump_fp;
518af1e0
ED
2373 if (preferred_family == PF_INET6)
2374 family = PF_INET6;
886d19d6 2375
486ccd99
VK
2376again:
2377 if ((err = sockdiag_send(family, rth.fd, protocol, f)))
2378 goto Exit;
aba5acdf 2379
486ccd99
VK
2380 if ((err = rtnl_dump_filter(&rth, show_one_inet_sock, &arg))) {
2381 if (family != PF_UNSPEC) {
2382 family = PF_UNSPEC;
2383 goto again;
aba5acdf 2384 }
486ccd99 2385 goto Exit;
aba5acdf 2386 }
518af1e0 2387 if (family == PF_INET && preferred_family != PF_INET) {
886d19d6
PE
2388 family = PF_INET6;
2389 goto again;
2390 }
2391
486ccd99
VK
2392Exit:
2393 rtnl_close(&rth);
fb2594c1
LC
2394 if (arg.rth)
2395 rtnl_close(arg.rth);
486ccd99 2396 return err;
aba5acdf
SH
2397}
2398
ab01dbbb 2399static int tcp_show_netlink_file(struct filter *f)
aba5acdf
SH
2400{
2401 FILE *fp;
e557212e 2402 char buf[16384];
aba5acdf
SH
2403
2404 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
2405 perror("fopen($TCPDIAG_FILE)");
2406 return -1;
2407 }
2408
2409 while (1) {
2410 int status, err;
acd1e437 2411 struct nlmsghdr *h = (struct nlmsghdr *)buf;
82d73ea0 2412 struct sockstat s = {};
aba5acdf
SH
2413
2414 status = fread(buf, 1, sizeof(*h), fp);
2415 if (status < 0) {
2416 perror("Reading header from $TCPDIAG_FILE");
2417 return -1;
2418 }
2419 if (status != sizeof(*h)) {
2420 perror("Unexpected EOF reading $TCPDIAG_FILE");
2421 return -1;
2422 }
2423
2424 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
2425
2426 if (status < 0) {
2427 perror("Reading $TCPDIAG_FILE");
2428 return -1;
2429 }
2430 if (status + sizeof(*h) < h->nlmsg_len) {
2431 perror("Unexpected EOF reading $TCPDIAG_FILE");
2432 return -1;
2433 }
2434
2435 /* The only legal exit point */
2436 if (h->nlmsg_type == NLMSG_DONE)
2437 return 0;
2438
2439 if (h->nlmsg_type == NLMSG_ERROR) {
acd1e437
SH
2440 struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(h);
2441
aba5acdf
SH
2442 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2443 fprintf(stderr, "ERROR truncated\n");
2444 } else {
2445 errno = -err->error;
2446 perror("TCPDIAG answered");
2447 }
2448 return -1;
2449 }
2450
82d73ea0
DA
2451 parse_diag_msg(h, &s);
2452
2453 if (f && f->f && run_ssfilter(f->f, &s) == 0)
2454 continue;
2455
2456 err = inet_show_sock(h, &s, IPPROTO_TCP);
aba5acdf
SH
2457 if (err < 0)
2458 return err;
2459 }
2460}
2461
ab01dbbb 2462static int tcp_show(struct filter *f, int socktype)
aba5acdf 2463{
ab01dbbb 2464 FILE *fp = NULL;
aba5acdf
SH
2465 char *buf = NULL;
2466 int bufsize = 64*1024;
2467
1527a17e
VK
2468 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2469 return 0;
2470
aba5acdf
SH
2471 dg_proto = TCP_PROTO;
2472
2473 if (getenv("TCPDIAG_FILE"))
2474 return tcp_show_netlink_file(f);
2475
2476 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3fe5b534 2477 && inet_show_netlink(f, NULL, socktype) == 0)
aba5acdf
SH
2478 return 0;
2479
2480 /* Sigh... We have to parse /proc/net/tcp... */
2481
ab01dbbb 2482
aba5acdf
SH
2483 /* Estimate amount of sockets and try to allocate
2484 * huge buffer to read all the table at one read.
2485 * Limit it by 16MB though. The assumption is: as soon as
2486 * kernel was able to hold information about N connections,
2487 * it is able to give us some memory for snapshot.
2488 */
2489 if (1) {
a221d621
BL
2490 get_slabstat(&slabstat);
2491
aba5acdf 2492 int guess = slabstat.socks+slabstat.tcp_syns;
acd1e437 2493
aba5acdf
SH
2494 if (f->states&(1<<SS_TIME_WAIT))
2495 guess += slabstat.tcp_tws;
2496 if (guess > (16*1024*1024)/128)
2497 guess = (16*1024*1024)/128;
2498 guess *= 128;
2499 if (guess > bufsize)
2500 bufsize = guess;
2501 }
2502 while (bufsize >= 64*1024) {
2503 if ((buf = malloc(bufsize)) != NULL)
2504 break;
2505 bufsize /= 2;
2506 }
2507 if (buf == NULL) {
2508 errno = ENOMEM;
2509 return -1;
2510 }
2511
2512 if (f->families & (1<<AF_INET)) {
69cae645 2513 if ((fp = net_tcp_open()) == NULL)
aba5acdf 2514 goto outerr;
ab01dbbb
SH
2515
2516 setbuffer(fp, buf, bufsize);
2517 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
aba5acdf 2518 goto outerr;
ab01dbbb 2519 fclose(fp);
aba5acdf
SH
2520 }
2521
2522 if ((f->families & (1<<AF_INET6)) &&
69cae645 2523 (fp = net_tcp6_open()) != NULL) {
ab01dbbb
SH
2524 setbuffer(fp, buf, bufsize);
2525 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
aba5acdf 2526 goto outerr;
ab01dbbb 2527 fclose(fp);
aba5acdf
SH
2528 }
2529
2530 free(buf);
2531 return 0;
2532
2533outerr:
2534 do {
2535 int saved_errno = errno;
acd1e437 2536
92de1c2c 2537 free(buf);
ab01dbbb
SH
2538 if (fp)
2539 fclose(fp);
aba5acdf
SH
2540 errno = saved_errno;
2541 return -1;
2542 } while (0);
2543}
2544
2545
d1f28cf1 2546static int dgram_show_line(char *line, const struct filter *f, int family)
aba5acdf 2547{
055840f2 2548 struct sockstat s = {};
aba5acdf
SH
2549 char *loc, *rem, *data;
2550 char opt[256];
2551 int n;
aba5acdf 2552
8250bc9f 2553 if (proc_inet_split_line(line, &loc, &rem, &data))
aba5acdf 2554 return -1;
aba5acdf 2555
8250bc9f 2556 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
acd1e437 2557
8250bc9f
VK
2558 if (!(f->states & (1 << state)))
2559 return 0;
aba5acdf 2560
8250bc9f 2561 proc_parse_inet_addr(loc, rem, family, &s);
aba5acdf
SH
2562
2563 if (f->f && run_ssfilter(f->f, &s) == 0)
2564 return 0;
2565
2566 opt[0] = 0;
e7113c61 2567 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
aba5acdf
SH
2568 &s.state, &s.wq, &s.rq,
2569 &s.uid, &s.ino,
2570 &s.refcnt, &s.sk, opt);
2571
2572 if (n < 9)
2573 opt[0] = 0;
2574
235c4453 2575 inet_stats_print(&s, dg_proto == UDP_PROTO ? IPPROTO_UDP : 0);
aba5acdf 2576
f1b39e1b
VK
2577 if (show_details && opt[0])
2578 printf(" opt:\"%s\"", opt);
aba5acdf 2579
8250bc9f 2580 printf("\n");
aba5acdf
SH
2581 return 0;
2582}
2583
d1f28cf1 2584static int udp_show(struct filter *f)
aba5acdf 2585{
ab01dbbb 2586 FILE *fp = NULL;
aba5acdf 2587
1527a17e
VK
2588 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2589 return 0;
2590
ace5cb31
VK
2591 dg_proto = UDP_PROTO;
2592
346f8ca8
PE
2593 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
2594 && inet_show_netlink(f, NULL, IPPROTO_UDP) == 0)
2595 return 0;
2596
aba5acdf 2597 if (f->families&(1<<AF_INET)) {
69cae645 2598 if ((fp = net_udp_open()) == NULL)
aba5acdf 2599 goto outerr;
ab01dbbb 2600 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
aba5acdf 2601 goto outerr;
ab01dbbb 2602 fclose(fp);
aba5acdf
SH
2603 }
2604
2605 if ((f->families&(1<<AF_INET6)) &&
69cae645 2606 (fp = net_udp6_open()) != NULL) {
ab01dbbb 2607 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
aba5acdf 2608 goto outerr;
ab01dbbb 2609 fclose(fp);
aba5acdf
SH
2610 }
2611 return 0;
2612
2613outerr:
2614 do {
2615 int saved_errno = errno;
acd1e437 2616
ab01dbbb
SH
2617 if (fp)
2618 fclose(fp);
aba5acdf
SH
2619 errno = saved_errno;
2620 return -1;
2621 } while (0);
2622}
2623
d1f28cf1 2624static int raw_show(struct filter *f)
aba5acdf 2625{
ab01dbbb 2626 FILE *fp = NULL;
aba5acdf 2627
1527a17e
VK
2628 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2629 return 0;
2630
aba5acdf
SH
2631 dg_proto = RAW_PROTO;
2632
2633 if (f->families&(1<<AF_INET)) {
69cae645 2634 if ((fp = net_raw_open()) == NULL)
aba5acdf 2635 goto outerr;
ab01dbbb 2636 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
aba5acdf 2637 goto outerr;
ab01dbbb 2638 fclose(fp);
aba5acdf
SH
2639 }
2640
2641 if ((f->families&(1<<AF_INET6)) &&
69cae645 2642 (fp = net_raw6_open()) != NULL) {
ab01dbbb 2643 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
aba5acdf 2644 goto outerr;
ab01dbbb 2645 fclose(fp);
aba5acdf
SH
2646 }
2647 return 0;
2648
2649outerr:
2650 do {
2651 int saved_errno = errno;
acd1e437 2652
ab01dbbb
SH
2653 if (fp)
2654 fclose(fp);
aba5acdf
SH
2655 errno = saved_errno;
2656 return -1;
2657 } while (0);
2658}
2659
aba5acdf
SH
2660int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
2661 SS_ESTABLISHED, SS_CLOSING };
2662
ec4d0d8a 2663#define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
aba5acdf 2664
ec4d0d8a 2665static void unix_list_free(struct sockstat *list)
aba5acdf
SH
2666{
2667 while (list) {
ec4d0d8a 2668 struct sockstat *s = list;
ec4d0d8a 2669
aba5acdf 2670 list = list->next;
99bb68ff 2671 free(s->name);
aba5acdf
SH
2672 free(s);
2673 }
2674}
2675
30b669d7
MY
2676static const char *unix_netid_name(int type)
2677{
2678 const char *netid;
2679
2680 switch (type) {
2681 case SOCK_STREAM:
2682 netid = "u_str";
2683 break;
2684 case SOCK_SEQPACKET:
2685 netid = "u_seq";
2686 break;
2687 case SOCK_DGRAM:
2688 default:
2689 netid = "u_dgr";
2690 break;
2691 }
2692 return netid;
2693}
2694
ec4d0d8a 2695static bool unix_type_skip(struct sockstat *s, struct filter *f)
bf4ceee6
VK
2696{
2697 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2698 return true;
2699 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2700 return true;
2701 if (s->type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2702 return true;
2703 return false;
2704}
2705
ec4d0d8a
VK
2706static bool unix_use_proc(void)
2707{
2708 return getenv("PROC_NET_UNIX") || getenv("PROC_ROOT");
2709}
2710
2711static void unix_stats_print(struct sockstat *list, struct filter *f)
aba5acdf 2712{
ec4d0d8a 2713 struct sockstat *s;
99bb68ff 2714 char *peer;
b217df10 2715 char *ctx_buf = NULL;
ec4d0d8a 2716 bool use_proc = unix_use_proc();
b217df10 2717 char port_name[30] = {};
aba5acdf
SH
2718
2719 for (s = list; s; s = s->next) {
ec4d0d8a 2720 if (!(f->states & (1 << s->state)))
aba5acdf 2721 continue;
bf4ceee6 2722 if (unix_type_skip(s, f))
30b669d7 2723 continue;
aba5acdf 2724
99bb68ff
VK
2725 peer = "*";
2726 if (s->peer_name)
2727 peer = s->peer_name;
ec4d0d8a
VK
2728
2729 if (s->rport && use_proc) {
2730 struct sockstat *p;
bf4ceee6 2731
aba5acdf 2732 for (p = list; p; p = p->next) {
ec4d0d8a 2733 if (s->rport == p->lport)
aba5acdf
SH
2734 break;
2735 }
ec4d0d8a 2736
aba5acdf
SH
2737 if (!p) {
2738 peer = "?";
2739 } else {
99bb68ff 2740 peer = p->name ? : "*";
aba5acdf
SH
2741 }
2742 }
2743
29999b0f 2744 if (use_proc && f->f) {
d17b136f
PS
2745 struct sockstat st = {
2746 .local.family = AF_UNIX,
2747 .remote.family = AF_UNIX,
2748 };
acd1e437 2749
99bb68ff 2750 memcpy(st.local.data, &s->name, sizeof(s->name));
d17b136f 2751 if (strcmp(peer, "*"))
99bb68ff
VK
2752 memcpy(st.remote.data, &peer, sizeof(peer));
2753 if (run_ssfilter(f->f, &st) == 0)
aba5acdf
SH
2754 continue;
2755 }
2756
2d791bc8
VK
2757 sock_state_print(s, unix_netid_name(s->type));
2758
99bb68ff 2759 sock_addr_print(s->name ?: "*", " ",
b217df10
VK
2760 int_to_str(s->lport, port_name), NULL);
2761 sock_addr_print(peer, " ", int_to_str(s->rport, port_name),
2762 NULL);
116ac927
RH
2763
2764 if (show_proc_ctx || show_sock_ctx) {
b217df10 2765 if (find_entry(s->ino, &ctx_buf,
116ac927
RH
2766 (show_proc_ctx & show_sock_ctx) ?
2767 PROC_SOCK_CTX : PROC_CTX) > 0) {
b217df10
VK
2768 printf(" users:(%s)", ctx_buf);
2769 free(ctx_buf);
116ac927
RH
2770 }
2771 } else if (show_users) {
b217df10
VK
2772 if (find_entry(s->ino, &ctx_buf, USERS) > 0) {
2773 printf(" users:(%s)", ctx_buf);
2774 free(ctx_buf);
116ac927 2775 }
aba5acdf
SH
2776 }
2777 printf("\n");
2778 }
2779}
2780
8a4025f6 2781static int unix_show_sock(const struct sockaddr_nl *addr, struct nlmsghdr *nlh,
2782 void *arg)
dfbaa90d 2783{
8a4025f6 2784 struct filter *f = (struct filter *)arg;
dfbaa90d
PE
2785 struct unix_diag_msg *r = NLMSG_DATA(nlh);
2786 struct rtattr *tb[UNIX_DIAG_MAX+1];
99bb68ff
VK
2787 char name[128];
2788 struct sockstat stat = { .name = "*", .peer_name = "*" };
dfbaa90d 2789
acd1e437 2790 parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr *)(r+1),
dfbaa90d
PE
2791 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2792
bf4ceee6
VK
2793 stat.type = r->udiag_type;
2794 stat.state = r->udiag_state;
ec4d0d8a
VK
2795 stat.ino = stat.lport = r->udiag_ino;
2796 stat.local.family = stat.remote.family = AF_UNIX;
0d2e01c5 2797
bf4ceee6
VK
2798 if (unix_type_skip(&stat, f))
2799 return 0;
dfbaa90d 2800
defd61ca
HFS
2801 if (tb[UNIX_DIAG_RQLEN]) {
2802 struct unix_diag_rqlen *rql = RTA_DATA(tb[UNIX_DIAG_RQLEN]);
acd1e437 2803
bf4ceee6
VK
2804 stat.rq = rql->udiag_rqueue;
2805 stat.wq = rql->udiag_wqueue;
defd61ca 2806 }
dfbaa90d
PE
2807 if (tb[UNIX_DIAG_NAME]) {
2808 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
2809
2810 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
2811 name[len] = '\0';
2812 if (name[0] == '\0')
2813 name[0] = '@';
99bb68ff
VK
2814 stat.name = &name[0];
2815 memcpy(stat.local.data, &stat.name, sizeof(stat.name));
bf4ceee6 2816 }
dfbaa90d 2817 if (tb[UNIX_DIAG_PEER])
ec4d0d8a 2818 stat.rport = rta_getattr_u32(tb[UNIX_DIAG_PEER]);
dfbaa90d 2819
29999b0f
VK
2820 if (f->f && run_ssfilter(f->f, &stat) == 0)
2821 return 0;
2822
bf4ceee6 2823 unix_stats_print(&stat, f);
dfbaa90d 2824
51ff9f24 2825 if (show_mem) {
bf4ceee6 2826 printf("\t");
51ff9f24
HFS
2827 print_skmeminfo(tb, UNIX_DIAG_MEMINFO);
2828 }
5b816047
PE
2829 if (show_details) {
2830 if (tb[UNIX_DIAG_SHUTDOWN]) {
2831 unsigned char mask;
acd1e437 2832
5b816047
PE
2833 mask = *(__u8 *)RTA_DATA(tb[UNIX_DIAG_SHUTDOWN]);
2834 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2835 }
2836 }
bf4ceee6
VK
2837 if (show_mem || show_details)
2838 printf("\n");
ec4d0d8a 2839
dfbaa90d
PE
2840 return 0;
2841}
2842
8a4025f6 2843static int handle_netlink_request(struct filter *f, struct nlmsghdr *req,
2844 size_t size, rtnl_filter_t show_one_sock)
dfbaa90d 2845{
8a4025f6 2846 int ret = -1;
2847 struct rtnl_handle rth;
dfbaa90d 2848
8a4025f6 2849 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
dfbaa90d
PE
2850 return -1;
2851
8a4025f6 2852 rth.dump = MAGIC_SEQ;
dfbaa90d 2853
8a4025f6 2854 if (rtnl_send(&rth, req, size) < 0)
2855 goto Exit;
dfbaa90d 2856
8a4025f6 2857 if (rtnl_dump_filter(&rth, show_one_sock, f))
2858 goto Exit;
dfbaa90d 2859
8a4025f6 2860 ret = 0;
2861Exit:
2862 rtnl_close(&rth);
2863 return ret;
dfbaa90d
PE
2864}
2865
8a4025f6 2866static int unix_show_netlink(struct filter *f)
d8402b96 2867{
5fb421d4 2868 DIAG_REQUEST(req, struct unix_diag_req r);
d8402b96
AV
2869
2870 req.r.sdiag_family = AF_UNIX;
2871 req.r.udiag_states = f->states;
2872 req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
2873 if (show_mem)
2874 req.r.udiag_show |= UDIAG_SHOW_MEMINFO;
2875
8a4025f6 2876 return handle_netlink_request(f, &req.nlh, sizeof(req), unix_show_sock);
d8402b96
AV
2877}
2878
d1f28cf1 2879static int unix_show(struct filter *f)
aba5acdf
SH
2880{
2881 FILE *fp;
2882 char buf[256];
2883 char name[128];
2884 int newformat = 0;
2885 int cnt;
ec4d0d8a 2886 struct sockstat *list = NULL;
aba5acdf 2887
9db7bf15
VK
2888 if (!filter_af_get(f, AF_UNIX))
2889 return 0;
2890
ec4d0d8a 2891 if (!unix_use_proc() && unix_show_netlink(f) == 0)
dfbaa90d
PE
2892 return 0;
2893
ab01dbbb 2894 if ((fp = net_unix_open()) == NULL)
aba5acdf 2895 return -1;
61170fd8 2896 if (!fgets(buf, sizeof(buf), fp)) {
d572ed4d
PS
2897 fclose(fp);
2898 return -1;
2899 }
aba5acdf 2900
ae665a52 2901 if (memcmp(buf, "Peer", 4) == 0)
aba5acdf
SH
2902 newformat = 1;
2903 cnt = 0;
2904
61170fd8 2905 while (fgets(buf, sizeof(buf), fp)) {
ec4d0d8a 2906 struct sockstat *u, **insp;
aba5acdf
SH
2907 int flags;
2908
0ee9052f 2909 if (!(u = calloc(1, sizeof(*u))))
aba5acdf 2910 break;
99bb68ff
VK
2911 u->name = NULL;
2912 u->peer_name = NULL;
aba5acdf
SH
2913
2914 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
ec4d0d8a 2915 &u->rport, &u->rq, &u->wq, &flags, &u->type,
aba5acdf
SH
2916 &u->state, &u->ino, name) < 8)
2917 name[0] = 0;
2918
ec4d0d8a
VK
2919 u->lport = u->ino;
2920 u->local.family = u->remote.family = AF_UNIX;
2921
2922 if (flags & (1 << 16)) {
aba5acdf
SH
2923 u->state = SS_LISTEN;
2924 } else {
2925 u->state = unix_state_map[u->state-1];
ec4d0d8a 2926 if (u->type == SOCK_DGRAM && u->state == SS_CLOSE && u->rport)
aba5acdf
SH
2927 u->state = SS_ESTABLISHED;
2928 }
2929
2930 if (!newformat) {
ec4d0d8a 2931 u->rport = 0;
aba5acdf
SH
2932 u->rq = 0;
2933 u->wq = 0;
2934 }
2935
2936 insp = &list;
2937 while (*insp) {
2938 if (u->type < (*insp)->type ||
2939 (u->type == (*insp)->type &&
2940 u->ino < (*insp)->ino))
2941 break;
2942 insp = &(*insp)->next;
2943 }
2944 u->next = *insp;
2945 *insp = u;
2946
2947 if (name[0]) {
99bb68ff
VK
2948 if ((u->name = malloc(strlen(name)+1)) == NULL)
2949 break;
2950 strcpy(u->name, name);
aba5acdf
SH
2951 }
2952 if (++cnt > MAX_UNIX_REMEMBER) {
bf4ceee6 2953 unix_stats_print(list, f);
aba5acdf
SH
2954 unix_list_free(list);
2955 list = NULL;
2956 cnt = 0;
2957 }
2958 }
a3fd8e58 2959 fclose(fp);
aba5acdf 2960 if (list) {
bf4ceee6 2961 unix_stats_print(list, f);
aba5acdf
SH
2962 unix_list_free(list);
2963 list = NULL;
2964 cnt = 0;
2965 }
2966
2967 return 0;
2968}
2969
89f634f9 2970static int packet_stats_print(struct sockstat *s, const struct filter *f)
4a0053b6
VK
2971{
2972 char *buf = NULL;
b217df10
VK
2973 const char *addr, *port;
2974 char ll_name[16];
372c30d2 2975
4a0053b6 2976 if (f->f) {
89f634f9
VK
2977 s->local.family = AF_PACKET;
2978 s->remote.family = AF_PACKET;
89f634f9 2979 s->local.data[0] = s->prot;
89f634f9 2980 if (run_ssfilter(f->f, s) == 0)
4a0053b6
VK
2981 return 1;
2982 }
372c30d2 2983
2d791bc8 2984 sock_state_print(s, s->type == SOCK_RAW ? "p_raw" : "p_dgr");
372c30d2 2985
b217df10
VK
2986 if (s->prot == 3)
2987 addr = "*";
2988 else
2989 addr = ll_proto_n2a(htons(s->prot), ll_name, sizeof(ll_name));
2990
2991 if (s->iface == 0)
2992 port = "*";
2993 else
2994 port = xll_index_to_name(s->iface);
372c30d2 2995
b217df10
VK
2996 sock_addr_print(addr, ":", port, NULL);
2997 sock_addr_print("", "*", "", NULL);
116ac927
RH
2998
2999 if (show_proc_ctx || show_sock_ctx) {
4a0053b6
VK
3000 if (find_entry(s->ino, &buf,
3001 (show_proc_ctx & show_sock_ctx) ?
3002 PROC_SOCK_CTX : PROC_CTX) > 0) {
116ac927
RH
3003 printf(" users:(%s)", buf);
3004 free(buf);
3005 }
3006 } else if (show_users) {
4a0053b6 3007 if (find_entry(s->ino, &buf, USERS) > 0) {
116ac927
RH
3008 printf(" users:(%s)", buf);
3009 free(buf);
3010 }
372c30d2 3011 }
116ac927 3012
f1b39e1b
VK
3013 if (show_details)
3014 sock_details_print(s);
3015
4a0053b6
VK
3016 return 0;
3017}
3018
2631b856
VK
3019static void packet_show_ring(struct packet_diag_ring *ring)
3020{
3021 printf("blk_size:%d", ring->pdr_block_size);
3022 printf(",blk_nr:%d", ring->pdr_block_nr);
3023 printf(",frm_size:%d", ring->pdr_frame_size);
3024 printf(",frm_nr:%d", ring->pdr_frame_nr);
3025 printf(",tmo:%d", ring->pdr_retire_tmo);
3026 printf(",features:0x%x", ring->pdr_features);
3027}
3028
4a0053b6
VK
3029static int packet_show_sock(const struct sockaddr_nl *addr,
3030 struct nlmsghdr *nlh, void *arg)
3031{
3032 const struct filter *f = arg;
3033 struct packet_diag_msg *r = NLMSG_DATA(nlh);
2631b856
VK
3034 struct packet_diag_info *pinfo = NULL;
3035 struct packet_diag_ring *ring_rx = NULL, *ring_tx = NULL;
4a0053b6 3036 struct rtattr *tb[PACKET_DIAG_MAX+1];
89f634f9 3037 struct sockstat stat = {};
2631b856
VK
3038 uint32_t fanout = 0;
3039 bool has_fanout = false;
4a0053b6 3040
acd1e437 3041 parse_rtattr(tb, PACKET_DIAG_MAX, (struct rtattr *)(r+1),
4a0053b6
VK
3042 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
3043
3044 /* use /proc/net/packet if all info are not available */
3045 if (!tb[PACKET_DIAG_MEMINFO])
3046 return -1;
3047
2d791bc8
VK
3048 stat.type = r->pdiag_type;
3049 stat.prot = r->pdiag_num;
3050 stat.ino = r->pdiag_ino;
3051 stat.state = SS_CLOSE;
f1b39e1b 3052 stat.sk = cookie_sk_get(&r->pdiag_cookie[0]);
4a0053b6
VK
3053
3054 if (tb[PACKET_DIAG_MEMINFO]) {
3055 __u32 *skmeminfo = RTA_DATA(tb[PACKET_DIAG_MEMINFO]);
acd1e437 3056
4a0053b6
VK
3057 stat.rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
3058 }
3059
3060 if (tb[PACKET_DIAG_INFO]) {
2631b856 3061 pinfo = RTA_DATA(tb[PACKET_DIAG_INFO]);
2d791bc8 3062 stat.lport = stat.iface = pinfo->pdi_index;
4a0053b6
VK
3063 }
3064
f1b39e1b
VK
3065 if (tb[PACKET_DIAG_UID])
3066 stat.uid = *(__u32 *)RTA_DATA(tb[PACKET_DIAG_UID]);
3067
2631b856
VK
3068 if (tb[PACKET_DIAG_RX_RING])
3069 ring_rx = RTA_DATA(tb[PACKET_DIAG_RX_RING]);
3070
3071 if (tb[PACKET_DIAG_TX_RING])
3072 ring_tx = RTA_DATA(tb[PACKET_DIAG_TX_RING]);
3073
3074 if (tb[PACKET_DIAG_FANOUT]) {
3075 has_fanout = true;
3076 fanout = *(uint32_t *)RTA_DATA(tb[PACKET_DIAG_FANOUT]);
3077 }
3078
4a0053b6
VK
3079 if (packet_stats_print(&stat, f))
3080 return 0;
3081
2631b856
VK
3082 if (show_details) {
3083 if (pinfo) {
3084 printf("\n\tver:%d", pinfo->pdi_version);
3085 printf(" cpy_thresh:%d", pinfo->pdi_copy_thresh);
3086 printf(" flags( ");
3087 if (pinfo->pdi_flags & PDI_RUNNING)
3088 printf("running");
3089 if (pinfo->pdi_flags & PDI_AUXDATA)
3090 printf(" auxdata");
3091 if (pinfo->pdi_flags & PDI_ORIGDEV)
3092 printf(" origdev");
3093 if (pinfo->pdi_flags & PDI_VNETHDR)
3094 printf(" vnethdr");
3095 if (pinfo->pdi_flags & PDI_LOSS)
3096 printf(" loss");
3097 if (!pinfo->pdi_flags)
3098 printf("0");
3099 printf(" )");
3100 }
3101 if (ring_rx) {
3102 printf("\n\tring_rx(");
3103 packet_show_ring(ring_rx);
3104 printf(")");
3105 }
3106 if (ring_tx) {
3107 printf("\n\tring_tx(");
3108 packet_show_ring(ring_tx);
3109 printf(")");
3110 }
3111 if (has_fanout) {
3112 uint16_t type = (fanout >> 16) & 0xffff;
3113
3114 printf("\n\tfanout(");
3115 printf("id:%d,", fanout & 0xffff);
3116 printf("type:");
3117
3118 if (type == 0)
3119 printf("hash");
3120 else if (type == 1)
3121 printf("lb");
3122 else if (type == 2)
3123 printf("cpu");
3124 else if (type == 3)
3125 printf("roll");
3126 else if (type == 4)
3127 printf("random");
3128 else if (type == 5)
3129 printf("qm");
3130 else
3131 printf("0x%x", type);
3132
3133 printf(")");
3134 }
3135 }
3136
372c30d2
ND
3137 if (show_bpf && tb[PACKET_DIAG_FILTER]) {
3138 struct sock_filter *fil =
3139 RTA_DATA(tb[PACKET_DIAG_FILTER]);
3140 int num = RTA_PAYLOAD(tb[PACKET_DIAG_FILTER]) /
3141 sizeof(struct sock_filter);
3142
3143 printf("\n\tbpf filter (%d): ", num);
3144 while (num) {
3145 printf(" 0x%02x %u %u %u,",
3146 fil->code, fil->jt, fil->jf, fil->k);
3147 num--;
3148 fil++;
3149 }
3150 }
3151 printf("\n");
3152 return 0;
3153}
3154
8a4025f6 3155static int packet_show_netlink(struct filter *f)
372c30d2 3156{
5fb421d4 3157 DIAG_REQUEST(req, struct packet_diag_req r);
372c30d2 3158
372c30d2 3159 req.r.sdiag_family = AF_PACKET;
2631b856
VK
3160 req.r.pdiag_show = PACKET_SHOW_INFO | PACKET_SHOW_MEMINFO |
3161 PACKET_SHOW_FILTER | PACKET_SHOW_RING_CFG | PACKET_SHOW_FANOUT;
372c30d2 3162
8a4025f6 3163 return handle_netlink_request(f, &req.nlh, sizeof(req), packet_show_sock);
372c30d2
ND
3164}
3165
4a0053b6
VK
3166static int packet_show_line(char *buf, const struct filter *f, int fam)
3167{
3168 unsigned long long sk;
89f634f9 3169 struct sockstat stat = {};
4a0053b6
VK
3170 int type, prot, iface, state, rq, uid, ino;
3171
3172 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
3173 &sk,
3174 &type, &prot, &iface, &state,
3175 &rq, &uid, &ino);
3176
3177 if (stat.type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
3178 return 0;
3179 if (stat.type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
3180 return 0;
3181
3182 stat.type = type;
3183 stat.prot = prot;
2d791bc8 3184 stat.lport = stat.iface = iface;
4a0053b6
VK
3185 stat.state = state;
3186 stat.rq = rq;
3187 stat.uid = uid;
3188 stat.ino = ino;
2d791bc8
VK
3189 stat.state = SS_CLOSE;
3190
4a0053b6
VK
3191 if (packet_stats_print(&stat, f))
3192 return 0;
3193
4a0053b6
VK
3194 printf("\n");
3195 return 0;
3196}
aba5acdf 3197
d1f28cf1 3198static int packet_show(struct filter *f)
aba5acdf
SH
3199{
3200 FILE *fp;
b95d28c3 3201 int rc = 0;
3d0b7439 3202
9db7bf15 3203 if (!filter_af_get(f, AF_PACKET) || !(f->states & (1 << SS_CLOSE)))
b9ea445d 3204 return 0;
aba5acdf 3205
4a0053b6
VK
3206 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
3207 packet_show_netlink(f) == 0)
372c30d2
ND
3208 return 0;
3209
ab01dbbb 3210 if ((fp = net_packet_open()) == NULL)
aba5acdf 3211 return -1;
4a0053b6 3212 if (generic_record_read(fp, packet_show_line, f, AF_PACKET))
b95d28c3 3213 rc = -1;
aba5acdf 3214
b95d28c3
PS
3215 fclose(fp);
3216 return rc;
aba5acdf
SH
3217}
3218
5f24ec0e 3219static int netlink_show_one(struct filter *f,
acd1e437
SH
3220 int prot, int pid, unsigned int groups,
3221 int state, int dst_pid, unsigned int dst_group,
129709ae
AV
3222 int rq, int wq,
3223 unsigned long long sk, unsigned long long cb)
3224{
2d791bc8 3225 struct sockstat st;
acd1e437 3226
b217df10
VK
3227 SPRINT_BUF(prot_buf) = {};
3228 const char *prot_name;
3229 char procname[64] = {};
eef43b50 3230
2d791bc8
VK
3231 st.state = SS_CLOSE;
3232 st.rq = rq;
3233 st.wq = wq;
3234
129709ae 3235 if (f->f) {
055840f2
VK
3236 st.local.family = AF_NETLINK;
3237 st.remote.family = AF_NETLINK;
3238 st.rport = -1;
3239 st.lport = pid;
3240 st.local.data[0] = prot;
055840f2 3241 if (run_ssfilter(f->f, &st) == 0)
5f24ec0e 3242 return 1;
129709ae
AV
3243 }
3244
2d791bc8 3245 sock_state_print(&st, "nl");
eef43b50 3246
b217df10
VK
3247 if (resolve_services)
3248 prot_name = nl_proto_n2a(prot, prot_buf, sizeof(prot_buf));
3249 else
3250 prot_name = int_to_str(prot, prot_buf);
eef43b50 3251
129709ae 3252 if (pid == -1) {
b217df10 3253 procname[0] = '*';
129709ae
AV
3254 } else if (resolve_services) {
3255 int done = 0;
acd1e437 3256
129709ae
AV
3257 if (!pid) {
3258 done = 1;
b217df10 3259 strncpy(procname, "kernel", 6);
129709ae 3260 } else if (pid > 0) {
129709ae 3261 FILE *fp;
acd1e437 3262
0ee9052f 3263 snprintf(procname, sizeof(procname), "%s/%d/stat",
129709ae
AV
3264 getenv("PROC_ROOT") ? : "/proc", pid);
3265 if ((fp = fopen(procname, "r")) != NULL) {
3266 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
0ee9052f 3267 snprintf(procname+strlen(procname),
3268 sizeof(procname)-strlen(procname),
3269 "/%d", pid);
129709ae
AV
3270 done = 1;
3271 }
3272 fclose(fp);
3273 }
3274 }
3275 if (!done)
b217df10 3276 int_to_str(pid, procname);
129709ae 3277 } else {
b217df10 3278 int_to_str(pid, procname);
129709ae 3279 }
f271fe01 3280
b217df10
VK
3281 sock_addr_print(prot_name, ":", procname, NULL);
3282
f271fe01 3283 if (state == NETLINK_CONNECTED) {
b217df10
VK
3284 char dst_group_buf[30];
3285 char dst_pid_buf[30];
acd1e437 3286
b217df10
VK
3287 sock_addr_print(int_to_str(dst_group, dst_group_buf), ":",
3288 int_to_str(dst_pid, dst_pid_buf), NULL);
f271fe01 3289 } else {
b217df10 3290 sock_addr_print("", "*", "", NULL);
f271fe01 3291 }
129709ae 3292
116ac927 3293 char *pid_context = NULL;
acd1e437 3294
116ac927
RH
3295 if (show_proc_ctx) {
3296 /* The pid value will either be:
3297 * 0 if destination kernel - show kernel initial context.
3298 * A valid process pid - use getpidcon.
3299 * A unique value allocated by the kernel or netlink user
3300 * to the process - show context as "not available".
3301 */
3302 if (!pid)
3303 security_get_initial_context("kernel", &pid_context);
3304 else if (pid > 0)
3305 getpidcon(pid, &pid_context);
3306
3307 if (pid_context != NULL) {
3308 printf("proc_ctx=%-*s ", serv_width, pid_context);
3309 free(pid_context);
3310 } else {
3311 printf("proc_ctx=%-*s ", serv_width, "unavailable");
3312 }
3313 }
3314
129709ae
AV
3315 if (show_details) {
3316 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
3317 }
3318 printf("\n");
3319
5f24ec0e 3320 return 0;
129709ae
AV
3321}
3322
8a4025f6 3323static int netlink_show_sock(const struct sockaddr_nl *addr,
3324 struct nlmsghdr *nlh, void *arg)
ecb928c8 3325{
8a4025f6 3326 struct filter *f = (struct filter *)arg;
ecb928c8
AV
3327 struct netlink_diag_msg *r = NLMSG_DATA(nlh);
3328 struct rtattr *tb[NETLINK_DIAG_MAX+1];
3329 int rq = 0, wq = 0;
3330 unsigned long groups = 0;
3331
acd1e437 3332 parse_rtattr(tb, NETLINK_DIAG_MAX, (struct rtattr *)(r+1),
ecb928c8
AV
3333 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
3334
3335 if (tb[NETLINK_DIAG_GROUPS] && RTA_PAYLOAD(tb[NETLINK_DIAG_GROUPS]))
3336 groups = *(unsigned long *) RTA_DATA(tb[NETLINK_DIAG_GROUPS]);
3337
3338 if (tb[NETLINK_DIAG_MEMINFO]) {
3339 const __u32 *skmeminfo;
acd1e437 3340
ecb928c8
AV
3341 skmeminfo = RTA_DATA(tb[NETLINK_DIAG_MEMINFO]);
3342
3343 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
3344 wq = skmeminfo[SK_MEMINFO_WMEM_ALLOC];
3345 }
3346
5f24ec0e 3347 if (netlink_show_one(f, r->ndiag_protocol, r->ndiag_portid, groups,
ecb928c8 3348 r->ndiag_state, r->ndiag_dst_portid, r->ndiag_dst_group,
5f24ec0e
VK
3349 rq, wq, 0, 0)) {
3350 return 0;
3351 }
ecb928c8
AV
3352
3353 if (show_mem) {
3354 printf("\t");
3355 print_skmeminfo(tb, NETLINK_DIAG_MEMINFO);
3356 printf("\n");
3357 }
3358
3359 return 0;
3360}
3361
8a4025f6 3362static int netlink_show_netlink(struct filter *f)
ecb928c8 3363{
5fb421d4 3364 DIAG_REQUEST(req, struct netlink_diag_req r);
ecb928c8
AV
3365
3366 req.r.sdiag_family = AF_NETLINK;
3367 req.r.sdiag_protocol = NDIAG_PROTO_ALL;
3368 req.r.ndiag_show = NDIAG_SHOW_GROUPS | NDIAG_SHOW_MEMINFO;
3369
8a4025f6 3370 return handle_netlink_request(f, &req.nlh, sizeof(req), netlink_show_sock);
ecb928c8
AV
3371}
3372
d1f28cf1 3373static int netlink_show(struct filter *f)
aba5acdf
SH
3374{
3375 FILE *fp;
3376 char buf[256];
3377 int prot, pid;
acd1e437 3378 unsigned int groups;
aba5acdf
SH
3379 int rq, wq, rc;
3380 unsigned long long sk, cb;
3381
9db7bf15 3382 if (!filter_af_get(f, AF_NETLINK) || !(f->states & (1 << SS_CLOSE)))
b9ea445d
VK
3383 return 0;
3384
129709ae 3385 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
8a4025f6 3386 netlink_show_netlink(f) == 0)
129709ae
AV
3387 return 0;
3388
ab01dbbb 3389 if ((fp = net_netlink_open()) == NULL)
aba5acdf 3390 return -1;
61170fd8 3391 if (!fgets(buf, sizeof(buf), fp)) {
d572ed4d
PS
3392 fclose(fp);
3393 return -1;
3394 }
aba5acdf 3395
61170fd8 3396 while (fgets(buf, sizeof(buf), fp)) {
aba5acdf
SH
3397 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
3398 &sk,
3399 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
3400
f271fe01 3401 netlink_show_one(f, prot, pid, groups, 0, 0, 0, rq, wq, sk, cb);
aba5acdf
SH
3402 }
3403
b95d28c3 3404 fclose(fp);
aba5acdf
SH
3405 return 0;
3406}
3407
6885e3bf
CG
3408struct sock_diag_msg {
3409 __u8 sdiag_family;
3410};
3411
3412static int generic_show_sock(const struct sockaddr_nl *addr,
3413 struct nlmsghdr *nlh, void *arg)
3414{
3415 struct sock_diag_msg *r = NLMSG_DATA(nlh);
3416 struct inet_diag_arg inet_arg = { .f = arg, .protocol = IPPROTO_MAX };
3417
3418 switch (r->sdiag_family) {
3419 case AF_INET:
3420 case AF_INET6:
3421 return show_one_inet_sock(addr, nlh, &inet_arg);
3422 case AF_UNIX:
3423 return unix_show_sock(addr, nlh, arg);
3424 case AF_PACKET:
3425 return packet_show_sock(addr, nlh, arg);
3426 case AF_NETLINK:
3427 return netlink_show_sock(addr, nlh, arg);
3428 default:
3429 return -1;
3430 }
3431}
3432
3433static int handle_follow_request(struct filter *f)
3434{
3435 int ret = -1;
3436 int groups = 0;
3437 struct rtnl_handle rth;
3438
3439 if (f->families & (1 << AF_INET) && f->dbs & (1 << TCP_DB))
3440 groups |= 1 << (SKNLGRP_INET_TCP_DESTROY - 1);
3441 if (f->families & (1 << AF_INET) && f->dbs & (1 << UDP_DB))
3442 groups |= 1 << (SKNLGRP_INET_UDP_DESTROY - 1);
3443 if (f->families & (1 << AF_INET6) && f->dbs & (1 << TCP_DB))
3444 groups |= 1 << (SKNLGRP_INET6_TCP_DESTROY - 1);
3445 if (f->families & (1 << AF_INET6) && f->dbs & (1 << UDP_DB))
3446 groups |= 1 << (SKNLGRP_INET6_UDP_DESTROY - 1);
3447
3448 if (groups == 0)
3449 return -1;
3450
3451 if (rtnl_open_byproto(&rth, groups, NETLINK_SOCK_DIAG))
3452 return -1;
3453
3454 rth.dump = 0;
3455 rth.local.nl_pid = 0;
3456
3457 if (rtnl_dump_filter(&rth, generic_show_sock, f))
3458 goto Exit;
3459
3460 ret = 0;
3461Exit:
3462 rtnl_close(&rth);
3463 return ret;
3464}
3465
acd1e437 3466struct snmpstat {
aba5acdf
SH
3467 int tcp_estab;
3468};
3469
d1f28cf1 3470static int get_snmp_int(char *proto, char *key, int *result)
aba5acdf
SH
3471{
3472 char buf[1024];
3473 FILE *fp;
3474 int protolen = strlen(proto);
3475 int keylen = strlen(key);
3476
3477 *result = 0;
3478
ab01dbbb 3479 if ((fp = net_snmp_open()) == NULL)
aba5acdf
SH
3480 return -1;
3481
3482 while (fgets(buf, sizeof(buf), fp) != NULL) {
3483 char *p = buf;
3484 int pos = 0;
acd1e437 3485
aba5acdf
SH
3486 if (memcmp(buf, proto, protolen))
3487 continue;
3488 while ((p = strchr(p, ' ')) != NULL) {
3489 pos++;
3490 p++;
3491 if (memcmp(p, key, keylen) == 0 &&
3492 (p[keylen] == ' ' || p[keylen] == '\n'))
3493 break;
3494 }
3495 if (fgets(buf, sizeof(buf), fp) == NULL)
3496 break;
3497 if (memcmp(buf, proto, protolen))
3498 break;
3499 p = buf;
3500 while ((p = strchr(p, ' ')) != NULL) {
3501 p++;
3502 if (--pos == 0) {
3503 sscanf(p, "%d", result);
3504 fclose(fp);
3505 return 0;
3506 }
3507 }
3508 }
3509
3510 fclose(fp);
3511 errno = ESRCH;
3512 return -1;
3513}
3514
3515
3516/* Get stats from sockstat */
3517
acd1e437 3518struct ssummary {
aba5acdf
SH
3519 int socks;
3520 int tcp_mem;
3521 int tcp_total;
3522 int tcp_orphans;
3523 int tcp_tws;
3524 int tcp4_hashed;
3525 int udp4;
3526 int raw4;
3527 int frag4;
3528 int frag4_mem;
3529 int tcp6_hashed;
3530 int udp6;
3531 int raw6;
3532 int frag6;
3533 int frag6_mem;
3534};
3535
055840f2 3536static void get_sockstat_line(char *line, struct ssummary *s)
aba5acdf
SH
3537{
3538 char id[256], rem[256];
3539
3540 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
3541 return;
3542
3543 if (strcmp(id, "sockets:") == 0)
3544 sscanf(rem, "%*s%d", &s->socks);
3545 else if (strcmp(id, "UDP:") == 0)
3546 sscanf(rem, "%*s%d", &s->udp4);
3547 else if (strcmp(id, "UDP6:") == 0)
3548 sscanf(rem, "%*s%d", &s->udp6);
3549 else if (strcmp(id, "RAW:") == 0)
3550 sscanf(rem, "%*s%d", &s->raw4);
3551 else if (strcmp(id, "RAW6:") == 0)
3552 sscanf(rem, "%*s%d", &s->raw6);
3553 else if (strcmp(id, "TCP6:") == 0)
3554 sscanf(rem, "%*s%d", &s->tcp6_hashed);
3555 else if (strcmp(id, "FRAG:") == 0)
3556 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
3557 else if (strcmp(id, "FRAG6:") == 0)
3558 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
3559 else if (strcmp(id, "TCP:") == 0)
3560 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
3561 &s->tcp4_hashed,
3562 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
3563}
3564
055840f2 3565static int get_sockstat(struct ssummary *s)
aba5acdf
SH
3566{
3567 char buf[256];
3568 FILE *fp;
3569
3570 memset(s, 0, sizeof(*s));
3571
ab01dbbb 3572 if ((fp = net_sockstat_open()) == NULL)
aba5acdf 3573 return -1;
acd1e437 3574 while (fgets(buf, sizeof(buf), fp) != NULL)
aba5acdf
SH
3575 get_sockstat_line(buf, s);
3576 fclose(fp);
3577
ab01dbbb 3578 if ((fp = net_sockstat6_open()) == NULL)
aba5acdf 3579 return 0;
acd1e437 3580 while (fgets(buf, sizeof(buf), fp) != NULL)
aba5acdf
SH
3581 get_sockstat_line(buf, s);
3582 fclose(fp);
3583
3584 return 0;
3585}
3586
d1f28cf1 3587static int print_summary(void)
aba5acdf 3588{
055840f2 3589 struct ssummary s;
aba5acdf
SH
3590 struct snmpstat sn;
3591
3592 if (get_sockstat(&s) < 0)
3593 perror("ss: get_sockstat");
3594 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
3595 perror("ss: get_snmpstat");
3596
a221d621
BL
3597 get_slabstat(&slabstat);
3598
aba5acdf
SH
3599 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
3600
3601 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
3602 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
3603 sn.tcp_estab,
3604 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
3605 s.tcp_orphans,
3606 slabstat.tcp_syns,
3607 s.tcp_tws, slabstat.tcp_tws,
3608 slabstat.tcp_ports
3609 );
3610
3611 printf("\n");
3612 printf("Transport Total IP IPv6\n");
3613 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
3614 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
3615 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
3616 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
ae665a52 3617 printf("INET %-9d %-9d %-9d\n",
aba5acdf
SH
3618 s.raw4+s.udp4+s.tcp4_hashed+
3619 s.raw6+s.udp6+s.tcp6_hashed,
3620 s.raw4+s.udp4+s.tcp4_hashed,
3621 s.raw6+s.udp6+s.tcp6_hashed);
3622 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
3623
3624 printf("\n");
3625
3626 return 0;
3627}
3628
7a96e199 3629static void _usage(FILE *dest)
aba5acdf 3630{
7a96e199 3631 fprintf(dest,
aba5acdf
SH
3632"Usage: ss [ OPTIONS ]\n"
3633" ss [ OPTIONS ] [ FILTER ]\n"
ff041f16
VK
3634" -h, --help this message\n"
3635" -V, --version output version information\n"
3636" -n, --numeric don't resolve service names\n"
ab61159a 3637" -r, --resolve resolve host names\n"
ff041f16
VK
3638" -a, --all display all sockets\n"
3639" -l, --listening display listening sockets\n"
ab61159a
SH
3640" -o, --options show timer information\n"
3641" -e, --extended show detailed socket information\n"
3642" -m, --memory show socket memory usage\n"
ff041f16
VK
3643" -p, --processes show process using socket\n"
3644" -i, --info show internal TCP information\n"
3645" -s, --summary show socket usage summary\n"
b0f01cf6 3646" -b, --bpf show bpf filter socket information\n"
6885e3bf 3647" -E, --events continually display sockets as they are destroyed\n"
ff041f16
VK
3648" -Z, --context display process SELinux security contexts\n"
3649" -z, --contexts display process and socket SELinux security contexts\n"
95ce04bc 3650" -N, --net switch to the specified network namespace name\n"
ab61159a
SH
3651"\n"
3652" -4, --ipv4 display only IP version 4 sockets\n"
3653" -6, --ipv6 display only IP version 6 sockets\n"
ff041f16
VK
3654" -0, --packet display PACKET sockets\n"
3655" -t, --tcp display only TCP sockets\n"
3656" -u, --udp display only UDP sockets\n"
3657" -d, --dccp display only DCCP sockets\n"
3658" -w, --raw display only RAW sockets\n"
3659" -x, --unix display only Unix domain sockets\n"
ab61159a 3660" -f, --family=FAMILY display sockets of type FAMILY\n"
ebef3174 3661" FAMILY := {inet|inet6|link|unix|netlink|help}\n"
ab61159a 3662"\n"
fb2594c1 3663" -K, --kill forcibly close sockets, display what was closed\n"
7a4559f6 3664" -H, --no-header Suppress header line\n"
fb2594c1 3665"\n"
583de149 3666" -A, --query=QUERY, --socket=QUERY\n"
56dee73e 3667" QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink}[,QUERY]\n"
ab61159a 3668"\n"
583de149 3669" -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
ab61159a 3670" -F, --filter=FILE read filter information from FILE\n"
ff041f16
VK
3671" FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
3672" STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
3673" TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listen|closing}\n"
3674" connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
3675" synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
3676" bucket := {syn-recv|time-wait}\n"
3677" big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listen|closing}\n"
ab61159a 3678 );
7a96e199
AH
3679}
3680
3681static void help(void) __attribute__((noreturn));
3682static void help(void)
3683{
3684 _usage(stdout);
3685 exit(0);
3686}
3687
3688static void usage(void) __attribute__((noreturn));
3689static void usage(void)
3690{
3691 _usage(stderr);
aba5acdf
SH
3692 exit(-1);
3693}
3694
3695
d1f28cf1 3696static int scan_state(const char *state)
aba5acdf
SH
3697{
3698 int i;
acd1e437 3699
aba5acdf
SH
3700 if (strcasecmp(state, "close") == 0 ||
3701 strcasecmp(state, "closed") == 0)
3702 return (1<<SS_CLOSE);
3703 if (strcasecmp(state, "syn-rcv") == 0)
3704 return (1<<SS_SYN_RECV);
1a5bad5a 3705 if (strcasecmp(state, "established") == 0)
aba5acdf
SH
3706 return (1<<SS_ESTABLISHED);
3707 if (strcasecmp(state, "all") == 0)
3708 return SS_ALL;
3709 if (strcasecmp(state, "connected") == 0)
3710 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
1a5bad5a 3711 if (strcasecmp(state, "synchronized") == 0)
aba5acdf
SH
3712 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
3713 if (strcasecmp(state, "bucket") == 0)
3714 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
3715 if (strcasecmp(state, "big") == 0)
3716 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
acd1e437 3717 for (i = 0; i < SS_MAX; i++) {
1a5bad5a 3718 if (strcasecmp(state, sstate_namel[i]) == 0)
aba5acdf
SH
3719 return (1<<i);
3720 }
9db7bf15
VK
3721
3722 fprintf(stderr, "ss: wrong state name: %s\n", state);
3723 exit(-1);
aba5acdf
SH
3724}
3725
ab61159a
SH
3726static const struct option long_opts[] = {
3727 { "numeric", 0, 0, 'n' },
3728 { "resolve", 0, 0, 'r' },
3729 { "options", 0, 0, 'o' },
3730 { "extended", 0, 0, 'e' },
3731 { "memory", 0, 0, 'm' },
3732 { "info", 0, 0, 'i' },
3733 { "processes", 0, 0, 'p' },
372c30d2 3734 { "bpf", 0, 0, 'b' },
6885e3bf 3735 { "events", 0, 0, 'E' },
351efcde 3736 { "dccp", 0, 0, 'd' },
ab61159a
SH
3737 { "tcp", 0, 0, 't' },
3738 { "udp", 0, 0, 'u' },
3739 { "raw", 0, 0, 'w' },
3740 { "unix", 0, 0, 'x' },
3741 { "all", 0, 0, 'a' },
3742 { "listening", 0, 0, 'l' },
3743 { "ipv4", 0, 0, '4' },
3744 { "ipv6", 0, 0, '6' },
3745 { "packet", 0, 0, '0' },
3746 { "family", 1, 0, 'f' },
3747 { "socket", 1, 0, 'A' },
583de149 3748 { "query", 1, 0, 'A' },
c3f346b0 3749 { "summary", 0, 0, 's' },
583de149 3750 { "diag", 1, 0, 'D' },
ab61159a
SH
3751 { "filter", 1, 0, 'F' },
3752 { "version", 0, 0, 'V' },
3753 { "help", 0, 0, 'h' },
116ac927
RH
3754 { "context", 0, 0, 'Z' },
3755 { "contexts", 0, 0, 'z' },
95ce04bc 3756 { "net", 1, 0, 'N' },
fb2594c1 3757 { "kill", 0, 0, 'K' },
7a4559f6 3758 { "no-header", 0, 0, 'H' },
ab61159a 3759 { 0 }
ae665a52 3760
ab61159a
SH
3761};
3762
aba5acdf
SH
3763int main(int argc, char *argv[])
3764{
aba5acdf
SH
3765 int saw_states = 0;
3766 int saw_query = 0;
3767 int do_summary = 0;
7d105b56 3768 const char *dump_tcpdiag = NULL;
aba5acdf
SH
3769 FILE *filter_fp = NULL;
3770 int ch;
9db7bf15 3771 int state_filter = 0;
aba5acdf 3772
7a4559f6 3773 while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KH",
ab61159a 3774 long_opts, NULL)) != EOF) {
acd1e437 3775 switch (ch) {
aba5acdf
SH
3776 case 'n':
3777 resolve_services = 0;
3778 break;
3779 case 'r':
3780 resolve_hosts = 1;
3781 break;
3782 case 'o':
3783 show_options = 1;
3784 break;
3785 case 'e':
3786 show_options = 1;
3787 show_details++;
3788 break;
3789 case 'm':
3790 show_mem = 1;
3791 break;
3792 case 'i':
3793 show_tcpinfo = 1;
3794 break;
3795 case 'p':
3796 show_users++;
fbc0f876 3797 user_ent_hash_build();
aba5acdf 3798 break;
372c30d2
ND
3799 case 'b':
3800 show_options = 1;
3801 show_bpf++;
3802 break;
6885e3bf
CG
3803 case 'E':
3804 follow_events = 1;
3805 break;
351efcde 3806 case 'd':
57ff5a10 3807 filter_db_set(&current_filter, DCCP_DB);
351efcde 3808 break;
aba5acdf 3809 case 't':
57ff5a10 3810 filter_db_set(&current_filter, TCP_DB);
aba5acdf
SH
3811 break;
3812 case 'u':
57ff5a10 3813 filter_db_set(&current_filter, UDP_DB);
aba5acdf
SH
3814 break;
3815 case 'w':
57ff5a10 3816 filter_db_set(&current_filter, RAW_DB);
aba5acdf
SH
3817 break;
3818 case 'x':
9db7bf15 3819 filter_af_set(&current_filter, AF_UNIX);
aba5acdf
SH
3820 break;
3821 case 'a':
9db7bf15 3822 state_filter = SS_ALL;
aba5acdf
SH
3823 break;
3824 case 'l':
9db7bf15 3825 state_filter = (1 << SS_LISTEN) | (1 << SS_CLOSE);
aba5acdf
SH
3826 break;
3827 case '4':
9db7bf15 3828 filter_af_set(&current_filter, AF_INET);
aba5acdf
SH
3829 break;
3830 case '6':
9db7bf15 3831 filter_af_set(&current_filter, AF_INET6);
aba5acdf
SH
3832 break;
3833 case '0':
9db7bf15 3834 filter_af_set(&current_filter, AF_PACKET);
aba5acdf
SH
3835 break;
3836 case 'f':
3837 if (strcmp(optarg, "inet") == 0)
9db7bf15 3838 filter_af_set(&current_filter, AF_INET);
aba5acdf 3839 else if (strcmp(optarg, "inet6") == 0)
9db7bf15 3840 filter_af_set(&current_filter, AF_INET6);
aba5acdf 3841 else if (strcmp(optarg, "link") == 0)
9db7bf15 3842 filter_af_set(&current_filter, AF_PACKET);
aba5acdf 3843 else if (strcmp(optarg, "unix") == 0)
9db7bf15 3844 filter_af_set(&current_filter, AF_UNIX);
aba5acdf 3845 else if (strcmp(optarg, "netlink") == 0)
9db7bf15 3846 filter_af_set(&current_filter, AF_NETLINK);
aba5acdf 3847 else if (strcmp(optarg, "help") == 0)
7a96e199 3848 help();
aba5acdf 3849 else {
9db7bf15
VK
3850 fprintf(stderr, "ss: \"%s\" is invalid family\n",
3851 optarg);
aba5acdf
SH
3852 usage();
3853 }
3854 break;
3855 case 'A':
3856 {
3857 char *p, *p1;
acd1e437 3858
aba5acdf
SH
3859 if (!saw_query) {
3860 current_filter.dbs = 0;
7f9dddbe 3861 state_filter = state_filter ?
acd1e437 3862 state_filter : SS_CONN;
aba5acdf
SH
3863 saw_query = 1;
3864 do_default = 0;
3865 }
3866 p = p1 = optarg;
3867 do {
3868 if ((p1 = strchr(p, ',')) != NULL)
ae665a52 3869 *p1 = 0;
aba5acdf 3870 if (strcmp(p, "all") == 0) {
57ff5a10 3871 filter_default_dbs(&current_filter);
aba5acdf 3872 } else if (strcmp(p, "inet") == 0) {
57ff5a10
VK
3873 filter_db_set(&current_filter, UDP_DB);
3874 filter_db_set(&current_filter, DCCP_DB);
3875 filter_db_set(&current_filter, TCP_DB);
3876 filter_db_set(&current_filter, RAW_DB);
aba5acdf 3877 } else if (strcmp(p, "udp") == 0) {
57ff5a10 3878 filter_db_set(&current_filter, UDP_DB);
351efcde 3879 } else if (strcmp(p, "dccp") == 0) {
57ff5a10 3880 filter_db_set(&current_filter, DCCP_DB);
aba5acdf 3881 } else if (strcmp(p, "tcp") == 0) {
57ff5a10 3882 filter_db_set(&current_filter, TCP_DB);
aba5acdf 3883 } else if (strcmp(p, "raw") == 0) {
57ff5a10 3884 filter_db_set(&current_filter, RAW_DB);
aba5acdf 3885 } else if (strcmp(p, "unix") == 0) {
57ff5a10
VK
3886 filter_db_set(&current_filter, UNIX_ST_DB);
3887 filter_db_set(&current_filter, UNIX_DG_DB);
3888 filter_db_set(&current_filter, UNIX_SQ_DB);
1a5bad5a 3889 } else if (strcasecmp(p, "unix_stream") == 0 ||
aba5acdf 3890 strcmp(p, "u_str") == 0) {
57ff5a10 3891 filter_db_set(&current_filter, UNIX_ST_DB);
1a5bad5a 3892 } else if (strcasecmp(p, "unix_dgram") == 0 ||
aba5acdf 3893 strcmp(p, "u_dgr") == 0) {
57ff5a10 3894 filter_db_set(&current_filter, UNIX_DG_DB);
30b669d7
MY
3895 } else if (strcasecmp(p, "unix_seqpacket") == 0 ||
3896 strcmp(p, "u_seq") == 0) {
57ff5a10 3897 filter_db_set(&current_filter, UNIX_SQ_DB);
aba5acdf 3898 } else if (strcmp(p, "packet") == 0) {
57ff5a10
VK
3899 filter_db_set(&current_filter, PACKET_R_DB);
3900 filter_db_set(&current_filter, PACKET_DG_DB);
aba5acdf
SH
3901 } else if (strcmp(p, "packet_raw") == 0 ||
3902 strcmp(p, "p_raw") == 0) {
57ff5a10 3903 filter_db_set(&current_filter, PACKET_R_DB);
aba5acdf
SH
3904 } else if (strcmp(p, "packet_dgram") == 0 ||
3905 strcmp(p, "p_dgr") == 0) {
57ff5a10 3906 filter_db_set(&current_filter, PACKET_DG_DB);
aba5acdf 3907 } else if (strcmp(p, "netlink") == 0) {
57ff5a10 3908 filter_db_set(&current_filter, NETLINK_DB);
aba5acdf
SH
3909 } else {
3910 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
3911 usage();
3912 }
3913 p = p1 + 1;
3914 } while (p1);
3915 break;
3916 }
3917 case 's':
3918 do_summary = 1;
3919 break;
3920 case 'D':
3921 dump_tcpdiag = optarg;
3922 break;
3923 case 'F':
3924 if (filter_fp) {
3925 fprintf(stderr, "More than one filter file\n");
3926 exit(-1);
3927 }
3928 if (optarg[0] == '-')
3929 filter_fp = stdin;
3930 else
3931 filter_fp = fopen(optarg, "r");
3932 if (!filter_fp) {
3933 perror("fopen filter file");
3934 exit(-1);
3935 }
3936 break;
3937 case 'v':
3938 case 'V':
3939 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
3940 exit(0);
116ac927
RH
3941 case 'z':
3942 show_sock_ctx++;
3943 case 'Z':
3944 if (is_selinux_enabled() <= 0) {
3945 fprintf(stderr, "ss: SELinux is not enabled.\n");
3946 exit(1);
3947 }
3948 show_proc_ctx++;
3949 user_ent_hash_build();
3950 break;
95ce04bc
VK
3951 case 'N':
3952 if (netns_switch(optarg))
3953 exit(1);
3954 break;
fb2594c1
LC
3955 case 'K':
3956 current_filter.kill = 1;
3957 break;
7a4559f6
DA
3958 case 'H':
3959 show_header = 0;
3960 break;
aba5acdf 3961 case 'h':
7a96e199 3962 help();
f73105ab 3963 case '?':
aba5acdf
SH
3964 default:
3965 usage();
3966 }
3967 }
3968
3969 argc -= optind;
3970 argv += optind;
3971
aba5acdf
SH
3972 if (do_summary) {
3973 print_summary();
3974 if (do_default && argc == 0)
3975 exit(0);
3976 }
3977
aba5acdf
SH
3978 while (argc > 0) {
3979 if (strcmp(*argv, "state") == 0) {
3980 NEXT_ARG();
3981 if (!saw_states)
9db7bf15
VK
3982 state_filter = 0;
3983 state_filter |= scan_state(*argv);
aba5acdf
SH
3984 saw_states = 1;
3985 } else if (strcmp(*argv, "exclude") == 0 ||
3986 strcmp(*argv, "excl") == 0) {
3987 NEXT_ARG();
3988 if (!saw_states)
9db7bf15
VK
3989 state_filter = SS_ALL;
3990 state_filter &= ~scan_state(*argv);
aba5acdf
SH
3991 saw_states = 1;
3992 } else {
aba5acdf
SH
3993 break;
3994 }
3995 argc--; argv++;
3996 }
3997
9db7bf15
VK
3998 if (do_default) {
3999 state_filter = state_filter ? state_filter : SS_CONN;
4000 filter_default_dbs(&current_filter);
9db7bf15
VK
4001 }
4002
57ff5a10
VK
4003 filter_states_set(&current_filter, state_filter);
4004 filter_merge_defaults(&current_filter);
4005
9db7bf15
VK
4006 if (resolve_services && resolve_hosts &&
4007 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
4008 init_service_resolver();
4009
4010
4011 if (current_filter.dbs == 0) {
4012 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
4013 exit(0);
4014 }
4015 if (current_filter.families == 0) {
4016 fprintf(stderr, "ss: no families to show with such filter.\n");
4017 exit(0);
4018 }
aba5acdf
SH
4019 if (current_filter.states == 0) {
4020 fprintf(stderr, "ss: no socket states to show with such filter.\n");
4021 exit(0);
4022 }
4023
4024 if (dump_tcpdiag) {
4025 FILE *dump_fp = stdout;
acd1e437 4026
aba5acdf
SH
4027 if (!(current_filter.dbs & (1<<TCP_DB))) {
4028 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
4029 exit(0);
4030 }
4031 if (dump_tcpdiag[0] != '-') {
4032 dump_fp = fopen(dump_tcpdiag, "w");
4033 if (!dump_tcpdiag) {
4034 perror("fopen dump file");
4035 exit(-1);
4036 }
4037 }
3fe5b534 4038 inet_show_netlink(&current_filter, dump_fp, IPPROTO_TCP);
aba5acdf
SH
4039 fflush(dump_fp);
4040 exit(0);
4041 }
4042
1527a17e
VK
4043 if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
4044 usage();
4045
aba5acdf
SH
4046 netid_width = 0;
4047 if (current_filter.dbs&(current_filter.dbs-1))
4048 netid_width = 5;
4049
4050 state_width = 0;
4051 if (current_filter.states&(current_filter.states-1))
4052 state_width = 10;
4053
4054 screen_width = 80;
4055 if (isatty(STDOUT_FILENO)) {
4056 struct winsize w;
4057
4058 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
4059 if (w.ws_col > 0)
4060 screen_width = w.ws_col;
4061 }
4062 }
4063
4064 addrp_width = screen_width;
4065 addrp_width -= netid_width+1;
4066 addrp_width -= state_width+1;
4067 addrp_width -= 14;
4068
4069 if (addrp_width&1) {
4070 if (netid_width)
4071 netid_width++;
4072 else if (state_width)
4073 state_width++;
4074 }
4075
4076 addrp_width /= 2;
4077 addrp_width--;
4078
4079 serv_width = resolve_services ? 7 : 5;
4080
4081 if (addrp_width < 15+serv_width+1)
4082 addrp_width = 15+serv_width+1;
4083
ae665a52 4084 addr_width = addrp_width - serv_width - 1;
aba5acdf 4085
7a4559f6
DA
4086 if (show_header) {
4087 if (netid_width)
4088 printf("%-*s ", netid_width, "Netid");
4089 if (state_width)
4090 printf("%-*s ", state_width, "State");
4091 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
4092 }
aba5acdf 4093
d68e00f7 4094 /* Make enough space for the local/remote port field */
4095 addr_width -= 13;
4096 serv_width += 13;
2dc85485 4097
7a4559f6
DA
4098 if (show_header) {
4099 printf("%*s:%-*s %*s:%-*s\n",
4100 addr_width, "Local Address", serv_width, "Port",
4101 addr_width, "Peer Address", serv_width, "Port");
4102 }
aba5acdf 4103
aba5acdf
SH
4104 fflush(stdout);
4105
6885e3bf
CG
4106 if (follow_events)
4107 exit(handle_follow_request(&current_filter));
4108
aba5acdf
SH
4109 if (current_filter.dbs & (1<<NETLINK_DB))
4110 netlink_show(&current_filter);
4111 if (current_filter.dbs & PACKET_DBM)
4112 packet_show(&current_filter);
4113 if (current_filter.dbs & UNIX_DBM)
4114 unix_show(&current_filter);
4115 if (current_filter.dbs & (1<<RAW_DB))
4116 raw_show(&current_filter);
4117 if (current_filter.dbs & (1<<UDP_DB))
4118 udp_show(&current_filter);
4119 if (current_filter.dbs & (1<<TCP_DB))
3fe5b534 4120 tcp_show(&current_filter, IPPROTO_TCP);
351efcde 4121 if (current_filter.dbs & (1<<DCCP_DB))
3fe5b534 4122 tcp_show(&current_filter, IPPROTO_DCCP);
116ac927
RH
4123
4124 if (show_users || show_proc_ctx || show_sock_ctx)
4125 user_ent_destroy();
4126
aba5acdf
SH
4127 return 0;
4128}