1 /* $NetBSD: ping.c,v 1.86 2007/01/17 21:59:49 hubertf Exp $ */ 2 3 /* 4 * Copyright (c) 1989, 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Mike Muuss. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 /* 36 * P I N G . C 37 * 38 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility, 39 * measure round-trip-delays and packet loss across network paths. 40 * 41 * Author - 42 * Mike Muuss 43 * U. S. Army Ballistic Research Laboratory 44 * December, 1983 45 * Modified at Uc Berkeley 46 * Record Route and verbose headers - Phil Dykstra, BRL, March 1988. 47 * Multicast options (ttl, if, loop) - Steve Deering, Stanford, August 1988. 48 * ttl, duplicate detection - Cliff Frost, UCB, April 1989 49 * Pad pattern - Cliff Frost (from Tom Ferrin, UCSF), April 1989 50 * 51 * Status - 52 * Public Domain. Distribution Unlimited. 53 * 54 * Bugs - 55 * More statistics could always be gathered. 56 * This program has to run SUID to ROOT to access the ICMP socket. 57 */ 58 59 #include <sys/cdefs.h> 60 #ifndef lint 61 __RCSID("$NetBSD: ping.c,v 1.86 2007/01/17 21:59:49 hubertf Exp $"); 62 #endif 63 64 #include <stdio.h> 65 #include <stddef.h> 66 #include <errno.h> 67 #include <signal.h> 68 #include <sys/time.h> 69 #include <sys/types.h> 70 #include <sys/param.h> 71 #include <sys/socket.h> 72 #include <sys/file.h> 73 #include <termios.h> 74 #include <stdlib.h> 75 #include <unistd.h> 76 #include <poll.h> 77 #include <limits.h> 78 #include <math.h> 79 #include <string.h> 80 #include <err.h> 81 #ifdef sgi 82 #include <bstring.h> 83 #include <getopt.h> 84 #include <sys/prctl.h> 85 #ifndef PRE_KUDZU 86 #include <cap_net.h> 87 #else 88 #define cap_socket socket 89 #endif 90 #else 91 #define cap_socket socket 92 #endif 93 94 #include <netinet/in_systm.h> 95 #include <netinet/in.h> 96 #include <netinet/ip.h> 97 #include <netinet/ip_icmp.h> 98 #include <netinet/ip_var.h> 99 #include <arpa/inet.h> 100 #include <ctype.h> 101 #include <netdb.h> 102 103 #ifdef IPSEC 104 #include <netinet6/ipsec.h> 105 #endif /*IPSEC*/ 106 107 #define FLOOD_INTVL 0.01 /* default flood output interval */ 108 #define MAXPACKET (IP_MAXPACKET-60-8) /* max packet size */ 109 110 #define F_VERBOSE 0x0001 111 #define F_QUIET 0x0002 /* minimize all output */ 112 #define F_SEMI_QUIET 0x0004 /* ignore our ICMP errors */ 113 #define F_FLOOD 0x0008 /* flood-ping */ 114 #define F_RECORD_ROUTE 0x0010 /* record route */ 115 #define F_SOURCE_ROUTE 0x0020 /* loose source route */ 116 #define F_PING_FILLED 0x0040 /* is buffer filled with user data? */ 117 #define F_PING_RANDOM 0x0080 /* use random data */ 118 #define F_NUMERIC 0x0100 /* do not do gethostbyaddr() calls */ 119 #define F_TIMING 0x0200 /* room for a timestamp */ 120 #define F_DF 0x0400 /* set IP DF bit */ 121 #define F_SOURCE_ADDR 0x0800 /* set source IP address/interface */ 122 #define F_ONCE 0x1000 /* exit(0) after receiving 1 reply */ 123 #define F_MCAST 0x2000 /* multicast target */ 124 #define F_MCAST_NOLOOP 0x4000 /* no multicast loopback */ 125 #define F_AUDIBLE 0x8000 /* audible output */ 126 #ifdef IPSEC 127 #ifdef IPSEC_POLICY_IPSEC 128 #define F_POLICY 0x10000 129 #else 130 #define F_AUTHHDR 0x10000 131 #define F_ENCRYPT 0x20000 132 #endif /*IPSEC_POLICY_IPSEC*/ 133 #endif /*IPSEC*/ 134 135 136 /* MAX_DUP_CHK is the number of bits in received table, the 137 * maximum number of received sequence numbers we can track to check 138 * for duplicates. 139 */ 140 #define MAX_DUP_CHK (8 * 2048) 141 u_char rcvd_tbl[MAX_DUP_CHK/8]; 142 int nrepeats = 0; 143 #define A(seq) rcvd_tbl[(seq/8)%sizeof(rcvd_tbl)] /* byte in array */ 144 #define B(seq) (1 << (seq & 0x07)) /* bit in byte */ 145 #define SET(seq) (A(seq) |= B(seq)) 146 #define CLR(seq) (A(seq) &= (~B(seq))) 147 #define TST(seq) (A(seq) & B(seq)) 148 149 struct tv32 { 150 int32_t tv32_sec; 151 int32_t tv32_usec; 152 }; 153 154 155 u_char *packet; 156 int packlen; 157 int pingflags = 0, options; 158 char *fill_pat; 159 160 int s; /* Socket file descriptor */ 161 int sloop; /* Socket file descriptor/loopback */ 162 163 #define PHDR_LEN sizeof(struct tv32) /* size of timestamp header */ 164 struct sockaddr_in whereto, send_addr; /* Who to ping */ 165 struct sockaddr_in src_addr; /* from where */ 166 struct sockaddr_in loc_addr; /* 127.1 */ 167 int datalen = 64 - PHDR_LEN; /* How much data */ 168 169 #ifndef __NetBSD__ 170 static char *progname; 171 #define getprogname() (progname) 172 #define setprogname(name) ((void)(progname = (name))) 173 #endif 174 175 char hostname[MAXHOSTNAMELEN]; 176 177 static struct { 178 struct ip o_ip; 179 char o_opt[MAX_IPOPTLEN]; 180 union { 181 u_char u_buf[MAXPACKET+offsetof(struct icmp, icmp_data)]; 182 struct icmp u_icmp; 183 } o_u; 184 } out_pack; 185 #define opack_icmp out_pack.o_u.u_icmp 186 struct ip *opack_ip; 187 188 char optspace[MAX_IPOPTLEN]; /* record route space */ 189 int optlen; 190 191 192 int npackets; /* total packets to send */ 193 int preload; /* number of packets to "preload" */ 194 int ntransmitted; /* output sequence # = #sent */ 195 int ident; /* our ID, in network byte order */ 196 197 int nreceived; /* # of packets we got back */ 198 199 double interval; /* interval between packets */ 200 struct timeval interval_tv; 201 double tmin = 999999999.0; 202 double tmax = 0.0; 203 double tsum = 0.0; /* sum of all times */ 204 double tsumsq = 0.0; 205 double maxwait = 0.0; 206 207 int bufspace = IP_MAXPACKET; 208 209 struct timeval now, clear_cache, last_tx, next_tx, first_tx; 210 struct timeval last_rx, first_rx; 211 int lastrcvd = 1; /* last ping sent has been received */ 212 213 static struct timeval jiggle_time; 214 static int jiggle_cnt, total_jiggled, jiggle_direction = -1; 215 216 static void doit(void); 217 static void prefinish(int); 218 static void prtsig(int); 219 static void finish(int); 220 static void summary(int); 221 static void pinger(void); 222 static void fill(void); 223 static void rnd_fill(void); 224 static double diffsec(struct timeval *, struct timeval *); 225 static void timevaladd(struct timeval *, struct timeval *); 226 static void sec_to_timeval(const double, struct timeval *); 227 static double timeval_to_sec(const struct timeval *); 228 static void pr_pack(u_char *, int, struct sockaddr_in *); 229 static u_int16_t in_cksum(u_int16_t *, u_int); 230 static void pr_saddr(u_char *); 231 static char *pr_addr(struct in_addr *); 232 static void pr_iph(struct icmp *, int); 233 static void pr_retip(struct icmp *, int); 234 static int pr_icmph(struct icmp *, struct sockaddr_in *, int); 235 static void jiggle(int), jiggle_flush(int); 236 static void gethost(const char *, const char *, 237 struct sockaddr_in *, char *, int); 238 static void usage(void); 239 240 int 241 main(int argc, char *argv[]) 242 { 243 int c, i, on = 1, hostind = 0; 244 long l; 245 u_char ttl = 0; 246 u_long tos = 0; 247 char *p; 248 #ifdef IPSEC 249 #ifdef IPSEC_POLICY_IPSEC 250 char *policy_in = NULL; 251 char *policy_out = NULL; 252 #endif 253 #endif 254 #ifdef SIGINFO 255 struct sigaction sa; 256 #endif 257 258 if ((s = cap_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) 259 err(1, "Cannot create socket"); 260 if ((sloop = cap_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) 261 err(1, "Cannot create socket"); 262 263 if (setuid(getuid()) == -1) 264 err(1, "setuid"); 265 266 setprogname(argv[0]); 267 268 #ifndef IPSEC 269 #define IPSECOPT 270 #else 271 #ifdef IPSEC_POLICY_IPSEC 272 #define IPSECOPT "E:" 273 #else 274 #define IPSECOPT "AE" 275 #endif /*IPSEC_POLICY_IPSEC*/ 276 #endif 277 while ((c = getopt(argc, argv, 278 "ac:dDfg:h:i:I:l:Lnop:PqQrRs:t:T:vw:" IPSECOPT)) != -1) { 279 #undef IPSECOPT 280 switch (c) { 281 case 'a': 282 pingflags |= F_AUDIBLE; 283 break; 284 case 'c': 285 npackets = strtol(optarg, &p, 0); 286 if (*p != '\0' || npackets <= 0) 287 errx(1, "Bad/invalid number of packets"); 288 break; 289 case 'D': 290 pingflags |= F_DF; 291 break; 292 case 'd': 293 options |= SO_DEBUG; 294 break; 295 case 'f': 296 pingflags |= F_FLOOD; 297 break; 298 case 'h': 299 hostind = optind-1; 300 break; 301 case 'i': /* wait between sending packets */ 302 interval = strtod(optarg, &p); 303 if (*p != '\0' || interval <= 0) 304 errx(1, "Bad/invalid interval %s", optarg); 305 break; 306 case 'l': 307 preload = strtol(optarg, &p, 0); 308 if (*p != '\0' || preload < 0) 309 errx(1, "Bad/invalid preload value %s", 310 optarg); 311 break; 312 case 'n': 313 pingflags |= F_NUMERIC; 314 break; 315 case 'o': 316 pingflags |= F_ONCE; 317 break; 318 case 'p': /* fill buffer with user pattern */ 319 if (pingflags & F_PING_RANDOM) 320 errx(1, "Only one of -P and -p allowed"); 321 pingflags |= F_PING_FILLED; 322 fill_pat = optarg; 323 break; 324 case 'P': 325 if (pingflags & F_PING_FILLED) 326 errx(1, "Only one of -P and -p allowed"); 327 pingflags |= F_PING_RANDOM; 328 break; 329 case 'q': 330 pingflags |= F_QUIET; 331 break; 332 case 'Q': 333 pingflags |= F_SEMI_QUIET; 334 break; 335 case 'r': 336 options |= SO_DONTROUTE; 337 break; 338 case 's': /* size of packet to send */ 339 datalen = strtol(optarg, &p, 0); 340 if (*p != '\0' || datalen < 0) 341 errx(1, "Bad/invalid packet size %s", optarg); 342 if (datalen > MAXPACKET) 343 errx(1, "packet size is too large"); 344 break; 345 case 'v': 346 pingflags |= F_VERBOSE; 347 break; 348 case 'R': 349 pingflags |= F_RECORD_ROUTE; 350 break; 351 case 'L': 352 pingflags |= F_MCAST_NOLOOP; 353 break; 354 case 't': 355 tos = strtoul(optarg, &p, 0); 356 if (*p != '\0' || tos > 0xFF) 357 errx(1, "bad tos value: %s", optarg); 358 break; 359 case 'T': 360 l = strtol(optarg, &p, 0); 361 if (*p != '\0' || l > 255 || l <= 0) 362 errx(1, "ttl out of range"); 363 ttl = (u_char)l; /* cannot check >255 otherwise */ 364 break; 365 case 'I': 366 pingflags |= F_SOURCE_ADDR; 367 gethost("-I", optarg, &src_addr, 0, 0); 368 break; 369 case 'g': 370 pingflags |= F_SOURCE_ROUTE; 371 gethost("-g", optarg, &send_addr, 0, 0); 372 break; 373 case 'w': 374 maxwait = strtod(optarg, &p); 375 if (*p != '\0' || maxwait <= 0) 376 errx(1, "Bad/invalid maxwait time %s", optarg); 377 break; 378 #ifdef IPSEC 379 #ifdef IPSEC_POLICY_IPSEC 380 case 'E': 381 pingflags |= F_POLICY; 382 if (!strncmp("in", optarg, 2)) { 383 policy_in = strdup(optarg); 384 if (!policy_in) 385 err(1, "strdup"); 386 } else if (!strncmp("out", optarg, 3)) { 387 policy_out = strdup(optarg); 388 if (!policy_out) 389 err(1, "strdup"); 390 } else 391 errx(1, "invalid security policy"); 392 break; 393 #else 394 case 'A': 395 pingflags |= F_AUTHHDR; 396 break; 397 case 'E': 398 pingflags |= F_ENCRYPT; 399 break; 400 #endif /*IPSEC_POLICY_IPSEC*/ 401 #endif /*IPSEC*/ 402 default: 403 usage(); 404 break; 405 } 406 } 407 408 if (interval == 0) 409 interval = (pingflags & F_FLOOD) ? FLOOD_INTVL : 1.0; 410 #ifndef sgi 411 if (pingflags & F_FLOOD && getuid()) 412 errx(1, "Must be superuser to use -f"); 413 if (interval < 1.0 && getuid()) 414 errx(1, "Must be superuser to use < 1 sec ping interval"); 415 if (preload > 0 && getuid()) 416 errx(1, "Must be superuser to use -l"); 417 #endif 418 sec_to_timeval(interval, &interval_tv); 419 420 if ((pingflags & (F_AUDIBLE|F_FLOOD)) == (F_AUDIBLE|F_FLOOD)) 421 warnx("Sorry, no audible output for flood pings"); 422 423 if (npackets != 0) { 424 npackets += preload; 425 } else { 426 npackets = INT_MAX; 427 } 428 429 if (hostind == 0) { 430 if (optind != argc-1) 431 usage(); 432 else 433 hostind = optind; 434 } 435 else if (hostind >= argc - 1) 436 usage(); 437 438 gethost("", argv[hostind], &whereto, hostname, sizeof(hostname)); 439 if (IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) 440 pingflags |= F_MCAST; 441 if (!(pingflags & F_SOURCE_ROUTE)) 442 (void) memcpy(&send_addr, &whereto, sizeof(send_addr)); 443 444 loc_addr.sin_family = AF_INET; 445 loc_addr.sin_len = sizeof(struct sockaddr_in); 446 loc_addr.sin_addr.s_addr = htonl((127<<24)+1); 447 448 if (datalen >= PHDR_LEN) /* can we time them? */ 449 pingflags |= F_TIMING; 450 packlen = datalen + 60 + 76; /* MAXIP + MAXICMP */ 451 if ((packet = (u_char *)malloc(packlen)) == NULL) 452 err(1, "Out of memory"); 453 454 if (pingflags & F_PING_FILLED) { 455 fill(); 456 } else if (pingflags & F_PING_RANDOM) { 457 rnd_fill(); 458 } else { 459 for (i = PHDR_LEN; i < datalen; i++) 460 opack_icmp.icmp_data[i] = i; 461 } 462 463 ident = arc4random() & 0xFFFF; 464 465 if (options & SO_DEBUG) { 466 if (setsockopt(s, SOL_SOCKET, SO_DEBUG, 467 (char *)&on, sizeof(on)) == -1) 468 warn("Can't turn on socket debugging"); 469 } 470 if (options & SO_DONTROUTE) { 471 if (setsockopt(s, SOL_SOCKET, SO_DONTROUTE, 472 (char *)&on, sizeof(on)) == -1) 473 warn("SO_DONTROUTE"); 474 } 475 476 if (options & SO_DEBUG) { 477 if (setsockopt(sloop, SOL_SOCKET, SO_DEBUG, 478 (char *)&on, sizeof(on)) == -1) 479 warn("Can't turn on socket debugging"); 480 } 481 if (options & SO_DONTROUTE) { 482 if (setsockopt(sloop, SOL_SOCKET, SO_DONTROUTE, 483 (char *)&on, sizeof(on)) == -1) 484 warn("SO_DONTROUTE"); 485 } 486 487 if (pingflags & F_SOURCE_ROUTE) { 488 optspace[IPOPT_OPTVAL] = IPOPT_LSRR; 489 optspace[IPOPT_OLEN] = optlen = 7; 490 optspace[IPOPT_OFFSET] = IPOPT_MINOFF; 491 (void)memcpy(&optspace[IPOPT_MINOFF-1], &whereto.sin_addr, 492 sizeof(whereto.sin_addr)); 493 optspace[optlen++] = IPOPT_NOP; 494 } 495 if (pingflags & F_RECORD_ROUTE) { 496 optspace[optlen+IPOPT_OPTVAL] = IPOPT_RR; 497 optspace[optlen+IPOPT_OLEN] = (MAX_IPOPTLEN -1-optlen); 498 optspace[optlen+IPOPT_OFFSET] = IPOPT_MINOFF; 499 optlen = MAX_IPOPTLEN; 500 } 501 /* this leaves opack_ip 0(mod 4) aligned */ 502 opack_ip = (struct ip *)((char *)&out_pack.o_ip 503 + sizeof(out_pack.o_opt) 504 - optlen); 505 (void) memcpy(opack_ip + 1, optspace, optlen); 506 507 if (setsockopt(s,IPPROTO_IP,IP_HDRINCL, (char *) &on, sizeof(on)) < 0) 508 err(1, "Can't set special IP header"); 509 510 opack_ip->ip_v = IPVERSION; 511 opack_ip->ip_hl = (sizeof(struct ip)+optlen) >> 2; 512 opack_ip->ip_tos = tos; 513 opack_ip->ip_off = (pingflags & F_DF) ? IP_DF : 0; 514 opack_ip->ip_ttl = ttl ? ttl : MAXTTL; 515 opack_ip->ip_p = IPPROTO_ICMP; 516 opack_ip->ip_src = src_addr.sin_addr; 517 opack_ip->ip_dst = send_addr.sin_addr; 518 519 if (pingflags & F_MCAST) { 520 if (pingflags & F_MCAST_NOLOOP) { 521 u_char loop = 0; 522 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, 523 (char *) &loop, 1) < 0) 524 err(1, "Can't disable multicast loopback"); 525 } 526 527 if (ttl != 0 528 && setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, 529 (char *) &ttl, 1) < 0) 530 err(1, "Can't set multicast time-to-live"); 531 532 if ((pingflags & F_SOURCE_ADDR) 533 && setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, 534 (char *) &src_addr.sin_addr, 535 sizeof(src_addr.sin_addr)) < 0) 536 err(1, "Can't set multicast source interface"); 537 538 } else if (pingflags & F_SOURCE_ADDR) { 539 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, 540 (char *) &src_addr.sin_addr, 541 sizeof(src_addr.sin_addr)) < 0) 542 err(1, "Can't set source interface/address"); 543 } 544 #ifdef IPSEC 545 #ifdef IPSEC_POLICY_IPSEC 546 { 547 char *buf; 548 if (pingflags & F_POLICY) { 549 if (policy_in != NULL) { 550 buf = ipsec_set_policy(policy_in, strlen(policy_in)); 551 if (buf == NULL) 552 errx(1, "%s", ipsec_strerror()); 553 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 554 buf, ipsec_get_policylen(buf)) < 0) { 555 err(1, "ipsec policy cannot be configured"); 556 } 557 free(buf); 558 } 559 if (policy_out != NULL) { 560 buf = ipsec_set_policy(policy_out, strlen(policy_out)); 561 if (buf == NULL) 562 errx(1, "%s", ipsec_strerror()); 563 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 564 buf, ipsec_get_policylen(buf)) < 0) { 565 err(1, "ipsec policy cannot be configured"); 566 } 567 free(buf); 568 } 569 } 570 buf = ipsec_set_policy("out bypass", strlen("out bypass")); 571 if (buf == NULL) 572 errx(1, "%s", ipsec_strerror()); 573 if (setsockopt(sloop, IPPROTO_IP, IP_IPSEC_POLICY, 574 buf, ipsec_get_policylen(buf)) < 0) { 575 #if 0 576 warnx("ipsec is not configured"); 577 #else 578 /* ignore it, should be okay */ 579 #endif 580 } 581 free(buf); 582 } 583 #else 584 { 585 int optval; 586 if (pingflags & F_AUTHHDR) { 587 optval = IPSEC_LEVEL_REQUIRE; 588 #ifdef IP_AUTH_TRANS_LEVEL 589 (void)setsockopt(s, IPPROTO_IP, IP_AUTH_TRANS_LEVEL, 590 (char *)&optval, sizeof(optval)); 591 #else 592 (void)setsockopt(s, IPPROTO_IP, IP_AUTH_LEVEL, 593 (char *)&optval, sizeof(optval)); 594 #endif 595 } 596 if (pingflags & F_ENCRYPT) { 597 optval = IPSEC_LEVEL_REQUIRE; 598 (void)setsockopt(s, IPPROTO_IP, IP_ESP_TRANS_LEVEL, 599 (char *)&optval, sizeof(optval)); 600 } 601 optval = IPSEC_LEVEL_BYPASS; 602 #ifdef IP_AUTH_TRANS_LEVEL 603 (void)setsockopt(sloop, IPPROTO_IP, IP_AUTH_TRANS_LEVEL, 604 (char *)&optval, sizeof(optval)); 605 #else 606 (void)setsockopt(sloop, IPPROTO_IP, IP_AUTH_LEVEL, 607 (char *)&optval, sizeof(optval)); 608 #endif 609 (void)setsockopt(sloop, IPPROTO_IP, IP_ESP_TRANS_LEVEL, 610 (char *)&optval, sizeof(optval)); 611 } 612 #endif /*IPSEC_POLICY_IPSEC*/ 613 #endif /*IPSEC*/ 614 615 (void)printf("PING %s (%s): %d data bytes\n", hostname, 616 inet_ntoa(whereto.sin_addr), datalen); 617 618 /* When pinging the broadcast address, you can get a lot 619 * of answers. Doing something so evil is useful if you 620 * are trying to stress the ethernet, or just want to 621 * fill the arp cache to get some stuff for /etc/ethers. 622 */ 623 while (0 > setsockopt(s, SOL_SOCKET, SO_RCVBUF, 624 (char*)&bufspace, sizeof(bufspace))) { 625 if ((bufspace -= 4096) <= 0) 626 err(1, "Cannot set the receive buffer size"); 627 } 628 629 /* make it possible to send giant probes, but do not worry now 630 * if it fails, since we probably won't send giant probes. 631 */ 632 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, 633 (char*)&bufspace, sizeof(bufspace)); 634 635 (void)signal(SIGINT, prefinish); 636 637 #ifdef SIGINFO 638 sa.sa_handler = prtsig; 639 sa.sa_flags = SA_NOKERNINFO; 640 sigemptyset(&sa.sa_mask); 641 (void)sigaction(SIGINFO, &sa, NULL); 642 #else 643 (void)signal(SIGQUIT, prtsig); 644 #endif 645 (void)signal(SIGCONT, prtsig); 646 647 /* fire off them quickies */ 648 for (i = 0; i < preload; i++) { 649 (void)gettimeofday(&now, 0); 650 pinger(); 651 } 652 653 doit(); 654 return 0; 655 } 656 657 658 static void 659 doit(void) 660 { 661 int cc; 662 struct sockaddr_in from; 663 socklen_t fromlen; 664 double sec, last, d_last; 665 struct pollfd fdmaskp[1]; 666 667 (void)gettimeofday(&clear_cache,0); 668 if (maxwait != 0) { 669 last = timeval_to_sec(&clear_cache) + maxwait; 670 d_last = 0; 671 } else { 672 last = 0; 673 d_last = 365*24*60*60; 674 } 675 676 do { 677 (void)gettimeofday(&now,0); 678 679 if (last != 0) 680 d_last = last - timeval_to_sec(&now); 681 682 if (ntransmitted < npackets && d_last > 0) { 683 /* send if within 100 usec or late for next packet */ 684 sec = diffsec(&next_tx,&now); 685 if (sec <= 0.0001 || 686 (lastrcvd && (pingflags & F_FLOOD))) { 687 pinger(); 688 sec = diffsec(&next_tx,&now); 689 } 690 if (sec < 0.0) 691 sec = 0.0; 692 if (d_last < sec) 693 sec = d_last; 694 695 } else { 696 /* For the last response, wait twice as long as the 697 * worst case seen, or 10 times as long as the 698 * maximum interpacket interval, whichever is longer. 699 */ 700 sec = MAX(2 * tmax, 10 * interval) - 701 diffsec(&now, &last_tx); 702 if (d_last < sec) 703 sec = d_last; 704 if (sec <= 0) 705 break; 706 } 707 708 709 fdmaskp[0].fd = s; 710 fdmaskp[0].events = POLLIN; 711 cc = poll(fdmaskp, 1, (int)(sec * 1000)); 712 if (cc <= 0) { 713 if (cc < 0) { 714 if (errno == EINTR) 715 continue; 716 jiggle_flush(1); 717 err(1, "poll"); 718 } 719 continue; 720 } 721 722 fromlen = sizeof(from); 723 cc = recvfrom(s, (char *) packet, packlen, 724 0, (struct sockaddr *)&from, 725 &fromlen); 726 if (cc < 0) { 727 if (errno != EINTR) { 728 jiggle_flush(1); 729 warn("recvfrom"); 730 (void)fflush(stderr); 731 } 732 continue; 733 } 734 (void)gettimeofday(&now, 0); 735 pr_pack(packet, cc, &from); 736 737 } while (nreceived < npackets 738 && (nreceived == 0 || !(pingflags & F_ONCE))); 739 740 finish(0); 741 } 742 743 744 static void 745 jiggle_flush(int nl) /* new line if there are dots */ 746 { 747 int serrno = errno; 748 749 if (jiggle_cnt > 0) { 750 total_jiggled += jiggle_cnt; 751 jiggle_direction = 1; 752 do { 753 (void)putchar('.'); 754 } while (--jiggle_cnt > 0); 755 756 } else if (jiggle_cnt < 0) { 757 total_jiggled -= jiggle_cnt; 758 jiggle_direction = -1; 759 do { 760 (void)putchar('\b'); 761 } while (++jiggle_cnt < 0); 762 } 763 764 if (nl) { 765 if (total_jiggled != 0) 766 (void)putchar('\n'); 767 total_jiggled = 0; 768 jiggle_direction = -1; 769 } 770 771 (void)fflush(stdout); 772 (void)fflush(stderr); 773 jiggle_time = now; 774 errno = serrno; 775 } 776 777 778 /* jiggle the cursor for flood-ping 779 */ 780 static void 781 jiggle(int delta) 782 { 783 double dt; 784 785 if (pingflags & F_QUIET) 786 return; 787 788 /* do not back up into messages */ 789 if (total_jiggled+jiggle_cnt+delta < 0) 790 return; 791 792 jiggle_cnt += delta; 793 794 /* flush the FLOOD dots when things are quiet 795 * or occassionally to make the cursor jiggle. 796 */ 797 dt = diffsec(&last_tx, &jiggle_time); 798 if (dt > 0.2 || (dt >= 0.15 && delta*jiggle_direction < 0)) 799 jiggle_flush(0); 800 } 801 802 803 /* 804 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 805 * will be added on by the kernel. The ID field is our UNIX process ID, 806 * and the sequence number is an ascending integer. The first PHDR_LEN bytes 807 * of the data portion are used to hold a UNIX "timeval" struct in VAX 808 * byte-order, to compute the round-trip time. 809 */ 810 static void 811 pinger(void) 812 { 813 struct tv32 tv32; 814 int i, cc, sw; 815 816 opack_icmp.icmp_code = 0; 817 opack_icmp.icmp_seq = htons((u_int16_t)(ntransmitted)); 818 819 /* clear the cached route in the kernel after an ICMP 820 * response such as a Redirect is seen to stop causing 821 * more such packets. Also clear the cached route 822 * periodically in case of routing changes that make 823 * black holes come and go. 824 */ 825 if (clear_cache.tv_sec != now.tv_sec) { 826 opack_icmp.icmp_type = ICMP_ECHOREPLY; 827 opack_icmp.icmp_id = ~ident; 828 opack_icmp.icmp_cksum = 0; 829 opack_icmp.icmp_cksum = in_cksum((u_int16_t *)&opack_icmp, 830 PHDR_LEN); 831 sw = 0; 832 if (setsockopt(sloop,IPPROTO_IP,IP_HDRINCL, 833 (char *)&sw,sizeof(sw)) < 0) 834 err(1, "Can't turn off special IP header"); 835 if (sendto(sloop, (char *) &opack_icmp, PHDR_LEN, MSG_DONTROUTE, 836 (struct sockaddr *)&loc_addr, 837 sizeof(struct sockaddr_in)) < 0) { 838 /* 839 * XXX: we only report this as a warning in verbose 840 * mode because people get confused when they see 841 * this error when they are running in single user 842 * mode and they have not configured lo0 843 */ 844 if (pingflags & F_VERBOSE) 845 warn("failed to clear cached route"); 846 } 847 sw = 1; 848 if (setsockopt(sloop,IPPROTO_IP,IP_HDRINCL, 849 (char *)&sw, sizeof(sw)) < 0) 850 err(1, "Can't set special IP header"); 851 852 (void)gettimeofday(&clear_cache,0); 853 } 854 855 opack_icmp.icmp_type = ICMP_ECHO; 856 opack_icmp.icmp_id = ident; 857 tv32.tv32_sec = htonl(now.tv_sec); 858 tv32.tv32_usec = htonl(now.tv_usec); 859 if (pingflags & F_TIMING) 860 (void) memcpy(&opack_icmp.icmp_data[0], &tv32, sizeof(tv32)); 861 cc = datalen + PHDR_LEN; 862 opack_icmp.icmp_cksum = 0; 863 opack_icmp.icmp_cksum = in_cksum((u_int16_t *)&opack_icmp, cc); 864 865 cc += opack_ip->ip_hl<<2; 866 opack_ip->ip_len = cc; 867 i = sendto(s, (char *) opack_ip, cc, 0, 868 (struct sockaddr *)&send_addr, sizeof(struct sockaddr_in)); 869 if (i != cc) { 870 jiggle_flush(1); 871 if (i < 0) 872 warn("sendto"); 873 else 874 warnx("wrote %s %d chars, ret=%d", hostname, cc, i); 875 (void)fflush(stderr); 876 } 877 lastrcvd = 0; 878 879 CLR(ntransmitted); 880 ntransmitted++; 881 882 last_tx = now; 883 if (next_tx.tv_sec == 0) { 884 first_tx = now; 885 next_tx = now; 886 } 887 888 /* Transmit regularly, at always the same microsecond in the 889 * second when going at one packet per second. 890 * If we are at most 100 ms behind, send extras to get caught up. 891 * Otherwise, skip packets we were too slow to send. 892 */ 893 if (diffsec(&next_tx, &now) <= interval) { 894 do { 895 timevaladd(&next_tx, &interval_tv); 896 } while (diffsec(&next_tx, &now) < -0.1); 897 } 898 899 if (pingflags & F_FLOOD) 900 jiggle(1); 901 902 /* While the packet is going out, ready buffer for the next 903 * packet. Use a fast but not very good random number generator. 904 */ 905 if (pingflags & F_PING_RANDOM) 906 rnd_fill(); 907 } 908 909 910 static void 911 pr_pack_sub(int cc, 912 char *addr, 913 int seqno, 914 int dupflag, 915 int ttl, 916 double triptime) 917 { 918 jiggle_flush(1); 919 920 if (pingflags & F_FLOOD) 921 return; 922 923 (void)printf("%d bytes from %s: icmp_seq=%u", cc, addr, seqno); 924 if (dupflag) 925 (void)printf(" DUP!"); 926 (void)printf(" ttl=%d", ttl); 927 if (pingflags & F_TIMING) 928 (void)printf(" time=%.3f ms", triptime*1000.0); 929 930 /* 931 * Send beep to stderr, since that's more likely than stdout 932 * to go to a terminal.. 933 */ 934 if (pingflags & F_AUDIBLE && !dupflag) 935 (void)fprintf(stderr,"\a"); 936 } 937 938 939 /* 940 * Print out the packet, if it came from us. This logic is necessary 941 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 942 * which arrive ('tis only fair). This permits multiple copies of this 943 * program to be run without having intermingled output (or statistics!). 944 */ 945 static void 946 pr_pack(u_char *buf, 947 int tot_len, 948 struct sockaddr_in *from) 949 { 950 struct ip *ip; 951 struct icmp *icp; 952 int i, j, net_len; 953 u_char *cp; 954 static int old_rrlen; 955 static char old_rr[MAX_IPOPTLEN]; 956 int hlen, dupflag = 0, dumped; 957 double triptime = 0.0; 958 #define PR_PACK_SUB() {if (!dumped) { \ 959 dumped = 1; \ 960 pr_pack_sub(net_len, inet_ntoa(from->sin_addr), \ 961 ntohs((u_int16_t)icp->icmp_seq), \ 962 dupflag, ip->ip_ttl, triptime);}} 963 964 /* Check the IP header */ 965 ip = (struct ip *) buf; 966 hlen = ip->ip_hl << 2; 967 if (tot_len < hlen + ICMP_MINLEN) { 968 if (pingflags & F_VERBOSE) { 969 jiggle_flush(1); 970 (void)printf("packet too short (%d bytes) from %s\n", 971 tot_len, inet_ntoa(from->sin_addr)); 972 } 973 return; 974 } 975 976 /* Now the ICMP part */ 977 dumped = 0; 978 net_len = tot_len - hlen; 979 icp = (struct icmp *)(buf + hlen); 980 if (icp->icmp_type == ICMP_ECHOREPLY 981 && icp->icmp_id == ident) { 982 if (icp->icmp_seq == htons((u_int16_t)(ntransmitted-1))) 983 lastrcvd = 1; 984 last_rx = now; 985 if (first_rx.tv_sec == 0) 986 first_rx = last_rx; 987 nreceived++; 988 if (pingflags & F_TIMING) { 989 struct timeval tv; 990 struct tv32 tv32; 991 992 (void) memcpy(&tv32, icp->icmp_data, sizeof(tv32)); 993 tv.tv_sec = ntohl(tv32.tv32_sec); 994 tv.tv_usec = ntohl(tv32.tv32_usec); 995 triptime = diffsec(&last_rx, &tv); 996 tsum += triptime; 997 tsumsq += triptime * triptime; 998 if (triptime < tmin) 999 tmin = triptime; 1000 if (triptime > tmax) 1001 tmax = triptime; 1002 } 1003 1004 if (TST(ntohs((u_int16_t)icp->icmp_seq))) { 1005 nrepeats++, nreceived--; 1006 dupflag=1; 1007 } else { 1008 SET(ntohs((u_int16_t)icp->icmp_seq)); 1009 } 1010 1011 if (tot_len != opack_ip->ip_len) { 1012 PR_PACK_SUB(); 1013 (void)printf("\nwrong total length %d instead of %d", 1014 tot_len, opack_ip->ip_len); 1015 } 1016 1017 if (!dupflag) { 1018 static u_int16_t last_seqno = 0xffff; 1019 u_int16_t seqno = ntohs((u_int16_t)icp->icmp_seq); 1020 u_int16_t gap = seqno - (last_seqno + 1); 1021 if (gap > 0 && gap < 0x8000 && 1022 (pingflags & F_VERBOSE)) { 1023 (void)printf("[*** sequence gap of %u " 1024 "packets from %u ... %u ***]\n", gap, 1025 (u_int16_t) (last_seqno + 1), 1026 (u_int16_t) (seqno - 1)); 1027 if (pingflags & F_QUIET) 1028 summary(0); 1029 } 1030 1031 if (gap < 0x8000) 1032 last_seqno = seqno; 1033 } 1034 1035 if (pingflags & F_QUIET) 1036 return; 1037 1038 if (!(pingflags & F_FLOOD)) 1039 PR_PACK_SUB(); 1040 1041 /* check the data */ 1042 if (datalen > PHDR_LEN 1043 && !(pingflags & F_PING_RANDOM) 1044 && memcmp(&icp->icmp_data[PHDR_LEN], 1045 &opack_icmp.icmp_data[PHDR_LEN], 1046 datalen-PHDR_LEN)) { 1047 for (i=PHDR_LEN; i<datalen; i++) { 1048 if (icp->icmp_data[i] != 1049 opack_icmp.icmp_data[i]) 1050 break; 1051 } 1052 PR_PACK_SUB(); 1053 (void)printf("\nwrong data byte #%d should have been" 1054 " %#x but was %#x", i, 1055 (u_char)opack_icmp.icmp_data[i], 1056 (u_char)icp->icmp_data[i]); 1057 for (i=PHDR_LEN; i<datalen; i++) { 1058 if ((i%16) == PHDR_LEN) 1059 (void)printf("\n\t"); 1060 (void)printf("%2x ",(u_char)icp->icmp_data[i]); 1061 } 1062 } 1063 1064 } else { 1065 if (!pr_icmph(icp, from, net_len)) 1066 return; 1067 dumped = 2; 1068 } 1069 1070 /* Display any IP options */ 1071 cp = buf + sizeof(struct ip); 1072 while (hlen > (int)sizeof(struct ip)) { 1073 switch (*cp) { 1074 case IPOPT_EOL: 1075 hlen = 0; 1076 break; 1077 case IPOPT_LSRR: 1078 hlen -= 2; 1079 j = *++cp; 1080 ++cp; 1081 j -= IPOPT_MINOFF; 1082 if (j <= 0) 1083 continue; 1084 if (dumped <= 1) { 1085 j = ((j+3)/4)*4; 1086 hlen -= j; 1087 cp += j; 1088 break; 1089 } 1090 PR_PACK_SUB(); 1091 (void)printf("\nLSRR: "); 1092 for (;;) { 1093 pr_saddr(cp); 1094 cp += 4; 1095 hlen -= 4; 1096 j -= 4; 1097 if (j <= 0) 1098 break; 1099 (void)putchar('\n'); 1100 } 1101 break; 1102 case IPOPT_RR: 1103 j = *++cp; /* get length */ 1104 i = *++cp; /* and pointer */ 1105 hlen -= 2; 1106 if (i > j) 1107 i = j; 1108 i -= IPOPT_MINOFF; 1109 if (i <= 0) 1110 continue; 1111 if (dumped <= 1) { 1112 if (i == old_rrlen 1113 && !memcmp(cp, old_rr, i)) { 1114 if (dumped) 1115 (void)printf("\t(same route)"); 1116 j = ((i+3)/4)*4; 1117 hlen -= j; 1118 cp += j; 1119 break; 1120 } 1121 old_rrlen = i; 1122 (void) memcpy(old_rr, cp, i); 1123 } 1124 if (!dumped) { 1125 jiggle_flush(1); 1126 (void)printf("RR: "); 1127 dumped = 1; 1128 } else { 1129 (void)printf("\nRR: "); 1130 } 1131 for (;;) { 1132 pr_saddr(cp); 1133 cp += 4; 1134 hlen -= 4; 1135 i -= 4; 1136 if (i <= 0) 1137 break; 1138 (void)putchar('\n'); 1139 } 1140 break; 1141 case IPOPT_NOP: 1142 if (dumped <= 1) 1143 break; 1144 PR_PACK_SUB(); 1145 (void)printf("\nNOP"); 1146 break; 1147 #ifdef sgi 1148 case IPOPT_SECURITY: /* RFC 1108 RIPSO BSO */ 1149 case IPOPT_ESO: /* RFC 1108 RIPSO ESO */ 1150 case IPOPT_CIPSO: /* Commercial IPSO */ 1151 if ((sysconf(_SC_IP_SECOPTS)) > 0) { 1152 i = (unsigned)cp[1]; 1153 hlen -= i - 1; 1154 PR_PACK_SUB(); 1155 (void)printf("\nSEC:"); 1156 while (i--) { 1157 (void)printf(" %02x", *cp++); 1158 } 1159 cp--; 1160 break; 1161 } 1162 #endif 1163 default: 1164 PR_PACK_SUB(); 1165 (void)printf("\nunknown option 0x%x", *cp); 1166 break; 1167 } 1168 hlen--; 1169 cp++; 1170 } 1171 1172 if (dumped) { 1173 (void)putchar('\n'); 1174 (void)fflush(stdout); 1175 } else { 1176 jiggle(-1); 1177 } 1178 } 1179 1180 1181 /* Compute the IP checksum 1182 * This assumes the packet is less than 32K long. 1183 */ 1184 static u_int16_t 1185 in_cksum(u_int16_t *p, u_int len) 1186 { 1187 u_int32_t sum = 0; 1188 int nwords = len >> 1; 1189 1190 while (nwords-- != 0) 1191 sum += *p++; 1192 1193 if (len & 1) { 1194 union { 1195 u_int16_t w; 1196 u_int8_t c[2]; 1197 } u; 1198 u.c[0] = *(u_char *)p; 1199 u.c[1] = 0; 1200 sum += u.w; 1201 } 1202 1203 /* end-around-carry */ 1204 sum = (sum >> 16) + (sum & 0xffff); 1205 sum += (sum >> 16); 1206 return (~sum); 1207 } 1208 1209 1210 /* 1211 * compute the difference of two timevals in seconds 1212 */ 1213 static double 1214 diffsec(struct timeval *timenow, 1215 struct timeval *then) 1216 { 1217 return ((timenow->tv_sec - then->tv_sec)*1.0 1218 + (timenow->tv_usec - then->tv_usec)/1000000.0); 1219 } 1220 1221 1222 static void 1223 timevaladd(struct timeval *t1, 1224 struct timeval *t2) 1225 { 1226 1227 t1->tv_sec += t2->tv_sec; 1228 if ((t1->tv_usec += t2->tv_usec) >= 1000000) { 1229 t1->tv_sec++; 1230 t1->tv_usec -= 1000000; 1231 } 1232 } 1233 1234 1235 static void 1236 sec_to_timeval(const double sec, struct timeval *tp) 1237 { 1238 tp->tv_sec = sec; 1239 tp->tv_usec = (sec - tp->tv_sec) * 1000000.0; 1240 } 1241 1242 1243 static double 1244 timeval_to_sec(const struct timeval *tp) 1245 { 1246 return tp->tv_sec + tp->tv_usec / 1000000.0; 1247 } 1248 1249 1250 /* 1251 * Print statistics. 1252 * Heavily buffered STDIO is used here, so that all the statistics 1253 * will be written with 1 sys-write call. This is nice when more 1254 * than one copy of the program is running on a terminal; it prevents 1255 * the statistics output from becomming intermingled. 1256 */ 1257 static void 1258 summary(int header) 1259 { 1260 jiggle_flush(1); 1261 1262 if (header) 1263 (void)printf("\n----%s PING Statistics----\n", hostname); 1264 (void)printf("%d packets transmitted, ", ntransmitted); 1265 (void)printf("%d packets received, ", nreceived); 1266 if (nrepeats) 1267 (void)printf("+%d duplicates, ", nrepeats); 1268 if (ntransmitted) { 1269 if (nreceived > ntransmitted) 1270 (void)printf("-- somebody's duplicating packets!"); 1271 else 1272 (void)printf("%.1f%% packet loss", 1273 (((ntransmitted-nreceived)*100.0) / 1274 ntransmitted)); 1275 } 1276 (void)printf("\n"); 1277 if (nreceived && (pingflags & F_TIMING)) { 1278 double n = nreceived + nrepeats; 1279 double avg = (tsum / n); 1280 double variance = 0.0; 1281 if (n>1) 1282 variance = (tsumsq - n*avg*avg) /(n-1); 1283 1284 printf("round-trip min/avg/max/stddev = " 1285 "%.3f/%.3f/%.3f/%.3f ms\n", 1286 tmin * 1000.0, avg * 1000.0, 1287 tmax * 1000.0, sqrt(variance) * 1000.0); 1288 if (pingflags & F_FLOOD) { 1289 double r = diffsec(&last_rx, &first_rx); 1290 double t = diffsec(&last_tx, &first_tx); 1291 if (r == 0) 1292 r = 0.0001; 1293 if (t == 0) 1294 t = 0.0001; 1295 (void)printf(" %.1f packets/sec sent, " 1296 " %.1f packets/sec received\n", 1297 ntransmitted/t, nreceived/r); 1298 } 1299 } 1300 } 1301 1302 1303 /* 1304 * Print statistics when SIGINFO is received. 1305 */ 1306 /* ARGSUSED */ 1307 static void 1308 prtsig(int dummy) 1309 { 1310 1311 summary(0); 1312 #ifndef SIGINFO 1313 (void)signal(SIGQUIT, prtsig); 1314 #endif 1315 } 1316 1317 1318 /* 1319 * On the first SIGINT, allow any outstanding packets to dribble in 1320 */ 1321 static void 1322 prefinish(int dummy) 1323 { 1324 if (lastrcvd /* quit now if caught up */ 1325 || nreceived == 0) /* or if remote is dead */ 1326 finish(0); 1327 1328 (void)signal(dummy, finish); /* do this only the 1st time */ 1329 1330 if (npackets > ntransmitted) /* let the normal limit work */ 1331 npackets = ntransmitted; 1332 } 1333 1334 /* 1335 * Print statistics and give up. 1336 */ 1337 /* ARGSUSED */ 1338 static void 1339 finish(int dummy) 1340 { 1341 #ifdef SIGINFO 1342 (void)signal(SIGINFO, SIG_DFL); 1343 #else 1344 (void)signal(SIGQUIT, SIG_DFL); 1345 #endif 1346 1347 summary(1); 1348 exit(nreceived > 0 ? 0 : 2); 1349 } 1350 1351 1352 static int /* 0=do not print it */ 1353 ck_pr_icmph(struct icmp *icp, 1354 struct sockaddr_in *from, 1355 int cc, 1356 int override) /* 1=override VERBOSE if interesting */ 1357 { 1358 int hlen; 1359 struct ip ipb, *ip = &ipb; 1360 struct icmp icp2b, *icp2 = &icp2b; 1361 int res; 1362 1363 if (pingflags & F_VERBOSE) { 1364 res = 1; 1365 jiggle_flush(1); 1366 } else { 1367 res = 0; 1368 } 1369 1370 (void) memcpy(ip, icp->icmp_data, sizeof(*ip)); 1371 hlen = ip->ip_hl << 2; 1372 if (ip->ip_p == IPPROTO_ICMP 1373 && hlen + 6 <= cc) { 1374 (void) memcpy(icp2, &icp->icmp_data[hlen], sizeof(*icp2)); 1375 if (icp2->icmp_id == ident) { 1376 /* remember to clear route cached in kernel 1377 * if this non-Echo-Reply ICMP message was for one 1378 * of our packets. 1379 */ 1380 clear_cache.tv_sec = 0; 1381 1382 if (!res && override 1383 && (pingflags & (F_QUIET|F_SEMI_QUIET)) == 0) { 1384 jiggle_flush(1); 1385 (void)printf("%d bytes from %s: ", 1386 cc, pr_addr(&from->sin_addr)); 1387 res = 1; 1388 } 1389 } 1390 } 1391 1392 return res; 1393 } 1394 1395 1396 /* 1397 * Print a descriptive string about an ICMP header other than an echo reply. 1398 */ 1399 static int /* 0=printed nothing */ 1400 pr_icmph(struct icmp *icp, 1401 struct sockaddr_in *from, 1402 int cc) 1403 { 1404 switch (icp->icmp_type ) { 1405 case ICMP_UNREACH: 1406 if (!ck_pr_icmph(icp, from, cc, 1)) 1407 return 0; 1408 switch (icp->icmp_code) { 1409 case ICMP_UNREACH_NET: 1410 (void)printf("Destination Net Unreachable"); 1411 break; 1412 case ICMP_UNREACH_HOST: 1413 (void)printf("Destination Host Unreachable"); 1414 break; 1415 case ICMP_UNREACH_PROTOCOL: 1416 (void)printf("Destination Protocol Unreachable"); 1417 break; 1418 case ICMP_UNREACH_PORT: 1419 (void)printf("Destination Port Unreachable"); 1420 break; 1421 case ICMP_UNREACH_NEEDFRAG: 1422 (void)printf("frag needed and DF set. Next MTU=%d", 1423 ntohs(icp->icmp_nextmtu)); 1424 break; 1425 case ICMP_UNREACH_SRCFAIL: 1426 (void)printf("Source Route Failed"); 1427 break; 1428 case ICMP_UNREACH_NET_UNKNOWN: 1429 (void)printf("Unreachable unknown net"); 1430 break; 1431 case ICMP_UNREACH_HOST_UNKNOWN: 1432 (void)printf("Unreachable unknown host"); 1433 break; 1434 case ICMP_UNREACH_ISOLATED: 1435 (void)printf("Unreachable host isolated"); 1436 break; 1437 case ICMP_UNREACH_NET_PROHIB: 1438 (void)printf("Net prohibited access"); 1439 break; 1440 case ICMP_UNREACH_HOST_PROHIB: 1441 (void)printf("Host prohibited access"); 1442 break; 1443 case ICMP_UNREACH_TOSNET: 1444 (void)printf("Bad TOS for net"); 1445 break; 1446 case ICMP_UNREACH_TOSHOST: 1447 (void)printf("Bad TOS for host"); 1448 break; 1449 case 13: 1450 (void)printf("Communication prohibited"); 1451 break; 1452 case 14: 1453 (void)printf("Host precedence violation"); 1454 break; 1455 case 15: 1456 (void)printf("Precedence cutoff"); 1457 break; 1458 default: 1459 (void)printf("Bad Destination Unreachable Code: %d", 1460 icp->icmp_code); 1461 break; 1462 } 1463 /* Print returned IP header information */ 1464 pr_retip(icp, cc); 1465 break; 1466 1467 case ICMP_SOURCEQUENCH: 1468 if (!ck_pr_icmph(icp, from, cc, 1)) 1469 return 0; 1470 (void)printf("Source Quench"); 1471 pr_retip(icp, cc); 1472 break; 1473 1474 case ICMP_REDIRECT: 1475 if (!ck_pr_icmph(icp, from, cc, 1)) 1476 return 0; 1477 switch (icp->icmp_code) { 1478 case ICMP_REDIRECT_NET: 1479 (void)printf("Redirect Network"); 1480 break; 1481 case ICMP_REDIRECT_HOST: 1482 (void)printf("Redirect Host"); 1483 break; 1484 case ICMP_REDIRECT_TOSNET: 1485 (void)printf("Redirect Type of Service and Network"); 1486 break; 1487 case ICMP_REDIRECT_TOSHOST: 1488 (void)printf("Redirect Type of Service and Host"); 1489 break; 1490 default: 1491 (void)printf("Redirect--Bad Code: %d", icp->icmp_code); 1492 break; 1493 } 1494 (void)printf(" New router addr: %s", 1495 pr_addr(&icp->icmp_hun.ih_gwaddr)); 1496 pr_retip(icp, cc); 1497 break; 1498 1499 case ICMP_ECHO: 1500 if (!ck_pr_icmph(icp, from, cc, 0)) 1501 return 0; 1502 (void)printf("Echo Request: ID=%d seq=%d", 1503 ntohs(icp->icmp_id), ntohs(icp->icmp_seq)); 1504 break; 1505 1506 case ICMP_ECHOREPLY: 1507 /* displaying other's pings is too noisey */ 1508 #if 0 1509 if (!ck_pr_icmph(icp, from, cc, 0)) 1510 return 0; 1511 (void)printf("Echo Reply: ID=%d seq=%d", 1512 ntohs(icp->icmp_id), ntohs(icp->icmp_seq)); 1513 break; 1514 #else 1515 return 0; 1516 #endif 1517 1518 case ICMP_ROUTERADVERT: 1519 if (!ck_pr_icmph(icp, from, cc, 0)) 1520 return 0; 1521 (void)printf("Router Discovery Advert"); 1522 break; 1523 1524 case ICMP_ROUTERSOLICIT: 1525 if (!ck_pr_icmph(icp, from, cc, 0)) 1526 return 0; 1527 (void)printf("Router Discovery Solicit"); 1528 break; 1529 1530 case ICMP_TIMXCEED: 1531 if (!ck_pr_icmph(icp, from, cc, 1)) 1532 return 0; 1533 switch (icp->icmp_code ) { 1534 case ICMP_TIMXCEED_INTRANS: 1535 (void)printf("Time To Live exceeded"); 1536 break; 1537 case ICMP_TIMXCEED_REASS: 1538 (void)printf("Frag reassembly time exceeded"); 1539 break; 1540 default: 1541 (void)printf("Time exceeded, Bad Code: %d", 1542 icp->icmp_code); 1543 break; 1544 } 1545 pr_retip(icp, cc); 1546 break; 1547 1548 case ICMP_PARAMPROB: 1549 if (!ck_pr_icmph(icp, from, cc, 1)) 1550 return 0; 1551 (void)printf("Parameter problem: pointer = 0x%02x", 1552 icp->icmp_hun.ih_pptr); 1553 pr_retip(icp, cc); 1554 break; 1555 1556 case ICMP_TSTAMP: 1557 if (!ck_pr_icmph(icp, from, cc, 0)) 1558 return 0; 1559 (void)printf("Timestamp"); 1560 break; 1561 1562 case ICMP_TSTAMPREPLY: 1563 if (!ck_pr_icmph(icp, from, cc, 0)) 1564 return 0; 1565 (void)printf("Timestamp Reply"); 1566 break; 1567 1568 case ICMP_IREQ: 1569 if (!ck_pr_icmph(icp, from, cc, 0)) 1570 return 0; 1571 (void)printf("Information Request"); 1572 break; 1573 1574 case ICMP_IREQREPLY: 1575 if (!ck_pr_icmph(icp, from, cc, 0)) 1576 return 0; 1577 (void)printf("Information Reply"); 1578 break; 1579 1580 case ICMP_MASKREQ: 1581 if (!ck_pr_icmph(icp, from, cc, 0)) 1582 return 0; 1583 (void)printf("Address Mask Request"); 1584 break; 1585 1586 case ICMP_MASKREPLY: 1587 if (!ck_pr_icmph(icp, from, cc, 0)) 1588 return 0; 1589 (void)printf("Address Mask Reply"); 1590 break; 1591 1592 default: 1593 if (!ck_pr_icmph(icp, from, cc, 0)) 1594 return 0; 1595 (void)printf("Bad ICMP type: %d", icp->icmp_type); 1596 if (pingflags & F_VERBOSE) 1597 pr_iph(icp, cc); 1598 } 1599 1600 return 1; 1601 } 1602 1603 1604 /* 1605 * Print an IP header with options. 1606 */ 1607 static void 1608 pr_iph(struct icmp *icp, 1609 int cc) 1610 { 1611 int hlen; 1612 u_char *cp; 1613 struct ip ipb, *ip = &ipb; 1614 1615 (void) memcpy(ip, icp->icmp_data, sizeof(*ip)); 1616 1617 hlen = ip->ip_hl << 2; 1618 cp = (u_char *) &icp->icmp_data[20]; /* point to options */ 1619 1620 (void)printf("\n Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1621 (void)printf(" %1x %1x %02x %04x %04x", 1622 ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id); 1623 (void)printf(" %1x %04x", 1624 ((ip->ip_off)&0xe000)>>13, (ip->ip_off)&0x1fff); 1625 (void)printf(" %02x %02x %04x", 1626 ip->ip_ttl, ip->ip_p, ip->ip_sum); 1627 (void)printf(" %15s ", 1628 inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1629 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1630 /* dump any option bytes */ 1631 while (hlen-- > 20 && cp < (u_char*)icp+cc) { 1632 (void)printf("%02x", *cp++); 1633 } 1634 } 1635 1636 /* 1637 * Print an ASCII host address starting from a string of bytes. 1638 */ 1639 static void 1640 pr_saddr(u_char *cp) 1641 { 1642 n_long l; 1643 struct in_addr addr; 1644 1645 l = (u_char)*++cp; 1646 l = (l<<8) + (u_char)*++cp; 1647 l = (l<<8) + (u_char)*++cp; 1648 l = (l<<8) + (u_char)*++cp; 1649 addr.s_addr = htonl(l); 1650 (void)printf("\t%s", (l == 0) ? "0.0.0.0" : pr_addr(&addr)); 1651 } 1652 1653 1654 /* 1655 * Return an ASCII host address 1656 * as a dotted quad and optionally with a hostname 1657 */ 1658 static char * 1659 pr_addr(struct in_addr *addr) /* in network order */ 1660 { 1661 struct hostent *hp; 1662 static char buf[MAXHOSTNAMELEN+4+16+1]; 1663 1664 if ((pingflags & F_NUMERIC) 1665 || !(hp = gethostbyaddr((char *)addr, sizeof(*addr), AF_INET))) { 1666 (void)snprintf(buf, sizeof(buf), "%s", inet_ntoa(*addr)); 1667 } else { 1668 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1669 inet_ntoa(*addr)); 1670 } 1671 1672 return buf; 1673 } 1674 1675 /* 1676 * Dump some info on a returned (via ICMP) IP packet. 1677 */ 1678 static void 1679 pr_retip(struct icmp *icp, 1680 int cc) 1681 { 1682 int hlen; 1683 u_char *cp; 1684 struct ip ipb, *ip = &ipb; 1685 1686 (void) memcpy(ip, icp->icmp_data, sizeof(*ip)); 1687 1688 if (pingflags & F_VERBOSE) 1689 pr_iph(icp, cc); 1690 1691 hlen = ip->ip_hl << 2; 1692 cp = (u_char *) &icp->icmp_data[hlen]; 1693 1694 if (ip->ip_p == IPPROTO_TCP) { 1695 if (pingflags & F_VERBOSE) 1696 (void)printf("\n TCP: from port %u, to port %u", 1697 (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3))); 1698 } else if (ip->ip_p == IPPROTO_UDP) { 1699 if (pingflags & F_VERBOSE) 1700 (void)printf("\n UDP: from port %u, to port %u", 1701 (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3))); 1702 } else if (ip->ip_p == IPPROTO_ICMP) { 1703 struct icmp icp2; 1704 (void) memcpy(&icp2, cp, sizeof(icp2)); 1705 if (icp2.icmp_type == ICMP_ECHO) { 1706 if (pingflags & F_VERBOSE) 1707 (void)printf("\n ID=%u icmp_seq=%u", 1708 ntohs((u_int16_t)icp2.icmp_id), 1709 ntohs((u_int16_t)icp2.icmp_seq)); 1710 else 1711 (void)printf(" for icmp_seq=%u", 1712 ntohs((u_int16_t)icp2.icmp_seq)); 1713 } 1714 } 1715 } 1716 1717 static void 1718 fill(void) 1719 { 1720 int i, j, k; 1721 char *cp; 1722 int pat[16]; 1723 1724 for (cp = fill_pat; *cp != '\0'; cp++) { 1725 if (!isxdigit((unsigned char)*cp)) 1726 break; 1727 } 1728 if (cp == fill_pat || *cp != '\0' || (cp-fill_pat) > 16*2) { 1729 (void)fflush(stdout); 1730 errx(1, "\"-p %s\": patterns must be specified with" 1731 " 1-32 hex digits\n", 1732 fill_pat); 1733 } 1734 1735 i = sscanf(fill_pat, 1736 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1737 &pat[0], &pat[1], &pat[2], &pat[3], 1738 &pat[4], &pat[5], &pat[6], &pat[7], 1739 &pat[8], &pat[9], &pat[10], &pat[11], 1740 &pat[12], &pat[13], &pat[14], &pat[15]); 1741 1742 for (k=PHDR_LEN, j = 0; k <= datalen; k++) { 1743 opack_icmp.icmp_data[k] = pat[j]; 1744 if (++j >= i) 1745 j = 0; 1746 } 1747 1748 if (!(pingflags & F_QUIET)) { 1749 (void)printf("PATTERN: 0x"); 1750 for (j=0; j<i; j++) 1751 (void)printf("%02x", 1752 (u_char)opack_icmp.icmp_data[PHDR_LEN+j]); 1753 (void)printf("\n"); 1754 } 1755 1756 } 1757 1758 1759 static void 1760 rnd_fill(void) 1761 { 1762 static u_int32_t rnd; 1763 int i; 1764 1765 for (i = PHDR_LEN; i < datalen; i++) { 1766 rnd = (3141592621U * rnd + 663896637U); 1767 opack_icmp.icmp_data[i] = rnd>>24; 1768 } 1769 } 1770 1771 1772 static void 1773 gethost(const char *arg, 1774 const char *name, 1775 struct sockaddr_in *sa, 1776 char *realname, 1777 int realname_len) 1778 { 1779 struct hostent *hp; 1780 1781 (void)memset(sa, 0, sizeof(*sa)); 1782 sa->sin_family = AF_INET; 1783 sa->sin_len = sizeof(struct sockaddr_in); 1784 1785 /* If it is an IP address, try to convert it to a name to 1786 * have something nice to display. 1787 */ 1788 if (inet_aton(name, &sa->sin_addr) != 0) { 1789 if (realname) { 1790 if (pingflags & F_NUMERIC) 1791 hp = 0; 1792 else 1793 hp = gethostbyaddr((char *)&sa->sin_addr, 1794 sizeof(sa->sin_addr), 1795 AF_INET); 1796 (void)strlcpy(realname, hp ? hp->h_name : name, 1797 realname_len); 1798 } 1799 return; 1800 } 1801 1802 hp = gethostbyname(name); 1803 if (!hp) 1804 errx(1, "Cannot resolve \"%s\" (%s)",name,hstrerror(h_errno)); 1805 1806 if (hp->h_addrtype != AF_INET) 1807 errx(1, "%s only supported with IP", arg); 1808 1809 (void)memcpy(&sa->sin_addr, hp->h_addr, sizeof(sa->sin_addr)); 1810 1811 if (realname) 1812 (void)strlcpy(realname, hp->h_name, realname_len); 1813 } 1814 1815 1816 static void 1817 usage(void) 1818 { 1819 #ifdef IPSEC 1820 #ifdef IPSEC_POLICY_IPSEC 1821 #define IPSECOPT "\n [-E policy] " 1822 #else 1823 #define IPSECOPT "\n [-AE] " 1824 #endif /*IPSEC_POLICY_IPSEC*/ 1825 #else 1826 #define IPSECOPT "" 1827 #endif /*IPSEC*/ 1828 1829 (void)fprintf(stderr, "usage: \n" 1830 "%s [-adDfLnoPqQrRv] [-c count] [-g gateway] [-h host]" 1831 " [-i interval] [-I addr]\n" 1832 " [-l preload] [-p pattern] [-s size] [-t tos] [-T ttl]" 1833 " [-w maxwait] " IPSECOPT "host\n", 1834 getprogname()); 1835 exit(1); 1836 } 1837