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