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