]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/tcpdump/tcpdump.c
MFV r304060:
[FreeBSD/FreeBSD.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 #endif
33
34 /* $FreeBSD$ */
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 /*
49  * Mac OS X may ship pcap.h from libpcap 0.6 with a libpcap based on
50  * 0.8.  That means it has pcap_findalldevs() but the header doesn't
51  * define pcap_if_t, meaning that we can't actually *use* pcap_findalldevs().
52  */
53 #ifdef HAVE_PCAP_FINDALLDEVS
54 #ifndef HAVE_PCAP_IF_T
55 #undef HAVE_PCAP_FINDALLDEVS
56 #endif
57 #endif
58
59 #include <tcpdump-stdinc.h>
60
61 #ifdef WIN32
62 #include "w32_fzs.h"
63 extern int strcasecmp (const char *__s1, const char *__s2);
64 extern int SIZE_BUF;
65 #define off_t long
66 #define uint UINT
67 #endif /* WIN32 */
68
69 #ifdef USE_LIBSMI
70 #include <smi.h>
71 #endif
72
73 #ifdef HAVE_LIBCRYPTO
74 #include <openssl/crypto.h>
75 #endif
76
77 #ifdef HAVE_GETOPT_LONG
78 #include <getopt.h>
79 #else
80 #include "getopt_long.h"
81 #endif
82 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
83  * to compile if <pcap.h> has already been included; including the headers
84  * in the opposite order works fine.
85  */
86 #ifdef __FreeBSD__
87 #include <sys/capsicum.h>
88 #include <sys/sysctl.h>
89 #include <libgen.h>
90 #endif /* __FreeBSD__ */
91 #ifdef HAVE_CASPER
92 #include <libcasper.h>
93 #include <casper/cap_dns.h>
94 #include <sys/nv.h>
95 #include <sys/capability.h>
96 #include <sys/ioccom.h>
97 #include <net/bpf.h>
98 #include <fcntl.h>
99 #endif  /* HAVE_CASPER */
100 #include <pcap.h>
101 #include <signal.h>
102 #include <stdio.h>
103 #include <stdlib.h>
104 #include <string.h>
105 #include <limits.h>
106 #ifndef WIN32
107 #include <sys/wait.h>
108 #include <sys/resource.h>
109 #include <pwd.h>
110 #include <grp.h>
111 #endif /* WIN32 */
112
113 /* capabilities convenience library */
114 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
115  * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
116  * Thus, the later tests are done only on HAVE_LIBCAP_NG.
117  */
118 #ifdef HAVE_LIBCAP_NG
119 #ifdef HAVE_CAP_NG_H
120 #include <cap-ng.h>
121 #else
122 #undef HAVE_LIBCAP_NG
123 #endif /* HAVE_CAP_NG_H */
124 #endif /* HAVE_LIBCAP_NG */
125
126 #include "netdissect.h"
127 #include "interface.h"
128 #include "addrtoname.h"
129 #include "machdep.h"
130 #include "setsignal.h"
131 #include "gmt2local.h"
132 #include "pcap-missing.h"
133
134 #ifndef PATH_MAX
135 #define PATH_MAX 1024
136 #endif
137
138 #ifdef SIGINFO
139 #define SIGNAL_REQ_INFO SIGINFO
140 #elif SIGUSR1
141 #define SIGNAL_REQ_INFO SIGUSR1
142 #endif
143
144 netdissect_options Gndo;
145 netdissect_options *gndo = &Gndo;
146
147 static int Dflag;                       /* list available devices and exit */
148 static int dflag;                       /* print filter code */
149 static int Lflag;                       /* list available data link types and exit */
150 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
151 static int Jflag;                       /* list available time stamp types */
152 #endif
153 #ifdef HAVE_PCAP_SETDIRECTION
154 int Qflag = -1;                         /* restrict captured packet by send/receive direction */
155 #endif
156 static char *zflag = NULL;              /* compress each savefile using a specified command (like gzip or bzip2) */
157
158 static int infodelay;
159 static int infoprint;
160
161 char *program_name;
162
163 #ifdef HAVE_CASPER
164 cap_channel_t *capdns;
165 #endif
166
167 int32_t thiszone;               /* seconds offset from gmt to local time */
168
169 /* Forwards */
170 static RETSIGTYPE cleanup(int);
171 static RETSIGTYPE child_cleanup(int);
172 static void print_version(void);
173 static void print_usage(void);
174 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
175
176 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
177 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
178 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
179 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
180 static void droproot(const char *, const char *);
181 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
182      __attribute__((noreturn))
183 #ifdef __ATTRIBUTE___FORMAT_OK
184      __attribute__((format (printf, 2, 3)))
185 #endif /* __ATTRIBUTE___FORMAT_OK */
186     ;
187 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...)
188 #ifdef __ATTRIBUTE___FORMAT_OK
189      __attribute__((format (printf, 2, 3)))
190 #endif /* __ATTRIBUTE___FORMAT_OK */
191     ;
192
193 #ifdef SIGNAL_REQ_INFO
194 RETSIGTYPE requestinfo(int);
195 #endif
196
197 #if defined(USE_WIN32_MM_TIMER)
198   #include <MMsystem.h>
199   static UINT timer_id;
200   static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
201 #elif defined(HAVE_ALARM)
202   static void verbose_stats_dump(int sig);
203 #endif
204
205 static void info(int);
206 static u_int packets_captured;
207
208 struct printer {
209         if_printer f;
210         int type;
211 };
212
213
214 struct ndo_printer {
215         if_ndo_printer f;
216         int type;
217 };
218
219
220 static const struct printer printers[] = {
221         { NULL,                 0 },
222 };
223
224 static const struct ndo_printer ndo_printers[] = {
225         { ether_if_print,       DLT_EN10MB },
226 #ifdef DLT_IPNET
227         { ipnet_if_print,       DLT_IPNET },
228 #endif
229 #ifdef DLT_IEEE802_15_4
230         { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
231 #endif
232 #ifdef DLT_IEEE802_15_4_NOFCS
233         { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
234 #endif
235 #ifdef DLT_PPI
236         { ppi_if_print,         DLT_PPI },
237 #endif
238 #ifdef DLT_NETANALYZER
239         { netanalyzer_if_print, DLT_NETANALYZER },
240 #endif
241 #ifdef DLT_NETANALYZER_TRANSPARENT
242         { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
243 #endif
244 #if defined(DLT_NFLOG) && defined(HAVE_PCAP_NFLOG_H)
245         { nflog_if_print,       DLT_NFLOG},
246 #endif
247 #ifdef DLT_CIP
248         { cip_if_print,         DLT_CIP },
249 #endif
250 #ifdef DLT_ATM_CLIP
251         { cip_if_print,         DLT_ATM_CLIP },
252 #endif
253 #ifdef DLT_IP_OVER_FC
254         { ipfc_if_print,        DLT_IP_OVER_FC },
255 #endif
256         { null_if_print,        DLT_NULL },
257 #ifdef DLT_LOOP
258         { null_if_print,        DLT_LOOP },
259 #endif
260 #ifdef DLT_APPLE_IP_OVER_IEEE1394
261         { ap1394_if_print,      DLT_APPLE_IP_OVER_IEEE1394 },
262 #endif
263 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
264         { bt_if_print,          DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
265 #endif
266 #ifdef DLT_LANE8023
267         { lane_if_print,        DLT_LANE8023 },
268 #endif
269         { arcnet_if_print,      DLT_ARCNET },
270 #ifdef DLT_ARCNET_LINUX
271         { arcnet_linux_if_print, DLT_ARCNET_LINUX },
272 #endif
273         { raw_if_print,         DLT_RAW },
274 #ifdef DLT_IPV4
275         { raw_if_print,         DLT_IPV4 },
276 #endif
277 #ifdef DLT_IPV6
278         { raw_if_print,         DLT_IPV6 },
279 #endif
280 #ifdef HAVE_PCAP_USB_H
281 #ifdef DLT_USB_LINUX
282         { usb_linux_48_byte_print, DLT_USB_LINUX},
283 #endif /* DLT_USB_LINUX */
284 #ifdef DLT_USB_LINUX_MMAPPED
285         { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
286 #endif /* DLT_USB_LINUX_MMAPPED */
287 #endif /* HAVE_PCAP_USB_H */
288 #ifdef DLT_SYMANTEC_FIREWALL
289         { symantec_if_print,    DLT_SYMANTEC_FIREWALL },
290 #endif
291 #ifdef DLT_C_HDLC
292         { chdlc_if_print,       DLT_C_HDLC },
293 #endif
294 #ifdef DLT_HDLC
295         { chdlc_if_print,       DLT_HDLC },
296 #endif
297 #ifdef DLT_PPP_ETHER
298         { pppoe_if_print,       DLT_PPP_ETHER },
299 #endif
300 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
301         { pflog_if_print,       DLT_PFLOG },
302 #endif
303         { token_if_print,       DLT_IEEE802 },
304         { fddi_if_print,        DLT_FDDI },
305 #ifdef DLT_LINUX_SLL
306         { sll_if_print,         DLT_LINUX_SLL },
307 #endif
308 #ifdef DLT_FR
309         { fr_if_print,          DLT_FR },
310 #endif
311 #ifdef DLT_FRELAY
312         { fr_if_print,          DLT_FRELAY },
313 #endif
314 #ifdef DLT_MFR
315         { mfr_if_print,         DLT_MFR },
316 #endif
317         { atm_if_print,         DLT_ATM_RFC1483 },
318 #ifdef DLT_SUNATM
319         { sunatm_if_print,      DLT_SUNATM },
320 #endif
321 #ifdef DLT_ENC
322         { enc_if_print,         DLT_ENC },
323 #endif
324         { sl_if_print,          DLT_SLIP },
325 #ifdef DLT_SLIP_BSDOS
326         { sl_bsdos_if_print,    DLT_SLIP_BSDOS },
327 #endif
328 #ifdef DLT_LTALK
329         { ltalk_if_print,       DLT_LTALK },
330 #endif
331 #ifdef DLT_JUNIPER_ATM1
332         { juniper_atm1_print,   DLT_JUNIPER_ATM1 },
333 #endif
334 #ifdef DLT_JUNIPER_ATM2
335         { juniper_atm2_print,   DLT_JUNIPER_ATM2 },
336 #endif
337 #ifdef DLT_JUNIPER_MFR
338         { juniper_mfr_print,    DLT_JUNIPER_MFR },
339 #endif
340 #ifdef DLT_JUNIPER_MLFR
341         { juniper_mlfr_print,   DLT_JUNIPER_MLFR },
342 #endif
343 #ifdef DLT_JUNIPER_MLPPP
344         { juniper_mlppp_print,  DLT_JUNIPER_MLPPP },
345 #endif
346 #ifdef DLT_JUNIPER_PPPOE
347         { juniper_pppoe_print,  DLT_JUNIPER_PPPOE },
348 #endif
349 #ifdef DLT_JUNIPER_PPPOE_ATM
350         { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
351 #endif
352 #ifdef DLT_JUNIPER_GGSN
353         { juniper_ggsn_print,   DLT_JUNIPER_GGSN },
354 #endif
355 #ifdef DLT_JUNIPER_ES
356         { juniper_es_print,     DLT_JUNIPER_ES },
357 #endif
358 #ifdef DLT_JUNIPER_MONITOR
359         { juniper_monitor_print, DLT_JUNIPER_MONITOR },
360 #endif
361 #ifdef DLT_JUNIPER_SERVICES
362         { juniper_services_print, DLT_JUNIPER_SERVICES },
363 #endif
364 #ifdef DLT_JUNIPER_ETHER
365         { juniper_ether_print,  DLT_JUNIPER_ETHER },
366 #endif
367 #ifdef DLT_JUNIPER_PPP
368         { juniper_ppp_print,    DLT_JUNIPER_PPP },
369 #endif
370 #ifdef DLT_JUNIPER_FRELAY
371         { juniper_frelay_print, DLT_JUNIPER_FRELAY },
372 #endif
373 #ifdef DLT_JUNIPER_CHDLC
374         { juniper_chdlc_print,  DLT_JUNIPER_CHDLC },
375 #endif
376 #ifdef DLT_PKTAP
377         { pktap_if_print,       DLT_PKTAP },
378 #endif
379 #ifdef DLT_IEEE802_11_RADIO
380         { ieee802_11_radio_if_print,    DLT_IEEE802_11_RADIO },
381 #endif
382 #ifdef DLT_IEEE802_11
383         { ieee802_11_if_print,  DLT_IEEE802_11},
384 #endif
385 #ifdef DLT_IEEE802_11_RADIO_AVS
386         { ieee802_11_radio_avs_if_print,        DLT_IEEE802_11_RADIO_AVS },
387 #endif
388 #ifdef DLT_PRISM_HEADER
389         { prism_if_print,       DLT_PRISM_HEADER },
390 #endif
391         { ppp_if_print,         DLT_PPP },
392 #ifdef DLT_PPP_WITHDIRECTION
393         { ppp_if_print,         DLT_PPP_WITHDIRECTION },
394 #endif
395 #ifdef DLT_PPP_BSDOS
396         { ppp_bsdos_if_print,   DLT_PPP_BSDOS },
397 #endif
398 #ifdef DLT_PPP_SERIAL
399         { ppp_hdlc_if_print,    DLT_PPP_SERIAL },
400 #endif
401         { NULL,                 0 },
402 };
403
404 static const struct tok status_flags[] = {
405 #ifdef PCAP_IF_UP
406         { PCAP_IF_UP,       "Up"       },
407 #endif
408 #ifdef PCAP_IF_RUNNING
409         { PCAP_IF_RUNNING,  "Running"  },
410 #endif
411         { PCAP_IF_LOOPBACK, "Loopback" },
412         { 0, NULL }
413 };
414
415 if_printer
416 lookup_printer(int type)
417 {
418         const struct printer *p;
419
420         for (p = printers; p->f; ++p)
421                 if (type == p->type)
422                         return p->f;
423
424         return NULL;
425         /* NOTREACHED */
426 }
427
428 if_ndo_printer
429 lookup_ndo_printer(int type)
430 {
431         const struct ndo_printer *p;
432
433         for (p = ndo_printers; p->f; ++p)
434                 if (type == p->type)
435                         return p->f;
436
437 #if defined(DLT_USER2) && defined(DLT_PKTAP)
438         /*
439          * Apple incorrectly chose to use DLT_USER2 for their PKTAP
440          * header.
441          *
442          * We map DLT_PKTAP, whether it's DLT_USER2 as it is on Darwin-
443          * based OSes or the same value as LINKTYPE_PKTAP as it is on
444          * other OSes, to LINKTYPE_PKTAP, so files written with
445          * this version of libpcap for a DLT_PKTAP capture have a link-
446          * layer header type of LINKTYPE_PKTAP.
447          *
448          * However, files written on OS X Mavericks for a DLT_PKTAP
449          * capture have a link-layer header type of LINKTYPE_USER2.
450          * If we don't have a printer for DLT_USER2, and type is
451          * DLT_USER2, we look up the printer for DLT_PKTAP and use
452          * that.
453          */
454         if (type == DLT_USER2) {
455                 for (p = ndo_printers; p->f; ++p)
456                         if (DLT_PKTAP == p->type)
457                                 return p->f;
458         }
459 #endif
460
461         return NULL;
462         /* NOTREACHED */
463 }
464
465 static pcap_t *pd;
466
467 static int supports_monitor_mode;
468
469 extern int optind;
470 extern int opterr;
471 extern char *optarg;
472
473 struct print_info {
474         netdissect_options *ndo;
475         union {
476                 if_printer     printer;
477                 if_ndo_printer ndo_printer;
478         } p;
479         int ndo_type;
480 };
481
482 struct dump_info {
483         char    *WFileName;
484         char    *CurrentFileName;
485         pcap_t  *pd;
486         pcap_dumper_t *p;
487 #ifdef __FreeBSD__
488         int     dirfd;
489 #endif
490 };
491
492 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
493 static void
494 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
495 {
496         int n_tstamp_types;
497         int *tstamp_types = 0;
498         const char *tstamp_type_name;
499         int i;
500
501         n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
502         if (n_tstamp_types < 0)
503                 error("%s", pcap_geterr(pd));
504
505         if (n_tstamp_types == 0) {
506                 fprintf(stderr, "Time stamp type cannot be set for %s\n",
507                     device);
508                 exit(0);
509         }
510         fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
511             device);
512         for (i = 0; i < n_tstamp_types; i++) {
513                 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
514                 if (tstamp_type_name != NULL) {
515                         (void) fprintf(stderr, "  %s (%s)\n", tstamp_type_name,
516                             pcap_tstamp_type_val_to_description(tstamp_types[i]));
517                 } else {
518                         (void) fprintf(stderr, "  %d\n", tstamp_types[i]);
519                 }
520         }
521         pcap_free_tstamp_types(tstamp_types);
522         exit(0);
523 }
524 #endif
525
526 static void
527 show_dlts_and_exit(const char *device, pcap_t *pd)
528 {
529         int n_dlts;
530         int *dlts = 0;
531         const char *dlt_name;
532
533         n_dlts = pcap_list_datalinks(pd, &dlts);
534         if (n_dlts < 0)
535                 error("%s", pcap_geterr(pd));
536         else if (n_dlts == 0 || !dlts)
537                 error("No data link types.");
538
539         /*
540          * If the interface is known to support monitor mode, indicate
541          * whether these are the data link types available when not in
542          * monitor mode, if -I wasn't specified, or when in monitor mode,
543          * when -I was specified (the link-layer types available in
544          * monitor mode might be different from the ones available when
545          * not in monitor mode).
546          */
547         if (supports_monitor_mode)
548                 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
549                     device,
550                     Iflag ? "when in monitor mode" : "when not in monitor mode");
551         else
552                 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
553                     device);
554
555         while (--n_dlts >= 0) {
556                 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
557                 if (dlt_name != NULL) {
558                         (void) fprintf(stderr, "  %s (%s)", dlt_name,
559                             pcap_datalink_val_to_description(dlts[n_dlts]));
560
561                         /*
562                          * OK, does tcpdump handle that type?
563                          */
564                         if (lookup_printer(dlts[n_dlts]) == NULL
565                             && lookup_ndo_printer(dlts[n_dlts]) == NULL)
566                                 (void) fprintf(stderr, " (printing not supported)");
567                         fprintf(stderr, "\n");
568                 } else {
569                         (void) fprintf(stderr, "  DLT %d (printing not supported)\n",
570                             dlts[n_dlts]);
571                 }
572         }
573 #ifdef HAVE_PCAP_FREE_DATALINKS
574         pcap_free_datalinks(dlts);
575 #endif
576         exit(0);
577 }
578
579 #ifdef HAVE_PCAP_FINDALLDEVS
580 static void
581 show_devices_and_exit (void)
582 {
583         pcap_if_t *devpointer;
584         char ebuf[PCAP_ERRBUF_SIZE];
585         int i;
586
587         if (pcap_findalldevs(&devpointer, ebuf) < 0)
588                 error("%s", ebuf);
589         else {
590                 for (i = 0; devpointer != NULL; i++) {
591                         printf("%d.%s", i+1, devpointer->name);
592                         if (devpointer->description != NULL)
593                                 printf(" (%s)", devpointer->description);
594                         if (devpointer->flags != 0)
595                                 printf(" [%s]", bittok2str(status_flags, "none", devpointer->flags));
596                         printf("\n");
597                         devpointer = devpointer->next;
598                 }
599         }
600         exit(0);
601 }
602 #endif /* HAVE_PCAP_FINDALLDEVS */
603
604 /*
605  * Short options.
606  *
607  * Note that there we use all letters for short options except for g, k,
608  * o, and P, and those are used by other versions of tcpdump, and we should
609  * only use them for the same purposes that the other versions of tcpdump
610  * use them:
611  *
612  * OS X tcpdump uses -g to force non--v output for IP to be on one
613  * line, making it more "g"repable;
614  *
615  * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
616  * should be printed;
617  *
618  * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
619  * for hosts sending TCP SYN packets;
620  *
621  * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
622  * than pcap files.
623  *
624  * OS X tcpdump also uses -Q to specify expressions that match packet
625  * metadata, including but not limited to the packet direction.
626  * The expression syntax is different from a simple "in|out|inout",
627  * and those expressions aren't accepted by OS X tcpdump, but the
628  * equivalents would be "in" = "dir=in", "out" = "dir=out", and
629  * "inout" = "dir=in or dir=out", and the parser could conceivably
630  * special-case "in", "out", and "inout" as expressions for backwards
631  * compatibility, so all is not (yet) lost.
632  */
633
634 /*
635  * Set up flags that might or might not be supported depending on the
636  * version of libpcap we're using.
637  */
638 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
639 #define B_FLAG          "B:"
640 #define B_FLAG_USAGE    " [ -B size ]"
641 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
642 #define B_FLAG
643 #define B_FLAG_USAGE
644 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
645
646 #ifdef HAVE_PCAP_CREATE
647 #define I_FLAG          "I"
648 #else /* HAVE_PCAP_CREATE */
649 #define I_FLAG
650 #endif /* HAVE_PCAP_CREATE */
651
652 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
653 #define j_FLAG          "j:"
654 #define j_FLAG_USAGE    " [ -j tstamptype ]"
655 #define J_FLAG          "J"
656 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
657 #define j_FLAG
658 #define j_FLAG_USAGE
659 #define J_FLAG
660 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
661
662 #ifdef HAVE_PCAP_FINDALLDEVS
663 #define D_FLAG  "D"
664 #else
665 #define D_FLAG
666 #endif
667
668 #ifdef HAVE_PCAP_DUMP_FLUSH
669 #define U_FLAG  "U"
670 #else
671 #define U_FLAG
672 #endif
673
674 #ifdef HAVE_PCAP_SETDIRECTION
675 #define Q_FLAG "Q:"
676 #else
677 #define Q_FLAG
678 #endif
679
680 #define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:Rs:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#"
681
682 /*
683  * Long options.
684  *
685  * We do not currently have long options corresponding to all short
686  * options; we should probably pick appropriate option names for them.
687  *
688  * However, the short options where the number of times the option is
689  * specified matters, such as -v and -d and -t, should probably not
690  * just map to a long option, as saying
691  *
692  *  tcpdump --verbose --verbose
693  *
694  * doesn't make sense; it should be --verbosity={N} or something such
695  * as that.
696  *
697  * For long options with no corresponding short options, we define values
698  * outside the range of ASCII graphic characters, make that the last
699  * component of the entry for the long option, and have a case for that
700  * option in the switch statement.
701  */
702 #define OPTION_VERSION          128
703 #define OPTION_TSTAMP_PRECISION 129
704 #define OPTION_IMMEDIATE_MODE   130
705
706 static const struct option longopts[] = {
707 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
708         { "buffer-size", required_argument, NULL, 'B' },
709 #endif
710         { "list-interfaces", no_argument, NULL, 'D' },
711         { "help", no_argument, NULL, 'h' },
712         { "interface", required_argument, NULL, 'i' },
713 #ifdef HAVE_PCAP_CREATE
714         { "monitor-mode", no_argument, NULL, 'I' },
715 #endif
716 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
717         { "time-stamp-type", required_argument, NULL, 'j' },
718         { "list-time-stamp-types", no_argument, NULL, 'J' },
719 #endif
720 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
721         { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
722 #endif
723         { "dont-verify-checksums", no_argument, NULL, 'K' },
724         { "list-data-link-types", no_argument, NULL, 'L' },
725         { "no-optimize", no_argument, NULL, 'O' },
726         { "no-promiscuous-mode", no_argument, NULL, 'p' },
727 #ifdef HAVE_PCAP_SETDIRECTION
728         { "direction", required_argument, NULL, 'Q' },
729 #endif
730         { "snapshot-length", required_argument, NULL, 's' },
731         { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
732 #ifdef HAVE_PCAP_DUMP_FLUSH
733         { "packet-buffered", no_argument, NULL, 'U' },
734 #endif
735         { "linktype", required_argument, NULL, 'y' },
736 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
737         { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
738 #endif
739 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
740         { "debug-filter-parser", no_argument, NULL, 'Y' },
741 #endif
742         { "relinquish-privileges", required_argument, NULL, 'Z' },
743         { "number", no_argument, NULL, '#' },
744         { "version", no_argument, NULL, OPTION_VERSION },
745         { NULL, 0, NULL, 0 }
746 };
747
748 #ifndef WIN32
749 /* Drop root privileges and chroot if necessary */
750 static void
751 droproot(const char *username, const char *chroot_dir)
752 {
753         struct passwd *pw = NULL;
754
755         if (chroot_dir && !username) {
756                 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
757                 exit(1);
758         }
759
760         pw = getpwnam(username);
761         if (pw) {
762                 if (chroot_dir) {
763                         if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
764                                 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
765                                     chroot_dir, pcap_strerror(errno));
766                                 exit(1);
767                         }
768                 }
769 #ifdef HAVE_LIBCAP_NG
770                 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
771                 if (ret < 0) {
772                         fprintf(stderr, "error : ret %d\n", ret);
773                 }
774                 else {
775                         fprintf(stderr, "dropped privs to %s\n", username);
776                 }
777 #else
778                 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
779                     setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
780                         fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
781                             username,
782                             (unsigned long)pw->pw_uid,
783                             (unsigned long)pw->pw_gid,
784                             pcap_strerror(errno));
785                         exit(1);
786                 }
787                 else {
788                         fprintf(stderr, "dropped privs to %s\n", username);
789                 }
790 #endif /* HAVE_LIBCAP_NG */
791         }
792         else {
793                 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
794                     username);
795                 exit(1);
796         }
797 #ifdef HAVE_LIBCAP_NG
798         /* We don't need CAP_SETUID and CAP_SETGID any more. */
799         capng_updatev(
800                 CAPNG_DROP,
801                 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
802                 CAP_SETUID,
803                 CAP_SETGID,
804                 -1);
805         capng_apply(CAPNG_SELECT_BOTH);
806 #endif /* HAVE_LIBCAP_NG */
807
808 }
809 #endif /* WIN32 */
810
811 static int
812 getWflagChars(int x)
813 {
814         int c = 0;
815
816         x -= 1;
817         while (x > 0) {
818                 c += 1;
819                 x /= 10;
820         }
821
822         return c;
823 }
824
825
826 static void
827 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
828 {
829         char *filename = malloc(PATH_MAX + 1);
830         if (filename == NULL)
831             error("Makefilename: malloc");
832
833         /* Process with strftime if Gflag is set. */
834         if (Gflag != 0) {
835           struct tm *local_tm;
836
837           /* Convert Gflag_time to a usable format */
838           if ((local_tm = localtime(&Gflag_time)) == NULL) {
839                   error("MakeTimedFilename: localtime");
840           }
841
842           /* There's no good way to detect an error in strftime since a return
843            * value of 0 isn't necessarily failure.
844            */
845           strftime(filename, PATH_MAX, orig_name, local_tm);
846         } else {
847           strncpy(filename, orig_name, PATH_MAX);
848         }
849
850         if (cnt == 0 && max_chars == 0)
851                 strncpy(buffer, filename, PATH_MAX + 1);
852         else
853                 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
854                   /* Report an error if the filename is too large */
855                   error("too many output files or filename is too long (> %d)", PATH_MAX);
856         free(filename);
857 }
858
859 static int tcpdump_printf(netdissect_options *ndo _U_,
860                           const char *fmt, ...)
861 {
862
863   va_list args;
864   int ret;
865
866   va_start(args, fmt);
867   ret=vfprintf(stdout, fmt, args);
868   va_end(args);
869
870   return ret;
871 }
872
873 static struct print_info
874 get_print_info(int type)
875 {
876         struct print_info printinfo;
877
878         printinfo.ndo_type = 1;
879         printinfo.ndo = gndo;
880         printinfo.p.ndo_printer = lookup_ndo_printer(type);
881         if (printinfo.p.ndo_printer == NULL) {
882                 printinfo.p.printer = lookup_printer(type);
883                 printinfo.ndo_type = 0;
884                 if (printinfo.p.printer == NULL) {
885                         gndo->ndo_dltname = pcap_datalink_val_to_name(type);
886                         if (gndo->ndo_dltname != NULL)
887                                 error("packet printing is not supported for link type %s: use -w",
888                                       gndo->ndo_dltname);
889                         else
890                                 error("packet printing is not supported for link type %d: use -w", type);
891                 }
892         }
893         return (printinfo);
894 }
895
896 static char *
897 get_next_file(FILE *VFile, char *ptr)
898 {
899         char *ret;
900
901         ret = fgets(ptr, PATH_MAX, VFile);
902         if (!ret)
903                 return NULL;
904
905         if (ptr[strlen(ptr) - 1] == '\n')
906                 ptr[strlen(ptr) - 1] = '\0';
907
908         return ret;
909 }
910
911 #ifdef HAVE_CASPER
912 static cap_channel_t *
913 capdns_setup(void)
914 {
915         cap_channel_t *capcas, *capdnsloc;
916         const char *types[1];
917         int families[2];
918
919         capcas = cap_init();
920         if (capcas == NULL)
921                 error("unable to create casper process");
922         capdnsloc = cap_service_open(capcas, "system.dns");
923         /* Casper capability no longer needed. */
924         cap_close(capcas);
925         if (capdnsloc == NULL)
926                 error("unable to open system.dns service");
927         /* Limit system.dns to reverse DNS lookups. */
928         types[0] = "ADDR";
929         if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
930                 error("unable to limit access to system.dns service");
931         families[0] = AF_INET;
932         families[1] = AF_INET6;
933         if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
934                 error("unable to limit access to system.dns service");
935
936         return (capdnsloc);
937 }
938 #endif  /* HAVE_CASPER */
939
940 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
941 static int
942 tstamp_precision_from_string(const char *precision)
943 {
944         if (strncmp(precision, "nano", strlen("nano")) == 0)
945                 return PCAP_TSTAMP_PRECISION_NANO;
946
947         if (strncmp(precision, "micro", strlen("micro")) == 0)
948                 return PCAP_TSTAMP_PRECISION_MICRO;
949
950         return -EINVAL;
951 }
952
953 static const char *
954 tstamp_precision_to_string(int precision)
955 {
956         switch (precision) {
957
958         case PCAP_TSTAMP_PRECISION_MICRO:
959                 return "micro";
960
961         case PCAP_TSTAMP_PRECISION_NANO:
962                 return "nano";
963
964         default:
965                 return "unknown";
966         }
967 }
968 #endif
969
970 #ifdef __FreeBSD__
971 /*
972  * Ensure that, on a dump file's descriptor, we have all the rights
973  * necessary to make the standard I/O library work with an fdopen()ed
974  * FILE * from that descriptor.
975  *
976  * A long time ago, in a galaxy far far away, AT&T decided that, instead
977  * of providing separate APIs for getting and setting the FD_ flags on a
978  * descriptor, getting and setting the O_ flags on a descriptor, and
979  * locking files, they'd throw them all into a kitchen-sink fcntl() call
980  * along the lines of ioctl(), the fact that ioctl() operations are
981  * largely specific to particular character devices but fcntl() operations
982  * are either generic to all descriptors or generic to all descriptors for
983  * regular files nonwithstanding.
984  *
985  * The Capsicum people decided that fine-grained control of descriptor
986  * operations was required, so that you need to grant permission for
987  * reading, writing, seeking, and fcntl-ing.  The latter, courtesy of
988  * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
989  * collection of things, so there are *individual* fcntls for which
990  * permission needs to be granted.
991  *
992  * The FreeBSD standard I/O people implemented some optimizations that
993  * requires that the standard I/O routines be able to determine whether
994  * the descriptor for the FILE * is open append-only or not; as that
995  * descriptor could have come from an open() rather than an fopen(),
996  * that requires that it be able to do an F_GETFL fcntl() to read
997  * the O_ flags.
998  *
999  * Tcpdump uses ftell() to determine how much data has been written
1000  * to a file in order to, when used with -C, determine when it's time
1001  * to rotate capture files.  ftell() therefore needs to do an lseek()
1002  * to find out the file offset and must, thanks to the aforementioned
1003  * optimization, also know whether the descriptor is open append-only
1004  * or not.
1005  *
1006  * The net result of all the above is that we need to grant CAP_SEEK,
1007  * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
1008  *
1009  * Perhaps this is the universe's way of saying that either
1010  *
1011  *      1) there needs to be an fopenat() call and a pcap_dump_openat() call
1012  *         using it, so that Capsicum-capable tcpdump wouldn't need to do
1013  *         an fdopen()
1014  *
1015  * or
1016  *
1017  *      2) there needs to be a cap_fdopen() call in the FreeBSD standard
1018  *         I/O library that knows what rights are needed by the standard
1019  *         I/O library, based on the open mode, and assigns them, perhaps
1020  *         with an additional argument indicating, for example, whether
1021  *         seeking should be allowed, so that tcpdump doesn't need to know
1022  *         what the standard I/O library happens to require this week.
1023  */
1024 static void
1025 set_dumper_capsicum_rights(pcap_dumper_t *p)
1026 {
1027         int fd = fileno(pcap_dump_file(p));
1028         cap_rights_t rights;
1029
1030         cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
1031         if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
1032                 error("unable to limit dump descriptor");
1033         }
1034         if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
1035                 error("unable to limit dump descriptor fcntls");
1036         }
1037 }
1038 #endif
1039
1040 int
1041 main(int argc, char **argv)
1042 {
1043         register int cnt, op, i;
1044         bpf_u_int32 localnet =0 , netmask = 0;
1045         register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
1046         pcap_handler callback;
1047         int type;
1048         int dlt;
1049         int new_dlt;
1050         const char *dlt_name;
1051         struct bpf_program fcode;
1052 #ifndef WIN32
1053         RETSIGTYPE (*oldhandler)(int);
1054 #endif
1055         struct print_info printinfo;
1056         struct dump_info dumpinfo;
1057         u_char *pcap_userdata;
1058         char ebuf[PCAP_ERRBUF_SIZE];
1059         char VFileLine[PATH_MAX + 1];
1060         char *username = NULL;
1061         char *chroot_dir = NULL;
1062         char *ret = NULL;
1063         char *end;
1064 #ifdef HAVE_PCAP_FINDALLDEVS
1065         pcap_if_t *devpointer;
1066         int devnum;
1067 #endif
1068         int status;
1069         FILE *VFile;
1070 #ifdef __FreeBSD__
1071         cap_rights_t rights;
1072 #endif  /* !__FreeBSD__ */
1073         int cansandbox;
1074
1075 #ifdef WIN32
1076         if(wsockinit() != 0) return 1;
1077 #endif /* WIN32 */
1078
1079         jflag=-1;       /* not set */
1080         gndo->ndo_Oflag=1;
1081         gndo->ndo_Rflag=1;
1082         gndo->ndo_dlt=-1;
1083         gndo->ndo_default_print=ndo_default_print;
1084         gndo->ndo_printf=tcpdump_printf;
1085         gndo->ndo_error=ndo_error;
1086         gndo->ndo_warning=ndo_warning;
1087         gndo->ndo_snaplen = DEFAULT_SNAPLEN;
1088         gndo->ndo_immediate = 0;
1089
1090         cnt = -1;
1091         device = NULL;
1092         infile = NULL;
1093         RFileName = NULL;
1094         VFileName = NULL;
1095         VFile = NULL;
1096         WFileName = NULL;
1097         dlt = -1;
1098         if ((cp = strrchr(argv[0], '/')) != NULL)
1099                 program_name = cp + 1;
1100         else
1101                 program_name = argv[0];
1102
1103         /*
1104          * On platforms where the CPU doesn't support unaligned loads,
1105          * force unaligned accesses to abort with SIGBUS, rather than
1106          * being fixed up (slowly) by the OS kernel; on those platforms,
1107          * misaligned accesses are bugs, and we want tcpdump to crash so
1108          * that the bugs are reported.
1109          */
1110         if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1111                 error("%s", ebuf);
1112
1113 #ifdef USE_LIBSMI
1114         smiInit("tcpdump");
1115 #endif
1116
1117         while (
1118             (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
1119                 switch (op) {
1120
1121                 case 'a':
1122                         /* compatibility for old -a */
1123                         break;
1124
1125                 case 'A':
1126                         ++Aflag;
1127                         break;
1128
1129                 case 'b':
1130                         ++bflag;
1131                         break;
1132
1133 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
1134                 case 'B':
1135                         Bflag = atoi(optarg)*1024;
1136                         if (Bflag <= 0)
1137                                 error("invalid packet buffer size %s", optarg);
1138                         break;
1139 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
1140
1141                 case 'c':
1142                         cnt = atoi(optarg);
1143                         if (cnt <= 0)
1144                                 error("invalid packet count %s", optarg);
1145                         break;
1146
1147                 case 'C':
1148                         Cflag = atoi(optarg) * 1000000;
1149                         if (Cflag < 0)
1150                                 error("invalid file size %s", optarg);
1151                         break;
1152
1153                 case 'd':
1154                         ++dflag;
1155                         break;
1156
1157                 case 'D':
1158                         Dflag++;
1159                         break;
1160
1161                 case 'L':
1162                         Lflag++;
1163                         break;
1164
1165                 case 'e':
1166                         ++eflag;
1167                         break;
1168
1169                 case 'E':
1170 #ifndef HAVE_LIBCRYPTO
1171                         warning("crypto code not compiled in");
1172 #endif
1173                         gndo->ndo_espsecret = optarg;
1174                         break;
1175
1176                 case 'f':
1177                         ++fflag;
1178                         break;
1179
1180                 case 'F':
1181                         infile = optarg;
1182                         break;
1183
1184                 case 'G':
1185                         Gflag = atoi(optarg);
1186                         if (Gflag < 0)
1187                                 error("invalid number of seconds %s", optarg);
1188
1189                         /* We will create one file initially. */
1190                         Gflag_count = 0;
1191
1192                         /* Grab the current time for rotation use. */
1193                         if ((Gflag_time = time(NULL)) == (time_t)-1) {
1194                                 error("main: can't get current time: %s",
1195                                     pcap_strerror(errno));
1196                         }
1197                         break;
1198
1199                 case 'h':
1200                         print_usage();
1201                         exit(0);
1202                         break;
1203
1204                 case 'H':
1205                         ++Hflag;
1206                         break;
1207
1208                 case 'i':
1209                         if (optarg[0] == '0' && optarg[1] == 0)
1210                                 error("Invalid adapter index");
1211
1212 #ifdef HAVE_PCAP_FINDALLDEVS
1213                         /*
1214                          * If the argument is a number, treat it as
1215                          * an index into the list of adapters, as
1216                          * printed by "tcpdump -D".
1217                          *
1218                          * This should be OK on UNIX systems, as interfaces
1219                          * shouldn't have names that begin with digits.
1220                          * It can be useful on Windows, where more than
1221                          * one interface can have the same name.
1222                          */
1223                         devnum = strtol(optarg, &end, 10);
1224                         if (optarg != end && *end == '\0') {
1225                                 if (devnum < 0)
1226                                         error("Invalid adapter index");
1227
1228                                 if (pcap_findalldevs(&devpointer, ebuf) < 0)
1229                                         error("%s", ebuf);
1230                                 else {
1231                                         /*
1232                                          * Look for the devnum-th entry
1233                                          * in the list of devices
1234                                          * (1-based).
1235                                          */
1236                                         for (i = 0;
1237                                             i < devnum-1 && devpointer != NULL;
1238                                             i++, devpointer = devpointer->next)
1239                                                 ;
1240                                         if (devpointer == NULL)
1241                                                 error("Invalid adapter index");
1242                                 }
1243                                 device = devpointer->name;
1244                                 break;
1245                         }
1246 #endif /* HAVE_PCAP_FINDALLDEVS */
1247                         device = optarg;
1248                         break;
1249
1250 #ifdef HAVE_PCAP_CREATE
1251                 case 'I':
1252                         ++Iflag;
1253                         break;
1254 #endif /* HAVE_PCAP_CREATE */
1255
1256 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1257                 case 'j':
1258                         jflag = pcap_tstamp_type_name_to_val(optarg);
1259                         if (jflag < 0)
1260                                 error("invalid time stamp type %s", optarg);
1261                         break;
1262
1263                 case 'J':
1264                         Jflag++;
1265                         break;
1266 #endif
1267
1268                 case 'l':
1269 #ifdef WIN32
1270                         /*
1271                          * _IOLBF is the same as _IOFBF in Microsoft's C
1272                          * libraries; the only alternative they offer
1273                          * is _IONBF.
1274                          *
1275                          * XXX - this should really be checking for MSVC++,
1276                          * not WIN32, if, for example, MinGW has its own
1277                          * C library that is more UNIX-compatible.
1278                          */
1279                         setvbuf(stdout, NULL, _IONBF, 0);
1280 #else /* WIN32 */
1281 #ifdef HAVE_SETLINEBUF
1282                         setlinebuf(stdout);
1283 #else
1284                         setvbuf(stdout, NULL, _IOLBF, 0);
1285 #endif
1286 #endif /* WIN32 */
1287                         break;
1288
1289                 case 'K':
1290                         ++Kflag;
1291                         break;
1292
1293                 case 'm':
1294 #ifdef USE_LIBSMI
1295                         if (smiLoadModule(optarg) == 0) {
1296                                 error("could not load MIB module %s", optarg);
1297                         }
1298                         sflag = 1;
1299 #else
1300                         (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1301                                       program_name, optarg);
1302                         (void)fprintf(stderr, "(no libsmi support)\n");
1303 #endif
1304                         break;
1305
1306                 case 'M':
1307                         /* TCP-MD5 shared secret */
1308 #ifndef HAVE_LIBCRYPTO
1309                         warning("crypto code not compiled in");
1310 #endif
1311                         sigsecret = optarg;
1312                         break;
1313
1314                 case 'n':
1315                         ++nflag;
1316                         break;
1317
1318                 case 'N':
1319                         ++Nflag;
1320                         break;
1321
1322                 case 'O':
1323                         Oflag = 0;
1324                         break;
1325
1326                 case 'p':
1327                         ++pflag;
1328                         break;
1329
1330                 case 'q':
1331                         ++qflag;
1332                         ++suppress_default_print;
1333                         break;
1334
1335 #ifdef HAVE_PCAP_SETDIRECTION
1336                 case 'Q':
1337                         if (strcasecmp(optarg, "in") == 0)
1338                                 Qflag = PCAP_D_IN;
1339                         else if (strcasecmp(optarg, "out") == 0)
1340                                 Qflag = PCAP_D_OUT;
1341                         else if (strcasecmp(optarg, "inout") == 0)
1342                                 Qflag = PCAP_D_INOUT;
1343                         else
1344                                 error("unknown capture direction `%s'", optarg);
1345                         break;
1346 #endif /* HAVE_PCAP_SETDIRECTION */
1347
1348                 case 'r':
1349                         RFileName = optarg;
1350                         break;
1351
1352                 case 'R':
1353                         Rflag = 0;
1354                         break;
1355
1356                 case 's':
1357                         snaplen = strtol(optarg, &end, 0);
1358                         if (optarg == end || *end != '\0'
1359                             || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
1360                                 error("invalid snaplen %s", optarg);
1361                         else if (snaplen == 0)
1362                                 snaplen = MAXIMUM_SNAPLEN;
1363                         break;
1364
1365                 case 'S':
1366                         ++Sflag;
1367                         break;
1368
1369                 case 't':
1370                         ++tflag;
1371                         break;
1372
1373                 case 'T':
1374                         if (strcasecmp(optarg, "vat") == 0)
1375                                 packettype = PT_VAT;
1376                         else if (strcasecmp(optarg, "wb") == 0)
1377                                 packettype = PT_WB;
1378                         else if (strcasecmp(optarg, "rpc") == 0)
1379                                 packettype = PT_RPC;
1380                         else if (strcasecmp(optarg, "rtp") == 0)
1381                                 packettype = PT_RTP;
1382                         else if (strcasecmp(optarg, "rtcp") == 0)
1383                                 packettype = PT_RTCP;
1384                         else if (strcasecmp(optarg, "snmp") == 0)
1385                                 packettype = PT_SNMP;
1386                         else if (strcasecmp(optarg, "cnfp") == 0)
1387                                 packettype = PT_CNFP;
1388                         else if (strcasecmp(optarg, "tftp") == 0)
1389                                 packettype = PT_TFTP;
1390                         else if (strcasecmp(optarg, "aodv") == 0)
1391                                 packettype = PT_AODV;
1392                         else if (strcasecmp(optarg, "carp") == 0)
1393                                 packettype = PT_CARP;
1394                         else if (strcasecmp(optarg, "radius") == 0)
1395                                 packettype = PT_RADIUS;
1396                         else if (strcasecmp(optarg, "zmtp1") == 0)
1397                                 packettype = PT_ZMTP1;
1398                         else if (strcasecmp(optarg, "vxlan") == 0)
1399                                 packettype = PT_VXLAN;
1400                         else if (strcasecmp(optarg, "pgm") == 0)
1401                                 packettype = PT_PGM;
1402                         else if (strcasecmp(optarg, "pgm_zmtp1") == 0)
1403                                 packettype = PT_PGM_ZMTP1;
1404                         else if (strcasecmp(optarg, "lmp") == 0)
1405                                 packettype = PT_LMP;
1406                         else
1407                                 error("unknown packet type `%s'", optarg);
1408                         break;
1409
1410                 case 'u':
1411                         ++uflag;
1412                         break;
1413
1414 #ifdef HAVE_PCAP_DUMP_FLUSH
1415                 case 'U':
1416                         ++Uflag;
1417                         break;
1418 #endif
1419
1420                 case 'v':
1421                         ++vflag;
1422                         break;
1423
1424                 case 'V':
1425                         VFileName = optarg;
1426                         break;
1427
1428                 case 'w':
1429                         WFileName = optarg;
1430                         break;
1431
1432                 case 'W':
1433                         Wflag = atoi(optarg);
1434                         if (Wflag < 0)
1435                                 error("invalid number of output files %s", optarg);
1436                         WflagChars = getWflagChars(Wflag);
1437                         break;
1438
1439                 case 'x':
1440                         ++xflag;
1441                         ++suppress_default_print;
1442                         break;
1443
1444                 case 'X':
1445                         ++Xflag;
1446                         ++suppress_default_print;
1447                         break;
1448
1449                 case 'y':
1450                         gndo->ndo_dltname = optarg;
1451                         gndo->ndo_dlt =
1452                           pcap_datalink_name_to_val(gndo->ndo_dltname);
1453                         if (gndo->ndo_dlt < 0)
1454                                 error("invalid data link type %s", gndo->ndo_dltname);
1455                         break;
1456
1457 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1458                 case 'Y':
1459                         {
1460                         /* Undocumented flag */
1461 #ifdef HAVE_PCAP_DEBUG
1462                         extern int pcap_debug;
1463                         pcap_debug = 1;
1464 #else
1465                         extern int yydebug;
1466                         yydebug = 1;
1467 #endif
1468                         }
1469                         break;
1470 #endif
1471                 case 'z':
1472                         zflag = strdup(optarg);
1473                         break;
1474
1475                 case 'Z':
1476                         username = strdup(optarg);
1477                         break;
1478
1479                 case '#':
1480                         gndo->ndo_packet_number = 1;
1481                         break;
1482
1483                 case OPTION_VERSION:
1484                         print_version();
1485                         exit(0);
1486                         break;
1487
1488 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1489                 case OPTION_TSTAMP_PRECISION:
1490                         gndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1491                         if (gndo->ndo_tstamp_precision < 0)
1492                                 error("unsupported time stamp precision");
1493                         break;
1494 #endif
1495
1496 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1497                 case OPTION_IMMEDIATE_MODE:
1498                         gndo->ndo_immediate = 1;
1499                         break;
1500 #endif
1501
1502                 default:
1503                         print_usage();
1504                         exit(1);
1505                         /* NOTREACHED */
1506                 }
1507
1508 #ifdef HAVE_PCAP_FINDALLDEVS
1509         if (Dflag)
1510                 show_devices_and_exit();
1511 #endif
1512
1513         switch (tflag) {
1514
1515         case 0: /* Default */
1516         case 4: /* Default + Date*/
1517                 thiszone = gmt2local(0);
1518                 break;
1519
1520         case 1: /* No time stamp */
1521         case 2: /* Unix timeval style */
1522         case 3: /* Microseconds since previous packet */
1523         case 5: /* Microseconds since first packet */
1524                 break;
1525
1526         default: /* Not supported */
1527                 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1528                 break;
1529         }
1530
1531         if (fflag != 0 && (VFileName != NULL || RFileName != NULL))
1532                 error("-f can not be used with -V or -r");
1533
1534         if (VFileName != NULL && RFileName != NULL)
1535                 error("-V and -r are mutually exclusive.");
1536
1537 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1538         /*
1539          * If we're printing dissected packets to the standard output
1540          * rather than saving raw packets to a file, and the standard
1541          * output is a terminal, use immediate mode, as the user's
1542          * probably expecting to see packets pop up immediately.
1543          */
1544         if (WFileName == NULL && isatty(1))
1545                 gndo->ndo_immediate = 1;
1546 #endif
1547
1548 #ifdef WITH_CHROOT
1549         /* if run as root, prepare for chrooting */
1550         if (getuid() == 0 || geteuid() == 0) {
1551                 /* future extensibility for cmd-line arguments */
1552                 if (!chroot_dir)
1553                         chroot_dir = WITH_CHROOT;
1554         }
1555 #endif
1556
1557 #ifdef WITH_USER
1558         /* if run as root, prepare for dropping root privileges */
1559         if (getuid() == 0 || geteuid() == 0) {
1560                 /* Run with '-Z root' to restore old behaviour */
1561                 if (!username)
1562                         username = WITH_USER;
1563         }
1564 #endif
1565
1566         if (RFileName != NULL || VFileName != NULL) {
1567                 /*
1568                  * If RFileName is non-null, it's the pathname of a
1569                  * savefile to read.  If VFileName is non-null, it's
1570                  * the pathname of a file containing a list of pathnames
1571                  * (one per line) of savefiles to read.
1572                  *
1573                  * In either case, we're reading a savefile, not doing
1574                  * a live capture.
1575                  */
1576 #ifndef WIN32
1577                 /*
1578                  * We don't need network access, so relinquish any set-UID
1579                  * or set-GID privileges we have (if any).
1580                  *
1581                  * We do *not* want set-UID privileges when opening a
1582                  * trace file, as that might let the user read other
1583                  * people's trace files (especially if we're set-UID
1584                  * root).
1585                  */
1586                 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1587                         fprintf(stderr, "Warning: setgid/setuid failed !\n");
1588 #endif /* WIN32 */
1589                 if (VFileName != NULL) {
1590                         if (VFileName[0] == '-' && VFileName[1] == '\0')
1591                                 VFile = stdin;
1592                         else
1593                                 VFile = fopen(VFileName, "r");
1594
1595                         if (VFile == NULL)
1596                                 error("Unable to open file: %s\n", strerror(errno));
1597
1598                         ret = get_next_file(VFile, VFileLine);
1599                         if (!ret)
1600                                 error("Nothing in %s\n", VFileName);
1601                         RFileName = VFileLine;
1602                 }
1603
1604 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1605                 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1606                     gndo->ndo_tstamp_precision, ebuf);
1607 #else
1608                 pd = pcap_open_offline(RFileName, ebuf);
1609 #endif
1610
1611                 if (pd == NULL)
1612                         error("%s", ebuf);
1613 #ifdef HAVE_CASPER
1614                 cap_rights_init(&rights, CAP_READ);
1615                 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1616                     errno != ENOSYS) {
1617                         error("unable to limit pcap descriptor");
1618                 }
1619 #endif
1620                 dlt = pcap_datalink(pd);
1621                 dlt_name = pcap_datalink_val_to_name(dlt);
1622                 if (dlt_name == NULL) {
1623                         fprintf(stderr, "reading from file %s, link-type %u\n",
1624                             RFileName, dlt);
1625                 } else {
1626                         fprintf(stderr,
1627                             "reading from file %s, link-type %s (%s)\n",
1628                             RFileName, dlt_name,
1629                             pcap_datalink_val_to_description(dlt));
1630                 }
1631         } else {
1632                 /*
1633                  * We're doing a live capture.
1634                  */
1635                 if (device == NULL) {
1636                         device = pcap_lookupdev(ebuf);
1637                         if (device == NULL)
1638                                 error("%s", ebuf);
1639                 }
1640 #ifdef WIN32
1641                 /*
1642                  * Print a message to the standard error on Windows.
1643                  * XXX - why do it here, with a different message?
1644                  */
1645                 if(strlen(device) == 1) /* we assume that an ASCII string is always longer than 1 char */
1646                 {                                               /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1647                         fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1648                 }
1649                 else
1650                 {
1651                         fprintf(stderr, "%s: listening on %s\n", program_name, device);
1652                 }
1653
1654                 fflush(stderr);
1655 #endif /* WIN32 */
1656 #ifdef HAVE_PCAP_CREATE
1657                 pd = pcap_create(device, ebuf);
1658                 if (pd == NULL)
1659                         error("%s", ebuf);
1660 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1661                 if (Jflag)
1662                         show_tstamp_types_and_exit(device, pd);
1663 #endif
1664 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1665                 status = pcap_set_tstamp_precision(pd, gndo->ndo_tstamp_precision);
1666                 if (status != 0)
1667                         error("%s: Can't set %ssecond time stamp precision: %s",
1668                                 device,
1669                                 tstamp_precision_to_string(gndo->ndo_tstamp_precision),
1670                                 pcap_statustostr(status));
1671 #endif
1672
1673 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1674                 if (gndo->ndo_immediate) {
1675                         status = pcap_set_immediate_mode(pd, 1);
1676                         if (status != 0)
1677                                 error("%s: Can't set immediate mode: %s",
1678                                 device,
1679                                 pcap_statustostr(status));
1680                 }
1681 #endif
1682                 /*
1683                  * Is this an interface that supports monitor mode?
1684                  */
1685                 if (pcap_can_set_rfmon(pd) == 1)
1686                         supports_monitor_mode = 1;
1687                 else
1688                         supports_monitor_mode = 0;
1689                 status = pcap_set_snaplen(pd, snaplen);
1690                 if (status != 0)
1691                         error("%s: Can't set snapshot length: %s",
1692                             device, pcap_statustostr(status));
1693                 status = pcap_set_promisc(pd, !pflag);
1694                 if (status != 0)
1695                         error("%s: Can't set promiscuous mode: %s",
1696                             device, pcap_statustostr(status));
1697                 if (Iflag) {
1698                         status = pcap_set_rfmon(pd, 1);
1699                         if (status != 0)
1700                                 error("%s: Can't set monitor mode: %s",
1701                                     device, pcap_statustostr(status));
1702                 }
1703                 status = pcap_set_timeout(pd, 1000);
1704                 if (status != 0)
1705                         error("%s: pcap_set_timeout failed: %s",
1706                             device, pcap_statustostr(status));
1707                 if (Bflag != 0) {
1708                         status = pcap_set_buffer_size(pd, Bflag);
1709                         if (status != 0)
1710                                 error("%s: Can't set buffer size: %s",
1711                                     device, pcap_statustostr(status));
1712                 }
1713 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1714                 if (jflag != -1) {
1715                         status = pcap_set_tstamp_type(pd, jflag);
1716                         if (status < 0)
1717                                 error("%s: Can't set time stamp type: %s",
1718                                       device, pcap_statustostr(status));
1719                 }
1720 #endif
1721                 status = pcap_activate(pd);
1722                 if (status < 0) {
1723                         /*
1724                          * pcap_activate() failed.
1725                          */
1726                         cp = pcap_geterr(pd);
1727                         if (status == PCAP_ERROR)
1728                                 error("%s", cp);
1729                         else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1730                                   status == PCAP_ERROR_PERM_DENIED) &&
1731                                  *cp != '\0')
1732                                 error("%s: %s\n(%s)", device,
1733                                     pcap_statustostr(status), cp);
1734 #ifdef __FreeBSD__
1735                         else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1736                             strncmp(device, "wlan", 4) == 0) {
1737                                 char parent[8], newdev[8];
1738                                 char sysctl[32];
1739                                 size_t s = sizeof(parent);
1740
1741                                 snprintf(sysctl, sizeof(sysctl),
1742                                     "net.wlan.%d.%%parent", atoi(device + 4));
1743                                 sysctlbyname(sysctl, parent, &s, NULL, 0);
1744                                 strlcpy(newdev, device, sizeof(newdev));
1745                                 /* Suggest a new wlan device. */
1746                                 newdev[strlen(newdev)-1]++;
1747                                 error("%s is not a monitor mode VAP\n"
1748                                     "To create a new monitor mode VAP use:\n"
1749                                     "  ifconfig %s create wlandev %s wlanmode "
1750                                     "monitor\nand use %s as the tcpdump "
1751                                     "interface", device, newdev, parent,
1752                                     newdev);
1753                         }
1754 #endif
1755                         else
1756                                 error("%s: %s", device,
1757                                     pcap_statustostr(status));
1758                 } else if (status > 0) {
1759                         /*
1760                          * pcap_activate() succeeded, but it's warning us
1761                          * of a problem it had.
1762                          */
1763                         cp = pcap_geterr(pd);
1764                         if (status == PCAP_WARNING)
1765                                 warning("%s", cp);
1766                         else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1767                                  *cp != '\0')
1768                                 warning("%s: %s\n(%s)", device,
1769                                     pcap_statustostr(status), cp);
1770                         else
1771                                 warning("%s: %s", device,
1772                                     pcap_statustostr(status));
1773                 }
1774 #ifdef HAVE_PCAP_SETDIRECTION
1775                 if (Qflag != -1) {
1776                         status = pcap_setdirection(pd, Qflag);
1777                         if (status != 0)
1778                                 error("%s: pcap_setdirection() failed: %s",
1779                                       device,  pcap_geterr(pd));
1780                 }
1781 #endif /* HAVE_PCAP_SETDIRECTION */
1782 #else
1783                 *ebuf = '\0';
1784                 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1785                 if (pd == NULL)
1786                         error("%s", ebuf);
1787                 else if (*ebuf)
1788                         warning("%s", ebuf);
1789 #endif /* HAVE_PCAP_CREATE */
1790                 /*
1791                  * Let user own process after socket has been opened.
1792                  */
1793 #ifndef WIN32
1794                 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1795                         fprintf(stderr, "Warning: setgid/setuid failed !\n");
1796 #endif /* WIN32 */
1797 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1798                 if(Bflag != 0)
1799                         if(pcap_setbuff(pd, Bflag)==-1){
1800                                 error("%s", pcap_geterr(pd));
1801                         }
1802 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1803                 if (Lflag)
1804                         show_dlts_and_exit(device, pd);
1805                 if (gndo->ndo_dlt >= 0) {
1806 #ifdef HAVE_PCAP_SET_DATALINK
1807                         if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1808                                 error("%s", pcap_geterr(pd));
1809 #else
1810                         /*
1811                          * We don't actually support changing the
1812                          * data link type, so we only let them
1813                          * set it to what it already is.
1814                          */
1815                         if (gndo->ndo_dlt != pcap_datalink(pd)) {
1816                                 error("%s is not one of the DLTs supported by this device\n",
1817                                       gndo->ndo_dltname);
1818                         }
1819 #endif
1820                         (void)fprintf(stderr, "%s: data link type %s\n",
1821                                       program_name, gndo->ndo_dltname);
1822                         (void)fflush(stderr);
1823                 }
1824                 i = pcap_snapshot(pd);
1825                 if (snaplen < i) {
1826                         warning("snaplen raised from %d to %d", snaplen, i);
1827                         snaplen = i;
1828                 }
1829                 if(fflag != 0) {
1830                         if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1831                                 warning("foreign (-f) flag used but: %s", ebuf);
1832                         }
1833                 }
1834
1835         }
1836         if (infile)
1837                 cmdbuf = read_infile(infile);
1838         else
1839                 cmdbuf = copy_argv(&argv[optind]);
1840
1841         if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1842                 error("%s", pcap_geterr(pd));
1843         if (dflag) {
1844                 bpf_dump(&fcode, dflag);
1845                 pcap_close(pd);
1846                 free(cmdbuf);
1847                 exit(0);
1848         }
1849
1850 #ifdef HAVE_CASPER
1851         if (!nflag)
1852                 capdns = capdns_setup();
1853 #endif  /* HAVE_CASPER */
1854
1855         init_addrtoname(gndo, localnet, netmask);
1856         init_checksum();
1857
1858 #ifndef WIN32
1859         (void)setsignal(SIGPIPE, cleanup);
1860         (void)setsignal(SIGTERM, cleanup);
1861         (void)setsignal(SIGINT, cleanup);
1862 #endif /* WIN32 */
1863 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1864         (void)setsignal(SIGCHLD, child_cleanup);
1865 #endif
1866         /* Cooperate with nohup(1) */
1867 #ifndef WIN32
1868         if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1869                 (void)setsignal(SIGHUP, oldhandler);
1870 #endif /* WIN32 */
1871
1872 #ifndef WIN32
1873         /*
1874          * If a user name was specified with "-Z", attempt to switch to
1875          * that user's UID.  This would probably be used with sudo,
1876          * to allow tcpdump to be run in a special restricted
1877          * account (if you just want to allow users to open capture
1878          * devices, and can't just give users that permission,
1879          * you'd make tcpdump set-UID or set-GID).
1880          *
1881          * Tcpdump doesn't necessarily write only to one savefile;
1882          * the general only way to allow a -Z instance to write to
1883          * savefiles as the user under whose UID it's run, rather
1884          * than as the user specified with -Z, would thus be to switch
1885          * to the original user ID before opening a capture file and
1886          * then switch back to the -Z user ID after opening the savefile.
1887          * Switching to the -Z user ID only after opening the first
1888          * savefile doesn't handle the general case.
1889          */
1890
1891         if (getuid() == 0 || geteuid() == 0) {
1892 #ifdef HAVE_LIBCAP_NG
1893                 /* Initialize capng */
1894                 capng_clear(CAPNG_SELECT_BOTH);
1895                 if (username) {
1896                         capng_updatev(
1897                                 CAPNG_ADD,
1898                                 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1899                                 CAP_SETUID,
1900                                 CAP_SETGID,
1901                                 -1);
1902                 }
1903
1904                 if (WFileName) {
1905                         capng_update(
1906                                 CAPNG_ADD,
1907                                 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1908                                 CAP_DAC_OVERRIDE
1909                                 );
1910                 }
1911                 capng_apply(CAPNG_SELECT_BOTH);
1912 #endif /* HAVE_LIBCAP_NG */
1913                 if (username || chroot_dir)
1914                         droproot(username, chroot_dir);
1915
1916         }
1917 #endif /* WIN32 */
1918
1919         if (pcap_setfilter(pd, &fcode) < 0)
1920                 error("%s", pcap_geterr(pd));
1921 #ifdef HAVE_CASPER
1922         if (RFileName == NULL && VFileName == NULL) {
1923                 static const unsigned long cmds[] = { BIOCGSTATS };
1924
1925                 /*
1926                  * The various libpcap devices use a combination of
1927                  * read (bpf), ioctl (bpf, netmap), poll (netmap).
1928                  * Grant the relevant access rights, sorted by name.
1929                  */
1930                 cap_rights_init(&rights, CAP_EVENT, CAP_IOCTL, CAP_READ);
1931                 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1932                     errno != ENOSYS) {
1933                         error("unable to limit pcap descriptor");
1934                 }
1935                 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1936                     sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1937                         error("unable to limit ioctls on pcap descriptor");
1938                 }
1939         }
1940 #endif
1941         if (WFileName) {
1942                 pcap_dumper_t *p;
1943                 /* Do not exceed the default PATH_MAX for files. */
1944                 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1945
1946                 if (dumpinfo.CurrentFileName == NULL)
1947                         error("malloc of dumpinfo.CurrentFileName");
1948
1949                 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1950                 if (Cflag != 0)
1951                   MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1952                 else
1953                   MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1954
1955                 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1956 #ifdef HAVE_LIBCAP_NG
1957                 /* Give up CAP_DAC_OVERRIDE capability.
1958                  * Only allow it to be restored if the -C or -G flag have been
1959                  * set since we may need to create more files later on.
1960                  */
1961                 capng_update(
1962                         CAPNG_DROP,
1963                         (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1964                                 | CAPNG_EFFECTIVE,
1965                         CAP_DAC_OVERRIDE
1966                         );
1967                 capng_apply(CAPNG_SELECT_BOTH);
1968 #endif /* HAVE_LIBCAP_NG */
1969                 if (p == NULL)
1970                         error("%s", pcap_geterr(pd));
1971 #ifdef __FreeBSD__
1972                 set_dumper_capsicum_rights(p);
1973 #endif
1974                 if (Cflag != 0 || Gflag != 0) {
1975 #ifdef __FreeBSD__
1976                         dumpinfo.WFileName = strdup(basename(WFileName));
1977                         dumpinfo.dirfd = open(dirname(WFileName),
1978                             O_DIRECTORY | O_RDONLY);
1979                         if (dumpinfo.dirfd < 0) {
1980                                 error("unable to open directory %s",
1981                                     dirname(WFileName));
1982                         }
1983                         cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1984                             CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1985                         if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1986                             errno != ENOSYS) {
1987                                 error("unable to limit directory rights");
1988                         }
1989                         if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1990                             errno != ENOSYS) {
1991                                 error("unable to limit dump descriptor fcntls");
1992                         }
1993 #else   /* !__FreeBSD__ */
1994                         dumpinfo.WFileName = WFileName;
1995 #endif
1996                         callback = dump_packet_and_trunc;
1997                         dumpinfo.pd = pd;
1998                         dumpinfo.p = p;
1999                         pcap_userdata = (u_char *)&dumpinfo;
2000                 } else {
2001                         callback = dump_packet;
2002                         pcap_userdata = (u_char *)p;
2003                 }
2004 #ifdef HAVE_PCAP_DUMP_FLUSH
2005                 if (Uflag)
2006                         pcap_dump_flush(p);
2007 #endif
2008         } else {
2009                 type = pcap_datalink(pd);
2010                 printinfo = get_print_info(type);
2011                 callback = print_packet;
2012                 pcap_userdata = (u_char *)&printinfo;
2013         }
2014
2015 #ifdef SIGNAL_REQ_INFO
2016         /*
2017          * We can't get statistics when reading from a file rather
2018          * than capturing from a device.
2019          */
2020         if (RFileName == NULL)
2021                 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
2022 #endif
2023
2024         if (vflag > 0 && WFileName) {
2025                 /*
2026                  * When capturing to a file, "-v" means tcpdump should,
2027                  * every 10 secodns, "v"erbosely report the number of
2028                  * packets captured.
2029                  */
2030 #ifdef USE_WIN32_MM_TIMER
2031                 /* call verbose_stats_dump() each 1000 +/-100msec */
2032                 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
2033                 setvbuf(stderr, NULL, _IONBF, 0);
2034 #elif defined(HAVE_ALARM)
2035                 (void)setsignal(SIGALRM, verbose_stats_dump);
2036                 alarm(1);
2037 #endif
2038         }
2039
2040 #ifndef WIN32
2041         if (RFileName == NULL) {
2042                 /*
2043                  * Live capture (if -V was specified, we set RFileName
2044                  * to a file from the -V file).  Print a message to
2045                  * the standard error on UN*X.
2046                  */
2047                 if (!vflag && !WFileName) {
2048                         (void)fprintf(stderr,
2049                             "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2050                             program_name);
2051                 } else
2052                         (void)fprintf(stderr, "%s: ", program_name);
2053                 dlt = pcap_datalink(pd);
2054                 dlt_name = pcap_datalink_val_to_name(dlt);
2055                 if (dlt_name == NULL) {
2056                         (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
2057                             device, dlt, snaplen);
2058                 } else {
2059                         (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2060                             device, dlt_name,
2061                             pcap_datalink_val_to_description(dlt), snaplen);
2062                 }
2063                 (void)fflush(stderr);
2064         }
2065 #endif /* WIN32 */
2066
2067 #ifdef __FreeBSD__
2068         cansandbox = (VFileName == NULL && zflag == NULL);
2069 #ifdef HAVE_CASPER
2070         cansandbox = (cansandbox && (nflag || capdns != NULL));
2071 #else
2072         cansandbox = (cansandbox && nflag);
2073 #endif
2074         if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
2075                 error("unable to enter the capability mode");
2076 #endif  /* __FreeBSD__ */
2077
2078         do {
2079                 status = pcap_loop(pd, cnt, callback, pcap_userdata);
2080                 if (WFileName == NULL) {
2081                         /*
2082                          * We're printing packets.  Flush the printed output,
2083                          * so it doesn't get intermingled with error output.
2084                          */
2085                         if (status == -2) {
2086                                 /*
2087                                  * We got interrupted, so perhaps we didn't
2088                                  * manage to finish a line we were printing.
2089                                  * Print an extra newline, just in case.
2090                                  */
2091                                 putchar('\n');
2092                         }
2093                         (void)fflush(stdout);
2094                 }
2095                 if (status == -2) {
2096                         /*
2097                          * We got interrupted. If we are reading multiple
2098                          * files (via -V) set these so that we stop.
2099                          */
2100                         VFileName = NULL;
2101                         ret = NULL;
2102                 }
2103                 if (status == -1) {
2104                         /*
2105                          * Error.  Report it.
2106                          */
2107                         (void)fprintf(stderr, "%s: pcap_loop: %s\n",
2108                             program_name, pcap_geterr(pd));
2109                 }
2110                 if (RFileName == NULL) {
2111                         /*
2112                          * We're doing a live capture.  Report the capture
2113                          * statistics.
2114                          */
2115                         info(1);
2116                 }
2117                 pcap_close(pd);
2118                 if (VFileName != NULL) {
2119                         ret = get_next_file(VFile, VFileLine);
2120                         if (ret) {
2121                                 RFileName = VFileLine;
2122                                 pd = pcap_open_offline(RFileName, ebuf);
2123                                 if (pd == NULL)
2124                                         error("%s", ebuf);
2125 #ifdef HAVE_CASPER
2126                                 cap_rights_init(&rights, CAP_READ);
2127                                 if (cap_rights_limit(fileno(pcap_file(pd)),
2128                                     &rights) < 0 && errno != ENOSYS) {
2129                                         error("unable to limit pcap descriptor");
2130                                 }
2131 #endif
2132                                 new_dlt = pcap_datalink(pd);
2133                                 if (WFileName && new_dlt != dlt)
2134                                         error("%s: new dlt does not match original", RFileName);
2135                                 printinfo = get_print_info(new_dlt);
2136                                 dlt_name = pcap_datalink_val_to_name(new_dlt);
2137                                 if (dlt_name == NULL) {
2138                                         fprintf(stderr, "reading from file %s, link-type %u\n",
2139                                         RFileName, new_dlt);
2140                                 } else {
2141                                         fprintf(stderr,
2142                                         "reading from file %s, link-type %s (%s)\n",
2143                                         RFileName, dlt_name,
2144                                         pcap_datalink_val_to_description(new_dlt));
2145                                 }
2146                                 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2147                                         error("%s", pcap_geterr(pd));
2148                                 if (pcap_setfilter(pd, &fcode) < 0)
2149                                         error("%s", pcap_geterr(pd));
2150                         }
2151                 }
2152         }
2153         while (ret != NULL);
2154
2155         free(cmdbuf);
2156         exit(status == -1 ? 1 : 0);
2157 }
2158
2159 /* make a clean exit on interrupts */
2160 static RETSIGTYPE
2161 cleanup(int signo _U_)
2162 {
2163 #ifdef USE_WIN32_MM_TIMER
2164         if (timer_id)
2165                 timeKillEvent(timer_id);
2166         timer_id = 0;
2167 #elif defined(HAVE_ALARM)
2168         alarm(0);
2169 #endif
2170
2171 #ifdef HAVE_PCAP_BREAKLOOP
2172         /*
2173          * We have "pcap_breakloop()"; use it, so that we do as little
2174          * as possible in the signal handler (it's probably not safe
2175          * to do anything with standard I/O streams in a signal handler -
2176          * the ANSI C standard doesn't say it is).
2177          */
2178         pcap_breakloop(pd);
2179 #else
2180         /*
2181          * We don't have "pcap_breakloop()"; this isn't safe, but
2182          * it's the best we can do.  Print the summary if we're
2183          * not reading from a savefile - i.e., if we're doing a
2184          * live capture - and exit.
2185          */
2186         if (pd != NULL && pcap_file(pd) == NULL) {
2187                 /*
2188                  * We got interrupted, so perhaps we didn't
2189                  * manage to finish a line we were printing.
2190                  * Print an extra newline, just in case.
2191                  */
2192                 putchar('\n');
2193                 (void)fflush(stdout);
2194                 info(1);
2195         }
2196         exit(0);
2197 #endif
2198 }
2199
2200 /*
2201   On windows, we do not use a fork, so we do not care less about
2202   waiting a child processes to die
2203  */
2204 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2205 static RETSIGTYPE
2206 child_cleanup(int signo _U_)
2207 {
2208   wait(NULL);
2209 }
2210 #endif /* HAVE_FORK && HAVE_VFORK */
2211
2212 static void
2213 info(register int verbose)
2214 {
2215         struct pcap_stat stat;
2216
2217         /*
2218          * Older versions of libpcap didn't set ps_ifdrop on some
2219          * platforms; initialize it to 0 to handle that.
2220          */
2221         stat.ps_ifdrop = 0;
2222         if (pcap_stats(pd, &stat) < 0) {
2223                 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2224                 infoprint = 0;
2225                 return;
2226         }
2227
2228         if (!verbose)
2229                 fprintf(stderr, "%s: ", program_name);
2230
2231         (void)fprintf(stderr, "%u packet%s captured", packets_captured,
2232             PLURAL_SUFFIX(packets_captured));
2233         if (!verbose)
2234                 fputs(", ", stderr);
2235         else
2236                 putc('\n', stderr);
2237         (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
2238             PLURAL_SUFFIX(stat.ps_recv));
2239         if (!verbose)
2240                 fputs(", ", stderr);
2241         else
2242                 putc('\n', stderr);
2243         (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
2244             PLURAL_SUFFIX(stat.ps_drop));
2245         if (stat.ps_ifdrop != 0) {
2246                 if (!verbose)
2247                         fputs(", ", stderr);
2248                 else
2249                         putc('\n', stderr);
2250                 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
2251                     stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
2252         } else
2253                 putc('\n', stderr);
2254         infoprint = 0;
2255 }
2256
2257 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2258 static void
2259 compress_savefile(const char *filename)
2260 {
2261 # ifdef HAVE_FORK
2262         if (fork())
2263 # else
2264         if (vfork())
2265 # endif
2266                 return;
2267         /*
2268          * Set to lowest priority so that this doesn't disturb the capture
2269          */
2270 #ifdef NZERO
2271         setpriority(PRIO_PROCESS, 0, NZERO - 1);
2272 #else
2273         setpriority(PRIO_PROCESS, 0, 19);
2274 #endif
2275         if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2276                 fprintf(stderr,
2277                         "compress_savefile:execlp(%s, %s): %s\n",
2278                         zflag,
2279                         filename,
2280                         strerror(errno));
2281 # ifdef HAVE_FORK
2282         exit(1);
2283 # else
2284         _exit(1);
2285 # endif
2286 }
2287 #else  /* HAVE_FORK && HAVE_VFORK */
2288 static void
2289 compress_savefile(const char *filename)
2290 {
2291         fprintf(stderr,
2292                 "compress_savefile failed. Functionality not implemented under your system\n");
2293 }
2294 #endif /* HAVE_FORK && HAVE_VFORK */
2295
2296 static void
2297 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2298 {
2299         struct dump_info *dump_info;
2300
2301         ++packets_captured;
2302
2303         ++infodelay;
2304
2305         dump_info = (struct dump_info *)user;
2306
2307         /*
2308          * XXX - this won't force the file to rotate on the specified time
2309          * boundary, but it will rotate on the first packet received after the
2310          * specified Gflag number of seconds. Note: if a Gflag time boundary
2311          * and a Cflag size boundary coincide, the time rotation will occur
2312          * first thereby cancelling the Cflag boundary (since the file should
2313          * be 0).
2314          */
2315         if (Gflag != 0) {
2316                 /* Check if it is time to rotate */
2317                 time_t t;
2318
2319                 /* Get the current time */
2320                 if ((t = time(NULL)) == (time_t)-1) {
2321                         error("dump_and_trunc_packet: can't get current_time: %s",
2322                             pcap_strerror(errno));
2323                 }
2324
2325
2326                 /* If the time is greater than the specified window, rotate */
2327                 if (t - Gflag_time >= Gflag) {
2328 #ifdef __FreeBSD__
2329                         FILE *fp;
2330                         int fd;
2331 #endif
2332
2333                         /* Update the Gflag_time */
2334                         Gflag_time = t;
2335                         /* Update Gflag_count */
2336                         Gflag_count++;
2337                         /*
2338                          * Close the current file and open a new one.
2339                          */
2340                         pcap_dump_close(dump_info->p);
2341
2342                         /*
2343                          * Compress the file we just closed, if the user asked for it
2344                          */
2345                         if (zflag != NULL)
2346                                 compress_savefile(dump_info->CurrentFileName);
2347
2348                         /*
2349                          * Check to see if we've exceeded the Wflag (when
2350                          * not using Cflag).
2351                          */
2352                         if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2353                                 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2354                                     Wflag);
2355                                 exit(0);
2356                                 /* NOTREACHED */
2357                         }
2358                         if (dump_info->CurrentFileName != NULL)
2359                                 free(dump_info->CurrentFileName);
2360                         /* Allocate space for max filename + \0. */
2361                         dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2362                         if (dump_info->CurrentFileName == NULL)
2363                                 error("dump_packet_and_trunc: malloc");
2364                         /*
2365                          * Gflag was set otherwise we wouldn't be here. Reset the count
2366                          * so multiple files would end with 1,2,3 in the filename.
2367                          * The counting is handled with the -C flow after this.
2368                          */
2369                         Cflag_count = 0;
2370
2371                         /*
2372                          * This is always the first file in the Cflag
2373                          * rotation: e.g. 0
2374                          * We also don't need numbering if Cflag is not set.
2375                          */
2376                         if (Cflag != 0)
2377                                 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2378                                     WflagChars);
2379                         else
2380                                 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2381
2382 #ifdef HAVE_LIBCAP_NG
2383                         capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2384                         capng_apply(CAPNG_SELECT_BOTH);
2385 #endif /* HAVE_LIBCAP_NG */
2386 #ifdef __FreeBSD__
2387                         fd = openat(dump_info->dirfd,
2388                             dump_info->CurrentFileName,
2389                             O_CREAT | O_WRONLY | O_TRUNC, 0644);
2390                         if (fd < 0) {
2391                                 error("unable to open file %s",
2392                                     dump_info->CurrentFileName);
2393                         }
2394                         fp = fdopen(fd, "w");
2395                         if (fp == NULL) {
2396                                 error("unable to fdopen file %s",
2397                                     dump_info->CurrentFileName);
2398                         }
2399                         dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2400 #else   /* !__FreeBSD__ */
2401                         dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2402 #endif
2403 #ifdef HAVE_LIBCAP_NG
2404                         capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2405                         capng_apply(CAPNG_SELECT_BOTH);
2406 #endif /* HAVE_LIBCAP_NG */
2407                         if (dump_info->p == NULL)
2408                                 error("%s", pcap_geterr(pd));
2409 #ifdef __FreeBSD__
2410                         set_dumper_capsicum_rights(dump_info->p);
2411 #endif
2412                 }
2413         }
2414
2415         /*
2416          * XXX - this won't prevent capture files from getting
2417          * larger than Cflag - the last packet written to the
2418          * file could put it over Cflag.
2419          */
2420         if (Cflag != 0) {
2421                 long size = pcap_dump_ftell(dump_info->p);
2422
2423                 if (size == -1)
2424                         error("ftell fails on output file");
2425                 if (size > Cflag) {
2426 #ifdef __FreeBSD__
2427                         FILE *fp;
2428                         int fd;
2429 #endif
2430
2431                         /*
2432                          * Close the current file and open a new one.
2433                          */
2434                         pcap_dump_close(dump_info->p);
2435
2436                         /*
2437                          * Compress the file we just closed, if the user
2438                          * asked for it.
2439                          */
2440                         if (zflag != NULL)
2441                                 compress_savefile(dump_info->CurrentFileName);
2442
2443                         Cflag_count++;
2444                         if (Wflag > 0) {
2445                                 if (Cflag_count >= Wflag)
2446                                         Cflag_count = 0;
2447                         }
2448                         if (dump_info->CurrentFileName != NULL)
2449                                 free(dump_info->CurrentFileName);
2450                         dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2451                         if (dump_info->CurrentFileName == NULL)
2452                                 error("dump_packet_and_trunc: malloc");
2453                         MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2454 #ifdef HAVE_LIBCAP_NG
2455                         capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2456                         capng_apply(CAPNG_SELECT_BOTH);
2457 #endif /* HAVE_LIBCAP_NG */
2458 #ifdef __FreeBSD__
2459                         fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2460                             O_CREAT | O_WRONLY | O_TRUNC, 0644);
2461                         if (fd < 0) {
2462                                 error("unable to open file %s",
2463                                     dump_info->CurrentFileName);
2464                         }
2465                         fp = fdopen(fd, "w");
2466                         if (fp == NULL) {
2467                                 error("unable to fdopen file %s",
2468                                     dump_info->CurrentFileName);
2469                         }
2470                         dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2471 #else   /* !__FreeBSD__ */
2472                         dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2473 #endif
2474 #ifdef HAVE_LIBCAP_NG
2475                         capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2476                         capng_apply(CAPNG_SELECT_BOTH);
2477 #endif /* HAVE_LIBCAP_NG */
2478                         if (dump_info->p == NULL)
2479                                 error("%s", pcap_geterr(pd));
2480 #ifdef __FreeBSD__
2481                         set_dumper_capsicum_rights(dump_info->p);
2482 #endif
2483                 }
2484         }
2485
2486         pcap_dump((u_char *)dump_info->p, h, sp);
2487 #ifdef HAVE_PCAP_DUMP_FLUSH
2488         if (Uflag)
2489                 pcap_dump_flush(dump_info->p);
2490 #endif
2491
2492         --infodelay;
2493         if (infoprint)
2494                 info(0);
2495 }
2496
2497 static void
2498 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2499 {
2500         ++packets_captured;
2501
2502         ++infodelay;
2503
2504         pcap_dump(user, h, sp);
2505 #ifdef HAVE_PCAP_DUMP_FLUSH
2506         if (Uflag)
2507                 pcap_dump_flush((pcap_dumper_t *)user);
2508 #endif
2509
2510         --infodelay;
2511         if (infoprint)
2512                 info(0);
2513 }
2514
2515 static void
2516 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2517 {
2518         struct print_info *print_info;
2519         u_int hdrlen;
2520         netdissect_options *ndo;
2521
2522         ++packets_captured;
2523
2524         ++infodelay;
2525
2526         print_info = (struct print_info *)user;
2527         ndo = print_info->ndo;
2528
2529         if(ndo->ndo_packet_number)
2530                 ND_PRINT((ndo, "%5u  ", packets_captured));
2531
2532         ts_print(ndo, &h->ts);
2533
2534         /*
2535          * Some printers want to check that they're not walking off the
2536          * end of the packet.
2537          * Rather than pass it all the way down, we set this member
2538          * of the netdissect_options structure.
2539          */
2540         ndo->ndo_snapend = sp + h->caplen;
2541
2542         if(print_info->ndo_type) {
2543                 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
2544         } else {
2545                 hdrlen = (*print_info->p.printer)(h, sp);
2546         }
2547
2548         /*
2549          * Restore the original snapend, as a printer might have
2550          * changed it.
2551          */
2552         ndo->ndo_snapend = sp + h->caplen;
2553         if (ndo->ndo_Xflag) {
2554                 /*
2555                  * Print the raw packet data in hex and ASCII.
2556                  */
2557                 if (ndo->ndo_Xflag > 1) {
2558                         /*
2559                          * Include the link-layer header.
2560                          */
2561                         hex_and_ascii_print(ndo, "\n\t", sp, h->caplen);
2562                 } else {
2563                         /*
2564                          * Don't include the link-layer header - and if
2565                          * we have nothing past the link-layer header,
2566                          * print nothing.
2567                          */
2568                         if (h->caplen > hdrlen)
2569                                 hex_and_ascii_print(ndo, "\n\t", sp + hdrlen,
2570                                     h->caplen - hdrlen);
2571                 }
2572         } else if (ndo->ndo_xflag) {
2573                 /*
2574                  * Print the raw packet data in hex.
2575                  */
2576                 if (ndo->ndo_xflag > 1) {
2577                         /*
2578                          * Include the link-layer header.
2579                          */
2580                         hex_print(ndo, "\n\t", sp, h->caplen);
2581                 } else {
2582                         /*
2583                          * Don't include the link-layer header - and if
2584                          * we have nothing past the link-layer header,
2585                          * print nothing.
2586                          */
2587                         if (h->caplen > hdrlen)
2588                                 hex_print(ndo, "\n\t", sp + hdrlen,
2589                                           h->caplen - hdrlen);
2590                 }
2591         } else if (ndo->ndo_Aflag) {
2592                 /*
2593                  * Print the raw packet data in ASCII.
2594                  */
2595                 if (ndo->ndo_Aflag > 1) {
2596                         /*
2597                          * Include the link-layer header.
2598                          */
2599                         ascii_print(ndo, sp, h->caplen);
2600                 } else {
2601                         /*
2602                          * Don't include the link-layer header - and if
2603                          * we have nothing past the link-layer header,
2604                          * print nothing.
2605                          */
2606                         if (h->caplen > hdrlen)
2607                                 ascii_print(ndo, sp + hdrlen, h->caplen - hdrlen);
2608                 }
2609         }
2610
2611         putchar('\n');
2612
2613         --infodelay;
2614         if (infoprint)
2615                 info(0);
2616 }
2617
2618 #ifdef WIN32
2619         /*
2620          * XXX - there should really be libpcap calls to get the version
2621          * number as a string (the string would be generated from #defines
2622          * at run time, so that it's not generated from string constants
2623          * in the library, as, on many UNIX systems, those constants would
2624          * be statically linked into the application executable image, and
2625          * would thus reflect the version of libpcap on the system on
2626          * which the application was *linked*, not the system on which it's
2627          * *running*.
2628          *
2629          * That routine should be documented, unlike the "version[]"
2630          * string, so that UNIX vendors providing their own libpcaps
2631          * don't omit it (as a couple of vendors have...).
2632          *
2633          * Packet.dll should perhaps also export a routine to return the
2634          * version number of the Packet.dll code, to supply the
2635          * "Wpcap_version" information on Windows.
2636          */
2637         char WDversion[]="current-git.tcpdump.org";
2638 #if !defined(HAVE_GENERATED_VERSION)
2639         char version[]="current-git.tcpdump.org";
2640 #endif
2641         char pcap_version[]="current-git.tcpdump.org";
2642         char Wpcap_version[]="3.1";
2643 #endif
2644
2645 /*
2646  * By default, print the specified data out in hex and ASCII.
2647  */
2648 static void
2649 ndo_default_print(netdissect_options *ndo, const u_char *bp, u_int length)
2650 {
2651         hex_and_ascii_print(ndo, "\n\t", bp, length); /* pass on lf and indentation string */
2652 }
2653
2654 void
2655 default_print(const u_char *bp, u_int length)
2656 {
2657         ndo_default_print(gndo, bp, length);
2658 }
2659
2660 #ifdef SIGNAL_REQ_INFO
2661 RETSIGTYPE requestinfo(int signo _U_)
2662 {
2663         if (infodelay)
2664                 ++infoprint;
2665         else
2666                 info(0);
2667 }
2668 #endif
2669
2670 /*
2671  * Called once each second in verbose mode while dumping to file
2672  */
2673 #ifdef USE_WIN32_MM_TIMER
2674 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2675                                   DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2676 {
2677         struct pcap_stat stat;
2678
2679         if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2680                 fprintf(stderr, "Got %u\r", packets_captured);
2681 }
2682 #elif defined(HAVE_ALARM)
2683 static void verbose_stats_dump(int sig _U_)
2684 {
2685         struct pcap_stat stat;
2686
2687         if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2688                 fprintf(stderr, "Got %u\r", packets_captured);
2689         alarm(1);
2690 }
2691 #endif
2692
2693 USES_APPLE_DEPRECATED_API
2694 static void
2695 print_version(void)
2696 {
2697         extern char version[];
2698 #ifndef HAVE_PCAP_LIB_VERSION
2699 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
2700         extern char pcap_version[];
2701 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2702         static char pcap_version[] = "unknown";
2703 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2704 #endif /* HAVE_PCAP_LIB_VERSION */
2705
2706 #ifdef HAVE_PCAP_LIB_VERSION
2707 #ifdef WIN32
2708         (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2709 #else /* WIN32 */
2710         (void)fprintf(stderr, "%s version %s\n", program_name, version);
2711 #endif /* WIN32 */
2712         (void)fprintf(stderr, "%s\n",pcap_lib_version());
2713 #else /* HAVE_PCAP_LIB_VERSION */
2714 #ifdef WIN32
2715         (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2716         (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2717 #else /* WIN32 */
2718         (void)fprintf(stderr, "%s version %s\n", program_name, version);
2719         (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2720 #endif /* WIN32 */
2721 #endif /* HAVE_PCAP_LIB_VERSION */
2722
2723 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2724         (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2725 #endif
2726
2727 #ifdef USE_LIBSMI
2728         (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2729 #endif
2730 }
2731 USES_APPLE_RST
2732
2733 static void
2734 print_usage(void)
2735 {
2736         print_version();
2737         (void)fprintf(stderr,
2738 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2739         (void)fprintf(stderr,
2740 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2741         (void)fprintf(stderr,
2742 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2743 #ifdef HAVE_PCAP_SETDIRECTION
2744         (void)fprintf(stderr,
2745 "\t\t[ -Q in|out|inout ]\n");
2746 #endif
2747         (void)fprintf(stderr,
2748 "\t\t[ -r file ] [ -s snaplen ] ");
2749 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2750         (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2751         (void)fprintf(stderr,
2752 "\t\t");
2753 #endif
2754 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2755         (void)fprintf(stderr, "[ --immediate-mode ] ");
2756 #endif
2757         (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2758         (void)fprintf(stderr,
2759 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2760         (void)fprintf(stderr,
2761 "\t\t[ -Z user ] [ expression ]\n");
2762 }
2763
2764
2765
2766 /* VARARGS */
2767 static void
2768 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
2769 {
2770         va_list ap;
2771
2772         (void)fprintf(stderr, "%s: ", program_name);
2773         va_start(ap, fmt);
2774         (void)vfprintf(stderr, fmt, ap);
2775         va_end(ap);
2776         if (*fmt) {
2777                 fmt += strlen(fmt);
2778                 if (fmt[-1] != '\n')
2779                         (void)fputc('\n', stderr);
2780         }
2781         exit(1);
2782         /* NOTREACHED */
2783 }
2784
2785 /* VARARGS */
2786 static void
2787 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2788 {
2789         va_list ap;
2790
2791         (void)fprintf(stderr, "%s: WARNING: ", program_name);
2792         va_start(ap, fmt);
2793         (void)vfprintf(stderr, fmt, ap);
2794         va_end(ap);
2795         if (*fmt) {
2796                 fmt += strlen(fmt);
2797                 if (fmt[-1] != '\n')
2798                         (void)fputc('\n', stderr);
2799         }
2800 }
2801 /*
2802  * Local Variables:
2803  * c-style: whitesmith
2804  * c-basic-offset: 8
2805  * End:
2806  */