xref: /freebsd/usr.bin/sockstat/main.c (revision fe81e3944c085e765c83c4f78941d7529ceb556e)
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 	int error, off, port = 0;
930 	char addrstr[NI_MAXHOST] = "";
931 	bool needs_ipv6_brackets = false;
932 
933 	switch (ss->ss_family) {
934 	case AF_INET:
935 		if (sstosin(ss)->sin_addr.s_addr == INADDR_ANY)
936 			addrstr[0] = '*';
937 		port = ntohs(sstosin(ss)->sin_port);
938 		break;
939 	case AF_INET6:
940 		if (IN6_IS_ADDR_UNSPECIFIED(&sstosin6(ss)->sin6_addr))
941 			addrstr[0] = '*';
942 		else
943 			needs_ipv6_brackets = true;
944 		port = ntohs(sstosin6(ss)->sin6_port);
945 		break;
946 	case AF_UNIX:
947 		sun = sstosun(ss);
948 		off = (int)((char *)&sun->sun_path - (char *)sun);
949 		if (is_xo_style_encoding) {
950 			xo_emit("{:path/%.*s}", sun->sun_len - off,
951 				sun->sun_path);
952 			return (0);
953 		}
954 		return snprintf(buf, bufsize, "%.*s",
955 				sun->sun_len - off, sun->sun_path);
956 	}
957 	if (addrstr[0] == '\0') {
958 		error = cap_getnameinfo(capnet, sstosa(ss), ss->ss_len,
959 		    addrstr, sizeof(addrstr), NULL, 0, NI_NUMERICHOST);
960 		if (error)
961 			xo_errx(1, "cap_getnameinfo()");
962 	}
963 	if (is_xo_style_encoding) {
964 		xo_emit("{:address/%s}", addrstr);
965 		xo_emit("{:port/%d}", port);
966 		return (0);
967 	}
968 	if (needs_ipv6_brackets) {
969 		if (port == 0)
970 			return (snprintf(buf, bufsize, "[%s]:*", addrstr));
971 		return (snprintf(buf, bufsize, "[%s]:%d", addrstr, port));
972 	}
973 	if (port == 0)
974 		return (snprintf(buf, bufsize, "%s:*", addrstr));
975 	return (snprintf(buf, bufsize, "%s:%d", addrstr, port));
976 }
977 
978 static const char *
getprocname(pid_t pid)979 getprocname(pid_t pid)
980 {
981 	static struct kinfo_proc proc;
982 	size_t len;
983 	int mib[4];
984 
985 	mib[0] = CTL_KERN;
986 	mib[1] = KERN_PROC;
987 	mib[2] = KERN_PROC_PID;
988 	mib[3] = (int)pid;
989 	len = sizeof(proc);
990 	if (cap_sysctl(capsysctl, mib, nitems(mib), &proc, &len, NULL, 0)
991 	    == -1) {
992 		/* Do not warn if the process exits before we get its name. */
993 		if (errno != ESRCH)
994 			xo_warn("cap_sysctl()");
995 		return ("??");
996 	}
997 	return (proc.ki_comm);
998 }
999 
1000 static int
getprocjid(pid_t pid)1001 getprocjid(pid_t pid)
1002 {
1003 	static struct kinfo_proc proc;
1004 	size_t len;
1005 	int mib[4];
1006 
1007 	mib[0] = CTL_KERN;
1008 	mib[1] = KERN_PROC;
1009 	mib[2] = KERN_PROC_PID;
1010 	mib[3] = (int)pid;
1011 	len = sizeof(proc);
1012 	if (cap_sysctl(capsysctl, mib, nitems(mib), &proc, &len, NULL, 0)
1013 	    == -1) {
1014 		/* Do not warn if the process exits before we get its jid. */
1015 		if (errno != ESRCH)
1016 			xo_warn("cap_sysctl()");
1017 		return (-1);
1018 	}
1019 	return (proc.ki_jid);
1020 }
1021 
1022 static int
check_ports(struct sock * s)1023 check_ports(struct sock *s)
1024 {
1025 	int port;
1026 	struct addr *addr;
1027 
1028 	if (ports == NULL)
1029 		return (1);
1030 	if ((s->family != AF_INET) && (s->family != AF_INET6))
1031 		return (1);
1032 	for (addr = s->laddr; 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 	for (addr = s->faddr; addr != NULL; addr = addr->next) {
1041 		if (s->family == AF_INET)
1042 			port = ntohs(sstosin(&addr->address)->sin_port);
1043 		else
1044 			port = ntohs(sstosin6(&addr->address)->sin6_port);
1045 		if (CHK_PORT(port))
1046 			return (1);
1047 	}
1048 	return (0);
1049 }
1050 
1051 static const char *
sctp_conn_state(int state)1052 sctp_conn_state(int state)
1053 {
1054 	switch (state) {
1055 	case SCTP_CLOSED:
1056 		return "CLOSED";
1057 		break;
1058 	case SCTP_BOUND:
1059 		return "BOUND";
1060 		break;
1061 	case SCTP_LISTEN:
1062 		return "LISTEN";
1063 		break;
1064 	case SCTP_COOKIE_WAIT:
1065 		return "COOKIE_WAIT";
1066 		break;
1067 	case SCTP_COOKIE_ECHOED:
1068 		return "COOKIE_ECHOED";
1069 		break;
1070 	case SCTP_ESTABLISHED:
1071 		return "ESTABLISHED";
1072 		break;
1073 	case SCTP_SHUTDOWN_SENT:
1074 		return "SHUTDOWN_SENT";
1075 		break;
1076 	case SCTP_SHUTDOWN_RECEIVED:
1077 		return "SHUTDOWN_RECEIVED";
1078 		break;
1079 	case SCTP_SHUTDOWN_ACK_SENT:
1080 		return "SHUTDOWN_ACK_SENT";
1081 		break;
1082 	case SCTP_SHUTDOWN_PENDING:
1083 		return "SHUTDOWN_PENDING";
1084 		break;
1085 	default:
1086 		return "UNKNOWN";
1087 		break;
1088 	}
1089 }
1090 
1091 static const char *
sctp_path_state(int state)1092 sctp_path_state(int state)
1093 {
1094 	switch (state) {
1095 	case SCTP_UNCONFIRMED:
1096 		return "UNCONFIRMED";
1097 		break;
1098 	case SCTP_ACTIVE:
1099 		return "ACTIVE";
1100 		break;
1101 	case SCTP_INACTIVE:
1102 		return "INACTIVE";
1103 		break;
1104 	default:
1105 		return "UNKNOWN";
1106 		break;
1107 	}
1108 }
1109 
1110 static const char *
bblog_state(int state)1111 bblog_state(int state)
1112 {
1113 	switch (state) {
1114 	case TCP_LOG_STATE_OFF:
1115 		return "OFF";
1116 		break;
1117 	case TCP_LOG_STATE_TAIL:
1118 		return "TAIL";
1119 		break;
1120 	case TCP_LOG_STATE_HEAD:
1121 		return "HEAD";
1122 		break;
1123 	case TCP_LOG_STATE_HEAD_AUTO:
1124 		return "HEAD_AUTO";
1125 		break;
1126 	case TCP_LOG_STATE_CONTINUAL:
1127 		return "CONTINUAL";
1128 		break;
1129 	case TCP_LOG_STATE_TAIL_AUTO:
1130 		return "TAIL_AUTO";
1131 		break;
1132 	case TCP_LOG_VIA_BBPOINTS:
1133 		return "BBPOINTS";
1134 		break;
1135 	default:
1136 		return "UNKNOWN";
1137 		break;
1138 	}
1139 }
1140 
1141 static int
format_unix_faddr(struct addr * faddr,char * buf,size_t bufsize)1142 format_unix_faddr(struct addr *faddr, char *buf, size_t bufsize) {
1143 	#define SAFEBUF  (buf == NULL ? NULL : buf + pos)
1144 	#define SAFESIZE (buf == NULL ? 0 : bufsize - pos)
1145 
1146 	size_t pos = 0;
1147 	if (faddr->conn != 0) {
1148 		/* Remote peer we connect(2) to, if any. */
1149 		struct sock *p;
1150 		if (!is_xo_style_encoding)
1151 			pos += strlcpy(SAFEBUF, "-> ", SAFESIZE);
1152 		p = RB_FIND(pcbs_t, &pcbs,
1153 			&(struct sock){ .pcb = faddr->conn });
1154 		if (__predict_false(p == NULL) && !is_xo_style_encoding) {
1155 			/* XXGL: can this happen at all? */
1156 			pos += snprintf(SAFEBUF, SAFESIZE, "??");
1157 		} else if (p->laddr->address.ss_len == 0) {
1158 			struct file *f;
1159 			f = RB_FIND(files_t, &ftree,
1160 				&(struct file){ .xf_data =
1161 				p->socket });
1162 			if (f != NULL) {
1163 				if (!is_xo_style_encoding) {
1164 					pos += snprintf(SAFEBUF, SAFESIZE,
1165 						"[%lu %d]", (u_long)f->xf_pid,
1166 						f->xf_fd);
1167 				} else {
1168 					xo_open_list("connections");
1169 					xo_open_instance("connections");
1170 					xo_emit("{:pid/%lu}", (u_long)f->xf_pid);
1171 					xo_emit("{:fd/%d}", f->xf_fd);
1172 					xo_close_instance("connections");
1173 					xo_close_list("connections");
1174 				}
1175 			}
1176 		} else
1177 			pos += formataddr(&p->laddr->address,
1178 				SAFEBUF, SAFESIZE);
1179 	} else if (faddr->firstref != 0) {
1180 		/* Remote peer(s) connect(2)ed to us, if any. */
1181 		struct sock *p;
1182 		struct file *f;
1183 		kvaddr_t ref = faddr->firstref;
1184 		bool fref = true;
1185 
1186 		if (!is_xo_style_encoding)
1187 			pos += snprintf(SAFEBUF, SAFESIZE, " <- ");
1188 		xo_open_list("connections");
1189 		while ((p = RB_FIND(pcbs_t, &pcbs,
1190 			&(struct sock){ .pcb = ref })) != 0) {
1191 			f = RB_FIND(files_t, &ftree,
1192 				&(struct file){ .xf_data = p->socket });
1193 			if (f != NULL) {
1194 				if (!is_xo_style_encoding) {
1195 					pos += snprintf(SAFEBUF, SAFESIZE,
1196 						"%s[%lu %d]", fref ? "" : ",",
1197 						(u_long)f->xf_pid, f->xf_fd);
1198 				} else {
1199 					xo_open_instance("connections");
1200 					xo_emit("{:pid/%lu}", (u_long)f->xf_pid);
1201 					xo_emit("{:fd/%d}", f->xf_fd);
1202 					xo_close_instance("connections");
1203 				}
1204 			}
1205 			ref = p->faddr->nextref;
1206 			fref = false;
1207 		}
1208 		xo_close_list("connections");
1209 	}
1210 	return pos;
1211 }
1212 
1213 struct col_widths {
1214 	int user;
1215 	int command;
1216 	int pid;
1217 	int fd;
1218 	int proto;
1219 	int local_addr;
1220 	int foreign_addr;
1221 	int pcb_kva;
1222 	int fib;
1223 	int splice_address;
1224 	int inp_gencnt;
1225 	int encaps;
1226 	int path_state;
1227 	int conn_state;
1228 	int bblog_state;
1229 	int stack;
1230 	int cc;
1231 };
1232 
1233 static void
calculate_sock_column_widths(struct col_widths * cw,struct sock * s)1234 calculate_sock_column_widths(struct col_widths *cw, struct sock *s)
1235 {
1236 	struct addr *laddr, *faddr;
1237 	bool first = true;
1238 	int len = 0;
1239 	laddr = s->laddr;
1240 	faddr = s->faddr;
1241 	first = true;
1242 
1243 	len = strlen(s->protoname);
1244 	if (s->vflag & INP_IPV4)
1245 		len += 1;
1246 	if (s->vflag & INP_IPV6)
1247 		len += 1;
1248 	cw->proto = MAX(cw->proto, len);
1249 
1250 	while (laddr != NULL || faddr != NULL) {
1251 		if (opt_w && s->family == AF_UNIX) {
1252 			if ((laddr == NULL) || (faddr == NULL))
1253 				xo_errx(1, "laddr = %p or faddr = %p is NULL",
1254 					(void *)laddr, (void *)faddr);
1255 			if (laddr->address.ss_len > 0)
1256 				len = formataddr(&laddr->address, NULL, 0);
1257 			cw->local_addr = MAX(cw->local_addr, len);
1258 			len = format_unix_faddr(faddr, NULL, 0);
1259 			cw->foreign_addr = MAX(cw->foreign_addr, len);
1260 		} else if (opt_w) {
1261 			if (laddr != NULL) {
1262 				len = formataddr(&laddr->address, NULL, 0);
1263 				cw->local_addr = MAX(cw->local_addr, len);
1264 			}
1265 			if (faddr != NULL) {
1266 				len = formataddr(&faddr->address, NULL, 0);
1267 				cw->foreign_addr = MAX(cw->foreign_addr, len);
1268 			}
1269 		}
1270 		if (opt_f) {
1271 			len = snprintf(NULL, 0, "%d", s->fibnum);
1272 			cw->fib = MAX(cw->fib, len);
1273 		}
1274 		if (opt_I) {
1275 			if (s->splice_socket != 0) {
1276 				struct sock *sp;
1277 
1278 				sp = RB_FIND(socks_t, &socks, &(struct sock)
1279 					{ .socket = s->splice_socket });
1280 				if (sp != NULL) {
1281 					len = formataddr(&sp->laddr->address,
1282 					    NULL, 0);
1283 					cw->splice_address = MAX(
1284 					    cw->splice_address, len);
1285 				}
1286 			}
1287 		}
1288 		if (opt_i) {
1289 			if (s->proto == IPPROTO_TCP ||
1290 			    s->proto == IPPROTO_UDP) {
1291 				len = snprintf(NULL, 0,
1292 				    "%" PRIu64, s->inp_gencnt);
1293 				cw->inp_gencnt = MAX(cw->inp_gencnt, len);
1294 			}
1295 		}
1296 		if (opt_U) {
1297 			if (faddr != NULL &&
1298 			    ((s->proto == IPPROTO_SCTP &&
1299 			      s->state != SCTP_CLOSED &&
1300 			      s->state != SCTP_BOUND &&
1301 			      s->state != SCTP_LISTEN) ||
1302 			    (s->proto == IPPROTO_TCP &&
1303 			     s->state != TCPS_CLOSED &&
1304 			     s->state != TCPS_LISTEN))) {
1305 				len = snprintf(NULL, 0, "%u",
1306 				    ntohs(faddr->encaps_port));
1307 				cw->encaps = MAX(cw->encaps, len);
1308 			}
1309 		}
1310 		if (opt_s) {
1311 			if (faddr != NULL &&
1312 			    s->proto == IPPROTO_SCTP &&
1313 			    s->state != SCTP_CLOSED &&
1314 			    s->state != SCTP_BOUND &&
1315 			    s->state != SCTP_LISTEN) {
1316 				len = strlen(sctp_path_state(faddr->state));
1317 				cw->path_state = MAX(cw->path_state, len);
1318 			}
1319 		}
1320 		if (first) {
1321 			if (opt_s) {
1322 				if (s->proto == IPPROTO_SCTP ||
1323 				    s->proto == IPPROTO_TCP) {
1324 					switch (s->proto) {
1325 					case IPPROTO_SCTP:
1326 						len = strlen(
1327 						    sctp_conn_state(s->state));
1328 						cw->conn_state = MAX(
1329 						    cw->conn_state, len);
1330 						break;
1331 					case IPPROTO_TCP:
1332 						if (s->state >= 0 &&
1333 						    s->state < TCP_NSTATES) {
1334 							len = strlen(
1335 							    tcpstates[s->state]);
1336 							cw->conn_state = MAX(
1337 							    cw->conn_state,
1338 							    len);
1339 						}
1340 						break;
1341 					}
1342 				}
1343 			}
1344 			if (opt_S && s->proto == IPPROTO_TCP) {
1345 				len = strlen(s->stack);
1346 				cw->stack = MAX(cw->stack, len);
1347 			}
1348 			if (opt_C && s->proto == IPPROTO_TCP) {
1349 				len = strlen(s->cc);
1350 				cw->cc = MAX(cw->cc, len);
1351 			}
1352 		}
1353 		if (laddr != NULL)
1354 			laddr = laddr->next;
1355 		if (faddr != NULL)
1356 			faddr = faddr->next;
1357 		first = false;
1358 	}
1359 }
1360 
1361 static void
calculate_column_widths(struct col_widths * cw)1362 calculate_column_widths(struct col_widths *cw)
1363 {
1364 	int n, len;
1365 	struct file *xf;
1366 	struct sock *s;
1367 	struct passwd *pwd;
1368 
1369 	cap_setpassent(cappwd, 1);
1370 	for (xf = files, n = 0; n < nfiles; ++n, ++xf) {
1371 		if (xf->xf_data == 0)
1372 			continue;
1373 		if (opt_j >= 0 && opt_j != getprocjid(xf->xf_pid))
1374 			continue;
1375 		s = RB_FIND(socks_t, &socks,
1376 			&(struct sock){ .socket = xf->xf_data});
1377 		if (s == NULL || (!check_ports(s)))
1378 			continue;
1379 		s->shown = 1;
1380 		if (opt_n ||
1381 			(pwd = cap_getpwuid(cappwd, xf->xf_uid)) == NULL)
1382 			len = snprintf(NULL, 0, "%lu", (u_long)xf->xf_uid);
1383 		else
1384 			len = snprintf(NULL, 0, "%s", pwd->pw_name);
1385 		cw->user = MAX(cw->user, len);
1386 		len = snprintf(NULL, 0, "%lu", (u_long)xf->xf_pid);
1387 		cw->pid = MAX(cw->pid, len);
1388 		len = snprintf(NULL, 0, "%d", xf->xf_fd);
1389 		cw->fd = MAX(cw->fd, len);
1390 
1391 		calculate_sock_column_widths(cw, s);
1392 	}
1393 	if (opt_j >= 0)
1394 		return;
1395 	SLIST_FOREACH(s, &nosocks, socket_list) {
1396 		if (!check_ports(s))
1397 			continue;
1398 		calculate_sock_column_widths(cw, s);
1399 	}
1400 	RB_FOREACH(s, socks_t, &socks) {
1401 		if (s->shown)
1402 			continue;
1403 		if (!check_ports(s))
1404 			continue;
1405 		calculate_sock_column_widths(cw, s);
1406 	}
1407 }
1408 
1409 static void
display_sock(struct sock * s,struct col_widths * cw,char * buf,size_t bufsize)1410 display_sock(struct sock *s, struct col_widths *cw, char *buf, size_t bufsize)
1411 {
1412 	struct addr *laddr, *faddr;
1413 	bool first;
1414 	laddr = s->laddr;
1415 	faddr = s->faddr;
1416 	first = true;
1417 
1418 	snprintf(buf, bufsize, "%s%s%s",
1419 		s->protoname,
1420 		s->vflag & INP_IPV4 ? "4" : "",
1421 		s->vflag & INP_IPV6 ? "6" : "");
1422 	xo_emit(" {:proto/%-*s}", cw->proto, buf);
1423 	while (laddr != NULL || faddr != NULL) {
1424 		if (s->family == AF_UNIX) {
1425 			if ((laddr == NULL) || (faddr == NULL))
1426 				xo_errx(1, "laddr = %p or faddr = %p is NULL",
1427 					(void *)laddr, (void *)faddr);
1428 			if (laddr->address.ss_len > 0) {
1429 				xo_open_container("local");
1430 				formataddr(&laddr->address, buf, bufsize);
1431 				if (!is_xo_style_encoding) {
1432 					xo_emit(" {:local-address/%-*.*s}",
1433 						cw->local_addr, cw->local_addr,
1434 						buf);
1435 				}
1436 				xo_close_container("local");
1437 			} else if (laddr->address.ss_len == 0 &&
1438 				faddr->conn == 0 && !is_xo_style_encoding) {
1439 				xo_emit(" {:local-address/%-*.*s}",
1440 					cw->local_addr,	cw->local_addr,
1441 					"(not connected)");
1442 			} else if (!is_xo_style_encoding) {
1443 				xo_emit(" {:local-address/%-*.*s}",
1444 					cw->local_addr, cw->local_addr, "??");
1445 			}
1446 			if (faddr->conn != 0 || faddr->firstref != 0) {
1447 				xo_open_container("foreign");
1448 				int len = format_unix_faddr(faddr, buf,
1449 						bufsize);
1450 				if (len == 0 && !is_xo_style_encoding)
1451 					xo_emit(" {:foreign-address/%-*s}",
1452 						cw->foreign_addr, "??");
1453 				else if (!is_xo_style_encoding)
1454 					xo_emit(" {:foreign-address/%-*.*s}",
1455 						cw->foreign_addr,
1456 						cw->foreign_addr, buf);
1457 				xo_close_container("foreign");
1458 			} else if (!is_xo_style_encoding)
1459 				xo_emit(" {:foreign-address/%-*s}",
1460 					cw->foreign_addr, "??");
1461 		} else {
1462 			if (laddr != NULL) {
1463 				xo_open_container("local");
1464 				formataddr(&laddr->address, buf, bufsize);
1465 				if (!is_xo_style_encoding) {
1466 					xo_emit(" {:local-address/%-*.*s}",
1467 						cw->local_addr, cw->local_addr,
1468 						buf);
1469 				}
1470 				xo_close_container("local");
1471 			} else if (!is_xo_style_encoding)
1472 				xo_emit(" {:local-address/%-*.*s}",
1473 					cw->local_addr, cw->local_addr, "??");
1474 			if (faddr != NULL) {
1475 				xo_open_container("foreign");
1476 				formataddr(&faddr->address, buf, bufsize);
1477 				if (!is_xo_style_encoding) {
1478 					xo_emit(" {:foreign-address/%-*.*s}",
1479 						cw->foreign_addr,
1480 						cw->foreign_addr, buf);
1481 				}
1482 				xo_close_container("foreign");
1483 			} else if (!is_xo_style_encoding) {
1484 				xo_emit(" {:foreign-address/%-*.*s}",
1485 					cw->foreign_addr, cw->foreign_addr,
1486 					"??");
1487 			}
1488 		}
1489 		if (opt_A) {
1490 			snprintf(buf, bufsize, "%#*" PRIx64,
1491 				cw->pcb_kva, s->pcb);
1492 			xo_emit(" {:pcb-kva/%s}", buf);
1493 		}
1494 		if (opt_f)
1495 			xo_emit(" {:fib/%*d}", cw->fib, s->fibnum);
1496 		if (opt_I) {
1497 			if (s->splice_socket != 0) {
1498 				struct sock *sp;
1499 				sp = RB_FIND(socks_t, &socks, &(struct sock)
1500 					{ .socket = s->splice_socket });
1501 				if (sp != NULL) {
1502 					xo_open_container("splice");
1503 					formataddr(&sp->laddr->address,
1504 								buf, bufsize);
1505 					xo_close_container("splice");
1506 				} else if (!is_xo_style_encoding)
1507 					strlcpy(buf, "??", bufsize);
1508 			} else if (!is_xo_style_encoding)
1509 				strlcpy(buf, "??", bufsize);
1510 			if (!is_xo_style_encoding)
1511 				xo_emit(" {:splice-address/%-*s}",
1512 					cw->splice_address, buf);
1513 		}
1514 		if (opt_i) {
1515 			if (s->proto == IPPROTO_TCP ||
1516 			    s->proto == IPPROTO_UDP) {
1517 				snprintf(buf, bufsize, "%" PRIu64,
1518 					s->inp_gencnt);
1519 				xo_emit(" {:id/%*s}", cw->inp_gencnt, buf);
1520 			} else if (!is_xo_style_encoding)
1521 				xo_emit(" {:id/%*s}", cw->inp_gencnt, "??");
1522 		}
1523 		if (opt_U) {
1524 			if (faddr != NULL &&
1525 			    ((s->proto == IPPROTO_SCTP &&
1526 			      s->state != SCTP_CLOSED &&
1527 			      s->state != SCTP_BOUND &&
1528 			      s->state != SCTP_LISTEN) ||
1529 			     (s->proto == IPPROTO_TCP &&
1530 			      s->state != TCPS_CLOSED &&
1531 			      s->state != TCPS_LISTEN))) {
1532 				xo_emit(" {:encaps/%*u}", cw->encaps,
1533 				    ntohs(faddr->encaps_port));
1534 			} else if (!is_xo_style_encoding)
1535 				xo_emit(" {:encaps/%*s}", cw->encaps, "??");
1536 		}
1537 		if (opt_s && show_path_state) {
1538 			if (faddr != NULL &&
1539 			    s->proto == IPPROTO_SCTP &&
1540 			    s->state != SCTP_CLOSED &&
1541 			    s->state != SCTP_BOUND &&
1542 			    s->state != SCTP_LISTEN) {
1543 				xo_emit(" {:path-state/%-*s}", cw->path_state,
1544 				    sctp_path_state(faddr->state));
1545 			} else if (!is_xo_style_encoding)
1546 				xo_emit(" {:path-state/%-*s}", cw->path_state,
1547 				    "??");
1548 		}
1549 		if (first) {
1550 			if (opt_s) {
1551 				if (s->proto == IPPROTO_SCTP ||
1552 				    s->proto == IPPROTO_TCP) {
1553 					switch (s->proto) {
1554 					case IPPROTO_SCTP:
1555 						xo_emit(" {:conn-state/%-*s}",
1556 						    cw->conn_state,
1557 						    sctp_conn_state(s->state));
1558 						break;
1559 					case IPPROTO_TCP:
1560 						if (s->state >= 0 &&
1561 						    s->state < TCP_NSTATES)
1562 							xo_emit(" {:conn-state/%-*s}",
1563 							    cw->conn_state,
1564 							    tcpstates[s->state]);
1565 						else if (!is_xo_style_encoding)
1566 							xo_emit(" {:conn-state/%-*s}",
1567 							    cw->conn_state, "??");
1568 						break;
1569 					}
1570 				} else if (!is_xo_style_encoding)
1571 					xo_emit(" {:conn-state/%-*s}",
1572 					    cw->conn_state, "??");
1573 			}
1574 			if (opt_b) {
1575 				if (s->proto == IPPROTO_TCP)
1576 					xo_emit(" {:bblog-state/%-*s}",
1577 					    cw->bblog_state,
1578 					    bblog_state(s->bblog_state));
1579 				else if (!is_xo_style_encoding)
1580 					xo_emit(" {:bblog-state/%-*s}",
1581 					    cw->bblog_state, "??");
1582 			}
1583 			if (opt_S) {
1584 				if (s->proto == IPPROTO_TCP)
1585 					xo_emit(" {:stack/%-*s}",
1586 					    cw->stack, s->stack);
1587 				else if (!is_xo_style_encoding)
1588 					xo_emit(" {:stack/%-*s}",
1589 					    cw->stack, "??");
1590 			}
1591 			if (opt_C) {
1592 				if (s->proto == IPPROTO_TCP)
1593 					xo_emit(" {:cc/%-*s}", cw->cc, s->cc);
1594 				else if (!is_xo_style_encoding)
1595 					xo_emit(" {:cc/%-*s}", cw->cc, "??");
1596 			}
1597 		} else if (!is_xo_style_encoding) {
1598 			if (opt_s)
1599 				xo_emit(" {:conn-state/%-*s}", cw->conn_state,
1600 				    "??");
1601 			if (opt_b)
1602 				xo_emit(" {:bblog-state/%-*s}", cw->bblog_state,
1603 				    "??");
1604 			if (opt_S)
1605 				xo_emit(" {:stack/%-*s}", cw->stack, "??");
1606 			if (opt_C)
1607 				xo_emit(" {:cc/%-*s}", cw->cc, "??");
1608 		}
1609 		if (laddr != NULL)
1610 			laddr = laddr->next;
1611 		if (faddr != NULL)
1612 			faddr = faddr->next;
1613 		xo_emit("\n");
1614 		if (!is_xo_style_encoding && (laddr != NULL || faddr != NULL))
1615 			xo_emit("{:user/%-*s} {:command/%-*s} {:pid/%*s}"
1616 			    " {:fd/%*s} {:proto/%-*s}", cw->user, "??",
1617 			    cw->command, "??", cw->pid, "??", cw->fd, "??",
1618 			    cw->proto, "??");
1619 		first = false;
1620 	}
1621 }
1622 
1623 static void
display(void)1624 display(void)
1625 {
1626 	static const char *__HDR_USER="USER",
1627 			  *__HDR_COMMAND="COMMAND",
1628 			  *__HDR_PID="PID",
1629 			  *__HDR_FD="FD",
1630 			  *__HDR_PROTO="PROTO",
1631 			  *__HDR_LOCAL_ADDRESS="LOCAL ADDRESS",
1632 			  *__HDR_FOREIGN_ADDRESS="FOREIGN ADDRESS",
1633 			  *__HDR_PCB_KVA="PCB KVA",
1634 			  *__HDR_FIB="FIB",
1635 			  *__HDR_SPLICE_ADDRESS="SPLICE ADDRESS",
1636 			  *__HDR_ID="ID",
1637 			  *__HDR_ENCAPS="ENCAPS",
1638 			  *__HDR_PATH_STATE="PATH STATE",
1639 			  *__HDR_CONN_STATE="CONN STATE",
1640 			  *__HDR_BBLOG_STATE="BBLOG STATE",
1641 			  *__HDR_STACK="STACK",
1642 			  *__HDR_CC="CC";
1643 
1644 	struct passwd *pwd;
1645 	struct file *xf;
1646 	struct sock *s;
1647 	int n;
1648 	struct col_widths cw;
1649 	const size_t bufsize = 512;
1650 	void *buf;
1651 	if ((buf = (char *)malloc(bufsize)) == NULL) {
1652 		xo_err(1, "malloc()");
1653 		return;
1654 	}
1655 
1656 	if (!is_xo_style_encoding) {
1657 		cw = (struct col_widths) {
1658 			.user = strlen(__HDR_USER),
1659 			.command = 10,
1660 			.pid = strlen(__HDR_PID),
1661 			.fd = strlen(__HDR_FD),
1662 			.proto = strlen(__HDR_PROTO),
1663 			.local_addr = opt_w ? strlen(__HDR_LOCAL_ADDRESS) : 21,
1664 			.foreign_addr = opt_w ? strlen(__HDR_FOREIGN_ADDRESS) : 21,
1665 			.pcb_kva = 18,
1666 			.fib = strlen(__HDR_FIB),
1667 			.splice_address = strlen(__HDR_SPLICE_ADDRESS),
1668 			.inp_gencnt = strlen(__HDR_ID),
1669 			.encaps = strlen(__HDR_ENCAPS),
1670 			.path_state = strlen(__HDR_PATH_STATE),
1671 			.conn_state = strlen(__HDR_CONN_STATE),
1672 			.bblog_state = strlen(__HDR_BBLOG_STATE),
1673 			.stack = strlen(__HDR_STACK),
1674 			.cc = strlen(__HDR_CC),
1675 		};
1676 		calculate_column_widths(&cw);
1677 	} else
1678 		memset(&cw, 0, sizeof(cw));
1679 
1680 	xo_set_version(SOCKSTAT_XO_VERSION);
1681 	xo_open_container("sockstat");
1682 	xo_open_list("socket");
1683 	if (!opt_q) {
1684 		xo_emit("{T:/%-*s} {T:/%-*s} {T:/%*s} {T:/%*s} {T:/%-*s} "
1685 			"{T:/%-*s} {T:/%-*s}", cw.user, __HDR_USER, cw.command,
1686 			__HDR_COMMAND, cw.pid, __HDR_PID, cw.fd, __HDR_FD, cw.proto,
1687 			__HDR_PROTO, cw.local_addr, __HDR_LOCAL_ADDRESS,
1688 			cw.foreign_addr, __HDR_FOREIGN_ADDRESS);
1689 		if (opt_A)
1690 			xo_emit(" {T:/%-*s}", cw.pcb_kva, __HDR_PCB_KVA);
1691 		if (opt_f)
1692 			/* RT_MAXFIBS is 65535. */
1693 			xo_emit(" {T:/%*s}", cw.fib, __HDR_FIB);
1694 		if (opt_I)
1695 			xo_emit(" {T:/%-*s}", cw.splice_address,
1696 			    __HDR_SPLICE_ADDRESS);
1697 		if (opt_i)
1698 			xo_emit(" {T:/%*s}", cw.inp_gencnt, __HDR_ID);
1699 		if (opt_U)
1700 			xo_emit(" {T:/%*s}", cw.encaps, __HDR_ENCAPS);
1701 		if (opt_s) {
1702 			if (show_path_state)
1703 				xo_emit(" {T:/%-*s}", cw.path_state,
1704 				    __HDR_PATH_STATE);
1705 			xo_emit(" {T:/%-*s}", cw.conn_state, __HDR_CONN_STATE);
1706 		}
1707 		if (opt_b)
1708 			xo_emit(" {T:/%-*s}", cw.bblog_state, __HDR_BBLOG_STATE);
1709 		if (opt_S)
1710 			xo_emit(" {T:/%-*s}", cw.stack, __HDR_STACK);
1711 		if (opt_C)
1712 			xo_emit(" {T:/%-*s}", cw.cc, __HDR_CC);
1713 		xo_emit("\n");
1714 	}
1715 	cap_setpassent(cappwd, 1);
1716 	for (xf = files, n = 0; n < nfiles; ++n, ++xf) {
1717 		if (xf->xf_data == 0)
1718 			continue;
1719 		if (opt_j >= 0 && opt_j != getprocjid(xf->xf_pid))
1720 			continue;
1721 		s = RB_FIND(socks_t, &socks,
1722 			&(struct sock){ .socket = xf->xf_data});
1723 		if (s != NULL && check_ports(s)) {
1724 			xo_open_instance("socket");
1725 			s->shown = 1;
1726 			if (opt_n ||
1727 			    (pwd = cap_getpwuid(cappwd, xf->xf_uid)) == NULL)
1728 				xo_emit("{:user/%-*lu}", cw.user,
1729 				    (u_long)xf->xf_uid);
1730 			else
1731 				xo_emit("{:user/%-*s}", cw.user, pwd->pw_name);
1732 			if (!is_xo_style_encoding)
1733 				xo_emit(" {:command/%-*.10s}", cw.command,
1734 				    getprocname(xf->xf_pid));
1735 			else
1736 				xo_emit(" {:command/%-*s}", cw.command,
1737 				    getprocname(xf->xf_pid));
1738 			xo_emit(" {:pid/%*lu}", cw.pid, (u_long)xf->xf_pid);
1739 			xo_emit(" {:fd/%*d}", cw.fd, xf->xf_fd);
1740 			display_sock(s, &cw, buf, bufsize);
1741 			xo_close_instance("socket");
1742 		}
1743 	}
1744 	if (!need_nosocks())
1745 		goto out;
1746 	SLIST_FOREACH(s, &nosocks, socket_list) {
1747 		if (!check_ports(s))
1748 			continue;
1749 		xo_open_instance("socket");
1750 		if (!is_xo_style_encoding)
1751 			xo_emit("{:user/%-*s} {:command/%-*s} {:pid/%*s}"
1752 			    " {:fd/%*s}", cw.user, "??", cw.command, "??",
1753 			    cw.pid, "??", cw.fd, "??");
1754 		display_sock(s, &cw, buf, bufsize);
1755 		xo_close_instance("socket");
1756 	}
1757 	RB_FOREACH(s, socks_t, &socks) {
1758 		if (s->shown)
1759 			continue;
1760 		if (!check_ports(s))
1761 			continue;
1762 		xo_open_instance("socket");
1763 		if (!is_xo_style_encoding)
1764 			xo_emit("{:user/%-*s} {:command/%-*s} {:pid/%*s}"
1765 			    " {:fd/%*s}", cw.user, "??", cw.command, "??",
1766 			    cw.pid, "??", cw.fd, "??");
1767 		display_sock(s, &cw, buf, bufsize);
1768 		xo_close_instance("socket");
1769 	}
1770 out:
1771 	xo_close_list("socket");
1772 	xo_close_container("sockstat");
1773 	if (xo_finish() < 0)
1774 		xo_err(1, "stdout");
1775 	free(buf);
1776 	cap_endpwent(cappwd);
1777 }
1778 
1779 static int
set_default_protos(void)1780 set_default_protos(void)
1781 {
1782 	struct protoent *prot;
1783 	const char *pname;
1784 	size_t pindex;
1785 
1786 	init_protos(default_numprotos);
1787 
1788 	for (pindex = 0; pindex < default_numprotos; pindex++) {
1789 		pname = default_protos[pindex];
1790 		prot = cap_getprotobyname(capnetdb, pname);
1791 		if (prot == NULL)
1792 			xo_err(1, "cap_getprotobyname: %s", pname);
1793 		protos[pindex] = prot->p_proto;
1794 	}
1795 	numprotos = pindex;
1796 	return (pindex);
1797 }
1798 
1799 /*
1800  * Return the vnet property of the jail, or -1 on error.
1801  */
1802 static int
jail_getvnet(int jid)1803 jail_getvnet(int jid)
1804 {
1805 	struct iovec jiov[6];
1806 	int vnet;
1807 	size_t len = sizeof(vnet);
1808 
1809 	if (sysctlbyname("kern.features.vimage", &vnet, &len, NULL, 0) != 0)
1810 		return (0);
1811 
1812 	vnet = -1;
1813 	jiov[0].iov_base = __DECONST(char *, "jid");
1814 	jiov[0].iov_len = sizeof("jid");
1815 	jiov[1].iov_base = &jid;
1816 	jiov[1].iov_len = sizeof(jid);
1817 	jiov[2].iov_base = __DECONST(char *, "vnet");
1818 	jiov[2].iov_len = sizeof("vnet");
1819 	jiov[3].iov_base = &vnet;
1820 	jiov[3].iov_len = sizeof(vnet);
1821 	jiov[4].iov_base = __DECONST(char *, "errmsg");
1822 	jiov[4].iov_len = sizeof("errmsg");
1823 	jiov[5].iov_base = jail_errmsg;
1824 	jiov[5].iov_len = JAIL_ERRMSGLEN;
1825 	jail_errmsg[0] = '\0';
1826 	if (jail_get(jiov, nitems(jiov), 0) < 0) {
1827 		if (!jail_errmsg[0])
1828 			snprintf(jail_errmsg, JAIL_ERRMSGLEN,
1829 			    "jail_get: %s", strerror(errno));
1830 		return (-1);
1831 	}
1832 	return (vnet);
1833 }
1834 
1835 /*
1836  * Parse username and/or UID
1837  */
1838 static bool
parse_filter_user(void)1839 parse_filter_user(void)
1840 {
1841 	struct passwd *pwd;
1842 	char *ep;
1843 	uid_t uid;
1844 	bool rv = false;
1845 
1846 	uid = (uid_t)strtol(filter_user_optarg, &ep, 10);
1847 
1848 	/* Open and/or rewind capsicumized password file */
1849 	cap_setpassent(cappwd, 1);
1850 
1851 	if (*ep == '\0') {
1852 		/* We have an UID specified, check if it's valid */
1853 		if ((pwd = cap_getpwuid(cappwd, uid)) == NULL)
1854 			goto out;
1855 		filter_user_uid = uid;
1856 	} else {
1857 		/* Check if we have a valid username */
1858 		if ((pwd = cap_getpwnam(cappwd, filter_user_optarg)) == NULL)
1859 			goto out;
1860 		filter_user_uid = pwd->pw_uid;
1861 	}
1862 
1863 	rv = true;
1864 out:
1865 	return (rv);
1866 }
1867 
1868 static void
usage(void)1869 usage(void)
1870 {
1871 	xo_error(
1872 "usage: sockstat [--libxo ...] [-46AbCcfIiLlnqSsUuvw] [-F uid/username] [-j jid] [-p ports]\n"
1873 "                [-P protocols]\n");
1874 	exit(1);
1875 }
1876 
1877 int
main(int argc,char * argv[])1878 main(int argc, char *argv[])
1879 {
1880 	cap_channel_t *capcas;
1881 	cap_net_limit_t *limit;
1882 	const char *pwdcmds[] = { "setpassent", "getpwuid", "getpwnam" };
1883 	const char *pwdfields[] = { "pw_name", "pw_uid" };
1884 	int protos_defined = -1;
1885 	int o, i, err;
1886 
1887 	argc = xo_parse_args(argc, argv);
1888 	if (argc < 0)
1889 		exit(1);
1890 	if (xo_get_style(NULL) != XO_STYLE_TEXT) {
1891 		show_path_state = true;
1892 		if (xo_get_style(NULL) != XO_STYLE_HTML)
1893 			is_xo_style_encoding = true;
1894 	}
1895 	opt_j = -1;
1896 	while ((o = getopt(argc, argv, "46AbCcF:fIij:Llnp:P:qSsUuvw")) != -1)
1897 		switch (o) {
1898 		case '4':
1899 			opt_4 = true;
1900 			break;
1901 		case '6':
1902 			opt_6 = true;
1903 			break;
1904 		case 'A':
1905 			opt_A = true;
1906 			break;
1907 		case 'b':
1908 			opt_b = true;
1909 			break;
1910 		case 'C':
1911 			opt_C = true;
1912 			break;
1913 		case 'c':
1914 			opt_c = true;
1915 			break;
1916 		case 'F':
1917 			/* Save optarg for later use when we enter capabilities mode */
1918 			filter_user_optarg = optarg;
1919 			opt_F = true;
1920 			break;
1921 		case 'f':
1922 			opt_f = true;
1923 			break;
1924 		case 'I':
1925 			opt_I = true;
1926 			break;
1927 		case 'i':
1928 			opt_i = true;
1929 			break;
1930 		case 'j':
1931 			opt_j = jail_getid(optarg);
1932 			if (opt_j < 0)
1933 				xo_errx(1, "jail_getid: %s", jail_errmsg);
1934 			break;
1935 		case 'L':
1936 			opt_L = true;
1937 			break;
1938 		case 'l':
1939 			opt_l = true;
1940 			break;
1941 		case 'n':
1942 			opt_n = true;
1943 			break;
1944 		case 'p':
1945 			err = parse_ports(optarg);
1946 			switch (err) {
1947 			case EINVAL:
1948 				xo_errx(1, "syntax error in port range");
1949 				break;
1950 			case ERANGE:
1951 				xo_errx(1, "invalid port number");
1952 				break;
1953 			}
1954 			break;
1955 		case 'P':
1956 			protos_defined = parse_protos(optarg);
1957 			break;
1958 		case 'q':
1959 			opt_q = true;
1960 			break;
1961 		case 'S':
1962 			opt_S = true;
1963 			break;
1964 		case 's':
1965 			opt_s = true;
1966 			break;
1967 		case 'U':
1968 			opt_U = true;
1969 			break;
1970 		case 'u':
1971 			opt_u = true;
1972 			break;
1973 		case 'v':
1974 			++opt_v;
1975 			break;
1976 		case 'w':
1977 			opt_w = true;
1978 			break;
1979 		default:
1980 			usage();
1981 		}
1982 
1983 	argc -= optind;
1984 	argv += optind;
1985 
1986 	if (argc > 0)
1987 		usage();
1988 
1989 	if (opt_j > 0) {
1990 		switch (jail_getvnet(opt_j)) {
1991 		case -1:
1992 			xo_errx(2, "jail_getvnet: %s", jail_errmsg);
1993 		case JAIL_SYS_NEW:
1994 			if (jail_attach(opt_j) < 0)
1995 				xo_err(3, "jail_attach()");
1996 			/* Set back to -1 for normal output in vnet jail. */
1997 			opt_j = -1;
1998 			break;
1999 		default:
2000 			break;
2001 		}
2002 	}
2003 
2004 	capcas = cap_init();
2005 	if (capcas == NULL)
2006 		xo_err(1, "Unable to contact Casper");
2007 	if (caph_enter_casper() < 0)
2008 		xo_err(1, "Unable to enter capability mode");
2009 	capnet = cap_service_open(capcas, "system.net");
2010 	if (capnet == NULL)
2011 		xo_err(1, "Unable to open system.net service");
2012 	capnetdb = cap_service_open(capcas, "system.netdb");
2013 	if (capnetdb == NULL)
2014 		xo_err(1, "Unable to open system.netdb service");
2015 	capsysctl = cap_service_open(capcas, "system.sysctl");
2016 	if (capsysctl == NULL)
2017 		xo_err(1, "Unable to open system.sysctl service");
2018 	cappwd = cap_service_open(capcas, "system.pwd");
2019 	if (cappwd == NULL)
2020 		xo_err(1, "Unable to open system.pwd service");
2021 	cap_close(capcas);
2022 	limit = cap_net_limit_init(capnet, CAPNET_ADDR2NAME);
2023 	if (limit == NULL)
2024 		xo_err(1, "Unable to init cap_net limits");
2025 	if (cap_net_limit(limit) < 0)
2026 		xo_err(1, "Unable to apply limits");
2027 	if (cap_pwd_limit_cmds(cappwd, pwdcmds, nitems(pwdcmds)) < 0)
2028 		xo_err(1, "Unable to apply pwd commands limits");
2029 	if (cap_pwd_limit_fields(cappwd, pwdfields, nitems(pwdfields)) < 0)
2030 		xo_err(1, "Unable to apply pwd commands limits");
2031 
2032 	if (opt_F && !parse_filter_user())
2033 		xo_errx(1, "Invalid username or UID specified");
2034 
2035 	if ((!opt_4 && !opt_6) && protos_defined != -1)
2036 		opt_4 = opt_6 = true;
2037 	if (!opt_4 && !opt_6 && !opt_u)
2038 		opt_4 = opt_6 = opt_u = true;
2039 	if ((opt_4 || opt_6) && protos_defined == -1)
2040 		protos_defined = set_default_protos();
2041 	if (!opt_c && !opt_l)
2042 		opt_c = opt_l = true;
2043 
2044 	if (opt_4 || opt_6) {
2045 		for (i = 0; i < protos_defined; i++)
2046 			if (protos[i] == IPPROTO_SCTP)
2047 				gather_sctp();
2048 			else
2049 				gather_inet(protos[i]);
2050 	}
2051 
2052 	if (opt_u || (protos_defined == -1 && !opt_4 && !opt_6)) {
2053 		gather_unix(SOCK_STREAM);
2054 		gather_unix(SOCK_DGRAM);
2055 		gather_unix(SOCK_SEQPACKET);
2056 	}
2057 	getfiles();
2058 	display();
2059 	exit(0);
2060 }
2061