buildworld - Fix breakage
[dragonfly.git] / usr.bin / sockstat / sockstat.c
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  * $DragonFly: src/usr.bin/sockstat/sockstat.c,v 1.7 2007/02/01 10:33:26 corecode Exp $
31  */
32
33 #include <sys/user.h>
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <sys/socketvar.h>
37 #include <sys/sysctl.h>
38 #include <sys/file.h>
39
40 #include <sys/un.h>
41 #include <sys/unpcb.h>
42
43 #include <net/route.h>
44
45 #include <netinet/in.h>
46 #include <netinet/in_pcb.h>
47 #include <netinet/tcp.h>
48 #include <netinet/tcp_seq.h>
49 #include <netinet/tcp_var.h>
50 #include <arpa/inet.h>
51
52 #include <ctype.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <kinfo.h>
56 #include <netdb.h>
57 #include <pwd.h>
58 #include <stdarg.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63
64 static int       opt_4;         /* Show IPv4 sockets */
65 static int       opt_6;         /* Show IPv6 sockets */
66 static int       opt_c;         /* Show connected sockets */
67 static int       opt_l;         /* Show listening sockets */
68 static int       opt_u;         /* Show Unix domain sockets */
69 static int       opt_v;         /* Verbose mode */
70
71 static int      *ports;
72
73 #define INT_BIT (sizeof(int)*CHAR_BIT)
74 #define SET_PORT(p) do { ports[p / INT_BIT] |= 1 << (p % INT_BIT); } while (0)
75 #define CHK_PORT(p) (ports[p / INT_BIT] & (1 << (p % INT_BIT)))
76
77 struct sock {
78         void *socket;
79         void *pcb;
80         int vflag;
81         int family;
82         int proto;
83         const char *protoname;
84         struct sockaddr_storage laddr;
85         struct sockaddr_storage faddr;
86         struct sock *next;
87 };
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, vflag;
193
194         vflag = 0;
195         if (opt_4)
196                 vflag |= INP_IPV4;
197         if (opt_6)
198                 vflag |= INP_IPV6;
199
200         switch (proto) {
201         case IPPROTO_TCP:
202                 varname = "net.inet.tcp.pcblist";
203                 protoname = "tcp";
204                 break;
205         case IPPROTO_UDP:
206                 varname = "net.inet.udp.pcblist";
207                 protoname = "udp";
208                 break;
209         case IPPROTO_DIVERT:
210                 varname = "net.inet.divert.pcblist";
211                 protoname = "div";
212                 break;
213         default:
214                 abort();
215         }
216
217         buf = NULL;
218         len = 0;
219
220         if (sysctlbyname(varname, NULL, &len, NULL, 0)) {
221                 if (errno == ENOENT)
222                         goto out;
223                 err(1, "fetching %s", varname);
224         }
225         if ((buf = malloc(len)) == NULL)
226                 err(1, "malloc()");
227         if (sysctlbyname(varname, buf, &len, NULL, 0)) {
228                 if (errno == ENOENT)
229                         goto out;
230                 err(1, "fetching %s", varname);
231         }
232
233         so_begin = buf;
234         so_end = (uint8_t *)buf + len;
235
236         for (so_begin = buf, so_end = (uint8_t *)so_begin + len;
237              (uint8_t *)so_begin + sizeof(size_t) < (uint8_t *)so_end &&
238              (uint8_t *)so_begin + *(size_t *)so_begin <= (uint8_t *)so_end;
239              so_begin = (uint8_t *)so_begin + *(size_t *)so_begin) {
240                 switch (proto) {
241                 case IPPROTO_TCP:
242                         xtp = (struct xtcpcb *)so_begin;
243                         if (xtp->xt_len != sizeof *xtp) {
244                                 warnx("struct xtcpcb size mismatch");
245                                 goto out;
246                         }
247                         inp = &xtp->xt_inp;
248                         so = &xtp->xt_socket;
249                         break;
250                 case IPPROTO_UDP:
251                 case IPPROTO_DIVERT:
252                         xip = (struct xinpcb *)so_begin;
253                         if (xip->xi_len != sizeof *xip) {
254                                 warnx("struct xinpcb size mismatch");
255                                 goto out;
256                         }
257                         inp = &xip->xi_inp;
258                         so = &xip->xi_socket;
259                         break;
260                 default:
261                         abort();
262                 }
263                 if ((inp->inp_vflag & vflag) == 0)
264                         continue;
265                 if (inp->inp_vflag & INP_IPV4) {
266                         if ((inp->inp_fport == 0 && !opt_l) ||
267                             (inp->inp_fport != 0 && !opt_c))
268                                 continue;
269                 } else if (inp->inp_vflag & INP_IPV6) {
270                         if ((inp->in6p_fport == 0 && !opt_l) ||
271                             (inp->in6p_fport != 0 && !opt_c))
272                                 continue;
273                 } else {
274                         if (opt_v)
275                                 warnx("invalid vflag 0x%x", inp->inp_vflag);
276                         continue;
277                 }
278                 if ((sock = calloc(1, sizeof *sock)) == NULL)
279                         err(1, "malloc()");
280                 sock->socket = so->xso_so;
281                 sock->proto = proto;
282                 if (inp->inp_vflag & INP_IPV4) {
283                         sock->family = AF_INET;
284                         sockaddr(&sock->laddr, sock->family,
285                             &inp->inp_laddr, inp->inp_lport);
286                         sockaddr(&sock->faddr, sock->family,
287                             &inp->inp_faddr, inp->inp_fport);
288                 } else if (inp->inp_vflag & INP_IPV6) {
289                         sock->family = AF_INET6;
290                         sockaddr(&sock->laddr, sock->family,
291                             &inp->in6p_laddr, inp->in6p_lport);
292                         sockaddr(&sock->faddr, sock->family,
293                             &inp->in6p_faddr, inp->in6p_fport);
294                 }
295                 sock->vflag = inp->inp_vflag;
296                 sock->protoname = protoname;
297                 hash = (int)((uintptr_t)sock->socket % HASHSIZE);
298                 sock->next = sockhash[hash];
299                 sockhash[hash] = sock;
300         }
301 out:
302         free(buf);
303 }
304
305 static void
306 gather_unix(int proto)
307 {
308         void *so_begin, *so_end;
309         struct xunpcb *xup;
310         struct sock *sock;
311         const char *varname, *protoname;
312         size_t len;
313         void *buf;
314         int hash;
315
316         switch (proto) {
317         case SOCK_STREAM:
318                 varname = "net.local.stream.pcblist";
319                 protoname = "stream";
320                 break;
321         case SOCK_DGRAM:
322                 varname = "net.local.dgram.pcblist";
323                 protoname = "dgram";
324                 break;
325         default:
326                 abort();
327         }
328
329         buf = NULL;
330         len = 0;
331
332         if (sysctlbyname(varname, NULL, &len, NULL, 0))
333                 err(1, "fetching %s", varname);
334
335         if ((buf = malloc(len)) == NULL)
336                 err(1, "malloc()");
337         if (sysctlbyname(varname, buf, &len, NULL, 0))
338                 err(1, "fetching %s", varname);
339
340         for (so_begin = buf, so_end = (uint8_t *)buf + len;
341              (uint8_t *)so_begin + sizeof(size_t) < (uint8_t *)so_end &&
342              (uint8_t *)so_begin + *(size_t *)so_begin <= (uint8_t *)so_end;
343              so_begin = (uint8_t *)so_begin + *(size_t *)so_begin) {
344                 xup = so_begin;
345                 if (xup->xu_len != sizeof *xup) {
346                         warnx("struct xunpcb size mismatch");
347                         goto out;
348                 }
349                 if ((xup->xu_unp.unp_conn == NULL && !opt_l) ||
350                     (xup->xu_unp.unp_conn != NULL && !opt_c))
351                         continue;
352                 if ((sock = calloc(1, sizeof *sock)) == NULL)
353                         err(1, "malloc()");
354                 sock->socket = xup->xu_socket.xso_so;
355                 sock->pcb = xup->xu_unpp;
356                 sock->proto = proto;
357                 sock->family = AF_UNIX;
358                 sock->protoname = protoname;
359                 if (xup->xu_unp.unp_addr != NULL)
360                         sock->laddr =
361                             *(struct sockaddr_storage *)(void *)&xup->xu_addr;
362                 else if (xup->xu_unp.unp_conn != NULL)
363                         *(void **)&sock->faddr = xup->xu_unp.unp_conn;
364                 hash = (int)((uintptr_t)sock->socket % HASHSIZE);
365                 sock->next = sockhash[hash];
366                 sockhash[hash] = sock;
367         }
368 out:
369         free(buf);
370 }
371
372 static void
373 getfiles(void)
374 {
375         if (kinfo_get_files(&xfiles, &nxfiles))
376                 err(1, "kinfo_get_files");
377 }
378
379 static int
380 printaddr(int af, struct sockaddr_storage *ss)
381 {
382         char addrstr[INET6_ADDRSTRLEN] = { '\0', '\0' };
383         struct sockaddr_un *sun;
384         void *addr;
385         int off, port;
386
387         switch (af) {
388         case AF_INET:
389                 addr = &((struct sockaddr_in *)ss)->sin_addr;
390                 if (inet_lnaof(*(struct in_addr *)addr) == INADDR_ANY)
391                         addrstr[0] = '*';
392                 port = ntohs(((struct sockaddr_in *)ss)->sin_port);
393                 break;
394         case AF_INET6:
395                 addr = &((struct sockaddr_in6 *)ss)->sin6_addr;
396                 if (IN6_IS_ADDR_UNSPECIFIED((struct in6_addr *)addr))
397                         addrstr[0] = '*';
398                 port = ntohs(((struct sockaddr_in6 *)ss)->sin6_port);
399                 break;
400         case AF_UNIX:
401                 sun = (struct sockaddr_un *)ss;
402                 off = (int)((char *)&sun->sun_path - (char *)sun);
403                 return (xprintf("%.*s", sun->sun_len - off, sun->sun_path));
404         default:
405                 abort();
406         }
407         if (addrstr[0] == '\0')
408                 inet_ntop(af, addr, addrstr, sizeof addrstr);
409         if (port == 0)
410                 return xprintf("%s:*", addrstr);
411         else
412                 return xprintf("%s:%d", addrstr, port);
413 }
414
415 static const char *
416 getprocname(pid_t pid)
417 {
418         static struct kinfo_proc proc;
419         size_t len;
420         int mib[4];
421
422         mib[0] = CTL_KERN;
423         mib[1] = KERN_PROC;
424         mib[2] = KERN_PROC_PID;
425         mib[3] = (int)pid;
426         len = sizeof proc;
427         if (sysctl(mib, 4, &proc, &len, NULL, 0) == -1) {
428                 warn("sysctl()");
429                 return ("??");
430         }
431         return (proc.kp_comm);
432 }
433
434 static int
435 check_ports(struct sock *s)
436 {
437         int port;
438
439         if (ports == NULL)
440                 return (1);
441         if ((s->family != AF_INET) && (s->family != AF_INET6))
442                 return (1);
443         if (s->family == AF_INET)
444                 port = ntohs(((struct sockaddr_in *)(&s->laddr))->sin_port);
445         else
446                 port = ntohs(((struct sockaddr_in6 *)(&s->laddr))->sin6_port);
447         if (CHK_PORT(port))
448                 return (1);
449         if (s->family == AF_INET)
450                 port = ntohs(((struct sockaddr_in *)(&s->faddr))->sin_port);
451         else
452                 port = ntohs(((struct sockaddr_in6 *)(&s->faddr))->sin6_port);
453         if (CHK_PORT(port))
454                 return (1);
455         return (0);
456 }
457
458 static void
459 display(void)
460 {
461         struct passwd *pwd;
462         struct kinfo_file *xf;
463         struct sock *s;
464         void *p;
465         int hash, n, pos;
466
467         printf("%-8s %-10s %-5s %-2s %-6s %-21s %-21s\n",
468             "USER", "COMMAND", "PID", "FD", "PROTO",
469             "LOCAL ADDRESS", "FOREIGN ADDRESS");
470         setpassent(1);
471         for (xf = xfiles, n = 0; n < nxfiles; ++n, ++xf) {
472                 if (xf->f_data == NULL)
473                         continue;
474                 hash = (int)((uintptr_t)xf->f_data % HASHSIZE);
475                 for (s = sockhash[hash]; s != NULL; s = s->next)
476                         if ((void *)s->socket == xf->f_data)
477                                 break;
478                 if (s == NULL)
479                         continue;
480                 if (!check_ports(s))
481                         continue;
482                 pos = 0;
483                 if ((pwd = getpwuid(xf->f_uid)) == NULL)
484                         pos += xprintf("%lu", (u_long)xf->f_uid);
485                 else
486                         pos += xprintf("%s", pwd->pw_name);
487                 while (pos < 9)
488                         pos += xprintf(" ");
489                 pos += xprintf("%.10s", getprocname(xf->f_pid));
490                 while (pos < 20)
491                         pos += xprintf(" ");
492                 pos += xprintf("%lu", (u_long)xf->f_pid);
493                 while (pos < 26)
494                         pos += xprintf(" ");
495                 pos += xprintf("%d", xf->f_fd);
496                 while (pos < 29)
497                         pos += xprintf(" ");
498                 pos += xprintf("%s", s->protoname);
499                 if (s->vflag & INP_IPV4)
500                         pos += xprintf("4");
501                 if (s->vflag & INP_IPV6)
502                         pos += xprintf("6");
503                 while (pos < 36)
504                         pos += xprintf(" ");
505                 switch (s->family) {
506                 case AF_INET:
507                 case AF_INET6:
508                         pos += printaddr(s->family, &s->laddr);
509                         while (pos < 57)
510                                 pos += xprintf(" ");
511                         pos += xprintf(" ");
512                         pos += printaddr(s->family, &s->faddr);
513                         break;
514                 case AF_UNIX:
515                         /* server */
516                         if (s->laddr.ss_len > 0) {
517                                 pos += printaddr(s->family, &s->laddr);
518                                 break;
519                         }
520                         /* client */
521                         p = *(void **)&s->faddr;
522                         if (p == NULL) {
523                                 pos += xprintf("(not connected)");
524                                 break;
525                         }
526                         pos += xprintf("-> ");
527                         for (hash = 0; hash < HASHSIZE; ++hash) {
528                                 for (s = sockhash[hash]; s != NULL; s = s->next)
529                                         if (s->pcb == p)
530                                                 break;
531                                 if (s != NULL)
532                                         break;
533                         }
534                         if (s == NULL || s->laddr.ss_len == 0)
535                                 pos += xprintf("??");
536                         else
537                                 pos += printaddr(s->family, &s->laddr);
538                         break;
539                 default:
540                         abort();
541                 }
542                 xprintf("\n");
543         }
544 }
545
546 static void
547 usage(void)
548 {
549         fprintf(stderr, "Usage: sockstat [-46clu] [-p ports]\n");
550         exit(1);
551 }
552
553 int
554 main(int argc, char *argv[])
555 {
556         int o;
557
558         while ((o = getopt(argc, argv, "46clp:uv")) != -1)
559                 switch (o) {
560                 case '4':
561                         opt_4 = 1;
562                         break;
563                 case '6':
564                         opt_6 = 1;
565                         break;
566                 case 'c':
567                         opt_c = 1;
568                         break;
569                 case 'l':
570                         opt_l = 1;
571                         break;
572                 case 'p':
573                         parse_ports(optarg);
574                         break;
575                 case 'u':
576                         opt_u = 1;
577                         break;
578                 case 'v':
579                         ++opt_v;
580                         break;
581                 default:
582                         usage();
583                 }
584
585         argc -= optind;
586         argv += optind;
587
588         if (argc > 0)
589                 usage();
590
591         if (!opt_4 && !opt_6 && !opt_u)
592                 opt_4 = opt_6 = opt_u = 1;
593         if (!opt_c && !opt_l)
594                 opt_c = opt_l = 1;
595
596         if (opt_4 || opt_6) {
597                 gather_inet(IPPROTO_TCP);
598                 gather_inet(IPPROTO_UDP);
599                 gather_inet(IPPROTO_DIVERT);
600         }
601         if (opt_u) {
602                 gather_unix(SOCK_STREAM);
603                 gather_unix(SOCK_DGRAM);
604         }
605         getfiles();
606         display();
607
608         exit(0);
609 }