xref: /dragonfly/usr.bin/systat/netstat.c (revision 36a3d1d6)
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.11 2008/11/10 04:59:45 swildner 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 #ifdef INET6
54 #include <netinet/ip6.h>
55 #endif
56 #include <netinet/in_pcb.h>
57 #include <netinet/ip_icmp.h>
58 #include <netinet/icmp_var.h>
59 #include <netinet/ip_var.h>
60 #include <netinet/tcp.h>
61 #include <netinet/tcpip.h>
62 #include <netinet/tcp_seq.h>
63 #define TCPSTATES
64 #include <netinet/tcp_fsm.h>
65 #include <netinet/tcp_timer.h>
66 #include <netinet/tcp_var.h>
67 #include <netinet/tcp_debug.h>
68 #include <netinet/udp.h>
69 #include <netinet/udp_var.h>
70 
71 #include <err.h>
72 #include <errno.h>
73 #include <netdb.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <nlist.h>
77 #include <paths.h>
78 #include "systat.h"
79 #include "extern.h"
80 
81 static void enter(struct inpcb *, struct xsocket *, int, const char *);
82 static char *inetname(struct in_addr);
83 static void inetprint(struct in_addr *, int, const char *);
84 
85 #define	streq(a,b)	(strcmp(a,b)==0)
86 #define	YMAX(w)		((w)->_maxy-1)
87 
88 WINDOW *
89 opennetstat(void)
90 {
91 	sethostent(1);
92 	setnetent(1);
93 	return (subwin(stdscr, LINES-5-1, 0, 5, 0));
94 }
95 
96 struct netinfo {
97 	struct	netinfo *ni_forw, *ni_prev;
98 	short	ni_line;		/* line on screen */
99 	short	ni_seen;		/* 0 when not present in list */
100 	short	ni_flags;
101 #define	NIF_LACHG	0x1		/* local address changed */
102 #define	NIF_FACHG	0x2		/* foreign address changed */
103 	short	ni_state;		/* tcp state */
104 	const char *ni_proto;		/* protocol */
105 	struct	in_addr ni_laddr;	/* local address */
106 	long	ni_lport;		/* local port */
107 	struct	in_addr	ni_faddr;	/* foreign address */
108 	long	ni_fport;		/* foreign port */
109 	long	ni_rcvcc;		/* rcv buffer character count */
110 	long	ni_sndcc;		/* snd buffer character count */
111 };
112 
113 static struct {
114 	struct	netinfo *ni_forw, *ni_prev;
115 } netcb;
116 
117 static	int aflag = 0;
118 static	int nflag = 0;
119 static	int lastrow = 1;
120 
121 void
122 closenetstat(WINDOW *w)
123 {
124 	struct netinfo *p;
125 
126 	endhostent();
127 	endnetent();
128 	p = (struct netinfo *)netcb.ni_forw;
129 	while (p != (struct netinfo *)&netcb) {
130 		if (p->ni_line != -1)
131 			lastrow--;
132 		p->ni_line = -1;
133 		p = p->ni_forw;
134 	}
135         if (w != NULL) {
136 		wclear(w);
137 		wrefresh(w);
138 		delwin(w);
139 	}
140 }
141 
142 int
143 initnetstat(void)
144 {
145 	netcb.ni_forw = netcb.ni_prev = (struct netinfo *)&netcb;
146 	protos = TCP|UDP;
147 	return(1);
148 }
149 
150 static void
151 enter_tcp(void *xig)
152 {
153 	struct xtcpcb *xtcp = (struct xtcpcb *)xig;
154 	struct xsocket *xso;
155 	int state;
156 
157 	if (xtcp->xt_len < sizeof(*xtcp))
158 		return;
159 	xso = &xtcp->xt_socket;
160 	state = xtcp->xt_tp.t_state;
161 	enter(&xtcp->xt_inp, xso, state, "tcp");
162 }
163 
164 static void
165 enter_udp(void *xig)
166 {
167 	struct xinpcb *xinp = (struct xinpcb *)xig;
168 	struct xsocket *xso;
169 
170 	if (xinp->xi_len < sizeof(*xinp))
171 		return;
172 	xso = &xinp->xi_socket;
173 	enter(&xinp->xi_inp, xso, 0, "udp");
174 }
175 
176 static void
177 fetchnetstat_proto(void (*enter_proto)(void *),
178     const char *mibvar)
179 {
180 	char *buf, *buf2;
181 	size_t i, len, elem_len;
182 
183 	if (sysctlbyname(mibvar, 0, &len, 0, 0) < 0) {
184 		if (errno != ENOENT)
185 			warn("sysctl: %s", mibvar);
186 		return;
187 	}
188 	if ((buf = malloc(len)) == NULL) {
189 		warn("malloc %lu bytes", (u_long)len);
190 		return;
191 	}
192 	if (sysctlbyname(mibvar, buf, &len, 0, 0) < 0) {
193 		warn("sysctl: %s", mibvar);
194 		free(buf);
195 		return;
196 	}
197 
198 	/*
199 	 * XXX this is better with a single PCB type
200 	 */
201 	if (len == 0) {
202 		free(buf);
203 		return;
204 	}
205 	if (len < sizeof(size_t)) {
206 		warnx("sysctl: short read");
207 		free(buf);
208 		return;
209 	}
210 	elem_len = *(size_t *)buf;
211 	len /= elem_len;
212 	buf2 = buf;
213 	for (i = 0; i < len; i++, buf2 += elem_len) {
214 		if (*(size_t *)(buf2) != elem_len) {
215 			warn("sysctl: inconsistent PCB len");
216 			free(buf);
217 			return;
218 		}
219 		enter_proto(buf2);
220 	}
221 	free(buf);
222 }
223 
224 void
225 fetchnetstat(void)
226 {
227 	struct netinfo *p;
228 
229 	for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw)
230 		p->ni_seen = 0;
231 	if (protos & TCP)
232 		fetchnetstat_proto(enter_tcp, "net.inet.tcp.pcblist");
233 	if (protos & UDP)
234 		fetchnetstat_proto(enter_udp, "net.inet.udp.pcblist");
235 }
236 
237 static void
238 enter(struct inpcb *inp, struct xsocket *so, int state, const char *proto)
239 {
240 	struct netinfo *p;
241 
242 	if (!aflag && inet_lnaof(inp->inp_laddr) == INADDR_ANY)
243 		return;
244 	if (nhosts && !checkhost(inp))
245 		return;
246 	if (nports && !checkport(inp))
247 		return;
248 	/*
249 	 * pcblist may return non-ipv4 sockets, but at the moment
250 	 * -netstat code doesn't support other than ipv4.
251 	 */
252 	if ((inp->inp_vflag & INP_IPV4) == 0)
253 		return;
254 	/*
255 	 * Only take exact matches, any sockets with
256 	 * previously unbound addresses will be deleted
257 	 * below in the display routine because they
258 	 * will appear as ``not seen'' in the kernel
259 	 * data structures.
260 	 */
261 	for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw) {
262 		if (!streq(proto, p->ni_proto))
263 			continue;
264 		if (p->ni_lport != inp->inp_lport ||
265 		    p->ni_laddr.s_addr != inp->inp_laddr.s_addr)
266 			continue;
267 		if (p->ni_faddr.s_addr == inp->inp_faddr.s_addr &&
268 		    p->ni_fport == inp->inp_fport)
269 			break;
270 	}
271 	if (p == (struct netinfo *)&netcb) {
272 		if ((p = malloc(sizeof(*p))) == NULL) {
273 			error("Out of memory");
274 			return;
275 		}
276 		p->ni_prev = (struct netinfo *)&netcb;
277 		p->ni_forw = netcb.ni_forw;
278 		netcb.ni_forw->ni_prev = p;
279 		netcb.ni_forw = p;
280 		p->ni_line = -1;
281 		p->ni_laddr = inp->inp_laddr;
282 		p->ni_lport = inp->inp_lport;
283 		p->ni_faddr = inp->inp_faddr;
284 		p->ni_fport = inp->inp_fport;
285 		p->ni_proto = proto;
286 		p->ni_flags = NIF_LACHG|NIF_FACHG;
287 	}
288 	p->ni_rcvcc = so->so_rcv.sb_cc;
289 	p->ni_sndcc = so->so_snd.sb_cc;
290 	p->ni_state = state;
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 	mvwaddstr(wnd, 0, PROTO, "Proto");
311 	mvwaddstr(wnd, 0, RCVCC, "Recv-Q");
312 	mvwaddstr(wnd, 0, SNDCC, "Send-Q");
313 	mvwaddstr(wnd, 0, STATE, "(state)");
314 }
315 
316 void
317 shownetstat(void)
318 {
319 	struct netinfo *p, *q;
320 
321 	/*
322 	 * First, delete any connections that have gone
323 	 * away and adjust the position of connections
324 	 * below to reflect the deleted line.
325 	 */
326 	p = netcb.ni_forw;
327 	while (p != (struct netinfo *)&netcb) {
328 		if (p->ni_line == -1 || p->ni_seen) {
329 			p = p->ni_forw;
330 			continue;
331 		}
332 		wmove(wnd, p->ni_line, 0); wdeleteln(wnd);
333 		q = netcb.ni_forw;
334 		for (; q != (struct netinfo *)&netcb; q = q->ni_forw)
335 			if (q != p && q->ni_line > p->ni_line) {
336 				q->ni_line--;
337 				/* this shouldn't be necessary */
338 				q->ni_flags |= NIF_LACHG|NIF_FACHG;
339 			}
340 		lastrow--;
341 		q = p->ni_forw;
342 		p->ni_prev->ni_forw = p->ni_forw;
343 		p->ni_forw->ni_prev = p->ni_prev;
344 		free(p);
345 		p = q;
346 	}
347 	/*
348 	 * Update existing connections and add new ones.
349 	 */
350 	for (p = netcb.ni_forw; p != (struct netinfo *)&netcb; p = p->ni_forw) {
351 		if (p->ni_line == -1) {
352 			/*
353 			 * Add a new entry if possible.
354 			 */
355 			if (lastrow > YMAX(wnd))
356 				continue;
357 			p->ni_line = lastrow++;
358 			p->ni_flags |= NIF_LACHG|NIF_FACHG;
359 		}
360 		if (p->ni_flags & NIF_LACHG) {
361 			wmove(wnd, p->ni_line, LADDR);
362 			inetprint(&p->ni_laddr, p->ni_lport, p->ni_proto);
363 			p->ni_flags &= ~NIF_LACHG;
364 		}
365 		if (p->ni_flags & NIF_FACHG) {
366 			wmove(wnd, p->ni_line, FADDR);
367 			inetprint(&p->ni_faddr, p->ni_fport, p->ni_proto);
368 			p->ni_flags &= ~NIF_FACHG;
369 		}
370 		mvwaddstr(wnd, p->ni_line, PROTO, p->ni_proto);
371 		mvwprintw(wnd, p->ni_line, RCVCC, "%6d", p->ni_rcvcc);
372 		mvwprintw(wnd, p->ni_line, SNDCC, "%6d", p->ni_sndcc);
373 		if (streq(p->ni_proto, "tcp")) {
374 			if (p->ni_state < 0 || p->ni_state >= TCP_NSTATES)
375 				mvwprintw(wnd, p->ni_line, STATE, "%d",
376 				    p->ni_state);
377 			else
378 				mvwaddstr(wnd, p->ni_line, STATE,
379 				    tcpstates[p->ni_state]);
380 		}
381 		wclrtoeol(wnd);
382 	}
383 	if (lastrow < YMAX(wnd)) {
384 		wmove(wnd, lastrow, 0); wclrtobot(wnd);
385 		wmove(wnd, YMAX(wnd), 0); wdeleteln(wnd);	/* XXX */
386 	}
387 }
388 
389 /*
390  * Pretty print an Internet address (net address + port).
391  * If the nflag was specified, use numbers instead of names.
392  */
393 static void
394 inetprint(struct in_addr *in, int port, const char *proto)
395 {
396 	struct servent *sp = 0;
397 	char line[80], *cp;
398 
399 	snprintf(line, sizeof(line), "%.*s.", 16, inetname(*in));
400 	cp = strchr(line, '\0');
401 	if (!nflag && port)
402 		sp = getservbyport(port, proto);
403 	if (sp || port == 0)
404 		snprintf(cp, sizeof(line) - (cp - line), "%.8s",
405 		    sp ? sp->s_name : "*");
406 	else
407 		snprintf(cp, sizeof(line) - (cp - line), "%d",
408 		    ntohs((u_short)port));
409 	/* pad to full column to clear any garbage */
410 	cp = strchr(line, '\0');
411 	while (cp - line < 22)
412 		*cp++ = ' ';
413 	line[22] = '\0';
414 	waddstr(wnd, line);
415 }
416 
417 /*
418  * Construct an Internet address representation.
419  * If the nflag has been supplied, give
420  * numeric value, otherwise try for symbolic name.
421  */
422 static char *
423 inetname(struct in_addr in)
424 {
425 	char *cp = 0;
426 	static char line[50];
427 	struct hostent *hp;
428 	struct netent *np;
429 
430 	if (!nflag && in.s_addr != INADDR_ANY) {
431 		int net = inet_netof(in);
432 		int lna = inet_lnaof(in);
433 
434 		if (lna == INADDR_ANY) {
435 			np = getnetbyaddr(net, AF_INET);
436 			if (np)
437 				cp = np->n_name;
438 		}
439 		if (cp == 0) {
440 			hp = gethostbyaddr(&in, sizeof (in), AF_INET);
441 			if (hp)
442 				cp = hp->h_name;
443 		}
444 	}
445 	if (in.s_addr == INADDR_ANY)
446 		strcpy(line, "*");
447 	else if (cp)
448 		snprintf(line, sizeof(line), "%s", cp);
449 	else {
450 		in.s_addr = ntohl(in.s_addr);
451 #define C(x)	((x) & 0xff)
452 		snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in.s_addr >> 24),
453 			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
454 	}
455 	return (line);
456 }
457 
458 int
459 cmdnetstat(const char *cmd, char *args)
460 {
461 	struct netinfo *p;
462 
463 	if (prefix(cmd, "all")) {
464 		aflag = !aflag;
465 		goto fixup;
466 	}
467 	if  (prefix(cmd, "numbers") || prefix(cmd, "names")) {
468 		int new;
469 
470 		new = prefix(cmd, "numbers");
471 		if (new == nflag)
472 			return (1);
473 		p = netcb.ni_forw;
474 		for (; p != (struct netinfo *)&netcb; p = p->ni_forw) {
475 			if (p->ni_line == -1)
476 				continue;
477 			p->ni_flags |= NIF_LACHG|NIF_FACHG;
478 		}
479 		nflag = new;
480 		goto redisplay;
481 	}
482 	if (!netcmd(cmd, args))
483 		return (0);
484 fixup:
485 	fetchnetstat();
486 redisplay:
487 	shownetstat();
488 	refresh();
489 	return (1);
490 }
491