xref: /freebsd/usr.bin/systat/netstat.c (revision 4ac8f4067096a9d4a00e41cd53bd5c4fa295fd15)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 
34 __FBSDID("$FreeBSD$");
35 
36 #ifdef lint
37 static const char sccsid[] = "@(#)netstat.c	8.1 (Berkeley) 6/6/93";
38 #endif
39 
40 /*
41  * netstat
42  */
43 #include <sys/param.h>
44 #include <sys/queue.h>
45 #include <sys/socket.h>
46 #include <sys/callout.h>
47 #define	_WANT_SOCKET
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 #define	_WANT_INPCB
60 #include <netinet/in_pcb.h>
61 #include <netinet/ip_icmp.h>
62 #include <netinet/icmp_var.h>
63 #include <netinet/ip_var.h>
64 #include <netinet/tcp.h>
65 #include <netinet/tcpip.h>
66 #include <netinet/tcp_seq.h>
67 #define TCPSTATES
68 #include <netinet/tcp_fsm.h>
69 #include <netinet/tcp_timer.h>
70 #define	_WANT_TCPCB
71 #include <netinet/tcp_var.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 in_conninfo *, uint8_t, int, const char *);
85 static void enter_kvm(struct inpcb *, struct socket *, int, const char *);
86 static void enter_sysctl(struct xinpcb *, struct xsocket *, int, const char *);
87 static void fetchnetstat_kvm(void);
88 static void fetchnetstat_sysctl(void);
89 static char *inetname(struct sockaddr *);
90 static void inetprint(struct sockaddr *, const char *);
91 
92 #define	streq(a,b)	(strcmp(a,b)==0)
93 #define	YMAX(w)		(getmaxy(w)-2)
94 
95 WINDOW *
96 opennetstat(void)
97 {
98 	sethostent(1);
99 	setnetent(1);
100 	return (subwin(stdscr, LINES-3-1, 0, MAINWIN_ROW, 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 sockaddr_storage ni_lsa;	/* local address */
113 	struct sockaddr_storage	ni_fsa;	/* foreign address */
114 	u_int	ni_rcvcc;		/* rcv buffer character count */
115 	u_int	ni_sndcc;		/* snd buffer character count */
116 };
117 
118 static TAILQ_HEAD(netinfohead, netinfo) netcb = TAILQ_HEAD_INITIALIZER(netcb);
119 
120 static	int aflag = 0;
121 static	int nflag = 0;
122 static	int lastrow = 1;
123 
124 void
125 closenetstat(WINDOW *w)
126 {
127 	struct netinfo *p;
128 
129 	endhostent();
130 	endnetent();
131 	TAILQ_FOREACH(p, &netcb, chain) {
132 		if (p->ni_line != -1)
133 			lastrow--;
134 		p->ni_line = -1;
135 	}
136 	if (w != NULL) {
137 		wclear(w);
138 		wrefresh(w);
139 		delwin(w);
140 	}
141 }
142 
143 static const char *miblist[] = {
144 	"net.inet.tcp.pcblist",
145 	"net.inet.udp.pcblist"
146 };
147 
148 static char tcb[] = "tcb", udb[] = "udb";
149 
150 struct nlist namelist[] = {
151 #define	X_TCB	0
152 	{ .n_name = tcb },
153 #define	X_UDB	1
154 	{ .n_name = udb },
155 	{ .n_name = NULL },
156 };
157 
158 int
159 initnetstat(void)
160 {
161 	protos = TCP|UDP;
162 	return(1);
163 }
164 
165 void
166 fetchnetstat(void)
167 {
168 	if (use_kvm)
169 		fetchnetstat_kvm();
170 	else
171 		fetchnetstat_sysctl();
172 }
173 
174 static void
175 fetchnetstat_kvm(void)
176 {
177 	struct inpcb *next;
178 	struct netinfo *p;
179 	struct inpcbhead head;
180 	struct inpcb inpcb;
181 	struct socket sockb;
182 	struct tcpcb tcpcb;
183 	void *off;
184 	int istcp;
185 
186 	if (namelist[X_TCB].n_value == 0)
187 		return;
188 	TAILQ_FOREACH(p, &netcb, chain)
189 		p->ni_seen = 0;
190 	if (protos&TCP) {
191 		off = NPTR(X_TCB);
192 		istcp = 1;
193 	}
194 	else if (protos&UDP) {
195 		off = NPTR(X_UDB);
196 		istcp = 0;
197 	}
198 	else {
199 		error("No protocols to display");
200 		return;
201 	}
202 again:
203 	KREAD(off, &head, sizeof (struct inpcbhead));
204 	LIST_FOREACH(next, &head, inp_list) {
205 		KREAD(next, &inpcb, sizeof (inpcb));
206 		next = &inpcb;
207 		if (!aflag) {
208 			if (inpcb.inp_vflag & INP_IPV4) {
209 				if (inpcb.inp_laddr.s_addr == INADDR_ANY)
210 					continue;
211 			}
212 #ifdef INET6
213 			else if (inpcb.inp_vflag & INP_IPV6) {
214 				if (memcmp(&inpcb.in6p_laddr,
215 				    &in6addr_any, sizeof(in6addr_any)) == 0)
216 					continue;
217 			}
218 #endif
219 		}
220 		if (nhosts && !checkhost(&inpcb.inp_inc))
221 			continue;
222 		if (nports && !checkport(&inpcb.inp_inc))
223 			continue;
224 		if (istcp) {
225 			KREAD(inpcb.inp_socket, &sockb, sizeof (sockb));
226 			KREAD(inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
227 			enter_kvm(&inpcb, &sockb, tcpcb.t_state, "tcp");
228 		} else
229 			enter_kvm(&inpcb, &sockb, 0, "udp");
230 	}
231 	if (istcp && (protos&UDP)) {
232 		istcp = 0;
233 		off = NPTR(X_UDB);
234 		goto again;
235 	}
236 }
237 
238 static void
239 fetchnetstat_sysctl(void)
240 {
241 	struct netinfo *p;
242 	int idx;
243 	struct xinpgen *inpg;
244 	char *cur, *end;
245 	struct xinpcb *xip = NULL;
246 	struct xtcpcb *xtp = NULL;
247 	int plen;
248 	size_t lsz;
249 
250 	TAILQ_FOREACH(p, &netcb, chain)
251 		p->ni_seen = 0;
252 	if (protos&TCP) {
253 		idx = 0;
254 	} else if (protos&UDP) {
255 		idx = 1;
256 	} else {
257 		error("No protocols to display");
258 		return;
259 	}
260 
261 	for (;idx < 2; idx++) {
262 		if (idx == 1 && !(protos&UDP))
263 			break;
264 		inpg = (struct xinpgen *)sysctl_dynread(miblist[idx], &lsz);
265 		if (inpg == NULL) {
266 			error("sysctl(%s...) failed", miblist[idx]);
267 			continue;
268 		}
269 		/*
270 		 * We currently do no require a consistent pcb list.
271 		 * Try to be robust in case of struct size changes
272 		 */
273 		cur = ((char *)inpg) + inpg->xig_len;
274 		/* There is also a trailing struct xinpgen */
275 		end = ((char *)inpg) + lsz - inpg->xig_len;
276 		if (end <= cur) {
277 			free(inpg);
278 			continue;
279 		}
280 		if (idx == 0) { /* TCP */
281 			xtp = (struct xtcpcb *)cur;
282 			plen = xtp->xt_len;
283 		} else {
284 			xip = (struct xinpcb *)cur;
285 			plen = xip->xi_len;
286 		}
287 		while (cur + plen <= end) {
288 			if (idx == 0) { /* TCP */
289 				xtp = (struct xtcpcb *)cur;
290 				xip = &xtp->xt_inp;
291 			} else {
292 				xip = (struct xinpcb *)cur;
293 			}
294 			cur += plen;
295 
296 			if (!aflag) {
297 				if (xip->inp_vflag & INP_IPV4) {
298 					if (xip->inp_laddr.s_addr == INADDR_ANY)
299 						continue;
300 				}
301 #ifdef INET6
302 				else if (xip->inp_vflag & INP_IPV6) {
303 					if (memcmp(&xip->in6p_laddr,
304 					    &in6addr_any, sizeof(in6addr_any))
305 					    == 0)
306 						continue;
307 				}
308 #endif
309 			}
310 			if (nhosts && !checkhost(&xip->inp_inc))
311 				continue;
312 			if (nports && !checkport(&xip->inp_inc))
313 				continue;
314 			if (idx == 0)
315 				enter_sysctl(xip, &xip->xi_socket,
316 				    xtp->t_state, "tcp");
317 			else
318 				enter_sysctl(xip, &xip->xi_socket, 0, "udp");
319 		}
320 		free(inpg);
321 	}
322 }
323 
324 static void
325 enter_kvm(struct inpcb *inp, struct socket *so, int state, const char *proto)
326 {
327 	struct netinfo *p;
328 
329 	if ((p = enter(&inp->inp_inc, inp->inp_vflag, state, proto)) != NULL) {
330 		p->ni_rcvcc = so->so_rcv.sb_ccc;
331 		p->ni_sndcc = so->so_snd.sb_ccc;
332 	}
333 }
334 
335 static void
336 enter_sysctl(struct xinpcb *xip, struct xsocket *so, int state,
337     const char *proto)
338 {
339 	struct netinfo *p;
340 
341 	if ((p = enter(&xip->inp_inc, xip->inp_vflag, state, proto)) != NULL) {
342 		p->ni_rcvcc = so->so_rcv.sb_cc;
343 		p->ni_sndcc = so->so_snd.sb_cc;
344 	}
345 }
346 
347 static struct netinfo *
348 enter(struct in_conninfo *inc, uint8_t vflag, int state, const char *proto)
349 {
350 	struct netinfo *p;
351 	struct sockaddr_storage lsa, fsa;
352 	struct sockaddr_in *sa4;
353 #ifdef INET6
354 	struct sockaddr_in6 *sa6;
355 #endif
356 
357 	memset(&lsa, 0, sizeof(lsa));
358 	memset(&fsa, 0, sizeof(fsa));
359 	if (vflag & INP_IPV4) {
360 		sa4 = (struct sockaddr_in *)&lsa;
361 		sa4->sin_addr = inc->inc_laddr;
362 		sa4->sin_port = inc->inc_lport;
363 		sa4->sin_family = AF_INET;
364 		sa4->sin_len = sizeof(struct sockaddr_in);
365 
366 		sa4 = (struct sockaddr_in *)&fsa;
367 		sa4->sin_addr = inc->inc_faddr;
368 		sa4->sin_port = inc->inc_fport;
369 		sa4->sin_family = AF_INET;
370 		sa4->sin_len = sizeof(struct sockaddr_in);
371 	}
372 #ifdef INET6
373 	else if (vflag & INP_IPV6) {
374 		sa6 = (struct sockaddr_in6 *)&lsa;
375 		memcpy(&sa6->sin6_addr, &inc->inc6_laddr,
376 		    sizeof(struct in6_addr));
377 		sa6->sin6_port = inc->inc_lport;
378 		sa6->sin6_family = AF_INET6;
379 		sa6->sin6_len = sizeof(struct sockaddr_in6);
380 
381 		sa6 = (struct sockaddr_in6 *)&fsa;
382 		memcpy(&sa6->sin6_addr, &inc->inc6_faddr,
383 		    sizeof(struct in6_addr));
384 		sa6->sin6_port = inc->inc_fport;
385 		sa6->sin6_family = AF_INET6;
386 		sa6->sin6_len = sizeof(struct sockaddr_in6);
387 	}
388 #endif
389 	else
390 		return NULL;
391 
392 	/*
393 	 * Only take exact matches, any sockets with
394 	 * previously unbound addresses will be deleted
395 	 * below in the display routine because they
396 	 * will appear as ``not seen'' in the kernel
397 	 * data structures.
398 	 */
399 	TAILQ_FOREACH(p, &netcb, chain) {
400 		if (!streq(proto, p->ni_proto))
401 			continue;
402 		if (p->ni_lsa.ss_family != lsa.ss_family ||
403 		    memcmp(&p->ni_lsa, &lsa, lsa.ss_len) != 0)
404 			continue;
405 		if (p->ni_fsa.ss_family == fsa.ss_family &&
406 		    memcmp(&p->ni_fsa, &fsa, fsa.ss_len) == 0)
407 			break;
408 	}
409 	if (p == NULL) {
410 		if ((p = malloc(sizeof(*p))) == NULL) {
411 			error("Out of memory");
412 			return NULL;
413 		}
414 		TAILQ_INSERT_HEAD(&netcb, p, chain);
415 		p->ni_line = -1;
416 		memcpy(&p->ni_lsa, &lsa, lsa.ss_len);
417 		memcpy(&p->ni_fsa, &fsa, fsa.ss_len);
418 		p->ni_proto = strdup(proto);
419 		p->ni_flags = NIF_LACHG|NIF_FACHG;
420 	}
421 	p->ni_state = state;
422 	p->ni_seen = 1;
423 	return p;
424 }
425 
426 /* column locations */
427 #define	LADDR	0
428 #define	FADDR	LADDR+23
429 #define	PROTO	FADDR+23
430 #define	RCVCC	PROTO+6
431 #define	SNDCC	RCVCC+7
432 #define	STATE	SNDCC+7
433 
434 void
435 labelnetstat(void)
436 {
437 	if (use_kvm && namelist[X_TCB].n_type == 0)
438 		return;
439 	wmove(wnd, 0, 0); wclrtobot(wnd);
440 	mvwaddstr(wnd, 0, LADDR, "Local Address");
441 	mvwaddstr(wnd, 0, FADDR, "Foreign Address");
442 	mvwaddstr(wnd, 0, PROTO, "Proto");
443 	mvwaddstr(wnd, 0, RCVCC, "Recv-Q");
444 	mvwaddstr(wnd, 0, SNDCC, "Send-Q");
445 	mvwaddstr(wnd, 0, STATE, "(state)");
446 }
447 
448 void
449 shownetstat(void)
450 {
451 	struct netinfo *p, *q;
452 	char proto[6];
453 	const char *family = "";
454 
455 	/*
456 	 * First, delete any connections that have gone
457 	 * away and adjust the position of connections
458 	 * below to reflect the deleted line.
459 	 */
460 	p = TAILQ_FIRST(&netcb);
461 	while (p != NULL) {
462 		if (p->ni_line == -1 || p->ni_seen) {
463 			p = TAILQ_NEXT(p, chain);
464 			continue;
465 		}
466 		wmove(wnd, p->ni_line, 0); wdeleteln(wnd);
467 		TAILQ_FOREACH(q, &netcb, chain)
468 			if (q != p && q->ni_line > p->ni_line) {
469 				q->ni_line--;
470 				/* this shouldn't be necessary */
471 				q->ni_flags |= NIF_LACHG|NIF_FACHG;
472 			}
473 		lastrow--;
474 		q = TAILQ_NEXT(p, chain);
475 		TAILQ_REMOVE(&netcb, p, chain);
476 		free(p);
477 		p = q;
478 	}
479 	/*
480 	 * Update existing connections and add new ones.
481 	 */
482 	TAILQ_FOREACH(p, &netcb, chain) {
483 		if (p->ni_line == -1) {
484 			/*
485 			 * Add a new entry if possible.
486 			 */
487 			if (lastrow > YMAX(wnd))
488 				continue;
489 			p->ni_line = lastrow++;
490 			p->ni_flags |= NIF_LACHG|NIF_FACHG;
491 		}
492 		if (p->ni_flags & NIF_LACHG) {
493 			wmove(wnd, p->ni_line, LADDR);
494 			inetprint((struct sockaddr *)&p->ni_lsa, p->ni_proto);
495 			p->ni_flags &= ~NIF_LACHG;
496 		}
497 		if (p->ni_flags & NIF_FACHG) {
498 			wmove(wnd, p->ni_line, FADDR);
499 			inetprint((struct sockaddr *)&p->ni_fsa, p->ni_proto);
500 			p->ni_flags &= ~NIF_FACHG;
501 		}
502 #ifdef INET6
503 		family = (p->ni_lsa.ss_family == AF_INET) ? "4" : "6";
504 #endif
505 		snprintf(proto, sizeof(proto), "%s%s", p->ni_proto, family);
506 		mvwaddstr(wnd, p->ni_line, PROTO, proto);
507 		mvwprintw(wnd, p->ni_line, RCVCC, "%6u", p->ni_rcvcc);
508 		mvwprintw(wnd, p->ni_line, SNDCC, "%6u", p->ni_sndcc);
509 		if (streq(p->ni_proto, "tcp")) {
510 			if (p->ni_state < 0 || p->ni_state >= TCP_NSTATES)
511 				mvwprintw(wnd, p->ni_line, STATE, "%d",
512 				    p->ni_state);
513 			else
514 				mvwaddstr(wnd, p->ni_line, STATE,
515 				    tcpstates[p->ni_state]);
516 		}
517 		wclrtoeol(wnd);
518 	}
519 	if (lastrow < YMAX(wnd)) {
520 		wmove(wnd, lastrow, 0); wclrtobot(wnd);
521 		wmove(wnd, YMAX(wnd), 0); wdeleteln(wnd);	/* XXX */
522 	}
523 }
524 
525 /*
526  * Pretty print an Internet address (net address + port).
527  * If the nflag was specified, use numbers instead of names.
528  */
529 static void
530 inetprint(struct sockaddr *sa, const char *proto)
531 {
532 	struct servent *sp = 0;
533 	char line[80], *cp;
534 	int port;
535 
536 	switch (sa->sa_family) {
537 	case AF_INET:
538 		port = ((struct sockaddr_in *)sa)->sin_port;
539 		break;
540 #ifdef INET6
541 	case AF_INET6:
542 		port = ((struct sockaddr_in6 *)sa)->sin6_port;
543 		break;
544 #endif
545 	default:
546 		port = 0;
547 		break;
548 	}
549 	snprintf(line, sizeof(line), "%.*s.", 16, inetname(sa));
550 	cp = strchr(line, '\0');
551 	if (!nflag && port)
552 		sp = getservbyport(port, proto);
553 	if (sp || port == 0)
554 		snprintf(cp, sizeof(line) - (cp - line), "%.8s",
555 		    sp ? sp->s_name : "*");
556 	else
557 		snprintf(cp, sizeof(line) - (cp - line), "%d",
558 		    ntohs((u_short)port));
559 	/* pad to full column to clear any garbage */
560 	cp = strchr(line, '\0');
561 	while (cp - line < 22)
562 		*cp++ = ' ';
563 	line[22] = '\0';
564 	waddstr(wnd, line);
565 }
566 
567 /*
568  * Construct an Internet address representation.
569  * If the nflag has been supplied, give
570  * numeric value, otherwise try for symbolic name.
571  */
572 static char *
573 inetname(struct sockaddr *sa)
574 {
575 	char *cp = 0;
576 	static char line[NI_MAXHOST];
577 	struct hostent *hp;
578 	struct in_addr in;
579 
580 #ifdef INET6
581 	if (sa->sa_family == AF_INET6) {
582 		if (memcmp(&((struct sockaddr_in6 *)sa)->sin6_addr,
583 		    &in6addr_any, sizeof(in6addr_any)) == 0)
584 			strcpy(line, "*");
585 		else
586 			getnameinfo(sa, sa->sa_len, line, sizeof(line), NULL, 0,
587 			    nflag ? NI_NUMERICHOST : 0);
588 		return (line);
589 	}
590 #endif
591 
592 	in = ((struct sockaddr_in *)sa)->sin_addr;
593 	if (!nflag && in.s_addr != INADDR_ANY) {
594 		hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
595 		if (hp)
596 			cp = hp->h_name;
597 	}
598 	if (in.s_addr == INADDR_ANY)
599 		strcpy(line, "*");
600 	else if (cp)
601 		snprintf(line, sizeof(line), "%s", cp);
602 	else {
603 		in.s_addr = ntohl(in.s_addr);
604 #define C(x)	((x) & 0xff)
605 		snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in.s_addr >> 24),
606 			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
607 	}
608 	return (line);
609 }
610 
611 int
612 cmdnetstat(const char *cmd, const char *args)
613 {
614 	if (prefix(cmd, "all")) {
615 		aflag = !aflag;
616 		goto fixup;
617 	}
618 	if  (prefix(cmd, "numbers") || prefix(cmd, "names")) {
619 		struct netinfo *p;
620 		int new;
621 
622 		new = prefix(cmd, "numbers");
623 		if (new == nflag)
624 			return (1);
625 		TAILQ_FOREACH(p, &netcb, chain) {
626 			if (p->ni_line == -1)
627 				continue;
628 			p->ni_flags |= NIF_LACHG|NIF_FACHG;
629 		}
630 		nflag = new;
631 		goto redisplay;
632 	}
633 	if (!netcmd(cmd, args))
634 		return (0);
635 fixup:
636 	fetchnetstat();
637 redisplay:
638 	shownetstat();
639 	refresh();
640 	return (1);
641 }
642