Explicitly request literal mode after .Xr.
[netbsd-mini2440.git] / dist / tcpdump / tcpdump.c
blob6e3955d4e563ba7dc6a1b2782722c53c6e3c673a
1 /* $NetBSD: tcpdump.c,v 1.8 2007/07/24 11:53:50 drochner Exp $ */
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
5 * The Regents of the University of California. All rights reserved.
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.
23 * Support for splitting captures into multiple files with a maximum
24 * file size:
26 * Copyright (c) 2001
27 * Seth Webster <swebster@sst.ll.mit.edu>
30 #include <sys/cdefs.h>
31 #ifndef lint
32 #if 0
33 static const char copyright[] _U_ =
34 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
35 The Regents of the University of California. All rights reserved.\n";
36 static const char rcsid[] _U_ =
37 "@(#) Header: /tcpdump/master/tcpdump/tcpdump.c,v 1.253.2.12 2006/02/01 14:39:56 hannes Exp (LBL)";
38 #else
39 __RCSID("$NetBSD: tcpdump.c,v 1.8 2007/07/24 11:53:50 drochner Exp $");
40 #endif
41 #endif
44 * tcpdump - monitor tcp/ip traffic on an ethernet.
46 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
47 * Mercilessly hacked and occasionally improved since then via the
48 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
51 #ifdef HAVE_CONFIG_H
52 #include "config.h"
53 #endif
55 #include <tcpdump-stdinc.h>
57 #ifdef WIN32
58 #include "getopt.h"
59 #include "w32_fzs.h"
60 extern int strcasecmp (const char *__s1, const char *__s2);
61 extern int SIZE_BUF;
62 #define off_t long
63 #define uint UINT
64 #endif /* WIN32 */
66 #ifdef HAVE_SMI_H
67 #include <smi.h>
68 #endif
70 #include <pcap.h>
71 #include <signal.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #ifndef WIN32
76 #include <pwd.h>
77 #include <grp.h>
78 #include <errno.h>
79 #endif /* WIN32 */
81 #include "netdissect.h"
82 #include "interface.h"
83 #include "addrtoname.h"
84 #include "machdep.h"
85 #include "setsignal.h"
86 #include "gmt2local.h"
87 #include "pcap-missing.h"
89 netdissect_options Gndo;
90 netdissect_options *gndo = &Gndo;
93 * Define the maximum number of files for the -C flag, and how many
94 * characters can be added to a filename for the -C flag (which
95 * should be enough to handle MAX_CFLAG - 1).
97 #define MAX_CFLAG 1000000
98 #define MAX_CFLAG_CHARS 6
100 int dflag; /* print filter code */
101 int Lflag; /* list available data link types and exit */
103 static int infodelay;
104 static int infoprint;
106 char *program_name;
108 int32_t thiszone; /* seconds offset from gmt to local time */
110 /* Forwards */
111 static RETSIGTYPE cleanup(int);
112 static void usage(void) __attribute__((noreturn));
113 static void show_dlts_and_exit(pcap_t *pd) __attribute__((noreturn));
115 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
116 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
117 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
118 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
119 static void droproot(const char *, const char *);
120 static void ndo_error(netdissect_options *ndo, const char *fmt, ...);
121 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
123 #ifdef SIGINFO
124 RETSIGTYPE requestinfo(int);
125 #endif
127 #if defined(USE_WIN32_MM_TIMER)
128 #include <MMsystem.h>
129 static UINT timer_id;
130 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
131 #elif defined(HAVE_ALARM)
132 static void verbose_stats_dump(int sig);
133 #endif
135 static void info(int);
136 static u_int packets_captured;
138 typedef u_int (*if_printer)(const struct pcap_pkthdr *, const u_char *);
140 struct printer {
141 if_printer f;
142 int type;
145 static struct printer printers[] = {
146 { arcnet_if_print, DLT_ARCNET },
147 #ifdef DLT_ARCNET_LINUX
148 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
149 #endif
150 { ether_if_print, DLT_EN10MB },
151 { token_if_print, DLT_IEEE802 },
152 #ifdef DLT_LANE8023
153 { lane_if_print, DLT_LANE8023 },
154 #endif
155 #ifdef DLT_CIP
156 { cip_if_print, DLT_CIP },
157 #endif
158 #ifdef DLT_ATM_CLIP
159 { cip_if_print, DLT_ATM_CLIP },
160 #endif
161 { sl_if_print, DLT_SLIP },
162 #ifdef DLT_SLIP_BSDOS
163 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
164 #endif
165 { ppp_if_print, DLT_PPP },
166 #ifdef DLT_PPP_WITHDIRECTION
167 { ppp_if_print, DLT_PPP_WITHDIRECTION },
168 #endif
169 #ifdef DLT_PPP_BSDOS
170 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
171 #endif
172 { fddi_if_print, DLT_FDDI },
173 { null_if_print, DLT_NULL },
174 #ifdef DLT_LOOP
175 { null_if_print, DLT_LOOP },
176 #endif
177 { raw_if_print, DLT_RAW },
178 { atm_if_print, DLT_ATM_RFC1483 },
179 #ifdef DLT_C_HDLC
180 { chdlc_if_print, DLT_C_HDLC },
181 #endif
182 #ifdef DLT_HDLC
183 { chdlc_if_print, DLT_HDLC },
184 #endif
185 #ifdef DLT_PPP_SERIAL
186 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
187 #endif
188 #ifdef DLT_PPP_ETHER
189 { pppoe_if_print, DLT_PPP_ETHER },
190 #endif
191 #ifdef DLT_LINUX_SLL
192 { sll_if_print, DLT_LINUX_SLL },
193 #endif
194 #ifdef DLT_IEEE802_11
195 { ieee802_11_if_print, DLT_IEEE802_11},
196 #endif
197 #ifdef DLT_LTALK
198 { ltalk_if_print, DLT_LTALK },
199 #endif
200 #ifdef DLT_PFLOG
201 { pflog_if_print, DLT_PFLOG },
202 #endif
203 #ifdef DLT_PFSYNC
204 { pfsync_if_print, DLT_PFSYNC },
205 #endif
206 #ifdef DLT_FR
207 { fr_if_print, DLT_FR },
208 #endif
209 #ifdef DLT_FRELAY
210 { fr_if_print, DLT_FRELAY },
211 #endif
212 #ifdef DLT_SUNATM
213 { sunatm_if_print, DLT_SUNATM },
214 #endif
215 #ifdef DLT_IP_OVER_FC
216 { ipfc_if_print, DLT_IP_OVER_FC },
217 #endif
218 #ifdef DLT_PRISM_HEADER
219 { prism_if_print, DLT_PRISM_HEADER },
220 #endif
221 #ifdef DLT_IEEE802_11_RADIO
222 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
223 #endif
224 #ifdef DLT_ENC
225 { enc_if_print, DLT_ENC },
226 #endif
227 #ifdef DLT_SYMANTEC_FIREWALL
228 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
229 #endif
230 #ifdef DLT_APPLE_IP_OVER_IEEE1394
231 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
232 #endif
233 #ifdef DLT_JUNIPER_ATM1
234 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
235 #endif
236 #ifdef DLT_JUNIPER_ATM2
237 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
238 #endif
239 #ifdef DLT_JUNIPER_MFR
240 { juniper_mfr_print, DLT_JUNIPER_MFR },
241 #endif
242 #ifdef DLT_JUNIPER_MLFR
243 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
244 #endif
245 #ifdef DLT_JUNIPER_MLPPP
246 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
247 #endif
248 #ifdef DLT_JUNIPER_PPPOE
249 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
250 #endif
251 #ifdef DLT_JUNIPER_PPPOE_ATM
252 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
253 #endif
254 #ifdef DLT_JUNIPER_GGSN
255 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
256 #endif
257 #ifdef DLT_JUNIPER_ES
258 { juniper_es_print, DLT_JUNIPER_ES },
259 #endif
260 #ifdef DLT_JUNIPER_MONITOR
261 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
262 #endif
263 #ifdef DLT_JUNIPER_SERVICES
264 { juniper_services_print, DLT_JUNIPER_SERVICES },
265 #endif
266 #ifdef DLT_JUNIPER_ETHER
267 { juniper_ether_print, DLT_JUNIPER_ETHER },
268 #endif
269 #ifdef DLT_JUNIPER_PPP
270 { juniper_ppp_print, DLT_JUNIPER_PPP },
271 #endif
272 #ifdef DLT_JUNIPER_FRELAY
273 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
274 #endif
275 #ifdef DLT_JUNIPER_CHDLC
276 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
277 #endif
278 #ifdef DLT_MFR
279 { mfr_if_print, DLT_MFR },
280 #endif
281 { NULL, 0 },
284 static if_printer
285 lookup_printer(int type)
287 struct printer *p;
289 for (p = printers; p->f; ++p)
290 if (type == p->type)
291 return p->f;
293 return NULL;
294 /* NOTREACHED */
297 static pcap_t *pd;
299 extern int optind;
300 extern int opterr;
301 extern char *optarg;
303 struct print_info {
304 if_printer printer;
307 struct dump_info {
308 char *WFileName;
309 pcap_t *pd;
310 pcap_dumper_t *p;
313 static void
314 show_dlts_and_exit(pcap_t *pd)
316 int n_dlts;
317 int *dlts = 0;
318 const char *dlt_name;
320 n_dlts = pcap_list_datalinks(pd, &dlts);
321 if (n_dlts < 0)
322 error("%s", pcap_geterr(pd));
323 else if (n_dlts == 0 || !dlts)
324 error("No data link types.");
326 (void) fprintf(stderr, "Data link types (use option -y to set):\n");
328 while (--n_dlts >= 0) {
329 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
330 if (dlt_name != NULL) {
331 (void) fprintf(stderr, " %s (%s)", dlt_name,
332 pcap_datalink_val_to_description(dlts[n_dlts]));
335 * OK, does tcpdump handle that type?
337 if (lookup_printer(dlts[n_dlts]) == NULL)
338 (void) fprintf(stderr, " (not supported)");
339 putchar('\n');
340 } else {
341 (void) fprintf(stderr, " DLT %d (not supported)\n",
342 dlts[n_dlts]);
345 free(dlts);
346 exit(0);
350 * Set up flags that might or might not be supported depending on the
351 * version of libpcap we're using.
353 #ifdef WIN32
354 #define B_FLAG "B:"
355 #define B_FLAG_USAGE " [ -B size ]"
356 #else /* WIN32 */
357 #define B_FLAG
358 #define B_FLAG_USAGE
359 #endif /* WIN32 */
361 #ifdef HAVE_PCAP_FINDALLDEVS
362 #ifndef HAVE_PCAP_IF_T
363 #undef HAVE_PCAP_FINDALLDEVS
364 #endif
365 #endif
367 #ifdef HAVE_PCAP_FINDALLDEVS
368 #define D_FLAG "D"
369 #else
370 #define D_FLAG
371 #endif
373 #ifdef HAVE_PCAP_DUMP_FLUSH
374 #define U_FLAG "U"
375 #else
376 #define U_FLAG
377 #endif
379 #ifndef WIN32
380 /* Drop root privileges and chroot if necessary */
381 static void
382 droproot(const char *username, const char *chroot_dir)
384 struct passwd *pw = NULL;
386 if (chroot_dir && !username) {
387 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
388 exit(1);
391 pw = getpwnam(username);
392 if (pw) {
393 if (chroot_dir) {
394 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
395 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
396 chroot_dir, pcap_strerror(errno));
397 exit(1);
400 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
401 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
402 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
403 username,
404 (unsigned long)pw->pw_uid,
405 (unsigned long)pw->pw_gid,
406 pcap_strerror(errno));
407 exit(1);
410 else {
411 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
412 username);
413 exit(1);
416 #endif /* WIN32 */
418 static int
419 getWflagChars(int x)
421 int c = 0;
423 x -= 1;
424 while (x > 0) {
425 c += 1;
426 x /= 10;
429 return c;
433 static void
434 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
436 if (cnt == 0 && max_chars == 0)
437 strcpy(buffer, orig_name);
438 else
439 sprintf(buffer, "%s%0*d", orig_name, max_chars, cnt);
442 static int tcpdump_printf(netdissect_options *ndo _U_,
443 const char *fmt, ...)
446 va_list args;
447 int ret;
449 va_start(args, fmt);
450 ret=vfprintf(stdout, fmt, args);
451 va_end(args);
453 return ret;
457 main(int argc, char **argv)
459 register int cnt, op, i;
460 bpf_u_int32 localnet, netmask;
461 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName, *WFileNameAlt;
462 pcap_handler callback;
463 int type;
464 struct bpf_program fcode;
465 #ifndef WIN32
466 RETSIGTYPE (*oldhandler)(int);
467 #endif
468 struct print_info printinfo;
469 struct dump_info dumpinfo;
470 u_char *pcap_userdata;
471 char ebuf[PCAP_ERRBUF_SIZE];
472 char *username = NULL;
473 char *chroot_dir = NULL;
474 #ifdef HAVE_PCAP_FINDALLDEVS
475 pcap_if_t *devpointer;
476 int devnum;
477 #endif
478 int status;
479 #ifdef WIN32
480 u_int UserBufferSize = 1000000;
481 if(wsockinit() != 0) return 1;
482 #endif /* WIN32 */
484 gndo->ndo_Oflag=1;
485 gndo->ndo_Rflag=1;
486 gndo->ndo_dlt=-1;
487 gndo->ndo_default_print=ndo_default_print;
488 gndo->ndo_printf=tcpdump_printf;
489 gndo->ndo_error=ndo_error;
490 gndo->ndo_warning=ndo_warning;
491 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
493 cnt = -1;
494 device = NULL;
495 infile = NULL;
496 RFileName = NULL;
497 WFileName = NULL;
498 if ((cp = strrchr(argv[0], '/')) != NULL)
499 program_name = cp + 1;
500 else
501 program_name = argv[0];
503 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
504 error("%s", ebuf);
506 #ifdef LIBSMI
507 smiInit("tcpdump");
508 #endif
510 opterr = 0;
511 while (
512 (op = getopt(argc, argv, "aA" B_FLAG "c:C:d" D_FLAG "eE:fF:i:lLm:M:nNOpqr:Rs:StT:u" U_FLAG "vw:W:xXy:YZ:")) != -1)
513 switch (op) {
515 case 'a':
516 /* compatibility for old -a */
517 break;
519 case 'A':
520 ++Aflag;
521 break;
523 #ifdef WIN32
524 case 'B':
525 UserBufferSize = atoi(optarg)*1024;
526 if (UserBufferSize < 0)
527 error("invalid packet buffer size %s", optarg);
528 break;
529 #endif /* WIN32 */
531 case 'c':
532 cnt = atoi(optarg);
533 if (cnt <= 0)
534 error("invalid packet count %s", optarg);
535 break;
537 case 'C':
538 Cflag = atoi(optarg) * 1000000;
539 if (Cflag < 0)
540 error("invalid file size %s", optarg);
541 break;
543 case 'd':
544 ++dflag;
545 break;
547 #ifdef HAVE_PCAP_FINDALLDEVS
548 case 'D':
549 if (pcap_findalldevs(&devpointer, ebuf) < 0)
550 error("%s", ebuf);
551 else {
552 for (i = 0; devpointer != 0; i++) {
553 printf("%d.%s", i+1, devpointer->name);
554 if (devpointer->description != NULL)
555 printf(" (%s)", devpointer->description);
556 printf("\n");
557 devpointer = devpointer->next;
560 return 0;
561 #endif /* HAVE_PCAP_FINDALLDEVS */
563 case 'L':
564 Lflag++;
565 break;
567 case 'e':
568 ++eflag;
569 break;
571 case 'E':
572 #ifndef HAVE_LIBCRYPTO
573 warning("crypto code not compiled in");
574 #endif
575 gndo->ndo_espsecret = optarg;
576 break;
578 case 'f':
579 ++fflag;
580 break;
582 case 'F':
583 infile = optarg;
584 break;
586 case 'i':
587 if (optarg[0] == '0' && optarg[1] == 0)
588 error("Invalid adapter index");
590 #ifdef HAVE_PCAP_FINDALLDEVS
592 * If the argument is a number, treat it as
593 * an index into the list of adapters, as
594 * printed by "tcpdump -D".
596 * This should be OK on UNIX systems, as interfaces
597 * shouldn't have names that begin with digits.
598 * It can be useful on Windows, where more than
599 * one interface can have the same name.
601 if ((devnum = atoi(optarg)) != 0) {
602 if (devnum < 0)
603 error("Invalid adapter index");
605 if (pcap_findalldevs(&devpointer, ebuf) < 0)
606 error("%s", ebuf);
607 else {
608 for (i = 0; i < devnum-1; i++){
609 devpointer = devpointer->next;
610 if (devpointer == NULL)
611 error("Invalid adapter index");
614 device = devpointer->name;
615 break;
617 #endif /* HAVE_PCAP_FINDALLDEVS */
618 device = optarg;
619 break;
621 case 'l':
622 #ifdef WIN32
624 * _IOLBF is the same as _IOFBF in Microsoft's C
625 * libraries; the only alternative they offer
626 * is _IONBF.
628 * XXX - this should really be checking for MSVC++,
629 * not WIN32, if, for example, MinGW has its own
630 * C library that is more UNIX-compatible.
632 setvbuf(stdout, NULL, _IONBF, 0);
633 #else /* WIN32 */
634 #ifdef HAVE_SETLINEBUF
635 setlinebuf(stdout);
636 #else
637 setvbuf(stdout, NULL, _IOLBF, 0);
638 #endif
639 #endif /* WIN32 */
640 break;
642 case 'n':
643 ++nflag;
644 break;
646 case 'N':
647 ++Nflag;
648 break;
650 case 'm':
651 #ifdef LIBSMI
652 if (smiLoadModule(optarg) == 0) {
653 error("could not load MIB module %s", optarg);
655 sflag = 1;
656 #else
657 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
658 program_name, optarg);
659 (void)fprintf(stderr, "(no libsmi support)\n");
660 #endif
661 break;
663 case 'M':
664 /* TCP-MD5 shared secret */
665 #ifndef HAVE_LIBCRYPTO
666 warning("crypto code not compiled in");
667 #endif
668 tcpmd5secret = optarg;
669 break;
671 case 'O':
672 Oflag = 0;
673 break;
675 case 'p':
676 ++pflag;
677 break;
679 case 'q':
680 ++qflag;
681 ++suppress_default_print;
682 break;
684 case 'r':
685 RFileName = optarg;
686 break;
688 case 'R':
689 Rflag = 0;
690 break;
692 case 's': {
693 char *end;
695 snaplen = strtol(optarg, &end, 0);
696 if (optarg == end || *end != '\0'
697 || snaplen < 0 || snaplen > 65535)
698 error("invalid snaplen %s", optarg);
699 else if (snaplen == 0)
700 snaplen = 65535;
701 break;
704 case 'S':
705 ++Sflag;
706 break;
708 case 't':
709 ++tflag;
710 break;
712 case 'T':
713 if (strcasecmp(optarg, "vat") == 0)
714 packettype = PT_VAT;
715 else if (strcasecmp(optarg, "wb") == 0)
716 packettype = PT_WB;
717 else if (strcasecmp(optarg, "rpc") == 0)
718 packettype = PT_RPC;
719 else if (strcasecmp(optarg, "rtp") == 0)
720 packettype = PT_RTP;
721 else if (strcasecmp(optarg, "rtcp") == 0)
722 packettype = PT_RTCP;
723 else if (strcasecmp(optarg, "snmp") == 0)
724 packettype = PT_SNMP;
725 else if (strcasecmp(optarg, "cnfp") == 0)
726 packettype = PT_CNFP;
727 else if (strcasecmp(optarg, "tftp") == 0)
728 packettype = PT_TFTP;
729 else if (strcasecmp(optarg, "aodv") == 0)
730 packettype = PT_AODV;
731 else
732 error("unknown packet type `%s'", optarg);
733 break;
735 case 'u':
736 ++uflag;
737 break;
739 #ifdef HAVE_PCAP_DUMP_FLUSH
740 case 'U':
741 ++Uflag;
742 break;
743 #endif
745 case 'v':
746 ++vflag;
747 break;
749 case 'w':
750 WFileName = optarg;
751 break;
753 case 'W':
754 Wflag = atoi(optarg);
755 if (Wflag < 0)
756 error("invalid number of output files %s", optarg);
757 WflagChars = getWflagChars(Wflag);
758 break;
760 case 'x':
761 ++xflag;
762 ++suppress_default_print;
763 break;
765 case 'X':
766 ++Xflag;
767 ++suppress_default_print;
768 break;
770 case 'y':
771 gndo->ndo_dltname = optarg;
772 gndo->ndo_dlt =
773 pcap_datalink_name_to_val(gndo->ndo_dltname);
774 if (gndo->ndo_dlt < 0)
775 error("invalid data link type %s", gndo->ndo_dltname);
776 break;
778 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
779 case 'Y':
781 /* Undocumented flag */
782 #ifdef HAVE_PCAP_DEBUG
783 extern int pcap_debug;
784 pcap_debug = 1;
785 #else
786 extern int yydebug;
787 yydebug = 1;
788 #endif
790 break;
791 #endif
792 case 'Z':
793 if (optarg) {
794 username = strdup(optarg);
796 else {
797 usage();
798 /* NOTREACHED */
800 break;
802 default:
803 usage();
804 /* NOTREACHED */
807 switch (tflag) {
809 case 0: /* Default */
810 case 4: /* Default + Date*/
811 thiszone = gmt2local(0);
812 break;
814 case 1: /* No time stamp */
815 case 2: /* Unix timeval style */
816 case 3: /* Microseconds since previous packet */
817 break;
819 default: /* Not supported */
820 error("only -t, -tt, -ttt, and -tttt are supported");
821 break;
824 #ifdef WITH_CHROOT
825 /* if run as root, prepare for chrooting */
826 if (getuid() == 0 || geteuid() == 0) {
827 /* future extensibility for cmd-line arguments */
828 if (!chroot_dir)
829 chroot_dir = WITH_CHROOT;
831 #endif
833 #ifdef WITH_USER
834 /* if run as root, prepare for dropping root privileges */
835 if (getuid() == 0 || geteuid() == 0) {
836 /* Run with '-Z root' to restore old behaviour */
837 if (!username)
838 username = WITH_USER;
840 #endif
842 if (RFileName != NULL) {
843 int dlt;
844 const char *dlt_name;
846 #ifndef WIN32
848 * We don't need network access, so relinquish any set-UID
849 * or set-GID privileges we have (if any).
851 * We do *not* want set-UID privileges when opening a
852 * trace file, as that might let the user read other
853 * people's trace files (especially if we're set-UID
854 * root).
856 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
857 fprintf(stderr, "Warning: setgid/setuid failed !\n");
858 #endif /* WIN32 */
859 pd = pcap_open_offline(RFileName, ebuf);
860 if (pd == NULL)
861 error("%s", ebuf);
862 dlt = pcap_datalink(pd);
863 dlt_name = pcap_datalink_val_to_name(dlt);
864 if (dlt_name == NULL) {
865 fprintf(stderr, "reading from file %s, link-type %u\n",
866 RFileName, dlt);
867 } else {
868 fprintf(stderr,
869 "reading from file %s, link-type %s (%s)\n",
870 RFileName, dlt_name,
871 pcap_datalink_val_to_description(dlt));
873 localnet = 0;
874 netmask = 0;
875 if (fflag != 0)
876 error("-f and -r options are incompatible");
877 } else {
878 if (device == NULL) {
879 device = pcap_lookupdev(ebuf);
880 if (device == NULL)
881 error("%s", ebuf);
883 #ifdef WIN32
884 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
885 { //a Unicode string has a \0 as second byte (so strlen() is 1)
886 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
888 else
890 fprintf(stderr, "%s: listening on %s\n", program_name, device);
893 fflush(stderr);
894 #endif /* WIN32 */
895 *ebuf = '\0';
896 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
897 if (pd == NULL)
898 error("%s", ebuf);
899 else if (*ebuf)
900 warning("%s", ebuf);
902 * Let user own process after socket has been opened.
904 #ifndef WIN32
905 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
906 fprintf(stderr, "Warning: setgid/setuid failed !\n");
907 #endif /* WIN32 */
908 #ifdef WIN32
909 if(UserBufferSize != 1000000)
910 if(pcap_setbuff(pd, UserBufferSize)==-1){
911 error("%s", pcap_geterr(pd));
913 #endif /* WIN32 */
914 if (Lflag)
915 show_dlts_and_exit(pd);
916 if (gndo->ndo_dlt >= 0) {
917 #ifdef HAVE_PCAP_SET_DATALINK
918 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
919 error("%s", pcap_geterr(pd));
920 #else
922 * We don't actually support changing the
923 * data link type, so we only let them
924 * set it to what it already is.
926 if (gndo->ndo_dlt != pcap_datalink(pd)) {
927 error("%s is not one of the DLTs supported by this device\n",
928 gndo->ndo_dltname);
930 #endif
931 (void)fprintf(stderr, "%s: data link type %s\n",
932 program_name, gndo->ndo_dltname);
933 (void)fflush(stderr);
935 i = pcap_snapshot(pd);
936 if (snaplen < i) {
937 warning("snaplen raised from %d to %d", snaplen, i);
938 snaplen = i;
940 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
941 localnet = 0;
942 netmask = 0;
943 warning("%s", ebuf);
946 if (infile)
947 cmdbuf = read_infile(infile);
948 else
949 cmdbuf = copy_argv(&argv[optind]);
951 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
952 error("%s", pcap_geterr(pd));
953 if (dflag) {
954 bpf_dump(&fcode, dflag);
955 pcap_close(pd);
956 exit(0);
958 init_addrtoname(localnet, netmask);
960 #ifndef WIN32
961 (void)setsignal(SIGPIPE, cleanup);
962 #endif /* WIN32 */
963 (void)setsignal(SIGTERM, cleanup);
964 (void)setsignal(SIGINT, cleanup);
965 /* Cooperate with nohup(1) */
966 #ifndef WIN32
967 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
968 (void)setsignal(SIGHUP, oldhandler);
969 #endif /* WIN32 */
971 if (pcap_setfilter(pd, &fcode) < 0)
972 error("%s", pcap_geterr(pd));
973 if (WFileName) {
974 pcap_dumper_t *p;
976 WFileNameAlt = (char *)malloc(strlen(WFileName) + MAX_CFLAG_CHARS + 1);
977 if (WFileNameAlt == NULL)
978 error("malloc of WFileNameAlt");
979 MakeFilename(WFileNameAlt, WFileName, 0, WflagChars);
980 p = pcap_dump_open(pd, WFileNameAlt);
981 if (p == NULL)
982 error("%s", pcap_geterr(pd));
983 if (Cflag != 0) {
984 callback = dump_packet_and_trunc;
985 dumpinfo.WFileName = WFileName;
986 dumpinfo.pd = pd;
987 dumpinfo.p = p;
988 pcap_userdata = (u_char *)&dumpinfo;
989 } else {
990 callback = dump_packet;
991 pcap_userdata = (u_char *)p;
993 } else {
994 type = pcap_datalink(pd);
995 printinfo.printer = lookup_printer(type);
996 if (printinfo.printer == NULL) {
997 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
998 if (gndo->ndo_dltname != NULL)
999 error("unsupported data link type %s",
1000 gndo->ndo_dltname);
1001 else
1002 error("unsupported data link type %d", type);
1004 callback = print_packet;
1005 pcap_userdata = (u_char *)&printinfo;
1007 #ifndef WIN32
1009 * We cannot do this earlier, because we want to be able to open
1010 * the file (if done) for writing before giving up permissions.
1012 if (getuid() == 0 || geteuid() == 0) {
1013 if (username || chroot_dir)
1014 droproot(username, chroot_dir);
1016 #endif /* WIN32 */
1017 #ifdef SIGINFO
1018 (void)setsignal(SIGINFO, requestinfo);
1019 #endif
1021 if (vflag > 0 && WFileName) {
1023 * When capturing to a file, "-v" means tcpdump should,
1024 * every 10 secodns, "v"erbosely report the number of
1025 * packets captured.
1027 #ifdef USE_WIN32_MM_TIMER
1028 /* call verbose_stats_dump() each 1000 +/-100msec */
1029 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1030 setvbuf(stderr, NULL, _IONBF, 0);
1031 #elif defined(HAVE_ALARM)
1032 (void)setsignal(SIGALRM, verbose_stats_dump);
1033 alarm(1);
1034 #endif
1037 #ifndef WIN32
1038 if (RFileName == NULL) {
1039 int dlt;
1040 const char *dlt_name;
1042 if (!vflag && !WFileName) {
1043 (void)fprintf(stderr,
1044 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1045 program_name);
1046 } else
1047 (void)fprintf(stderr, "%s: ", program_name);
1048 dlt = pcap_datalink(pd);
1049 dlt_name = pcap_datalink_val_to_name(dlt);
1050 if (dlt_name == NULL) {
1051 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1052 device, dlt, snaplen);
1053 } else {
1054 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1055 device, dlt_name,
1056 pcap_datalink_val_to_description(dlt), snaplen);
1058 (void)fflush(stderr);
1060 #endif /* WIN32 */
1061 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1062 if (WFileName == NULL) {
1064 * We're printing packets. Flush the printed output,
1065 * so it doesn't get intermingled with error output.
1067 if (status == -2) {
1069 * We got interrupted, so perhaps we didn't
1070 * manage to finish a line we were printing.
1071 * Print an extra newline, just in case.
1073 putchar('\n');
1075 (void)fflush(stdout);
1077 if (status == -1) {
1079 * Error. Report it.
1081 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1082 program_name, pcap_geterr(pd));
1084 if (RFileName == NULL) {
1086 * We're doing a live capture. Report the capture
1087 * statistics.
1089 info(1);
1091 pcap_close(pd);
1092 exit(status == -1 ? 1 : 0);
1095 /* make a clean exit on interrupts */
1096 static RETSIGTYPE
1097 cleanup(int signo _U_)
1099 #ifdef USE_WIN32_MM_TIMER
1100 if (timer_id)
1101 timeKillEvent(timer_id);
1102 timer_id = 0;
1103 #elif defined(HAVE_ALARM)
1104 alarm(0);
1105 #endif
1107 #ifdef HAVE_PCAP_BREAKLOOP
1109 * We have "pcap_breakloop()"; use it, so that we do as little
1110 * as possible in the signal handler (it's probably not safe
1111 * to do anything with standard I/O streams in a signal handler -
1112 * the ANSI C standard doesn't say it is).
1114 pcap_breakloop(pd);
1115 #else
1117 * We don't have "pcap_breakloop()"; this isn't safe, but
1118 * it's the best we can do. Print the summary if we're
1119 * not reading from a savefile - i.e., if we're doing a
1120 * live capture - and exit.
1122 if (pd != NULL && pcap_file(pd) == NULL) {
1124 * We got interrupted, so perhaps we didn't
1125 * manage to finish a line we were printing.
1126 * Print an extra newline, just in case.
1128 putchar('\n');
1129 (void)fflush(stdout);
1130 info(1);
1132 exit(0);
1133 #endif
1136 static void
1137 info(register int verbose)
1139 struct pcap_stat stat;
1141 if (pcap_stats(pd, &stat) < 0) {
1142 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1143 return;
1146 if (!verbose)
1147 fprintf(stderr, "%s: ", program_name);
1149 (void)fprintf(stderr, "%u packets captured", packets_captured);
1150 if (!verbose)
1151 fputs(", ", stderr);
1152 else
1153 putc('\n', stderr);
1154 (void)fprintf(stderr, "%d packets received by filter", stat.ps_recv);
1155 if (!verbose)
1156 fputs(", ", stderr);
1157 else
1158 putc('\n', stderr);
1159 (void)fprintf(stderr, "%d packets dropped by kernel\n", stat.ps_drop);
1160 infoprint = 0;
1163 static void
1164 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1166 struct dump_info *dump_info;
1167 char *name;
1169 ++packets_captured;
1171 ++infodelay;
1173 dump_info = (struct dump_info *)user;
1176 * XXX - this won't prevent capture files from getting
1177 * larger than Cflag - the last packet written to the
1178 * file could put it over Cflag.
1180 if (pcap_dump_ftell(dump_info->p) > Cflag) {
1182 * Close the current file and open a new one.
1184 pcap_dump_close(dump_info->p);
1185 Cflag_count++;
1186 if (Wflag > 0) {
1187 if (Cflag_count >= Wflag)
1188 Cflag_count = 0;
1189 } else {
1190 if (Cflag_count >= MAX_CFLAG)
1191 error("too many output files");
1193 name = (char *)malloc(strlen(dump_info->WFileName) + MAX_CFLAG_CHARS + 1);
1194 if (name == NULL)
1195 error("dump_packet_and_trunc: malloc");
1196 MakeFilename(name, dump_info->WFileName, Cflag_count, WflagChars);
1197 dump_info->p = pcap_dump_open(dump_info->pd, name);
1198 free(name);
1199 if (dump_info->p == NULL)
1200 error("%s", pcap_geterr(pd));
1203 pcap_dump((u_char *)dump_info->p, h, sp);
1204 #ifdef HAVE_PCAP_DUMP_FLUSH
1205 if (Uflag)
1206 pcap_dump_flush(dump_info->p);
1207 #endif
1209 --infodelay;
1210 if (infoprint)
1211 info(0);
1214 static void
1215 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1217 ++packets_captured;
1219 ++infodelay;
1221 pcap_dump(user, h, sp);
1222 #ifdef HAVE_PCAP_DUMP_FLUSH
1223 if (Uflag)
1224 pcap_dump_flush((pcap_dumper_t *)user);
1225 #endif
1227 --infodelay;
1228 if (infoprint)
1229 info(0);
1232 static void
1233 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1235 struct print_info *print_info;
1236 u_int hdrlen;
1238 ++packets_captured;
1240 ++infodelay;
1241 ts_print(&h->ts);
1243 print_info = (struct print_info *)user;
1246 * Some printers want to check that they're not walking off the
1247 * end of the packet.
1248 * Rather than pass it all the way down, we set this global.
1250 snapend = sp + h->caplen;
1252 hdrlen = (*print_info->printer)(h, sp);
1253 if (Xflag) {
1255 * Print the raw packet data in hex and ASCII.
1257 if (Xflag > 1) {
1259 * Include the link-layer header.
1261 hex_and_ascii_print("\n\t", sp, h->caplen);
1262 } else {
1264 * Don't include the link-layer header - and if
1265 * we have nothing past the link-layer header,
1266 * print nothing.
1268 if (h->caplen > hdrlen)
1269 hex_and_ascii_print("\n\t", sp + hdrlen,
1270 h->caplen - hdrlen);
1272 } else if (xflag) {
1274 * Print the raw packet data in hex.
1276 if (xflag > 1) {
1278 * Include the link-layer header.
1280 hex_print("\n\t", sp, h->caplen);
1281 } else {
1283 * Don't include the link-layer header - and if
1284 * we have nothing past the link-layer header,
1285 * print nothing.
1287 if (h->caplen > hdrlen)
1288 hex_print("\n\t", sp + hdrlen,
1289 h->caplen - hdrlen);
1291 } else if (Aflag) {
1293 * Print the raw packet data in ASCII.
1295 if (Aflag > 1) {
1297 * Include the link-layer header.
1299 ascii_print(sp, h->caplen);
1300 } else {
1302 * Don't include the link-layer header - and if
1303 * we have nothing past the link-layer header,
1304 * print nothing.
1306 if (h->caplen > hdrlen)
1307 ascii_print(sp + hdrlen, h->caplen - hdrlen);
1311 putchar('\n');
1313 --infodelay;
1314 if (infoprint)
1315 info(0);
1318 #ifdef WIN32
1320 * XXX - there should really be libpcap calls to get the version
1321 * number as a string (the string would be generated from #defines
1322 * at run time, so that it's not generated from string constants
1323 * in the library, as, on many UNIX systems, those constants would
1324 * be statically linked into the application executable image, and
1325 * would thus reflect the version of libpcap on the system on
1326 * which the application was *linked*, not the system on which it's
1327 * *running*.
1329 * That routine should be documented, unlike the "version[]"
1330 * string, so that UNIX vendors providing their own libpcaps
1331 * don't omit it (as a couple of vendors have...).
1333 * Packet.dll should perhaps also export a routine to return the
1334 * version number of the Packet.dll code, to supply the
1335 * "Wpcap_version" information on Windows.
1337 char WDversion[]="current-cvs.tcpdump.org";
1338 #if !defined(HAVE_GENERATED_VERSION)
1339 char version[]="current-cvs.tcpdump.org";
1340 #endif
1341 char pcap_version[]="current-cvs.tcpdump.org";
1342 char Wpcap_version[]="3.1";
1343 #endif
1346 * By default, print the specified data out in hex and ASCII.
1348 static void
1349 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1351 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1354 void
1355 default_print(const u_char *bp, u_int length)
1357 ndo_default_print(gndo, bp, length);
1360 #ifdef SIGINFO
1361 RETSIGTYPE requestinfo(int signo _U_)
1363 if (infodelay)
1364 ++infoprint;
1365 else
1366 info(0);
1368 #endif
1371 * Called once each second in verbose mode while dumping to file
1373 #ifdef USE_WIN32_MM_TIMER
1374 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1375 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1377 struct pcap_stat stat;
1379 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1380 fprintf(stderr, "Got %u\r", packets_captured);
1382 #elif defined(HAVE_ALARM)
1383 static void verbose_stats_dump(int sig _U_)
1385 struct pcap_stat stat;
1387 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1388 fprintf(stderr, "Got %u\r", packets_captured);
1389 alarm(1);
1391 #endif
1393 static void
1394 usage(void)
1396 extern char version[];
1397 #ifndef HAVE_PCAP_LIB_VERSION
1398 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1399 extern char pcap_version[];
1400 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1401 static char pcap_version[] = "unknown";
1402 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1403 #endif /* HAVE_PCAP_LIB_VERSION */
1405 #ifdef HAVE_PCAP_LIB_VERSION
1406 #ifdef WIN32
1407 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1408 #else /* WIN32 */
1409 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1410 #endif /* WIN32 */
1411 (void)fprintf(stderr, "%s\n",pcap_lib_version());
1412 #else /* HAVE_PCAP_LIB_VERSION */
1413 #ifdef WIN32
1414 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1415 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1416 #else /* WIN32 */
1417 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1418 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1419 #endif /* WIN32 */
1420 #endif /* HAVE_PCAP_LIB_VERSION */
1421 (void)fprintf(stderr,
1422 "Usage: %s [-aAd" D_FLAG "eflLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [-c count] [ -C file_size ]\n", program_name);
1423 (void)fprintf(stderr,
1424 "\t\t[ -E algo:secret ] [ -F file ] [ -i interface ] [ -M secret ]\n");
1425 (void)fprintf(stderr,
1426 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]\n");
1427 (void)fprintf(stderr,
1428 "\t\t[ -W filecount ] [ -y datalinktype ] [ -Z user ]\n");
1429 (void)fprintf(stderr,
1430 "\t\t[ expression ]\n");
1431 exit(1);
1436 /* VARARGS */
1437 static void
1438 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1440 va_list ap;
1442 (void)fprintf(stderr, "%s: ", program_name);
1443 va_start(ap, fmt);
1444 (void)vfprintf(stderr, fmt, ap);
1445 va_end(ap);
1446 if (*fmt) {
1447 fmt += strlen(fmt);
1448 if (fmt[-1] != '\n')
1449 (void)fputc('\n', stderr);
1451 exit(1);
1452 /* NOTREACHED */
1455 /* VARARGS */
1456 static void
1457 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
1459 va_list ap;
1461 (void)fprintf(stderr, "%s: WARNING: ", program_name);
1462 va_start(ap, fmt);
1463 (void)vfprintf(stderr, fmt, ap);
1464 va_end(ap);
1465 if (*fmt) {
1466 fmt += strlen(fmt);
1467 if (fmt[-1] != '\n')
1468 (void)fputc('\n', stderr);