Correct math and limerick.
[dragonfly.git] / contrib / tcpdump / tcpdump.c
blob587ed32170ac925df013cd2d8cb8473737e71003
1 /*
2 * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
16 * written permission.
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21 * Support for splitting captures into multiple files with a maximum
22 * file size:
24 * Copyright (c) 2001
25 * Seth Webster <swebster@sst.ll.mit.edu>
28 #ifndef lint
29 static const char copyright[] _U_ =
30 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
31 The Regents of the University of California. All rights reserved.\n";
32 static const char rcsid[] _U_ =
33 "@(#) $Header: /tcpdump/master/tcpdump/tcpdump.c,v 1.283 2008-09-25 21:45:50 guy Exp $ (LBL)";
34 #endif
37 * tcpdump - monitor tcp/ip traffic on an ethernet.
39 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
40 * Mercilessly hacked and occasionally improved since then via the
41 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
44 #ifdef HAVE_CONFIG_H
45 #include "config.h"
46 #endif
48 #include <tcpdump-stdinc.h>
50 #ifdef WIN32
51 #include "getopt.h"
52 #include "w32_fzs.h"
53 extern int strcasecmp (const char *__s1, const char *__s2);
54 extern int SIZE_BUF;
55 #define off_t long
56 #define uint UINT
57 #endif /* WIN32 */
59 #ifdef HAVE_SMI_H
60 #include <smi.h>
61 #endif
63 #include <pcap.h>
64 #include <signal.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <limits.h>
69 #ifndef WIN32
70 #include <sys/wait.h>
71 #include <sys/resource.h>
72 #include <pwd.h>
73 #include <grp.h>
74 #include <errno.h>
75 #endif /* WIN32 */
78 #include "netdissect.h"
79 #include "interface.h"
80 #include "addrtoname.h"
81 #include "machdep.h"
82 #include "setsignal.h"
83 #include "gmt2local.h"
84 #include "pcap-missing.h"
86 #ifndef NAME_MAX
87 #define NAME_MAX 255
88 #endif
90 #ifdef SIGINFO
91 #define SIGNAL_REQ_INFO SIGINFO
92 #elif SIGUSR1
93 #define SIGNAL_REQ_INFO SIGUSR1
94 #endif
96 netdissect_options Gndo;
97 netdissect_options *gndo = &Gndo;
99 static int dflag; /* print filter code */
100 static int Lflag; /* list available data link types and exit */
101 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
102 static int Jflag; /* list available time stamp types */
103 #endif
104 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
106 static int infodelay;
107 static int infoprint;
109 char *program_name;
111 int32_t thiszone; /* seconds offset from gmt to local time */
113 /* Forwards */
114 static RETSIGTYPE cleanup(int);
115 static RETSIGTYPE child_cleanup(int);
116 static void usage(void) __attribute__((noreturn));
117 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
119 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
120 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
121 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
122 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
123 static void droproot(const char *, const char *);
124 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
125 __attribute__ ((noreturn, format (printf, 2, 3)));
126 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
128 #ifdef SIGNAL_REQ_INFO
129 RETSIGTYPE requestinfo(int);
130 #endif
132 #if defined(USE_WIN32_MM_TIMER)
133 #include <MMsystem.h>
134 static UINT timer_id;
135 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
136 #elif defined(HAVE_ALARM)
137 static void verbose_stats_dump(int sig);
138 #endif
140 static void info(int);
141 static u_int packets_captured;
143 struct printer {
144 if_printer f;
145 int type;
149 struct ndo_printer {
150 if_ndo_printer f;
151 int type;
155 static struct printer printers[] = {
156 { arcnet_if_print, DLT_ARCNET },
157 #ifdef DLT_ARCNET_LINUX
158 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
159 #endif
160 { token_if_print, DLT_IEEE802 },
161 #ifdef DLT_LANE8023
162 { lane_if_print, DLT_LANE8023 },
163 #endif
164 #ifdef DLT_CIP
165 { cip_if_print, DLT_CIP },
166 #endif
167 #ifdef DLT_ATM_CLIP
168 { cip_if_print, DLT_ATM_CLIP },
169 #endif
170 { sl_if_print, DLT_SLIP },
171 #ifdef DLT_SLIP_BSDOS
172 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
173 #endif
174 { ppp_if_print, DLT_PPP },
175 #ifdef DLT_PPP_WITHDIRECTION
176 { ppp_if_print, DLT_PPP_WITHDIRECTION },
177 #endif
178 #ifdef DLT_PPP_BSDOS
179 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
180 #endif
181 { fddi_if_print, DLT_FDDI },
182 { null_if_print, DLT_NULL },
183 #ifdef DLT_LOOP
184 { null_if_print, DLT_LOOP },
185 #endif
186 { raw_if_print, DLT_RAW },
187 { atm_if_print, DLT_ATM_RFC1483 },
188 #ifdef DLT_C_HDLC
189 { chdlc_if_print, DLT_C_HDLC },
190 #endif
191 #ifdef DLT_HDLC
192 { chdlc_if_print, DLT_HDLC },
193 #endif
194 #ifdef DLT_PPP_SERIAL
195 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
196 #endif
197 #ifdef DLT_PPP_ETHER
198 { pppoe_if_print, DLT_PPP_ETHER },
199 #endif
200 #ifdef DLT_LINUX_SLL
201 { sll_if_print, DLT_LINUX_SLL },
202 #endif
203 #ifdef DLT_IEEE802_11
204 { ieee802_11_if_print, DLT_IEEE802_11},
205 #endif
206 #ifdef DLT_LTALK
207 { ltalk_if_print, DLT_LTALK },
208 #endif
209 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
210 { pflog_if_print, DLT_PFLOG },
211 #endif
212 #ifdef DLT_FR
213 { fr_if_print, DLT_FR },
214 #endif
215 #ifdef DLT_FRELAY
216 { fr_if_print, DLT_FRELAY },
217 #endif
218 #ifdef DLT_SUNATM
219 { sunatm_if_print, DLT_SUNATM },
220 #endif
221 #ifdef DLT_IP_OVER_FC
222 { ipfc_if_print, DLT_IP_OVER_FC },
223 #endif
224 #ifdef DLT_PRISM_HEADER
225 { prism_if_print, DLT_PRISM_HEADER },
226 #endif
227 #ifdef DLT_IEEE802_11_RADIO
228 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
229 #endif
230 #ifdef DLT_ENC
231 { enc_if_print, DLT_ENC },
232 #endif
233 #ifdef DLT_SYMANTEC_FIREWALL
234 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
235 #endif
236 #ifdef DLT_APPLE_IP_OVER_IEEE1394
237 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
238 #endif
239 #ifdef DLT_IEEE802_11_RADIO_AVS
240 { ieee802_11_radio_avs_if_print, DLT_IEEE802_11_RADIO_AVS },
241 #endif
242 #ifdef DLT_JUNIPER_ATM1
243 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
244 #endif
245 #ifdef DLT_JUNIPER_ATM2
246 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
247 #endif
248 #ifdef DLT_JUNIPER_MFR
249 { juniper_mfr_print, DLT_JUNIPER_MFR },
250 #endif
251 #ifdef DLT_JUNIPER_MLFR
252 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
253 #endif
254 #ifdef DLT_JUNIPER_MLPPP
255 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
256 #endif
257 #ifdef DLT_JUNIPER_PPPOE
258 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
259 #endif
260 #ifdef DLT_JUNIPER_PPPOE_ATM
261 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
262 #endif
263 #ifdef DLT_JUNIPER_GGSN
264 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
265 #endif
266 #ifdef DLT_JUNIPER_ES
267 { juniper_es_print, DLT_JUNIPER_ES },
268 #endif
269 #ifdef DLT_JUNIPER_MONITOR
270 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
271 #endif
272 #ifdef DLT_JUNIPER_SERVICES
273 { juniper_services_print, DLT_JUNIPER_SERVICES },
274 #endif
275 #ifdef DLT_JUNIPER_ETHER
276 { juniper_ether_print, DLT_JUNIPER_ETHER },
277 #endif
278 #ifdef DLT_JUNIPER_PPP
279 { juniper_ppp_print, DLT_JUNIPER_PPP },
280 #endif
281 #ifdef DLT_JUNIPER_FRELAY
282 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
283 #endif
284 #ifdef DLT_JUNIPER_CHDLC
285 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
286 #endif
287 #ifdef DLT_MFR
288 { mfr_if_print, DLT_MFR },
289 #endif
290 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
291 { bt_if_print, DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
292 #endif
293 #ifdef HAVE_PCAP_USB_H
294 #ifdef DLT_USB_LINUX
295 { usb_linux_48_byte_print, DLT_USB_LINUX},
296 #endif /* DLT_USB_LINUX */
297 #ifdef DLT_USB_LINUX_MMAPPED
298 { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
299 #endif /* DLT_USB_LINUX_MMAPPED */
300 #endif /* HAVE_PCAP_USB_H */
301 #ifdef DLT_IPV4
302 { raw_if_print, DLT_IPV4 },
303 #endif
304 #ifdef DLT_IPV6
305 { raw_if_print, DLT_IPV6 },
306 #endif
307 { NULL, 0 },
310 static struct ndo_printer ndo_printers[] = {
311 { ether_if_print, DLT_EN10MB },
312 #ifdef DLT_IPNET
313 { ipnet_if_print, DLT_IPNET },
314 #endif
315 #ifdef DLT_IEEE802_15_4
316 { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
317 #endif
318 #ifdef DLT_IEEE802_15_4_NOFCS
319 { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
320 #endif
321 #ifdef DLT_PPI
322 { ppi_if_print, DLT_PPI },
323 #endif
324 #ifdef DLT_NETANALYZER
325 { netanalyzer_if_print, DLT_NETANALYZER },
326 #endif
327 #ifdef DLT_NETANALYZER_TRANSPARENT
328 { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
329 #endif
330 { NULL, 0 },
333 if_printer
334 lookup_printer(int type)
336 struct printer *p;
338 for (p = printers; p->f; ++p)
339 if (type == p->type)
340 return p->f;
342 return NULL;
343 /* NOTREACHED */
346 if_ndo_printer
347 lookup_ndo_printer(int type)
349 struct ndo_printer *p;
351 for (p = ndo_printers; p->f; ++p)
352 if (type == p->type)
353 return p->f;
355 return NULL;
356 /* NOTREACHED */
359 static pcap_t *pd;
361 static int supports_monitor_mode;
363 extern int optind;
364 extern int opterr;
365 extern char *optarg;
367 struct print_info {
368 netdissect_options *ndo;
369 union {
370 if_printer printer;
371 if_ndo_printer ndo_printer;
372 } p;
373 int ndo_type;
376 struct dump_info {
377 char *WFileName;
378 char *CurrentFileName;
379 pcap_t *pd;
380 pcap_dumper_t *p;
383 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
384 static void
385 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
387 int n_tstamp_types;
388 int *tstamp_types = 0;
389 const char *tstamp_type_name;
390 int i;
392 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
393 if (n_tstamp_types < 0)
394 error("%s", pcap_geterr(pd));
396 if (n_tstamp_types == 0) {
397 fprintf(stderr, "Time stamp type cannot be set for %s\n",
398 device);
399 exit(0);
401 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
402 device);
403 for (i = 0; i < n_tstamp_types; i++) {
404 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
405 if (tstamp_type_name != NULL) {
406 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
407 pcap_tstamp_type_val_to_description(tstamp_types[i]));
408 } else {
409 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
412 pcap_free_tstamp_types(tstamp_types);
413 exit(0);
415 #endif
417 static void
418 show_dlts_and_exit(const char *device, pcap_t *pd)
420 int n_dlts;
421 int *dlts = 0;
422 const char *dlt_name;
424 n_dlts = pcap_list_datalinks(pd, &dlts);
425 if (n_dlts < 0)
426 error("%s", pcap_geterr(pd));
427 else if (n_dlts == 0 || !dlts)
428 error("No data link types.");
431 * If the interface is known to support monitor mode, indicate
432 * whether these are the data link types available when not in
433 * monitor mode, if -I wasn't specified, or when in monitor mode,
434 * when -I was specified (the link-layer types available in
435 * monitor mode might be different from the ones available when
436 * not in monitor mode).
438 if (supports_monitor_mode)
439 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
440 device,
441 Iflag ? "when in monitor mode" : "when not in monitor mode");
442 else
443 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
444 device);
446 while (--n_dlts >= 0) {
447 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
448 if (dlt_name != NULL) {
449 (void) fprintf(stderr, " %s (%s)", dlt_name,
450 pcap_datalink_val_to_description(dlts[n_dlts]));
453 * OK, does tcpdump handle that type?
455 if (lookup_printer(dlts[n_dlts]) == NULL
456 && lookup_ndo_printer(dlts[n_dlts]) == NULL)
457 (void) fprintf(stderr, " (printing not supported)");
458 fprintf(stderr, "\n");
459 } else {
460 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
461 dlts[n_dlts]);
464 pcap_free_datalinks(dlts);
465 exit(0);
469 * Set up flags that might or might not be supported depending on the
470 * version of libpcap we're using.
472 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
473 #define B_FLAG "B:"
474 #define B_FLAG_USAGE " [ -B size ]"
475 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
476 #define B_FLAG
477 #define B_FLAG_USAGE
478 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
480 #ifdef HAVE_PCAP_CREATE
481 #define I_FLAG "I"
482 #else /* HAVE_PCAP_CREATE */
483 #define I_FLAG
484 #endif /* HAVE_PCAP_CREATE */
486 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
487 #define j_FLAG "j:"
488 #define j_FLAG_USAGE " [ -j tstamptype ]"
489 #define J_FLAG "J"
490 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
491 #define j_FLAG
492 #define j_FLAG_USAGE
493 #define J_FLAG
494 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
496 #ifdef HAVE_PCAP_FINDALLDEVS
497 #ifndef HAVE_PCAP_IF_T
498 #undef HAVE_PCAP_FINDALLDEVS
499 #endif
500 #endif
502 #ifdef HAVE_PCAP_FINDALLDEVS
503 #define D_FLAG "D"
504 #else
505 #define D_FLAG
506 #endif
508 #ifdef HAVE_PCAP_DUMP_FLUSH
509 #define U_FLAG "U"
510 #else
511 #define U_FLAG
512 #endif
514 #ifndef WIN32
515 /* Drop root privileges and chroot if necessary */
516 static void
517 droproot(const char *username, const char *chroot_dir)
519 struct passwd *pw = NULL;
521 if (chroot_dir && !username) {
522 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
523 exit(1);
526 pw = getpwnam(username);
527 if (pw) {
528 if (chroot_dir) {
529 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
530 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
531 chroot_dir, pcap_strerror(errno));
532 exit(1);
535 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
536 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
537 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
538 username,
539 (unsigned long)pw->pw_uid,
540 (unsigned long)pw->pw_gid,
541 pcap_strerror(errno));
542 exit(1);
545 else {
546 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
547 username);
548 exit(1);
551 #endif /* WIN32 */
553 static int
554 getWflagChars(int x)
556 int c = 0;
558 x -= 1;
559 while (x > 0) {
560 c += 1;
561 x /= 10;
564 return c;
568 static void
569 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
571 char *filename = malloc(NAME_MAX + 1);
573 /* Process with strftime if Gflag is set. */
574 if (Gflag != 0) {
575 struct tm *local_tm;
577 /* Convert Gflag_time to a usable format */
578 if ((local_tm = localtime(&Gflag_time)) == NULL) {
579 error("MakeTimedFilename: localtime");
582 /* There's no good way to detect an error in strftime since a return
583 * value of 0 isn't necessarily failure.
585 strftime(filename, NAME_MAX, orig_name, local_tm);
586 } else {
587 strncpy(filename, orig_name, NAME_MAX);
590 if (cnt == 0 && max_chars == 0)
591 strncpy(buffer, filename, NAME_MAX + 1);
592 else
593 if (snprintf(buffer, NAME_MAX + 1, "%s%0*d", filename, max_chars, cnt) > NAME_MAX)
594 /* Report an error if the filename is too large */
595 error("too many output files or filename is too long (> %d)", NAME_MAX);
596 free(filename);
599 static int tcpdump_printf(netdissect_options *ndo _U_,
600 const char *fmt, ...)
603 va_list args;
604 int ret;
606 va_start(args, fmt);
607 ret=vfprintf(stdout, fmt, args);
608 va_end(args);
610 return ret;
614 main(int argc, char **argv)
616 register int cnt, op, i;
617 bpf_u_int32 localnet, netmask;
618 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
619 pcap_handler callback;
620 int type;
621 struct bpf_program fcode;
622 #ifndef WIN32
623 RETSIGTYPE (*oldhandler)(int);
624 #endif
625 struct print_info printinfo;
626 struct dump_info dumpinfo;
627 u_char *pcap_userdata;
628 char ebuf[PCAP_ERRBUF_SIZE];
629 char *username = NULL;
630 char *chroot_dir = NULL;
631 #ifdef HAVE_PCAP_FINDALLDEVS
632 pcap_if_t *devpointer;
633 int devnum;
634 #endif
635 int status;
636 #ifdef WIN32
637 if(wsockinit() != 0) return 1;
638 #endif /* WIN32 */
640 jflag=-1; /* not set */
641 gndo->ndo_Oflag=1;
642 gndo->ndo_Rflag=1;
643 gndo->ndo_dlt=-1;
644 gndo->ndo_default_print=ndo_default_print;
645 gndo->ndo_printf=tcpdump_printf;
646 gndo->ndo_error=ndo_error;
647 gndo->ndo_warning=ndo_warning;
648 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
650 cnt = -1;
651 device = NULL;
652 infile = NULL;
653 RFileName = NULL;
654 WFileName = NULL;
655 if ((cp = strrchr(argv[0], '/')) != NULL)
656 program_name = cp + 1;
657 else
658 program_name = argv[0];
660 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
661 error("%s", ebuf);
663 #ifdef LIBSMI
664 smiInit("tcpdump");
665 #endif
667 while (
668 (op = getopt(argc, argv, "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpqr:Rs:StT:u" U_FLAG "vw:W:xXy:Yz:Z:")) != -1)
669 switch (op) {
671 case 'a':
672 /* compatibility for old -a */
673 break;
675 case 'A':
676 ++Aflag;
677 break;
679 case 'b':
680 ++bflag;
681 break;
683 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
684 case 'B':
685 Bflag = atoi(optarg)*1024;
686 if (Bflag <= 0)
687 error("invalid packet buffer size %s", optarg);
688 break;
689 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
691 case 'c':
692 cnt = atoi(optarg);
693 if (cnt <= 0)
694 error("invalid packet count %s", optarg);
695 break;
697 case 'C':
698 Cflag = atoi(optarg) * 1000000;
699 if (Cflag < 0)
700 error("invalid file size %s", optarg);
701 break;
703 case 'd':
704 ++dflag;
705 break;
707 #ifdef HAVE_PCAP_FINDALLDEVS
708 case 'D':
709 if (pcap_findalldevs(&devpointer, ebuf) < 0)
710 error("%s", ebuf);
711 else {
712 for (i = 0; devpointer != 0; i++) {
713 printf("%d.%s", i+1, devpointer->name);
714 if (devpointer->description != NULL)
715 printf(" (%s)", devpointer->description);
716 printf("\n");
717 devpointer = devpointer->next;
720 return 0;
721 #endif /* HAVE_PCAP_FINDALLDEVS */
723 case 'L':
724 Lflag++;
725 break;
727 case 'e':
728 ++eflag;
729 break;
731 case 'E':
732 #ifndef HAVE_LIBCRYPTO
733 warning("crypto code not compiled in");
734 #endif
735 gndo->ndo_espsecret = optarg;
736 break;
738 case 'f':
739 ++fflag;
740 break;
742 case 'F':
743 infile = optarg;
744 break;
746 case 'G':
747 Gflag = atoi(optarg);
748 if (Gflag < 0)
749 error("invalid number of seconds %s", optarg);
751 /* We will create one file initially. */
752 Gflag_count = 0;
754 /* Grab the current time for rotation use. */
755 if ((Gflag_time = time(NULL)) == (time_t)-1) {
756 error("main: can't get current time: %s",
757 pcap_strerror(errno));
759 break;
761 case 'h':
762 usage();
763 break;
765 case 'H':
766 ++Hflag;
767 break;
769 case 'i':
770 if (optarg[0] == '0' && optarg[1] == 0)
771 error("Invalid adapter index");
773 #ifdef HAVE_PCAP_FINDALLDEVS
775 * If the argument is a number, treat it as
776 * an index into the list of adapters, as
777 * printed by "tcpdump -D".
779 * This should be OK on UNIX systems, as interfaces
780 * shouldn't have names that begin with digits.
781 * It can be useful on Windows, where more than
782 * one interface can have the same name.
784 if ((devnum = atoi(optarg)) != 0) {
785 if (devnum < 0)
786 error("Invalid adapter index");
788 if (pcap_findalldevs(&devpointer, ebuf) < 0)
789 error("%s", ebuf);
790 else {
792 * Look for the devnum-th entry
793 * in the list of devices
794 * (1-based).
796 for (i = 0;
797 i < devnum-1 && devpointer != NULL;
798 i++, devpointer = devpointer->next)
800 if (devpointer == NULL)
801 error("Invalid adapter index");
803 device = devpointer->name;
804 break;
806 #endif /* HAVE_PCAP_FINDALLDEVS */
807 device = optarg;
808 break;
810 #ifdef HAVE_PCAP_CREATE
811 case 'I':
812 ++Iflag;
813 break;
814 #endif /* HAVE_PCAP_CREATE */
816 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
817 case 'j':
818 jflag = pcap_tstamp_type_name_to_val(optarg);
819 if (jflag < 0)
820 error("invalid time stamp type %s", optarg);
821 break;
823 case 'J':
824 Jflag++;
825 break;
826 #endif
828 case 'l':
829 #ifdef WIN32
831 * _IOLBF is the same as _IOFBF in Microsoft's C
832 * libraries; the only alternative they offer
833 * is _IONBF.
835 * XXX - this should really be checking for MSVC++,
836 * not WIN32, if, for example, MinGW has its own
837 * C library that is more UNIX-compatible.
839 setvbuf(stdout, NULL, _IONBF, 0);
840 #else /* WIN32 */
841 #ifdef HAVE_SETLINEBUF
842 setlinebuf(stdout);
843 #else
844 setvbuf(stdout, NULL, _IOLBF, 0);
845 #endif
846 #endif /* WIN32 */
847 break;
849 case 'K':
850 ++Kflag;
851 break;
853 case 'm':
854 #ifdef LIBSMI
855 if (smiLoadModule(optarg) == 0) {
856 error("could not load MIB module %s", optarg);
858 sflag = 1;
859 #else
860 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
861 program_name, optarg);
862 (void)fprintf(stderr, "(no libsmi support)\n");
863 #endif
864 break;
866 case 'M':
867 /* TCP-MD5 shared secret */
868 #ifndef HAVE_LIBCRYPTO
869 warning("crypto code not compiled in");
870 #endif
871 sigsecret = optarg;
872 break;
874 case 'n':
875 ++nflag;
876 break;
878 case 'N':
879 ++Nflag;
880 break;
882 case 'O':
883 Oflag = 0;
884 break;
886 case 'p':
887 ++pflag;
888 break;
890 case 'q':
891 ++qflag;
892 ++suppress_default_print;
893 break;
895 case 'r':
896 RFileName = optarg;
897 break;
899 case 'R':
900 Rflag = 0;
901 break;
903 case 's': {
904 char *end;
906 snaplen = strtol(optarg, &end, 0);
907 if (optarg == end || *end != '\0'
908 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
909 error("invalid snaplen %s", optarg);
910 else if (snaplen == 0)
911 snaplen = MAXIMUM_SNAPLEN;
912 break;
915 case 'S':
916 ++Sflag;
917 break;
919 case 't':
920 ++tflag;
921 break;
923 case 'T':
924 if (strcasecmp(optarg, "vat") == 0)
925 packettype = PT_VAT;
926 else if (strcasecmp(optarg, "wb") == 0)
927 packettype = PT_WB;
928 else if (strcasecmp(optarg, "rpc") == 0)
929 packettype = PT_RPC;
930 else if (strcasecmp(optarg, "rtp") == 0)
931 packettype = PT_RTP;
932 else if (strcasecmp(optarg, "rtcp") == 0)
933 packettype = PT_RTCP;
934 else if (strcasecmp(optarg, "snmp") == 0)
935 packettype = PT_SNMP;
936 else if (strcasecmp(optarg, "cnfp") == 0)
937 packettype = PT_CNFP;
938 else if (strcasecmp(optarg, "tftp") == 0)
939 packettype = PT_TFTP;
940 else if (strcasecmp(optarg, "aodv") == 0)
941 packettype = PT_AODV;
942 else if (strcasecmp(optarg, "carp") == 0)
943 packettype = PT_CARP;
944 else
945 error("unknown packet type `%s'", optarg);
946 break;
948 case 'u':
949 ++uflag;
950 break;
952 #ifdef HAVE_PCAP_DUMP_FLUSH
953 case 'U':
954 ++Uflag;
955 break;
956 #endif
958 case 'v':
959 ++vflag;
960 break;
962 case 'w':
963 WFileName = optarg;
964 break;
966 case 'W':
967 Wflag = atoi(optarg);
968 if (Wflag < 0)
969 error("invalid number of output files %s", optarg);
970 WflagChars = getWflagChars(Wflag);
971 break;
973 case 'x':
974 ++xflag;
975 ++suppress_default_print;
976 break;
978 case 'X':
979 ++Xflag;
980 ++suppress_default_print;
981 break;
983 case 'y':
984 gndo->ndo_dltname = optarg;
985 gndo->ndo_dlt =
986 pcap_datalink_name_to_val(gndo->ndo_dltname);
987 if (gndo->ndo_dlt < 0)
988 error("invalid data link type %s", gndo->ndo_dltname);
989 break;
991 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
992 case 'Y':
994 /* Undocumented flag */
995 #ifdef HAVE_PCAP_DEBUG
996 extern int pcap_debug;
997 pcap_debug = 1;
998 #else
999 extern int yydebug;
1000 yydebug = 1;
1001 #endif
1003 break;
1004 #endif
1005 case 'z':
1006 if (optarg) {
1007 zflag = strdup(optarg);
1008 } else {
1009 usage();
1010 /* NOTREACHED */
1012 break;
1014 case 'Z':
1015 if (optarg) {
1016 username = strdup(optarg);
1018 else {
1019 usage();
1020 /* NOTREACHED */
1022 break;
1024 default:
1025 usage();
1026 /* NOTREACHED */
1029 switch (tflag) {
1031 case 0: /* Default */
1032 case 4: /* Default + Date*/
1033 thiszone = gmt2local(0);
1034 break;
1036 case 1: /* No time stamp */
1037 case 2: /* Unix timeval style */
1038 case 3: /* Microseconds since previous packet */
1039 case 5: /* Microseconds since first packet */
1040 break;
1042 default: /* Not supported */
1043 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1044 break;
1047 #ifdef WITH_CHROOT
1048 /* if run as root, prepare for chrooting */
1049 if (getuid() == 0 || geteuid() == 0) {
1050 /* future extensibility for cmd-line arguments */
1051 if (!chroot_dir)
1052 chroot_dir = WITH_CHROOT;
1054 #endif
1056 #ifdef WITH_USER
1057 /* if run as root, prepare for dropping root privileges */
1058 if (getuid() == 0 || geteuid() == 0) {
1059 /* Run with '-Z root' to restore old behaviour */
1060 if (!username)
1061 username = WITH_USER;
1063 #endif
1065 if (RFileName != NULL) {
1066 int dlt;
1067 const char *dlt_name;
1069 #ifndef WIN32
1071 * We don't need network access, so relinquish any set-UID
1072 * or set-GID privileges we have (if any).
1074 * We do *not* want set-UID privileges when opening a
1075 * trace file, as that might let the user read other
1076 * people's trace files (especially if we're set-UID
1077 * root).
1079 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1080 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1081 #endif /* WIN32 */
1082 pd = pcap_open_offline(RFileName, ebuf);
1083 if (pd == NULL)
1084 error("%s", ebuf);
1085 dlt = pcap_datalink(pd);
1086 dlt_name = pcap_datalink_val_to_name(dlt);
1087 if (dlt_name == NULL) {
1088 fprintf(stderr, "reading from file %s, link-type %u\n",
1089 RFileName, dlt);
1090 } else {
1091 fprintf(stderr,
1092 "reading from file %s, link-type %s (%s)\n",
1093 RFileName, dlt_name,
1094 pcap_datalink_val_to_description(dlt));
1096 localnet = 0;
1097 netmask = 0;
1098 if (fflag != 0)
1099 error("-f and -r options are incompatible");
1100 } else {
1101 if (device == NULL) {
1102 device = pcap_lookupdev(ebuf);
1103 if (device == NULL)
1104 error("%s", ebuf);
1106 #ifdef WIN32
1107 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
1108 { //a Unicode string has a \0 as second byte (so strlen() is 1)
1109 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1111 else
1113 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1116 fflush(stderr);
1117 #endif /* WIN32 */
1118 #ifdef HAVE_PCAP_CREATE
1119 pd = pcap_create(device, ebuf);
1120 if (pd == NULL)
1121 error("%s", ebuf);
1122 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1123 if (Jflag)
1124 show_tstamp_types_and_exit(device, pd);
1125 #endif
1127 * Is this an interface that supports monitor mode?
1129 if (pcap_can_set_rfmon(pd) == 1)
1130 supports_monitor_mode = 1;
1131 else
1132 supports_monitor_mode = 0;
1133 status = pcap_set_snaplen(pd, snaplen);
1134 if (status != 0)
1135 error("%s: Can't set snapshot length: %s",
1136 device, pcap_statustostr(status));
1137 status = pcap_set_promisc(pd, !pflag);
1138 if (status != 0)
1139 error("%s: Can't set promiscuous mode: %s",
1140 device, pcap_statustostr(status));
1141 if (Iflag) {
1142 status = pcap_set_rfmon(pd, 1);
1143 if (status != 0)
1144 error("%s: Can't set monitor mode: %s",
1145 device, pcap_statustostr(status));
1147 status = pcap_set_timeout(pd, 1000);
1148 if (status != 0)
1149 error("%s: pcap_set_timeout failed: %s",
1150 device, pcap_statustostr(status));
1151 if (Bflag != 0) {
1152 status = pcap_set_buffer_size(pd, Bflag);
1153 if (status != 0)
1154 error("%s: Can't set buffer size: %s",
1155 device, pcap_statustostr(status));
1157 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1158 if (jflag != -1) {
1159 status = pcap_set_tstamp_type(pd, jflag);
1160 if (status < 0)
1161 error("%s: Can't set time stamp type: %s",
1162 device, pcap_statustostr(status));
1164 #endif
1165 status = pcap_activate(pd);
1166 if (status < 0) {
1168 * pcap_activate() failed.
1170 cp = pcap_geterr(pd);
1171 if (status == PCAP_ERROR)
1172 error("%s", cp);
1173 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1174 status == PCAP_ERROR_PERM_DENIED) &&
1175 *cp != '\0')
1176 error("%s: %s\n(%s)", device,
1177 pcap_statustostr(status), cp);
1178 else
1179 error("%s: %s", device,
1180 pcap_statustostr(status));
1181 } else if (status > 0) {
1183 * pcap_activate() succeeded, but it's warning us
1184 * of a problem it had.
1186 cp = pcap_geterr(pd);
1187 if (status == PCAP_WARNING)
1188 warning("%s", cp);
1189 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1190 *cp != '\0')
1191 warning("%s: %s\n(%s)", device,
1192 pcap_statustostr(status), cp);
1193 else
1194 warning("%s: %s", device,
1195 pcap_statustostr(status));
1197 #else
1198 *ebuf = '\0';
1199 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1200 if (pd == NULL)
1201 error("%s", ebuf);
1202 else if (*ebuf)
1203 warning("%s", ebuf);
1204 #endif /* HAVE_PCAP_CREATE */
1206 * Let user own process after socket has been opened.
1208 #ifndef WIN32
1209 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1210 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1211 #endif /* WIN32 */
1212 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1213 if(Bflag != 0)
1214 if(pcap_setbuff(pd, Bflag)==-1){
1215 error("%s", pcap_geterr(pd));
1217 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1218 if (Lflag)
1219 show_dlts_and_exit(device, pd);
1220 if (gndo->ndo_dlt >= 0) {
1221 #ifdef HAVE_PCAP_SET_DATALINK
1222 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1223 error("%s", pcap_geterr(pd));
1224 #else
1226 * We don't actually support changing the
1227 * data link type, so we only let them
1228 * set it to what it already is.
1230 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1231 error("%s is not one of the DLTs supported by this device\n",
1232 gndo->ndo_dltname);
1234 #endif
1235 (void)fprintf(stderr, "%s: data link type %s\n",
1236 program_name, gndo->ndo_dltname);
1237 (void)fflush(stderr);
1239 i = pcap_snapshot(pd);
1240 if (snaplen < i) {
1241 warning("snaplen raised from %d to %d", snaplen, i);
1242 snaplen = i;
1244 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1245 localnet = 0;
1246 netmask = 0;
1247 warning("%s", ebuf);
1250 if (infile)
1251 cmdbuf = read_infile(infile);
1252 else
1253 cmdbuf = copy_argv(&argv[optind]);
1255 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1256 error("%s", pcap_geterr(pd));
1257 free(cmdbuf);
1258 if (dflag) {
1259 bpf_dump(&fcode, dflag);
1260 pcap_close(pd);
1261 exit(0);
1263 init_addrtoname(localnet, netmask);
1264 init_checksum();
1266 #ifndef WIN32
1267 (void)setsignal(SIGPIPE, cleanup);
1268 (void)setsignal(SIGTERM, cleanup);
1269 (void)setsignal(SIGINT, cleanup);
1270 #endif /* WIN32 */
1271 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1272 (void)setsignal(SIGCHLD, child_cleanup);
1273 #endif
1274 /* Cooperate with nohup(1) */
1275 #ifndef WIN32
1276 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1277 (void)setsignal(SIGHUP, oldhandler);
1278 #endif /* WIN32 */
1280 #ifndef WIN32
1282 * If a user name was specified with "-Z", attempt to switch to
1283 * that user's UID. This would probably be used with sudo,
1284 * to allow tcpdump to be run in a special restricted
1285 * account (if you just want to allow users to open capture
1286 * devices, and can't just give users that permission,
1287 * you'd make tcpdump set-UID or set-GID).
1289 * Tcpdump doesn't necessarily write only to one savefile;
1290 * the general only way to allow a -Z instance to write to
1291 * savefiles as the user under whose UID it's run, rather
1292 * than as the user specified with -Z, would thus be to switch
1293 * to the original user ID before opening a capture file and
1294 * then switch back to the -Z user ID after opening the savefile.
1295 * Switching to the -Z user ID only after opening the first
1296 * savefile doesn't handle the general case.
1298 if (getuid() == 0 || geteuid() == 0) {
1299 if (username || chroot_dir)
1300 droproot(username, chroot_dir);
1302 #endif /* WIN32 */
1304 if (pcap_setfilter(pd, &fcode) < 0)
1305 error("%s", pcap_geterr(pd));
1306 if (WFileName) {
1307 pcap_dumper_t *p;
1308 /* Do not exceed the default NAME_MAX for files. */
1309 dumpinfo.CurrentFileName = (char *)malloc(NAME_MAX + 1);
1311 if (dumpinfo.CurrentFileName == NULL)
1312 error("malloc of dumpinfo.CurrentFileName");
1314 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1315 if (Cflag != 0)
1316 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1317 else
1318 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1320 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1321 if (p == NULL)
1322 error("%s", pcap_geterr(pd));
1323 if (Cflag != 0 || Gflag != 0) {
1324 callback = dump_packet_and_trunc;
1325 dumpinfo.WFileName = WFileName;
1326 dumpinfo.pd = pd;
1327 dumpinfo.p = p;
1328 pcap_userdata = (u_char *)&dumpinfo;
1329 } else {
1330 callback = dump_packet;
1331 pcap_userdata = (u_char *)p;
1333 #ifdef HAVE_PCAP_DUMP_FLUSH
1334 if (Uflag)
1335 pcap_dump_flush(p);
1336 #endif
1337 } else {
1338 type = pcap_datalink(pd);
1339 printinfo.ndo_type = 1;
1340 printinfo.ndo = gndo;
1341 printinfo.p.ndo_printer = lookup_ndo_printer(type);
1342 if (printinfo.p.ndo_printer == NULL) {
1343 printinfo.p.printer = lookup_printer(type);
1344 printinfo.ndo_type = 0;
1345 if (printinfo.p.printer == NULL) {
1346 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
1347 if (gndo->ndo_dltname != NULL)
1348 error("packet printing is not supported for link type %s: use -w",
1349 gndo->ndo_dltname);
1350 else
1351 error("packet printing is not supported for link type %d: use -w", type);
1354 callback = print_packet;
1355 pcap_userdata = (u_char *)&printinfo;
1358 #ifdef SIGNAL_REQ_INFO
1360 * We can't get statistics when reading from a file rather
1361 * than capturing from a device.
1363 if (RFileName == NULL)
1364 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1365 #endif
1367 if (vflag > 0 && WFileName) {
1369 * When capturing to a file, "-v" means tcpdump should,
1370 * every 10 secodns, "v"erbosely report the number of
1371 * packets captured.
1373 #ifdef USE_WIN32_MM_TIMER
1374 /* call verbose_stats_dump() each 1000 +/-100msec */
1375 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1376 setvbuf(stderr, NULL, _IONBF, 0);
1377 #elif defined(HAVE_ALARM)
1378 (void)setsignal(SIGALRM, verbose_stats_dump);
1379 alarm(1);
1380 #endif
1383 #ifndef WIN32
1384 if (RFileName == NULL) {
1385 int dlt;
1386 const char *dlt_name;
1388 if (!vflag && !WFileName) {
1389 (void)fprintf(stderr,
1390 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1391 program_name);
1392 } else
1393 (void)fprintf(stderr, "%s: ", program_name);
1394 dlt = pcap_datalink(pd);
1395 dlt_name = pcap_datalink_val_to_name(dlt);
1396 if (dlt_name == NULL) {
1397 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1398 device, dlt, snaplen);
1399 } else {
1400 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1401 device, dlt_name,
1402 pcap_datalink_val_to_description(dlt), snaplen);
1404 (void)fflush(stderr);
1406 #endif /* WIN32 */
1407 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1408 if (WFileName == NULL) {
1410 * We're printing packets. Flush the printed output,
1411 * so it doesn't get intermingled with error output.
1413 if (status == -2) {
1415 * We got interrupted, so perhaps we didn't
1416 * manage to finish a line we were printing.
1417 * Print an extra newline, just in case.
1419 putchar('\n');
1421 (void)fflush(stdout);
1423 if (status == -1) {
1425 * Error. Report it.
1427 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1428 program_name, pcap_geterr(pd));
1430 if (RFileName == NULL) {
1432 * We're doing a live capture. Report the capture
1433 * statistics.
1435 info(1);
1437 pcap_close(pd);
1438 exit(status == -1 ? 1 : 0);
1441 /* make a clean exit on interrupts */
1442 static RETSIGTYPE
1443 cleanup(int signo _U_)
1445 #ifdef USE_WIN32_MM_TIMER
1446 if (timer_id)
1447 timeKillEvent(timer_id);
1448 timer_id = 0;
1449 #elif defined(HAVE_ALARM)
1450 alarm(0);
1451 #endif
1453 #ifdef HAVE_PCAP_BREAKLOOP
1455 * We have "pcap_breakloop()"; use it, so that we do as little
1456 * as possible in the signal handler (it's probably not safe
1457 * to do anything with standard I/O streams in a signal handler -
1458 * the ANSI C standard doesn't say it is).
1460 pcap_breakloop(pd);
1461 #else
1463 * We don't have "pcap_breakloop()"; this isn't safe, but
1464 * it's the best we can do. Print the summary if we're
1465 * not reading from a savefile - i.e., if we're doing a
1466 * live capture - and exit.
1468 if (pd != NULL && pcap_file(pd) == NULL) {
1470 * We got interrupted, so perhaps we didn't
1471 * manage to finish a line we were printing.
1472 * Print an extra newline, just in case.
1474 putchar('\n');
1475 (void)fflush(stdout);
1476 info(1);
1478 exit(0);
1479 #endif
1483 On windows, we do not use a fork, so we do not care less about
1484 waiting a child processes to die
1486 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1487 static RETSIGTYPE
1488 child_cleanup(int signo _U_)
1490 wait(NULL);
1492 #endif /* HAVE_FORK && HAVE_VFORK */
1494 static void
1495 info(register int verbose)
1497 struct pcap_stat stat;
1500 * Older versions of libpcap didn't set ps_ifdrop on some
1501 * platforms; initialize it to 0 to handle that.
1503 stat.ps_ifdrop = 0;
1504 if (pcap_stats(pd, &stat) < 0) {
1505 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1506 infoprint = 0;
1507 return;
1510 if (!verbose)
1511 fprintf(stderr, "%s: ", program_name);
1513 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1514 PLURAL_SUFFIX(packets_captured));
1515 if (!verbose)
1516 fputs(", ", stderr);
1517 else
1518 putc('\n', stderr);
1519 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1520 PLURAL_SUFFIX(stat.ps_recv));
1521 if (!verbose)
1522 fputs(", ", stderr);
1523 else
1524 putc('\n', stderr);
1525 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1526 PLURAL_SUFFIX(stat.ps_drop));
1527 if (stat.ps_ifdrop != 0) {
1528 if (!verbose)
1529 fputs(", ", stderr);
1530 else
1531 putc('\n', stderr);
1532 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1533 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1534 } else
1535 putc('\n', stderr);
1536 infoprint = 0;
1539 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1540 static void
1541 compress_savefile(const char *filename)
1543 # ifdef HAVE_FORK
1544 if (fork())
1545 # else
1546 if (vfork())
1547 # endif
1548 return;
1550 * Set to lowest priority so that this doesn't disturb the capture
1552 #ifdef NZERO
1553 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1554 #else
1555 setpriority(PRIO_PROCESS, 0, 19);
1556 #endif
1557 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1558 fprintf(stderr,
1559 "compress_savefile:execlp(%s, %s): %s\n",
1560 zflag,
1561 filename,
1562 strerror(errno));
1563 # ifdef HAVE_FORK
1564 exit(1);
1565 # else
1566 _exit(1);
1567 # endif
1569 #else /* HAVE_FORK && HAVE_VFORK */
1570 static void
1571 compress_savefile(const char *filename)
1573 fprintf(stderr,
1574 "compress_savefile failed. Functionality not implemented under your system\n");
1576 #endif /* HAVE_FORK && HAVE_VFORK */
1578 static void
1579 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1581 struct dump_info *dump_info;
1583 ++packets_captured;
1585 ++infodelay;
1587 dump_info = (struct dump_info *)user;
1590 * XXX - this won't force the file to rotate on the specified time
1591 * boundary, but it will rotate on the first packet received after the
1592 * specified Gflag number of seconds. Note: if a Gflag time boundary
1593 * and a Cflag size boundary coincide, the time rotation will occur
1594 * first thereby cancelling the Cflag boundary (since the file should
1595 * be 0).
1597 if (Gflag != 0) {
1598 /* Check if it is time to rotate */
1599 time_t t;
1601 /* Get the current time */
1602 if ((t = time(NULL)) == (time_t)-1) {
1603 error("dump_and_trunc_packet: can't get current_time: %s",
1604 pcap_strerror(errno));
1608 /* If the time is greater than the specified window, rotate */
1609 if (t - Gflag_time >= Gflag) {
1610 /* Update the Gflag_time */
1611 Gflag_time = t;
1612 /* Update Gflag_count */
1613 Gflag_count++;
1615 * Close the current file and open a new one.
1617 pcap_dump_close(dump_info->p);
1620 * Compress the file we just closed, if the user asked for it
1622 if (zflag != NULL)
1623 compress_savefile(dump_info->CurrentFileName);
1626 * Check to see if we've exceeded the Wflag (when
1627 * not using Cflag).
1629 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1630 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1631 Wflag);
1632 exit(0);
1633 /* NOTREACHED */
1635 if (dump_info->CurrentFileName != NULL)
1636 free(dump_info->CurrentFileName);
1637 /* Allocate space for max filename + \0. */
1638 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1639 if (dump_info->CurrentFileName == NULL)
1640 error("dump_packet_and_trunc: malloc");
1642 * This is always the first file in the Cflag
1643 * rotation: e.g. 0
1644 * We also don't need numbering if Cflag is not set.
1646 if (Cflag != 0)
1647 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1648 WflagChars);
1649 else
1650 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1652 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1653 if (dump_info->p == NULL)
1654 error("%s", pcap_geterr(pd));
1659 * XXX - this won't prevent capture files from getting
1660 * larger than Cflag - the last packet written to the
1661 * file could put it over Cflag.
1663 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1665 * Close the current file and open a new one.
1667 pcap_dump_close(dump_info->p);
1670 * Compress the file we just closed, if the user asked for it
1672 if (zflag != NULL)
1673 compress_savefile(dump_info->CurrentFileName);
1675 Cflag_count++;
1676 if (Wflag > 0) {
1677 if (Cflag_count >= Wflag)
1678 Cflag_count = 0;
1680 if (dump_info->CurrentFileName != NULL)
1681 free(dump_info->CurrentFileName);
1682 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1683 if (dump_info->CurrentFileName == NULL)
1684 error("dump_packet_and_trunc: malloc");
1685 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1686 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1687 if (dump_info->p == NULL)
1688 error("%s", pcap_geterr(pd));
1691 pcap_dump((u_char *)dump_info->p, h, sp);
1692 #ifdef HAVE_PCAP_DUMP_FLUSH
1693 if (Uflag)
1694 pcap_dump_flush(dump_info->p);
1695 #endif
1697 --infodelay;
1698 if (infoprint)
1699 info(0);
1702 static void
1703 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1705 ++packets_captured;
1707 ++infodelay;
1709 pcap_dump(user, h, sp);
1710 #ifdef HAVE_PCAP_DUMP_FLUSH
1711 if (Uflag)
1712 pcap_dump_flush((pcap_dumper_t *)user);
1713 #endif
1715 --infodelay;
1716 if (infoprint)
1717 info(0);
1720 static void
1721 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1723 struct print_info *print_info;
1724 u_int hdrlen;
1726 ++packets_captured;
1728 ++infodelay;
1729 ts_print(&h->ts);
1731 print_info = (struct print_info *)user;
1734 * Some printers want to check that they're not walking off the
1735 * end of the packet.
1736 * Rather than pass it all the way down, we set this global.
1738 snapend = sp + h->caplen;
1740 if(print_info->ndo_type) {
1741 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
1742 } else {
1743 hdrlen = (*print_info->p.printer)(h, sp);
1746 if (Xflag) {
1748 * Print the raw packet data in hex and ASCII.
1750 if (Xflag > 1) {
1752 * Include the link-layer header.
1754 hex_and_ascii_print("\n\t", sp, h->caplen);
1755 } else {
1757 * Don't include the link-layer header - and if
1758 * we have nothing past the link-layer header,
1759 * print nothing.
1761 if (h->caplen > hdrlen)
1762 hex_and_ascii_print("\n\t", sp + hdrlen,
1763 h->caplen - hdrlen);
1765 } else if (xflag) {
1767 * Print the raw packet data in hex.
1769 if (xflag > 1) {
1771 * Include the link-layer header.
1773 hex_print("\n\t", sp, h->caplen);
1774 } else {
1776 * Don't include the link-layer header - and if
1777 * we have nothing past the link-layer header,
1778 * print nothing.
1780 if (h->caplen > hdrlen)
1781 hex_print("\n\t", sp + hdrlen,
1782 h->caplen - hdrlen);
1784 } else if (Aflag) {
1786 * Print the raw packet data in ASCII.
1788 if (Aflag > 1) {
1790 * Include the link-layer header.
1792 ascii_print(sp, h->caplen);
1793 } else {
1795 * Don't include the link-layer header - and if
1796 * we have nothing past the link-layer header,
1797 * print nothing.
1799 if (h->caplen > hdrlen)
1800 ascii_print(sp + hdrlen, h->caplen - hdrlen);
1804 putchar('\n');
1806 --infodelay;
1807 if (infoprint)
1808 info(0);
1811 #ifdef WIN32
1813 * XXX - there should really be libpcap calls to get the version
1814 * number as a string (the string would be generated from #defines
1815 * at run time, so that it's not generated from string constants
1816 * in the library, as, on many UNIX systems, those constants would
1817 * be statically linked into the application executable image, and
1818 * would thus reflect the version of libpcap on the system on
1819 * which the application was *linked*, not the system on which it's
1820 * *running*.
1822 * That routine should be documented, unlike the "version[]"
1823 * string, so that UNIX vendors providing their own libpcaps
1824 * don't omit it (as a couple of vendors have...).
1826 * Packet.dll should perhaps also export a routine to return the
1827 * version number of the Packet.dll code, to supply the
1828 * "Wpcap_version" information on Windows.
1830 char WDversion[]="current-cvs.tcpdump.org";
1831 #if !defined(HAVE_GENERATED_VERSION)
1832 char version[]="current-cvs.tcpdump.org";
1833 #endif
1834 char pcap_version[]="current-cvs.tcpdump.org";
1835 char Wpcap_version[]="3.1";
1836 #endif
1839 * By default, print the specified data out in hex and ASCII.
1841 static void
1842 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1844 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1847 void
1848 default_print(const u_char *bp, u_int length)
1850 ndo_default_print(gndo, bp, length);
1853 #ifdef SIGNAL_REQ_INFO
1854 RETSIGTYPE requestinfo(int signo _U_)
1856 if (infodelay)
1857 ++infoprint;
1858 else
1859 info(0);
1861 #endif
1864 * Called once each second in verbose mode while dumping to file
1866 #ifdef USE_WIN32_MM_TIMER
1867 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1868 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1870 struct pcap_stat stat;
1872 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1873 fprintf(stderr, "Got %u\r", packets_captured);
1875 #elif defined(HAVE_ALARM)
1876 static void verbose_stats_dump(int sig _U_)
1878 struct pcap_stat stat;
1880 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1881 fprintf(stderr, "Got %u\r", packets_captured);
1882 alarm(1);
1884 #endif
1886 static void
1887 usage(void)
1889 extern char version[];
1890 #ifndef HAVE_PCAP_LIB_VERSION
1891 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1892 extern char pcap_version[];
1893 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1894 static char pcap_version[] = "unknown";
1895 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1896 #endif /* HAVE_PCAP_LIB_VERSION */
1898 #ifdef HAVE_PCAP_LIB_VERSION
1899 #ifdef WIN32
1900 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1901 #else /* WIN32 */
1902 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1903 #endif /* WIN32 */
1904 (void)fprintf(stderr, "%s\n",pcap_lib_version());
1905 #else /* HAVE_PCAP_LIB_VERSION */
1906 #ifdef WIN32
1907 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1908 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1909 #else /* WIN32 */
1910 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1911 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1912 #endif /* WIN32 */
1913 #endif /* HAVE_PCAP_LIB_VERSION */
1914 (void)fprintf(stderr,
1915 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
1916 (void)fprintf(stderr,
1917 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
1918 (void)fprintf(stderr,
1919 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
1920 (void)fprintf(stderr,
1921 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]\n");
1922 (void)fprintf(stderr,
1923 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
1924 (void)fprintf(stderr,
1925 "\t\t[ -Z user ] [ expression ]\n");
1926 exit(1);
1931 /* VARARGS */
1932 static void
1933 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1935 va_list ap;
1937 (void)fprintf(stderr, "%s: ", program_name);
1938 va_start(ap, fmt);
1939 (void)vfprintf(stderr, fmt, ap);
1940 va_end(ap);
1941 if (*fmt) {
1942 fmt += strlen(fmt);
1943 if (fmt[-1] != '\n')
1944 (void)fputc('\n', stderr);
1946 exit(1);
1947 /* NOTREACHED */
1950 /* VARARGS */
1951 static void
1952 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
1954 va_list ap;
1956 (void)fprintf(stderr, "%s: WARNING: ", program_name);
1957 va_start(ap, fmt);
1958 (void)vfprintf(stderr, fmt, ap);
1959 va_end(ap);
1960 if (*fmt) {
1961 fmt += strlen(fmt);
1962 if (fmt[-1] != '\n')
1963 (void)fputc('\n', stderr);