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