1 /* 2 * Copyright (c) 1989, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Mike Muuss. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. All advertising materials mentioning features or use of this software 17 * must display the following acknowledgement: 18 * This product includes software developed by the University of 19 * California, Berkeley and its contributors. 20 * 4. Neither the name of the University nor the names of its contributors 21 * may be used to endorse or promote products derived from this software 22 * without specific prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34 * SUCH DAMAGE. 35 */ 36 37 #ifndef lint 38 static const char copyright[] = 39 "@(#) Copyright (c) 1989, 1993\n\ 40 The Regents of the University of California. All rights reserved.\n"; 41 #endif /* not lint */ 42 43 #ifndef lint 44 #if 0 45 static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; 46 #endif 47 static const char rcsid[] = 48 "$Id: ping.c,v 1.41 1998/08/26 18:51:37 des Exp $"; 49 #endif /* not lint */ 50 51 /* 52 * P I N G . C 53 * 54 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility, 55 * measure round-trip-delays and packet loss across network paths. 56 * 57 * Author - 58 * Mike Muuss 59 * U. S. Army Ballistic Research Laboratory 60 * December, 1983 61 * 62 * Status - 63 * Public Domain. Distribution Unlimited. 64 * Bugs - 65 * More statistics could always be gathered. 66 * This program has to run SUID to ROOT to access the ICMP socket. 67 */ 68 69 #include <sys/param.h> /* NB: we rely on this for <sys/types.h> */ 70 71 #include <ctype.h> 72 #include <err.h> 73 #include <errno.h> 74 #include <math.h> 75 #include <netdb.h> 76 #include <signal.h> 77 #include <stdio.h> 78 #include <stdlib.h> 79 #include <string.h> 80 #include <sysexits.h> 81 #include <termios.h> 82 #include <unistd.h> 83 84 #include <sys/socket.h> 85 #include <sys/time.h> 86 #include <sys/uio.h> 87 88 #include <netinet/in.h> 89 #include <netinet/in_systm.h> 90 #include <netinet/ip.h> 91 #include <netinet/ip_icmp.h> 92 #include <netinet/ip_var.h> 93 #include <arpa/inet.h> 94 95 #define PHDR_LEN sizeof(struct timeval) 96 #define DEFDATALEN (64 - PHDR_LEN) /* default data length */ 97 #define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */ 98 /* runs out of buffer space */ 99 #define MAXIPLEN 60 100 #define MAXICMPLEN 76 101 #define MAXPACKET (65536 - 60 - 8)/* max packet size */ 102 #define MAXWAIT 10 /* max seconds to wait for response */ 103 #define NROUTES 9 /* number of record route slots */ 104 105 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ 106 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ 107 #define SET(bit) (A(bit) |= B(bit)) 108 #define CLR(bit) (A(bit) &= (~B(bit))) 109 #define TST(bit) (A(bit) & B(bit)) 110 111 /* various options */ 112 int options; 113 #define F_FLOOD 0x0001 114 #define F_INTERVAL 0x0002 115 #define F_NUMERIC 0x0004 116 #define F_PINGFILLED 0x0008 117 #define F_QUIET 0x0010 118 #define F_RROUTE 0x0020 119 #define F_SO_DEBUG 0x0040 120 #define F_SO_DONTROUTE 0x0080 121 #define F_VERBOSE 0x0100 122 #define F_QUIET2 0x0200 123 #define F_NOLOOP 0x0400 124 #define F_MTTL 0x0800 125 #define F_MIF 0x1000 126 #define F_AUDIBLE 0x2000 127 128 /* 129 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum 130 * number of received sequence numbers we can keep track of. Change 128 131 * to 8192 for complete accuracy... 132 */ 133 #define MAX_DUP_CHK (8 * 128) 134 int mx_dup_ck = MAX_DUP_CHK; 135 char rcvd_tbl[MAX_DUP_CHK / 8]; 136 137 struct sockaddr whereto; /* who to ping */ 138 int datalen = DEFDATALEN; 139 int s; /* socket file descriptor */ 140 u_char outpack[MAXPACKET]; 141 char BSPACE = '\b'; /* characters written for flood */ 142 char DOT = '.'; 143 char *hostname; 144 char *shostname; 145 int ident; /* process id to identify our packets */ 146 int uid; /* cached uid for micro-optimization */ 147 148 /* counters */ 149 long npackets; /* max packets to transmit */ 150 long nreceived; /* # of packets we got back */ 151 long nrepeats; /* number of duplicates */ 152 long ntransmitted; /* sequence # for outbound packets = #sent */ 153 int interval = 1000; /* interval between packets, ms */ 154 155 /* timing */ 156 int timing; /* flag to do timing */ 157 double tmin = 999999999.0; /* minimum round trip time */ 158 double tmax = 0.0; /* maximum round trip time */ 159 double tsum = 0.0; /* sum of all times, for doing average */ 160 double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ 161 162 volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */ 163 int reset_kerninfo; 164 volatile sig_atomic_t siginfo_p; 165 166 static void fill(char *, char *); 167 static u_short in_cksum(u_short *, int); 168 static void check_status(void); 169 static void finish(void) __dead2; 170 static void pinger(void); 171 static char *pr_addr(struct in_addr); 172 static void pr_icmph(struct icmp *); 173 static void pr_iph(struct ip *); 174 static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *); 175 static void pr_retip(struct ip *); 176 static void status(int); 177 static void stopit(int); 178 static void tvsub(struct timeval *, struct timeval *); 179 static void usage(void) __dead2; 180 181 int 182 main(argc, argv) 183 int argc; 184 char *const *argv; 185 { 186 struct timeval last, intvl; 187 struct hostent *hp; 188 struct sockaddr_in *to, sin; 189 struct termios ts; 190 register int i; 191 int ch, hold, packlen, preload, sockerrno, almost_done = 0; 192 struct in_addr ifaddr; 193 unsigned char ttl, loop; 194 u_char *datap, *packet; 195 char *source = NULL, *target, hnamebuf[MAXHOSTNAMELEN]; 196 char snamebuf[MAXHOSTNAMELEN]; 197 char *ep; 198 u_long ultmp; 199 #ifdef IP_OPTIONS 200 char rspace[3 + 4 * NROUTES + 1]; /* record route space */ 201 #endif 202 struct sigaction si_sa; 203 struct iovec iov; 204 struct msghdr msg; 205 struct sockaddr_in from; 206 char ctrl[sizeof(struct cmsghdr) + sizeof(struct timeval)]; 207 208 /* 209 * Do the stuff that we need root priv's for *first*, and 210 * then drop our setuid bit. Save error reporting for 211 * after arg parsing. 212 */ 213 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 214 sockerrno = errno; 215 216 setuid(getuid()); 217 uid = getuid(); 218 219 preload = 0; 220 221 datap = &outpack[8 + PHDR_LEN]; 222 while ((ch = getopt(argc, argv, "I:LQRS:T:c:adfi:l:np:qrs:v")) != -1) { 223 switch(ch) { 224 case 'a': 225 options |= F_AUDIBLE; 226 break; 227 case 'c': 228 ultmp = strtoul(optarg, &ep, 0); 229 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp) 230 errx(EX_USAGE, 231 "invalid count of packets to transmit: `%s'", 232 optarg); 233 npackets = ultmp; 234 break; 235 case 'd': 236 options |= F_SO_DEBUG; 237 break; 238 case 'f': 239 if (uid) { 240 errno = EPERM; 241 err(EX_NOPERM, "-f flag"); 242 } 243 options |= F_FLOOD; 244 setbuf(stdout, (char *)NULL); 245 break; 246 case 'i': /* wait between sending packets */ 247 { 248 double t = strtod(optarg, &ep) * 1000.0; 249 250 if (*ep || ep == optarg || t > (double)INT_MAX) { 251 errx( 252 EX_USAGE, 253 "invalid timing interval: `%s'", 254 optarg 255 ); 256 } 257 options |= F_INTERVAL; 258 interval = (int)t; 259 if (uid && interval < 1000) { 260 errno = EPERM; 261 err(EX_NOPERM, "-i interval too short"); 262 } 263 } 264 break; 265 case 'I': /* multicast interface */ 266 if (inet_aton(optarg, &ifaddr) == 0) 267 errx(EX_USAGE, 268 "invalid multicast interface: `%s'", 269 optarg); 270 options |= F_MIF; 271 break; 272 case 'l': 273 ultmp = strtoul(optarg, &ep, 0); 274 if (*ep || ep == optarg || ultmp > INT_MAX) 275 errx(EX_USAGE, 276 "invalid preload value: `%s'", optarg); 277 if (getuid()) { 278 errno = EPERM; 279 err(EX_NOPERM, "-l flag"); 280 } 281 options |= F_FLOOD; 282 preload = ultmp; 283 break; 284 case 'L': 285 options |= F_NOLOOP; 286 loop = 0; 287 break; 288 case 'n': 289 options |= F_NUMERIC; 290 break; 291 case 'p': /* fill buffer with user pattern */ 292 options |= F_PINGFILLED; 293 fill((char *)datap, optarg); 294 break; 295 case 'Q': 296 options |= F_QUIET2; 297 break; 298 case 'q': 299 options |= F_QUIET; 300 break; 301 case 'R': 302 options |= F_RROUTE; 303 break; 304 case 'r': 305 options |= F_SO_DONTROUTE; 306 break; 307 case 's': /* size of packet to send */ 308 if (uid) { 309 errno = EPERM; 310 err(EX_NOPERM, "-s flag"); 311 } 312 ultmp = strtoul(optarg, &ep, 0); 313 if (ultmp > MAXPACKET) 314 errx(EX_USAGE, "packet size too large: %lu", 315 ultmp); 316 if (*ep || ep == optarg || !ultmp) 317 errx(EX_USAGE, "invalid packet size: `%s'", 318 optarg); 319 datalen = ultmp; 320 break; 321 case 'S': 322 source = optarg; 323 break; 324 case 'T': /* multicast TTL */ 325 ultmp = strtoul(optarg, &ep, 0); 326 if (*ep || ep == optarg || ultmp > 255) 327 errx(EX_USAGE, "invalid multicast TTL: `%s'", 328 optarg); 329 ttl = ultmp; 330 options |= F_MTTL; 331 break; 332 case 'v': 333 options |= F_VERBOSE; 334 break; 335 default: 336 usage(); 337 } 338 } 339 340 if (argc - optind != 1) 341 usage(); 342 target = argv[optind]; 343 344 if (source) { 345 bzero((char *)&sin, sizeof(sin)); 346 sin.sin_family = AF_INET; 347 if (inet_aton(source, &sin.sin_addr) != 0) { 348 shostname = source; 349 } else { 350 hp = gethostbyname2(source, AF_INET); 351 if (!hp) 352 errx(EX_NOHOST, "cannot resolve %s: %s", 353 source, hstrerror(h_errno)); 354 355 sin.sin_len = sizeof sin; 356 if (hp->h_length > sizeof(sin.sin_addr)) 357 errx(1,"gethostbyname2: illegal address"); 358 memcpy(&sin.sin_addr, hp->h_addr_list[0], 359 sizeof (sin.sin_addr)); 360 (void)strncpy(snamebuf, hp->h_name, 361 sizeof(snamebuf) - 1); 362 snamebuf[sizeof(snamebuf) - 1] = '\0'; 363 shostname = snamebuf; 364 } 365 if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1) 366 err(1, "bind"); 367 } 368 369 bzero((char *)&whereto, sizeof(struct sockaddr)); 370 to = (struct sockaddr_in *)&whereto; 371 to->sin_family = AF_INET; 372 if (inet_aton(target, &to->sin_addr) != 0) { 373 hostname = target; 374 } else { 375 hp = gethostbyname2(target, AF_INET); 376 if (!hp) 377 errx(EX_NOHOST, "cannot resolve %s: %s", 378 target, hstrerror(h_errno)); 379 380 to->sin_len = sizeof *to; 381 if (hp->h_length > sizeof(to->sin_addr)) 382 errx(1,"gethostbyname2 returned an illegal address"); 383 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 384 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 385 hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 386 hostname = hnamebuf; 387 } 388 389 if (options & F_FLOOD && options & F_INTERVAL) 390 errx(EX_USAGE, "-f and -i: incompatible options"); 391 392 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 393 errx(EX_USAGE, 394 "-f flag cannot be used with multicast destination"); 395 if (options & (F_MIF | F_NOLOOP | F_MTTL) 396 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 397 errx(EX_USAGE, 398 "-I, -L, -T flags cannot be used with unicast destination"); 399 400 if (datalen >= PHDR_LEN) /* can we time transfer */ 401 timing = 1; 402 packlen = datalen + MAXIPLEN + MAXICMPLEN; 403 if (!(packet = (u_char *)malloc((size_t)packlen))) 404 err(EX_UNAVAILABLE, "malloc"); 405 406 if (!(options & F_PINGFILLED)) 407 for (i = PHDR_LEN; i < datalen; ++i) 408 *datap++ = i; 409 410 ident = getpid() & 0xFFFF; 411 412 if (s < 0) { 413 errno = sockerrno; 414 err(EX_OSERR, "socket"); 415 } 416 hold = 1; 417 if (options & F_SO_DEBUG) 418 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold, 419 sizeof(hold)); 420 if (options & F_SO_DONTROUTE) 421 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, 422 sizeof(hold)); 423 424 /* record route option */ 425 if (options & F_RROUTE) { 426 #ifdef IP_OPTIONS 427 bzero(rspace, sizeof(rspace)); 428 rspace[IPOPT_OPTVAL] = IPOPT_RR; 429 rspace[IPOPT_OLEN] = sizeof(rspace) - 1; 430 rspace[IPOPT_OFFSET] = IPOPT_MINOFF; 431 rspace[sizeof(rspace) - 1] = IPOPT_EOL; 432 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace, 433 sizeof(rspace)) < 0) 434 err(EX_OSERR, "setsockopt IP_OPTIONS"); 435 #else 436 errx(EX_UNAVAILABLE, 437 "record route not available in this implementation"); 438 #endif /* IP_OPTIONS */ 439 } 440 441 if (options & F_NOLOOP) { 442 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, 443 sizeof(loop)) < 0) { 444 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP"); 445 } 446 } 447 if (options & F_MTTL) { 448 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, 449 sizeof(ttl)) < 0) { 450 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL"); 451 } 452 } 453 if (options & F_MIF) { 454 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, 455 sizeof(ifaddr)) < 0) { 456 err(EX_OSERR, "setsockopt IP_MULTICAST_IF"); 457 } 458 } 459 #ifdef SO_TIMESTAMP 460 { int on = 1; 461 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0) 462 err(EX_OSERR, "setsockopt SO_TIMESTAMP"); 463 } 464 #endif 465 466 /* 467 * When pinging the broadcast address, you can get a lot of answers. 468 * Doing something so evil is useful if you are trying to stress the 469 * ethernet, or just want to fill the arp cache to get some stuff for 470 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast 471 * or multicast pings if they wish. 472 */ 473 hold = 48 * 1024; 474 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold, 475 sizeof(hold)); 476 477 if (to->sin_family == AF_INET) { 478 (void)printf("PING %s (%s)", hostname, 479 inet_ntoa(to->sin_addr)); 480 if (source) 481 (void)printf(" from %s", shostname); 482 (void)printf(": %d data bytes\n", datalen); 483 } else 484 (void)printf("PING %s: %d data bytes\n", hostname, datalen); 485 486 /* 487 * Use sigaction() instead of signal() to get unambiguous semantics, 488 * in particular with SA_RESTART not set. 489 */ 490 491 sigemptyset(&si_sa.sa_mask); 492 si_sa.sa_flags = 0; 493 494 si_sa.sa_handler = stopit; 495 if (sigaction(SIGINT, &si_sa, 0) == -1) { 496 err(EX_OSERR, "sigaction SIGINT"); 497 } 498 499 si_sa.sa_handler = status; 500 if (sigaction(SIGINFO, &si_sa, 0) == -1) { 501 err(EX_OSERR, "sigaction"); 502 } 503 504 bzero(&msg, sizeof(msg)); 505 msg.msg_name = (caddr_t)&from; 506 msg.msg_iov = &iov; 507 msg.msg_iovlen = 1; 508 #ifdef SO_TIMESTAMP 509 msg.msg_control = (caddr_t)ctrl; 510 #endif 511 iov.iov_base = packet; 512 iov.iov_len = packlen; 513 514 if (tcgetattr(STDOUT_FILENO, &ts) != -1) { 515 reset_kerninfo = !(ts.c_lflag & NOKERNINFO); 516 ts.c_lflag |= NOKERNINFO; 517 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 518 } 519 520 while (preload--) /* fire off them quickies */ 521 pinger(); 522 523 if (options & F_FLOOD) { 524 intvl.tv_sec = 0; 525 intvl.tv_usec = 10000; 526 } else { 527 intvl.tv_sec = interval / 1000; 528 intvl.tv_usec = interval % 1000 * 1000; 529 } 530 531 pinger(); /* send the first ping */ 532 (void)gettimeofday(&last, NULL); 533 534 while (!finish_up) { 535 register int cc; 536 int n; 537 struct timeval timeout, now; 538 fd_set rfds; 539 540 check_status(); 541 FD_ZERO(&rfds); 542 FD_SET(s, &rfds); 543 (void)gettimeofday(&now, NULL); 544 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec; 545 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec; 546 while (timeout.tv_usec < 0) { 547 timeout.tv_usec += 1000000; 548 timeout.tv_sec--; 549 } 550 while (timeout.tv_usec >= 1000000) { 551 timeout.tv_usec -= 1000000; 552 timeout.tv_sec++; 553 } 554 if (timeout.tv_sec < 0) 555 timeout.tv_sec = timeout.tv_usec = 0; 556 n = select(s + 1, &rfds, NULL, NULL, &timeout); 557 if (n == 1) { 558 struct timeval *t = 0; 559 #ifdef SO_TIMESTAMP 560 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl; 561 562 msg.msg_controllen = sizeof(ctrl); 563 #endif 564 msg.msg_namelen = sizeof(from); 565 if ((cc = recvmsg(s, &msg, 0)) < 0) { 566 if (errno == EINTR) 567 continue; 568 warn("recvmsg"); 569 continue; 570 } 571 #ifdef SO_TIMESTAMP 572 if (cmsg->cmsg_level == SOL_SOCKET && 573 cmsg->cmsg_type == SCM_TIMESTAMP && 574 cmsg->cmsg_len == (sizeof *cmsg + sizeof *t)) { 575 /* Copy to avoid alignment problems: */ 576 memcpy(&now,CMSG_DATA(cmsg),sizeof(now)); 577 t = &now; 578 } 579 #endif 580 if (t == 0) { 581 (void)gettimeofday(&now, NULL); 582 t = &now; 583 } 584 pr_pack((char *)packet, cc, &from, t); 585 if (npackets && nreceived >= npackets) 586 break; 587 } 588 if (n == 0) { 589 if (!npackets || ntransmitted < npackets) 590 pinger(); 591 else { 592 if (almost_done) 593 break; 594 almost_done = 1; 595 if (nreceived) { 596 intvl.tv_sec = 2 * tmax / 1000; 597 if (!intvl.tv_sec) 598 intvl.tv_sec = 1; 599 } else 600 intvl.tv_sec = MAXWAIT; 601 } 602 (void)gettimeofday(&last, NULL); 603 } 604 } 605 finish(); 606 /* NOTREACHED */ 607 exit(0); /* Make the compiler happy */ 608 } 609 610 /* 611 * stopit -- 612 * Set the global bit that causes the main loop to quit. 613 * Do NOT call finish() from here, since finish() does far too much 614 * to be called from a signal handler. 615 */ 616 void 617 stopit(sig) 618 int sig; 619 { 620 finish_up = 1; 621 } 622 623 /* 624 * pinger -- 625 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 626 * will be added on by the kernel. The ID field is our UNIX process ID, 627 * and the sequence number is an ascending integer. The first 8 bytes 628 * of the data portion are used to hold a UNIX "timeval" struct in host 629 * byte-order, to compute the round-trip time. 630 */ 631 static void 632 pinger(void) 633 { 634 register struct icmp *icp; 635 register int cc; 636 int i; 637 638 icp = (struct icmp *)outpack; 639 icp->icmp_type = ICMP_ECHO; 640 icp->icmp_code = 0; 641 icp->icmp_cksum = 0; 642 icp->icmp_seq = ntransmitted; 643 icp->icmp_id = ident; /* ID */ 644 645 CLR(icp->icmp_seq % mx_dup_ck); 646 647 if (timing) 648 (void)gettimeofday((struct timeval *)&outpack[8], 649 (struct timezone *)NULL); 650 651 cc = datalen + PHDR_LEN; /* skips ICMP portion */ 652 653 /* compute ICMP checksum here */ 654 icp->icmp_cksum = in_cksum((u_short *)icp, cc); 655 656 i = sendto(s, (char *)outpack, cc, 0, &whereto, 657 sizeof(struct sockaddr)); 658 659 if (i < 0 || i != cc) { 660 if (i < 0) { 661 if (options & F_FLOOD && errno == ENOBUFS) { 662 usleep(FLOOD_BACKOFF); 663 return; 664 } 665 warn("sendto"); 666 } else { 667 warn("%s: partial write: %d of %d bytes", 668 hostname, i, cc); 669 } 670 } 671 ntransmitted++; 672 if (!(options & F_QUIET) && options & F_FLOOD) 673 (void)write(STDOUT_FILENO, &DOT, 1); 674 } 675 676 /* 677 * pr_pack -- 678 * Print out the packet, if it came from us. This logic is necessary 679 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 680 * which arrive ('tis only fair). This permits multiple copies of this 681 * program to be run without having intermingled output (or statistics!). 682 */ 683 static void 684 pr_pack(buf, cc, from, tv) 685 char *buf; 686 int cc; 687 struct sockaddr_in *from; 688 struct timeval *tv; 689 { 690 register struct icmp *icp; 691 register u_long l; 692 register int i, j; 693 register u_char *cp,*dp; 694 static int old_rrlen; 695 static char old_rr[MAX_IPOPTLEN]; 696 struct ip *ip; 697 struct timeval *tp; 698 double triptime; 699 int hlen, dupflag; 700 701 /* Check the IP header */ 702 ip = (struct ip *)buf; 703 hlen = ip->ip_hl << 2; 704 if (cc < hlen + ICMP_MINLEN) { 705 if (options & F_VERBOSE) 706 warn("packet too short (%d bytes) from %s", cc, 707 inet_ntoa(from->sin_addr)); 708 return; 709 } 710 711 /* Now the ICMP part */ 712 cc -= hlen; 713 icp = (struct icmp *)(buf + hlen); 714 if (icp->icmp_type == ICMP_ECHOREPLY) { 715 if (icp->icmp_id != ident) 716 return; /* 'Twas not our ECHO */ 717 ++nreceived; 718 triptime = 0.0; 719 if (timing) { 720 struct timeval tv1; 721 #ifndef icmp_data 722 tp = (struct timeval *)&icp->icmp_ip; 723 #else 724 tp = (struct timeval *)icp->icmp_data; 725 #endif 726 /* Avoid unaligned data: */ 727 memcpy(&tv1,tp,sizeof(tv1)); 728 tvsub(tv, &tv1); 729 triptime = ((double)tv->tv_sec) * 1000.0 + 730 ((double)tv->tv_usec) / 1000.0; 731 tsum += triptime; 732 tsumsq += triptime * triptime; 733 if (triptime < tmin) 734 tmin = triptime; 735 if (triptime > tmax) 736 tmax = triptime; 737 } 738 739 if (TST(icp->icmp_seq % mx_dup_ck)) { 740 ++nrepeats; 741 --nreceived; 742 dupflag = 1; 743 } else { 744 SET(icp->icmp_seq % mx_dup_ck); 745 dupflag = 0; 746 } 747 748 if (options & F_QUIET) 749 return; 750 751 if (options & F_FLOOD) 752 (void)write(STDOUT_FILENO, &BSPACE, 1); 753 else { 754 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 755 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 756 icp->icmp_seq); 757 (void)printf(" ttl=%d", ip->ip_ttl); 758 if (timing) 759 (void)printf(" time=%.3f ms", triptime); 760 if (dupflag) 761 (void)printf(" (DUP!)"); 762 if (options & F_AUDIBLE) 763 (void)printf("\a"); 764 /* check the data */ 765 cp = (u_char*)&icp->icmp_data[PHDR_LEN]; 766 dp = &outpack[8 + PHDR_LEN]; 767 for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) { 768 if (*cp != *dp) { 769 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 770 i, *dp, *cp); 771 printf("\ncp:"); 772 cp = (u_char*)&icp->icmp_data[0]; 773 for (i = 0; i < datalen; ++i, ++cp) { 774 if ((i % 32) == 8) 775 (void)printf("\n\t"); 776 (void)printf("%x ", *cp); 777 } 778 printf("\ndp:"); 779 cp = &outpack[8]; 780 for (i = 0; i < datalen; ++i, ++cp) { 781 if ((i % 32) == 8) 782 (void)printf("\n\t"); 783 (void)printf("%x ", *cp); 784 } 785 break; 786 } 787 } 788 } 789 } else { 790 /* 791 * We've got something other than an ECHOREPLY. 792 * See if it's a reply to something that we sent. 793 * We can compare IP destination, protocol, 794 * and ICMP type and ID. 795 * 796 * Only print all the error messages if we are running 797 * as root to avoid leaking information not normally 798 * available to those not running as root. 799 */ 800 #ifndef icmp_data 801 struct ip *oip = &icp->icmp_ip; 802 #else 803 struct ip *oip = (struct ip *)icp->icmp_data; 804 #endif 805 struct icmp *oicmp = (struct icmp *)(oip + 1); 806 807 if (((options & F_VERBOSE) && uid == 0) || 808 (!(options & F_QUIET2) && 809 (oip->ip_dst.s_addr == 810 ((struct sockaddr_in *)&whereto)->sin_addr.s_addr) && 811 (oip->ip_p == IPPROTO_ICMP) && 812 (oicmp->icmp_type == ICMP_ECHO) && 813 (oicmp->icmp_id == ident))) { 814 (void)printf("%d bytes from %s: ", cc, 815 pr_addr(from->sin_addr)); 816 pr_icmph(icp); 817 } else 818 return; 819 } 820 821 /* Display any IP options */ 822 cp = (u_char *)buf + sizeof(struct ip); 823 824 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 825 switch (*cp) { 826 case IPOPT_EOL: 827 hlen = 0; 828 break; 829 case IPOPT_LSRR: 830 (void)printf("\nLSRR: "); 831 hlen -= 2; 832 j = *++cp; 833 ++cp; 834 if (j > IPOPT_MINOFF) 835 for (;;) { 836 l = *++cp; 837 l = (l<<8) + *++cp; 838 l = (l<<8) + *++cp; 839 l = (l<<8) + *++cp; 840 if (l == 0) { 841 printf("\t0.0.0.0"); 842 } else { 843 struct in_addr ina; 844 ina.s_addr = ntohl(l); 845 printf("\t%s", pr_addr(ina)); 846 } 847 hlen -= 4; 848 j -= 4; 849 if (j <= IPOPT_MINOFF) 850 break; 851 (void)putchar('\n'); 852 } 853 break; 854 case IPOPT_RR: 855 j = *++cp; /* get length */ 856 i = *++cp; /* and pointer */ 857 hlen -= 2; 858 if (i > j) 859 i = j; 860 i -= IPOPT_MINOFF; 861 if (i <= 0) 862 continue; 863 if (i == old_rrlen 864 && cp == (u_char *)buf + sizeof(struct ip) + 2 865 && !bcmp((char *)cp, old_rr, i) 866 && !(options & F_FLOOD)) { 867 (void)printf("\t(same route)"); 868 i = ((i + 3) / 4) * 4; 869 hlen -= i; 870 cp += i; 871 break; 872 } 873 if (i < MAX_IPOPTLEN) { 874 old_rrlen = i; 875 bcopy((char *)cp, old_rr, i); 876 } else 877 old_rrlen = 0; 878 879 (void)printf("\nRR: "); 880 j = 0; 881 for (;;) { 882 l = *++cp; 883 l = (l<<8) + *++cp; 884 l = (l<<8) + *++cp; 885 l = (l<<8) + *++cp; 886 if (l == 0) { 887 printf("\t0.0.0.0"); 888 } else { 889 struct in_addr ina; 890 ina.s_addr = ntohl(l); 891 printf("\t%s", pr_addr(ina)); 892 } 893 hlen -= 4; 894 i -= 4; 895 j += 4; 896 if (i <= 0) 897 break; 898 if (j >= MAX_IPOPTLEN) { 899 (void) printf("\t(truncated route)"); 900 break; 901 } 902 (void)putchar('\n'); 903 } 904 break; 905 case IPOPT_NOP: 906 (void)printf("\nNOP"); 907 break; 908 default: 909 (void)printf("\nunknown option %x", *cp); 910 break; 911 } 912 if (!(options & F_FLOOD)) { 913 (void)putchar('\n'); 914 (void)fflush(stdout); 915 } 916 } 917 918 /* 919 * in_cksum -- 920 * Checksum routine for Internet Protocol family headers (C Version) 921 */ 922 u_short 923 in_cksum(addr, len) 924 u_short *addr; 925 int len; 926 { 927 register int nleft = len; 928 register u_short *w = addr; 929 register int sum = 0; 930 u_short answer = 0; 931 932 /* 933 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 934 * sequential 16 bit words to it, and at the end, fold back all the 935 * carry bits from the top 16 bits into the lower 16 bits. 936 */ 937 while (nleft > 1) { 938 sum += *w++; 939 nleft -= 2; 940 } 941 942 /* mop up an odd byte, if necessary */ 943 if (nleft == 1) { 944 *(u_char *)(&answer) = *(u_char *)w ; 945 sum += answer; 946 } 947 948 /* add back carry outs from top 16 bits to low 16 bits */ 949 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 950 sum += (sum >> 16); /* add carry */ 951 answer = ~sum; /* truncate to 16 bits */ 952 return(answer); 953 } 954 955 /* 956 * tvsub -- 957 * Subtract 2 timeval structs: out = out - in. Out is assumed to 958 * be >= in. 959 */ 960 static void 961 tvsub(out, in) 962 register struct timeval *out, *in; 963 { 964 if ((out->tv_usec -= in->tv_usec) < 0) { 965 --out->tv_sec; 966 out->tv_usec += 1000000; 967 } 968 out->tv_sec -= in->tv_sec; 969 } 970 971 /* 972 * status -- 973 * Print out statistics when SIGINFO is received. 974 */ 975 976 static void 977 status(sig) 978 int sig; 979 { 980 siginfo_p = 1; 981 } 982 983 static void 984 check_status() 985 { 986 if (siginfo_p) { 987 siginfo_p = 0; 988 (void)fprintf(stderr, 989 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n", 990 nreceived, ntransmitted, 991 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0, 992 nreceived ? tmin : 0.0, 993 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum, 994 tmax); 995 } 996 } 997 998 /* 999 * finish -- 1000 * Print out statistics, and give up. 1001 */ 1002 static void 1003 finish() 1004 { 1005 struct termios ts; 1006 1007 (void)signal(SIGINT, SIG_IGN); 1008 (void)signal(SIGALRM, SIG_IGN); 1009 (void)putchar('\n'); 1010 (void)fflush(stdout); 1011 (void)printf("--- %s ping statistics ---\n", hostname); 1012 (void)printf("%ld packets transmitted, ", ntransmitted); 1013 (void)printf("%ld packets received, ", nreceived); 1014 if (nrepeats) 1015 (void)printf("+%ld duplicates, ", nrepeats); 1016 if (ntransmitted) 1017 if (nreceived > ntransmitted) 1018 (void)printf("-- somebody's printing up packets!"); 1019 else 1020 (void)printf("%d%% packet loss", 1021 (int) (((ntransmitted - nreceived) * 100) / 1022 ntransmitted)); 1023 (void)putchar('\n'); 1024 if (nreceived && timing) { 1025 double n = nreceived + nrepeats; 1026 double avg = tsum / n; 1027 double vari = tsumsq / n - avg * avg; 1028 printf("round-trip min/avg/max/stddev = " 1029 "%.3f/%.3f/%.3f/%.3f ms\n", 1030 tmin, avg, tmax, sqrt(vari)); 1031 } 1032 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 1033 ts.c_lflag &= ~NOKERNINFO; 1034 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 1035 } 1036 1037 if (nreceived) 1038 exit(0); 1039 else 1040 exit(2); 1041 } 1042 1043 #ifdef notdef 1044 static char *ttab[] = { 1045 "Echo Reply", /* ip + seq + udata */ 1046 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1047 "Source Quench", /* IP */ 1048 "Redirect", /* redirect type, gateway, + IP */ 1049 "Echo", 1050 "Time Exceeded", /* transit, frag reassem + IP */ 1051 "Parameter Problem", /* pointer + IP */ 1052 "Timestamp", /* id + seq + three timestamps */ 1053 "Timestamp Reply", /* " */ 1054 "Info Request", /* id + sq */ 1055 "Info Reply" /* " */ 1056 }; 1057 #endif 1058 1059 /* 1060 * pr_icmph -- 1061 * Print a descriptive string about an ICMP header. 1062 */ 1063 static void 1064 pr_icmph(icp) 1065 struct icmp *icp; 1066 { 1067 switch(icp->icmp_type) { 1068 case ICMP_ECHOREPLY: 1069 (void)printf("Echo Reply\n"); 1070 /* XXX ID + Seq + Data */ 1071 break; 1072 case ICMP_UNREACH: 1073 switch(icp->icmp_code) { 1074 case ICMP_UNREACH_NET: 1075 (void)printf("Destination Net Unreachable\n"); 1076 break; 1077 case ICMP_UNREACH_HOST: 1078 (void)printf("Destination Host Unreachable\n"); 1079 break; 1080 case ICMP_UNREACH_PROTOCOL: 1081 (void)printf("Destination Protocol Unreachable\n"); 1082 break; 1083 case ICMP_UNREACH_PORT: 1084 (void)printf("Destination Port Unreachable\n"); 1085 break; 1086 case ICMP_UNREACH_NEEDFRAG: 1087 (void)printf("frag needed and DF set (MTU %d)\n", 1088 ntohs(icp->icmp_nextmtu)); 1089 break; 1090 case ICMP_UNREACH_SRCFAIL: 1091 (void)printf("Source Route Failed\n"); 1092 break; 1093 case ICMP_UNREACH_FILTER_PROHIB: 1094 (void)printf("Communication prohibited by filter\n"); 1095 break; 1096 default: 1097 (void)printf("Dest Unreachable, Bad Code: %d\n", 1098 icp->icmp_code); 1099 break; 1100 } 1101 /* Print returned IP header information */ 1102 #ifndef icmp_data 1103 pr_retip(&icp->icmp_ip); 1104 #else 1105 pr_retip((struct ip *)icp->icmp_data); 1106 #endif 1107 break; 1108 case ICMP_SOURCEQUENCH: 1109 (void)printf("Source Quench\n"); 1110 #ifndef icmp_data 1111 pr_retip(&icp->icmp_ip); 1112 #else 1113 pr_retip((struct ip *)icp->icmp_data); 1114 #endif 1115 break; 1116 case ICMP_REDIRECT: 1117 switch(icp->icmp_code) { 1118 case ICMP_REDIRECT_NET: 1119 (void)printf("Redirect Network"); 1120 break; 1121 case ICMP_REDIRECT_HOST: 1122 (void)printf("Redirect Host"); 1123 break; 1124 case ICMP_REDIRECT_TOSNET: 1125 (void)printf("Redirect Type of Service and Network"); 1126 break; 1127 case ICMP_REDIRECT_TOSHOST: 1128 (void)printf("Redirect Type of Service and Host"); 1129 break; 1130 default: 1131 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1132 break; 1133 } 1134 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1135 #ifndef icmp_data 1136 pr_retip(&icp->icmp_ip); 1137 #else 1138 pr_retip((struct ip *)icp->icmp_data); 1139 #endif 1140 break; 1141 case ICMP_ECHO: 1142 (void)printf("Echo Request\n"); 1143 /* XXX ID + Seq + Data */ 1144 break; 1145 case ICMP_TIMXCEED: 1146 switch(icp->icmp_code) { 1147 case ICMP_TIMXCEED_INTRANS: 1148 (void)printf("Time to live exceeded\n"); 1149 break; 1150 case ICMP_TIMXCEED_REASS: 1151 (void)printf("Frag reassembly time exceeded\n"); 1152 break; 1153 default: 1154 (void)printf("Time exceeded, Bad Code: %d\n", 1155 icp->icmp_code); 1156 break; 1157 } 1158 #ifndef icmp_data 1159 pr_retip(&icp->icmp_ip); 1160 #else 1161 pr_retip((struct ip *)icp->icmp_data); 1162 #endif 1163 break; 1164 case ICMP_PARAMPROB: 1165 (void)printf("Parameter problem: pointer = 0x%02x\n", 1166 icp->icmp_hun.ih_pptr); 1167 #ifndef icmp_data 1168 pr_retip(&icp->icmp_ip); 1169 #else 1170 pr_retip((struct ip *)icp->icmp_data); 1171 #endif 1172 break; 1173 case ICMP_TSTAMP: 1174 (void)printf("Timestamp\n"); 1175 /* XXX ID + Seq + 3 timestamps */ 1176 break; 1177 case ICMP_TSTAMPREPLY: 1178 (void)printf("Timestamp Reply\n"); 1179 /* XXX ID + Seq + 3 timestamps */ 1180 break; 1181 case ICMP_IREQ: 1182 (void)printf("Information Request\n"); 1183 /* XXX ID + Seq */ 1184 break; 1185 case ICMP_IREQREPLY: 1186 (void)printf("Information Reply\n"); 1187 /* XXX ID + Seq */ 1188 break; 1189 case ICMP_MASKREQ: 1190 (void)printf("Address Mask Request\n"); 1191 break; 1192 case ICMP_MASKREPLY: 1193 (void)printf("Address Mask Reply\n"); 1194 break; 1195 case ICMP_ROUTERADVERT: 1196 (void)printf("Router Advertisement\n"); 1197 break; 1198 case ICMP_ROUTERSOLICIT: 1199 (void)printf("Router Solicitation\n"); 1200 break; 1201 default: 1202 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1203 } 1204 } 1205 1206 /* 1207 * pr_iph -- 1208 * Print an IP header with options. 1209 */ 1210 static void 1211 pr_iph(ip) 1212 struct ip *ip; 1213 { 1214 int hlen; 1215 u_char *cp; 1216 1217 hlen = ip->ip_hl << 2; 1218 cp = (u_char *)ip + 20; /* point to options */ 1219 1220 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1221 (void)printf(" %1x %1x %02x %04x %04x", 1222 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1223 ntohs(ip->ip_id)); 1224 (void)printf(" %1lx %04lx", 1225 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1226 (u_long) ntohl(ip->ip_off) & 0x1fff); 1227 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1228 ntohs(ip->ip_sum)); 1229 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1230 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1231 /* dump any option bytes */ 1232 while (hlen-- > 20) { 1233 (void)printf("%02x", *cp++); 1234 } 1235 (void)putchar('\n'); 1236 } 1237 1238 /* 1239 * pr_addr -- 1240 * Return an ascii host address as a dotted quad and optionally with 1241 * a hostname. 1242 */ 1243 static char * 1244 pr_addr(ina) 1245 struct in_addr ina; 1246 { 1247 struct hostent *hp; 1248 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1249 1250 if ((options & F_NUMERIC) || 1251 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1252 return inet_ntoa(ina); 1253 else 1254 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1255 inet_ntoa(ina)); 1256 return(buf); 1257 } 1258 1259 /* 1260 * pr_retip -- 1261 * Dump some info on a returned (via ICMP) IP packet. 1262 */ 1263 static void 1264 pr_retip(ip) 1265 struct ip *ip; 1266 { 1267 int hlen; 1268 u_char *cp; 1269 1270 pr_iph(ip); 1271 hlen = ip->ip_hl << 2; 1272 cp = (u_char *)ip + hlen; 1273 1274 if (ip->ip_p == 6) 1275 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1276 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1277 else if (ip->ip_p == 17) 1278 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1279 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1280 } 1281 1282 static void 1283 fill(bp, patp) 1284 char *bp, *patp; 1285 { 1286 register int ii, jj, kk; 1287 int pat[16]; 1288 char *cp; 1289 1290 for (cp = patp; *cp; cp++) { 1291 if (!isxdigit(*cp)) 1292 errx(EX_USAGE, 1293 "patterns must be specified as hex digits"); 1294 1295 } 1296 ii = sscanf(patp, 1297 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1298 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1299 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1300 &pat[13], &pat[14], &pat[15]); 1301 1302 if (ii > 0) 1303 for (kk = 0; 1304 kk <= MAXPACKET - (8 + PHDR_LEN + ii); 1305 kk += ii) 1306 for (jj = 0; jj < ii; ++jj) 1307 bp[jj + kk] = pat[jj]; 1308 if (!(options & F_QUIET)) { 1309 (void)printf("PATTERN: 0x"); 1310 for (jj = 0; jj < ii; ++jj) 1311 (void)printf("%02x", bp[jj] & 0xFF); 1312 (void)printf("\n"); 1313 } 1314 } 1315 1316 static void 1317 usage() 1318 { 1319 fprintf(stderr, "%s\n%s\n%s\n", 1320 "usage: ping [-QRadfnqrv] [-c count] [-i wait] [-l preload] [-p pattern]", 1321 " [-s packetsize] [-S src_addr]", 1322 " [host | [-L] [-I iface] [-T ttl] mcast-group]"); 1323 exit(EX_USAGE); 1324 } 1325