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