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