]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
Have a #define to squelch -Wunused-result warnings.
[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 /*
29 * tcpdump - dump traffic on a network
30 *
31 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
32 * Mercilessly hacked and occasionally improved since then via the
33 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
34 */
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 /*
41 * Some older versions of Mac OS X may ship pcap.h from libpcap 0.6 with a
42 * libpcap based on 0.8. That means it has pcap_findalldevs() but the
43 * header doesn't define pcap_if_t, meaning that we can't actually *use*
44 * pcap_findalldevs().
45 */
46 #ifdef HAVE_PCAP_FINDALLDEVS
47 #ifndef HAVE_PCAP_IF_T
48 #undef HAVE_PCAP_FINDALLDEVS
49 #endif
50 #endif
51
52 #include "netdissect-stdinc.h"
53
54 /*
55 * This must appear after including netdissect-stdinc.h, so that _U_ is
56 * defined.
57 */
58 #ifndef lint
59 static const char copyright[] _U_ =
60 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
61 The Regents of the University of California. All rights reserved.\n";
62 #endif
63
64 #include <sys/stat.h>
65
66 #ifdef HAVE_FCNTL_H
67 #include <fcntl.h>
68 #endif
69
70 #ifdef HAVE_LIBCRYPTO
71 #include <openssl/crypto.h>
72 #endif
73
74 #ifdef HAVE_GETOPT_LONG
75 #include <getopt.h>
76 #else
77 #include "missing/getopt_long.h"
78 #endif
79 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
80 * to compile if <pcap.h> has already been included; including the headers
81 * in the opposite order works fine. For the most part anyway, because in
82 * FreeBSD <pcap/pcap.h> declares bpf_dump() instead of <net/bpf.h>. Thus
83 * interface.h takes care of it later to avoid a compiler warning.
84 */
85 #ifdef HAVE_CAPSICUM
86 #include <sys/capsicum.h>
87 #include <sys/ioccom.h>
88 #include <net/bpf.h>
89 #include <libgen.h>
90 #ifdef HAVE_CASPER
91 #include <libcasper.h>
92 #include <casper/cap_dns.h>
93 #include <sys/nv.h>
94 #endif /* HAVE_CASPER */
95 #endif /* HAVE_CAPSICUM */
96 #ifdef HAVE_PCAP_OPEN
97 /*
98 * We found pcap_open() in the capture library, so we'll be using
99 * the remote capture APIs; define PCAP_REMOTE before we include pcap.h,
100 * so we get those APIs declared, and the types and #defines that they
101 * use defined.
102 *
103 * WinPcap's headers require that PCAP_REMOTE be defined in order to get
104 * remote-capture APIs declared and types and #defines that they use
105 * defined.
106 *
107 * (Versions of libpcap with those APIs, and thus Npcap, which is based on
108 * those versions of libpcap, don't require it.)
109 */
110 #define HAVE_REMOTE
111 #endif
112 #include <pcap.h>
113 #include <signal.h>
114 #include <stdio.h>
115 #include <stdarg.h>
116 #include <stdlib.h>
117 #include <string.h>
118 #include <limits.h>
119 #ifdef _WIN32
120 #include <windows.h>
121 #else
122 #include <sys/time.h>
123 #include <sys/wait.h>
124 #include <sys/resource.h>
125 #include <pwd.h>
126 #include <grp.h>
127 #endif /* _WIN32 */
128
129 /*
130 * Pathname separator.
131 * Use this in pathnames, but do *not* use it in URLs.
132 */
133 #ifdef _WIN32
134 #define PATH_SEPARATOR '\\'
135 #else
136 #define PATH_SEPARATOR '/'
137 #endif
138
139 /* capabilities convenience library */
140 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
141 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
142 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
143 */
144 #ifdef HAVE_LIBCAP_NG
145 #ifdef HAVE_CAP_NG_H
146 #include <cap-ng.h>
147 #else
148 #undef HAVE_LIBCAP_NG
149 #endif /* HAVE_CAP_NG_H */
150 #endif /* HAVE_LIBCAP_NG */
151
152 #ifdef __FreeBSD__
153 #include <sys/sysctl.h>
154 #endif /* __FreeBSD__ */
155
156 #include "netdissect-stdinc.h"
157 #include "netdissect.h"
158 #include "interface.h"
159 #include "addrtoname.h"
160 #include "machdep.h"
161 #include "pcap-missing.h"
162 #include "ascii_strcasecmp.h"
163
164 #include "print.h"
165
166 #include "diag-control.h"
167
168 #include "fptype.h"
169
170 #ifndef PATH_MAX
171 #define PATH_MAX 1024
172 #endif
173
174 #if defined(SIGINFO)
175 #define SIGNAL_REQ_INFO SIGINFO
176 #elif defined(SIGUSR1)
177 #define SIGNAL_REQ_INFO SIGUSR1
178 #endif
179
180 #if defined(HAVE_PCAP_DUMP_FLUSH) && defined(SIGUSR2)
181 #define SIGNAL_FLUSH_PCAP SIGUSR2
182 #endif
183
184 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
185 static int Bflag; /* buffer size */
186 #endif
187 #ifdef HAVE_PCAP_DUMP_FTELL64
188 static int64_t Cflag; /* rotate dump files after this many bytes */
189 #else
190 static long Cflag; /* rotate dump files after this many bytes */
191 #endif
192 static int Cflag_count; /* Keep track of which file number we're writing */
193 #ifdef HAVE_PCAP_FINDALLDEVS
194 static int Dflag; /* list available devices and exit */
195 #endif
196 #ifdef HAVE_PCAP_FINDALLDEVS_EX
197 static char *remote_interfaces_source; /* list available devices from this source and exit */
198 #endif
199
200 /*
201 * This is exported because, in some versions of libpcap, if libpcap
202 * is built with optimizer debugging code (which is *NOT* the default
203 * configuration!), the library *imports*(!) a variable named dflag,
204 * under the expectation that tcpdump is exporting it, to govern
205 * how much debugging information to print when optimizing
206 * the generated BPF code.
207 *
208 * This is a horrible hack; newer versions of libpcap don't import
209 * dflag but, instead, *if* built with optimizer debugging code,
210 * *export* a routine to set that flag.
211 */
212 extern int dflag;
213 int dflag; /* print filter code */
214 static int Gflag; /* rotate dump files after this many seconds */
215 static int Gflag_count; /* number of files created with Gflag rotation */
216 static time_t Gflag_time; /* The last time_t the dump file was rotated. */
217 static int Lflag; /* list available data link types and exit */
218 static int Iflag; /* rfmon (monitor) mode */
219 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
220 static int Jflag; /* list available time stamp types */
221 static int jflag = -1; /* packet time stamp source */
222 #endif
223 static int lflag; /* line-buffered output */
224 static int pflag; /* don't go promiscuous */
225 #ifdef HAVE_PCAP_SETDIRECTION
226 static int Qflag = -1; /* restrict captured packet by send/receive direction */
227 #endif
228 #ifdef HAVE_PCAP_DUMP_FLUSH
229 static int Uflag; /* "unbuffered" output of dump files */
230 #endif
231 static int Wflag; /* recycle output files after this number of files */
232 static int WflagChars;
233 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
234 static int timeout = 1000; /* default timeout = 1000 ms = 1 s */
235 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
236 static int immediate_mode;
237 #endif
238 static int count_mode;
239
240 static int infodelay;
241 static int infoprint;
242
243 char *program_name;
244
245 /* Forwards */
246 static NORETURN void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
247 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
248 static NORETURN void exit_tcpdump(int);
249 static void (*setsignal (int sig, void (*func)(int)))(int);
250 static void cleanup(int);
251 static void child_cleanup(int);
252 static void print_version(FILE *);
253 static void print_usage(FILE *);
254 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
255 static NORETURN void show_tstamp_types_and_exit(pcap_t *, const char *device);
256 #endif
257 static NORETURN void show_dlts_and_exit(pcap_t *, const char *device);
258 #ifdef HAVE_PCAP_FINDALLDEVS
259 static NORETURN void show_devices_and_exit(void);
260 #endif
261 #ifdef HAVE_PCAP_FINDALLDEVS_EX
262 static NORETURN void show_remote_devices_and_exit(void);
263 #endif
264
265 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
266 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
267 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
268 static void droproot(const char *, const char *);
269
270 #ifdef SIGNAL_REQ_INFO
271 static void requestinfo(int);
272 #endif
273
274 #ifdef SIGNAL_FLUSH_PCAP
275 static void flushpcap(int);
276 #endif
277
278 #ifdef _WIN32
279 static HANDLE timer_handle = INVALID_HANDLE_VALUE;
280 static void CALLBACK verbose_stats_dump(PVOID param, BOOLEAN timer_fired);
281 #else /* _WIN32 */
282 static void verbose_stats_dump(int sig);
283 #endif /* _WIN32 */
284
285 static void info(int);
286 static u_int packets_captured;
287
288 #ifdef HAVE_PCAP_FINDALLDEVS
289 static const struct tok status_flags[] = {
290 #ifdef PCAP_IF_UP
291 { PCAP_IF_UP, "Up" },
292 #endif
293 #ifdef PCAP_IF_RUNNING
294 { PCAP_IF_RUNNING, "Running" },
295 #endif
296 { PCAP_IF_LOOPBACK, "Loopback" },
297 #ifdef PCAP_IF_WIRELESS
298 { PCAP_IF_WIRELESS, "Wireless" },
299 #endif
300 { 0, NULL }
301 };
302 #endif
303
304 static pcap_t *pd;
305 static pcap_dumper_t *pdd = NULL;
306
307 static int supports_monitor_mode;
308
309 extern int optind;
310 extern int opterr;
311 extern char *optarg;
312
313 struct dump_info {
314 char *WFileName;
315 char *CurrentFileName;
316 pcap_t *pd;
317 pcap_dumper_t *pdd;
318 netdissect_options *ndo;
319 #ifdef HAVE_CAPSICUM
320 int dirfd;
321 #endif
322 };
323
324 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
325 /*
326 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
327 * by any libpcap header, because it's a special hack, only available if
328 * libpcap was configured to include it, and only intended for use by
329 * libpcap developers trying to debug the parser for filter expressions).
330 */
331 #ifdef _WIN32
332 __declspec(dllimport)
333 #else /* _WIN32 */
334 extern
335 #endif /* _WIN32 */
336 void pcap_set_parser_debug(int);
337 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
338 /*
339 * We don't have pcap_set_parser_debug() in libpcap, but we do have
340 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
341 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
342 */
343 static void
344 pcap_set_parser_debug(int value)
345 {
346 #ifdef HAVE_PCAP_DEBUG
347 extern int pcap_debug;
348
349 pcap_debug = value;
350 #else /* HAVE_PCAP_DEBUG */
351 extern int yydebug;
352
353 yydebug = value;
354 #endif /* HAVE_PCAP_DEBUG */
355 }
356
357 #define HAVE_PCAP_SET_PARSER_DEBUG
358 #endif
359
360 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
361 /*
362 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
363 * by any libpcap header, because it's a special hack, only available if
364 * libpcap was configured to include it, and only intended for use by
365 * libpcap developers trying to debug the optimizer for filter expressions).
366 */
367 #ifdef _WIN32
368 __declspec(dllimport)
369 #else /* _WIN32 */
370 extern
371 #endif /* _WIN32 */
372 void pcap_set_optimizer_debug(int);
373 #endif
374
375 /* VARARGS */
376 static void
377 error(const char *fmt, ...)
378 {
379 va_list ap;
380
381 (void)fprintf(stderr, "%s: ", program_name);
382 va_start(ap, fmt);
383 (void)vfprintf(stderr, fmt, ap);
384 va_end(ap);
385 if (*fmt) {
386 fmt += strlen(fmt);
387 if (fmt[-1] != '\n')
388 (void)fputc('\n', stderr);
389 }
390 exit_tcpdump(S_ERR_HOST_PROGRAM);
391 /* NOTREACHED */
392 }
393
394 /* VARARGS */
395 static void
396 warning(const char *fmt, ...)
397 {
398 va_list ap;
399
400 (void)fprintf(stderr, "%s: WARNING: ", program_name);
401 va_start(ap, fmt);
402 (void)vfprintf(stderr, fmt, ap);
403 va_end(ap);
404 if (*fmt) {
405 fmt += strlen(fmt);
406 if (fmt[-1] != '\n')
407 (void)fputc('\n', stderr);
408 }
409 }
410
411 static void
412 exit_tcpdump(int status)
413 {
414 nd_cleanup();
415 exit(status);
416 }
417
418 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
419 static void
420 show_tstamp_types_and_exit(pcap_t *pc, const char *device)
421 {
422 int n_tstamp_types;
423 int *tstamp_types = 0;
424 const char *tstamp_type_name;
425 int i;
426
427 n_tstamp_types = pcap_list_tstamp_types(pc, &tstamp_types);
428 if (n_tstamp_types < 0)
429 error("%s", pcap_geterr(pc));
430
431 if (n_tstamp_types == 0) {
432 fprintf(stderr, "Time stamp type cannot be set for %s\n",
433 device);
434 exit_tcpdump(S_SUCCESS);
435 }
436 fprintf(stdout, "Time stamp types for %s (use option -j to set):\n",
437 device);
438 for (i = 0; i < n_tstamp_types; i++) {
439 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
440 if (tstamp_type_name != NULL) {
441 (void) fprintf(stdout, " %s (%s)\n", tstamp_type_name,
442 pcap_tstamp_type_val_to_description(tstamp_types[i]));
443 } else {
444 (void) fprintf(stdout, " %d\n", tstamp_types[i]);
445 }
446 }
447 pcap_free_tstamp_types(tstamp_types);
448 exit_tcpdump(S_SUCCESS);
449 }
450 #endif
451
452 static void
453 show_dlts_and_exit(pcap_t *pc, const char *device)
454 {
455 int n_dlts, i;
456 int *dlts = 0;
457 const char *dlt_name;
458
459 n_dlts = pcap_list_datalinks(pc, &dlts);
460 if (n_dlts < 0)
461 error("%s", pcap_geterr(pc));
462 else if (n_dlts == 0 || !dlts)
463 error("No data link types.");
464
465 /*
466 * If the interface is known to support monitor mode, indicate
467 * whether these are the data link types available when not in
468 * monitor mode, if -I wasn't specified, or when in monitor mode,
469 * when -I was specified (the link-layer types available in
470 * monitor mode might be different from the ones available when
471 * not in monitor mode).
472 */
473 (void) fprintf(stdout, "Data link types for ");
474 if (supports_monitor_mode)
475 (void) fprintf(stdout, "%s %s",
476 device,
477 Iflag ? "when in monitor mode" : "when not in monitor mode");
478 else
479 (void) fprintf(stdout, "%s",
480 device);
481 (void) fprintf(stdout, " (use option -y to set):\n");
482
483 for (i = 0; i < n_dlts; i++) {
484 dlt_name = pcap_datalink_val_to_name(dlts[i]);
485 if (dlt_name != NULL) {
486 (void) fprintf(stdout, " %s (%s)", dlt_name,
487 pcap_datalink_val_to_description(dlts[i]));
488
489 /*
490 * OK, does tcpdump handle that type?
491 */
492 if (!has_printer(dlts[i]))
493 (void) fprintf(stdout, " (printing not supported)");
494 fprintf(stdout, "\n");
495 } else {
496 (void) fprintf(stdout, " DLT %d (printing not supported)\n",
497 dlts[i]);
498 }
499 }
500 #ifdef HAVE_PCAP_FREE_DATALINKS
501 pcap_free_datalinks(dlts);
502 #endif
503 exit_tcpdump(S_SUCCESS);
504 }
505
506 #ifdef HAVE_PCAP_FINDALLDEVS
507 static void
508 show_devices_and_exit(void)
509 {
510 pcap_if_t *dev, *devlist;
511 char ebuf[PCAP_ERRBUF_SIZE];
512 int i;
513
514 if (pcap_findalldevs(&devlist, ebuf) < 0)
515 error("%s", ebuf);
516 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
517 printf("%d.%s", i+1, dev->name);
518 if (dev->description != NULL)
519 printf(" (%s)", dev->description);
520 if (dev->flags != 0) {
521 printf(" [");
522 printf("%s", bittok2str(status_flags, "none", dev->flags));
523 #ifdef PCAP_IF_WIRELESS
524 if (dev->flags & PCAP_IF_WIRELESS) {
525 switch (dev->flags & PCAP_IF_CONNECTION_STATUS) {
526
527 case PCAP_IF_CONNECTION_STATUS_UNKNOWN:
528 printf(", Association status unknown");
529 break;
530
531 case PCAP_IF_CONNECTION_STATUS_CONNECTED:
532 printf(", Associated");
533 break;
534
535 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED:
536 printf(", Not associated");
537 break;
538
539 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE:
540 break;
541 }
542 } else {
543 switch (dev->flags & PCAP_IF_CONNECTION_STATUS) {
544
545 case PCAP_IF_CONNECTION_STATUS_UNKNOWN:
546 printf(", Connection status unknown");
547 break;
548
549 case PCAP_IF_CONNECTION_STATUS_CONNECTED:
550 printf(", Connected");
551 break;
552
553 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED:
554 printf(", Disconnected");
555 break;
556
557 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE:
558 break;
559 }
560 }
561 #endif
562 printf("]");
563 }
564 printf("\n");
565 }
566 pcap_freealldevs(devlist);
567 exit_tcpdump(S_SUCCESS);
568 }
569 #endif /* HAVE_PCAP_FINDALLDEVS */
570
571 #ifdef HAVE_PCAP_FINDALLDEVS_EX
572 static void
573 show_remote_devices_and_exit(void)
574 {
575 pcap_if_t *dev, *devlist;
576 char ebuf[PCAP_ERRBUF_SIZE];
577 int i;
578
579 if (pcap_findalldevs_ex(remote_interfaces_source, NULL, &devlist,
580 ebuf) < 0)
581 error("%s", ebuf);
582 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
583 printf("%d.%s", i+1, dev->name);
584 if (dev->description != NULL)
585 printf(" (%s)", dev->description);
586 if (dev->flags != 0)
587 printf(" [%s]", bittok2str(status_flags, "none", dev->flags));
588 printf("\n");
589 }
590 pcap_freealldevs(devlist);
591 exit_tcpdump(S_SUCCESS);
592 }
593 #endif /* HAVE_PCAP_FINDALLDEVS */
594
595 /*
596 * Short options.
597 *
598 * Note that there we use all letters for short options except for g, k,
599 * o, and P, and those are used by other versions of tcpdump, and we should
600 * only use them for the same purposes that the other versions of tcpdump
601 * use them:
602 *
603 * macOS tcpdump uses -g to force non--v output for IP to be on one
604 * line, making it more "g"repable;
605 *
606 * macOS tcpdump uses -k to specify that packet comments in pcapng files
607 * should be printed;
608 *
609 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
610 * for hosts sending TCP SYN packets;
611 *
612 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
613 * than pcap files.
614 *
615 * macOS tcpdump also uses -Q to specify expressions that match packet
616 * metadata, including but not limited to the packet direction.
617 * The expression syntax is different from a simple "in|out|inout",
618 * and those expressions aren't accepted by macOS tcpdump, but the
619 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
620 * "inout" = "dir=in or dir=out", and the parser could conceivably
621 * special-case "in", "out", and "inout" as expressions for backwards
622 * compatibility, so all is not (yet) lost.
623 */
624
625 /*
626 * Set up flags that might or might not be supported depending on the
627 * version of libpcap we're using.
628 */
629 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
630 #define B_FLAG "B:"
631 #define B_FLAG_USAGE " [ -B size ]"
632 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
633 #define B_FLAG
634 #define B_FLAG_USAGE
635 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
636
637 #ifdef HAVE_PCAP_FINDALLDEVS
638 #define D_FLAG "D"
639 #else
640 #define D_FLAG
641 #endif
642
643 #ifdef HAVE_PCAP_CREATE
644 #define I_FLAG "I"
645 #else /* HAVE_PCAP_CREATE */
646 #define I_FLAG
647 #endif /* HAVE_PCAP_CREATE */
648
649 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
650 #define j_FLAG "j:"
651 #define j_FLAG_USAGE " [ -j tstamptype ]"
652 #define J_FLAG "J"
653 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
654 #define j_FLAG
655 #define j_FLAG_USAGE
656 #define J_FLAG
657 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
658
659 #ifdef USE_LIBSMI
660 #define m_FLAG_USAGE "[ -m module ] ..."
661 #endif
662
663 #ifdef HAVE_PCAP_SETDIRECTION
664 #define Q_FLAG "Q:"
665 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
666 #else
667 #define Q_FLAG
668 #define Q_FLAG_USAGE
669 #endif
670
671 #ifdef HAVE_PCAP_DUMP_FLUSH
672 #define U_FLAG "U"
673 #else
674 #define U_FLAG
675 #endif
676
677 #define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#"
678
679 /*
680 * Long options.
681 *
682 * We do not currently have long options corresponding to all short
683 * options; we should probably pick appropriate option names for them.
684 *
685 * However, the short options where the number of times the option is
686 * specified matters, such as -v and -d and -t, should probably not
687 * just map to a long option, as saying
688 *
689 * tcpdump --verbose --verbose
690 *
691 * doesn't make sense; it should be --verbosity={N} or something such
692 * as that.
693 *
694 * For long options with no corresponding short options, we define values
695 * outside the range of ASCII graphic characters, make that the last
696 * component of the entry for the long option, and have a case for that
697 * option in the switch statement.
698 */
699 #define OPTION_VERSION 128
700 #define OPTION_TSTAMP_PRECISION 129
701 #define OPTION_IMMEDIATE_MODE 130
702 #define OPTION_PRINT 131
703 #define OPTION_LIST_REMOTE_INTERFACES 132
704 #define OPTION_TSTAMP_MICRO 133
705 #define OPTION_TSTAMP_NANO 134
706 #define OPTION_FP_TYPE 135
707 #define OPTION_COUNT 136
708
709 static const struct option longopts[] = {
710 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
711 { "buffer-size", required_argument, NULL, 'B' },
712 #endif
713 { "list-interfaces", no_argument, NULL, 'D' },
714 #ifdef HAVE_PCAP_FINDALLDEVS_EX
715 { "list-remote-interfaces", required_argument, NULL, OPTION_LIST_REMOTE_INTERFACES },
716 #endif
717 { "help", no_argument, NULL, 'h' },
718 { "interface", required_argument, NULL, 'i' },
719 #ifdef HAVE_PCAP_CREATE
720 { "monitor-mode", no_argument, NULL, 'I' },
721 #endif
722 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
723 { "time-stamp-type", required_argument, NULL, 'j' },
724 { "list-time-stamp-types", no_argument, NULL, 'J' },
725 #endif
726 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
727 { "micro", no_argument, NULL, OPTION_TSTAMP_MICRO},
728 { "nano", no_argument, NULL, OPTION_TSTAMP_NANO},
729 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
730 #endif
731 { "dont-verify-checksums", no_argument, NULL, 'K' },
732 { "list-data-link-types", no_argument, NULL, 'L' },
733 { "no-optimize", no_argument, NULL, 'O' },
734 { "no-promiscuous-mode", no_argument, NULL, 'p' },
735 #ifdef HAVE_PCAP_SETDIRECTION
736 { "direction", required_argument, NULL, 'Q' },
737 #endif
738 { "snapshot-length", required_argument, NULL, 's' },
739 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
740 #ifdef HAVE_PCAP_DUMP_FLUSH
741 { "packet-buffered", no_argument, NULL, 'U' },
742 #endif
743 { "linktype", required_argument, NULL, 'y' },
744 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
745 { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
746 #endif
747 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
748 { "debug-filter-parser", no_argument, NULL, 'Y' },
749 #endif
750 { "relinquish-privileges", required_argument, NULL, 'Z' },
751 { "count", no_argument, NULL, OPTION_COUNT },
752 { "fp-type", no_argument, NULL, OPTION_FP_TYPE },
753 { "number", no_argument, NULL, '#' },
754 { "print", no_argument, NULL, OPTION_PRINT },
755 { "version", no_argument, NULL, OPTION_VERSION },
756 { NULL, 0, NULL, 0 }
757 };
758
759 #ifdef HAVE_PCAP_FINDALLDEVS_EX
760 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
761 #else
762 #define LIST_REMOTE_INTERFACES_USAGE
763 #endif
764
765 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
766 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
767 #else
768 #define IMMEDIATE_MODE_USAGE ""
769 #endif
770
771 #ifndef _WIN32
772 /* Drop root privileges and chroot if necessary */
773 static void
774 droproot(const char *username, const char *chroot_dir)
775 {
776 struct passwd *pw = NULL;
777
778 if (chroot_dir && !username)
779 error("Chroot without dropping root is insecure");
780
781 pw = getpwnam(username);
782 if (pw) {
783 if (chroot_dir) {
784 if (chroot(chroot_dir) != 0 || chdir ("/") != 0)
785 error("Couldn't chroot/chdir to '%.64s': %s",
786 chroot_dir, pcap_strerror(errno));
787 }
788 #ifdef HAVE_LIBCAP_NG
789 {
790 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
791 if (ret < 0)
792 error("capng_change_id(): return %d\n", ret);
793 else
794 fprintf(stderr, "dropped privs to %s\n", username);
795 }
796 #else
797 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
798 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0)
799 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
800 username,
801 (unsigned long)pw->pw_uid,
802 (unsigned long)pw->pw_gid,
803 pcap_strerror(errno));
804 else {
805 fprintf(stderr, "dropped privs to %s\n", username);
806 }
807 #endif /* HAVE_LIBCAP_NG */
808 } else
809 error("Couldn't find user '%.32s'", username);
810 #ifdef HAVE_LIBCAP_NG
811 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT anymore. */
812 DIAG_OFF_ASSIGN_ENUM
813 capng_updatev(
814 CAPNG_DROP,
815 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
816 CAP_SETUID,
817 CAP_SETGID,
818 CAP_SYS_CHROOT,
819 -1);
820 DIAG_ON_ASSIGN_ENUM
821 capng_apply(CAPNG_SELECT_BOTH);
822 #endif /* HAVE_LIBCAP_NG */
823
824 }
825 #endif /* _WIN32 */
826
827 static int
828 getWflagChars(int x)
829 {
830 int c = 0;
831
832 x -= 1;
833 while (x > 0) {
834 c += 1;
835 x /= 10;
836 }
837
838 return c;
839 }
840
841
842 static void
843 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
844 {
845 char *filename = malloc(PATH_MAX + 1);
846 if (filename == NULL)
847 error("%s: malloc", __func__);
848 if (strlen(orig_name) == 0)
849 error("an empty string is not a valid file name");
850
851 /* Process with strftime if Gflag is set. */
852 if (Gflag != 0) {
853 struct tm *local_tm;
854
855 /* Convert Gflag_time to a usable format */
856 if ((local_tm = localtime(&Gflag_time)) == NULL) {
857 error("%s: localtime", __func__);
858 }
859
860 /* There's no good way to detect an error in strftime since a return
861 * value of 0 isn't necessarily failure; if orig_name is an empty
862 * string, the formatted string will be empty.
863 *
864 * However, the C90 standard says that, if there *is* a
865 * buffer overflow, the content of the buffer is undefined,
866 * so we must check for a buffer overflow.
867 *
868 * So we check above for an empty orig_name, and only call
869 * strftime() if it's non-empty, in which case the return
870 * value will only be 0 if the formatted date doesn't fit
871 * in the buffer.
872 *
873 * (We check above because, even if we don't use -G, we
874 * want a better error message than "tcpdump: : No such
875 * file or directory" for this case.)
876 */
877 if (strftime(filename, PATH_MAX, orig_name, local_tm) == 0) {
878 error("%s: strftime", __func__);
879 }
880 } else {
881 strncpy(filename, orig_name, PATH_MAX);
882 }
883
884 if (cnt == 0 && max_chars == 0)
885 strncpy(buffer, filename, PATH_MAX + 1);
886 else
887 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
888 /* Report an error if the filename is too large */
889 error("too many output files or filename is too long (> %d)", PATH_MAX);
890 free(filename);
891 }
892
893 static char *
894 get_next_file(FILE *VFile, char *ptr)
895 {
896 char *ret;
897 size_t len;
898
899 ret = fgets(ptr, PATH_MAX, VFile);
900 if (!ret)
901 return NULL;
902
903 len = strlen (ptr);
904 if (len > 0 && ptr[len - 1] == '\n')
905 ptr[len - 1] = '\0';
906
907 return ret;
908 }
909
910 #ifdef HAVE_CASPER
911 static cap_channel_t *
912 capdns_setup(void)
913 {
914 cap_channel_t *capcas, *capdnsloc;
915 const char *types[1];
916 int families[2];
917
918 capcas = cap_init();
919 if (capcas == NULL)
920 error("unable to create casper process");
921 capdnsloc = cap_service_open(capcas, "system.dns");
922 /* Casper capability no longer needed. */
923 cap_close(capcas);
924 if (capdnsloc == NULL)
925 error("unable to open system.dns service");
926 /* Limit system.dns to reverse DNS lookups. */
927 types[0] = "ADDR";
928 if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
929 error("unable to limit access to system.dns service");
930 families[0] = AF_INET;
931 families[1] = AF_INET6;
932 if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
933 error("unable to limit access to system.dns service");
934
935 return (capdnsloc);
936 }
937 #endif /* HAVE_CASPER */
938
939 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
940 static int
941 tstamp_precision_from_string(const char *precision)
942 {
943 if (strncmp(precision, "nano", strlen("nano")) == 0)
944 return PCAP_TSTAMP_PRECISION_NANO;
945
946 if (strncmp(precision, "micro", strlen("micro")) == 0)
947 return PCAP_TSTAMP_PRECISION_MICRO;
948
949 return -EINVAL;
950 }
951
952 static const char *
953 tstamp_precision_to_string(int precision)
954 {
955 switch (precision) {
956
957 case PCAP_TSTAMP_PRECISION_MICRO:
958 return "micro";
959
960 case PCAP_TSTAMP_PRECISION_NANO:
961 return "nano";
962
963 default:
964 return "unknown";
965 }
966 }
967 #endif
968
969 #ifdef HAVE_CAPSICUM
970 /*
971 * Ensure that, on a dump file's descriptor, we have all the rights
972 * necessary to make the standard I/O library work with an fdopen()ed
973 * FILE * from that descriptor.
974 *
975 * A long time ago in a galaxy far, far away, AT&T decided that, instead
976 * of providing separate APIs for getting and setting the FD_ flags on a
977 * descriptor, getting and setting the O_ flags on a descriptor, and
978 * locking files, they'd throw them all into a kitchen-sink fcntl() call
979 * along the lines of ioctl(), the fact that ioctl() operations are
980 * largely specific to particular character devices but fcntl() operations
981 * are either generic to all descriptors or generic to all descriptors for
982 * regular files notwithstanding.
983 *
984 * The Capsicum people decided that fine-grained control of descriptor
985 * operations was required, so that you need to grant permission for
986 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
987 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
988 * collection of things, so there are *individual* fcntls for which
989 * permission needs to be granted.
990 *
991 * The FreeBSD standard I/O people implemented some optimizations that
992 * requires that the standard I/O routines be able to determine whether
993 * the descriptor for the FILE * is open append-only or not; as that
994 * descriptor could have come from an open() rather than an fopen(),
995 * that requires that it be able to do an F_GETFL fcntl() to read
996 * the O_ flags.
997 *
998 * Tcpdump uses ftell() to determine how much data has been written
999 * to a file in order to, when used with -C, determine when it's time
1000 * to rotate capture files. ftell() therefore needs to do an lseek()
1001 * to find out the file offset and must, thanks to the aforementioned
1002 * optimization, also know whether the descriptor is open append-only
1003 * or not.
1004 *
1005 * The net result of all the above is that we need to grant CAP_SEEK,
1006 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
1007 *
1008 * Perhaps this is the universe's way of saying that either
1009 *
1010 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
1011 * using it, so that Capsicum-capable tcpdump wouldn't need to do
1012 * an fdopen()
1013 *
1014 * or
1015 *
1016 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
1017 * I/O library that knows what rights are needed by the standard
1018 * I/O library, based on the open mode, and assigns them, perhaps
1019 * with an additional argument indicating, for example, whether
1020 * seeking should be allowed, so that tcpdump doesn't need to know
1021 * what the standard I/O library happens to require this week.
1022 */
1023 static void
1024 set_dumper_capsicum_rights(pcap_dumper_t *p)
1025 {
1026 int fd = fileno(pcap_dump_file(p));
1027 cap_rights_t rights;
1028
1029 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
1030 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
1031 error("unable to limit dump descriptor");
1032 }
1033 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
1034 error("unable to limit dump descriptor fcntls");
1035 }
1036 }
1037 #endif
1038
1039 /*
1040 * Copy arg vector into a new buffer, concatenating arguments with spaces.
1041 */
1042 static char *
1043 copy_argv(char **argv)
1044 {
1045 char **p;
1046 size_t len = 0;
1047 char *buf;
1048 char *src, *dst;
1049
1050 p = argv;
1051 if (*p == NULL)
1052 return 0;
1053
1054 while (*p)
1055 len += strlen(*p++) + 1;
1056
1057 buf = (char *)malloc(len);
1058 if (buf == NULL)
1059 error("%s: malloc", __func__);
1060
1061 p = argv;
1062 dst = buf;
1063 while ((src = *p++) != NULL) {
1064 while ((*dst++ = *src++) != '\0')
1065 ;
1066 dst[-1] = ' ';
1067 }
1068 dst[-1] = '\0';
1069
1070 return buf;
1071 }
1072
1073 /*
1074 * On Windows, we need to open the file in binary mode, so that
1075 * we get all the bytes specified by the size we get from "fstat()".
1076 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1077 * we define it as 0 if it's not defined, so it does nothing.
1078 */
1079 #ifndef O_BINARY
1080 #define O_BINARY 0
1081 #endif
1082
1083 static char *
1084 read_infile(char *fname)
1085 {
1086 int i, fd;
1087 ssize_t cc;
1088 char *cp;
1089 our_statb buf;
1090
1091 fd = open(fname, O_RDONLY|O_BINARY);
1092 if (fd < 0)
1093 error("can't open %s: %s", fname, pcap_strerror(errno));
1094
1095 if (our_fstat(fd, &buf) < 0)
1096 error("can't stat %s: %s", fname, pcap_strerror(errno));
1097
1098 /*
1099 * Reject files whose size doesn't fit into an int; a filter
1100 * *that* large will probably be too big.
1101 */
1102 if (buf.st_size > INT_MAX)
1103 error("%s is too large", fname);
1104
1105 cp = malloc((u_int)buf.st_size + 1);
1106 if (cp == NULL)
1107 error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
1108 fname, pcap_strerror(errno));
1109 cc = read(fd, cp, (u_int)buf.st_size);
1110 if (cc < 0)
1111 error("read %s: %s", fname, pcap_strerror(errno));
1112 if (cc != buf.st_size)
1113 error("short read %s (%d != %d)", fname, (int) cc,
1114 (int)buf.st_size);
1115
1116 close(fd);
1117 /* replace "# comment" with spaces */
1118 for (i = 0; i < cc; i++) {
1119 if (cp[i] == '#')
1120 while (i < cc && cp[i] != '\n')
1121 cp[i++] = ' ';
1122 }
1123 cp[cc] = '\0';
1124 return (cp);
1125 }
1126
1127 #ifdef HAVE_PCAP_FINDALLDEVS
1128 static long
1129 parse_interface_number(const char *device)
1130 {
1131 const char *p;
1132 long devnum;
1133 char *end;
1134
1135 /*
1136 * Search for a colon, terminating any scheme at the beginning
1137 * of the device.
1138 */
1139 p = strchr(device, ':');
1140 if (p != NULL) {
1141 /*
1142 * We found it. Is it followed by "//"?
1143 */
1144 p++; /* skip the : */
1145 if (strncmp(p, "//", 2) == 0) {
1146 /*
1147 * Yes. Search for the next /, at the end of the
1148 * authority part of the URL.
1149 */
1150 p += 2; /* skip the // */
1151 p = strchr(p, '/');
1152 if (p != NULL) {
1153 /*
1154 * OK, past the / is the path.
1155 */
1156 device = p + 1;
1157 }
1158 }
1159 }
1160 devnum = strtol(device, &end, 10);
1161 if (device != end && *end == '\0') {
1162 /*
1163 * It's all-numeric, but is it a valid number?
1164 */
1165 if (devnum <= 0) {
1166 /*
1167 * No, it's not an ordinal.
1168 */
1169 error("Invalid adapter index");
1170 }
1171 return (devnum);
1172 } else {
1173 /*
1174 * It's not all-numeric; return -1, so our caller
1175 * knows that.
1176 */
1177 return (-1);
1178 }
1179 }
1180
1181 static char *
1182 find_interface_by_number(const char *url
1183 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1184 _U_
1185 #endif
1186 , long devnum)
1187 {
1188 pcap_if_t *dev, *devlist;
1189 long i;
1190 char ebuf[PCAP_ERRBUF_SIZE];
1191 char *device;
1192 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1193 const char *endp;
1194 char *host_url;
1195 #endif
1196 int status;
1197
1198 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1199 /*
1200 * Search for a colon, terminating any scheme at the beginning
1201 * of the URL.
1202 */
1203 endp = strchr(url, ':');
1204 if (endp != NULL) {
1205 /*
1206 * We found it. Is it followed by "//"?
1207 */
1208 endp++; /* skip the : */
1209 if (strncmp(endp, "//", 2) == 0) {
1210 /*
1211 * Yes. Search for the next /, at the end of the
1212 * authority part of the URL.
1213 */
1214 endp += 2; /* skip the // */
1215 endp = strchr(endp, '/');
1216 } else
1217 endp = NULL;
1218 }
1219 if (endp != NULL) {
1220 /*
1221 * OK, everything from device to endp is a URL to hand
1222 * to pcap_findalldevs_ex().
1223 */
1224 endp++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1225 host_url = malloc(endp - url + 1);
1226 if (host_url == NULL && (endp - url + 1) > 0)
1227 error("Invalid allocation for host");
1228
1229 memcpy(host_url, url, endp - url);
1230 host_url[endp - url] = '\0';
1231 status = pcap_findalldevs_ex(host_url, NULL, &devlist, ebuf);
1232 free(host_url);
1233 } else
1234 #endif
1235 status = pcap_findalldevs(&devlist, ebuf);
1236 if (status < 0)
1237 error("%s", ebuf);
1238 /*
1239 * Look for the devnum-th entry in the list of devices (1-based).
1240 */
1241 for (i = 0, dev = devlist; i < devnum-1 && dev != NULL;
1242 i++, dev = dev->next)
1243 ;
1244 if (dev == NULL)
1245 error("Invalid adapter index");
1246 device = strdup(dev->name);
1247 pcap_freealldevs(devlist);
1248 return (device);
1249 }
1250 #endif
1251
1252 #ifdef HAVE_PCAP_OPEN
1253 /*
1254 * Prefixes for rpcap URLs.
1255 */
1256 static char rpcap_prefix[] = "rpcap://";
1257 static char rpcap_ssl_prefix[] = "rpcaps://";
1258 #endif
1259
1260 static pcap_t *
1261 open_interface(const char *device, netdissect_options *ndo, char *ebuf)
1262 {
1263 pcap_t *pc;
1264 #ifdef HAVE_PCAP_CREATE
1265 int status;
1266 char *cp;
1267 #endif
1268
1269 #ifdef HAVE_PCAP_OPEN
1270 /*
1271 * Is this an rpcap URL?
1272 */
1273 if (strncmp(device, rpcap_prefix, sizeof(rpcap_prefix) - 1) == 0 ||
1274 strncmp(device, rpcap_ssl_prefix, sizeof(rpcap_ssl_prefix) - 1) == 0) {
1275 /*
1276 * Yes. Open it with pcap_open().
1277 */
1278 *ebuf = '\0';
1279 pc = pcap_open(device, ndo->ndo_snaplen,
1280 pflag ? 0 : PCAP_OPENFLAG_PROMISCUOUS, timeout, NULL,
1281 ebuf);
1282 if (pc == NULL) {
1283 /*
1284 * If this failed with "No such device" or "The system
1285 * cannot find the device specified", that means
1286 * the interface doesn't exist; return NULL, so that
1287 * the caller can see whether the device name is
1288 * actually an interface index.
1289 */
1290 if (strstr(ebuf, "No such device") != NULL ||
1291 strstr(ebuf, "The system cannot find the device specified") != NULL)
1292 return (NULL);
1293 error("%s", ebuf);
1294 }
1295 if (*ebuf)
1296 warning("%s", ebuf);
1297 return (pc);
1298 }
1299 #endif /* HAVE_PCAP_OPEN */
1300
1301 #ifdef HAVE_PCAP_CREATE
1302 pc = pcap_create(device, ebuf);
1303 if (pc == NULL) {
1304 /*
1305 * If this failed with "No such device", that means
1306 * the interface doesn't exist; return NULL, so that
1307 * the caller can see whether the device name is
1308 * actually an interface index.
1309 */
1310 if (strstr(ebuf, "No such device") != NULL)
1311 return (NULL);
1312 error("%s", ebuf);
1313 }
1314 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1315 if (Jflag)
1316 show_tstamp_types_and_exit(pc, device);
1317 #endif
1318 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1319 status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision);
1320 if (status != 0)
1321 error("%s: Can't set %ssecond time stamp precision: %s",
1322 device,
1323 tstamp_precision_to_string(ndo->ndo_tstamp_precision),
1324 pcap_statustostr(status));
1325 #endif
1326
1327 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1328 if (immediate_mode) {
1329 status = pcap_set_immediate_mode(pc, 1);
1330 if (status != 0)
1331 error("%s: Can't set immediate mode: %s",
1332 device, pcap_statustostr(status));
1333 }
1334 #endif
1335 /*
1336 * Is this an interface that supports monitor mode?
1337 */
1338 if (pcap_can_set_rfmon(pc) == 1)
1339 supports_monitor_mode = 1;
1340 else
1341 supports_monitor_mode = 0;
1342 if (ndo->ndo_snaplen != 0) {
1343 /*
1344 * A snapshot length was explicitly specified;
1345 * use it.
1346 */
1347 status = pcap_set_snaplen(pc, ndo->ndo_snaplen);
1348 if (status != 0)
1349 error("%s: Can't set snapshot length: %s",
1350 device, pcap_statustostr(status));
1351 }
1352 status = pcap_set_promisc(pc, !pflag);
1353 if (status != 0)
1354 error("%s: Can't set promiscuous mode: %s",
1355 device, pcap_statustostr(status));
1356 if (Iflag) {
1357 status = pcap_set_rfmon(pc, 1);
1358 if (status != 0)
1359 error("%s: Can't set monitor mode: %s",
1360 device, pcap_statustostr(status));
1361 }
1362 status = pcap_set_timeout(pc, timeout);
1363 if (status != 0)
1364 error("%s: pcap_set_timeout failed: %s",
1365 device, pcap_statustostr(status));
1366 if (Bflag != 0) {
1367 status = pcap_set_buffer_size(pc, Bflag);
1368 if (status != 0)
1369 error("%s: Can't set buffer size: %s",
1370 device, pcap_statustostr(status));
1371 }
1372 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1373 if (jflag != -1) {
1374 status = pcap_set_tstamp_type(pc, jflag);
1375 if (status < 0)
1376 error("%s: Can't set time stamp type: %s",
1377 device, pcap_statustostr(status));
1378 else if (status > 0)
1379 warning("When trying to set timestamp type '%s' on %s: %s",
1380 pcap_tstamp_type_val_to_name(jflag), device,
1381 pcap_statustostr(status));
1382 }
1383 #endif
1384 status = pcap_activate(pc);
1385 if (status < 0) {
1386 /*
1387 * pcap_activate() failed.
1388 */
1389 cp = pcap_geterr(pc);
1390 if (status == PCAP_ERROR)
1391 error("%s", cp);
1392 else if (status == PCAP_ERROR_NO_SUCH_DEVICE) {
1393 /*
1394 * Return an error for our caller to handle.
1395 */
1396 snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)",
1397 device, pcap_statustostr(status), cp);
1398 } else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0')
1399 error("%s: %s\n(%s)", device,
1400 pcap_statustostr(status), cp);
1401 #ifdef __FreeBSD__
1402 else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1403 strncmp(device, "wlan", 4) == 0) {
1404 char parent[8], newdev[8];
1405 char sysctl[32];
1406 size_t s = sizeof(parent);
1407
1408 snprintf(sysctl, sizeof(sysctl),
1409 "net.wlan.%d.%%parent", atoi(device + 4));
1410 sysctlbyname(sysctl, parent, &s, NULL, 0);
1411 strlcpy(newdev, device, sizeof(newdev));
1412 /* Suggest a new wlan device. */
1413 /* FIXME: incrementing the index this way is not going to work well
1414 * when the index is 9 or greater but the only consequence in this
1415 * specific case would be an error message that looks a bit odd.
1416 */
1417 newdev[strlen(newdev)-1]++;
1418 error("%s is not a monitor mode VAP\n"
1419 "To create a new monitor mode VAP use:\n"
1420 " ifconfig %s create wlandev %s wlanmode monitor\n"
1421 "and use %s as the tcpdump interface",
1422 device, newdev, parent, newdev);
1423 }
1424 #endif
1425 else
1426 error("%s: %s", device,
1427 pcap_statustostr(status));
1428 pcap_close(pc);
1429 return (NULL);
1430 } else if (status > 0) {
1431 /*
1432 * pcap_activate() succeeded, but it's warning us
1433 * of a problem it had.
1434 */
1435 cp = pcap_geterr(pc);
1436 if (status == PCAP_WARNING)
1437 warning("%s", cp);
1438 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1439 *cp != '\0')
1440 warning("%s: %s\n(%s)", device,
1441 pcap_statustostr(status), cp);
1442 else
1443 warning("%s: %s", device,
1444 pcap_statustostr(status));
1445 }
1446 #ifdef HAVE_PCAP_SETDIRECTION
1447 if (Qflag != -1) {
1448 status = pcap_setdirection(pc, Qflag);
1449 if (status != 0)
1450 error("%s: pcap_setdirection() failed: %s",
1451 device, pcap_geterr(pc));
1452 }
1453 #endif /* HAVE_PCAP_SETDIRECTION */
1454 #else /* HAVE_PCAP_CREATE */
1455 *ebuf = '\0';
1456 /*
1457 * If no snapshot length was specified, or a length of 0 was
1458 * specified, default to 256KB.
1459 */
1460 if (ndo->ndo_snaplen == 0)
1461 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1462 pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, timeout, ebuf);
1463 if (pc == NULL) {
1464 /*
1465 * If this failed with "No such device", that means
1466 * the interface doesn't exist; return NULL, so that
1467 * the caller can see whether the device name is
1468 * actually an interface index.
1469 */
1470 if (strstr(ebuf, "No such device") != NULL)
1471 return (NULL);
1472 error("%s", ebuf);
1473 }
1474 if (*ebuf)
1475 warning("%s", ebuf);
1476 #endif /* HAVE_PCAP_CREATE */
1477
1478 return (pc);
1479 }
1480
1481 int
1482 main(int argc, char **argv)
1483 {
1484 int cnt, op, i;
1485 bpf_u_int32 localnet = 0, netmask = 0;
1486 char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
1487 char *endp;
1488 pcap_handler callback;
1489 int dlt;
1490 const char *dlt_name;
1491 struct bpf_program fcode;
1492 #ifndef _WIN32
1493 void (*oldhandler)(int);
1494 #endif
1495 struct dump_info dumpinfo;
1496 u_char *pcap_userdata;
1497 char ebuf[PCAP_ERRBUF_SIZE];
1498 char VFileLine[PATH_MAX + 1];
1499 const char *username = NULL;
1500 #ifndef _WIN32
1501 const char *chroot_dir = NULL;
1502 #endif
1503 char *ret = NULL;
1504 char *end;
1505 #ifdef HAVE_PCAP_FINDALLDEVS
1506 pcap_if_t *devlist;
1507 long devnum;
1508 #endif
1509 int status;
1510 FILE *VFile;
1511 #ifdef HAVE_CAPSICUM
1512 cap_rights_t rights;
1513 int cansandbox;
1514 #endif /* HAVE_CAPSICUM */
1515 int Oflag = 1; /* run filter code optimizer */
1516 int yflag_dlt = -1;
1517 const char *yflag_dlt_name = NULL;
1518 int print = 0;
1519
1520 netdissect_options Ndo;
1521 netdissect_options *ndo = &Ndo;
1522
1523 /*
1524 * Initialize the netdissect code.
1525 */
1526 if (nd_init(ebuf, sizeof(ebuf)) == -1)
1527 error("%s", ebuf);
1528
1529 memset(ndo, 0, sizeof(*ndo));
1530 ndo_set_function_pointers(ndo);
1531
1532 cnt = -1;
1533 device = NULL;
1534 infile = NULL;
1535 RFileName = NULL;
1536 VFileName = NULL;
1537 VFile = NULL;
1538 WFileName = NULL;
1539 dlt = -1;
1540 if ((cp = strrchr(argv[0], PATH_SEPARATOR)) != NULL)
1541 ndo->program_name = program_name = cp + 1;
1542 else
1543 ndo->program_name = program_name = argv[0];
1544
1545 #if defined(HAVE_PCAP_WSOCKINIT)
1546 if (pcap_wsockinit() != 0)
1547 error("Attempting to initialize Winsock failed");
1548 #elif defined(HAVE_WSOCKINIT)
1549 if (wsockinit() != 0)
1550 error("Attempting to initialize Winsock failed");
1551 #endif
1552
1553 /*
1554 * On platforms where the CPU doesn't support unaligned loads,
1555 * force unaligned accesses to abort with SIGBUS, rather than
1556 * being fixed up (slowly) by the OS kernel; on those platforms,
1557 * misaligned accesses are bugs, and we want tcpdump to crash so
1558 * that the bugs are reported.
1559 */
1560 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1561 error("%s", ebuf);
1562
1563 /*
1564 * An explicit tzset() call is usually not needed as it happens
1565 * implicitly the first time we call localtime() or mktime(),
1566 * but in some cases (sandboxing, chroot) this may be too late.
1567 */
1568 tzset();
1569
1570 while (
1571 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
1572 switch (op) {
1573
1574 case 'a':
1575 /* compatibility for old -a */
1576 break;
1577
1578 case 'A':
1579 ++ndo->ndo_Aflag;
1580 break;
1581
1582 case 'b':
1583 ++ndo->ndo_bflag;
1584 break;
1585
1586 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1587 case 'B':
1588 Bflag = atoi(optarg)*1024;
1589 if (Bflag <= 0)
1590 error("invalid packet buffer size %s", optarg);
1591 break;
1592 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1593
1594 case 'c':
1595 cnt = atoi(optarg);
1596 if (cnt <= 0)
1597 error("invalid packet count %s", optarg);
1598 break;
1599
1600 case 'C':
1601 errno = 0;
1602 #ifdef HAVE_PCAP_DUMP_FTELL64
1603 Cflag = strtoint64_t(optarg, &endp, 10);
1604 #else
1605 Cflag = strtol(optarg, &endp, 10);
1606 #endif
1607 if (endp == optarg || *endp != '\0' || errno != 0
1608 || Cflag <= 0)
1609 error("invalid file size %s", optarg);
1610 /*
1611 * Will multiplying it by 1000000 overflow?
1612 */
1613 #ifdef HAVE_PCAP_DUMP_FTELL64
1614 if (Cflag > INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1615 #else
1616 if (Cflag > LONG_MAX / 1000000)
1617 #endif
1618 error("file size %s is too large", optarg);
1619 Cflag *= 1000000;
1620 break;
1621
1622 case 'd':
1623 ++dflag;
1624 break;
1625
1626 #ifdef HAVE_PCAP_FINDALLDEVS
1627 case 'D':
1628 Dflag++;
1629 break;
1630 #endif
1631
1632 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1633 case OPTION_LIST_REMOTE_INTERFACES:
1634 remote_interfaces_source = optarg;
1635 break;
1636 #endif
1637
1638 case 'L':
1639 Lflag++;
1640 break;
1641
1642 case 'e':
1643 ++ndo->ndo_eflag;
1644 break;
1645
1646 case 'E':
1647 #ifndef HAVE_LIBCRYPTO
1648 warning("crypto code not compiled in");
1649 #endif
1650 ndo->ndo_espsecret = optarg;
1651 break;
1652
1653 case 'f':
1654 ++ndo->ndo_fflag;
1655 break;
1656
1657 case 'F':
1658 infile = optarg;
1659 break;
1660
1661 case 'G':
1662 Gflag = atoi(optarg);
1663 if (Gflag < 0)
1664 error("invalid number of seconds %s", optarg);
1665
1666 /* We will create one file initially. */
1667 Gflag_count = 0;
1668
1669 /* Grab the current time for rotation use. */
1670 if ((Gflag_time = time(NULL)) == (time_t)-1) {
1671 error("%s: can't get current time: %s",
1672 __func__, pcap_strerror(errno));
1673 }
1674 break;
1675
1676 case 'h':
1677 print_usage(stdout);
1678 exit_tcpdump(S_SUCCESS);
1679 break;
1680
1681 case 'H':
1682 ++ndo->ndo_Hflag;
1683 break;
1684
1685 case 'i':
1686 device = optarg;
1687 break;
1688
1689 #ifdef HAVE_PCAP_CREATE
1690 case 'I':
1691 ++Iflag;
1692 break;
1693 #endif /* HAVE_PCAP_CREATE */
1694
1695 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1696 case 'j':
1697 jflag = pcap_tstamp_type_name_to_val(optarg);
1698 if (jflag < 0)
1699 error("invalid time stamp type %s", optarg);
1700 break;
1701
1702 case 'J':
1703 Jflag++;
1704 break;
1705 #endif
1706
1707 case 'l':
1708 #ifdef _WIN32
1709 /*
1710 * _IOLBF is the same as _IOFBF in Microsoft's C
1711 * libraries; the only alternative they offer
1712 * is _IONBF.
1713 *
1714 * XXX - this should really be checking for MSVC++,
1715 * not _WIN32, if, for example, MinGW has its own
1716 * C library that is more UNIX-compatible.
1717 */
1718 setvbuf(stdout, NULL, _IONBF, 0);
1719 #else /* _WIN32 */
1720 #ifdef HAVE_SETLINEBUF
1721 setlinebuf(stdout);
1722 #else
1723 setvbuf(stdout, NULL, _IOLBF, 0);
1724 #endif
1725 #endif /* _WIN32 */
1726 lflag = 1;
1727 break;
1728
1729 case 'K':
1730 ++ndo->ndo_Kflag;
1731 break;
1732
1733 case 'm':
1734 if (nd_have_smi_support()) {
1735 if (nd_load_smi_module(optarg, ebuf, sizeof(ebuf)) == -1)
1736 error("%s", ebuf);
1737 } else {
1738 (void)fprintf(stderr, "%s: ignoring option '-m %s' ",
1739 program_name, optarg);
1740 (void)fprintf(stderr, "(no libsmi support)\n");
1741 }
1742 break;
1743
1744 case 'M':
1745 /* TCP-MD5 shared secret */
1746 #ifndef HAVE_LIBCRYPTO
1747 warning("crypto code not compiled in");
1748 #endif
1749 ndo->ndo_sigsecret = optarg;
1750 break;
1751
1752 case 'n':
1753 ++ndo->ndo_nflag;
1754 break;
1755
1756 case 'N':
1757 ++ndo->ndo_Nflag;
1758 break;
1759
1760 case 'O':
1761 Oflag = 0;
1762 break;
1763
1764 case 'p':
1765 ++pflag;
1766 break;
1767
1768 case 'q':
1769 ++ndo->ndo_qflag;
1770 ++ndo->ndo_suppress_default_print;
1771 break;
1772
1773 #ifdef HAVE_PCAP_SETDIRECTION
1774 case 'Q':
1775 if (ascii_strcasecmp(optarg, "in") == 0)
1776 Qflag = PCAP_D_IN;
1777 else if (ascii_strcasecmp(optarg, "out") == 0)
1778 Qflag = PCAP_D_OUT;
1779 else if (ascii_strcasecmp(optarg, "inout") == 0)
1780 Qflag = PCAP_D_INOUT;
1781 else
1782 error("unknown capture direction '%s'", optarg);
1783 break;
1784 #endif /* HAVE_PCAP_SETDIRECTION */
1785
1786 case 'r':
1787 RFileName = optarg;
1788 break;
1789
1790 case 's':
1791 ndo->ndo_snaplen = (int)strtol(optarg, &end, 0);
1792 if (optarg == end || *end != '\0'
1793 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1794 error("invalid snaplen %s (must be >= 0 and <= %d)",
1795 optarg, MAXIMUM_SNAPLEN);
1796 break;
1797
1798 case 'S':
1799 ++ndo->ndo_Sflag;
1800 break;
1801
1802 case 't':
1803 ++ndo->ndo_tflag;
1804 break;
1805
1806 case 'T':
1807 if (ascii_strcasecmp(optarg, "vat") == 0)
1808 ndo->ndo_packettype = PT_VAT;
1809 else if (ascii_strcasecmp(optarg, "wb") == 0)
1810 ndo->ndo_packettype = PT_WB;
1811 else if (ascii_strcasecmp(optarg, "rpc") == 0)
1812 ndo->ndo_packettype = PT_RPC;
1813 else if (ascii_strcasecmp(optarg, "rtp") == 0)
1814 ndo->ndo_packettype = PT_RTP;
1815 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1816 ndo->ndo_packettype = PT_RTCP;
1817 else if (ascii_strcasecmp(optarg, "snmp") == 0)
1818 ndo->ndo_packettype = PT_SNMP;
1819 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1820 ndo->ndo_packettype = PT_CNFP;
1821 else if (ascii_strcasecmp(optarg, "tftp") == 0)
1822 ndo->ndo_packettype = PT_TFTP;
1823 else if (ascii_strcasecmp(optarg, "aodv") == 0)
1824 ndo->ndo_packettype = PT_AODV;
1825 else if (ascii_strcasecmp(optarg, "carp") == 0)
1826 ndo->ndo_packettype = PT_CARP;
1827 else if (ascii_strcasecmp(optarg, "radius") == 0)
1828 ndo->ndo_packettype = PT_RADIUS;
1829 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1830 ndo->ndo_packettype = PT_ZMTP1;
1831 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1832 ndo->ndo_packettype = PT_VXLAN;
1833 else if (ascii_strcasecmp(optarg, "pgm") == 0)
1834 ndo->ndo_packettype = PT_PGM;
1835 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1836 ndo->ndo_packettype = PT_PGM_ZMTP1;
1837 else if (ascii_strcasecmp(optarg, "lmp") == 0)
1838 ndo->ndo_packettype = PT_LMP;
1839 else if (ascii_strcasecmp(optarg, "resp") == 0)
1840 ndo->ndo_packettype = PT_RESP;
1841 else if (ascii_strcasecmp(optarg, "ptp") == 0)
1842 ndo->ndo_packettype = PT_PTP;
1843 else if (ascii_strcasecmp(optarg, "someip") == 0)
1844 ndo->ndo_packettype = PT_SOMEIP;
1845 else if (ascii_strcasecmp(optarg, "domain") == 0)
1846 ndo->ndo_packettype = PT_DOMAIN;
1847 else
1848 error("unknown packet type '%s'", optarg);
1849 break;
1850
1851 case 'u':
1852 ++ndo->ndo_uflag;
1853 break;
1854
1855 #ifdef HAVE_PCAP_DUMP_FLUSH
1856 case 'U':
1857 ++Uflag;
1858 break;
1859 #endif
1860
1861 case 'v':
1862 ++ndo->ndo_vflag;
1863 break;
1864
1865 case 'V':
1866 VFileName = optarg;
1867 break;
1868
1869 case 'w':
1870 WFileName = optarg;
1871 break;
1872
1873 case 'W':
1874 Wflag = atoi(optarg);
1875 if (Wflag <= 0)
1876 error("invalid number of output files %s", optarg);
1877 WflagChars = getWflagChars(Wflag);
1878 break;
1879
1880 case 'x':
1881 ++ndo->ndo_xflag;
1882 ++ndo->ndo_suppress_default_print;
1883 break;
1884
1885 case 'X':
1886 ++ndo->ndo_Xflag;
1887 ++ndo->ndo_suppress_default_print;
1888 break;
1889
1890 case 'y':
1891 yflag_dlt_name = optarg;
1892 yflag_dlt =
1893 pcap_datalink_name_to_val(yflag_dlt_name);
1894 if (yflag_dlt < 0)
1895 error("invalid data link type %s", yflag_dlt_name);
1896 break;
1897
1898 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1899 case 'Y':
1900 {
1901 /* Undocumented flag */
1902 pcap_set_parser_debug(1);
1903 }
1904 break;
1905 #endif
1906 case 'z':
1907 zflag = optarg;
1908 break;
1909
1910 case 'Z':
1911 username = optarg;
1912 break;
1913
1914 case '#':
1915 ndo->ndo_packet_number = 1;
1916 break;
1917
1918 case OPTION_VERSION:
1919 print_version(stdout);
1920 exit_tcpdump(S_SUCCESS);
1921 break;
1922
1923 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1924 case OPTION_TSTAMP_PRECISION:
1925 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1926 if (ndo->ndo_tstamp_precision < 0)
1927 error("unsupported time stamp precision");
1928 break;
1929 #endif
1930
1931 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1932 case OPTION_IMMEDIATE_MODE:
1933 immediate_mode = 1;
1934 break;
1935 #endif
1936
1937 case OPTION_PRINT:
1938 print = 1;
1939 break;
1940
1941 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1942 case OPTION_TSTAMP_MICRO:
1943 ndo->ndo_tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
1944 break;
1945
1946 case OPTION_TSTAMP_NANO:
1947 ndo->ndo_tstamp_precision = PCAP_TSTAMP_PRECISION_NANO;
1948 break;
1949 #endif
1950
1951 case OPTION_FP_TYPE:
1952 /*
1953 * Print out the type of floating-point arithmetic
1954 * we're doing; it's probably IEEE, unless somebody
1955 * tries to run this on a VAX, but the precision
1956 * may differ (e.g., it might be 32-bit, 64-bit,
1957 * or 80-bit).
1958 */
1959 float_type_check(0x4e93312d);
1960 return 0;
1961
1962 case OPTION_COUNT:
1963 count_mode = 1;
1964 break;
1965
1966 default:
1967 print_usage(stderr);
1968 exit_tcpdump(S_ERR_HOST_PROGRAM);
1969 /* NOTREACHED */
1970 }
1971
1972 #ifdef HAVE_PCAP_FINDALLDEVS
1973 if (Dflag)
1974 show_devices_and_exit();
1975 #endif
1976 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1977 if (remote_interfaces_source != NULL)
1978 show_remote_devices_and_exit();
1979 #endif
1980
1981 switch (ndo->ndo_tflag) {
1982
1983 case 0: /* Default */
1984 case 1: /* No time stamp */
1985 case 2: /* Unix timeval style */
1986 case 3: /* Microseconds/nanoseconds since previous packet */
1987 case 4: /* Date + Default */
1988 case 5: /* Microseconds/nanoseconds since first packet */
1989 break;
1990
1991 default: /* Not supported */
1992 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1993 break;
1994 }
1995
1996 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1997 error("-f can not be used with -V or -r");
1998
1999 if (VFileName != NULL && RFileName != NULL)
2000 error("-V and -r are mutually exclusive.");
2001
2002 /*
2003 * If we're printing dissected packets to the standard output,
2004 * and either the standard output is a terminal or we're doing
2005 * "line" buffering, set the capture timeout to .1 second rather
2006 * than 1 second, as the user's probably expecting to see packets
2007 * pop up immediately shortly after they arrive.
2008 *
2009 * XXX - would there be some value appropriate for all cases,
2010 * based on, say, the buffer size and packet input rate?
2011 */
2012 if ((WFileName == NULL || print) && (isatty(1) || lflag))
2013 timeout = 100;
2014
2015 #ifdef WITH_CHROOT
2016 /* if run as root, prepare for chrooting */
2017 if (getuid() == 0 || geteuid() == 0) {
2018 /* future extensibility for cmd-line arguments */
2019 if (!chroot_dir)
2020 chroot_dir = WITH_CHROOT;
2021 }
2022 #endif
2023
2024 #ifdef WITH_USER
2025 /* if run as root, prepare for dropping root privileges */
2026 if (getuid() == 0 || geteuid() == 0) {
2027 /* Run with '-Z root' to restore old behaviour */
2028 if (!username)
2029 username = WITH_USER;
2030 else if (strcmp(username, "root") == 0)
2031 username = NULL;
2032 }
2033 #endif
2034
2035 if (RFileName != NULL || VFileName != NULL) {
2036 /*
2037 * If RFileName is non-null, it's the pathname of a
2038 * savefile to read. If VFileName is non-null, it's
2039 * the pathname of a file containing a list of pathnames
2040 * (one per line) of savefiles to read.
2041 *
2042 * In either case, we're reading a savefile, not doing
2043 * a live capture.
2044 */
2045 #ifndef _WIN32
2046 /*
2047 * We don't need network access, so relinquish any set-UID
2048 * or set-GID privileges we have (if any).
2049 *
2050 * We do *not* want set-UID privileges when opening a
2051 * trace file, as that might let the user read other
2052 * people's trace files (especially if we're set-UID
2053 * root).
2054 */
2055 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
2056 fprintf(stderr, "Warning: setgid/setuid failed !\n");
2057 #endif /* _WIN32 */
2058 if (VFileName != NULL) {
2059 if (VFileName[0] == '-' && VFileName[1] == '\0')
2060 VFile = stdin;
2061 else
2062 VFile = fopen(VFileName, "r");
2063
2064 if (VFile == NULL)
2065 error("Unable to open file: %s\n", pcap_strerror(errno));
2066
2067 ret = get_next_file(VFile, VFileLine);
2068 if (!ret)
2069 error("Nothing in %s\n", VFileName);
2070 RFileName = VFileLine;
2071 }
2072
2073 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2074 pd = pcap_open_offline_with_tstamp_precision(RFileName,
2075 ndo->ndo_tstamp_precision, ebuf);
2076 #else
2077 pd = pcap_open_offline(RFileName, ebuf);
2078 #endif
2079
2080 if (pd == NULL)
2081 error("%s", ebuf);
2082 #ifdef HAVE_CAPSICUM
2083 cap_rights_init(&rights, CAP_READ);
2084 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
2085 errno != ENOSYS) {
2086 error("unable to limit pcap descriptor");
2087 }
2088 #endif
2089 dlt = pcap_datalink(pd);
2090 dlt_name = pcap_datalink_val_to_name(dlt);
2091 fprintf(stderr, "reading from file %s", RFileName);
2092 if (dlt_name == NULL) {
2093 fprintf(stderr, ", link-type %u", dlt);
2094 } else {
2095 fprintf(stderr, ", link-type %s (%s)", dlt_name,
2096 pcap_datalink_val_to_description(dlt));
2097 }
2098 fprintf(stderr, ", snapshot length %d\n", pcap_snapshot(pd));
2099 #ifdef DLT_LINUX_SLL2
2100 if (dlt == DLT_LINUX_SLL2)
2101 fprintf(stderr, "Warning: interface names might be incorrect\n");
2102 #endif
2103 } else if (dflag && !device) {
2104 int dump_dlt = DLT_EN10MB;
2105 /*
2106 * We're dumping the compiled code without an explicit
2107 * device specification. (If a device is specified, we
2108 * definitely want to open it to use the DLT of that device.)
2109 * Either default to DLT_EN10MB with a warning, or use
2110 * the user-specified value if supplied.
2111 */
2112 /*
2113 * If no snapshot length was specified, or a length of 0 was
2114 * specified, default to 256KB.
2115 */
2116 if (ndo->ndo_snaplen == 0)
2117 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
2118 /*
2119 * If a DLT was specified with the -y flag, use that instead.
2120 */
2121 if (yflag_dlt != -1)
2122 dump_dlt = yflag_dlt;
2123 else
2124 fprintf(stderr, "Warning: assuming Ethernet\n");
2125 pd = pcap_open_dead(dump_dlt, ndo->ndo_snaplen);
2126 } else {
2127 /*
2128 * We're doing a live capture.
2129 */
2130 if (device == NULL) {
2131 /*
2132 * No interface was specified. Pick one.
2133 */
2134 #ifdef HAVE_PCAP_FINDALLDEVS
2135 /*
2136 * Find the list of interfaces, and pick
2137 * the first interface.
2138 */
2139 if (pcap_findalldevs(&devlist, ebuf) == -1)
2140 error("%s", ebuf);
2141 if (devlist == NULL)
2142 error("no interfaces available for capture");
2143 device = strdup(devlist->name);
2144 pcap_freealldevs(devlist);
2145 #else /* HAVE_PCAP_FINDALLDEVS */
2146 /*
2147 * Use whatever interface pcap_lookupdev()
2148 * chooses.
2149 */
2150 device = pcap_lookupdev(ebuf);
2151 if (device == NULL)
2152 error("%s", ebuf);
2153 #endif
2154 }
2155
2156 /*
2157 * Try to open the interface with the specified name.
2158 */
2159 pd = open_interface(device, ndo, ebuf);
2160 if (pd == NULL) {
2161 /*
2162 * That failed. If we can get a list of
2163 * interfaces, and the interface name
2164 * is purely numeric, try to use it as
2165 * a 1-based index in the list of
2166 * interfaces.
2167 */
2168 #ifdef HAVE_PCAP_FINDALLDEVS
2169 devnum = parse_interface_number(device);
2170 if (devnum == -1) {
2171 /*
2172 * It's not a number; just report
2173 * the open error and fail.
2174 */
2175 error("%s", ebuf);
2176 }
2177
2178 /*
2179 * OK, it's a number; try to find the
2180 * interface with that index, and try
2181 * to open it.
2182 *
2183 * find_interface_by_number() exits if it
2184 * couldn't be found.
2185 */
2186 device = find_interface_by_number(device, devnum);
2187 pd = open_interface(device, ndo, ebuf);
2188 if (pd == NULL)
2189 error("%s", ebuf);
2190 #else /* HAVE_PCAP_FINDALLDEVS */
2191 /*
2192 * We can't get a list of interfaces; just
2193 * fail.
2194 */
2195 error("%s", ebuf);
2196 #endif /* HAVE_PCAP_FINDALLDEVS */
2197 }
2198
2199 /*
2200 * Let user own process after capture device has
2201 * been opened.
2202 */
2203 #ifndef _WIN32
2204 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2205 fprintf(stderr, "Warning: setgid/setuid failed !\n");
2206 #endif /* _WIN32 */
2207 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
2208 if(Bflag != 0)
2209 if(pcap_setbuff(pd, Bflag)==-1){
2210 error("%s", pcap_geterr(pd));
2211 }
2212 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
2213 if (Lflag)
2214 show_dlts_and_exit(pd, device);
2215 if (yflag_dlt >= 0) {
2216 #ifdef HAVE_PCAP_SET_DATALINK
2217 if (pcap_set_datalink(pd, yflag_dlt) < 0)
2218 error("%s", pcap_geterr(pd));
2219 #else
2220 /*
2221 * We don't actually support changing the
2222 * data link type, so we only let them
2223 * set it to what it already is.
2224 */
2225 if (yflag_dlt != pcap_datalink(pd)) {
2226 error("%s is not one of the DLTs supported by this device\n",
2227 yflag_dlt_name);
2228 }
2229 #endif
2230 (void)fprintf(stderr, "%s: data link type %s\n",
2231 program_name,
2232 pcap_datalink_val_to_name(yflag_dlt));
2233 (void)fflush(stderr);
2234 }
2235 #if defined(DLT_LINUX_SLL2) && defined(HAVE_PCAP_SET_DATALINK)
2236 else {
2237 /*
2238 * Attempt to set default linktype to
2239 * DLT_LINUX_SLL2 when capturing on the
2240 * "any" device.
2241 *
2242 * If the attempt fails, just quietly drive
2243 * on; this may be a non-Linux "any" device
2244 * that doesn't support DLT_LINUX_SLL2.
2245 */
2246 if (strcmp(device, "any") == 0) {
2247 DIAG_OFF_WARN_UNUSED_RESULT
2248 (void) pcap_set_datalink(pd, DLT_LINUX_SLL2);
2249 DIAG_ON_WARN_UNUSED_RESULT
2250 }
2251 }
2252 #endif
2253 i = pcap_snapshot(pd);
2254 if (ndo->ndo_snaplen < i) {
2255 if (ndo->ndo_snaplen != 0)
2256 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
2257 ndo->ndo_snaplen = i;
2258 } else if (ndo->ndo_snaplen > i) {
2259 warning("snaplen lowered from %d to %d", ndo->ndo_snaplen, i);
2260 ndo->ndo_snaplen = i;
2261 }
2262 if(ndo->ndo_fflag != 0) {
2263 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
2264 warning("foreign (-f) flag used but: %s", ebuf);
2265 }
2266 }
2267
2268 }
2269 if (infile)
2270 cmdbuf = read_infile(infile);
2271 else
2272 cmdbuf = copy_argv(&argv[optind]);
2273
2274 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2275 pcap_set_optimizer_debug(dflag);
2276 #endif
2277 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2278 error("%s", pcap_geterr(pd));
2279 if (dflag) {
2280 bpf_dump(&fcode, dflag);
2281 pcap_close(pd);
2282 free(cmdbuf);
2283 pcap_freecode(&fcode);
2284 exit_tcpdump(S_SUCCESS);
2285 }
2286
2287 #ifdef HAVE_CASPER
2288 if (!ndo->ndo_nflag)
2289 capdns = capdns_setup();
2290 #endif /* HAVE_CASPER */
2291
2292 init_print(ndo, localnet, netmask);
2293
2294 #ifndef _WIN32
2295 (void)setsignal(SIGPIPE, cleanup);
2296 (void)setsignal(SIGTERM, cleanup);
2297 #endif /* _WIN32 */
2298 (void)setsignal(SIGINT, cleanup);
2299 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2300 (void)setsignal(SIGCHLD, child_cleanup);
2301 #endif
2302 /* Cooperate with nohup(1) */
2303 #ifndef _WIN32
2304 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
2305 (void)setsignal(SIGHUP, oldhandler);
2306 #endif /* _WIN32 */
2307
2308 #ifndef _WIN32
2309 /*
2310 * If a user name was specified with "-Z", attempt to switch to
2311 * that user's UID. This would probably be used with sudo,
2312 * to allow tcpdump to be run in a special restricted
2313 * account (if you just want to allow users to open capture
2314 * devices, and can't just give users that permission,
2315 * you'd make tcpdump set-UID or set-GID).
2316 *
2317 * Tcpdump doesn't necessarily write only to one savefile;
2318 * the general only way to allow a -Z instance to write to
2319 * savefiles as the user under whose UID it's run, rather
2320 * than as the user specified with -Z, would thus be to switch
2321 * to the original user ID before opening a capture file and
2322 * then switch back to the -Z user ID after opening the savefile.
2323 * Switching to the -Z user ID only after opening the first
2324 * savefile doesn't handle the general case.
2325 */
2326
2327 if (getuid() == 0 || geteuid() == 0) {
2328 #ifdef HAVE_LIBCAP_NG
2329 /* Initialize capng */
2330 capng_clear(CAPNG_SELECT_BOTH);
2331 if (username) {
2332 DIAG_OFF_ASSIGN_ENUM
2333 capng_updatev(
2334 CAPNG_ADD,
2335 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2336 CAP_SETUID,
2337 CAP_SETGID,
2338 -1);
2339 DIAG_ON_ASSIGN_ENUM
2340 }
2341 if (chroot_dir) {
2342 DIAG_OFF_ASSIGN_ENUM
2343 capng_update(
2344 CAPNG_ADD,
2345 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2346 CAP_SYS_CHROOT
2347 );
2348 DIAG_ON_ASSIGN_ENUM
2349 }
2350
2351 if (WFileName) {
2352 DIAG_OFF_ASSIGN_ENUM
2353 capng_update(
2354 CAPNG_ADD,
2355 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2356 CAP_DAC_OVERRIDE
2357 );
2358 DIAG_ON_ASSIGN_ENUM
2359 }
2360 capng_apply(CAPNG_SELECT_BOTH);
2361 #endif /* HAVE_LIBCAP_NG */
2362 if (username || chroot_dir)
2363 droproot(username, chroot_dir);
2364
2365 }
2366 #endif /* _WIN32 */
2367
2368 if (pcap_setfilter(pd, &fcode) < 0)
2369 error("%s", pcap_geterr(pd));
2370 #ifdef HAVE_CAPSICUM
2371 if (RFileName == NULL && VFileName == NULL && pcap_fileno(pd) != -1) {
2372 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
2373
2374 /*
2375 * The various libpcap devices use a combination of
2376 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2377 * so we add the relevant access rights.
2378 */
2379 cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT);
2380 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
2381 errno != ENOSYS) {
2382 error("unable to limit pcap descriptor");
2383 }
2384 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
2385 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
2386 error("unable to limit ioctls on pcap descriptor");
2387 }
2388 }
2389 #endif
2390 if (WFileName) {
2391 /* Do not exceed the default PATH_MAX for files. */
2392 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
2393
2394 if (dumpinfo.CurrentFileName == NULL)
2395 error("malloc of dumpinfo.CurrentFileName");
2396
2397 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2398 if (Cflag != 0)
2399 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
2400 else
2401 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
2402
2403 pdd = pcap_dump_open(pd, dumpinfo.CurrentFileName);
2404 #ifdef HAVE_LIBCAP_NG
2405 /* Give up CAP_DAC_OVERRIDE capability.
2406 * Only allow it to be restored if the -C or -G flag have been
2407 * set since we may need to create more files later on.
2408 */
2409 capng_update(
2410 CAPNG_DROP,
2411 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
2412 | CAPNG_EFFECTIVE,
2413 CAP_DAC_OVERRIDE
2414 );
2415 capng_apply(CAPNG_SELECT_BOTH);
2416 #endif /* HAVE_LIBCAP_NG */
2417 if (pdd == NULL)
2418 error("%s", pcap_geterr(pd));
2419 #ifdef HAVE_CAPSICUM
2420 set_dumper_capsicum_rights(pdd);
2421 #endif
2422 if (Cflag != 0 || Gflag != 0) {
2423 #ifdef HAVE_CAPSICUM
2424 /*
2425 * basename() and dirname() may modify their input buffer
2426 * and they do since FreeBSD 12.0, but they didn't before.
2427 * Hence use the return value only, but always assume the
2428 * input buffer has been modified and would need to be
2429 * reset before the next use.
2430 */
2431 char *WFileName_copy;
2432
2433 if ((WFileName_copy = strdup(WFileName)) == NULL) {
2434 error("Unable to allocate memory for file %s",
2435 WFileName);
2436 }
2437 DIAG_OFF_C11_EXTENSIONS
2438 dumpinfo.WFileName = strdup(basename(WFileName_copy));
2439 DIAG_ON_C11_EXTENSIONS
2440 if (dumpinfo.WFileName == NULL) {
2441 error("Unable to allocate memory for file %s",
2442 WFileName);
2443 }
2444 free(WFileName_copy);
2445
2446 if ((WFileName_copy = strdup(WFileName)) == NULL) {
2447 error("Unable to allocate memory for file %s",
2448 WFileName);
2449 }
2450 DIAG_OFF_C11_EXTENSIONS
2451 char *WFileName_dirname = dirname(WFileName_copy);
2452 DIAG_ON_C11_EXTENSIONS
2453 dumpinfo.dirfd = open(WFileName_dirname,
2454 O_DIRECTORY | O_RDONLY);
2455 if (dumpinfo.dirfd < 0) {
2456 error("unable to open directory %s",
2457 WFileName_dirname);
2458 }
2459 free(WFileName_dirname);
2460 free(WFileName_copy);
2461
2462 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
2463 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
2464 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
2465 errno != ENOSYS) {
2466 error("unable to limit directory rights");
2467 }
2468 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
2469 errno != ENOSYS) {
2470 error("unable to limit dump descriptor fcntls");
2471 }
2472 #else /* !HAVE_CAPSICUM */
2473 dumpinfo.WFileName = WFileName;
2474 #endif
2475 callback = dump_packet_and_trunc;
2476 dumpinfo.pd = pd;
2477 dumpinfo.pdd = pdd;
2478 pcap_userdata = (u_char *)&dumpinfo;
2479 } else {
2480 callback = dump_packet;
2481 dumpinfo.WFileName = WFileName;
2482 dumpinfo.pd = pd;
2483 dumpinfo.pdd = pdd;
2484 pcap_userdata = (u_char *)&dumpinfo;
2485 }
2486 if (print) {
2487 dlt = pcap_datalink(pd);
2488 ndo->ndo_if_printer = get_if_printer(dlt);
2489 dumpinfo.ndo = ndo;
2490 } else
2491 dumpinfo.ndo = NULL;
2492
2493 #ifdef HAVE_PCAP_DUMP_FLUSH
2494 if (Uflag)
2495 pcap_dump_flush(pdd);
2496 #endif
2497 } else {
2498 dlt = pcap_datalink(pd);
2499 ndo->ndo_if_printer = get_if_printer(dlt);
2500 callback = print_packet;
2501 pcap_userdata = (u_char *)ndo;
2502 }
2503
2504 #ifdef SIGNAL_REQ_INFO
2505 /*
2506 * We can't get statistics when reading from a file rather
2507 * than capturing from a device.
2508 */
2509 if (RFileName == NULL)
2510 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
2511 #endif
2512 #ifdef SIGNAL_FLUSH_PCAP
2513 (void)setsignal(SIGNAL_FLUSH_PCAP, flushpcap);
2514 #endif
2515
2516 if (ndo->ndo_vflag > 0 && WFileName && RFileName == NULL && !print) {
2517 /*
2518 * When capturing to a file, if "--print" wasn't specified,
2519 *"-v" means tcpdump should, once per second,
2520 * "v"erbosely report the number of packets captured.
2521 * Except when reading from a file, because -r, -w and -v
2522 * together used to make a corner case, in which pcap_loop()
2523 * errored due to EINTR (see GH #155 for details).
2524 */
2525 #ifdef _WIN32
2526 /*
2527 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2528 *
2529 * suggests that this dates back to W2K.
2530 *
2531 * I don't know what a "long wait" is, but we'll assume
2532 * that printing the stats could be a "long wait".
2533 */
2534 CreateTimerQueueTimer(&timer_handle, NULL,
2535 verbose_stats_dump, NULL, 1000, 1000,
2536 WT_EXECUTEDEFAULT|WT_EXECUTELONGFUNCTION);
2537 setvbuf(stderr, NULL, _IONBF, 0);
2538 #else /* _WIN32 */
2539 /*
2540 * Assume this is UN*X, and that it has setitimer(); that
2541 * dates back to UNIX 95.
2542 */
2543 struct itimerval timer;
2544 (void)setsignal(SIGALRM, verbose_stats_dump);
2545 timer.it_interval.tv_sec = 1;
2546 timer.it_interval.tv_usec = 0;
2547 timer.it_value.tv_sec = 1;
2548 timer.it_value.tv_usec = 1;
2549 setitimer(ITIMER_REAL, &timer, NULL);
2550 #endif /* _WIN32 */
2551 }
2552
2553 if (RFileName == NULL) {
2554 /*
2555 * Live capture (if -V was specified, we set RFileName
2556 * to a file from the -V file). Print a message to
2557 * the standard error on UN*X.
2558 */
2559 if (!ndo->ndo_vflag && !WFileName) {
2560 (void)fprintf(stderr,
2561 "%s: verbose output suppressed, use -v[v]... for full protocol decode\n",
2562 program_name);
2563 } else
2564 (void)fprintf(stderr, "%s: ", program_name);
2565 dlt = pcap_datalink(pd);
2566 dlt_name = pcap_datalink_val_to_name(dlt);
2567 (void)fprintf(stderr, "listening on %s", device);
2568 if (dlt_name == NULL) {
2569 (void)fprintf(stderr, ", link-type %u", dlt);
2570 } else {
2571 (void)fprintf(stderr, ", link-type %s (%s)", dlt_name,
2572 pcap_datalink_val_to_description(dlt));
2573 }
2574 (void)fprintf(stderr, ", snapshot length %d bytes\n", ndo->ndo_snaplen);
2575 (void)fflush(stderr);
2576 }
2577
2578 #ifdef HAVE_CAPSICUM
2579 cansandbox = (VFileName == NULL && zflag == NULL);
2580 #ifdef HAVE_CASPER
2581 cansandbox = (cansandbox && (ndo->ndo_nflag || capdns != NULL));
2582 #else
2583 cansandbox = (cansandbox && ndo->ndo_nflag);
2584 #endif /* HAVE_CASPER */
2585 cansandbox = (cansandbox && (pcap_fileno(pd) != -1 ||
2586 RFileName != NULL));
2587
2588 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
2589 error("unable to enter the capability mode");
2590 #endif /* HAVE_CAPSICUM */
2591
2592 do {
2593 status = pcap_loop(pd, cnt, callback, pcap_userdata);
2594 if (WFileName == NULL) {
2595 /*
2596 * We're printing packets. Flush the printed output,
2597 * so it doesn't get intermingled with error output.
2598 */
2599 if (status == -2) {
2600 /*
2601 * We got interrupted, so perhaps we didn't
2602 * manage to finish a line we were printing.
2603 * Print an extra newline, just in case.
2604 */
2605 putchar('\n');
2606 }
2607 (void)fflush(stdout);
2608 }
2609 if (status == -2) {
2610 /*
2611 * We got interrupted. If we are reading multiple
2612 * files (via -V) set these so that we stop.
2613 */
2614 VFileName = NULL;
2615 ret = NULL;
2616 }
2617 if (status == -1) {
2618 /*
2619 * Error. Report it.
2620 */
2621 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
2622 program_name, pcap_geterr(pd));
2623 }
2624 if (RFileName == NULL) {
2625 /*
2626 * We're doing a live capture. Report the capture
2627 * statistics.
2628 */
2629 info(1);
2630 }
2631 pcap_close(pd);
2632 if (VFileName != NULL) {
2633 ret = get_next_file(VFile, VFileLine);
2634 if (ret) {
2635 int new_dlt;
2636
2637 RFileName = VFileLine;
2638 pd = pcap_open_offline(RFileName, ebuf);
2639 if (pd == NULL)
2640 error("%s", ebuf);
2641 #ifdef HAVE_CAPSICUM
2642 cap_rights_init(&rights, CAP_READ);
2643 if (cap_rights_limit(fileno(pcap_file(pd)),
2644 &rights) < 0 && errno != ENOSYS) {
2645 error("unable to limit pcap descriptor");
2646 }
2647 #endif
2648 new_dlt = pcap_datalink(pd);
2649 if (new_dlt != dlt) {
2650 /*
2651 * The new file has a different
2652 * link-layer header type from the
2653 * previous one.
2654 */
2655 if (WFileName != NULL) {
2656 /*
2657 * We're writing raw packets
2658 * that match the filter to
2659 * a pcap file. pcap files
2660 * don't support multiple
2661 * different link-layer
2662 * header types, so we fail
2663 * here.
2664 */
2665 error("%s: new dlt does not match original", RFileName);
2666 }
2667
2668 /*
2669 * We're printing the decoded packets;
2670 * switch to the new DLT.
2671 *
2672 * To do that, we need to change
2673 * the printer, change the DLT name,
2674 * and recompile the filter with
2675 * the new DLT.
2676 */
2677 dlt = new_dlt;
2678 ndo->ndo_if_printer = get_if_printer(dlt);
2679 /* Free the old filter */
2680 pcap_freecode(&fcode);
2681 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2682 error("%s", pcap_geterr(pd));
2683 }
2684
2685 /*
2686 * Set the filter on the new file.
2687 */
2688 if (pcap_setfilter(pd, &fcode) < 0)
2689 error("%s", pcap_geterr(pd));
2690
2691 /*
2692 * Report the new file.
2693 */
2694 dlt_name = pcap_datalink_val_to_name(dlt);
2695 fprintf(stderr, "reading from file %s", RFileName);
2696 if (dlt_name == NULL) {
2697 fprintf(stderr, ", link-type %u", dlt);
2698 } else {
2699 fprintf(stderr, ", link-type %s (%s)",
2700 dlt_name,
2701 pcap_datalink_val_to_description(dlt));
2702 }
2703 fprintf(stderr, ", snapshot length %d\n", pcap_snapshot(pd));
2704 }
2705 }
2706 }
2707 while (ret != NULL);
2708
2709 if (count_mode && RFileName != NULL)
2710 fprintf(stdout, "%u packet%s\n", packets_captured,
2711 PLURAL_SUFFIX(packets_captured));
2712
2713 free(cmdbuf);
2714 pcap_freecode(&fcode);
2715 exit_tcpdump(status == -1 ? S_ERR_HOST_PROGRAM : S_SUCCESS);
2716 }
2717
2718 /*
2719 * Catch a signal.
2720 */
2721 static void
2722 (*setsignal (int sig, void (*func)(int)))(int)
2723 {
2724 #ifdef _WIN32
2725 return (signal(sig, func));
2726 #else
2727 struct sigaction old, new;
2728
2729 memset(&new, 0, sizeof(new));
2730 new.sa_handler = func;
2731 if ((sig == SIGCHLD)
2732 # ifdef SIGNAL_REQ_INFO
2733 || (sig == SIGNAL_REQ_INFO)
2734 # endif
2735 # ifdef SIGNAL_FLUSH_PCAP
2736 || (sig == SIGNAL_FLUSH_PCAP)
2737 # endif
2738 )
2739 new.sa_flags = SA_RESTART;
2740 if (sigaction(sig, &new, &old) < 0)
2741 return (SIG_ERR);
2742 return (old.sa_handler);
2743 #endif
2744 }
2745
2746 /* make a clean exit on interrupts */
2747 static void
2748 cleanup(int signo _U_)
2749 {
2750 #ifdef _WIN32
2751 if (timer_handle != INVALID_HANDLE_VALUE) {
2752 DeleteTimerQueueTimer(NULL, timer_handle, NULL);
2753 CloseHandle(timer_handle);
2754 timer_handle = INVALID_HANDLE_VALUE;
2755 }
2756 #else /* _WIN32 */
2757 struct itimerval timer;
2758
2759 timer.it_interval.tv_sec = 0;
2760 timer.it_interval.tv_usec = 0;
2761 timer.it_value.tv_sec = 0;
2762 timer.it_value.tv_usec = 0;
2763 setitimer(ITIMER_REAL, &timer, NULL);
2764 #endif /* _WIN32 */
2765
2766 #ifdef HAVE_PCAP_BREAKLOOP
2767 /*
2768 * We have "pcap_breakloop()"; use it, so that we do as little
2769 * as possible in the signal handler (it's probably not safe
2770 * to do anything with standard I/O streams in a signal handler -
2771 * the ANSI C standard doesn't say it is).
2772 */
2773 pcap_breakloop(pd);
2774 #else
2775 /*
2776 * We don't have "pcap_breakloop()"; this isn't safe, but
2777 * it's the best we can do. Print the summary if we're
2778 * not reading from a savefile - i.e., if we're doing a
2779 * live capture - and exit.
2780 */
2781 if (pd != NULL && pcap_file(pd) == NULL) {
2782 /*
2783 * We got interrupted, so perhaps we didn't
2784 * manage to finish a line we were printing.
2785 * Print an extra newline, just in case.
2786 */
2787 putchar('\n');
2788 (void)fflush(stdout);
2789 info(1);
2790 }
2791 exit_tcpdump(S_SUCCESS);
2792 #endif
2793 }
2794
2795 /*
2796 On windows, we do not use a fork, so we do not care less about
2797 waiting a child processes to die
2798 */
2799 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2800 static void
2801 child_cleanup(int signo _U_)
2802 {
2803 while (waitpid(-1, NULL, WNOHANG) >= 0);
2804 }
2805 #endif /* HAVE_FORK && HAVE_VFORK */
2806
2807 static void
2808 info(int verbose)
2809 {
2810 struct pcap_stat stats;
2811
2812 /*
2813 * Older versions of libpcap didn't set ps_ifdrop on some
2814 * platforms; initialize it to 0 to handle that.
2815 */
2816 stats.ps_ifdrop = 0;
2817 if (pcap_stats(pd, &stats) < 0) {
2818 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2819 infoprint = 0;
2820 return;
2821 }
2822
2823 if (!verbose)
2824 fprintf(stderr, "%s: ", program_name);
2825
2826 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
2827 PLURAL_SUFFIX(packets_captured));
2828 if (!verbose)
2829 fputs(", ", stderr);
2830 else
2831 putc('\n', stderr);
2832 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
2833 PLURAL_SUFFIX(stats.ps_recv));
2834 if (!verbose)
2835 fputs(", ", stderr);
2836 else
2837 putc('\n', stderr);
2838 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
2839 PLURAL_SUFFIX(stats.ps_drop));
2840 if (stats.ps_ifdrop != 0) {
2841 if (!verbose)
2842 fputs(", ", stderr);
2843 else
2844 putc('\n', stderr);
2845 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
2846 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
2847 } else
2848 putc('\n', stderr);
2849 infoprint = 0;
2850 }
2851
2852 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2853 #ifdef HAVE_FORK
2854 #define fork_subprocess() fork()
2855 #else
2856 #define fork_subprocess() vfork()
2857 #endif
2858 static void
2859 compress_savefile(const char *filename)
2860 {
2861 pid_t child;
2862
2863 child = fork_subprocess();
2864 if (child == -1) {
2865 fprintf(stderr,
2866 "compress_savefile: fork failed: %s\n",
2867 pcap_strerror(errno));
2868 return;
2869 }
2870 if (child != 0) {
2871 /* Parent process. */
2872 return;
2873 }
2874
2875 /*
2876 * Child process.
2877 * Set to lowest priority so that this doesn't disturb the capture.
2878 */
2879 #ifdef NZERO
2880 setpriority(PRIO_PROCESS, 0, NZERO - 1);
2881 #else
2882 setpriority(PRIO_PROCESS, 0, 19);
2883 #endif
2884 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2885 fprintf(stderr,
2886 "compress_savefile: execlp(%s, %s) failed: %s\n",
2887 zflag,
2888 filename,
2889 pcap_strerror(errno));
2890 #ifdef HAVE_FORK
2891 exit(S_ERR_HOST_PROGRAM);
2892 #else
2893 _exit(S_ERR_HOST_PROGRAM);
2894 #endif
2895 }
2896 #else /* HAVE_FORK && HAVE_VFORK */
2897 static void
2898 compress_savefile(const char *filename)
2899 {
2900 fprintf(stderr,
2901 "compress_savefile failed. Functionality not implemented under your system\n");
2902 }
2903 #endif /* HAVE_FORK && HAVE_VFORK */
2904
2905 static void
2906 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2907 {
2908 struct dump_info *dump_info;
2909
2910 ++packets_captured;
2911
2912 ++infodelay;
2913
2914 dump_info = (struct dump_info *)user;
2915
2916 /*
2917 * XXX - this won't force the file to rotate on the specified time
2918 * boundary, but it will rotate on the first packet received after the
2919 * specified Gflag number of seconds. Note: if a Gflag time boundary
2920 * and a Cflag size boundary coincide, the time rotation will occur
2921 * first thereby cancelling the Cflag boundary (since the file should
2922 * be 0).
2923 */
2924 if (Gflag != 0) {
2925 /* Check if it is time to rotate */
2926 time_t t;
2927
2928 /* Get the current time */
2929 if ((t = time(NULL)) == (time_t)-1) {
2930 error("%s: can't get current_time: %s",
2931 __func__, pcap_strerror(errno));
2932 }
2933
2934
2935 /* If the time is greater than the specified window, rotate */
2936 if (t - Gflag_time >= Gflag) {
2937 #ifdef HAVE_CAPSICUM
2938 FILE *fp;
2939 int fd;
2940 #endif
2941
2942 /* Update the Gflag_time */
2943 Gflag_time = t;
2944 /* Update Gflag_count */
2945 Gflag_count++;
2946 /*
2947 * Close the current file and open a new one.
2948 */
2949 pcap_dump_close(dump_info->pdd);
2950
2951 /*
2952 * Compress the file we just closed, if the user asked for it
2953 */
2954 if (zflag != NULL)
2955 compress_savefile(dump_info->CurrentFileName);
2956
2957 /*
2958 * Check to see if we've exceeded the Wflag (when
2959 * not using Cflag).
2960 */
2961 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2962 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2963 Wflag);
2964 info(1);
2965 exit_tcpdump(S_SUCCESS);
2966 /* NOTREACHED */
2967 }
2968 if (dump_info->CurrentFileName != NULL)
2969 free(dump_info->CurrentFileName);
2970 /* Allocate space for max filename + \0. */
2971 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2972 if (dump_info->CurrentFileName == NULL)
2973 error("dump_packet_and_trunc: malloc");
2974 /*
2975 * Gflag was set otherwise we wouldn't be here. Reset the count
2976 * so multiple files would end with 1,2,3 in the filename.
2977 * The counting is handled with the -C flow after this.
2978 */
2979 Cflag_count = 0;
2980
2981 /*
2982 * This is always the first file in the Cflag
2983 * rotation: e.g. 0
2984 * We also don't need numbering if Cflag is not set.
2985 */
2986 if (Cflag != 0)
2987 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2988 WflagChars);
2989 else
2990 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2991
2992 #ifdef HAVE_LIBCAP_NG
2993 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2994 capng_apply(CAPNG_SELECT_BOTH);
2995 #endif /* HAVE_LIBCAP_NG */
2996 #ifdef HAVE_CAPSICUM
2997 fd = openat(dump_info->dirfd,
2998 dump_info->CurrentFileName,
2999 O_CREAT | O_WRONLY | O_TRUNC, 0644);
3000 if (fd < 0) {
3001 error("unable to open file %s",
3002 dump_info->CurrentFileName);
3003 }
3004 fp = fdopen(fd, "w");
3005 if (fp == NULL) {
3006 error("unable to fdopen file %s",
3007 dump_info->CurrentFileName);
3008 }
3009 dump_info->pdd = pcap_dump_fopen(dump_info->pd, fp);
3010 #else /* !HAVE_CAPSICUM */
3011 dump_info->pdd = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
3012 #endif
3013 #ifdef HAVE_LIBCAP_NG
3014 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
3015 capng_apply(CAPNG_SELECT_BOTH);
3016 #endif /* HAVE_LIBCAP_NG */
3017 if (dump_info->pdd == NULL)
3018 error("%s", pcap_geterr(pd));
3019 #ifdef HAVE_CAPSICUM
3020 set_dumper_capsicum_rights(dump_info->pdd);
3021 #endif
3022 }
3023 }
3024
3025 /*
3026 * XXX - this won't prevent capture files from getting
3027 * larger than Cflag - the last packet written to the
3028 * file could put it over Cflag.
3029 */
3030 if (Cflag != 0) {
3031 #ifdef HAVE_PCAP_DUMP_FTELL64
3032 int64_t size = pcap_dump_ftell64(dump_info->pdd);
3033 #else
3034 /*
3035 * XXX - this only handles a Cflag value > 2^31-1 on
3036 * LP64 platforms; to handle ILP32 (32-bit UN*X and
3037 * Windows) or LLP64 (64-bit Windows) would require
3038 * a version of libpcap with pcap_dump_ftell64().
3039 */
3040 long size = pcap_dump_ftell(dump_info->pdd);
3041 #endif
3042
3043 if (size == -1)
3044 error("ftell fails on output file");
3045 if (size > Cflag) {
3046 #ifdef HAVE_CAPSICUM
3047 FILE *fp;
3048 int fd;
3049 #endif
3050
3051 /*
3052 * Close the current file and open a new one.
3053 */
3054 pcap_dump_close(dump_info->pdd);
3055
3056 /*
3057 * Compress the file we just closed, if the user
3058 * asked for it.
3059 */
3060 if (zflag != NULL)
3061 compress_savefile(dump_info->CurrentFileName);
3062
3063 Cflag_count++;
3064 if (Wflag > 0) {
3065 if (Cflag_count >= Wflag)
3066 Cflag_count = 0;
3067 }
3068 if (dump_info->CurrentFileName != NULL)
3069 free(dump_info->CurrentFileName);
3070 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
3071 if (dump_info->CurrentFileName == NULL)
3072 error("%s: malloc", __func__);
3073 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
3074 #ifdef HAVE_LIBCAP_NG
3075 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
3076 capng_apply(CAPNG_SELECT_BOTH);
3077 #endif /* HAVE_LIBCAP_NG */
3078 #ifdef HAVE_CAPSICUM
3079 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
3080 O_CREAT | O_WRONLY | O_TRUNC, 0644);
3081 if (fd < 0) {
3082 error("unable to open file %s",
3083 dump_info->CurrentFileName);
3084 }
3085 fp = fdopen(fd, "w");
3086 if (fp == NULL) {
3087 error("unable to fdopen file %s",
3088 dump_info->CurrentFileName);
3089 }
3090 dump_info->pdd = pcap_dump_fopen(dump_info->pd, fp);
3091 #else /* !HAVE_CAPSICUM */
3092 dump_info->pdd = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
3093 #endif
3094 #ifdef HAVE_LIBCAP_NG
3095 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
3096 capng_apply(CAPNG_SELECT_BOTH);
3097 #endif /* HAVE_LIBCAP_NG */
3098 if (dump_info->pdd == NULL)
3099 error("%s", pcap_geterr(pd));
3100 #ifdef HAVE_CAPSICUM
3101 set_dumper_capsicum_rights(dump_info->pdd);
3102 #endif
3103 }
3104 }
3105
3106 pcap_dump((u_char *)dump_info->pdd, h, sp);
3107 #ifdef HAVE_PCAP_DUMP_FLUSH
3108 if (Uflag)
3109 pcap_dump_flush(dump_info->pdd);
3110 #endif
3111
3112 if (dump_info->ndo != NULL)
3113 pretty_print_packet(dump_info->ndo, h, sp, packets_captured);
3114
3115 --infodelay;
3116 if (infoprint)
3117 info(0);
3118 }
3119
3120 static void
3121 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
3122 {
3123 struct dump_info *dump_info;
3124
3125 ++packets_captured;
3126
3127 ++infodelay;
3128
3129 dump_info = (struct dump_info *)user;
3130
3131 pcap_dump((u_char *)dump_info->pdd, h, sp);
3132 #ifdef HAVE_PCAP_DUMP_FLUSH
3133 if (Uflag)
3134 pcap_dump_flush(dump_info->pdd);
3135 #endif
3136
3137 if (dump_info->ndo != NULL)
3138 pretty_print_packet(dump_info->ndo, h, sp, packets_captured);
3139
3140 --infodelay;
3141 if (infoprint)
3142 info(0);
3143 }
3144
3145 static void
3146 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
3147 {
3148 ++packets_captured;
3149
3150 ++infodelay;
3151
3152 if (!count_mode)
3153 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
3154
3155 --infodelay;
3156 if (infoprint)
3157 info(0);
3158 }
3159
3160 #ifdef SIGNAL_REQ_INFO
3161 static void
3162 requestinfo(int signo _U_)
3163 {
3164 if (infodelay)
3165 ++infoprint;
3166 else
3167 info(0);
3168 }
3169 #endif
3170
3171 #ifdef SIGNAL_FLUSH_PCAP
3172 static void
3173 flushpcap(int signo _U_)
3174 {
3175 if (pdd != NULL)
3176 pcap_dump_flush(pdd);
3177 }
3178 #endif
3179
3180 static void
3181 print_packets_captured (void)
3182 {
3183 static u_int prev_packets_captured, first = 1;
3184
3185 if (infodelay == 0 && (first || packets_captured != prev_packets_captured)) {
3186 fprintf(stderr, "Got %u\r", packets_captured);
3187 first = 0;
3188 prev_packets_captured = packets_captured;
3189 }
3190 }
3191
3192 /*
3193 * Called once each second in verbose mode while dumping to file
3194 */
3195 #ifdef _WIN32
3196 static void CALLBACK verbose_stats_dump(PVOID param _U_,
3197 BOOLEAN timer_fired _U_)
3198 {
3199 print_packets_captured();
3200 }
3201 #else /* _WIN32 */
3202 static void verbose_stats_dump(int sig _U_)
3203 {
3204 print_packets_captured();
3205 }
3206 #endif /* _WIN32 */
3207
3208 DIAG_OFF_DEPRECATION
3209 static void
3210 print_version(FILE *f)
3211 {
3212 #ifndef HAVE_PCAP_LIB_VERSION
3213 #ifdef HAVE_PCAP_VERSION
3214 extern char pcap_version[];
3215 #else /* HAVE_PCAP_VERSION */
3216 static char pcap_version[] = "unknown";
3217 #endif /* HAVE_PCAP_VERSION */
3218 #endif /* HAVE_PCAP_LIB_VERSION */
3219 const char *smi_version_string;
3220
3221 (void)fprintf(f, "%s version " PACKAGE_VERSION "\n", program_name);
3222 #ifdef HAVE_PCAP_LIB_VERSION
3223 (void)fprintf(f, "%s\n", pcap_lib_version());
3224 #else /* HAVE_PCAP_LIB_VERSION */
3225 (void)fprintf(f, "libpcap version %s\n", pcap_version);
3226 #endif /* HAVE_PCAP_LIB_VERSION */
3227
3228 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3229 (void)fprintf (f, "%s\n", SSLeay_version(SSLEAY_VERSION));
3230 #endif
3231
3232 smi_version_string = nd_smi_version_string();
3233 if (smi_version_string != NULL)
3234 (void)fprintf (f, "SMI-library: %s\n", smi_version_string);
3235
3236 #if defined(__SANITIZE_ADDRESS__)
3237 (void)fprintf (f, "Compiled with AddressSanitizer/GCC.\n");
3238 #elif defined(__has_feature)
3239 # if __has_feature(address_sanitizer)
3240 (void)fprintf (f, "Compiled with AddressSanitizer/Clang.\n");
3241 # elif __has_feature(memory_sanitizer)
3242 (void)fprintf (f, "Compiled with MemorySanitizer/Clang.\n");
3243 # endif
3244 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3245 }
3246 DIAG_ON_DEPRECATION
3247
3248 static void
3249 print_usage(FILE *f)
3250 {
3251 print_version(f);
3252 (void)fprintf(f,
3253 "Usage: %s [-Abd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ] [--count]\n", program_name);
3254 (void)fprintf(f,
3255 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3256 (void)fprintf(f,
3257 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE "\n");
3258 #ifdef HAVE_PCAP_FINDALLDEVS_EX
3259 (void)fprintf(f,
3260 "\t\t" LIST_REMOTE_INTERFACES_USAGE "\n");
3261 #endif
3262 #ifdef USE_LIBSMI
3263 (void)fprintf(f,
3264 "\t\t" m_FLAG_USAGE "\n");
3265 #endif
3266 (void)fprintf(f,
3267 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE "\n");
3268 (void)fprintf(f,
3269 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ --version ]\n");
3270 (void)fprintf(f,
3271 "\t\t[ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ]\n");
3272 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3273 (void)fprintf(f,
3274 "\t\t[ --time-stamp-precision precision ] [ --micro ] [ --nano ]\n");
3275 #endif
3276 (void)fprintf(f,
3277 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");
3278 }