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