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