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