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 "$FreeBSD$"; 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 #include <sys/socket.h> 71 #include <sys/sysctl.h> 72 #include <sys/time.h> 73 #include <sys/uio.h> 74 75 #include <netinet/in.h> 76 #include <netinet/in_systm.h> 77 #include <netinet/ip.h> 78 #include <netinet/ip_icmp.h> 79 #include <netinet/ip_var.h> 80 #include <arpa/inet.h> 81 82 #ifdef IPSEC 83 #include <netinet6/ipsec.h> 84 #endif /*IPSEC*/ 85 86 #include <ctype.h> 87 #include <err.h> 88 #include <errno.h> 89 #include <math.h> 90 #include <netdb.h> 91 #include <signal.h> 92 #include <stdio.h> 93 #include <stdlib.h> 94 #include <string.h> 95 #include <sysexits.h> 96 #include <termios.h> 97 #include <unistd.h> 98 99 #define INADDR_LEN ((int)sizeof(in_addr_t)) 100 #define PHDR_LEN ((int)sizeof(struct timeval)) 101 #define DEFDATALEN (64 - PHDR_LEN) /* default data length */ 102 #define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */ 103 /* runs out of buffer space */ 104 #define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN) 105 #define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN) 106 #define MINICMPLEN ICMP_MINLEN 107 #define MASKLEN (options & F_MASK ? 4 : 0) 108 #define MAXWAIT 10 /* max seconds to wait for response */ 109 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */ 110 #define MAXTOS 255 111 112 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ 113 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ 114 #define SET(bit) (A(bit) |= B(bit)) 115 #define CLR(bit) (A(bit) &= (~B(bit))) 116 #define TST(bit) (A(bit) & B(bit)) 117 118 /* various options */ 119 int options; 120 #define F_FLOOD 0x0001 121 #define F_INTERVAL 0x0002 122 #define F_NUMERIC 0x0004 123 #define F_PINGFILLED 0x0008 124 #define F_QUIET 0x0010 125 #define F_RROUTE 0x0020 126 #define F_SO_DEBUG 0x0040 127 #define F_SO_DONTROUTE 0x0080 128 #define F_VERBOSE 0x0100 129 #define F_QUIET2 0x0200 130 #define F_NOLOOP 0x0400 131 #define F_MTTL 0x0800 132 #define F_MIF 0x1000 133 #define F_AUDIBLE 0x2000 134 #ifdef IPSEC 135 #ifdef IPSEC_POLICY_IPSEC 136 #define F_POLICY 0x4000 137 #endif /*IPSEC_POLICY_IPSEC*/ 138 #endif /*IPSEC*/ 139 #define F_TTL 0x8000 140 #define F_MISSED 0x10000 141 #define F_ONCE 0x20000 142 #define F_HDRINCL 0x40000 143 #define F_MASK 0x80000 144 145 /* 146 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum 147 * number of received sequence numbers we can keep track of. Change 128 148 * to 8192 for complete accuracy... 149 */ 150 #define MAX_DUP_CHK (8 * 128) 151 int mx_dup_ck = MAX_DUP_CHK; 152 char rcvd_tbl[MAX_DUP_CHK / 8]; 153 154 struct sockaddr_in whereto; /* who to ping */ 155 long maxpayload; 156 int datalen = DEFDATALEN; 157 int s; /* socket file descriptor */ 158 u_char outpackhdr[IP_MAXPACKET], *outpack; 159 char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */ 160 char BSPACE = '\b'; /* characters written for flood */ 161 char DOT = '.'; 162 char *hostname; 163 char *shostname; 164 int ident; /* process id to identify our packets */ 165 int uid; /* cached uid for micro-optimization */ 166 167 /* counters */ 168 long nmissedmax; /* max value of ntransmitted - nreceived - 1 */ 169 long npackets; /* max packets to transmit */ 170 long nreceived; /* # of packets we got back */ 171 long nrepeats; /* number of duplicates */ 172 long ntransmitted; /* sequence # for outbound packets = #sent */ 173 int interval = 1000; /* interval between packets, ms */ 174 175 /* timing */ 176 int timing; /* flag to do timing */ 177 double tmin = 999999999.0; /* minimum round trip time */ 178 double tmax = 0.0; /* maximum round trip time */ 179 double tsum = 0.0; /* sum of all times, for doing average */ 180 double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ 181 182 volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */ 183 int reset_kerninfo; 184 volatile sig_atomic_t siginfo_p; 185 186 static void fill(char *, char *); 187 static u_short in_cksum(u_short *, int); 188 static void check_status(void); 189 static void finish(void) __dead2; 190 static void pinger(void); 191 static char *pr_addr(struct in_addr); 192 static void pr_icmph(struct icmp *); 193 static void pr_iph(struct ip *); 194 static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *); 195 static void pr_retip(struct ip *); 196 static void status(int); 197 static void stopit(int); 198 static void tvsub(struct timeval *, struct timeval *); 199 static void usage(void) __dead2; 200 201 int 202 main(argc, argv) 203 int argc; 204 char *const *argv; 205 { 206 struct sockaddr_in from, sin; 207 struct in_addr ifaddr; 208 struct timeval last, intvl; 209 struct iovec iov; 210 struct ip *ip; 211 struct msghdr msg; 212 struct sigaction si_sa; 213 struct termios ts; 214 size_t sz; 215 u_char *datap, packet[IP_MAXPACKET]; 216 char *ep, *source, *target; 217 struct hostent *hp; 218 #ifdef IPSEC_POLICY_IPSEC 219 char *policy_in, *policy_out; 220 #endif 221 struct sockaddr_in *to; 222 double t; 223 u_long alarmtimeout, ultmp; 224 int almost_done, ch, df, hold, i, mib[4], packlen, preload, sockerrno, 225 tos, ttl; 226 char ctrl[CMSG_SPACE(sizeof(struct timeval))]; 227 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN]; 228 #ifdef IP_OPTIONS 229 char rspace[MAX_IPOPTLEN]; /* record route space */ 230 #endif 231 unsigned char loop, mttl; 232 233 source = NULL; 234 #ifdef IPSEC_POLICY_IPSEC 235 policy_in = policy_out = NULL; 236 #endif 237 238 /* 239 * Do the stuff that we need root priv's for *first*, and 240 * then drop our setuid bit. Save error reporting for 241 * after arg parsing. 242 */ 243 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 244 sockerrno = errno; 245 246 setuid(getuid()); 247 uid = getuid(); 248 249 alarmtimeout = df = preload = tos = 0; 250 251 outpack = outpackhdr + sizeof(struct ip); 252 datap = &outpack[MINICMPLEN + PHDR_LEN]; 253 while ((ch = getopt(argc, argv, 254 "ADI:LQRS:T:c:adfi:l:m:Mnop:qrs:t:vz:" 255 #ifdef IPSEC 256 #ifdef IPSEC_POLICY_IPSEC 257 "P:" 258 #endif /*IPSEC_POLICY_IPSEC*/ 259 #endif /*IPSEC*/ 260 )) != -1) 261 { 262 switch(ch) { 263 case 'A': 264 options |= F_MISSED; 265 break; 266 case 'a': 267 options |= F_AUDIBLE; 268 break; 269 case 'c': 270 ultmp = strtoul(optarg, &ep, 0); 271 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp) 272 errx(EX_USAGE, 273 "invalid count of packets to transmit: `%s'", 274 optarg); 275 npackets = ultmp; 276 break; 277 case 'D': 278 options |= F_HDRINCL; 279 df = 1; 280 break; 281 case 'd': 282 options |= F_SO_DEBUG; 283 break; 284 case 'f': 285 if (uid) { 286 errno = EPERM; 287 err(EX_NOPERM, "-f flag"); 288 } 289 options |= F_FLOOD; 290 setbuf(stdout, (char *)NULL); 291 break; 292 case 'i': /* wait between sending packets */ 293 t = strtod(optarg, &ep) * 1000.0; 294 if (*ep || ep == optarg || t > (double)INT_MAX) 295 errx(EX_USAGE, "invalid timing interval: `%s'", 296 optarg); 297 options |= F_INTERVAL; 298 interval = (int)t; 299 if (uid && interval < 1000) { 300 errno = EPERM; 301 err(EX_NOPERM, "-i interval too short"); 302 } 303 break; 304 case 'I': /* multicast interface */ 305 if (inet_aton(optarg, &ifaddr) == 0) 306 errx(EX_USAGE, 307 "invalid multicast interface: `%s'", 308 optarg); 309 options |= F_MIF; 310 break; 311 case 'l': 312 ultmp = strtoul(optarg, &ep, 0); 313 if (*ep || ep == optarg || ultmp > INT_MAX) 314 errx(EX_USAGE, 315 "invalid preload value: `%s'", optarg); 316 if (uid) { 317 errno = EPERM; 318 err(EX_NOPERM, "-l flag"); 319 } 320 preload = ultmp; 321 break; 322 case 'L': 323 options |= F_NOLOOP; 324 loop = 0; 325 break; 326 case 'm': /* TTL */ 327 ultmp = strtoul(optarg, &ep, 0); 328 if (*ep || ep == optarg || ultmp > MAXTTL) 329 errx(EX_USAGE, "invalid TTL: `%s'", optarg); 330 ttl = ultmp; 331 options |= F_TTL; 332 break; 333 case 'M': 334 options |= F_MASK; 335 break; 336 case 'n': 337 options |= F_NUMERIC; 338 break; 339 case 'o': 340 options |= F_ONCE; 341 break; 342 case 'p': /* fill buffer with user pattern */ 343 options |= F_PINGFILLED; 344 fill((char *)datap, optarg); 345 break; 346 case 'Q': 347 options |= F_QUIET2; 348 break; 349 case 'q': 350 options |= F_QUIET; 351 break; 352 case 'R': 353 options |= F_RROUTE; 354 break; 355 case 'r': 356 options |= F_SO_DONTROUTE; 357 break; 358 case 's': /* size of packet to send */ 359 ultmp = strtoul(optarg, &ep, 0); 360 if (*ep || ep == optarg) 361 errx(EX_USAGE, "invalid packet size: `%s'", 362 optarg); 363 if (uid != 0 && ultmp > DEFDATALEN) { 364 errno = EPERM; 365 err(EX_NOPERM, 366 "packet size too large: %lu > %u", 367 ultmp, DEFDATALEN); 368 } 369 datalen = ultmp; 370 break; 371 case 'S': 372 source = optarg; 373 break; 374 case 't': 375 alarmtimeout = strtoul(optarg, &ep, 0); 376 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX)) 377 errx(EX_USAGE, "invalid timeout: `%s'", 378 optarg); 379 if (alarmtimeout > MAXALARM) 380 errx(EX_USAGE, "invalid timeout: `%s' > %d", 381 optarg, MAXALARM); 382 alarm((int)alarmtimeout); 383 break; 384 case 'T': /* multicast TTL */ 385 ultmp = strtoul(optarg, &ep, 0); 386 if (*ep || ep == optarg || ultmp > MAXTTL) 387 errx(EX_USAGE, "invalid multicast TTL: `%s'", 388 optarg); 389 mttl = ultmp; 390 options |= F_MTTL; 391 break; 392 case 'v': 393 options |= F_VERBOSE; 394 break; 395 #ifdef IPSEC 396 #ifdef IPSEC_POLICY_IPSEC 397 case 'P': 398 options |= F_POLICY; 399 if (!strncmp("in", optarg, 2)) 400 policy_in = strdup(optarg); 401 else if (!strncmp("out", optarg, 3)) 402 policy_out = strdup(optarg); 403 else 404 errx(1, "invalid security policy"); 405 break; 406 case 'z': 407 options |= F_HDRINCL; 408 ultmp = strtoul(optarg, &ep, 0); 409 if (*ep || ep == optarg || ultmp > MAXTOS) 410 errx(EX_USAGE, "invalid TOS: `%s'", optarg); 411 tos = ultmp; 412 break; 413 #endif /*IPSEC_POLICY_IPSEC*/ 414 #endif /*IPSEC*/ 415 default: 416 usage(); 417 } 418 } 419 420 if (argc - optind != 1) 421 usage(); 422 target = argv[optind]; 423 424 maxpayload = IP_MAXPACKET - sizeof(struct ip) - MINICMPLEN; 425 if (options & F_RROUTE) 426 maxpayload -= MAX_IPOPTLEN; 427 if (datalen > maxpayload) 428 errx(EX_USAGE, "packet size too large: %lu > %u", datalen, 429 maxpayload); 430 if (source) { 431 bzero((char *)&sin, sizeof(sin)); 432 sin.sin_family = AF_INET; 433 if (inet_aton(source, &sin.sin_addr) != 0) { 434 shostname = source; 435 } else { 436 hp = gethostbyname2(source, AF_INET); 437 if (!hp) 438 errx(EX_NOHOST, "cannot resolve %s: %s", 439 source, hstrerror(h_errno)); 440 441 sin.sin_len = sizeof sin; 442 if (hp->h_length > sizeof(sin.sin_addr) || 443 hp->h_length < 0) 444 errx(1, "gethostbyname2: illegal address"); 445 memcpy(&sin.sin_addr, hp->h_addr_list[0], 446 sizeof(sin.sin_addr)); 447 (void)strncpy(snamebuf, hp->h_name, 448 sizeof(snamebuf) - 1); 449 snamebuf[sizeof(snamebuf) - 1] = '\0'; 450 shostname = snamebuf; 451 } 452 if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1) 453 err(1, "bind"); 454 } 455 456 bzero(&whereto, sizeof(whereto)); 457 to = &whereto; 458 to->sin_family = AF_INET; 459 to->sin_len = sizeof *to; 460 if (inet_aton(target, &to->sin_addr) != 0) { 461 hostname = target; 462 } else { 463 hp = gethostbyname2(target, AF_INET); 464 if (!hp) 465 errx(EX_NOHOST, "cannot resolve %s: %s", 466 target, hstrerror(h_errno)); 467 468 if (hp->h_length > sizeof(to->sin_addr)) 469 errx(1, "gethostbyname2 returned an illegal address"); 470 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 471 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 472 hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 473 hostname = hnamebuf; 474 } 475 476 if (options & F_FLOOD && options & F_INTERVAL) 477 errx(EX_USAGE, "-f and -i: incompatible options"); 478 479 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 480 errx(EX_USAGE, 481 "-f flag cannot be used with multicast destination"); 482 if (options & (F_MIF | F_NOLOOP | F_MTTL) 483 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 484 errx(EX_USAGE, 485 "-I, -L, -T flags cannot be used with unicast destination"); 486 487 if (datalen - MASKLEN >= PHDR_LEN) /* can we time transfer */ 488 timing = 1; 489 packlen = MAXIPLEN + MAXICMPLEN + datalen; 490 packlen = packlen > IP_MAXPACKET ? IP_MAXPACKET : packlen; 491 492 if (!(options & F_PINGFILLED)) 493 for (i = PHDR_LEN; i < datalen; ++i) 494 *datap++ = i; 495 496 ident = getpid() & 0xFFFF; 497 498 if (s < 0) { 499 errno = sockerrno; 500 err(EX_OSERR, "socket"); 501 } 502 hold = 1; 503 if (options & F_SO_DEBUG) 504 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold, 505 sizeof(hold)); 506 if (options & F_SO_DONTROUTE) 507 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, 508 sizeof(hold)); 509 #ifdef IPSEC 510 #ifdef IPSEC_POLICY_IPSEC 511 if (options & F_POLICY) { 512 char *buf; 513 if (policy_in != NULL) { 514 buf = ipsec_set_policy(policy_in, strlen(policy_in)); 515 if (buf == NULL) 516 errx(EX_CONFIG, "%s", ipsec_strerror()); 517 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 518 buf, ipsec_get_policylen(buf)) < 0) 519 err(EX_CONFIG, 520 "ipsec policy cannot be configured"); 521 free(buf); 522 } 523 524 if (policy_out != NULL) { 525 buf = ipsec_set_policy(policy_out, strlen(policy_out)); 526 if (buf == NULL) 527 errx(EX_CONFIG, "%s", ipsec_strerror()); 528 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 529 buf, ipsec_get_policylen(buf)) < 0) 530 err(EX_CONFIG, 531 "ipsec policy cannot be configured"); 532 free(buf); 533 } 534 } 535 #endif /*IPSEC_POLICY_IPSEC*/ 536 #endif /*IPSEC*/ 537 538 if (options & F_HDRINCL) { 539 ip = (struct ip*)outpackhdr; 540 if (!(options & (F_TTL | F_MTTL))) { 541 mib[0] = CTL_NET; 542 mib[1] = PF_INET; 543 mib[2] = IPPROTO_IP; 544 mib[3] = IPCTL_DEFTTL; 545 sz = sizeof(ttl); 546 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1) 547 err(1, "sysctl(net.inet.ip.ttl)"); 548 } 549 setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold)); 550 ip->ip_v = IPVERSION; 551 ip->ip_hl = sizeof(struct ip) >> 2; 552 ip->ip_tos = tos; 553 ip->ip_id = 0; 554 ip->ip_off = df ? IP_DF : 0; 555 ip->ip_ttl = ttl; 556 ip->ip_p = IPPROTO_ICMP; 557 ip->ip_src.s_addr = source ? sin.sin_addr.s_addr : INADDR_ANY; 558 ip->ip_dst = to->sin_addr; 559 } 560 /* record route option */ 561 if (options & F_RROUTE) { 562 #ifdef IP_OPTIONS 563 bzero(rspace, sizeof(rspace)); 564 rspace[IPOPT_OPTVAL] = IPOPT_RR; 565 rspace[IPOPT_OLEN] = sizeof(rspace) - 1; 566 rspace[IPOPT_OFFSET] = IPOPT_MINOFF; 567 rspace[sizeof(rspace) - 1] = IPOPT_EOL; 568 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace, 569 sizeof(rspace)) < 0) 570 err(EX_OSERR, "setsockopt IP_OPTIONS"); 571 #else 572 errx(EX_UNAVAILABLE, 573 "record route not available in this implementation"); 574 #endif /* IP_OPTIONS */ 575 } 576 577 if (options & F_TTL) { 578 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl, 579 sizeof(ttl)) < 0) { 580 err(EX_OSERR, "setsockopt IP_TTL"); 581 } 582 } 583 if (options & F_NOLOOP) { 584 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, 585 sizeof(loop)) < 0) { 586 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP"); 587 } 588 } 589 if (options & F_MTTL) { 590 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, 591 sizeof(mttl)) < 0) { 592 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL"); 593 } 594 } 595 if (options & F_MIF) { 596 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, 597 sizeof(ifaddr)) < 0) { 598 err(EX_OSERR, "setsockopt IP_MULTICAST_IF"); 599 } 600 } 601 #ifdef SO_TIMESTAMP 602 { int on = 1; 603 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0) 604 err(EX_OSERR, "setsockopt SO_TIMESTAMP"); 605 } 606 #endif 607 608 /* 609 * When pinging the broadcast address, you can get a lot of answers. 610 * Doing something so evil is useful if you are trying to stress the 611 * ethernet, or just want to fill the arp cache to get some stuff for 612 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast 613 * or multicast pings if they wish. 614 */ 615 616 /* 617 * XXX receive buffer needs undetermined space for mbuf overhead 618 * as well. 619 */ 620 hold = IP_MAXPACKET + 128; 621 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold, 622 sizeof(hold)); 623 if (uid == 0) 624 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold, 625 sizeof(hold)); 626 627 if (to->sin_family == AF_INET) { 628 (void)printf("PING %s (%s)", hostname, 629 inet_ntoa(to->sin_addr)); 630 if (source) 631 (void)printf(" from %s", shostname); 632 (void)printf(": %d data bytes\n", datalen); 633 } else 634 (void)printf("PING %s: %d data bytes\n", hostname, datalen); 635 636 /* 637 * Use sigaction() instead of signal() to get unambiguous semantics, 638 * in particular with SA_RESTART not set. 639 */ 640 641 sigemptyset(&si_sa.sa_mask); 642 si_sa.sa_flags = 0; 643 644 si_sa.sa_handler = stopit; 645 if (sigaction(SIGINT, &si_sa, 0) == -1) { 646 err(EX_OSERR, "sigaction SIGINT"); 647 } 648 649 si_sa.sa_handler = status; 650 if (sigaction(SIGINFO, &si_sa, 0) == -1) { 651 err(EX_OSERR, "sigaction"); 652 } 653 654 if (alarmtimeout > 0) { 655 si_sa.sa_handler = stopit; 656 if (sigaction(SIGALRM, &si_sa, 0) == -1) 657 err(EX_OSERR, "sigaction SIGALRM"); 658 } 659 660 bzero(&msg, sizeof(msg)); 661 msg.msg_name = (caddr_t)&from; 662 msg.msg_iov = &iov; 663 msg.msg_iovlen = 1; 664 #ifdef SO_TIMESTAMP 665 msg.msg_control = (caddr_t)ctrl; 666 #endif 667 iov.iov_base = packet; 668 iov.iov_len = packlen; 669 670 if (tcgetattr(STDOUT_FILENO, &ts) != -1) { 671 reset_kerninfo = !(ts.c_lflag & NOKERNINFO); 672 ts.c_lflag |= NOKERNINFO; 673 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 674 } 675 676 if (preload == 0) 677 pinger(); /* send the first ping */ 678 else { 679 if (npackets != 0 && preload > npackets) 680 preload = npackets; 681 while (preload--) /* fire off them quickies */ 682 pinger(); 683 } 684 (void)gettimeofday(&last, NULL); 685 686 if (options & F_FLOOD) { 687 intvl.tv_sec = 0; 688 intvl.tv_usec = 10000; 689 } else { 690 intvl.tv_sec = interval / 1000; 691 intvl.tv_usec = interval % 1000 * 1000; 692 } 693 694 almost_done = 0; 695 while (!finish_up) { 696 struct timeval now, timeout; 697 fd_set rfds; 698 int cc, n; 699 700 check_status(); 701 if (s >= FD_SETSIZE) 702 errx(EX_OSERR, "descriptor too large"); 703 FD_ZERO(&rfds); 704 FD_SET(s, &rfds); 705 (void)gettimeofday(&now, NULL); 706 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec; 707 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec; 708 while (timeout.tv_usec < 0) { 709 timeout.tv_usec += 1000000; 710 timeout.tv_sec--; 711 } 712 while (timeout.tv_usec >= 1000000) { 713 timeout.tv_usec -= 1000000; 714 timeout.tv_sec++; 715 } 716 if (timeout.tv_sec < 0) 717 timeout.tv_sec = timeout.tv_usec = 0; 718 n = select(s + 1, &rfds, NULL, NULL, &timeout); 719 if (n < 0) 720 continue; /* Must be EINTR. */ 721 if (n == 1) { 722 struct timeval *t = NULL; 723 #ifdef SO_TIMESTAMP 724 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl; 725 726 msg.msg_controllen = sizeof(ctrl); 727 #endif 728 msg.msg_namelen = sizeof(from); 729 if ((cc = recvmsg(s, &msg, 0)) < 0) { 730 if (errno == EINTR) 731 continue; 732 warn("recvmsg"); 733 continue; 734 } 735 #ifdef SO_TIMESTAMP 736 if (cmsg->cmsg_level == SOL_SOCKET && 737 cmsg->cmsg_type == SCM_TIMESTAMP && 738 cmsg->cmsg_len == CMSG_LEN(sizeof *t)) { 739 /* Copy to avoid alignment problems: */ 740 memcpy(&now, CMSG_DATA(cmsg), sizeof(now)); 741 t = &now; 742 } 743 #endif 744 if (t == NULL) { 745 (void)gettimeofday(&now, NULL); 746 t = &now; 747 } 748 pr_pack((char *)packet, cc, &from, t); 749 if (options & F_ONCE && nreceived || 750 npackets && nreceived >= npackets) 751 break; 752 } 753 if (n == 0 || options & F_FLOOD) { 754 if (!npackets || ntransmitted < npackets) 755 pinger(); 756 else { 757 if (almost_done) 758 break; 759 almost_done = 1; 760 intvl.tv_usec = 0; 761 if (nreceived) { 762 intvl.tv_sec = 2 * tmax / 1000; 763 if (!intvl.tv_sec) 764 intvl.tv_sec = 1; 765 } else 766 intvl.tv_sec = MAXWAIT; 767 } 768 (void)gettimeofday(&last, NULL); 769 if (ntransmitted - nreceived - 1 > nmissedmax) { 770 nmissedmax = ntransmitted - nreceived - 1; 771 if (options & F_MISSED) 772 (void)write(STDOUT_FILENO, &BBELL, 1); 773 } 774 } 775 } 776 finish(); 777 /* NOTREACHED */ 778 exit(0); /* Make the compiler happy */ 779 } 780 781 /* 782 * stopit -- 783 * Set the global bit that causes the main loop to quit. 784 * Do NOT call finish() from here, since finish() does far too much 785 * to be called from a signal handler. 786 */ 787 void 788 stopit(sig) 789 int sig __unused; 790 { 791 792 finish_up = 1; 793 } 794 795 /* 796 * pinger -- 797 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 798 * will be added on by the kernel. The ID field is our UNIX process ID, 799 * and the sequence number is an ascending integer. The first PHDR_LEN 800 * bytes of the data portion are used to hold a UNIX "timeval" struct in 801 * host byte-order, to compute the round-trip time. 802 */ 803 static void 804 pinger(void) 805 { 806 struct ip *ip; 807 struct icmp *icp; 808 int cc, i; 809 u_char *packet; 810 811 packet = outpack; 812 icp = (struct icmp *)outpack; 813 if (options & F_MASK) 814 icp->icmp_type = ICMP_MASKREQ; 815 else 816 icp->icmp_type = ICMP_ECHO; 817 icp->icmp_code = 0; 818 icp->icmp_cksum = 0; 819 icp->icmp_seq = htons(ntransmitted); 820 icp->icmp_id = ident; /* ID */ 821 822 CLR(ntransmitted % mx_dup_ck); 823 824 if (timing) 825 (void)gettimeofday((struct timeval *)&outpack[ 826 MINICMPLEN + MASKLEN], NULL); 827 828 cc = MINICMPLEN + datalen; 829 830 /* compute ICMP checksum here */ 831 icp->icmp_cksum = in_cksum((u_short *)icp, cc); 832 833 if (options & F_HDRINCL) { 834 cc += sizeof(struct ip); 835 ip = (struct ip *)outpackhdr; 836 ip->ip_len = cc; 837 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc); 838 packet = outpackhdr; 839 } 840 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto, 841 sizeof(whereto)); 842 843 if (i < 0 || i != cc) { 844 if (i < 0) { 845 if (options & F_FLOOD && errno == ENOBUFS) { 846 usleep(FLOOD_BACKOFF); 847 return; 848 } 849 warn("sendto"); 850 } else { 851 warn("%s: partial write: %d of %d bytes", 852 hostname, i, cc); 853 } 854 } 855 ntransmitted++; 856 if (!(options & F_QUIET) && options & F_FLOOD) 857 (void)write(STDOUT_FILENO, &DOT, 1); 858 } 859 860 /* 861 * pr_pack -- 862 * Print out the packet, if it came from us. This logic is necessary 863 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 864 * which arrive ('tis only fair). This permits multiple copies of this 865 * program to be run without having intermingled output (or statistics!). 866 */ 867 static void 868 pr_pack(buf, cc, from, tv) 869 char *buf; 870 int cc; 871 struct sockaddr_in *from; 872 struct timeval *tv; 873 { 874 struct in_addr ina; 875 u_char *cp, *dp; 876 struct icmp *icp; 877 struct ip *ip; 878 const void *tp; 879 double triptime; 880 int dupflag, hlen, i, j, seq; 881 static int old_rrlen; 882 static char old_rr[MAX_IPOPTLEN]; 883 884 /* Check the IP header */ 885 ip = (struct ip *)buf; 886 hlen = ip->ip_hl << 2; 887 if (cc < hlen + ICMP_MINLEN) { 888 if (options & F_VERBOSE) 889 warn("packet too short (%d bytes) from %s", cc, 890 inet_ntoa(from->sin_addr)); 891 return; 892 } 893 894 /* Now the ICMP part */ 895 cc -= hlen; 896 icp = (struct icmp *)(buf + hlen); 897 if ((icp->icmp_type == ICMP_ECHOREPLY) || 898 ((icp->icmp_type == ICMP_MASKREPLY) && (options & F_MASK))) { 899 if (icp->icmp_id != ident) 900 return; /* 'Twas not our ECHO */ 901 ++nreceived; 902 triptime = 0.0; 903 if (timing) { 904 struct timeval tv1; 905 #ifndef icmp_data 906 tp = &icp->icmp_ip; 907 #else 908 tp = icp->icmp_data; 909 #endif 910 tp+=MASKLEN; 911 912 /* Copy to avoid alignment problems: */ 913 memcpy(&tv1, tp, sizeof(tv1)); 914 tvsub(tv, &tv1); 915 triptime = ((double)tv->tv_sec) * 1000.0 + 916 ((double)tv->tv_usec) / 1000.0; 917 tsum += triptime; 918 tsumsq += triptime * triptime; 919 if (triptime < tmin) 920 tmin = triptime; 921 if (triptime > tmax) 922 tmax = triptime; 923 } 924 925 seq = ntohs(icp->icmp_seq); 926 927 if (TST(seq % mx_dup_ck)) { 928 ++nrepeats; 929 --nreceived; 930 dupflag = 1; 931 } else { 932 SET(seq % mx_dup_ck); 933 dupflag = 0; 934 } 935 936 if (options & F_QUIET) 937 return; 938 939 if (options & F_FLOOD) 940 (void)write(STDOUT_FILENO, &BSPACE, 1); 941 else { 942 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 943 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 944 seq); 945 (void)printf(" ttl=%d", ip->ip_ttl); 946 if (timing) 947 (void)printf(" time=%.3f ms", triptime); 948 if (dupflag) 949 (void)printf(" (DUP!)"); 950 if (options & F_AUDIBLE) 951 (void)write(STDOUT_FILENO, &BBELL, 1); 952 if (options & F_MASK) { 953 /* Just prentend this cast isn't ugly */ 954 (void)printf(" mask=%s", 955 pr_addr(*(struct in_addr *)&(icp->icmp_mask))); 956 } 957 /* check the data */ 958 cp = (u_char*)&icp->icmp_data[PHDR_LEN]; 959 dp = &outpack[MINICMPLEN + PHDR_LEN]; 960 for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) { 961 if (*cp != *dp) { 962 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 963 i, *dp, *cp); 964 (void)printf("\ncp:"); 965 cp = (u_char*)&icp->icmp_data[0]; 966 for (i = 0; i < datalen; ++i, ++cp) { 967 if ((i % 32) == 8) 968 (void)printf("\n\t"); 969 (void)printf("%x ", *cp); 970 } 971 (void)printf("\ndp:"); 972 cp = &outpack[MINICMPLEN]; 973 for (i = 0; i < datalen; ++i, ++cp) { 974 if ((i % 32) == 8) 975 (void)printf("\n\t"); 976 (void)printf("%x ", *cp); 977 } 978 break; 979 } 980 } 981 } 982 } else { 983 /* 984 * We've got something other than an ECHOREPLY. 985 * See if it's a reply to something that we sent. 986 * We can compare IP destination, protocol, 987 * and ICMP type and ID. 988 * 989 * Only print all the error messages if we are running 990 * as root to avoid leaking information not normally 991 * available to those not running as root. 992 */ 993 #ifndef icmp_data 994 struct ip *oip = &icp->icmp_ip; 995 #else 996 struct ip *oip = (struct ip *)icp->icmp_data; 997 #endif 998 struct icmp *oicmp = (struct icmp *)(oip + 1); 999 1000 if (((options & F_VERBOSE) && uid == 0) || 1001 (!(options & F_QUIET2) && 1002 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) && 1003 (oip->ip_p == IPPROTO_ICMP) && 1004 (oicmp->icmp_type == ICMP_ECHO) && 1005 (oicmp->icmp_id == ident))) { 1006 (void)printf("%d bytes from %s: ", cc, 1007 pr_addr(from->sin_addr)); 1008 pr_icmph(icp); 1009 } else 1010 return; 1011 } 1012 1013 /* Display any IP options */ 1014 cp = (u_char *)buf + sizeof(struct ip); 1015 1016 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 1017 switch (*cp) { 1018 case IPOPT_EOL: 1019 hlen = 0; 1020 break; 1021 case IPOPT_LSRR: 1022 case IPOPT_SSRR: 1023 (void)printf(*cp == IPOPT_LSRR ? 1024 "\nLSRR: " : "\nSSRR: "); 1025 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1; 1026 hlen -= 2; 1027 cp += 2; 1028 if (j >= INADDR_LEN && 1029 j <= hlen - (int)sizeof(struct ip)) { 1030 for (;;) { 1031 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1032 if (ina.s_addr == 0) 1033 (void)printf("\t0.0.0.0"); 1034 else 1035 (void)printf("\t%s", 1036 pr_addr(ina)); 1037 hlen -= INADDR_LEN; 1038 cp += INADDR_LEN - 1; 1039 j -= INADDR_LEN; 1040 if (j < INADDR_LEN) 1041 break; 1042 (void)putchar('\n'); 1043 } 1044 } else 1045 (void)printf("\t(truncated route)\n"); 1046 break; 1047 case IPOPT_RR: 1048 j = cp[IPOPT_OLEN]; /* get length */ 1049 i = cp[IPOPT_OFFSET]; /* and pointer */ 1050 hlen -= 2; 1051 cp += 2; 1052 if (i > j) 1053 i = j; 1054 i = i - IPOPT_MINOFF + 1; 1055 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) { 1056 old_rrlen = 0; 1057 continue; 1058 } 1059 if (i == old_rrlen 1060 && !bcmp((char *)cp, old_rr, i) 1061 && !(options & F_FLOOD)) { 1062 (void)printf("\t(same route)"); 1063 hlen -= i; 1064 cp += i; 1065 break; 1066 } 1067 old_rrlen = i; 1068 bcopy((char *)cp, old_rr, i); 1069 (void)printf("\nRR: "); 1070 if (i >= INADDR_LEN && 1071 i <= hlen - (int)sizeof(struct ip)) { 1072 for (;;) { 1073 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1074 if (ina.s_addr == 0) 1075 (void)printf("\t0.0.0.0"); 1076 else 1077 (void)printf("\t%s", 1078 pr_addr(ina)); 1079 hlen -= INADDR_LEN; 1080 cp += INADDR_LEN - 1; 1081 i -= INADDR_LEN; 1082 if (i < INADDR_LEN) 1083 break; 1084 (void)putchar('\n'); 1085 } 1086 } else 1087 (void)printf("\t(truncated route)"); 1088 break; 1089 case IPOPT_NOP: 1090 (void)printf("\nNOP"); 1091 break; 1092 default: 1093 (void)printf("\nunknown option %x", *cp); 1094 break; 1095 } 1096 if (!(options & F_FLOOD)) { 1097 (void)putchar('\n'); 1098 (void)fflush(stdout); 1099 } 1100 } 1101 1102 /* 1103 * in_cksum -- 1104 * Checksum routine for Internet Protocol family headers (C Version) 1105 */ 1106 u_short 1107 in_cksum(addr, len) 1108 u_short *addr; 1109 int len; 1110 { 1111 int nleft, sum; 1112 u_short *w; 1113 union { 1114 u_short us; 1115 u_char uc[2]; 1116 } last; 1117 u_short answer; 1118 1119 nleft = len; 1120 sum = 0; 1121 w = addr; 1122 1123 /* 1124 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 1125 * sequential 16 bit words to it, and at the end, fold back all the 1126 * carry bits from the top 16 bits into the lower 16 bits. 1127 */ 1128 while (nleft > 1) { 1129 sum += *w++; 1130 nleft -= 2; 1131 } 1132 1133 /* mop up an odd byte, if necessary */ 1134 if (nleft == 1) { 1135 last.uc[0] = *(u_char *)w; 1136 last.uc[1] = 0; 1137 sum += last.us; 1138 } 1139 1140 /* add back carry outs from top 16 bits to low 16 bits */ 1141 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 1142 sum += (sum >> 16); /* add carry */ 1143 answer = ~sum; /* truncate to 16 bits */ 1144 return(answer); 1145 } 1146 1147 /* 1148 * tvsub -- 1149 * Subtract 2 timeval structs: out = out - in. Out is assumed to 1150 * be >= in. 1151 */ 1152 static void 1153 tvsub(out, in) 1154 struct timeval *out, *in; 1155 { 1156 1157 if ((out->tv_usec -= in->tv_usec) < 0) { 1158 --out->tv_sec; 1159 out->tv_usec += 1000000; 1160 } 1161 out->tv_sec -= in->tv_sec; 1162 } 1163 1164 /* 1165 * status -- 1166 * Print out statistics when SIGINFO is received. 1167 */ 1168 1169 static void 1170 status(sig) 1171 int sig __unused; 1172 { 1173 1174 siginfo_p = 1; 1175 } 1176 1177 static void 1178 check_status() 1179 { 1180 1181 if (siginfo_p) { 1182 siginfo_p = 0; 1183 (void)fprintf(stderr, 1184 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n", 1185 nreceived, ntransmitted, 1186 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0, 1187 nreceived ? tmin : 0.0, 1188 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum, 1189 tmax); 1190 } 1191 } 1192 1193 /* 1194 * finish -- 1195 * Print out statistics, and give up. 1196 */ 1197 static void 1198 finish() 1199 { 1200 struct termios ts; 1201 1202 (void)signal(SIGINT, SIG_IGN); 1203 (void)signal(SIGALRM, SIG_IGN); 1204 (void)putchar('\n'); 1205 (void)fflush(stdout); 1206 (void)printf("--- %s ping statistics ---\n", hostname); 1207 (void)printf("%ld packets transmitted, ", ntransmitted); 1208 (void)printf("%ld packets received, ", nreceived); 1209 if (nrepeats) 1210 (void)printf("+%ld duplicates, ", nrepeats); 1211 if (ntransmitted) { 1212 if (nreceived > ntransmitted) 1213 (void)printf("-- somebody's printing up packets!"); 1214 else 1215 (void)printf("%d%% packet loss", 1216 (int)(((ntransmitted - nreceived) * 100) / 1217 ntransmitted)); 1218 } 1219 (void)putchar('\n'); 1220 if (nreceived && timing) { 1221 double n = nreceived + nrepeats; 1222 double avg = tsum / n; 1223 double vari = tsumsq / n - avg * avg; 1224 (void)printf( 1225 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n", 1226 tmin, avg, tmax, sqrt(vari)); 1227 } 1228 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 1229 ts.c_lflag &= ~NOKERNINFO; 1230 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 1231 } 1232 1233 if (nreceived) 1234 exit(0); 1235 else 1236 exit(2); 1237 } 1238 1239 #ifdef notdef 1240 static char *ttab[] = { 1241 "Echo Reply", /* ip + seq + udata */ 1242 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1243 "Source Quench", /* IP */ 1244 "Redirect", /* redirect type, gateway, + IP */ 1245 "Echo", 1246 "Time Exceeded", /* transit, frag reassem + IP */ 1247 "Parameter Problem", /* pointer + IP */ 1248 "Timestamp", /* id + seq + three timestamps */ 1249 "Timestamp Reply", /* " */ 1250 "Info Request", /* id + sq */ 1251 "Info Reply" /* " */ 1252 }; 1253 #endif 1254 1255 /* 1256 * pr_icmph -- 1257 * Print a descriptive string about an ICMP header. 1258 */ 1259 static void 1260 pr_icmph(icp) 1261 struct icmp *icp; 1262 { 1263 1264 switch(icp->icmp_type) { 1265 case ICMP_ECHOREPLY: 1266 (void)printf("Echo Reply\n"); 1267 /* XXX ID + Seq + Data */ 1268 break; 1269 case ICMP_UNREACH: 1270 switch(icp->icmp_code) { 1271 case ICMP_UNREACH_NET: 1272 (void)printf("Destination Net Unreachable\n"); 1273 break; 1274 case ICMP_UNREACH_HOST: 1275 (void)printf("Destination Host Unreachable\n"); 1276 break; 1277 case ICMP_UNREACH_PROTOCOL: 1278 (void)printf("Destination Protocol Unreachable\n"); 1279 break; 1280 case ICMP_UNREACH_PORT: 1281 (void)printf("Destination Port Unreachable\n"); 1282 break; 1283 case ICMP_UNREACH_NEEDFRAG: 1284 (void)printf("frag needed and DF set (MTU %d)\n", 1285 ntohs(icp->icmp_nextmtu)); 1286 break; 1287 case ICMP_UNREACH_SRCFAIL: 1288 (void)printf("Source Route Failed\n"); 1289 break; 1290 case ICMP_UNREACH_FILTER_PROHIB: 1291 (void)printf("Communication prohibited by filter\n"); 1292 break; 1293 default: 1294 (void)printf("Dest Unreachable, Bad Code: %d\n", 1295 icp->icmp_code); 1296 break; 1297 } 1298 /* Print returned IP header information */ 1299 #ifndef icmp_data 1300 pr_retip(&icp->icmp_ip); 1301 #else 1302 pr_retip((struct ip *)icp->icmp_data); 1303 #endif 1304 break; 1305 case ICMP_SOURCEQUENCH: 1306 (void)printf("Source Quench\n"); 1307 #ifndef icmp_data 1308 pr_retip(&icp->icmp_ip); 1309 #else 1310 pr_retip((struct ip *)icp->icmp_data); 1311 #endif 1312 break; 1313 case ICMP_REDIRECT: 1314 switch(icp->icmp_code) { 1315 case ICMP_REDIRECT_NET: 1316 (void)printf("Redirect Network"); 1317 break; 1318 case ICMP_REDIRECT_HOST: 1319 (void)printf("Redirect Host"); 1320 break; 1321 case ICMP_REDIRECT_TOSNET: 1322 (void)printf("Redirect Type of Service and Network"); 1323 break; 1324 case ICMP_REDIRECT_TOSHOST: 1325 (void)printf("Redirect Type of Service and Host"); 1326 break; 1327 default: 1328 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1329 break; 1330 } 1331 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1332 #ifndef icmp_data 1333 pr_retip(&icp->icmp_ip); 1334 #else 1335 pr_retip((struct ip *)icp->icmp_data); 1336 #endif 1337 break; 1338 case ICMP_ECHO: 1339 (void)printf("Echo Request\n"); 1340 /* XXX ID + Seq + Data */ 1341 break; 1342 case ICMP_TIMXCEED: 1343 switch(icp->icmp_code) { 1344 case ICMP_TIMXCEED_INTRANS: 1345 (void)printf("Time to live exceeded\n"); 1346 break; 1347 case ICMP_TIMXCEED_REASS: 1348 (void)printf("Frag reassembly time exceeded\n"); 1349 break; 1350 default: 1351 (void)printf("Time exceeded, Bad Code: %d\n", 1352 icp->icmp_code); 1353 break; 1354 } 1355 #ifndef icmp_data 1356 pr_retip(&icp->icmp_ip); 1357 #else 1358 pr_retip((struct ip *)icp->icmp_data); 1359 #endif 1360 break; 1361 case ICMP_PARAMPROB: 1362 (void)printf("Parameter problem: pointer = 0x%02x\n", 1363 icp->icmp_hun.ih_pptr); 1364 #ifndef icmp_data 1365 pr_retip(&icp->icmp_ip); 1366 #else 1367 pr_retip((struct ip *)icp->icmp_data); 1368 #endif 1369 break; 1370 case ICMP_TSTAMP: 1371 (void)printf("Timestamp\n"); 1372 /* XXX ID + Seq + 3 timestamps */ 1373 break; 1374 case ICMP_TSTAMPREPLY: 1375 (void)printf("Timestamp Reply\n"); 1376 /* XXX ID + Seq + 3 timestamps */ 1377 break; 1378 case ICMP_IREQ: 1379 (void)printf("Information Request\n"); 1380 /* XXX ID + Seq */ 1381 break; 1382 case ICMP_IREQREPLY: 1383 (void)printf("Information Reply\n"); 1384 /* XXX ID + Seq */ 1385 break; 1386 case ICMP_MASKREQ: 1387 (void)printf("Address Mask Request\n"); 1388 break; 1389 case ICMP_MASKREPLY: 1390 (void)printf("Address Mask Reply\n"); 1391 break; 1392 case ICMP_ROUTERADVERT: 1393 (void)printf("Router Advertisement\n"); 1394 break; 1395 case ICMP_ROUTERSOLICIT: 1396 (void)printf("Router Solicitation\n"); 1397 break; 1398 default: 1399 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1400 } 1401 } 1402 1403 /* 1404 * pr_iph -- 1405 * Print an IP header with options. 1406 */ 1407 static void 1408 pr_iph(ip) 1409 struct ip *ip; 1410 { 1411 u_char *cp; 1412 int hlen; 1413 1414 hlen = ip->ip_hl << 2; 1415 cp = (u_char *)ip + 20; /* point to options */ 1416 1417 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1418 (void)printf(" %1x %1x %02x %04x %04x", 1419 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1420 ntohs(ip->ip_id)); 1421 (void)printf(" %1lx %04lx", 1422 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1423 (u_long) ntohl(ip->ip_off) & 0x1fff); 1424 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1425 ntohs(ip->ip_sum)); 1426 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1427 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1428 /* dump any option bytes */ 1429 while (hlen-- > 20) { 1430 (void)printf("%02x", *cp++); 1431 } 1432 (void)putchar('\n'); 1433 } 1434 1435 /* 1436 * pr_addr -- 1437 * Return an ascii host address as a dotted quad and optionally with 1438 * a hostname. 1439 */ 1440 static char * 1441 pr_addr(ina) 1442 struct in_addr ina; 1443 { 1444 struct hostent *hp; 1445 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1446 1447 if ((options & F_NUMERIC) || 1448 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1449 return inet_ntoa(ina); 1450 else 1451 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1452 inet_ntoa(ina)); 1453 return(buf); 1454 } 1455 1456 /* 1457 * pr_retip -- 1458 * Dump some info on a returned (via ICMP) IP packet. 1459 */ 1460 static void 1461 pr_retip(ip) 1462 struct ip *ip; 1463 { 1464 u_char *cp; 1465 int hlen; 1466 1467 pr_iph(ip); 1468 hlen = ip->ip_hl << 2; 1469 cp = (u_char *)ip + hlen; 1470 1471 if (ip->ip_p == 6) 1472 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1473 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1474 else if (ip->ip_p == 17) 1475 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1476 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1477 } 1478 1479 static void 1480 fill(bp, patp) 1481 char *bp, *patp; 1482 { 1483 char *cp; 1484 int pat[16]; 1485 u_int ii, jj, kk; 1486 1487 for (cp = patp; *cp; cp++) { 1488 if (!isxdigit(*cp)) 1489 errx(EX_USAGE, 1490 "patterns must be specified as hex digits"); 1491 1492 } 1493 ii = sscanf(patp, 1494 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1495 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1496 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1497 &pat[13], &pat[14], &pat[15]); 1498 1499 if (ii > 0) 1500 for (kk = 0; kk <= maxpayload - (PHDR_LEN + ii); kk += ii) 1501 for (jj = 0; jj < ii; ++jj) 1502 bp[jj + kk] = pat[jj]; 1503 if (!(options & F_QUIET)) { 1504 (void)printf("PATTERN: 0x"); 1505 for (jj = 0; jj < ii; ++jj) 1506 (void)printf("%02x", bp[jj] & 0xFF); 1507 (void)printf("\n"); 1508 } 1509 } 1510 1511 static void 1512 usage() 1513 { 1514 (void)fprintf(stderr, "%s\n%s\n%s\n", 1515 "usage: ping [-ADQRadfnoqrv] [-c count] [-i wait] [-l preload] [-m ttl]", 1516 " [-p pattern] " 1517 #ifdef IPSEC 1518 #ifdef IPSEC_POLICY_IPSEC 1519 "[-P policy] " 1520 #endif 1521 #endif 1522 "[-s packetsize] [-S src_addr] [-t timeout]", 1523 " [-z tos ] [host | [-L] [-I iface] [-T ttl] mcast-group]"); 1524 exit(EX_USAGE); 1525 } 1526