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