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