netstat.c revision 158160
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: head/usr.bin/systat/netstat.c 158160 2006-04-30 04:26:46Z bde $");
37
38#ifdef lint
39static 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
84static struct netinfo *enter(struct inpcb *, int, const char *);
85static void enter_kvm(struct inpcb *, struct socket *, int, const char *);
86static void enter_sysctl(struct inpcb *, 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)		((w)->_maxy-1)
94
95WINDOW *
96opennetstat()
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(w)
126        WINDOW *w;
127{
128	struct netinfo *p;
129
130	endhostent();
131	endnetent();
132	TAILQ_FOREACH(p, &netcb, chain) {
133		if (p->ni_line != -1)
134			lastrow--;
135		p->ni_line = -1;
136	}
137        if (w != NULL) {
138		wclear(w);
139		wrefresh(w);
140		delwin(w);
141	}
142}
143
144static const char *miblist[] = {
145	"net.inet.tcp.pcblist",
146	"net.inet.udp.pcblist"
147};
148
149struct nlist namelist[] = {
150#define	X_TCB	0
151	{ "tcb" },
152#define	X_UDB	1
153	{ "udb" },
154	{ "" },
155};
156
157int
158initnetstat()
159{
160	protos = TCP|UDP;
161	return(1);
162}
163
164void
165fetchnetstat()
166{
167	if (use_kvm)
168		fetchnetstat_kvm();
169	else
170		fetchnetstat_sysctl();
171}
172
173static void
174fetchnetstat_kvm()
175{
176	struct inpcb *next;
177	struct netinfo *p;
178	struct inpcbhead head;
179	struct inpcb inpcb;
180	struct socket sockb;
181	struct tcpcb tcpcb;
182	void *off;
183	int istcp;
184
185	if (namelist[X_TCB].n_value == 0)
186		return;
187	TAILQ_FOREACH(p, &netcb, chain)
188		p->ni_seen = 0;
189	if (protos&TCP) {
190		off = NPTR(X_TCB);
191		istcp = 1;
192	}
193	else if (protos&UDP) {
194		off = NPTR(X_UDB);
195		istcp = 0;
196	}
197	else {
198		error("No protocols to display");
199		return;
200	}
201again:
202	KREAD(off, &head, sizeof (struct inpcbhead));
203	LIST_FOREACH(next, &head, inp_list) {
204		KREAD(next, &inpcb, sizeof (inpcb));
205		next = &inpcb;
206		if (!aflag) {
207			if (inpcb.inp_vflag & INP_IPV4) {
208				if (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY)
209					continue;
210			}
211#ifdef INET6
212			else if (inpcb.inp_vflag & INP_IPV6) {
213				if (memcmp(&inpcb.in6p_laddr,
214				    &in6addr_any, sizeof(in6addr_any)) == 0)
215					continue;
216			}
217#endif
218		}
219		if (nhosts && !checkhost(&inpcb))
220			continue;
221		if (nports && !checkport(&inpcb))
222			continue;
223		if (istcp) {
224			if (inpcb.inp_vflag & INP_TIMEWAIT) {
225				bzero(&sockb, sizeof(sockb));
226				enter_kvm(&inpcb, &sockb, TCPS_TIME_WAIT,
227					 "tcp");
228			} else {
229				KREAD(inpcb.inp_socket, &sockb,
230					sizeof (sockb));
231				KREAD(inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
232				enter_kvm(&inpcb, &sockb, tcpcb.t_state,
233					"tcp");
234			}
235		} else
236			enter_kvm(&inpcb, &sockb, 0, "udp");
237	}
238	if (istcp && (protos&UDP)) {
239		istcp = 0;
240		off = NPTR(X_UDB);
241		goto again;
242	}
243}
244
245static void
246fetchnetstat_sysctl()
247{
248	struct netinfo *p;
249	int idx;
250	struct xinpgen *inpg;
251	char *cur, *end;
252	struct inpcb *inpcb;
253	struct xinpcb *xip;
254	struct xtcpcb *xtp;
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				inpcb = &xtp->xt_inp;
299			} else {
300				xip = (struct xinpcb *)cur;
301				inpcb = &xip->xi_inp;
302			}
303			cur += plen;
304
305			if (!aflag) {
306				if (inpcb->inp_vflag & INP_IPV4) {
307					if (inet_lnaof(inpcb->inp_laddr) ==
308					    INADDR_ANY)
309						continue;
310				}
311#ifdef INET6
312				else if (inpcb->inp_vflag & INP_IPV6) {
313					if (memcmp(&inpcb->in6p_laddr,
314					    &in6addr_any, sizeof(in6addr_any))
315					    == 0)
316						continue;
317				}
318#endif
319			}
320			if (nhosts && !checkhost(inpcb))
321				continue;
322			if (nports && !checkport(inpcb))
323				continue;
324			if (idx == 0)	/* TCP */
325				enter_sysctl(inpcb, &xtp->xt_socket,
326				    xtp->xt_tp.t_state, "tcp");
327			else		/* UDP */
328				enter_sysctl(inpcb, &xip->xi_socket, 0, "udp");
329		}
330		free(inpg);
331	}
332}
333
334static void
335enter_kvm(inp, so, state, proto)
336	struct inpcb *inp;
337	struct socket *so;
338	int state;
339	const char *proto;
340{
341	struct netinfo *p;
342
343	if ((p = enter(inp, state, proto)) != NULL) {
344		p->ni_rcvcc = so->so_rcv.sb_cc;
345		p->ni_sndcc = so->so_snd.sb_cc;
346	}
347}
348
349static void
350enter_sysctl(inp, so, state, proto)
351	struct inpcb *inp;
352	struct xsocket *so;
353	int state;
354	const char *proto;
355{
356	struct netinfo *p;
357
358	if ((p = enter(inp, state, proto)) != NULL) {
359		p->ni_rcvcc = so->so_rcv.sb_cc;
360		p->ni_sndcc = so->so_snd.sb_cc;
361	}
362}
363
364
365static struct netinfo *
366enter(inp, state, proto)
367	struct inpcb *inp;
368	int state;
369	const char *proto;
370{
371	struct netinfo *p;
372	struct sockaddr_storage lsa, fsa;
373	struct sockaddr_in *sa4;
374#ifdef INET6
375	struct sockaddr_in6 *sa6;
376#endif
377
378	memset(&lsa, 0, sizeof(lsa));
379	memset(&fsa, 0, sizeof(fsa));
380	if (inp->inp_vflag & INP_IPV4) {
381		sa4 = (struct sockaddr_in *)&lsa;
382		sa4->sin_addr = inp->inp_laddr;
383		sa4->sin_port = inp->inp_lport;
384		sa4->sin_family = AF_INET;
385		sa4->sin_len = sizeof(struct sockaddr_in);
386
387		sa4 = (struct sockaddr_in *)&fsa;
388		sa4->sin_addr = inp->inp_faddr;
389		sa4->sin_port = inp->inp_fport;
390		sa4->sin_family = AF_INET;
391		sa4->sin_len = sizeof(struct sockaddr_in);
392	}
393#ifdef INET6
394	else if (inp->inp_vflag & INP_IPV6) {
395		sa6 = (struct sockaddr_in6 *)&lsa;
396		memcpy(&sa6->sin6_addr, &inp->in6p_laddr,
397		    sizeof(struct in6_addr));
398		sa6->sin6_port = inp->inp_lport;
399		sa6->sin6_family = AF_INET6;
400		sa6->sin6_len = sizeof(struct sockaddr_in6);
401
402		sa6 = (struct sockaddr_in6 *)&fsa;
403		memcpy(&sa6->sin6_addr, &inp->in6p_faddr,
404		    sizeof(struct in6_addr));
405		sa6->sin6_port = inp->inp_fport;
406		sa6->sin6_family = AF_INET6;
407		sa6->sin6_len = sizeof(struct sockaddr_in6);
408	}
409#endif
410	else
411		return NULL;
412
413	/*
414	 * Only take exact matches, any sockets with
415	 * previously unbound addresses will be deleted
416	 * below in the display routine because they
417	 * will appear as ``not seen'' in the kernel
418	 * data structures.
419	 */
420	TAILQ_FOREACH(p, &netcb, chain) {
421		if (!streq(proto, p->ni_proto))
422			continue;
423		if (p->ni_lsa.ss_family != lsa.ss_family ||
424		    memcmp(&p->ni_lsa, &lsa, lsa.ss_len) != 0)
425			continue;
426		if (p->ni_fsa.ss_family == fsa.ss_family &&
427		    memcmp(&p->ni_fsa, &fsa, fsa.ss_len) == 0)
428			break;
429	}
430	if (p == NULL) {
431		if ((p = malloc(sizeof(*p))) == NULL) {
432			error("Out of memory");
433			return NULL;
434		}
435		TAILQ_INSERT_HEAD(&netcb, p, chain);
436		p->ni_line = -1;
437		memcpy(&p->ni_lsa, &lsa, lsa.ss_len);
438		memcpy(&p->ni_fsa, &fsa, fsa.ss_len);
439		p->ni_proto = strdup(proto);
440		p->ni_flags = NIF_LACHG|NIF_FACHG;
441	}
442	p->ni_state = state;
443	p->ni_seen = 1;
444	return p;
445}
446
447/* column locations */
448#define	LADDR	0
449#define	FADDR	LADDR+23
450#define	PROTO	FADDR+23
451#define	RCVCC	PROTO+6
452#define	SNDCC	RCVCC+7
453#define	STATE	SNDCC+7
454
455
456void
457labelnetstat()
458{
459	if (use_kvm && namelist[X_TCB].n_type == 0)
460		return;
461	wmove(wnd, 0, 0); wclrtobot(wnd);
462	mvwaddstr(wnd, 0, LADDR, "Local Address");
463	mvwaddstr(wnd, 0, FADDR, "Foreign Address");
464	mvwaddstr(wnd, 0, PROTO, "Proto");
465	mvwaddstr(wnd, 0, RCVCC, "Recv-Q");
466	mvwaddstr(wnd, 0, SNDCC, "Send-Q");
467	mvwaddstr(wnd, 0, STATE, "(state)");
468}
469
470void
471shownetstat()
472{
473	struct netinfo *p, *q;
474	char proto[6], *family = "";
475
476	/*
477	 * First, delete any connections that have gone
478	 * away and adjust the position of connections
479	 * below to reflect the deleted line.
480	 */
481	p = TAILQ_FIRST(&netcb);
482	while (p != NULL) {
483		if (p->ni_line == -1 || p->ni_seen) {
484			p = TAILQ_NEXT(p, chain);
485			continue;
486		}
487		wmove(wnd, p->ni_line, 0); wdeleteln(wnd);
488		TAILQ_FOREACH(q, &netcb, chain)
489			if (q != p && q->ni_line > p->ni_line) {
490				q->ni_line--;
491				/* this shouldn't be necessary */
492				q->ni_flags |= NIF_LACHG|NIF_FACHG;
493			}
494		lastrow--;
495		q = TAILQ_NEXT(p, chain);
496		TAILQ_REMOVE(&netcb, p, chain);
497		free(p);
498		p = q;
499	}
500	/*
501	 * Update existing connections and add new ones.
502	 */
503	TAILQ_FOREACH(p, &netcb, chain) {
504		if (p->ni_line == -1) {
505			/*
506			 * Add a new entry if possible.
507			 */
508			if (lastrow > YMAX(wnd))
509				continue;
510			p->ni_line = lastrow++;
511			p->ni_flags |= NIF_LACHG|NIF_FACHG;
512		}
513		if (p->ni_flags & NIF_LACHG) {
514			wmove(wnd, p->ni_line, LADDR);
515			inetprint((struct sockaddr *)&p->ni_lsa, p->ni_proto);
516			p->ni_flags &= ~NIF_LACHG;
517		}
518		if (p->ni_flags & NIF_FACHG) {
519			wmove(wnd, p->ni_line, FADDR);
520			inetprint((struct sockaddr *)&p->ni_fsa, p->ni_proto);
521			p->ni_flags &= ~NIF_FACHG;
522		}
523#ifdef INET6
524		family = (p->ni_lsa.ss_family == AF_INET) ? "4" : "6";
525#endif
526		snprintf(proto, sizeof(proto), "%s%s", p->ni_proto, family);
527		mvwaddstr(wnd, p->ni_line, PROTO, proto);
528		mvwprintw(wnd, p->ni_line, RCVCC, "%6u", p->ni_rcvcc);
529		mvwprintw(wnd, p->ni_line, SNDCC, "%6u", p->ni_sndcc);
530		if (streq(p->ni_proto, "tcp")) {
531			if (p->ni_state < 0 || p->ni_state >= TCP_NSTATES)
532				mvwprintw(wnd, p->ni_line, STATE, "%d",
533				    p->ni_state);
534			else
535				mvwaddstr(wnd, p->ni_line, STATE,
536				    tcpstates[p->ni_state]);
537		}
538		wclrtoeol(wnd);
539	}
540	if (lastrow < YMAX(wnd)) {
541		wmove(wnd, lastrow, 0); wclrtobot(wnd);
542		wmove(wnd, YMAX(wnd), 0); wdeleteln(wnd);	/* XXX */
543	}
544}
545
546/*
547 * Pretty print an Internet address (net address + port).
548 * If the nflag was specified, use numbers instead of names.
549 */
550static void
551inetprint(sa, proto)
552	struct sockaddr *sa;
553	const char *proto;
554{
555	struct servent *sp = 0;
556	char line[80], *cp;
557	int port;
558
559	switch (sa->sa_family) {
560	case AF_INET:
561		port = ((struct sockaddr_in *)sa)->sin_port;
562		break;
563#ifdef INET6
564	case AF_INET6:
565		port = ((struct sockaddr_in6 *)sa)->sin6_port;
566		break;
567#endif
568	default:
569		port = 0;
570		break;
571	}
572	snprintf(line, sizeof(line), "%.*s.", 16, inetname(sa));
573	cp = index(line, '\0');
574	if (!nflag && port)
575		sp = getservbyport(port, proto);
576	if (sp || port == 0)
577		snprintf(cp, sizeof(line) - (cp - line), "%.8s",
578		    sp ? sp->s_name : "*");
579	else
580		snprintf(cp, sizeof(line) - (cp - line), "%d",
581		    ntohs((u_short)port));
582	/* pad to full column to clear any garbage */
583	cp = index(line, '\0');
584	while (cp - line < 22)
585		*cp++ = ' ';
586	line[22] = '\0';
587	waddstr(wnd, line);
588}
589
590/*
591 * Construct an Internet address representation.
592 * If the nflag has been supplied, give
593 * numeric value, otherwise try for symbolic name.
594 */
595static char *
596inetname(sa)
597	struct sockaddr *sa;
598{
599	char *cp = 0;
600	static char line[NI_MAXHOST];
601	struct hostent *hp;
602	struct netent *np;
603	struct in_addr in;
604
605#ifdef INET6
606	if (sa->sa_family == AF_INET6) {
607		if (memcmp(&((struct sockaddr_in6 *)sa)->sin6_addr,
608		    &in6addr_any, sizeof(in6addr_any)) == 0)
609			strcpy(line, "*");
610		else
611			getnameinfo(sa, sa->sa_len, line, sizeof(line), NULL, 0,
612			    nflag ? NI_NUMERICHOST : 0);
613		return (line);
614	}
615#endif
616
617	in = ((struct sockaddr_in *)sa)->sin_addr;
618	if (!nflag && in.s_addr != INADDR_ANY) {
619		int net = inet_netof(in);
620		int lna = inet_lnaof(in);
621
622		if (lna == INADDR_ANY) {
623			np = getnetbyaddr(net, AF_INET);
624			if (np)
625				cp = np->n_name;
626		}
627		if (cp == 0) {
628			hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
629			if (hp)
630				cp = hp->h_name;
631		}
632	}
633	if (in.s_addr == INADDR_ANY)
634		strcpy(line, "*");
635	else if (cp)
636		snprintf(line, sizeof(line), "%s", cp);
637	else {
638		in.s_addr = ntohl(in.s_addr);
639#define C(x)	((x) & 0xff)
640		snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in.s_addr >> 24),
641			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
642	}
643	return (line);
644}
645
646int
647cmdnetstat(cmd, args)
648	const char *cmd, *args;
649{
650	if (prefix(cmd, "all")) {
651		aflag = !aflag;
652		goto fixup;
653	}
654	if  (prefix(cmd, "numbers") || prefix(cmd, "names")) {
655		struct netinfo *p;
656		int new;
657
658		new = prefix(cmd, "numbers");
659		if (new == nflag)
660			return (1);
661		TAILQ_FOREACH(p, &netcb, chain) {
662			if (p->ni_line == -1)
663				continue;
664			p->ni_flags |= NIF_LACHG|NIF_FACHG;
665		}
666		nflag = new;
667		goto redisplay;
668	}
669	if (!netcmd(cmd, args))
670		return (0);
671fixup:
672	fetchnetstat();
673redisplay:
674	shownetstat();
675	refresh();
676	return (1);
677}
678