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