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 #if 0 38 #ifndef lint 39 static const char copyright[] = 40 "@(#) Copyright (c) 1989, 1993\n\ 41 The Regents of the University of California. All rights reserved.\n"; 42 #endif /* not lint */ 43 44 #ifndef lint 45 static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; 46 #endif /* not lint */ 47 #endif 48 #include <sys/cdefs.h> 49 __FBSDID("$FreeBSD$"); 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 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 #define F_TIME 0x100000 145 146 /* 147 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum 148 * number of received sequence numbers we can keep track of. Change 128 149 * to 8192 for complete accuracy... 150 */ 151 #define MAX_DUP_CHK (8 * 128) 152 int mx_dup_ck = MAX_DUP_CHK; 153 char rcvd_tbl[MAX_DUP_CHK / 8]; 154 155 struct sockaddr_in whereto; /* who to ping */ 156 int datalen = DEFDATALEN; 157 int maxpayload; 158 int s; /* socket file descriptor */ 159 u_char outpackhdr[IP_MAXPACKET], *outpack; 160 char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */ 161 char BSPACE = '\b'; /* characters written for flood */ 162 char DOT = '.'; 163 char *hostname; 164 char *shostname; 165 int ident; /* process id to identify our packets */ 166 int uid; /* cached uid for micro-optimization */ 167 u_char icmp_type = ICMP_ECHO; 168 u_char icmp_type_rsp = ICMP_ECHOREPLY; 169 int phdr_len = 0; 170 int send_len; 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, icmp_len, mib[4], 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 icmp_len = sizeof(struct ip) + ICMP_MINLEN + phdr_len; 462 if (options & F_RROUTE) 463 icmp_len += MAX_IPOPTLEN; 464 maxpayload = IP_MAXPACKET - icmp_len; 465 if (datalen > maxpayload) 466 errx(EX_USAGE, "packet size too large: %d > %d", datalen, 467 maxpayload); 468 send_len = icmp_len + datalen; 469 datap = &outpack[ICMP_MINLEN + phdr_len + TIMEVAL_LEN]; 470 if (options & F_PINGFILLED) { 471 fill((char *)datap, payload); 472 } 473 if (source) { 474 bzero((char *)&sock_in, sizeof(sock_in)); 475 sock_in.sin_family = AF_INET; 476 if (inet_aton(source, &sock_in.sin_addr) != 0) { 477 shostname = source; 478 } else { 479 hp = gethostbyname2(source, AF_INET); 480 if (!hp) 481 errx(EX_NOHOST, "cannot resolve %s: %s", 482 source, hstrerror(h_errno)); 483 484 sock_in.sin_len = sizeof sock_in; 485 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) || 486 hp->h_length < 0) 487 errx(1, "gethostbyname2: illegal address"); 488 memcpy(&sock_in.sin_addr, hp->h_addr_list[0], 489 sizeof(sock_in.sin_addr)); 490 (void)strncpy(snamebuf, hp->h_name, 491 sizeof(snamebuf) - 1); 492 snamebuf[sizeof(snamebuf) - 1] = '\0'; 493 shostname = snamebuf; 494 } 495 if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1) 496 err(1, "bind"); 497 } 498 499 bzero(&whereto, sizeof(whereto)); 500 to = &whereto; 501 to->sin_family = AF_INET; 502 to->sin_len = sizeof *to; 503 if (inet_aton(target, &to->sin_addr) != 0) { 504 hostname = target; 505 } else { 506 hp = gethostbyname2(target, AF_INET); 507 if (!hp) 508 errx(EX_NOHOST, "cannot resolve %s: %s", 509 target, hstrerror(h_errno)); 510 511 if ((unsigned)hp->h_length > sizeof(to->sin_addr)) 512 errx(1, "gethostbyname2 returned an illegal address"); 513 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 514 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 515 hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 516 hostname = hnamebuf; 517 } 518 519 if (options & F_FLOOD && options & F_INTERVAL) 520 errx(EX_USAGE, "-f and -i: incompatible options"); 521 522 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 523 errx(EX_USAGE, 524 "-f flag cannot be used with multicast destination"); 525 if (options & (F_MIF | F_NOLOOP | F_MTTL) 526 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 527 errx(EX_USAGE, 528 "-I, -L, -T flags cannot be used with unicast destination"); 529 530 if (datalen >= TIMEVAL_LEN) /* can we time transfer */ 531 timing = 1; 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 = IP_MAXPACKET; 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[ICMP_MINLEN + phdr_len], 872 sizeof(struct timeval)); 873 } 874 875 cc = ICMP_MINLEN + 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, recv_len, 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 recv_len = cc; 935 if (cc < hlen + ICMP_MINLEN) { 936 if (options & F_VERBOSE) 937 warn("packet too short (%d bytes) from %s", cc, 938 inet_ntoa(from->sin_addr)); 939 return; 940 } 941 942 /* Now the ICMP part */ 943 cc -= hlen; 944 icp = (struct icmp *)(buf + hlen); 945 if (icp->icmp_type == icmp_type_rsp) { 946 if (icp->icmp_id != ident) 947 return; /* 'Twas not our ECHO */ 948 ++nreceived; 949 triptime = 0.0; 950 if (timing) { 951 struct timeval tv1; 952 #ifndef icmp_data 953 tp = &icp->icmp_ip; 954 #else 955 tp = icp->icmp_data; 956 #endif 957 tp += phdr_len; 958 959 if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) { 960 /* Copy to avoid alignment problems: */ 961 memcpy(&tv1, tp, sizeof(tv1)); 962 tvsub(tv, &tv1); 963 triptime = ((double)tv->tv_sec) * 1000.0 + 964 ((double)tv->tv_usec) / 1000.0; 965 tsum += triptime; 966 tsumsq += triptime * triptime; 967 if (triptime < tmin) 968 tmin = triptime; 969 if (triptime > tmax) 970 tmax = triptime; 971 } else 972 timing = 0; 973 } 974 975 seq = ntohs(icp->icmp_seq); 976 977 if (TST(seq % mx_dup_ck)) { 978 ++nrepeats; 979 --nreceived; 980 dupflag = 1; 981 } else { 982 SET(seq % mx_dup_ck); 983 dupflag = 0; 984 } 985 986 if (options & F_QUIET) 987 return; 988 989 if (options & F_FLOOD) 990 (void)write(STDOUT_FILENO, &BSPACE, 1); 991 else { 992 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 993 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 994 seq); 995 (void)printf(" ttl=%d", ip->ip_ttl); 996 if (timing) 997 (void)printf(" time=%.3f ms", triptime); 998 if (dupflag) 999 (void)printf(" (DUP!)"); 1000 if (options & F_AUDIBLE) 1001 (void)write(STDOUT_FILENO, &BBELL, 1); 1002 if (options & F_MASK) { 1003 /* Just prentend this cast isn't ugly */ 1004 (void)printf(" mask=%s", 1005 pr_addr(*(struct in_addr *)&(icp->icmp_mask))); 1006 } 1007 if (options & F_TIME) { 1008 (void)printf(" tso=%s", pr_ntime(icp->icmp_otime)); 1009 (void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime)); 1010 (void)printf(" tst=%s", pr_ntime(icp->icmp_ttime)); 1011 } 1012 if (recv_len != send_len) { 1013 (void)printf( 1014 "\nwrong total length %d instead of %d", 1015 recv_len, send_len); 1016 } 1017 /* check the data */ 1018 cp = (u_char*)&icp->icmp_data[phdr_len]; 1019 dp = &outpack[ICMP_MINLEN + phdr_len]; 1020 cc -= ICMP_MINLEN + phdr_len; 1021 i = 0; 1022 if (timing) { /* don't check variable timestamp */ 1023 cp += TIMEVAL_LEN; 1024 dp += TIMEVAL_LEN; 1025 cc -= TIMEVAL_LEN; 1026 i += TIMEVAL_LEN; 1027 } 1028 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) { 1029 if (*cp != *dp) { 1030 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 1031 i, *dp, *cp); 1032 (void)printf("\ncp:"); 1033 cp = (u_char*)&icp->icmp_data[0]; 1034 for (i = 0; i < datalen; ++i, ++cp) { 1035 if ((i % 16) == 8) 1036 (void)printf("\n\t"); 1037 (void)printf("%2x ", *cp); 1038 } 1039 (void)printf("\ndp:"); 1040 cp = &outpack[ICMP_MINLEN]; 1041 for (i = 0; i < datalen; ++i, ++cp) { 1042 if ((i % 16) == 8) 1043 (void)printf("\n\t"); 1044 (void)printf("%2x ", *cp); 1045 } 1046 break; 1047 } 1048 } 1049 } 1050 } else { 1051 /* 1052 * We've got something other than an ECHOREPLY. 1053 * See if it's a reply to something that we sent. 1054 * We can compare IP destination, protocol, 1055 * and ICMP type and ID. 1056 * 1057 * Only print all the error messages if we are running 1058 * as root to avoid leaking information not normally 1059 * available to those not running as root. 1060 */ 1061 #ifndef icmp_data 1062 struct ip *oip = &icp->icmp_ip; 1063 #else 1064 struct ip *oip = (struct ip *)icp->icmp_data; 1065 #endif 1066 struct icmp *oicmp = (struct icmp *)(oip + 1); 1067 1068 if (((options & F_VERBOSE) && uid == 0) || 1069 (!(options & F_QUIET2) && 1070 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) && 1071 (oip->ip_p == IPPROTO_ICMP) && 1072 (oicmp->icmp_type == ICMP_ECHO) && 1073 (oicmp->icmp_id == ident))) { 1074 (void)printf("%d bytes from %s: ", cc, 1075 pr_addr(from->sin_addr)); 1076 pr_icmph(icp); 1077 } else 1078 return; 1079 } 1080 1081 /* Display any IP options */ 1082 cp = (u_char *)buf + sizeof(struct ip); 1083 1084 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 1085 switch (*cp) { 1086 case IPOPT_EOL: 1087 hlen = 0; 1088 break; 1089 case IPOPT_LSRR: 1090 case IPOPT_SSRR: 1091 (void)printf(*cp == IPOPT_LSRR ? 1092 "\nLSRR: " : "\nSSRR: "); 1093 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1; 1094 hlen -= 2; 1095 cp += 2; 1096 if (j >= INADDR_LEN && 1097 j <= hlen - (int)sizeof(struct ip)) { 1098 for (;;) { 1099 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1100 if (ina.s_addr == 0) 1101 (void)printf("\t0.0.0.0"); 1102 else 1103 (void)printf("\t%s", 1104 pr_addr(ina)); 1105 hlen -= INADDR_LEN; 1106 cp += INADDR_LEN - 1; 1107 j -= INADDR_LEN; 1108 if (j < INADDR_LEN) 1109 break; 1110 (void)putchar('\n'); 1111 } 1112 } else 1113 (void)printf("\t(truncated route)\n"); 1114 break; 1115 case IPOPT_RR: 1116 j = cp[IPOPT_OLEN]; /* get length */ 1117 i = cp[IPOPT_OFFSET]; /* and pointer */ 1118 hlen -= 2; 1119 cp += 2; 1120 if (i > j) 1121 i = j; 1122 i = i - IPOPT_MINOFF + 1; 1123 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) { 1124 old_rrlen = 0; 1125 continue; 1126 } 1127 if (i == old_rrlen 1128 && !bcmp((char *)cp, old_rr, i) 1129 && !(options & F_FLOOD)) { 1130 (void)printf("\t(same route)"); 1131 hlen -= i; 1132 cp += i; 1133 break; 1134 } 1135 old_rrlen = i; 1136 bcopy((char *)cp, old_rr, i); 1137 (void)printf("\nRR: "); 1138 if (i >= INADDR_LEN && 1139 i <= hlen - (int)sizeof(struct ip)) { 1140 for (;;) { 1141 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1142 if (ina.s_addr == 0) 1143 (void)printf("\t0.0.0.0"); 1144 else 1145 (void)printf("\t%s", 1146 pr_addr(ina)); 1147 hlen -= INADDR_LEN; 1148 cp += INADDR_LEN - 1; 1149 i -= INADDR_LEN; 1150 if (i < INADDR_LEN) 1151 break; 1152 (void)putchar('\n'); 1153 } 1154 } else 1155 (void)printf("\t(truncated route)"); 1156 break; 1157 case IPOPT_NOP: 1158 (void)printf("\nNOP"); 1159 break; 1160 default: 1161 (void)printf("\nunknown option %x", *cp); 1162 break; 1163 } 1164 if (!(options & F_FLOOD)) { 1165 (void)putchar('\n'); 1166 (void)fflush(stdout); 1167 } 1168 } 1169 1170 /* 1171 * in_cksum -- 1172 * Checksum routine for Internet Protocol family headers (C Version) 1173 */ 1174 u_short 1175 in_cksum(addr, len) 1176 u_short *addr; 1177 int len; 1178 { 1179 int nleft, sum; 1180 u_short *w; 1181 union { 1182 u_short us; 1183 u_char uc[2]; 1184 } last; 1185 u_short answer; 1186 1187 nleft = len; 1188 sum = 0; 1189 w = addr; 1190 1191 /* 1192 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 1193 * sequential 16 bit words to it, and at the end, fold back all the 1194 * carry bits from the top 16 bits into the lower 16 bits. 1195 */ 1196 while (nleft > 1) { 1197 sum += *w++; 1198 nleft -= 2; 1199 } 1200 1201 /* mop up an odd byte, if necessary */ 1202 if (nleft == 1) { 1203 last.uc[0] = *(u_char *)w; 1204 last.uc[1] = 0; 1205 sum += last.us; 1206 } 1207 1208 /* add back carry outs from top 16 bits to low 16 bits */ 1209 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 1210 sum += (sum >> 16); /* add carry */ 1211 answer = ~sum; /* truncate to 16 bits */ 1212 return(answer); 1213 } 1214 1215 /* 1216 * tvsub -- 1217 * Subtract 2 timeval structs: out = out - in. Out is assumed to 1218 * be >= in. 1219 */ 1220 static void 1221 tvsub(out, in) 1222 struct timeval *out, *in; 1223 { 1224 1225 if ((out->tv_usec -= in->tv_usec) < 0) { 1226 --out->tv_sec; 1227 out->tv_usec += 1000000; 1228 } 1229 out->tv_sec -= in->tv_sec; 1230 } 1231 1232 /* 1233 * status -- 1234 * Print out statistics when SIGINFO is received. 1235 */ 1236 1237 static void 1238 status(sig) 1239 int sig __unused; 1240 { 1241 1242 siginfo_p = 1; 1243 } 1244 1245 static void 1246 check_status() 1247 { 1248 1249 if (siginfo_p) { 1250 siginfo_p = 0; 1251 (void)fprintf(stderr, "\r%ld/%ld packets received (%.0f%%)", 1252 nreceived, ntransmitted, 1253 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0); 1254 if (nreceived && timing) 1255 (void)fprintf(stderr, " %.3f min / %.3f avg / %.3f max", 1256 tmin, tsum / (nreceived + nrepeats), tmax); 1257 (void)fprintf(stderr, "\n"); 1258 } 1259 } 1260 1261 /* 1262 * finish -- 1263 * Print out statistics, and give up. 1264 */ 1265 static void 1266 finish() 1267 { 1268 struct termios ts; 1269 1270 (void)signal(SIGINT, SIG_IGN); 1271 (void)signal(SIGALRM, SIG_IGN); 1272 (void)putchar('\n'); 1273 (void)fflush(stdout); 1274 (void)printf("--- %s ping statistics ---\n", hostname); 1275 (void)printf("%ld packets transmitted, ", ntransmitted); 1276 (void)printf("%ld packets received, ", nreceived); 1277 if (nrepeats) 1278 (void)printf("+%ld duplicates, ", nrepeats); 1279 if (ntransmitted) { 1280 if (nreceived > ntransmitted) 1281 (void)printf("-- somebody's printing up packets!"); 1282 else 1283 (void)printf("%d%% packet loss", 1284 (int)(((ntransmitted - nreceived) * 100) / 1285 ntransmitted)); 1286 } 1287 (void)putchar('\n'); 1288 if (nreceived && timing) { 1289 double n = nreceived + nrepeats; 1290 double avg = tsum / n; 1291 double vari = tsumsq / n - avg * avg; 1292 (void)printf( 1293 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n", 1294 tmin, avg, tmax, sqrt(vari)); 1295 } 1296 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 1297 ts.c_lflag &= ~NOKERNINFO; 1298 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 1299 } 1300 1301 if (nreceived) 1302 exit(0); 1303 else 1304 exit(2); 1305 } 1306 1307 #ifdef notdef 1308 static char *ttab[] = { 1309 "Echo Reply", /* ip + seq + udata */ 1310 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1311 "Source Quench", /* IP */ 1312 "Redirect", /* redirect type, gateway, + IP */ 1313 "Echo", 1314 "Time Exceeded", /* transit, frag reassem + IP */ 1315 "Parameter Problem", /* pointer + IP */ 1316 "Timestamp", /* id + seq + three timestamps */ 1317 "Timestamp Reply", /* " */ 1318 "Info Request", /* id + sq */ 1319 "Info Reply" /* " */ 1320 }; 1321 #endif 1322 1323 /* 1324 * pr_icmph -- 1325 * Print a descriptive string about an ICMP header. 1326 */ 1327 static void 1328 pr_icmph(icp) 1329 struct icmp *icp; 1330 { 1331 1332 switch(icp->icmp_type) { 1333 case ICMP_ECHOREPLY: 1334 (void)printf("Echo Reply\n"); 1335 /* XXX ID + Seq + Data */ 1336 break; 1337 case ICMP_UNREACH: 1338 switch(icp->icmp_code) { 1339 case ICMP_UNREACH_NET: 1340 (void)printf("Destination Net Unreachable\n"); 1341 break; 1342 case ICMP_UNREACH_HOST: 1343 (void)printf("Destination Host Unreachable\n"); 1344 break; 1345 case ICMP_UNREACH_PROTOCOL: 1346 (void)printf("Destination Protocol Unreachable\n"); 1347 break; 1348 case ICMP_UNREACH_PORT: 1349 (void)printf("Destination Port Unreachable\n"); 1350 break; 1351 case ICMP_UNREACH_NEEDFRAG: 1352 (void)printf("frag needed and DF set (MTU %d)\n", 1353 ntohs(icp->icmp_nextmtu)); 1354 break; 1355 case ICMP_UNREACH_SRCFAIL: 1356 (void)printf("Source Route Failed\n"); 1357 break; 1358 case ICMP_UNREACH_FILTER_PROHIB: 1359 (void)printf("Communication prohibited by filter\n"); 1360 break; 1361 default: 1362 (void)printf("Dest Unreachable, Bad Code: %d\n", 1363 icp->icmp_code); 1364 break; 1365 } 1366 /* Print returned IP header information */ 1367 #ifndef icmp_data 1368 pr_retip(&icp->icmp_ip); 1369 #else 1370 pr_retip((struct ip *)icp->icmp_data); 1371 #endif 1372 break; 1373 case ICMP_SOURCEQUENCH: 1374 (void)printf("Source Quench\n"); 1375 #ifndef icmp_data 1376 pr_retip(&icp->icmp_ip); 1377 #else 1378 pr_retip((struct ip *)icp->icmp_data); 1379 #endif 1380 break; 1381 case ICMP_REDIRECT: 1382 switch(icp->icmp_code) { 1383 case ICMP_REDIRECT_NET: 1384 (void)printf("Redirect Network"); 1385 break; 1386 case ICMP_REDIRECT_HOST: 1387 (void)printf("Redirect Host"); 1388 break; 1389 case ICMP_REDIRECT_TOSNET: 1390 (void)printf("Redirect Type of Service and Network"); 1391 break; 1392 case ICMP_REDIRECT_TOSHOST: 1393 (void)printf("Redirect Type of Service and Host"); 1394 break; 1395 default: 1396 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1397 break; 1398 } 1399 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1400 #ifndef icmp_data 1401 pr_retip(&icp->icmp_ip); 1402 #else 1403 pr_retip((struct ip *)icp->icmp_data); 1404 #endif 1405 break; 1406 case ICMP_ECHO: 1407 (void)printf("Echo Request\n"); 1408 /* XXX ID + Seq + Data */ 1409 break; 1410 case ICMP_TIMXCEED: 1411 switch(icp->icmp_code) { 1412 case ICMP_TIMXCEED_INTRANS: 1413 (void)printf("Time to live exceeded\n"); 1414 break; 1415 case ICMP_TIMXCEED_REASS: 1416 (void)printf("Frag reassembly time exceeded\n"); 1417 break; 1418 default: 1419 (void)printf("Time exceeded, Bad Code: %d\n", 1420 icp->icmp_code); 1421 break; 1422 } 1423 #ifndef icmp_data 1424 pr_retip(&icp->icmp_ip); 1425 #else 1426 pr_retip((struct ip *)icp->icmp_data); 1427 #endif 1428 break; 1429 case ICMP_PARAMPROB: 1430 (void)printf("Parameter problem: pointer = 0x%02x\n", 1431 icp->icmp_hun.ih_pptr); 1432 #ifndef icmp_data 1433 pr_retip(&icp->icmp_ip); 1434 #else 1435 pr_retip((struct ip *)icp->icmp_data); 1436 #endif 1437 break; 1438 case ICMP_TSTAMP: 1439 (void)printf("Timestamp\n"); 1440 /* XXX ID + Seq + 3 timestamps */ 1441 break; 1442 case ICMP_TSTAMPREPLY: 1443 (void)printf("Timestamp Reply\n"); 1444 /* XXX ID + Seq + 3 timestamps */ 1445 break; 1446 case ICMP_IREQ: 1447 (void)printf("Information Request\n"); 1448 /* XXX ID + Seq */ 1449 break; 1450 case ICMP_IREQREPLY: 1451 (void)printf("Information Reply\n"); 1452 /* XXX ID + Seq */ 1453 break; 1454 case ICMP_MASKREQ: 1455 (void)printf("Address Mask Request\n"); 1456 break; 1457 case ICMP_MASKREPLY: 1458 (void)printf("Address Mask Reply\n"); 1459 break; 1460 case ICMP_ROUTERADVERT: 1461 (void)printf("Router Advertisement\n"); 1462 break; 1463 case ICMP_ROUTERSOLICIT: 1464 (void)printf("Router Solicitation\n"); 1465 break; 1466 default: 1467 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1468 } 1469 } 1470 1471 /* 1472 * pr_iph -- 1473 * Print an IP header with options. 1474 */ 1475 static void 1476 pr_iph(ip) 1477 struct ip *ip; 1478 { 1479 u_char *cp; 1480 int hlen; 1481 1482 hlen = ip->ip_hl << 2; 1483 cp = (u_char *)ip + 20; /* point to options */ 1484 1485 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1486 (void)printf(" %1x %1x %02x %04x %04x", 1487 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1488 ntohs(ip->ip_id)); 1489 (void)printf(" %1lx %04lx", 1490 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1491 (u_long) ntohl(ip->ip_off) & 0x1fff); 1492 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1493 ntohs(ip->ip_sum)); 1494 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1495 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1496 /* dump any option bytes */ 1497 while (hlen-- > 20) { 1498 (void)printf("%02x", *cp++); 1499 } 1500 (void)putchar('\n'); 1501 } 1502 1503 /* 1504 * pr_addr -- 1505 * Return an ascii host address as a dotted quad and optionally with 1506 * a hostname. 1507 */ 1508 static char * 1509 pr_addr(ina) 1510 struct in_addr ina; 1511 { 1512 struct hostent *hp; 1513 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1514 1515 if ((options & F_NUMERIC) || 1516 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1517 return inet_ntoa(ina); 1518 else 1519 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1520 inet_ntoa(ina)); 1521 return(buf); 1522 } 1523 1524 /* 1525 * pr_retip -- 1526 * Dump some info on a returned (via ICMP) IP packet. 1527 */ 1528 static void 1529 pr_retip(ip) 1530 struct ip *ip; 1531 { 1532 u_char *cp; 1533 int hlen; 1534 1535 pr_iph(ip); 1536 hlen = ip->ip_hl << 2; 1537 cp = (u_char *)ip + hlen; 1538 1539 if (ip->ip_p == 6) 1540 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1541 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1542 else if (ip->ip_p == 17) 1543 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1544 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1545 } 1546 1547 static char * 1548 pr_ntime (n_time timestamp) 1549 { 1550 static char buf[10]; 1551 int hour, min, sec; 1552 1553 sec = ntohl(timestamp) / 1000; 1554 hour = sec / 60 / 60; 1555 min = (sec % (60 * 60)) / 60; 1556 sec = (sec % (60 * 60)) % 60; 1557 1558 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour, min, sec); 1559 1560 return (buf); 1561 } 1562 1563 static void 1564 fill(bp, patp) 1565 char *bp, *patp; 1566 { 1567 char *cp; 1568 int pat[16]; 1569 u_int ii, jj, kk; 1570 1571 for (cp = patp; *cp; cp++) { 1572 if (!isxdigit(*cp)) 1573 errx(EX_USAGE, 1574 "patterns must be specified as hex digits"); 1575 1576 } 1577 ii = sscanf(patp, 1578 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1579 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1580 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1581 &pat[13], &pat[14], &pat[15]); 1582 1583 if (ii > 0) 1584 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii) 1585 for (jj = 0; jj < ii; ++jj) 1586 bp[jj + kk] = pat[jj]; 1587 if (!(options & F_QUIET)) { 1588 (void)printf("PATTERN: 0x"); 1589 for (jj = 0; jj < ii; ++jj) 1590 (void)printf("%02x", bp[jj] & 0xFF); 1591 (void)printf("\n"); 1592 } 1593 } 1594 1595 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC) 1596 #define SECOPT " [-P policy]" 1597 #else 1598 #define SECOPT "" 1599 #endif 1600 static void 1601 usage() 1602 { 1603 1604 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n", 1605 "usage: ping [-AaDdfnoQqRrv] [-c count] [-i wait] [-l preload] [-M mask | time]", 1606 " [-m ttl]" SECOPT " [-p pattern] [-S src_addr] [-s packetsize]", 1607 " [-t timeout] [-z tos] host", 1608 " ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]", 1609 " [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]", 1610 " [-s packetsize] [-T ttl] [-t timeout] [-z tos] mcast-group"); 1611 exit(EX_USAGE); 1612 } 1613