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