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