netstat.c revision 872b698bd4a1bfc0bf008c09228e6fd238809c75
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
37static 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#define	_WANT_SOCKET
47#include <sys/socketvar.h>
48#include <sys/protosw.h>
49
50#include <netinet/in.h>
51#include <arpa/inet.h>
52#include <net/route.h>
53#include <netinet/in_systm.h>
54#include <netinet/ip.h>
55#ifdef INET6
56#include <netinet/ip6.h>
57#endif
58#define	_WANT_INPCB
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#define TCPSTATES
67#include <netinet/tcp_fsm.h>
68#include <netinet/tcp_timer.h>
69#define	_WANT_TCPCB
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
84static struct netinfo *enter(struct in_conninfo *, uint8_t, int, const char *);
85static void enter_kvm(struct inpcb *, struct socket *, int, const char *);
86static void enter_sysctl(struct xinpcb *, struct xsocket *, int, const char *);
87static void fetchnetstat_kvm(void);
88static void fetchnetstat_sysctl(void);
89static char *inetname(struct sockaddr *);
90static void inetprint(struct sockaddr *, const char *);
91
92#define	streq(a,b)	(strcmp(a,b)==0)
93#define	YMAX(w)		(getmaxy(w)-2)
94
95WINDOW *
96opennetstat(void)
97{
98	sethostent(1);
99	setnetent(1);
100	return (subwin(stdscr, LINES-3-1, 0, MAINWIN_ROW, 0));
101}
102
103struct 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
118TAILQ_HEAD(netinfohead, netinfo) netcb = TAILQ_HEAD_INITIALIZER(netcb);
119
120static	int aflag = 0;
121static	int nflag = 0;
122static	int lastrow = 1;
123
124void
125closenetstat(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
143static const char *miblist[] = {
144	"net.inet.tcp.pcblist",
145	"net.inet.udp.pcblist"
146};
147
148static char tcb[] = "tcb", udb[] = "udb";
149
150struct 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
158int
159initnetstat(void)
160{
161	protos = TCP|UDP;
162	return(1);
163}
164
165void
166fetchnetstat(void)
167{
168	if (use_kvm)
169		fetchnetstat_kvm();
170	else
171		fetchnetstat_sysctl();
172}
173
174static void
175fetchnetstat_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	}
202again:
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 (inet_lnaof(inpcb.inp_laddr) == 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			if (inpcb.inp_flags & INP_TIMEWAIT) {
226				bzero(&sockb, sizeof(sockb));
227				enter_kvm(&inpcb, &sockb, TCPS_TIME_WAIT,
228					 "tcp");
229			} else {
230				KREAD(inpcb.inp_socket, &sockb,
231					sizeof (sockb));
232				KREAD(inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
233				enter_kvm(&inpcb, &sockb, tcpcb.t_state,
234					"tcp");
235			}
236		} else
237			enter_kvm(&inpcb, &sockb, 0, "udp");
238	}
239	if (istcp && (protos&UDP)) {
240		istcp = 0;
241		off = NPTR(X_UDB);
242		goto again;
243	}
244}
245
246static void
247fetchnetstat_sysctl(void)
248{
249	struct netinfo *p;
250	int idx;
251	struct xinpgen *inpg;
252	char *cur, *end;
253	struct xinpcb *xip = NULL;
254	struct xtcpcb *xtp = NULL;
255	int plen;
256	size_t lsz;
257
258	TAILQ_FOREACH(p, &netcb, chain)
259		p->ni_seen = 0;
260	if (protos&TCP) {
261		idx = 0;
262	} else if (protos&UDP) {
263		idx = 1;
264	} else {
265		error("No protocols to display");
266		return;
267	}
268
269	for (;idx < 2; idx++) {
270		if (idx == 1 && !(protos&UDP))
271			break;
272		inpg = (struct xinpgen *)sysctl_dynread(miblist[idx], &lsz);
273		if (inpg == NULL) {
274			error("sysctl(%s...) failed", miblist[idx]);
275			continue;
276		}
277		/*
278		 * We currently do no require a consistent pcb list.
279		 * Try to be robust in case of struct size changes
280		 */
281		cur = ((char *)inpg) + inpg->xig_len;
282		/* There is also a trailing struct xinpgen */
283		end = ((char *)inpg) + lsz - inpg->xig_len;
284		if (end <= cur) {
285			free(inpg);
286			continue;
287		}
288		if (idx == 0) { /* TCP */
289			xtp = (struct xtcpcb *)cur;
290			plen = xtp->xt_len;
291		} else {
292			xip = (struct xinpcb *)cur;
293			plen = xip->xi_len;
294		}
295		while (cur + plen <= end) {
296			if (idx == 0) { /* TCP */
297				xtp = (struct xtcpcb *)cur;
298				xip = &xtp->xt_inp;
299			} else {
300				xip = (struct xinpcb *)cur;
301			}
302			cur += plen;
303
304			if (!aflag) {
305				if (xip->inp_vflag & INP_IPV4) {
306					if (inet_lnaof(xip->inp_laddr) ==
307					    INADDR_ANY)
308						continue;
309				}
310#ifdef INET6
311				else if (xip->inp_vflag & INP_IPV6) {
312					if (memcmp(&xip->in6p_laddr,
313					    &in6addr_any, sizeof(in6addr_any))
314					    == 0)
315						continue;
316				}
317#endif
318			}
319			if (nhosts && !checkhost(&xip->inp_inc))
320				continue;
321			if (nports && !checkport(&xip->inp_inc))
322				continue;
323			if (idx == 0)
324				enter_sysctl(xip, &xip->xi_socket,
325				    xtp->t_state, "tcp");
326			else
327				enter_sysctl(xip, &xip->xi_socket, 0, "udp");
328		}
329		free(inpg);
330	}
331}
332
333static void
334enter_kvm(struct inpcb *inp, struct socket *so, int state, const char *proto)
335{
336	struct netinfo *p;
337
338	if ((p = enter(&inp->inp_inc, inp->inp_vflag, state, proto)) != NULL) {
339		p->ni_rcvcc = so->so_rcv.sb_ccc;
340		p->ni_sndcc = so->so_snd.sb_ccc;
341	}
342}
343
344static void
345enter_sysctl(struct xinpcb *xip, struct xsocket *so, int state,
346    const char *proto)
347{
348	struct netinfo *p;
349
350	if ((p = enter(&xip->inp_inc, xip->inp_vflag, state, proto)) != NULL) {
351		p->ni_rcvcc = so->so_rcv.sb_cc;
352		p->ni_sndcc = so->so_snd.sb_cc;
353	}
354}
355
356static struct netinfo *
357enter(struct in_conninfo *inc, uint8_t vflag, int state, const char *proto)
358{
359	struct netinfo *p;
360	struct sockaddr_storage lsa, fsa;
361	struct sockaddr_in *sa4;
362#ifdef INET6
363	struct sockaddr_in6 *sa6;
364#endif
365
366	memset(&lsa, 0, sizeof(lsa));
367	memset(&fsa, 0, sizeof(fsa));
368	if (vflag & INP_IPV4) {
369		sa4 = (struct sockaddr_in *)&lsa;
370		sa4->sin_addr = inc->inc_laddr;
371		sa4->sin_port = inc->inc_lport;
372		sa4->sin_family = AF_INET;
373		sa4->sin_len = sizeof(struct sockaddr_in);
374
375		sa4 = (struct sockaddr_in *)&fsa;
376		sa4->sin_addr = inc->inc_faddr;
377		sa4->sin_port = inc->inc_fport;
378		sa4->sin_family = AF_INET;
379		sa4->sin_len = sizeof(struct sockaddr_in);
380	}
381#ifdef INET6
382	else if (vflag & INP_IPV6) {
383		sa6 = (struct sockaddr_in6 *)&lsa;
384		memcpy(&sa6->sin6_addr, &inc->inc6_laddr,
385		    sizeof(struct in6_addr));
386		sa6->sin6_port = inc->inc_lport;
387		sa6->sin6_family = AF_INET6;
388		sa6->sin6_len = sizeof(struct sockaddr_in6);
389
390		sa6 = (struct sockaddr_in6 *)&fsa;
391		memcpy(&sa6->sin6_addr, &inc->inc6_faddr,
392		    sizeof(struct in6_addr));
393		sa6->sin6_port = inc->inc_fport;
394		sa6->sin6_family = AF_INET6;
395		sa6->sin6_len = sizeof(struct sockaddr_in6);
396	}
397#endif
398	else
399		return NULL;
400
401	/*
402	 * Only take exact matches, any sockets with
403	 * previously unbound addresses will be deleted
404	 * below in the display routine because they
405	 * will appear as ``not seen'' in the kernel
406	 * data structures.
407	 */
408	TAILQ_FOREACH(p, &netcb, chain) {
409		if (!streq(proto, p->ni_proto))
410			continue;
411		if (p->ni_lsa.ss_family != lsa.ss_family ||
412		    memcmp(&p->ni_lsa, &lsa, lsa.ss_len) != 0)
413			continue;
414		if (p->ni_fsa.ss_family == fsa.ss_family &&
415		    memcmp(&p->ni_fsa, &fsa, fsa.ss_len) == 0)
416			break;
417	}
418	if (p == NULL) {
419		if ((p = malloc(sizeof(*p))) == NULL) {
420			error("Out of memory");
421			return NULL;
422		}
423		TAILQ_INSERT_HEAD(&netcb, p, chain);
424		p->ni_line = -1;
425		memcpy(&p->ni_lsa, &lsa, lsa.ss_len);
426		memcpy(&p->ni_fsa, &fsa, fsa.ss_len);
427		p->ni_proto = strdup(proto);
428		p->ni_flags = NIF_LACHG|NIF_FACHG;
429	}
430	p->ni_state = state;
431	p->ni_seen = 1;
432	return p;
433}
434
435/* column locations */
436#define	LADDR	0
437#define	FADDR	LADDR+23
438#define	PROTO	FADDR+23
439#define	RCVCC	PROTO+6
440#define	SNDCC	RCVCC+7
441#define	STATE	SNDCC+7
442
443void
444labelnetstat(void)
445{
446	if (use_kvm && namelist[X_TCB].n_type == 0)
447		return;
448	wmove(wnd, 0, 0); wclrtobot(wnd);
449	mvwaddstr(wnd, 0, LADDR, "Local Address");
450	mvwaddstr(wnd, 0, FADDR, "Foreign Address");
451	mvwaddstr(wnd, 0, PROTO, "Proto");
452	mvwaddstr(wnd, 0, RCVCC, "Recv-Q");
453	mvwaddstr(wnd, 0, SNDCC, "Send-Q");
454	mvwaddstr(wnd, 0, STATE, "(state)");
455}
456
457void
458shownetstat(void)
459{
460	struct netinfo *p, *q;
461	char proto[6];
462	const char *family = "";
463
464	/*
465	 * First, delete any connections that have gone
466	 * away and adjust the position of connections
467	 * below to reflect the deleted line.
468	 */
469	p = TAILQ_FIRST(&netcb);
470	while (p != NULL) {
471		if (p->ni_line == -1 || p->ni_seen) {
472			p = TAILQ_NEXT(p, chain);
473			continue;
474		}
475		wmove(wnd, p->ni_line, 0); wdeleteln(wnd);
476		TAILQ_FOREACH(q, &netcb, chain)
477			if (q != p && q->ni_line > p->ni_line) {
478				q->ni_line--;
479				/* this shouldn't be necessary */
480				q->ni_flags |= NIF_LACHG|NIF_FACHG;
481			}
482		lastrow--;
483		q = TAILQ_NEXT(p, chain);
484		TAILQ_REMOVE(&netcb, p, chain);
485		free(p);
486		p = q;
487	}
488	/*
489	 * Update existing connections and add new ones.
490	 */
491	TAILQ_FOREACH(p, &netcb, chain) {
492		if (p->ni_line == -1) {
493			/*
494			 * Add a new entry if possible.
495			 */
496			if (lastrow > YMAX(wnd))
497				continue;
498			p->ni_line = lastrow++;
499			p->ni_flags |= NIF_LACHG|NIF_FACHG;
500		}
501		if (p->ni_flags & NIF_LACHG) {
502			wmove(wnd, p->ni_line, LADDR);
503			inetprint((struct sockaddr *)&p->ni_lsa, p->ni_proto);
504			p->ni_flags &= ~NIF_LACHG;
505		}
506		if (p->ni_flags & NIF_FACHG) {
507			wmove(wnd, p->ni_line, FADDR);
508			inetprint((struct sockaddr *)&p->ni_fsa, p->ni_proto);
509			p->ni_flags &= ~NIF_FACHG;
510		}
511#ifdef INET6
512		family = (p->ni_lsa.ss_family == AF_INET) ? "4" : "6";
513#endif
514		snprintf(proto, sizeof(proto), "%s%s", p->ni_proto, family);
515		mvwaddstr(wnd, p->ni_line, PROTO, proto);
516		mvwprintw(wnd, p->ni_line, RCVCC, "%6u", p->ni_rcvcc);
517		mvwprintw(wnd, p->ni_line, SNDCC, "%6u", p->ni_sndcc);
518		if (streq(p->ni_proto, "tcp")) {
519			if (p->ni_state < 0 || p->ni_state >= TCP_NSTATES)
520				mvwprintw(wnd, p->ni_line, STATE, "%d",
521				    p->ni_state);
522			else
523				mvwaddstr(wnd, p->ni_line, STATE,
524				    tcpstates[p->ni_state]);
525		}
526		wclrtoeol(wnd);
527	}
528	if (lastrow < YMAX(wnd)) {
529		wmove(wnd, lastrow, 0); wclrtobot(wnd);
530		wmove(wnd, YMAX(wnd), 0); wdeleteln(wnd);	/* XXX */
531	}
532}
533
534/*
535 * Pretty print an Internet address (net address + port).
536 * If the nflag was specified, use numbers instead of names.
537 */
538static void
539inetprint(struct sockaddr *sa, const char *proto)
540{
541	struct servent *sp = 0;
542	char line[80], *cp;
543	int port;
544
545	switch (sa->sa_family) {
546	case AF_INET:
547		port = ((struct sockaddr_in *)sa)->sin_port;
548		break;
549#ifdef INET6
550	case AF_INET6:
551		port = ((struct sockaddr_in6 *)sa)->sin6_port;
552		break;
553#endif
554	default:
555		port = 0;
556		break;
557	}
558	snprintf(line, sizeof(line), "%.*s.", 16, inetname(sa));
559	cp = strchr(line, '\0');
560	if (!nflag && port)
561		sp = getservbyport(port, proto);
562	if (sp || port == 0)
563		snprintf(cp, sizeof(line) - (cp - line), "%.8s",
564		    sp ? sp->s_name : "*");
565	else
566		snprintf(cp, sizeof(line) - (cp - line), "%d",
567		    ntohs((u_short)port));
568	/* pad to full column to clear any garbage */
569	cp = strchr(line, '\0');
570	while (cp - line < 22)
571		*cp++ = ' ';
572	line[22] = '\0';
573	waddstr(wnd, line);
574}
575
576/*
577 * Construct an Internet address representation.
578 * If the nflag has been supplied, give
579 * numeric value, otherwise try for symbolic name.
580 */
581static char *
582inetname(struct sockaddr *sa)
583{
584	char *cp = 0;
585	static char line[NI_MAXHOST];
586	struct hostent *hp;
587	struct netent *np;
588	struct in_addr in;
589
590#ifdef INET6
591	if (sa->sa_family == AF_INET6) {
592		if (memcmp(&((struct sockaddr_in6 *)sa)->sin6_addr,
593		    &in6addr_any, sizeof(in6addr_any)) == 0)
594			strcpy(line, "*");
595		else
596			getnameinfo(sa, sa->sa_len, line, sizeof(line), NULL, 0,
597			    nflag ? NI_NUMERICHOST : 0);
598		return (line);
599	}
600#endif
601
602	in = ((struct sockaddr_in *)sa)->sin_addr;
603	if (!nflag && in.s_addr != INADDR_ANY) {
604		int net = inet_netof(in);
605		int lna = inet_lnaof(in);
606
607		if (lna == INADDR_ANY) {
608			np = getnetbyaddr(net, AF_INET);
609			if (np)
610				cp = np->n_name;
611		}
612		if (cp == NULL) {
613			hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
614			if (hp)
615				cp = hp->h_name;
616		}
617	}
618	if (in.s_addr == INADDR_ANY)
619		strcpy(line, "*");
620	else if (cp)
621		snprintf(line, sizeof(line), "%s", cp);
622	else {
623		in.s_addr = ntohl(in.s_addr);
624#define C(x)	((x) & 0xff)
625		snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in.s_addr >> 24),
626			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
627	}
628	return (line);
629}
630
631int
632cmdnetstat(const char *cmd, const char *args)
633{
634	if (prefix(cmd, "all")) {
635		aflag = !aflag;
636		goto fixup;
637	}
638	if  (prefix(cmd, "numbers") || prefix(cmd, "names")) {
639		struct netinfo *p;
640		int new;
641
642		new = prefix(cmd, "numbers");
643		if (new == nflag)
644			return (1);
645		TAILQ_FOREACH(p, &netcb, chain) {
646			if (p->ni_line == -1)
647				continue;
648			p->ni_flags |= NIF_LACHG|NIF_FACHG;
649		}
650		nflag = new;
651		goto redisplay;
652	}
653	if (!netcmd(cmd, args))
654		return (0);
655fixup:
656	fetchnetstat();
657redisplay:
658	shownetstat();
659	refresh();
660	return (1);
661}
662