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