xref: /openbsd-src/usr.sbin/tcpdump/tcpdump.c (revision 0eea0d082377cb9c3ec583313dc4d52b7b6a4d6d)
1 /*	$OpenBSD: tcpdump.c,v 1.38 2004/06/20 17:51:55 avsm 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.38 2004/06/20 17:51:55 avsm 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 #include "privsep.h"
66 
67 int aflag;			/* translate network and broadcast addresses */
68 int dflag;			/* print filter code */
69 int eflag;			/* print ethernet header */
70 int fflag;			/* don't translate "foreign" IP address */
71 int nflag;			/* leave addresses as numbers */
72 int Nflag;			/* remove domains from printed host names */
73 int Oflag = 1;			/* run filter code optimizer */
74 int oflag;			/* print passive OS fingerprints */
75 int pflag;			/* don't go promiscuous */
76 int qflag;			/* quick (shorter) output */
77 int Sflag;			/* print raw TCP sequence numbers */
78 int tflag = 1;			/* print packet arrival time */
79 int vflag;			/* verbose */
80 int xflag;			/* print packet in hex */
81 int Xflag;			/* print packet in emacs-hexl style */
82 
83 int packettype;
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);
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 	{ ppp_ether_if_print,	DLT_PPP_ETHER },
126 	{ NULL,			0 },
127 };
128 
129 static pcap_handler
130 lookup_printer(int type)
131 {
132 	struct printer *p;
133 
134 	for (p = printers; p->f; ++p)
135 		if (type == p->type)
136 			return p->f;
137 
138 	error("unknown data link type 0x%x", type);
139 	/* NOTREACHED */
140 }
141 
142 static int
143 init_pfosfp(void)
144 {
145 	pf_osfp_initialize();
146 	if (pfctl_file_fingerprints(-1,
147 	    PF_OPT_QUIET|PF_OPT_NOACTION, PF_OSFP_FILE) == 0)
148 		return 1;
149 	return 0;
150 }
151 
152 static pcap_t *pd;
153 
154 extern int optind;
155 extern int opterr;
156 extern char *optarg;
157 
158 int
159 main(int argc, char **argv)
160 {
161 	register int cnt, op, i;
162 	bpf_u_int32 localnet, netmask;
163 	register char *cp, *infile, *device, *RFileName, *WFileName;
164 	pcap_handler printer;
165 	struct bpf_program *fcode;
166 	RETSIGTYPE (*oldhandler)(int);
167 	u_char *pcap_userdata;
168 	char ebuf[PCAP_ERRBUF_SIZE];
169 
170 	cnt = -1;
171 	device = NULL;
172 	infile = NULL;
173 	RFileName = NULL;
174 	WFileName = NULL;
175 
176 	if (priv_init(argc, argv))
177 		error("Failed to setup privsep");
178 
179 	/* state: STATE_INIT */
180 	if ((cp = strrchr(argv[0], '/')) != NULL)
181 		program_name = cp + 1;
182 	else
183 		program_name = argv[0];
184 
185 	if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
186 		error("%s", ebuf);
187 
188 	opterr = 0;
189 	while ((op = getopt(argc, argv, "ac:deE:fF:i:lnNOopqr:s:StT:vw:xXY")) != -1)
190 		switch (op) {
191 
192 		case 'a':
193 			++aflag;
194 			break;
195 
196 		case 'c':
197 			cnt = atoi(optarg);
198 			if (cnt <= 0)
199 				error("invalid packet count %s", optarg);
200 			break;
201 
202 		case 'd':
203 			++dflag;
204 			break;
205 
206 		case 'e':
207 			++eflag;
208 			break;
209 
210 		case 'f':
211 			++fflag;
212 			break;
213 
214 		case 'F':
215 			infile = optarg;
216 			break;
217 
218 		case 'i':
219 			device = optarg;
220 			break;
221 
222 		case 'l':
223 #ifdef HAVE_SETLINEBUF
224 			setlinebuf(stdout);
225 #else
226 			setvbuf(stdout, NULL, _IOLBF, 0);
227 #endif
228 			break;
229 
230 		case 'n':
231 			++nflag;
232 			break;
233 
234 		case 'N':
235 			++Nflag;
236 			break;
237 
238 		case 'O':
239 			Oflag = 0;
240 			break;
241 
242 		case 'o':
243 				oflag = 1;
244 			break;
245 
246 		case 'p':
247 			++pflag;
248 			break;
249 
250 		case 'q':
251 			++qflag;
252 			break;
253 
254 		case 'r':
255 			RFileName = optarg;
256 			break;
257 
258 		case 's':
259 			snaplen = atoi(optarg);
260 			if (snaplen <= 0)
261 				error("invalid snaplen %s", optarg);
262 			break;
263 
264 		case 'S':
265 			++Sflag;
266 			break;
267 
268 		case 't':
269 			--tflag;
270 			break;
271 
272 		case 'T':
273 			if (strcasecmp(optarg, "vat") == 0)
274 				packettype = PT_VAT;
275 			else if (strcasecmp(optarg, "wb") == 0)
276 				packettype = PT_WB;
277 			else if (strcasecmp(optarg, "rpc") == 0)
278 				packettype = PT_RPC;
279 			else if (strcasecmp(optarg, "rtp") == 0)
280 				packettype = PT_RTP;
281 			else if (strcasecmp(optarg, "rtcp") == 0)
282 				packettype = PT_RTCP;
283 			else if (strcasecmp(optarg, "cnfp") == 0)
284 				packettype = PT_CNFP;
285 			else if (strcasecmp(optarg, "vrrp") == 0)
286 				packettype = PT_VRRP;
287 			else if (strcasecmp(optarg, "sack") == 0)
288 				snaplen = SACK_SNAPLEN;
289 			else
290 				error("unknown packet type `%s'", optarg);
291 			break;
292 
293 		case 'v':
294 			++vflag;
295 			break;
296 
297 		case 'w':
298 			WFileName = optarg;
299 			break;
300 #ifdef YYDEBUG
301 		case 'Y':
302 			{
303 			/* Undocumented flag */
304 			extern int yydebug;
305 			yydebug = 1;
306 			}
307 			break;
308 #endif
309 		case 'x':
310 			++xflag;
311 			break;
312 
313 		case 'X':
314 			++Xflag;
315 			if (xflag == 0) ++xflag;
316 			break;
317 
318 		case 'E':
319 			if (esp_init(optarg) < 0)
320 				error("bad esp specification `%s'", optarg);
321 			break;
322 
323 		default:
324 			usage();
325 			/* NOTREACHED */
326 		}
327 
328 	if (aflag && nflag)
329 		error("-a and -n options are incompatible");
330 
331 	if (RFileName != NULL) {
332 		pd = priv_pcap_offline(RFileName, ebuf);
333 		if (pd == NULL)
334 			error("%s", ebuf);
335 
336 		/* state: STATE_BPF */
337 		localnet = 0;
338 		netmask = 0;
339 		if (fflag != 0)
340 			error("-f and -r options are incompatible");
341 	} else {
342 		if (device == NULL) {
343 			device = pcap_lookupdev(ebuf);
344 			if (device == NULL)
345 				error("%s", ebuf);
346 		}
347 		pd = priv_pcap_live(device, snaplen, !pflag, 1000, ebuf);
348 		if (pd == NULL)
349 			error("%s", ebuf);
350 
351 		/* state: STATE_BPF */
352 		i = pcap_snapshot(pd);
353 		if (snaplen < i) {
354 			warning("snaplen raised from %d to %d", snaplen, i);
355 			snaplen = i;
356 		}
357 
358 		if (pcap_lookupnet(device, &localnet, &netmask, ebuf)) {
359 			warning("%s", ebuf);
360 			localnet = 0;
361 			netmask = 0;
362 		}
363 	}
364 
365 	fcode = priv_pcap_setfilter(pd, Oflag, netmask);
366 	/* state: STATE_FILTER */
367 	if (fcode == NULL)
368 		error("%s", pcap_geterr(pd));
369 	if (dflag) {
370 		bpf_dump(fcode, dflag);
371 		exit(0);
372 	}
373 	init_addrtoname(localnet, netmask);
374 
375 	setsignal(SIGTERM, cleanup);
376 	setsignal(SIGINT, cleanup);
377 	/* Cooperate with nohup(1) XXX is this still necessary/working? */
378 	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
379 		(void)setsignal(SIGHUP, oldhandler);
380 
381 	if (WFileName) {
382 		pcap_dumper_t *p;
383 
384 		p = priv_pcap_dump_open(pd, WFileName);
385 		/* state: STATE_RUN */
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 		priv_init_done();
399 		/* state: STATE_RUN */
400 	}
401 	if (RFileName == NULL) {
402 		(void)fprintf(stderr, "%s: listening on %s\n",
403 		    program_name, device);
404 		(void)fflush(stderr);
405 	}
406 
407 	if (oflag)
408 		oflag = init_pfosfp();
409 	if (tflag > 0)
410 		thiszone = gmt2local(0);
411 
412 
413 	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
414 		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
415 		    program_name, pcap_geterr(pd));
416 		exit(1);
417 	}
418 	pcap_close(pd);
419 	exit(0);
420 }
421 
422 /* make a clean exit on interrupts */
423 RETSIGTYPE
424 cleanup(int signo)
425 {
426 	struct pcap_stat stat;
427 	char buf[1024];
428 
429 	/* Can't print the summary if reading from a savefile */
430 	if (pd != NULL && pcap_file(pd) == NULL) {
431 #if 0
432 		(void)fflush(stdout);	/* XXX unsafe */
433 #endif
434 		(void)write(STDERR_FILENO, "\n", 1);
435 		if (pcap_stats(pd, &stat) < 0) {
436 			(void)snprintf(buf, sizeof buf,
437 			    "pcap_stats: %s\n", pcap_geterr(pd));
438 			write(STDOUT_FILENO, buf, strlen(buf));
439 		} else {
440 			(void)snprintf(buf, sizeof buf,
441 			    "%d packets received by filter\n", stat.ps_recv);
442 			write(STDOUT_FILENO, buf, strlen(buf));
443 			(void)snprintf(buf, sizeof buf,
444 			    "%d packets dropped by kernel\n", stat.ps_drop);
445 			write(STDOUT_FILENO, buf, strlen(buf));
446 		}
447 	}
448 	_exit(0);
449 }
450 
451 /* dump the buffer in `emacs-hexl' style */
452 void
453 default_print_hexl(const u_char *cp, unsigned int length, unsigned int offset)
454 {
455 	unsigned int i, j, jm;
456 	int c;
457 	char ln[128], buf[128];
458 
459 	printf("\n");
460 	for (i = 0; i < length; i += 0x10) {
461 		snprintf(ln, sizeof(ln), "  %04x: ",
462 		    (unsigned int)(i + offset));
463 		jm = length - i;
464 		jm = jm > 16 ? 16 : jm;
465 
466 		for (j = 0; j < jm; j++) {
467 			if ((j % 2) == 1)
468 				snprintf(buf, sizeof(buf), "%02x ",
469 				    (unsigned int)cp[i+j]);
470 			else
471 				snprintf(buf, sizeof(buf), "%02x",
472 				    (unsigned int)cp[i+j]);
473 			strlcat(ln, buf, sizeof ln);
474 		}
475 		for (; j < 16; j++) {
476 			if ((j % 2) == 1)
477 				snprintf(buf, sizeof buf, "   ");
478 			else
479 				snprintf(buf, sizeof buf, "  ");
480 			strlcat(ln, buf, sizeof ln);
481 		}
482 
483 		strlcat(ln, " ", sizeof ln);
484 		for (j = 0; j < jm; j++) {
485 			c = cp[i+j];
486 			c = isprint(c) ? c : '.';
487 			buf[0] = c;
488 			buf[1] = '\0';
489 			strlcat(ln, buf, sizeof ln);
490 		}
491 		printf("%s\n", ln);
492 	}
493 }
494 
495 /* Like default_print() but data need not be aligned */
496 void
497 default_print_unaligned(register const u_char *cp, register u_int length)
498 {
499 	register u_int i, s;
500 	register int nshorts;
501 
502 	if (Xflag) {
503 		/* dump the buffer in `emacs-hexl' style */
504 		default_print_hexl(cp, length, 0);
505 	} else {
506 		/* dump the buffer in old tcpdump style */
507 		nshorts = (u_int) length / sizeof(u_short);
508 		i = 0;
509 		while (--nshorts >= 0) {
510 			if ((i++ % 8) == 0)
511 				(void)printf("\n\t\t\t");
512 			s = *cp++;
513 			(void)printf(" %02x%02x", s, *cp++);
514 		}
515 		if (length & 1) {
516 			if ((i % 8) == 0)
517 				(void)printf("\n\t\t\t");
518 			(void)printf(" %02x", *cp);
519 		}
520 	}
521 }
522 
523 void
524 default_print(register const u_char *bp, register u_int length)
525 {
526 	register const u_short *sp;
527 	register u_int i;
528 	register int nshorts;
529 
530 	if (Xflag) {
531 		/* dump the buffer in `emacs-hexl' style */
532 		default_print_hexl(bp, length, 0);
533 	} else {
534 		/* dump the buffer in old tcpdump style */
535 		if ((long)bp & 1) {
536 			default_print_unaligned(bp, length);
537 			return;
538 		}
539 		sp = (u_short *)bp;
540 		nshorts = (u_int) length / sizeof(u_short);
541 		i = 0;
542 		while (--nshorts >= 0) {
543 			if ((i++ % 8) == 0)
544 				(void)printf("\n\t\t\t");
545 			(void)printf(" %04x", ntohs(*sp++));
546 		}
547 		if (length & 1) {
548 			if ((i % 8) == 0)
549 				(void)printf("\n\t\t\t");
550 			(void)printf(" %02x", *(u_char *)sp);
551 		}
552 	}
553 }
554 
555 __dead void
556 usage(void)
557 {
558 	extern char version[];
559 	extern char pcap_version[];
560 
561 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
562 	(void)fprintf(stderr, "libpcap version %s\n", pcap_version);
563 	(void)fprintf(stderr,
564 "Usage: %s [-adeflnNoOpqStvxX] [-c count] [-E [espalg:]espkey] [-F file]\n",
565 	    program_name);
566 	(void)fprintf(stderr,
567 "\t\t[-i interface] [-r file] [-s snaplen] [-T type] [-w file]\n");
568 	(void)fprintf(stderr,
569 "\t\t[expression]\n");
570 	exit(1);
571 }
572