]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/tcpdump/tcpdump.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / tcpdump / tcpdump.c
1 /*
2  * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that: (1) source code distributions
7  * retain the above copyright notice and this paragraph in its entirety, (2)
8  * distributions including binary code include the above copyright notice and
9  * this paragraph in its entirety in the documentation or other materials
10  * provided with the distribution, and (3) all advertising materials mentioning
11  * features or use of this software display the following acknowledgement:
12  * ``This product includes software developed by the University of California,
13  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14  * the University nor the names of its contributors may be used to endorse
15  * or promote products derived from this software without specific prior
16  * written permission.
17  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20  *
21  * Support for splitting captures into multiple files with a maximum
22  * file size:
23  *
24  * Copyright (c) 2001
25  *      Seth Webster <swebster@sst.ll.mit.edu>
26  */
27
28 #ifndef lint
29 static const char copyright[] _U_ =
30     "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
31 The Regents of the University of California.  All rights reserved.\n";
32 static const char rcsid[] _U_ =
33     "@(#) $Header: /tcpdump/master/tcpdump/tcpdump.c,v 1.283 2008-09-25 21:45:50 guy Exp $ (LBL)";
34 #endif
35
36 /* $FreeBSD$ */
37
38 /*
39  * tcpdump - monitor tcp/ip traffic on an ethernet.
40  *
41  * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
42  * Mercilessly hacked and occasionally improved since then via the
43  * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
44  */
45
46 #ifdef HAVE_CONFIG_H
47 #include "config.h"
48 #endif
49
50 #include <tcpdump-stdinc.h>
51
52 #ifdef WIN32
53 #include "getopt.h"
54 #include "w32_fzs.h"
55 extern int strcasecmp (const char *__s1, const char *__s2);
56 extern int SIZE_BUF;
57 #define off_t long
58 #define uint UINT
59 #endif /* WIN32 */
60
61 #ifdef HAVE_SMI_H
62 #include <smi.h>
63 #endif
64
65 #include <pcap.h>
66 #include <signal.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <limits.h>
71 #ifdef __FreeBSD__
72 #include <sys/capability.h>
73 #include <sys/ioccom.h>
74 #include <sys/types.h>
75 #include <sys/sysctl.h>
76 #include <net/bpf.h>
77 #include <fcntl.h>
78 #include <libgen.h>
79 #endif  /* __FreeBSD__ */
80 #ifndef WIN32
81 #include <sys/wait.h>
82 #include <sys/resource.h>
83 #include <pwd.h>
84 #include <grp.h>
85 #include <errno.h>
86 #endif /* WIN32 */
87
88 /* capabilities convinience library */
89 #ifdef HAVE_CAP_NG_H
90 #include <cap-ng.h>
91 #endif /* HAVE_CAP_NG_H */
92
93 #include "netdissect.h"
94 #include "interface.h"
95 #include "addrtoname.h"
96 #include "machdep.h"
97 #include "setsignal.h"
98 #include "gmt2local.h"
99 #include "pcap-missing.h"
100
101 #ifndef PATH_MAX
102 #define PATH_MAX 1024
103 #endif
104
105 #ifdef SIGINFO
106 #define SIGNAL_REQ_INFO SIGINFO
107 #elif SIGUSR1
108 #define SIGNAL_REQ_INFO SIGUSR1
109 #endif
110
111 netdissect_options Gndo;
112 netdissect_options *gndo = &Gndo;
113
114 static int dflag;                       /* print filter code */
115 static int Lflag;                       /* list available data link types and exit */
116 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
117 static int Jflag;                       /* list available time stamp types */
118 #endif
119 static char *zflag = NULL;              /* compress each savefile using a specified command (like gzip or bzip2) */
120
121 static int infodelay;
122 static int infoprint;
123
124 char *program_name;
125
126 int32_t thiszone;               /* seconds offset from gmt to local time */
127
128 /* Forwards */
129 static RETSIGTYPE cleanup(int);
130 static RETSIGTYPE child_cleanup(int);
131 static void usage(void) __attribute__((noreturn));
132 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
133
134 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
135 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
136 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
137 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
138 static void droproot(const char *, const char *);
139 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
140      __attribute__ ((noreturn, format (printf, 2, 3)));
141 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
142
143 #ifdef SIGNAL_REQ_INFO
144 RETSIGTYPE requestinfo(int);
145 #endif
146
147 #if defined(USE_WIN32_MM_TIMER)
148   #include <MMsystem.h>
149   static UINT timer_id;
150   static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
151 #elif defined(HAVE_ALARM)
152   static void verbose_stats_dump(int sig);
153 #endif
154
155 static void info(int);
156 static u_int packets_captured;
157
158 struct printer {
159         if_printer f;
160         int type;
161 };
162
163
164 struct ndo_printer {
165         if_ndo_printer f;
166         int type;
167 };
168
169
170 static struct printer printers[] = {
171         { arcnet_if_print,      DLT_ARCNET },
172 #ifdef DLT_ARCNET_LINUX
173         { arcnet_linux_if_print, DLT_ARCNET_LINUX },
174 #endif
175         { token_if_print,       DLT_IEEE802 },
176 #ifdef DLT_LANE8023
177         { lane_if_print,        DLT_LANE8023 },
178 #endif
179 #ifdef DLT_CIP
180         { cip_if_print,         DLT_CIP },
181 #endif
182 #ifdef DLT_ATM_CLIP
183         { cip_if_print,         DLT_ATM_CLIP },
184 #endif
185         { sl_if_print,          DLT_SLIP },
186 #ifdef DLT_SLIP_BSDOS
187         { sl_bsdos_if_print,    DLT_SLIP_BSDOS },
188 #endif
189         { ppp_if_print,         DLT_PPP },
190 #ifdef DLT_PPP_WITHDIRECTION
191         { ppp_if_print,         DLT_PPP_WITHDIRECTION },
192 #endif
193 #ifdef DLT_PPP_BSDOS
194         { ppp_bsdos_if_print,   DLT_PPP_BSDOS },
195 #endif
196         { fddi_if_print,        DLT_FDDI },
197         { null_if_print,        DLT_NULL },
198 #ifdef DLT_LOOP
199         { null_if_print,        DLT_LOOP },
200 #endif
201         { raw_if_print,         DLT_RAW },
202         { atm_if_print,         DLT_ATM_RFC1483 },
203 #ifdef DLT_C_HDLC
204         { chdlc_if_print,       DLT_C_HDLC },
205 #endif
206 #ifdef DLT_HDLC
207         { chdlc_if_print,       DLT_HDLC },
208 #endif
209 #ifdef DLT_PPP_SERIAL
210         { ppp_hdlc_if_print,    DLT_PPP_SERIAL },
211 #endif
212 #ifdef DLT_PPP_ETHER
213         { pppoe_if_print,       DLT_PPP_ETHER },
214 #endif
215 #ifdef DLT_LINUX_SLL
216         { sll_if_print,         DLT_LINUX_SLL },
217 #endif
218 #ifdef DLT_IEEE802_11
219         { ieee802_11_if_print,  DLT_IEEE802_11},
220 #endif
221 #ifdef DLT_LTALK
222         { ltalk_if_print,       DLT_LTALK },
223 #endif
224 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
225         { pflog_if_print,       DLT_PFLOG },
226 #endif
227 #ifdef DLT_FR
228         { fr_if_print,          DLT_FR },
229 #endif
230 #ifdef DLT_FRELAY
231         { fr_if_print,          DLT_FRELAY },
232 #endif
233 #ifdef DLT_SUNATM
234         { sunatm_if_print,      DLT_SUNATM },
235 #endif
236 #ifdef DLT_IP_OVER_FC
237         { ipfc_if_print,        DLT_IP_OVER_FC },
238 #endif
239 #ifdef DLT_PRISM_HEADER
240         { prism_if_print,       DLT_PRISM_HEADER },
241 #endif
242 #ifdef DLT_IEEE802_11_RADIO
243         { ieee802_11_radio_if_print,    DLT_IEEE802_11_RADIO },
244 #endif
245 #ifdef DLT_ENC
246         { enc_if_print,         DLT_ENC },
247 #endif
248 #ifdef DLT_SYMANTEC_FIREWALL
249         { symantec_if_print,    DLT_SYMANTEC_FIREWALL },
250 #endif
251 #ifdef DLT_APPLE_IP_OVER_IEEE1394
252         { ap1394_if_print,      DLT_APPLE_IP_OVER_IEEE1394 },
253 #endif
254 #ifdef DLT_IEEE802_11_RADIO_AVS
255         { ieee802_11_radio_avs_if_print,        DLT_IEEE802_11_RADIO_AVS },
256 #endif
257 #ifdef DLT_JUNIPER_ATM1
258         { juniper_atm1_print,   DLT_JUNIPER_ATM1 },
259 #endif
260 #ifdef DLT_JUNIPER_ATM2
261         { juniper_atm2_print,   DLT_JUNIPER_ATM2 },
262 #endif
263 #ifdef DLT_JUNIPER_MFR
264         { juniper_mfr_print,    DLT_JUNIPER_MFR },
265 #endif
266 #ifdef DLT_JUNIPER_MLFR
267         { juniper_mlfr_print,   DLT_JUNIPER_MLFR },
268 #endif
269 #ifdef DLT_JUNIPER_MLPPP
270         { juniper_mlppp_print,  DLT_JUNIPER_MLPPP },
271 #endif
272 #ifdef DLT_JUNIPER_PPPOE
273         { juniper_pppoe_print,  DLT_JUNIPER_PPPOE },
274 #endif
275 #ifdef DLT_JUNIPER_PPPOE_ATM
276         { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
277 #endif
278 #ifdef DLT_JUNIPER_GGSN
279         { juniper_ggsn_print,   DLT_JUNIPER_GGSN },
280 #endif
281 #ifdef DLT_JUNIPER_ES
282         { juniper_es_print,     DLT_JUNIPER_ES },
283 #endif
284 #ifdef DLT_JUNIPER_MONITOR
285         { juniper_monitor_print, DLT_JUNIPER_MONITOR },
286 #endif
287 #ifdef DLT_JUNIPER_SERVICES
288         { juniper_services_print, DLT_JUNIPER_SERVICES },
289 #endif
290 #ifdef DLT_JUNIPER_ETHER
291         { juniper_ether_print,  DLT_JUNIPER_ETHER },
292 #endif
293 #ifdef DLT_JUNIPER_PPP
294         { juniper_ppp_print,    DLT_JUNIPER_PPP },
295 #endif
296 #ifdef DLT_JUNIPER_FRELAY
297         { juniper_frelay_print, DLT_JUNIPER_FRELAY },
298 #endif
299 #ifdef DLT_JUNIPER_CHDLC
300         { juniper_chdlc_print,  DLT_JUNIPER_CHDLC },
301 #endif
302 #ifdef DLT_MFR
303         { mfr_if_print,         DLT_MFR },
304 #endif
305 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
306         { bt_if_print,          DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
307 #endif
308 #ifdef HAVE_PCAP_USB_H
309 #ifdef DLT_USB_LINUX
310         { usb_linux_48_byte_print, DLT_USB_LINUX},
311 #endif /* DLT_USB_LINUX */
312 #ifdef DLT_USB_LINUX_MMAPPED
313         { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
314 #endif /* DLT_USB_LINUX_MMAPPED */
315 #endif /* HAVE_PCAP_USB_H */
316 #ifdef DLT_IPV4
317         { raw_if_print,         DLT_IPV4 },
318 #endif
319 #ifdef DLT_IPV6
320         { raw_if_print,         DLT_IPV6 },
321 #endif
322         { NULL,                 0 },
323 };
324
325 static struct ndo_printer ndo_printers[] = {
326         { ether_if_print,       DLT_EN10MB },
327 #ifdef DLT_IPNET
328         { ipnet_if_print,       DLT_IPNET },
329 #endif
330 #ifdef DLT_IEEE802_15_4
331         { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
332 #endif
333 #ifdef DLT_IEEE802_15_4_NOFCS
334         { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
335 #endif
336 #ifdef DLT_PPI
337         { ppi_if_print,         DLT_PPI },
338 #endif
339 #ifdef DLT_NETANALYZER
340         { netanalyzer_if_print, DLT_NETANALYZER },
341 #endif
342 #ifdef DLT_NETANALYZER_TRANSPARENT
343         { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
344 #endif
345         { NULL,                 0 },
346 };
347
348 if_printer
349 lookup_printer(int type)
350 {
351         struct printer *p;
352
353         for (p = printers; p->f; ++p)
354                 if (type == p->type)
355                         return p->f;
356
357         return NULL;
358         /* NOTREACHED */
359 }
360
361 if_ndo_printer
362 lookup_ndo_printer(int type)
363 {
364         struct ndo_printer *p;
365
366         for (p = ndo_printers; p->f; ++p)
367                 if (type == p->type)
368                         return p->f;
369
370         return NULL;
371         /* NOTREACHED */
372 }
373
374 static pcap_t *pd;
375
376 static int supports_monitor_mode;
377
378 extern int optind;
379 extern int opterr;
380 extern char *optarg;
381
382 struct print_info {
383         netdissect_options *ndo;
384         union {
385                 if_printer     printer;
386                 if_ndo_printer ndo_printer;
387         } p;
388         int ndo_type;
389 };
390
391 struct dump_info {
392         char    *WFileName;
393         char    *CurrentFileName;
394         pcap_t  *pd;
395         pcap_dumper_t *p;
396 #ifdef __FreeBSD__
397         int     dirfd;
398 #endif
399 };
400
401 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
402 static void
403 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
404 {
405         int n_tstamp_types;
406         int *tstamp_types = 0;
407         const char *tstamp_type_name;
408         int i;
409
410         n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
411         if (n_tstamp_types < 0)
412                 error("%s", pcap_geterr(pd));
413
414         if (n_tstamp_types == 0) {
415                 fprintf(stderr, "Time stamp type cannot be set for %s\n",
416                     device);
417                 exit(0);
418         }
419         fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
420             device);
421         for (i = 0; i < n_tstamp_types; i++) {
422                 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
423                 if (tstamp_type_name != NULL) {
424                         (void) fprintf(stderr, "  %s (%s)\n", tstamp_type_name,
425                             pcap_tstamp_type_val_to_description(tstamp_types[i]));
426                 } else {
427                         (void) fprintf(stderr, "  %d\n", tstamp_types[i]);
428                 }
429         }
430         pcap_free_tstamp_types(tstamp_types);
431         exit(0);
432 }
433 #endif
434
435 static void
436 show_dlts_and_exit(const char *device, pcap_t *pd)
437 {
438         int n_dlts;
439         int *dlts = 0;
440         const char *dlt_name;
441
442         n_dlts = pcap_list_datalinks(pd, &dlts);
443         if (n_dlts < 0)
444                 error("%s", pcap_geterr(pd));
445         else if (n_dlts == 0 || !dlts)
446                 error("No data link types.");
447
448         /*
449          * If the interface is known to support monitor mode, indicate
450          * whether these are the data link types available when not in
451          * monitor mode, if -I wasn't specified, or when in monitor mode,
452          * when -I was specified (the link-layer types available in
453          * monitor mode might be different from the ones available when
454          * not in monitor mode).
455          */
456         if (supports_monitor_mode)
457                 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
458                     device,
459                     Iflag ? "when in monitor mode" : "when not in monitor mode");
460         else
461                 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
462                     device);
463
464         while (--n_dlts >= 0) {
465                 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
466                 if (dlt_name != NULL) {
467                         (void) fprintf(stderr, "  %s (%s)", dlt_name,
468                             pcap_datalink_val_to_description(dlts[n_dlts]));
469
470                         /*
471                          * OK, does tcpdump handle that type?
472                          */
473                         if (lookup_printer(dlts[n_dlts]) == NULL
474                             && lookup_ndo_printer(dlts[n_dlts]) == NULL)
475                                 (void) fprintf(stderr, " (printing not supported)");
476                         fprintf(stderr, "\n");
477                 } else {
478                         (void) fprintf(stderr, "  DLT %d (printing not supported)\n",
479                             dlts[n_dlts]);
480                 }
481         }
482 #ifdef HAVE_PCAP_FREE_DATALINKS
483         pcap_free_datalinks(dlts);
484 #endif
485         exit(0);
486 }
487
488 /*
489  * Set up flags that might or might not be supported depending on the
490  * version of libpcap we're using.
491  */
492 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
493 #define B_FLAG          "B:"
494 #define B_FLAG_USAGE    " [ -B size ]"
495 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
496 #define B_FLAG
497 #define B_FLAG_USAGE
498 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
499
500 #ifdef HAVE_PCAP_CREATE
501 #define I_FLAG          "I"
502 #else /* HAVE_PCAP_CREATE */
503 #define I_FLAG
504 #endif /* HAVE_PCAP_CREATE */
505
506 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
507 #define j_FLAG          "j:"
508 #define j_FLAG_USAGE    " [ -j tstamptype ]"
509 #define J_FLAG          "J"
510 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
511 #define j_FLAG
512 #define j_FLAG_USAGE
513 #define J_FLAG
514 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
515
516 #ifdef HAVE_PCAP_FINDALLDEVS
517 #ifndef HAVE_PCAP_IF_T
518 #undef HAVE_PCAP_FINDALLDEVS
519 #endif
520 #endif
521
522 #ifdef HAVE_PCAP_FINDALLDEVS
523 #define D_FLAG  "D"
524 #else
525 #define D_FLAG
526 #endif
527
528 #ifdef HAVE_PCAP_DUMP_FLUSH
529 #define U_FLAG  "U"
530 #else
531 #define U_FLAG
532 #endif
533
534 #ifndef WIN32
535 /* Drop root privileges and chroot if necessary */
536 static void
537 droproot(const char *username, const char *chroot_dir)
538 {
539         struct passwd *pw = NULL;
540
541         if (chroot_dir && !username) {
542                 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
543                 exit(1);
544         }
545         
546         pw = getpwnam(username);
547         if (pw) {
548                 if (chroot_dir) {
549                         if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
550                                 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
551                                     chroot_dir, pcap_strerror(errno));
552                                 exit(1);
553                         }
554                 }
555 #ifdef HAVE_CAP_NG_H
556                 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
557                 if (ret < 0) {
558                         printf("error : ret %d\n", ret);
559                 }
560                 /* We don't need CAP_SETUID and CAP_SETGID */
561                 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
562                 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
563                 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
564                 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
565                 capng_apply(CAPNG_SELECT_BOTH);
566
567 #else
568                 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
569                     setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
570                         fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
571                             username, 
572                             (unsigned long)pw->pw_uid,
573                             (unsigned long)pw->pw_gid,
574                             pcap_strerror(errno));
575                         exit(1);
576                 }
577 #endif /* HAVE_CAP_NG_H */
578         }
579         else {
580                 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
581                     username);
582                 exit(1);
583         }
584 }
585 #endif /* WIN32 */
586
587 static int
588 getWflagChars(int x)
589 {
590         int c = 0;
591
592         x -= 1;
593         while (x > 0) {
594                 c += 1;
595                 x /= 10;
596         }
597
598         return c;
599 }
600
601
602 static void
603 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
604 {
605         char *filename = malloc(PATH_MAX + 1);
606         if (filename == NULL)
607             error("Makefilename: malloc");
608
609         /* Process with strftime if Gflag is set. */
610         if (Gflag != 0) {
611           struct tm *local_tm;
612
613           /* Convert Gflag_time to a usable format */
614           if ((local_tm = localtime(&Gflag_time)) == NULL) {
615                   error("MakeTimedFilename: localtime");
616           }
617
618           /* There's no good way to detect an error in strftime since a return
619            * value of 0 isn't necessarily failure.
620            */
621           strftime(filename, PATH_MAX, orig_name, local_tm);
622         } else {
623           strncpy(filename, orig_name, PATH_MAX);
624         }
625
626         if (cnt == 0 && max_chars == 0)
627                 strncpy(buffer, filename, PATH_MAX + 1);
628         else
629                 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
630                   /* Report an error if the filename is too large */
631                   error("too many output files or filename is too long (> %d)", PATH_MAX);
632         free(filename);
633 }
634
635 static int tcpdump_printf(netdissect_options *ndo _U_,
636                           const char *fmt, ...)
637 {
638   
639   va_list args;
640   int ret;
641
642   va_start(args, fmt);
643   ret=vfprintf(stdout, fmt, args);
644   va_end(args);
645
646   return ret;
647 }
648
649 static struct print_info
650 get_print_info(int type)
651 {
652         struct print_info printinfo;
653
654         printinfo.ndo_type = 1;
655         printinfo.ndo = gndo;
656         printinfo.p.ndo_printer = lookup_ndo_printer(type);
657         if (printinfo.p.ndo_printer == NULL) {
658                 printinfo.p.printer = lookup_printer(type);
659                 printinfo.ndo_type = 0;
660                 if (printinfo.p.printer == NULL) {
661                         gndo->ndo_dltname = pcap_datalink_val_to_name(type);
662                         if (gndo->ndo_dltname != NULL)
663                                 error("packet printing is not supported for link type %s: use -w",
664                                       gndo->ndo_dltname);
665                         else
666                                 error("packet printing is not supported for link type %d: use -w", type);
667                 }
668         }
669         return (printinfo);
670 }
671
672 static char *
673 get_next_file(FILE *VFile, char *ptr)
674 {
675         char *ret;
676
677         ret = fgets(ptr, PATH_MAX, VFile);
678         if (!ret)
679                 return NULL;
680
681         if (ptr[strlen(ptr) - 1] == '\n')
682                 ptr[strlen(ptr) - 1] = '\0';
683
684         return ret;
685 }
686
687 int
688 main(int argc, char **argv)
689 {
690         register int cnt, op, i;
691         bpf_u_int32 localnet, netmask;
692         register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
693         pcap_handler callback;
694         int type;
695         int dlt;
696         int new_dlt;
697         const char *dlt_name;
698         struct bpf_program fcode;
699 #ifndef WIN32
700         RETSIGTYPE (*oldhandler)(int);
701 #endif
702         struct print_info printinfo;
703         struct dump_info dumpinfo;
704         u_char *pcap_userdata;
705         char ebuf[PCAP_ERRBUF_SIZE];
706         char VFileLine[PATH_MAX + 1];
707         char *username = NULL;
708         char *chroot_dir = NULL;
709         char *ret = NULL;
710         char *end;
711 #ifdef HAVE_PCAP_FINDALLDEVS
712         pcap_if_t *devpointer;
713         int devnum;
714 #endif
715         int status;
716         FILE *VFile;
717 #ifdef __FreeBSD__
718         cap_rights_t rights;
719         int cansandbox;
720 #endif  /* __FreeBSD__ */
721
722 #ifdef WIN32
723         if(wsockinit() != 0) return 1;
724 #endif /* WIN32 */
725
726         jflag=-1;       /* not set */
727         gndo->ndo_Oflag=1;
728         gndo->ndo_Rflag=1;
729         gndo->ndo_dlt=-1;
730         gndo->ndo_default_print=ndo_default_print;
731         gndo->ndo_printf=tcpdump_printf;
732         gndo->ndo_error=ndo_error;
733         gndo->ndo_warning=ndo_warning;
734         gndo->ndo_snaplen = DEFAULT_SNAPLEN;
735   
736         cnt = -1;
737         device = NULL;
738         infile = NULL;
739         RFileName = NULL;
740         VFileName = NULL;
741         VFile = NULL;
742         WFileName = NULL;
743         dlt = -1;
744         if ((cp = strrchr(argv[0], '/')) != NULL)
745                 program_name = cp + 1;
746         else
747                 program_name = argv[0];
748
749         if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
750                 error("%s", ebuf);
751
752 #ifdef LIBSMI
753         smiInit("tcpdump");
754 #endif
755
756         while (
757             (op = getopt(argc, argv, "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpqr:Rs:StT:u" U_FLAG "V:vw:W:xXy:Yz:Z:")) != -1)
758                 switch (op) {
759
760                 case 'a':
761                         /* compatibility for old -a */
762                         break;
763
764                 case 'A':
765                         ++Aflag;
766                         break;
767
768                 case 'b':
769                         ++bflag;
770                         break;
771
772 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
773                 case 'B':
774                         Bflag = atoi(optarg)*1024;
775                         if (Bflag <= 0)
776                                 error("invalid packet buffer size %s", optarg);
777                         break;
778 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
779
780                 case 'c':
781                         cnt = atoi(optarg);
782                         if (cnt <= 0)
783                                 error("invalid packet count %s", optarg);
784                         break;
785
786                 case 'C':
787                         Cflag = atoi(optarg) * 1000000;
788                         if (Cflag < 0)
789                                 error("invalid file size %s", optarg);
790                         break;
791
792                 case 'd':
793                         ++dflag;
794                         break;
795
796 #ifdef HAVE_PCAP_FINDALLDEVS
797                 case 'D':
798                         if (pcap_findalldevs(&devpointer, ebuf) < 0)
799                                 error("%s", ebuf);
800                         else {
801                                 for (i = 0; devpointer != 0; i++) {
802                                         printf("%d.%s", i+1, devpointer->name);
803                                         if (devpointer->description != NULL)
804                                                 printf(" (%s)", devpointer->description);
805                                         printf("\n");
806                                         devpointer = devpointer->next;
807                                 }
808                         }
809                         return 0;
810 #endif /* HAVE_PCAP_FINDALLDEVS */
811
812                 case 'L':
813                         Lflag++;
814                         break;
815
816                 case 'e':
817                         ++eflag;
818                         break;
819
820                 case 'E':
821 #ifndef HAVE_LIBCRYPTO
822                         warning("crypto code not compiled in");
823 #endif
824                         gndo->ndo_espsecret = optarg;
825                         break;
826
827                 case 'f':
828                         ++fflag;
829                         break;
830
831                 case 'F':
832                         infile = optarg;
833                         break;
834
835                 case 'G':
836                         Gflag = atoi(optarg);
837                         if (Gflag < 0)
838                                 error("invalid number of seconds %s", optarg);
839
840                         /* We will create one file initially. */
841                         Gflag_count = 0;
842
843                         /* Grab the current time for rotation use. */
844                         if ((Gflag_time = time(NULL)) == (time_t)-1) {
845                                 error("main: can't get current time: %s",
846                                     pcap_strerror(errno));
847                         }
848                         break;
849
850                 case 'h':
851                         usage();
852                         break;
853
854                 case 'H':
855                         ++Hflag;
856                         break;
857
858                 case 'i':
859                         if (optarg[0] == '0' && optarg[1] == 0)
860                                 error("Invalid adapter index");
861                         
862 #ifdef HAVE_PCAP_FINDALLDEVS
863                         /*
864                          * If the argument is a number, treat it as
865                          * an index into the list of adapters, as
866                          * printed by "tcpdump -D".
867                          *
868                          * This should be OK on UNIX systems, as interfaces
869                          * shouldn't have names that begin with digits.
870                          * It can be useful on Windows, where more than
871                          * one interface can have the same name.
872                          */
873                         devnum = strtol(optarg, &end, 10);
874                         if (optarg != end && *end == '\0') {
875                                 if (devnum < 0)
876                                         error("Invalid adapter index");
877
878                                 if (pcap_findalldevs(&devpointer, ebuf) < 0)
879                                         error("%s", ebuf);
880                                 else {
881                                         /*
882                                          * Look for the devnum-th entry
883                                          * in the list of devices
884                                          * (1-based).
885                                          */
886                                         for (i = 0;
887                                             i < devnum-1 && devpointer != NULL;
888                                             i++, devpointer = devpointer->next)
889                                                 ;
890                                         if (devpointer == NULL)
891                                                 error("Invalid adapter index");
892                                 }
893                                 device = devpointer->name;
894                                 break;
895                         }
896 #endif /* HAVE_PCAP_FINDALLDEVS */
897                         device = optarg;
898                         break;
899
900 #ifdef HAVE_PCAP_CREATE
901                 case 'I':
902                         ++Iflag;
903                         break;
904 #endif /* HAVE_PCAP_CREATE */
905
906 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
907                 case 'j':
908                         jflag = pcap_tstamp_type_name_to_val(optarg);
909                         if (jflag < 0)
910                                 error("invalid time stamp type %s", optarg);
911                         break;
912
913                 case 'J':
914                         Jflag++;
915                         break;
916 #endif
917
918                 case 'l':
919 #ifdef WIN32
920                         /*
921                          * _IOLBF is the same as _IOFBF in Microsoft's C
922                          * libraries; the only alternative they offer
923                          * is _IONBF.
924                          *
925                          * XXX - this should really be checking for MSVC++,
926                          * not WIN32, if, for example, MinGW has its own
927                          * C library that is more UNIX-compatible.
928                          */
929                         setvbuf(stdout, NULL, _IONBF, 0);
930 #else /* WIN32 */
931 #ifdef HAVE_SETLINEBUF
932                         setlinebuf(stdout);
933 #else
934                         setvbuf(stdout, NULL, _IOLBF, 0);
935 #endif
936 #endif /* WIN32 */
937                         break;
938
939                 case 'K':
940                         ++Kflag;
941                         break;
942
943                 case 'm':
944 #ifdef LIBSMI
945                         if (smiLoadModule(optarg) == 0) {
946                                 error("could not load MIB module %s", optarg);
947                         }
948                         sflag = 1;
949 #else
950                         (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
951                                       program_name, optarg);
952                         (void)fprintf(stderr, "(no libsmi support)\n");
953 #endif
954                         break;
955
956                 case 'M':
957                         /* TCP-MD5 shared secret */
958 #ifndef HAVE_LIBCRYPTO
959                         warning("crypto code not compiled in");
960 #endif
961                         sigsecret = optarg;
962                         break;
963
964                 case 'n':
965                         ++nflag;
966                         break;
967
968                 case 'N':
969                         ++Nflag;
970                         break;
971
972                 case 'O':
973                         Oflag = 0;
974                         break;
975
976                 case 'p':
977                         ++pflag;
978                         break;
979
980                 case 'q':
981                         ++qflag;
982                         ++suppress_default_print;
983                         break;
984
985                 case 'r':
986                         RFileName = optarg;
987                         break;
988
989                 case 'R':
990                         Rflag = 0;
991                         break;
992
993                 case 's':
994                         snaplen = strtol(optarg, &end, 0);
995                         if (optarg == end || *end != '\0'
996                             || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
997                                 error("invalid snaplen %s", optarg);
998                         else if (snaplen == 0)
999                                 snaplen = MAXIMUM_SNAPLEN;
1000                         break;
1001
1002                 case 'S':
1003                         ++Sflag;
1004                         break;
1005
1006                 case 't':
1007                         ++tflag;
1008                         break;
1009
1010                 case 'T':
1011                         if (strcasecmp(optarg, "vat") == 0)
1012                                 packettype = PT_VAT;
1013                         else if (strcasecmp(optarg, "wb") == 0)
1014                                 packettype = PT_WB;
1015                         else if (strcasecmp(optarg, "rpc") == 0)
1016                                 packettype = PT_RPC;
1017                         else if (strcasecmp(optarg, "rtp") == 0)
1018                                 packettype = PT_RTP;
1019                         else if (strcasecmp(optarg, "rtcp") == 0)
1020                                 packettype = PT_RTCP;
1021                         else if (strcasecmp(optarg, "snmp") == 0)
1022                                 packettype = PT_SNMP;
1023                         else if (strcasecmp(optarg, "cnfp") == 0)
1024                                 packettype = PT_CNFP;
1025                         else if (strcasecmp(optarg, "tftp") == 0)
1026                                 packettype = PT_TFTP;
1027                         else if (strcasecmp(optarg, "aodv") == 0)
1028                                 packettype = PT_AODV;
1029                         else if (strcasecmp(optarg, "carp") == 0)
1030                                 packettype = PT_CARP;
1031                         else if (strcasecmp(optarg, "radius") == 0)
1032                                 packettype = PT_RADIUS;
1033                         else if (strcasecmp(optarg, "zmtp1") == 0)
1034                                 packettype = PT_ZMTP1;
1035                         else if (strcasecmp(optarg, "vxlan") == 0)
1036                                 packettype = PT_VXLAN;
1037                         else
1038                                 error("unknown packet type `%s'", optarg);
1039                         break;
1040
1041                 case 'u':
1042                         ++uflag;
1043                         break;
1044
1045 #ifdef HAVE_PCAP_DUMP_FLUSH
1046                 case 'U':
1047                         ++Uflag;
1048                         break;
1049 #endif
1050
1051                 case 'v':
1052                         ++vflag;
1053                         break;
1054
1055                 case 'V':
1056                         VFileName = optarg;
1057                         break;
1058
1059                 case 'w':
1060                         WFileName = optarg;
1061                         break;
1062
1063                 case 'W':
1064                         Wflag = atoi(optarg);
1065                         if (Wflag < 0) 
1066                                 error("invalid number of output files %s", optarg);
1067                         WflagChars = getWflagChars(Wflag);
1068                         break;
1069
1070                 case 'x':
1071                         ++xflag;
1072                         ++suppress_default_print;
1073                         break;
1074
1075                 case 'X':
1076                         ++Xflag;
1077                         ++suppress_default_print;
1078                         break;
1079
1080                 case 'y':
1081                         gndo->ndo_dltname = optarg;
1082                         gndo->ndo_dlt =
1083                           pcap_datalink_name_to_val(gndo->ndo_dltname);
1084                         if (gndo->ndo_dlt < 0)
1085                                 error("invalid data link type %s", gndo->ndo_dltname);
1086                         break;
1087
1088 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1089                 case 'Y':
1090                         {
1091                         /* Undocumented flag */
1092 #ifdef HAVE_PCAP_DEBUG
1093                         extern int pcap_debug;
1094                         pcap_debug = 1;
1095 #else
1096                         extern int yydebug;
1097                         yydebug = 1;
1098 #endif
1099                         }
1100                         break;
1101 #endif
1102                 case 'z':
1103                         if (optarg) {
1104                                 zflag = strdup(optarg);
1105                         } else {
1106                                 usage();
1107                                 /* NOTREACHED */
1108                         }
1109                         break;
1110
1111                 case 'Z':
1112                         if (optarg) {
1113                                 username = strdup(optarg);
1114                         }
1115                         else {
1116                                 usage();
1117                                 /* NOTREACHED */
1118                         }
1119                         break;
1120
1121                 default:
1122                         usage();
1123                         /* NOTREACHED */
1124                 }
1125
1126         switch (tflag) {
1127
1128         case 0: /* Default */
1129         case 4: /* Default + Date*/
1130                 thiszone = gmt2local(0);
1131                 break;
1132
1133         case 1: /* No time stamp */
1134         case 2: /* Unix timeval style */
1135         case 3: /* Microseconds since previous packet */
1136         case 5: /* Microseconds since first packet */
1137                 break;
1138
1139         default: /* Not supported */
1140                 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1141                 break;
1142         }
1143
1144         if (fflag != 0 && (VFileName != NULL || RFileName != NULL))
1145                 error("-f can not be used with -V or -r");
1146
1147         if (VFileName != NULL && RFileName != NULL)
1148                 error("-V and -r are mutually exclusive.");
1149
1150 #ifdef WITH_CHROOT
1151         /* if run as root, prepare for chrooting */
1152         if (getuid() == 0 || geteuid() == 0) {
1153                 /* future extensibility for cmd-line arguments */
1154                 if (!chroot_dir)
1155                         chroot_dir = WITH_CHROOT;
1156         }
1157 #endif
1158
1159 #ifdef WITH_USER
1160         /* if run as root, prepare for dropping root privileges */
1161         if (getuid() == 0 || geteuid() == 0) {
1162                 /* Run with '-Z root' to restore old behaviour */ 
1163                 if (!username)
1164                         username = WITH_USER;
1165         }
1166 #endif
1167
1168         if (RFileName != NULL || VFileName != NULL) {
1169                 /*
1170                  * If RFileName is non-null, it's the pathname of a
1171                  * savefile to read.  If VFileName is non-null, it's
1172                  * the pathname of a file containing a list of pathnames
1173                  * (one per line) of savefiles to read.
1174                  *
1175                  * In either case, we're reading a savefile, not doing
1176                  * a live capture.
1177                  */
1178 #ifndef WIN32
1179                 /*
1180                  * We don't need network access, so relinquish any set-UID
1181                  * or set-GID privileges we have (if any).
1182                  *
1183                  * We do *not* want set-UID privileges when opening a
1184                  * trace file, as that might let the user read other
1185                  * people's trace files (especially if we're set-UID
1186                  * root).
1187                  */
1188                 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1189                         fprintf(stderr, "Warning: setgid/setuid failed !\n");
1190 #endif /* WIN32 */
1191                 if (VFileName != NULL) {
1192                         if (VFileName[0] == '-' && VFileName[1] == '\0')
1193                                 VFile = stdin;
1194                         else
1195                                 VFile = fopen(VFileName, "r");
1196
1197                         if (VFile == NULL)
1198                                 error("Unable to open file: %s\n", strerror(errno));
1199
1200                         ret = get_next_file(VFile, VFileLine);
1201                         if (!ret)
1202                                 error("Nothing in %s\n", VFileName);
1203                         RFileName = VFileLine;
1204                 }
1205
1206                 pd = pcap_open_offline(RFileName, ebuf);
1207                 if (pd == NULL)
1208                         error("%s", ebuf);
1209 #ifdef __FreeBSD__
1210                 cap_rights_init(&rights, CAP_READ);
1211                 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1212                     errno != ENOSYS) {
1213                         error("unable to limit pcap descriptor");
1214                 }
1215 #endif
1216                 dlt = pcap_datalink(pd);
1217                 dlt_name = pcap_datalink_val_to_name(dlt);
1218                 if (dlt_name == NULL) {
1219                         fprintf(stderr, "reading from file %s, link-type %u\n",
1220                             RFileName, dlt);
1221                 } else {
1222                         fprintf(stderr,
1223                             "reading from file %s, link-type %s (%s)\n",
1224                             RFileName, dlt_name,
1225                             pcap_datalink_val_to_description(dlt));
1226                 }
1227                 localnet = 0;
1228                 netmask = 0;
1229         } else {
1230                 /*
1231                  * We're doing a live capture.
1232                  */
1233                 if (device == NULL) {
1234                         device = pcap_lookupdev(ebuf);
1235                         if (device == NULL)
1236                                 error("%s", ebuf);
1237                 }
1238 #ifdef WIN32
1239                 /*
1240                  * Print a message to the standard error on Windows.
1241                  * XXX - why do it here, with a different message?
1242                  */
1243                 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
1244                 {                                               //a Unicode string has a \0 as second byte (so strlen() is 1)
1245                         fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1246                 }
1247                 else
1248                 {
1249                         fprintf(stderr, "%s: listening on %s\n", program_name, device);
1250                 }
1251
1252                 fflush(stderr); 
1253 #endif /* WIN32 */
1254 #ifdef HAVE_PCAP_CREATE
1255                 pd = pcap_create(device, ebuf);
1256                 if (pd == NULL)
1257                         error("%s", ebuf);
1258 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1259                 if (Jflag)
1260                         show_tstamp_types_and_exit(device, pd);
1261 #endif
1262                 /*
1263                  * Is this an interface that supports monitor mode?
1264                  */
1265                 if (pcap_can_set_rfmon(pd) == 1)
1266                         supports_monitor_mode = 1;
1267                 else
1268                         supports_monitor_mode = 0;
1269                 status = pcap_set_snaplen(pd, snaplen);
1270                 if (status != 0)
1271                         error("%s: Can't set snapshot length: %s",
1272                             device, pcap_statustostr(status));
1273                 status = pcap_set_promisc(pd, !pflag);
1274                 if (status != 0)
1275                         error("%s: Can't set promiscuous mode: %s",
1276                             device, pcap_statustostr(status));
1277                 if (Iflag) {
1278                         status = pcap_set_rfmon(pd, 1);
1279                         if (status != 0)
1280                                 error("%s: Can't set monitor mode: %s",
1281                                     device, pcap_statustostr(status));
1282                 }
1283                 status = pcap_set_timeout(pd, 1000);
1284                 if (status != 0)
1285                         error("%s: pcap_set_timeout failed: %s",
1286                             device, pcap_statustostr(status));
1287                 if (Bflag != 0) {
1288                         status = pcap_set_buffer_size(pd, Bflag);
1289                         if (status != 0)
1290                                 error("%s: Can't set buffer size: %s",
1291                                     device, pcap_statustostr(status));
1292                 }
1293 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1294                 if (jflag != -1) {
1295                         status = pcap_set_tstamp_type(pd, jflag);
1296                         if (status < 0)
1297                                 error("%s: Can't set time stamp type: %s",
1298                                     device, pcap_statustostr(status));
1299                 }
1300 #endif
1301                 status = pcap_activate(pd);
1302                 if (status < 0) {
1303                         /*
1304                          * pcap_activate() failed.
1305                          */
1306                         cp = pcap_geterr(pd);
1307                         if (status == PCAP_ERROR)
1308                                 error("%s", cp);
1309                         else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1310                                   status == PCAP_ERROR_PERM_DENIED) &&
1311                                  *cp != '\0')
1312                                 error("%s: %s\n(%s)", device,
1313                                     pcap_statustostr(status), cp);
1314 #ifdef __FreeBSD__
1315                         else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1316                             strncmp(device, "wlan", 4) == 0) {
1317                                 char parent[8], newdev[8];
1318                                 char sysctl[32];
1319                                 size_t s = sizeof(parent);
1320
1321                                 snprintf(sysctl, sizeof(sysctl),
1322                                     "net.wlan.%d.%%parent", atoi(device + 4));
1323                                 sysctlbyname(sysctl, parent, &s, NULL, 0);
1324                                 strlcpy(newdev, device, sizeof(newdev));
1325                                 /* Suggest a new wlan device. */
1326                                 newdev[strlen(newdev)-1]++;
1327                                 error("%s is not a monitor mode VAP\n"
1328                                     "To create a new monitor mode VAP use:\n"
1329                                     "  ifconfig %s create wlandev %s wlanmode "
1330                                     "monitor\nand use %s as the tcpdump "
1331                                     "interface", device, newdev, parent,
1332                                     newdev);
1333                         }
1334 #endif
1335                         else
1336                                 error("%s: %s", device,
1337                                     pcap_statustostr(status));
1338                 } else if (status > 0) {
1339                         /*
1340                          * pcap_activate() succeeded, but it's warning us
1341                          * of a problem it had.
1342                          */
1343                         cp = pcap_geterr(pd);
1344                         if (status == PCAP_WARNING)
1345                                 warning("%s", cp);
1346                         else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1347                                  *cp != '\0')
1348                                 warning("%s: %s\n(%s)", device,
1349                                     pcap_statustostr(status), cp);
1350                         else
1351                                 warning("%s: %s", device,
1352                                     pcap_statustostr(status));
1353                 }
1354 #else
1355                 *ebuf = '\0';
1356                 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1357                 if (pd == NULL)
1358                         error("%s", ebuf);
1359                 else if (*ebuf)
1360                         warning("%s", ebuf);
1361 #endif /* HAVE_PCAP_CREATE */
1362                 /*
1363                  * Let user own process after socket has been opened.
1364                  */
1365 #ifndef WIN32
1366                 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1367                         fprintf(stderr, "Warning: setgid/setuid failed !\n");
1368 #endif /* WIN32 */
1369 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1370                 if(Bflag != 0)
1371                         if(pcap_setbuff(pd, Bflag)==-1){
1372                                 error("%s", pcap_geterr(pd));
1373                         }
1374 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1375                 if (Lflag)
1376                         show_dlts_and_exit(device, pd);
1377                 if (gndo->ndo_dlt >= 0) {
1378 #ifdef HAVE_PCAP_SET_DATALINK
1379                         if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1380                                 error("%s", pcap_geterr(pd));
1381 #else
1382                         /*
1383                          * We don't actually support changing the
1384                          * data link type, so we only let them
1385                          * set it to what it already is.
1386                          */
1387                         if (gndo->ndo_dlt != pcap_datalink(pd)) {
1388                                 error("%s is not one of the DLTs supported by this device\n",
1389                                       gndo->ndo_dltname);
1390                         }
1391 #endif
1392                         (void)fprintf(stderr, "%s: data link type %s\n",
1393                                       program_name, gndo->ndo_dltname);
1394                         (void)fflush(stderr);
1395                 }
1396                 i = pcap_snapshot(pd);
1397                 if (snaplen < i) {
1398                         warning("snaplen raised from %d to %d", snaplen, i);
1399                         snaplen = i;
1400                 }
1401                 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1402                         localnet = 0;
1403                         netmask = 0;
1404                         warning("%s", ebuf);
1405                 }
1406         }
1407         if (infile)
1408                 cmdbuf = read_infile(infile);
1409         else
1410                 cmdbuf = copy_argv(&argv[optind]);
1411
1412         if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1413                 error("%s", pcap_geterr(pd));
1414         if (dflag) {
1415                 bpf_dump(&fcode, dflag);
1416                 pcap_close(pd);
1417                 free(cmdbuf);
1418                 exit(0);
1419         }
1420         init_addrtoname(localnet, netmask);
1421         init_checksum();
1422
1423 #ifndef WIN32   
1424         (void)setsignal(SIGPIPE, cleanup);
1425         (void)setsignal(SIGTERM, cleanup);
1426         (void)setsignal(SIGINT, cleanup);
1427 #endif /* WIN32 */
1428 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1429         (void)setsignal(SIGCHLD, child_cleanup);
1430 #endif
1431         /* Cooperate with nohup(1) */
1432 #ifndef WIN32   
1433         if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1434                 (void)setsignal(SIGHUP, oldhandler);
1435 #endif /* WIN32 */
1436
1437 #ifndef WIN32
1438         /*
1439          * If a user name was specified with "-Z", attempt to switch to
1440          * that user's UID.  This would probably be used with sudo,
1441          * to allow tcpdump to be run in a special restricted
1442          * account (if you just want to allow users to open capture
1443          * devices, and can't just give users that permission,
1444          * you'd make tcpdump set-UID or set-GID).
1445          *
1446          * Tcpdump doesn't necessarily write only to one savefile;
1447          * the general only way to allow a -Z instance to write to
1448          * savefiles as the user under whose UID it's run, rather
1449          * than as the user specified with -Z, would thus be to switch
1450          * to the original user ID before opening a capture file and
1451          * then switch back to the -Z user ID after opening the savefile.
1452          * Switching to the -Z user ID only after opening the first
1453          * savefile doesn't handle the general case.
1454          */
1455
1456 #ifdef HAVE_CAP_NG_H
1457         /* We are running as root and we will be writing to savefile */
1458         if ((getuid() == 0 || geteuid() == 0) && WFileName) {
1459                 if (username) {
1460                         /* Drop all capabilities from effective set */
1461                         capng_clear(CAPNG_EFFECTIVE);
1462                         /* Add capabilities we will need*/
1463                         capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETUID);
1464                         capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETGID);
1465                         capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_OVERRIDE);
1466
1467                         capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETUID);
1468                         capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETGID);
1469                         capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1470
1471                         capng_apply(CAPNG_SELECT_BOTH);
1472                 }
1473         }
1474 #endif /* HAVE_CAP_NG_H */
1475
1476         if (getuid() == 0 || geteuid() == 0) {
1477                 if (username || chroot_dir)
1478                         droproot(username, chroot_dir);
1479
1480         }
1481 #endif /* WIN32 */
1482
1483         if (pcap_setfilter(pd, &fcode) < 0)
1484                 error("%s", pcap_geterr(pd));
1485 #ifdef __FreeBSD__
1486         if (RFileName == NULL && VFileName == NULL) {
1487                 static const unsigned long cmds[] = { BIOCGSTATS };
1488
1489                 cap_rights_init(&rights, CAP_IOCTL, CAP_READ);
1490                 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1491                     errno != ENOSYS) {
1492                         error("unable to limit pcap descriptor");
1493                 }
1494                 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1495                     sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1496                         error("unable to limit ioctls on pcap descriptor");
1497                 }
1498         }
1499 #endif
1500         if (WFileName) {
1501                 pcap_dumper_t *p;
1502                 /* Do not exceed the default PATH_MAX for files. */
1503                 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1504
1505                 if (dumpinfo.CurrentFileName == NULL)
1506                         error("malloc of dumpinfo.CurrentFileName");
1507
1508                 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1509                 if (Cflag != 0)
1510                   MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1511                 else
1512                   MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1513
1514                 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1515 #ifdef HAVE_CAP_NG_H
1516         /* Give up capabilities, clear Effective set */
1517         capng_clear(CAPNG_EFFECTIVE);
1518 #endif
1519                 if (p == NULL)
1520                         error("%s", pcap_geterr(pd));
1521 #ifdef __FreeBSD__
1522                 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
1523                 if (cap_rights_limit(fileno(pcap_dump_file(p)), &rights) < 0 &&
1524                     errno != ENOSYS) {
1525                         error("unable to limit dump descriptor");
1526                 }
1527 #endif
1528                 if (Cflag != 0 || Gflag != 0) {
1529 #ifdef __FreeBSD__
1530                         dumpinfo.WFileName = strdup(basename(WFileName));
1531                         dumpinfo.dirfd = open(dirname(WFileName),
1532                             O_DIRECTORY | O_RDONLY);
1533                         if (dumpinfo.dirfd < 0) {
1534                                 error("unable to open directory %s",
1535                                     dirname(WFileName));
1536                         }
1537                         cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1538                             CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1539                         if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1540                             errno != ENOSYS) {
1541                                 error("unable to limit directory rights");
1542                         }
1543 #else   /* !__FreeBSD__ */
1544                         dumpinfo.WFileName = WFileName;
1545 #endif
1546                         callback = dump_packet_and_trunc;
1547                         dumpinfo.pd = pd;
1548                         dumpinfo.p = p;
1549                         pcap_userdata = (u_char *)&dumpinfo;
1550                 } else {
1551                         callback = dump_packet;
1552                         pcap_userdata = (u_char *)p;
1553                 }
1554 #ifdef HAVE_PCAP_DUMP_FLUSH
1555                 if (Uflag)
1556                         pcap_dump_flush(p);
1557 #endif
1558         } else {
1559                 type = pcap_datalink(pd);
1560                 printinfo = get_print_info(type);
1561                 callback = print_packet;
1562                 pcap_userdata = (u_char *)&printinfo;
1563         }
1564
1565 #ifdef SIGNAL_REQ_INFO
1566         /*
1567          * We can't get statistics when reading from a file rather
1568          * than capturing from a device.
1569          */
1570         if (RFileName == NULL)
1571                 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1572 #endif
1573
1574         if (vflag > 0 && WFileName) {
1575                 /*
1576                  * When capturing to a file, "-v" means tcpdump should,
1577                  * every 10 secodns, "v"erbosely report the number of
1578                  * packets captured.
1579                  */
1580 #ifdef USE_WIN32_MM_TIMER
1581                 /* call verbose_stats_dump() each 1000 +/-100msec */
1582                 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1583                 setvbuf(stderr, NULL, _IONBF, 0);
1584 #elif defined(HAVE_ALARM)
1585                 (void)setsignal(SIGALRM, verbose_stats_dump);
1586                 alarm(1);
1587 #endif
1588         }
1589
1590 #ifndef WIN32
1591         if (RFileName == NULL) {
1592                 /*
1593                  * Live capture (if -V was specified, we set RFileName
1594                  * to a file from the -V file).  Print a message to
1595                  * the standard error on UN*X.
1596                  */
1597                 if (!vflag && !WFileName) {
1598                         (void)fprintf(stderr,
1599                             "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1600                             program_name);
1601                 } else
1602                         (void)fprintf(stderr, "%s: ", program_name);
1603                 dlt = pcap_datalink(pd);
1604                 dlt_name = pcap_datalink_val_to_name(dlt);
1605                 if (dlt_name == NULL) {
1606                         (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1607                             device, dlt, snaplen);
1608                 } else {
1609                         (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1610                             device, dlt_name,
1611                             pcap_datalink_val_to_description(dlt), snaplen);
1612                 }
1613                 (void)fflush(stderr);
1614         }
1615 #endif /* WIN32 */
1616
1617 #ifdef __FreeBSD__
1618         cansandbox = (nflag && VFileName == NULL && zflag == NULL);
1619         if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1620                 error("unable to enter the capability mode");
1621         if (cap_sandboxed())
1622                 fprintf(stderr, "capability mode sandbox enabled\n");
1623 #endif  /* __FreeBSD__ */
1624
1625         do {
1626                 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1627                 if (WFileName == NULL) {
1628                         /*
1629                          * We're printing packets.  Flush the printed output,
1630                          * so it doesn't get intermingled with error output.
1631                          */
1632                         if (status == -2) {
1633                                 /*
1634                                  * We got interrupted, so perhaps we didn't
1635                                  * manage to finish a line we were printing.
1636                                  * Print an extra newline, just in case.
1637                                  */
1638                                 putchar('\n');
1639                         }
1640                         (void)fflush(stdout);
1641                 }
1642                 if (status == -1) {
1643                         /*
1644                          * Error.  Report it.
1645                          */
1646                         (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1647                             program_name, pcap_geterr(pd));
1648                 }
1649                 if (RFileName == NULL) {
1650                         /*
1651                          * We're doing a live capture.  Report the capture
1652                          * statistics.
1653                          */
1654                         info(1);
1655                 }
1656                 pcap_close(pd);
1657                 if (VFileName != NULL) {
1658                         ret = get_next_file(VFile, VFileLine);
1659                         if (ret) {
1660                                 RFileName = VFileLine;
1661                                 pd = pcap_open_offline(RFileName, ebuf);
1662                                 if (pd == NULL)
1663                                         error("%s", ebuf);
1664 #ifdef __FreeBSD__
1665                                 cap_rights_init(&rights, CAP_READ);
1666                                 if (cap_rights_limit(fileno(pcap_file(pd)),
1667                                     &rights) < 0 && errno != ENOSYS) {
1668                                         error("unable to limit pcap descriptor");
1669                                 }
1670 #endif
1671                                 new_dlt = pcap_datalink(pd);
1672                                 if (WFileName && new_dlt != dlt)
1673                                         error("%s: new dlt does not match original", RFileName);
1674                                 printinfo = get_print_info(new_dlt);
1675                                 dlt_name = pcap_datalink_val_to_name(new_dlt);
1676                                 if (dlt_name == NULL) {
1677                                         fprintf(stderr, "reading from file %s, link-type %u\n",
1678                                         RFileName, new_dlt);
1679                                 } else {
1680                                         fprintf(stderr,
1681                                         "reading from file %s, link-type %s (%s)\n",
1682                                         RFileName, dlt_name,
1683                                         pcap_datalink_val_to_description(new_dlt));
1684                                 }
1685                                 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1686                                         error("%s", pcap_geterr(pd));
1687                                 if (pcap_setfilter(pd, &fcode) < 0)
1688                                         error("%s", pcap_geterr(pd));
1689                         }
1690                 }
1691         }
1692         while (ret != NULL);
1693
1694         free(cmdbuf);
1695         exit(status == -1 ? 1 : 0);
1696 }
1697
1698 /* make a clean exit on interrupts */
1699 static RETSIGTYPE
1700 cleanup(int signo _U_)
1701 {
1702 #ifdef USE_WIN32_MM_TIMER
1703         if (timer_id)
1704                 timeKillEvent(timer_id);
1705         timer_id = 0;
1706 #elif defined(HAVE_ALARM)
1707         alarm(0);
1708 #endif
1709
1710 #ifdef HAVE_PCAP_BREAKLOOP
1711         /*
1712          * We have "pcap_breakloop()"; use it, so that we do as little
1713          * as possible in the signal handler (it's probably not safe
1714          * to do anything with standard I/O streams in a signal handler -
1715          * the ANSI C standard doesn't say it is).
1716          */
1717         pcap_breakloop(pd);
1718 #else
1719         /*
1720          * We don't have "pcap_breakloop()"; this isn't safe, but
1721          * it's the best we can do.  Print the summary if we're
1722          * not reading from a savefile - i.e., if we're doing a
1723          * live capture - and exit.
1724          */
1725         if (pd != NULL && pcap_file(pd) == NULL) {
1726                 /*
1727                  * We got interrupted, so perhaps we didn't
1728                  * manage to finish a line we were printing.
1729                  * Print an extra newline, just in case.
1730                  */
1731                 putchar('\n');
1732                 (void)fflush(stdout);
1733                 info(1);
1734         }
1735         exit(0);
1736 #endif
1737 }
1738
1739 /*
1740   On windows, we do not use a fork, so we do not care less about
1741   waiting a child processes to die
1742  */
1743 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1744 static RETSIGTYPE
1745 child_cleanup(int signo _U_)
1746 {
1747   wait(NULL);
1748 }
1749 #endif /* HAVE_FORK && HAVE_VFORK */
1750
1751 static void
1752 info(register int verbose)
1753 {
1754         struct pcap_stat stat;
1755
1756         /*
1757          * Older versions of libpcap didn't set ps_ifdrop on some
1758          * platforms; initialize it to 0 to handle that.
1759          */
1760         stat.ps_ifdrop = 0;
1761         if (pcap_stats(pd, &stat) < 0) {
1762                 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1763                 infoprint = 0;
1764                 return;
1765         }
1766
1767         if (!verbose)
1768                 fprintf(stderr, "%s: ", program_name);
1769
1770         (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1771             PLURAL_SUFFIX(packets_captured));
1772         if (!verbose)
1773                 fputs(", ", stderr);
1774         else
1775                 putc('\n', stderr);
1776         (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1777             PLURAL_SUFFIX(stat.ps_recv));
1778         if (!verbose)
1779                 fputs(", ", stderr);
1780         else
1781                 putc('\n', stderr);
1782         (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1783             PLURAL_SUFFIX(stat.ps_drop));
1784         if (stat.ps_ifdrop != 0) {
1785                 if (!verbose)
1786                         fputs(", ", stderr);
1787                 else
1788                         putc('\n', stderr);
1789                 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1790                     stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1791         } else
1792                 putc('\n', stderr);
1793         infoprint = 0;
1794 }
1795
1796 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1797 static void
1798 compress_savefile(const char *filename)
1799 {
1800 # ifdef HAVE_FORK
1801         if (fork())
1802 # else
1803         if (vfork())
1804 # endif
1805                 return;
1806         /*
1807          * Set to lowest priority so that this doesn't disturb the capture
1808          */
1809 #ifdef NZERO
1810         setpriority(PRIO_PROCESS, 0, NZERO - 1);
1811 #else
1812         setpriority(PRIO_PROCESS, 0, 19);
1813 #endif
1814         if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1815                 fprintf(stderr,
1816                         "compress_savefile:execlp(%s, %s): %s\n",
1817                         zflag,
1818                         filename,
1819                         strerror(errno));
1820 # ifdef HAVE_FORK
1821         exit(1);
1822 # else
1823         _exit(1);
1824 # endif
1825 }
1826 #else  /* HAVE_FORK && HAVE_VFORK */
1827 static void
1828 compress_savefile(const char *filename)
1829 {
1830         fprintf(stderr,
1831                 "compress_savefile failed. Functionality not implemented under your system\n");
1832 }
1833 #endif /* HAVE_FORK && HAVE_VFORK */
1834
1835 static void
1836 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1837 {
1838         struct dump_info *dump_info;
1839 #ifdef __FreeBSD__
1840         cap_rights_t rights;
1841 #endif
1842
1843         ++packets_captured;
1844
1845         ++infodelay;
1846
1847         dump_info = (struct dump_info *)user;
1848
1849         /*
1850          * XXX - this won't force the file to rotate on the specified time
1851          * boundary, but it will rotate on the first packet received after the
1852          * specified Gflag number of seconds. Note: if a Gflag time boundary
1853          * and a Cflag size boundary coincide, the time rotation will occur
1854          * first thereby cancelling the Cflag boundary (since the file should
1855          * be 0).
1856          */
1857         if (Gflag != 0) {
1858                 /* Check if it is time to rotate */
1859                 time_t t;
1860
1861                 /* Get the current time */
1862                 if ((t = time(NULL)) == (time_t)-1) {
1863                         error("dump_and_trunc_packet: can't get current_time: %s",
1864                             pcap_strerror(errno));
1865                 }
1866
1867
1868                 /* If the time is greater than the specified window, rotate */
1869                 if (t - Gflag_time >= Gflag) {
1870 #ifdef __FreeBSD__
1871                         FILE *fp;
1872                         int fd;
1873 #endif
1874
1875                         /* Update the Gflag_time */
1876                         Gflag_time = t;
1877                         /* Update Gflag_count */
1878                         Gflag_count++;
1879                         /*
1880                          * Close the current file and open a new one.
1881                          */
1882                         pcap_dump_close(dump_info->p);
1883
1884                         /*
1885                          * Compress the file we just closed, if the user asked for it
1886                          */
1887                         if (zflag != NULL)
1888                                 compress_savefile(dump_info->CurrentFileName);
1889
1890                         /*
1891                          * Check to see if we've exceeded the Wflag (when
1892                          * not using Cflag).
1893                          */
1894                         if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1895                                 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1896                                     Wflag);
1897                                 exit(0);
1898                                 /* NOTREACHED */
1899                         }
1900                         if (dump_info->CurrentFileName != NULL)
1901                                 free(dump_info->CurrentFileName);
1902                         /* Allocate space for max filename + \0. */
1903                         dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
1904                         if (dump_info->CurrentFileName == NULL)
1905                                 error("dump_packet_and_trunc: malloc");
1906                         /*
1907                          * This is always the first file in the Cflag
1908                          * rotation: e.g. 0
1909                          * We also don't need numbering if Cflag is not set.
1910                          */
1911                         if (Cflag != 0)
1912                                 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1913                                     WflagChars);
1914                         else
1915                                 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1916
1917 #ifdef HAVE_CAP_NG_H
1918                         capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1919                         capng_apply(CAPNG_EFFECTIVE);
1920 #endif /* HAVE_CAP_NG_H */
1921 #ifdef __FreeBSD__
1922                         fd = openat(dump_info->dirfd,
1923                             dump_info->CurrentFileName,
1924                             O_CREAT | O_WRONLY | O_TRUNC, 0644);
1925                         if (fd < 0) {
1926                                 error("unable to open file %s",
1927                                     dump_info->CurrentFileName);
1928                         }
1929                         fp = fdopen(fd, "w");
1930                         if (fp == NULL) {
1931                                 error("unable to fdopen file %s",
1932                                     dump_info->CurrentFileName);
1933                         }
1934                         dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
1935 #else   /* !__FreeBSD__ */
1936                         dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1937 #endif
1938 #ifdef HAVE_CAP_NG_H
1939                         capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1940                         capng_apply(CAPNG_EFFECTIVE);
1941 #endif /* HAVE_CAP_NG_H */
1942                         if (dump_info->p == NULL)
1943                                 error("%s", pcap_geterr(pd));
1944 #ifdef __FreeBSD__
1945                         cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
1946                         if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
1947                             &rights) < 0 && errno != ENOSYS) {
1948                                 error("unable to limit dump descriptor");
1949                         }
1950 #endif
1951                 }
1952         }
1953
1954         /*
1955          * XXX - this won't prevent capture files from getting
1956          * larger than Cflag - the last packet written to the
1957          * file could put it over Cflag.
1958          */
1959         if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1960 #ifdef __FreeBSD__
1961                 FILE *fp;
1962                 int fd;
1963 #endif
1964
1965                 /*
1966                  * Close the current file and open a new one.
1967                  */
1968                 pcap_dump_close(dump_info->p);
1969
1970                 /*
1971                  * Compress the file we just closed, if the user asked for it
1972                  */
1973                 if (zflag != NULL)
1974                         compress_savefile(dump_info->CurrentFileName);
1975
1976                 Cflag_count++;
1977                 if (Wflag > 0) {
1978                         if (Cflag_count >= Wflag)
1979                                 Cflag_count = 0;
1980                 }
1981                 if (dump_info->CurrentFileName != NULL)
1982                         free(dump_info->CurrentFileName);
1983                 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
1984                 if (dump_info->CurrentFileName == NULL)
1985                         error("dump_packet_and_trunc: malloc");
1986                 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1987 #ifdef __FreeBSD__
1988                 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
1989                     O_CREAT | O_WRONLY | O_TRUNC, 0644);
1990                 if (fd < 0) {
1991                         error("unable to open file %s",
1992                             dump_info->CurrentFileName);
1993                 }
1994                 fp = fdopen(fd, "w");
1995                 if (fp == NULL) {
1996                         error("unable to fdopen file %s",
1997                             dump_info->CurrentFileName);
1998                 }
1999                 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2000 #else   /* !__FreeBSD__ */
2001                 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2002 #endif
2003                 if (dump_info->p == NULL)
2004                         error("%s", pcap_geterr(pd));
2005 #ifdef __FreeBSD__
2006                 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
2007                 if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
2008                     &rights) < 0 && errno != ENOSYS) {
2009                         error("unable to limit dump descriptor");
2010                 }
2011 #endif
2012         }
2013
2014         pcap_dump((u_char *)dump_info->p, h, sp);
2015 #ifdef HAVE_PCAP_DUMP_FLUSH
2016         if (Uflag)
2017                 pcap_dump_flush(dump_info->p);
2018 #endif
2019
2020         --infodelay;
2021         if (infoprint)
2022                 info(0);
2023 }
2024
2025 static void
2026 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2027 {
2028         ++packets_captured;
2029
2030         ++infodelay;
2031
2032         pcap_dump(user, h, sp);
2033 #ifdef HAVE_PCAP_DUMP_FLUSH
2034         if (Uflag)
2035                 pcap_dump_flush((pcap_dumper_t *)user);
2036 #endif
2037
2038         --infodelay;
2039         if (infoprint)
2040                 info(0);
2041 }
2042
2043 static void
2044 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2045 {
2046         struct print_info *print_info;
2047         u_int hdrlen;
2048
2049         ++packets_captured;
2050
2051         ++infodelay;
2052         ts_print(&h->ts);
2053
2054         print_info = (struct print_info *)user;
2055
2056         /*
2057          * Some printers want to check that they're not walking off the
2058          * end of the packet.
2059          * Rather than pass it all the way down, we set this global.
2060          */
2061         snapend = sp + h->caplen;
2062
2063         if(print_info->ndo_type) {
2064                 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
2065         } else {
2066                 hdrlen = (*print_info->p.printer)(h, sp);
2067         }
2068                 
2069         if (Xflag) {
2070                 /*
2071                  * Print the raw packet data in hex and ASCII.
2072                  */
2073                 if (Xflag > 1) {
2074                         /*
2075                          * Include the link-layer header.
2076                          */
2077                         hex_and_ascii_print("\n\t", sp, h->caplen);
2078                 } else {
2079                         /*
2080                          * Don't include the link-layer header - and if
2081                          * we have nothing past the link-layer header,
2082                          * print nothing.
2083                          */
2084                         if (h->caplen > hdrlen)
2085                                 hex_and_ascii_print("\n\t", sp + hdrlen,
2086                                     h->caplen - hdrlen);
2087                 }
2088         } else if (xflag) {
2089                 /*
2090                  * Print the raw packet data in hex.
2091                  */
2092                 if (xflag > 1) {
2093                         /*
2094                          * Include the link-layer header.
2095                          */
2096                         hex_print("\n\t", sp, h->caplen);
2097                 } else {
2098                         /*
2099                          * Don't include the link-layer header - and if
2100                          * we have nothing past the link-layer header,
2101                          * print nothing.
2102                          */
2103                         if (h->caplen > hdrlen)
2104                                 hex_print("\n\t", sp + hdrlen,
2105                                     h->caplen - hdrlen);
2106                 }
2107         } else if (Aflag) {
2108                 /*
2109                  * Print the raw packet data in ASCII.
2110                  */
2111                 if (Aflag > 1) {
2112                         /*
2113                          * Include the link-layer header.
2114                          */
2115                         ascii_print(sp, h->caplen);
2116                 } else {
2117                         /*
2118                          * Don't include the link-layer header - and if
2119                          * we have nothing past the link-layer header,
2120                          * print nothing.
2121                          */
2122                         if (h->caplen > hdrlen)
2123                                 ascii_print(sp + hdrlen, h->caplen - hdrlen);
2124                 }
2125         }
2126
2127         putchar('\n');
2128
2129         --infodelay;
2130         if (infoprint)
2131                 info(0);
2132 }
2133
2134 #ifdef WIN32
2135         /*
2136          * XXX - there should really be libpcap calls to get the version
2137          * number as a string (the string would be generated from #defines
2138          * at run time, so that it's not generated from string constants
2139          * in the library, as, on many UNIX systems, those constants would
2140          * be statically linked into the application executable image, and
2141          * would thus reflect the version of libpcap on the system on
2142          * which the application was *linked*, not the system on which it's
2143          * *running*.
2144          *
2145          * That routine should be documented, unlike the "version[]"
2146          * string, so that UNIX vendors providing their own libpcaps
2147          * don't omit it (as a couple of vendors have...).
2148          *
2149          * Packet.dll should perhaps also export a routine to return the
2150          * version number of the Packet.dll code, to supply the
2151          * "Wpcap_version" information on Windows.
2152          */
2153         char WDversion[]="current-cvs.tcpdump.org";
2154 #if !defined(HAVE_GENERATED_VERSION)
2155         char version[]="current-cvs.tcpdump.org";
2156 #endif
2157         char pcap_version[]="current-cvs.tcpdump.org";
2158         char Wpcap_version[]="3.1";
2159 #endif
2160
2161 /*
2162  * By default, print the specified data out in hex and ASCII.
2163  */
2164 static void
2165 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
2166 {
2167         hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
2168 }
2169
2170 void
2171 default_print(const u_char *bp, u_int length)
2172 {
2173         ndo_default_print(gndo, bp, length);
2174 }
2175
2176 #ifdef SIGNAL_REQ_INFO
2177 RETSIGTYPE requestinfo(int signo _U_)
2178 {
2179         if (infodelay)
2180                 ++infoprint;
2181         else
2182                 info(0);
2183 }
2184 #endif
2185
2186 /*
2187  * Called once each second in verbose mode while dumping to file
2188  */
2189 #ifdef USE_WIN32_MM_TIMER
2190 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2191                                   DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2192 {
2193         struct pcap_stat stat;
2194
2195         if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2196                 fprintf(stderr, "Got %u\r", packets_captured);
2197 }
2198 #elif defined(HAVE_ALARM)
2199 static void verbose_stats_dump(int sig _U_)
2200 {
2201         struct pcap_stat stat;
2202
2203         if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2204                 fprintf(stderr, "Got %u\r", packets_captured);
2205         alarm(1);
2206 }
2207 #endif
2208
2209 static void
2210 usage(void)
2211 {
2212         extern char version[];
2213 #ifndef HAVE_PCAP_LIB_VERSION
2214 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
2215         extern char pcap_version[];
2216 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2217         static char pcap_version[] = "unknown";
2218 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2219 #endif /* HAVE_PCAP_LIB_VERSION */
2220
2221 #ifdef HAVE_PCAP_LIB_VERSION
2222 #ifdef WIN32
2223         (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2224 #else /* WIN32 */
2225         (void)fprintf(stderr, "%s version %s\n", program_name, version);
2226 #endif /* WIN32 */
2227         (void)fprintf(stderr, "%s\n",pcap_lib_version());
2228 #else /* HAVE_PCAP_LIB_VERSION */
2229 #ifdef WIN32
2230         (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2231         (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2232 #else /* WIN32 */
2233         (void)fprintf(stderr, "%s version %s\n", program_name, version);
2234         (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2235 #endif /* WIN32 */
2236 #endif /* HAVE_PCAP_LIB_VERSION */
2237         (void)fprintf(stderr,
2238 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2239         (void)fprintf(stderr,
2240 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2241         (void)fprintf(stderr,
2242 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
2243         (void)fprintf(stderr,
2244 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -V file ] [ -w file ]\n");
2245         (void)fprintf(stderr,
2246 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2247         (void)fprintf(stderr,
2248 "\t\t[ -Z user ] [ expression ]\n");
2249         exit(1);
2250 }
2251
2252
2253
2254 /* VARARGS */
2255 static void
2256 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
2257 {
2258         va_list ap;
2259
2260         (void)fprintf(stderr, "%s: ", program_name);
2261         va_start(ap, fmt);
2262         (void)vfprintf(stderr, fmt, ap);
2263         va_end(ap);
2264         if (*fmt) {
2265                 fmt += strlen(fmt);
2266                 if (fmt[-1] != '\n')
2267                         (void)fputc('\n', stderr);
2268         }
2269         exit(1);
2270         /* NOTREACHED */
2271 }
2272
2273 /* VARARGS */
2274 static void
2275 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2276 {
2277         va_list ap;
2278
2279         (void)fprintf(stderr, "%s: WARNING: ", program_name);
2280         va_start(ap, fmt);
2281         (void)vfprintf(stderr, fmt, ap);
2282         va_end(ap);
2283         if (*fmt) {
2284                 fmt += strlen(fmt);
2285                 if (fmt[-1] != '\n')
2286                         (void)fputc('\n', stderr);
2287         }
2288 }