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