xref: /openbsd-src/usr.sbin/tcpdump/tcpdump.c (revision 8500990981f885cbe5e6a4958549cacc238b5ae6)
1 /*	$OpenBSD: tcpdump.c,v 1.34 2003/09/25 13:32:58 jmc Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that: (1) source code distributions
9  * retain the above copyright notice and this paragraph in its entirety, (2)
10  * distributions including binary code include the above copyright notice and
11  * this paragraph in its entirety in the documentation or other materials
12  * provided with the distribution, and (3) all advertising materials mentioning
13  * features or use of this software display the following acknowledgement:
14  * ``This product includes software developed by the University of California,
15  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
16  * the University nor the names of its contributors may be used to endorse
17  * or promote products derived from this software without specific prior
18  * written permission.
19  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
20  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
21  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
22  */
23 
24 #ifndef lint
25 static const char copyright[] =
26     "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997\n\
27 The Regents of the University of California.  All rights reserved.\n";
28 static const char rcsid[] =
29     "@(#) $Header: /home/cvs/src/usr.sbin/tcpdump/tcpdump.c,v 1.34 2003/09/25 13:32:58 jmc Exp $ (LBL)";
30 #endif
31 
32 /*
33  * tcpdump - monitor tcp/ip traffic on an ethernet.
34  *
35  * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
36  * Mercilessly hacked and occasionally improved since then via the
37  * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
38  */
39 
40 #include <sys/types.h>
41 #include <sys/time.h>
42 
43 #include <netinet/in.h>
44 
45 #include <pcap.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <ctype.h>
52 
53 #include "interface.h"
54 #include "addrtoname.h"
55 #include "machdep.h"
56 #include "setsignal.h"
57 #include "gmt2local.h"
58 
59 #include <sys/socket.h>
60 #include <net/if.h>
61 #include <netinet/in.h>
62 #include <net/pfvar.h>
63 #include "pfctl.h"
64 #include "pfctl_parser.h"
65 
66 int aflag;			/* translate network and broadcast addresses */
67 int dflag;			/* print filter code */
68 int eflag;			/* print ethernet header */
69 int fflag;			/* don't translate "foreign" IP address */
70 int nflag;			/* leave addresses as numbers */
71 int Nflag;			/* remove domains from printed host names */
72 int Oflag = 1;			/* run filter code optimizer */
73 int oflag;			/* print passive OS fingerprints */
74 int pflag;			/* don't go promiscuous */
75 int qflag;			/* quick (shorter) output */
76 int Sflag;			/* print raw TCP sequence numbers */
77 int tflag = 1;			/* print packet arrival time */
78 int vflag;			/* verbose */
79 int xflag;			/* print packet in hex */
80 int Xflag;			/* print packet in emacs-hexl style */
81 
82 int packettype;
83 
84 
85 char *program_name;
86 
87 int32_t thiszone;		/* seconds offset from gmt to local time */
88 
89 /* Externs */
90 extern void bpf_dump(struct bpf_program *, int);
91 extern int esp_init(char *);
92 
93 /* Forwards */
94 RETSIGTYPE cleanup(int);
95 extern __dead void usage(void) __attribute__((volatile));
96 
97 /* Length of saved portion of packet. */
98 int snaplen = DEFAULT_SNAPLEN;
99 
100 struct printer {
101 	pcap_handler f;
102 	int type;
103 };
104 
105 /* XXX needed if using old bpf.h */
106 #ifndef DLT_ATM_RFC1483
107 #define DLT_ATM_RFC1483 11
108 #endif
109 
110 static struct printer printers[] = {
111 	{ ether_if_print,	DLT_EN10MB },
112 	{ ether_if_print,	DLT_IEEE802 },
113 	{ sl_if_print,		DLT_SLIP },
114 	{ sl_bsdos_if_print,	DLT_SLIP_BSDOS },
115 	{ ppp_if_print,		DLT_PPP },
116 	{ fddi_if_print,	DLT_FDDI },
117 	{ null_if_print,	DLT_NULL },
118 	{ raw_if_print,		DLT_RAW },
119 	{ atm_if_print,		DLT_ATM_RFC1483 },
120 	{ loop_if_print, 	DLT_LOOP },
121 	{ enc_if_print, 	DLT_ENC },
122 	{ pflog_if_print, 	DLT_PFLOG },
123 	{ pflog_old_if_print, 	DLT_OLD_PFLOG },
124 	{ pfsync_if_print, 	DLT_PFSYNC },
125 	{ NULL,			0 },
126 };
127 
128 static pcap_handler
129 lookup_printer(int type)
130 {
131 	struct printer *p;
132 
133 	for (p = printers; p->f; ++p)
134 		if (type == p->type)
135 			return p->f;
136 
137 	error("unknown data link type 0x%x", type);
138 	/* NOTREACHED */
139 }
140 
141 static pcap_t *pd;
142 
143 extern int optind;
144 extern int opterr;
145 extern char *optarg;
146 
147 int
148 main(int argc, char **argv)
149 {
150 	register int cnt, op, i;
151 	bpf_u_int32 localnet, netmask;
152 	register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
153 	pcap_handler printer;
154 	struct bpf_program fcode;
155 	RETSIGTYPE (*oldhandler)(int);
156 	u_char *pcap_userdata;
157 	char ebuf[PCAP_ERRBUF_SIZE];
158 
159 	cnt = -1;
160 	device = NULL;
161 	infile = NULL;
162 	RFileName = NULL;
163 	WFileName = NULL;
164 	if ((cp = strrchr(argv[0], '/')) != NULL)
165 		program_name = cp + 1;
166 	else
167 		program_name = argv[0];
168 
169 	if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
170 		error("%s", ebuf);
171 
172 	opterr = 0;
173 	while ((op = getopt(argc, argv, "ac:deE:fF:i:lnNOopqr:s:StT:vw:xXY")) != -1)
174 		switch (op) {
175 
176 		case 'a':
177 			++aflag;
178 			break;
179 
180 		case 'c':
181 			cnt = atoi(optarg);
182 			if (cnt <= 0)
183 				error("invalid packet count %s", optarg);
184 			break;
185 
186 		case 'd':
187 			++dflag;
188 			break;
189 
190 		case 'e':
191 			++eflag;
192 			break;
193 
194 		case 'f':
195 			++fflag;
196 			break;
197 
198 		case 'F':
199 			infile = optarg;
200 			break;
201 
202 		case 'i':
203 			device = optarg;
204 			break;
205 
206 		case 'l':
207 #ifdef HAVE_SETLINEBUF
208 			setlinebuf(stdout);
209 #else
210 			setvbuf(stdout, NULL, _IOLBF, 0);
211 #endif
212 			break;
213 
214 		case 'n':
215 			++nflag;
216 			break;
217 
218 		case 'N':
219 			++Nflag;
220 			break;
221 
222 		case 'O':
223 			Oflag = 0;
224 			break;
225 
226 		case 'o':
227 			pf_osfp_initialize();
228 			if (pfctl_file_fingerprints(-1,
229 			    PF_OPT_QUIET|PF_OPT_NOACTION, PF_OSFP_FILE) == 0)
230 				oflag = 1;
231 			break;
232 
233 		case 'p':
234 			++pflag;
235 			break;
236 
237 		case 'q':
238 			++qflag;
239 			break;
240 
241 		case 'r':
242 			RFileName = optarg;
243 			break;
244 
245 		case 's':
246 			snaplen = atoi(optarg);
247 			if (snaplen <= 0)
248 				error("invalid snaplen %s", optarg);
249 			break;
250 
251 		case 'S':
252 			++Sflag;
253 			break;
254 
255 		case 't':
256 			--tflag;
257 			break;
258 
259 		case 'T':
260 			if (strcasecmp(optarg, "vat") == 0)
261 				packettype = PT_VAT;
262 			else if (strcasecmp(optarg, "wb") == 0)
263 				packettype = PT_WB;
264 			else if (strcasecmp(optarg, "rpc") == 0)
265 				packettype = PT_RPC;
266 			else if (strcasecmp(optarg, "rtp") == 0)
267 				packettype = PT_RTP;
268 			else if (strcasecmp(optarg, "rtcp") == 0)
269 				packettype = PT_RTCP;
270 			else if (strcasecmp(optarg, "cnfp") == 0)
271 				packettype = PT_CNFP;
272 			else if (strcasecmp(optarg, "sack") == 0)
273 				snaplen = SACK_SNAPLEN;
274 			else
275 				error("unknown packet type `%s'", optarg);
276 			break;
277 
278 		case 'v':
279 			++vflag;
280 			break;
281 
282 		case 'w':
283 			WFileName = optarg;
284 			break;
285 #ifdef YYDEBUG
286 		case 'Y':
287 			{
288 			/* Undocumented flag */
289 			extern int yydebug;
290 			yydebug = 1;
291 			}
292 			break;
293 #endif
294 		case 'x':
295 			++xflag;
296 			break;
297 
298 		case 'X':
299 			++Xflag;
300 			if (xflag == 0) ++xflag;
301 			break;
302 
303 		case 'E':
304 			if (esp_init(optarg) < 0)
305 				error("bad esp specification `%s'", optarg);
306 			break;
307 
308 		default:
309 			usage();
310 			/* NOTREACHED */
311 		}
312 
313 	if (aflag && nflag)
314 		error("-a and -n options are incompatible");
315 
316 	if (tflag > 0)
317 		thiszone = gmt2local(0);
318 
319 	if (RFileName != NULL) {
320 		/*
321 		 * We don't need network access, so set it back to the user id.
322 		 * Also, this prevents the user from reading anyone's
323 		 * trace file.
324 		 */
325 		seteuid(getuid());
326 		setuid(getuid());
327 
328 		pd = pcap_open_offline(RFileName, ebuf);
329 		if (pd == NULL)
330 			error("%s", ebuf);
331 		localnet = 0;
332 		netmask = 0;
333 		if (fflag != 0)
334 			error("-f and -r options are incompatible");
335 	} else {
336 		if (device == NULL) {
337 			device = pcap_lookupdev(ebuf);
338 			if (device == NULL)
339 				error("%s", ebuf);
340 		}
341 		pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
342 		if (pd == NULL)
343 			error("%s", ebuf);
344 		i = pcap_snapshot(pd);
345 		if (snaplen < i) {
346 			warning("snaplen raised from %d to %d", snaplen, i);
347 			snaplen = i;
348 		}
349 		if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
350 			warning("%s", ebuf);
351 			localnet = 0;
352 			netmask = 0;
353 		}
354 
355 		/*
356 		 * Let user own process after socket has been opened.
357 		 */
358 		seteuid(getuid());
359 		setuid(getuid());
360 	}
361 	if (infile)
362 		cmdbuf = read_infile(infile);
363 	else
364 		cmdbuf = copy_argv(&argv[optind]);
365 
366 	if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
367 		error("%s", pcap_geterr(pd));
368 	if (dflag) {
369 		bpf_dump(&fcode, dflag);
370 		exit(0);
371 	}
372 	init_addrtoname(localnet, netmask);
373 
374 	(void)setsignal(SIGTERM, cleanup);
375 	(void)setsignal(SIGINT, cleanup);
376 	/* Cooperate with nohup(1) */
377 	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
378 		(void)setsignal(SIGHUP, oldhandler);
379 
380 	if (pcap_setfilter(pd, &fcode) < 0)
381 		error("%s", pcap_geterr(pd));
382 	if (WFileName) {
383 		pcap_dumper_t *p;
384 
385 		p = pcap_dump_open(pd, WFileName);
386 		if (p == NULL)
387 			error("%s", pcap_geterr(pd));
388 		{
389 			FILE *fp = (FILE *)p;	/* XXX touching pcap guts! */
390 			fflush(fp);
391 			setvbuf(fp, NULL, _IONBF, 0);
392 		}
393 		printer = pcap_dump;
394 		pcap_userdata = (u_char *)p;
395 	} else {
396 		printer = lookup_printer(pcap_datalink(pd));
397 		pcap_userdata = 0;
398 	}
399 	if (RFileName == NULL) {
400 		(void)fprintf(stderr, "%s: listening on %s\n",
401 		    program_name, device);
402 		(void)fflush(stderr);
403 	}
404 	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
405 		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
406 		    program_name, pcap_geterr(pd));
407 		exit(1);
408 	}
409 	pcap_close(pd);
410 	exit(0);
411 }
412 
413 /* make a clean exit on interrupts */
414 RETSIGTYPE
415 cleanup(int signo)
416 {
417 	struct pcap_stat stat;
418 	char buf[1024];
419 
420 	/* Can't print the summary if reading from a savefile */
421 	if (pd != NULL && pcap_file(pd) == NULL) {
422 #if 0
423 		(void)fflush(stdout);	/* XXX unsafe */
424 #endif
425 		(void)write(STDERR_FILENO, "\n", 1);
426 		if (pcap_stats(pd, &stat) < 0) {
427 			(void)snprintf(buf, sizeof buf,
428 			    "pcap_stats: %s\n", pcap_geterr(pd));
429 			write(STDOUT_FILENO, buf, strlen(buf));
430 		} else {
431 			(void)snprintf(buf, sizeof buf,
432 			    "%d packets received by filter\n", stat.ps_recv);
433 			write(STDOUT_FILENO, buf, strlen(buf));
434 			(void)snprintf(buf, sizeof buf,
435 			    "%d packets dropped by kernel\n", stat.ps_drop);
436 			write(STDOUT_FILENO, buf, strlen(buf));
437 		}
438 	}
439 	_exit(0);
440 }
441 
442 /* dump the buffer in `emacs-hexl' style */
443 void
444 default_print_hexl(const u_char *cp, unsigned int length, unsigned int offset)
445 {
446 	unsigned int i, j, jm;
447 	int c;
448 	char ln[128], buf[128];
449 
450 	printf("\n");
451 	for (i = 0; i < length; i += 0x10) {
452 		snprintf(ln, sizeof(ln), "  %04x: ",
453 		    (unsigned int)(i + offset));
454 		jm = length - i;
455 		jm = jm > 16 ? 16 : jm;
456 
457 		for (j = 0; j < jm; j++) {
458 			if ((j % 2) == 1)
459 				snprintf(buf, sizeof(buf), "%02x ",
460 				    (unsigned int)cp[i+j]);
461 			else
462 				snprintf(buf, sizeof(buf), "%02x",
463 				    (unsigned int)cp[i+j]);
464 			strlcat(ln, buf, sizeof ln);
465 		}
466 		for (; j < 16; j++) {
467 			if ((j % 2) == 1)
468 				snprintf(buf, sizeof buf, "   ");
469 			else
470 				snprintf(buf, sizeof buf, "  ");
471 			strlcat(ln, buf, sizeof ln);
472 		}
473 
474 		strlcat(ln, " ", sizeof ln);
475 		for (j = 0; j < jm; j++) {
476 			c = cp[i+j];
477 			c = isprint(c) ? c : '.';
478 			buf[0] = c;
479 			buf[1] = '\0';
480 			strlcat(ln, buf, sizeof ln);
481 		}
482 		printf("%s\n", ln);
483 	}
484 }
485 
486 /* Like default_print() but data need not be aligned */
487 void
488 default_print_unaligned(register const u_char *cp, register u_int length)
489 {
490 	register u_int i, s;
491 	register int nshorts;
492 
493 	if (Xflag) {
494 		/* dump the buffer in `emacs-hexl' style */
495 		default_print_hexl(cp, length, 0);
496 	} else {
497 		/* dump the buffer in old tcpdump style */
498 		nshorts = (u_int) length / sizeof(u_short);
499 		i = 0;
500 		while (--nshorts >= 0) {
501 			if ((i++ % 8) == 0)
502 				(void)printf("\n\t\t\t");
503 			s = *cp++;
504 			(void)printf(" %02x%02x", s, *cp++);
505 		}
506 		if (length & 1) {
507 			if ((i % 8) == 0)
508 				(void)printf("\n\t\t\t");
509 			(void)printf(" %02x", *cp);
510 		}
511 	}
512 }
513 
514 void
515 default_print(register const u_char *bp, register u_int length)
516 {
517 	register const u_short *sp;
518 	register u_int i;
519 	register int nshorts;
520 
521 	if (Xflag) {
522 		/* dump the buffer in `emacs-hexl' style */
523 		default_print_hexl(bp, length, 0);
524 	} else {
525 		/* dump the buffer in old tcpdump style */
526 		if ((long)bp & 1) {
527 			default_print_unaligned(bp, length);
528 			return;
529 		}
530 		sp = (u_short *)bp;
531 		nshorts = (u_int) length / sizeof(u_short);
532 		i = 0;
533 		while (--nshorts >= 0) {
534 			if ((i++ % 8) == 0)
535 				(void)printf("\n\t\t\t");
536 			(void)printf(" %04x", ntohs(*sp++));
537 		}
538 		if (length & 1) {
539 			if ((i % 8) == 0)
540 				(void)printf("\n\t\t\t");
541 			(void)printf(" %02x", *(u_char *)sp);
542 		}
543 	}
544 }
545 
546 __dead void
547 usage(void)
548 {
549 	extern char version[];
550 	extern char pcap_version[];
551 
552 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
553 	(void)fprintf(stderr, "libpcap version %s\n", pcap_version);
554 	(void)fprintf(stderr,
555 "Usage: %s [-adeflnNoOpqStvxX] [-c count] [-E [espalg:]espkey] [-F file]\n",
556 	    program_name);
557 	(void)fprintf(stderr,
558 "\t\t[-i interface] [-r file] [-s snaplen] [-T type] [-w file]\n");
559 	(void)fprintf(stderr,
560 "\t\t[expression]\n");
561 	exit(1);
562 }
563