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