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