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