xref: /openbsd-src/usr.sbin/trpt/trpt.c (revision 2b0358df1d88d06ef4139321dd05bd5e05d91eaf)
1 /*	$OpenBSD: trpt.c,v 1.24 2008/06/26 05:42:21 ray 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 #ifndef lint
63 char copyright[] =
64 "@(#) Copyright (c) 1983, 1988, 1993\n\
65 	The Regents of the University of California.  All rights reserved.\n";
66 #endif /* not lint */
67 
68 #ifndef lint
69 static char sccsid[] = "@(#)trpt.c	8.1 (Berkeley) 6/6/93";
70 #endif /* not lint */
71 
72 #include <sys/param.h>
73 #include <sys/queue.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #define PRUREQUESTS
77 #include <sys/protosw.h>
78 #include <sys/file.h>
79 
80 #include <net/route.h>
81 #include <net/if.h>
82 
83 #include <netinet/in.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/ip.h>
86 #include <netinet/in_pcb.h>
87 #include <netinet/ip_var.h>
88 #include <netinet/tcp.h>
89 #define TCPSTATES
90 #include <netinet/tcp_fsm.h>
91 #include <netinet/tcp_seq.h>
92 #define	TCPTIMERS
93 #include <netinet/tcp_timer.h>
94 #include <netinet/tcp_var.h>
95 #include <netinet/tcpip.h>
96 #define	TANAMES
97 #include <netinet/tcp_debug.h>
98 
99 #include <arpa/inet.h>
100 
101 #include <err.h>
102 #include <stdio.h>
103 #include <errno.h>
104 #include <kvm.h>
105 #include <nlist.h>
106 #include <paths.h>
107 #include <limits.h>
108 #include <stdlib.h>
109 #include <unistd.h>
110 
111 struct nlist nl[] = {
112 #define	N_TCP_DEBUG	0		/* no sysctl */
113 	{ "_tcp_debug" },
114 #define	N_TCP_DEBX	1		/* no sysctl */
115 	{ "_tcp_debx" },
116 	{ NULL },
117 };
118 
119 int	tcp_debx;
120 struct	tcp_debug tcp_debug[TCP_NDEBUG];
121 
122 static caddr_t tcp_pcbs[TCP_NDEBUG];
123 static n_time ntime;
124 static int aflag, follow, sflag, tflag;
125 
126 extern	char *__progname;
127 
128 void	dotrace(caddr_t);
129 void	tcp_trace(short, short, struct tcpcb *, struct tcpiphdr *,
130 	    struct tcpipv6hdr *, int);
131 int	numeric(const void *, const void *);
132 void	usage(void);
133 
134 kvm_t	*kd;
135 
136 int
137 main(int argc, char *argv[])
138 {
139 	char *sys = NULL, *core = NULL, *cp, errbuf[_POSIX2_LINE_MAX];
140 	int ch, i, jflag = 0, npcbs = 0;
141 	unsigned long l;
142 	gid_t gid;
143 
144 	while ((ch = getopt(argc, argv, "afjM:N:p:st")) != -1) {
145 		switch (ch) {
146 		case 'a':
147 			++aflag;
148 			break;
149 		case 'f':
150 			++follow;
151 			setlinebuf(stdout);
152 			break;
153 		case 'j':
154 			++jflag;
155 			break;
156 		case 'p':
157 			if (npcbs >= TCP_NDEBUG)
158 				errx(1, "too many pcbs specified");
159 			errno = 0;
160 			l = strtoul(optarg, &cp, 16);
161 			tcp_pcbs[npcbs] = (caddr_t)l;
162 			if (*optarg == '\0' || *cp != '\0' || errno ||
163 			    (unsigned long)tcp_pcbs[npcbs] != l)
164 				errx(1, "invalid address: %s", optarg);
165 			npcbs++;
166 			break;
167 		case 's':
168 			++sflag;
169 			break;
170 		case 't':
171 			++tflag;
172 			break;
173 		case 'N':
174 			sys = optarg;
175 			break;
176 		case 'M':
177 			core = optarg;
178 			break;
179 		default:
180 			usage();
181 			/* NOTREACHED */
182 		}
183 	}
184 	argc -= optind;
185 	argv += optind;
186 
187 	if (argc)
188 		usage();
189 
190 	/*
191 	 * Discard setgid privileged if not the running kernel so that bad
192 	 * guys can't print interesting stuff from kernel memory.
193 	 */
194 	gid = getgid();
195 	if (core != NULL || sys != NULL)
196 		if (setresgid(gid, gid, gid) == -1)
197 			err(1, "setresgid");
198 
199 	kd = kvm_openfiles(sys, core, NULL, O_RDONLY, errbuf);
200 	if (kd == NULL)
201 		errx(1, "can't open kmem: %s", errbuf);
202 
203 	if (core == NULL && sys == NULL)
204 		if (setresgid(gid, gid, gid) == -1)
205 			err(1, "setresgid");
206 
207 	if (kvm_nlist(kd, nl))
208 		errx(2, "%s: no namelist", sys ? sys : _PATH_UNIX);
209 
210 	if (kvm_read(kd, nl[N_TCP_DEBX].n_value, (char *)&tcp_debx,
211 	    sizeof(tcp_debx)) != sizeof(tcp_debx))
212 		errx(3, "tcp_debx: %s", kvm_geterr(kd));
213 
214 	if (kvm_read(kd, nl[N_TCP_DEBUG].n_value, (char *)tcp_debug,
215 	    sizeof(tcp_debug)) != sizeof(tcp_debug))
216 		errx(3, "tcp_debug: %s", kvm_geterr(kd));
217 
218 	/*
219 	 * If no control blocks have been specified, figure
220 	 * out how many distinct one we have and summarize
221 	 * them in tcp_pcbs for sorting the trace records
222 	 * below.
223 	 */
224 	if (npcbs == 0) {
225 		for (i = 0; i < TCP_NDEBUG; i++) {
226 			struct tcp_debug *td = &tcp_debug[i];
227 			int j;
228 
229 			if (td->td_tcb == 0)
230 				continue;
231 			for (j = 0; j < npcbs; j++)
232 				if (tcp_pcbs[j] == td->td_tcb)
233 					break;
234 			if (j >= npcbs)
235 				tcp_pcbs[npcbs++] = td->td_tcb;
236 		}
237 		if (npcbs == 0)
238 			exit(0);
239 	}
240 	qsort(tcp_pcbs, npcbs, sizeof(caddr_t), numeric);
241 	if (jflag) {
242 		for (i = 0;;) {
243 			printf("%lx", (long)tcp_pcbs[i]);
244 			if (++i == npcbs)
245 				break;
246 			fputs(", ", stdout);
247 		}
248 		putchar('\n');
249 	} else {
250 		for (i = 0; i < npcbs; i++) {
251 			printf("\n%lx:\n", (long)tcp_pcbs[i]);
252 			dotrace(tcp_pcbs[i]);
253 		}
254 	}
255 	exit(0);
256 }
257 
258 void
259 dotrace(caddr_t tcpcb)
260 {
261 	struct tcp_debug *td;
262 	int prev_debx = tcp_debx;
263 	int i;
264 
265  again:
266 	if (--tcp_debx < 0)
267 		tcp_debx = TCP_NDEBUG - 1;
268 	for (i = prev_debx % TCP_NDEBUG; i < TCP_NDEBUG; i++) {
269 		td = &tcp_debug[i];
270 		if (tcpcb && td->td_tcb != tcpcb)
271 			continue;
272 		ntime = ntohl(td->td_time);
273 		tcp_trace(td->td_act, td->td_ostate,
274 		    &td->td_cb, &td->td_ti,
275 		    &td->td_ti6, td->td_req);
276 		if (i == tcp_debx)
277 			goto done;
278 	}
279 	for (i = 0; i <= tcp_debx % TCP_NDEBUG; i++) {
280 		td = &tcp_debug[i];
281 		if (tcpcb && td->td_tcb != tcpcb)
282 			continue;
283 		ntime = ntohl(td->td_time);
284 		tcp_trace(td->td_act, td->td_ostate,
285 		    &td->td_cb, &td->td_ti,
286 		    &td->td_ti6, td->td_req);
287 	}
288  done:
289 	if (follow) {
290 		prev_debx = tcp_debx + 1;
291 		if (prev_debx >= TCP_NDEBUG)
292 			prev_debx = 0;
293 		do {
294 			sleep(1);
295 			if (kvm_read(kd, nl[N_TCP_DEBX].n_value,
296 			    (char *)&tcp_debx, sizeof(tcp_debx)) !=
297 			    sizeof(tcp_debx))
298 				errx(3, "tcp_debx: %s", kvm_geterr(kd));
299 		} while (tcp_debx == prev_debx);
300 
301 		if (kvm_read(kd, nl[N_TCP_DEBUG].n_value, (char *)tcp_debug,
302 		    sizeof(tcp_debug)) != sizeof(tcp_debug))
303 			errx(3, "tcp_debug: %s", kvm_geterr(kd));
304 
305 		goto again;
306 	}
307 }
308 
309 /*
310  * Tcp debug routines
311  */
312 /*ARGSUSED*/
313 void
314 tcp_trace(short act, short ostate, struct tcpcb *tp,
315     struct tcpiphdr *ti, struct tcpipv6hdr *ti6, int req)
316 {
317 	tcp_seq seq, ack;
318 	int flags, len, win, timer;
319 	struct tcphdr *th;
320 	char hbuf[INET6_ADDRSTRLEN];
321 
322 	if (ti->ti_src.s_addr)
323 		th = &ti->ti_t;
324 	else
325 		th = &ti6->ti6_t;
326 
327 	printf("%03d %s:%s ", (ntime/10) % 1000, tcpstates[ostate],
328 	    tanames[act]);
329 	switch (act) {
330 	case TA_INPUT:
331 	case TA_OUTPUT:
332 	case TA_DROP:
333 		if (aflag) {
334 			if (ti->ti_src.s_addr) {
335 				printf("(src=%s,%u, ",
336 				    inet_ntoa(ti->ti_src), ntohs(ti->ti_sport));
337 				printf("dst=%s,%u)",
338 				    inet_ntoa(ti->ti_dst), ntohs(ti->ti_dport));
339 			} else {
340 				printf("(src=%s,%u, ",
341 				    inet_ntop(AF_INET6, &ti6->ti6_src,
342 				    hbuf, sizeof(hbuf)), ntohs(ti->ti_sport));
343 				printf("dst=%s,%u)",
344 				    inet_ntop(AF_INET6, &ti6->ti6_dst,
345 				    hbuf, sizeof(hbuf)), ntohs(ti->ti_dport));
346 			}
347 		}
348 		seq = th->th_seq;
349 		ack = th->th_ack;
350 		if (ti->ti_src.s_addr)
351 			len = ti->ti_len;
352 		else
353 			len = ti6->ti6_plen;	/*XXX intermediate header*/
354 		win = th->th_win;
355 		if (act == TA_OUTPUT) {
356 			NTOHL(seq);
357 			NTOHL(ack);
358 			NTOHS(win);
359 		}
360 		if (len)
361 			printf("[%x..%x)", seq, seq + len);
362 		else
363 			printf("%x", seq);
364 		printf("@%x", ack);
365 		if (win)
366 			printf("(win=%x)", win);
367 		flags = th->th_flags;
368 		if (flags) {
369 			char *cp = "<";
370 #define	pf(flag, string) { \
371 	if (th->th_flags & flag) { \
372 		(void)printf("%s%s", cp, string); \
373 		cp = ","; \
374 	} \
375 }
376 			pf(TH_SYN, "SYN");
377 			pf(TH_ACK, "ACK");
378 			pf(TH_FIN, "FIN");
379 			pf(TH_RST, "RST");
380 			pf(TH_PUSH, "PUSH");
381 			pf(TH_URG, "URG");
382 			printf(">");
383 		}
384 		break;
385 	case TA_USER:
386 		timer = req >> 8;
387 		req &= 0xff;
388 		printf("%s", prurequests[req]);
389 		if (req == PRU_SLOWTIMO || req == PRU_FASTTIMO)
390 			printf("<%s>", tcptimers[timer]);
391 		break;
392 	}
393 	printf(" -> %s", tcpstates[tp->t_state]);
394 	/* print out internal state of tp !?! */
395 	printf("\n");
396 	if (sflag) {
397 		printf("\trcv_nxt %x rcv_wnd %lx snd_una %x snd_nxt %x snd_max %x\n",
398 		    tp->rcv_nxt, tp->rcv_wnd, tp->snd_una, tp->snd_nxt,
399 		    tp->snd_max);
400 		printf("\tsnd_wl1 %x snd_wl2 %x snd_wnd %lx\n", tp->snd_wl1,
401 		    tp->snd_wl2, tp->snd_wnd);
402 	}
403 	/* print out timers? */
404 	if (tflag) {
405 		char *cp = "\t";
406 		int i;
407 
408 		for (i = 0; i < TCPT_NTIMERS; i++) {
409 			if (timeout_pending(&tp->t_timer[i]))
410 				continue;
411 			printf("%s%s=%d", cp, tcptimers[i],
412 			    tp->t_timer[i].to_time);
413 			if (i == TCPT_REXMT)
414 				printf(" (t_rxtshft=%d)", tp->t_rxtshift);
415 			cp = ", ";
416 		}
417 		if (*cp != '\t')
418 			putchar('\n');
419 	}
420 }
421 
422 int
423 numeric(const void *v1, const void *v2)
424 {
425 	const caddr_t *c1 = v1;
426 	const caddr_t *c2 = v2;
427 	int rv;
428 
429 	if (*c1 < *c2)
430 		rv = -1;
431 	else if (*c1 > *c2)
432 		rv = 1;
433 	else
434 		rv = 0;
435 
436 	return (rv);
437 }
438 
439 void
440 usage(void)
441 {
442 
443 	(void) fprintf(stderr, "usage: %s [-afjst] [-M core]"
444 	    " [-N system] [-p hex-address]\n", __progname);
445 	exit(1);
446 }
447