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