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