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