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