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