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