xref: /netbsd-src/usr.bin/sockstat/sockstat.c (revision 8ac07aec990b9d2e483062509d0a9fa5b4f57cf2)
1 /*	$NetBSD: sockstat.c,v 1.13 2008/03/01 11:04:30 he Exp $ */
2 
3 /*
4  * Copyright (c) 2005 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andrew Brown.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of The NetBSD Foundation nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __RCSID("$NetBSD: sockstat.c,v 1.13 2008/03/01 11:04:30 he Exp $");
38 #endif
39 
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/sysctl.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
45 #include <sys/un.h>
46 #include <netinet/in.h>
47 #include <net/route.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
50 #include <netinet/in_pcb.h>
51 #include <netinet/in_pcb_hdr.h>
52 #include <netinet/tcp_fsm.h>
53 
54 #define _KERNEL
55 /* want DTYPE_* defines */
56 #include <sys/file.h>
57 #undef _KERNEL
58 
59 #include <arpa/inet.h>
60 
61 #include <bitstring.h>
62 #include <ctype.h>
63 #include <err.h>
64 #include <errno.h>
65 #include <netdb.h>
66 #include <pwd.h>
67 #include <stdio.h>
68 #include <strings.h>
69 #include <stdlib.h>
70 #include <unistd.h>
71 #include <util.h>
72 
73 #define satosun(sa)	((struct sockaddr_un *)(sa))
74 #define satosin(sa)	((struct sockaddr_in *)(sa))
75 #ifdef INET6
76 #define satosin6(sa)	((struct sockaddr_in6 *)(sa))
77 #endif
78 
79 void	parse_ports(const char *);
80 int	get_num(const char *, const char **, const char **);
81 void	get_sockets(const char *);
82 void	get_files(void);
83 int	sort_files(const void *, const void *);
84 void	sysctl_sucker(int *, u_int, void **, size_t *);
85 void	socket_add_hash(struct kinfo_pcb *, int);
86 int	isconnected(struct kinfo_pcb *);
87 int	islistening(struct kinfo_pcb *);
88 struct kinfo_pcb *pick_socket(struct kinfo_file *);
89 int	get_proc(struct kinfo_proc2 *, int);
90 int	print_socket(struct kinfo_file *, struct kinfo_pcb *,
91 		     struct kinfo_proc2 *);
92 void	print_addr(int, int, int, struct sockaddr *);
93 
94 LIST_HEAD(socklist, sockitem);
95 #define HASHSIZE 1009
96 struct socklist sockhash[HASHSIZE];
97 struct sockitem {
98 	LIST_ENTRY(sockitem) s_list;
99 	struct kinfo_pcb *s_sock;
100 };
101 
102 struct kinfo_file *flist;
103 u_int nfiles;
104 
105 int pf_list, only, nonames;
106 bitstr_t *portmap;
107 
108 #define PF_LIST_INET	1
109 #ifdef INET6
110 #define PF_LIST_INET6	2
111 #endif
112 #define PF_LIST_LOCAL	4
113 #define ONLY_CONNECTED	1
114 #define ONLY_LISTEN	2
115 
116 int
117 main(int argc, char *argv[])
118 {
119 	struct kinfo_pcb *kp;
120 	int i, ch;
121 	struct kinfo_proc2 p;
122 
123 	pf_list = only = 0;
124 
125 #ifdef INET6
126 	while ((ch = getopt(argc, argv, "46cf:lnp:u")) != - 1) {
127 #else
128 	while ((ch = getopt(argc, argv, "4cf:lnp:u")) != - 1) {
129 #endif
130 		switch (ch) {
131 		case '4':
132 			pf_list |= PF_LIST_INET;
133 			break;
134 #ifdef INET6
135 		case '6':
136 			pf_list |= PF_LIST_INET6;
137 			break;
138 #endif
139 		case 'c':
140 			only |= ONLY_CONNECTED;
141 			break;
142 		case 'f':
143 			if (strcasecmp(optarg, "inet") == 0)
144 				pf_list |= PF_LIST_INET;
145 #ifdef INET6
146 			else if (strcasecmp(optarg, "inet6") == 0)
147 				pf_list |= PF_LIST_INET6;
148 #endif
149 			else if (strcasecmp(optarg, "local") == 0)
150 				pf_list |= PF_LIST_LOCAL;
151 			else if (strcasecmp(optarg, "unix") == 0)
152 				pf_list |= PF_LIST_LOCAL;
153 			else
154 				errx(1, "%s: unsupported protocol family",
155 				    optarg);
156 			break;
157 		case 'l':
158 			only |= ONLY_LISTEN;
159 			break;
160 		case 'n':
161 			nonames++;
162 			break;
163 		case 'p':
164 			parse_ports(optarg);
165 			break;
166 		case 'u':
167 			pf_list |= PF_LIST_LOCAL;
168 			break;
169 		default:
170 			/* usage(); */
171 			exit(1);
172 		}
173 	}
174 	argc -= optind;
175 	argv += optind;
176 
177 	if ((portmap != NULL) && (pf_list == 0)) {
178 		pf_list = PF_LIST_INET;
179 #ifdef INET6
180 		pf_list |= PF_LIST_INET6;
181 #endif
182 	}
183 	if (pf_list == 0) {
184 		pf_list = PF_LIST_INET | PF_LIST_LOCAL;
185 #ifdef INET6
186 		pf_list |= PF_LIST_INET6;
187 #endif
188 	}
189 	if ((portmap != NULL) && (pf_list & PF_LIST_LOCAL))
190 		errx(1, "local domain sockets do not have ports");
191 
192 	if (pf_list & PF_LIST_INET) {
193 		get_sockets("net.inet.tcp.pcblist");
194 		get_sockets("net.inet.udp.pcblist");
195 		if (portmap == NULL)
196 			get_sockets("net.inet.raw.pcblist");
197 	}
198 
199 #ifdef INET6
200 	if (pf_list & PF_LIST_INET6) {
201 		get_sockets("net.inet6.tcp6.pcblist");
202 		get_sockets("net.inet6.udp6.pcblist");
203 		if (portmap == NULL)
204 			get_sockets("net.inet6.raw6.pcblist");
205 	}
206 #endif
207 
208 	if (pf_list & PF_LIST_LOCAL) {
209 		get_sockets("net.local.stream.pcblist");
210 		get_sockets("net.local.dgram.pcblist");
211 	}
212 
213 	get_files();
214 
215 	p.p_pid = 0;
216 	for (i = 0; i < nfiles; i++)
217 		if ((kp = pick_socket(&flist[i])) != NULL &&
218 		    get_proc(&p, flist[i].ki_pid) == 0)
219 			print_socket(&flist[i], kp, &p);
220 
221 	return (0);
222 }
223 
224 void
225 parse_ports(const char *l)
226 {
227 	struct servent *srv;
228 	const char *s, *e;
229 	long i, j;
230 
231 	if (portmap == NULL) {
232 		portmap = bit_alloc(65536);
233 		if (portmap == NULL)
234 			err(1, "malloc");
235 	}
236 
237 	if ((srv = getservbyname(l, NULL)) != NULL) {
238 		bit_set(portmap, ntohs(srv->s_port));
239 		return;
240 	}
241 
242 	s = e = l;
243 	while (*s != '\0') {
244 		i = get_num(l, &s, &e);
245 		switch (*e) {
246 		case ',':
247 			e++;
248 		case '\0':
249 			bit_set(portmap, i);
250 			s = e;
251 			continue;
252 		case '-':
253 			s = ++e;
254 			j = get_num(l, &s, &e);
255 			for (; i <= j; i++)
256 				bit_set(portmap, i);
257 			break;
258 		default:
259 			errno = EINVAL;
260 			err(1, "%s", l);
261 		}
262 	}
263 }
264 
265 int
266 get_num(const char *l, const char **s, const char **e)
267 {
268 	long x;
269 	char *t;
270 
271 	while (isdigit((u_int)**e))
272 		(*e)++;
273 	if (*s != *e) {
274 		errno = 0;
275 		x = strtol(*s, &t, 0);
276 		if (errno == 0 && x >= 0 && x <= 65535 && t == *e)
277 			return (x);
278 	}
279 
280 	errno = EINVAL;
281 	err(1, "%s", l);
282 }
283 
284 void
285 get_sockets(const char *mib)
286 {
287 	void *v;
288 	size_t sz;
289 	int rc, n, name[CTL_MAXNAME];
290 	u_int namelen;
291 
292 	sz = CTL_MAXNAME;
293 	rc = sysctlnametomib(mib, &name[0], &sz);
294 	if (rc == -1) {
295 		if (errno == ENOENT)
296 			return;
297 		err(1, "sysctlnametomib: %s", mib);
298 	}
299 	namelen = sz;
300 
301 	name[namelen++] = PCB_ALL;
302 	name[namelen++] = 0;		/* XXX all pids */
303 	name[namelen++] = sizeof(struct kinfo_pcb);
304 	name[namelen++] = INT_MAX;	/* all of them */
305 
306 	sysctl_sucker(&name[0], namelen, &v, &sz);
307 	n = sz / sizeof(struct kinfo_pcb);
308 	socket_add_hash(v, n);
309 }
310 
311 void
312 get_files(void)
313 {
314 	void *v;
315 	size_t sz;
316 	int rc, name[CTL_MAXNAME];
317 	u_int namelen;
318 
319 	sz = CTL_MAXNAME;
320 	rc = sysctlnametomib("kern.file2", &name[0], &sz);
321 	if (rc == -1)
322 		err(1, "sysctlnametomib");
323 	namelen = sz;
324 
325 	name[namelen++] = KERN_FILE_BYPID;
326 	name[namelen++] = 0;		/* XXX all pids */
327 	name[namelen++] = sizeof(struct kinfo_file);
328 	name[namelen++] = INT_MAX;	/* all of them */
329 
330 	sysctl_sucker(&name[0], namelen, &v, &sz);
331 	flist = v;
332 	nfiles = sz / sizeof(struct kinfo_file);
333 
334 	qsort(flist, nfiles, sizeof(*flist), sort_files);
335 }
336 
337 int
338 sort_files(const void *a, const void *b)
339 {
340 	const struct kinfo_file *ka = a, *kb = b;
341 
342 	if (ka->ki_pid == kb->ki_pid)
343 		return (ka->ki_fd - kb->ki_fd);
344 
345 	return (ka->ki_pid - kb->ki_pid);
346 }
347 
348 void
349 sysctl_sucker(int *name, u_int namelen, void **vp, size_t *szp)
350 {
351 	int rc;
352 	void *v;
353 	size_t sz;
354 
355 	/* printf("name %p, namelen %u\n", name, namelen); */
356 
357 	v = NULL;
358 	sz = 0;
359 	do {
360 		rc = sysctl(&name[0], namelen, v, &sz, NULL, 0);
361 		if (rc == -1 && errno != ENOMEM)
362 			err(1, "sysctl");
363 		if (rc == -1 && v != NULL) {
364 			free(v);
365 			v = NULL;
366 		}
367 		if (v == NULL) {
368 			v = malloc(sz);
369 			rc = -1;
370 		}
371 		if (v == NULL)
372 			err(1, "malloc");
373 	} while (rc == -1);
374 
375 	*vp = v;
376 	*szp = sz;
377 	/* printf("got %zu at %p\n", sz, v); */
378 }
379 
380 void
381 socket_add_hash(struct kinfo_pcb *kp, int n)
382 {
383 	struct sockitem *si;
384 	int hash, i;
385 
386 	if (n == 0)
387 		return;
388 
389 	si = malloc(sizeof(*si) * n);
390 	if (si== NULL)
391 		err(1, "malloc");
392 
393 	for (i = 0; i < n; i++) {
394 		si[i].s_sock = &kp[i];
395 		hash = (int)(kp[i].ki_sockaddr % HASHSIZE);
396 		LIST_INSERT_HEAD(&sockhash[hash], &si[i], s_list);
397 	}
398 }
399 
400 int
401 isconnected(struct kinfo_pcb *kp)
402 {
403 
404 	if ((kp->ki_sostate & SS_ISCONNECTED) ||
405 	    (kp->ki_prstate >= INP_CONNECTED) ||
406 	    (kp->ki_tstate > TCPS_LISTEN) ||
407 	    (kp->ki_conn != 0))
408 		return (1);
409 
410 	return (0);
411 }
412 
413 int
414 islistening(struct kinfo_pcb *kp)
415 {
416 
417 	if (isconnected(kp))
418 		return (0);
419 
420 	if (kp->ki_tstate == TCPS_LISTEN)
421 		return (1);
422 
423 	switch (kp->ki_family) {
424 	case PF_INET:
425 		if (kp->ki_type == SOCK_RAW ||
426 		    (kp->ki_type == SOCK_DGRAM &&
427 		     ntohs(satosin(&kp->ki_src)->sin_port) != 0))
428 			return (1);
429 		break;
430 #ifdef INET6
431 	case PF_INET6:
432 		if (kp->ki_type == SOCK_RAW ||
433 		    (kp->ki_type == SOCK_DGRAM &&
434 		     ntohs(satosin6(&kp->ki_src)->sin6_port) != 0))
435 			return (1);
436 		break;
437 #endif
438 	case PF_LOCAL:
439 		if (satosun(&kp->ki_src)->sun_path[0] != '\0')
440 			return (1);
441 		break;
442 	default:
443 		break;
444 	}
445 
446 	return (0);
447 }
448 
449 struct kinfo_pcb *
450 pick_socket(struct kinfo_file *f)
451 {
452 	struct sockitem *si;
453 	struct kinfo_pcb *kp;
454 	int hash;
455 
456 	if (f->ki_ftype != DTYPE_SOCKET)
457 		return (NULL);
458 
459 	hash = (int)(f->ki_fdata % HASHSIZE);
460 	LIST_FOREACH(si, &sockhash[hash], s_list) {
461 		if (si->s_sock->ki_sockaddr == f->ki_fdata)
462 			break;
463 	}
464 	if (si == NULL)
465 		return (NULL);
466 
467 	kp = si->s_sock;
468 
469 	if (only) {
470 		if (isconnected(kp)) {
471 			/*
472 			 * connected but you didn't say you wanted
473 			 * connected sockets
474 			 */
475 			if (!(only & ONLY_CONNECTED))
476 				return (NULL);
477 		}
478 		else if (islistening(kp)) {
479 			/*
480 			 * listening but you didn't ask for listening
481 			 * sockets
482 			 */
483 			if (!(only & ONLY_LISTEN))
484 				return (NULL);
485 		}
486 		else
487 			/*
488 			 * neither connected nor listening, so you
489 			 * don't get it
490 			 */
491 			return (NULL);
492 	}
493 
494 	if (portmap) {
495 		switch (kp->ki_family) {
496 		case AF_INET:
497 			if (!bit_test(portmap,
498 				      ntohs(satosin(&kp->ki_src)->sin_port)) &&
499 			    !bit_test(portmap,
500 				      ntohs(satosin(&kp->ki_dst)->sin_port)))
501 				return (NULL);
502 			break;
503 #ifdef INET6
504 		case AF_INET6:
505 			if (!bit_test(portmap,
506 			    ntohs(satosin6(&kp->ki_src)->sin6_port)) &&
507 			    !bit_test(portmap,
508 				      ntohs(satosin6(&kp->ki_dst)->sin6_port)))
509 				return (NULL);
510 			break;
511 #endif
512 		default:
513 			return (NULL);
514 		}
515 	}
516 
517 	return (kp);
518 }
519 
520 int
521 get_proc(struct kinfo_proc2 *p, int pid)
522 {
523 	int name[6];
524 	u_int namelen;
525 	size_t sz;
526 
527 	if (p->p_pid == pid)
528 		return (0);
529 
530 	sz = sizeof(*p);
531 	namelen = 0;
532 	name[namelen++] = CTL_KERN;
533 	name[namelen++] = KERN_PROC2;
534 	name[namelen++] = KERN_PROC_PID;
535 	name[namelen++] = pid;
536 	name[namelen++] = sz;
537 	name[namelen++] = 1;
538 
539 	return (sysctl(&name[0], namelen, p, &sz, NULL, 0));
540 }
541 
542 int
543 print_socket(struct kinfo_file *kf, struct kinfo_pcb *kp, struct kinfo_proc2 *p)
544 {
545 	static int first = 1;
546 	struct passwd *pw;
547 	const char *t;
548 	char proto[22];
549 
550 	if (first) {
551 		printf("%-8s " "%-10s "   "%-5s " "%-2s " "%-6s "
552 		       "%-21s "         "%s\n",
553 		       "USER", "COMMAND", "PID",  "FD",   "PROTO",
554 		       "LOCAL ADDRESS", "FOREIGN ADDRESS");
555 		first = 0;
556 	}
557 
558 	if ((pw = getpwuid(p->p_uid)) != NULL)
559 		printf("%-8s ", pw->pw_name);
560 	else
561 		printf("%-8d ", (int)p->p_uid);
562 
563 	printf("%-10.10s ", p->p_comm);
564 	printf("%-5d ", (int)kf->ki_pid);
565 	printf("%2d ", (int)kf->ki_fd);
566 
567 	snprintf(proto, sizeof(proto), "%d/%d", kp->ki_family, kp->ki_protocol);
568 
569 	switch (kp->ki_family) {
570 	case PF_INET:
571 		switch (kp->ki_protocol) {
572 		case IPPROTO_TCP:	t = "tcp";	break;
573 		case IPPROTO_UDP:	t = "udp";	break;
574 		case IPPROTO_RAW:	t = "raw";	break;
575 		default:		t = proto;	break;
576 		}
577 		break;
578 #ifdef INET6
579 	case PF_INET6:
580 		switch (kp->ki_protocol) {
581 		case IPPROTO_TCP:	t = "tcp6";	break;
582 		case IPPROTO_UDP:	t = "udp6";	break;
583 		case IPPROTO_RAW:	t = "raw6";	break;
584 		default:		t = proto;	break;
585 		}
586 		break;
587 #endif
588 	case PF_LOCAL:
589 		switch (kp->ki_type) {
590 		case SOCK_STREAM:	t = "stream";	break;
591 		case SOCK_DGRAM:	t = "dgram";	break;
592 		case SOCK_RAW:		t = "raw";	break;
593 		case SOCK_RDM:		t = "rdm";	break;
594 		case SOCK_SEQPACKET:	t = "seq";	break;
595 		default:		t = proto;	break;
596 		}
597 		break;
598 	default:
599 		snprintf(proto, sizeof(proto), "%d/%d/%d",
600 			 kp->ki_family, kp->ki_type, kp->ki_protocol);
601 		t = proto;
602 		break;
603 	}
604 
605 	printf("%-6s ", t);
606 
607 /*
608 	if (kp->ki_family == PF_LOCAL) {
609 		if (kp->ki_src.sa_len > 2) {
610 			print_addr(0, kp->ki_type, kp->ki_pflags, &kp->ki_src);
611 			if (kp->ki_dst.sa_family == PF_LOCAL)
612 				printf(" ");
613 		}
614 		if (kp->ki_dst.sa_family == PF_LOCAL)
615 			printf("-> ");
616 	}
617 	else */{
618 		print_addr(21, kp->ki_type, kp->ki_pflags, &kp->ki_src);
619 		printf(" ");
620 	}
621 
622 	if (isconnected(kp))
623 		print_addr(0, kp->ki_type, kp->ki_pflags, &kp->ki_dst);
624 	else if (kp->ki_family == PF_INET
625 #ifdef INET6
626 	    || kp->ki_family == PF_INET6
627 #endif
628 	    )
629 		printf("%-*s", 0, "*.*");
630 	/* else if (kp->ki_src.sa_len == 2)
631 	   printf("%-*s", 0, "-"); */
632 	else
633 		printf("-");
634 
635 	printf("\n");
636 
637 	return (0);
638 }
639 
640 void
641 print_addr(int l, int t, int f, struct sockaddr *sa)
642 {
643 	char sabuf[256], pbuf[32];
644 	int r = 0;
645 
646 	if (!(f & INP_ANONPORT))
647 		f = 0;
648 	else
649 		f = NI_NUMERICSERV;
650 	if (t == SOCK_DGRAM)
651 		f |= NI_DGRAM;
652 	if (nonames)
653 		f |= NI_NUMERICHOST|NI_NUMERICSERV;
654 
655 	getnameinfo(sa, sa->sa_len, sabuf, sizeof(sabuf),
656 		    pbuf, sizeof(pbuf), f);
657 
658 	switch (sa->sa_family) {
659 	case PF_UNSPEC:
660 		r = printf("(PF_UNSPEC)");
661 		break;
662 	case PF_INET: {
663 		struct sockaddr_in *si = satosin(sa);
664 		if (si->sin_addr.s_addr != INADDR_ANY)
665 			r = printf("%s.%s", sabuf, pbuf);
666 		else if (ntohs(si->sin_port) != 0)
667 			r = printf("*.%s", pbuf);
668 		else
669 			r = printf("*.*");
670 		break;
671 	}
672 #ifdef INET6
673 	case PF_INET6: {
674 		struct sockaddr_in6 *si6 = satosin6(sa);
675 		if (!IN6_IS_ADDR_UNSPECIFIED(&si6->sin6_addr))
676 			r = printf("%s.%s", sabuf, pbuf);
677 		else if (ntohs(si6->sin6_port) != 0)
678 			r = printf("*.%s", pbuf);
679 		else
680 			r = printf("*.*");
681 		break;
682 	}
683 #endif
684 	case PF_LOCAL: {
685 		struct sockaddr_un *sun = satosun(sa);
686 		r = printf("%s", sun->sun_path);
687 		if (r == 0)
688 			r = printf("-");
689 		break;
690 	}
691 	default:
692 		break;
693 	}
694 
695 	if (r > 0)
696 		l -= r;
697 	if (l > 0)
698 		printf("%*s", l, "");
699 }
700