]> git.proxmox.com Git - mirror_iproute2.git/blame - misc/ss.c
ss: Refactor inet_show_sock
[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
SH
668
669 for (i = 0; i < sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); 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;
1046 struct aafilter *next;
1047};
1048
d1f28cf1
SH
1049static int inet2_addr_match(const inet_prefix *a, const inet_prefix *p,
1050 int plen)
aba5acdf
SH
1051{
1052 if (!inet_addr_match(a, p, plen))
1053 return 0;
7d105b56 1054
aba5acdf
SH
1055 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1056 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1057 * sockets. Fair? */
1058 if (p->family == AF_INET && a->family == AF_INET6) {
1059 if (a->data[0] == 0 && a->data[1] == 0 &&
1060 a->data[2] == htonl(0xffff)) {
1061 inet_prefix tmp = *a;
acd1e437 1062
aba5acdf
SH
1063 tmp.data[0] = a->data[3];
1064 return inet_addr_match(&tmp, p, plen);
1065 }
1066 }
1067 return 1;
1068}
1069
d1f28cf1 1070static int unix_match(const inet_prefix *a, const inet_prefix *p)
aba5acdf 1071{
99bb68ff 1072 char *addr, *pattern;
acd1e437 1073
99bb68ff
VK
1074 memcpy(&addr, a->data, sizeof(addr));
1075 memcpy(&pattern, p->data, sizeof(pattern));
aba5acdf
SH
1076 if (pattern == NULL)
1077 return 1;
1078 if (addr == NULL)
1079 addr = "";
1080 return !fnmatch(pattern, addr, 0);
1081}
1082
055840f2 1083static int run_ssfilter(struct ssfilter *f, struct sockstat *s)
aba5acdf
SH
1084{
1085 switch (f->type) {
1086 case SSF_S_AUTO:
1087 {
aba5acdf 1088 if (s->local.family == AF_UNIX) {
99bb68ff 1089 char *p;
acd1e437 1090
99bb68ff 1091 memcpy(&p, s->local.data, sizeof(p));
aba5acdf 1092 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
ae665a52 1093 strspn(p+1, "0123456789abcdef") == 5);
aba5acdf
SH
1094 }
1095 if (s->local.family == AF_PACKET)
bbd303d1 1096 return s->lport == 0 && s->local.data[0] == 0;
aba5acdf
SH
1097 if (s->local.family == AF_NETLINK)
1098 return s->lport < 0;
1099
c29d3792 1100 return is_ephemeral(s->lport);
aba5acdf
SH
1101 }
1102 case SSF_DCOND:
1103 {
acd1e437
SH
1104 struct aafilter *a = (void *)f->pred;
1105
aba5acdf
SH
1106 if (a->addr.family == AF_UNIX)
1107 return unix_match(&s->remote, &a->addr);
1108 if (a->port != -1 && a->port != s->rport)
1109 return 0;
1110 if (a->addr.bitlen) {
1111 do {
1112 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
1113 return 1;
1114 } while ((a = a->next) != NULL);
1115 return 0;
1116 }
1117 return 1;
1118 }
1119 case SSF_SCOND:
1120 {
acd1e437
SH
1121 struct aafilter *a = (void *)f->pred;
1122
aba5acdf
SH
1123 if (a->addr.family == AF_UNIX)
1124 return unix_match(&s->local, &a->addr);
1125 if (a->port != -1 && a->port != s->lport)
1126 return 0;
1127 if (a->addr.bitlen) {
1128 do {
1129 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
1130 return 1;
ae665a52 1131 } while ((a = a->next) != NULL);
aba5acdf
SH
1132 return 0;
1133 }
1134 return 1;
1135 }
1136 case SSF_D_GE:
1137 {
acd1e437
SH
1138 struct aafilter *a = (void *)f->pred;
1139
aba5acdf
SH
1140 return s->rport >= a->port;
1141 }
1142 case SSF_D_LE:
1143 {
acd1e437
SH
1144 struct aafilter *a = (void *)f->pred;
1145
aba5acdf
SH
1146 return s->rport <= a->port;
1147 }
1148 case SSF_S_GE:
1149 {
acd1e437
SH
1150 struct aafilter *a = (void *)f->pred;
1151
aba5acdf
SH
1152 return s->lport >= a->port;
1153 }
1154 case SSF_S_LE:
1155 {
acd1e437
SH
1156 struct aafilter *a = (void *)f->pred;
1157
aba5acdf
SH
1158 return s->lport <= a->port;
1159 }
1160
1161 /* Yup. It is recursion. Sorry. */
1162 case SSF_AND:
1163 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
1164 case SSF_OR:
1165 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
1166 case SSF_NOT:
1167 return !run_ssfilter(f->pred, s);
1168 default:
1169 abort();
1170 }
1171}
1172
ae665a52 1173/* Relocate external jumps by reloc. */
b4b0b7d5 1174static void ssfilter_patch(char *a, int len, int reloc)
aba5acdf
SH
1175{
1176 while (len > 0) {
acd1e437
SH
1177 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)a;
1178
aba5acdf
SH
1179 if (op->no == len+4)
1180 op->no += reloc;
1181 len -= op->yes;
1182 a += op->yes;
1183 }
1184 if (len < 0)
1185 abort();
1186}
1187
b4b0b7d5 1188static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
aba5acdf
SH
1189{
1190 switch (f->type) {
1191 case SSF_S_AUTO:
1192 {
acd1e437
SH
1193 if (!(*bytecode = malloc(4))) abort();
1194 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
df39de8d 1195 return 4;
aba5acdf
SH
1196 }
1197 case SSF_DCOND:
1198 case SSF_SCOND:
1199 {
acd1e437 1200 struct aafilter *a = (void *)f->pred;
aba5acdf
SH
1201 struct aafilter *b;
1202 char *ptr;
351efcde 1203 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
aba5acdf
SH
1204 int len = 0;
1205
acd1e437 1206 for (b = a; b; b = b->next) {
351efcde 1207 len += 4 + sizeof(struct inet_diag_hostcond);
aba5acdf
SH
1208 if (a->addr.family == AF_INET6)
1209 len += 16;
1210 else
1211 len += 4;
1212 if (b->next)
1213 len += 4;
1214 }
1215 if (!(ptr = malloc(len))) abort();
1216 *bytecode = ptr;
acd1e437 1217 for (b = a; b; b = b->next) {
351efcde 1218 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
aba5acdf 1219 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
351efcde 1220 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
acd1e437 1221 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond *)(ptr+4);
aba5acdf 1222
351efcde 1223 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
aba5acdf
SH
1224 cond->family = a->addr.family;
1225 cond->port = a->port;
1226 cond->prefix_len = a->addr.bitlen;
1227 memcpy(cond->addr, a->addr.data, alen);
1228 ptr += oplen;
1229 if (b->next) {
351efcde
SH
1230 op = (struct inet_diag_bc_op *)ptr;
1231 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
aba5acdf
SH
1232 ptr += 4;
1233 }
1234 }
1235 return ptr - *bytecode;
1236 }
1237 case SSF_D_GE:
1238 {
acd1e437
SH
1239 struct aafilter *x = (void *)f->pred;
1240
1241 if (!(*bytecode = malloc(8))) abort();
1242 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
1243 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1244 return 8;
1245 }
1246 case SSF_D_LE:
1247 {
acd1e437
SH
1248 struct aafilter *x = (void *)f->pred;
1249
1250 if (!(*bytecode = malloc(8))) abort();
1251 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
1252 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1253 return 8;
1254 }
1255 case SSF_S_GE:
1256 {
acd1e437
SH
1257 struct aafilter *x = (void *)f->pred;
1258
1259 if (!(*bytecode = malloc(8))) abort();
1260 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
1261 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1262 return 8;
1263 }
1264 case SSF_S_LE:
1265 {
acd1e437
SH
1266 struct aafilter *x = (void *)f->pred;
1267
1268 if (!(*bytecode = malloc(8))) abort();
1269 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
1270 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1271 return 8;
1272 }
1273
1274 case SSF_AND:
1275 {
2a4fa1c3
AH
1276 char *a1, *a2, *a;
1277 int l1, l2;
acd1e437 1278
aba5acdf
SH
1279 l1 = ssfilter_bytecompile(f->pred, &a1);
1280 l2 = ssfilter_bytecompile(f->post, &a2);
1281 if (!(a = malloc(l1+l2))) abort();
1282 memcpy(a, a1, l1);
1283 memcpy(a+l1, a2, l2);
1284 free(a1); free(a2);
1285 ssfilter_patch(a, l1, l2);
1286 *bytecode = a;
1287 return l1+l2;
1288 }
1289 case SSF_OR:
1290 {
2a4fa1c3
AH
1291 char *a1, *a2, *a;
1292 int l1, l2;
acd1e437 1293
aba5acdf
SH
1294 l1 = ssfilter_bytecompile(f->pred, &a1);
1295 l2 = ssfilter_bytecompile(f->post, &a2);
1296 if (!(a = malloc(l1+l2+4))) abort();
1297 memcpy(a, a1, l1);
1298 memcpy(a+l1+4, a2, l2);
1299 free(a1); free(a2);
acd1e437 1300 *(struct inet_diag_bc_op *)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
aba5acdf
SH
1301 *bytecode = a;
1302 return l1+l2+4;
1303 }
1304 case SSF_NOT:
1305 {
2a4fa1c3
AH
1306 char *a1, *a;
1307 int l1;
acd1e437 1308
aba5acdf
SH
1309 l1 = ssfilter_bytecompile(f->pred, &a1);
1310 if (!(a = malloc(l1+4))) abort();
1311 memcpy(a, a1, l1);
1312 free(a1);
acd1e437 1313 *(struct inet_diag_bc_op *)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
aba5acdf
SH
1314 *bytecode = a;
1315 return l1+4;
1316 }
1317 default:
1318 abort();
1319 }
1320}
1321
b4b0b7d5 1322static int remember_he(struct aafilter *a, struct hostent *he)
aba5acdf 1323{
ae665a52 1324 char **ptr = he->h_addr_list;
aba5acdf
SH
1325 int cnt = 0;
1326 int len;
1327
1328 if (he->h_addrtype == AF_INET)
1329 len = 4;
1330 else if (he->h_addrtype == AF_INET6)
1331 len = 16;
1332 else
1333 return 0;
1334
1335 while (*ptr) {
1336 struct aafilter *b = a;
acd1e437 1337
aba5acdf
SH
1338 if (a->addr.bitlen) {
1339 if ((b = malloc(sizeof(*b))) == NULL)
1340 return cnt;
1341 *b = *a;
1342 b->next = a->next;
1343 a->next = b;
1344 }
1345 memcpy(b->addr.data, *ptr, len);
1346 b->addr.bytelen = len;
1347 b->addr.bitlen = len*8;
1348 b->addr.family = he->h_addrtype;
1349 ptr++;
1350 cnt++;
1351 }
1352 return cnt;
1353}
1354
b4b0b7d5 1355static int get_dns_host(struct aafilter *a, const char *addr, int fam)
aba5acdf
SH
1356{
1357 static int notfirst;
1358 int cnt = 0;
1359 struct hostent *he;
1360
1361 a->addr.bitlen = 0;
1362 if (!notfirst) {
1363 sethostent(1);
1364 notfirst = 1;
1365 }
1366 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
1367 if (he)
1368 cnt = remember_he(a, he);
1369 if (fam == AF_UNSPEC) {
1370 he = gethostbyname2(addr, AF_INET6);
1371 if (he)
1372 cnt += remember_he(a, he);
1373 }
1374 return !cnt;
1375}
1376
acd1e437 1377static int xll_initted;
aba5acdf 1378
b4b0b7d5 1379static void xll_init(void)
aba5acdf
SH
1380{
1381 struct rtnl_handle rth;
acd1e437 1382
d2468da0
SH
1383 if (rtnl_open(&rth, 0) < 0)
1384 exit(1);
1385
aba5acdf
SH
1386 ll_init_map(&rth);
1387 rtnl_close(&rth);
1388 xll_initted = 1;
1389}
1390
b4b0b7d5 1391static const char *xll_index_to_name(int index)
aba5acdf
SH
1392{
1393 if (!xll_initted)
1394 xll_init();
1395 return ll_index_to_name(index);
1396}
1397
b4b0b7d5 1398static int xll_name_to_index(const char *dev)
aba5acdf
SH
1399{
1400 if (!xll_initted)
1401 xll_init();
1402 return ll_name_to_index(dev);
1403}
1404
7871f7db 1405void *parse_hostcond(char *addr, bool is_port)
aba5acdf
SH
1406{
1407 char *port = NULL;
1527a17e 1408 struct aafilter a = { .port = -1 };
aba5acdf 1409 struct aafilter *res;
1527a17e 1410 int fam = preferred_family;
9db7bf15 1411 struct filter *f = &current_filter;
aba5acdf 1412
1527a17e 1413 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
aba5acdf 1414 char *p;
acd1e437 1415
aba5acdf
SH
1416 a.addr.family = AF_UNIX;
1417 if (strncmp(addr, "unix:", 5) == 0)
acd1e437 1418 addr += 5;
aba5acdf
SH
1419 p = strdup(addr);
1420 a.addr.bitlen = 8*strlen(p);
99bb68ff 1421 memcpy(a.addr.data, &p, sizeof(p));
9db7bf15 1422 fam = AF_UNIX;
aba5acdf
SH
1423 goto out;
1424 }
1425
1527a17e 1426 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
aba5acdf
SH
1427 a.addr.family = AF_PACKET;
1428 a.addr.bitlen = 0;
1429 if (strncmp(addr, "link:", 5) == 0)
acd1e437 1430 addr += 5;
aba5acdf
SH
1431 port = strchr(addr, ':');
1432 if (port) {
1433 *port = 0;
1434 if (port[1] && strcmp(port+1, "*")) {
1435 if (get_integer(&a.port, port+1, 0)) {
1436 if ((a.port = xll_name_to_index(port+1)) <= 0)
1437 return NULL;
1438 }
1439 }
1440 }
1441 if (addr[0] && strcmp(addr, "*")) {
1442 unsigned short tmp;
acd1e437 1443
aba5acdf
SH
1444 a.addr.bitlen = 32;
1445 if (ll_proto_a2n(&tmp, addr))
1446 return NULL;
1447 a.addr.data[0] = ntohs(tmp);
1448 }
9db7bf15 1449 fam = AF_PACKET;
aba5acdf
SH
1450 goto out;
1451 }
1452
1527a17e 1453 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
aba5acdf
SH
1454 a.addr.family = AF_NETLINK;
1455 a.addr.bitlen = 0;
1456 if (strncmp(addr, "netlink:", 8) == 0)
acd1e437 1457 addr += 8;
aba5acdf
SH
1458 port = strchr(addr, ':');
1459 if (port) {
1460 *port = 0;
1461 if (port[1] && strcmp(port+1, "*")) {
1462 if (get_integer(&a.port, port+1, 0)) {
1463 if (strcmp(port+1, "kernel") == 0)
1464 a.port = 0;
1465 else
1466 return NULL;
1467 }
1468 }
1469 }
1470 if (addr[0] && strcmp(addr, "*")) {
1471 a.addr.bitlen = 32;
b00daf6a 1472 if (nl_proto_a2n(&a.addr.data[0], addr) == -1)
1473 return NULL;
aba5acdf 1474 }
9db7bf15 1475 fam = AF_NETLINK;
aba5acdf
SH
1476 goto out;
1477 }
1478
1527a17e 1479 if (fam == AF_INET || !strncmp(addr, "inet:", 5)) {
aba5acdf 1480 fam = AF_INET;
1527a17e
VK
1481 if (!strncmp(addr, "inet:", 5))
1482 addr += 5;
1483 } else if (fam == AF_INET6 || !strncmp(addr, "inet6:", 6)) {
aba5acdf 1484 fam = AF_INET6;
1527a17e
VK
1485 if (!strncmp(addr, "inet6:", 6))
1486 addr += 6;
aba5acdf
SH
1487 }
1488
1489 /* URL-like literal [] */
1490 if (addr[0] == '[') {
1491 addr++;
1492 if ((port = strchr(addr, ']')) == NULL)
1493 return NULL;
1494 *port++ = 0;
1495 } else if (addr[0] == '*') {
1496 port = addr+1;
1497 } else {
1498 port = strrchr(strchr(addr, '/') ? : addr, ':');
1499 }
7871f7db
VK
1500
1501 if (is_port)
1502 port = addr;
1503
aba5acdf 1504 if (port && *port) {
7871f7db
VK
1505 if (*port == ':')
1506 *port++ = 0;
1507
aba5acdf
SH
1508 if (*port && *port != '*') {
1509 if (get_integer(&a.port, port, 0)) {
1510 struct servent *se1 = NULL;
1511 struct servent *se2 = NULL;
acd1e437 1512
aba5acdf
SH
1513 if (current_filter.dbs&(1<<UDP_DB))
1514 se1 = getservbyname(port, UDP_PROTO);
1515 if (current_filter.dbs&(1<<TCP_DB))
1516 se2 = getservbyname(port, TCP_PROTO);
1517 if (se1 && se2 && se1->s_port != se2->s_port) {
1518 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1519 return NULL;
1520 }
1521 if (!se1)
1522 se1 = se2;
1523 if (se1) {
1524 a.port = ntohs(se1->s_port);
1525 } else {
1526 struct scache *s;
acd1e437 1527
aba5acdf
SH
1528 for (s = rlist; s; s = s->next) {
1529 if ((s->proto == UDP_PROTO &&
1530 (current_filter.dbs&(1<<UDP_DB))) ||
1531 (s->proto == TCP_PROTO &&
1532 (current_filter.dbs&(1<<TCP_DB)))) {
1533 if (s->name && strcmp(s->name, port) == 0) {
1534 if (a.port > 0 && a.port != s->port) {
1535 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1536 return NULL;
1537 }
1538 a.port = s->port;
1539 }
1540 }
1541 }
1542 if (a.port <= 0) {
1543 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1544 return NULL;
1545 }
1546 }
1547 }
1548 }
1549 }
7871f7db 1550 if (!is_port && addr && *addr && *addr != '*') {
aba5acdf
SH
1551 if (get_prefix_1(&a.addr, addr, fam)) {
1552 if (get_dns_host(&a, addr, fam)) {
1553 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1554 return NULL;
1555 }
1556 }
1557 }
1558
9db7bf15 1559out:
1527a17e 1560 if (fam != AF_UNSPEC) {
e56a959e 1561 int states = f->states;
1527a17e 1562 f->families = 0;
9db7bf15 1563 filter_af_set(f, fam);
e56a959e 1564 filter_states_set(f, states);
1527a17e 1565 }
9db7bf15 1566
aba5acdf
SH
1567 res = malloc(sizeof(*res));
1568 if (res)
1569 memcpy(res, &a, sizeof(a));
1570 return res;
1571}
1572
8250bc9f
VK
1573static char *proto_name(int protocol)
1574{
1575 switch (protocol) {
235c4453
NA
1576 case 0:
1577 return "raw";
8250bc9f
VK
1578 case IPPROTO_UDP:
1579 return "udp";
1580 case IPPROTO_TCP:
1581 return "tcp";
1582 case IPPROTO_DCCP:
1583 return "dccp";
1584 }
1585
1586 return "???";
1587}
1588
055840f2 1589static void inet_stats_print(struct sockstat *s, int protocol)
8250bc9f
VK
1590{
1591 char *buf = NULL;
1592
2d791bc8 1593 sock_state_print(s, proto_name(protocol));
8250bc9f 1594
b217df10
VK
1595 inet_addr_print(&s->local, s->lport, s->iface);
1596 inet_addr_print(&s->remote, s->rport, 0);
8250bc9f 1597
8250bc9f
VK
1598 if (show_proc_ctx || show_sock_ctx) {
1599 if (find_entry(s->ino, &buf,
1600 (show_proc_ctx & show_sock_ctx) ?
1601 PROC_SOCK_CTX : PROC_CTX) > 0) {
1602 printf(" users:(%s)", buf);
1603 free(buf);
1604 }
1605 } else if (show_users) {
1606 if (find_entry(s->ino, &buf, USERS) > 0) {
1607 printf(" users:(%s)", buf);
1608 free(buf);
1609 }
1610 }
1611}
1612
055840f2 1613static int proc_parse_inet_addr(char *loc, char *rem, int family, struct
acd1e437 1614 sockstat * s)
8250bc9f
VK
1615{
1616 s->local.family = s->remote.family = family;
1617 if (family == AF_INET) {
acd1e437
SH
1618 sscanf(loc, "%x:%x", s->local.data, (unsigned *)&s->lport);
1619 sscanf(rem, "%x:%x", s->remote.data, (unsigned *)&s->rport);
8250bc9f
VK
1620 s->local.bytelen = s->remote.bytelen = 4;
1621 return 0;
1622 } else {
1623 sscanf(loc, "%08x%08x%08x%08x:%x",
1624 s->local.data,
1625 s->local.data + 1,
1626 s->local.data + 2,
1627 s->local.data + 3,
1628 &s->lport);
1629 sscanf(rem, "%08x%08x%08x%08x:%x",
1630 s->remote.data,
1631 s->remote.data + 1,
1632 s->remote.data + 2,
1633 s->remote.data + 3,
1634 &s->rport);
1635 s->local.bytelen = s->remote.bytelen = 16;
1636 return 0;
1637 }
1638 return -1;
1639}
1640
1641static int proc_inet_split_line(char *line, char **loc, char **rem, char **data)
aba5acdf 1642{
aba5acdf 1643 char *p;
ae665a52 1644
aba5acdf
SH
1645 if ((p = strchr(line, ':')) == NULL)
1646 return -1;
ae665a52 1647
8250bc9f
VK
1648 *loc = p+2;
1649 if ((p = strchr(*loc, ':')) == NULL)
aba5acdf 1650 return -1;
ae665a52 1651
8250bc9f
VK
1652 p[5] = 0;
1653 *rem = p+6;
1654 if ((p = strchr(*rem, ':')) == NULL)
aba5acdf 1655 return -1;
8250bc9f 1656
aba5acdf 1657 p[5] = 0;
8250bc9f
VK
1658 *data = p+6;
1659 return 0;
1660}
ae665a52 1661
8250bc9f
VK
1662static char *sprint_bw(char *buf, double bw)
1663{
1664 if (bw > 1000000.)
acd1e437 1665 sprintf(buf, "%.1fM", bw / 1000000.);
8250bc9f 1666 else if (bw > 1000.)
acd1e437 1667 sprintf(buf, "%.1fK", bw / 1000.);
8250bc9f
VK
1668 else
1669 sprintf(buf, "%g", bw);
aba5acdf 1670
8250bc9f
VK
1671 return buf;
1672}
ae665a52 1673
8250bc9f
VK
1674static void tcp_stats_print(struct tcpstat *s)
1675{
1676 char b1[64];
1677
1678 if (s->has_ts_opt)
1679 printf(" ts");
1680 if (s->has_sack_opt)
1681 printf(" sack");
1682 if (s->has_ecn_opt)
1683 printf(" ecn");
1684 if (s->has_ecnseen_opt)
1685 printf(" ecnseen");
1686 if (s->has_fastopen_opt)
1687 printf(" fastopen");
d2055ea5 1688 if (s->cong_alg[0])
8250bc9f
VK
1689 printf(" %s", s->cong_alg);
1690 if (s->has_wscale_opt)
1691 printf(" wscale:%d,%d", s->snd_wscale, s->rcv_wscale);
1692 if (s->rto)
1693 printf(" rto:%g", s->rto);
1694 if (s->backoff)
1695 printf(" backoff:%u", s->backoff);
1696 if (s->rtt)
1697 printf(" rtt:%g/%g", s->rtt, s->rttvar);
1698 if (s->ato)
1699 printf(" ato:%g", s->ato);
1700
1701 if (s->qack)
1702 printf(" qack:%d", s->qack);
1703 if (s->qack & 1)
1704 printf(" bidir");
1705
1706 if (s->mss)
1707 printf(" mss:%d", s->mss);
3bf5445c 1708 if (s->cwnd)
8250bc9f
VK
1709 printf(" cwnd:%d", s->cwnd);
1710 if (s->ssthresh)
1711 printf(" ssthresh:%d", s->ssthresh);
1712
1a4dda71
ED
1713 if (s->bytes_acked)
1714 printf(" bytes_acked:%llu", s->bytes_acked);
1715 if (s->bytes_received)
1716 printf(" bytes_received:%llu", s->bytes_received);
ecb435ea
CG
1717 if (s->segs_out)
1718 printf(" segs_out:%u", s->segs_out);
1719 if (s->segs_in)
1720 printf(" segs_in:%u", s->segs_in);
414aeec9
MKL
1721 if (s->data_segs_out)
1722 printf(" data_segs_out:%u", s->data_segs_out);
1723 if (s->data_segs_in)
1724 printf(" data_segs_in:%u", s->data_segs_in);
1a4dda71 1725
8250bc9f
VK
1726 if (s->dctcp && s->dctcp->enabled) {
1727 struct dctcpstat *dctcp = s->dctcp;
1728
3bf5445c 1729 printf(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
8250bc9f
VK
1730 dctcp->ce_state, dctcp->alpha, dctcp->ab_ecn,
1731 dctcp->ab_tot);
1732 } else if (s->dctcp) {
3bf5445c 1733 printf(" dctcp:fallback_mode");
8250bc9f
VK
1734 }
1735
1736 if (s->send_bps)
1737 printf(" send %sbps", sprint_bw(b1, s->send_bps));
1738 if (s->lastsnd)
1739 printf(" lastsnd:%u", s->lastsnd);
1740 if (s->lastrcv)
1741 printf(" lastrcv:%u", s->lastrcv);
1742 if (s->lastack)
1743 printf(" lastack:%u", s->lastack);
1744
1745 if (s->pacing_rate) {
1746 printf(" pacing_rate %sbps", sprint_bw(b1, s->pacing_rate));
1747 if (s->pacing_rate_max)
1748 printf("/%sbps", sprint_bw(b1,
1749 s->pacing_rate_max));
1750 }
1751
1752 if (s->unacked)
1753 printf(" unacked:%u", s->unacked);
1754 if (s->retrans || s->retrans_total)
1755 printf(" retrans:%u/%u", s->retrans, s->retrans_total);
1756 if (s->lost)
1757 printf(" lost:%u", s->lost);
055840f2 1758 if (s->sacked && s->ss.state != SS_LISTEN)
8250bc9f
VK
1759 printf(" sacked:%u", s->sacked);
1760 if (s->fackets)
1761 printf(" fackets:%u", s->fackets);
1762 if (s->reordering != 3)
1763 printf(" reordering:%d", s->reordering);
1764 if (s->rcv_rtt)
1765 printf(" rcv_rtt:%g", s->rcv_rtt);
1766 if (s->rcv_space)
1767 printf(" rcv_space:%d", s->rcv_space);
9e99e495
SH
1768 if (s->not_sent)
1769 printf(" notsent:%u", s->not_sent);
1770 if (s->min_rtt)
1771 printf(" minrtt:%g", s->min_rtt);
8250bc9f
VK
1772}
1773
055840f2
VK
1774static void tcp_timer_print(struct tcpstat *s)
1775{
1776 if (s->timer) {
1777 if (s->timer > 4)
1778 s->timer = 5;
1779 printf(" timer:(%s,%s,%d)",
1780 tmr_name[s->timer],
1781 print_ms_timer(s->timeout),
1782 s->retrans);
1783 }
1784}
1785
8250bc9f
VK
1786static int tcp_show_line(char *line, const struct filter *f, int family)
1787{
1788 int rto = 0, ato = 0;
1789 struct tcpstat s = {};
1790 char *loc, *rem, *data;
1791 char opt[256];
1792 int n;
1793 int hz = get_user_hz();
1794
1795 if (proc_inet_split_line(line, &loc, &rem, &data))
1796 return -1;
1797
1798 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
acd1e437 1799
8250bc9f
VK
1800 if (!(f->states & (1 << state)))
1801 return 0;
1802
055840f2 1803 proc_parse_inet_addr(loc, rem, family, &s.ss);
ae665a52 1804
055840f2 1805 if (f->f && run_ssfilter(f->f, &s.ss) == 0)
aba5acdf 1806 return 0;
ae665a52 1807
aba5acdf 1808 opt[0] = 0;
e7113c61 1809 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
055840f2
VK
1810 &s.ss.state, &s.ss.wq, &s.ss.rq,
1811 &s.timer, &s.timeout, &s.retrans, &s.ss.uid, &s.probes,
1812 &s.ss.ino, &s.ss.refcnt, &s.ss.sk, &rto, &ato, &s.qack, &s.cwnd,
1813 &s.ssthresh, opt);
ae665a52 1814
aba5acdf
SH
1815 if (n < 17)
1816 opt[0] = 0;
ae665a52 1817
aba5acdf 1818 if (n < 12) {
8250bc9f 1819 rto = 0;
aba5acdf
SH
1820 s.cwnd = 2;
1821 s.ssthresh = -1;
8250bc9f 1822 ato = s.qack = 0;
aba5acdf 1823 }
ae665a52 1824
8250bc9f
VK
1825 s.retrans = s.timer != 1 ? s.probes : s.retrans;
1826 s.timeout = (s.timeout * 1000 + hz - 1) / hz;
1827 s.ato = (double)ato / hz;
1828 s.qack /= 2;
1829 s.rto = (double)rto;
1830 s.ssthresh = s.ssthresh == -1 ? 0 : s.ssthresh;
1831 s.rto = s.rto != 3 * hz ? s.rto / hz : 0;
ae665a52 1832
055840f2
VK
1833 inet_stats_print(&s.ss, IPPROTO_TCP);
1834
1835 if (show_options)
1836 tcp_timer_print(&s);
116ac927 1837
aba5acdf 1838 if (show_details) {
f1b39e1b 1839 sock_details_print(&s.ss);
aba5acdf
SH
1840 if (opt[0])
1841 printf(" opt:\"%s\"", opt);
1842 }
aba5acdf 1843
8250bc9f
VK
1844 if (show_tcpinfo)
1845 tcp_stats_print(&s);
1846
1847 printf("\n");
aba5acdf
SH
1848 return 0;
1849}
1850
ab01dbbb
SH
1851static int generic_record_read(FILE *fp,
1852 int (*worker)(char*, const struct filter *, int),
1853 const struct filter *f, int fam)
aba5acdf 1854{
ab01dbbb 1855 char line[256];
aba5acdf 1856
ab01dbbb
SH
1857 /* skip header */
1858 if (fgets(line, sizeof(line), fp) == NULL)
aba5acdf 1859 goto outerr;
ab01dbbb
SH
1860
1861 while (fgets(line, sizeof(line), fp) != NULL) {
1862 int n = strlen(line);
acd1e437 1863
ab01dbbb
SH
1864 if (n == 0 || line[n-1] != '\n') {
1865 errno = -EINVAL;
1866 return -1;
aba5acdf 1867 }
ab01dbbb 1868 line[n-1] = 0;
aba5acdf 1869
ab01dbbb
SH
1870 if (worker(line, f, fam) < 0)
1871 return 0;
1872 }
aba5acdf 1873outerr:
ab01dbbb
SH
1874
1875 return ferror(fp) ? -1 : 0;
aba5acdf 1876}
ae665a52 1877
51ff9f24
HFS
1878static void print_skmeminfo(struct rtattr *tb[], int attrtype)
1879{
1880 const __u32 *skmeminfo;
db08bdb8
VK
1881
1882 if (!tb[attrtype]) {
1883 if (attrtype == INET_DIAG_SKMEMINFO) {
1884 if (!tb[INET_DIAG_MEMINFO])
1885 return;
1886
1887 const struct inet_diag_meminfo *minfo =
1888 RTA_DATA(tb[INET_DIAG_MEMINFO]);
1889
1890 printf(" mem:(r%u,w%u,f%u,t%u)",
1891 minfo->idiag_rmem,
1892 minfo->idiag_wmem,
1893 minfo->idiag_fmem,
1894 minfo->idiag_tmem);
1895 }
51ff9f24 1896 return;
db08bdb8
VK
1897 }
1898
51ff9f24
HFS
1899 skmeminfo = RTA_DATA(tb[attrtype]);
1900
1901 printf(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
1902 skmeminfo[SK_MEMINFO_RMEM_ALLOC],
1903 skmeminfo[SK_MEMINFO_RCVBUF],
1904 skmeminfo[SK_MEMINFO_WMEM_ALLOC],
1905 skmeminfo[SK_MEMINFO_SNDBUF],
1906 skmeminfo[SK_MEMINFO_FWD_ALLOC],
1907 skmeminfo[SK_MEMINFO_WMEM_QUEUED],
1908 skmeminfo[SK_MEMINFO_OPTMEM]);
1909
1910 if (RTA_PAYLOAD(tb[attrtype]) >=
1911 (SK_MEMINFO_BACKLOG + 1) * sizeof(__u32))
1912 printf(",bl%u", skmeminfo[SK_MEMINFO_BACKLOG]);
1913
6df9c7a0
ED
1914 if (RTA_PAYLOAD(tb[attrtype]) >=
1915 (SK_MEMINFO_DROPS + 1) * sizeof(__u32))
1916 printf(",d%u", skmeminfo[SK_MEMINFO_DROPS]);
1917
51ff9f24
HFS
1918 printf(")");
1919}
1920
8250bc9f
VK
1921#define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
1922
5b816047
PE
1923static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r,
1924 struct rtattr *tb[])
7d105b56 1925{
b4b0b7d5 1926 double rtt = 0;
8250bc9f 1927 struct tcpstat s = {};
7d105b56 1928
055840f2
VK
1929 s.ss.state = r->idiag_state;
1930
db08bdb8 1931 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
7d105b56 1932
351efcde 1933 if (tb[INET_DIAG_INFO]) {
05e18118 1934 struct tcp_info *info;
351efcde 1935 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
05e18118
SH
1936
1937 /* workaround for older kernels with less fields */
1938 if (len < sizeof(*info)) {
1939 info = alloca(sizeof(*info));
351efcde 1940 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
656e8fdd 1941 memset((char *)info + len, 0, sizeof(*info) - len);
05e18118 1942 } else
351efcde 1943 info = RTA_DATA(tb[INET_DIAG_INFO]);
05e18118 1944
b4b0b7d5 1945 if (show_options) {
8250bc9f
VK
1946 s.has_ts_opt = TCPI_HAS_OPT(info, TCPI_OPT_TIMESTAMPS);
1947 s.has_sack_opt = TCPI_HAS_OPT(info, TCPI_OPT_SACK);
1948 s.has_ecn_opt = TCPI_HAS_OPT(info, TCPI_OPT_ECN);
1949 s.has_ecnseen_opt = TCPI_HAS_OPT(info, TCPI_OPT_ECN_SEEN);
1950 s.has_fastopen_opt = TCPI_HAS_OPT(info, TCPI_OPT_SYN_DATA);
b4b0b7d5 1951 }
52d5ac3f 1952
d2055ea5
ED
1953 if (tb[INET_DIAG_CONG])
1954 strncpy(s.cong_alg,
1955 rta_getattr_str(tb[INET_DIAG_CONG]),
1956 sizeof(s.cong_alg) - 1);
8250bc9f
VK
1957
1958 if (TCPI_HAS_OPT(info, TCPI_OPT_WSCALE)) {
1959 s.has_wscale_opt = true;
1960 s.snd_wscale = info->tcpi_snd_wscale;
1961 s.rcv_wscale = info->tcpi_rcv_wscale;
1962 }
ea8fc104 1963
7d105b56 1964 if (info->tcpi_rto && info->tcpi_rto != 3000000)
8250bc9f
VK
1965 s.rto = (double)info->tcpi_rto / 1000;
1966
1967 s.backoff = info->tcpi_backoff;
1968 s.rtt = (double)info->tcpi_rtt / 1000;
1969 s.rttvar = (double)info->tcpi_rttvar / 1000;
11ba90fc 1970 s.ato = (double)info->tcpi_ato / 1000;
8250bc9f
VK
1971 s.mss = info->tcpi_snd_mss;
1972 s.rcv_space = info->tcpi_rcv_space;
1973 s.rcv_rtt = (double)info->tcpi_rcv_rtt / 1000;
1974 s.lastsnd = info->tcpi_last_data_sent;
1975 s.lastrcv = info->tcpi_last_data_recv;
1976 s.lastack = info->tcpi_last_ack_recv;
1977 s.unacked = info->tcpi_unacked;
1978 s.retrans = info->tcpi_retrans;
1979 s.retrans_total = info->tcpi_total_retrans;
1980 s.lost = info->tcpi_lost;
1981 s.sacked = info->tcpi_sacked;
1982 s.reordering = info->tcpi_reordering;
1983 s.rcv_space = info->tcpi_rcv_space;
1984 s.cwnd = info->tcpi_snd_cwnd;
1985
7d105b56 1986 if (info->tcpi_snd_ssthresh < 0xFFFF)
8250bc9f 1987 s.ssthresh = info->tcpi_snd_ssthresh;
52d5ac3f 1988
b4b0b7d5 1989 rtt = (double) info->tcpi_rtt;
351efcde 1990 if (tb[INET_DIAG_VEGASINFO]) {
05e18118 1991 const struct tcpvegas_info *vinfo
351efcde 1992 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
7d105b56 1993
ae665a52 1994 if (vinfo->tcpv_enabled &&
8250bc9f 1995 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
ea8fc104 1996 rtt = vinfo->tcpv_rtt;
b4b0b7d5
SH
1997 }
1998
907e1aca 1999 if (tb[INET_DIAG_DCTCPINFO]) {
8250bc9f
VK
2000 struct dctcpstat *dctcp = malloc(sizeof(struct
2001 dctcpstat));
2002
907e1aca
DB
2003 const struct tcp_dctcp_info *dinfo
2004 = RTA_DATA(tb[INET_DIAG_DCTCPINFO]);
2005
8250bc9f
VK
2006 dctcp->enabled = !!dinfo->dctcp_enabled;
2007 dctcp->ce_state = dinfo->dctcp_ce_state;
2008 dctcp->alpha = dinfo->dctcp_alpha;
2009 dctcp->ab_ecn = dinfo->dctcp_ab_ecn;
2010 dctcp->ab_tot = dinfo->dctcp_ab_tot;
2011 s.dctcp = dctcp;
907e1aca
DB
2012 }
2013
b4b0b7d5 2014 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
8250bc9f
VK
2015 s.send_bps = (double) info->tcpi_snd_cwnd *
2016 (double)info->tcpi_snd_mss * 8000000. / rtt;
7d105b56 2017 }
b4b0b7d5 2018
eb6028b2 2019 if (info->tcpi_pacing_rate &&
8250bc9f
VK
2020 info->tcpi_pacing_rate != ~0ULL) {
2021 s.pacing_rate = info->tcpi_pacing_rate * 8.;
eb6028b2
ED
2022
2023 if (info->tcpi_max_pacing_rate &&
8250bc9f
VK
2024 info->tcpi_max_pacing_rate != ~0ULL)
2025 s.pacing_rate_max = info->tcpi_max_pacing_rate * 8.;
eb6028b2 2026 }
1a4dda71
ED
2027 s.bytes_acked = info->tcpi_bytes_acked;
2028 s.bytes_received = info->tcpi_bytes_received;
ecb435ea
CG
2029 s.segs_out = info->tcpi_segs_out;
2030 s.segs_in = info->tcpi_segs_in;
414aeec9
MKL
2031 s.data_segs_out = info->tcpi_data_segs_out;
2032 s.data_segs_in = info->tcpi_data_segs_in;
9e99e495 2033 s.not_sent = info->tcpi_notsent_bytes;
d9ba887e
ED
2034 if (info->tcpi_min_rtt && info->tcpi_min_rtt != ~0U)
2035 s.min_rtt = (double) info->tcpi_min_rtt / 1000;
8250bc9f 2036 tcp_stats_print(&s);
92de1c2c 2037 free(s.dctcp);
77a8ca81 2038 }
77a8ca81
PE
2039}
2040
82d73ea0 2041static void parse_diag_msg(struct nlmsghdr *nlh, struct sockstat *s)
aba5acdf 2042{
acd1e437 2043 struct rtattr *tb[INET_DIAG_MAX+1];
351efcde 2044 struct inet_diag_msg *r = NLMSG_DATA(nlh);
aba5acdf 2045
acd1e437 2046 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr *)(r+1),
5b816047
PE
2047 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2048
82d73ea0
DA
2049 s->state = r->idiag_state;
2050 s->local.family = s->remote.family = r->idiag_family;
2051 s->lport = ntohs(r->id.idiag_sport);
2052 s->rport = ntohs(r->id.idiag_dport);
2053 s->wq = r->idiag_wqueue;
2054 s->rq = r->idiag_rqueue;
2055 s->ino = r->idiag_inode;
2056 s->uid = r->idiag_uid;
2057 s->iface = r->id.idiag_if;
2058 s->sk = cookie_sk_get(&r->id.idiag_cookie[0]);
2059
2060 if (s->local.family == AF_INET)
2061 s->local.bytelen = s->remote.bytelen = 4;
2062 else
2063 s->local.bytelen = s->remote.bytelen = 16;
8250bc9f 2064
82d73ea0
DA
2065 memcpy(s->local.data, r->id.idiag_src, s->local.bytelen);
2066 memcpy(s->remote.data, r->id.idiag_dst, s->local.bytelen);
2067}
aba5acdf 2068
82d73ea0
DA
2069static int inet_show_sock(struct nlmsghdr *nlh,
2070 struct sockstat *s,
2071 int protocol)
2072{
2073 struct rtattr *tb[INET_DIAG_MAX+1];
2074 struct inet_diag_msg *r = NLMSG_DATA(nlh);
2075
2076 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr *)(r+1),
2077 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
aba5acdf 2078
6885e3bf
CG
2079 if (tb[INET_DIAG_PROTOCOL])
2080 protocol = *(__u8 *)RTA_DATA(tb[INET_DIAG_PROTOCOL]);
2081
82d73ea0 2082 inet_stats_print(s, protocol);
116ac927 2083
055840f2
VK
2084 if (show_options) {
2085 struct tcpstat t = {};
2086
2087 t.timer = r->idiag_timer;
2088 t.timeout = r->idiag_expires;
2089 t.retrans = r->idiag_retrans;
2090 tcp_timer_print(&t);
2091 }
2092
aba5acdf 2093 if (show_details) {
82d73ea0
DA
2094 sock_details_print(s);
2095 if (s->local.family == AF_INET6 && tb[INET_DIAG_SKV6ONLY]) {
f32dc746 2096 unsigned char v6only;
acd1e437 2097
f32dc746
PS
2098 v6only = *(__u8 *)RTA_DATA(tb[INET_DIAG_SKV6ONLY]);
2099 printf(" v6only:%u", v6only);
2100 }
5b816047
PE
2101 if (tb[INET_DIAG_SHUTDOWN]) {
2102 unsigned char mask;
acd1e437 2103
5b816047
PE
2104 mask = *(__u8 *)RTA_DATA(tb[INET_DIAG_SHUTDOWN]);
2105 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2106 }
aba5acdf 2107 }
8250bc9f 2108
aba5acdf 2109 if (show_mem || show_tcpinfo) {
7d105b56 2110 printf("\n\t");
5b816047 2111 tcp_show_info(nlh, r, tb);
aba5acdf 2112 }
7d105b56 2113
aba5acdf 2114 printf("\n");
aba5acdf 2115 return 0;
aba5acdf
SH
2116}
2117
746a695f 2118static int tcpdiag_send(int fd, int protocol, struct filter *f)
aba5acdf 2119{
aba5acdf
SH
2120 struct sockaddr_nl nladdr;
2121 struct {
2122 struct nlmsghdr nlh;
351efcde 2123 struct inet_diag_req r;
aba5acdf
SH
2124 } req;
2125 char *bc = NULL;
2126 int bclen;
2127 struct msghdr msg;
2128 struct rtattr rta;
aba5acdf
SH
2129 struct iovec iov[3];
2130
346f8ca8
PE
2131 if (protocol == IPPROTO_UDP)
2132 return -1;
2133
aba5acdf
SH
2134 memset(&nladdr, 0, sizeof(nladdr));
2135 nladdr.nl_family = AF_NETLINK;
2136
2137 req.nlh.nlmsg_len = sizeof(req);
3fe5b534
PE
2138 if (protocol == IPPROTO_TCP)
2139 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
2140 else
2141 req.nlh.nlmsg_type = DCCPDIAG_GETSOCK;
aba5acdf
SH
2142 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
2143 req.nlh.nlmsg_pid = 0;
8a4025f6 2144 req.nlh.nlmsg_seq = MAGIC_SEQ;
aba5acdf 2145 memset(&req.r, 0, sizeof(req.r));
351efcde
SH
2146 req.r.idiag_family = AF_INET;
2147 req.r.idiag_states = f->states;
910b0397 2148 if (show_mem) {
ae665a52 2149 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
910b0397
SW
2150 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
2151 }
b4b0b7d5 2152
7d105b56 2153 if (show_tcpinfo) {
351efcde
SH
2154 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
2155 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
2156 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
7d105b56 2157 }
aba5acdf 2158
ae665a52
SH
2159 iov[0] = (struct iovec){
2160 .iov_base = &req,
2161 .iov_len = sizeof(req)
ea8fc104 2162 };
aba5acdf
SH
2163 if (f->f) {
2164 bclen = ssfilter_bytecompile(f->f, &bc);
351efcde 2165 rta.rta_type = INET_DIAG_REQ_BYTECODE;
aba5acdf
SH
2166 rta.rta_len = RTA_LENGTH(bclen);
2167 iov[1] = (struct iovec){ &rta, sizeof(rta) };
2168 iov[2] = (struct iovec){ bc, bclen };
2169 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
2170 }
2171
2172 msg = (struct msghdr) {
acd1e437 2173 .msg_name = (void *)&nladdr,
ea8fc104 2174 .msg_namelen = sizeof(nladdr),
ae665a52 2175 .msg_iov = iov,
ea8fc104 2176 .msg_iovlen = f->f ? 3 : 1,
aba5acdf
SH
2177 };
2178
930a75f9
ED
2179 if (sendmsg(fd, &msg, 0) < 0) {
2180 close(fd);
aba5acdf 2181 return -1;
930a75f9 2182 }
aba5acdf 2183
746a695f
PE
2184 return 0;
2185}
2186
886d19d6
PE
2187static int sockdiag_send(int family, int fd, int protocol, struct filter *f)
2188{
2189 struct sockaddr_nl nladdr;
acd1e437 2190
5fb421d4 2191 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
886d19d6
PE
2192 char *bc = NULL;
2193 int bclen;
2194 struct msghdr msg;
2195 struct rtattr rta;
2196 struct iovec iov[3];
2197
2198 if (family == PF_UNSPEC)
2199 return tcpdiag_send(fd, protocol, f);
2200
2201 memset(&nladdr, 0, sizeof(nladdr));
2202 nladdr.nl_family = AF_NETLINK;
2203
886d19d6
PE
2204 memset(&req.r, 0, sizeof(req.r));
2205 req.r.sdiag_family = family;
2206 req.r.sdiag_protocol = protocol;
2207 req.r.idiag_states = f->states;
2208 if (show_mem) {
2209 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
2210 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
2211 }
2212
2213 if (show_tcpinfo) {
2214 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
2215 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
2216 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
2217 }
2218
2219 iov[0] = (struct iovec){
2220 .iov_base = &req,
2221 .iov_len = sizeof(req)
2222 };
2223 if (f->f) {
2224 bclen = ssfilter_bytecompile(f->f, &bc);
2225 rta.rta_type = INET_DIAG_REQ_BYTECODE;
2226 rta.rta_len = RTA_LENGTH(bclen);
2227 iov[1] = (struct iovec){ &rta, sizeof(rta) };
2228 iov[2] = (struct iovec){ bc, bclen };
2229 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
2230 }
2231
2232 msg = (struct msghdr) {
acd1e437 2233 .msg_name = (void *)&nladdr,
886d19d6
PE
2234 .msg_namelen = sizeof(nladdr),
2235 .msg_iov = iov,
2236 .msg_iovlen = f->f ? 3 : 1,
2237 };
2238
2239 if (sendmsg(fd, &msg, 0) < 0) {
2240 close(fd);
2241 return -1;
2242 }
2243
2244 return 0;
2245}
2246
486ccd99
VK
2247struct inet_diag_arg {
2248 struct filter *f;
2249 int protocol;
fb2594c1 2250 struct rtnl_handle *rth;
486ccd99 2251};
aba5acdf 2252
b38e7409 2253static int kill_inet_sock(struct nlmsghdr *h, void *arg)
fb2594c1
LC
2254{
2255 struct inet_diag_msg *d = NLMSG_DATA(h);
2256 struct inet_diag_arg *diag_arg = arg;
2257 struct rtnl_handle *rth = diag_arg->rth;
acd1e437 2258
fb2594c1
LC
2259 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
2260
2261 req.nlh.nlmsg_type = SOCK_DESTROY;
2262 req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2263 req.nlh.nlmsg_seq = ++rth->seq;
2264 req.r.sdiag_family = d->idiag_family;
2265 req.r.sdiag_protocol = diag_arg->protocol;
2266 req.r.id = d->id;
2267
2268 return rtnl_talk(rth, &req.nlh, NULL, 0);
2269}
2270
486ccd99
VK
2271static int show_one_inet_sock(const struct sockaddr_nl *addr,
2272 struct nlmsghdr *h, void *arg)
2273{
2274 int err;
2275 struct inet_diag_arg *diag_arg = arg;
2276 struct inet_diag_msg *r = NLMSG_DATA(h);
82d73ea0 2277 struct sockstat s = {};
aba5acdf 2278
486ccd99
VK
2279 if (!(diag_arg->f->families & (1 << r->idiag_family)))
2280 return 0;
82d73ea0
DA
2281
2282 parse_diag_msg(h, &s);
2283
2284 if (diag_arg->f->f && run_ssfilter(diag_arg->f->f, &s) == 0)
2285 return 0;
2286
b38e7409 2287 if (diag_arg->f->kill && kill_inet_sock(h, arg) != 0) {
fb2594c1
LC
2288 if (errno == EOPNOTSUPP || errno == ENOENT) {
2289 /* Socket can't be closed, or is already closed. */
2290 return 0;
2291 } else {
2292 perror("SOCK_DESTROY answers");
2293 return -1;
2294 }
2295 }
82d73ea0
DA
2296
2297 err = inet_show_sock(h, &s, diag_arg->protocol);
2298 if (err < 0)
486ccd99 2299 return err;
aba5acdf 2300
486ccd99
VK
2301 return 0;
2302}
886d19d6 2303
486ccd99
VK
2304static int inet_show_netlink(struct filter *f, FILE *dump_fp, int protocol)
2305{
2306 int err = 0;
fb2594c1 2307 struct rtnl_handle rth, rth2;
486ccd99
VK
2308 int family = PF_INET;
2309 struct inet_diag_arg arg = { .f = f, .protocol = protocol };
886d19d6 2310
486ccd99
VK
2311 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
2312 return -1;
fb2594c1
LC
2313
2314 if (f->kill) {
2315 if (rtnl_open_byproto(&rth2, 0, NETLINK_SOCK_DIAG)) {
2316 rtnl_close(&rth);
2317 return -1;
2318 }
2319 arg.rth = &rth2;
2320 }
2321
486ccd99
VK
2322 rth.dump = MAGIC_SEQ;
2323 rth.dump_fp = dump_fp;
518af1e0
ED
2324 if (preferred_family == PF_INET6)
2325 family = PF_INET6;
886d19d6 2326
486ccd99
VK
2327again:
2328 if ((err = sockdiag_send(family, rth.fd, protocol, f)))
2329 goto Exit;
aba5acdf 2330
486ccd99
VK
2331 if ((err = rtnl_dump_filter(&rth, show_one_inet_sock, &arg))) {
2332 if (family != PF_UNSPEC) {
2333 family = PF_UNSPEC;
2334 goto again;
aba5acdf 2335 }
486ccd99 2336 goto Exit;
aba5acdf 2337 }
518af1e0 2338 if (family == PF_INET && preferred_family != PF_INET) {
886d19d6
PE
2339 family = PF_INET6;
2340 goto again;
2341 }
2342
486ccd99
VK
2343Exit:
2344 rtnl_close(&rth);
fb2594c1
LC
2345 if (arg.rth)
2346 rtnl_close(arg.rth);
486ccd99 2347 return err;
aba5acdf
SH
2348}
2349
ab01dbbb 2350static int tcp_show_netlink_file(struct filter *f)
aba5acdf
SH
2351{
2352 FILE *fp;
e557212e 2353 char buf[16384];
aba5acdf
SH
2354
2355 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
2356 perror("fopen($TCPDIAG_FILE)");
2357 return -1;
2358 }
2359
2360 while (1) {
2361 int status, err;
acd1e437 2362 struct nlmsghdr *h = (struct nlmsghdr *)buf;
82d73ea0 2363 struct sockstat s = {};
aba5acdf
SH
2364
2365 status = fread(buf, 1, sizeof(*h), fp);
2366 if (status < 0) {
2367 perror("Reading header from $TCPDIAG_FILE");
2368 return -1;
2369 }
2370 if (status != sizeof(*h)) {
2371 perror("Unexpected EOF reading $TCPDIAG_FILE");
2372 return -1;
2373 }
2374
2375 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
2376
2377 if (status < 0) {
2378 perror("Reading $TCPDIAG_FILE");
2379 return -1;
2380 }
2381 if (status + sizeof(*h) < h->nlmsg_len) {
2382 perror("Unexpected EOF reading $TCPDIAG_FILE");
2383 return -1;
2384 }
2385
2386 /* The only legal exit point */
2387 if (h->nlmsg_type == NLMSG_DONE)
2388 return 0;
2389
2390 if (h->nlmsg_type == NLMSG_ERROR) {
acd1e437
SH
2391 struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(h);
2392
aba5acdf
SH
2393 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2394 fprintf(stderr, "ERROR truncated\n");
2395 } else {
2396 errno = -err->error;
2397 perror("TCPDIAG answered");
2398 }
2399 return -1;
2400 }
2401
82d73ea0
DA
2402 parse_diag_msg(h, &s);
2403
2404 if (f && f->f && run_ssfilter(f->f, &s) == 0)
2405 continue;
2406
2407 err = inet_show_sock(h, &s, IPPROTO_TCP);
aba5acdf
SH
2408 if (err < 0)
2409 return err;
2410 }
2411}
2412
ab01dbbb 2413static int tcp_show(struct filter *f, int socktype)
aba5acdf 2414{
ab01dbbb 2415 FILE *fp = NULL;
aba5acdf
SH
2416 char *buf = NULL;
2417 int bufsize = 64*1024;
2418
1527a17e
VK
2419 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2420 return 0;
2421
aba5acdf
SH
2422 dg_proto = TCP_PROTO;
2423
2424 if (getenv("TCPDIAG_FILE"))
2425 return tcp_show_netlink_file(f);
2426
2427 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3fe5b534 2428 && inet_show_netlink(f, NULL, socktype) == 0)
aba5acdf
SH
2429 return 0;
2430
2431 /* Sigh... We have to parse /proc/net/tcp... */
2432
ab01dbbb 2433
aba5acdf
SH
2434 /* Estimate amount of sockets and try to allocate
2435 * huge buffer to read all the table at one read.
2436 * Limit it by 16MB though. The assumption is: as soon as
2437 * kernel was able to hold information about N connections,
2438 * it is able to give us some memory for snapshot.
2439 */
2440 if (1) {
a221d621
BL
2441 get_slabstat(&slabstat);
2442
aba5acdf 2443 int guess = slabstat.socks+slabstat.tcp_syns;
acd1e437 2444
aba5acdf
SH
2445 if (f->states&(1<<SS_TIME_WAIT))
2446 guess += slabstat.tcp_tws;
2447 if (guess > (16*1024*1024)/128)
2448 guess = (16*1024*1024)/128;
2449 guess *= 128;
2450 if (guess > bufsize)
2451 bufsize = guess;
2452 }
2453 while (bufsize >= 64*1024) {
2454 if ((buf = malloc(bufsize)) != NULL)
2455 break;
2456 bufsize /= 2;
2457 }
2458 if (buf == NULL) {
2459 errno = ENOMEM;
2460 return -1;
2461 }
2462
2463 if (f->families & (1<<AF_INET)) {
69cae645 2464 if ((fp = net_tcp_open()) == NULL)
aba5acdf 2465 goto outerr;
ab01dbbb
SH
2466
2467 setbuffer(fp, buf, bufsize);
2468 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
aba5acdf 2469 goto outerr;
ab01dbbb 2470 fclose(fp);
aba5acdf
SH
2471 }
2472
2473 if ((f->families & (1<<AF_INET6)) &&
69cae645 2474 (fp = net_tcp6_open()) != NULL) {
ab01dbbb
SH
2475 setbuffer(fp, buf, bufsize);
2476 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
aba5acdf 2477 goto outerr;
ab01dbbb 2478 fclose(fp);
aba5acdf
SH
2479 }
2480
2481 free(buf);
2482 return 0;
2483
2484outerr:
2485 do {
2486 int saved_errno = errno;
acd1e437 2487
92de1c2c 2488 free(buf);
ab01dbbb
SH
2489 if (fp)
2490 fclose(fp);
aba5acdf
SH
2491 errno = saved_errno;
2492 return -1;
2493 } while (0);
2494}
2495
2496
d1f28cf1 2497static int dgram_show_line(char *line, const struct filter *f, int family)
aba5acdf 2498{
055840f2 2499 struct sockstat s = {};
aba5acdf
SH
2500 char *loc, *rem, *data;
2501 char opt[256];
2502 int n;
aba5acdf 2503
8250bc9f 2504 if (proc_inet_split_line(line, &loc, &rem, &data))
aba5acdf 2505 return -1;
aba5acdf 2506
8250bc9f 2507 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
acd1e437 2508
8250bc9f
VK
2509 if (!(f->states & (1 << state)))
2510 return 0;
aba5acdf 2511
8250bc9f 2512 proc_parse_inet_addr(loc, rem, family, &s);
aba5acdf
SH
2513
2514 if (f->f && run_ssfilter(f->f, &s) == 0)
2515 return 0;
2516
2517 opt[0] = 0;
e7113c61 2518 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
aba5acdf
SH
2519 &s.state, &s.wq, &s.rq,
2520 &s.uid, &s.ino,
2521 &s.refcnt, &s.sk, opt);
2522
2523 if (n < 9)
2524 opt[0] = 0;
2525
235c4453 2526 inet_stats_print(&s, dg_proto == UDP_PROTO ? IPPROTO_UDP : 0);
aba5acdf 2527
f1b39e1b
VK
2528 if (show_details && opt[0])
2529 printf(" opt:\"%s\"", opt);
aba5acdf 2530
8250bc9f 2531 printf("\n");
aba5acdf
SH
2532 return 0;
2533}
2534
d1f28cf1 2535static int udp_show(struct filter *f)
aba5acdf 2536{
ab01dbbb 2537 FILE *fp = NULL;
aba5acdf 2538
1527a17e
VK
2539 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2540 return 0;
2541
ace5cb31
VK
2542 dg_proto = UDP_PROTO;
2543
346f8ca8
PE
2544 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
2545 && inet_show_netlink(f, NULL, IPPROTO_UDP) == 0)
2546 return 0;
2547
aba5acdf 2548 if (f->families&(1<<AF_INET)) {
69cae645 2549 if ((fp = net_udp_open()) == NULL)
aba5acdf 2550 goto outerr;
ab01dbbb 2551 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
aba5acdf 2552 goto outerr;
ab01dbbb 2553 fclose(fp);
aba5acdf
SH
2554 }
2555
2556 if ((f->families&(1<<AF_INET6)) &&
69cae645 2557 (fp = net_udp6_open()) != NULL) {
ab01dbbb 2558 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
aba5acdf 2559 goto outerr;
ab01dbbb 2560 fclose(fp);
aba5acdf
SH
2561 }
2562 return 0;
2563
2564outerr:
2565 do {
2566 int saved_errno = errno;
acd1e437 2567
ab01dbbb
SH
2568 if (fp)
2569 fclose(fp);
aba5acdf
SH
2570 errno = saved_errno;
2571 return -1;
2572 } while (0);
2573}
2574
d1f28cf1 2575static int raw_show(struct filter *f)
aba5acdf 2576{
ab01dbbb 2577 FILE *fp = NULL;
aba5acdf 2578
1527a17e
VK
2579 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2580 return 0;
2581
aba5acdf
SH
2582 dg_proto = RAW_PROTO;
2583
2584 if (f->families&(1<<AF_INET)) {
69cae645 2585 if ((fp = net_raw_open()) == NULL)
aba5acdf 2586 goto outerr;
ab01dbbb 2587 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
aba5acdf 2588 goto outerr;
ab01dbbb 2589 fclose(fp);
aba5acdf
SH
2590 }
2591
2592 if ((f->families&(1<<AF_INET6)) &&
69cae645 2593 (fp = net_raw6_open()) != NULL) {
ab01dbbb 2594 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
aba5acdf 2595 goto outerr;
ab01dbbb 2596 fclose(fp);
aba5acdf
SH
2597 }
2598 return 0;
2599
2600outerr:
2601 do {
2602 int saved_errno = errno;
acd1e437 2603
ab01dbbb
SH
2604 if (fp)
2605 fclose(fp);
aba5acdf
SH
2606 errno = saved_errno;
2607 return -1;
2608 } while (0);
2609}
2610
aba5acdf
SH
2611int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
2612 SS_ESTABLISHED, SS_CLOSING };
2613
ec4d0d8a 2614#define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
aba5acdf 2615
ec4d0d8a 2616static void unix_list_free(struct sockstat *list)
aba5acdf
SH
2617{
2618 while (list) {
ec4d0d8a 2619 struct sockstat *s = list;
ec4d0d8a 2620
aba5acdf 2621 list = list->next;
99bb68ff 2622 free(s->name);
aba5acdf
SH
2623 free(s);
2624 }
2625}
2626
30b669d7
MY
2627static const char *unix_netid_name(int type)
2628{
2629 const char *netid;
2630
2631 switch (type) {
2632 case SOCK_STREAM:
2633 netid = "u_str";
2634 break;
2635 case SOCK_SEQPACKET:
2636 netid = "u_seq";
2637 break;
2638 case SOCK_DGRAM:
2639 default:
2640 netid = "u_dgr";
2641 break;
2642 }
2643 return netid;
2644}
2645
ec4d0d8a 2646static bool unix_type_skip(struct sockstat *s, struct filter *f)
bf4ceee6
VK
2647{
2648 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2649 return true;
2650 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2651 return true;
2652 if (s->type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2653 return true;
2654 return false;
2655}
2656
ec4d0d8a
VK
2657static bool unix_use_proc(void)
2658{
2659 return getenv("PROC_NET_UNIX") || getenv("PROC_ROOT");
2660}
2661
2662static void unix_stats_print(struct sockstat *list, struct filter *f)
aba5acdf 2663{
ec4d0d8a 2664 struct sockstat *s;
99bb68ff 2665 char *peer;
b217df10 2666 char *ctx_buf = NULL;
ec4d0d8a 2667 bool use_proc = unix_use_proc();
b217df10 2668 char port_name[30] = {};
aba5acdf
SH
2669
2670 for (s = list; s; s = s->next) {
ec4d0d8a 2671 if (!(f->states & (1 << s->state)))
aba5acdf 2672 continue;
bf4ceee6 2673 if (unix_type_skip(s, f))
30b669d7 2674 continue;
aba5acdf 2675
99bb68ff
VK
2676 peer = "*";
2677 if (s->peer_name)
2678 peer = s->peer_name;
ec4d0d8a
VK
2679
2680 if (s->rport && use_proc) {
2681 struct sockstat *p;
bf4ceee6 2682
aba5acdf 2683 for (p = list; p; p = p->next) {
ec4d0d8a 2684 if (s->rport == p->lport)
aba5acdf
SH
2685 break;
2686 }
ec4d0d8a 2687
aba5acdf
SH
2688 if (!p) {
2689 peer = "?";
2690 } else {
99bb68ff 2691 peer = p->name ? : "*";
aba5acdf
SH
2692 }
2693 }
2694
29999b0f 2695 if (use_proc && f->f) {
99bb68ff 2696 struct sockstat st;
acd1e437 2697
99bb68ff
VK
2698 st.local.family = AF_UNIX;
2699 st.remote.family = AF_UNIX;
2700 memcpy(st.local.data, &s->name, sizeof(s->name));
aba5acdf 2701 if (strcmp(peer, "*") == 0)
99bb68ff 2702 memset(st.remote.data, 0, sizeof(peer));
aba5acdf 2703 else
99bb68ff
VK
2704 memcpy(st.remote.data, &peer, sizeof(peer));
2705 if (run_ssfilter(f->f, &st) == 0)
aba5acdf
SH
2706 continue;
2707 }
2708
2d791bc8
VK
2709 sock_state_print(s, unix_netid_name(s->type));
2710
99bb68ff 2711 sock_addr_print(s->name ?: "*", " ",
b217df10
VK
2712 int_to_str(s->lport, port_name), NULL);
2713 sock_addr_print(peer, " ", int_to_str(s->rport, port_name),
2714 NULL);
116ac927
RH
2715
2716 if (show_proc_ctx || show_sock_ctx) {
b217df10 2717 if (find_entry(s->ino, &ctx_buf,
116ac927
RH
2718 (show_proc_ctx & show_sock_ctx) ?
2719 PROC_SOCK_CTX : PROC_CTX) > 0) {
b217df10
VK
2720 printf(" users:(%s)", ctx_buf);
2721 free(ctx_buf);
116ac927
RH
2722 }
2723 } else if (show_users) {
b217df10
VK
2724 if (find_entry(s->ino, &ctx_buf, USERS) > 0) {
2725 printf(" users:(%s)", ctx_buf);
2726 free(ctx_buf);
116ac927 2727 }
aba5acdf
SH
2728 }
2729 printf("\n");
2730 }
2731}
2732
8a4025f6 2733static int unix_show_sock(const struct sockaddr_nl *addr, struct nlmsghdr *nlh,
2734 void *arg)
dfbaa90d 2735{
8a4025f6 2736 struct filter *f = (struct filter *)arg;
dfbaa90d
PE
2737 struct unix_diag_msg *r = NLMSG_DATA(nlh);
2738 struct rtattr *tb[UNIX_DIAG_MAX+1];
99bb68ff
VK
2739 char name[128];
2740 struct sockstat stat = { .name = "*", .peer_name = "*" };
dfbaa90d 2741
acd1e437 2742 parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr *)(r+1),
dfbaa90d
PE
2743 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2744
bf4ceee6
VK
2745 stat.type = r->udiag_type;
2746 stat.state = r->udiag_state;
ec4d0d8a
VK
2747 stat.ino = stat.lport = r->udiag_ino;
2748 stat.local.family = stat.remote.family = AF_UNIX;
0d2e01c5 2749
bf4ceee6
VK
2750 if (unix_type_skip(&stat, f))
2751 return 0;
dfbaa90d 2752
defd61ca
HFS
2753 if (tb[UNIX_DIAG_RQLEN]) {
2754 struct unix_diag_rqlen *rql = RTA_DATA(tb[UNIX_DIAG_RQLEN]);
acd1e437 2755
bf4ceee6
VK
2756 stat.rq = rql->udiag_rqueue;
2757 stat.wq = rql->udiag_wqueue;
defd61ca 2758 }
dfbaa90d
PE
2759 if (tb[UNIX_DIAG_NAME]) {
2760 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
2761
2762 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
2763 name[len] = '\0';
2764 if (name[0] == '\0')
2765 name[0] = '@';
99bb68ff
VK
2766 stat.name = &name[0];
2767 memcpy(stat.local.data, &stat.name, sizeof(stat.name));
bf4ceee6 2768 }
dfbaa90d 2769 if (tb[UNIX_DIAG_PEER])
ec4d0d8a 2770 stat.rport = rta_getattr_u32(tb[UNIX_DIAG_PEER]);
dfbaa90d 2771
29999b0f
VK
2772 if (f->f && run_ssfilter(f->f, &stat) == 0)
2773 return 0;
2774
bf4ceee6 2775 unix_stats_print(&stat, f);
dfbaa90d 2776
51ff9f24 2777 if (show_mem) {
bf4ceee6 2778 printf("\t");
51ff9f24
HFS
2779 print_skmeminfo(tb, UNIX_DIAG_MEMINFO);
2780 }
5b816047
PE
2781 if (show_details) {
2782 if (tb[UNIX_DIAG_SHUTDOWN]) {
2783 unsigned char mask;
acd1e437 2784
5b816047
PE
2785 mask = *(__u8 *)RTA_DATA(tb[UNIX_DIAG_SHUTDOWN]);
2786 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2787 }
2788 }
bf4ceee6
VK
2789 if (show_mem || show_details)
2790 printf("\n");
ec4d0d8a 2791
dfbaa90d
PE
2792 return 0;
2793}
2794
8a4025f6 2795static int handle_netlink_request(struct filter *f, struct nlmsghdr *req,
2796 size_t size, rtnl_filter_t show_one_sock)
dfbaa90d 2797{
8a4025f6 2798 int ret = -1;
2799 struct rtnl_handle rth;
dfbaa90d 2800
8a4025f6 2801 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
dfbaa90d
PE
2802 return -1;
2803
8a4025f6 2804 rth.dump = MAGIC_SEQ;
dfbaa90d 2805
8a4025f6 2806 if (rtnl_send(&rth, req, size) < 0)
2807 goto Exit;
dfbaa90d 2808
8a4025f6 2809 if (rtnl_dump_filter(&rth, show_one_sock, f))
2810 goto Exit;
dfbaa90d 2811
8a4025f6 2812 ret = 0;
2813Exit:
2814 rtnl_close(&rth);
2815 return ret;
dfbaa90d
PE
2816}
2817
8a4025f6 2818static int unix_show_netlink(struct filter *f)
d8402b96 2819{
5fb421d4 2820 DIAG_REQUEST(req, struct unix_diag_req r);
d8402b96
AV
2821
2822 req.r.sdiag_family = AF_UNIX;
2823 req.r.udiag_states = f->states;
2824 req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
2825 if (show_mem)
2826 req.r.udiag_show |= UDIAG_SHOW_MEMINFO;
2827
8a4025f6 2828 return handle_netlink_request(f, &req.nlh, sizeof(req), unix_show_sock);
d8402b96
AV
2829}
2830
d1f28cf1 2831static int unix_show(struct filter *f)
aba5acdf
SH
2832{
2833 FILE *fp;
2834 char buf[256];
2835 char name[128];
2836 int newformat = 0;
2837 int cnt;
ec4d0d8a 2838 struct sockstat *list = NULL;
aba5acdf 2839
9db7bf15
VK
2840 if (!filter_af_get(f, AF_UNIX))
2841 return 0;
2842
ec4d0d8a 2843 if (!unix_use_proc() && unix_show_netlink(f) == 0)
dfbaa90d
PE
2844 return 0;
2845
ab01dbbb 2846 if ((fp = net_unix_open()) == NULL)
aba5acdf 2847 return -1;
61170fd8 2848 if (!fgets(buf, sizeof(buf), fp)) {
d572ed4d
PS
2849 fclose(fp);
2850 return -1;
2851 }
aba5acdf 2852
ae665a52 2853 if (memcmp(buf, "Peer", 4) == 0)
aba5acdf
SH
2854 newformat = 1;
2855 cnt = 0;
2856
61170fd8 2857 while (fgets(buf, sizeof(buf), fp)) {
ec4d0d8a 2858 struct sockstat *u, **insp;
aba5acdf
SH
2859 int flags;
2860
0ee9052f 2861 if (!(u = calloc(1, sizeof(*u))))
aba5acdf 2862 break;
99bb68ff
VK
2863 u->name = NULL;
2864 u->peer_name = NULL;
aba5acdf
SH
2865
2866 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
ec4d0d8a 2867 &u->rport, &u->rq, &u->wq, &flags, &u->type,
aba5acdf
SH
2868 &u->state, &u->ino, name) < 8)
2869 name[0] = 0;
2870
ec4d0d8a
VK
2871 u->lport = u->ino;
2872 u->local.family = u->remote.family = AF_UNIX;
2873
2874 if (flags & (1 << 16)) {
aba5acdf
SH
2875 u->state = SS_LISTEN;
2876 } else {
2877 u->state = unix_state_map[u->state-1];
ec4d0d8a 2878 if (u->type == SOCK_DGRAM && u->state == SS_CLOSE && u->rport)
aba5acdf
SH
2879 u->state = SS_ESTABLISHED;
2880 }
2881
2882 if (!newformat) {
ec4d0d8a 2883 u->rport = 0;
aba5acdf
SH
2884 u->rq = 0;
2885 u->wq = 0;
2886 }
2887
2888 insp = &list;
2889 while (*insp) {
2890 if (u->type < (*insp)->type ||
2891 (u->type == (*insp)->type &&
2892 u->ino < (*insp)->ino))
2893 break;
2894 insp = &(*insp)->next;
2895 }
2896 u->next = *insp;
2897 *insp = u;
2898
2899 if (name[0]) {
99bb68ff
VK
2900 if ((u->name = malloc(strlen(name)+1)) == NULL)
2901 break;
2902 strcpy(u->name, name);
aba5acdf
SH
2903 }
2904 if (++cnt > MAX_UNIX_REMEMBER) {
bf4ceee6 2905 unix_stats_print(list, f);
aba5acdf
SH
2906 unix_list_free(list);
2907 list = NULL;
2908 cnt = 0;
2909 }
2910 }
a3fd8e58 2911 fclose(fp);
aba5acdf 2912 if (list) {
bf4ceee6 2913 unix_stats_print(list, f);
aba5acdf
SH
2914 unix_list_free(list);
2915 list = NULL;
2916 cnt = 0;
2917 }
2918
2919 return 0;
2920}
2921
89f634f9 2922static int packet_stats_print(struct sockstat *s, const struct filter *f)
4a0053b6
VK
2923{
2924 char *buf = NULL;
b217df10
VK
2925 const char *addr, *port;
2926 char ll_name[16];
372c30d2 2927
4a0053b6 2928 if (f->f) {
89f634f9
VK
2929 s->local.family = AF_PACKET;
2930 s->remote.family = AF_PACKET;
89f634f9 2931 s->local.data[0] = s->prot;
89f634f9 2932 if (run_ssfilter(f->f, s) == 0)
4a0053b6
VK
2933 return 1;
2934 }
372c30d2 2935
2d791bc8 2936 sock_state_print(s, s->type == SOCK_RAW ? "p_raw" : "p_dgr");
372c30d2 2937
b217df10
VK
2938 if (s->prot == 3)
2939 addr = "*";
2940 else
2941 addr = ll_proto_n2a(htons(s->prot), ll_name, sizeof(ll_name));
2942
2943 if (s->iface == 0)
2944 port = "*";
2945 else
2946 port = xll_index_to_name(s->iface);
372c30d2 2947
b217df10
VK
2948 sock_addr_print(addr, ":", port, NULL);
2949 sock_addr_print("", "*", "", NULL);
116ac927
RH
2950
2951 if (show_proc_ctx || show_sock_ctx) {
4a0053b6
VK
2952 if (find_entry(s->ino, &buf,
2953 (show_proc_ctx & show_sock_ctx) ?
2954 PROC_SOCK_CTX : PROC_CTX) > 0) {
116ac927
RH
2955 printf(" users:(%s)", buf);
2956 free(buf);
2957 }
2958 } else if (show_users) {
4a0053b6 2959 if (find_entry(s->ino, &buf, USERS) > 0) {
116ac927
RH
2960 printf(" users:(%s)", buf);
2961 free(buf);
2962 }
372c30d2 2963 }
116ac927 2964
f1b39e1b
VK
2965 if (show_details)
2966 sock_details_print(s);
2967
4a0053b6
VK
2968 return 0;
2969}
2970
2631b856
VK
2971static void packet_show_ring(struct packet_diag_ring *ring)
2972{
2973 printf("blk_size:%d", ring->pdr_block_size);
2974 printf(",blk_nr:%d", ring->pdr_block_nr);
2975 printf(",frm_size:%d", ring->pdr_frame_size);
2976 printf(",frm_nr:%d", ring->pdr_frame_nr);
2977 printf(",tmo:%d", ring->pdr_retire_tmo);
2978 printf(",features:0x%x", ring->pdr_features);
2979}
2980
4a0053b6
VK
2981static int packet_show_sock(const struct sockaddr_nl *addr,
2982 struct nlmsghdr *nlh, void *arg)
2983{
2984 const struct filter *f = arg;
2985 struct packet_diag_msg *r = NLMSG_DATA(nlh);
2631b856
VK
2986 struct packet_diag_info *pinfo = NULL;
2987 struct packet_diag_ring *ring_rx = NULL, *ring_tx = NULL;
4a0053b6 2988 struct rtattr *tb[PACKET_DIAG_MAX+1];
89f634f9 2989 struct sockstat stat = {};
2631b856
VK
2990 uint32_t fanout = 0;
2991 bool has_fanout = false;
4a0053b6 2992
acd1e437 2993 parse_rtattr(tb, PACKET_DIAG_MAX, (struct rtattr *)(r+1),
4a0053b6
VK
2994 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2995
2996 /* use /proc/net/packet if all info are not available */
2997 if (!tb[PACKET_DIAG_MEMINFO])
2998 return -1;
2999
2d791bc8
VK
3000 stat.type = r->pdiag_type;
3001 stat.prot = r->pdiag_num;
3002 stat.ino = r->pdiag_ino;
3003 stat.state = SS_CLOSE;
f1b39e1b 3004 stat.sk = cookie_sk_get(&r->pdiag_cookie[0]);
4a0053b6
VK
3005
3006 if (tb[PACKET_DIAG_MEMINFO]) {
3007 __u32 *skmeminfo = RTA_DATA(tb[PACKET_DIAG_MEMINFO]);
acd1e437 3008
4a0053b6
VK
3009 stat.rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
3010 }
3011
3012 if (tb[PACKET_DIAG_INFO]) {
2631b856 3013 pinfo = RTA_DATA(tb[PACKET_DIAG_INFO]);
2d791bc8 3014 stat.lport = stat.iface = pinfo->pdi_index;
4a0053b6
VK
3015 }
3016
f1b39e1b
VK
3017 if (tb[PACKET_DIAG_UID])
3018 stat.uid = *(__u32 *)RTA_DATA(tb[PACKET_DIAG_UID]);
3019
2631b856
VK
3020 if (tb[PACKET_DIAG_RX_RING])
3021 ring_rx = RTA_DATA(tb[PACKET_DIAG_RX_RING]);
3022
3023 if (tb[PACKET_DIAG_TX_RING])
3024 ring_tx = RTA_DATA(tb[PACKET_DIAG_TX_RING]);
3025
3026 if (tb[PACKET_DIAG_FANOUT]) {
3027 has_fanout = true;
3028 fanout = *(uint32_t *)RTA_DATA(tb[PACKET_DIAG_FANOUT]);
3029 }
3030
4a0053b6
VK
3031 if (packet_stats_print(&stat, f))
3032 return 0;
3033
2631b856
VK
3034 if (show_details) {
3035 if (pinfo) {
3036 printf("\n\tver:%d", pinfo->pdi_version);
3037 printf(" cpy_thresh:%d", pinfo->pdi_copy_thresh);
3038 printf(" flags( ");
3039 if (pinfo->pdi_flags & PDI_RUNNING)
3040 printf("running");
3041 if (pinfo->pdi_flags & PDI_AUXDATA)
3042 printf(" auxdata");
3043 if (pinfo->pdi_flags & PDI_ORIGDEV)
3044 printf(" origdev");
3045 if (pinfo->pdi_flags & PDI_VNETHDR)
3046 printf(" vnethdr");
3047 if (pinfo->pdi_flags & PDI_LOSS)
3048 printf(" loss");
3049 if (!pinfo->pdi_flags)
3050 printf("0");
3051 printf(" )");
3052 }
3053 if (ring_rx) {
3054 printf("\n\tring_rx(");
3055 packet_show_ring(ring_rx);
3056 printf(")");
3057 }
3058 if (ring_tx) {
3059 printf("\n\tring_tx(");
3060 packet_show_ring(ring_tx);
3061 printf(")");
3062 }
3063 if (has_fanout) {
3064 uint16_t type = (fanout >> 16) & 0xffff;
3065
3066 printf("\n\tfanout(");
3067 printf("id:%d,", fanout & 0xffff);
3068 printf("type:");
3069
3070 if (type == 0)
3071 printf("hash");
3072 else if (type == 1)
3073 printf("lb");
3074 else if (type == 2)
3075 printf("cpu");
3076 else if (type == 3)
3077 printf("roll");
3078 else if (type == 4)
3079 printf("random");
3080 else if (type == 5)
3081 printf("qm");
3082 else
3083 printf("0x%x", type);
3084
3085 printf(")");
3086 }
3087 }
3088
372c30d2
ND
3089 if (show_bpf && tb[PACKET_DIAG_FILTER]) {
3090 struct sock_filter *fil =
3091 RTA_DATA(tb[PACKET_DIAG_FILTER]);
3092 int num = RTA_PAYLOAD(tb[PACKET_DIAG_FILTER]) /
3093 sizeof(struct sock_filter);
3094
3095 printf("\n\tbpf filter (%d): ", num);
3096 while (num) {
3097 printf(" 0x%02x %u %u %u,",
3098 fil->code, fil->jt, fil->jf, fil->k);
3099 num--;
3100 fil++;
3101 }
3102 }
3103 printf("\n");
3104 return 0;
3105}
3106
8a4025f6 3107static int packet_show_netlink(struct filter *f)
372c30d2 3108{
5fb421d4 3109 DIAG_REQUEST(req, struct packet_diag_req r);
372c30d2 3110
372c30d2 3111 req.r.sdiag_family = AF_PACKET;
2631b856
VK
3112 req.r.pdiag_show = PACKET_SHOW_INFO | PACKET_SHOW_MEMINFO |
3113 PACKET_SHOW_FILTER | PACKET_SHOW_RING_CFG | PACKET_SHOW_FANOUT;
372c30d2 3114
8a4025f6 3115 return handle_netlink_request(f, &req.nlh, sizeof(req), packet_show_sock);
372c30d2
ND
3116}
3117
4a0053b6
VK
3118static int packet_show_line(char *buf, const struct filter *f, int fam)
3119{
3120 unsigned long long sk;
89f634f9 3121 struct sockstat stat = {};
4a0053b6
VK
3122 int type, prot, iface, state, rq, uid, ino;
3123
3124 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
3125 &sk,
3126 &type, &prot, &iface, &state,
3127 &rq, &uid, &ino);
3128
3129 if (stat.type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
3130 return 0;
3131 if (stat.type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
3132 return 0;
3133
3134 stat.type = type;
3135 stat.prot = prot;
2d791bc8 3136 stat.lport = stat.iface = iface;
4a0053b6
VK
3137 stat.state = state;
3138 stat.rq = rq;
3139 stat.uid = uid;
3140 stat.ino = ino;
2d791bc8
VK
3141 stat.state = SS_CLOSE;
3142
4a0053b6
VK
3143 if (packet_stats_print(&stat, f))
3144 return 0;
3145
4a0053b6
VK
3146 printf("\n");
3147 return 0;
3148}
aba5acdf 3149
d1f28cf1 3150static int packet_show(struct filter *f)
aba5acdf
SH
3151{
3152 FILE *fp;
b95d28c3 3153 int rc = 0;
3d0b7439 3154
9db7bf15 3155 if (!filter_af_get(f, AF_PACKET) || !(f->states & (1 << SS_CLOSE)))
b9ea445d 3156 return 0;
aba5acdf 3157
4a0053b6
VK
3158 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
3159 packet_show_netlink(f) == 0)
372c30d2
ND
3160 return 0;
3161
ab01dbbb 3162 if ((fp = net_packet_open()) == NULL)
aba5acdf 3163 return -1;
4a0053b6 3164 if (generic_record_read(fp, packet_show_line, f, AF_PACKET))
b95d28c3 3165 rc = -1;
aba5acdf 3166
b95d28c3
PS
3167 fclose(fp);
3168 return rc;
aba5acdf
SH
3169}
3170
5f24ec0e 3171static int netlink_show_one(struct filter *f,
acd1e437
SH
3172 int prot, int pid, unsigned int groups,
3173 int state, int dst_pid, unsigned int dst_group,
129709ae
AV
3174 int rq, int wq,
3175 unsigned long long sk, unsigned long long cb)
3176{
2d791bc8 3177 struct sockstat st;
acd1e437 3178
b217df10
VK
3179 SPRINT_BUF(prot_buf) = {};
3180 const char *prot_name;
3181 char procname[64] = {};
eef43b50 3182
2d791bc8
VK
3183 st.state = SS_CLOSE;
3184 st.rq = rq;
3185 st.wq = wq;
3186
129709ae 3187 if (f->f) {
055840f2
VK
3188 st.local.family = AF_NETLINK;
3189 st.remote.family = AF_NETLINK;
3190 st.rport = -1;
3191 st.lport = pid;
3192 st.local.data[0] = prot;
055840f2 3193 if (run_ssfilter(f->f, &st) == 0)
5f24ec0e 3194 return 1;
129709ae
AV
3195 }
3196
2d791bc8 3197 sock_state_print(&st, "nl");
eef43b50 3198
b217df10
VK
3199 if (resolve_services)
3200 prot_name = nl_proto_n2a(prot, prot_buf, sizeof(prot_buf));
3201 else
3202 prot_name = int_to_str(prot, prot_buf);
eef43b50 3203
129709ae 3204 if (pid == -1) {
b217df10 3205 procname[0] = '*';
129709ae
AV
3206 } else if (resolve_services) {
3207 int done = 0;
acd1e437 3208
129709ae
AV
3209 if (!pid) {
3210 done = 1;
b217df10 3211 strncpy(procname, "kernel", 6);
129709ae 3212 } else if (pid > 0) {
129709ae 3213 FILE *fp;
acd1e437 3214
0ee9052f 3215 snprintf(procname, sizeof(procname), "%s/%d/stat",
129709ae
AV
3216 getenv("PROC_ROOT") ? : "/proc", pid);
3217 if ((fp = fopen(procname, "r")) != NULL) {
3218 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
0ee9052f 3219 snprintf(procname+strlen(procname),
3220 sizeof(procname)-strlen(procname),
3221 "/%d", pid);
129709ae
AV
3222 done = 1;
3223 }
3224 fclose(fp);
3225 }
3226 }
3227 if (!done)
b217df10 3228 int_to_str(pid, procname);
129709ae 3229 } else {
b217df10 3230 int_to_str(pid, procname);
129709ae 3231 }
f271fe01 3232
b217df10
VK
3233 sock_addr_print(prot_name, ":", procname, NULL);
3234
f271fe01 3235 if (state == NETLINK_CONNECTED) {
b217df10
VK
3236 char dst_group_buf[30];
3237 char dst_pid_buf[30];
acd1e437 3238
b217df10
VK
3239 sock_addr_print(int_to_str(dst_group, dst_group_buf), ":",
3240 int_to_str(dst_pid, dst_pid_buf), NULL);
f271fe01 3241 } else {
b217df10 3242 sock_addr_print("", "*", "", NULL);
f271fe01 3243 }
129709ae 3244
116ac927 3245 char *pid_context = NULL;
acd1e437 3246
116ac927
RH
3247 if (show_proc_ctx) {
3248 /* The pid value will either be:
3249 * 0 if destination kernel - show kernel initial context.
3250 * A valid process pid - use getpidcon.
3251 * A unique value allocated by the kernel or netlink user
3252 * to the process - show context as "not available".
3253 */
3254 if (!pid)
3255 security_get_initial_context("kernel", &pid_context);
3256 else if (pid > 0)
3257 getpidcon(pid, &pid_context);
3258
3259 if (pid_context != NULL) {
3260 printf("proc_ctx=%-*s ", serv_width, pid_context);
3261 free(pid_context);
3262 } else {
3263 printf("proc_ctx=%-*s ", serv_width, "unavailable");
3264 }
3265 }
3266
129709ae
AV
3267 if (show_details) {
3268 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
3269 }
3270 printf("\n");
3271
5f24ec0e 3272 return 0;
129709ae
AV
3273}
3274
8a4025f6 3275static int netlink_show_sock(const struct sockaddr_nl *addr,
3276 struct nlmsghdr *nlh, void *arg)
ecb928c8 3277{
8a4025f6 3278 struct filter *f = (struct filter *)arg;
ecb928c8
AV
3279 struct netlink_diag_msg *r = NLMSG_DATA(nlh);
3280 struct rtattr *tb[NETLINK_DIAG_MAX+1];
3281 int rq = 0, wq = 0;
3282 unsigned long groups = 0;
3283
acd1e437 3284 parse_rtattr(tb, NETLINK_DIAG_MAX, (struct rtattr *)(r+1),
ecb928c8
AV
3285 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
3286
3287 if (tb[NETLINK_DIAG_GROUPS] && RTA_PAYLOAD(tb[NETLINK_DIAG_GROUPS]))
3288 groups = *(unsigned long *) RTA_DATA(tb[NETLINK_DIAG_GROUPS]);
3289
3290 if (tb[NETLINK_DIAG_MEMINFO]) {
3291 const __u32 *skmeminfo;
acd1e437 3292
ecb928c8
AV
3293 skmeminfo = RTA_DATA(tb[NETLINK_DIAG_MEMINFO]);
3294
3295 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
3296 wq = skmeminfo[SK_MEMINFO_WMEM_ALLOC];
3297 }
3298
5f24ec0e 3299 if (netlink_show_one(f, r->ndiag_protocol, r->ndiag_portid, groups,
ecb928c8 3300 r->ndiag_state, r->ndiag_dst_portid, r->ndiag_dst_group,
5f24ec0e
VK
3301 rq, wq, 0, 0)) {
3302 return 0;
3303 }
ecb928c8
AV
3304
3305 if (show_mem) {
3306 printf("\t");
3307 print_skmeminfo(tb, NETLINK_DIAG_MEMINFO);
3308 printf("\n");
3309 }
3310
3311 return 0;
3312}
3313
8a4025f6 3314static int netlink_show_netlink(struct filter *f)
ecb928c8 3315{
5fb421d4 3316 DIAG_REQUEST(req, struct netlink_diag_req r);
ecb928c8
AV
3317
3318 req.r.sdiag_family = AF_NETLINK;
3319 req.r.sdiag_protocol = NDIAG_PROTO_ALL;
3320 req.r.ndiag_show = NDIAG_SHOW_GROUPS | NDIAG_SHOW_MEMINFO;
3321
8a4025f6 3322 return handle_netlink_request(f, &req.nlh, sizeof(req), netlink_show_sock);
ecb928c8
AV
3323}
3324
d1f28cf1 3325static int netlink_show(struct filter *f)
aba5acdf
SH
3326{
3327 FILE *fp;
3328 char buf[256];
3329 int prot, pid;
acd1e437 3330 unsigned int groups;
aba5acdf
SH
3331 int rq, wq, rc;
3332 unsigned long long sk, cb;
3333
9db7bf15 3334 if (!filter_af_get(f, AF_NETLINK) || !(f->states & (1 << SS_CLOSE)))
b9ea445d
VK
3335 return 0;
3336
129709ae 3337 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
8a4025f6 3338 netlink_show_netlink(f) == 0)
129709ae
AV
3339 return 0;
3340
ab01dbbb 3341 if ((fp = net_netlink_open()) == NULL)
aba5acdf 3342 return -1;
61170fd8 3343 if (!fgets(buf, sizeof(buf), fp)) {
d572ed4d
PS
3344 fclose(fp);
3345 return -1;
3346 }
aba5acdf 3347
61170fd8 3348 while (fgets(buf, sizeof(buf), fp)) {
aba5acdf
SH
3349 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
3350 &sk,
3351 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
3352
f271fe01 3353 netlink_show_one(f, prot, pid, groups, 0, 0, 0, rq, wq, sk, cb);
aba5acdf
SH
3354 }
3355
b95d28c3 3356 fclose(fp);
aba5acdf
SH
3357 return 0;
3358}
3359
6885e3bf
CG
3360struct sock_diag_msg {
3361 __u8 sdiag_family;
3362};
3363
3364static int generic_show_sock(const struct sockaddr_nl *addr,
3365 struct nlmsghdr *nlh, void *arg)
3366{
3367 struct sock_diag_msg *r = NLMSG_DATA(nlh);
3368 struct inet_diag_arg inet_arg = { .f = arg, .protocol = IPPROTO_MAX };
3369
3370 switch (r->sdiag_family) {
3371 case AF_INET:
3372 case AF_INET6:
3373 return show_one_inet_sock(addr, nlh, &inet_arg);
3374 case AF_UNIX:
3375 return unix_show_sock(addr, nlh, arg);
3376 case AF_PACKET:
3377 return packet_show_sock(addr, nlh, arg);
3378 case AF_NETLINK:
3379 return netlink_show_sock(addr, nlh, arg);
3380 default:
3381 return -1;
3382 }
3383}
3384
3385static int handle_follow_request(struct filter *f)
3386{
3387 int ret = -1;
3388 int groups = 0;
3389 struct rtnl_handle rth;
3390
3391 if (f->families & (1 << AF_INET) && f->dbs & (1 << TCP_DB))
3392 groups |= 1 << (SKNLGRP_INET_TCP_DESTROY - 1);
3393 if (f->families & (1 << AF_INET) && f->dbs & (1 << UDP_DB))
3394 groups |= 1 << (SKNLGRP_INET_UDP_DESTROY - 1);
3395 if (f->families & (1 << AF_INET6) && f->dbs & (1 << TCP_DB))
3396 groups |= 1 << (SKNLGRP_INET6_TCP_DESTROY - 1);
3397 if (f->families & (1 << AF_INET6) && f->dbs & (1 << UDP_DB))
3398 groups |= 1 << (SKNLGRP_INET6_UDP_DESTROY - 1);
3399
3400 if (groups == 0)
3401 return -1;
3402
3403 if (rtnl_open_byproto(&rth, groups, NETLINK_SOCK_DIAG))
3404 return -1;
3405
3406 rth.dump = 0;
3407 rth.local.nl_pid = 0;
3408
3409 if (rtnl_dump_filter(&rth, generic_show_sock, f))
3410 goto Exit;
3411
3412 ret = 0;
3413Exit:
3414 rtnl_close(&rth);
3415 return ret;
3416}
3417
acd1e437 3418struct snmpstat {
aba5acdf
SH
3419 int tcp_estab;
3420};
3421
d1f28cf1 3422static int get_snmp_int(char *proto, char *key, int *result)
aba5acdf
SH
3423{
3424 char buf[1024];
3425 FILE *fp;
3426 int protolen = strlen(proto);
3427 int keylen = strlen(key);
3428
3429 *result = 0;
3430
ab01dbbb 3431 if ((fp = net_snmp_open()) == NULL)
aba5acdf
SH
3432 return -1;
3433
3434 while (fgets(buf, sizeof(buf), fp) != NULL) {
3435 char *p = buf;
3436 int pos = 0;
acd1e437 3437
aba5acdf
SH
3438 if (memcmp(buf, proto, protolen))
3439 continue;
3440 while ((p = strchr(p, ' ')) != NULL) {
3441 pos++;
3442 p++;
3443 if (memcmp(p, key, keylen) == 0 &&
3444 (p[keylen] == ' ' || p[keylen] == '\n'))
3445 break;
3446 }
3447 if (fgets(buf, sizeof(buf), fp) == NULL)
3448 break;
3449 if (memcmp(buf, proto, protolen))
3450 break;
3451 p = buf;
3452 while ((p = strchr(p, ' ')) != NULL) {
3453 p++;
3454 if (--pos == 0) {
3455 sscanf(p, "%d", result);
3456 fclose(fp);
3457 return 0;
3458 }
3459 }
3460 }
3461
3462 fclose(fp);
3463 errno = ESRCH;
3464 return -1;
3465}
3466
3467
3468/* Get stats from sockstat */
3469
acd1e437 3470struct ssummary {
aba5acdf
SH
3471 int socks;
3472 int tcp_mem;
3473 int tcp_total;
3474 int tcp_orphans;
3475 int tcp_tws;
3476 int tcp4_hashed;
3477 int udp4;
3478 int raw4;
3479 int frag4;
3480 int frag4_mem;
3481 int tcp6_hashed;
3482 int udp6;
3483 int raw6;
3484 int frag6;
3485 int frag6_mem;
3486};
3487
055840f2 3488static void get_sockstat_line(char *line, struct ssummary *s)
aba5acdf
SH
3489{
3490 char id[256], rem[256];
3491
3492 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
3493 return;
3494
3495 if (strcmp(id, "sockets:") == 0)
3496 sscanf(rem, "%*s%d", &s->socks);
3497 else if (strcmp(id, "UDP:") == 0)
3498 sscanf(rem, "%*s%d", &s->udp4);
3499 else if (strcmp(id, "UDP6:") == 0)
3500 sscanf(rem, "%*s%d", &s->udp6);
3501 else if (strcmp(id, "RAW:") == 0)
3502 sscanf(rem, "%*s%d", &s->raw4);
3503 else if (strcmp(id, "RAW6:") == 0)
3504 sscanf(rem, "%*s%d", &s->raw6);
3505 else if (strcmp(id, "TCP6:") == 0)
3506 sscanf(rem, "%*s%d", &s->tcp6_hashed);
3507 else if (strcmp(id, "FRAG:") == 0)
3508 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
3509 else if (strcmp(id, "FRAG6:") == 0)
3510 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
3511 else if (strcmp(id, "TCP:") == 0)
3512 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
3513 &s->tcp4_hashed,
3514 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
3515}
3516
055840f2 3517static int get_sockstat(struct ssummary *s)
aba5acdf
SH
3518{
3519 char buf[256];
3520 FILE *fp;
3521
3522 memset(s, 0, sizeof(*s));
3523
ab01dbbb 3524 if ((fp = net_sockstat_open()) == NULL)
aba5acdf 3525 return -1;
acd1e437 3526 while (fgets(buf, sizeof(buf), fp) != NULL)
aba5acdf
SH
3527 get_sockstat_line(buf, s);
3528 fclose(fp);
3529
ab01dbbb 3530 if ((fp = net_sockstat6_open()) == NULL)
aba5acdf 3531 return 0;
acd1e437 3532 while (fgets(buf, sizeof(buf), fp) != NULL)
aba5acdf
SH
3533 get_sockstat_line(buf, s);
3534 fclose(fp);
3535
3536 return 0;
3537}
3538
d1f28cf1 3539static int print_summary(void)
aba5acdf 3540{
055840f2 3541 struct ssummary s;
aba5acdf
SH
3542 struct snmpstat sn;
3543
3544 if (get_sockstat(&s) < 0)
3545 perror("ss: get_sockstat");
3546 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
3547 perror("ss: get_snmpstat");
3548
a221d621
BL
3549 get_slabstat(&slabstat);
3550
aba5acdf
SH
3551 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
3552
3553 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
3554 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
3555 sn.tcp_estab,
3556 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
3557 s.tcp_orphans,
3558 slabstat.tcp_syns,
3559 s.tcp_tws, slabstat.tcp_tws,
3560 slabstat.tcp_ports
3561 );
3562
3563 printf("\n");
3564 printf("Transport Total IP IPv6\n");
3565 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
3566 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
3567 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
3568 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
ae665a52 3569 printf("INET %-9d %-9d %-9d\n",
aba5acdf
SH
3570 s.raw4+s.udp4+s.tcp4_hashed+
3571 s.raw6+s.udp6+s.tcp6_hashed,
3572 s.raw4+s.udp4+s.tcp4_hashed,
3573 s.raw6+s.udp6+s.tcp6_hashed);
3574 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
3575
3576 printf("\n");
3577
3578 return 0;
3579}
3580
7a96e199 3581static void _usage(FILE *dest)
aba5acdf 3582{
7a96e199 3583 fprintf(dest,
aba5acdf
SH
3584"Usage: ss [ OPTIONS ]\n"
3585" ss [ OPTIONS ] [ FILTER ]\n"
ff041f16
VK
3586" -h, --help this message\n"
3587" -V, --version output version information\n"
3588" -n, --numeric don't resolve service names\n"
ab61159a 3589" -r, --resolve resolve host names\n"
ff041f16
VK
3590" -a, --all display all sockets\n"
3591" -l, --listening display listening sockets\n"
ab61159a
SH
3592" -o, --options show timer information\n"
3593" -e, --extended show detailed socket information\n"
3594" -m, --memory show socket memory usage\n"
ff041f16
VK
3595" -p, --processes show process using socket\n"
3596" -i, --info show internal TCP information\n"
3597" -s, --summary show socket usage summary\n"
b0f01cf6 3598" -b, --bpf show bpf filter socket information\n"
6885e3bf 3599" -E, --events continually display sockets as they are destroyed\n"
ff041f16
VK
3600" -Z, --context display process SELinux security contexts\n"
3601" -z, --contexts display process and socket SELinux security contexts\n"
95ce04bc 3602" -N, --net switch to the specified network namespace name\n"
ab61159a
SH
3603"\n"
3604" -4, --ipv4 display only IP version 4 sockets\n"
3605" -6, --ipv6 display only IP version 6 sockets\n"
ff041f16
VK
3606" -0, --packet display PACKET sockets\n"
3607" -t, --tcp display only TCP sockets\n"
3608" -u, --udp display only UDP sockets\n"
3609" -d, --dccp display only DCCP sockets\n"
3610" -w, --raw display only RAW sockets\n"
3611" -x, --unix display only Unix domain sockets\n"
ab61159a 3612" -f, --family=FAMILY display sockets of type FAMILY\n"
ebef3174 3613" FAMILY := {inet|inet6|link|unix|netlink|help}\n"
ab61159a 3614"\n"
fb2594c1
LC
3615" -K, --kill forcibly close sockets, display what was closed\n"
3616"\n"
583de149 3617" -A, --query=QUERY, --socket=QUERY\n"
56dee73e 3618" QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink}[,QUERY]\n"
ab61159a 3619"\n"
583de149 3620" -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
ab61159a 3621" -F, --filter=FILE read filter information from FILE\n"
ff041f16
VK
3622" FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
3623" STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
3624" TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listen|closing}\n"
3625" connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
3626" synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
3627" bucket := {syn-recv|time-wait}\n"
3628" big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listen|closing}\n"
ab61159a 3629 );
7a96e199
AH
3630}
3631
3632static void help(void) __attribute__((noreturn));
3633static void help(void)
3634{
3635 _usage(stdout);
3636 exit(0);
3637}
3638
3639static void usage(void) __attribute__((noreturn));
3640static void usage(void)
3641{
3642 _usage(stderr);
aba5acdf
SH
3643 exit(-1);
3644}
3645
3646
d1f28cf1 3647static int scan_state(const char *state)
aba5acdf
SH
3648{
3649 int i;
acd1e437 3650
aba5acdf
SH
3651 if (strcasecmp(state, "close") == 0 ||
3652 strcasecmp(state, "closed") == 0)
3653 return (1<<SS_CLOSE);
3654 if (strcasecmp(state, "syn-rcv") == 0)
3655 return (1<<SS_SYN_RECV);
1a5bad5a 3656 if (strcasecmp(state, "established") == 0)
aba5acdf
SH
3657 return (1<<SS_ESTABLISHED);
3658 if (strcasecmp(state, "all") == 0)
3659 return SS_ALL;
3660 if (strcasecmp(state, "connected") == 0)
3661 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
1a5bad5a 3662 if (strcasecmp(state, "synchronized") == 0)
aba5acdf
SH
3663 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
3664 if (strcasecmp(state, "bucket") == 0)
3665 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
3666 if (strcasecmp(state, "big") == 0)
3667 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
acd1e437 3668 for (i = 0; i < SS_MAX; i++) {
1a5bad5a 3669 if (strcasecmp(state, sstate_namel[i]) == 0)
aba5acdf
SH
3670 return (1<<i);
3671 }
9db7bf15
VK
3672
3673 fprintf(stderr, "ss: wrong state name: %s\n", state);
3674 exit(-1);
aba5acdf
SH
3675}
3676
ab61159a
SH
3677static const struct option long_opts[] = {
3678 { "numeric", 0, 0, 'n' },
3679 { "resolve", 0, 0, 'r' },
3680 { "options", 0, 0, 'o' },
3681 { "extended", 0, 0, 'e' },
3682 { "memory", 0, 0, 'm' },
3683 { "info", 0, 0, 'i' },
3684 { "processes", 0, 0, 'p' },
372c30d2 3685 { "bpf", 0, 0, 'b' },
6885e3bf 3686 { "events", 0, 0, 'E' },
351efcde 3687 { "dccp", 0, 0, 'd' },
ab61159a
SH
3688 { "tcp", 0, 0, 't' },
3689 { "udp", 0, 0, 'u' },
3690 { "raw", 0, 0, 'w' },
3691 { "unix", 0, 0, 'x' },
3692 { "all", 0, 0, 'a' },
3693 { "listening", 0, 0, 'l' },
3694 { "ipv4", 0, 0, '4' },
3695 { "ipv6", 0, 0, '6' },
3696 { "packet", 0, 0, '0' },
3697 { "family", 1, 0, 'f' },
3698 { "socket", 1, 0, 'A' },
583de149 3699 { "query", 1, 0, 'A' },
c3f346b0 3700 { "summary", 0, 0, 's' },
583de149 3701 { "diag", 1, 0, 'D' },
ab61159a
SH
3702 { "filter", 1, 0, 'F' },
3703 { "version", 0, 0, 'V' },
3704 { "help", 0, 0, 'h' },
116ac927
RH
3705 { "context", 0, 0, 'Z' },
3706 { "contexts", 0, 0, 'z' },
95ce04bc 3707 { "net", 1, 0, 'N' },
fb2594c1 3708 { "kill", 0, 0, 'K' },
ab61159a 3709 { 0 }
ae665a52 3710
ab61159a
SH
3711};
3712
aba5acdf
SH
3713int main(int argc, char *argv[])
3714{
aba5acdf
SH
3715 int saw_states = 0;
3716 int saw_query = 0;
3717 int do_summary = 0;
7d105b56 3718 const char *dump_tcpdiag = NULL;
aba5acdf
SH
3719 FILE *filter_fp = NULL;
3720 int ch;
9db7bf15 3721 int state_filter = 0;
aba5acdf 3722
fb2594c1 3723 while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spbEf:miA:D:F:vVzZN:K",
ab61159a 3724 long_opts, NULL)) != EOF) {
acd1e437 3725 switch (ch) {
aba5acdf
SH
3726 case 'n':
3727 resolve_services = 0;
3728 break;
3729 case 'r':
3730 resolve_hosts = 1;
3731 break;
3732 case 'o':
3733 show_options = 1;
3734 break;
3735 case 'e':
3736 show_options = 1;
3737 show_details++;
3738 break;
3739 case 'm':
3740 show_mem = 1;
3741 break;
3742 case 'i':
3743 show_tcpinfo = 1;
3744 break;
3745 case 'p':
3746 show_users++;
fbc0f876 3747 user_ent_hash_build();
aba5acdf 3748 break;
372c30d2
ND
3749 case 'b':
3750 show_options = 1;
3751 show_bpf++;
3752 break;
6885e3bf
CG
3753 case 'E':
3754 follow_events = 1;
3755 break;
351efcde 3756 case 'd':
57ff5a10 3757 filter_db_set(&current_filter, DCCP_DB);
351efcde 3758 break;
aba5acdf 3759 case 't':
57ff5a10 3760 filter_db_set(&current_filter, TCP_DB);
aba5acdf
SH
3761 break;
3762 case 'u':
57ff5a10 3763 filter_db_set(&current_filter, UDP_DB);
aba5acdf
SH
3764 break;
3765 case 'w':
57ff5a10 3766 filter_db_set(&current_filter, RAW_DB);
aba5acdf
SH
3767 break;
3768 case 'x':
9db7bf15 3769 filter_af_set(&current_filter, AF_UNIX);
aba5acdf
SH
3770 break;
3771 case 'a':
9db7bf15 3772 state_filter = SS_ALL;
aba5acdf
SH
3773 break;
3774 case 'l':
9db7bf15 3775 state_filter = (1 << SS_LISTEN) | (1 << SS_CLOSE);
aba5acdf
SH
3776 break;
3777 case '4':
9db7bf15 3778 filter_af_set(&current_filter, AF_INET);
aba5acdf
SH
3779 break;
3780 case '6':
9db7bf15 3781 filter_af_set(&current_filter, AF_INET6);
aba5acdf
SH
3782 break;
3783 case '0':
9db7bf15 3784 filter_af_set(&current_filter, AF_PACKET);
aba5acdf
SH
3785 break;
3786 case 'f':
3787 if (strcmp(optarg, "inet") == 0)
9db7bf15 3788 filter_af_set(&current_filter, AF_INET);
aba5acdf 3789 else if (strcmp(optarg, "inet6") == 0)
9db7bf15 3790 filter_af_set(&current_filter, AF_INET6);
aba5acdf 3791 else if (strcmp(optarg, "link") == 0)
9db7bf15 3792 filter_af_set(&current_filter, AF_PACKET);
aba5acdf 3793 else if (strcmp(optarg, "unix") == 0)
9db7bf15 3794 filter_af_set(&current_filter, AF_UNIX);
aba5acdf 3795 else if (strcmp(optarg, "netlink") == 0)
9db7bf15 3796 filter_af_set(&current_filter, AF_NETLINK);
aba5acdf 3797 else if (strcmp(optarg, "help") == 0)
7a96e199 3798 help();
aba5acdf 3799 else {
9db7bf15
VK
3800 fprintf(stderr, "ss: \"%s\" is invalid family\n",
3801 optarg);
aba5acdf
SH
3802 usage();
3803 }
3804 break;
3805 case 'A':
3806 {
3807 char *p, *p1;
acd1e437 3808
aba5acdf
SH
3809 if (!saw_query) {
3810 current_filter.dbs = 0;
7f9dddbe 3811 state_filter = state_filter ?
acd1e437 3812 state_filter : SS_CONN;
aba5acdf
SH
3813 saw_query = 1;
3814 do_default = 0;
3815 }
3816 p = p1 = optarg;
3817 do {
3818 if ((p1 = strchr(p, ',')) != NULL)
ae665a52 3819 *p1 = 0;
aba5acdf 3820 if (strcmp(p, "all") == 0) {
57ff5a10 3821 filter_default_dbs(&current_filter);
aba5acdf 3822 } else if (strcmp(p, "inet") == 0) {
57ff5a10
VK
3823 filter_db_set(&current_filter, UDP_DB);
3824 filter_db_set(&current_filter, DCCP_DB);
3825 filter_db_set(&current_filter, TCP_DB);
3826 filter_db_set(&current_filter, RAW_DB);
aba5acdf 3827 } else if (strcmp(p, "udp") == 0) {
57ff5a10 3828 filter_db_set(&current_filter, UDP_DB);
351efcde 3829 } else if (strcmp(p, "dccp") == 0) {
57ff5a10 3830 filter_db_set(&current_filter, DCCP_DB);
aba5acdf 3831 } else if (strcmp(p, "tcp") == 0) {
57ff5a10 3832 filter_db_set(&current_filter, TCP_DB);
aba5acdf 3833 } else if (strcmp(p, "raw") == 0) {
57ff5a10 3834 filter_db_set(&current_filter, RAW_DB);
aba5acdf 3835 } else if (strcmp(p, "unix") == 0) {
57ff5a10
VK
3836 filter_db_set(&current_filter, UNIX_ST_DB);
3837 filter_db_set(&current_filter, UNIX_DG_DB);
3838 filter_db_set(&current_filter, UNIX_SQ_DB);
1a5bad5a 3839 } else if (strcasecmp(p, "unix_stream") == 0 ||
aba5acdf 3840 strcmp(p, "u_str") == 0) {
57ff5a10 3841 filter_db_set(&current_filter, UNIX_ST_DB);
1a5bad5a 3842 } else if (strcasecmp(p, "unix_dgram") == 0 ||
aba5acdf 3843 strcmp(p, "u_dgr") == 0) {
57ff5a10 3844 filter_db_set(&current_filter, UNIX_DG_DB);
30b669d7
MY
3845 } else if (strcasecmp(p, "unix_seqpacket") == 0 ||
3846 strcmp(p, "u_seq") == 0) {
57ff5a10 3847 filter_db_set(&current_filter, UNIX_SQ_DB);
aba5acdf 3848 } else if (strcmp(p, "packet") == 0) {
57ff5a10
VK
3849 filter_db_set(&current_filter, PACKET_R_DB);
3850 filter_db_set(&current_filter, PACKET_DG_DB);
aba5acdf
SH
3851 } else if (strcmp(p, "packet_raw") == 0 ||
3852 strcmp(p, "p_raw") == 0) {
57ff5a10 3853 filter_db_set(&current_filter, PACKET_R_DB);
aba5acdf
SH
3854 } else if (strcmp(p, "packet_dgram") == 0 ||
3855 strcmp(p, "p_dgr") == 0) {
57ff5a10 3856 filter_db_set(&current_filter, PACKET_DG_DB);
aba5acdf 3857 } else if (strcmp(p, "netlink") == 0) {
57ff5a10 3858 filter_db_set(&current_filter, NETLINK_DB);
aba5acdf
SH
3859 } else {
3860 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
3861 usage();
3862 }
3863 p = p1 + 1;
3864 } while (p1);
3865 break;
3866 }
3867 case 's':
3868 do_summary = 1;
3869 break;
3870 case 'D':
3871 dump_tcpdiag = optarg;
3872 break;
3873 case 'F':
3874 if (filter_fp) {
3875 fprintf(stderr, "More than one filter file\n");
3876 exit(-1);
3877 }
3878 if (optarg[0] == '-')
3879 filter_fp = stdin;
3880 else
3881 filter_fp = fopen(optarg, "r");
3882 if (!filter_fp) {
3883 perror("fopen filter file");
3884 exit(-1);
3885 }
3886 break;
3887 case 'v':
3888 case 'V':
3889 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
3890 exit(0);
116ac927
RH
3891 case 'z':
3892 show_sock_ctx++;
3893 case 'Z':
3894 if (is_selinux_enabled() <= 0) {
3895 fprintf(stderr, "ss: SELinux is not enabled.\n");
3896 exit(1);
3897 }
3898 show_proc_ctx++;
3899 user_ent_hash_build();
3900 break;
95ce04bc
VK
3901 case 'N':
3902 if (netns_switch(optarg))
3903 exit(1);
3904 break;
fb2594c1
LC
3905 case 'K':
3906 current_filter.kill = 1;
3907 break;
aba5acdf 3908 case 'h':
7a96e199 3909 help();
f73105ab 3910 case '?':
aba5acdf
SH
3911 default:
3912 usage();
3913 }
3914 }
3915
3916 argc -= optind;
3917 argv += optind;
3918
aba5acdf
SH
3919 if (do_summary) {
3920 print_summary();
3921 if (do_default && argc == 0)
3922 exit(0);
3923 }
3924
aba5acdf
SH
3925 while (argc > 0) {
3926 if (strcmp(*argv, "state") == 0) {
3927 NEXT_ARG();
3928 if (!saw_states)
9db7bf15
VK
3929 state_filter = 0;
3930 state_filter |= scan_state(*argv);
aba5acdf
SH
3931 saw_states = 1;
3932 } else if (strcmp(*argv, "exclude") == 0 ||
3933 strcmp(*argv, "excl") == 0) {
3934 NEXT_ARG();
3935 if (!saw_states)
9db7bf15
VK
3936 state_filter = SS_ALL;
3937 state_filter &= ~scan_state(*argv);
aba5acdf
SH
3938 saw_states = 1;
3939 } else {
aba5acdf
SH
3940 break;
3941 }
3942 argc--; argv++;
3943 }
3944
9db7bf15
VK
3945 if (do_default) {
3946 state_filter = state_filter ? state_filter : SS_CONN;
3947 filter_default_dbs(&current_filter);
9db7bf15
VK
3948 }
3949
57ff5a10
VK
3950 filter_states_set(&current_filter, state_filter);
3951 filter_merge_defaults(&current_filter);
3952
9db7bf15
VK
3953 if (resolve_services && resolve_hosts &&
3954 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
3955 init_service_resolver();
3956
3957
3958 if (current_filter.dbs == 0) {
3959 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
3960 exit(0);
3961 }
3962 if (current_filter.families == 0) {
3963 fprintf(stderr, "ss: no families to show with such filter.\n");
3964 exit(0);
3965 }
aba5acdf
SH
3966 if (current_filter.states == 0) {
3967 fprintf(stderr, "ss: no socket states to show with such filter.\n");
3968 exit(0);
3969 }
3970
3971 if (dump_tcpdiag) {
3972 FILE *dump_fp = stdout;
acd1e437 3973
aba5acdf
SH
3974 if (!(current_filter.dbs & (1<<TCP_DB))) {
3975 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
3976 exit(0);
3977 }
3978 if (dump_tcpdiag[0] != '-') {
3979 dump_fp = fopen(dump_tcpdiag, "w");
3980 if (!dump_tcpdiag) {
3981 perror("fopen dump file");
3982 exit(-1);
3983 }
3984 }
3fe5b534 3985 inet_show_netlink(&current_filter, dump_fp, IPPROTO_TCP);
aba5acdf
SH
3986 fflush(dump_fp);
3987 exit(0);
3988 }
3989
1527a17e
VK
3990 if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
3991 usage();
3992
aba5acdf
SH
3993 netid_width = 0;
3994 if (current_filter.dbs&(current_filter.dbs-1))
3995 netid_width = 5;
3996
3997 state_width = 0;
3998 if (current_filter.states&(current_filter.states-1))
3999 state_width = 10;
4000
4001 screen_width = 80;
4002 if (isatty(STDOUT_FILENO)) {
4003 struct winsize w;
4004
4005 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
4006 if (w.ws_col > 0)
4007 screen_width = w.ws_col;
4008 }
4009 }
4010
4011 addrp_width = screen_width;
4012 addrp_width -= netid_width+1;
4013 addrp_width -= state_width+1;
4014 addrp_width -= 14;
4015
4016 if (addrp_width&1) {
4017 if (netid_width)
4018 netid_width++;
4019 else if (state_width)
4020 state_width++;
4021 }
4022
4023 addrp_width /= 2;
4024 addrp_width--;
4025
4026 serv_width = resolve_services ? 7 : 5;
4027
4028 if (addrp_width < 15+serv_width+1)
4029 addrp_width = 15+serv_width+1;
4030
ae665a52 4031 addr_width = addrp_width - serv_width - 1;
aba5acdf
SH
4032
4033 if (netid_width)
4034 printf("%-*s ", netid_width, "Netid");
4035 if (state_width)
4036 printf("%-*s ", state_width, "State");
4037 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
4038
d68e00f7 4039 /* Make enough space for the local/remote port field */
4040 addr_width -= 13;
4041 serv_width += 13;
2dc85485 4042
aba5acdf
SH
4043 printf("%*s:%-*s %*s:%-*s\n",
4044 addr_width, "Local Address", serv_width, "Port",
d68e00f7 4045 addr_width, "Peer Address", serv_width, "Port");
aba5acdf 4046
aba5acdf
SH
4047 fflush(stdout);
4048
6885e3bf
CG
4049 if (follow_events)
4050 exit(handle_follow_request(&current_filter));
4051
aba5acdf
SH
4052 if (current_filter.dbs & (1<<NETLINK_DB))
4053 netlink_show(&current_filter);
4054 if (current_filter.dbs & PACKET_DBM)
4055 packet_show(&current_filter);
4056 if (current_filter.dbs & UNIX_DBM)
4057 unix_show(&current_filter);
4058 if (current_filter.dbs & (1<<RAW_DB))
4059 raw_show(&current_filter);
4060 if (current_filter.dbs & (1<<UDP_DB))
4061 udp_show(&current_filter);
4062 if (current_filter.dbs & (1<<TCP_DB))
3fe5b534 4063 tcp_show(&current_filter, IPPROTO_TCP);
351efcde 4064 if (current_filter.dbs & (1<<DCCP_DB))
3fe5b534 4065 tcp_show(&current_filter, IPPROTO_DCCP);
116ac927
RH
4066
4067 if (show_users || show_proc_ctx || show_sock_ctx)
4068 user_ent_destroy();
4069
aba5acdf
SH
4070 return 0;
4071}