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