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