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