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