]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
Fix the pointer tests in the non-ndoified TTEST2() macro as well.
[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 #endif /* WIN32 */
1248 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1249 (void)setsignal(SIGCHLD, child_cleanup);
1250 #endif
1251 /* Cooperate with nohup(1) */
1252 #ifndef WIN32
1253 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1254 (void)setsignal(SIGHUP, oldhandler);
1255 #endif /* WIN32 */
1256
1257 #ifndef WIN32
1258 /*
1259 * If a user name was specified with "-Z", attempt to switch to
1260 * that user's UID. This would probably be used with sudo,
1261 * to allow tcpdump to be run in a special restricted
1262 * account (if you just want to allow users to open capture
1263 * devices, and can't just give users that permission,
1264 * you'd make tcpdump set-UID or set-GID).
1265 *
1266 * Tcpdump doesn't necessarily write only to one savefile;
1267 * the general only way to allow a -Z instance to write to
1268 * savefiles as the user under whose UID it's run, rather
1269 * than as the user specified with -Z, would thus be to switch
1270 * to the original user ID before opening a capture file and
1271 * then switch back to the -Z user ID after opening the savefile.
1272 * Switching to the -Z user ID only after opening the first
1273 * savefile doesn't handle the general case.
1274 */
1275 if (getuid() == 0 || geteuid() == 0) {
1276 if (username || chroot_dir)
1277 droproot(username, chroot_dir);
1278 }
1279 #endif /* WIN32 */
1280
1281 if (pcap_setfilter(pd, &fcode) < 0)
1282 error("%s", pcap_geterr(pd));
1283 if (WFileName) {
1284 pcap_dumper_t *p;
1285 /* Do not exceed the default NAME_MAX for files. */
1286 dumpinfo.CurrentFileName = (char *)malloc(NAME_MAX + 1);
1287
1288 if (dumpinfo.CurrentFileName == NULL)
1289 error("malloc of dumpinfo.CurrentFileName");
1290
1291 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1292 if (Cflag != 0)
1293 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1294 else
1295 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1296
1297 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1298 if (p == NULL)
1299 error("%s", pcap_geterr(pd));
1300 if (Cflag != 0 || Gflag != 0) {
1301 callback = dump_packet_and_trunc;
1302 dumpinfo.WFileName = WFileName;
1303 dumpinfo.pd = pd;
1304 dumpinfo.p = p;
1305 pcap_userdata = (u_char *)&dumpinfo;
1306 } else {
1307 callback = dump_packet;
1308 pcap_userdata = (u_char *)p;
1309 }
1310 #ifdef HAVE_PCAP_DUMP_FLUSH
1311 if (Uflag)
1312 pcap_dump_flush(p);
1313 #endif
1314 } else {
1315 type = pcap_datalink(pd);
1316 printinfo.ndo_type = 1;
1317 printinfo.ndo = gndo;
1318 printinfo.p.ndo_printer = lookup_ndo_printer(type);
1319 if (printinfo.p.ndo_printer == NULL) {
1320 printinfo.p.printer = lookup_printer(type);
1321 printinfo.ndo_type = 0;
1322 if (printinfo.p.printer == NULL) {
1323 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
1324 if (gndo->ndo_dltname != NULL)
1325 error("packet printing is not supported for link type %s: use -w",
1326 gndo->ndo_dltname);
1327 else
1328 error("packet printing is not supported for link type %d: use -w", type);
1329 }
1330 }
1331 callback = print_packet;
1332 pcap_userdata = (u_char *)&printinfo;
1333 }
1334
1335 #ifdef SIGINFO
1336 /*
1337 * We can't get statistics when reading from a file rather
1338 * than capturing from a device.
1339 */
1340 if (RFileName == NULL)
1341 (void)setsignal(SIGINFO, requestinfo);
1342 #endif
1343
1344 if (vflag > 0 && WFileName) {
1345 /*
1346 * When capturing to a file, "-v" means tcpdump should,
1347 * every 10 secodns, "v"erbosely report the number of
1348 * packets captured.
1349 */
1350 #ifdef USE_WIN32_MM_TIMER
1351 /* call verbose_stats_dump() each 1000 +/-100msec */
1352 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1353 setvbuf(stderr, NULL, _IONBF, 0);
1354 #elif defined(HAVE_ALARM)
1355 (void)setsignal(SIGALRM, verbose_stats_dump);
1356 alarm(1);
1357 #endif
1358 }
1359
1360 #ifndef WIN32
1361 if (RFileName == NULL) {
1362 int dlt;
1363 const char *dlt_name;
1364
1365 if (!vflag && !WFileName) {
1366 (void)fprintf(stderr,
1367 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1368 program_name);
1369 } else
1370 (void)fprintf(stderr, "%s: ", program_name);
1371 dlt = pcap_datalink(pd);
1372 dlt_name = pcap_datalink_val_to_name(dlt);
1373 if (dlt_name == NULL) {
1374 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1375 device, dlt, snaplen);
1376 } else {
1377 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1378 device, dlt_name,
1379 pcap_datalink_val_to_description(dlt), snaplen);
1380 }
1381 (void)fflush(stderr);
1382 }
1383 #endif /* WIN32 */
1384 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1385 if (WFileName == NULL) {
1386 /*
1387 * We're printing packets. Flush the printed output,
1388 * so it doesn't get intermingled with error output.
1389 */
1390 if (status == -2) {
1391 /*
1392 * We got interrupted, so perhaps we didn't
1393 * manage to finish a line we were printing.
1394 * Print an extra newline, just in case.
1395 */
1396 putchar('\n');
1397 }
1398 (void)fflush(stdout);
1399 }
1400 if (status == -1) {
1401 /*
1402 * Error. Report it.
1403 */
1404 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1405 program_name, pcap_geterr(pd));
1406 }
1407 if (RFileName == NULL) {
1408 /*
1409 * We're doing a live capture. Report the capture
1410 * statistics.
1411 */
1412 info(1);
1413 }
1414 pcap_close(pd);
1415 exit(status == -1 ? 1 : 0);
1416 }
1417
1418 /* make a clean exit on interrupts */
1419 static RETSIGTYPE
1420 cleanup(int signo _U_)
1421 {
1422 #ifdef USE_WIN32_MM_TIMER
1423 if (timer_id)
1424 timeKillEvent(timer_id);
1425 timer_id = 0;
1426 #elif defined(HAVE_ALARM)
1427 alarm(0);
1428 #endif
1429
1430 #ifdef HAVE_PCAP_BREAKLOOP
1431 /*
1432 * We have "pcap_breakloop()"; use it, so that we do as little
1433 * as possible in the signal handler (it's probably not safe
1434 * to do anything with standard I/O streams in a signal handler -
1435 * the ANSI C standard doesn't say it is).
1436 */
1437 pcap_breakloop(pd);
1438 #else
1439 /*
1440 * We don't have "pcap_breakloop()"; this isn't safe, but
1441 * it's the best we can do. Print the summary if we're
1442 * not reading from a savefile - i.e., if we're doing a
1443 * live capture - and exit.
1444 */
1445 if (pd != NULL && pcap_file(pd) == NULL) {
1446 /*
1447 * We got interrupted, so perhaps we didn't
1448 * manage to finish a line we were printing.
1449 * Print an extra newline, just in case.
1450 */
1451 putchar('\n');
1452 (void)fflush(stdout);
1453 info(1);
1454 }
1455 exit(0);
1456 #endif
1457 }
1458
1459 /*
1460 On windows, we do not use a fork, so we do not care less about
1461 waiting a child processes to die
1462 */
1463 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1464 static RETSIGTYPE
1465 child_cleanup(int signo _U_)
1466 {
1467 wait(NULL);
1468 }
1469 #endif /* HAVE_FORK && HAVE_VFORK */
1470
1471 static void
1472 info(register int verbose)
1473 {
1474 struct pcap_stat stat;
1475
1476 /*
1477 * Older versions of libpcap didn't set ps_ifdrop on some
1478 * platforms; initialize it to 0 to handle that.
1479 */
1480 stat.ps_ifdrop = 0;
1481 if (pcap_stats(pd, &stat) < 0) {
1482 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1483 infoprint = 0;
1484 return;
1485 }
1486
1487 if (!verbose)
1488 fprintf(stderr, "%s: ", program_name);
1489
1490 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1491 PLURAL_SUFFIX(packets_captured));
1492 if (!verbose)
1493 fputs(", ", stderr);
1494 else
1495 putc('\n', stderr);
1496 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1497 PLURAL_SUFFIX(stat.ps_recv));
1498 if (!verbose)
1499 fputs(", ", stderr);
1500 else
1501 putc('\n', stderr);
1502 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1503 PLURAL_SUFFIX(stat.ps_drop));
1504 if (stat.ps_ifdrop != 0) {
1505 if (!verbose)
1506 fputs(", ", stderr);
1507 else
1508 putc('\n', stderr);
1509 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1510 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1511 } else
1512 putc('\n', stderr);
1513 infoprint = 0;
1514 }
1515
1516 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1517 static void
1518 compress_savefile(const char *filename)
1519 {
1520 # ifdef HAVE_FORK
1521 if (fork())
1522 # else
1523 if (vfork())
1524 # endif
1525 return;
1526 /*
1527 * Set to lowest priority so that this doesn't disturb the capture
1528 */
1529 #ifdef NZERO
1530 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1531 #else
1532 setpriority(PRIO_PROCESS, 0, 19);
1533 #endif
1534 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1535 fprintf(stderr,
1536 "compress_savefile:execlp(%s, %s): %s\n",
1537 zflag,
1538 filename,
1539 strerror(errno));
1540 # ifdef HAVE_FORK
1541 exit(1);
1542 # else
1543 _exit(1);
1544 # endif
1545 }
1546 #else /* HAVE_FORK && HAVE_VFORK */
1547 static void
1548 compress_savefile(const char *filename)
1549 {
1550 fprintf(stderr,
1551 "compress_savefile failed. Functionality not implemented under your system\n");
1552 }
1553 #endif /* HAVE_FORK && HAVE_VFORK */
1554
1555 static void
1556 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1557 {
1558 struct dump_info *dump_info;
1559
1560 ++packets_captured;
1561
1562 ++infodelay;
1563
1564 dump_info = (struct dump_info *)user;
1565
1566 /*
1567 * XXX - this won't force the file to rotate on the specified time
1568 * boundary, but it will rotate on the first packet received after the
1569 * specified Gflag number of seconds. Note: if a Gflag time boundary
1570 * and a Cflag size boundary coincide, the time rotation will occur
1571 * first thereby cancelling the Cflag boundary (since the file should
1572 * be 0).
1573 */
1574 if (Gflag != 0) {
1575 /* Check if it is time to rotate */
1576 time_t t;
1577
1578 /* Get the current time */
1579 if ((t = time(NULL)) == (time_t)-1) {
1580 error("dump_and_trunc_packet: can't get current_time: %s",
1581 pcap_strerror(errno));
1582 }
1583
1584
1585 /* If the time is greater than the specified window, rotate */
1586 if (t - Gflag_time >= Gflag) {
1587 /* Update the Gflag_time */
1588 Gflag_time = t;
1589 /* Update Gflag_count */
1590 Gflag_count++;
1591 /*
1592 * Close the current file and open a new one.
1593 */
1594 pcap_dump_close(dump_info->p);
1595
1596 /*
1597 * Compress the file we just closed, if the user asked for it
1598 */
1599 if (zflag != NULL)
1600 compress_savefile(dump_info->CurrentFileName);
1601
1602 /*
1603 * Check to see if we've exceeded the Wflag (when
1604 * not using Cflag).
1605 */
1606 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1607 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1608 Wflag);
1609 exit(0);
1610 /* NOTREACHED */
1611 }
1612 if (dump_info->CurrentFileName != NULL)
1613 free(dump_info->CurrentFileName);
1614 /* Allocate space for max filename + \0. */
1615 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1616 if (dump_info->CurrentFileName == NULL)
1617 error("dump_packet_and_trunc: malloc");
1618 /*
1619 * This is always the first file in the Cflag
1620 * rotation: e.g. 0
1621 * We also don't need numbering if Cflag is not set.
1622 */
1623 if (Cflag != 0)
1624 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1625 WflagChars);
1626 else
1627 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1628
1629 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1630 if (dump_info->p == NULL)
1631 error("%s", pcap_geterr(pd));
1632 }
1633 }
1634
1635 /*
1636 * XXX - this won't prevent capture files from getting
1637 * larger than Cflag - the last packet written to the
1638 * file could put it over Cflag.
1639 */
1640 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1641 /*
1642 * Close the current file and open a new one.
1643 */
1644 pcap_dump_close(dump_info->p);
1645
1646 /*
1647 * Compress the file we just closed, if the user asked for it
1648 */
1649 if (zflag != NULL)
1650 compress_savefile(dump_info->CurrentFileName);
1651
1652 Cflag_count++;
1653 if (Wflag > 0) {
1654 if (Cflag_count >= Wflag)
1655 Cflag_count = 0;
1656 }
1657 if (dump_info->CurrentFileName != NULL)
1658 free(dump_info->CurrentFileName);
1659 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1660 if (dump_info->CurrentFileName == NULL)
1661 error("dump_packet_and_trunc: malloc");
1662 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1663 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1664 if (dump_info->p == NULL)
1665 error("%s", pcap_geterr(pd));
1666 }
1667
1668 pcap_dump((u_char *)dump_info->p, h, sp);
1669 #ifdef HAVE_PCAP_DUMP_FLUSH
1670 if (Uflag)
1671 pcap_dump_flush(dump_info->p);
1672 #endif
1673
1674 --infodelay;
1675 if (infoprint)
1676 info(0);
1677 }
1678
1679 static void
1680 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1681 {
1682 ++packets_captured;
1683
1684 ++infodelay;
1685
1686 pcap_dump(user, h, sp);
1687 #ifdef HAVE_PCAP_DUMP_FLUSH
1688 if (Uflag)
1689 pcap_dump_flush((pcap_dumper_t *)user);
1690 #endif
1691
1692 --infodelay;
1693 if (infoprint)
1694 info(0);
1695 }
1696
1697 static void
1698 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1699 {
1700 struct print_info *print_info;
1701 u_int hdrlen;
1702
1703 ++packets_captured;
1704
1705 ++infodelay;
1706 ts_print(&h->ts);
1707
1708 print_info = (struct print_info *)user;
1709
1710 /*
1711 * Some printers want to check that they're not walking off the
1712 * end of the packet.
1713 * Rather than pass it all the way down, we set this global.
1714 */
1715 snapend = sp + h->caplen;
1716
1717 if(print_info->ndo_type) {
1718 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
1719 } else {
1720 hdrlen = (*print_info->p.printer)(h, sp);
1721 }
1722
1723 /*
1724 * Restore the original snapend, as a printer might have
1725 * changed it.
1726 */
1727 snapend = sp + h->caplen;
1728 if (Xflag) {
1729 /*
1730 * Print the raw packet data in hex and ASCII.
1731 */
1732 if (Xflag > 1) {
1733 /*
1734 * Include the link-layer header.
1735 */
1736 hex_and_ascii_print("\n\t", sp, h->caplen);
1737 } else {
1738 /*
1739 * Don't include the link-layer header - and if
1740 * we have nothing past the link-layer header,
1741 * print nothing.
1742 */
1743 if (h->caplen > hdrlen)
1744 hex_and_ascii_print("\n\t", sp + hdrlen,
1745 h->caplen - hdrlen);
1746 }
1747 } else if (xflag) {
1748 /*
1749 * Print the raw packet data in hex.
1750 */
1751 if (xflag > 1) {
1752 /*
1753 * Include the link-layer header.
1754 */
1755 hex_print("\n\t", sp, h->caplen);
1756 } else {
1757 /*
1758 * Don't include the link-layer header - and if
1759 * we have nothing past the link-layer header,
1760 * print nothing.
1761 */
1762 if (h->caplen > hdrlen)
1763 hex_print("\n\t", sp + hdrlen,
1764 h->caplen - hdrlen);
1765 }
1766 } else if (Aflag) {
1767 /*
1768 * Print the raw packet data in ASCII.
1769 */
1770 if (Aflag > 1) {
1771 /*
1772 * Include the link-layer header.
1773 */
1774 ascii_print(sp, h->caplen);
1775 } else {
1776 /*
1777 * Don't include the link-layer header - and if
1778 * we have nothing past the link-layer header,
1779 * print nothing.
1780 */
1781 if (h->caplen > hdrlen)
1782 ascii_print(sp + hdrlen, h->caplen - hdrlen);
1783 }
1784 }
1785
1786 putchar('\n');
1787
1788 --infodelay;
1789 if (infoprint)
1790 info(0);
1791 }
1792
1793 #ifdef WIN32
1794 /*
1795 * XXX - there should really be libpcap calls to get the version
1796 * number as a string (the string would be generated from #defines
1797 * at run time, so that it's not generated from string constants
1798 * in the library, as, on many UNIX systems, those constants would
1799 * be statically linked into the application executable image, and
1800 * would thus reflect the version of libpcap on the system on
1801 * which the application was *linked*, not the system on which it's
1802 * *running*.
1803 *
1804 * That routine should be documented, unlike the "version[]"
1805 * string, so that UNIX vendors providing their own libpcaps
1806 * don't omit it (as a couple of vendors have...).
1807 *
1808 * Packet.dll should perhaps also export a routine to return the
1809 * version number of the Packet.dll code, to supply the
1810 * "Wpcap_version" information on Windows.
1811 */
1812 char WDversion[]="current-cvs.tcpdump.org";
1813 #if !defined(HAVE_GENERATED_VERSION)
1814 char version[]="current-cvs.tcpdump.org";
1815 #endif
1816 char pcap_version[]="current-cvs.tcpdump.org";
1817 char Wpcap_version[]="3.1";
1818 #endif
1819
1820 /*
1821 * By default, print the specified data out in hex and ASCII.
1822 */
1823 static void
1824 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1825 {
1826 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1827 }
1828
1829 void
1830 default_print(const u_char *bp, u_int length)
1831 {
1832 ndo_default_print(gndo, bp, length);
1833 }
1834
1835 #ifdef SIGINFO
1836 RETSIGTYPE requestinfo(int signo _U_)
1837 {
1838 if (infodelay)
1839 ++infoprint;
1840 else
1841 info(0);
1842 }
1843 #endif
1844
1845 /*
1846 * Called once each second in verbose mode while dumping to file
1847 */
1848 #ifdef USE_WIN32_MM_TIMER
1849 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1850 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1851 {
1852 struct pcap_stat stat;
1853
1854 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1855 fprintf(stderr, "Got %u\r", packets_captured);
1856 }
1857 #elif defined(HAVE_ALARM)
1858 static void verbose_stats_dump(int sig _U_)
1859 {
1860 struct pcap_stat stat;
1861
1862 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1863 fprintf(stderr, "Got %u\r", packets_captured);
1864 alarm(1);
1865 }
1866 #endif
1867
1868 static void
1869 usage(void)
1870 {
1871 extern char version[];
1872 #ifndef HAVE_PCAP_LIB_VERSION
1873 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1874 extern char pcap_version[];
1875 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1876 static char pcap_version[] = "unknown";
1877 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1878 #endif /* HAVE_PCAP_LIB_VERSION */
1879
1880 #ifdef HAVE_PCAP_LIB_VERSION
1881 #ifdef WIN32
1882 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1883 #else /* WIN32 */
1884 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1885 #endif /* WIN32 */
1886 (void)fprintf(stderr, "%s\n",pcap_lib_version());
1887 #else /* HAVE_PCAP_LIB_VERSION */
1888 #ifdef WIN32
1889 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1890 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1891 #else /* WIN32 */
1892 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1893 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1894 #endif /* WIN32 */
1895 #endif /* HAVE_PCAP_LIB_VERSION */
1896 (void)fprintf(stderr,
1897 "Usage: %s [-aAbd" D_FLAG "efh" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
1898 (void)fprintf(stderr,
1899 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
1900 (void)fprintf(stderr,
1901 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
1902 (void)fprintf(stderr,
1903 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]\n");
1904 (void)fprintf(stderr,
1905 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
1906 (void)fprintf(stderr,
1907 "\t\t[ -Z user ] [ expression ]\n");
1908 exit(1);
1909 }
1910
1911
1912
1913 /* VARARGS */
1914 static void
1915 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1916 {
1917 va_list ap;
1918
1919 (void)fprintf(stderr, "%s: ", program_name);
1920 va_start(ap, fmt);
1921 (void)vfprintf(stderr, fmt, ap);
1922 va_end(ap);
1923 if (*fmt) {
1924 fmt += strlen(fmt);
1925 if (fmt[-1] != '\n')
1926 (void)fputc('\n', stderr);
1927 }
1928 exit(1);
1929 /* NOTREACHED */
1930 }
1931
1932 /* VARARGS */
1933 static void
1934 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
1935 {
1936 va_list ap;
1937
1938 (void)fprintf(stderr, "%s: WARNING: ", program_name);
1939 va_start(ap, fmt);
1940 (void)vfprintf(stderr, fmt, ap);
1941 va_end(ap);
1942 if (*fmt) {
1943 fmt += strlen(fmt);
1944 if (fmt[-1] != '\n')
1945 (void)fputc('\n', stderr);
1946 }
1947 }