ping.c revision 330897
1/*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1989, 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Mike Muuss. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 4. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35#if 0 36#ifndef lint 37static const char copyright[] = 38"@(#) Copyright (c) 1989, 1993\n\ 39 The Regents of the University of California. All rights reserved.\n"; 40#endif /* not lint */ 41 42#ifndef lint 43static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; 44#endif /* not lint */ 45#endif 46#include <sys/cdefs.h> 47__FBSDID("$FreeBSD: stable/11/sbin/ping/ping.c 330897 2018-03-14 03:19:51Z eadler $"); 48 49/* 50 * P I N G . C 51 * 52 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility, 53 * measure round-trip-delays and packet loss across network paths. 54 * 55 * Author - 56 * Mike Muuss 57 * U. S. Army Ballistic Research Laboratory 58 * December, 1983 59 * 60 * Status - 61 * Public Domain. Distribution Unlimited. 62 * Bugs - 63 * More statistics could always be gathered. 64 * This program has to run SUID to ROOT to access the ICMP socket. 65 */ 66 67#include <sys/param.h> /* NB: we rely on this for <sys/types.h> */ 68#include <sys/capsicum.h> 69#include <sys/socket.h> 70#include <sys/sysctl.h> 71#include <sys/time.h> 72#include <sys/uio.h> 73 74#include <netinet/in.h> 75#include <netinet/in_systm.h> 76#include <netinet/ip.h> 77#include <netinet/ip_icmp.h> 78#include <netinet/ip_var.h> 79#include <arpa/inet.h> 80 81#ifdef HAVE_LIBCASPER 82#include <libcasper.h> 83#include <casper/cap_dns.h> 84#endif 85 86#ifdef IPSEC 87#include <netipsec/ipsec.h> 88#endif /*IPSEC*/ 89 90#include <ctype.h> 91#include <err.h> 92#include <errno.h> 93#include <math.h> 94#include <netdb.h> 95#include <signal.h> 96#include <stdio.h> 97#include <stdlib.h> 98#include <string.h> 99#include <sysexits.h> 100#include <unistd.h> 101 102#define INADDR_LEN ((int)sizeof(in_addr_t)) 103#define TIMEVAL_LEN ((int)sizeof(struct tv32)) 104#define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN) 105#define TS_LEN (ICMP_TSLEN - ICMP_MINLEN) 106#define DEFDATALEN 56 /* default data length */ 107#define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */ 108 /* runs out of buffer space */ 109#define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN) 110#define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN) 111#define MAXWAIT 10000 /* max ms to wait for response */ 112#define MAXALARM (60 * 60) /* max seconds for alarm timeout */ 113#define MAXTOS 255 114 115#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ 116#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ 117#define SET(bit) (A(bit) |= B(bit)) 118#define CLR(bit) (A(bit) &= (~B(bit))) 119#define TST(bit) (A(bit) & B(bit)) 120 121struct tv32 { 122 int32_t tv32_sec; 123 int32_t tv32_usec; 124}; 125 126/* various options */ 127static int options; 128#define F_FLOOD 0x0001 129#define F_INTERVAL 0x0002 130#define F_NUMERIC 0x0004 131#define F_PINGFILLED 0x0008 132#define F_QUIET 0x0010 133#define F_RROUTE 0x0020 134#define F_SO_DEBUG 0x0040 135#define F_SO_DONTROUTE 0x0080 136#define F_VERBOSE 0x0100 137#define F_QUIET2 0x0200 138#define F_NOLOOP 0x0400 139#define F_MTTL 0x0800 140#define F_MIF 0x1000 141#define F_AUDIBLE 0x2000 142#ifdef IPSEC 143#ifdef IPSEC_POLICY_IPSEC 144#define F_POLICY 0x4000 145#endif /*IPSEC_POLICY_IPSEC*/ 146#endif /*IPSEC*/ 147#define F_TTL 0x8000 148#define F_MISSED 0x10000 149#define F_ONCE 0x20000 150#define F_HDRINCL 0x40000 151#define F_MASK 0x80000 152#define F_TIME 0x100000 153#define F_SWEEP 0x200000 154#define F_WAITTIME 0x400000 155 156/* 157 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum 158 * number of received sequence numbers we can keep track of. Change 128 159 * to 8192 for complete accuracy... 160 */ 161#define MAX_DUP_CHK (8 * 128) 162static int mx_dup_ck = MAX_DUP_CHK; 163static char rcvd_tbl[MAX_DUP_CHK / 8]; 164 165static struct sockaddr_in whereto; /* who to ping */ 166static int datalen = DEFDATALEN; 167static int maxpayload; 168static int ssend; /* send socket file descriptor */ 169static int srecv; /* receive socket file descriptor */ 170static u_char outpackhdr[IP_MAXPACKET], *outpack; 171static char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */ 172static char BSPACE = '\b'; /* characters written for flood */ 173static char DOT = '.'; 174static char *hostname; 175static char *shostname; 176static int ident; /* process id to identify our packets */ 177static int uid; /* cached uid for micro-optimization */ 178static u_char icmp_type = ICMP_ECHO; 179static u_char icmp_type_rsp = ICMP_ECHOREPLY; 180static int phdr_len = 0; 181static int send_len; 182 183/* counters */ 184static long nmissedmax; /* max value of ntransmitted - nreceived - 1 */ 185static long npackets; /* max packets to transmit */ 186static long nreceived; /* # of packets we got back */ 187static long nrepeats; /* number of duplicates */ 188static long ntransmitted; /* sequence # for outbound packets = #sent */ 189static long snpackets; /* max packets to transmit in one sweep */ 190static long sntransmitted; /* # of packets we sent in this sweep */ 191static int sweepmax; /* max value of payload in sweep */ 192static int sweepmin = 0; /* start value of payload in sweep */ 193static int sweepincr = 1; /* payload increment in sweep */ 194static int interval = 1000; /* interval between packets, ms */ 195static int waittime = MAXWAIT; /* timeout for each packet */ 196static long nrcvtimeout = 0; /* # of packets we got back after waittime */ 197 198/* timing */ 199static int timing; /* flag to do timing */ 200static double tmin = 999999999.0; /* minimum round trip time */ 201static double tmax = 0.0; /* maximum round trip time */ 202static double tsum = 0.0; /* sum of all times, for doing average */ 203static double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ 204 205/* nonzero if we've been told to finish up */ 206static volatile sig_atomic_t finish_up; 207static volatile sig_atomic_t siginfo_p; 208 209#ifdef HAVE_LIBCASPER 210static cap_channel_t *capdns; 211#endif 212 213static void fill(char *, char *); 214static u_short in_cksum(u_short *, int); 215#ifdef HAVE_LIBCASPER 216static cap_channel_t *capdns_setup(void); 217#endif 218static void check_status(void); 219static void finish(void) __dead2; 220static void pinger(void); 221static char *pr_addr(struct in_addr); 222static char *pr_ntime(n_time); 223static void pr_icmph(struct icmp *); 224static void pr_iph(struct ip *); 225static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *); 226static void pr_retip(struct ip *); 227static void status(int); 228static void stopit(int); 229static void tvsub(struct timeval *, const struct timeval *); 230static void usage(void) __dead2; 231 232int 233main(int argc, char *const *argv) 234{ 235 struct sockaddr_in from, sock_in; 236 struct in_addr ifaddr; 237 struct timeval last, intvl; 238 struct iovec iov; 239 struct ip *ip; 240 struct msghdr msg; 241 struct sigaction si_sa; 242 size_t sz; 243 u_char *datap, packet[IP_MAXPACKET] __aligned(4); 244 char *ep, *source, *target, *payload; 245 struct hostent *hp; 246#ifdef IPSEC_POLICY_IPSEC 247 char *policy_in, *policy_out; 248#endif 249 struct sockaddr_in *to; 250 double t; 251 u_long alarmtimeout, ultmp; 252 int almost_done, ch, df, hold, i, icmp_len, mib[4], preload; 253 int ssend_errno, srecv_errno, tos, ttl; 254 char ctrl[CMSG_SPACE(sizeof(struct timeval))]; 255 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN]; 256#ifdef IP_OPTIONS 257 char rspace[MAX_IPOPTLEN]; /* record route space */ 258#endif 259 unsigned char loop, mttl; 260 261 payload = source = NULL; 262#ifdef IPSEC_POLICY_IPSEC 263 policy_in = policy_out = NULL; 264#endif 265 cap_rights_t rights; 266 bool cansandbox; 267 268 /* 269 * Do the stuff that we need root priv's for *first*, and 270 * then drop our setuid bit. Save error reporting for 271 * after arg parsing. 272 * 273 * Historicaly ping was using one socket 's' for sending and for 274 * receiving. After capsicum(4) related changes we use two 275 * sockets. It was done for special ping use case - when user 276 * issue ping on multicast or broadcast address replies come 277 * from different addresses, not from the address we 278 * connect(2)'ed to, and send socket do not receive those 279 * packets. 280 */ 281 ssend = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 282 ssend_errno = errno; 283 srecv = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 284 srecv_errno = errno; 285 286 if (setuid(getuid()) != 0) 287 err(EX_NOPERM, "setuid() failed"); 288 uid = getuid(); 289 290 if (ssend < 0) { 291 errno = ssend_errno; 292 err(EX_OSERR, "ssend socket"); 293 } 294 295 if (srecv < 0) { 296 errno = srecv_errno; 297 err(EX_OSERR, "srecv socket"); 298 } 299 300 alarmtimeout = df = preload = tos = 0; 301 302 outpack = outpackhdr + sizeof(struct ip); 303 while ((ch = getopt(argc, argv, 304 "Aac:DdfG:g:h:I:i:Ll:M:m:nop:QqRrS:s:T:t:vW:z:" 305#ifdef IPSEC 306#ifdef IPSEC_POLICY_IPSEC 307 "P:" 308#endif /*IPSEC_POLICY_IPSEC*/ 309#endif /*IPSEC*/ 310 )) != -1) 311 { 312 switch(ch) { 313 case 'A': 314 options |= F_MISSED; 315 break; 316 case 'a': 317 options |= F_AUDIBLE; 318 break; 319 case 'c': 320 ultmp = strtoul(optarg, &ep, 0); 321 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp) 322 errx(EX_USAGE, 323 "invalid count of packets to transmit: `%s'", 324 optarg); 325 npackets = ultmp; 326 break; 327 case 'D': 328 options |= F_HDRINCL; 329 df = 1; 330 break; 331 case 'd': 332 options |= F_SO_DEBUG; 333 break; 334 case 'f': 335 if (uid) { 336 errno = EPERM; 337 err(EX_NOPERM, "-f flag"); 338 } 339 options |= F_FLOOD; 340 setbuf(stdout, (char *)NULL); 341 break; 342 case 'G': /* Maximum packet size for ping sweep */ 343 ultmp = strtoul(optarg, &ep, 0); 344 if (*ep || ep == optarg) 345 errx(EX_USAGE, "invalid packet size: `%s'", 346 optarg); 347 if (uid != 0 && ultmp > DEFDATALEN) { 348 errno = EPERM; 349 err(EX_NOPERM, 350 "packet size too large: %lu > %u", 351 ultmp, DEFDATALEN); 352 } 353 options |= F_SWEEP; 354 sweepmax = ultmp; 355 break; 356 case 'g': /* Minimum packet size for ping sweep */ 357 ultmp = strtoul(optarg, &ep, 0); 358 if (*ep || ep == optarg) 359 errx(EX_USAGE, "invalid packet size: `%s'", 360 optarg); 361 if (uid != 0 && ultmp > DEFDATALEN) { 362 errno = EPERM; 363 err(EX_NOPERM, 364 "packet size too large: %lu > %u", 365 ultmp, DEFDATALEN); 366 } 367 options |= F_SWEEP; 368 sweepmin = ultmp; 369 break; 370 case 'h': /* Packet size increment for ping sweep */ 371 ultmp = strtoul(optarg, &ep, 0); 372 if (*ep || ep == optarg || ultmp < 1) 373 errx(EX_USAGE, "invalid increment size: `%s'", 374 optarg); 375 if (uid != 0 && ultmp > DEFDATALEN) { 376 errno = EPERM; 377 err(EX_NOPERM, 378 "packet size too large: %lu > %u", 379 ultmp, DEFDATALEN); 380 } 381 options |= F_SWEEP; 382 sweepincr = ultmp; 383 break; 384 case 'I': /* multicast interface */ 385 if (inet_aton(optarg, &ifaddr) == 0) 386 errx(EX_USAGE, 387 "invalid multicast interface: `%s'", 388 optarg); 389 options |= F_MIF; 390 break; 391 case 'i': /* wait between sending packets */ 392 t = strtod(optarg, &ep) * 1000.0; 393 if (*ep || ep == optarg || t > (double)INT_MAX) 394 errx(EX_USAGE, "invalid timing interval: `%s'", 395 optarg); 396 options |= F_INTERVAL; 397 interval = (int)t; 398 if (uid && interval < 1000) { 399 errno = EPERM; 400 err(EX_NOPERM, "-i interval too short"); 401 } 402 break; 403 case 'L': 404 options |= F_NOLOOP; 405 loop = 0; 406 break; 407 case 'l': 408 ultmp = strtoul(optarg, &ep, 0); 409 if (*ep || ep == optarg || ultmp > INT_MAX) 410 errx(EX_USAGE, 411 "invalid preload value: `%s'", optarg); 412 if (uid) { 413 errno = EPERM; 414 err(EX_NOPERM, "-l flag"); 415 } 416 preload = ultmp; 417 break; 418 case 'M': 419 switch(optarg[0]) { 420 case 'M': 421 case 'm': 422 options |= F_MASK; 423 break; 424 case 'T': 425 case 't': 426 options |= F_TIME; 427 break; 428 default: 429 errx(EX_USAGE, "invalid message: `%c'", optarg[0]); 430 break; 431 } 432 break; 433 case 'm': /* TTL */ 434 ultmp = strtoul(optarg, &ep, 0); 435 if (*ep || ep == optarg || ultmp > MAXTTL) 436 errx(EX_USAGE, "invalid TTL: `%s'", optarg); 437 ttl = ultmp; 438 options |= F_TTL; 439 break; 440 case 'n': 441 options |= F_NUMERIC; 442 break; 443 case 'o': 444 options |= F_ONCE; 445 break; 446#ifdef IPSEC 447#ifdef IPSEC_POLICY_IPSEC 448 case 'P': 449 options |= F_POLICY; 450 if (!strncmp("in", optarg, 2)) 451 policy_in = strdup(optarg); 452 else if (!strncmp("out", optarg, 3)) 453 policy_out = strdup(optarg); 454 else 455 errx(1, "invalid security policy"); 456 break; 457#endif /*IPSEC_POLICY_IPSEC*/ 458#endif /*IPSEC*/ 459 case 'p': /* fill buffer with user pattern */ 460 options |= F_PINGFILLED; 461 payload = optarg; 462 break; 463 case 'Q': 464 options |= F_QUIET2; 465 break; 466 case 'q': 467 options |= F_QUIET; 468 break; 469 case 'R': 470 options |= F_RROUTE; 471 break; 472 case 'r': 473 options |= F_SO_DONTROUTE; 474 break; 475 case 'S': 476 source = optarg; 477 break; 478 case 's': /* size of packet to send */ 479 ultmp = strtoul(optarg, &ep, 0); 480 if (*ep || ep == optarg) 481 errx(EX_USAGE, "invalid packet size: `%s'", 482 optarg); 483 if (uid != 0 && ultmp > DEFDATALEN) { 484 errno = EPERM; 485 err(EX_NOPERM, 486 "packet size too large: %lu > %u", 487 ultmp, DEFDATALEN); 488 } 489 datalen = ultmp; 490 break; 491 case 'T': /* multicast TTL */ 492 ultmp = strtoul(optarg, &ep, 0); 493 if (*ep || ep == optarg || ultmp > MAXTTL) 494 errx(EX_USAGE, "invalid multicast TTL: `%s'", 495 optarg); 496 mttl = ultmp; 497 options |= F_MTTL; 498 break; 499 case 't': 500 alarmtimeout = strtoul(optarg, &ep, 0); 501 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX)) 502 errx(EX_USAGE, "invalid timeout: `%s'", 503 optarg); 504 if (alarmtimeout > MAXALARM) 505 errx(EX_USAGE, "invalid timeout: `%s' > %d", 506 optarg, MAXALARM); 507 alarm((int)alarmtimeout); 508 break; 509 case 'v': 510 options |= F_VERBOSE; 511 break; 512 case 'W': /* wait ms for answer */ 513 t = strtod(optarg, &ep); 514 if (*ep || ep == optarg || t > (double)INT_MAX) 515 errx(EX_USAGE, "invalid timing interval: `%s'", 516 optarg); 517 options |= F_WAITTIME; 518 waittime = (int)t; 519 break; 520 case 'z': 521 options |= F_HDRINCL; 522 ultmp = strtoul(optarg, &ep, 0); 523 if (*ep || ep == optarg || ultmp > MAXTOS) 524 errx(EX_USAGE, "invalid TOS: `%s'", optarg); 525 tos = ultmp; 526 break; 527 default: 528 usage(); 529 } 530 } 531 532 if (argc - optind != 1) 533 usage(); 534 target = argv[optind]; 535 536 switch (options & (F_MASK|F_TIME)) { 537 case 0: break; 538 case F_MASK: 539 icmp_type = ICMP_MASKREQ; 540 icmp_type_rsp = ICMP_MASKREPLY; 541 phdr_len = MASK_LEN; 542 if (!(options & F_QUIET)) 543 (void)printf("ICMP_MASKREQ\n"); 544 break; 545 case F_TIME: 546 icmp_type = ICMP_TSTAMP; 547 icmp_type_rsp = ICMP_TSTAMPREPLY; 548 phdr_len = TS_LEN; 549 if (!(options & F_QUIET)) 550 (void)printf("ICMP_TSTAMP\n"); 551 break; 552 default: 553 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive."); 554 break; 555 } 556 icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len; 557 if (options & F_RROUTE) 558 icmp_len += MAX_IPOPTLEN; 559 maxpayload = IP_MAXPACKET - icmp_len; 560 if (datalen > maxpayload) 561 errx(EX_USAGE, "packet size too large: %d > %d", datalen, 562 maxpayload); 563 send_len = icmp_len + datalen; 564 datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN]; 565 if (options & F_PINGFILLED) { 566 fill((char *)datap, payload); 567 } 568#ifdef HAVE_LIBCASPER 569 capdns = capdns_setup(); 570#endif 571 if (source) { 572 bzero((char *)&sock_in, sizeof(sock_in)); 573 sock_in.sin_family = AF_INET; 574 if (inet_aton(source, &sock_in.sin_addr) != 0) { 575 shostname = source; 576 } else { 577#ifdef HAVE_LIBCASPER 578 if (capdns != NULL) 579 hp = cap_gethostbyname2(capdns, source, 580 AF_INET); 581 else 582#endif 583 hp = gethostbyname2(source, AF_INET); 584 if (!hp) 585 errx(EX_NOHOST, "cannot resolve %s: %s", 586 source, hstrerror(h_errno)); 587 588 sock_in.sin_len = sizeof sock_in; 589 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) || 590 hp->h_length < 0) 591 errx(1, "gethostbyname2: illegal address"); 592 memcpy(&sock_in.sin_addr, hp->h_addr_list[0], 593 sizeof(sock_in.sin_addr)); 594 (void)strncpy(snamebuf, hp->h_name, 595 sizeof(snamebuf) - 1); 596 snamebuf[sizeof(snamebuf) - 1] = '\0'; 597 shostname = snamebuf; 598 } 599 if (bind(ssend, (struct sockaddr *)&sock_in, sizeof sock_in) == 600 -1) 601 err(1, "bind"); 602 } 603 604 bzero(&whereto, sizeof(whereto)); 605 to = &whereto; 606 to->sin_family = AF_INET; 607 to->sin_len = sizeof *to; 608 if (inet_aton(target, &to->sin_addr) != 0) { 609 hostname = target; 610 } else { 611#ifdef HAVE_LIBCASPER 612 if (capdns != NULL) 613 hp = cap_gethostbyname2(capdns, target, AF_INET); 614 else 615#endif 616 hp = gethostbyname2(target, AF_INET); 617 if (!hp) 618 errx(EX_NOHOST, "cannot resolve %s: %s", 619 target, hstrerror(h_errno)); 620 621 if ((unsigned)hp->h_length > sizeof(to->sin_addr)) 622 errx(1, "gethostbyname2 returned an illegal address"); 623 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 624 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 625 hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 626 hostname = hnamebuf; 627 } 628 629#ifdef HAVE_LIBCASPER 630 /* From now on we will use only reverse DNS lookups. */ 631 if (capdns != NULL) { 632 const char *types[1]; 633 634 types[0] = "ADDR"; 635 if (cap_dns_type_limit(capdns, types, 1) < 0) 636 err(1, "unable to limit access to system.dns service"); 637 } 638#endif 639 640 if (connect(ssend, (struct sockaddr *)&whereto, sizeof(whereto)) != 0) 641 err(1, "connect"); 642 643 if (options & F_FLOOD && options & F_INTERVAL) 644 errx(EX_USAGE, "-f and -i: incompatible options"); 645 646 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 647 errx(EX_USAGE, 648 "-f flag cannot be used with multicast destination"); 649 if (options & (F_MIF | F_NOLOOP | F_MTTL) 650 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 651 errx(EX_USAGE, 652 "-I, -L, -T flags cannot be used with unicast destination"); 653 654 if (datalen >= TIMEVAL_LEN) /* can we time transfer */ 655 timing = 1; 656 657 if (!(options & F_PINGFILLED)) 658 for (i = TIMEVAL_LEN; i < datalen; ++i) 659 *datap++ = i; 660 661 ident = getpid() & 0xFFFF; 662 663 hold = 1; 664 if (options & F_SO_DEBUG) { 665 (void)setsockopt(ssend, SOL_SOCKET, SO_DEBUG, (char *)&hold, 666 sizeof(hold)); 667 (void)setsockopt(srecv, SOL_SOCKET, SO_DEBUG, (char *)&hold, 668 sizeof(hold)); 669 } 670 if (options & F_SO_DONTROUTE) 671 (void)setsockopt(ssend, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, 672 sizeof(hold)); 673#ifdef IPSEC 674#ifdef IPSEC_POLICY_IPSEC 675 if (options & F_POLICY) { 676 char *buf; 677 if (policy_in != NULL) { 678 buf = ipsec_set_policy(policy_in, strlen(policy_in)); 679 if (buf == NULL) 680 errx(EX_CONFIG, "%s", ipsec_strerror()); 681 if (setsockopt(srecv, IPPROTO_IP, IP_IPSEC_POLICY, 682 buf, ipsec_get_policylen(buf)) < 0) 683 err(EX_CONFIG, 684 "ipsec policy cannot be configured"); 685 free(buf); 686 } 687 688 if (policy_out != NULL) { 689 buf = ipsec_set_policy(policy_out, strlen(policy_out)); 690 if (buf == NULL) 691 errx(EX_CONFIG, "%s", ipsec_strerror()); 692 if (setsockopt(ssend, IPPROTO_IP, IP_IPSEC_POLICY, 693 buf, ipsec_get_policylen(buf)) < 0) 694 err(EX_CONFIG, 695 "ipsec policy cannot be configured"); 696 free(buf); 697 } 698 } 699#endif /*IPSEC_POLICY_IPSEC*/ 700#endif /*IPSEC*/ 701 702 if (options & F_HDRINCL) { 703 ip = (struct ip*)outpackhdr; 704 if (!(options & (F_TTL | F_MTTL))) { 705 mib[0] = CTL_NET; 706 mib[1] = PF_INET; 707 mib[2] = IPPROTO_IP; 708 mib[3] = IPCTL_DEFTTL; 709 sz = sizeof(ttl); 710 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1) 711 err(1, "sysctl(net.inet.ip.ttl)"); 712 } 713 setsockopt(ssend, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold)); 714 ip->ip_v = IPVERSION; 715 ip->ip_hl = sizeof(struct ip) >> 2; 716 ip->ip_tos = tos; 717 ip->ip_id = 0; 718 ip->ip_off = htons(df ? IP_DF : 0); 719 ip->ip_ttl = ttl; 720 ip->ip_p = IPPROTO_ICMP; 721 ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY; 722 ip->ip_dst = to->sin_addr; 723 } 724 725 if (options & F_NUMERIC) 726 cansandbox = true; 727#ifdef HAVE_LIBCASPER 728 else if (capdns != NULL) 729 cansandbox = true; 730#endif 731 else 732 cansandbox = false; 733 734 /* 735 * Here we enter capability mode. Further down access to global 736 * namespaces (e.g filesystem) is restricted (see capsicum(4)). 737 * We must connect(2) our socket before this point. 738 */ 739 if (cansandbox && cap_enter() < 0 && errno != ENOSYS) 740 err(1, "cap_enter"); 741 742 cap_rights_init(&rights, CAP_RECV, CAP_EVENT, CAP_SETSOCKOPT); 743 if (cap_rights_limit(srecv, &rights) < 0 && errno != ENOSYS) 744 err(1, "cap_rights_limit srecv"); 745 746 cap_rights_init(&rights, CAP_SEND, CAP_SETSOCKOPT); 747 if (cap_rights_limit(ssend, &rights) < 0 && errno != ENOSYS) 748 err(1, "cap_rights_limit ssend"); 749 750 /* record route option */ 751 if (options & F_RROUTE) { 752#ifdef IP_OPTIONS 753 bzero(rspace, sizeof(rspace)); 754 rspace[IPOPT_OPTVAL] = IPOPT_RR; 755 rspace[IPOPT_OLEN] = sizeof(rspace) - 1; 756 rspace[IPOPT_OFFSET] = IPOPT_MINOFF; 757 rspace[sizeof(rspace) - 1] = IPOPT_EOL; 758 if (setsockopt(ssend, IPPROTO_IP, IP_OPTIONS, rspace, 759 sizeof(rspace)) < 0) 760 err(EX_OSERR, "setsockopt IP_OPTIONS"); 761#else 762 errx(EX_UNAVAILABLE, 763 "record route not available in this implementation"); 764#endif /* IP_OPTIONS */ 765 } 766 767 if (options & F_TTL) { 768 if (setsockopt(ssend, IPPROTO_IP, IP_TTL, &ttl, 769 sizeof(ttl)) < 0) { 770 err(EX_OSERR, "setsockopt IP_TTL"); 771 } 772 } 773 if (options & F_NOLOOP) { 774 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, 775 sizeof(loop)) < 0) { 776 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP"); 777 } 778 } 779 if (options & F_MTTL) { 780 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, 781 sizeof(mttl)) < 0) { 782 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL"); 783 } 784 } 785 if (options & F_MIF) { 786 if (setsockopt(ssend, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, 787 sizeof(ifaddr)) < 0) { 788 err(EX_OSERR, "setsockopt IP_MULTICAST_IF"); 789 } 790 } 791#ifdef SO_TIMESTAMP 792 { int on = 1; 793 if (setsockopt(srecv, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0) 794 err(EX_OSERR, "setsockopt SO_TIMESTAMP"); 795 } 796#endif 797 if (sweepmax) { 798 if (sweepmin > sweepmax) 799 errx(EX_USAGE, "Maximum packet size must be no less than the minimum packet size"); 800 801 if (datalen != DEFDATALEN) 802 errx(EX_USAGE, "Packet size and ping sweep are mutually exclusive"); 803 804 if (npackets > 0) { 805 snpackets = npackets; 806 npackets = 0; 807 } else 808 snpackets = 1; 809 datalen = sweepmin; 810 send_len = icmp_len + sweepmin; 811 } 812 if (options & F_SWEEP && !sweepmax) 813 errx(EX_USAGE, "Maximum sweep size must be specified"); 814 815 /* 816 * When pinging the broadcast address, you can get a lot of answers. 817 * Doing something so evil is useful if you are trying to stress the 818 * ethernet, or just want to fill the arp cache to get some stuff for 819 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast 820 * or multicast pings if they wish. 821 */ 822 823 /* 824 * XXX receive buffer needs undetermined space for mbuf overhead 825 * as well. 826 */ 827 hold = IP_MAXPACKET + 128; 828 (void)setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, (char *)&hold, 829 sizeof(hold)); 830 /* CAP_SETSOCKOPT removed */ 831 cap_rights_init(&rights, CAP_RECV, CAP_EVENT); 832 if (cap_rights_limit(srecv, &rights) < 0 && errno != ENOSYS) 833 err(1, "cap_rights_limit srecv setsockopt"); 834 if (uid == 0) 835 (void)setsockopt(ssend, SOL_SOCKET, SO_SNDBUF, (char *)&hold, 836 sizeof(hold)); 837 /* CAP_SETSOCKOPT removed */ 838 cap_rights_init(&rights, CAP_SEND); 839 if (cap_rights_limit(ssend, &rights) < 0 && errno != ENOSYS) 840 err(1, "cap_rights_limit ssend setsockopt"); 841 842 if (to->sin_family == AF_INET) { 843 (void)printf("PING %s (%s)", hostname, 844 inet_ntoa(to->sin_addr)); 845 if (source) 846 (void)printf(" from %s", shostname); 847 if (sweepmax) 848 (void)printf(": (%d ... %d) data bytes\n", 849 sweepmin, sweepmax); 850 else 851 (void)printf(": %d data bytes\n", datalen); 852 853 } else { 854 if (sweepmax) 855 (void)printf("PING %s: (%d ... %d) data bytes\n", 856 hostname, sweepmin, sweepmax); 857 else 858 (void)printf("PING %s: %d data bytes\n", hostname, datalen); 859 } 860 861 /* 862 * Use sigaction() instead of signal() to get unambiguous semantics, 863 * in particular with SA_RESTART not set. 864 */ 865 866 sigemptyset(&si_sa.sa_mask); 867 si_sa.sa_flags = 0; 868 869 si_sa.sa_handler = stopit; 870 if (sigaction(SIGINT, &si_sa, 0) == -1) { 871 err(EX_OSERR, "sigaction SIGINT"); 872 } 873 874 si_sa.sa_handler = status; 875 if (sigaction(SIGINFO, &si_sa, 0) == -1) { 876 err(EX_OSERR, "sigaction"); 877 } 878 879 if (alarmtimeout > 0) { 880 si_sa.sa_handler = stopit; 881 if (sigaction(SIGALRM, &si_sa, 0) == -1) 882 err(EX_OSERR, "sigaction SIGALRM"); 883 } 884 885 bzero(&msg, sizeof(msg)); 886 msg.msg_name = (caddr_t)&from; 887 msg.msg_iov = &iov; 888 msg.msg_iovlen = 1; 889#ifdef SO_TIMESTAMP 890 msg.msg_control = (caddr_t)ctrl; 891#endif 892 iov.iov_base = packet; 893 iov.iov_len = IP_MAXPACKET; 894 895 if (preload == 0) 896 pinger(); /* send the first ping */ 897 else { 898 if (npackets != 0 && preload > npackets) 899 preload = npackets; 900 while (preload--) /* fire off them quickies */ 901 pinger(); 902 } 903 (void)gettimeofday(&last, NULL); 904 905 if (options & F_FLOOD) { 906 intvl.tv_sec = 0; 907 intvl.tv_usec = 10000; 908 } else { 909 intvl.tv_sec = interval / 1000; 910 intvl.tv_usec = interval % 1000 * 1000; 911 } 912 913 almost_done = 0; 914 while (!finish_up) { 915 struct timeval now, timeout; 916 fd_set rfds; 917 int cc, n; 918 919 check_status(); 920 if ((unsigned)srecv >= FD_SETSIZE) 921 errx(EX_OSERR, "descriptor too large"); 922 FD_ZERO(&rfds); 923 FD_SET(srecv, &rfds); 924 (void)gettimeofday(&now, NULL); 925 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec; 926 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec; 927 while (timeout.tv_usec < 0) { 928 timeout.tv_usec += 1000000; 929 timeout.tv_sec--; 930 } 931 while (timeout.tv_usec >= 1000000) { 932 timeout.tv_usec -= 1000000; 933 timeout.tv_sec++; 934 } 935 if (timeout.tv_sec < 0) 936 timerclear(&timeout); 937 n = select(srecv + 1, &rfds, NULL, NULL, &timeout); 938 if (n < 0) 939 continue; /* Must be EINTR. */ 940 if (n == 1) { 941 struct timeval *tv = NULL; 942#ifdef SO_TIMESTAMP 943 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl; 944 945 msg.msg_controllen = sizeof(ctrl); 946#endif 947 msg.msg_namelen = sizeof(from); 948 if ((cc = recvmsg(srecv, &msg, 0)) < 0) { 949 if (errno == EINTR) 950 continue; 951 warn("recvmsg"); 952 continue; 953 } 954#ifdef SO_TIMESTAMP 955 if (cmsg->cmsg_level == SOL_SOCKET && 956 cmsg->cmsg_type == SCM_TIMESTAMP && 957 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) { 958 /* Copy to avoid alignment problems: */ 959 memcpy(&now, CMSG_DATA(cmsg), sizeof(now)); 960 tv = &now; 961 } 962#endif 963 if (tv == NULL) { 964 (void)gettimeofday(&now, NULL); 965 tv = &now; 966 } 967 pr_pack((char *)packet, cc, &from, tv); 968 if ((options & F_ONCE && nreceived) || 969 (npackets && nreceived >= npackets)) 970 break; 971 } 972 if (n == 0 || options & F_FLOOD) { 973 if (sweepmax && sntransmitted == snpackets) { 974 for (i = 0; i < sweepincr ; ++i) 975 *datap++ = i; 976 datalen += sweepincr; 977 if (datalen > sweepmax) 978 break; 979 send_len = icmp_len + datalen; 980 sntransmitted = 0; 981 } 982 if (!npackets || ntransmitted < npackets) 983 pinger(); 984 else { 985 if (almost_done) 986 break; 987 almost_done = 1; 988 intvl.tv_usec = 0; 989 if (nreceived) { 990 intvl.tv_sec = 2 * tmax / 1000; 991 if (!intvl.tv_sec) 992 intvl.tv_sec = 1; 993 } else { 994 intvl.tv_sec = waittime / 1000; 995 intvl.tv_usec = waittime % 1000 * 1000; 996 } 997 } 998 (void)gettimeofday(&last, NULL); 999 if (ntransmitted - nreceived - 1 > nmissedmax) { 1000 nmissedmax = ntransmitted - nreceived - 1; 1001 if (options & F_MISSED) 1002 (void)write(STDOUT_FILENO, &BBELL, 1); 1003 } 1004 } 1005 } 1006 finish(); 1007 /* NOTREACHED */ 1008 exit(0); /* Make the compiler happy */ 1009} 1010 1011/* 1012 * stopit -- 1013 * Set the global bit that causes the main loop to quit. 1014 * Do NOT call finish() from here, since finish() does far too much 1015 * to be called from a signal handler. 1016 */ 1017void 1018stopit(int sig __unused) 1019{ 1020 1021 /* 1022 * When doing reverse DNS lookups, the finish_up flag might not 1023 * be noticed for a while. Just exit if we get a second SIGINT. 1024 */ 1025 if (!(options & F_NUMERIC) && finish_up) 1026 _exit(nreceived ? 0 : 2); 1027 finish_up = 1; 1028} 1029 1030/* 1031 * pinger -- 1032 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 1033 * will be added on by the kernel. The ID field is our UNIX process ID, 1034 * and the sequence number is an ascending integer. The first TIMEVAL_LEN 1035 * bytes of the data portion are used to hold a UNIX "timeval" struct in 1036 * host byte-order, to compute the round-trip time. 1037 */ 1038static void 1039pinger(void) 1040{ 1041 struct timeval now; 1042 struct tv32 tv32; 1043 struct ip *ip; 1044 struct icmp *icp; 1045 int cc, i; 1046 u_char *packet; 1047 1048 packet = outpack; 1049 icp = (struct icmp *)outpack; 1050 icp->icmp_type = icmp_type; 1051 icp->icmp_code = 0; 1052 icp->icmp_cksum = 0; 1053 icp->icmp_seq = htons(ntransmitted); 1054 icp->icmp_id = ident; /* ID */ 1055 1056 CLR(ntransmitted % mx_dup_ck); 1057 1058 if ((options & F_TIME) || timing) { 1059 (void)gettimeofday(&now, NULL); 1060 1061 tv32.tv32_sec = htonl(now.tv_sec); 1062 tv32.tv32_usec = htonl(now.tv_usec); 1063 if (options & F_TIME) 1064 icp->icmp_otime = htonl((now.tv_sec % (24*60*60)) 1065 * 1000 + now.tv_usec / 1000); 1066 if (timing) 1067 bcopy((void *)&tv32, 1068 (void *)&outpack[ICMP_MINLEN + phdr_len], 1069 sizeof(tv32)); 1070 } 1071 1072 cc = ICMP_MINLEN + phdr_len + datalen; 1073 1074 /* compute ICMP checksum here */ 1075 icp->icmp_cksum = in_cksum((u_short *)icp, cc); 1076 1077 if (options & F_HDRINCL) { 1078 cc += sizeof(struct ip); 1079 ip = (struct ip *)outpackhdr; 1080 ip->ip_len = htons(cc); 1081 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc); 1082 packet = outpackhdr; 1083 } 1084 i = send(ssend, (char *)packet, cc, 0); 1085 if (i < 0 || i != cc) { 1086 if (i < 0) { 1087 if (options & F_FLOOD && errno == ENOBUFS) { 1088 usleep(FLOOD_BACKOFF); 1089 return; 1090 } 1091 warn("sendto"); 1092 } else { 1093 warn("%s: partial write: %d of %d bytes", 1094 hostname, i, cc); 1095 } 1096 } 1097 ntransmitted++; 1098 sntransmitted++; 1099 if (!(options & F_QUIET) && options & F_FLOOD) 1100 (void)write(STDOUT_FILENO, &DOT, 1); 1101} 1102 1103/* 1104 * pr_pack -- 1105 * Print out the packet, if it came from us. This logic is necessary 1106 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 1107 * which arrive ('tis only fair). This permits multiple copies of this 1108 * program to be run without having intermingled output (or statistics!). 1109 */ 1110static void 1111pr_pack(char *buf, int cc, struct sockaddr_in *from, struct timeval *tv) 1112{ 1113 struct in_addr ina; 1114 u_char *cp, *dp; 1115 struct icmp *icp; 1116 struct ip *ip; 1117 const void *tp; 1118 double triptime; 1119 int dupflag, hlen, i, j, recv_len, seq; 1120 static int old_rrlen; 1121 static char old_rr[MAX_IPOPTLEN]; 1122 1123 /* Check the IP header */ 1124 ip = (struct ip *)buf; 1125 hlen = ip->ip_hl << 2; 1126 recv_len = cc; 1127 if (cc < hlen + ICMP_MINLEN) { 1128 if (options & F_VERBOSE) 1129 warn("packet too short (%d bytes) from %s", cc, 1130 inet_ntoa(from->sin_addr)); 1131 return; 1132 } 1133 1134 /* Now the ICMP part */ 1135 cc -= hlen; 1136 icp = (struct icmp *)(buf + hlen); 1137 if (icp->icmp_type == icmp_type_rsp) { 1138 if (icp->icmp_id != ident) 1139 return; /* 'Twas not our ECHO */ 1140 ++nreceived; 1141 triptime = 0.0; 1142 if (timing) { 1143 struct timeval tv1; 1144 struct tv32 tv32; 1145#ifndef icmp_data 1146 tp = &icp->icmp_ip; 1147#else 1148 tp = icp->icmp_data; 1149#endif 1150 tp = (const char *)tp + phdr_len; 1151 1152 if ((size_t)(cc - ICMP_MINLEN - phdr_len) >= 1153 sizeof(tv1)) { 1154 /* Copy to avoid alignment problems: */ 1155 memcpy(&tv32, tp, sizeof(tv32)); 1156 tv1.tv_sec = ntohl(tv32.tv32_sec); 1157 tv1.tv_usec = ntohl(tv32.tv32_usec); 1158 tvsub(tv, &tv1); 1159 triptime = ((double)tv->tv_sec) * 1000.0 + 1160 ((double)tv->tv_usec) / 1000.0; 1161 tsum += triptime; 1162 tsumsq += triptime * triptime; 1163 if (triptime < tmin) 1164 tmin = triptime; 1165 if (triptime > tmax) 1166 tmax = triptime; 1167 } else 1168 timing = 0; 1169 } 1170 1171 seq = ntohs(icp->icmp_seq); 1172 1173 if (TST(seq % mx_dup_ck)) { 1174 ++nrepeats; 1175 --nreceived; 1176 dupflag = 1; 1177 } else { 1178 SET(seq % mx_dup_ck); 1179 dupflag = 0; 1180 } 1181 1182 if (options & F_QUIET) 1183 return; 1184 1185 if (options & F_WAITTIME && triptime > waittime) { 1186 ++nrcvtimeout; 1187 return; 1188 } 1189 1190 if (options & F_FLOOD) 1191 (void)write(STDOUT_FILENO, &BSPACE, 1); 1192 else { 1193 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 1194 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 1195 seq); 1196 (void)printf(" ttl=%d", ip->ip_ttl); 1197 if (timing) 1198 (void)printf(" time=%.3f ms", triptime); 1199 if (dupflag) 1200 (void)printf(" (DUP!)"); 1201 if (options & F_AUDIBLE) 1202 (void)write(STDOUT_FILENO, &BBELL, 1); 1203 if (options & F_MASK) { 1204 /* Just prentend this cast isn't ugly */ 1205 (void)printf(" mask=%s", 1206 inet_ntoa(*(struct in_addr *)&(icp->icmp_mask))); 1207 } 1208 if (options & F_TIME) { 1209 (void)printf(" tso=%s", pr_ntime(icp->icmp_otime)); 1210 (void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime)); 1211 (void)printf(" tst=%s", pr_ntime(icp->icmp_ttime)); 1212 } 1213 if (recv_len != send_len) { 1214 (void)printf( 1215 "\nwrong total length %d instead of %d", 1216 recv_len, send_len); 1217 } 1218 /* check the data */ 1219 cp = (u_char*)&icp->icmp_data[phdr_len]; 1220 dp = &outpack[ICMP_MINLEN + phdr_len]; 1221 cc -= ICMP_MINLEN + phdr_len; 1222 i = 0; 1223 if (timing) { /* don't check variable timestamp */ 1224 cp += TIMEVAL_LEN; 1225 dp += TIMEVAL_LEN; 1226 cc -= TIMEVAL_LEN; 1227 i += TIMEVAL_LEN; 1228 } 1229 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) { 1230 if (*cp != *dp) { 1231 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 1232 i, *dp, *cp); 1233 (void)printf("\ncp:"); 1234 cp = (u_char*)&icp->icmp_data[0]; 1235 for (i = 0; i < datalen; ++i, ++cp) { 1236 if ((i % 16) == 8) 1237 (void)printf("\n\t"); 1238 (void)printf("%2x ", *cp); 1239 } 1240 (void)printf("\ndp:"); 1241 cp = &outpack[ICMP_MINLEN]; 1242 for (i = 0; i < datalen; ++i, ++cp) { 1243 if ((i % 16) == 8) 1244 (void)printf("\n\t"); 1245 (void)printf("%2x ", *cp); 1246 } 1247 break; 1248 } 1249 } 1250 } 1251 } else { 1252 /* 1253 * We've got something other than an ECHOREPLY. 1254 * See if it's a reply to something that we sent. 1255 * We can compare IP destination, protocol, 1256 * and ICMP type and ID. 1257 * 1258 * Only print all the error messages if we are running 1259 * as root to avoid leaking information not normally 1260 * available to those not running as root. 1261 */ 1262#ifndef icmp_data 1263 struct ip *oip = &icp->icmp_ip; 1264#else 1265 struct ip *oip = (struct ip *)icp->icmp_data; 1266#endif 1267 struct icmp *oicmp = (struct icmp *)(oip + 1); 1268 1269 if (((options & F_VERBOSE) && uid == 0) || 1270 (!(options & F_QUIET2) && 1271 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) && 1272 (oip->ip_p == IPPROTO_ICMP) && 1273 (oicmp->icmp_type == ICMP_ECHO) && 1274 (oicmp->icmp_id == ident))) { 1275 (void)printf("%d bytes from %s: ", cc, 1276 pr_addr(from->sin_addr)); 1277 pr_icmph(icp); 1278 } else 1279 return; 1280 } 1281 1282 /* Display any IP options */ 1283 cp = (u_char *)buf + sizeof(struct ip); 1284 1285 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 1286 switch (*cp) { 1287 case IPOPT_EOL: 1288 hlen = 0; 1289 break; 1290 case IPOPT_LSRR: 1291 case IPOPT_SSRR: 1292 (void)printf(*cp == IPOPT_LSRR ? 1293 "\nLSRR: " : "\nSSRR: "); 1294 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1; 1295 hlen -= 2; 1296 cp += 2; 1297 if (j >= INADDR_LEN && 1298 j <= hlen - (int)sizeof(struct ip)) { 1299 for (;;) { 1300 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1301 if (ina.s_addr == 0) 1302 (void)printf("\t0.0.0.0"); 1303 else 1304 (void)printf("\t%s", 1305 pr_addr(ina)); 1306 hlen -= INADDR_LEN; 1307 cp += INADDR_LEN - 1; 1308 j -= INADDR_LEN; 1309 if (j < INADDR_LEN) 1310 break; 1311 (void)putchar('\n'); 1312 } 1313 } else 1314 (void)printf("\t(truncated route)\n"); 1315 break; 1316 case IPOPT_RR: 1317 j = cp[IPOPT_OLEN]; /* get length */ 1318 i = cp[IPOPT_OFFSET]; /* and pointer */ 1319 hlen -= 2; 1320 cp += 2; 1321 if (i > j) 1322 i = j; 1323 i = i - IPOPT_MINOFF + 1; 1324 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) { 1325 old_rrlen = 0; 1326 continue; 1327 } 1328 if (i == old_rrlen 1329 && !bcmp((char *)cp, old_rr, i) 1330 && !(options & F_FLOOD)) { 1331 (void)printf("\t(same route)"); 1332 hlen -= i; 1333 cp += i; 1334 break; 1335 } 1336 old_rrlen = i; 1337 bcopy((char *)cp, old_rr, i); 1338 (void)printf("\nRR: "); 1339 if (i >= INADDR_LEN && 1340 i <= hlen - (int)sizeof(struct ip)) { 1341 for (;;) { 1342 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1343 if (ina.s_addr == 0) 1344 (void)printf("\t0.0.0.0"); 1345 else 1346 (void)printf("\t%s", 1347 pr_addr(ina)); 1348 hlen -= INADDR_LEN; 1349 cp += INADDR_LEN - 1; 1350 i -= INADDR_LEN; 1351 if (i < INADDR_LEN) 1352 break; 1353 (void)putchar('\n'); 1354 } 1355 } else 1356 (void)printf("\t(truncated route)"); 1357 break; 1358 case IPOPT_NOP: 1359 (void)printf("\nNOP"); 1360 break; 1361 default: 1362 (void)printf("\nunknown option %x", *cp); 1363 break; 1364 } 1365 if (!(options & F_FLOOD)) { 1366 (void)putchar('\n'); 1367 (void)fflush(stdout); 1368 } 1369} 1370 1371/* 1372 * in_cksum -- 1373 * Checksum routine for Internet Protocol family headers (C Version) 1374 */ 1375u_short 1376in_cksum(u_short *addr, int len) 1377{ 1378 int nleft, sum; 1379 u_short *w; 1380 union { 1381 u_short us; 1382 u_char uc[2]; 1383 } last; 1384 u_short answer; 1385 1386 nleft = len; 1387 sum = 0; 1388 w = addr; 1389 1390 /* 1391 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 1392 * sequential 16 bit words to it, and at the end, fold back all the 1393 * carry bits from the top 16 bits into the lower 16 bits. 1394 */ 1395 while (nleft > 1) { 1396 sum += *w++; 1397 nleft -= 2; 1398 } 1399 1400 /* mop up an odd byte, if necessary */ 1401 if (nleft == 1) { 1402 last.uc[0] = *(u_char *)w; 1403 last.uc[1] = 0; 1404 sum += last.us; 1405 } 1406 1407 /* add back carry outs from top 16 bits to low 16 bits */ 1408 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 1409 sum += (sum >> 16); /* add carry */ 1410 answer = ~sum; /* truncate to 16 bits */ 1411 return(answer); 1412} 1413 1414/* 1415 * tvsub -- 1416 * Subtract 2 timeval structs: out = out - in. Out is assumed to 1417 * be >= in. 1418 */ 1419static void 1420tvsub(struct timeval *out, const struct timeval *in) 1421{ 1422 1423 if ((out->tv_usec -= in->tv_usec) < 0) { 1424 --out->tv_sec; 1425 out->tv_usec += 1000000; 1426 } 1427 out->tv_sec -= in->tv_sec; 1428} 1429 1430/* 1431 * status -- 1432 * Print out statistics when SIGINFO is received. 1433 */ 1434 1435static void 1436status(int sig __unused) 1437{ 1438 1439 siginfo_p = 1; 1440} 1441 1442static void 1443check_status(void) 1444{ 1445 1446 if (siginfo_p) { 1447 siginfo_p = 0; 1448 (void)fprintf(stderr, "\r%ld/%ld packets received (%.1f%%)", 1449 nreceived, ntransmitted, 1450 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0); 1451 if (nreceived && timing) 1452 (void)fprintf(stderr, " %.3f min / %.3f avg / %.3f max", 1453 tmin, tsum / (nreceived + nrepeats), tmax); 1454 (void)fprintf(stderr, "\n"); 1455 } 1456} 1457 1458/* 1459 * finish -- 1460 * Print out statistics, and give up. 1461 */ 1462static void 1463finish(void) 1464{ 1465 1466 (void)signal(SIGINT, SIG_IGN); 1467 (void)signal(SIGALRM, SIG_IGN); 1468 (void)putchar('\n'); 1469 (void)fflush(stdout); 1470 (void)printf("--- %s ping statistics ---\n", hostname); 1471 (void)printf("%ld packets transmitted, ", ntransmitted); 1472 (void)printf("%ld packets received, ", nreceived); 1473 if (nrepeats) 1474 (void)printf("+%ld duplicates, ", nrepeats); 1475 if (ntransmitted) { 1476 if (nreceived > ntransmitted) 1477 (void)printf("-- somebody's printing up packets!"); 1478 else 1479 (void)printf("%.1f%% packet loss", 1480 ((ntransmitted - nreceived) * 100.0) / 1481 ntransmitted); 1482 } 1483 if (nrcvtimeout) 1484 (void)printf(", %ld packets out of wait time", nrcvtimeout); 1485 (void)putchar('\n'); 1486 if (nreceived && timing) { 1487 double n = nreceived + nrepeats; 1488 double avg = tsum / n; 1489 double vari = tsumsq / n - avg * avg; 1490 (void)printf( 1491 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n", 1492 tmin, avg, tmax, sqrt(vari)); 1493 } 1494 1495 if (nreceived) 1496 exit(0); 1497 else 1498 exit(2); 1499} 1500 1501#ifdef notdef 1502static char *ttab[] = { 1503 "Echo Reply", /* ip + seq + udata */ 1504 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1505 "Source Quench", /* IP */ 1506 "Redirect", /* redirect type, gateway, + IP */ 1507 "Echo", 1508 "Time Exceeded", /* transit, frag reassem + IP */ 1509 "Parameter Problem", /* pointer + IP */ 1510 "Timestamp", /* id + seq + three timestamps */ 1511 "Timestamp Reply", /* " */ 1512 "Info Request", /* id + sq */ 1513 "Info Reply" /* " */ 1514}; 1515#endif 1516 1517/* 1518 * pr_icmph -- 1519 * Print a descriptive string about an ICMP header. 1520 */ 1521static void 1522pr_icmph(struct icmp *icp) 1523{ 1524 1525 switch(icp->icmp_type) { 1526 case ICMP_ECHOREPLY: 1527 (void)printf("Echo Reply\n"); 1528 /* XXX ID + Seq + Data */ 1529 break; 1530 case ICMP_UNREACH: 1531 switch(icp->icmp_code) { 1532 case ICMP_UNREACH_NET: 1533 (void)printf("Destination Net Unreachable\n"); 1534 break; 1535 case ICMP_UNREACH_HOST: 1536 (void)printf("Destination Host Unreachable\n"); 1537 break; 1538 case ICMP_UNREACH_PROTOCOL: 1539 (void)printf("Destination Protocol Unreachable\n"); 1540 break; 1541 case ICMP_UNREACH_PORT: 1542 (void)printf("Destination Port Unreachable\n"); 1543 break; 1544 case ICMP_UNREACH_NEEDFRAG: 1545 (void)printf("frag needed and DF set (MTU %d)\n", 1546 ntohs(icp->icmp_nextmtu)); 1547 break; 1548 case ICMP_UNREACH_SRCFAIL: 1549 (void)printf("Source Route Failed\n"); 1550 break; 1551 case ICMP_UNREACH_FILTER_PROHIB: 1552 (void)printf("Communication prohibited by filter\n"); 1553 break; 1554 default: 1555 (void)printf("Dest Unreachable, Bad Code: %d\n", 1556 icp->icmp_code); 1557 break; 1558 } 1559 /* Print returned IP header information */ 1560#ifndef icmp_data 1561 pr_retip(&icp->icmp_ip); 1562#else 1563 pr_retip((struct ip *)icp->icmp_data); 1564#endif 1565 break; 1566 case ICMP_SOURCEQUENCH: 1567 (void)printf("Source Quench\n"); 1568#ifndef icmp_data 1569 pr_retip(&icp->icmp_ip); 1570#else 1571 pr_retip((struct ip *)icp->icmp_data); 1572#endif 1573 break; 1574 case ICMP_REDIRECT: 1575 switch(icp->icmp_code) { 1576 case ICMP_REDIRECT_NET: 1577 (void)printf("Redirect Network"); 1578 break; 1579 case ICMP_REDIRECT_HOST: 1580 (void)printf("Redirect Host"); 1581 break; 1582 case ICMP_REDIRECT_TOSNET: 1583 (void)printf("Redirect Type of Service and Network"); 1584 break; 1585 case ICMP_REDIRECT_TOSHOST: 1586 (void)printf("Redirect Type of Service and Host"); 1587 break; 1588 default: 1589 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1590 break; 1591 } 1592 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1593#ifndef icmp_data 1594 pr_retip(&icp->icmp_ip); 1595#else 1596 pr_retip((struct ip *)icp->icmp_data); 1597#endif 1598 break; 1599 case ICMP_ECHO: 1600 (void)printf("Echo Request\n"); 1601 /* XXX ID + Seq + Data */ 1602 break; 1603 case ICMP_TIMXCEED: 1604 switch(icp->icmp_code) { 1605 case ICMP_TIMXCEED_INTRANS: 1606 (void)printf("Time to live exceeded\n"); 1607 break; 1608 case ICMP_TIMXCEED_REASS: 1609 (void)printf("Frag reassembly time exceeded\n"); 1610 break; 1611 default: 1612 (void)printf("Time exceeded, Bad Code: %d\n", 1613 icp->icmp_code); 1614 break; 1615 } 1616#ifndef icmp_data 1617 pr_retip(&icp->icmp_ip); 1618#else 1619 pr_retip((struct ip *)icp->icmp_data); 1620#endif 1621 break; 1622 case ICMP_PARAMPROB: 1623 (void)printf("Parameter problem: pointer = 0x%02x\n", 1624 icp->icmp_hun.ih_pptr); 1625#ifndef icmp_data 1626 pr_retip(&icp->icmp_ip); 1627#else 1628 pr_retip((struct ip *)icp->icmp_data); 1629#endif 1630 break; 1631 case ICMP_TSTAMP: 1632 (void)printf("Timestamp\n"); 1633 /* XXX ID + Seq + 3 timestamps */ 1634 break; 1635 case ICMP_TSTAMPREPLY: 1636 (void)printf("Timestamp Reply\n"); 1637 /* XXX ID + Seq + 3 timestamps */ 1638 break; 1639 case ICMP_IREQ: 1640 (void)printf("Information Request\n"); 1641 /* XXX ID + Seq */ 1642 break; 1643 case ICMP_IREQREPLY: 1644 (void)printf("Information Reply\n"); 1645 /* XXX ID + Seq */ 1646 break; 1647 case ICMP_MASKREQ: 1648 (void)printf("Address Mask Request\n"); 1649 break; 1650 case ICMP_MASKREPLY: 1651 (void)printf("Address Mask Reply\n"); 1652 break; 1653 case ICMP_ROUTERADVERT: 1654 (void)printf("Router Advertisement\n"); 1655 break; 1656 case ICMP_ROUTERSOLICIT: 1657 (void)printf("Router Solicitation\n"); 1658 break; 1659 default: 1660 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1661 } 1662} 1663 1664/* 1665 * pr_iph -- 1666 * Print an IP header with options. 1667 */ 1668static void 1669pr_iph(struct ip *ip) 1670{ 1671 struct in_addr ina; 1672 u_char *cp; 1673 int hlen; 1674 1675 hlen = ip->ip_hl << 2; 1676 cp = (u_char *)ip + 20; /* point to options */ 1677 1678 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1679 (void)printf(" %1x %1x %02x %04x %04x", 1680 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1681 ntohs(ip->ip_id)); 1682 (void)printf(" %1lx %04lx", 1683 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1684 (u_long) ntohl(ip->ip_off) & 0x1fff); 1685 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1686 ntohs(ip->ip_sum)); 1687 memcpy(&ina, &ip->ip_src.s_addr, sizeof ina); 1688 (void)printf(" %s ", inet_ntoa(ina)); 1689 memcpy(&ina, &ip->ip_dst.s_addr, sizeof ina); 1690 (void)printf(" %s ", inet_ntoa(ina)); 1691 /* dump any option bytes */ 1692 while (hlen-- > 20) { 1693 (void)printf("%02x", *cp++); 1694 } 1695 (void)putchar('\n'); 1696} 1697 1698/* 1699 * pr_addr -- 1700 * Return an ascii host address as a dotted quad and optionally with 1701 * a hostname. 1702 */ 1703static char * 1704pr_addr(struct in_addr ina) 1705{ 1706 struct hostent *hp; 1707 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1708 1709 if (options & F_NUMERIC) 1710 return inet_ntoa(ina); 1711 1712#ifdef HAVE_LIBCASPER 1713 if (capdns != NULL) 1714 hp = cap_gethostbyaddr(capdns, (char *)&ina, 4, AF_INET); 1715 else 1716#endif 1717 hp = gethostbyaddr((char *)&ina, 4, AF_INET); 1718 1719 if (hp == NULL) 1720 return inet_ntoa(ina); 1721 1722 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1723 inet_ntoa(ina)); 1724 return(buf); 1725} 1726 1727/* 1728 * pr_retip -- 1729 * Dump some info on a returned (via ICMP) IP packet. 1730 */ 1731static void 1732pr_retip(struct ip *ip) 1733{ 1734 u_char *cp; 1735 int hlen; 1736 1737 pr_iph(ip); 1738 hlen = ip->ip_hl << 2; 1739 cp = (u_char *)ip + hlen; 1740 1741 if (ip->ip_p == 6) 1742 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1743 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1744 else if (ip->ip_p == 17) 1745 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1746 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1747} 1748 1749static char * 1750pr_ntime(n_time timestamp) 1751{ 1752 static char buf[10]; 1753 int hour, min, sec; 1754 1755 sec = ntohl(timestamp) / 1000; 1756 hour = sec / 60 / 60; 1757 min = (sec % (60 * 60)) / 60; 1758 sec = (sec % (60 * 60)) % 60; 1759 1760 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec); 1761 1762 return (buf); 1763} 1764 1765static void 1766fill(char *bp, char *patp) 1767{ 1768 char *cp; 1769 int pat[16]; 1770 u_int ii, jj, kk; 1771 1772 for (cp = patp; *cp; cp++) { 1773 if (!isxdigit(*cp)) 1774 errx(EX_USAGE, 1775 "patterns must be specified as hex digits"); 1776 1777 } 1778 ii = sscanf(patp, 1779 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1780 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1781 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1782 &pat[13], &pat[14], &pat[15]); 1783 1784 if (ii > 0) 1785 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii) 1786 for (jj = 0; jj < ii; ++jj) 1787 bp[jj + kk] = pat[jj]; 1788 if (!(options & F_QUIET)) { 1789 (void)printf("PATTERN: 0x"); 1790 for (jj = 0; jj < ii; ++jj) 1791 (void)printf("%02x", bp[jj] & 0xFF); 1792 (void)printf("\n"); 1793 } 1794} 1795 1796#ifdef HAVE_LIBCASPER 1797static cap_channel_t * 1798capdns_setup(void) 1799{ 1800 cap_channel_t *capcas, *capdnsloc; 1801 const char *types[2]; 1802 int families[1]; 1803 1804 capcas = cap_init(); 1805 if (capcas == NULL) 1806 err(1, "unable to create casper process"); 1807 capdnsloc = cap_service_open(capcas, "system.dns"); 1808 /* Casper capability no longer needed. */ 1809 cap_close(capcas); 1810 if (capdnsloc == NULL) 1811 err(1, "unable to open system.dns service"); 1812 types[0] = "NAME"; 1813 types[1] = "ADDR"; 1814 if (cap_dns_type_limit(capdnsloc, types, 2) < 0) 1815 err(1, "unable to limit access to system.dns service"); 1816 families[0] = AF_INET; 1817 if (cap_dns_family_limit(capdnsloc, families, 1) < 0) 1818 err(1, "unable to limit access to system.dns service"); 1819 1820 return (capdnsloc); 1821} 1822#endif /* HAVE_LIBCASPER */ 1823 1824#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC) 1825#define SECOPT " [-P policy]" 1826#else 1827#define SECOPT "" 1828#endif 1829static void 1830usage(void) 1831{ 1832 1833 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n", 1834"usage: ping [-AaDdfnoQqRrv] [-c count] [-G sweepmaxsize] [-g sweepminsize]", 1835" [-h sweepincrsize] [-i wait] [-l preload] [-M mask | time] [-m ttl]", 1836" " SECOPT " [-p pattern] [-S src_addr] [-s packetsize] [-t timeout]", 1837" [-W waittime] [-z tos] host", 1838" ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]", 1839" [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]", 1840" [-s packetsize] [-T ttl] [-t timeout] [-W waittime]", 1841" [-z tos] mcast-group"); 1842 exit(EX_USAGE); 1843} 1844