xref: /freebsd/usr.bin/sockstat/sockstat.c (revision 9f55128fecb5b5eb8e8fffa5b65d38255762d176)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002 Dag-Erling Smørgrav
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer
12  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/param.h>
32 #include <sys/file.h>
33 #include <sys/socket.h>
34 #include <sys/socketvar.h>
35 #include <sys/sysctl.h>
36 #include <sys/jail.h>
37 #include <sys/user.h>
38 #include <sys/queue.h>
39 #include <sys/tree.h>
40 
41 #include <sys/un.h>
42 #include <sys/unpcb.h>
43 
44 #include <net/route.h>
45 
46 #include <netinet/in.h>
47 #include <netinet/in_pcb.h>
48 #include <netinet/sctp.h>
49 #include <netinet/tcp.h>
50 #define TCPSTATES /* load state names */
51 #include <netinet/tcp_fsm.h>
52 #include <netinet/tcp_seq.h>
53 #include <netinet/tcp_var.h>
54 #include <arpa/inet.h>
55 
56 #include <capsicum_helpers.h>
57 #include <ctype.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <inttypes.h>
61 #include <jail.h>
62 #include <netdb.h>
63 #include <pwd.h>
64 #include <stdarg.h>
65 #include <stdbool.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70 
71 #include <libcasper.h>
72 #include <casper/cap_net.h>
73 #include <casper/cap_netdb.h>
74 #include <casper/cap_pwd.h>
75 #include <casper/cap_sysctl.h>
76 
77 #define	sstosin(ss)	((struct sockaddr_in *)(ss))
78 #define	sstosin6(ss)	((struct sockaddr_in6 *)(ss))
79 #define	sstosun(ss)	((struct sockaddr_un *)(ss))
80 #define	sstosa(ss)	((struct sockaddr *)(ss))
81 
82 static bool	 opt_4;		/* Show IPv4 sockets */
83 static bool	 opt_6;		/* Show IPv6 sockets */
84 static bool	 opt_A;		/* Show kernel address of pcb */
85 static bool	 opt_C;		/* Show congestion control */
86 static bool	 opt_c;		/* Show connected sockets */
87 static bool	 opt_f;		/* Show FIB numbers */
88 static bool	 opt_I;		/* Show spliced socket addresses */
89 static bool	 opt_i;		/* Show inp_gencnt */
90 static int	 opt_j;		/* Show specified jail */
91 static bool	 opt_L;		/* Don't show IPv4 or IPv6 loopback sockets */
92 static bool	 opt_l;		/* Show listening sockets */
93 static bool	 opt_n;		/* Don't resolve UIDs to user names */
94 static bool	 opt_q;		/* Don't show header */
95 static bool	 opt_S;		/* Show protocol stack if applicable */
96 static bool	 opt_s;		/* Show protocol state if applicable */
97 static bool	 opt_U;		/* Show remote UDP encapsulation port number */
98 static bool	 opt_u;		/* Show Unix domain sockets */
99 static u_int	 opt_v;		/* Verbose mode */
100 static bool	 opt_w;		/* Wide print area for addresses */
101 
102 /*
103  * Default protocols to use if no -P was defined.
104  */
105 static const char *default_protos[] = {"sctp", "tcp", "udp", "divert" };
106 static size_t	   default_numprotos = nitems(default_protos);
107 
108 static int	*protos;	/* protocols to use */
109 static size_t	 numprotos;	/* allocated size of protos[] */
110 
111 static int	*ports;
112 
113 #define	INT_BIT (sizeof(int)*CHAR_BIT)
114 #define	SET_PORT(p) do { ports[p / INT_BIT] |= 1 << (p % INT_BIT); } while (0)
115 #define	CHK_PORT(p) (ports[p / INT_BIT] & (1 << (p % INT_BIT)))
116 
117 struct addr {
118 	union {
119 		struct sockaddr_storage address;
120 		struct {	/* unix(4) faddr */
121 			kvaddr_t conn;
122 			kvaddr_t firstref;
123 			kvaddr_t nextref;
124 		};
125 	};
126 	unsigned int encaps_port;
127 	int state;
128 	struct addr *next;
129 };
130 
131 struct sock {
132 	union {
133 		RB_ENTRY(sock) socket_tree;	/* tree of pcbs with socket */
134 		SLIST_ENTRY(sock) socket_list;	/* list of pcbs w/o socket */
135 	};
136 	RB_ENTRY(sock) pcb_tree;
137 	kvaddr_t socket;
138 	kvaddr_t pcb;
139 	kvaddr_t splice_socket;
140 	uint64_t inp_gencnt;
141 	int shown;
142 	int vflag;
143 	int family;
144 	int proto;
145 	int state;
146 	int fibnum;
147 	const char *protoname;
148 	char stack[TCP_FUNCTION_NAME_LEN_MAX];
149 	char cc[TCP_CA_NAME_MAX];
150 	struct addr *laddr;
151 	struct addr *faddr;
152 };
153 
154 static RB_HEAD(socks_t, sock) socks = RB_INITIALIZER(&socks);
155 static int64_t
socket_compare(const struct sock * a,const struct sock * b)156 socket_compare(const struct sock *a, const struct sock *b)
157 {
158 	return ((int64_t)(a->socket/2 - b->socket/2));
159 }
160 RB_GENERATE_STATIC(socks_t, sock, socket_tree, socket_compare);
161 
162 static RB_HEAD(pcbs_t, sock) pcbs = RB_INITIALIZER(&pcbs);
163 static int64_t
pcb_compare(const struct sock * a,const struct sock * b)164 pcb_compare(const struct sock *a, const struct sock *b)
165 {
166         return ((int64_t)(a->pcb/2 - b->pcb/2));
167 }
168 RB_GENERATE_STATIC(pcbs_t, sock, pcb_tree, pcb_compare);
169 
170 static SLIST_HEAD(, sock) nosocks = SLIST_HEAD_INITIALIZER(&nosocks);
171 
172 struct file {
173 	RB_ENTRY(file)	file_tree;
174 	kvaddr_t	xf_data;
175 	pid_t	xf_pid;
176 	uid_t	xf_uid;
177 	int	xf_fd;
178 };
179 
180 static RB_HEAD(files_t, file) ftree = RB_INITIALIZER(&ftree);
181 static int64_t
file_compare(const struct file * a,const struct file * b)182 file_compare(const struct file *a, const struct file *b)
183 {
184 	return ((int64_t)(a->xf_data/2 - b->xf_data/2));
185 }
186 RB_GENERATE_STATIC(files_t, file, file_tree, file_compare);
187 
188 static struct file *files;
189 static int nfiles;
190 
191 static cap_channel_t *capnet;
192 static cap_channel_t *capnetdb;
193 static cap_channel_t *capsysctl;
194 static cap_channel_t *cappwd;
195 
196 static int
xprintf(const char * fmt,...)197 xprintf(const char *fmt, ...)
198 {
199 	va_list ap;
200 	int len;
201 
202 	va_start(ap, fmt);
203 	len = vprintf(fmt, ap);
204 	va_end(ap);
205 	if (len < 0)
206 		err(1, "printf()");
207 	return (len);
208 }
209 
210 static bool
_check_ksize(size_t received_size,size_t expected_size,const char * struct_name)211 _check_ksize(size_t received_size, size_t expected_size, const char *struct_name)
212 {
213 	if (received_size != expected_size) {
214 		warnx("%s size mismatch: expected %zd, received %zd",
215 		    struct_name, expected_size, received_size);
216 		return false;
217 	}
218 	return true;
219 }
220 #define check_ksize(_sz, _struct)	(_check_ksize(_sz, sizeof(_struct), #_struct))
221 
222 static void
_enforce_ksize(size_t received_size,size_t expected_size,const char * struct_name)223 _enforce_ksize(size_t received_size, size_t expected_size, const char *struct_name)
224 {
225 	if (received_size != expected_size) {
226 		errx(1, "fatal: struct %s size mismatch: expected %zd, received %zd",
227 		    struct_name, expected_size, received_size);
228 	}
229 }
230 #define enforce_ksize(_sz, _struct)	(_enforce_ksize(_sz, sizeof(_struct), #_struct))
231 
232 static int
get_proto_type(const char * proto)233 get_proto_type(const char *proto)
234 {
235 	struct protoent *pent;
236 
237 	if (strlen(proto) == 0)
238 		return (0);
239 	if (capnetdb != NULL)
240 		pent = cap_getprotobyname(capnetdb, proto);
241 	else
242 		pent = getprotobyname(proto);
243 	if (pent == NULL) {
244 		warn("cap_getprotobyname");
245 		return (-1);
246 	}
247 	return (pent->p_proto);
248 }
249 
250 static void
init_protos(int num)251 init_protos(int num)
252 {
253 	int proto_count = 0;
254 
255 	if (num > 0) {
256 		proto_count = num;
257 	} else {
258 		/* Find the maximum number of possible protocols. */
259 		while (getprotoent() != NULL)
260 			proto_count++;
261 		endprotoent();
262 	}
263 
264 	if ((protos = malloc(sizeof(int) * proto_count)) == NULL)
265 		err(1, "malloc");
266 	numprotos = proto_count;
267 }
268 
269 static int
parse_protos(char * protospec)270 parse_protos(char *protospec)
271 {
272 	char *prot;
273 	int proto_type, proto_index;
274 
275 	if (protospec == NULL)
276 		return (-1);
277 
278 	init_protos(0);
279 	proto_index = 0;
280 	while ((prot = strsep(&protospec, ",")) != NULL) {
281 		if (strlen(prot) == 0)
282 			continue;
283 		proto_type = get_proto_type(prot);
284 		if (proto_type != -1)
285 			protos[proto_index++] = proto_type;
286 	}
287 	numprotos = proto_index;
288 	return (proto_index);
289 }
290 
291 static void
parse_ports(const char * portspec)292 parse_ports(const char *portspec)
293 {
294 	const char *p, *q;
295 	int port, end;
296 
297 	if (ports == NULL)
298 		if ((ports = calloc(65536 / INT_BIT, sizeof(int))) == NULL)
299 			err(1, "calloc()");
300 	p = portspec;
301 	while (*p != '\0') {
302 		if (!isdigit(*p))
303 			errx(1, "syntax error in port range");
304 		for (q = p; *q != '\0' && isdigit(*q); ++q)
305 			/* nothing */ ;
306 		for (port = 0; p < q; ++p)
307 			port = port * 10 + digittoint(*p);
308 		if (port < 0 || port > 65535)
309 			errx(1, "invalid port number");
310 		SET_PORT(port);
311 		switch (*p) {
312 		case '-':
313 			++p;
314 			break;
315 		case ',':
316 			++p;
317 			/* fall through */
318 		case '\0':
319 		default:
320 			continue;
321 		}
322 		for (q = p; *q != '\0' && isdigit(*q); ++q)
323 			/* nothing */ ;
324 		for (end = 0; p < q; ++p)
325 			end = end * 10 + digittoint(*p);
326 		if (end < port || end > 65535)
327 			errx(1, "invalid port number");
328 		while (port++ < end)
329 			SET_PORT(port);
330 		if (*p == ',')
331 			++p;
332 	}
333 }
334 
335 static void
sockaddr(struct sockaddr_storage * ss,int af,void * addr,int port)336 sockaddr(struct sockaddr_storage *ss, int af, void *addr, int port)
337 {
338 	struct sockaddr_in *sin4;
339 	struct sockaddr_in6 *sin6;
340 
341 	bzero(ss, sizeof(*ss));
342 	switch (af) {
343 	case AF_INET:
344 		sin4 = sstosin(ss);
345 		sin4->sin_len = sizeof(*sin4);
346 		sin4->sin_family = af;
347 		sin4->sin_port = port;
348 		sin4->sin_addr = *(struct in_addr *)addr;
349 		break;
350 	case AF_INET6:
351 		sin6 = sstosin6(ss);
352 		sin6->sin6_len = sizeof(*sin6);
353 		sin6->sin6_family = af;
354 		sin6->sin6_port = port;
355 		sin6->sin6_addr = *(struct in6_addr *)addr;
356 #define	s6_addr16	__u6_addr.__u6_addr16
357 		if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
358 			sin6->sin6_scope_id =
359 			    ntohs(sin6->sin6_addr.s6_addr16[1]);
360 			sin6->sin6_addr.s6_addr16[1] = 0;
361 		}
362 		break;
363 	default:
364 		abort();
365 	}
366 }
367 
368 static void
free_socket(struct sock * sock)369 free_socket(struct sock *sock)
370 {
371 	struct addr *cur, *next;
372 
373 	cur = sock->laddr;
374 	while (cur != NULL) {
375 		next = cur->next;
376 		free(cur);
377 		cur = next;
378 	}
379 	cur = sock->faddr;
380 	while (cur != NULL) {
381 		next = cur->next;
382 		free(cur);
383 		cur = next;
384 	}
385 	free(sock);
386 }
387 
388 static void
gather_sctp(void)389 gather_sctp(void)
390 {
391 	struct sock *sock;
392 	struct addr *laddr, *prev_laddr, *faddr, *prev_faddr;
393 	struct xsctp_inpcb *xinpcb;
394 	struct xsctp_tcb *xstcb;
395 	struct xsctp_raddr *xraddr;
396 	struct xsctp_laddr *xladdr;
397 	const char *varname;
398 	size_t len, offset;
399 	char *buf;
400 	int vflag;
401 	int no_stcb, local_all_loopback, foreign_all_loopback;
402 
403 	vflag = 0;
404 	if (opt_4)
405 		vflag |= INP_IPV4;
406 	if (opt_6)
407 		vflag |= INP_IPV6;
408 
409 	varname = "net.inet.sctp.assoclist";
410 	if (cap_sysctlbyname(capsysctl, varname, 0, &len, 0, 0) < 0) {
411 		if (errno != ENOENT)
412 			err(1, "cap_sysctlbyname()");
413 		return;
414 	}
415 	if ((buf = (char *)malloc(len)) == NULL) {
416 		err(1, "malloc()");
417 		return;
418 	}
419 	if (cap_sysctlbyname(capsysctl, varname, buf, &len, 0, 0) < 0) {
420 		err(1, "cap_sysctlbyname()");
421 		free(buf);
422 		return;
423 	}
424 	xinpcb = (struct xsctp_inpcb *)(void *)buf;
425 	offset = sizeof(struct xsctp_inpcb);
426 	while ((offset < len) && (xinpcb->last == 0)) {
427 		if ((sock = calloc(1, sizeof *sock)) == NULL)
428 			err(1, "malloc()");
429 		sock->socket = xinpcb->socket;
430 		sock->proto = IPPROTO_SCTP;
431 		sock->protoname = "sctp";
432 		if (xinpcb->maxqlen == 0)
433 			sock->state = SCTP_CLOSED;
434 		else
435 			sock->state = SCTP_LISTEN;
436 		if (xinpcb->flags & SCTP_PCB_FLAGS_BOUND_V6) {
437 			sock->family = AF_INET6;
438 			/*
439 			 * Currently there is no way to distinguish between
440 			 * IPv6 only sockets or dual family sockets.
441 			 * So mark it as dual socket.
442 			 */
443 			sock->vflag = INP_IPV6 | INP_IPV4;
444 		} else {
445 			sock->family = AF_INET;
446 			sock->vflag = INP_IPV4;
447 		}
448 		prev_laddr = NULL;
449 		local_all_loopback = 1;
450 		while (offset < len) {
451 			xladdr = (struct xsctp_laddr *)(void *)(buf + offset);
452 			offset += sizeof(struct xsctp_laddr);
453 			if (xladdr->last == 1)
454 				break;
455 			if ((laddr = calloc(1, sizeof(struct addr))) == NULL)
456 				err(1, "malloc()");
457 			switch (xladdr->address.sa.sa_family) {
458 			case AF_INET:
459 #define	__IN_IS_ADDR_LOOPBACK(pina) \
460 	((ntohl((pina)->s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
461 				if (!__IN_IS_ADDR_LOOPBACK(
462 				    &xladdr->address.sin.sin_addr))
463 					local_all_loopback = 0;
464 #undef	__IN_IS_ADDR_LOOPBACK
465 				sockaddr(&laddr->address, AF_INET,
466 				    &xladdr->address.sin.sin_addr,
467 				    htons(xinpcb->local_port));
468 				break;
469 			case AF_INET6:
470 				if (!IN6_IS_ADDR_LOOPBACK(
471 				    &xladdr->address.sin6.sin6_addr))
472 					local_all_loopback = 0;
473 				sockaddr(&laddr->address, AF_INET6,
474 				    &xladdr->address.sin6.sin6_addr,
475 				    htons(xinpcb->local_port));
476 				break;
477 			default:
478 				errx(1, "address family %d not supported",
479 				    xladdr->address.sa.sa_family);
480 			}
481 			laddr->next = NULL;
482 			if (prev_laddr == NULL)
483 				sock->laddr = laddr;
484 			else
485 				prev_laddr->next = laddr;
486 			prev_laddr = laddr;
487 		}
488 		if (sock->laddr == NULL) {
489 			if ((sock->laddr =
490 			    calloc(1, sizeof(struct addr))) == NULL)
491 				err(1, "malloc()");
492 			sock->laddr->address.ss_family = sock->family;
493 			if (sock->family == AF_INET)
494 				sock->laddr->address.ss_len =
495 				    sizeof(struct sockaddr_in);
496 			else
497 				sock->laddr->address.ss_len =
498 				    sizeof(struct sockaddr_in6);
499 			local_all_loopback = 0;
500 		}
501 		if ((sock->faddr = calloc(1, sizeof(struct addr))) == NULL)
502 			err(1, "malloc()");
503 		sock->faddr->address.ss_family = sock->family;
504 		if (sock->family == AF_INET)
505 			sock->faddr->address.ss_len =
506 			    sizeof(struct sockaddr_in);
507 		else
508 			sock->faddr->address.ss_len =
509 			    sizeof(struct sockaddr_in6);
510 		no_stcb = 1;
511 		while (offset < len) {
512 			xstcb = (struct xsctp_tcb *)(void *)(buf + offset);
513 			offset += sizeof(struct xsctp_tcb);
514 			if (no_stcb) {
515 				if (opt_l && (sock->vflag & vflag) &&
516 				    (!opt_L || !local_all_loopback) &&
517 				    ((xinpcb->flags & SCTP_PCB_FLAGS_UDPTYPE) ||
518 				     (xstcb->last == 1))) {
519 					RB_INSERT(socks_t, &socks, sock);
520 				} else {
521 					free_socket(sock);
522 				}
523 			}
524 			if (xstcb->last == 1)
525 				break;
526 			no_stcb = 0;
527 			if (opt_c) {
528 				if ((sock = calloc(1, sizeof *sock)) == NULL)
529 					err(1, "malloc()");
530 				sock->socket = xinpcb->socket;
531 				sock->proto = IPPROTO_SCTP;
532 				sock->protoname = "sctp";
533 				sock->state = (int)xstcb->state;
534 				if (xinpcb->flags & SCTP_PCB_FLAGS_BOUND_V6) {
535 					sock->family = AF_INET6;
536 				/*
537 				 * Currently there is no way to distinguish
538 				 * between IPv6 only sockets or dual family
539 				 *  sockets. So mark it as dual socket.
540 				 */
541 					sock->vflag = INP_IPV6 | INP_IPV4;
542 				} else {
543 					sock->family = AF_INET;
544 					sock->vflag = INP_IPV4;
545 				}
546 			}
547 			prev_laddr = NULL;
548 			local_all_loopback = 1;
549 			while (offset < len) {
550 				xladdr = (struct xsctp_laddr *)(void *)(buf +
551 				    offset);
552 				offset += sizeof(struct xsctp_laddr);
553 				if (xladdr->last == 1)
554 					break;
555 				if (!opt_c)
556 					continue;
557 				laddr = calloc(1, sizeof(struct addr));
558 				if (laddr == NULL)
559 					err(1, "malloc()");
560 				switch (xladdr->address.sa.sa_family) {
561 				case AF_INET:
562 #define	__IN_IS_ADDR_LOOPBACK(pina) \
563 	((ntohl((pina)->s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
564 					if (!__IN_IS_ADDR_LOOPBACK(
565 					    &xladdr->address.sin.sin_addr))
566 						local_all_loopback = 0;
567 #undef	__IN_IS_ADDR_LOOPBACK
568 					sockaddr(&laddr->address, AF_INET,
569 					    &xladdr->address.sin.sin_addr,
570 					    htons(xstcb->local_port));
571 					break;
572 				case AF_INET6:
573 					if (!IN6_IS_ADDR_LOOPBACK(
574 					    &xladdr->address.sin6.sin6_addr))
575 						local_all_loopback = 0;
576 					sockaddr(&laddr->address, AF_INET6,
577 					    &xladdr->address.sin6.sin6_addr,
578 					    htons(xstcb->local_port));
579 					break;
580 				default:
581 					errx(1,
582 					    "address family %d not supported",
583 					    xladdr->address.sa.sa_family);
584 				}
585 				laddr->next = NULL;
586 				if (prev_laddr == NULL)
587 					sock->laddr = laddr;
588 				else
589 					prev_laddr->next = laddr;
590 				prev_laddr = laddr;
591 			}
592 			prev_faddr = NULL;
593 			foreign_all_loopback = 1;
594 			while (offset < len) {
595 				xraddr = (struct xsctp_raddr *)(void *)(buf +
596 				    offset);
597 				offset += sizeof(struct xsctp_raddr);
598 				if (xraddr->last == 1)
599 					break;
600 				if (!opt_c)
601 					continue;
602 				faddr = calloc(1, sizeof(struct addr));
603 				if (faddr == NULL)
604 					err(1, "malloc()");
605 				switch (xraddr->address.sa.sa_family) {
606 				case AF_INET:
607 #define	__IN_IS_ADDR_LOOPBACK(pina) \
608 	((ntohl((pina)->s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
609 					if (!__IN_IS_ADDR_LOOPBACK(
610 					    &xraddr->address.sin.sin_addr))
611 						foreign_all_loopback = 0;
612 #undef	__IN_IS_ADDR_LOOPBACK
613 					sockaddr(&faddr->address, AF_INET,
614 					    &xraddr->address.sin.sin_addr,
615 					    htons(xstcb->remote_port));
616 					break;
617 				case AF_INET6:
618 					if (!IN6_IS_ADDR_LOOPBACK(
619 					    &xraddr->address.sin6.sin6_addr))
620 						foreign_all_loopback = 0;
621 					sockaddr(&faddr->address, AF_INET6,
622 					    &xraddr->address.sin6.sin6_addr,
623 					    htons(xstcb->remote_port));
624 					break;
625 				default:
626 					errx(1,
627 					    "address family %d not supported",
628 					    xraddr->address.sa.sa_family);
629 				}
630 				faddr->encaps_port = xraddr->encaps_port;
631 				faddr->state = xraddr->state;
632 				faddr->next = NULL;
633 				if (prev_faddr == NULL)
634 					sock->faddr = faddr;
635 				else
636 					prev_faddr->next = faddr;
637 				prev_faddr = faddr;
638 			}
639 			if (opt_c) {
640 				if ((sock->vflag & vflag) &&
641 				    (!opt_L ||
642 				     !(local_all_loopback ||
643 				     foreign_all_loopback))) {
644 					RB_INSERT(socks_t, &socks, sock);
645 				} else {
646 					free_socket(sock);
647 				}
648 			}
649 		}
650 		xinpcb = (struct xsctp_inpcb *)(void *)(buf + offset);
651 		offset += sizeof(struct xsctp_inpcb);
652 	}
653 	free(buf);
654 }
655 
656 static void
gather_inet(int proto)657 gather_inet(int proto)
658 {
659 	struct xinpgen *xig, *exig;
660 	struct xinpcb *xip;
661 	struct xtcpcb *xtp = NULL;
662 	struct xsocket *so;
663 	struct sock *sock;
664 	struct addr *laddr, *faddr;
665 	const char *varname, *protoname;
666 	size_t len, bufsize;
667 	void *buf;
668 	int retry, vflag;
669 
670 	vflag = 0;
671 	if (opt_4)
672 		vflag |= INP_IPV4;
673 	if (opt_6)
674 		vflag |= INP_IPV6;
675 
676 	switch (proto) {
677 	case IPPROTO_TCP:
678 		varname = "net.inet.tcp.pcblist";
679 		protoname = "tcp";
680 		break;
681 	case IPPROTO_UDP:
682 		varname = "net.inet.udp.pcblist";
683 		protoname = "udp";
684 		break;
685 	case IPPROTO_DIVERT:
686 		varname = "net.inet.divert.pcblist";
687 		protoname = "div";
688 		break;
689 	default:
690 		errx(1, "protocol %d not supported", proto);
691 	}
692 
693 	buf = NULL;
694 	bufsize = 8192;
695 	retry = 5;
696 	do {
697 		for (;;) {
698 			if ((buf = realloc(buf, bufsize)) == NULL)
699 				err(1, "realloc()");
700 			len = bufsize;
701 			if (cap_sysctlbyname(capsysctl, varname, buf, &len,
702 			    NULL, 0) == 0)
703 				break;
704 			if (errno == ENOENT)
705 				goto out;
706 			if (errno != ENOMEM || len != bufsize)
707 				err(1, "cap_sysctlbyname()");
708 			bufsize *= 2;
709 		}
710 		xig = (struct xinpgen *)buf;
711 		exig = (struct xinpgen *)(void *)
712 		    ((char *)buf + len - sizeof *exig);
713 		enforce_ksize(xig->xig_len, struct xinpgen);
714 		enforce_ksize(exig->xig_len, struct xinpgen);
715 	} while (xig->xig_gen != exig->xig_gen && retry--);
716 
717 	if (xig->xig_gen != exig->xig_gen && opt_v)
718 		warnx("warning: data may be inconsistent");
719 
720 	for (;;) {
721 		xig = (struct xinpgen *)(void *)((char *)xig + xig->xig_len);
722 		if (xig >= exig)
723 			break;
724 		switch (proto) {
725 		case IPPROTO_TCP:
726 			xtp = (struct xtcpcb *)xig;
727 			xip = &xtp->xt_inp;
728 			if (!check_ksize(xtp->xt_len, struct xtcpcb))
729 				goto out;
730 			protoname = xtp->t_flags & TF_TOE ? "toe" : "tcp";
731 			break;
732 		case IPPROTO_UDP:
733 		case IPPROTO_DIVERT:
734 			xip = (struct xinpcb *)xig;
735 			if (!check_ksize(xip->xi_len, struct xinpcb))
736 				goto out;
737 			break;
738 		default:
739 			errx(1, "protocol %d not supported", proto);
740 		}
741 		so = &xip->xi_socket;
742 		if ((xip->inp_vflag & vflag) == 0)
743 			continue;
744 		if (xip->inp_vflag & INP_IPV4) {
745 			if ((xip->inp_fport == 0 && !opt_l) ||
746 			    (xip->inp_fport != 0 && !opt_c))
747 				continue;
748 #define	__IN_IS_ADDR_LOOPBACK(pina) \
749 	((ntohl((pina)->s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
750 			if (opt_L &&
751 			    (__IN_IS_ADDR_LOOPBACK(&xip->inp_faddr) ||
752 			     __IN_IS_ADDR_LOOPBACK(&xip->inp_laddr)))
753 				continue;
754 #undef	__IN_IS_ADDR_LOOPBACK
755 		} else if (xip->inp_vflag & INP_IPV6) {
756 			if ((xip->inp_fport == 0 && !opt_l) ||
757 			    (xip->inp_fport != 0 && !opt_c))
758 				continue;
759 			if (opt_L &&
760 			    (IN6_IS_ADDR_LOOPBACK(&xip->in6p_faddr) ||
761 			     IN6_IS_ADDR_LOOPBACK(&xip->in6p_laddr)))
762 				continue;
763 		} else {
764 			if (opt_v)
765 				warnx("invalid vflag 0x%x", xip->inp_vflag);
766 			continue;
767 		}
768 		if ((sock = calloc(1, sizeof(*sock))) == NULL)
769 			err(1, "malloc()");
770 		if ((laddr = calloc(1, sizeof *laddr)) == NULL)
771 			err(1, "malloc()");
772 		if ((faddr = calloc(1, sizeof *faddr)) == NULL)
773 			err(1, "malloc()");
774 		sock->socket = so->xso_so;
775 		sock->pcb = so->so_pcb;
776 		sock->splice_socket = so->so_splice_so;
777 		sock->proto = proto;
778 		sock->inp_gencnt = xip->inp_gencnt;
779 		sock->fibnum = so->so_fibnum;
780 		if (xip->inp_vflag & INP_IPV4) {
781 			sock->family = AF_INET;
782 			sockaddr(&laddr->address, sock->family,
783 			    &xip->inp_laddr, xip->inp_lport);
784 			sockaddr(&faddr->address, sock->family,
785 			    &xip->inp_faddr, xip->inp_fport);
786 		} else if (xip->inp_vflag & INP_IPV6) {
787 			sock->family = AF_INET6;
788 			sockaddr(&laddr->address, sock->family,
789 			    &xip->in6p_laddr, xip->inp_lport);
790 			sockaddr(&faddr->address, sock->family,
791 			    &xip->in6p_faddr, xip->inp_fport);
792 		}
793 		if (proto == IPPROTO_TCP)
794 			faddr->encaps_port = xtp->xt_encaps_port;
795 		laddr->next = NULL;
796 		faddr->next = NULL;
797 		sock->laddr = laddr;
798 		sock->faddr = faddr;
799 		sock->vflag = xip->inp_vflag;
800 		if (proto == IPPROTO_TCP) {
801 			sock->state = xtp->t_state;
802 			memcpy(sock->stack, xtp->xt_stack,
803 			    TCP_FUNCTION_NAME_LEN_MAX);
804 			memcpy(sock->cc, xtp->xt_cc, TCP_CA_NAME_MAX);
805 		}
806 		sock->protoname = protoname;
807 		if (sock->socket != 0)
808 			RB_INSERT(socks_t, &socks, sock);
809 		else
810 			SLIST_INSERT_HEAD(&nosocks, sock, socket_list);
811 	}
812 out:
813 	free(buf);
814 }
815 
816 static void
gather_unix(int proto)817 gather_unix(int proto)
818 {
819 	struct xunpgen *xug, *exug;
820 	struct xunpcb *xup;
821 	struct sock *sock;
822 	struct addr *laddr, *faddr;
823 	const char *varname, *protoname;
824 	size_t len, bufsize;
825 	void *buf;
826 	int retry;
827 
828 	switch (proto) {
829 	case SOCK_STREAM:
830 		varname = "net.local.stream.pcblist";
831 		protoname = "stream";
832 		break;
833 	case SOCK_DGRAM:
834 		varname = "net.local.dgram.pcblist";
835 		protoname = "dgram";
836 		break;
837 	case SOCK_SEQPACKET:
838 		varname = "net.local.seqpacket.pcblist";
839 		protoname = "seqpac";
840 		break;
841 	default:
842 		abort();
843 	}
844 	buf = NULL;
845 	bufsize = 8192;
846 	retry = 5;
847 	do {
848 		for (;;) {
849 			if ((buf = realloc(buf, bufsize)) == NULL)
850 				err(1, "realloc()");
851 			len = bufsize;
852 			if (cap_sysctlbyname(capsysctl, varname, buf, &len,
853 			    NULL, 0) == 0)
854 				break;
855 			if (errno != ENOMEM || len != bufsize)
856 				err(1, "cap_sysctlbyname()");
857 			bufsize *= 2;
858 		}
859 		xug = (struct xunpgen *)buf;
860 		exug = (struct xunpgen *)(void *)
861 		    ((char *)buf + len - sizeof(*exug));
862 		if (!check_ksize(xug->xug_len, struct xunpgen) ||
863 		    !check_ksize(exug->xug_len, struct xunpgen))
864 			goto out;
865 	} while (xug->xug_gen != exug->xug_gen && retry--);
866 
867 	if (xug->xug_gen != exug->xug_gen && opt_v)
868 		warnx("warning: data may be inconsistent");
869 
870 	for (;;) {
871 		xug = (struct xunpgen *)(void *)((char *)xug + xug->xug_len);
872 		if (xug >= exug)
873 			break;
874 		xup = (struct xunpcb *)xug;
875 		if (!check_ksize(xup->xu_len, struct xunpcb))
876 			goto out;
877 		if ((xup->unp_conn == 0 && !opt_l) ||
878 		    (xup->unp_conn != 0 && !opt_c))
879 			continue;
880 		if ((sock = calloc(1, sizeof(*sock))) == NULL)
881 			err(1, "malloc()");
882 		if ((laddr = calloc(1, sizeof *laddr)) == NULL)
883 			err(1, "malloc()");
884 		if ((faddr = calloc(1, sizeof *faddr)) == NULL)
885 			err(1, "malloc()");
886 		sock->socket = xup->xu_socket.xso_so;
887 		sock->pcb = xup->xu_unpp;
888 		sock->proto = proto;
889 		sock->family = AF_UNIX;
890 		sock->protoname = protoname;
891 		if (xup->xu_addr.sun_family == AF_UNIX)
892 			laddr->address =
893 			    *(struct sockaddr_storage *)(void *)&xup->xu_addr;
894 		faddr->conn = xup->unp_conn;
895 		faddr->firstref = xup->xu_firstref;
896 		faddr->nextref = xup->xu_nextref;
897 		laddr->next = NULL;
898 		faddr->next = NULL;
899 		sock->laddr = laddr;
900 		sock->faddr = faddr;
901 		RB_INSERT(socks_t, &socks, sock);
902 		RB_INSERT(pcbs_t, &pcbs, sock);
903 	}
904 out:
905 	free(buf);
906 }
907 
908 static void
getfiles(void)909 getfiles(void)
910 {
911 	struct xfile *xfiles;
912 	size_t len, olen;
913 
914 	olen = len = sizeof(*xfiles);
915 	if ((xfiles = malloc(len)) == NULL)
916 		err(1, "malloc()");
917 	while (cap_sysctlbyname(capsysctl, "kern.file", xfiles, &len, 0, 0)
918 	    == -1) {
919 		if (errno != ENOMEM || len != olen)
920 			err(1, "cap_sysctlbyname()");
921 		olen = len *= 2;
922 		if ((xfiles = realloc(xfiles, len)) == NULL)
923 			err(1, "realloc()");
924 	}
925 	if (len > 0)
926 		enforce_ksize(xfiles->xf_size, struct xfile);
927 	nfiles = len / sizeof(*xfiles);
928 
929 	if ((files = malloc(nfiles * sizeof(struct file))) == NULL)
930 		err(1, "malloc()");
931 
932 	for (int i = 0; i < nfiles; i++) {
933 		files[i].xf_data = xfiles[i].xf_data;
934 		files[i].xf_pid = xfiles[i].xf_pid;
935 		files[i].xf_uid = xfiles[i].xf_uid;
936 		files[i].xf_fd = xfiles[i].xf_fd;
937 		RB_INSERT(files_t, &ftree, &files[i]);
938 	}
939 
940 	free(xfiles);
941 }
942 
943 static int
printaddr(struct sockaddr_storage * ss)944 printaddr(struct sockaddr_storage *ss)
945 {
946 	struct sockaddr_un *sun;
947 	char addrstr[NI_MAXHOST] = { '\0', '\0' };
948 	int error, off, port = 0;
949 
950 	switch (ss->ss_family) {
951 	case AF_INET:
952 		if (sstosin(ss)->sin_addr.s_addr == INADDR_ANY)
953 			addrstr[0] = '*';
954 		port = ntohs(sstosin(ss)->sin_port);
955 		break;
956 	case AF_INET6:
957 		if (IN6_IS_ADDR_UNSPECIFIED(&sstosin6(ss)->sin6_addr))
958 			addrstr[0] = '*';
959 		port = ntohs(sstosin6(ss)->sin6_port);
960 		break;
961 	case AF_UNIX:
962 		sun = sstosun(ss);
963 		off = (int)((char *)&sun->sun_path - (char *)sun);
964 		return (xprintf("%.*s", sun->sun_len - off, sun->sun_path));
965 	}
966 	if (addrstr[0] == '\0') {
967 		error = cap_getnameinfo(capnet, sstosa(ss), ss->ss_len,
968 		    addrstr, sizeof(addrstr), NULL, 0, NI_NUMERICHOST);
969 		if (error)
970 			errx(1, "cap_getnameinfo()");
971 	}
972 	if (port == 0)
973 		return xprintf("%s:*", addrstr);
974 	else
975 		return xprintf("%s:%d", addrstr, port);
976 }
977 
978 static const char *
getprocname(pid_t pid)979 getprocname(pid_t pid)
980 {
981 	static struct kinfo_proc proc;
982 	size_t len;
983 	int mib[4];
984 
985 	mib[0] = CTL_KERN;
986 	mib[1] = KERN_PROC;
987 	mib[2] = KERN_PROC_PID;
988 	mib[3] = (int)pid;
989 	len = sizeof(proc);
990 	if (cap_sysctl(capsysctl, mib, nitems(mib), &proc, &len, NULL, 0)
991 	    == -1) {
992 		/* Do not warn if the process exits before we get its name. */
993 		if (errno != ESRCH)
994 			warn("cap_sysctl()");
995 		return ("??");
996 	}
997 	return (proc.ki_comm);
998 }
999 
1000 static int
getprocjid(pid_t pid)1001 getprocjid(pid_t pid)
1002 {
1003 	static struct kinfo_proc proc;
1004 	size_t len;
1005 	int mib[4];
1006 
1007 	mib[0] = CTL_KERN;
1008 	mib[1] = KERN_PROC;
1009 	mib[2] = KERN_PROC_PID;
1010 	mib[3] = (int)pid;
1011 	len = sizeof(proc);
1012 	if (cap_sysctl(capsysctl, mib, nitems(mib), &proc, &len, NULL, 0)
1013 	    == -1) {
1014 		/* Do not warn if the process exits before we get its jid. */
1015 		if (errno != ESRCH)
1016 			warn("cap_sysctl()");
1017 		return (-1);
1018 	}
1019 	return (proc.ki_jid);
1020 }
1021 
1022 static int
check_ports(struct sock * s)1023 check_ports(struct sock *s)
1024 {
1025 	int port;
1026 	struct addr *addr;
1027 
1028 	if (ports == NULL)
1029 		return (1);
1030 	if ((s->family != AF_INET) && (s->family != AF_INET6))
1031 		return (1);
1032 	for (addr = s->laddr; addr != NULL; addr = addr->next) {
1033 		if (s->family == AF_INET)
1034 			port = ntohs(sstosin(&addr->address)->sin_port);
1035 		else
1036 			port = ntohs(sstosin6(&addr->address)->sin6_port);
1037 		if (CHK_PORT(port))
1038 			return (1);
1039 	}
1040 	for (addr = s->faddr; addr != NULL; addr = addr->next) {
1041 		if (s->family == AF_INET)
1042 			port = ntohs(sstosin(&addr->address)->sin_port);
1043 		else
1044 			port = ntohs(sstosin6(&addr->address)->sin6_port);
1045 		if (CHK_PORT(port))
1046 			return (1);
1047 	}
1048 	return (0);
1049 }
1050 
1051 static const char *
sctp_conn_state(int state)1052 sctp_conn_state(int state)
1053 {
1054 	switch (state) {
1055 	case SCTP_CLOSED:
1056 		return "CLOSED";
1057 		break;
1058 	case SCTP_BOUND:
1059 		return "BOUND";
1060 		break;
1061 	case SCTP_LISTEN:
1062 		return "LISTEN";
1063 		break;
1064 	case SCTP_COOKIE_WAIT:
1065 		return "COOKIE_WAIT";
1066 		break;
1067 	case SCTP_COOKIE_ECHOED:
1068 		return "COOKIE_ECHOED";
1069 		break;
1070 	case SCTP_ESTABLISHED:
1071 		return "ESTABLISHED";
1072 		break;
1073 	case SCTP_SHUTDOWN_SENT:
1074 		return "SHUTDOWN_SENT";
1075 		break;
1076 	case SCTP_SHUTDOWN_RECEIVED:
1077 		return "SHUTDOWN_RECEIVED";
1078 		break;
1079 	case SCTP_SHUTDOWN_ACK_SENT:
1080 		return "SHUTDOWN_ACK_SENT";
1081 		break;
1082 	case SCTP_SHUTDOWN_PENDING:
1083 		return "SHUTDOWN_PENDING";
1084 		break;
1085 	default:
1086 		return "UNKNOWN";
1087 		break;
1088 	}
1089 }
1090 
1091 static const char *
sctp_path_state(int state)1092 sctp_path_state(int state)
1093 {
1094 	switch (state) {
1095 	case SCTP_UNCONFIRMED:
1096 		return "UNCONFIRMED";
1097 		break;
1098 	case SCTP_ACTIVE:
1099 		return "ACTIVE";
1100 		break;
1101 	case SCTP_INACTIVE:
1102 		return "INACTIVE";
1103 		break;
1104 	default:
1105 		return "UNKNOWN";
1106 		break;
1107 	}
1108 }
1109 
1110 static void
displaysock(struct sock * s,int pos)1111 displaysock(struct sock *s, int pos)
1112 {
1113 	int first, offset;
1114 	struct addr *laddr, *faddr;
1115 
1116 	while (pos < 30)
1117 		pos += xprintf(" ");
1118 	pos += xprintf("%s", s->protoname);
1119 	if (s->vflag & INP_IPV4)
1120 		pos += xprintf("4");
1121 	if (s->vflag & INP_IPV6)
1122 		pos += xprintf("6");
1123 	if (s->vflag & (INP_IPV4 | INP_IPV6))
1124 		pos += xprintf(" ");
1125 	laddr = s->laddr;
1126 	faddr = s->faddr;
1127 	first = 1;
1128 	while (laddr != NULL || faddr != NULL) {
1129 		offset = 37;
1130 		while (pos < offset)
1131 			pos += xprintf(" ");
1132 		switch (s->family) {
1133 		case AF_INET:
1134 		case AF_INET6:
1135 			if (laddr != NULL)
1136 				pos += printaddr(&laddr->address);
1137 			offset += opt_w ? 46 : 22;
1138 			do
1139 				pos += xprintf(" ");
1140 			while (pos < offset);
1141 			if (faddr != NULL)
1142 				pos += printaddr(&faddr->address);
1143 			offset += opt_w ? 46 : 22;
1144 			break;
1145 		case AF_UNIX:
1146 			if ((laddr == NULL) || (faddr == NULL))
1147 				errx(1, "laddr = %p or faddr = %p is NULL",
1148 				    (void *)laddr, (void *)faddr);
1149 			if (laddr->address.ss_len == 0 && faddr->conn == 0) {
1150 				pos += xprintf("(not connected)");
1151 				offset += opt_w ? 92 : 44;
1152 				break;
1153 			}
1154 			/* Local bind(2) address, if any. */
1155 			if (laddr->address.ss_len > 0)
1156 				pos += printaddr(&laddr->address);
1157 			/* Remote peer we connect(2) to, if any. */
1158 			if (faddr->conn != 0) {
1159 				struct sock *p;
1160 
1161 				pos += xprintf("%s-> ",
1162 				    laddr->address.ss_len > 0 ? " " : "");
1163 				p = RB_FIND(pcbs_t, &pcbs,
1164 				    &(struct sock){ .pcb = faddr->conn });
1165 				if (__predict_false(p == NULL)) {
1166 					/* XXGL: can this happen at all? */
1167 					pos += xprintf("??");
1168 				}  else if (p->laddr->address.ss_len == 0) {
1169 					struct file *f;
1170 
1171 					f = RB_FIND(files_t, &ftree,
1172 					    &(struct file){ .xf_data =
1173 					    p->socket });
1174 					if (f != NULL) {
1175 						pos += xprintf("[%lu %d]",
1176 						    (u_long)f->xf_pid,
1177 						    f->xf_fd);
1178 					}
1179 				} else
1180 					pos += printaddr(&p->laddr->address);
1181 			}
1182 			/* Remote peer(s) connect(2)ed to us, if any. */
1183 			if (faddr->firstref != 0) {
1184 				struct sock *p;
1185 				struct file *f;
1186 				kvaddr_t ref = faddr->firstref;
1187 				bool fref = true;
1188 
1189 				pos += xprintf(" <- ");
1190 
1191 				while ((p = RB_FIND(pcbs_t, &pcbs,
1192 				    &(struct sock){ .pcb = ref })) != 0) {
1193 					f = RB_FIND(files_t, &ftree,
1194 					    &(struct file){ .xf_data =
1195 					    p->socket });
1196 					if (f != NULL) {
1197 						pos += xprintf("%s[%lu %d]",
1198 						    fref ? "" : ",",
1199 						    (u_long)f->xf_pid,
1200 						    f->xf_fd);
1201 					}
1202 					ref = p->faddr->nextref;
1203 					fref = false;
1204 				}
1205 			}
1206 			offset += opt_w ? 92 : 44;
1207 			break;
1208 		default:
1209 			abort();
1210 		}
1211 		while (pos < offset)
1212 			pos += xprintf(" ");
1213 		if (opt_A) {
1214 			pos += xprintf("0x%16lx", s->pcb);
1215 			offset += 18;
1216 		}
1217 		if (opt_f) {
1218 			pos += xprintf("%d", s->fibnum);
1219 			offset += 7;
1220 		}
1221 		if (opt_I) {
1222 			if (s->splice_socket != 0) {
1223 				struct sock *sp;
1224 
1225 				sp = RB_FIND(socks_t, &socks, &(struct sock)
1226 				    { .socket = s->splice_socket });
1227 				if (sp != NULL) {
1228 					do
1229 						pos += xprintf(" ");
1230 					while (pos < offset);
1231 					pos += printaddr(&sp->laddr->address);
1232 				} else {
1233 					do
1234 						pos += xprintf(" ");
1235 					while (pos < offset);
1236 					pos += xprintf("??");
1237 					offset += opt_w ? 46 : 22;
1238 				}
1239 			}
1240 			offset += opt_w ? 46 : 22;
1241 		}
1242 		if (opt_i) {
1243 			if (s->proto == IPPROTO_TCP ||
1244 			    s->proto == IPPROTO_UDP) {
1245 				do
1246 					pos += xprintf(" ");
1247 				while (pos < offset);
1248 				pos += xprintf("%" PRIu64, s->inp_gencnt);
1249 			}
1250 			offset += 9;
1251 		}
1252 		if (opt_U) {
1253 			if (faddr != NULL &&
1254 			    ((s->proto == IPPROTO_SCTP &&
1255 			      s->state != SCTP_CLOSED &&
1256 			      s->state != SCTP_BOUND &&
1257 			      s->state != SCTP_LISTEN) ||
1258 			     (s->proto == IPPROTO_TCP &&
1259 			      s->state != TCPS_CLOSED &&
1260 			      s->state != TCPS_LISTEN))) {
1261 				do
1262 					pos += xprintf(" ");
1263 				while (pos < offset);
1264 				pos += xprintf("%u",
1265 				    ntohs(faddr->encaps_port));
1266 			}
1267 			offset += 7;
1268 		}
1269 		if (opt_s) {
1270 			if (faddr != NULL &&
1271 			    s->proto == IPPROTO_SCTP &&
1272 			    s->state != SCTP_CLOSED &&
1273 			    s->state != SCTP_BOUND &&
1274 			    s->state != SCTP_LISTEN) {
1275 				do
1276 					pos += xprintf(" ");
1277 				while (pos < offset);
1278 				pos += xprintf("%s",
1279 				    sctp_path_state(faddr->state));
1280 			}
1281 			offset += 13;
1282 		}
1283 		if (first) {
1284 			if (opt_s) {
1285 				if (s->proto == IPPROTO_SCTP ||
1286 				    s->proto == IPPROTO_TCP) {
1287 					do
1288 						pos += xprintf(" ");
1289 					while (pos < offset);
1290 					switch (s->proto) {
1291 					case IPPROTO_SCTP:
1292 						pos += xprintf("%s",
1293 						    sctp_conn_state(s->state));
1294 						break;
1295 					case IPPROTO_TCP:
1296 						if (s->state >= 0 &&
1297 						    s->state < TCP_NSTATES)
1298 							pos += xprintf("%s",
1299 							    tcpstates[s->state]);
1300 						else
1301 							pos += xprintf("?");
1302 						break;
1303 					}
1304 				}
1305 				offset += 13;
1306 			}
1307 			if (opt_S) {
1308 				if (s->proto == IPPROTO_TCP) {
1309 					do
1310 						pos += xprintf(" ");
1311 					while (pos < offset);
1312 					pos += xprintf("%.*s",
1313 					    TCP_FUNCTION_NAME_LEN_MAX,
1314 					    s->stack);
1315 				}
1316 				offset += TCP_FUNCTION_NAME_LEN_MAX + 1;
1317 			}
1318 			if (opt_C) {
1319 				if (s->proto == IPPROTO_TCP) {
1320 					do
1321 						pos += xprintf(" ");
1322 					while (pos < offset);
1323 					xprintf("%.*s", TCP_CA_NAME_MAX, s->cc);
1324 				}
1325 				offset += TCP_CA_NAME_MAX + 1;
1326 			}
1327 		}
1328 		if (laddr != NULL)
1329 			laddr = laddr->next;
1330 		if (faddr != NULL)
1331 			faddr = faddr->next;
1332 		if ((laddr != NULL) || (faddr != NULL)) {
1333 			xprintf("\n");
1334 			pos = 0;
1335 		}
1336 		first = 0;
1337 	}
1338 	xprintf("\n");
1339 }
1340 
1341 static void
display(void)1342 display(void)
1343 {
1344 	struct passwd *pwd;
1345 	struct file *xf;
1346 	struct sock *s;
1347 	int n, pos;
1348 
1349 	if (!opt_q) {
1350 		printf("%-8s %-10s %-5s %-3s %-6s %-*s %-*s",
1351 		    "USER", "COMMAND", "PID", "FD", "PROTO",
1352 		    opt_w ? 45 : 21, "LOCAL ADDRESS",
1353 		    opt_w ? 45 : 21, "FOREIGN ADDRESS");
1354 		if (opt_A)
1355 			printf(" %-18s", "PCB KVA");
1356 		if (opt_f)
1357 			/* RT_MAXFIBS is 65535. */
1358 			printf(" %-6s", "FIB");
1359 		if (opt_I)
1360 			printf(" %-*s", opt_w ? 45 : 21, "SPLICE ADDRESS");
1361 		if (opt_i)
1362 			printf(" %-8s", "ID");
1363 		if (opt_U)
1364 			printf(" %-6s", "ENCAPS");
1365 		if (opt_s) {
1366 			printf(" %-12s", "PATH STATE");
1367 			printf(" %-12s", "CONN STATE");
1368 		}
1369 		if (opt_S)
1370 			printf(" %-*.*s", TCP_FUNCTION_NAME_LEN_MAX,
1371 			    TCP_FUNCTION_NAME_LEN_MAX, "STACK");
1372 		if (opt_C)
1373 			printf(" %-.*s", TCP_CA_NAME_MAX, "CC");
1374 		printf("\n");
1375 	}
1376 	cap_setpassent(cappwd, 1);
1377 	for (xf = files, n = 0; n < nfiles; ++n, ++xf) {
1378 		if (xf->xf_data == 0)
1379 			continue;
1380 		if (opt_j >= 0 && opt_j != getprocjid(xf->xf_pid))
1381 			continue;
1382 		s = RB_FIND(socks_t, &socks,
1383 		    &(struct sock){ .socket = xf->xf_data});
1384 		if (s != NULL && check_ports(s)) {
1385 			s->shown = 1;
1386 			pos = 0;
1387 			if (opt_n ||
1388 			    (pwd = cap_getpwuid(cappwd, xf->xf_uid)) == NULL)
1389 				pos += xprintf("%lu", (u_long)xf->xf_uid);
1390 			else
1391 				pos += xprintf("%s", pwd->pw_name);
1392 			do
1393 				pos += xprintf(" ");
1394 			while (pos < 9);
1395 			pos += xprintf("%.10s", getprocname(xf->xf_pid));
1396 			do
1397 				pos += xprintf(" ");
1398 			while (pos < 20);
1399 			pos += xprintf("%5lu", (u_long)xf->xf_pid);
1400 			do
1401 				pos += xprintf(" ");
1402 			while (pos < 26);
1403 			pos += xprintf("%-3d", xf->xf_fd);
1404 			displaysock(s, pos);
1405 		}
1406 	}
1407 	if (opt_j >= 0)
1408 		return;
1409 	SLIST_FOREACH(s, &nosocks, socket_list) {
1410 		if (!check_ports(s))
1411 			continue;
1412 		pos = xprintf("%-8s %-10s %-5s %-3s",
1413 		    "?", "?", "?", "?");
1414 		displaysock(s, pos);
1415 	}
1416 	RB_FOREACH(s, socks_t, &socks) {
1417 		if (s->shown)
1418 			continue;
1419 		if (!check_ports(s))
1420 			continue;
1421 		pos = xprintf("%-8s %-10s %-5s %-3s",
1422 		    "?", "?", "?", "?");
1423 		displaysock(s, pos);
1424 	}
1425 }
1426 
1427 static int
set_default_protos(void)1428 set_default_protos(void)
1429 {
1430 	struct protoent *prot;
1431 	const char *pname;
1432 	size_t pindex;
1433 
1434 	init_protos(default_numprotos);
1435 
1436 	for (pindex = 0; pindex < default_numprotos; pindex++) {
1437 		pname = default_protos[pindex];
1438 		prot = cap_getprotobyname(capnetdb, pname);
1439 		if (prot == NULL)
1440 			err(1, "cap_getprotobyname: %s", pname);
1441 		protos[pindex] = prot->p_proto;
1442 	}
1443 	numprotos = pindex;
1444 	return (pindex);
1445 }
1446 
1447 /*
1448  * Return the vnet property of the jail, or -1 on error.
1449  */
1450 static int
jail_getvnet(int jid)1451 jail_getvnet(int jid)
1452 {
1453 	struct iovec jiov[6];
1454 	int vnet;
1455 	size_t len = sizeof(vnet);
1456 
1457 	if (sysctlbyname("kern.features.vimage", &vnet, &len, NULL, 0) != 0)
1458 		return (0);
1459 
1460 	vnet = -1;
1461 	jiov[0].iov_base = __DECONST(char *, "jid");
1462 	jiov[0].iov_len = sizeof("jid");
1463 	jiov[1].iov_base = &jid;
1464 	jiov[1].iov_len = sizeof(jid);
1465 	jiov[2].iov_base = __DECONST(char *, "vnet");
1466 	jiov[2].iov_len = sizeof("vnet");
1467 	jiov[3].iov_base = &vnet;
1468 	jiov[3].iov_len = sizeof(vnet);
1469 	jiov[4].iov_base = __DECONST(char *, "errmsg");
1470 	jiov[4].iov_len = sizeof("errmsg");
1471 	jiov[5].iov_base = jail_errmsg;
1472 	jiov[5].iov_len = JAIL_ERRMSGLEN;
1473 	jail_errmsg[0] = '\0';
1474 	if (jail_get(jiov, nitems(jiov), 0) < 0) {
1475 		if (!jail_errmsg[0])
1476 			snprintf(jail_errmsg, JAIL_ERRMSGLEN,
1477 			    "jail_get: %s", strerror(errno));
1478 		return (-1);
1479 	}
1480 	return (vnet);
1481 }
1482 
1483 static void
usage(void)1484 usage(void)
1485 {
1486 	errx(1,
1487     "usage: sockstat [-46ACcfIiLlnqSsUuvw] [-j jid] [-p ports] [-P protocols]");
1488 }
1489 
1490 int
main(int argc,char * argv[])1491 main(int argc, char *argv[])
1492 {
1493 	cap_channel_t *capcas;
1494 	cap_net_limit_t *limit;
1495 	const char *pwdcmds[] = { "setpassent", "getpwuid" };
1496 	const char *pwdfields[] = { "pw_name" };
1497 	int protos_defined = -1;
1498 	int o, i;
1499 
1500 	opt_j = -1;
1501 	while ((o = getopt(argc, argv, "46ACcfIij:Llnp:P:qSsUuvw")) != -1)
1502 		switch (o) {
1503 		case '4':
1504 			opt_4 = true;
1505 			break;
1506 		case '6':
1507 			opt_6 = true;
1508 			break;
1509 		case 'A':
1510 			opt_A = true;
1511 			break;
1512 		case 'C':
1513 			opt_C = true;
1514 			break;
1515 		case 'c':
1516 			opt_c = true;
1517 			break;
1518 		case 'f':
1519 			opt_f = true;
1520 			break;
1521 		case 'I':
1522 			opt_I = true;
1523 			break;
1524 		case 'i':
1525 			opt_i = true;
1526 			break;
1527 		case 'j':
1528 			opt_j = jail_getid(optarg);
1529 			if (opt_j < 0)
1530 				errx(1, "jail_getid: %s", jail_errmsg);
1531 			break;
1532 		case 'L':
1533 			opt_L = true;
1534 			break;
1535 		case 'l':
1536 			opt_l = true;
1537 			break;
1538 		case 'n':
1539 			opt_n = true;
1540 			break;
1541 		case 'p':
1542 			parse_ports(optarg);
1543 			break;
1544 		case 'P':
1545 			protos_defined = parse_protos(optarg);
1546 			break;
1547 		case 'q':
1548 			opt_q = true;
1549 			break;
1550 		case 'S':
1551 			opt_S = true;
1552 			break;
1553 		case 's':
1554 			opt_s = true;
1555 			break;
1556 		case 'U':
1557 			opt_U = true;
1558 			break;
1559 		case 'u':
1560 			opt_u = true;
1561 			break;
1562 		case 'v':
1563 			++opt_v;
1564 			break;
1565 		case 'w':
1566 			opt_w = true;
1567 			break;
1568 		default:
1569 			usage();
1570 		}
1571 
1572 	argc -= optind;
1573 	argv += optind;
1574 
1575 	if (argc > 0)
1576 		usage();
1577 
1578 	if (opt_j > 0) {
1579 		switch (jail_getvnet(opt_j)) {
1580 		case -1:
1581 			errx(2, "jail_getvnet: %s", jail_errmsg);
1582 		case JAIL_SYS_NEW:
1583 			if (jail_attach(opt_j) < 0)
1584 				err(3, "jail_attach()");
1585 			/* Set back to -1 for normal output in vnet jail. */
1586 			opt_j = -1;
1587 			break;
1588 		default:
1589 			break;
1590 		}
1591 	}
1592 
1593 	capcas = cap_init();
1594 	if (capcas == NULL)
1595 		err(1, "Unable to contact Casper");
1596 	if (caph_enter_casper() < 0)
1597 		err(1, "Unable to enter capability mode");
1598 	capnet = cap_service_open(capcas, "system.net");
1599 	if (capnet == NULL)
1600 		err(1, "Unable to open system.net service");
1601 	capnetdb = cap_service_open(capcas, "system.netdb");
1602 	if (capnetdb == NULL)
1603 		err(1, "Unable to open system.netdb service");
1604 	capsysctl = cap_service_open(capcas, "system.sysctl");
1605 	if (capsysctl == NULL)
1606 		err(1, "Unable to open system.sysctl service");
1607 	cappwd = cap_service_open(capcas, "system.pwd");
1608 	if (cappwd == NULL)
1609 		err(1, "Unable to open system.pwd service");
1610 	cap_close(capcas);
1611 	limit = cap_net_limit_init(capnet, CAPNET_ADDR2NAME);
1612 	if (limit == NULL)
1613 		err(1, "Unable to init cap_net limits");
1614 	if (cap_net_limit(limit) < 0)
1615 		err(1, "Unable to apply limits");
1616 	if (cap_pwd_limit_cmds(cappwd, pwdcmds, nitems(pwdcmds)) < 0)
1617 		err(1, "Unable to apply pwd commands limits");
1618 	if (cap_pwd_limit_fields(cappwd, pwdfields, nitems(pwdfields)) < 0)
1619 		err(1, "Unable to apply pwd commands limits");
1620 
1621 	if ((!opt_4 && !opt_6) && protos_defined != -1)
1622 		opt_4 = opt_6 = true;
1623 	if (!opt_4 && !opt_6 && !opt_u)
1624 		opt_4 = opt_6 = opt_u = true;
1625 	if ((opt_4 || opt_6) && protos_defined == -1)
1626 		protos_defined = set_default_protos();
1627 	if (!opt_c && !opt_l)
1628 		opt_c = opt_l = true;
1629 
1630 	if (opt_4 || opt_6) {
1631 		for (i = 0; i < protos_defined; i++)
1632 			if (protos[i] == IPPROTO_SCTP)
1633 				gather_sctp();
1634 			else
1635 				gather_inet(protos[i]);
1636 	}
1637 
1638 	if (opt_u || (protos_defined == -1 && !opt_4 && !opt_6)) {
1639 		gather_unix(SOCK_STREAM);
1640 		gather_unix(SOCK_DGRAM);
1641 		gather_unix(SOCK_SEQPACKET);
1642 	}
1643 	getfiles();
1644 	display();
1645 	exit(0);
1646 }
1647