]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
Free the entire list of devices, not just its tail
[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 * Mac OS X may ship pcap.h from libpcap 0.6 with a libpcap based on
48 * 0.8. That means it has pcap_findalldevs() but the header doesn't
49 * define pcap_if_t, meaning that we can't actually *use* pcap_findalldevs().
50 */
51 #ifdef HAVE_PCAP_FINDALLDEVS
52 #ifndef HAVE_PCAP_IF_T
53 #undef HAVE_PCAP_FINDALLDEVS
54 #endif
55 #endif
56
57 #include <netdissect-stdinc.h>
58
59 #ifdef USE_LIBSMI
60 #include <smi.h>
61 #endif
62
63 #ifdef HAVE_LIBCRYPTO
64 #include <openssl/crypto.h>
65 #endif
66
67 #ifdef HAVE_GETOPT_LONG
68 #include <getopt.h>
69 #else
70 #include "getopt_long.h"
71 #endif
72 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
73 * to compile if <pcap.h> has already been included; including the headers
74 * in the opposite order works fine.
75 */
76 #ifdef HAVE_CAPSICUM
77 #include <sys/capability.h>
78 #include <sys/ioccom.h>
79 #include <net/bpf.h>
80 #include <fcntl.h>
81 #include <libgen.h>
82 #endif /* HAVE_CAPSICUM */
83 #include <pcap.h>
84 #include <signal.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <limits.h>
89 #ifndef _WIN32
90 #include <sys/wait.h>
91 #include <sys/resource.h>
92 #include <pwd.h>
93 #include <grp.h>
94 #endif /* _WIN32 */
95
96 /* capabilities convenience library */
97 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
98 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
99 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
100 */
101 #ifdef HAVE_LIBCAP_NG
102 #ifdef HAVE_CAP_NG_H
103 #include <cap-ng.h>
104 #else
105 #undef HAVE_LIBCAP_NG
106 #endif /* HAVE_CAP_NG_H */
107 #endif /* HAVE_LIBCAP_NG */
108
109 #include "netdissect.h"
110 #include "interface.h"
111 #include "addrtoname.h"
112 #include "machdep.h"
113 #include "setsignal.h"
114 #include "gmt2local.h"
115 #include "pcap-missing.h"
116 #include "ascii_strcasecmp.h"
117
118 #include "print.h"
119
120 #ifndef PATH_MAX
121 #define PATH_MAX 1024
122 #endif
123
124 #ifdef SIGINFO
125 #define SIGNAL_REQ_INFO SIGINFO
126 #elif SIGUSR1
127 #define SIGNAL_REQ_INFO SIGUSR1
128 #endif
129
130 static int Cflag; /* rotate dump files after this many bytes */
131 static int Cflag_count; /* Keep track of which file number we're writing */
132 static int Dflag; /* list available devices and exit */
133 static int dflag; /* print filter code */
134 static int Gflag; /* rotate dump files after this many seconds */
135 static int Gflag_count; /* number of files created with Gflag rotation */
136 static time_t Gflag_time; /* The last time_t the dump file was rotated. */
137 static int Lflag; /* list available data link types and exit */
138 static int Iflag; /* rfmon (monitor) mode */
139 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
140 static int Jflag; /* list available time stamp types */
141 #endif
142 #ifdef HAVE_PCAP_SETDIRECTION
143 int Qflag = -1; /* restrict captured packet by send/receive direction */
144 #endif
145 static int Uflag; /* "unbuffered" output of dump files */
146 static int Wflag; /* recycle output files after this number of files */
147 static int WflagChars;
148 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
149
150 static int infodelay;
151 static int infoprint;
152
153 char *program_name;
154
155 /* Forwards */
156 static RETSIGTYPE cleanup(int);
157 static RETSIGTYPE child_cleanup(int);
158 static void print_version(void);
159 static void print_usage(void);
160 static void show_tstamp_types_and_exit(const char *device) __attribute__((noreturn));
161 static void show_dlts_and_exit(const char *device) __attribute__((noreturn));
162
163 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
164 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
165 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
166 static void droproot(const char *, const char *);
167
168 #ifdef SIGNAL_REQ_INFO
169 RETSIGTYPE requestinfo(int);
170 #endif
171
172 #if defined(USE_WIN32_MM_TIMER)
173 #include <MMsystem.h>
174 static UINT timer_id;
175 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
176 #elif defined(HAVE_ALARM)
177 static void verbose_stats_dump(int sig);
178 #endif
179
180 static void info(int);
181 static u_int packets_captured;
182
183 static const struct tok status_flags[] = {
184 #ifdef PCAP_IF_UP
185 { PCAP_IF_UP, "Up" },
186 #endif
187 #ifdef PCAP_IF_RUNNING
188 { PCAP_IF_RUNNING, "Running" },
189 #endif
190 { PCAP_IF_LOOPBACK, "Loopback" },
191 { 0, NULL }
192 };
193
194 static pcap_t *pd;
195
196 static int supports_monitor_mode;
197
198 extern int optind;
199 extern int opterr;
200 extern char *optarg;
201
202 struct dump_info {
203 char *WFileName;
204 char *CurrentFileName;
205 pcap_t *pd;
206 pcap_dumper_t *p;
207 #ifdef HAVE_CAPSICUM
208 int dirfd;
209 #endif
210 };
211
212 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
213 static void
214 show_tstamp_types_and_exit(const char *device)
215 {
216 int n_tstamp_types;
217 int *tstamp_types = 0;
218 const char *tstamp_type_name;
219 int i;
220
221 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
222 if (n_tstamp_types < 0)
223 error("%s", pcap_geterr(pd));
224
225 if (n_tstamp_types == 0) {
226 fprintf(stderr, "Time stamp type cannot be set for %s\n",
227 device);
228 exit(0);
229 }
230 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
231 device);
232 for (i = 0; i < n_tstamp_types; i++) {
233 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
234 if (tstamp_type_name != NULL) {
235 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
236 pcap_tstamp_type_val_to_description(tstamp_types[i]));
237 } else {
238 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
239 }
240 }
241 pcap_free_tstamp_types(tstamp_types);
242 exit(0);
243 }
244 #endif
245
246 static void
247 show_dlts_and_exit(const char *device)
248 {
249 int n_dlts, i;
250 int *dlts = 0;
251 const char *dlt_name;
252
253 n_dlts = pcap_list_datalinks(pd, &dlts);
254 if (n_dlts < 0)
255 error("%s", pcap_geterr(pd));
256 else if (n_dlts == 0 || !dlts)
257 error("No data link types.");
258
259 /*
260 * If the interface is known to support monitor mode, indicate
261 * whether these are the data link types available when not in
262 * monitor mode, if -I wasn't specified, or when in monitor mode,
263 * when -I was specified (the link-layer types available in
264 * monitor mode might be different from the ones available when
265 * not in monitor mode).
266 */
267 if (supports_monitor_mode)
268 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
269 device,
270 Iflag ? "when in monitor mode" : "when not in monitor mode");
271 else
272 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
273 device);
274
275 for (i = 0; i < n_dlts; i++) {
276 dlt_name = pcap_datalink_val_to_name(dlts[i]);
277 if (dlt_name != NULL) {
278 (void) fprintf(stderr, " %s (%s)", dlt_name,
279 pcap_datalink_val_to_description(dlts[i]));
280
281 /*
282 * OK, does tcpdump handle that type?
283 */
284 if (!has_printer(dlts[i]))
285 (void) fprintf(stderr, " (printing not supported)");
286 fprintf(stderr, "\n");
287 } else {
288 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
289 dlts[i]);
290 }
291 }
292 #ifdef HAVE_PCAP_FREE_DATALINKS
293 pcap_free_datalinks(dlts);
294 #endif
295 exit(0);
296 }
297
298 #ifdef HAVE_PCAP_FINDALLDEVS
299 static void
300 show_devices_and_exit (void)
301 {
302 pcap_if_t *devpointer;
303 char ebuf[PCAP_ERRBUF_SIZE];
304 int i;
305
306 if (pcap_findalldevs(&devpointer, ebuf) < 0)
307 error("%s", ebuf);
308 else {
309 for (i = 0; devpointer != NULL; i++) {
310 printf("%d.%s", i+1, devpointer->name);
311 if (devpointer->description != NULL)
312 printf(" (%s)", devpointer->description);
313 if (devpointer->flags != 0)
314 printf(" [%s]", bittok2str(status_flags, "none", devpointer->flags));
315 printf("\n");
316 devpointer = devpointer->next;
317 }
318 }
319 exit(0);
320 }
321 #endif /* HAVE_PCAP_FINDALLDEVS */
322
323 /*
324 * Short options.
325 *
326 * Note that there we use all letters for short options except for g, k,
327 * o, and P, and those are used by other versions of tcpdump, and we should
328 * only use them for the same purposes that the other versions of tcpdump
329 * use them:
330 *
331 * OS X tcpdump uses -g to force non--v output for IP to be on one
332 * line, making it more "g"repable;
333 *
334 * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
335 * should be printed;
336 *
337 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
338 * for hosts sending TCP SYN packets;
339 *
340 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
341 * than pcap files.
342 *
343 * OS X tcpdump also uses -Q to specify expressions that match packet
344 * metadata, including but not limited to the packet direction.
345 * The expression syntax is different from a simple "in|out|inout",
346 * and those expressions aren't accepted by OS X tcpdump, but the
347 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
348 * "inout" = "dir=in or dir=out", and the parser could conceivably
349 * special-case "in", "out", and "inout" as expressions for backwards
350 * compatibility, so all is not (yet) lost.
351 */
352
353 /*
354 * Set up flags that might or might not be supported depending on the
355 * version of libpcap we're using.
356 */
357 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
358 #define B_FLAG "B:"
359 #define B_FLAG_USAGE " [ -B size ]"
360 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
361 #define B_FLAG
362 #define B_FLAG_USAGE
363 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
364
365 #ifdef HAVE_PCAP_CREATE
366 #define I_FLAG "I"
367 #else /* HAVE_PCAP_CREATE */
368 #define I_FLAG
369 #endif /* HAVE_PCAP_CREATE */
370
371 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
372 #define j_FLAG "j:"
373 #define j_FLAG_USAGE " [ -j tstamptype ]"
374 #define J_FLAG "J"
375 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
376 #define j_FLAG
377 #define j_FLAG_USAGE
378 #define J_FLAG
379 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
380
381 #ifdef HAVE_PCAP_FINDALLDEVS
382 #define D_FLAG "D"
383 #else
384 #define D_FLAG
385 #endif
386
387 #ifdef HAVE_PCAP_DUMP_FLUSH
388 #define U_FLAG "U"
389 #else
390 #define U_FLAG
391 #endif
392
393 #ifdef HAVE_PCAP_SETDIRECTION
394 #define Q_FLAG "Q:"
395 #else
396 #define Q_FLAG
397 #endif
398
399 #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:#"
400
401 /*
402 * Long options.
403 *
404 * We do not currently have long options corresponding to all short
405 * options; we should probably pick appropriate option names for them.
406 *
407 * However, the short options where the number of times the option is
408 * specified matters, such as -v and -d and -t, should probably not
409 * just map to a long option, as saying
410 *
411 * tcpdump --verbose --verbose
412 *
413 * doesn't make sense; it should be --verbosity={N} or something such
414 * as that.
415 *
416 * For long options with no corresponding short options, we define values
417 * outside the range of ASCII graphic characters, make that the last
418 * component of the entry for the long option, and have a case for that
419 * option in the switch statement.
420 */
421 #define OPTION_VERSION 128
422 #define OPTION_TSTAMP_PRECISION 129
423 #define OPTION_IMMEDIATE_MODE 130
424
425 static const struct option longopts[] = {
426 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
427 { "buffer-size", required_argument, NULL, 'B' },
428 #endif
429 { "list-interfaces", no_argument, NULL, 'D' },
430 { "help", no_argument, NULL, 'h' },
431 { "interface", required_argument, NULL, 'i' },
432 #ifdef HAVE_PCAP_CREATE
433 { "monitor-mode", no_argument, NULL, 'I' },
434 #endif
435 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
436 { "time-stamp-type", required_argument, NULL, 'j' },
437 { "list-time-stamp-types", no_argument, NULL, 'J' },
438 #endif
439 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
440 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
441 #endif
442 { "dont-verify-checksums", no_argument, NULL, 'K' },
443 { "list-data-link-types", no_argument, NULL, 'L' },
444 { "no-optimize", no_argument, NULL, 'O' },
445 { "no-promiscuous-mode", no_argument, NULL, 'p' },
446 #ifdef HAVE_PCAP_SETDIRECTION
447 { "direction", required_argument, NULL, 'Q' },
448 #endif
449 { "snapshot-length", required_argument, NULL, 's' },
450 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
451 #ifdef HAVE_PCAP_DUMP_FLUSH
452 { "packet-buffered", no_argument, NULL, 'U' },
453 #endif
454 { "linktype", required_argument, NULL, 'y' },
455 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
456 { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
457 #endif
458 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
459 { "debug-filter-parser", no_argument, NULL, 'Y' },
460 #endif
461 { "relinquish-privileges", required_argument, NULL, 'Z' },
462 { "number", no_argument, NULL, '#' },
463 { "version", no_argument, NULL, OPTION_VERSION },
464 { NULL, 0, NULL, 0 }
465 };
466
467 #ifndef _WIN32
468 /* Drop root privileges and chroot if necessary */
469 static void
470 droproot(const char *username, const char *chroot_dir)
471 {
472 struct passwd *pw = NULL;
473
474 if (chroot_dir && !username) {
475 fprintf(stderr, "%s: Chroot without dropping root is insecure\n",
476 program_name);
477 exit(1);
478 }
479
480 pw = getpwnam(username);
481 if (pw) {
482 if (chroot_dir) {
483 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
484 fprintf(stderr, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
485 program_name, chroot_dir, pcap_strerror(errno));
486 exit(1);
487 }
488 }
489 #ifdef HAVE_LIBCAP_NG
490 {
491 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
492 if (ret < 0) {
493 fprintf(stderr, "error : ret %d\n", ret);
494 } else {
495 fprintf(stderr, "dropped privs to %s\n", username);
496 }
497 }
498 #else
499 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
500 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
501 fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
502 program_name, username,
503 (unsigned long)pw->pw_uid,
504 (unsigned long)pw->pw_gid,
505 pcap_strerror(errno));
506 exit(1);
507 }
508 else {
509 fprintf(stderr, "dropped privs to %s\n", username);
510 }
511 #endif /* HAVE_LIBCAP_NG */
512 }
513 else {
514 fprintf(stderr, "%s: Couldn't find user '%.32s'\n",
515 program_name, username);
516 exit(1);
517 }
518 #ifdef HAVE_LIBCAP_NG
519 /* We don't need CAP_SETUID and CAP_SETGID any more. */
520 capng_updatev(
521 CAPNG_DROP,
522 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
523 CAP_SETUID,
524 CAP_SETGID,
525 -1);
526 capng_apply(CAPNG_SELECT_BOTH);
527 #endif /* HAVE_LIBCAP_NG */
528
529 }
530 #endif /* _WIN32 */
531
532 static int
533 getWflagChars(int x)
534 {
535 int c = 0;
536
537 x -= 1;
538 while (x > 0) {
539 c += 1;
540 x /= 10;
541 }
542
543 return c;
544 }
545
546
547 static void
548 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
549 {
550 char *filename = malloc(PATH_MAX + 1);
551 if (filename == NULL)
552 error("Makefilename: malloc");
553
554 /* Process with strftime if Gflag is set. */
555 if (Gflag != 0) {
556 struct tm *local_tm;
557
558 /* Convert Gflag_time to a usable format */
559 if ((local_tm = localtime(&Gflag_time)) == NULL) {
560 error("MakeTimedFilename: localtime");
561 }
562
563 /* There's no good way to detect an error in strftime since a return
564 * value of 0 isn't necessarily failure.
565 */
566 strftime(filename, PATH_MAX, orig_name, local_tm);
567 } else {
568 strncpy(filename, orig_name, PATH_MAX);
569 }
570
571 if (cnt == 0 && max_chars == 0)
572 strncpy(buffer, filename, PATH_MAX + 1);
573 else
574 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
575 /* Report an error if the filename is too large */
576 error("too many output files or filename is too long (> %d)", PATH_MAX);
577 free(filename);
578 }
579
580 static char *
581 get_next_file(FILE *VFile, char *ptr)
582 {
583 char *ret;
584
585 ret = fgets(ptr, PATH_MAX, VFile);
586 if (!ret)
587 return NULL;
588
589 if (ptr[strlen(ptr) - 1] == '\n')
590 ptr[strlen(ptr) - 1] = '\0';
591
592 return ret;
593 }
594
595 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
596 static int
597 tstamp_precision_from_string(const char *precision)
598 {
599 if (strncmp(precision, "nano", strlen("nano")) == 0)
600 return PCAP_TSTAMP_PRECISION_NANO;
601
602 if (strncmp(precision, "micro", strlen("micro")) == 0)
603 return PCAP_TSTAMP_PRECISION_MICRO;
604
605 return -EINVAL;
606 }
607
608 static const char *
609 tstamp_precision_to_string(int precision)
610 {
611 switch (precision) {
612
613 case PCAP_TSTAMP_PRECISION_MICRO:
614 return "micro";
615
616 case PCAP_TSTAMP_PRECISION_NANO:
617 return "nano";
618
619 default:
620 return "unknown";
621 }
622 }
623 #endif
624
625 #ifdef HAVE_CAPSICUM
626 /*
627 * Ensure that, on a dump file's descriptor, we have all the rights
628 * necessary to make the standard I/O library work with an fdopen()ed
629 * FILE * from that descriptor.
630 *
631 * A long time ago, in a galaxy far far away, AT&T decided that, instead
632 * of providing separate APIs for getting and setting the FD_ flags on a
633 * descriptor, getting and setting the O_ flags on a descriptor, and
634 * locking files, they'd throw them all into a kitchen-sink fcntl() call
635 * along the lines of ioctl(), the fact that ioctl() operations are
636 * largely specific to particular character devices but fcntl() operations
637 * are either generic to all descriptors or generic to all descriptors for
638 * regular files nonwithstanding.
639 *
640 * The Capsicum people decided that fine-grained control of descriptor
641 * operations was required, so that you need to grant permission for
642 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
643 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
644 * collection of things, so there are *individual* fcntls for which
645 * permission needs to be granted.
646 *
647 * The FreeBSD standard I/O people implemented some optimizations that
648 * requires that the standard I/O routines be able to determine whether
649 * the descriptor for the FILE * is open append-only or not; as that
650 * descriptor could have come from an open() rather than an fopen(),
651 * that requires that it be able to do an F_GETFL fcntl() to read
652 * the O_ flags.
653 *
654 * Tcpdump uses ftell() to determine how much data has been written
655 * to a file in order to, when used with -C, determine when it's time
656 * to rotate capture files. ftell() therefore needs to do an lseek()
657 * to find out the file offset and must, thanks to the aforementioned
658 * optimization, also know whether the descriptor is open append-only
659 * or not.
660 *
661 * The net result of all the above is that we need to grant CAP_SEEK,
662 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
663 *
664 * Perhaps this is the universe's way of saying that either
665 *
666 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
667 * using it, so that Capsicum-capable tcpdump wouldn't need to do
668 * an fdopen()
669 *
670 * or
671 *
672 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
673 * I/O library that knows what rights are needed by the standard
674 * I/O library, based on the open mode, and assigns them, perhaps
675 * with an additional argument indicating, for example, whether
676 * seeking should be allowed, so that tcpdump doesn't need to know
677 * what the standard I/O library happens to require this week.
678 */
679 static void
680 set_dumper_capsicum_rights(pcap_dumper_t *p)
681 {
682 int fd = fileno(pcap_dump_file(p));
683 cap_rights_t rights;
684
685 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
686 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
687 error("unable to limit dump descriptor");
688 }
689 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
690 error("unable to limit dump descriptor fcntls");
691 }
692 }
693 #endif
694
695 int
696 main(int argc, char **argv)
697 {
698 register int cnt, op, i;
699 bpf_u_int32 localnet =0 , netmask = 0;
700 int timezone_offset = 0;
701 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
702 pcap_handler callback;
703 int dlt;
704 int new_dlt;
705 const char *dlt_name;
706 struct bpf_program fcode;
707 #ifndef _WIN32
708 RETSIGTYPE (*oldhandler)(int);
709 #endif
710 struct dump_info dumpinfo;
711 u_char *pcap_userdata;
712 char ebuf[PCAP_ERRBUF_SIZE];
713 char VFileLine[PATH_MAX + 1];
714 char *username = NULL;
715 char *chroot_dir = NULL;
716 char *ret = NULL;
717 char *end;
718 #ifdef HAVE_PCAP_FINDALLDEVS
719 pcap_if_t *p, *devpointer;
720 int devnum;
721 #endif
722 int status;
723 FILE *VFile;
724 #ifdef HAVE_CAPSICUM
725 cap_rights_t rights;
726 int cansandbox;
727 #endif /* HAVE_CAPSICUM */
728 int Bflag = 0; /* buffer size */
729 int jflag = -1; /* packet time stamp source */
730 int Oflag = 1; /* run filter code optimizer */
731 int pflag = 0; /* don't go promiscuous */
732 int yflag_dlt = -1;
733 const char *yflag_dlt_name = NULL;
734
735 netdissect_options Ndo;
736 netdissect_options *ndo = &Ndo;
737 int immediate_mode = 0;
738
739 memset(ndo, 0, sizeof(*ndo));
740 ndo_set_function_pointers(ndo);
741 ndo->ndo_snaplen = DEFAULT_SNAPLEN;
742
743 cnt = -1;
744 device = NULL;
745 infile = NULL;
746 RFileName = NULL;
747 VFileName = NULL;
748 VFile = NULL;
749 WFileName = NULL;
750 dlt = -1;
751 if ((cp = strrchr(argv[0], '/')) != NULL)
752 ndo->program_name = program_name = cp + 1;
753 else
754 ndo->program_name = program_name = argv[0];
755
756 #ifdef _WIN32
757 if (pcap_wsockinit() != 0)
758 error("Attempting to initialize Winsock failed");
759 #endif /* _WIN32 */
760
761 /*
762 * On platforms where the CPU doesn't support unaligned loads,
763 * force unaligned accesses to abort with SIGBUS, rather than
764 * being fixed up (slowly) by the OS kernel; on those platforms,
765 * misaligned accesses are bugs, and we want tcpdump to crash so
766 * that the bugs are reported.
767 */
768 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
769 error("%s", ebuf);
770
771 #ifdef USE_LIBSMI
772 smiInit("tcpdump");
773 #endif
774
775 while (
776 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
777 switch (op) {
778
779 case 'a':
780 /* compatibility for old -a */
781 break;
782
783 case 'A':
784 ++ndo->ndo_Aflag;
785 break;
786
787 case 'b':
788 ++ndo->ndo_bflag;
789 break;
790
791 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
792 case 'B':
793 Bflag = atoi(optarg)*1024;
794 if (Bflag <= 0)
795 error("invalid packet buffer size %s", optarg);
796 break;
797 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
798
799 case 'c':
800 cnt = atoi(optarg);
801 if (cnt <= 0)
802 error("invalid packet count %s", optarg);
803 break;
804
805 case 'C':
806 Cflag = atoi(optarg) * 1000000;
807 if (Cflag < 0)
808 error("invalid file size %s", optarg);
809 break;
810
811 case 'd':
812 ++dflag;
813 break;
814
815 case 'D':
816 Dflag++;
817 break;
818
819 case 'L':
820 Lflag++;
821 break;
822
823 case 'e':
824 ++ndo->ndo_eflag;
825 break;
826
827 case 'E':
828 #ifndef HAVE_LIBCRYPTO
829 warning("crypto code not compiled in");
830 #endif
831 ndo->ndo_espsecret = optarg;
832 break;
833
834 case 'f':
835 ++ndo->ndo_fflag;
836 break;
837
838 case 'F':
839 infile = optarg;
840 break;
841
842 case 'G':
843 Gflag = atoi(optarg);
844 if (Gflag < 0)
845 error("invalid number of seconds %s", optarg);
846
847 /* We will create one file initially. */
848 Gflag_count = 0;
849
850 /* Grab the current time for rotation use. */
851 if ((Gflag_time = time(NULL)) == (time_t)-1) {
852 error("main: can't get current time: %s",
853 pcap_strerror(errno));
854 }
855 break;
856
857 case 'h':
858 print_usage();
859 exit(0);
860 break;
861
862 case 'H':
863 ++ndo->ndo_Hflag;
864 break;
865
866 case 'i':
867 if (optarg[0] == '0' && optarg[1] == 0)
868 error("Invalid adapter index");
869
870 #ifdef HAVE_PCAP_FINDALLDEVS
871 /*
872 * If the argument is a number, treat it as
873 * an index into the list of adapters, as
874 * printed by "tcpdump -D".
875 *
876 * This should be OK on UNIX systems, as interfaces
877 * shouldn't have names that begin with digits.
878 * It can be useful on Windows, where more than
879 * one interface can have the same name.
880 */
881 devnum = strtol(optarg, &end, 10);
882 if (optarg != end && *end == '\0') {
883 if (devnum < 0)
884 error("Invalid adapter index");
885
886 if (pcap_findalldevs(&devpointer, ebuf) < 0)
887 error("%s", ebuf);
888 /*
889 * Look for the devnum-th entry in the
890 * list of devices (1-based).
891 */
892 for (i = 0, p = devpointer;
893 i < devnum-1 && p != NULL;
894 i++, p = p->next)
895 ;
896 if (p == NULL)
897 error("Invalid adapter index");
898 device = strdup(p->name);
899 pcap_freealldevs(devpointer);
900 break;
901 }
902 #endif /* HAVE_PCAP_FINDALLDEVS */
903 device = optarg;
904 break;
905
906 #ifdef HAVE_PCAP_CREATE
907 case 'I':
908 ++Iflag;
909 break;
910 #endif /* HAVE_PCAP_CREATE */
911
912 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
913 case 'j':
914 jflag = pcap_tstamp_type_name_to_val(optarg);
915 if (jflag < 0)
916 error("invalid time stamp type %s", optarg);
917 break;
918
919 case 'J':
920 Jflag++;
921 break;
922 #endif
923
924 case 'l':
925 #ifdef _WIN32
926 /*
927 * _IOLBF is the same as _IOFBF in Microsoft's C
928 * libraries; the only alternative they offer
929 * is _IONBF.
930 *
931 * XXX - this should really be checking for MSVC++,
932 * not _WIN32, if, for example, MinGW has its own
933 * C library that is more UNIX-compatible.
934 */
935 setvbuf(stdout, NULL, _IONBF, 0);
936 #else /* _WIN32 */
937 #ifdef HAVE_SETLINEBUF
938 setlinebuf(stdout);
939 #else
940 setvbuf(stdout, NULL, _IOLBF, 0);
941 #endif
942 #endif /* _WIN32 */
943 break;
944
945 case 'K':
946 ++ndo->ndo_Kflag;
947 break;
948
949 case 'm':
950 #ifdef USE_LIBSMI
951 if (smiLoadModule(optarg) == 0) {
952 error("could not load MIB module %s", optarg);
953 }
954 ndo->ndo_mflag = 1;
955 #else
956 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
957 program_name, optarg);
958 (void)fprintf(stderr, "(no libsmi support)\n");
959 #endif
960 break;
961
962 case 'M':
963 /* TCP-MD5 shared secret */
964 #ifndef HAVE_LIBCRYPTO
965 warning("crypto code not compiled in");
966 #endif
967 ndo->ndo_sigsecret = optarg;
968 break;
969
970 case 'n':
971 ++ndo->ndo_nflag;
972 break;
973
974 case 'N':
975 ++ndo->ndo_Nflag;
976 break;
977
978 case 'O':
979 Oflag = 0;
980 break;
981
982 case 'p':
983 ++pflag;
984 break;
985
986 case 'q':
987 ++ndo->ndo_qflag;
988 ++ndo->ndo_suppress_default_print;
989 break;
990
991 #ifdef HAVE_PCAP_SETDIRECTION
992 case 'Q':
993 if (ascii_strcasecmp(optarg, "in") == 0)
994 Qflag = PCAP_D_IN;
995 else if (ascii_strcasecmp(optarg, "out") == 0)
996 Qflag = PCAP_D_OUT;
997 else if (ascii_strcasecmp(optarg, "inout") == 0)
998 Qflag = PCAP_D_INOUT;
999 else
1000 error("unknown capture direction `%s'", optarg);
1001 break;
1002 #endif /* HAVE_PCAP_SETDIRECTION */
1003
1004 case 'r':
1005 RFileName = optarg;
1006 break;
1007
1008 case 's':
1009 ndo->ndo_snaplen = strtol(optarg, &end, 0);
1010 if (optarg == end || *end != '\0'
1011 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1012 error("invalid snaplen %s", optarg);
1013 else if (ndo->ndo_snaplen == 0)
1014 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1015 break;
1016
1017 case 'S':
1018 ++ndo->ndo_Sflag;
1019 break;
1020
1021 case 't':
1022 ++ndo->ndo_tflag;
1023 break;
1024
1025 case 'T':
1026 if (ascii_strcasecmp(optarg, "vat") == 0)
1027 ndo->ndo_packettype = PT_VAT;
1028 else if (ascii_strcasecmp(optarg, "wb") == 0)
1029 ndo->ndo_packettype = PT_WB;
1030 else if (ascii_strcasecmp(optarg, "rpc") == 0)
1031 ndo->ndo_packettype = PT_RPC;
1032 else if (ascii_strcasecmp(optarg, "rtp") == 0)
1033 ndo->ndo_packettype = PT_RTP;
1034 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1035 ndo->ndo_packettype = PT_RTCP;
1036 else if (ascii_strcasecmp(optarg, "snmp") == 0)
1037 ndo->ndo_packettype = PT_SNMP;
1038 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1039 ndo->ndo_packettype = PT_CNFP;
1040 else if (ascii_strcasecmp(optarg, "tftp") == 0)
1041 ndo->ndo_packettype = PT_TFTP;
1042 else if (ascii_strcasecmp(optarg, "aodv") == 0)
1043 ndo->ndo_packettype = PT_AODV;
1044 else if (ascii_strcasecmp(optarg, "carp") == 0)
1045 ndo->ndo_packettype = PT_CARP;
1046 else if (ascii_strcasecmp(optarg, "radius") == 0)
1047 ndo->ndo_packettype = PT_RADIUS;
1048 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1049 ndo->ndo_packettype = PT_ZMTP1;
1050 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1051 ndo->ndo_packettype = PT_VXLAN;
1052 else if (ascii_strcasecmp(optarg, "pgm") == 0)
1053 ndo->ndo_packettype = PT_PGM;
1054 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1055 ndo->ndo_packettype = PT_PGM_ZMTP1;
1056 else if (ascii_strcasecmp(optarg, "lmp") == 0)
1057 ndo->ndo_packettype = PT_LMP;
1058 else
1059 error("unknown packet type `%s'", optarg);
1060 break;
1061
1062 case 'u':
1063 ++ndo->ndo_uflag;
1064 break;
1065
1066 #ifdef HAVE_PCAP_DUMP_FLUSH
1067 case 'U':
1068 ++Uflag;
1069 break;
1070 #endif
1071
1072 case 'v':
1073 ++ndo->ndo_vflag;
1074 break;
1075
1076 case 'V':
1077 VFileName = optarg;
1078 break;
1079
1080 case 'w':
1081 WFileName = optarg;
1082 break;
1083
1084 case 'W':
1085 Wflag = atoi(optarg);
1086 if (Wflag < 0)
1087 error("invalid number of output files %s", optarg);
1088 WflagChars = getWflagChars(Wflag);
1089 break;
1090
1091 case 'x':
1092 ++ndo->ndo_xflag;
1093 ++ndo->ndo_suppress_default_print;
1094 break;
1095
1096 case 'X':
1097 ++ndo->ndo_Xflag;
1098 ++ndo->ndo_suppress_default_print;
1099 break;
1100
1101 case 'y':
1102 yflag_dlt_name = optarg;
1103 yflag_dlt =
1104 pcap_datalink_name_to_val(yflag_dlt_name);
1105 if (yflag_dlt < 0)
1106 error("invalid data link type %s", yflag_dlt_name);
1107 break;
1108
1109 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1110 case 'Y':
1111 {
1112 /* Undocumented flag */
1113 #ifdef HAVE_PCAP_DEBUG
1114 extern int pcap_debug;
1115 pcap_debug = 1;
1116 #else
1117 extern int yydebug;
1118 yydebug = 1;
1119 #endif
1120 }
1121 break;
1122 #endif
1123 case 'z':
1124 zflag = strdup(optarg);
1125 if (zflag == NULL)
1126 error("Unable to allocate memory for -z argument");
1127 break;
1128
1129 case 'Z':
1130 username = strdup(optarg);
1131 if (username == NULL)
1132 error("Unable to allocate memory for -Z argument");
1133 break;
1134
1135 case '#':
1136 ndo->ndo_packet_number = 1;
1137 break;
1138
1139 case OPTION_VERSION:
1140 print_version();
1141 exit(0);
1142 break;
1143
1144 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1145 case OPTION_TSTAMP_PRECISION:
1146 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1147 if (ndo->ndo_tstamp_precision < 0)
1148 error("unsupported time stamp precision");
1149 break;
1150 #endif
1151
1152 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1153 case OPTION_IMMEDIATE_MODE:
1154 immediate_mode = 1;
1155 break;
1156 #endif
1157
1158 default:
1159 print_usage();
1160 exit(1);
1161 /* NOTREACHED */
1162 }
1163
1164 #ifdef HAVE_PCAP_FINDALLDEVS
1165 if (Dflag)
1166 show_devices_and_exit();
1167 #endif
1168
1169 switch (ndo->ndo_tflag) {
1170
1171 case 0: /* Default */
1172 case 4: /* Default + Date*/
1173 timezone_offset = gmt2local(0);
1174 break;
1175
1176 case 1: /* No time stamp */
1177 case 2: /* Unix timeval style */
1178 case 3: /* Microseconds since previous packet */
1179 case 5: /* Microseconds since first packet */
1180 break;
1181
1182 default: /* Not supported */
1183 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1184 break;
1185 }
1186
1187 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1188 error("-f can not be used with -V or -r");
1189
1190 if (VFileName != NULL && RFileName != NULL)
1191 error("-V and -r are mutually exclusive.");
1192
1193 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1194 /*
1195 * If we're printing dissected packets to the standard output
1196 * rather than saving raw packets to a file, and the standard
1197 * output is a terminal, use immediate mode, as the user's
1198 * probably expecting to see packets pop up immediately.
1199 */
1200 if (WFileName == NULL && isatty(1))
1201 immediate_mode = 1;
1202 #endif
1203
1204 #ifdef WITH_CHROOT
1205 /* if run as root, prepare for chrooting */
1206 if (getuid() == 0 || geteuid() == 0) {
1207 /* future extensibility for cmd-line arguments */
1208 if (!chroot_dir)
1209 chroot_dir = WITH_CHROOT;
1210 }
1211 #endif
1212
1213 #ifdef WITH_USER
1214 /* if run as root, prepare for dropping root privileges */
1215 if (getuid() == 0 || geteuid() == 0) {
1216 /* Run with '-Z root' to restore old behaviour */
1217 if (!username)
1218 username = WITH_USER;
1219 }
1220 #endif
1221
1222 if (RFileName != NULL || VFileName != NULL) {
1223 /*
1224 * If RFileName is non-null, it's the pathname of a
1225 * savefile to read. If VFileName is non-null, it's
1226 * the pathname of a file containing a list of pathnames
1227 * (one per line) of savefiles to read.
1228 *
1229 * In either case, we're reading a savefile, not doing
1230 * a live capture.
1231 */
1232 #ifndef _WIN32
1233 /*
1234 * We don't need network access, so relinquish any set-UID
1235 * or set-GID privileges we have (if any).
1236 *
1237 * We do *not* want set-UID privileges when opening a
1238 * trace file, as that might let the user read other
1239 * people's trace files (especially if we're set-UID
1240 * root).
1241 */
1242 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1243 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1244 #endif /* _WIN32 */
1245 if (VFileName != NULL) {
1246 if (VFileName[0] == '-' && VFileName[1] == '\0')
1247 VFile = stdin;
1248 else
1249 VFile = fopen(VFileName, "r");
1250
1251 if (VFile == NULL)
1252 error("Unable to open file: %s\n", strerror(errno));
1253
1254 ret = get_next_file(VFile, VFileLine);
1255 if (!ret)
1256 error("Nothing in %s\n", VFileName);
1257 RFileName = VFileLine;
1258 }
1259
1260 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1261 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1262 ndo->ndo_tstamp_precision, ebuf);
1263 #else
1264 pd = pcap_open_offline(RFileName, ebuf);
1265 #endif
1266
1267 if (pd == NULL)
1268 error("%s", ebuf);
1269 #ifdef HAVE_CAPSICUM
1270 cap_rights_init(&rights, CAP_READ);
1271 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1272 errno != ENOSYS) {
1273 error("unable to limit pcap descriptor");
1274 }
1275 #endif
1276 dlt = pcap_datalink(pd);
1277 dlt_name = pcap_datalink_val_to_name(dlt);
1278 if (dlt_name == NULL) {
1279 fprintf(stderr, "reading from file %s, link-type %u\n",
1280 RFileName, dlt);
1281 } else {
1282 fprintf(stderr,
1283 "reading from file %s, link-type %s (%s)\n",
1284 RFileName, dlt_name,
1285 pcap_datalink_val_to_description(dlt));
1286 }
1287 } else {
1288 /*
1289 * We're doing a live capture.
1290 */
1291 if (device == NULL) {
1292 #ifdef HAVE_PCAP_FINDALLDEVS
1293 if (pcap_findalldevs(&devpointer, ebuf) >= 0 &&
1294 devpointer != NULL) {
1295 device = strdup(devpointer->name);
1296 pcap_freealldevs(devpointer);
1297 }
1298 #else /* HAVE_PCAP_FINDALLDEVS */
1299 device = pcap_lookupdev(ebuf);
1300 #endif
1301 if (device == NULL)
1302 error("%s", ebuf);
1303 }
1304 #ifdef _WIN32
1305 /*
1306 * Print a message to the standard error on Windows.
1307 * XXX - why do it here, with a different message?
1308 */
1309 if(strlen(device) == 1) /* we assume that an ASCII string is always longer than 1 char */
1310 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1311 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1312 }
1313 else
1314 {
1315 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1316 }
1317
1318 fflush(stderr);
1319 #endif /* _WIN32 */
1320 #ifdef HAVE_PCAP_CREATE
1321 pd = pcap_create(device, ebuf);
1322 if (pd == NULL)
1323 error("%s", ebuf);
1324 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1325 if (Jflag)
1326 show_tstamp_types_and_exit(device);
1327 #endif
1328 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1329 status = pcap_set_tstamp_precision(pd, ndo->ndo_tstamp_precision);
1330 if (status != 0)
1331 error("%s: Can't set %ssecond time stamp precision: %s",
1332 device,
1333 tstamp_precision_to_string(ndo->ndo_tstamp_precision),
1334 pcap_statustostr(status));
1335 #endif
1336
1337 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1338 if (immediate_mode) {
1339 status = pcap_set_immediate_mode(pd, 1);
1340 if (status != 0)
1341 error("%s: Can't set immediate mode: %s",
1342 device,
1343 pcap_statustostr(status));
1344 }
1345 #endif
1346 /*
1347 * Is this an interface that supports monitor mode?
1348 */
1349 if (pcap_can_set_rfmon(pd) == 1)
1350 supports_monitor_mode = 1;
1351 else
1352 supports_monitor_mode = 0;
1353 status = pcap_set_snaplen(pd, ndo->ndo_snaplen);
1354 if (status != 0)
1355 error("%s: Can't set snapshot length: %s",
1356 device, pcap_statustostr(status));
1357 status = pcap_set_promisc(pd, !pflag);
1358 if (status != 0)
1359 error("%s: Can't set promiscuous mode: %s",
1360 device, pcap_statustostr(status));
1361 if (Iflag) {
1362 status = pcap_set_rfmon(pd, 1);
1363 if (status != 0)
1364 error("%s: Can't set monitor mode: %s",
1365 device, pcap_statustostr(status));
1366 }
1367 status = pcap_set_timeout(pd, 1000);
1368 if (status != 0)
1369 error("%s: pcap_set_timeout failed: %s",
1370 device, pcap_statustostr(status));
1371 if (Bflag != 0) {
1372 status = pcap_set_buffer_size(pd, Bflag);
1373 if (status != 0)
1374 error("%s: Can't set buffer size: %s",
1375 device, pcap_statustostr(status));
1376 }
1377 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1378 if (jflag != -1) {
1379 status = pcap_set_tstamp_type(pd, jflag);
1380 if (status < 0)
1381 error("%s: Can't set time stamp type: %s",
1382 device, pcap_statustostr(status));
1383 }
1384 #endif
1385 status = pcap_activate(pd);
1386 if (status < 0) {
1387 /*
1388 * pcap_activate() failed.
1389 */
1390 cp = pcap_geterr(pd);
1391 if (status == PCAP_ERROR)
1392 error("%s", cp);
1393 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1394 status == PCAP_ERROR_PERM_DENIED) &&
1395 *cp != '\0')
1396 error("%s: %s\n(%s)", device,
1397 pcap_statustostr(status), cp);
1398 else
1399 error("%s: %s", device,
1400 pcap_statustostr(status));
1401 } else if (status > 0) {
1402 /*
1403 * pcap_activate() succeeded, but it's warning us
1404 * of a problem it had.
1405 */
1406 cp = pcap_geterr(pd);
1407 if (status == PCAP_WARNING)
1408 warning("%s", cp);
1409 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1410 *cp != '\0')
1411 warning("%s: %s\n(%s)", device,
1412 pcap_statustostr(status), cp);
1413 else
1414 warning("%s: %s", device,
1415 pcap_statustostr(status));
1416 }
1417 #ifdef HAVE_PCAP_SETDIRECTION
1418 if (Qflag != -1) {
1419 status = pcap_setdirection(pd, Qflag);
1420 if (status != 0)
1421 error("%s: pcap_setdirection() failed: %s",
1422 device, pcap_geterr(pd));
1423 }
1424 #endif /* HAVE_PCAP_SETDIRECTION */
1425 #else
1426 *ebuf = '\0';
1427 pd = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000,
1428 ebuf);
1429 if (pd == NULL)
1430 error("%s", ebuf);
1431 else if (*ebuf)
1432 warning("%s", ebuf);
1433 #endif /* HAVE_PCAP_CREATE */
1434 /*
1435 * Let user own process after socket has been opened.
1436 */
1437 #ifndef _WIN32
1438 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1439 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1440 #endif /* _WIN32 */
1441 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1442 if(Bflag != 0)
1443 if(pcap_setbuff(pd, Bflag)==-1){
1444 error("%s", pcap_geterr(pd));
1445 }
1446 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1447 if (Lflag)
1448 show_dlts_and_exit(device);
1449 if (yflag_dlt >= 0) {
1450 #ifdef HAVE_PCAP_SET_DATALINK
1451 if (pcap_set_datalink(pd, yflag_dlt) < 0)
1452 error("%s", pcap_geterr(pd));
1453 #else
1454 /*
1455 * We don't actually support changing the
1456 * data link type, so we only let them
1457 * set it to what it already is.
1458 */
1459 if (yflag_dlt != pcap_datalink(pd)) {
1460 error("%s is not one of the DLTs supported by this device\n",
1461 yflag_dlt_name);
1462 }
1463 #endif
1464 (void)fprintf(stderr, "%s: data link type %s\n",
1465 program_name, yflag_dlt_name);
1466 (void)fflush(stderr);
1467 }
1468 i = pcap_snapshot(pd);
1469 if (ndo->ndo_snaplen < i) {
1470 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
1471 ndo->ndo_snaplen = i;
1472 }
1473 if(ndo->ndo_fflag != 0) {
1474 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1475 warning("foreign (-f) flag used but: %s", ebuf);
1476 }
1477 }
1478
1479 }
1480 if (infile)
1481 cmdbuf = read_infile(infile);
1482 else
1483 cmdbuf = copy_argv(&argv[optind]);
1484
1485 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1486 error("%s", pcap_geterr(pd));
1487 if (dflag) {
1488 bpf_dump(&fcode, dflag);
1489 pcap_close(pd);
1490 free(cmdbuf);
1491 exit(0);
1492 }
1493 init_print(ndo, localnet, netmask, timezone_offset);
1494
1495 #ifndef _WIN32
1496 (void)setsignal(SIGPIPE, cleanup);
1497 (void)setsignal(SIGTERM, cleanup);
1498 (void)setsignal(SIGINT, cleanup);
1499 #endif /* _WIN32 */
1500 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1501 (void)setsignal(SIGCHLD, child_cleanup);
1502 #endif
1503 /* Cooperate with nohup(1) */
1504 #ifndef _WIN32
1505 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1506 (void)setsignal(SIGHUP, oldhandler);
1507 #endif /* _WIN32 */
1508
1509 #ifndef _WIN32
1510 /*
1511 * If a user name was specified with "-Z", attempt to switch to
1512 * that user's UID. This would probably be used with sudo,
1513 * to allow tcpdump to be run in a special restricted
1514 * account (if you just want to allow users to open capture
1515 * devices, and can't just give users that permission,
1516 * you'd make tcpdump set-UID or set-GID).
1517 *
1518 * Tcpdump doesn't necessarily write only to one savefile;
1519 * the general only way to allow a -Z instance to write to
1520 * savefiles as the user under whose UID it's run, rather
1521 * than as the user specified with -Z, would thus be to switch
1522 * to the original user ID before opening a capture file and
1523 * then switch back to the -Z user ID after opening the savefile.
1524 * Switching to the -Z user ID only after opening the first
1525 * savefile doesn't handle the general case.
1526 */
1527
1528 if (getuid() == 0 || geteuid() == 0) {
1529 #ifdef HAVE_LIBCAP_NG
1530 /* Initialize capng */
1531 capng_clear(CAPNG_SELECT_BOTH);
1532 if (username) {
1533 capng_updatev(
1534 CAPNG_ADD,
1535 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1536 CAP_SETUID,
1537 CAP_SETGID,
1538 -1);
1539 }
1540
1541 if (WFileName) {
1542 capng_update(
1543 CAPNG_ADD,
1544 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1545 CAP_DAC_OVERRIDE
1546 );
1547 }
1548 capng_apply(CAPNG_SELECT_BOTH);
1549 #endif /* HAVE_LIBCAP_NG */
1550 if (username || chroot_dir)
1551 droproot(username, chroot_dir);
1552
1553 }
1554 #endif /* _WIN32 */
1555
1556 if (pcap_setfilter(pd, &fcode) < 0)
1557 error("%s", pcap_geterr(pd));
1558 #ifdef HAVE_CAPSICUM
1559 if (RFileName == NULL && VFileName == NULL) {
1560 static const unsigned long cmds[] = { BIOCGSTATS };
1561
1562 cap_rights_init(&rights, CAP_IOCTL, CAP_READ);
1563 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1564 errno != ENOSYS) {
1565 error("unable to limit pcap descriptor");
1566 }
1567 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1568 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1569 error("unable to limit ioctls on pcap descriptor");
1570 }
1571 }
1572 #endif
1573 if (WFileName) {
1574 pcap_dumper_t *p;
1575 /* Do not exceed the default PATH_MAX for files. */
1576 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1577
1578 if (dumpinfo.CurrentFileName == NULL)
1579 error("malloc of dumpinfo.CurrentFileName");
1580
1581 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1582 if (Cflag != 0)
1583 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1584 else
1585 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1586
1587 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1588 #ifdef HAVE_LIBCAP_NG
1589 /* Give up CAP_DAC_OVERRIDE capability.
1590 * Only allow it to be restored if the -C or -G flag have been
1591 * set since we may need to create more files later on.
1592 */
1593 capng_update(
1594 CAPNG_DROP,
1595 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1596 | CAPNG_EFFECTIVE,
1597 CAP_DAC_OVERRIDE
1598 );
1599 capng_apply(CAPNG_SELECT_BOTH);
1600 #endif /* HAVE_LIBCAP_NG */
1601 if (p == NULL)
1602 error("%s", pcap_geterr(pd));
1603 #ifdef HAVE_CAPSICUM
1604 set_dumper_capsicum_rights(p);
1605 #endif
1606 if (Cflag != 0 || Gflag != 0) {
1607 #ifdef HAVE_CAPSICUM
1608 dumpinfo.WFileName = strdup(basename(WFileName));
1609 if (dumpinfo.WFileName == NULL) {
1610 error("Unable to allocate memory for file %s",
1611 WFileName);
1612 }
1613 dumpinfo.dirfd = open(dirname(WFileName),
1614 O_DIRECTORY | O_RDONLY);
1615 if (dumpinfo.dirfd < 0) {
1616 error("unable to open directory %s",
1617 dirname(WFileName));
1618 }
1619 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1620 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1621 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1622 errno != ENOSYS) {
1623 error("unable to limit directory rights");
1624 }
1625 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1626 errno != ENOSYS) {
1627 error("unable to limit dump descriptor fcntls");
1628 }
1629 #else /* !HAVE_CAPSICUM */
1630 dumpinfo.WFileName = WFileName;
1631 #endif
1632 callback = dump_packet_and_trunc;
1633 dumpinfo.pd = pd;
1634 dumpinfo.p = p;
1635 pcap_userdata = (u_char *)&dumpinfo;
1636 } else {
1637 callback = dump_packet;
1638 pcap_userdata = (u_char *)p;
1639 }
1640 #ifdef HAVE_PCAP_DUMP_FLUSH
1641 if (Uflag)
1642 pcap_dump_flush(p);
1643 #endif
1644 } else {
1645 dlt = pcap_datalink(pd);
1646 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1647 callback = print_packet;
1648 pcap_userdata = (u_char *)ndo;
1649 }
1650
1651 #ifdef SIGNAL_REQ_INFO
1652 /*
1653 * We can't get statistics when reading from a file rather
1654 * than capturing from a device.
1655 */
1656 if (RFileName == NULL)
1657 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1658 #endif
1659
1660 if (ndo->ndo_vflag > 0 && WFileName) {
1661 /*
1662 * When capturing to a file, "-v" means tcpdump should,
1663 * every 10 seconds, "v"erbosely report the number of
1664 * packets captured.
1665 */
1666 #ifdef USE_WIN32_MM_TIMER
1667 /* call verbose_stats_dump() each 1000 +/-100msec */
1668 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1669 setvbuf(stderr, NULL, _IONBF, 0);
1670 #elif defined(HAVE_ALARM)
1671 (void)setsignal(SIGALRM, verbose_stats_dump);
1672 alarm(1);
1673 #endif
1674 }
1675
1676 #ifndef _WIN32
1677 if (RFileName == NULL) {
1678 /*
1679 * Live capture (if -V was specified, we set RFileName
1680 * to a file from the -V file). Print a message to
1681 * the standard error on UN*X.
1682 */
1683 if (!ndo->ndo_vflag && !WFileName) {
1684 (void)fprintf(stderr,
1685 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1686 program_name);
1687 } else
1688 (void)fprintf(stderr, "%s: ", program_name);
1689 dlt = pcap_datalink(pd);
1690 dlt_name = pcap_datalink_val_to_name(dlt);
1691 if (dlt_name == NULL) {
1692 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1693 device, dlt, ndo->ndo_snaplen);
1694 } else {
1695 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1696 device, dlt_name,
1697 pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
1698 }
1699 (void)fflush(stderr);
1700 }
1701 #endif /* _WIN32 */
1702
1703 #ifdef HAVE_CAPSICUM
1704 cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL);
1705 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1706 error("unable to enter the capability mode");
1707 #endif /* HAVE_CAPSICUM */
1708
1709 do {
1710 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1711 if (WFileName == NULL) {
1712 /*
1713 * We're printing packets. Flush the printed output,
1714 * so it doesn't get intermingled with error output.
1715 */
1716 if (status == -2) {
1717 /*
1718 * We got interrupted, so perhaps we didn't
1719 * manage to finish a line we were printing.
1720 * Print an extra newline, just in case.
1721 */
1722 putchar('\n');
1723 }
1724 (void)fflush(stdout);
1725 }
1726 if (status == -2) {
1727 /*
1728 * We got interrupted. If we are reading multiple
1729 * files (via -V) set these so that we stop.
1730 */
1731 VFileName = NULL;
1732 ret = NULL;
1733 }
1734 if (status == -1) {
1735 /*
1736 * Error. Report it.
1737 */
1738 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1739 program_name, pcap_geterr(pd));
1740 }
1741 if (RFileName == NULL) {
1742 /*
1743 * We're doing a live capture. Report the capture
1744 * statistics.
1745 */
1746 info(1);
1747 }
1748 pcap_close(pd);
1749 if (VFileName != NULL) {
1750 ret = get_next_file(VFile, VFileLine);
1751 if (ret) {
1752 RFileName = VFileLine;
1753 pd = pcap_open_offline(RFileName, ebuf);
1754 if (pd == NULL)
1755 error("%s", ebuf);
1756 #ifdef HAVE_CAPSICUM
1757 cap_rights_init(&rights, CAP_READ);
1758 if (cap_rights_limit(fileno(pcap_file(pd)),
1759 &rights) < 0 && errno != ENOSYS) {
1760 error("unable to limit pcap descriptor");
1761 }
1762 #endif
1763 new_dlt = pcap_datalink(pd);
1764 if (WFileName && new_dlt != dlt)
1765 error("%s: new dlt does not match original", RFileName);
1766 ndo->ndo_if_printer = get_if_printer(ndo, new_dlt);
1767 dlt_name = pcap_datalink_val_to_name(new_dlt);
1768 if (dlt_name == NULL) {
1769 fprintf(stderr, "reading from file %s, link-type %u\n",
1770 RFileName, new_dlt);
1771 } else {
1772 fprintf(stderr,
1773 "reading from file %s, link-type %s (%s)\n",
1774 RFileName, dlt_name,
1775 pcap_datalink_val_to_description(new_dlt));
1776 }
1777 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1778 error("%s", pcap_geterr(pd));
1779 if (pcap_setfilter(pd, &fcode) < 0)
1780 error("%s", pcap_geterr(pd));
1781 }
1782 }
1783 }
1784 while (ret != NULL);
1785
1786 free(cmdbuf);
1787 exit(status == -1 ? 1 : 0);
1788 }
1789
1790 /* make a clean exit on interrupts */
1791 static RETSIGTYPE
1792 cleanup(int signo _U_)
1793 {
1794 #ifdef USE_WIN32_MM_TIMER
1795 if (timer_id)
1796 timeKillEvent(timer_id);
1797 timer_id = 0;
1798 #elif defined(HAVE_ALARM)
1799 alarm(0);
1800 #endif
1801
1802 #ifdef HAVE_PCAP_BREAKLOOP
1803 /*
1804 * We have "pcap_breakloop()"; use it, so that we do as little
1805 * as possible in the signal handler (it's probably not safe
1806 * to do anything with standard I/O streams in a signal handler -
1807 * the ANSI C standard doesn't say it is).
1808 */
1809 pcap_breakloop(pd);
1810 #else
1811 /*
1812 * We don't have "pcap_breakloop()"; this isn't safe, but
1813 * it's the best we can do. Print the summary if we're
1814 * not reading from a savefile - i.e., if we're doing a
1815 * live capture - and exit.
1816 */
1817 if (pd != NULL && pcap_file(pd) == NULL) {
1818 /*
1819 * We got interrupted, so perhaps we didn't
1820 * manage to finish a line we were printing.
1821 * Print an extra newline, just in case.
1822 */
1823 putchar('\n');
1824 (void)fflush(stdout);
1825 info(1);
1826 }
1827 exit(0);
1828 #endif
1829 }
1830
1831 /*
1832 On windows, we do not use a fork, so we do not care less about
1833 waiting a child processes to die
1834 */
1835 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1836 static RETSIGTYPE
1837 child_cleanup(int signo _U_)
1838 {
1839 wait(NULL);
1840 }
1841 #endif /* HAVE_FORK && HAVE_VFORK */
1842
1843 static void
1844 info(register int verbose)
1845 {
1846 struct pcap_stat stats;
1847
1848 /*
1849 * Older versions of libpcap didn't set ps_ifdrop on some
1850 * platforms; initialize it to 0 to handle that.
1851 */
1852 stats.ps_ifdrop = 0;
1853 if (pcap_stats(pd, &stats) < 0) {
1854 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1855 infoprint = 0;
1856 return;
1857 }
1858
1859 if (!verbose)
1860 fprintf(stderr, "%s: ", program_name);
1861
1862 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1863 PLURAL_SUFFIX(packets_captured));
1864 if (!verbose)
1865 fputs(", ", stderr);
1866 else
1867 putc('\n', stderr);
1868 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
1869 PLURAL_SUFFIX(stats.ps_recv));
1870 if (!verbose)
1871 fputs(", ", stderr);
1872 else
1873 putc('\n', stderr);
1874 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
1875 PLURAL_SUFFIX(stats.ps_drop));
1876 if (stats.ps_ifdrop != 0) {
1877 if (!verbose)
1878 fputs(", ", stderr);
1879 else
1880 putc('\n', stderr);
1881 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1882 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
1883 } else
1884 putc('\n', stderr);
1885 infoprint = 0;
1886 }
1887
1888 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1889 static void
1890 compress_savefile(const char *filename)
1891 {
1892 # ifdef HAVE_FORK
1893 if (fork())
1894 # else
1895 if (vfork())
1896 # endif
1897 return;
1898 /*
1899 * Set to lowest priority so that this doesn't disturb the capture
1900 */
1901 #ifdef NZERO
1902 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1903 #else
1904 setpriority(PRIO_PROCESS, 0, 19);
1905 #endif
1906 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1907 fprintf(stderr,
1908 "compress_savefile:execlp(%s, %s): %s\n",
1909 zflag,
1910 filename,
1911 strerror(errno));
1912 # ifdef HAVE_FORK
1913 exit(1);
1914 # else
1915 _exit(1);
1916 # endif
1917 }
1918 #else /* HAVE_FORK && HAVE_VFORK */
1919 static void
1920 compress_savefile(const char *filename)
1921 {
1922 fprintf(stderr,
1923 "compress_savefile failed. Functionality not implemented under your system\n");
1924 }
1925 #endif /* HAVE_FORK && HAVE_VFORK */
1926
1927 static void
1928 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1929 {
1930 struct dump_info *dump_info;
1931
1932 ++packets_captured;
1933
1934 ++infodelay;
1935
1936 dump_info = (struct dump_info *)user;
1937
1938 /*
1939 * XXX - this won't force the file to rotate on the specified time
1940 * boundary, but it will rotate on the first packet received after the
1941 * specified Gflag number of seconds. Note: if a Gflag time boundary
1942 * and a Cflag size boundary coincide, the time rotation will occur
1943 * first thereby cancelling the Cflag boundary (since the file should
1944 * be 0).
1945 */
1946 if (Gflag != 0) {
1947 /* Check if it is time to rotate */
1948 time_t t;
1949
1950 /* Get the current time */
1951 if ((t = time(NULL)) == (time_t)-1) {
1952 error("dump_and_trunc_packet: can't get current_time: %s",
1953 pcap_strerror(errno));
1954 }
1955
1956
1957 /* If the time is greater than the specified window, rotate */
1958 if (t - Gflag_time >= Gflag) {
1959 #ifdef HAVE_CAPSICUM
1960 FILE *fp;
1961 int fd;
1962 #endif
1963
1964 /* Update the Gflag_time */
1965 Gflag_time = t;
1966 /* Update Gflag_count */
1967 Gflag_count++;
1968 /*
1969 * Close the current file and open a new one.
1970 */
1971 pcap_dump_close(dump_info->p);
1972
1973 /*
1974 * Compress the file we just closed, if the user asked for it
1975 */
1976 if (zflag != NULL)
1977 compress_savefile(dump_info->CurrentFileName);
1978
1979 /*
1980 * Check to see if we've exceeded the Wflag (when
1981 * not using Cflag).
1982 */
1983 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1984 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1985 Wflag);
1986 exit(0);
1987 /* NOTREACHED */
1988 }
1989 if (dump_info->CurrentFileName != NULL)
1990 free(dump_info->CurrentFileName);
1991 /* Allocate space for max filename + \0. */
1992 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
1993 if (dump_info->CurrentFileName == NULL)
1994 error("dump_packet_and_trunc: malloc");
1995 /*
1996 * Gflag was set otherwise we wouldn't be here. Reset the count
1997 * so multiple files would end with 1,2,3 in the filename.
1998 * The counting is handled with the -C flow after this.
1999 */
2000 Cflag_count = 0;
2001
2002 /*
2003 * This is always the first file in the Cflag
2004 * rotation: e.g. 0
2005 * We also don't need numbering if Cflag is not set.
2006 */
2007 if (Cflag != 0)
2008 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2009 WflagChars);
2010 else
2011 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2012
2013 #ifdef HAVE_LIBCAP_NG
2014 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2015 capng_apply(CAPNG_SELECT_BOTH);
2016 #endif /* HAVE_LIBCAP_NG */
2017 #ifdef HAVE_CAPSICUM
2018 fd = openat(dump_info->dirfd,
2019 dump_info->CurrentFileName,
2020 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2021 if (fd < 0) {
2022 error("unable to open file %s",
2023 dump_info->CurrentFileName);
2024 }
2025 fp = fdopen(fd, "w");
2026 if (fp == NULL) {
2027 error("unable to fdopen file %s",
2028 dump_info->CurrentFileName);
2029 }
2030 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2031 #else /* !HAVE_CAPSICUM */
2032 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2033 #endif
2034 #ifdef HAVE_LIBCAP_NG
2035 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2036 capng_apply(CAPNG_SELECT_BOTH);
2037 #endif /* HAVE_LIBCAP_NG */
2038 if (dump_info->p == NULL)
2039 error("%s", pcap_geterr(pd));
2040 #ifdef HAVE_CAPSICUM
2041 set_dumper_capsicum_rights(dump_info->p);
2042 #endif
2043 }
2044 }
2045
2046 /*
2047 * XXX - this won't prevent capture files from getting
2048 * larger than Cflag - the last packet written to the
2049 * file could put it over Cflag.
2050 */
2051 if (Cflag != 0) {
2052 long size = pcap_dump_ftell(dump_info->p);
2053
2054 if (size == -1)
2055 error("ftell fails on output file");
2056 if (size > Cflag) {
2057 #ifdef HAVE_CAPSICUM
2058 FILE *fp;
2059 int fd;
2060 #endif
2061
2062 /*
2063 * Close the current file and open a new one.
2064 */
2065 pcap_dump_close(dump_info->p);
2066
2067 /*
2068 * Compress the file we just closed, if the user
2069 * asked for it.
2070 */
2071 if (zflag != NULL)
2072 compress_savefile(dump_info->CurrentFileName);
2073
2074 Cflag_count++;
2075 if (Wflag > 0) {
2076 if (Cflag_count >= Wflag)
2077 Cflag_count = 0;
2078 }
2079 if (dump_info->CurrentFileName != NULL)
2080 free(dump_info->CurrentFileName);
2081 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2082 if (dump_info->CurrentFileName == NULL)
2083 error("dump_packet_and_trunc: malloc");
2084 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2085 #ifdef HAVE_LIBCAP_NG
2086 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2087 capng_apply(CAPNG_SELECT_BOTH);
2088 #endif /* HAVE_LIBCAP_NG */
2089 #ifdef HAVE_CAPSICUM
2090 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2091 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2092 if (fd < 0) {
2093 error("unable to open file %s",
2094 dump_info->CurrentFileName);
2095 }
2096 fp = fdopen(fd, "w");
2097 if (fp == NULL) {
2098 error("unable to fdopen file %s",
2099 dump_info->CurrentFileName);
2100 }
2101 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2102 #else /* !HAVE_CAPSICUM */
2103 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2104 #endif
2105 #ifdef HAVE_LIBCAP_NG
2106 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2107 capng_apply(CAPNG_SELECT_BOTH);
2108 #endif /* HAVE_LIBCAP_NG */
2109 if (dump_info->p == NULL)
2110 error("%s", pcap_geterr(pd));
2111 #ifdef HAVE_CAPSICUM
2112 set_dumper_capsicum_rights(dump_info->p);
2113 #endif
2114 }
2115 }
2116
2117 pcap_dump((u_char *)dump_info->p, h, sp);
2118 #ifdef HAVE_PCAP_DUMP_FLUSH
2119 if (Uflag)
2120 pcap_dump_flush(dump_info->p);
2121 #endif
2122
2123 --infodelay;
2124 if (infoprint)
2125 info(0);
2126 }
2127
2128 static void
2129 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2130 {
2131 ++packets_captured;
2132
2133 ++infodelay;
2134
2135 pcap_dump(user, h, sp);
2136 #ifdef HAVE_PCAP_DUMP_FLUSH
2137 if (Uflag)
2138 pcap_dump_flush((pcap_dumper_t *)user);
2139 #endif
2140
2141 --infodelay;
2142 if (infoprint)
2143 info(0);
2144 }
2145
2146 static void
2147 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2148 {
2149 ++packets_captured;
2150
2151 ++infodelay;
2152
2153 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2154
2155 --infodelay;
2156 if (infoprint)
2157 info(0);
2158 }
2159
2160 #ifdef _WIN32
2161 /*
2162 * XXX - there should really be libpcap calls to get the version
2163 * number as a string (the string would be generated from #defines
2164 * at run time, so that it's not generated from string constants
2165 * in the library, as, on many UNIX systems, those constants would
2166 * be statically linked into the application executable image, and
2167 * would thus reflect the version of libpcap on the system on
2168 * which the application was *linked*, not the system on which it's
2169 * *running*.
2170 *
2171 * That routine should be documented, unlike the "version[]"
2172 * string, so that UNIX vendors providing their own libpcaps
2173 * don't omit it (as a couple of vendors have...).
2174 *
2175 * Packet.dll should perhaps also export a routine to return the
2176 * version number of the Packet.dll code, to supply the
2177 * "Wpcap_version" information on Windows.
2178 */
2179 char WDversion[]="current-git.tcpdump.org";
2180 #if !defined(HAVE_GENERATED_VERSION)
2181 char version[]="current-git.tcpdump.org";
2182 #endif
2183 char pcap_version[]="current-git.tcpdump.org";
2184 char Wpcap_version[]="3.1";
2185 #endif
2186
2187 #ifdef SIGNAL_REQ_INFO
2188 RETSIGTYPE requestinfo(int signo _U_)
2189 {
2190 if (infodelay)
2191 ++infoprint;
2192 else
2193 info(0);
2194 }
2195 #endif
2196
2197 /*
2198 * Called once each second in verbose mode while dumping to file
2199 */
2200 #ifdef USE_WIN32_MM_TIMER
2201 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2202 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2203 {
2204 if (infodelay == 0)
2205 fprintf(stderr, "Got %u\r", packets_captured);
2206 }
2207 #elif defined(HAVE_ALARM)
2208 static void verbose_stats_dump(int sig _U_)
2209 {
2210 if (infodelay == 0)
2211 fprintf(stderr, "Got %u\r", packets_captured);
2212 alarm(1);
2213 }
2214 #endif
2215
2216 USES_APPLE_DEPRECATED_API
2217 static void
2218 print_version(void)
2219 {
2220 extern char version[];
2221 #ifndef HAVE_PCAP_LIB_VERSION
2222 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2223 extern char pcap_version[];
2224 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2225 static char pcap_version[] = "unknown";
2226 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2227 #endif /* HAVE_PCAP_LIB_VERSION */
2228
2229 #ifdef HAVE_PCAP_LIB_VERSION
2230 #ifdef _WIN32
2231 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2232 #else /* _WIN32 */
2233 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2234 #endif /* _WIN32 */
2235 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2236 #else /* HAVE_PCAP_LIB_VERSION */
2237 #ifdef _WIN32
2238 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2239 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2240 #else /* _WIN32 */
2241 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2242 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2243 #endif /* _WIN32 */
2244 #endif /* HAVE_PCAP_LIB_VERSION */
2245
2246 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2247 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2248 #endif
2249
2250 #ifdef USE_LIBSMI
2251 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2252 #endif
2253 }
2254 USES_APPLE_RST
2255
2256 static void
2257 print_usage(void)
2258 {
2259 print_version();
2260 (void)fprintf(stderr,
2261 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2262 (void)fprintf(stderr,
2263 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2264 (void)fprintf(stderr,
2265 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2266 #ifdef HAVE_PCAP_SETDIRECTION
2267 (void)fprintf(stderr,
2268 "\t\t[ -Q in|out|inout ]\n");
2269 #endif
2270 (void)fprintf(stderr,
2271 "\t\t[ -r file ] [ -s snaplen ] ");
2272 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2273 (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2274 (void)fprintf(stderr,
2275 "\t\t");
2276 #endif
2277 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2278 (void)fprintf(stderr, "[ --immediate-mode ] ");
2279 #endif
2280 (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2281 (void)fprintf(stderr,
2282 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2283 (void)fprintf(stderr,
2284 "\t\t[ -Z user ] [ expression ]\n");
2285 }
2286 /*
2287 * Local Variables:
2288 * c-style: whitesmith
2289 * c-basic-offset: 8
2290 * End:
2291 */