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