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