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