]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
1eb2e206b6ec1b9a6a12eebc8f576117983aa9b1
[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 #define OPTION_IMMEDIATE_MODE 130
673
674 static const struct option longopts[] = {
675 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
676 { "buffer-size", required_argument, NULL, 'B' },
677 #endif
678 { "list-interfaces", no_argument, NULL, 'D' },
679 { "help", no_argument, NULL, 'h' },
680 { "interface", required_argument, NULL, 'i' },
681 #ifdef HAVE_PCAP_CREATE
682 { "monitor-mode", no_argument, NULL, 'I' },
683 #endif
684 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
685 { "time-stamp-type", required_argument, NULL, 'j' },
686 { "list-time-stamp-types", no_argument, NULL, 'J' },
687 #endif
688 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
689 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
690 #endif
691 { "dont-verify-checksums", no_argument, NULL, 'K' },
692 { "list-data-link-types", no_argument, NULL, 'L' },
693 { "no-optimize", no_argument, NULL, 'O' },
694 { "no-promiscuous-mode", no_argument, NULL, 'p' },
695 #ifdef HAVE_PCAP_SETDIRECTION
696 { "direction", required_argument, NULL, 'Q' },
697 #endif
698 { "snapshot-length", required_argument, NULL, 's' },
699 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
700 #ifdef HAVE_PCAP_DUMP_FLUSH
701 { "packet-buffered", no_argument, NULL, 'U' },
702 #endif
703 { "linktype", required_argument, NULL, 'y' },
704 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
705 { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
706 #endif
707 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
708 { "debug-filter-parser", no_argument, NULL, 'Y' },
709 #endif
710 { "relinquish-privileges", required_argument, NULL, 'Z' },
711 { "number", no_argument, NULL, '#' },
712 { "version", no_argument, NULL, OPTION_VERSION },
713 { NULL, 0, NULL, 0 }
714 };
715
716 #ifndef WIN32
717 /* Drop root privileges and chroot if necessary */
718 static void
719 droproot(const char *username, const char *chroot_dir)
720 {
721 struct passwd *pw = NULL;
722
723 if (chroot_dir && !username) {
724 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
725 exit(1);
726 }
727
728 pw = getpwnam(username);
729 if (pw) {
730 if (chroot_dir) {
731 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
732 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
733 chroot_dir, pcap_strerror(errno));
734 exit(1);
735 }
736 }
737 #ifdef HAVE_CAP_NG_H
738 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
739 if (ret < 0) {
740 fprintf(stderr, "error : ret %d\n", ret);
741 }
742 else {
743 fprintf(stderr, "dropped privs to %s\n", username);
744 }
745 /* We don't need CAP_SETUID and CAP_SETGID */
746 capng_updatev(
747 CAPNG_DROP,
748 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
749 CAP_SETUID,
750 CAP_SETGID,
751 -1);
752 capng_apply(CAPNG_SELECT_BOTH);
753
754 #else
755 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
756 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
757 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
758 username,
759 (unsigned long)pw->pw_uid,
760 (unsigned long)pw->pw_gid,
761 pcap_strerror(errno));
762 exit(1);
763 }
764 else {
765 fprintf(stderr, "dropped privs to %s\n", username);
766 }
767 #endif /* HAVE_CAP_NG_H */
768 }
769 else {
770 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
771 username);
772 exit(1);
773 }
774 }
775 #endif /* WIN32 */
776
777 static int
778 getWflagChars(int x)
779 {
780 int c = 0;
781
782 x -= 1;
783 while (x > 0) {
784 c += 1;
785 x /= 10;
786 }
787
788 return c;
789 }
790
791
792 static void
793 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
794 {
795 char *filename = malloc(PATH_MAX + 1);
796 if (filename == NULL)
797 error("Makefilename: malloc");
798
799 /* Process with strftime if Gflag is set. */
800 if (Gflag != 0) {
801 struct tm *local_tm;
802
803 /* Convert Gflag_time to a usable format */
804 if ((local_tm = localtime(&Gflag_time)) == NULL) {
805 error("MakeTimedFilename: localtime");
806 }
807
808 /* There's no good way to detect an error in strftime since a return
809 * value of 0 isn't necessarily failure.
810 */
811 strftime(filename, PATH_MAX, orig_name, local_tm);
812 } else {
813 strncpy(filename, orig_name, PATH_MAX);
814 }
815
816 if (cnt == 0 && max_chars == 0)
817 strncpy(buffer, filename, PATH_MAX + 1);
818 else
819 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
820 /* Report an error if the filename is too large */
821 error("too many output files or filename is too long (> %d)", PATH_MAX);
822 free(filename);
823 }
824
825 static int tcpdump_printf(netdissect_options *ndo _U_,
826 const char *fmt, ...)
827 {
828
829 va_list args;
830 int ret;
831
832 va_start(args, fmt);
833 ret=vfprintf(stdout, fmt, args);
834 va_end(args);
835
836 return ret;
837 }
838
839 static struct print_info
840 get_print_info(int type)
841 {
842 struct print_info printinfo;
843
844 printinfo.ndo_type = 1;
845 printinfo.ndo = gndo;
846 printinfo.p.ndo_printer = lookup_ndo_printer(type);
847 if (printinfo.p.ndo_printer == NULL) {
848 printinfo.p.printer = lookup_printer(type);
849 printinfo.ndo_type = 0;
850 if (printinfo.p.printer == NULL) {
851 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
852 if (gndo->ndo_dltname != NULL)
853 error("packet printing is not supported for link type %s: use -w",
854 gndo->ndo_dltname);
855 else
856 error("packet printing is not supported for link type %d: use -w", type);
857 }
858 }
859 return (printinfo);
860 }
861
862 static char *
863 get_next_file(FILE *VFile, char *ptr)
864 {
865 char *ret;
866
867 ret = fgets(ptr, PATH_MAX, VFile);
868 if (!ret)
869 return NULL;
870
871 if (ptr[strlen(ptr) - 1] == '\n')
872 ptr[strlen(ptr) - 1] = '\0';
873
874 return ret;
875 }
876
877 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
878 static int
879 tstamp_precision_from_string(const char *precision)
880 {
881 if (strncmp(precision, "nano", strlen("nano")) == 0)
882 return PCAP_TSTAMP_PRECISION_NANO;
883
884 if (strncmp(precision, "micro", strlen("micro")) == 0)
885 return PCAP_TSTAMP_PRECISION_MICRO;
886
887 return -EINVAL;
888 }
889
890 static const char *
891 tstamp_precision_to_string(int precision)
892 {
893 switch (precision) {
894
895 case PCAP_TSTAMP_PRECISION_MICRO:
896 return "micro";
897
898 case PCAP_TSTAMP_PRECISION_NANO:
899 return "nano";
900
901 default:
902 return "unknown";
903 }
904 }
905 #endif
906
907 int
908 main(int argc, char **argv)
909 {
910 register int cnt, op, i;
911 bpf_u_int32 localnet =0 , netmask = 0;
912 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
913 pcap_handler callback;
914 int type;
915 int dlt;
916 int new_dlt;
917 const char *dlt_name;
918 struct bpf_program fcode;
919 #ifndef WIN32
920 RETSIGTYPE (*oldhandler)(int);
921 #endif
922 struct print_info printinfo;
923 struct dump_info dumpinfo;
924 u_char *pcap_userdata;
925 char ebuf[PCAP_ERRBUF_SIZE];
926 char VFileLine[PATH_MAX + 1];
927 char *username = NULL;
928 char *chroot_dir = NULL;
929 char *ret = NULL;
930 char *end;
931 #ifdef HAVE_PCAP_FINDALLDEVS
932 pcap_if_t *devpointer;
933 int devnum;
934 #endif
935 int status;
936 FILE *VFile;
937 #ifdef HAVE_CAPSICUM
938 cap_rights_t rights;
939 int cansandbox;
940 #endif /* HAVE_CAPSICUM */
941
942 #ifdef WIN32
943 if(wsockinit() != 0) return 1;
944 #endif /* WIN32 */
945
946 jflag=-1; /* not set */
947 gndo->ndo_Oflag=1;
948 gndo->ndo_Rflag=1;
949 gndo->ndo_dlt=-1;
950 gndo->ndo_default_print=ndo_default_print;
951 gndo->ndo_printf=tcpdump_printf;
952 gndo->ndo_error=ndo_error;
953 gndo->ndo_warning=ndo_warning;
954 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
955 gndo->ndo_immediate = 0;
956
957 cnt = -1;
958 device = NULL;
959 infile = NULL;
960 RFileName = NULL;
961 VFileName = NULL;
962 VFile = NULL;
963 WFileName = NULL;
964 dlt = -1;
965 if ((cp = strrchr(argv[0], '/')) != NULL)
966 program_name = cp + 1;
967 else
968 program_name = argv[0];
969
970 /*
971 * On platforms where the CPU doesn't support unaligned loads,
972 * force unaligned accesses to abort with SIGBUS, rather than
973 * being fixed up (slowly) by the OS kernel; on those platforms,
974 * misaligned accesses are bugs, and we want tcpdump to crash so
975 * that the bugs are reported.
976 */
977 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
978 error("%s", ebuf);
979
980 #ifdef USE_LIBSMI
981 smiInit("tcpdump");
982 #endif
983
984 while (
985 (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)
986 switch (op) {
987
988 case 'a':
989 /* compatibility for old -a */
990 break;
991
992 case 'A':
993 ++Aflag;
994 break;
995
996 case 'b':
997 ++bflag;
998 break;
999
1000 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
1001 case 'B':
1002 Bflag = atoi(optarg)*1024;
1003 if (Bflag <= 0)
1004 error("invalid packet buffer size %s", optarg);
1005 break;
1006 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
1007
1008 case 'c':
1009 cnt = atoi(optarg);
1010 if (cnt <= 0)
1011 error("invalid packet count %s", optarg);
1012 break;
1013
1014 case 'C':
1015 Cflag = atoi(optarg) * 1000000;
1016 if (Cflag < 0)
1017 error("invalid file size %s", optarg);
1018 break;
1019
1020 case 'd':
1021 ++dflag;
1022 break;
1023
1024 case 'D':
1025 Dflag++;
1026 break;
1027
1028 case 'L':
1029 Lflag++;
1030 break;
1031
1032 case 'e':
1033 ++eflag;
1034 break;
1035
1036 case 'E':
1037 #ifndef HAVE_LIBCRYPTO
1038 warning("crypto code not compiled in");
1039 #endif
1040 gndo->ndo_espsecret = optarg;
1041 break;
1042
1043 case 'f':
1044 ++fflag;
1045 break;
1046
1047 case 'F':
1048 infile = optarg;
1049 break;
1050
1051 case 'G':
1052 Gflag = atoi(optarg);
1053 if (Gflag < 0)
1054 error("invalid number of seconds %s", optarg);
1055
1056 /* We will create one file initially. */
1057 Gflag_count = 0;
1058
1059 /* Grab the current time for rotation use. */
1060 if ((Gflag_time = time(NULL)) == (time_t)-1) {
1061 error("main: can't get current time: %s",
1062 pcap_strerror(errno));
1063 }
1064 break;
1065
1066 case 'h':
1067 print_usage();
1068 exit(0);
1069 break;
1070
1071 case 'H':
1072 ++Hflag;
1073 break;
1074
1075 case 'i':
1076 if (optarg[0] == '0' && optarg[1] == 0)
1077 error("Invalid adapter index");
1078
1079 #ifdef HAVE_PCAP_FINDALLDEVS
1080 /*
1081 * If the argument is a number, treat it as
1082 * an index into the list of adapters, as
1083 * printed by "tcpdump -D".
1084 *
1085 * This should be OK on UNIX systems, as interfaces
1086 * shouldn't have names that begin with digits.
1087 * It can be useful on Windows, where more than
1088 * one interface can have the same name.
1089 */
1090 devnum = strtol(optarg, &end, 10);
1091 if (optarg != end && *end == '\0') {
1092 if (devnum < 0)
1093 error("Invalid adapter index");
1094
1095 if (pcap_findalldevs(&devpointer, ebuf) < 0)
1096 error("%s", ebuf);
1097 else {
1098 /*
1099 * Look for the devnum-th entry
1100 * in the list of devices
1101 * (1-based).
1102 */
1103 for (i = 0;
1104 i < devnum-1 && devpointer != NULL;
1105 i++, devpointer = devpointer->next)
1106 ;
1107 if (devpointer == NULL)
1108 error("Invalid adapter index");
1109 }
1110 device = devpointer->name;
1111 break;
1112 }
1113 #endif /* HAVE_PCAP_FINDALLDEVS */
1114 device = optarg;
1115 break;
1116
1117 #ifdef HAVE_PCAP_CREATE
1118 case 'I':
1119 ++Iflag;
1120 break;
1121 #endif /* HAVE_PCAP_CREATE */
1122
1123 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1124 case 'j':
1125 jflag = pcap_tstamp_type_name_to_val(optarg);
1126 if (jflag < 0)
1127 error("invalid time stamp type %s", optarg);
1128 break;
1129
1130 case 'J':
1131 Jflag++;
1132 break;
1133 #endif
1134
1135 case 'l':
1136 #ifdef WIN32
1137 /*
1138 * _IOLBF is the same as _IOFBF in Microsoft's C
1139 * libraries; the only alternative they offer
1140 * is _IONBF.
1141 *
1142 * XXX - this should really be checking for MSVC++,
1143 * not WIN32, if, for example, MinGW has its own
1144 * C library that is more UNIX-compatible.
1145 */
1146 setvbuf(stdout, NULL, _IONBF, 0);
1147 #else /* WIN32 */
1148 #ifdef HAVE_SETLINEBUF
1149 setlinebuf(stdout);
1150 #else
1151 setvbuf(stdout, NULL, _IOLBF, 0);
1152 #endif
1153 #endif /* WIN32 */
1154 break;
1155
1156 case 'K':
1157 ++Kflag;
1158 break;
1159
1160 case 'm':
1161 #ifdef USE_LIBSMI
1162 if (smiLoadModule(optarg) == 0) {
1163 error("could not load MIB module %s", optarg);
1164 }
1165 sflag = 1;
1166 #else
1167 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1168 program_name, optarg);
1169 (void)fprintf(stderr, "(no libsmi support)\n");
1170 #endif
1171 break;
1172
1173 case 'M':
1174 /* TCP-MD5 shared secret */
1175 #ifndef HAVE_LIBCRYPTO
1176 warning("crypto code not compiled in");
1177 #endif
1178 sigsecret = optarg;
1179 break;
1180
1181 case 'n':
1182 ++nflag;
1183 break;
1184
1185 case 'N':
1186 ++Nflag;
1187 break;
1188
1189 case 'O':
1190 Oflag = 0;
1191 break;
1192
1193 case 'p':
1194 ++pflag;
1195 break;
1196
1197 case 'q':
1198 ++qflag;
1199 ++suppress_default_print;
1200 break;
1201
1202 #ifdef HAVE_PCAP_SETDIRECTION
1203 case 'Q':
1204 if (strcasecmp(optarg, "in") == 0)
1205 Qflag = PCAP_D_IN;
1206 else if (strcasecmp(optarg, "out") == 0)
1207 Qflag = PCAP_D_OUT;
1208 else if (strcasecmp(optarg, "inout") == 0)
1209 Qflag = PCAP_D_INOUT;
1210 else
1211 error("unknown capture direction `%s'", optarg);
1212 break;
1213 #endif /* HAVE_PCAP_SETDIRECTION */
1214
1215 case 'r':
1216 RFileName = optarg;
1217 break;
1218
1219 case 'R':
1220 Rflag = 0;
1221 break;
1222
1223 case 's':
1224 snaplen = strtol(optarg, &end, 0);
1225 if (optarg == end || *end != '\0'
1226 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
1227 error("invalid snaplen %s", optarg);
1228 else if (snaplen == 0)
1229 snaplen = MAXIMUM_SNAPLEN;
1230 break;
1231
1232 case 'S':
1233 ++Sflag;
1234 break;
1235
1236 case 't':
1237 ++tflag;
1238 break;
1239
1240 case 'T':
1241 if (strcasecmp(optarg, "vat") == 0)
1242 packettype = PT_VAT;
1243 else if (strcasecmp(optarg, "wb") == 0)
1244 packettype = PT_WB;
1245 else if (strcasecmp(optarg, "rpc") == 0)
1246 packettype = PT_RPC;
1247 else if (strcasecmp(optarg, "rtp") == 0)
1248 packettype = PT_RTP;
1249 else if (strcasecmp(optarg, "rtcp") == 0)
1250 packettype = PT_RTCP;
1251 else if (strcasecmp(optarg, "snmp") == 0)
1252 packettype = PT_SNMP;
1253 else if (strcasecmp(optarg, "cnfp") == 0)
1254 packettype = PT_CNFP;
1255 else if (strcasecmp(optarg, "tftp") == 0)
1256 packettype = PT_TFTP;
1257 else if (strcasecmp(optarg, "aodv") == 0)
1258 packettype = PT_AODV;
1259 else if (strcasecmp(optarg, "carp") == 0)
1260 packettype = PT_CARP;
1261 else if (strcasecmp(optarg, "radius") == 0)
1262 packettype = PT_RADIUS;
1263 else if (strcasecmp(optarg, "zmtp1") == 0)
1264 packettype = PT_ZMTP1;
1265 else if (strcasecmp(optarg, "vxlan") == 0)
1266 packettype = PT_VXLAN;
1267 else if (strcasecmp(optarg, "pgm") == 0)
1268 packettype = PT_PGM;
1269 else if (strcasecmp(optarg, "pgm_zmtp1") == 0)
1270 packettype = PT_PGM_ZMTP1;
1271 else if (strcasecmp(optarg, "lmp") == 0)
1272 packettype = PT_LMP;
1273 else
1274 error("unknown packet type `%s'", optarg);
1275 break;
1276
1277 case 'u':
1278 ++uflag;
1279 break;
1280
1281 #ifdef HAVE_PCAP_DUMP_FLUSH
1282 case 'U':
1283 ++Uflag;
1284 break;
1285 #endif
1286
1287 case 'v':
1288 ++vflag;
1289 break;
1290
1291 case 'V':
1292 VFileName = optarg;
1293 break;
1294
1295 case 'w':
1296 WFileName = optarg;
1297 break;
1298
1299 case 'W':
1300 Wflag = atoi(optarg);
1301 if (Wflag < 0)
1302 error("invalid number of output files %s", optarg);
1303 WflagChars = getWflagChars(Wflag);
1304 break;
1305
1306 case 'x':
1307 ++xflag;
1308 ++suppress_default_print;
1309 break;
1310
1311 case 'X':
1312 ++Xflag;
1313 ++suppress_default_print;
1314 break;
1315
1316 case 'y':
1317 gndo->ndo_dltname = optarg;
1318 gndo->ndo_dlt =
1319 pcap_datalink_name_to_val(gndo->ndo_dltname);
1320 if (gndo->ndo_dlt < 0)
1321 error("invalid data link type %s", gndo->ndo_dltname);
1322 break;
1323
1324 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1325 case 'Y':
1326 {
1327 /* Undocumented flag */
1328 #ifdef HAVE_PCAP_DEBUG
1329 extern int pcap_debug;
1330 pcap_debug = 1;
1331 #else
1332 extern int yydebug;
1333 yydebug = 1;
1334 #endif
1335 }
1336 break;
1337 #endif
1338 case 'z':
1339 zflag = strdup(optarg);
1340 break;
1341
1342 case 'Z':
1343 username = strdup(optarg);
1344 break;
1345
1346 case '#':
1347 gndo->ndo_packet_number = 1;
1348 break;
1349
1350 case OPTION_VERSION:
1351 print_version();
1352 exit(0);
1353 break;
1354
1355 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1356 case OPTION_TSTAMP_PRECISION:
1357 gndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1358 if (gndo->ndo_tstamp_precision < 0)
1359 error("unsupported time stamp precision");
1360 break;
1361 #endif
1362
1363 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1364 case OPTION_IMMEDIATE_MODE:
1365 gndo->ndo_immediate = 1;
1366 break;
1367 #endif
1368
1369 default:
1370 print_usage();
1371 exit(1);
1372 /* NOTREACHED */
1373 }
1374
1375 #ifdef HAVE_PCAP_FINDALLDEVS
1376 if (Dflag)
1377 show_devices_and_exit();
1378 #endif
1379
1380 switch (tflag) {
1381
1382 case 0: /* Default */
1383 case 4: /* Default + Date*/
1384 thiszone = gmt2local(0);
1385 break;
1386
1387 case 1: /* No time stamp */
1388 case 2: /* Unix timeval style */
1389 case 3: /* Microseconds since previous packet */
1390 case 5: /* Microseconds since first packet */
1391 break;
1392
1393 default: /* Not supported */
1394 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1395 break;
1396 }
1397
1398 if (fflag != 0 && (VFileName != NULL || RFileName != NULL))
1399 error("-f can not be used with -V or -r");
1400
1401 if (VFileName != NULL && RFileName != NULL)
1402 error("-V and -r are mutually exclusive.");
1403
1404 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1405 /*
1406 * If we're printing dissected packets to the standard output
1407 * rather than saving raw packets to a file, and the standard
1408 * output is a terminal, use immediate mode, as the user's
1409 * probably expecting to see packets pop up immediately.
1410 */
1411 if (WFileName == NULL && isatty(1))
1412 gndo->ndo_immediate = 1;
1413 #endif
1414
1415 #ifdef WITH_CHROOT
1416 /* if run as root, prepare for chrooting */
1417 if (getuid() == 0 || geteuid() == 0) {
1418 /* future extensibility for cmd-line arguments */
1419 if (!chroot_dir)
1420 chroot_dir = WITH_CHROOT;
1421 }
1422 #endif
1423
1424 #ifdef WITH_USER
1425 /* if run as root, prepare for dropping root privileges */
1426 if (getuid() == 0 || geteuid() == 0) {
1427 /* Run with '-Z root' to restore old behaviour */
1428 if (!username)
1429 username = WITH_USER;
1430 }
1431 #endif
1432
1433 if (RFileName != NULL || VFileName != NULL) {
1434 /*
1435 * If RFileName is non-null, it's the pathname of a
1436 * savefile to read. If VFileName is non-null, it's
1437 * the pathname of a file containing a list of pathnames
1438 * (one per line) of savefiles to read.
1439 *
1440 * In either case, we're reading a savefile, not doing
1441 * a live capture.
1442 */
1443 #ifndef WIN32
1444 /*
1445 * We don't need network access, so relinquish any set-UID
1446 * or set-GID privileges we have (if any).
1447 *
1448 * We do *not* want set-UID privileges when opening a
1449 * trace file, as that might let the user read other
1450 * people's trace files (especially if we're set-UID
1451 * root).
1452 */
1453 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1454 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1455 #endif /* WIN32 */
1456 if (VFileName != NULL) {
1457 if (VFileName[0] == '-' && VFileName[1] == '\0')
1458 VFile = stdin;
1459 else
1460 VFile = fopen(VFileName, "r");
1461
1462 if (VFile == NULL)
1463 error("Unable to open file: %s\n", strerror(errno));
1464
1465 ret = get_next_file(VFile, VFileLine);
1466 if (!ret)
1467 error("Nothing in %s\n", VFileName);
1468 RFileName = VFileLine;
1469 }
1470
1471 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1472 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1473 gndo->ndo_tstamp_precision, ebuf);
1474 #else
1475 pd = pcap_open_offline(RFileName, ebuf);
1476 #endif
1477
1478 if (pd == NULL)
1479 error("%s", ebuf);
1480 #ifdef HAVE_CAPSICUM
1481 cap_rights_init(&rights, CAP_READ);
1482 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1483 errno != ENOSYS) {
1484 error("unable to limit pcap descriptor");
1485 }
1486 #endif
1487 dlt = pcap_datalink(pd);
1488 dlt_name = pcap_datalink_val_to_name(dlt);
1489 if (dlt_name == NULL) {
1490 fprintf(stderr, "reading from file %s, link-type %u\n",
1491 RFileName, dlt);
1492 } else {
1493 fprintf(stderr,
1494 "reading from file %s, link-type %s (%s)\n",
1495 RFileName, dlt_name,
1496 pcap_datalink_val_to_description(dlt));
1497 }
1498 } else {
1499 /*
1500 * We're doing a live capture.
1501 */
1502 if (device == NULL) {
1503 device = pcap_lookupdev(ebuf);
1504 if (device == NULL)
1505 error("%s", ebuf);
1506 }
1507 #ifdef WIN32
1508 /*
1509 * Print a message to the standard error on Windows.
1510 * XXX - why do it here, with a different message?
1511 */
1512 if(strlen(device) == 1) /* we assume that an ASCII string is always longer than 1 char */
1513 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1514 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1515 }
1516 else
1517 {
1518 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1519 }
1520
1521 fflush(stderr);
1522 #endif /* WIN32 */
1523 #ifdef HAVE_PCAP_CREATE
1524 pd = pcap_create(device, ebuf);
1525 if (pd == NULL)
1526 error("%s", ebuf);
1527 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1528 if (Jflag)
1529 show_tstamp_types_and_exit(device, pd);
1530 #endif
1531 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1532 status = pcap_set_tstamp_precision(pd, gndo->ndo_tstamp_precision);
1533 if (status != 0)
1534 error("%s: Can't set %ssecond time stamp precision: %s",
1535 device,
1536 tstamp_precision_to_string(gndo->ndo_tstamp_precision),
1537 pcap_statustostr(status));
1538 #endif
1539
1540 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1541 if (gndo->ndo_immediate) {
1542 status = pcap_set_immediate_mode(pd, 1);
1543 if (status != 0)
1544 error("%s: Can't set immediate mode: %s",
1545 device,
1546 pcap_statustostr(status));
1547 }
1548 #endif
1549 /*
1550 * Is this an interface that supports monitor mode?
1551 */
1552 if (pcap_can_set_rfmon(pd) == 1)
1553 supports_monitor_mode = 1;
1554 else
1555 supports_monitor_mode = 0;
1556 status = pcap_set_snaplen(pd, snaplen);
1557 if (status != 0)
1558 error("%s: Can't set snapshot length: %s",
1559 device, pcap_statustostr(status));
1560 status = pcap_set_promisc(pd, !pflag);
1561 if (status != 0)
1562 error("%s: Can't set promiscuous mode: %s",
1563 device, pcap_statustostr(status));
1564 if (Iflag) {
1565 status = pcap_set_rfmon(pd, 1);
1566 if (status != 0)
1567 error("%s: Can't set monitor mode: %s",
1568 device, pcap_statustostr(status));
1569 }
1570 status = pcap_set_timeout(pd, 1000);
1571 if (status != 0)
1572 error("%s: pcap_set_timeout failed: %s",
1573 device, pcap_statustostr(status));
1574 if (Bflag != 0) {
1575 status = pcap_set_buffer_size(pd, Bflag);
1576 if (status != 0)
1577 error("%s: Can't set buffer size: %s",
1578 device, pcap_statustostr(status));
1579 }
1580 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1581 if (jflag != -1) {
1582 status = pcap_set_tstamp_type(pd, jflag);
1583 if (status < 0)
1584 error("%s: Can't set time stamp type: %s",
1585 device, pcap_statustostr(status));
1586 }
1587 #endif
1588 status = pcap_activate(pd);
1589 if (status < 0) {
1590 /*
1591 * pcap_activate() failed.
1592 */
1593 cp = pcap_geterr(pd);
1594 if (status == PCAP_ERROR)
1595 error("%s", cp);
1596 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1597 status == PCAP_ERROR_PERM_DENIED) &&
1598 *cp != '\0')
1599 error("%s: %s\n(%s)", device,
1600 pcap_statustostr(status), cp);
1601 else
1602 error("%s: %s", device,
1603 pcap_statustostr(status));
1604 } else if (status > 0) {
1605 /*
1606 * pcap_activate() succeeded, but it's warning us
1607 * of a problem it had.
1608 */
1609 cp = pcap_geterr(pd);
1610 if (status == PCAP_WARNING)
1611 warning("%s", cp);
1612 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1613 *cp != '\0')
1614 warning("%s: %s\n(%s)", device,
1615 pcap_statustostr(status), cp);
1616 else
1617 warning("%s: %s", device,
1618 pcap_statustostr(status));
1619 }
1620 #ifdef HAVE_PCAP_SETDIRECTION
1621 if (Qflag != -1) {
1622 status = pcap_setdirection(pd, Qflag);
1623 if (status != 0)
1624 error("%s: pcap_setdirection() failed: %s",
1625 device, pcap_geterr(pd));
1626 }
1627 #endif /* HAVE_PCAP_SETDIRECTION */
1628 #else
1629 *ebuf = '\0';
1630 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1631 if (pd == NULL)
1632 error("%s", ebuf);
1633 else if (*ebuf)
1634 warning("%s", ebuf);
1635 #endif /* HAVE_PCAP_CREATE */
1636 /*
1637 * Let user own process after socket has been opened.
1638 */
1639 #ifndef WIN32
1640 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1641 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1642 #endif /* WIN32 */
1643 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1644 if(Bflag != 0)
1645 if(pcap_setbuff(pd, Bflag)==-1){
1646 error("%s", pcap_geterr(pd));
1647 }
1648 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1649 if (Lflag)
1650 show_dlts_and_exit(device, pd);
1651 if (gndo->ndo_dlt >= 0) {
1652 #ifdef HAVE_PCAP_SET_DATALINK
1653 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1654 error("%s", pcap_geterr(pd));
1655 #else
1656 /*
1657 * We don't actually support changing the
1658 * data link type, so we only let them
1659 * set it to what it already is.
1660 */
1661 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1662 error("%s is not one of the DLTs supported by this device\n",
1663 gndo->ndo_dltname);
1664 }
1665 #endif
1666 (void)fprintf(stderr, "%s: data link type %s\n",
1667 program_name, gndo->ndo_dltname);
1668 (void)fflush(stderr);
1669 }
1670 i = pcap_snapshot(pd);
1671 if (snaplen < i) {
1672 warning("snaplen raised from %d to %d", snaplen, i);
1673 snaplen = i;
1674 }
1675 if(fflag != 0) {
1676 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1677 warning("foreign (-f) flag used but: %s", ebuf);
1678 }
1679 }
1680
1681 }
1682 if (infile)
1683 cmdbuf = read_infile(infile);
1684 else
1685 cmdbuf = copy_argv(&argv[optind]);
1686
1687 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1688 error("%s", pcap_geterr(pd));
1689 if (dflag) {
1690 bpf_dump(&fcode, dflag);
1691 pcap_close(pd);
1692 free(cmdbuf);
1693 exit(0);
1694 }
1695 init_addrtoname(gndo, localnet, netmask);
1696 init_checksum();
1697
1698 #ifndef WIN32
1699 (void)setsignal(SIGPIPE, cleanup);
1700 (void)setsignal(SIGTERM, cleanup);
1701 (void)setsignal(SIGINT, cleanup);
1702 #endif /* WIN32 */
1703 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1704 (void)setsignal(SIGCHLD, child_cleanup);
1705 #endif
1706 /* Cooperate with nohup(1) */
1707 #ifndef WIN32
1708 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1709 (void)setsignal(SIGHUP, oldhandler);
1710 #endif /* WIN32 */
1711
1712 #ifndef WIN32
1713 /*
1714 * If a user name was specified with "-Z", attempt to switch to
1715 * that user's UID. This would probably be used with sudo,
1716 * to allow tcpdump to be run in a special restricted
1717 * account (if you just want to allow users to open capture
1718 * devices, and can't just give users that permission,
1719 * you'd make tcpdump set-UID or set-GID).
1720 *
1721 * Tcpdump doesn't necessarily write only to one savefile;
1722 * the general only way to allow a -Z instance to write to
1723 * savefiles as the user under whose UID it's run, rather
1724 * than as the user specified with -Z, would thus be to switch
1725 * to the original user ID before opening a capture file and
1726 * then switch back to the -Z user ID after opening the savefile.
1727 * Switching to the -Z user ID only after opening the first
1728 * savefile doesn't handle the general case.
1729 */
1730
1731 if (getuid() == 0 || geteuid() == 0) {
1732 #ifdef HAVE_CAP_NG_H
1733 /* Drop all capabilities from effective set */
1734 capng_clear(CAPNG_EFFECTIVE);
1735 /* We are running as root and we will be writing to savefile */
1736 if (WFileName && username) {
1737 /* Add capabilities we will need*/
1738 capng_updatev(
1739 CAPNG_ADD,
1740 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1741 CAP_SETUID,
1742 CAP_SETGID,
1743 CAP_DAC_OVERRIDE,
1744 -1);
1745 capng_apply(CAPNG_SELECT_BOTH);
1746 }
1747 #endif /* HAVE_CAP_NG_H */
1748 if (username || chroot_dir)
1749 droproot(username, chroot_dir);
1750
1751 }
1752 #endif /* WIN32 */
1753
1754 if (pcap_setfilter(pd, &fcode) < 0)
1755 error("%s", pcap_geterr(pd));
1756 #ifdef HAVE_CAPSICUM
1757 if (RFileName == NULL && VFileName == NULL) {
1758 static const unsigned long cmds[] = { BIOCGSTATS };
1759
1760 cap_rights_init(&rights, CAP_IOCTL, CAP_READ);
1761 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1762 errno != ENOSYS) {
1763 error("unable to limit pcap descriptor");
1764 }
1765 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1766 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1767 error("unable to limit ioctls on pcap descriptor");
1768 }
1769 }
1770 #endif
1771 if (WFileName) {
1772 pcap_dumper_t *p;
1773 /* Do not exceed the default PATH_MAX for files. */
1774 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1775
1776 if (dumpinfo.CurrentFileName == NULL)
1777 error("malloc of dumpinfo.CurrentFileName");
1778
1779 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1780 if (Cflag != 0)
1781 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1782 else
1783 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1784
1785 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1786 #ifdef HAVE_CAP_NG_H
1787 /* Give up capabilities, clear Effective set */
1788 capng_clear(CAPNG_EFFECTIVE);
1789 #endif
1790 if (p == NULL)
1791 error("%s", pcap_geterr(pd));
1792 #ifdef HAVE_CAPSICUM
1793 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
1794 if (cap_rights_limit(fileno(pcap_dump_file(p)), &rights) < 0 &&
1795 errno != ENOSYS) {
1796 error("unable to limit dump descriptor");
1797 }
1798 #endif
1799 if (Cflag != 0 || Gflag != 0) {
1800 #ifdef HAVE_CAPSICUM
1801 dumpinfo.WFileName = strdup(basename(WFileName));
1802 dumpinfo.dirfd = open(dirname(WFileName),
1803 O_DIRECTORY | O_RDONLY);
1804 if (dumpinfo.dirfd < 0) {
1805 error("unable to open directory %s",
1806 dirname(WFileName));
1807 }
1808 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1809 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1810 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1811 errno != ENOSYS) {
1812 error("unable to limit directory rights");
1813 }
1814 #else /* !HAVE_CAPSICUM */
1815 dumpinfo.WFileName = WFileName;
1816 #endif
1817 callback = dump_packet_and_trunc;
1818 dumpinfo.pd = pd;
1819 dumpinfo.p = p;
1820 pcap_userdata = (u_char *)&dumpinfo;
1821 } else {
1822 callback = dump_packet;
1823 pcap_userdata = (u_char *)p;
1824 }
1825 #ifdef HAVE_PCAP_DUMP_FLUSH
1826 if (Uflag)
1827 pcap_dump_flush(p);
1828 #endif
1829 } else {
1830 type = pcap_datalink(pd);
1831 printinfo = get_print_info(type);
1832 callback = print_packet;
1833 pcap_userdata = (u_char *)&printinfo;
1834 }
1835
1836 #ifdef SIGNAL_REQ_INFO
1837 /*
1838 * We can't get statistics when reading from a file rather
1839 * than capturing from a device.
1840 */
1841 if (RFileName == NULL)
1842 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1843 #endif
1844
1845 if (vflag > 0 && WFileName) {
1846 /*
1847 * When capturing to a file, "-v" means tcpdump should,
1848 * every 10 secodns, "v"erbosely report the number of
1849 * packets captured.
1850 */
1851 #ifdef USE_WIN32_MM_TIMER
1852 /* call verbose_stats_dump() each 1000 +/-100msec */
1853 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1854 setvbuf(stderr, NULL, _IONBF, 0);
1855 #elif defined(HAVE_ALARM)
1856 (void)setsignal(SIGALRM, verbose_stats_dump);
1857 alarm(1);
1858 #endif
1859 }
1860
1861 #ifndef WIN32
1862 if (RFileName == NULL) {
1863 /*
1864 * Live capture (if -V was specified, we set RFileName
1865 * to a file from the -V file). Print a message to
1866 * the standard error on UN*X.
1867 */
1868 if (!vflag && !WFileName) {
1869 (void)fprintf(stderr,
1870 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1871 program_name);
1872 } else
1873 (void)fprintf(stderr, "%s: ", program_name);
1874 dlt = pcap_datalink(pd);
1875 dlt_name = pcap_datalink_val_to_name(dlt);
1876 if (dlt_name == NULL) {
1877 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1878 device, dlt, snaplen);
1879 } else {
1880 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1881 device, dlt_name,
1882 pcap_datalink_val_to_description(dlt), snaplen);
1883 }
1884 (void)fflush(stderr);
1885 }
1886 #endif /* WIN32 */
1887
1888 #ifdef HAVE_CAPSICUM
1889 cansandbox = (nflag && VFileName == NULL && zflag == NULL);
1890 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1891 error("unable to enter the capability mode");
1892 if (cap_sandboxed())
1893 fprintf(stderr, "capability mode sandbox enabled\n");
1894 #endif /* HAVE_CAPSICUM */
1895
1896 do {
1897 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1898 if (WFileName == NULL) {
1899 /*
1900 * We're printing packets. Flush the printed output,
1901 * so it doesn't get intermingled with error output.
1902 */
1903 if (status == -2) {
1904 /*
1905 * We got interrupted, so perhaps we didn't
1906 * manage to finish a line we were printing.
1907 * Print an extra newline, just in case.
1908 */
1909 putchar('\n');
1910 }
1911 (void)fflush(stdout);
1912 }
1913 if (status == -2) {
1914 /*
1915 * We got interrupted. If we are reading multiple
1916 * files (via -V) set these so that we stop.
1917 */
1918 VFileName = NULL;
1919 ret = NULL;
1920 }
1921 if (status == -1) {
1922 /*
1923 * Error. Report it.
1924 */
1925 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1926 program_name, pcap_geterr(pd));
1927 }
1928 if (RFileName == NULL) {
1929 /*
1930 * We're doing a live capture. Report the capture
1931 * statistics.
1932 */
1933 info(1);
1934 }
1935 pcap_close(pd);
1936 if (VFileName != NULL) {
1937 ret = get_next_file(VFile, VFileLine);
1938 if (ret) {
1939 RFileName = VFileLine;
1940 pd = pcap_open_offline(RFileName, ebuf);
1941 if (pd == NULL)
1942 error("%s", ebuf);
1943 #ifdef HAVE_CAPSICUM
1944 cap_rights_init(&rights, CAP_READ);
1945 if (cap_rights_limit(fileno(pcap_file(pd)),
1946 &rights) < 0 && errno != ENOSYS) {
1947 error("unable to limit pcap descriptor");
1948 }
1949 #endif
1950 new_dlt = pcap_datalink(pd);
1951 if (WFileName && new_dlt != dlt)
1952 error("%s: new dlt does not match original", RFileName);
1953 printinfo = get_print_info(new_dlt);
1954 dlt_name = pcap_datalink_val_to_name(new_dlt);
1955 if (dlt_name == NULL) {
1956 fprintf(stderr, "reading from file %s, link-type %u\n",
1957 RFileName, new_dlt);
1958 } else {
1959 fprintf(stderr,
1960 "reading from file %s, link-type %s (%s)\n",
1961 RFileName, dlt_name,
1962 pcap_datalink_val_to_description(new_dlt));
1963 }
1964 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1965 error("%s", pcap_geterr(pd));
1966 if (pcap_setfilter(pd, &fcode) < 0)
1967 error("%s", pcap_geterr(pd));
1968 }
1969 }
1970 }
1971 while (ret != NULL);
1972
1973 free(cmdbuf);
1974 exit(status == -1 ? 1 : 0);
1975 }
1976
1977 /* make a clean exit on interrupts */
1978 static RETSIGTYPE
1979 cleanup(int signo _U_)
1980 {
1981 #ifdef USE_WIN32_MM_TIMER
1982 if (timer_id)
1983 timeKillEvent(timer_id);
1984 timer_id = 0;
1985 #elif defined(HAVE_ALARM)
1986 alarm(0);
1987 #endif
1988
1989 #ifdef HAVE_PCAP_BREAKLOOP
1990 /*
1991 * We have "pcap_breakloop()"; use it, so that we do as little
1992 * as possible in the signal handler (it's probably not safe
1993 * to do anything with standard I/O streams in a signal handler -
1994 * the ANSI C standard doesn't say it is).
1995 */
1996 pcap_breakloop(pd);
1997 #else
1998 /*
1999 * We don't have "pcap_breakloop()"; this isn't safe, but
2000 * it's the best we can do. Print the summary if we're
2001 * not reading from a savefile - i.e., if we're doing a
2002 * live capture - and exit.
2003 */
2004 if (pd != NULL && pcap_file(pd) == NULL) {
2005 /*
2006 * We got interrupted, so perhaps we didn't
2007 * manage to finish a line we were printing.
2008 * Print an extra newline, just in case.
2009 */
2010 putchar('\n');
2011 (void)fflush(stdout);
2012 info(1);
2013 }
2014 exit(0);
2015 #endif
2016 }
2017
2018 /*
2019 On windows, we do not use a fork, so we do not care less about
2020 waiting a child processes to die
2021 */
2022 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2023 static RETSIGTYPE
2024 child_cleanup(int signo _U_)
2025 {
2026 wait(NULL);
2027 }
2028 #endif /* HAVE_FORK && HAVE_VFORK */
2029
2030 static void
2031 info(register int verbose)
2032 {
2033 struct pcap_stat stat;
2034
2035 /*
2036 * Older versions of libpcap didn't set ps_ifdrop on some
2037 * platforms; initialize it to 0 to handle that.
2038 */
2039 stat.ps_ifdrop = 0;
2040 if (pcap_stats(pd, &stat) < 0) {
2041 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2042 infoprint = 0;
2043 return;
2044 }
2045
2046 if (!verbose)
2047 fprintf(stderr, "%s: ", program_name);
2048
2049 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
2050 PLURAL_SUFFIX(packets_captured));
2051 if (!verbose)
2052 fputs(", ", stderr);
2053 else
2054 putc('\n', stderr);
2055 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
2056 PLURAL_SUFFIX(stat.ps_recv));
2057 if (!verbose)
2058 fputs(", ", stderr);
2059 else
2060 putc('\n', stderr);
2061 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
2062 PLURAL_SUFFIX(stat.ps_drop));
2063 if (stat.ps_ifdrop != 0) {
2064 if (!verbose)
2065 fputs(", ", stderr);
2066 else
2067 putc('\n', stderr);
2068 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
2069 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
2070 } else
2071 putc('\n', stderr);
2072 infoprint = 0;
2073 }
2074
2075 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2076 static void
2077 compress_savefile(const char *filename)
2078 {
2079 # ifdef HAVE_FORK
2080 if (fork())
2081 # else
2082 if (vfork())
2083 # endif
2084 return;
2085 /*
2086 * Set to lowest priority so that this doesn't disturb the capture
2087 */
2088 #ifdef NZERO
2089 setpriority(PRIO_PROCESS, 0, NZERO - 1);
2090 #else
2091 setpriority(PRIO_PROCESS, 0, 19);
2092 #endif
2093 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2094 fprintf(stderr,
2095 "compress_savefile:execlp(%s, %s): %s\n",
2096 zflag,
2097 filename,
2098 strerror(errno));
2099 # ifdef HAVE_FORK
2100 exit(1);
2101 # else
2102 _exit(1);
2103 # endif
2104 }
2105 #else /* HAVE_FORK && HAVE_VFORK */
2106 static void
2107 compress_savefile(const char *filename)
2108 {
2109 fprintf(stderr,
2110 "compress_savefile failed. Functionality not implemented under your system\n");
2111 }
2112 #endif /* HAVE_FORK && HAVE_VFORK */
2113
2114 static void
2115 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2116 {
2117 struct dump_info *dump_info;
2118 #ifdef HAVE_CAPSICUM
2119 cap_rights_t rights;
2120 #endif
2121
2122 ++packets_captured;
2123
2124 ++infodelay;
2125
2126 dump_info = (struct dump_info *)user;
2127
2128 /*
2129 * XXX - this won't force the file to rotate on the specified time
2130 * boundary, but it will rotate on the first packet received after the
2131 * specified Gflag number of seconds. Note: if a Gflag time boundary
2132 * and a Cflag size boundary coincide, the time rotation will occur
2133 * first thereby cancelling the Cflag boundary (since the file should
2134 * be 0).
2135 */
2136 if (Gflag != 0) {
2137 /* Check if it is time to rotate */
2138 time_t t;
2139
2140 /* Get the current time */
2141 if ((t = time(NULL)) == (time_t)-1) {
2142 error("dump_and_trunc_packet: can't get current_time: %s",
2143 pcap_strerror(errno));
2144 }
2145
2146
2147 /* If the time is greater than the specified window, rotate */
2148 if (t - Gflag_time >= Gflag) {
2149 #ifdef HAVE_CAPSICUM
2150 FILE *fp;
2151 int fd;
2152 #endif
2153
2154 /* Update the Gflag_time */
2155 Gflag_time = t;
2156 /* Update Gflag_count */
2157 Gflag_count++;
2158 /*
2159 * Close the current file and open a new one.
2160 */
2161 pcap_dump_close(dump_info->p);
2162
2163 /*
2164 * Compress the file we just closed, if the user asked for it
2165 */
2166 if (zflag != NULL)
2167 compress_savefile(dump_info->CurrentFileName);
2168
2169 /*
2170 * Check to see if we've exceeded the Wflag (when
2171 * not using Cflag).
2172 */
2173 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2174 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2175 Wflag);
2176 exit(0);
2177 /* NOTREACHED */
2178 }
2179 if (dump_info->CurrentFileName != NULL)
2180 free(dump_info->CurrentFileName);
2181 /* Allocate space for max filename + \0. */
2182 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2183 if (dump_info->CurrentFileName == NULL)
2184 error("dump_packet_and_trunc: malloc");
2185 /*
2186 * Gflag was set otherwise we wouldn't be here. Reset the count
2187 * so multiple files would end with 1,2,3 in the filename.
2188 * The counting is handled with the -C flow after this.
2189 */
2190 Cflag_count = 0;
2191
2192 /*
2193 * This is always the first file in the Cflag
2194 * rotation: e.g. 0
2195 * We also don't need numbering if Cflag is not set.
2196 */
2197 if (Cflag != 0)
2198 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2199 WflagChars);
2200 else
2201 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2202
2203 #ifdef HAVE_CAP_NG_H
2204 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2205 capng_apply(CAPNG_EFFECTIVE);
2206 #endif /* HAVE_CAP_NG_H */
2207 #ifdef HAVE_CAPSICUM
2208 fd = openat(dump_info->dirfd,
2209 dump_info->CurrentFileName,
2210 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2211 if (fd < 0) {
2212 error("unable to open file %s",
2213 dump_info->CurrentFileName);
2214 }
2215 fp = fdopen(fd, "w");
2216 if (fp == NULL) {
2217 error("unable to fdopen file %s",
2218 dump_info->CurrentFileName);
2219 }
2220 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2221 #else /* !HAVE_CAPSICUM */
2222 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2223 #endif
2224 #ifdef HAVE_CAP_NG_H
2225 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2226 capng_apply(CAPNG_EFFECTIVE);
2227 #endif /* HAVE_CAP_NG_H */
2228 if (dump_info->p == NULL)
2229 error("%s", pcap_geterr(pd));
2230 #ifdef HAVE_CAPSICUM
2231 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
2232 if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
2233 &rights) < 0 && errno != ENOSYS) {
2234 error("unable to limit dump descriptor");
2235 }
2236 #endif
2237 }
2238 }
2239
2240 /*
2241 * XXX - this won't prevent capture files from getting
2242 * larger than Cflag - the last packet written to the
2243 * file could put it over Cflag.
2244 */
2245 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
2246 #ifdef HAVE_CAPSICUM
2247 FILE *fp;
2248 int fd;
2249 #endif
2250
2251 /*
2252 * Close the current file and open a new one.
2253 */
2254 pcap_dump_close(dump_info->p);
2255
2256 /*
2257 * Compress the file we just closed, if the user asked for it
2258 */
2259 if (zflag != NULL)
2260 compress_savefile(dump_info->CurrentFileName);
2261
2262 Cflag_count++;
2263 if (Wflag > 0) {
2264 if (Cflag_count >= Wflag)
2265 Cflag_count = 0;
2266 }
2267 if (dump_info->CurrentFileName != NULL)
2268 free(dump_info->CurrentFileName);
2269 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2270 if (dump_info->CurrentFileName == NULL)
2271 error("dump_packet_and_trunc: malloc");
2272 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2273 #ifdef HAVE_CAPSICUM
2274 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2275 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2276 if (fd < 0) {
2277 error("unable to open file %s",
2278 dump_info->CurrentFileName);
2279 }
2280 fp = fdopen(fd, "w");
2281 if (fp == NULL) {
2282 error("unable to fdopen file %s",
2283 dump_info->CurrentFileName);
2284 }
2285 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2286 #else /* !HAVE_CAPSICUM */
2287 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2288 #endif
2289 if (dump_info->p == NULL)
2290 error("%s", pcap_geterr(pd));
2291 #ifdef HAVE_CAPSICUM
2292 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
2293 if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
2294 &rights) < 0 && errno != ENOSYS) {
2295 error("unable to limit dump descriptor");
2296 }
2297 #endif
2298 }
2299
2300 pcap_dump((u_char *)dump_info->p, h, sp);
2301 #ifdef HAVE_PCAP_DUMP_FLUSH
2302 if (Uflag)
2303 pcap_dump_flush(dump_info->p);
2304 #endif
2305
2306 --infodelay;
2307 if (infoprint)
2308 info(0);
2309 }
2310
2311 static void
2312 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2313 {
2314 ++packets_captured;
2315
2316 ++infodelay;
2317
2318 pcap_dump(user, h, sp);
2319 #ifdef HAVE_PCAP_DUMP_FLUSH
2320 if (Uflag)
2321 pcap_dump_flush((pcap_dumper_t *)user);
2322 #endif
2323
2324 --infodelay;
2325 if (infoprint)
2326 info(0);
2327 }
2328
2329 static void
2330 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2331 {
2332 struct print_info *print_info;
2333 u_int hdrlen;
2334 netdissect_options *ndo;
2335
2336 ++packets_captured;
2337
2338 ++infodelay;
2339
2340 print_info = (struct print_info *)user;
2341 ndo = print_info->ndo;
2342
2343 if(ndo->ndo_packet_number)
2344 ND_PRINT((ndo, "%5u ", packets_captured));
2345
2346 ts_print(ndo, &h->ts);
2347
2348 /*
2349 * Some printers want to check that they're not walking off the
2350 * end of the packet.
2351 * Rather than pass it all the way down, we set this member
2352 * of the netdissect_options structure.
2353 */
2354 ndo->ndo_snapend = sp + h->caplen;
2355
2356 if(print_info->ndo_type) {
2357 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
2358 } else {
2359 hdrlen = (*print_info->p.printer)(h, sp);
2360 }
2361
2362 /*
2363 * Restore the original snapend, as a printer might have
2364 * changed it.
2365 */
2366 ndo->ndo_snapend = sp + h->caplen;
2367 if (ndo->ndo_Xflag) {
2368 /*
2369 * Print the raw packet data in hex and ASCII.
2370 */
2371 if (ndo->ndo_Xflag > 1) {
2372 /*
2373 * Include the link-layer header.
2374 */
2375 hex_and_ascii_print(ndo, "\n\t", sp, h->caplen);
2376 } else {
2377 /*
2378 * Don't include the link-layer header - and if
2379 * we have nothing past the link-layer header,
2380 * print nothing.
2381 */
2382 if (h->caplen > hdrlen)
2383 hex_and_ascii_print(ndo, "\n\t", sp + hdrlen,
2384 h->caplen - hdrlen);
2385 }
2386 } else if (ndo->ndo_xflag) {
2387 /*
2388 * Print the raw packet data in hex.
2389 */
2390 if (ndo->ndo_xflag > 1) {
2391 /*
2392 * Include the link-layer header.
2393 */
2394 hex_print(ndo, "\n\t", sp, h->caplen);
2395 } else {
2396 /*
2397 * Don't include the link-layer header - and if
2398 * we have nothing past the link-layer header,
2399 * print nothing.
2400 */
2401 if (h->caplen > hdrlen)
2402 hex_print(ndo, "\n\t", sp + hdrlen,
2403 h->caplen - hdrlen);
2404 }
2405 } else if (ndo->ndo_Aflag) {
2406 /*
2407 * Print the raw packet data in ASCII.
2408 */
2409 if (ndo->ndo_Aflag > 1) {
2410 /*
2411 * Include the link-layer header.
2412 */
2413 ascii_print(ndo, sp, h->caplen);
2414 } else {
2415 /*
2416 * Don't include the link-layer header - and if
2417 * we have nothing past the link-layer header,
2418 * print nothing.
2419 */
2420 if (h->caplen > hdrlen)
2421 ascii_print(ndo, sp + hdrlen, h->caplen - hdrlen);
2422 }
2423 }
2424
2425 putchar('\n');
2426
2427 --infodelay;
2428 if (infoprint)
2429 info(0);
2430 }
2431
2432 #ifdef WIN32
2433 /*
2434 * XXX - there should really be libpcap calls to get the version
2435 * number as a string (the string would be generated from #defines
2436 * at run time, so that it's not generated from string constants
2437 * in the library, as, on many UNIX systems, those constants would
2438 * be statically linked into the application executable image, and
2439 * would thus reflect the version of libpcap on the system on
2440 * which the application was *linked*, not the system on which it's
2441 * *running*.
2442 *
2443 * That routine should be documented, unlike the "version[]"
2444 * string, so that UNIX vendors providing their own libpcaps
2445 * don't omit it (as a couple of vendors have...).
2446 *
2447 * Packet.dll should perhaps also export a routine to return the
2448 * version number of the Packet.dll code, to supply the
2449 * "Wpcap_version" information on Windows.
2450 */
2451 char WDversion[]="current-git.tcpdump.org";
2452 #if !defined(HAVE_GENERATED_VERSION)
2453 char version[]="current-git.tcpdump.org";
2454 #endif
2455 char pcap_version[]="current-git.tcpdump.org";
2456 char Wpcap_version[]="3.1";
2457 #endif
2458
2459 /*
2460 * By default, print the specified data out in hex and ASCII.
2461 */
2462 static void
2463 ndo_default_print(netdissect_options *ndo, const u_char *bp, u_int length)
2464 {
2465 hex_and_ascii_print(ndo, "\n\t", bp, length); /* pass on lf and indentation string */
2466 }
2467
2468 void
2469 default_print(const u_char *bp, u_int length)
2470 {
2471 ndo_default_print(gndo, bp, length);
2472 }
2473
2474 #ifdef SIGNAL_REQ_INFO
2475 RETSIGTYPE requestinfo(int signo _U_)
2476 {
2477 if (infodelay)
2478 ++infoprint;
2479 else
2480 info(0);
2481 }
2482 #endif
2483
2484 /*
2485 * Called once each second in verbose mode while dumping to file
2486 */
2487 #ifdef USE_WIN32_MM_TIMER
2488 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2489 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2490 {
2491 struct pcap_stat stat;
2492
2493 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2494 fprintf(stderr, "Got %u\r", packets_captured);
2495 }
2496 #elif defined(HAVE_ALARM)
2497 static void verbose_stats_dump(int sig _U_)
2498 {
2499 struct pcap_stat stat;
2500
2501 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2502 fprintf(stderr, "Got %u\r", packets_captured);
2503 alarm(1);
2504 }
2505 #endif
2506
2507 USES_APPLE_DEPRECATED_API
2508 static void
2509 print_version(void)
2510 {
2511 extern char version[];
2512 #ifndef HAVE_PCAP_LIB_VERSION
2513 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
2514 extern char pcap_version[];
2515 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2516 static char pcap_version[] = "unknown";
2517 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2518 #endif /* HAVE_PCAP_LIB_VERSION */
2519
2520 #ifdef HAVE_PCAP_LIB_VERSION
2521 #ifdef WIN32
2522 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2523 #else /* WIN32 */
2524 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2525 #endif /* WIN32 */
2526 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2527 #else /* HAVE_PCAP_LIB_VERSION */
2528 #ifdef WIN32
2529 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2530 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2531 #else /* WIN32 */
2532 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2533 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2534 #endif /* WIN32 */
2535 #endif /* HAVE_PCAP_LIB_VERSION */
2536
2537 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2538 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2539 #endif
2540
2541 #ifdef USE_LIBSMI
2542 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2543 #endif
2544 }
2545 USES_APPLE_RST
2546
2547 static void
2548 print_usage(void)
2549 {
2550 print_version();
2551 (void)fprintf(stderr,
2552 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2553 (void)fprintf(stderr,
2554 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2555 (void)fprintf(stderr,
2556 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2557 #ifdef HAVE_PCAP_SETDIRECTION
2558 (void)fprintf(stderr,
2559 "\t\t[ -Q in|out|inout ]\n");
2560 #endif
2561 (void)fprintf(stderr,
2562 "\t\t[ -r file ] [ -s snaplen ] ");
2563 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2564 (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2565 (void)fprintf(stderr,
2566 "\t\t");
2567 #endif
2568 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2569 (void)fprintf(stderr, "[ --immediate-mode ] ");
2570 #endif
2571 (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2572 (void)fprintf(stderr,
2573 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2574 (void)fprintf(stderr,
2575 "\t\t[ -Z user ] [ expression ]\n");
2576 }
2577
2578
2579
2580 /* VARARGS */
2581 static void
2582 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
2583 {
2584 va_list ap;
2585
2586 (void)fprintf(stderr, "%s: ", program_name);
2587 va_start(ap, fmt);
2588 (void)vfprintf(stderr, fmt, ap);
2589 va_end(ap);
2590 if (*fmt) {
2591 fmt += strlen(fmt);
2592 if (fmt[-1] != '\n')
2593 (void)fputc('\n', stderr);
2594 }
2595 exit(1);
2596 /* NOTREACHED */
2597 }
2598
2599 /* VARARGS */
2600 static void
2601 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2602 {
2603 va_list ap;
2604
2605 (void)fprintf(stderr, "%s: WARNING: ", program_name);
2606 va_start(ap, fmt);
2607 (void)vfprintf(stderr, fmt, ap);
2608 va_end(ap);
2609 if (*fmt) {
2610 fmt += strlen(fmt);
2611 if (fmt[-1] != '\n')
2612 (void)fputc('\n', stderr);
2613 }
2614 }
2615 /*
2616 * Local Variables:
2617 * c-style: whitesmith
2618 * c-basic-offset: 8
2619 * End:
2620 */