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