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