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