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