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