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