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