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