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