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