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