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