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