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