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