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