ping.c revision 117548
1/* 2 * Copyright (c) 1989, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Mike Muuss. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. All advertising materials mentioning features or use of this software 17 * must display the following acknowledgement: 18 * This product includes software developed by the University of 19 * California, Berkeley and its contributors. 20 * 4. Neither the name of the University nor the names of its contributors 21 * may be used to endorse or promote products derived from this software 22 * without specific prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34 * SUCH DAMAGE. 35 */ 36 37#if 0 38#ifndef lint 39static const char copyright[] = 40"@(#) Copyright (c) 1989, 1993\n\ 41 The Regents of the University of California. All rights reserved.\n"; 42#endif /* not lint */ 43 44#ifndef lint 45static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; 46#endif /* not lint */ 47#endif 48#include <sys/cdefs.h> 49__FBSDID("$FreeBSD: head/sbin/ping/ping.c 117548 2003-07-14 12:37:03Z maxim $"); 50 51/* 52 * P I N G . C 53 * 54 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility, 55 * measure round-trip-delays and packet loss across network paths. 56 * 57 * Author - 58 * Mike Muuss 59 * U. S. Army Ballistic Research Laboratory 60 * December, 1983 61 * 62 * Status - 63 * Public Domain. Distribution Unlimited. 64 * Bugs - 65 * More statistics could always be gathered. 66 * This program has to run SUID to ROOT to access the ICMP socket. 67 */ 68 69#include <sys/param.h> /* NB: we rely on this for <sys/types.h> */ 70#include <sys/socket.h> 71#include <sys/sysctl.h> 72#include <sys/time.h> 73#include <sys/uio.h> 74 75#include <netinet/in.h> 76#include <netinet/in_systm.h> 77#include <netinet/ip.h> 78#include <netinet/ip_icmp.h> 79#include <netinet/ip_var.h> 80#include <arpa/inet.h> 81 82#ifdef IPSEC 83#include <netinet6/ipsec.h> 84#endif /*IPSEC*/ 85 86#include <ctype.h> 87#include <err.h> 88#include <errno.h> 89#include <math.h> 90#include <netdb.h> 91#include <signal.h> 92#include <stdio.h> 93#include <stdlib.h> 94#include <string.h> 95#include <sysexits.h> 96#include <termios.h> 97#include <unistd.h> 98 99#define INADDR_LEN ((int)sizeof(in_addr_t)) 100#define TIMEVAL_LEN ((int)sizeof(struct timeval)) 101#define MASK_LEN (ICMP_MASKLEN - ICMP_MINLEN) 102#define TS_LEN (ICMP_TSLEN - ICMP_MINLEN) 103#define DEFDATALEN 56 /* default data length */ 104#define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */ 105 /* runs out of buffer space */ 106#define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN) 107#define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN) 108#define MINICMPLEN ICMP_MINLEN 109#define MAXWAIT 10 /* max seconds to wait for response */ 110#define MAXALARM (60 * 60) /* max seconds for alarm timeout */ 111#define MAXTOS 255 112 113#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ 114#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ 115#define SET(bit) (A(bit) |= B(bit)) 116#define CLR(bit) (A(bit) &= (~B(bit))) 117#define TST(bit) (A(bit) & B(bit)) 118 119/* various options */ 120int options; 121#define F_FLOOD 0x0001 122#define F_INTERVAL 0x0002 123#define F_NUMERIC 0x0004 124#define F_PINGFILLED 0x0008 125#define F_QUIET 0x0010 126#define F_RROUTE 0x0020 127#define F_SO_DEBUG 0x0040 128#define F_SO_DONTROUTE 0x0080 129#define F_VERBOSE 0x0100 130#define F_QUIET2 0x0200 131#define F_NOLOOP 0x0400 132#define F_MTTL 0x0800 133#define F_MIF 0x1000 134#define F_AUDIBLE 0x2000 135#ifdef IPSEC 136#ifdef IPSEC_POLICY_IPSEC 137#define F_POLICY 0x4000 138#endif /*IPSEC_POLICY_IPSEC*/ 139#endif /*IPSEC*/ 140#define F_TTL 0x8000 141#define F_MISSED 0x10000 142#define F_ONCE 0x20000 143#define F_HDRINCL 0x40000 144#define F_MASK 0x80000 145#define F_TIME 0x100000 146 147/* 148 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum 149 * number of received sequence numbers we can keep track of. Change 128 150 * to 8192 for complete accuracy... 151 */ 152#define MAX_DUP_CHK (8 * 128) 153int mx_dup_ck = MAX_DUP_CHK; 154char rcvd_tbl[MAX_DUP_CHK / 8]; 155 156struct sockaddr_in whereto; /* who to ping */ 157int datalen = DEFDATALEN; 158int maxpayload; 159int s; /* socket file descriptor */ 160u_char outpackhdr[IP_MAXPACKET], *outpack; 161char BBELL = '\a'; /* characters written for MISSED and AUDIBLE */ 162char BSPACE = '\b'; /* characters written for flood */ 163char DOT = '.'; 164char *hostname; 165char *shostname; 166int ident; /* process id to identify our packets */ 167int uid; /* cached uid for micro-optimization */ 168u_char icmp_type = ICMP_ECHO; 169u_char icmp_type_rsp = ICMP_ECHOREPLY; 170int phdr_len = 0; 171int send_len; 172 173/* counters */ 174long nmissedmax; /* max value of ntransmitted - nreceived - 1 */ 175long npackets; /* max packets to transmit */ 176long nreceived; /* # of packets we got back */ 177long nrepeats; /* number of duplicates */ 178long ntransmitted; /* sequence # for outbound packets = #sent */ 179int interval = 1000; /* interval between packets, ms */ 180 181/* timing */ 182int timing; /* flag to do timing */ 183double tmin = 999999999.0; /* minimum round trip time */ 184double tmax = 0.0; /* maximum round trip time */ 185double tsum = 0.0; /* sum of all times, for doing average */ 186double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ 187 188volatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */ 189int reset_kerninfo; 190volatile sig_atomic_t siginfo_p; 191 192static void fill(char *, char *); 193static u_short in_cksum(u_short *, int); 194static void check_status(void); 195static void finish(void) __dead2; 196static void pinger(void); 197static char *pr_addr(struct in_addr); 198static char *pr_ntime(n_time); 199static void pr_icmph(struct icmp *); 200static void pr_iph(struct ip *); 201static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *); 202static void pr_retip(struct ip *); 203static void status(int); 204static void stopit(int); 205static void tvsub(struct timeval *, struct timeval *); 206static void usage(void) __dead2; 207 208int 209main(argc, argv) 210 int argc; 211 char *const *argv; 212{ 213 struct sockaddr_in from, sock_in; 214 struct in_addr ifaddr; 215 struct timeval last, intvl; 216 struct iovec iov; 217 struct ip *ip; 218 struct msghdr msg; 219 struct sigaction si_sa; 220 struct termios ts; 221 size_t sz; 222 u_char *datap, packet[IP_MAXPACKET]; 223 char *ep, *source, *target, *payload; 224 struct hostent *hp; 225#ifdef IPSEC_POLICY_IPSEC 226 char *policy_in, *policy_out; 227#endif 228 struct sockaddr_in *to; 229 double t; 230 u_long alarmtimeout, ultmp; 231 int almost_done, ch, df, hold, i, icmp_len, mib[4], preload, sockerrno, 232 tos, ttl; 233 char ctrl[CMSG_SPACE(sizeof(struct timeval))]; 234 char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN]; 235#ifdef IP_OPTIONS 236 char rspace[MAX_IPOPTLEN]; /* record route space */ 237#endif 238 unsigned char loop, mttl; 239 240 payload = source = NULL; 241#ifdef IPSEC_POLICY_IPSEC 242 policy_in = policy_out = NULL; 243#endif 244 245 /* 246 * Do the stuff that we need root priv's for *first*, and 247 * then drop our setuid bit. Save error reporting for 248 * after arg parsing. 249 */ 250 s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 251 sockerrno = errno; 252 253 setuid(getuid()); 254 uid = getuid(); 255 256 alarmtimeout = df = preload = tos = 0; 257 258 outpack = outpackhdr + sizeof(struct ip); 259 while ((ch = getopt(argc, argv, 260 "Aac:DdfI:i:Ll:M:m:nop:QqRrS:s:T:t:vz:" 261#ifdef IPSEC 262#ifdef IPSEC_POLICY_IPSEC 263 "P:" 264#endif /*IPSEC_POLICY_IPSEC*/ 265#endif /*IPSEC*/ 266 )) != -1) 267 { 268 switch(ch) { 269 case 'A': 270 options |= F_MISSED; 271 break; 272 case 'a': 273 options |= F_AUDIBLE; 274 break; 275 case 'c': 276 ultmp = strtoul(optarg, &ep, 0); 277 if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp) 278 errx(EX_USAGE, 279 "invalid count of packets to transmit: `%s'", 280 optarg); 281 npackets = ultmp; 282 break; 283 case 'D': 284 options |= F_HDRINCL; 285 df = 1; 286 break; 287 case 'd': 288 options |= F_SO_DEBUG; 289 break; 290 case 'f': 291 if (uid) { 292 errno = EPERM; 293 err(EX_NOPERM, "-f flag"); 294 } 295 options |= F_FLOOD; 296 setbuf(stdout, (char *)NULL); 297 break; 298 case 'I': /* multicast interface */ 299 if (inet_aton(optarg, &ifaddr) == 0) 300 errx(EX_USAGE, 301 "invalid multicast interface: `%s'", 302 optarg); 303 options |= F_MIF; 304 break; 305 case 'i': /* wait between sending packets */ 306 t = strtod(optarg, &ep) * 1000.0; 307 if (*ep || ep == optarg || t > (double)INT_MAX) 308 errx(EX_USAGE, "invalid timing interval: `%s'", 309 optarg); 310 options |= F_INTERVAL; 311 interval = (int)t; 312 if (uid && interval < 1000) { 313 errno = EPERM; 314 err(EX_NOPERM, "-i interval too short"); 315 } 316 break; 317 case 'L': 318 options |= F_NOLOOP; 319 loop = 0; 320 break; 321 case 'l': 322 ultmp = strtoul(optarg, &ep, 0); 323 if (*ep || ep == optarg || ultmp > INT_MAX) 324 errx(EX_USAGE, 325 "invalid preload value: `%s'", optarg); 326 if (uid) { 327 errno = EPERM; 328 err(EX_NOPERM, "-l flag"); 329 } 330 preload = ultmp; 331 break; 332 case 'M': 333 switch(optarg[0]) { 334 case 'M': 335 case 'm': 336 options |= F_MASK; 337 break; 338 case 'T': 339 case 't': 340 options |= F_TIME; 341 break; 342 default: 343 errx(EX_USAGE, "invalid message: `%c'", optarg[0]); 344 break; 345 } 346 break; 347 case 'm': /* TTL */ 348 ultmp = strtoul(optarg, &ep, 0); 349 if (*ep || ep == optarg || ultmp > MAXTTL) 350 errx(EX_USAGE, "invalid TTL: `%s'", optarg); 351 ttl = ultmp; 352 options |= F_TTL; 353 break; 354 case 'n': 355 options |= F_NUMERIC; 356 break; 357 case 'o': 358 options |= F_ONCE; 359 break; 360#ifdef IPSEC 361#ifdef IPSEC_POLICY_IPSEC 362 case 'P': 363 options |= F_POLICY; 364 if (!strncmp("in", optarg, 2)) 365 policy_in = strdup(optarg); 366 else if (!strncmp("out", optarg, 3)) 367 policy_out = strdup(optarg); 368 else 369 errx(1, "invalid security policy"); 370 break; 371#endif /*IPSEC_POLICY_IPSEC*/ 372#endif /*IPSEC*/ 373 case 'p': /* fill buffer with user pattern */ 374 options |= F_PINGFILLED; 375 payload = optarg; 376 break; 377 case 'Q': 378 options |= F_QUIET2; 379 break; 380 case 'q': 381 options |= F_QUIET; 382 break; 383 case 'R': 384 options |= F_RROUTE; 385 break; 386 case 'r': 387 options |= F_SO_DONTROUTE; 388 break; 389 case 'S': 390 source = optarg; 391 break; 392 case 's': /* size of packet to send */ 393 ultmp = strtoul(optarg, &ep, 0); 394 if (*ep || ep == optarg) 395 errx(EX_USAGE, "invalid packet size: `%s'", 396 optarg); 397 if (uid != 0 && ultmp > DEFDATALEN) { 398 errno = EPERM; 399 err(EX_NOPERM, 400 "packet size too large: %lu > %u", 401 ultmp, DEFDATALEN); 402 } 403 datalen = ultmp; 404 break; 405 case 'T': /* multicast TTL */ 406 ultmp = strtoul(optarg, &ep, 0); 407 if (*ep || ep == optarg || ultmp > MAXTTL) 408 errx(EX_USAGE, "invalid multicast TTL: `%s'", 409 optarg); 410 mttl = ultmp; 411 options |= F_MTTL; 412 break; 413 case 't': 414 alarmtimeout = strtoul(optarg, &ep, 0); 415 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX)) 416 errx(EX_USAGE, "invalid timeout: `%s'", 417 optarg); 418 if (alarmtimeout > MAXALARM) 419 errx(EX_USAGE, "invalid timeout: `%s' > %d", 420 optarg, MAXALARM); 421 alarm((int)alarmtimeout); 422 break; 423 case 'v': 424 options |= F_VERBOSE; 425 break; 426 case 'z': 427 options |= F_HDRINCL; 428 ultmp = strtoul(optarg, &ep, 0); 429 if (*ep || ep == optarg || ultmp > MAXTOS) 430 errx(EX_USAGE, "invalid TOS: `%s'", optarg); 431 tos = ultmp; 432 break; 433 default: 434 usage(); 435 } 436 } 437 438 if (argc - optind != 1) 439 usage(); 440 target = argv[optind]; 441 442 switch (options & (F_MASK|F_TIME)) { 443 case 0: break; 444 case F_MASK: 445 icmp_type = ICMP_MASKREQ; 446 icmp_type_rsp = ICMP_MASKREPLY; 447 phdr_len = MASK_LEN; 448 if (!(options & F_QUIET)) 449 (void)printf("ICMP_MASKREQ\n"); 450 break; 451 case F_TIME: 452 icmp_type = ICMP_TSTAMP; 453 icmp_type_rsp = ICMP_TSTAMPREPLY; 454 phdr_len = TS_LEN; 455 if (!(options & F_QUIET)) 456 (void)printf("ICMP_TSTAMP\n"); 457 break; 458 default: 459 errx(EX_USAGE, "ICMP_TSTAMP and ICMP_MASKREQ are exclusive."); 460 break; 461 } 462 icmp_len = sizeof(struct ip) + MINICMPLEN + phdr_len; 463 if (options & F_RROUTE) 464 icmp_len += MAX_IPOPTLEN; 465 maxpayload = IP_MAXPACKET - icmp_len; 466 if (datalen > maxpayload) 467 errx(EX_USAGE, "packet size too large: %d > %d", datalen, 468 maxpayload); 469 send_len = icmp_len + datalen; 470 datap = &outpack[MINICMPLEN + phdr_len + TIMEVAL_LEN]; 471 if (options & F_PINGFILLED) { 472 fill((char *)datap, payload); 473 } 474 if (source) { 475 bzero((char *)&sock_in, sizeof(sock_in)); 476 sock_in.sin_family = AF_INET; 477 if (inet_aton(source, &sock_in.sin_addr) != 0) { 478 shostname = source; 479 } else { 480 hp = gethostbyname2(source, AF_INET); 481 if (!hp) 482 errx(EX_NOHOST, "cannot resolve %s: %s", 483 source, hstrerror(h_errno)); 484 485 sock_in.sin_len = sizeof sock_in; 486 if ((unsigned)hp->h_length > sizeof(sock_in.sin_addr) || 487 hp->h_length < 0) 488 errx(1, "gethostbyname2: illegal address"); 489 memcpy(&sock_in.sin_addr, hp->h_addr_list[0], 490 sizeof(sock_in.sin_addr)); 491 (void)strncpy(snamebuf, hp->h_name, 492 sizeof(snamebuf) - 1); 493 snamebuf[sizeof(snamebuf) - 1] = '\0'; 494 shostname = snamebuf; 495 } 496 if (bind(s, (struct sockaddr *)&sock_in, sizeof sock_in) == -1) 497 err(1, "bind"); 498 } 499 500 bzero(&whereto, sizeof(whereto)); 501 to = &whereto; 502 to->sin_family = AF_INET; 503 to->sin_len = sizeof *to; 504 if (inet_aton(target, &to->sin_addr) != 0) { 505 hostname = target; 506 } else { 507 hp = gethostbyname2(target, AF_INET); 508 if (!hp) 509 errx(EX_NOHOST, "cannot resolve %s: %s", 510 target, hstrerror(h_errno)); 511 512 if ((unsigned)hp->h_length > sizeof(to->sin_addr)) 513 errx(1, "gethostbyname2 returned an illegal address"); 514 memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 515 (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 516 hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 517 hostname = hnamebuf; 518 } 519 520 if (options & F_FLOOD && options & F_INTERVAL) 521 errx(EX_USAGE, "-f and -i: incompatible options"); 522 523 if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 524 errx(EX_USAGE, 525 "-f flag cannot be used with multicast destination"); 526 if (options & (F_MIF | F_NOLOOP | F_MTTL) 527 && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 528 errx(EX_USAGE, 529 "-I, -L, -T flags cannot be used with unicast destination"); 530 531 if (datalen >= TIMEVAL_LEN) /* can we time transfer */ 532 timing = 1; 533 534 if (!(options & F_PINGFILLED)) 535 for (i = TIMEVAL_LEN; i < datalen; ++i) 536 *datap++ = i; 537 538 ident = getpid() & 0xFFFF; 539 540 if (s < 0) { 541 errno = sockerrno; 542 err(EX_OSERR, "socket"); 543 } 544 hold = 1; 545 if (options & F_SO_DEBUG) 546 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold, 547 sizeof(hold)); 548 if (options & F_SO_DONTROUTE) 549 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, 550 sizeof(hold)); 551#ifdef IPSEC 552#ifdef IPSEC_POLICY_IPSEC 553 if (options & F_POLICY) { 554 char *buf; 555 if (policy_in != NULL) { 556 buf = ipsec_set_policy(policy_in, strlen(policy_in)); 557 if (buf == NULL) 558 errx(EX_CONFIG, "%s", ipsec_strerror()); 559 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 560 buf, ipsec_get_policylen(buf)) < 0) 561 err(EX_CONFIG, 562 "ipsec policy cannot be configured"); 563 free(buf); 564 } 565 566 if (policy_out != NULL) { 567 buf = ipsec_set_policy(policy_out, strlen(policy_out)); 568 if (buf == NULL) 569 errx(EX_CONFIG, "%s", ipsec_strerror()); 570 if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 571 buf, ipsec_get_policylen(buf)) < 0) 572 err(EX_CONFIG, 573 "ipsec policy cannot be configured"); 574 free(buf); 575 } 576 } 577#endif /*IPSEC_POLICY_IPSEC*/ 578#endif /*IPSEC*/ 579 580 if (options & F_HDRINCL) { 581 ip = (struct ip*)outpackhdr; 582 if (!(options & (F_TTL | F_MTTL))) { 583 mib[0] = CTL_NET; 584 mib[1] = PF_INET; 585 mib[2] = IPPROTO_IP; 586 mib[3] = IPCTL_DEFTTL; 587 sz = sizeof(ttl); 588 if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1) 589 err(1, "sysctl(net.inet.ip.ttl)"); 590 } 591 setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold)); 592 ip->ip_v = IPVERSION; 593 ip->ip_hl = sizeof(struct ip) >> 2; 594 ip->ip_tos = tos; 595 ip->ip_id = 0; 596 ip->ip_off = df ? IP_DF : 0; 597 ip->ip_ttl = ttl; 598 ip->ip_p = IPPROTO_ICMP; 599 ip->ip_src.s_addr = source ? sock_in.sin_addr.s_addr : INADDR_ANY; 600 ip->ip_dst = to->sin_addr; 601 } 602 /* record route option */ 603 if (options & F_RROUTE) { 604#ifdef IP_OPTIONS 605 bzero(rspace, sizeof(rspace)); 606 rspace[IPOPT_OPTVAL] = IPOPT_RR; 607 rspace[IPOPT_OLEN] = sizeof(rspace) - 1; 608 rspace[IPOPT_OFFSET] = IPOPT_MINOFF; 609 rspace[sizeof(rspace) - 1] = IPOPT_EOL; 610 if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace, 611 sizeof(rspace)) < 0) 612 err(EX_OSERR, "setsockopt IP_OPTIONS"); 613#else 614 errx(EX_UNAVAILABLE, 615 "record route not available in this implementation"); 616#endif /* IP_OPTIONS */ 617 } 618 619 if (options & F_TTL) { 620 if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl, 621 sizeof(ttl)) < 0) { 622 err(EX_OSERR, "setsockopt IP_TTL"); 623 } 624 } 625 if (options & F_NOLOOP) { 626 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, 627 sizeof(loop)) < 0) { 628 err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP"); 629 } 630 } 631 if (options & F_MTTL) { 632 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, 633 sizeof(mttl)) < 0) { 634 err(EX_OSERR, "setsockopt IP_MULTICAST_TTL"); 635 } 636 } 637 if (options & F_MIF) { 638 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, 639 sizeof(ifaddr)) < 0) { 640 err(EX_OSERR, "setsockopt IP_MULTICAST_IF"); 641 } 642 } 643#ifdef SO_TIMESTAMP 644 { int on = 1; 645 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0) 646 err(EX_OSERR, "setsockopt SO_TIMESTAMP"); 647 } 648#endif 649 650 /* 651 * When pinging the broadcast address, you can get a lot of answers. 652 * Doing something so evil is useful if you are trying to stress the 653 * ethernet, or just want to fill the arp cache to get some stuff for 654 * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast 655 * or multicast pings if they wish. 656 */ 657 658 /* 659 * XXX receive buffer needs undetermined space for mbuf overhead 660 * as well. 661 */ 662 hold = IP_MAXPACKET + 128; 663 (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold, 664 sizeof(hold)); 665 if (uid == 0) 666 (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold, 667 sizeof(hold)); 668 669 if (to->sin_family == AF_INET) { 670 (void)printf("PING %s (%s)", hostname, 671 inet_ntoa(to->sin_addr)); 672 if (source) 673 (void)printf(" from %s", shostname); 674 (void)printf(": %d data bytes\n", datalen); 675 } else 676 (void)printf("PING %s: %d data bytes\n", hostname, datalen); 677 678 /* 679 * Use sigaction() instead of signal() to get unambiguous semantics, 680 * in particular with SA_RESTART not set. 681 */ 682 683 sigemptyset(&si_sa.sa_mask); 684 si_sa.sa_flags = 0; 685 686 si_sa.sa_handler = stopit; 687 if (sigaction(SIGINT, &si_sa, 0) == -1) { 688 err(EX_OSERR, "sigaction SIGINT"); 689 } 690 691 si_sa.sa_handler = status; 692 if (sigaction(SIGINFO, &si_sa, 0) == -1) { 693 err(EX_OSERR, "sigaction"); 694 } 695 696 if (alarmtimeout > 0) { 697 si_sa.sa_handler = stopit; 698 if (sigaction(SIGALRM, &si_sa, 0) == -1) 699 err(EX_OSERR, "sigaction SIGALRM"); 700 } 701 702 bzero(&msg, sizeof(msg)); 703 msg.msg_name = (caddr_t)&from; 704 msg.msg_iov = &iov; 705 msg.msg_iovlen = 1; 706#ifdef SO_TIMESTAMP 707 msg.msg_control = (caddr_t)ctrl; 708#endif 709 iov.iov_base = packet; 710 iov.iov_len = IP_MAXPACKET; 711 712 if (tcgetattr(STDOUT_FILENO, &ts) != -1) { 713 reset_kerninfo = !(ts.c_lflag & NOKERNINFO); 714 ts.c_lflag |= NOKERNINFO; 715 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 716 } 717 718 if (preload == 0) 719 pinger(); /* send the first ping */ 720 else { 721 if (npackets != 0 && preload > npackets) 722 preload = npackets; 723 while (preload--) /* fire off them quickies */ 724 pinger(); 725 } 726 (void)gettimeofday(&last, NULL); 727 728 if (options & F_FLOOD) { 729 intvl.tv_sec = 0; 730 intvl.tv_usec = 10000; 731 } else { 732 intvl.tv_sec = interval / 1000; 733 intvl.tv_usec = interval % 1000 * 1000; 734 } 735 736 almost_done = 0; 737 while (!finish_up) { 738 struct timeval now, timeout; 739 fd_set rfds; 740 int cc, n; 741 742 check_status(); 743 if ((unsigned)s >= FD_SETSIZE) 744 errx(EX_OSERR, "descriptor too large"); 745 FD_ZERO(&rfds); 746 FD_SET(s, &rfds); 747 (void)gettimeofday(&now, NULL); 748 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec; 749 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec; 750 while (timeout.tv_usec < 0) { 751 timeout.tv_usec += 1000000; 752 timeout.tv_sec--; 753 } 754 while (timeout.tv_usec >= 1000000) { 755 timeout.tv_usec -= 1000000; 756 timeout.tv_sec++; 757 } 758 if (timeout.tv_sec < 0) 759 timeout.tv_sec = timeout.tv_usec = 0; 760 n = select(s + 1, &rfds, NULL, NULL, &timeout); 761 if (n < 0) 762 continue; /* Must be EINTR. */ 763 if (n == 1) { 764 struct timeval *tv = NULL; 765#ifdef SO_TIMESTAMP 766 struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl; 767 768 msg.msg_controllen = sizeof(ctrl); 769#endif 770 msg.msg_namelen = sizeof(from); 771 if ((cc = recvmsg(s, &msg, 0)) < 0) { 772 if (errno == EINTR) 773 continue; 774 warn("recvmsg"); 775 continue; 776 } 777#ifdef SO_TIMESTAMP 778 if (cmsg->cmsg_level == SOL_SOCKET && 779 cmsg->cmsg_type == SCM_TIMESTAMP && 780 cmsg->cmsg_len == CMSG_LEN(sizeof *tv)) { 781 /* Copy to avoid alignment problems: */ 782 memcpy(&now, CMSG_DATA(cmsg), sizeof(now)); 783 tv = &now; 784 } 785#endif 786 if (tv == NULL) { 787 (void)gettimeofday(&now, NULL); 788 tv = &now; 789 } 790 pr_pack((char *)packet, cc, &from, tv); 791 if ((options & F_ONCE && nreceived) || 792 (npackets && nreceived >= npackets)) 793 break; 794 } 795 if (n == 0 || options & F_FLOOD) { 796 if (!npackets || ntransmitted < npackets) 797 pinger(); 798 else { 799 if (almost_done) 800 break; 801 almost_done = 1; 802 intvl.tv_usec = 0; 803 if (nreceived) { 804 intvl.tv_sec = 2 * tmax / 1000; 805 if (!intvl.tv_sec) 806 intvl.tv_sec = 1; 807 } else 808 intvl.tv_sec = MAXWAIT; 809 } 810 (void)gettimeofday(&last, NULL); 811 if (ntransmitted - nreceived - 1 > nmissedmax) { 812 nmissedmax = ntransmitted - nreceived - 1; 813 if (options & F_MISSED) 814 (void)write(STDOUT_FILENO, &BBELL, 1); 815 } 816 } 817 } 818 finish(); 819 /* NOTREACHED */ 820 exit(0); /* Make the compiler happy */ 821} 822 823/* 824 * stopit -- 825 * Set the global bit that causes the main loop to quit. 826 * Do NOT call finish() from here, since finish() does far too much 827 * to be called from a signal handler. 828 */ 829void 830stopit(sig) 831 int sig __unused; 832{ 833 834 finish_up = 1; 835} 836 837/* 838 * pinger -- 839 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 840 * will be added on by the kernel. The ID field is our UNIX process ID, 841 * and the sequence number is an ascending integer. The first TIMEVAL_LEN 842 * bytes of the data portion are used to hold a UNIX "timeval" struct in 843 * host byte-order, to compute the round-trip time. 844 */ 845static void 846pinger(void) 847{ 848 struct timeval now; 849 struct ip *ip; 850 struct icmp *icp; 851 int cc, i; 852 u_char *packet; 853 854 packet = outpack; 855 icp = (struct icmp *)outpack; 856 icp->icmp_type = icmp_type; 857 icp->icmp_code = 0; 858 icp->icmp_cksum = 0; 859 icp->icmp_seq = htons(ntransmitted); 860 icp->icmp_id = ident; /* ID */ 861 862 CLR(ntransmitted % mx_dup_ck); 863 864 if ((options & F_TIME) || timing) { 865 (void)gettimeofday(&now, NULL); 866 867 if (options & F_TIME) 868 icp->icmp_otime = htonl((now.tv_sec % (24*60*60)) 869 * 1000 + now.tv_usec / 1000); 870 if (timing) 871 bcopy((void *)&now, 872 (void *)&outpack[MINICMPLEN + phdr_len], 873 sizeof(struct timeval)); 874 } 875 876 cc = MINICMPLEN + phdr_len + datalen; 877 878 /* compute ICMP checksum here */ 879 icp->icmp_cksum = in_cksum((u_short *)icp, cc); 880 881 if (options & F_HDRINCL) { 882 cc += sizeof(struct ip); 883 ip = (struct ip *)outpackhdr; 884 ip->ip_len = cc; 885 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc); 886 packet = outpackhdr; 887 } 888 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto, 889 sizeof(whereto)); 890 891 if (i < 0 || i != cc) { 892 if (i < 0) { 893 if (options & F_FLOOD && errno == ENOBUFS) { 894 usleep(FLOOD_BACKOFF); 895 return; 896 } 897 warn("sendto"); 898 } else { 899 warn("%s: partial write: %d of %d bytes", 900 hostname, i, cc); 901 } 902 } 903 ntransmitted++; 904 if (!(options & F_QUIET) && options & F_FLOOD) 905 (void)write(STDOUT_FILENO, &DOT, 1); 906} 907 908/* 909 * pr_pack -- 910 * Print out the packet, if it came from us. This logic is necessary 911 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 912 * which arrive ('tis only fair). This permits multiple copies of this 913 * program to be run without having intermingled output (or statistics!). 914 */ 915static void 916pr_pack(buf, cc, from, tv) 917 char *buf; 918 int cc; 919 struct sockaddr_in *from; 920 struct timeval *tv; 921{ 922 struct in_addr ina; 923 u_char *cp, *dp; 924 struct icmp *icp; 925 struct ip *ip; 926 const void *tp; 927 double triptime; 928 int dupflag, hlen, i, j, recv_len, seq; 929 static int old_rrlen; 930 static char old_rr[MAX_IPOPTLEN]; 931 932 /* Check the IP header */ 933 ip = (struct ip *)buf; 934 hlen = ip->ip_hl << 2; 935 recv_len = cc; 936 if (cc < hlen + ICMP_MINLEN) { 937 if (options & F_VERBOSE) 938 warn("packet too short (%d bytes) from %s", cc, 939 inet_ntoa(from->sin_addr)); 940 return; 941 } 942 943 /* Now the ICMP part */ 944 cc -= hlen; 945 icp = (struct icmp *)(buf + hlen); 946 if (icp->icmp_type == icmp_type_rsp) { 947 if (icp->icmp_id != ident) 948 return; /* 'Twas not our ECHO */ 949 ++nreceived; 950 triptime = 0.0; 951 if (timing) { 952 struct timeval tv1; 953#ifndef icmp_data 954 tp = &icp->icmp_ip; 955#else 956 tp = icp->icmp_data; 957#endif 958 tp += phdr_len; 959 960 if (cc - ICMP_MINLEN - phdr_len >= sizeof(tv1)) { 961 /* Copy to avoid alignment problems: */ 962 memcpy(&tv1, tp, sizeof(tv1)); 963 tvsub(tv, &tv1); 964 triptime = ((double)tv->tv_sec) * 1000.0 + 965 ((double)tv->tv_usec) / 1000.0; 966 tsum += triptime; 967 tsumsq += triptime * triptime; 968 if (triptime < tmin) 969 tmin = triptime; 970 if (triptime > tmax) 971 tmax = triptime; 972 } else 973 timing = 0; 974 } 975 976 seq = ntohs(icp->icmp_seq); 977 978 if (TST(seq % mx_dup_ck)) { 979 ++nrepeats; 980 --nreceived; 981 dupflag = 1; 982 } else { 983 SET(seq % mx_dup_ck); 984 dupflag = 0; 985 } 986 987 if (options & F_QUIET) 988 return; 989 990 if (options & F_FLOOD) 991 (void)write(STDOUT_FILENO, &BSPACE, 1); 992 else { 993 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 994 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 995 seq); 996 (void)printf(" ttl=%d", ip->ip_ttl); 997 if (timing) 998 (void)printf(" time=%.3f ms", triptime); 999 if (dupflag) 1000 (void)printf(" (DUP!)"); 1001 if (options & F_AUDIBLE) 1002 (void)write(STDOUT_FILENO, &BBELL, 1); 1003 if (options & F_MASK) { 1004 /* Just prentend this cast isn't ugly */ 1005 (void)printf(" mask=%s", 1006 pr_addr(*(struct in_addr *)&(icp->icmp_mask))); 1007 } 1008 if (options & F_TIME) { 1009 (void)printf(" tso=%s", pr_ntime(icp->icmp_otime)); 1010 (void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime)); 1011 (void)printf(" tst=%s", pr_ntime(icp->icmp_ttime)); 1012 } 1013 if (recv_len != send_len) { 1014 (void)printf( 1015 "\nwrong total length %d instead of %d", 1016 recv_len, send_len); 1017 } 1018 /* check the data */ 1019 cp = (u_char*)&icp->icmp_data[phdr_len]; 1020 dp = &outpack[MINICMPLEN + phdr_len]; 1021 cc -= ICMP_MINLEN + phdr_len; 1022 i = 0; 1023 if (timing) { /* don't check variable timestamp */ 1024 cp += TIMEVAL_LEN; 1025 dp += TIMEVAL_LEN; 1026 cc -= TIMEVAL_LEN; 1027 i += TIMEVAL_LEN; 1028 } 1029 for (; i < datalen && cc > 0; ++i, ++cp, ++dp, --cc) { 1030 if (*cp != *dp) { 1031 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 1032 i, *dp, *cp); 1033 (void)printf("\ncp:"); 1034 cp = (u_char*)&icp->icmp_data[0]; 1035 for (i = 0; i < datalen; ++i, ++cp) { 1036 if ((i % 16) == 8) 1037 (void)printf("\n\t"); 1038 (void)printf("%2x ", *cp); 1039 } 1040 (void)printf("\ndp:"); 1041 cp = &outpack[MINICMPLEN]; 1042 for (i = 0; i < datalen; ++i, ++cp) { 1043 if ((i % 16) == 8) 1044 (void)printf("\n\t"); 1045 (void)printf("%2x ", *cp); 1046 } 1047 break; 1048 } 1049 } 1050 } 1051 } else { 1052 /* 1053 * We've got something other than an ECHOREPLY. 1054 * See if it's a reply to something that we sent. 1055 * We can compare IP destination, protocol, 1056 * and ICMP type and ID. 1057 * 1058 * Only print all the error messages if we are running 1059 * as root to avoid leaking information not normally 1060 * available to those not running as root. 1061 */ 1062#ifndef icmp_data 1063 struct ip *oip = &icp->icmp_ip; 1064#else 1065 struct ip *oip = (struct ip *)icp->icmp_data; 1066#endif 1067 struct icmp *oicmp = (struct icmp *)(oip + 1); 1068 1069 if (((options & F_VERBOSE) && uid == 0) || 1070 (!(options & F_QUIET2) && 1071 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) && 1072 (oip->ip_p == IPPROTO_ICMP) && 1073 (oicmp->icmp_type == ICMP_ECHO) && 1074 (oicmp->icmp_id == ident))) { 1075 (void)printf("%d bytes from %s: ", cc, 1076 pr_addr(from->sin_addr)); 1077 pr_icmph(icp); 1078 } else 1079 return; 1080 } 1081 1082 /* Display any IP options */ 1083 cp = (u_char *)buf + sizeof(struct ip); 1084 1085 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 1086 switch (*cp) { 1087 case IPOPT_EOL: 1088 hlen = 0; 1089 break; 1090 case IPOPT_LSRR: 1091 case IPOPT_SSRR: 1092 (void)printf(*cp == IPOPT_LSRR ? 1093 "\nLSRR: " : "\nSSRR: "); 1094 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1; 1095 hlen -= 2; 1096 cp += 2; 1097 if (j >= INADDR_LEN && 1098 j <= hlen - (int)sizeof(struct ip)) { 1099 for (;;) { 1100 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1101 if (ina.s_addr == 0) 1102 (void)printf("\t0.0.0.0"); 1103 else 1104 (void)printf("\t%s", 1105 pr_addr(ina)); 1106 hlen -= INADDR_LEN; 1107 cp += INADDR_LEN - 1; 1108 j -= INADDR_LEN; 1109 if (j < INADDR_LEN) 1110 break; 1111 (void)putchar('\n'); 1112 } 1113 } else 1114 (void)printf("\t(truncated route)\n"); 1115 break; 1116 case IPOPT_RR: 1117 j = cp[IPOPT_OLEN]; /* get length */ 1118 i = cp[IPOPT_OFFSET]; /* and pointer */ 1119 hlen -= 2; 1120 cp += 2; 1121 if (i > j) 1122 i = j; 1123 i = i - IPOPT_MINOFF + 1; 1124 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) { 1125 old_rrlen = 0; 1126 continue; 1127 } 1128 if (i == old_rrlen 1129 && !bcmp((char *)cp, old_rr, i) 1130 && !(options & F_FLOOD)) { 1131 (void)printf("\t(same route)"); 1132 hlen -= i; 1133 cp += i; 1134 break; 1135 } 1136 old_rrlen = i; 1137 bcopy((char *)cp, old_rr, i); 1138 (void)printf("\nRR: "); 1139 if (i >= INADDR_LEN && 1140 i <= hlen - (int)sizeof(struct ip)) { 1141 for (;;) { 1142 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1143 if (ina.s_addr == 0) 1144 (void)printf("\t0.0.0.0"); 1145 else 1146 (void)printf("\t%s", 1147 pr_addr(ina)); 1148 hlen -= INADDR_LEN; 1149 cp += INADDR_LEN - 1; 1150 i -= INADDR_LEN; 1151 if (i < INADDR_LEN) 1152 break; 1153 (void)putchar('\n'); 1154 } 1155 } else 1156 (void)printf("\t(truncated route)"); 1157 break; 1158 case IPOPT_NOP: 1159 (void)printf("\nNOP"); 1160 break; 1161 default: 1162 (void)printf("\nunknown option %x", *cp); 1163 break; 1164 } 1165 if (!(options & F_FLOOD)) { 1166 (void)putchar('\n'); 1167 (void)fflush(stdout); 1168 } 1169} 1170 1171/* 1172 * in_cksum -- 1173 * Checksum routine for Internet Protocol family headers (C Version) 1174 */ 1175u_short 1176in_cksum(addr, len) 1177 u_short *addr; 1178 int len; 1179{ 1180 int nleft, sum; 1181 u_short *w; 1182 union { 1183 u_short us; 1184 u_char uc[2]; 1185 } last; 1186 u_short answer; 1187 1188 nleft = len; 1189 sum = 0; 1190 w = addr; 1191 1192 /* 1193 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 1194 * sequential 16 bit words to it, and at the end, fold back all the 1195 * carry bits from the top 16 bits into the lower 16 bits. 1196 */ 1197 while (nleft > 1) { 1198 sum += *w++; 1199 nleft -= 2; 1200 } 1201 1202 /* mop up an odd byte, if necessary */ 1203 if (nleft == 1) { 1204 last.uc[0] = *(u_char *)w; 1205 last.uc[1] = 0; 1206 sum += last.us; 1207 } 1208 1209 /* add back carry outs from top 16 bits to low 16 bits */ 1210 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 1211 sum += (sum >> 16); /* add carry */ 1212 answer = ~sum; /* truncate to 16 bits */ 1213 return(answer); 1214} 1215 1216/* 1217 * tvsub -- 1218 * Subtract 2 timeval structs: out = out - in. Out is assumed to 1219 * be >= in. 1220 */ 1221static void 1222tvsub(out, in) 1223 struct timeval *out, *in; 1224{ 1225 1226 if ((out->tv_usec -= in->tv_usec) < 0) { 1227 --out->tv_sec; 1228 out->tv_usec += 1000000; 1229 } 1230 out->tv_sec -= in->tv_sec; 1231} 1232 1233/* 1234 * status -- 1235 * Print out statistics when SIGINFO is received. 1236 */ 1237 1238static void 1239status(sig) 1240 int sig __unused; 1241{ 1242 1243 siginfo_p = 1; 1244} 1245 1246static void 1247check_status() 1248{ 1249 1250 if (siginfo_p) { 1251 siginfo_p = 0; 1252 (void)fprintf(stderr, "\r%ld/%ld packets received (%.0f%%)", 1253 nreceived, ntransmitted, 1254 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0); 1255 if (nreceived && timing) 1256 (void)fprintf(stderr, " %.3f min / %.3f avg / %.3f max", 1257 tmin, tsum / (nreceived + nrepeats), tmax); 1258 (void)fprintf(stderr, "\n"); 1259 } 1260} 1261 1262/* 1263 * finish -- 1264 * Print out statistics, and give up. 1265 */ 1266static void 1267finish() 1268{ 1269 struct termios ts; 1270 1271 (void)signal(SIGINT, SIG_IGN); 1272 (void)signal(SIGALRM, SIG_IGN); 1273 (void)putchar('\n'); 1274 (void)fflush(stdout); 1275 (void)printf("--- %s ping statistics ---\n", hostname); 1276 (void)printf("%ld packets transmitted, ", ntransmitted); 1277 (void)printf("%ld packets received, ", nreceived); 1278 if (nrepeats) 1279 (void)printf("+%ld duplicates, ", nrepeats); 1280 if (ntransmitted) { 1281 if (nreceived > ntransmitted) 1282 (void)printf("-- somebody's printing up packets!"); 1283 else 1284 (void)printf("%d%% packet loss", 1285 (int)(((ntransmitted - nreceived) * 100) / 1286 ntransmitted)); 1287 } 1288 (void)putchar('\n'); 1289 if (nreceived && timing) { 1290 double n = nreceived + nrepeats; 1291 double avg = tsum / n; 1292 double vari = tsumsq / n - avg * avg; 1293 (void)printf( 1294 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n", 1295 tmin, avg, tmax, sqrt(vari)); 1296 } 1297 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 1298 ts.c_lflag &= ~NOKERNINFO; 1299 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 1300 } 1301 1302 if (nreceived) 1303 exit(0); 1304 else 1305 exit(2); 1306} 1307 1308#ifdef notdef 1309static char *ttab[] = { 1310 "Echo Reply", /* ip + seq + udata */ 1311 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1312 "Source Quench", /* IP */ 1313 "Redirect", /* redirect type, gateway, + IP */ 1314 "Echo", 1315 "Time Exceeded", /* transit, frag reassem + IP */ 1316 "Parameter Problem", /* pointer + IP */ 1317 "Timestamp", /* id + seq + three timestamps */ 1318 "Timestamp Reply", /* " */ 1319 "Info Request", /* id + sq */ 1320 "Info Reply" /* " */ 1321}; 1322#endif 1323 1324/* 1325 * pr_icmph -- 1326 * Print a descriptive string about an ICMP header. 1327 */ 1328static void 1329pr_icmph(icp) 1330 struct icmp *icp; 1331{ 1332 1333 switch(icp->icmp_type) { 1334 case ICMP_ECHOREPLY: 1335 (void)printf("Echo Reply\n"); 1336 /* XXX ID + Seq + Data */ 1337 break; 1338 case ICMP_UNREACH: 1339 switch(icp->icmp_code) { 1340 case ICMP_UNREACH_NET: 1341 (void)printf("Destination Net Unreachable\n"); 1342 break; 1343 case ICMP_UNREACH_HOST: 1344 (void)printf("Destination Host Unreachable\n"); 1345 break; 1346 case ICMP_UNREACH_PROTOCOL: 1347 (void)printf("Destination Protocol Unreachable\n"); 1348 break; 1349 case ICMP_UNREACH_PORT: 1350 (void)printf("Destination Port Unreachable\n"); 1351 break; 1352 case ICMP_UNREACH_NEEDFRAG: 1353 (void)printf("frag needed and DF set (MTU %d)\n", 1354 ntohs(icp->icmp_nextmtu)); 1355 break; 1356 case ICMP_UNREACH_SRCFAIL: 1357 (void)printf("Source Route Failed\n"); 1358 break; 1359 case ICMP_UNREACH_FILTER_PROHIB: 1360 (void)printf("Communication prohibited by filter\n"); 1361 break; 1362 default: 1363 (void)printf("Dest Unreachable, Bad Code: %d\n", 1364 icp->icmp_code); 1365 break; 1366 } 1367 /* Print returned IP header information */ 1368#ifndef icmp_data 1369 pr_retip(&icp->icmp_ip); 1370#else 1371 pr_retip((struct ip *)icp->icmp_data); 1372#endif 1373 break; 1374 case ICMP_SOURCEQUENCH: 1375 (void)printf("Source Quench\n"); 1376#ifndef icmp_data 1377 pr_retip(&icp->icmp_ip); 1378#else 1379 pr_retip((struct ip *)icp->icmp_data); 1380#endif 1381 break; 1382 case ICMP_REDIRECT: 1383 switch(icp->icmp_code) { 1384 case ICMP_REDIRECT_NET: 1385 (void)printf("Redirect Network"); 1386 break; 1387 case ICMP_REDIRECT_HOST: 1388 (void)printf("Redirect Host"); 1389 break; 1390 case ICMP_REDIRECT_TOSNET: 1391 (void)printf("Redirect Type of Service and Network"); 1392 break; 1393 case ICMP_REDIRECT_TOSHOST: 1394 (void)printf("Redirect Type of Service and Host"); 1395 break; 1396 default: 1397 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1398 break; 1399 } 1400 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1401#ifndef icmp_data 1402 pr_retip(&icp->icmp_ip); 1403#else 1404 pr_retip((struct ip *)icp->icmp_data); 1405#endif 1406 break; 1407 case ICMP_ECHO: 1408 (void)printf("Echo Request\n"); 1409 /* XXX ID + Seq + Data */ 1410 break; 1411 case ICMP_TIMXCEED: 1412 switch(icp->icmp_code) { 1413 case ICMP_TIMXCEED_INTRANS: 1414 (void)printf("Time to live exceeded\n"); 1415 break; 1416 case ICMP_TIMXCEED_REASS: 1417 (void)printf("Frag reassembly time exceeded\n"); 1418 break; 1419 default: 1420 (void)printf("Time exceeded, Bad Code: %d\n", 1421 icp->icmp_code); 1422 break; 1423 } 1424#ifndef icmp_data 1425 pr_retip(&icp->icmp_ip); 1426#else 1427 pr_retip((struct ip *)icp->icmp_data); 1428#endif 1429 break; 1430 case ICMP_PARAMPROB: 1431 (void)printf("Parameter problem: pointer = 0x%02x\n", 1432 icp->icmp_hun.ih_pptr); 1433#ifndef icmp_data 1434 pr_retip(&icp->icmp_ip); 1435#else 1436 pr_retip((struct ip *)icp->icmp_data); 1437#endif 1438 break; 1439 case ICMP_TSTAMP: 1440 (void)printf("Timestamp\n"); 1441 /* XXX ID + Seq + 3 timestamps */ 1442 break; 1443 case ICMP_TSTAMPREPLY: 1444 (void)printf("Timestamp Reply\n"); 1445 /* XXX ID + Seq + 3 timestamps */ 1446 break; 1447 case ICMP_IREQ: 1448 (void)printf("Information Request\n"); 1449 /* XXX ID + Seq */ 1450 break; 1451 case ICMP_IREQREPLY: 1452 (void)printf("Information Reply\n"); 1453 /* XXX ID + Seq */ 1454 break; 1455 case ICMP_MASKREQ: 1456 (void)printf("Address Mask Request\n"); 1457 break; 1458 case ICMP_MASKREPLY: 1459 (void)printf("Address Mask Reply\n"); 1460 break; 1461 case ICMP_ROUTERADVERT: 1462 (void)printf("Router Advertisement\n"); 1463 break; 1464 case ICMP_ROUTERSOLICIT: 1465 (void)printf("Router Solicitation\n"); 1466 break; 1467 default: 1468 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1469 } 1470} 1471 1472/* 1473 * pr_iph -- 1474 * Print an IP header with options. 1475 */ 1476static void 1477pr_iph(ip) 1478 struct ip *ip; 1479{ 1480 u_char *cp; 1481 int hlen; 1482 1483 hlen = ip->ip_hl << 2; 1484 cp = (u_char *)ip + 20; /* point to options */ 1485 1486 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1487 (void)printf(" %1x %1x %02x %04x %04x", 1488 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1489 ntohs(ip->ip_id)); 1490 (void)printf(" %1lx %04lx", 1491 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1492 (u_long) ntohl(ip->ip_off) & 0x1fff); 1493 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1494 ntohs(ip->ip_sum)); 1495 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1496 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1497 /* dump any option bytes */ 1498 while (hlen-- > 20) { 1499 (void)printf("%02x", *cp++); 1500 } 1501 (void)putchar('\n'); 1502} 1503 1504/* 1505 * pr_addr -- 1506 * Return an ascii host address as a dotted quad and optionally with 1507 * a hostname. 1508 */ 1509static char * 1510pr_addr(ina) 1511 struct in_addr ina; 1512{ 1513 struct hostent *hp; 1514 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1515 1516 if ((options & F_NUMERIC) || 1517 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1518 return inet_ntoa(ina); 1519 else 1520 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1521 inet_ntoa(ina)); 1522 return(buf); 1523} 1524 1525/* 1526 * pr_retip -- 1527 * Dump some info on a returned (via ICMP) IP packet. 1528 */ 1529static void 1530pr_retip(ip) 1531 struct ip *ip; 1532{ 1533 u_char *cp; 1534 int hlen; 1535 1536 pr_iph(ip); 1537 hlen = ip->ip_hl << 2; 1538 cp = (u_char *)ip + hlen; 1539 1540 if (ip->ip_p == 6) 1541 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1542 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1543 else if (ip->ip_p == 17) 1544 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1545 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1546} 1547 1548static char * 1549pr_ntime (n_time time) 1550{ 1551 static char buf[10]; 1552 int h, m, s; 1553 1554 s = ntohl(time) / 1000; 1555 h = s / 60 / 60; 1556 m = (s % (60 * 60)) / 60; 1557 s = (s % (60 * 60)) % 60; 1558 1559 (void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", h, m, s); 1560 1561 return (buf); 1562} 1563 1564static void 1565fill(bp, patp) 1566 char *bp, *patp; 1567{ 1568 char *cp; 1569 int pat[16]; 1570 u_int ii, jj, kk; 1571 1572 for (cp = patp; *cp; cp++) { 1573 if (!isxdigit(*cp)) 1574 errx(EX_USAGE, 1575 "patterns must be specified as hex digits"); 1576 1577 } 1578 ii = sscanf(patp, 1579 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1580 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1581 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1582 &pat[13], &pat[14], &pat[15]); 1583 1584 if (ii > 0) 1585 for (kk = 0; kk <= maxpayload - (TIMEVAL_LEN + ii); kk += ii) 1586 for (jj = 0; jj < ii; ++jj) 1587 bp[jj + kk] = pat[jj]; 1588 if (!(options & F_QUIET)) { 1589 (void)printf("PATTERN: 0x"); 1590 for (jj = 0; jj < ii; ++jj) 1591 (void)printf("%02x", bp[jj] & 0xFF); 1592 (void)printf("\n"); 1593 } 1594} 1595 1596#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC) 1597#define SECOPT " [-P policy]" 1598#else 1599#define SECOPT "" 1600#endif 1601static void 1602usage() 1603{ 1604 1605 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n", 1606"usage: ping [-AaDdfnoQqRrv] [-c count] [-i wait] [-l preload] [-M mask | time]", 1607" [-m ttl]" SECOPT " [-p pattern] [-S src_addr] [-s packetsize]", 1608" [-t timeout] [-z tos] host", 1609" ping [-AaDdfLnoQqRrv] [-c count] [-I iface] [-i wait] [-l preload]", 1610" [-M mask | time] [-m ttl]" SECOPT " [-p pattern] [-S src_addr]", 1611" [-s packetsize] [-T ttl] [-t timeout] [-z tos] mcast-group"); 1612 exit(EX_USAGE); 1613} 1614