Correct BSD License clause numbering from 1-2-4 to 1-2-3.
[dragonfly.git] / usr.bin / systat / netstat.c
1 /*-
2  * Copyright (c) 1980, 1992, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#)netstat.c        8.1 (Berkeley) 6/6/93
30  * $FreeBSD: src/usr.bin/systat/netstat.c,v 1.13 1999/08/30 08:18:08 peter Exp $
31  */
32
33 /*
34  * netstat
35  */
36 #include <sys/param.h>
37 #include <sys/queue.h>
38 #include <sys/socket.h>
39 #include <sys/socketvar.h>
40 #include <sys/protosw.h>
41 #include <sys/sysctl.h>
42
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <net/route.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
48 #ifdef INET6
49 #include <netinet/ip6.h>
50 #endif
51 #include <netinet/in_pcb.h>
52 #include <netinet/ip_icmp.h>
53 #include <netinet/icmp_var.h>
54 #include <netinet/ip_var.h>
55 #include <netinet/tcp.h>
56 #include <netinet/tcpip.h>
57 #include <netinet/tcp_seq.h>
58 #define TCPSTATES
59 #include <netinet/tcp_fsm.h>
60 #include <netinet/tcp_timer.h>
61 #include <netinet/tcp_var.h>
62 #include <netinet/tcp_debug.h>
63 #include <netinet/udp.h>
64 #include <netinet/udp_var.h>
65
66 #include <err.h>
67 #include <errno.h>
68 #include <netdb.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <nlist.h>
72 #include <paths.h>
73 #include "systat.h"
74 #include "extern.h"
75
76 static void enter(struct inpcb *, struct xsocket *, int, const char *);
77 static char *inetname(struct in_addr);
78 static void inetprint(struct in_addr *, int, const char *);
79
80 #define streq(a,b)      (strcmp(a,b)==0)
81 #define YMAX(w)         ((w)->_maxy-1)
82
83 WINDOW *
84 opennetstat(void)
85 {
86         sethostent(1);
87         setnetent(1);
88         return (subwin(stdscr, LINES-5-1, 0, 5, 0));
89 }
90
91 struct netinfo {
92         struct  netinfo *ni_forw, *ni_prev;
93         short   ni_line;                /* line on screen */
94         short   ni_seen;                /* 0 when not present in list */
95         short   ni_flags;
96 #define NIF_LACHG       0x1             /* local address changed */
97 #define NIF_FACHG       0x2             /* foreign address changed */
98         short   ni_state;               /* tcp state */
99         const char *ni_proto;           /* protocol */
100         struct  in_addr ni_laddr;       /* local address */
101         long    ni_lport;               /* local port */
102         struct  in_addr ni_faddr;       /* foreign address */
103         long    ni_fport;               /* foreign port */
104         long    ni_rcvcc;               /* rcv buffer character count */
105         long    ni_sndcc;               /* snd buffer character count */
106 };
107
108 static struct {
109         struct  netinfo *ni_forw, *ni_prev;
110 } netcb;
111
112 static  int aflag = 0;
113 static  int nflag = 0;
114 static  int lastrow = 1;
115
116 void
117 closenetstat(WINDOW *w)
118 {
119         struct netinfo *p;
120
121         endhostent();
122         endnetent();
123         p = (struct netinfo *)netcb.ni_forw;
124         while (p != (struct netinfo *)&netcb) {
125                 if (p->ni_line != -1)
126                         lastrow--;
127                 p->ni_line = -1;
128                 p = p->ni_forw;
129         }
130         if (w != NULL) {
131                 wclear(w);
132                 wrefresh(w);
133                 delwin(w);
134         }
135 }
136
137 int
138 initnetstat(void)
139 {
140         netcb.ni_forw = netcb.ni_prev = (struct netinfo *)&netcb;
141         protos = TCP|UDP;
142         return(1);
143 }
144
145 static void
146 enter_tcp(void *xig)
147 {
148         struct xtcpcb *xtcp = (struct xtcpcb *)xig;
149         struct xsocket *xso;
150         int state;
151
152         if (xtcp->xt_len < sizeof(*xtcp))
153                 return;
154         xso = &xtcp->xt_socket;
155         state = xtcp->xt_tp.t_state;
156         enter(&xtcp->xt_inp, xso, state, "tcp");
157 }
158
159 static void
160 enter_udp(void *xig)
161 {
162         struct xinpcb *xinp = (struct xinpcb *)xig;
163         struct xsocket *xso;
164
165         if (xinp->xi_len < sizeof(*xinp))
166                 return;
167         xso = &xinp->xi_socket;
168         enter(&xinp->xi_inp, xso, 0, "udp");
169 }
170
171 static void
172 fetchnetstat_proto(void (*enter_proto)(void *),
173     const char *mibvar)
174 {
175         char *buf, *buf2;
176         size_t i, len, elem_len;
177
178         if (sysctlbyname(mibvar, 0, &len, 0, 0) < 0) {
179                 if (errno != ENOENT)
180                         warn("sysctl: %s", mibvar);
181                 return;
182         }
183         if ((buf = malloc(len)) == NULL) {
184                 warn("malloc %lu bytes", (u_long)len);
185                 return;
186         }
187         if (sysctlbyname(mibvar, buf, &len, 0, 0) < 0) {
188                 warn("sysctl: %s", mibvar);
189                 free(buf);
190                 return;
191         }
192
193         /*
194          * XXX this is better with a single PCB type
195          */
196         if (len == 0) {
197                 free(buf);
198                 return;
199         }
200         if (len < sizeof(size_t)) {
201                 warnx("sysctl: short read");
202                 free(buf);
203                 return;
204         }
205         elem_len = *(size_t *)buf;
206         len /= elem_len;
207         buf2 = buf;
208         for (i = 0; i < len; i++, buf2 += elem_len) {
209                 if (*(size_t *)(buf2) != elem_len) {
210                         warn("sysctl: inconsistent PCB len");
211                         free(buf);
212                         return;
213                 }
214                 enter_proto(buf2);
215         }
216         free(buf);
217 }
218
219 void
220 fetchnetstat(void)
221 {
222         struct netinfo *p;
223
224         for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw)
225                 p->ni_seen = 0;
226         if (protos & TCP)
227                 fetchnetstat_proto(enter_tcp, "net.inet.tcp.pcblist");
228         if (protos & UDP)
229                 fetchnetstat_proto(enter_udp, "net.inet.udp.pcblist");
230 }
231
232 static void
233 enter(struct inpcb *inp, struct xsocket *so, int state, const char *proto)
234 {
235         struct netinfo *p;
236
237         if (!aflag && inet_lnaof(inp->inp_laddr) == INADDR_ANY)
238                 return;
239         if (nhosts && !checkhost(inp))
240                 return;
241         if (nports && !checkport(inp))
242                 return;
243         /*
244          * pcblist may return non-ipv4 sockets, but at the moment
245          * -netstat code doesn't support other than ipv4.
246          */
247         if ((inp->inp_vflag & INP_IPV4) == 0)
248                 return;
249         /*
250          * Only take exact matches, any sockets with
251          * previously unbound addresses will be deleted
252          * below in the display routine because they
253          * will appear as ``not seen'' in the kernel
254          * data structures.
255          */
256         for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw) {
257                 if (!streq(proto, p->ni_proto))
258                         continue;
259                 if (p->ni_lport != inp->inp_lport ||
260                     p->ni_laddr.s_addr != inp->inp_laddr.s_addr)
261                         continue;
262                 if (p->ni_faddr.s_addr == inp->inp_faddr.s_addr &&
263                     p->ni_fport == inp->inp_fport)
264                         break;
265         }
266         if (p == (struct netinfo *)&netcb) {
267                 if ((p = malloc(sizeof(*p))) == NULL) {
268                         error("Out of memory");
269                         return;
270                 }
271                 p->ni_prev = (struct netinfo *)&netcb;
272                 p->ni_forw = netcb.ni_forw;
273                 netcb.ni_forw->ni_prev = p;
274                 netcb.ni_forw = p;
275                 p->ni_line = -1;
276                 p->ni_laddr = inp->inp_laddr;
277                 p->ni_lport = inp->inp_lport;
278                 p->ni_faddr = inp->inp_faddr;
279                 p->ni_fport = inp->inp_fport;
280                 p->ni_proto = proto;
281                 p->ni_flags = NIF_LACHG|NIF_FACHG;
282         }
283         p->ni_rcvcc = so->so_rcv.sb_cc;
284         p->ni_sndcc = so->so_snd.sb_cc;
285         p->ni_state = state;
286         p->ni_seen = 1;
287 }
288
289 /* column locations */
290 #define LADDR   0
291 #define FADDR   LADDR+22
292 #define CPUID   FADDR+22
293 #define PROTO   CPUID+4
294 #define RCVCC   PROTO+6
295 #define SNDCC   RCVCC+7
296 #define STATE   SNDCC+7
297
298
299 void
300 labelnetstat(void)
301 {
302         wmove(wnd, 0, 0); wclrtobot(wnd);
303         mvwaddstr(wnd, 0, LADDR, "Local Address");
304         mvwaddstr(wnd, 0, FADDR, "Foreign Address");
305         mvwaddstr(wnd, 0, PROTO, "Proto");
306         mvwaddstr(wnd, 0, RCVCC, "Recv-Q");
307         mvwaddstr(wnd, 0, SNDCC, "Send-Q");
308         mvwaddstr(wnd, 0, STATE, "(state)");
309 }
310
311 void
312 shownetstat(void)
313 {
314         struct netinfo *p, *q;
315
316         /*
317          * First, delete any connections that have gone
318          * away and adjust the position of connections
319          * below to reflect the deleted line.
320          */
321         p = netcb.ni_forw;
322         while (p != (struct netinfo *)&netcb) {
323                 if (p->ni_line == -1 || p->ni_seen) {
324                         p = p->ni_forw;
325                         continue;
326                 }
327                 wmove(wnd, p->ni_line, 0); wdeleteln(wnd);
328                 q = netcb.ni_forw;
329                 for (; q != (struct netinfo *)&netcb; q = q->ni_forw)
330                         if (q != p && q->ni_line > p->ni_line) {
331                                 q->ni_line--;
332                                 /* this shouldn't be necessary */
333                                 q->ni_flags |= NIF_LACHG|NIF_FACHG;
334                         }
335                 lastrow--;
336                 q = p->ni_forw;
337                 p->ni_prev->ni_forw = p->ni_forw;
338                 p->ni_forw->ni_prev = p->ni_prev;
339                 free(p);
340                 p = q;
341         }
342         /*
343          * Update existing connections and add new ones.
344          */
345         for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw) {
346                 if (p->ni_line == -1) {
347                         /*
348                          * Add a new entry if possible.
349                          */
350                         if (lastrow > YMAX(wnd))
351                                 continue;
352                         p->ni_line = lastrow++;
353                         p->ni_flags |= NIF_LACHG|NIF_FACHG;
354                 }
355                 if (p->ni_flags & NIF_LACHG) {
356                         wmove(wnd, p->ni_line, LADDR);
357                         inetprint(&p->ni_laddr, p->ni_lport, p->ni_proto);
358                         p->ni_flags &= ~NIF_LACHG;
359                 }
360                 if (p->ni_flags & NIF_FACHG) {
361                         wmove(wnd, p->ni_line, FADDR);
362                         inetprint(&p->ni_faddr, p->ni_fport, p->ni_proto);
363                         p->ni_flags &= ~NIF_FACHG;
364                 }
365                 mvwaddstr(wnd, p->ni_line, PROTO, p->ni_proto);
366                 mvwprintw(wnd, p->ni_line, RCVCC, "%6d", p->ni_rcvcc);
367                 mvwprintw(wnd, p->ni_line, SNDCC, "%6d", p->ni_sndcc);
368                 if (streq(p->ni_proto, "tcp")) {
369                         if (p->ni_state < 0 || p->ni_state >= TCP_NSTATES)
370                                 mvwprintw(wnd, p->ni_line, STATE, "%d",
371                                     p->ni_state);
372                         else
373                                 mvwaddstr(wnd, p->ni_line, STATE,
374                                     tcpstates[p->ni_state]);
375                 }
376                 wclrtoeol(wnd);
377         }
378         if (lastrow < YMAX(wnd)) {
379                 wmove(wnd, lastrow, 0); wclrtobot(wnd);
380                 wmove(wnd, YMAX(wnd), 0); wdeleteln(wnd);       /* XXX */
381         }
382 }
383
384 /*
385  * Pretty print an Internet address (net address + port).
386  * If the nflag was specified, use numbers instead of names.
387  */
388 static void
389 inetprint(struct in_addr *in, int port, const char *proto)
390 {
391         struct servent *sp = NULL;
392         char line[80], *cp;
393
394         snprintf(line, sizeof(line), "%.*s.", 16, inetname(*in));
395         cp = strchr(line, '\0');
396         if (!nflag && port)
397                 sp = getservbyport(port, proto);
398         if (sp || port == 0)
399                 snprintf(cp, sizeof(line) - (cp - line), "%.8s", 
400                     sp ? sp->s_name : "*");
401         else
402                 snprintf(cp, sizeof(line) - (cp - line), "%d", 
403                     ntohs((u_short)port));
404         /* pad to full column to clear any garbage */
405         cp = strchr(line, '\0');
406         while (cp - line < 22)
407                 *cp++ = ' ';
408         line[22] = '\0';
409         waddstr(wnd, line);
410 }
411
412 /*
413  * Construct an Internet address representation.
414  * If the nflag has been supplied, give
415  * numeric value, otherwise try for symbolic name.
416  */
417 static char *
418 inetname(struct in_addr in)
419 {
420         char *cp = NULL;
421         static char line[50];
422         struct hostent *hp;
423         struct netent *np;
424
425         if (!nflag && in.s_addr != INADDR_ANY) {
426                 int net = inet_netof(in);
427                 int lna = inet_lnaof(in);
428
429                 if (lna == INADDR_ANY) {
430                         np = getnetbyaddr(net, AF_INET);
431                         if (np)
432                                 cp = np->n_name;
433                 }
434                 if (cp == NULL) {
435                         hp = gethostbyaddr(&in, sizeof (in), AF_INET);
436                         if (hp)
437                                 cp = hp->h_name;
438                 }
439         }
440         if (in.s_addr == INADDR_ANY)
441                 strcpy(line, "*");
442         else if (cp)
443                 snprintf(line, sizeof(line), "%s", cp);
444         else {
445                 in.s_addr = ntohl(in.s_addr);
446 #define C(x)    ((x) & 0xff)
447                 snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in.s_addr >> 24),
448                         C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
449         }
450         return (line);
451 }
452
453 int
454 cmdnetstat(const char *cmd, char *args)
455 {
456         struct netinfo *p;
457
458         if (prefix(cmd, "all")) {
459                 aflag = !aflag;
460                 goto fixup;
461         }
462         if  (prefix(cmd, "numbers") || prefix(cmd, "names")) {
463                 int new;
464
465                 new = prefix(cmd, "numbers");
466                 if (new == nflag)
467                         return (1);
468                 p = netcb.ni_forw;
469                 for (; p != (struct netinfo *)&netcb; p = p->ni_forw) {
470                         if (p->ni_line == -1)
471                                 continue;
472                         p->ni_flags |= NIF_LACHG|NIF_FACHG;
473                 }
474                 nflag = new;
475                 goto redisplay;
476         }
477         if (!netcmd(cmd, args))
478                 return (0);
479 fixup:
480         fetchnetstat();
481 redisplay:
482         shownetstat();
483         refresh();
484         return (1);
485 }