xref: /openbsd/usr.sbin/trpt/trpt.c (revision 5b133f3f)
1 /*	$OpenBSD: trpt.c,v 1.40 2023/03/08 04:43:15 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 
71 #include <net/route.h>
72 #include <net/if.h>
73 
74 #include <netinet/in.h>
75 #include <netinet/ip.h>
76 #include <netinet/in_pcb.h>
77 #include <netinet/ip_var.h>
78 #include <netinet/tcp.h>
79 #define TCPSTATES
80 #include <netinet/tcp_fsm.h>
81 #include <netinet/tcp_seq.h>
82 #define	TCPTIMERS
83 #include <netinet/tcp_timer.h>
84 #include <netinet/tcp_var.h>
85 #define	TANAMES
86 #include <netinet/tcp_debug.h>
87 
88 #include <arpa/inet.h>
89 
90 #include <err.h>
91 #include <stdio.h>
92 #include <errno.h>
93 #include <fcntl.h>
94 #include <kvm.h>
95 #include <nlist.h>
96 #include <paths.h>
97 #include <limits.h>
98 #include <stdlib.h>
99 #include <unistd.h>
100 
101 struct nlist nl[] = {
102 #define	N_TCP_DEBUG	0		/* no sysctl */
103 	{ "_tcp_debug" },
104 #define	N_TCP_DEBX	1		/* no sysctl */
105 	{ "_tcp_debx" },
106 	{ NULL },
107 };
108 
109 int	tcp_debx;
110 struct	tcp_debug tcp_debug[TCP_NDEBUG];
111 
112 static caddr_t tcp_pcbs[TCP_NDEBUG];
113 static u_int32_t ntime;
114 static int aflag, follow, sflag, tflag;
115 
116 extern	char *__progname;
117 
118 void	dotrace(caddr_t);
119 void	tcp_trace(short, short, struct tcpcb *, struct tcpiphdr *,
120 	    struct tcpipv6hdr *, int);
121 int	numeric(const void *, const void *);
122 void	usage(void);
123 
124 kvm_t	*kd;
125 
126 int
main(int argc,char * argv[])127 main(int argc, char *argv[])
128 {
129 	char *sys = NULL, *core = NULL, *cp, errbuf[_POSIX2_LINE_MAX];
130 	int ch, i, jflag = 0, npcbs = 0;
131 	unsigned long l;
132 	gid_t gid;
133 
134 	while ((ch = getopt(argc, argv, "afjM:N:p:st")) != -1) {
135 		switch (ch) {
136 		case 'a':
137 			aflag = 1;
138 			break;
139 		case 'f':
140 			follow = 1;
141 			setvbuf(stdout, NULL, _IOLBF, 0);
142 			break;
143 		case 'j':
144 			jflag = 1;
145 			break;
146 		case 'p':
147 			if (npcbs >= TCP_NDEBUG)
148 				errx(1, "too many pcbs specified");
149 			errno = 0;
150 			l = strtoul(optarg, &cp, 16);
151 			tcp_pcbs[npcbs] = (caddr_t)l;
152 			if (*optarg == '\0' || *cp != '\0' || errno ||
153 			    (unsigned long)tcp_pcbs[npcbs] != l)
154 				errx(1, "invalid address: %s", optarg);
155 			npcbs++;
156 			break;
157 		case 's':
158 			sflag = 1;
159 			break;
160 		case 't':
161 			tflag = 1;
162 			break;
163 		case 'N':
164 			sys = optarg;
165 			break;
166 		case 'M':
167 			core = optarg;
168 			break;
169 		default:
170 			usage();
171 			/* NOTREACHED */
172 		}
173 	}
174 	argc -= optind;
175 	argv += optind;
176 
177 	if (argc)
178 		usage();
179 
180 	/*
181 	 * Discard setgid privileged if not the running kernel so that bad
182 	 * guys can't print interesting stuff from kernel memory.
183 	 */
184 	gid = getgid();
185 	if (core != NULL || sys != NULL)
186 		if (setresgid(gid, gid, gid) == -1)
187 			err(1, "setresgid");
188 
189 	kd = kvm_openfiles(sys, core, NULL, O_RDONLY, errbuf);
190 	if (kd == NULL)
191 		errx(1, "can't open kmem: %s", errbuf);
192 
193 	if (core == NULL && sys == NULL)
194 		if (setresgid(gid, gid, gid) == -1)
195 			err(1, "setresgid");
196 
197 	if (kvm_nlist(kd, nl))
198 		errx(2, "%s: no namelist", sys ? sys : _PATH_UNIX);
199 
200 	if (pledge("stdio", NULL) == -1)
201 		err(1, "pledge");
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 
251 void
dotrace(caddr_t tcpcb)252 dotrace(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 void
tcp_trace(short act,short ostate,struct tcpcb * tp,struct tcpiphdr * ti,struct tcpipv6hdr * ti6,int req)306 tcp_trace(short act, short ostate, struct tcpcb *tp,
307     struct tcpiphdr *ti, struct tcpipv6hdr *ti6, int req)
308 {
309 	tcp_seq seq, ack;
310 	int flags, len, win;
311 	struct tcphdr *th;
312 	char hbuf[INET6_ADDRSTRLEN];
313 
314 	if (ti->ti_src.s_addr)
315 		th = &ti->ti_t;
316 	else
317 		th = &ti6->ti6_t;
318 
319 	printf("%03d %s:%s ", (ntime/10) % 1000, tcpstates[ostate],
320 	    tanames[act]);
321 	switch (act) {
322 	case TA_INPUT:
323 	case TA_OUTPUT:
324 	case TA_DROP:
325 		if (aflag) {
326 			if (ti->ti_src.s_addr) {
327 				printf("(src=%s,%u, ",
328 				    inet_ntoa(ti->ti_src), ntohs(ti->ti_sport));
329 				printf("dst=%s,%u)",
330 				    inet_ntoa(ti->ti_dst), ntohs(ti->ti_dport));
331 			} else {
332 				printf("(src=%s,%u, ",
333 				    inet_ntop(AF_INET6, &ti6->ti6_src,
334 				    hbuf, sizeof(hbuf)), ntohs(ti->ti_sport));
335 				printf("dst=%s,%u)",
336 				    inet_ntop(AF_INET6, &ti6->ti6_dst,
337 				    hbuf, sizeof(hbuf)), ntohs(ti->ti_dport));
338 			}
339 		}
340 		seq = th->th_seq;
341 		ack = th->th_ack;
342 		if (ti->ti_src.s_addr)
343 			len = ti->ti_len;
344 		else
345 			len = ti6->ti6_plen;	/*XXX intermediate header*/
346 		win = th->th_win;
347 		if (act == TA_OUTPUT) {
348 			NTOHL(seq);
349 			NTOHL(ack);
350 			NTOHS(win);
351 		}
352 		if (len)
353 			printf("[%x..%x)", seq, seq + len);
354 		else
355 			printf("%x", seq);
356 		printf("@%x", ack);
357 		if (win)
358 			printf("(win=%x)", win);
359 		flags = th->th_flags;
360 		if (flags) {
361 			char *cp = "<";
362 #define	pf(flag, string) { \
363 	if (th->th_flags & flag) { \
364 		(void)printf("%s%s", cp, string); \
365 		cp = ","; \
366 	} \
367 }
368 			pf(TH_SYN, "SYN");
369 			pf(TH_ACK, "ACK");
370 			pf(TH_FIN, "FIN");
371 			pf(TH_RST, "RST");
372 			pf(TH_PUSH, "PUSH");
373 			pf(TH_URG, "URG");
374 			printf(">");
375 		}
376 		break;
377 	case TA_USER:
378 		printf("%s", prurequests[req]);
379 		break;
380 	case TA_TIMER:
381 		printf("%s", tcptimers[req]);
382 		break;
383 	}
384 	printf(" -> %s", tcpstates[tp->t_state]);
385 	/* print out internal state of tp !?! */
386 	printf("\n");
387 	if (sflag) {
388 		printf("\trcv_nxt %x rcv_wnd %lx snd_una %x snd_nxt %x snd_max %x\n",
389 		    tp->rcv_nxt, tp->rcv_wnd, tp->snd_una, tp->snd_nxt,
390 		    tp->snd_max);
391 		printf("\tsnd_wl1 %x snd_wl2 %x snd_wnd %lx\n", tp->snd_wl1,
392 		    tp->snd_wl2, tp->snd_wnd);
393 	}
394 	/* print out timers? */
395 	if (tflag) {
396 		char *cp = "\t";
397 		int i;
398 
399 		for (i = 0; i < TCPT_NTIMERS; i++) {
400 			if (timeout_pending(&tp->t_timer[i]))
401 				continue;
402 			printf("%s%s=%d", cp, tcptimers[i],
403 			    tp->t_timer[i].to_time);
404 			if (i == TCPT_REXMT)
405 				printf(" (t_rxtshft=%d)", tp->t_rxtshift);
406 			cp = ", ";
407 		}
408 		if (*cp != '\t')
409 			putchar('\n');
410 	}
411 }
412 
413 int
numeric(const void * v1,const void * v2)414 numeric(const void *v1, const void *v2)
415 {
416 	const caddr_t *c1 = v1;
417 	const caddr_t *c2 = v2;
418 	int rv;
419 
420 	if (*c1 < *c2)
421 		rv = -1;
422 	else if (*c1 > *c2)
423 		rv = 1;
424 	else
425 		rv = 0;
426 
427 	return (rv);
428 }
429 
430 void
usage(void)431 usage(void)
432 {
433 
434 	(void) fprintf(stderr, "usage: %s [-afjst] [-M core]"
435 	    " [-N system] [-p hex-address]\n", __progname);
436 	exit(1);
437 }
438