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