netstat.c revision 87715
1139825Simp/*-
268549Sbenno * Copyright (c) 1980, 1992, 1993
368549Sbenno *	The Regents of the University of California.  All rights reserved.
468549Sbenno *
568549Sbenno * Redistribution and use in source and binary forms, with or without
668549Sbenno * modification, are permitted provided that the following conditions
768549Sbenno * are met:
868549Sbenno * 1. Redistributions of source code must retain the above copyright
968549Sbenno *    notice, this list of conditions and the following disclaimer.
1068549Sbenno * 2. Redistributions in binary form must reproduce the above copyright
1168549Sbenno *    notice, this list of conditions and the following disclaimer in the
1268549Sbenno *    documentation and/or other materials provided with the distribution.
1368549Sbenno * 3. All advertising materials mentioning features or use of this software
1468549Sbenno *    must display the following acknowledgement:
1568549Sbenno *	This product includes software developed by the University of
1668549Sbenno *	California, Berkeley and its contributors.
1768549Sbenno * 4. Neither the name of the University nor the names of its contributors
1868549Sbenno *    may be used to endorse or promote products derived from this software
1968549Sbenno *    without specific prior written permission.
2068549Sbenno *
2168549Sbenno * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2268549Sbenno * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2368549Sbenno * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2468549Sbenno * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2568549Sbenno * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2668549Sbenno * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2768549Sbenno * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2868549Sbenno * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2968549Sbenno * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3070585Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3177944Sobrien * SUCH DAMAGE.
3270585Sobrien */
3368549Sbenno
3470585Sobrien#include <sys/cdefs.h>
3568549Sbenno
3668549Sbenno__FBSDID("$FreeBSD: head/usr.bin/systat/netstat.c 87715 2001-12-12 00:13:37Z markm $");
3768549Sbenno
38103614Sgrehan#ifdef lint
3968549Sbennostatic const char sccsid[] = "@(#)netstat.c	8.1 (Berkeley) 6/6/93";
4068549Sbenno#endif
4168549Sbenno
4268549Sbenno/*
4368549Sbenno * netstat
4468549Sbenno */
4568549Sbenno#include <sys/param.h>
4668549Sbenno#include <sys/queue.h>
4768549Sbenno#include <sys/socket.h>
4868549Sbenno#include <sys/socketvar.h>
4968549Sbenno#include <sys/protosw.h>
5068549Sbenno
5168549Sbenno#include <netinet/in.h>
5268549Sbenno#include <arpa/inet.h>
53209975Snwhitehorn#include <net/route.h>
54209975Snwhitehorn#include <netinet/in_systm.h>
5568549Sbenno#include <netinet/ip.h>
5668549Sbenno#include <netinet/in_pcb.h>
5768549Sbenno#include <netinet/ip_icmp.h>
58209975Snwhitehorn#include <netinet/icmp_var.h>
59279601Snwhitehorn#include <netinet/ip_var.h>
60176742Sraj#include <netinet/tcp.h>
61176742Sraj#include <netinet/tcpip.h>
62279601Snwhitehorn#include <netinet/tcp_seq.h>
63209975Snwhitehorn#include <netinet/tcp_var.h>
64176742Sraj#define TCPSTATES
65176742Sraj#include <netinet/tcp_fsm.h>
66176742Sraj#include <netinet/tcp_timer.h>
67189100Sraj#include <netinet/tcp_var.h>
68176742Sraj#include <netinet/tcp_debug.h>
69176742Sraj#include <netinet/udp.h>
7068549Sbenno#include <netinet/udp_var.h>
71176742Sraj
7268549Sbenno#include <netdb.h>
73209975Snwhitehorn#include <nlist.h>
74209975Snwhitehorn#include <paths.h>
75209975Snwhitehorn#include <stdlib.h>
76209975Snwhitehorn#include <string.h>
7768549Sbenno
78209975Snwhitehorn#include "systat.h"
79209975Snwhitehorn#include "extern.h"
8083682Smp
8168549Sbennostatic struct netinfo *enter __P((struct inpcb *, int, const char *));
8268549Sbennostatic void enter_kvm __P((struct inpcb *, struct socket *, int, const char *));
8368549Sbennostatic void enter_sysctl __P((struct inpcb *, struct xsocket *, int, const char *));
8468549Sbennostatic void fetchnetstat_kvm __P((void));
85209975Snwhitehornstatic void fetchnetstat_sysctl __P((void));
8668549Sbennostatic char *inetname __P((struct in_addr));
87132520Sgrehanstatic void inetprint __P((struct in_addr *, int, const char *));
88209975Snwhitehorn
89209975Snwhitehorn#define	streq(a,b)	(strcmp(a,b)==0)
90209975Snwhitehorn#define	YMAX(w)		((w)->_maxy-1)
91209975Snwhitehorn
92209975SnwhitehornWINDOW *
93209975Snwhitehornopennetstat()
94209975Snwhitehorn{
95209975Snwhitehorn	sethostent(1);
96255273Snwhitehorn	setnetent(1);
97209975Snwhitehorn	return (subwin(stdscr, LINES-5-1, 0, 5, 0));
98209975Snwhitehorn}
99209975Snwhitehorn
100209975Snwhitehornstruct netinfo {
101132520Sgrehan	TAILQ_ENTRY(netinfo) chain;
10291467Sbenno	short	ni_line;		/* line on screen */
10391467Sbenno	short	ni_seen;		/* 0 when not present in list */
10491467Sbenno	short	ni_flags;
105255282Snwhitehorn#define	NIF_LACHG	0x1		/* local address changed */
10668549Sbenno#define	NIF_FACHG	0x2		/* foreign address changed */
107209975Snwhitehorn	short	ni_state;		/* tcp state */
10868549Sbenno	const char	*ni_proto;		/* protocol */
10997397Sbenno	struct	in_addr ni_laddr;	/* local address */
11097397Sbenno	long	ni_lport;		/* local port */
11197397Sbenno	struct	in_addr	ni_faddr;	/* foreign address */
112209975Snwhitehorn	long	ni_fport;		/* foreign port */
113209975Snwhitehorn	long	ni_rcvcc;		/* rcv buffer character count */
11497397Sbenno	long	ni_sndcc;		/* snd buffer character count */
11568549Sbenno};
116
117TAILQ_HEAD(netinfohead, netinfo) netcb = TAILQ_HEAD_INITIALIZER(netcb);
118
119static	int aflag = 0;
120static	int nflag = 0;
121static	int lastrow = 1;
122
123void
124closenetstat(w)
125        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
148struct nlist namelist[] = {
149#define	X_TCB	0
150	{ "tcb" },
151#define	X_UDB	1
152	{ "udb" },
153	{ "" },
154};
155
156int
157initnetstat()
158{
159	protos = TCP|UDP;
160	return(1);
161}
162
163void
164fetchnetstat()
165{
166	if (use_kvm)
167		fetchnetstat_kvm();
168	else
169		fetchnetstat_sysctl();
170}
171
172static void
173fetchnetstat_kvm()
174{
175	struct inpcb *next;
176	struct netinfo *p;
177	struct inpcbhead head;
178	struct inpcb inpcb;
179	struct socket sockb;
180	struct tcpcb tcpcb;
181	void *off;
182	int istcp;
183
184	if (namelist[X_TCB].n_value == 0)
185		return;
186	TAILQ_FOREACH(p, &netcb, chain)
187		p->ni_seen = 0;
188	if (protos&TCP) {
189		off = NPTR(X_TCB);
190		istcp = 1;
191	}
192	else if (protos&UDP) {
193		off = NPTR(X_UDB);
194		istcp = 0;
195	}
196	else {
197		error("No protocols to display");
198		return;
199	}
200again:
201	KREAD(off, &head, sizeof (struct inpcbhead));
202	LIST_FOREACH(next, &head, inp_list) {
203		KREAD(next, &inpcb, sizeof (inpcb));
204		next = &inpcb;
205		if (!aflag && inet_lnaof(inpcb.inp_laddr) == INADDR_ANY)
206			continue;
207		if (nhosts && !checkhost(&inpcb))
208			continue;
209		if (nports && !checkport(&inpcb))
210			continue;
211		KREAD(inpcb.inp_socket, &sockb, sizeof (sockb));
212		if (istcp) {
213			KREAD(inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
214			enter_kvm(&inpcb, &sockb, tcpcb.t_state, "tcp");
215		} else
216			enter_kvm(&inpcb, &sockb, 0, "udp");
217	}
218	if (istcp && (protos&UDP)) {
219		istcp = 0;
220		off = NPTR(X_UDB);
221		goto again;
222	}
223}
224
225static void
226fetchnetstat_sysctl()
227{
228	struct netinfo *p;
229	int idx;
230	struct xinpgen *inpg;
231	char *cur, *end;
232	struct inpcb *inpcb;
233	struct xinpcb *xip;
234	struct xtcpcb *xtp;
235	int plen;
236	size_t lsz;
237
238	TAILQ_FOREACH(p, &netcb, chain)
239		p->ni_seen = 0;
240	if (protos&TCP) {
241		idx = 0;
242	} else if (protos&UDP) {
243		idx = 1;
244	} else {
245		error("No protocols to display");
246		return;
247	}
248
249	for (;idx < 2; idx++) {
250		if (idx == 1 && !(protos&UDP))
251			break;
252		inpg = (struct xinpgen *)sysctl_dynread(miblist[idx], &lsz);
253		if (inpg == NULL) {
254			error("sysctl(%s...) failed", miblist[idx]);
255			continue;
256		}
257		/*
258		 * We currently do no require a consistent pcb list.
259		 * Try to be robust in case of struct size changes
260		 */
261		cur = ((char *)inpg) + inpg->xig_len;
262		/* There is also a trailing struct xinpgen */
263		end = ((char *)inpg) + lsz - inpg->xig_len;
264		if (end <= cur) {
265			free(inpg);
266			continue;
267		}
268		if (idx == 0) { /* TCP */
269			xtp = (struct xtcpcb *)cur;
270			plen = xtp->xt_len;
271		} else {
272			xip = (struct xinpcb *)cur;
273			plen = xip->xi_len;
274		}
275		while (cur + plen <= end) {
276			if (idx == 0) { /* TCP */
277				xtp = (struct xtcpcb *)cur;
278				inpcb = &xtp->xt_inp;
279			} else {
280				xip = (struct xinpcb *)cur;
281				inpcb = &xip->xi_inp;
282			}
283			cur += plen;
284
285			if (!aflag && inet_lnaof(inpcb->inp_laddr) ==
286			    INADDR_ANY)
287				continue;
288			if (nhosts && !checkhost(inpcb))
289				continue;
290			if (nports && !checkport(inpcb))
291				continue;
292			if (idx == 0)	/* TCP */
293				enter_sysctl(inpcb, &xtp->xt_socket,
294				    xtp->xt_tp.t_state, "tcp");
295			else		/* UDP */
296				enter_sysctl(inpcb, &xip->xi_socket, 0, "udp");
297		}
298		free(inpg);
299	}
300}
301
302static void
303enter_kvm(inp, so, state, proto)
304	struct inpcb *inp;
305	struct socket *so;
306	int state;
307	const char *proto;
308{
309	struct netinfo *p;
310
311	if ((p = enter(inp, state, proto)) != NULL) {
312		p->ni_rcvcc = so->so_rcv.sb_cc;
313		p->ni_sndcc = so->so_snd.sb_cc;
314	}
315}
316
317static void
318enter_sysctl(inp, so, state, proto)
319	struct inpcb *inp;
320	struct xsocket *so;
321	int state;
322	const char *proto;
323{
324	struct netinfo *p;
325
326	if ((p = enter(inp, state, proto)) != NULL) {
327		p->ni_rcvcc = so->so_rcv.sb_cc;
328		p->ni_sndcc = so->so_snd.sb_cc;
329	}
330}
331
332
333static struct netinfo *
334enter(inp, state, proto)
335	struct inpcb *inp;
336	int state;
337	const char *proto;
338{
339	struct netinfo *p;
340
341	/*
342	 * Only take exact matches, any sockets with
343	 * previously unbound addresses will be deleted
344	 * below in the display routine because they
345	 * will appear as ``not seen'' in the kernel
346	 * data structures.
347	 */
348	TAILQ_FOREACH(p, &netcb, chain) {
349		if (!streq(proto, p->ni_proto))
350			continue;
351		if (p->ni_lport != inp->inp_lport ||
352		    p->ni_laddr.s_addr != inp->inp_laddr.s_addr)
353			continue;
354		if (p->ni_faddr.s_addr == inp->inp_faddr.s_addr &&
355		    p->ni_fport == inp->inp_fport)
356			break;
357	}
358	if (p == NULL) {
359		if ((p = malloc(sizeof(*p))) == NULL) {
360			error("Out of memory");
361			return NULL;
362		}
363		TAILQ_INSERT_HEAD(&netcb, p, chain);
364		p->ni_line = -1;
365		p->ni_laddr = inp->inp_laddr;
366		p->ni_lport = inp->inp_lport;
367		p->ni_faddr = inp->inp_faddr;
368		p->ni_fport = inp->inp_fport;
369		p->ni_proto = strdup(proto);
370		p->ni_flags = NIF_LACHG|NIF_FACHG;
371	}
372	p->ni_state = state;
373	p->ni_seen = 1;
374	return p;
375}
376
377/* column locations */
378#define	LADDR	0
379#define	FADDR	LADDR+23
380#define	PROTO	FADDR+23
381#define	RCVCC	PROTO+6
382#define	SNDCC	RCVCC+7
383#define	STATE	SNDCC+7
384
385
386void
387labelnetstat()
388{
389	if (use_kvm && namelist[X_TCB].n_type == 0)
390		return;
391	wmove(wnd, 0, 0); wclrtobot(wnd);
392	mvwaddstr(wnd, 0, LADDR, "Local Address");
393	mvwaddstr(wnd, 0, FADDR, "Foreign Address");
394	mvwaddstr(wnd, 0, PROTO, "Proto");
395	mvwaddstr(wnd, 0, RCVCC, "Recv-Q");
396	mvwaddstr(wnd, 0, SNDCC, "Send-Q");
397	mvwaddstr(wnd, 0, STATE, "(state)");
398}
399
400void
401shownetstat()
402{
403	struct netinfo *p, *q;
404
405	/*
406	 * First, delete any connections that have gone
407	 * away and adjust the position of connections
408	 * below to reflect the deleted line.
409	 */
410	p = TAILQ_FIRST(&netcb);
411	while (p != NULL) {
412		if (p->ni_line == -1 || p->ni_seen) {
413			p = TAILQ_NEXT(p, chain);
414			continue;
415		}
416		wmove(wnd, p->ni_line, 0); wdeleteln(wnd);
417		TAILQ_FOREACH(q, &netcb, chain)
418			if (q != p && q->ni_line > p->ni_line) {
419				q->ni_line--;
420				/* this shouldn't be necessary */
421				q->ni_flags |= NIF_LACHG|NIF_FACHG;
422			}
423		lastrow--;
424		q = TAILQ_NEXT(p, chain);
425		TAILQ_REMOVE(&netcb, p, chain);
426		free(p);
427		p = q;
428	}
429	/*
430	 * Update existing connections and add new ones.
431	 */
432	TAILQ_FOREACH(p, &netcb, chain) {
433		if (p->ni_line == -1) {
434			/*
435			 * Add a new entry if possible.
436			 */
437			if (lastrow > YMAX(wnd))
438				continue;
439			p->ni_line = lastrow++;
440			p->ni_flags |= NIF_LACHG|NIF_FACHG;
441		}
442		if (p->ni_flags & NIF_LACHG) {
443			wmove(wnd, p->ni_line, LADDR);
444			inetprint(&p->ni_laddr, p->ni_lport, p->ni_proto);
445			p->ni_flags &= ~NIF_LACHG;
446		}
447		if (p->ni_flags & NIF_FACHG) {
448			wmove(wnd, p->ni_line, FADDR);
449			inetprint(&p->ni_faddr, p->ni_fport, p->ni_proto);
450			p->ni_flags &= ~NIF_FACHG;
451		}
452		mvwaddstr(wnd, p->ni_line, PROTO, p->ni_proto);
453		mvwprintw(wnd, p->ni_line, RCVCC, "%6d", p->ni_rcvcc);
454		mvwprintw(wnd, p->ni_line, SNDCC, "%6d", p->ni_sndcc);
455		if (streq(p->ni_proto, "tcp")) {
456			if (p->ni_state < 0 || p->ni_state >= TCP_NSTATES)
457				mvwprintw(wnd, p->ni_line, STATE, "%d",
458				    p->ni_state);
459			else
460				mvwaddstr(wnd, p->ni_line, STATE,
461				    tcpstates[p->ni_state]);
462		}
463		wclrtoeol(wnd);
464	}
465	if (lastrow < YMAX(wnd)) {
466		wmove(wnd, lastrow, 0); wclrtobot(wnd);
467		wmove(wnd, YMAX(wnd), 0); wdeleteln(wnd);	/* XXX */
468	}
469}
470
471/*
472 * Pretty print an Internet address (net address + port).
473 * If the nflag was specified, use numbers instead of names.
474 */
475static void
476inetprint(in, port, proto)
477	struct in_addr *in;
478	int port;
479	const char *proto;
480{
481	struct servent *sp = 0;
482	char line[80], *cp;
483
484	snprintf(line, sizeof(line), "%.*s.", 16, inetname(*in));
485	cp = index(line, '\0');
486	if (!nflag && port)
487		sp = getservbyport(port, proto);
488	if (sp || port == 0)
489		snprintf(cp, sizeof(line) - (cp - line), "%.8s",
490		    sp ? sp->s_name : "*");
491	else
492		snprintf(cp, sizeof(line) - (cp - line), "%d",
493		    ntohs((u_short)port));
494	/* pad to full column to clear any garbage */
495	cp = index(line, '\0');
496	while (cp - line < 22)
497		*cp++ = ' ';
498	line[22] = '\0';
499	waddstr(wnd, line);
500}
501
502/*
503 * Construct an Internet address representation.
504 * If the nflag has been supplied, give
505 * numeric value, otherwise try for symbolic name.
506 */
507static char *
508inetname(in)
509	struct in_addr in;
510{
511	char *cp = 0;
512	static char line[50];
513	struct hostent *hp;
514	struct netent *np;
515
516	if (!nflag && in.s_addr != INADDR_ANY) {
517		int net = inet_netof(in);
518		int lna = inet_lnaof(in);
519
520		if (lna == INADDR_ANY) {
521			np = getnetbyaddr(net, AF_INET);
522			if (np)
523				cp = np->n_name;
524		}
525		if (cp == 0) {
526			hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
527			if (hp)
528				cp = hp->h_name;
529		}
530	}
531	if (in.s_addr == INADDR_ANY)
532		strcpy(line, "*");
533	else if (cp)
534		snprintf(line, sizeof(line), "%s", cp);
535	else {
536		in.s_addr = ntohl(in.s_addr);
537#define C(x)	((x) & 0xff)
538		snprintf(line, sizeof(line), "%u.%u.%u.%u", C(in.s_addr >> 24),
539			C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
540	}
541	return (line);
542}
543
544int
545cmdnetstat(cmd, args)
546	const char *cmd, *args;
547{
548	if (prefix(cmd, "all")) {
549		aflag = !aflag;
550		goto fixup;
551	}
552	if  (prefix(cmd, "numbers") || prefix(cmd, "names")) {
553		struct netinfo *p;
554		int new;
555
556		new = prefix(cmd, "numbers");
557		if (new == nflag)
558			return (1);
559		TAILQ_FOREACH(p, &netcb, chain) {
560			if (p->ni_line == -1)
561				continue;
562			p->ni_flags |= NIF_LACHG|NIF_FACHG;
563		}
564		nflag = new;
565		goto redisplay;
566	}
567	if (!netcmd(cmd, args))
568		return (0);
569fixup:
570	fetchnetstat();
571redisplay:
572	shownetstat();
573	refresh();
574	return (1);
575}
576