]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
do not redirect input from /dev/tty
[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 long 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(FORMAT_STRING(const char *), ...) NORETURN PRINTFLIKE(1, 2);
175 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
176 static void exit_tcpdump(int) NORETURN;
177 static RETSIGTYPE cleanup(int);
178 static RETSIGTYPE child_cleanup(int);
179 static void print_version(void);
180 static void print_usage(void);
181 static void show_tstamp_types_and_exit(pcap_t *, const char *device) NORETURN;
182 static void show_dlts_and_exit(pcap_t *, const char *device) NORETURN;
183 #ifdef HAVE_PCAP_FINDALLDEVS
184 static void show_devices_and_exit (void) NORETURN;
185 #endif
186
187 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
188 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
189 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
190 static void droproot(const char *, const char *);
191
192 #ifdef SIGNAL_REQ_INFO
193 RETSIGTYPE requestinfo(int);
194 #endif
195
196 #if defined(USE_WIN32_MM_TIMER)
197 #include <MMsystem.h>
198 static UINT timer_id;
199 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
200 #elif defined(HAVE_ALARM)
201 static void verbose_stats_dump(int sig);
202 #endif
203
204 static void info(int);
205 static u_int packets_captured;
206
207 #ifdef HAVE_PCAP_FINDALLDEVS
208 static const struct tok status_flags[] = {
209 #ifdef PCAP_IF_UP
210 { PCAP_IF_UP, "Up" },
211 #endif
212 #ifdef PCAP_IF_RUNNING
213 { PCAP_IF_RUNNING, "Running" },
214 #endif
215 { PCAP_IF_LOOPBACK, "Loopback" },
216 { 0, NULL }
217 };
218 #endif
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(pcap_t *pc, 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(pc, &tstamp_types);
342 if (n_tstamp_types < 0)
343 error("%s", pcap_geterr(pc));
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(pcap_t *pc, 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(pc, &dlts);
374 if (n_dlts < 0)
375 error("%s", pcap_geterr(pc));
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 to specify 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 error("capng_change_id(): return %d\n", ret);
612 else
613 fprintf(stderr, "dropped privs to %s\n", username);
614 }
615 #else
616 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
617 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
618 fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
619 program_name, username,
620 (unsigned long)pw->pw_uid,
621 (unsigned long)pw->pw_gid,
622 pcap_strerror(errno));
623 exit_tcpdump(1);
624 }
625 else {
626 fprintf(stderr, "dropped privs to %s\n", username);
627 }
628 #endif /* HAVE_LIBCAP_NG */
629 }
630 else {
631 fprintf(stderr, "%s: Couldn't find user '%.32s'\n",
632 program_name, username);
633 exit_tcpdump(1);
634 }
635 #ifdef HAVE_LIBCAP_NG
636 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
637 capng_updatev(
638 CAPNG_DROP,
639 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
640 CAP_SETUID,
641 CAP_SETGID,
642 CAP_SYS_CHROOT,
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 size_t len;
703
704 ret = fgets(ptr, PATH_MAX, VFile);
705 if (!ret)
706 return NULL;
707
708 len = strlen (ptr);
709 if (len > 0 && ptr[len - 1] == '\n')
710 ptr[len - 1] = '\0';
711
712 return ret;
713 }
714
715 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
716 static int
717 tstamp_precision_from_string(const char *precision)
718 {
719 if (strncmp(precision, "nano", strlen("nano")) == 0)
720 return PCAP_TSTAMP_PRECISION_NANO;
721
722 if (strncmp(precision, "micro", strlen("micro")) == 0)
723 return PCAP_TSTAMP_PRECISION_MICRO;
724
725 return -EINVAL;
726 }
727
728 static const char *
729 tstamp_precision_to_string(int precision)
730 {
731 switch (precision) {
732
733 case PCAP_TSTAMP_PRECISION_MICRO:
734 return "micro";
735
736 case PCAP_TSTAMP_PRECISION_NANO:
737 return "nano";
738
739 default:
740 return "unknown";
741 }
742 }
743 #endif
744
745 #ifdef HAVE_CAPSICUM
746 /*
747 * Ensure that, on a dump file's descriptor, we have all the rights
748 * necessary to make the standard I/O library work with an fdopen()ed
749 * FILE * from that descriptor.
750 *
751 * A long time ago, in a galaxy far far away, AT&T decided that, instead
752 * of providing separate APIs for getting and setting the FD_ flags on a
753 * descriptor, getting and setting the O_ flags on a descriptor, and
754 * locking files, they'd throw them all into a kitchen-sink fcntl() call
755 * along the lines of ioctl(), the fact that ioctl() operations are
756 * largely specific to particular character devices but fcntl() operations
757 * are either generic to all descriptors or generic to all descriptors for
758 * regular files nonwithstanding.
759 *
760 * The Capsicum people decided that fine-grained control of descriptor
761 * operations was required, so that you need to grant permission for
762 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
763 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
764 * collection of things, so there are *individual* fcntls for which
765 * permission needs to be granted.
766 *
767 * The FreeBSD standard I/O people implemented some optimizations that
768 * requires that the standard I/O routines be able to determine whether
769 * the descriptor for the FILE * is open append-only or not; as that
770 * descriptor could have come from an open() rather than an fopen(),
771 * that requires that it be able to do an F_GETFL fcntl() to read
772 * the O_ flags.
773 *
774 * Tcpdump uses ftell() to determine how much data has been written
775 * to a file in order to, when used with -C, determine when it's time
776 * to rotate capture files. ftell() therefore needs to do an lseek()
777 * to find out the file offset and must, thanks to the aforementioned
778 * optimization, also know whether the descriptor is open append-only
779 * or not.
780 *
781 * The net result of all the above is that we need to grant CAP_SEEK,
782 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
783 *
784 * Perhaps this is the universe's way of saying that either
785 *
786 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
787 * using it, so that Capsicum-capable tcpdump wouldn't need to do
788 * an fdopen()
789 *
790 * or
791 *
792 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
793 * I/O library that knows what rights are needed by the standard
794 * I/O library, based on the open mode, and assigns them, perhaps
795 * with an additional argument indicating, for example, whether
796 * seeking should be allowed, so that tcpdump doesn't need to know
797 * what the standard I/O library happens to require this week.
798 */
799 static void
800 set_dumper_capsicum_rights(pcap_dumper_t *p)
801 {
802 int fd = fileno(pcap_dump_file(p));
803 cap_rights_t rights;
804
805 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
806 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
807 error("unable to limit dump descriptor");
808 }
809 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
810 error("unable to limit dump descriptor fcntls");
811 }
812 }
813 #endif
814
815 /*
816 * Copy arg vector into a new buffer, concatenating arguments with spaces.
817 */
818 static char *
819 copy_argv(register char **argv)
820 {
821 register char **p;
822 register u_int len = 0;
823 char *buf;
824 char *src, *dst;
825
826 p = argv;
827 if (*p == NULL)
828 return 0;
829
830 while (*p)
831 len += strlen(*p++) + 1;
832
833 buf = (char *)malloc(len);
834 if (buf == NULL)
835 error("copy_argv: malloc");
836
837 p = argv;
838 dst = buf;
839 while ((src = *p++) != NULL) {
840 while ((*dst++ = *src++) != '\0')
841 ;
842 dst[-1] = ' ';
843 }
844 dst[-1] = '\0';
845
846 return buf;
847 }
848
849 /*
850 * On Windows, we need to open the file in binary mode, so that
851 * we get all the bytes specified by the size we get from "fstat()".
852 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
853 * we define it as 0 if it's not defined, so it does nothing.
854 */
855 #ifndef O_BINARY
856 #define O_BINARY 0
857 #endif
858
859 static char *
860 read_infile(char *fname)
861 {
862 register int i, fd, cc;
863 register char *cp;
864 struct stat buf;
865
866 fd = open(fname, O_RDONLY|O_BINARY);
867 if (fd < 0)
868 error("can't open %s: %s", fname, pcap_strerror(errno));
869
870 if (fstat(fd, &buf) < 0)
871 error("can't stat %s: %s", fname, pcap_strerror(errno));
872
873 cp = malloc((u_int)buf.st_size + 1);
874 if (cp == NULL)
875 error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
876 fname, pcap_strerror(errno));
877 cc = read(fd, cp, (u_int)buf.st_size);
878 if (cc < 0)
879 error("read %s: %s", fname, pcap_strerror(errno));
880 if (cc != buf.st_size)
881 error("short read %s (%d != %d)", fname, cc, (int)buf.st_size);
882
883 close(fd);
884 /* replace "# comment" with spaces */
885 for (i = 0; i < cc; i++) {
886 if (cp[i] == '#')
887 while (i < cc && cp[i] != '\n')
888 cp[i++] = ' ';
889 }
890 cp[cc] = '\0';
891 return (cp);
892 }
893
894 #ifdef HAVE_PCAP_FINDALLDEVS
895 static long
896 parse_interface_number(const char *device)
897 {
898 long devnum;
899 char *end;
900
901 devnum = strtol(device, &end, 10);
902 if (device != end && *end == '\0') {
903 /*
904 * It's all-numeric, but is it a valid number?
905 */
906 if (devnum <= 0) {
907 /*
908 * No, it's not an ordinal.
909 */
910 error("Invalid adapter index");
911 }
912 return (devnum);
913 } else {
914 /*
915 * It's not all-numeric; return -1, so our caller
916 * knows that.
917 */
918 return (-1);
919 }
920 }
921
922 static char *
923 find_interface_by_number(long devnum)
924 {
925 pcap_if_t *dev, *devlist;
926 long i;
927 char ebuf[PCAP_ERRBUF_SIZE];
928 char *device;
929
930 if (pcap_findalldevs(&devlist, ebuf) < 0)
931 error("%s", ebuf);
932 /*
933 * Look for the devnum-th entry in the list of devices (1-based).
934 */
935 for (i = 0, dev = devlist; i < devnum-1 && dev != NULL;
936 i++, dev = dev->next)
937 ;
938 if (dev == NULL)
939 error("Invalid adapter index");
940 device = strdup(dev->name);
941 pcap_freealldevs(devlist);
942 return (device);
943 }
944 #endif
945
946 static pcap_t *
947 open_interface(const char *device, netdissect_options *ndo, char *ebuf)
948 {
949 pcap_t *pc;
950 #ifdef HAVE_PCAP_CREATE
951 int status;
952 char *cp;
953 #endif
954
955 #ifdef HAVE_PCAP_CREATE
956 pc = pcap_create(device, ebuf);
957 if (pc == NULL) {
958 /*
959 * If this failed with "No such device", that means
960 * the interface doesn't exist; return NULL, so that
961 * the caller can see whether the device name is
962 * actually an interface index.
963 */
964 if (strstr(ebuf, "No such device") != NULL)
965 return (NULL);
966 error("%s", ebuf);
967 }
968 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
969 if (Jflag)
970 show_tstamp_types_and_exit(pc, device);
971 #endif
972 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
973 status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision);
974 if (status != 0)
975 error("%s: Can't set %ssecond time stamp precision: %s",
976 device,
977 tstamp_precision_to_string(ndo->ndo_tstamp_precision),
978 pcap_statustostr(status));
979 #endif
980
981 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
982 if (immediate_mode) {
983 status = pcap_set_immediate_mode(pc, 1);
984 if (status != 0)
985 error("%s: Can't set immediate mode: %s",
986 device,
987 pcap_statustostr(status));
988 }
989 #endif
990 /*
991 * Is this an interface that supports monitor mode?
992 */
993 if (pcap_can_set_rfmon(pc) == 1)
994 supports_monitor_mode = 1;
995 else
996 supports_monitor_mode = 0;
997 status = pcap_set_snaplen(pc, ndo->ndo_snaplen);
998 if (status != 0)
999 error("%s: Can't set snapshot length: %s",
1000 device, pcap_statustostr(status));
1001 status = pcap_set_promisc(pc, !pflag);
1002 if (status != 0)
1003 error("%s: Can't set promiscuous mode: %s",
1004 device, pcap_statustostr(status));
1005 if (Iflag) {
1006 status = pcap_set_rfmon(pc, 1);
1007 if (status != 0)
1008 error("%s: Can't set monitor mode: %s",
1009 device, pcap_statustostr(status));
1010 }
1011 status = pcap_set_timeout(pc, 1000);
1012 if (status != 0)
1013 error("%s: pcap_set_timeout failed: %s",
1014 device, pcap_statustostr(status));
1015 if (Bflag != 0) {
1016 status = pcap_set_buffer_size(pc, Bflag);
1017 if (status != 0)
1018 error("%s: Can't set buffer size: %s",
1019 device, pcap_statustostr(status));
1020 }
1021 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1022 if (jflag != -1) {
1023 status = pcap_set_tstamp_type(pc, jflag);
1024 if (status < 0)
1025 error("%s: Can't set time stamp type: %s",
1026 device, pcap_statustostr(status));
1027 else if (status > 0)
1028 warning("When trying to set timestamp type '%s' on %s: %s",
1029 pcap_tstamp_type_val_to_name(jflag), device,
1030 pcap_statustostr(status));
1031 }
1032 #endif
1033 status = pcap_activate(pc);
1034 if (status < 0) {
1035 /*
1036 * pcap_activate() failed.
1037 */
1038 cp = pcap_geterr(pc);
1039 if (status == PCAP_ERROR)
1040 error("%s", cp);
1041 else if (status == PCAP_ERROR_NO_SUCH_DEVICE) {
1042 /*
1043 * Return an error for our caller to handle.
1044 */
1045 snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)",
1046 device, pcap_statustostr(status), cp);
1047 pcap_close(pc);
1048 return (NULL);
1049 } else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0')
1050 error("%s: %s\n(%s)", device,
1051 pcap_statustostr(status), cp);
1052 else
1053 error("%s: %s", device,
1054 pcap_statustostr(status));
1055 } else if (status > 0) {
1056 /*
1057 * pcap_activate() succeeded, but it's warning us
1058 * of a problem it had.
1059 */
1060 cp = pcap_geterr(pc);
1061 if (status == PCAP_WARNING)
1062 warning("%s", cp);
1063 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1064 *cp != '\0')
1065 warning("%s: %s\n(%s)", device,
1066 pcap_statustostr(status), cp);
1067 else
1068 warning("%s: %s", device,
1069 pcap_statustostr(status));
1070 }
1071 #ifdef HAVE_PCAP_SETDIRECTION
1072 if (Qflag != -1) {
1073 status = pcap_setdirection(pc, Qflag);
1074 if (status != 0)
1075 error("%s: pcap_setdirection() failed: %s",
1076 device, pcap_geterr(pc));
1077 }
1078 #endif /* HAVE_PCAP_SETDIRECTION */
1079 #else /* HAVE_PCAP_CREATE */
1080 *ebuf = '\0';
1081 pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000, ebuf);
1082 if (pc == NULL) {
1083 /*
1084 * If this failed with "No such device", that means
1085 * the interface doesn't exist; return NULL, so that
1086 * the caller can see whether the device name is
1087 * actually an interface index.
1088 */
1089 if (strstr(ebuf, "No such device") != NULL)
1090 return (NULL);
1091 error("%s", ebuf);
1092 }
1093 if (*ebuf)
1094 warning("%s", ebuf);
1095 #endif /* HAVE_PCAP_CREATE */
1096
1097 return (pc);
1098 }
1099
1100 int
1101 main(int argc, char **argv)
1102 {
1103 register int cnt, op, i;
1104 bpf_u_int32 localnet =0 , netmask = 0;
1105 int timezone_offset = 0;
1106 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
1107 pcap_handler callback;
1108 int dlt;
1109 const char *dlt_name;
1110 struct bpf_program fcode;
1111 #ifndef _WIN32
1112 RETSIGTYPE (*oldhandler)(int);
1113 #endif
1114 struct dump_info dumpinfo;
1115 u_char *pcap_userdata;
1116 char ebuf[PCAP_ERRBUF_SIZE];
1117 char VFileLine[PATH_MAX + 1];
1118 char *username = NULL;
1119 char *chroot_dir = NULL;
1120 char *ret = NULL;
1121 char *end;
1122 #ifdef HAVE_PCAP_FINDALLDEVS
1123 pcap_if_t *devlist;
1124 long devnum;
1125 #endif
1126 int status;
1127 FILE *VFile;
1128 #ifdef HAVE_CAPSICUM
1129 cap_rights_t rights;
1130 int cansandbox;
1131 #endif /* HAVE_CAPSICUM */
1132 int Oflag = 1; /* run filter code optimizer */
1133 int yflag_dlt = -1;
1134 const char *yflag_dlt_name = NULL;
1135
1136 netdissect_options Ndo;
1137 netdissect_options *ndo = &Ndo;
1138
1139 /*
1140 * Initialize the netdissect code.
1141 */
1142 if (nd_init(ebuf, sizeof ebuf) == -1)
1143 error("%s", ebuf);
1144
1145 memset(ndo, 0, sizeof(*ndo));
1146 ndo_set_function_pointers(ndo);
1147 ndo->ndo_snaplen = DEFAULT_SNAPLEN;
1148
1149 cnt = -1;
1150 device = NULL;
1151 infile = NULL;
1152 RFileName = NULL;
1153 VFileName = NULL;
1154 VFile = NULL;
1155 WFileName = NULL;
1156 dlt = -1;
1157 if ((cp = strrchr(argv[0], '/')) != NULL)
1158 ndo->program_name = program_name = cp + 1;
1159 else
1160 ndo->program_name = program_name = argv[0];
1161
1162 #ifdef _WIN32
1163 if (pcap_wsockinit() != 0)
1164 error("Attempting to initialize Winsock failed");
1165 #endif /* _WIN32 */
1166
1167 /*
1168 * On platforms where the CPU doesn't support unaligned loads,
1169 * force unaligned accesses to abort with SIGBUS, rather than
1170 * being fixed up (slowly) by the OS kernel; on those platforms,
1171 * misaligned accesses are bugs, and we want tcpdump to crash so
1172 * that the bugs are reported.
1173 */
1174 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1175 error("%s", ebuf);
1176
1177 while (
1178 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
1179 switch (op) {
1180
1181 case 'a':
1182 /* compatibility for old -a */
1183 break;
1184
1185 case 'A':
1186 ++ndo->ndo_Aflag;
1187 break;
1188
1189 case 'b':
1190 ++ndo->ndo_bflag;
1191 break;
1192
1193 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1194 case 'B':
1195 Bflag = atoi(optarg)*1024;
1196 if (Bflag <= 0)
1197 error("invalid packet buffer size %s", optarg);
1198 break;
1199 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1200
1201 case 'c':
1202 cnt = atoi(optarg);
1203 if (cnt <= 0)
1204 error("invalid packet count %s", optarg);
1205 break;
1206
1207 case 'C':
1208 Cflag = atoi(optarg) * 1000000;
1209 if (Cflag <= 0)
1210 error("invalid file size %s", optarg);
1211 break;
1212
1213 case 'd':
1214 ++dflag;
1215 break;
1216
1217 case 'D':
1218 Dflag++;
1219 break;
1220
1221 case 'L':
1222 Lflag++;
1223 break;
1224
1225 case 'e':
1226 ++ndo->ndo_eflag;
1227 break;
1228
1229 case 'E':
1230 #ifndef HAVE_LIBCRYPTO
1231 warning("crypto code not compiled in");
1232 #endif
1233 ndo->ndo_espsecret = optarg;
1234 break;
1235
1236 case 'f':
1237 ++ndo->ndo_fflag;
1238 break;
1239
1240 case 'F':
1241 infile = optarg;
1242 break;
1243
1244 case 'G':
1245 Gflag = atoi(optarg);
1246 if (Gflag < 0)
1247 error("invalid number of seconds %s", optarg);
1248
1249 /* We will create one file initially. */
1250 Gflag_count = 0;
1251
1252 /* Grab the current time for rotation use. */
1253 if ((Gflag_time = time(NULL)) == (time_t)-1) {
1254 error("main: can't get current time: %s",
1255 pcap_strerror(errno));
1256 }
1257 break;
1258
1259 case 'h':
1260 print_usage();
1261 exit_tcpdump(0);
1262 break;
1263
1264 case 'H':
1265 ++ndo->ndo_Hflag;
1266 break;
1267
1268 case 'i':
1269 device = optarg;
1270 break;
1271
1272 #ifdef HAVE_PCAP_CREATE
1273 case 'I':
1274 ++Iflag;
1275 break;
1276 #endif /* HAVE_PCAP_CREATE */
1277
1278 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1279 case 'j':
1280 jflag = pcap_tstamp_type_name_to_val(optarg);
1281 if (jflag < 0)
1282 error("invalid time stamp type %s", optarg);
1283 break;
1284
1285 case 'J':
1286 Jflag++;
1287 break;
1288 #endif
1289
1290 case 'l':
1291 #ifdef _WIN32
1292 /*
1293 * _IOLBF is the same as _IOFBF in Microsoft's C
1294 * libraries; the only alternative they offer
1295 * is _IONBF.
1296 *
1297 * XXX - this should really be checking for MSVC++,
1298 * not _WIN32, if, for example, MinGW has its own
1299 * C library that is more UNIX-compatible.
1300 */
1301 setvbuf(stdout, NULL, _IONBF, 0);
1302 #else /* _WIN32 */
1303 #ifdef HAVE_SETLINEBUF
1304 setlinebuf(stdout);
1305 #else
1306 setvbuf(stdout, NULL, _IOLBF, 0);
1307 #endif
1308 #endif /* _WIN32 */
1309 break;
1310
1311 case 'K':
1312 ++ndo->ndo_Kflag;
1313 break;
1314
1315 case 'm':
1316 if (nd_have_smi_support()) {
1317 if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1)
1318 error("%s", ebuf);
1319 } else {
1320 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1321 program_name, optarg);
1322 (void)fprintf(stderr, "(no libsmi support)\n");
1323 }
1324 break;
1325
1326 case 'M':
1327 /* TCP-MD5 shared secret */
1328 #ifndef HAVE_LIBCRYPTO
1329 warning("crypto code not compiled in");
1330 #endif
1331 ndo->ndo_sigsecret = optarg;
1332 break;
1333
1334 case 'n':
1335 ++ndo->ndo_nflag;
1336 break;
1337
1338 case 'N':
1339 ++ndo->ndo_Nflag;
1340 break;
1341
1342 case 'O':
1343 Oflag = 0;
1344 break;
1345
1346 case 'p':
1347 ++pflag;
1348 break;
1349
1350 case 'q':
1351 ++ndo->ndo_qflag;
1352 ++ndo->ndo_suppress_default_print;
1353 break;
1354
1355 #ifdef HAVE_PCAP_SETDIRECTION
1356 case 'Q':
1357 if (ascii_strcasecmp(optarg, "in") == 0)
1358 Qflag = PCAP_D_IN;
1359 else if (ascii_strcasecmp(optarg, "out") == 0)
1360 Qflag = PCAP_D_OUT;
1361 else if (ascii_strcasecmp(optarg, "inout") == 0)
1362 Qflag = PCAP_D_INOUT;
1363 else
1364 error("unknown capture direction `%s'", optarg);
1365 break;
1366 #endif /* HAVE_PCAP_SETDIRECTION */
1367
1368 case 'r':
1369 RFileName = optarg;
1370 break;
1371
1372 case 's':
1373 ndo->ndo_snaplen = strtol(optarg, &end, 0);
1374 if (optarg == end || *end != '\0'
1375 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1376 error("invalid snaplen %s", optarg);
1377 else if (ndo->ndo_snaplen == 0)
1378 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1379 break;
1380
1381 case 'S':
1382 ++ndo->ndo_Sflag;
1383 break;
1384
1385 case 't':
1386 ++ndo->ndo_tflag;
1387 break;
1388
1389 case 'T':
1390 if (ascii_strcasecmp(optarg, "vat") == 0)
1391 ndo->ndo_packettype = PT_VAT;
1392 else if (ascii_strcasecmp(optarg, "wb") == 0)
1393 ndo->ndo_packettype = PT_WB;
1394 else if (ascii_strcasecmp(optarg, "rpc") == 0)
1395 ndo->ndo_packettype = PT_RPC;
1396 else if (ascii_strcasecmp(optarg, "rtp") == 0)
1397 ndo->ndo_packettype = PT_RTP;
1398 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1399 ndo->ndo_packettype = PT_RTCP;
1400 else if (ascii_strcasecmp(optarg, "snmp") == 0)
1401 ndo->ndo_packettype = PT_SNMP;
1402 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1403 ndo->ndo_packettype = PT_CNFP;
1404 else if (ascii_strcasecmp(optarg, "tftp") == 0)
1405 ndo->ndo_packettype = PT_TFTP;
1406 else if (ascii_strcasecmp(optarg, "aodv") == 0)
1407 ndo->ndo_packettype = PT_AODV;
1408 else if (ascii_strcasecmp(optarg, "carp") == 0)
1409 ndo->ndo_packettype = PT_CARP;
1410 else if (ascii_strcasecmp(optarg, "radius") == 0)
1411 ndo->ndo_packettype = PT_RADIUS;
1412 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1413 ndo->ndo_packettype = PT_ZMTP1;
1414 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1415 ndo->ndo_packettype = PT_VXLAN;
1416 else if (ascii_strcasecmp(optarg, "pgm") == 0)
1417 ndo->ndo_packettype = PT_PGM;
1418 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1419 ndo->ndo_packettype = PT_PGM_ZMTP1;
1420 else if (ascii_strcasecmp(optarg, "lmp") == 0)
1421 ndo->ndo_packettype = PT_LMP;
1422 else if (ascii_strcasecmp(optarg, "resp") == 0)
1423 ndo->ndo_packettype = PT_RESP;
1424 else
1425 error("unknown packet type `%s'", optarg);
1426 break;
1427
1428 case 'u':
1429 ++ndo->ndo_uflag;
1430 break;
1431
1432 #ifdef HAVE_PCAP_DUMP_FLUSH
1433 case 'U':
1434 ++Uflag;
1435 break;
1436 #endif
1437
1438 case 'v':
1439 ++ndo->ndo_vflag;
1440 break;
1441
1442 case 'V':
1443 VFileName = optarg;
1444 break;
1445
1446 case 'w':
1447 WFileName = optarg;
1448 break;
1449
1450 case 'W':
1451 Wflag = atoi(optarg);
1452 if (Wflag <= 0)
1453 error("invalid number of output files %s", optarg);
1454 WflagChars = getWflagChars(Wflag);
1455 break;
1456
1457 case 'x':
1458 ++ndo->ndo_xflag;
1459 ++ndo->ndo_suppress_default_print;
1460 break;
1461
1462 case 'X':
1463 ++ndo->ndo_Xflag;
1464 ++ndo->ndo_suppress_default_print;
1465 break;
1466
1467 case 'y':
1468 yflag_dlt_name = optarg;
1469 yflag_dlt =
1470 pcap_datalink_name_to_val(yflag_dlt_name);
1471 if (yflag_dlt < 0)
1472 error("invalid data link type %s", yflag_dlt_name);
1473 break;
1474
1475 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1476 case 'Y':
1477 {
1478 /* Undocumented flag */
1479 pcap_set_parser_debug(1);
1480 }
1481 break;
1482 #endif
1483 case 'z':
1484 zflag = optarg;
1485 break;
1486
1487 case 'Z':
1488 username = optarg;
1489 break;
1490
1491 case '#':
1492 ndo->ndo_packet_number = 1;
1493 break;
1494
1495 case OPTION_VERSION:
1496 print_version();
1497 exit_tcpdump(0);
1498 break;
1499
1500 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1501 case OPTION_TSTAMP_PRECISION:
1502 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1503 if (ndo->ndo_tstamp_precision < 0)
1504 error("unsupported time stamp precision");
1505 break;
1506 #endif
1507
1508 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1509 case OPTION_IMMEDIATE_MODE:
1510 immediate_mode = 1;
1511 break;
1512 #endif
1513
1514 default:
1515 print_usage();
1516 exit_tcpdump(1);
1517 /* NOTREACHED */
1518 }
1519
1520 #ifdef HAVE_PCAP_FINDALLDEVS
1521 if (Dflag)
1522 show_devices_and_exit();
1523 #endif
1524
1525 switch (ndo->ndo_tflag) {
1526
1527 case 0: /* Default */
1528 case 4: /* Default + Date*/
1529 timezone_offset = gmt2local(0);
1530 break;
1531
1532 case 1: /* No time stamp */
1533 case 2: /* Unix timeval style */
1534 case 3: /* Microseconds since previous packet */
1535 case 5: /* Microseconds since first packet */
1536 break;
1537
1538 default: /* Not supported */
1539 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1540 break;
1541 }
1542
1543 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1544 error("-f can not be used with -V or -r");
1545
1546 if (VFileName != NULL && RFileName != NULL)
1547 error("-V and -r are mutually exclusive.");
1548
1549 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1550 /*
1551 * If we're printing dissected packets to the standard output
1552 * rather than saving raw packets to a file, and the standard
1553 * output is a terminal, use immediate mode, as the user's
1554 * probably expecting to see packets pop up immediately.
1555 */
1556 if (WFileName == NULL && isatty(1))
1557 immediate_mode = 1;
1558 #endif
1559
1560 #ifdef WITH_CHROOT
1561 /* if run as root, prepare for chrooting */
1562 if (getuid() == 0 || geteuid() == 0) {
1563 /* future extensibility for cmd-line arguments */
1564 if (!chroot_dir)
1565 chroot_dir = WITH_CHROOT;
1566 }
1567 #endif
1568
1569 #ifdef WITH_USER
1570 /* if run as root, prepare for dropping root privileges */
1571 if (getuid() == 0 || geteuid() == 0) {
1572 /* Run with '-Z root' to restore old behaviour */
1573 if (!username)
1574 username = WITH_USER;
1575 }
1576 #endif
1577
1578 if (RFileName != NULL || VFileName != NULL) {
1579 /*
1580 * If RFileName is non-null, it's the pathname of a
1581 * savefile to read. If VFileName is non-null, it's
1582 * the pathname of a file containing a list of pathnames
1583 * (one per line) of savefiles to read.
1584 *
1585 * In either case, we're reading a savefile, not doing
1586 * a live capture.
1587 */
1588 #ifndef _WIN32
1589 /*
1590 * We don't need network access, so relinquish any set-UID
1591 * or set-GID privileges we have (if any).
1592 *
1593 * We do *not* want set-UID privileges when opening a
1594 * trace file, as that might let the user read other
1595 * people's trace files (especially if we're set-UID
1596 * root).
1597 */
1598 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1599 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1600 #endif /* _WIN32 */
1601 if (VFileName != NULL) {
1602 if (VFileName[0] == '-' && VFileName[1] == '\0')
1603 VFile = stdin;
1604 else
1605 VFile = fopen(VFileName, "r");
1606
1607 if (VFile == NULL)
1608 error("Unable to open file: %s\n", pcap_strerror(errno));
1609
1610 ret = get_next_file(VFile, VFileLine);
1611 if (!ret)
1612 error("Nothing in %s\n", VFileName);
1613 RFileName = VFileLine;
1614 }
1615
1616 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1617 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1618 ndo->ndo_tstamp_precision, ebuf);
1619 #else
1620 pd = pcap_open_offline(RFileName, ebuf);
1621 #endif
1622
1623 if (pd == NULL)
1624 error("%s", ebuf);
1625 #ifdef HAVE_CAPSICUM
1626 cap_rights_init(&rights, CAP_READ);
1627 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1628 errno != ENOSYS) {
1629 error("unable to limit pcap descriptor");
1630 }
1631 #endif
1632 dlt = pcap_datalink(pd);
1633 dlt_name = pcap_datalink_val_to_name(dlt);
1634 if (dlt_name == NULL) {
1635 fprintf(stderr, "reading from file %s, link-type %u\n",
1636 RFileName, dlt);
1637 } else {
1638 fprintf(stderr,
1639 "reading from file %s, link-type %s (%s)\n",
1640 RFileName, dlt_name,
1641 pcap_datalink_val_to_description(dlt));
1642 }
1643 } else {
1644 /*
1645 * We're doing a live capture.
1646 */
1647 if (device == NULL) {
1648 /*
1649 * No interface was specified. Pick one.
1650 */
1651 #ifdef HAVE_PCAP_FINDALLDEVS
1652 /*
1653 * Find the list of interfaces, and pick
1654 * the first interface.
1655 */
1656 if (pcap_findalldevs(&devlist, ebuf) >= 0 &&
1657 devlist != NULL) {
1658 device = strdup(devlist->name);
1659 pcap_freealldevs(devlist);
1660 }
1661 #else /* HAVE_PCAP_FINDALLDEVS */
1662 /*
1663 * Use whatever interface pcap_lookupdev()
1664 * chooses.
1665 */
1666 device = pcap_lookupdev(ebuf);
1667 #endif
1668 if (device == NULL)
1669 error("%s", ebuf);
1670 }
1671
1672 /*
1673 * Try to open the interface with the specified name.
1674 */
1675 pd = open_interface(device, ndo, ebuf);
1676 if (pd == NULL) {
1677 /*
1678 * That failed. If we can get a list of
1679 * interfaces, and the interface name
1680 * is purely numeric, try to use it as
1681 * a 1-based index in the list of
1682 * interfaces.
1683 */
1684 #ifdef HAVE_PCAP_FINDALLDEVS
1685 devnum = parse_interface_number(device);
1686 if (devnum == -1) {
1687 /*
1688 * It's not a number; just report
1689 * the open error and fail.
1690 */
1691 error("%s", ebuf);
1692 }
1693
1694 /*
1695 * OK, it's a number; try to find the
1696 * interface with that index, and try
1697 * to open it.
1698 *
1699 * find_interface_by_number() exits if it
1700 * couldn't be found.
1701 */
1702 device = find_interface_by_number(devnum);
1703 pd = open_interface(device, ndo, ebuf);
1704 if (pd == NULL)
1705 error("%s", ebuf);
1706 #else /* HAVE_PCAP_FINDALLDEVS */
1707 /*
1708 * We can't get a list of interfaces; just
1709 * fail.
1710 */
1711 error("%s", ebuf);
1712 #endif /* HAVE_PCAP_FINDALLDEVS */
1713 }
1714
1715 /*
1716 * Let user own process after socket has been opened.
1717 */
1718 #ifndef _WIN32
1719 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1720 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1721 #endif /* _WIN32 */
1722 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1723 if(Bflag != 0)
1724 if(pcap_setbuff(pd, Bflag)==-1){
1725 error("%s", pcap_geterr(pd));
1726 }
1727 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1728 if (Lflag)
1729 show_dlts_and_exit(pd, device);
1730 if (yflag_dlt >= 0) {
1731 #ifdef HAVE_PCAP_SET_DATALINK
1732 if (pcap_set_datalink(pd, yflag_dlt) < 0)
1733 error("%s", pcap_geterr(pd));
1734 #else
1735 /*
1736 * We don't actually support changing the
1737 * data link type, so we only let them
1738 * set it to what it already is.
1739 */
1740 if (yflag_dlt != pcap_datalink(pd)) {
1741 error("%s is not one of the DLTs supported by this device\n",
1742 yflag_dlt_name);
1743 }
1744 #endif
1745 (void)fprintf(stderr, "%s: data link type %s\n",
1746 program_name, yflag_dlt_name);
1747 (void)fflush(stderr);
1748 }
1749 i = pcap_snapshot(pd);
1750 if (ndo->ndo_snaplen < i) {
1751 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
1752 ndo->ndo_snaplen = i;
1753 }
1754 if(ndo->ndo_fflag != 0) {
1755 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1756 warning("foreign (-f) flag used but: %s", ebuf);
1757 }
1758 }
1759
1760 }
1761 if (infile)
1762 cmdbuf = read_infile(infile);
1763 else
1764 cmdbuf = copy_argv(&argv[optind]);
1765
1766 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1767 pcap_set_optimizer_debug(dflag);
1768 #endif
1769 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1770 error("%s", pcap_geterr(pd));
1771 if (dflag) {
1772 bpf_dump(&fcode, dflag);
1773 pcap_close(pd);
1774 free(cmdbuf);
1775 pcap_freecode(&fcode);
1776 exit_tcpdump(0);
1777 }
1778 init_print(ndo, localnet, netmask, timezone_offset);
1779
1780 #ifndef _WIN32
1781 (void)setsignal(SIGPIPE, cleanup);
1782 (void)setsignal(SIGTERM, cleanup);
1783 (void)setsignal(SIGINT, cleanup);
1784 #endif /* _WIN32 */
1785 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1786 (void)setsignal(SIGCHLD, child_cleanup);
1787 #endif
1788 /* Cooperate with nohup(1) */
1789 #ifndef _WIN32
1790 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1791 (void)setsignal(SIGHUP, oldhandler);
1792 #endif /* _WIN32 */
1793
1794 #ifndef _WIN32
1795 /*
1796 * If a user name was specified with "-Z", attempt to switch to
1797 * that user's UID. This would probably be used with sudo,
1798 * to allow tcpdump to be run in a special restricted
1799 * account (if you just want to allow users to open capture
1800 * devices, and can't just give users that permission,
1801 * you'd make tcpdump set-UID or set-GID).
1802 *
1803 * Tcpdump doesn't necessarily write only to one savefile;
1804 * the general only way to allow a -Z instance to write to
1805 * savefiles as the user under whose UID it's run, rather
1806 * than as the user specified with -Z, would thus be to switch
1807 * to the original user ID before opening a capture file and
1808 * then switch back to the -Z user ID after opening the savefile.
1809 * Switching to the -Z user ID only after opening the first
1810 * savefile doesn't handle the general case.
1811 */
1812
1813 if (getuid() == 0 || geteuid() == 0) {
1814 #ifdef HAVE_LIBCAP_NG
1815 /* Initialize capng */
1816 capng_clear(CAPNG_SELECT_BOTH);
1817 if (username) {
1818 capng_updatev(
1819 CAPNG_ADD,
1820 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1821 CAP_SETUID,
1822 CAP_SETGID,
1823 -1);
1824 }
1825 if (chroot_dir) {
1826 capng_update(
1827 CAPNG_ADD,
1828 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1829 CAP_SYS_CHROOT
1830 );
1831 }
1832
1833 if (WFileName) {
1834 capng_update(
1835 CAPNG_ADD,
1836 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1837 CAP_DAC_OVERRIDE
1838 );
1839 }
1840 capng_apply(CAPNG_SELECT_BOTH);
1841 #endif /* HAVE_LIBCAP_NG */
1842 if (username || chroot_dir)
1843 droproot(username, chroot_dir);
1844
1845 }
1846 #endif /* _WIN32 */
1847
1848 if (pcap_setfilter(pd, &fcode) < 0)
1849 error("%s", pcap_geterr(pd));
1850 #ifdef HAVE_CAPSICUM
1851 if (RFileName == NULL && VFileName == NULL) {
1852 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
1853
1854 /*
1855 * The various libpcap devices use a combination of
1856 * read (bpf), ioctl (bpf, netmap), poll (netmap)
1857 * so we add the relevant access rights.
1858 */
1859 cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT);
1860 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1861 errno != ENOSYS) {
1862 error("unable to limit pcap descriptor");
1863 }
1864 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1865 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1866 error("unable to limit ioctls on pcap descriptor");
1867 }
1868 }
1869 #endif
1870 if (WFileName) {
1871 pcap_dumper_t *p;
1872 /* Do not exceed the default PATH_MAX for files. */
1873 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1874
1875 if (dumpinfo.CurrentFileName == NULL)
1876 error("malloc of dumpinfo.CurrentFileName");
1877
1878 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1879 if (Cflag != 0)
1880 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1881 else
1882 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1883
1884 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1885 #ifdef HAVE_LIBCAP_NG
1886 /* Give up CAP_DAC_OVERRIDE capability.
1887 * Only allow it to be restored if the -C or -G flag have been
1888 * set since we may need to create more files later on.
1889 */
1890 capng_update(
1891 CAPNG_DROP,
1892 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1893 | CAPNG_EFFECTIVE,
1894 CAP_DAC_OVERRIDE
1895 );
1896 capng_apply(CAPNG_SELECT_BOTH);
1897 #endif /* HAVE_LIBCAP_NG */
1898 if (p == NULL)
1899 error("%s", pcap_geterr(pd));
1900 #ifdef HAVE_CAPSICUM
1901 set_dumper_capsicum_rights(p);
1902 #endif
1903 if (Cflag != 0 || Gflag != 0) {
1904 #ifdef HAVE_CAPSICUM
1905 dumpinfo.WFileName = strdup(basename(WFileName));
1906 if (dumpinfo.WFileName == NULL) {
1907 error("Unable to allocate memory for file %s",
1908 WFileName);
1909 }
1910 dumpinfo.dirfd = open(dirname(WFileName),
1911 O_DIRECTORY | O_RDONLY);
1912 if (dumpinfo.dirfd < 0) {
1913 error("unable to open directory %s",
1914 dirname(WFileName));
1915 }
1916 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1917 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1918 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1919 errno != ENOSYS) {
1920 error("unable to limit directory rights");
1921 }
1922 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1923 errno != ENOSYS) {
1924 error("unable to limit dump descriptor fcntls");
1925 }
1926 #else /* !HAVE_CAPSICUM */
1927 dumpinfo.WFileName = WFileName;
1928 #endif
1929 callback = dump_packet_and_trunc;
1930 dumpinfo.pd = pd;
1931 dumpinfo.p = p;
1932 pcap_userdata = (u_char *)&dumpinfo;
1933 } else {
1934 callback = dump_packet;
1935 pcap_userdata = (u_char *)p;
1936 }
1937 #ifdef HAVE_PCAP_DUMP_FLUSH
1938 if (Uflag)
1939 pcap_dump_flush(p);
1940 #endif
1941 } else {
1942 dlt = pcap_datalink(pd);
1943 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1944 callback = print_packet;
1945 pcap_userdata = (u_char *)ndo;
1946 }
1947
1948 #ifdef SIGNAL_REQ_INFO
1949 /*
1950 * We can't get statistics when reading from a file rather
1951 * than capturing from a device.
1952 */
1953 if (RFileName == NULL)
1954 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1955 #endif
1956
1957 if (ndo->ndo_vflag > 0 && WFileName) {
1958 /*
1959 * When capturing to a file, "-v" means tcpdump should,
1960 * every 10 seconds, "v"erbosely report the number of
1961 * packets captured.
1962 */
1963 #ifdef USE_WIN32_MM_TIMER
1964 /* call verbose_stats_dump() each 1000 +/-100msec */
1965 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1966 setvbuf(stderr, NULL, _IONBF, 0);
1967 #elif defined(HAVE_ALARM)
1968 (void)setsignal(SIGALRM, verbose_stats_dump);
1969 alarm(1);
1970 #endif
1971 }
1972
1973 if (RFileName == NULL) {
1974 /*
1975 * Live capture (if -V was specified, we set RFileName
1976 * to a file from the -V file). Print a message to
1977 * the standard error on UN*X.
1978 */
1979 if (!ndo->ndo_vflag && !WFileName) {
1980 (void)fprintf(stderr,
1981 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1982 program_name);
1983 } else
1984 (void)fprintf(stderr, "%s: ", program_name);
1985 dlt = pcap_datalink(pd);
1986 dlt_name = pcap_datalink_val_to_name(dlt);
1987 if (dlt_name == NULL) {
1988 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1989 device, dlt, ndo->ndo_snaplen);
1990 } else {
1991 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1992 device, dlt_name,
1993 pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
1994 }
1995 (void)fflush(stderr);
1996 }
1997
1998 #ifdef HAVE_CAPSICUM
1999 cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL);
2000 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
2001 error("unable to enter the capability mode");
2002 #endif /* HAVE_CAPSICUM */
2003
2004 do {
2005 status = pcap_loop(pd, cnt, callback, pcap_userdata);
2006 if (WFileName == NULL) {
2007 /*
2008 * We're printing packets. Flush the printed output,
2009 * so it doesn't get intermingled with error output.
2010 */
2011 if (status == -2) {
2012 /*
2013 * We got interrupted, so perhaps we didn't
2014 * manage to finish a line we were printing.
2015 * Print an extra newline, just in case.
2016 */
2017 putchar('\n');
2018 }
2019 (void)fflush(stdout);
2020 }
2021 if (status == -2) {
2022 /*
2023 * We got interrupted. If we are reading multiple
2024 * files (via -V) set these so that we stop.
2025 */
2026 VFileName = NULL;
2027 ret = NULL;
2028 }
2029 if (status == -1) {
2030 /*
2031 * Error. Report it.
2032 */
2033 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
2034 program_name, pcap_geterr(pd));
2035 }
2036 if (RFileName == NULL) {
2037 /*
2038 * We're doing a live capture. Report the capture
2039 * statistics.
2040 */
2041 info(1);
2042 }
2043 pcap_close(pd);
2044 if (VFileName != NULL) {
2045 ret = get_next_file(VFile, VFileLine);
2046 if (ret) {
2047 int new_dlt;
2048
2049 RFileName = VFileLine;
2050 pd = pcap_open_offline(RFileName, ebuf);
2051 if (pd == NULL)
2052 error("%s", ebuf);
2053 #ifdef HAVE_CAPSICUM
2054 cap_rights_init(&rights, CAP_READ);
2055 if (cap_rights_limit(fileno(pcap_file(pd)),
2056 &rights) < 0 && errno != ENOSYS) {
2057 error("unable to limit pcap descriptor");
2058 }
2059 #endif
2060 new_dlt = pcap_datalink(pd);
2061 if (new_dlt != dlt) {
2062 /*
2063 * The new file has a different
2064 * link-layer header type from the
2065 * previous one.
2066 */
2067 if (WFileName != NULL) {
2068 /*
2069 * We're writing raw packets
2070 * that match the filter to
2071 * a pcap file. pcap files
2072 * don't support multiple
2073 * different link-layer
2074 * header types, so we fail
2075 * here.
2076 */
2077 error("%s: new dlt does not match original", RFileName);
2078 }
2079
2080 /*
2081 * We're printing the decoded packets;
2082 * switch to the new DLT.
2083 *
2084 * To do that, we need to change
2085 * the printer, change the DLT name,
2086 * and recompile the filter with
2087 * the new DLT.
2088 */
2089 dlt = new_dlt;
2090 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
2091 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2092 error("%s", pcap_geterr(pd));
2093 }
2094
2095 /*
2096 * Set the filter on the new file.
2097 */
2098 if (pcap_setfilter(pd, &fcode) < 0)
2099 error("%s", pcap_geterr(pd));
2100
2101 /*
2102 * Report the new file.
2103 */
2104 dlt_name = pcap_datalink_val_to_name(dlt);
2105 if (dlt_name == NULL) {
2106 fprintf(stderr, "reading from file %s, link-type %u\n",
2107 RFileName, dlt);
2108 } else {
2109 fprintf(stderr,
2110 "reading from file %s, link-type %s (%s)\n",
2111 RFileName, dlt_name,
2112 pcap_datalink_val_to_description(dlt));
2113 }
2114 }
2115 }
2116 }
2117 while (ret != NULL);
2118
2119 free(cmdbuf);
2120 pcap_freecode(&fcode);
2121 exit_tcpdump(status == -1 ? 1 : 0);
2122 }
2123
2124 /* make a clean exit on interrupts */
2125 static RETSIGTYPE
2126 cleanup(int signo _U_)
2127 {
2128 #ifdef USE_WIN32_MM_TIMER
2129 if (timer_id)
2130 timeKillEvent(timer_id);
2131 timer_id = 0;
2132 #elif defined(HAVE_ALARM)
2133 alarm(0);
2134 #endif
2135
2136 #ifdef HAVE_PCAP_BREAKLOOP
2137 /*
2138 * We have "pcap_breakloop()"; use it, so that we do as little
2139 * as possible in the signal handler (it's probably not safe
2140 * to do anything with standard I/O streams in a signal handler -
2141 * the ANSI C standard doesn't say it is).
2142 */
2143 pcap_breakloop(pd);
2144 #else
2145 /*
2146 * We don't have "pcap_breakloop()"; this isn't safe, but
2147 * it's the best we can do. Print the summary if we're
2148 * not reading from a savefile - i.e., if we're doing a
2149 * live capture - and exit.
2150 */
2151 if (pd != NULL && pcap_file(pd) == NULL) {
2152 /*
2153 * We got interrupted, so perhaps we didn't
2154 * manage to finish a line we were printing.
2155 * Print an extra newline, just in case.
2156 */
2157 putchar('\n');
2158 (void)fflush(stdout);
2159 info(1);
2160 }
2161 exit_tcpdump(0);
2162 #endif
2163 }
2164
2165 /*
2166 On windows, we do not use a fork, so we do not care less about
2167 waiting a child processes to die
2168 */
2169 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2170 static RETSIGTYPE
2171 child_cleanup(int signo _U_)
2172 {
2173 wait(NULL);
2174 }
2175 #endif /* HAVE_FORK && HAVE_VFORK */
2176
2177 static void
2178 info(register int verbose)
2179 {
2180 struct pcap_stat stats;
2181
2182 /*
2183 * Older versions of libpcap didn't set ps_ifdrop on some
2184 * platforms; initialize it to 0 to handle that.
2185 */
2186 stats.ps_ifdrop = 0;
2187 if (pcap_stats(pd, &stats) < 0) {
2188 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2189 infoprint = 0;
2190 return;
2191 }
2192
2193 if (!verbose)
2194 fprintf(stderr, "%s: ", program_name);
2195
2196 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
2197 PLURAL_SUFFIX(packets_captured));
2198 if (!verbose)
2199 fputs(", ", stderr);
2200 else
2201 putc('\n', stderr);
2202 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
2203 PLURAL_SUFFIX(stats.ps_recv));
2204 if (!verbose)
2205 fputs(", ", stderr);
2206 else
2207 putc('\n', stderr);
2208 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
2209 PLURAL_SUFFIX(stats.ps_drop));
2210 if (stats.ps_ifdrop != 0) {
2211 if (!verbose)
2212 fputs(", ", stderr);
2213 else
2214 putc('\n', stderr);
2215 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
2216 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
2217 } else
2218 putc('\n', stderr);
2219 infoprint = 0;
2220 }
2221
2222 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2223 #ifdef HAVE_FORK
2224 #define fork_subprocess() fork()
2225 #else
2226 #define fork_subprocess() vfork()
2227 #endif
2228 static void
2229 compress_savefile(const char *filename)
2230 {
2231 pid_t child;
2232
2233 child = fork_subprocess();
2234 if (child == -1) {
2235 fprintf(stderr,
2236 "compress_savefile: fork failed: %s\n",
2237 pcap_strerror(errno));
2238 return;
2239 }
2240 if (child != 0) {
2241 /* Parent process. */
2242 return;
2243 }
2244
2245 /*
2246 * Child process.
2247 * Set to lowest priority so that this doesn't disturb the capture.
2248 */
2249 #ifdef NZERO
2250 setpriority(PRIO_PROCESS, 0, NZERO - 1);
2251 #else
2252 setpriority(PRIO_PROCESS, 0, 19);
2253 #endif
2254 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2255 fprintf(stderr,
2256 "compress_savefile: execlp(%s, %s) failed: %s\n",
2257 zflag,
2258 filename,
2259 pcap_strerror(errno));
2260 #ifdef HAVE_FORK
2261 exit(1);
2262 #else
2263 _exit(1);
2264 #endif
2265 }
2266 #else /* HAVE_FORK && HAVE_VFORK */
2267 static void
2268 compress_savefile(const char *filename)
2269 {
2270 fprintf(stderr,
2271 "compress_savefile failed. Functionality not implemented under your system\n");
2272 }
2273 #endif /* HAVE_FORK && HAVE_VFORK */
2274
2275 static void
2276 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2277 {
2278 struct dump_info *dump_info;
2279
2280 ++packets_captured;
2281
2282 ++infodelay;
2283
2284 dump_info = (struct dump_info *)user;
2285
2286 /*
2287 * XXX - this won't force the file to rotate on the specified time
2288 * boundary, but it will rotate on the first packet received after the
2289 * specified Gflag number of seconds. Note: if a Gflag time boundary
2290 * and a Cflag size boundary coincide, the time rotation will occur
2291 * first thereby cancelling the Cflag boundary (since the file should
2292 * be 0).
2293 */
2294 if (Gflag != 0) {
2295 /* Check if it is time to rotate */
2296 time_t t;
2297
2298 /* Get the current time */
2299 if ((t = time(NULL)) == (time_t)-1) {
2300 error("dump_and_trunc_packet: can't get current_time: %s",
2301 pcap_strerror(errno));
2302 }
2303
2304
2305 /* If the time is greater than the specified window, rotate */
2306 if (t - Gflag_time >= Gflag) {
2307 #ifdef HAVE_CAPSICUM
2308 FILE *fp;
2309 int fd;
2310 #endif
2311
2312 /* Update the Gflag_time */
2313 Gflag_time = t;
2314 /* Update Gflag_count */
2315 Gflag_count++;
2316 /*
2317 * Close the current file and open a new one.
2318 */
2319 pcap_dump_close(dump_info->p);
2320
2321 /*
2322 * Compress the file we just closed, if the user asked for it
2323 */
2324 if (zflag != NULL)
2325 compress_savefile(dump_info->CurrentFileName);
2326
2327 /*
2328 * Check to see if we've exceeded the Wflag (when
2329 * not using Cflag).
2330 */
2331 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2332 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2333 Wflag);
2334 info(1);
2335 exit_tcpdump(0);
2336 /* NOTREACHED */
2337 }
2338 if (dump_info->CurrentFileName != NULL)
2339 free(dump_info->CurrentFileName);
2340 /* Allocate space for max filename + \0. */
2341 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2342 if (dump_info->CurrentFileName == NULL)
2343 error("dump_packet_and_trunc: malloc");
2344 /*
2345 * Gflag was set otherwise we wouldn't be here. Reset the count
2346 * so multiple files would end with 1,2,3 in the filename.
2347 * The counting is handled with the -C flow after this.
2348 */
2349 Cflag_count = 0;
2350
2351 /*
2352 * This is always the first file in the Cflag
2353 * rotation: e.g. 0
2354 * We also don't need numbering if Cflag is not set.
2355 */
2356 if (Cflag != 0)
2357 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2358 WflagChars);
2359 else
2360 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2361
2362 #ifdef HAVE_LIBCAP_NG
2363 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2364 capng_apply(CAPNG_SELECT_BOTH);
2365 #endif /* HAVE_LIBCAP_NG */
2366 #ifdef HAVE_CAPSICUM
2367 fd = openat(dump_info->dirfd,
2368 dump_info->CurrentFileName,
2369 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2370 if (fd < 0) {
2371 error("unable to open file %s",
2372 dump_info->CurrentFileName);
2373 }
2374 fp = fdopen(fd, "w");
2375 if (fp == NULL) {
2376 error("unable to fdopen file %s",
2377 dump_info->CurrentFileName);
2378 }
2379 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2380 #else /* !HAVE_CAPSICUM */
2381 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2382 #endif
2383 #ifdef HAVE_LIBCAP_NG
2384 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2385 capng_apply(CAPNG_SELECT_BOTH);
2386 #endif /* HAVE_LIBCAP_NG */
2387 if (dump_info->p == NULL)
2388 error("%s", pcap_geterr(pd));
2389 #ifdef HAVE_CAPSICUM
2390 set_dumper_capsicum_rights(dump_info->p);
2391 #endif
2392 }
2393 }
2394
2395 /*
2396 * XXX - this won't prevent capture files from getting
2397 * larger than Cflag - the last packet written to the
2398 * file could put it over Cflag.
2399 */
2400 if (Cflag != 0) {
2401 long size = pcap_dump_ftell(dump_info->p);
2402
2403 if (size == -1)
2404 error("ftell fails on output file");
2405 if (size > Cflag) {
2406 #ifdef HAVE_CAPSICUM
2407 FILE *fp;
2408 int fd;
2409 #endif
2410
2411 /*
2412 * Close the current file and open a new one.
2413 */
2414 pcap_dump_close(dump_info->p);
2415
2416 /*
2417 * Compress the file we just closed, if the user
2418 * asked for it.
2419 */
2420 if (zflag != NULL)
2421 compress_savefile(dump_info->CurrentFileName);
2422
2423 Cflag_count++;
2424 if (Wflag > 0) {
2425 if (Cflag_count >= Wflag)
2426 Cflag_count = 0;
2427 }
2428 if (dump_info->CurrentFileName != NULL)
2429 free(dump_info->CurrentFileName);
2430 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2431 if (dump_info->CurrentFileName == NULL)
2432 error("dump_packet_and_trunc: malloc");
2433 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2434 #ifdef HAVE_LIBCAP_NG
2435 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2436 capng_apply(CAPNG_SELECT_BOTH);
2437 #endif /* HAVE_LIBCAP_NG */
2438 #ifdef HAVE_CAPSICUM
2439 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2440 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2441 if (fd < 0) {
2442 error("unable to open file %s",
2443 dump_info->CurrentFileName);
2444 }
2445 fp = fdopen(fd, "w");
2446 if (fp == NULL) {
2447 error("unable to fdopen file %s",
2448 dump_info->CurrentFileName);
2449 }
2450 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2451 #else /* !HAVE_CAPSICUM */
2452 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2453 #endif
2454 #ifdef HAVE_LIBCAP_NG
2455 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2456 capng_apply(CAPNG_SELECT_BOTH);
2457 #endif /* HAVE_LIBCAP_NG */
2458 if (dump_info->p == NULL)
2459 error("%s", pcap_geterr(pd));
2460 #ifdef HAVE_CAPSICUM
2461 set_dumper_capsicum_rights(dump_info->p);
2462 #endif
2463 }
2464 }
2465
2466 pcap_dump((u_char *)dump_info->p, h, sp);
2467 #ifdef HAVE_PCAP_DUMP_FLUSH
2468 if (Uflag)
2469 pcap_dump_flush(dump_info->p);
2470 #endif
2471
2472 --infodelay;
2473 if (infoprint)
2474 info(0);
2475 }
2476
2477 static void
2478 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2479 {
2480 ++packets_captured;
2481
2482 ++infodelay;
2483
2484 pcap_dump(user, h, sp);
2485 #ifdef HAVE_PCAP_DUMP_FLUSH
2486 if (Uflag)
2487 pcap_dump_flush((pcap_dumper_t *)user);
2488 #endif
2489
2490 --infodelay;
2491 if (infoprint)
2492 info(0);
2493 }
2494
2495 static void
2496 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2497 {
2498 ++packets_captured;
2499
2500 ++infodelay;
2501
2502 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2503
2504 --infodelay;
2505 if (infoprint)
2506 info(0);
2507 }
2508
2509 #ifdef _WIN32
2510 /*
2511 * XXX - there should really be libpcap calls to get the version
2512 * number as a string (the string would be generated from #defines
2513 * at run time, so that it's not generated from string constants
2514 * in the library, as, on many UNIX systems, those constants would
2515 * be statically linked into the application executable image, and
2516 * would thus reflect the version of libpcap on the system on
2517 * which the application was *linked*, not the system on which it's
2518 * *running*.
2519 *
2520 * That routine should be documented, unlike the "version[]"
2521 * string, so that UNIX vendors providing their own libpcaps
2522 * don't omit it (as a couple of vendors have...).
2523 *
2524 * Packet.dll should perhaps also export a routine to return the
2525 * version number of the Packet.dll code, to supply the
2526 * "Wpcap_version" information on Windows.
2527 */
2528 char WDversion[]="current-git.tcpdump.org";
2529 #if !defined(HAVE_GENERATED_VERSION)
2530 char version[]="current-git.tcpdump.org";
2531 #endif
2532 char pcap_version[]="current-git.tcpdump.org";
2533 char Wpcap_version[]="3.1";
2534 #endif
2535
2536 #ifdef SIGNAL_REQ_INFO
2537 RETSIGTYPE requestinfo(int signo _U_)
2538 {
2539 if (infodelay)
2540 ++infoprint;
2541 else
2542 info(0);
2543 }
2544 #endif
2545
2546 /*
2547 * Called once each second in verbose mode while dumping to file
2548 */
2549 #ifdef USE_WIN32_MM_TIMER
2550 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2551 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2552 {
2553 if (infodelay == 0)
2554 fprintf(stderr, "Got %u\r", packets_captured);
2555 }
2556 #elif defined(HAVE_ALARM)
2557 static void verbose_stats_dump(int sig _U_)
2558 {
2559 if (infodelay == 0)
2560 fprintf(stderr, "Got %u\r", packets_captured);
2561 alarm(1);
2562 }
2563 #endif
2564
2565 USES_APPLE_DEPRECATED_API
2566 static void
2567 print_version(void)
2568 {
2569 extern char version[];
2570 #ifndef HAVE_PCAP_LIB_VERSION
2571 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2572 extern char pcap_version[];
2573 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2574 static char pcap_version[] = "unknown";
2575 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2576 #endif /* HAVE_PCAP_LIB_VERSION */
2577 const char *smi_version_string;
2578
2579 #ifdef HAVE_PCAP_LIB_VERSION
2580 #ifdef _WIN32
2581 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2582 #else /* _WIN32 */
2583 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2584 #endif /* _WIN32 */
2585 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2586 #else /* HAVE_PCAP_LIB_VERSION */
2587 #ifdef _WIN32
2588 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2589 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2590 #else /* _WIN32 */
2591 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2592 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2593 #endif /* _WIN32 */
2594 #endif /* HAVE_PCAP_LIB_VERSION */
2595
2596 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2597 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2598 #endif
2599
2600 smi_version_string = nd_smi_version_string();
2601 if (smi_version_string != NULL)
2602 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2603
2604 #if defined(__SANITIZE_ADDRESS__)
2605 (void)fprintf (stderr, "Compiled with AddressSanitizer/GCC.\n");
2606 #elif defined(__has_feature)
2607 # if __has_feature(address_sanitizer)
2608 (void)fprintf (stderr, "Compiled with AddressSanitizer/CLang.\n");
2609 # endif
2610 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2611 }
2612 USES_APPLE_RST
2613
2614 static void
2615 print_usage(void)
2616 {
2617 print_version();
2618 (void)fprintf(stderr,
2619 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2620 (void)fprintf(stderr,
2621 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2622 (void)fprintf(stderr,
2623 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2624 #ifdef HAVE_PCAP_SETDIRECTION
2625 (void)fprintf(stderr,
2626 "\t\t[ -Q in|out|inout ]\n");
2627 #endif
2628 (void)fprintf(stderr,
2629 "\t\t[ -r file ] [ -s snaplen ] ");
2630 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2631 (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2632 (void)fprintf(stderr,
2633 "\t\t");
2634 #endif
2635 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2636 (void)fprintf(stderr, "[ --immediate-mode ] ");
2637 #endif
2638 (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2639 (void)fprintf(stderr,
2640 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n");
2641 (void)fprintf(stderr,
2642 "\t\t[ -Z user ] [ expression ]\n");
2643 }
2644 /*
2645 * Local Variables:
2646 * c-style: whitesmith
2647 * c-basic-offset: 8
2648 * End:
2649 */