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