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