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