xref: /freebsd/usr.bin/systat/netstat.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 
34 #include <sys/cdefs.h>
35 
36 __FBSDID("$FreeBSD$");
37 
38 #ifdef lint
39 static const char sccsid[] = "@(#)netstat.c	8.1 (Berkeley) 6/6/93";
40 #endif
41 
42 /*
43  * netstat
44  */
45 #include <sys/param.h>
46 #include <sys/queue.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/protosw.h>
50 
51 #include <netinet/in.h>
52 #include <arpa/inet.h>
53 #include <net/route.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #ifdef INET6
57 #include <netinet/ip6.h>
58 #endif
59 #include <netinet/in_pcb.h>
60 #include <netinet/ip_icmp.h>
61 #include <netinet/icmp_var.h>
62 #include <netinet/ip_var.h>
63 #include <netinet/tcp.h>
64 #include <netinet/tcpip.h>
65 #include <netinet/tcp_seq.h>
66 #include <netinet/tcp_var.h>
67 #define TCPSTATES
68 #include <netinet/tcp_fsm.h>
69 #include <netinet/tcp_timer.h>
70 #include <netinet/tcp_var.h>
71 #include <netinet/tcp_debug.h>
72 #include <netinet/udp.h>
73 #include <netinet/udp_var.h>
74 
75 #include <netdb.h>
76 #include <nlist.h>
77 #include <paths.h>
78 #include <stdlib.h>
79 #include <string.h>
80 
81 #include "systat.h"
82 #include "extern.h"
83 
84 static struct netinfo *enter(struct inpcb *, int, const char *);
85 static void enter_kvm(struct inpcb *, struct socket *, int, const char *);
86 static void enter_sysctl(struct inpcb *, struct xsocket *, int, const char *);
87 static void fetchnetstat_kvm(void);
88 static void fetchnetstat_sysctl(void);
89 static char *inetname(struct in_addr);
90 static void inetprint(struct in_addr *, int, const char *);
91 
92 #define	streq(a,b)	(strcmp(a,b)==0)
93 #define	YMAX(w)		((w)->_maxy-1)
94 
95 WINDOW *
96 opennetstat()
97 {
98 	sethostent(1);
99 	setnetent(1);
100 	return (subwin(stdscr, LINES-5-1, 0, 5, 0));
101 }
102 
103 struct netinfo {
104 	TAILQ_ENTRY(netinfo) chain;
105 	short	ni_line;		/* line on screen */
106 	short	ni_seen;		/* 0 when not present in list */
107 	short	ni_flags;
108 #define	NIF_LACHG	0x1		/* local address changed */
109 #define	NIF_FACHG	0x2		/* foreign address changed */
110 	short	ni_state;		/* tcp state */
111 	const char	*ni_proto;		/* protocol */
112 	struct	in_addr ni_laddr;	/* local address */
113 	long	ni_lport;		/* local port */
114 	struct	in_addr	ni_faddr;	/* foreign address */
115 	long	ni_fport;		/* foreign port */
116 	u_int	ni_rcvcc;		/* rcv buffer character count */
117 	u_int	ni_sndcc;		/* snd buffer character count */
118 };
119 
120 TAILQ_HEAD(netinfohead, netinfo) netcb = TAILQ_HEAD_INITIALIZER(netcb);
121 
122 static	int aflag = 0;
123 static	int nflag = 0;
124 static	int lastrow = 1;
125 
126 void
127 closenetstat(w)
128         WINDOW *w;
129 {
130 	struct netinfo *p;
131 
132 	endhostent();
133 	endnetent();
134 	TAILQ_FOREACH(p, &netcb, chain) {
135 		if (p->ni_line != -1)
136 			lastrow--;
137 		p->ni_line = -1;
138 	}
139         if (w != NULL) {
140 		wclear(w);
141 		wrefresh(w);
142 		delwin(w);
143 	}
144 }
145 
146 static const char *miblist[] = {
147 	"net.inet.tcp.pcblist",
148 	"net.inet.udp.pcblist"
149 };
150 
151 struct nlist namelist[] = {
152 #define	X_TCB	0
153 	{ "tcb" },
154 #define	X_UDB	1
155 	{ "udb" },
156 	{ "" },
157 };
158 
159 int
160 initnetstat()
161 {
162 	protos = TCP|UDP;
163 	return(1);
164 }
165 
166 void
167 fetchnetstat()
168 {
169 	if (use_kvm)
170 		fetchnetstat_kvm();
171 	else
172 		fetchnetstat_sysctl();
173 }
174 
175 static void
176 fetchnetstat_kvm()
177 {
178 	struct inpcb *next;
179 	struct netinfo *p;
180 	struct inpcbhead head;
181 	struct inpcb inpcb;
182 	struct socket sockb;
183 	struct tcpcb tcpcb;
184 	void *off;
185 	int istcp;
186 
187 	if (namelist[X_TCB].n_value == 0)
188 		return;
189 	TAILQ_FOREACH(p, &netcb, chain)
190 		p->ni_seen = 0;
191 	if (protos&TCP) {
192 		off = NPTR(X_TCB);
193 		istcp = 1;
194 	}
195 	else if (protos&UDP) {
196 		off = NPTR(X_UDB);
197 		istcp = 0;
198 	}
199 	else {
200 		error("No protocols to display");
201 		return;
202 	}
203 again:
204 	KREAD(off, &head, sizeof (struct inpcbhead));
205 	LIST_FOREACH(next, &head, inp_list) {
206 		KREAD(next, &inpcb, sizeof (inpcb));
207 		next = &inpcb;
208 		if (!aflag && inet_lnaof(inpcb.inp_laddr) == INADDR_ANY)
209 			continue;
210 		if (nhosts && !checkhost(&inpcb))
211 			continue;
212 		if (nports && !checkport(&inpcb))
213 			continue;
214 		KREAD(inpcb.inp_socket, &sockb, sizeof (sockb));
215 		if (istcp) {
216 			KREAD(inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
217 			enter_kvm(&inpcb, &sockb, tcpcb.t_state, "tcp");
218 		} else
219 			enter_kvm(&inpcb, &sockb, 0, "udp");
220 	}
221 	if (istcp && (protos&UDP)) {
222 		istcp = 0;
223 		off = NPTR(X_UDB);
224 		goto again;
225 	}
226 }
227 
228 static void
229 fetchnetstat_sysctl()
230 {
231 	struct netinfo *p;
232 	int idx;
233 	struct xinpgen *inpg;
234 	char *cur, *end;
235 	struct inpcb *inpcb;
236 	struct xinpcb *xip;
237 	struct xtcpcb *xtp;
238 	int plen;
239 	size_t lsz;
240 
241 	TAILQ_FOREACH(p, &netcb, chain)
242 		p->ni_seen = 0;
243 	if (protos&TCP) {
244 		idx = 0;
245 	} else if (protos&UDP) {
246 		idx = 1;
247 	} else {
248 		error("No protocols to display");
249 		return;
250 	}
251 
252 	for (;idx < 2; idx++) {
253 		if (idx == 1 && !(protos&UDP))
254 			break;
255 		inpg = (struct xinpgen *)sysctl_dynread(miblist[idx], &lsz);
256 		if (inpg == NULL) {
257 			error("sysctl(%s...) failed", miblist[idx]);
258 			continue;
259 		}
260 		/*
261 		 * We currently do no require a consistent pcb list.
262 		 * Try to be robust in case of struct size changes
263 		 */
264 		cur = ((char *)inpg) + inpg->xig_len;
265 		/* There is also a trailing struct xinpgen */
266 		end = ((char *)inpg) + lsz - inpg->xig_len;
267 		if (end <= cur) {
268 			free(inpg);
269 			continue;
270 		}
271 		if (idx == 0) { /* TCP */
272 			xtp = (struct xtcpcb *)cur;
273 			plen = xtp->xt_len;
274 		} else {
275 			xip = (struct xinpcb *)cur;
276 			plen = xip->xi_len;
277 		}
278 		while (cur + plen <= end) {
279 			if (idx == 0) { /* TCP */
280 				xtp = (struct xtcpcb *)cur;
281 				inpcb = &xtp->xt_inp;
282 			} else {
283 				xip = (struct xinpcb *)cur;
284 				inpcb = &xip->xi_inp;
285 			}
286 			cur += plen;
287 
288 			if (!aflag && inet_lnaof(inpcb->inp_laddr) ==
289 			    INADDR_ANY)
290 				continue;
291 			if (nhosts && !checkhost(inpcb))
292 				continue;
293 			if (nports && !checkport(inpcb))
294 				continue;
295 			if (idx == 0)	/* TCP */
296 				enter_sysctl(inpcb, &xtp->xt_socket,
297 				    xtp->xt_tp.t_state, "tcp");
298 			else		/* UDP */
299 				enter_sysctl(inpcb, &xip->xi_socket, 0, "udp");
300 		}
301 		free(inpg);
302 	}
303 }
304 
305 static void
306 enter_kvm(inp, so, state, proto)
307 	struct inpcb *inp;
308 	struct socket *so;
309 	int state;
310 	const char *proto;
311 {
312 	struct netinfo *p;
313 
314 	if ((p = enter(inp, state, proto)) != NULL) {
315 		p->ni_rcvcc = so->so_rcv.sb_cc;
316 		p->ni_sndcc = so->so_snd.sb_cc;
317 	}
318 }
319 
320 static void
321 enter_sysctl(inp, so, state, proto)
322 	struct inpcb *inp;
323 	struct xsocket *so;
324 	int state;
325 	const char *proto;
326 {
327 	struct netinfo *p;
328 
329 	if ((p = enter(inp, state, proto)) != NULL) {
330 		p->ni_rcvcc = so->so_rcv.sb_cc;
331 		p->ni_sndcc = so->so_snd.sb_cc;
332 	}
333 }
334 
335 
336 static struct netinfo *
337 enter(inp, state, proto)
338 	struct inpcb *inp;
339 	int state;
340 	const char *proto;
341 {
342 	struct netinfo *p;
343 
344 	/*
345 	 * Only take exact matches, any sockets with
346 	 * previously unbound addresses will be deleted
347 	 * below in the display routine because they
348 	 * will appear as ``not seen'' in the kernel
349 	 * data structures.
350 	 */
351 	TAILQ_FOREACH(p, &netcb, chain) {
352 		if (!streq(proto, p->ni_proto))
353 			continue;
354 		if (p->ni_lport != inp->inp_lport ||
355 		    p->ni_laddr.s_addr != inp->inp_laddr.s_addr)
356 			continue;
357 		if (p->ni_faddr.s_addr == inp->inp_faddr.s_addr &&
358 		    p->ni_fport == inp->inp_fport)
359 			break;
360 	}
361 	if (p == NULL) {
362 		if ((p = malloc(sizeof(*p))) == NULL) {
363 			error("Out of memory");
364 			return NULL;
365 		}
366 		TAILQ_INSERT_HEAD(&netcb, p, chain);
367 		p->ni_line = -1;
368 		p->ni_laddr = inp->inp_laddr;
369 		p->ni_lport = inp->inp_lport;
370 		p->ni_faddr = inp->inp_faddr;
371 		p->ni_fport = inp->inp_fport;
372 		p->ni_proto = strdup(proto);
373 		p->ni_flags = NIF_LACHG|NIF_FACHG;
374 	}
375 	p->ni_state = state;
376 	p->ni_seen = 1;
377 	return p;
378 }
379 
380 /* column locations */
381 #define	LADDR	0
382 #define	FADDR	LADDR+23
383 #define	PROTO	FADDR+23
384 #define	RCVCC	PROTO+6
385 #define	SNDCC	RCVCC+7
386 #define	STATE	SNDCC+7
387 
388 
389 void
390 labelnetstat()
391 {
392 	if (use_kvm && namelist[X_TCB].n_type == 0)
393 		return;
394 	wmove(wnd, 0, 0); wclrtobot(wnd);
395 	mvwaddstr(wnd, 0, LADDR, "Local Address");
396 	mvwaddstr(wnd, 0, FADDR, "Foreign Address");
397 	mvwaddstr(wnd, 0, PROTO, "Proto");
398 	mvwaddstr(wnd, 0, RCVCC, "Recv-Q");
399 	mvwaddstr(wnd, 0, SNDCC, "Send-Q");
400 	mvwaddstr(wnd, 0, STATE, "(state)");
401 }
402 
403 void
404 shownetstat()
405 {
406 	struct netinfo *p, *q;
407 
408 	/*
409 	 * First, delete any connections that have gone
410 	 * away and adjust the position of connections
411 	 * below to reflect the deleted line.
412 	 */
413 	p = TAILQ_FIRST(&netcb);
414 	while (p != NULL) {
415 		if (p->ni_line == -1 || p->ni_seen) {
416 			p = TAILQ_NEXT(p, chain);
417 			continue;
418 		}
419 		wmove(wnd, p->ni_line, 0); wdeleteln(wnd);
420 		TAILQ_FOREACH(q, &netcb, chain)
421 			if (q != p && q->ni_line > p->ni_line) {
422 				q->ni_line--;
423 				/* this shouldn't be necessary */
424 				q->ni_flags |= NIF_LACHG|NIF_FACHG;
425 			}
426 		lastrow--;
427 		q = TAILQ_NEXT(p, chain);
428 		TAILQ_REMOVE(&netcb, p, chain);
429 		free(p);
430 		p = q;
431 	}
432 	/*
433 	 * Update existing connections and add new ones.
434 	 */
435 	TAILQ_FOREACH(p, &netcb, chain) {
436 		if (p->ni_line == -1) {
437 			/*
438 			 * Add a new entry if possible.
439 			 */
440 			if (lastrow > YMAX(wnd))
441 				continue;
442 			p->ni_line = lastrow++;
443 			p->ni_flags |= NIF_LACHG|NIF_FACHG;
444 		}
445 		if (p->ni_flags & NIF_LACHG) {
446 			wmove(wnd, p->ni_line, LADDR);
447 			inetprint(&p->ni_laddr, p->ni_lport, p->ni_proto);
448 			p->ni_flags &= ~NIF_LACHG;
449 		}
450 		if (p->ni_flags & NIF_FACHG) {
451 			wmove(wnd, p->ni_line, FADDR);
452 			inetprint(&p->ni_faddr, p->ni_fport, p->ni_proto);
453 			p->ni_flags &= ~NIF_FACHG;
454 		}
455 		mvwaddstr(wnd, p->ni_line, PROTO, p->ni_proto);
456 		mvwprintw(wnd, p->ni_line, RCVCC, "%6u", p->ni_rcvcc);
457 		mvwprintw(wnd, p->ni_line, SNDCC, "%6u", p->ni_sndcc);
458 		if (streq(p->ni_proto, "tcp")) {
459 			if (p->ni_state < 0 || p->ni_state >= TCP_NSTATES)
460 				mvwprintw(wnd, p->ni_line, STATE, "%d",
461 				    p->ni_state);
462 			else
463 				mvwaddstr(wnd, p->ni_line, STATE,
464 				    tcpstates[p->ni_state]);
465 		}
466 		wclrtoeol(wnd);
467 	}
468 	if (lastrow < YMAX(wnd)) {
469 		wmove(wnd, lastrow, 0); wclrtobot(wnd);
470 		wmove(wnd, YMAX(wnd), 0); wdeleteln(wnd);	/* XXX */
471 	}
472 }
473 
474 /*
475  * Pretty print an Internet address (net address + port).
476  * If the nflag was specified, use numbers instead of names.
477  */
478 static void
479 inetprint(in, port, proto)
480 	struct in_addr *in;
481 	int port;
482 	const char *proto;
483 {
484 	struct servent *sp = 0;
485 	char line[80], *cp;
486 
487 	snprintf(line, sizeof(line), "%.*s.", 16, inetname(*in));
488 	cp = index(line, '\0');
489 	if (!nflag && port)
490 		sp = getservbyport(port, proto);
491 	if (sp || port == 0)
492 		snprintf(cp, sizeof(line) - (cp - line), "%.8s",
493 		    sp ? sp->s_name : "*");
494 	else
495 		snprintf(cp, sizeof(line) - (cp - line), "%d",
496 		    ntohs((u_short)port));
497 	/* pad to full column to clear any garbage */
498 	cp = index(line, '\0');
499 	while (cp - line < 22)
500 		*cp++ = ' ';
501 	line[22] = '\0';
502 	waddstr(wnd, line);
503 }
504 
505 /*
506  * Construct an Internet address representation.
507  * If the nflag has been supplied, give
508  * numeric value, otherwise try for symbolic name.
509  */
510 static char *
511 inetname(in)
512 	struct in_addr in;
513 {
514 	char *cp = 0;
515 	static char line[50];
516 	struct hostent *hp;
517 	struct netent *np;
518 
519 	if (!nflag && in.s_addr != INADDR_ANY) {
520 		int net = inet_netof(in);
521 		int lna = inet_lnaof(in);
522 
523 		if (lna == INADDR_ANY) {
524 			np = getnetbyaddr(net, AF_INET);
525 			if (np)
526 				cp = np->n_name;
527 		}
528 		if (cp == 0) {
529 			hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
530 			if (hp)
531 				cp = hp->h_name;
532 		}
533 	}
534 	if (in.s_addr == INADDR_ANY)
535 		strcpy(line, "*");
536 	else if (cp)
537 		snprintf(line, sizeof(line), "%s", cp);
538 	else {
539 		in.s_addr = ntohl(in.s_addr);
540 #define C(x)	((x) & 0xff)
541 		snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in.s_addr >> 24),
542 			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
543 	}
544 	return (line);
545 }
546 
547 int
548 cmdnetstat(cmd, args)
549 	const char *cmd, *args;
550 {
551 	if (prefix(cmd, "all")) {
552 		aflag = !aflag;
553 		goto fixup;
554 	}
555 	if  (prefix(cmd, "numbers") || prefix(cmd, "names")) {
556 		struct netinfo *p;
557 		int new;
558 
559 		new = prefix(cmd, "numbers");
560 		if (new == nflag)
561 			return (1);
562 		TAILQ_FOREACH(p, &netcb, chain) {
563 			if (p->ni_line == -1)
564 				continue;
565 			p->ni_flags |= NIF_LACHG|NIF_FACHG;
566 		}
567 		nflag = new;
568 		goto redisplay;
569 	}
570 	if (!netcmd(cmd, args))
571 		return (0);
572 fixup:
573 	fetchnetstat();
574 redisplay:
575 	shownetstat();
576 	refresh();
577 	return (1);
578 }
579