trpt.c revision 1.26
1/*	$OpenBSD: trpt.c,v 1.26 2010/05/26 17:49:57 deraadt Exp $	*/
2
3/*-
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33/*
34 * Copyright (c) 1983, 1988, 1993
35 *	The Regents of the University of California.  All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 *    notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 *    notice, this list of conditions and the following disclaimer in the
44 *    documentation and/or other materials provided with the distribution.
45 * 3. Neither the name of the University nor the names of its contributors
46 *    may be used to endorse or promote products derived from this software
47 *    without specific prior written permission.
48 *
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * SUCH DAMAGE.
60 */
61
62#include <sys/param.h>
63#include <sys/queue.h>
64#include <sys/socket.h>
65#include <sys/socketvar.h>
66#define PRUREQUESTS
67#include <sys/protosw.h>
68#define _KERNEL
69#include <sys/timeout.h>		/* to get timeout_pending() and such */
70#undef _KERNEL
71#include <sys/file.h>
72
73#include <net/route.h>
74#include <net/if.h>
75
76#include <netinet/in.h>
77#include <netinet/in_systm.h>
78#include <netinet/ip.h>
79#include <netinet/in_pcb.h>
80#include <netinet/ip_var.h>
81#include <netinet/tcp.h>
82#define TCPSTATES
83#include <netinet/tcp_fsm.h>
84#include <netinet/tcp_seq.h>
85#define	TCPTIMERS
86#include <netinet/tcp_timer.h>
87#include <netinet/tcp_var.h>
88#include <netinet/tcpip.h>
89#define	TANAMES
90#include <netinet/tcp_debug.h>
91
92#include <arpa/inet.h>
93
94#include <err.h>
95#include <stdio.h>
96#include <errno.h>
97#include <kvm.h>
98#include <nlist.h>
99#include <paths.h>
100#include <limits.h>
101#include <stdlib.h>
102#include <unistd.h>
103
104struct nlist nl[] = {
105#define	N_TCP_DEBUG	0		/* no sysctl */
106	{ "_tcp_debug" },
107#define	N_TCP_DEBX	1		/* no sysctl */
108	{ "_tcp_debx" },
109	{ NULL },
110};
111
112int	tcp_debx;
113struct	tcp_debug tcp_debug[TCP_NDEBUG];
114
115static caddr_t tcp_pcbs[TCP_NDEBUG];
116static n_time ntime;
117static int aflag, follow, sflag, tflag;
118
119extern	char *__progname;
120
121void	dotrace(caddr_t);
122void	tcp_trace(short, short, struct tcpcb *, struct tcpiphdr *,
123	    struct tcpipv6hdr *, int);
124int	numeric(const void *, const void *);
125void	usage(void);
126
127kvm_t	*kd;
128
129int
130main(int argc, char *argv[])
131{
132	char *sys = NULL, *core = NULL, *cp, errbuf[_POSIX2_LINE_MAX];
133	int ch, i, jflag = 0, npcbs = 0;
134	unsigned long l;
135	gid_t gid;
136
137	while ((ch = getopt(argc, argv, "afjM:N:p:st")) != -1) {
138		switch (ch) {
139		case 'a':
140			++aflag;
141			break;
142		case 'f':
143			++follow;
144			setlinebuf(stdout);
145			break;
146		case 'j':
147			++jflag;
148			break;
149		case 'p':
150			if (npcbs >= TCP_NDEBUG)
151				errx(1, "too many pcbs specified");
152			errno = 0;
153			l = strtoul(optarg, &cp, 16);
154			tcp_pcbs[npcbs] = (caddr_t)l;
155			if (*optarg == '\0' || *cp != '\0' || errno ||
156			    (unsigned long)tcp_pcbs[npcbs] != l)
157				errx(1, "invalid address: %s", optarg);
158			npcbs++;
159			break;
160		case 's':
161			++sflag;
162			break;
163		case 't':
164			++tflag;
165			break;
166		case 'N':
167			sys = optarg;
168			break;
169		case 'M':
170			core = optarg;
171			break;
172		default:
173			usage();
174			/* NOTREACHED */
175		}
176	}
177	argc -= optind;
178	argv += optind;
179
180	if (argc)
181		usage();
182
183	/*
184	 * Discard setgid privileged if not the running kernel so that bad
185	 * guys can't print interesting stuff from kernel memory.
186	 */
187	gid = getgid();
188	if (core != NULL || sys != NULL)
189		if (setresgid(gid, gid, gid) == -1)
190			err(1, "setresgid");
191
192	kd = kvm_openfiles(sys, core, NULL, O_RDONLY, errbuf);
193	if (kd == NULL)
194		errx(1, "can't open kmem: %s", errbuf);
195
196	if (core == NULL && sys == NULL)
197		if (setresgid(gid, gid, gid) == -1)
198			err(1, "setresgid");
199
200	if (kvm_nlist(kd, nl))
201		errx(2, "%s: no namelist", sys ? sys : _PATH_UNIX);
202
203	if (kvm_read(kd, nl[N_TCP_DEBX].n_value, (char *)&tcp_debx,
204	    sizeof(tcp_debx)) != sizeof(tcp_debx))
205		errx(3, "tcp_debx: %s", kvm_geterr(kd));
206
207	if (kvm_read(kd, nl[N_TCP_DEBUG].n_value, (char *)tcp_debug,
208	    sizeof(tcp_debug)) != sizeof(tcp_debug))
209		errx(3, "tcp_debug: %s", kvm_geterr(kd));
210
211	/*
212	 * If no control blocks have been specified, figure
213	 * out how many distinct one we have and summarize
214	 * them in tcp_pcbs for sorting the trace records
215	 * below.
216	 */
217	if (npcbs == 0) {
218		for (i = 0; i < TCP_NDEBUG; i++) {
219			struct tcp_debug *td = &tcp_debug[i];
220			int j;
221
222			if (td->td_tcb == 0)
223				continue;
224			for (j = 0; j < npcbs; j++)
225				if (tcp_pcbs[j] == td->td_tcb)
226					break;
227			if (j >= npcbs)
228				tcp_pcbs[npcbs++] = td->td_tcb;
229		}
230		if (npcbs == 0)
231			exit(0);
232	}
233	qsort(tcp_pcbs, npcbs, sizeof(caddr_t), numeric);
234	if (jflag) {
235		for (i = 0;;) {
236			printf("%lx", (long)tcp_pcbs[i]);
237			if (++i == npcbs)
238				break;
239			fputs(", ", stdout);
240		}
241		putchar('\n');
242	} else {
243		for (i = 0; i < npcbs; i++) {
244			printf("\n%lx:\n", (long)tcp_pcbs[i]);
245			dotrace(tcp_pcbs[i]);
246		}
247	}
248	exit(0);
249}
250
251void
252dotrace(caddr_t tcpcb)
253{
254	struct tcp_debug *td;
255	int prev_debx = tcp_debx;
256	int i;
257
258 again:
259	if (--tcp_debx < 0)
260		tcp_debx = TCP_NDEBUG - 1;
261	for (i = prev_debx % TCP_NDEBUG; i < TCP_NDEBUG; i++) {
262		td = &tcp_debug[i];
263		if (tcpcb && td->td_tcb != tcpcb)
264			continue;
265		ntime = ntohl(td->td_time);
266		tcp_trace(td->td_act, td->td_ostate,
267		    &td->td_cb, &td->td_ti,
268		    &td->td_ti6, td->td_req);
269		if (i == tcp_debx)
270			goto done;
271	}
272	for (i = 0; i <= tcp_debx % TCP_NDEBUG; i++) {
273		td = &tcp_debug[i];
274		if (tcpcb && td->td_tcb != tcpcb)
275			continue;
276		ntime = ntohl(td->td_time);
277		tcp_trace(td->td_act, td->td_ostate,
278		    &td->td_cb, &td->td_ti,
279		    &td->td_ti6, td->td_req);
280	}
281 done:
282	if (follow) {
283		prev_debx = tcp_debx + 1;
284		if (prev_debx >= TCP_NDEBUG)
285			prev_debx = 0;
286		do {
287			sleep(1);
288			if (kvm_read(kd, nl[N_TCP_DEBX].n_value,
289			    (char *)&tcp_debx, sizeof(tcp_debx)) !=
290			    sizeof(tcp_debx))
291				errx(3, "tcp_debx: %s", kvm_geterr(kd));
292		} while (tcp_debx == prev_debx);
293
294		if (kvm_read(kd, nl[N_TCP_DEBUG].n_value, (char *)tcp_debug,
295		    sizeof(tcp_debug)) != sizeof(tcp_debug))
296			errx(3, "tcp_debug: %s", kvm_geterr(kd));
297
298		goto again;
299	}
300}
301
302/*
303 * Tcp debug routines
304 */
305/*ARGSUSED*/
306void
307tcp_trace(short act, short ostate, struct tcpcb *tp,
308    struct tcpiphdr *ti, struct tcpipv6hdr *ti6, int req)
309{
310	tcp_seq seq, ack;
311	int flags, len, win, timer;
312	struct tcphdr *th;
313	char hbuf[INET6_ADDRSTRLEN];
314
315	if (ti->ti_src.s_addr)
316		th = &ti->ti_t;
317	else
318		th = &ti6->ti6_t;
319
320	printf("%03d %s:%s ", (ntime/10) % 1000, tcpstates[ostate],
321	    tanames[act]);
322	switch (act) {
323	case TA_INPUT:
324	case TA_OUTPUT:
325	case TA_DROP:
326		if (aflag) {
327			if (ti->ti_src.s_addr) {
328				printf("(src=%s,%u, ",
329				    inet_ntoa(ti->ti_src), ntohs(ti->ti_sport));
330				printf("dst=%s,%u)",
331				    inet_ntoa(ti->ti_dst), ntohs(ti->ti_dport));
332			} else {
333				printf("(src=%s,%u, ",
334				    inet_ntop(AF_INET6, &ti6->ti6_src,
335				    hbuf, sizeof(hbuf)), ntohs(ti->ti_sport));
336				printf("dst=%s,%u)",
337				    inet_ntop(AF_INET6, &ti6->ti6_dst,
338				    hbuf, sizeof(hbuf)), ntohs(ti->ti_dport));
339			}
340		}
341		seq = th->th_seq;
342		ack = th->th_ack;
343		if (ti->ti_src.s_addr)
344			len = ti->ti_len;
345		else
346			len = ti6->ti6_plen;	/*XXX intermediate header*/
347		win = th->th_win;
348		if (act == TA_OUTPUT) {
349			NTOHL(seq);
350			NTOHL(ack);
351			NTOHS(win);
352		}
353		if (len)
354			printf("[%x..%x)", seq, seq + len);
355		else
356			printf("%x", seq);
357		printf("@%x", ack);
358		if (win)
359			printf("(win=%x)", win);
360		flags = th->th_flags;
361		if (flags) {
362			char *cp = "<";
363#define	pf(flag, string) { \
364	if (th->th_flags & flag) { \
365		(void)printf("%s%s", cp, string); \
366		cp = ","; \
367	} \
368}
369			pf(TH_SYN, "SYN");
370			pf(TH_ACK, "ACK");
371			pf(TH_FIN, "FIN");
372			pf(TH_RST, "RST");
373			pf(TH_PUSH, "PUSH");
374			pf(TH_URG, "URG");
375			printf(">");
376		}
377		break;
378	case TA_USER:
379		timer = req >> 8;
380		req &= 0xff;
381		printf("%s", prurequests[req]);
382		if (req == PRU_SLOWTIMO || req == PRU_FASTTIMO)
383			printf("<%s>", tcptimers[timer]);
384		break;
385	}
386	printf(" -> %s", tcpstates[tp->t_state]);
387	/* print out internal state of tp !?! */
388	printf("\n");
389	if (sflag) {
390		printf("\trcv_nxt %x rcv_wnd %lx snd_una %x snd_nxt %x snd_max %x\n",
391		    tp->rcv_nxt, tp->rcv_wnd, tp->snd_una, tp->snd_nxt,
392		    tp->snd_max);
393		printf("\tsnd_wl1 %x snd_wl2 %x snd_wnd %lx\n", tp->snd_wl1,
394		    tp->snd_wl2, tp->snd_wnd);
395	}
396	/* print out timers? */
397	if (tflag) {
398		char *cp = "\t";
399		int i;
400
401		for (i = 0; i < TCPT_NTIMERS; i++) {
402			if (timeout_pending(&tp->t_timer[i]))
403				continue;
404			printf("%s%s=%d", cp, tcptimers[i],
405			    tp->t_timer[i].to_time);
406			if (i == TCPT_REXMT)
407				printf(" (t_rxtshft=%d)", tp->t_rxtshift);
408			cp = ", ";
409		}
410		if (*cp != '\t')
411			putchar('\n');
412	}
413}
414
415int
416numeric(const void *v1, const void *v2)
417{
418	const caddr_t *c1 = v1;
419	const caddr_t *c2 = v2;
420	int rv;
421
422	if (*c1 < *c2)
423		rv = -1;
424	else if (*c1 > *c2)
425		rv = 1;
426	else
427		rv = 0;
428
429	return (rv);
430}
431
432void
433usage(void)
434{
435
436	(void) fprintf(stderr, "usage: %s [-afjst] [-M core]"
437	    " [-N system] [-p hex-address]\n", __progname);
438	exit(1);
439}
440