Merge from vendor branch FILE:
[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.7 2004/11/13 13:57:36 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 *, int);
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         int     ni_cpuid;               /* cpu id */
109 };
110
111 static struct {
112         struct  netinfo *ni_forw, *ni_prev;
113 } netcb;
114
115 static  int aflag = 0;
116 static  int nflag = 0;
117 static  int lastrow = 1;
118 static int      showcpu;
119
120 void
121 closenetstat(WINDOW *w)
122 {
123         register struct netinfo *p;
124
125         endhostent();
126         endnetent();
127         p = (struct netinfo *)netcb.ni_forw;
128         while (p != (struct netinfo *)&netcb) {
129                 if (p->ni_line != -1)
130                         lastrow--;
131                 p->ni_line = -1;
132                 p = p->ni_forw;
133         }
134         if (w != NULL) {
135                 wclear(w);
136                 wrefresh(w);
137                 delwin(w);
138         }
139 }
140
141 int
142 initnetstat(void)
143 {
144         int ncpu;
145         size_t len;
146
147         len = sizeof(ncpu);
148         if (sysctlbyname("hw.ncpu", &ncpu, &len, NULL, 0) == -1) {
149                 warn("cannot determine number of CPUs, assuming SMP");
150                 showcpu = 1;
151         } else if (ncpu != 1) {
152                 showcpu = 1;
153         }
154         
155         netcb.ni_forw = netcb.ni_prev = (struct netinfo *)&netcb;
156         protos = TCP|UDP;
157         return(1);
158 }
159
160 static void
161 enter_tcp(struct xinpgen *xig, int cpu)
162 {
163         struct xtcpcb *xtcp = (struct xtcpcb *)xig;
164         struct xsocket *xso;
165         int state;
166
167         if (xig->xig_len < sizeof(*xtcp))
168                 return;
169         xso = &xtcp->xt_socket;
170         state = xtcp->xt_tp.t_state;
171         enter(&xtcp->xt_inp, xso, state, "tcp", cpu);
172 }
173
174 static void
175 enter_udp(struct xinpgen *xig, int cpu)
176 {
177         struct xinpcb *xinp = (struct xinpcb *)xig;
178         struct xsocket *xso;
179
180         if (xig->xig_len < sizeof(*xinp))
181                 return;
182         xso = &xinp->xi_socket;
183         enter(&xinp->xi_inp, xso, 0, "udp", cpu);
184 }
185
186 static void
187 fetchnetstat_proto(void (*enter_proto)(struct xinpgen *, int),
188     const char *mibvar)
189 {
190         struct xinpgen *xig, *oxig, *end;
191         char *buf;
192         size_t i;
193         int len;
194
195         if (sysctlbyname(mibvar, 0, &len, 0, 0) < 0) {
196                 if (errno != ENOENT)
197                         warn("sysctl: %s", mibvar);
198                 return;
199         }
200         if ((buf = malloc(len)) == NULL) {
201                 warn("malloc %lu bytes", (u_long)len);
202                 return;
203         }
204         if (sysctlbyname(mibvar, buf, &len, 0, 0) < 0) {
205                 warn("sysctl: %s", mibvar);
206                 free(buf);
207                 return;
208         }
209         oxig = (struct xinpgen *)buf;
210         end = (struct xinpgen *)(buf + len);
211         while (oxig + 1 < end && oxig->xig_len > 0) {
212                 xig = (struct xinpgen *)((char *)oxig + oxig->xig_len);
213                 for (i = 0; i < oxig->xig_count; ++i) {
214                         enter_proto(xig, oxig->xig_cpu);
215                         xig = (void *)((char *)xig + xig->xig_len);
216                 }
217                 oxig = (struct xinpgen *)((char *)xig + xig->xig_len);
218         }
219         free(buf);
220 }
221
222 void
223 fetchnetstat(void)
224 {
225         register struct netinfo *p;
226
227         for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw)
228                 p->ni_seen = 0;
229         if (protos & TCP)
230                 fetchnetstat_proto(enter_tcp, "net.inet.tcp.pcblist");
231         if (protos & UDP)
232                 fetchnetstat_proto(enter_udp, "net.inet.udp.pcblist");
233 }
234
235 static void
236 enter(struct inpcb *inp, struct xsocket *so, int state, const char *proto,
237       int cpu)
238 {
239         register struct netinfo *p;
240
241         if (!aflag && inet_lnaof(inp->inp_laddr) == INADDR_ANY)
242                 return;
243         if (nhosts && !checkhost(inp))
244                 return;
245         if (nports && !checkport(inp))
246                 return;
247         /*
248          * pcblist may return non-ipv4 sockets, but at the moment
249          * -netstat code doesn't support other than ipv4.
250          */
251         if ((inp->inp_vflag & INP_IPV4) == 0)
252                 return;
253         /*
254          * Only take exact matches, any sockets with
255          * previously unbound addresses will be deleted
256          * below in the display routine because they
257          * will appear as ``not seen'' in the kernel
258          * data structures.
259          */
260         for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw) {
261                 if (!streq(proto, p->ni_proto))
262                         continue;
263                 if (p->ni_lport != inp->inp_lport ||
264                     p->ni_laddr.s_addr != inp->inp_laddr.s_addr)
265                         continue;
266                 if (p->ni_faddr.s_addr == inp->inp_faddr.s_addr &&
267                     p->ni_fport == inp->inp_fport)
268                         break;
269         }
270         if (p == (struct netinfo *)&netcb) {
271                 if ((p = malloc(sizeof(*p))) == NULL) {
272                         error("Out of memory");
273                         return;
274                 }
275                 p->ni_prev = (struct netinfo *)&netcb;
276                 p->ni_forw = netcb.ni_forw;
277                 netcb.ni_forw->ni_prev = p;
278                 netcb.ni_forw = p;
279                 p->ni_line = -1;
280                 p->ni_laddr = inp->inp_laddr;
281                 p->ni_lport = inp->inp_lport;
282                 p->ni_faddr = inp->inp_faddr;
283                 p->ni_fport = inp->inp_fport;
284                 p->ni_proto = proto;
285                 p->ni_flags = NIF_LACHG|NIF_FACHG;
286         }
287         p->ni_rcvcc = so->so_rcv.sb_cc;
288         p->ni_sndcc = so->so_snd.sb_cc;
289         p->ni_state = state;
290         p->ni_cpuid = cpu;
291         p->ni_seen = 1;
292 }
293
294 /* column locations */
295 #define LADDR   0
296 #define FADDR   LADDR+22
297 #define CPUID   FADDR+22
298 #define PROTO   CPUID+4
299 #define RCVCC   PROTO+6
300 #define SNDCC   RCVCC+7
301 #define STATE   SNDCC+7
302
303
304 void
305 labelnetstat(void)
306 {
307         wmove(wnd, 0, 0); wclrtobot(wnd);
308         mvwaddstr(wnd, 0, LADDR, "Local Address");
309         mvwaddstr(wnd, 0, FADDR, "Foreign Address");
310         if (showcpu)
311                 mvwaddstr(wnd, 0, CPUID, "Cpu");
312         mvwaddstr(wnd, 0, PROTO, "Proto");
313         mvwaddstr(wnd, 0, RCVCC, "Recv-Q");
314         mvwaddstr(wnd, 0, SNDCC, "Send-Q");
315         mvwaddstr(wnd, 0, STATE, "(state)");
316 }
317
318 void
319 shownetstat(void)
320 {
321         register struct netinfo *p, *q;
322
323         /*
324          * First, delete any connections that have gone
325          * away and adjust the position of connections
326          * below to reflect the deleted line.
327          */
328         p = netcb.ni_forw;
329         while (p != (struct netinfo *)&netcb) {
330                 if (p->ni_line == -1 || p->ni_seen) {
331                         p = p->ni_forw;
332                         continue;
333                 }
334                 wmove(wnd, p->ni_line, 0); wdeleteln(wnd);
335                 q = netcb.ni_forw;
336                 for (; q != (struct netinfo *)&netcb; q = q->ni_forw)
337                         if (q != p && q->ni_line > p->ni_line) {
338                                 q->ni_line--;
339                                 /* this shouldn't be necessary */
340                                 q->ni_flags |= NIF_LACHG|NIF_FACHG;
341                         }
342                 lastrow--;
343                 q = p->ni_forw;
344                 p->ni_prev->ni_forw = p->ni_forw;
345                 p->ni_forw->ni_prev = p->ni_prev;
346                 free(p);
347                 p = q;
348         }
349         /*
350          * Update existing connections and add new ones.
351          */
352         for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw) {
353                 if (p->ni_line == -1) {
354                         /*
355                          * Add a new entry if possible.
356                          */
357                         if (lastrow > YMAX(wnd))
358                                 continue;
359                         p->ni_line = lastrow++;
360                         p->ni_flags |= NIF_LACHG|NIF_FACHG;
361                 }
362                 if (p->ni_flags & NIF_LACHG) {
363                         wmove(wnd, p->ni_line, LADDR);
364                         inetprint(&p->ni_laddr, p->ni_lport, p->ni_proto);
365                         p->ni_flags &= ~NIF_LACHG;
366                 }
367                 if (p->ni_flags & NIF_FACHG) {
368                         wmove(wnd, p->ni_line, FADDR);
369                         inetprint(&p->ni_faddr, p->ni_fport, p->ni_proto);
370                         p->ni_flags &= ~NIF_FACHG;
371                 }
372                 if (showcpu)
373                         mvwprintw(wnd, p->ni_line, CPUID, "%d", p->ni_cpuid);
374                 mvwaddstr(wnd, p->ni_line, PROTO, p->ni_proto);
375                 mvwprintw(wnd, p->ni_line, RCVCC, "%6d", p->ni_rcvcc);
376                 mvwprintw(wnd, p->ni_line, SNDCC, "%6d", p->ni_sndcc);
377                 if (streq(p->ni_proto, "tcp"))
378                         if (p->ni_state < 0 || p->ni_state >= TCP_NSTATES)
379                                 mvwprintw(wnd, p->ni_line, STATE, "%d",
380                                     p->ni_state);
381                         else
382                                 mvwaddstr(wnd, p->ni_line, STATE,
383                                     tcpstates[p->ni_state]);
384                 wclrtoeol(wnd);
385         }
386         if (lastrow < YMAX(wnd)) {
387                 wmove(wnd, lastrow, 0); wclrtobot(wnd);
388                 wmove(wnd, YMAX(wnd), 0); wdeleteln(wnd);       /* XXX */
389         }
390 }
391
392 /*
393  * Pretty print an Internet address (net address + port).
394  * If the nflag was specified, use numbers instead of names.
395  */
396 static void
397 inetprint(register struct in_addr *in, int port, const char *proto)
398 {
399         struct servent *sp = 0;
400         char line[80], *cp;
401
402         snprintf(line, sizeof(line), "%.*s.", 16, inetname(*in));
403         cp = strchr(line, '\0');
404         if (!nflag && port)
405                 sp = getservbyport(port, proto);
406         if (sp || port == 0)
407                 snprintf(cp, sizeof(line) - (cp - line), "%.8s", 
408                     sp ? sp->s_name : "*");
409         else
410                 snprintf(cp, sizeof(line) - (cp - line), "%d", 
411                     ntohs((u_short)port));
412         /* pad to full column to clear any garbage */
413         cp = strchr(line, '\0');
414         while (cp - line < 22)
415                 *cp++ = ' ';
416         line[22] = '\0';
417         waddstr(wnd, line);
418 }
419
420 /*
421  * Construct an Internet address representation.
422  * If the nflag has been supplied, give
423  * numeric value, otherwise try for symbolic name.
424  */
425 static char *
426 inetname(struct in_addr in)
427 {
428         char *cp = 0;
429         static char line[50];
430         struct hostent *hp;
431         struct netent *np;
432
433         if (!nflag && in.s_addr != INADDR_ANY) {
434                 int net = inet_netof(in);
435                 int lna = inet_lnaof(in);
436
437                 if (lna == INADDR_ANY) {
438                         np = getnetbyaddr(net, AF_INET);
439                         if (np)
440                                 cp = np->n_name;
441                 }
442                 if (cp == 0) {
443                         hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
444                         if (hp)
445                                 cp = hp->h_name;
446                 }
447         }
448         if (in.s_addr == INADDR_ANY)
449                 strcpy(line, "*");
450         else if (cp)
451                 snprintf(line, sizeof(line), "%s", cp);
452         else {
453                 in.s_addr = ntohl(in.s_addr);
454 #define C(x)    ((x) & 0xff)
455                 snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in.s_addr >> 24),
456                         C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
457         }
458         return (line);
459 }
460
461 int
462 cmdnetstat(char *cmd, char *args)
463 {
464         register struct netinfo *p;
465
466         if (prefix(cmd, "all")) {
467                 aflag = !aflag;
468                 goto fixup;
469         }
470         if  (prefix(cmd, "numbers") || prefix(cmd, "names")) {
471                 int new;
472
473                 new = prefix(cmd, "numbers");
474                 if (new == nflag)
475                         return (1);
476                 p = netcb.ni_forw;
477                 for (; p != (struct netinfo *)&netcb; p = p->ni_forw) {
478                         if (p->ni_line == -1)
479                                 continue;
480                         p->ni_flags |= NIF_LACHG|NIF_FACHG;
481                 }
482                 nflag = new;
483                 goto redisplay;
484         }
485         if (!netcmd(cmd, args))
486                 return (0);
487 fixup:
488         fetchnetstat();
489 redisplay:
490         shownetstat();
491         refresh();
492         return (1);
493 }