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