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