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