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