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