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