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