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