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