xref: /dragonfly/usr.bin/sockstat/sockstat.c (revision 279dd846)
1 /*-
2  * Copyright (c) 2005 Joerg Sonnenberger <joerg@bec.de>.  All rights reserved.
3  * Copyright (c) 2002 Dag-Erling Coïdan Smørgrav
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer
11  *    in this position and unchanged.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * $FreeBSD: src/usr.bin/sockstat/sockstat.c,v 1.12 2004/12/06 09:28:05 ru Exp $
30  */
31 
32 #include <sys/user.h>
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/socketvar.h>
36 #include <sys/sysctl.h>
37 #include <sys/file.h>
38 
39 #include <sys/un.h>
40 #include <sys/unpcb.h>
41 
42 #include <net/route.h>
43 
44 #include <netinet/in.h>
45 #include <netinet/in_pcb.h>
46 #include <netinet/tcp.h>
47 #include <netinet/tcp_seq.h>
48 #include <netinet/tcp_var.h>
49 #include <arpa/inet.h>
50 
51 #include <ctype.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <kinfo.h>
55 #include <netdb.h>
56 #include <pwd.h>
57 #include <stdarg.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 
63 static int	 opt_4;		/* Show IPv4 sockets */
64 static int	 opt_6;		/* Show IPv6 sockets */
65 static int	 opt_c;		/* Show connected sockets */
66 static int	 opt_l;		/* Show listening sockets */
67 static int	 opt_u;		/* Show Unix domain sockets */
68 static int	 opt_v;		/* Verbose mode */
69 
70 static int	*ports;
71 
72 #define INT_BIT (sizeof(int)*CHAR_BIT)
73 #define SET_PORT(p) do { ports[p / INT_BIT] |= 1 << (p % INT_BIT); } while (0)
74 #define CHK_PORT(p) (ports[p / INT_BIT] & (1 << (p % INT_BIT)))
75 
76 struct sock {
77 	void *socket;
78 	void *pcb;
79 	int family;
80 	int proto;
81 	const char *protoname;
82 	struct sockaddr_storage laddr;
83 	struct sockaddr_storage faddr;
84 	struct sock *next;
85 };
86 
87 static int xprintf(const char *, ...) __printflike(1, 2);
88 
89 #define HASHSIZE 1009
90 static struct sock *sockhash[HASHSIZE];
91 
92 static struct kinfo_file *xfiles;
93 static size_t nxfiles;
94 
95 static int
96 xprintf(const char *fmt, ...)
97 {
98 	va_list ap;
99 	int len;
100 
101 	va_start(ap, fmt);
102 	len = vprintf(fmt, ap);
103 	va_end(ap);
104 	if (len < 0)
105 		err(1, "printf()");
106 	return (len);
107 }
108 
109 static void
110 parse_ports(const char *portspec)
111 {
112 	const char *p, *q;
113 	int port, end;
114 
115 	if (ports == NULL)
116 		if ((ports = calloc(65536 / INT_BIT, sizeof(int))) == NULL)
117 			err(1, "calloc()");
118 	p = portspec;
119 	while (*p != '\0') {
120 		if (!isdigit(*p))
121 			errx(1, "syntax error in port range");
122 		for (q = p; *q != '\0' && isdigit(*q); ++q)
123 			/* nothing */ ;
124 		for (port = 0; p < q; ++p)
125 			port = port * 10 + (*p - '0');
126 		if (port < 0 || port > 65535)
127 			errx(1, "invalid port number");
128 		SET_PORT(port);
129 		switch (*p) {
130 		case '-':
131 			++p;
132 			break;
133 		case ',':
134 			++p;
135 			/* fall through */
136 		case '\0':
137 		default:
138 			continue;
139 		}
140 		for (q = p; *q != '\0' && isdigit(*q); ++q)
141 			/* nothing */ ;
142 		for (end = 0; p < q; ++p)
143 			end = end * 10 + (*p - '0');
144 		if (end < port || end > 65535)
145 			errx(1, "invalid port number");
146 		while (port++ < end)
147 			SET_PORT(port);
148 		if (*p == ',')
149 			++p;
150 	}
151 }
152 
153 static void
154 sockaddr(struct sockaddr_storage *sa, int af, void *addr, int port)
155 {
156 	struct sockaddr_in *sin4;
157 	struct sockaddr_in6 *sin6;
158 
159 	bzero(sa, sizeof *sa);
160 	switch (af) {
161 	case AF_INET:
162 		sin4 = (struct sockaddr_in *)sa;
163 		sin4->sin_len = sizeof *sin4;
164 		sin4->sin_family = af;
165 		sin4->sin_port = port;
166 		sin4->sin_addr = *(struct in_addr *)addr;
167 		break;
168 	case AF_INET6:
169 		sin6 = (struct sockaddr_in6 *)sa;
170 		sin6->sin6_len = sizeof *sin6;
171 		sin6->sin6_family = af;
172 		sin6->sin6_port = port;
173 		sin6->sin6_addr = *(struct in6_addr *)addr;
174 		break;
175 	default:
176 		abort();
177 	}
178 }
179 
180 static void
181 gather_inet(int proto)
182 {
183 	void *so_begin, *so_end;
184 	struct xinpcb *xip;
185 	struct xtcpcb *xtp;
186 	struct inpcb *inp;
187 	struct xsocket *so;
188 	struct sock *sock;
189 	const char *varname, *protoname;
190 	size_t len;
191 	void *buf;
192 	int hash;
193 
194 	switch (proto) {
195 	case IPPROTO_TCP:
196 		varname = "net.inet.tcp.pcblist";
197 		protoname = "tcp";
198 		break;
199 	case IPPROTO_UDP:
200 		varname = "net.inet.udp.pcblist";
201 		protoname = "udp";
202 		break;
203 	case IPPROTO_DIVERT:
204 		varname = "net.inet.divert.pcblist";
205 		protoname = "div";
206 		break;
207 	default:
208 		abort();
209 	}
210 
211 	buf = NULL;
212 	len = 0;
213 
214 	if (sysctlbyname(varname, NULL, &len, NULL, 0)) {
215 		if (errno == ENOENT)
216 			goto out;
217 		err(1, "fetching %s", varname);
218 	}
219 	if ((buf = malloc(len)) == NULL)
220 		err(1, "malloc()");
221 	if (sysctlbyname(varname, buf, &len, NULL, 0)) {
222 		if (errno == ENOENT)
223 			goto out;
224 		err(1, "fetching %s", varname);
225 	}
226 
227 	so_begin = buf;
228 	so_end = (uint8_t *)buf + len;
229 
230 	for (so_begin = buf, so_end = (uint8_t *)so_begin + len;
231 	     (uint8_t *)so_begin + sizeof(size_t) < (uint8_t *)so_end &&
232 	     (uint8_t *)so_begin + *(size_t *)so_begin <= (uint8_t *)so_end;
233 	     so_begin = (uint8_t *)so_begin + *(size_t *)so_begin) {
234 		switch (proto) {
235 		case IPPROTO_TCP:
236 			xtp = (struct xtcpcb *)so_begin;
237 			if (xtp->xt_len != sizeof *xtp) {
238 				warnx("struct xtcpcb size mismatch");
239 				goto out;
240 			}
241 			inp = &xtp->xt_inp;
242 			so = &xtp->xt_socket;
243 			break;
244 		case IPPROTO_UDP:
245 		case IPPROTO_DIVERT:
246 			xip = (struct xinpcb *)so_begin;
247 			if (xip->xi_len != sizeof *xip) {
248 				warnx("struct xinpcb size mismatch");
249 				goto out;
250 			}
251 			inp = &xip->xi_inp;
252 			so = &xip->xi_socket;
253 			break;
254 		default:
255 			abort();
256 		}
257 		if ((INP_ISIPV4(inp) && !opt_4) || (INP_ISIPV6(inp) && !opt_6))
258 			continue;
259 		if (INP_ISIPV4(inp)) {
260 			if ((inp->inp_fport == 0 && !opt_l) ||
261 			    (inp->inp_fport != 0 && !opt_c))
262 				continue;
263 		} else if (INP_ISIPV6(inp)) {
264 			if ((inp->in6p_fport == 0 && !opt_l) ||
265 			    (inp->in6p_fport != 0 && !opt_c))
266 				continue;
267 		} else {
268 			if (opt_v)
269 				warnx("invalid af 0x%x", inp->inp_af);
270 			continue;
271 		}
272 		if ((sock = calloc(1, sizeof *sock)) == NULL)
273 			err(1, "malloc()");
274 		sock->socket = so->xso_so;
275 		sock->proto = proto;
276 		if (INP_ISIPV4(inp)) {
277 			sock->family = AF_INET;
278 			sockaddr(&sock->laddr, sock->family,
279 			    &inp->inp_laddr, inp->inp_lport);
280 			sockaddr(&sock->faddr, sock->family,
281 			    &inp->inp_faddr, inp->inp_fport);
282 		} else if (INP_ISIPV6(inp)) {
283 			sock->family = AF_INET6;
284 			sockaddr(&sock->laddr, sock->family,
285 			    &inp->in6p_laddr, inp->in6p_lport);
286 			sockaddr(&sock->faddr, sock->family,
287 			    &inp->in6p_faddr, inp->in6p_fport);
288 		}
289 		sock->protoname = protoname;
290 		hash = (int)((uintptr_t)sock->socket % HASHSIZE);
291 		sock->next = sockhash[hash];
292 		sockhash[hash] = sock;
293 	}
294 out:
295 	free(buf);
296 }
297 
298 static void
299 gather_unix(int proto)
300 {
301 	void *so_begin, *so_end;
302 	struct xunpcb *xup;
303 	struct sock *sock;
304 	const char *varname, *protoname;
305 	size_t len;
306 	void *buf;
307 	int hash;
308 
309 	switch (proto) {
310 	case SOCK_STREAM:
311 		varname = "net.local.stream.pcblist";
312 		protoname = "stream";
313 		break;
314 	case SOCK_DGRAM:
315 		varname = "net.local.dgram.pcblist";
316 		protoname = "dgram";
317 		break;
318 	default:
319 		abort();
320 	}
321 
322 	buf = NULL;
323 	len = 0;
324 
325 	if (sysctlbyname(varname, NULL, &len, NULL, 0))
326 		err(1, "fetching %s", varname);
327 
328 	if ((buf = malloc(len)) == NULL)
329 		err(1, "malloc()");
330 	if (sysctlbyname(varname, buf, &len, NULL, 0))
331 		err(1, "fetching %s", varname);
332 
333 	for (so_begin = buf, so_end = (uint8_t *)buf + len;
334 	     (uint8_t *)so_begin + sizeof(size_t) < (uint8_t *)so_end &&
335 	     (uint8_t *)so_begin + *(size_t *)so_begin <= (uint8_t *)so_end;
336 	     so_begin = (uint8_t *)so_begin + *(size_t *)so_begin) {
337 		xup = so_begin;
338 		if (xup->xu_len != sizeof *xup) {
339 			warnx("struct xunpcb size mismatch");
340 			goto out;
341 		}
342 		if ((xup->xu_unp.unp_conn == NULL && !opt_l) ||
343 		    (xup->xu_unp.unp_conn != NULL && !opt_c))
344 			continue;
345 		if ((sock = calloc(1, sizeof *sock)) == NULL)
346 			err(1, "malloc()");
347 		sock->socket = xup->xu_socket.xso_so;
348 		sock->pcb = xup->xu_unpp;
349 		sock->proto = proto;
350 		sock->family = AF_UNIX;
351 		sock->protoname = protoname;
352 		if (xup->xu_unp.unp_addr != NULL)
353 			sock->laddr =
354 			    *(struct sockaddr_storage *)(void *)&xup->xu_addr;
355 		else if (xup->xu_unp.unp_conn != NULL)
356 			*(void **)&sock->faddr = xup->xu_unp.unp_conn;
357 		hash = (int)((uintptr_t)sock->socket % HASHSIZE);
358 		sock->next = sockhash[hash];
359 		sockhash[hash] = sock;
360 	}
361 out:
362 	free(buf);
363 }
364 
365 static void
366 getfiles(void)
367 {
368 	if (kinfo_get_files(&xfiles, &nxfiles))
369 		err(1, "kinfo_get_files");
370 }
371 
372 static int
373 printaddr(int af, struct sockaddr_storage *ss)
374 {
375 	char addrstr[INET6_ADDRSTRLEN] = { '\0', '\0' };
376 	struct sockaddr_un *sun;
377 	void *addr;
378 	int off, port;
379 
380 	switch (af) {
381 	case AF_INET:
382 		addr = &((struct sockaddr_in *)ss)->sin_addr;
383 		if (inet_lnaof(*(struct in_addr *)addr) == INADDR_ANY)
384 			addrstr[0] = '*';
385 		port = ntohs(((struct sockaddr_in *)ss)->sin_port);
386 		break;
387 	case AF_INET6:
388 		addr = &((struct sockaddr_in6 *)ss)->sin6_addr;
389 		if (IN6_IS_ADDR_UNSPECIFIED((struct in6_addr *)addr))
390 			addrstr[0] = '*';
391 		port = ntohs(((struct sockaddr_in6 *)ss)->sin6_port);
392 		break;
393 	case AF_UNIX:
394 		sun = (struct sockaddr_un *)ss;
395 		off = (int)((char *)&sun->sun_path - (char *)sun);
396 		return (xprintf("%.*s", sun->sun_len - off, sun->sun_path));
397 	default:
398 		abort();
399 	}
400 	if (addrstr[0] == '\0')
401 		inet_ntop(af, addr, addrstr, sizeof addrstr);
402 	if (port == 0)
403 		return xprintf("%s:*", addrstr);
404 	else
405 		return xprintf("%s:%d", addrstr, port);
406 }
407 
408 static const char *
409 getprocname(pid_t pid)
410 {
411 	static struct kinfo_proc proc;
412 	size_t len;
413 	int mib[4];
414 
415 	mib[0] = CTL_KERN;
416 	mib[1] = KERN_PROC;
417 	mib[2] = KERN_PROC_PID;
418 	mib[3] = (int)pid;
419 	len = sizeof proc;
420 	if (sysctl(mib, 4, &proc, &len, NULL, 0) == -1) {
421 		warn("sysctl()");
422 		return ("??");
423 	}
424 	return (proc.kp_comm);
425 }
426 
427 static int
428 check_ports(struct sock *s)
429 {
430 	int port;
431 
432 	if (ports == NULL)
433 		return (1);
434 	if ((s->family != AF_INET) && (s->family != AF_INET6))
435 		return (1);
436 	if (s->family == AF_INET)
437 		port = ntohs(((struct sockaddr_in *)(&s->laddr))->sin_port);
438 	else
439 		port = ntohs(((struct sockaddr_in6 *)(&s->laddr))->sin6_port);
440 	if (CHK_PORT(port))
441 		return (1);
442 	if (s->family == AF_INET)
443 		port = ntohs(((struct sockaddr_in *)(&s->faddr))->sin_port);
444 	else
445 		port = ntohs(((struct sockaddr_in6 *)(&s->faddr))->sin6_port);
446 	if (CHK_PORT(port))
447 		return (1);
448 	return (0);
449 }
450 
451 static void
452 display(void)
453 {
454 	struct passwd *pwd;
455 	struct kinfo_file *xf;
456 	struct sock *s;
457 	void *p;
458 	int hash, n, pos;
459 
460 	printf("%-8s %-10s %-5s %-2s %-6s %-21s %-21s\n",
461 	    "USER", "COMMAND", "PID", "FD", "PROTO",
462 	    "LOCAL ADDRESS", "FOREIGN ADDRESS");
463 	setpassent(1);
464 	for (xf = xfiles, n = 0; n < (int)nxfiles; ++n, ++xf) {
465 		if (xf->f_data == NULL)
466 			continue;
467 		hash = (int)((uintptr_t)xf->f_data % HASHSIZE);
468 		for (s = sockhash[hash]; s != NULL; s = s->next)
469 			if ((void *)s->socket == xf->f_data)
470 				break;
471 		if (s == NULL)
472 			continue;
473 		if (!check_ports(s))
474 			continue;
475 		pos = 0;
476 		if ((pwd = getpwuid(xf->f_uid)) == NULL)
477 			pos += xprintf("%lu", (u_long)xf->f_uid);
478 		else
479 			pos += xprintf("%s", pwd->pw_name);
480 		while (pos < 9)
481 			pos += xprintf(" ");
482 		pos += xprintf("%.10s", getprocname(xf->f_pid));
483 		while (pos < 20)
484 			pos += xprintf(" ");
485 		pos += xprintf("%lu", (u_long)xf->f_pid);
486 		while (pos < 26)
487 			pos += xprintf(" ");
488 		pos += xprintf("%d", xf->f_fd);
489 		while (pos < 29)
490 			pos += xprintf(" ");
491 		pos += xprintf("%s", s->protoname);
492 		if (s->family == AF_INET)
493 			pos += xprintf("4");
494 		if (s->family == AF_INET6)
495 			pos += xprintf("6");
496 		while (pos < 36)
497 			pos += xprintf(" ");
498 		switch (s->family) {
499 		case AF_INET:
500 		case AF_INET6:
501 			pos += printaddr(s->family, &s->laddr);
502 			while (pos < 57)
503 				pos += xprintf(" ");
504 			pos += xprintf(" ");
505 			pos += printaddr(s->family, &s->faddr);
506 			break;
507 		case AF_UNIX:
508 			/* server */
509 			if (s->laddr.ss_len > 0) {
510 				pos += printaddr(s->family, &s->laddr);
511 				break;
512 			}
513 			/* client */
514 			p = *(void **)&s->faddr;
515 			if (p == NULL) {
516 				pos += xprintf("(not connected)");
517 				break;
518 			}
519 			pos += xprintf("-> ");
520 			for (hash = 0; hash < HASHSIZE; ++hash) {
521 				for (s = sockhash[hash]; s != NULL; s = s->next)
522 					if (s->pcb == p)
523 						break;
524 				if (s != NULL)
525 					break;
526 			}
527 			if (s == NULL || s->laddr.ss_len == 0)
528 				pos += xprintf("??");
529 			else
530 				pos += printaddr(s->family, &s->laddr);
531 			break;
532 		default:
533 			abort();
534 		}
535 		xprintf("\n");
536 	}
537 }
538 
539 static void
540 usage(void)
541 {
542 	fprintf(stderr, "Usage: sockstat [-46clu] [-p ports]\n");
543 	exit(1);
544 }
545 
546 int
547 main(int argc, char *argv[])
548 {
549 	int o;
550 
551 	while ((o = getopt(argc, argv, "46clp:uv")) != -1)
552 		switch (o) {
553 		case '4':
554 			opt_4 = 1;
555 			break;
556 		case '6':
557 			opt_6 = 1;
558 			break;
559 		case 'c':
560 			opt_c = 1;
561 			break;
562 		case 'l':
563 			opt_l = 1;
564 			break;
565 		case 'p':
566 			parse_ports(optarg);
567 			break;
568 		case 'u':
569 			opt_u = 1;
570 			break;
571 		case 'v':
572 			++opt_v;
573 			break;
574 		default:
575 			usage();
576 		}
577 
578 	argc -= optind;
579 	argv += optind;
580 
581 	if (argc > 0)
582 		usage();
583 
584 	if (!opt_4 && !opt_6 && !opt_u)
585 		opt_4 = opt_6 = opt_u = 1;
586 	if (!opt_c && !opt_l)
587 		opt_c = opt_l = 1;
588 
589 	if (opt_4 || opt_6) {
590 		gather_inet(IPPROTO_TCP);
591 		gather_inet(IPPROTO_UDP);
592 		gather_inet(IPPROTO_DIVERT);
593 	}
594 	if (opt_u) {
595 		gather_unix(SOCK_STREAM);
596 		gather_unix(SOCK_DGRAM);
597 	}
598 	getfiles();
599 	display();
600 
601 	exit(0);
602 }
603