ping.c revision 110054
1226031Sstas/* 2226031Sstas * Copyright (c) 1989, 1993 3226031Sstas * The Regents of the University of California. All rights reserved. 4226031Sstas * 5226031Sstas * This code is derived from software contributed to Berkeley by 6226031Sstas * Mike Muuss. 7226031Sstas * 8226031Sstas * Redistribution and use in source and binary forms, with or without 9226031Sstas * modification, are permitted provided that the following conditions 10226031Sstas * are met: 11226031Sstas * 1. Redistributions of source code must retain the above copyright 12226031Sstas * notice, this list of conditions and the following disclaimer. 13226031Sstas * 2. Redistributions in binary form must reproduce the above copyright 14226031Sstas * notice, this list of conditions and the following disclaimer in the 15226031Sstas * documentation and/or other materials provided with the distribution. 16226031Sstas * 3. All advertising materials mentioning features or use of this software 17226031Sstas * must display the following acknowledgement: 18226031Sstas * This product includes software developed by the University of 19226031Sstas * California, Berkeley and its contributors. 20226031Sstas * 4. Neither the name of the University nor the names of its contributors 21226031Sstas * may be used to endorse or promote products derived from this software 22226031Sstas * without specific prior written permission. 23226031Sstas * 24226031Sstas * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25226031Sstas * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26226031Sstas * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27226031Sstas * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28226031Sstas * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29226031Sstas * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30226031Sstas * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31226031Sstas * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32226031Sstas * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33226031Sstas * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34226031Sstas * SUCH DAMAGE. 35226031Sstas */ 36226031Sstas 37226031Sstas#ifndef lint 38226031Sstasstatic const char copyright[] = 39226031Sstas"@(#) Copyright (c) 1989, 1993\n\ 40226031Sstas The Regents of the University of California. All rights reserved.\n"; 41226031Sstas#endif /* not lint */ 42226031Sstas 43226031Sstas#ifndef lint 44226031Sstas#if 0 45226031Sstasstatic char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; 46226031Sstas#endif 47226031Sstasstatic const char rcsid[] = 48226031Sstas "$FreeBSD: head/sbin/ping/ping.c 110054 2003-01-29 20:42:42Z mdodd $"; 49226031Sstas#endif /* not lint */ 50226031Sstas 51226031Sstas/* 52226031Sstas * P I N G . C 53226031Sstas * 54226031Sstas * Using the Internet Control Message Protocol (ICMP) "ECHO" facility, 55226031Sstas * measure round-trip-delays and packet loss across network paths. 56226031Sstas * 57226031Sstas * Author - 58226031Sstas * Mike Muuss 59226031Sstas * U. S. Army Ballistic Research Laboratory 60226031Sstas * December, 1983 61226031Sstas * 62226031Sstas * Status - 63226031Sstas * Public Domain. Distribution Unlimited. 64226031Sstas * Bugs - 65226031Sstas * More statistics could always be gathered. 66226031Sstas * This program has to run SUID to ROOT to access the ICMP socket. 67226031Sstas */ 68226031Sstas 69226031Sstas#include <sys/param.h> /* NB: we rely on this for <sys/types.h> */ 70226031Sstas#include <sys/socket.h> 71226031Sstas#include <sys/sysctl.h> 72226031Sstas#include <sys/time.h> 73226031Sstas#include <sys/uio.h> 74226031Sstas 75226031Sstas#include <netinet/in.h> 76226031Sstas#include <netinet/in_systm.h> 77226031Sstas#include <netinet/ip.h> 78226031Sstas#include <netinet/ip_icmp.h> 79226031Sstas#include <netinet/ip_var.h> 80226031Sstas#include <arpa/inet.h> 81226031Sstas 82226031Sstas#ifdef IPSEC 83226031Sstas#include <netinet6/ipsec.h> 84226031Sstas#endif /*IPSEC*/ 85226031Sstas 86226031Sstas#include <ctype.h> 87226031Sstas#include <err.h> 88226031Sstas#include <errno.h> 89226031Sstas#include <math.h> 90226031Sstas#include <netdb.h> 91226031Sstas#include <signal.h> 92226031Sstas#include <stdio.h> 93226031Sstas#include <stdlib.h> 94226031Sstas#include <string.h> 95226031Sstas#include <sysexits.h> 96226031Sstas#include <termios.h> 97226031Sstas#include <unistd.h> 98226031Sstas 99226031Sstas#define INADDR_LEN ((int)sizeof(in_addr_t)) 100226031Sstas#define PHDR_LEN ((int)sizeof(struct timeval)) 101226031Sstas#define DEFDATALEN (64 - PHDR_LEN) /* default data length */ 102226031Sstas#define FLOOD_BACKOFF 20000 /* usecs to back off if F_FLOOD mode */ 103226031Sstas /* runs out of buffer space */ 104226031Sstas#define MAXIPLEN (sizeof(struct ip) + MAX_IPOPTLEN) 105226031Sstas#define MAXICMPLEN (ICMP_ADVLENMIN + MAX_IPOPTLEN) 106226031Sstas#define MINICMPLEN ICMP_MINLEN 107226031Sstas#define MASKLEN (options & F_MASK ? 4 : 0) 108226031Sstas#define MAXWAIT 10 /* max seconds to wait for response */ 109226031Sstas#define MAXALARM (60 * 60) /* max seconds for alarm timeout */ 110226031Sstas#define MAXTOS 255 111226031Sstas 112226031Sstas#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ 113226031Sstas#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ 114226031Sstas#define SET(bit) (A(bit) |= B(bit)) 115226031Sstas#define CLR(bit) (A(bit) &= (~B(bit))) 116226031Sstas#define TST(bit) (A(bit) & B(bit)) 117226031Sstas 118226031Sstas/* various options */ 119226031Sstasint options; 120226031Sstas#define F_FLOOD 0x0001 121226031Sstas#define F_INTERVAL 0x0002 122226031Sstas#define F_NUMERIC 0x0004 123226031Sstas#define F_PINGFILLED 0x0008 124226031Sstas#define F_QUIET 0x0010 125226031Sstas#define F_RROUTE 0x0020 126226031Sstas#define F_SO_DEBUG 0x0040 127226031Sstas#define F_SO_DONTROUTE 0x0080 128226031Sstas#define F_VERBOSE 0x0100 129226031Sstas#define F_QUIET2 0x0200 130226031Sstas#define F_NOLOOP 0x0400 131226031Sstas#define F_MTTL 0x0800 132226031Sstas#define F_MIF 0x1000 133226031Sstas#define F_AUDIBLE 0x2000 134226031Sstas#ifdef IPSEC 135226031Sstas#ifdef IPSEC_POLICY_IPSEC 136226031Sstas#define F_POLICY 0x4000 137226031Sstas#endif /*IPSEC_POLICY_IPSEC*/ 138226031Sstas#endif /*IPSEC*/ 139226031Sstas#define F_TTL 0x8000 140226031Sstas#define F_MISSED 0x10000 141226031Sstas#define F_ONCE 0x20000 142226031Sstas#define F_HDRINCL 0x40000 143226031Sstas#define F_MASK 0x80000 144226031Sstas 145226031Sstas/* 146226031Sstas * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum 147226031Sstas * number of received sequence numbers we can keep track of. Change 128 148226031Sstas * to 8192 for complete accuracy... 149226031Sstas */ 150226031Sstas#define MAX_DUP_CHK (8 * 128) 151226031Sstasint mx_dup_ck = MAX_DUP_CHK; 152226031Sstaschar rcvd_tbl[MAX_DUP_CHK / 8]; 153226031Sstas 154226031Sstasstruct sockaddr_in whereto; /* who to ping */ 155226031Sstaslong maxpayload; 156226031Sstasint datalen = DEFDATALEN; 157226031Sstasint s; /* socket file descriptor */ 158226031Sstasu_char outpackhdr[IP_MAXPACKET], *outpack; 159226031Sstaschar BBELL = '\a'; /* characters written for MISSED and AUDIBLE */ 160226031Sstaschar BSPACE = '\b'; /* characters written for flood */ 161226031Sstaschar DOT = '.'; 162226031Sstaschar *hostname; 163226031Sstaschar *shostname; 164226031Sstasint ident; /* process id to identify our packets */ 165226031Sstasint uid; /* cached uid for micro-optimization */ 166226031Sstas 167226031Sstas/* counters */ 168226031Sstaslong nmissedmax; /* max value of ntransmitted - nreceived - 1 */ 169226031Sstaslong npackets; /* max packets to transmit */ 170226031Sstaslong nreceived; /* # of packets we got back */ 171226031Sstaslong nrepeats; /* number of duplicates */ 172226031Sstaslong ntransmitted; /* sequence # for outbound packets = #sent */ 173226031Sstasint interval = 1000; /* interval between packets, ms */ 174226031Sstas 175226031Sstas/* timing */ 176226031Sstasint timing; /* flag to do timing */ 177226031Sstasdouble tmin = 999999999.0; /* minimum round trip time */ 178226031Sstasdouble tmax = 0.0; /* maximum round trip time */ 179226031Sstasdouble tsum = 0.0; /* sum of all times, for doing average */ 180226031Sstasdouble tsumsq = 0.0; /* sum of all times squared, for std. dev. */ 181226031Sstas 182226031Sstasvolatile sig_atomic_t finish_up; /* nonzero if we've been told to finish up */ 183226031Sstasint reset_kerninfo; 184226031Sstasvolatile sig_atomic_t siginfo_p; 185226031Sstas 186226031Sstasstatic void fill(char *, char *); 187226031Sstasstatic u_short in_cksum(u_short *, int); 188226031Sstasstatic void check_status(void); 189226031Sstasstatic void finish(void) __dead2; 190226031Sstasstatic void pinger(void); 191226031Sstasstatic char *pr_addr(struct in_addr); 192226031Sstasstatic void pr_icmph(struct icmp *); 193226031Sstasstatic void pr_iph(struct ip *); 194226031Sstasstatic void pr_pack(char *, int, struct sockaddr_in *, struct timeval *); 195226031Sstasstatic void pr_retip(struct ip *); 196226031Sstasstatic void status(int); 197226031Sstasstatic void stopit(int); 198226031Sstasstatic void tvsub(struct timeval *, struct timeval *); 199226031Sstasstatic void usage(void) __dead2; 200226031Sstas 201226031Sstasint 202226031Sstasmain(argc, argv) 203226031Sstas int argc; 204226031Sstas char *const *argv; 205226031Sstas{ 206226031Sstas struct sockaddr_in from, sin; 207226031Sstas struct in_addr ifaddr; 208226031Sstas struct timeval last, intvl; 209226031Sstas struct iovec iov; 210226031Sstas struct ip *ip; 211226031Sstas struct msghdr msg; 212226031Sstas struct sigaction si_sa; 213226031Sstas struct termios ts; 214226031Sstas size_t sz; 215226031Sstas u_char *datap, packet[IP_MAXPACKET]; 216226031Sstas char *ep, *source, *target, *payload; 217226031Sstas struct hostent *hp; 218226031Sstas#ifdef IPSEC_POLICY_IPSEC 219226031Sstas char *policy_in, *policy_out; 220226031Sstas#endif 221226031Sstas struct sockaddr_in *to; 222226031Sstas double t; 223226031Sstas u_long alarmtimeout, ultmp; 224226031Sstas int almost_done, ch, df, hold, i, mib[4], packlen, preload, sockerrno, 225226031Sstas tos, ttl; 226226031Sstas char ctrl[CMSG_SPACE(sizeof(struct timeval))]; 227226031Sstas char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN]; 228226031Sstas#ifdef IP_OPTIONS 229226031Sstas char rspace[MAX_IPOPTLEN]; /* record route space */ 230226031Sstas#endif 231226031Sstas unsigned char loop, mttl; 232226031Sstas 233226031Sstas source = NULL; 234226031Sstas#ifdef IPSEC_POLICY_IPSEC 235226031Sstas policy_in = policy_out = NULL; 236226031Sstas#endif 237226031Sstas 238226031Sstas /* 239226031Sstas * Do the stuff that we need root priv's for *first*, and 240226031Sstas * then drop our setuid bit. Save error reporting for 241226031Sstas * after arg parsing. 242226031Sstas */ 243226031Sstas s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 244226031Sstas sockerrno = errno; 245226031Sstas 246226031Sstas setuid(getuid()); 247226031Sstas uid = getuid(); 248226031Sstas 249226031Sstas alarmtimeout = df = preload = tos = 0; 250226031Sstas 251226031Sstas outpack = outpackhdr + sizeof(struct ip); 252226031Sstas while ((ch = getopt(argc, argv, 253226031Sstas "ADI:LQRS:T:c:adfi:l:m:Mnop:qrs:t:vz:" 254226031Sstas#ifdef IPSEC 255226031Sstas#ifdef IPSEC_POLICY_IPSEC 256226031Sstas "P:" 257226031Sstas#endif /*IPSEC_POLICY_IPSEC*/ 258226031Sstas#endif /*IPSEC*/ 259226031Sstas )) != -1) 260226031Sstas { 261226031Sstas switch(ch) { 262226031Sstas case 'A': 263226031Sstas options |= F_MISSED; 264226031Sstas break; 265226031Sstas case 'a': 266226031Sstas options |= F_AUDIBLE; 267226031Sstas break; 268226031Sstas case 'c': 269226031Sstas ultmp = strtoul(optarg, &ep, 0); 270226031Sstas if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp) 271226031Sstas errx(EX_USAGE, 272226031Sstas "invalid count of packets to transmit: `%s'", 273226031Sstas optarg); 274226031Sstas npackets = ultmp; 275226031Sstas break; 276226031Sstas case 'D': 277226031Sstas options |= F_HDRINCL; 278226031Sstas df = 1; 279226031Sstas break; 280226031Sstas case 'd': 281226031Sstas options |= F_SO_DEBUG; 282226031Sstas break; 283226031Sstas case 'f': 284226031Sstas if (uid) { 285226031Sstas errno = EPERM; 286226031Sstas err(EX_NOPERM, "-f flag"); 287226031Sstas } 288226031Sstas options |= F_FLOOD; 289226031Sstas setbuf(stdout, (char *)NULL); 290226031Sstas break; 291226031Sstas case 'i': /* wait between sending packets */ 292226031Sstas t = strtod(optarg, &ep) * 1000.0; 293226031Sstas if (*ep || ep == optarg || t > (double)INT_MAX) 294226031Sstas errx(EX_USAGE, "invalid timing interval: `%s'", 295226031Sstas optarg); 296226031Sstas options |= F_INTERVAL; 297226031Sstas interval = (int)t; 298226031Sstas if (uid && interval < 1000) { 299226031Sstas errno = EPERM; 300226031Sstas err(EX_NOPERM, "-i interval too short"); 301226031Sstas } 302226031Sstas break; 303226031Sstas case 'I': /* multicast interface */ 304226031Sstas if (inet_aton(optarg, &ifaddr) == 0) 305226031Sstas errx(EX_USAGE, 306226031Sstas "invalid multicast interface: `%s'", 307226031Sstas optarg); 308226031Sstas options |= F_MIF; 309226031Sstas break; 310226031Sstas case 'l': 311226031Sstas ultmp = strtoul(optarg, &ep, 0); 312226031Sstas if (*ep || ep == optarg || ultmp > INT_MAX) 313226031Sstas errx(EX_USAGE, 314226031Sstas "invalid preload value: `%s'", optarg); 315226031Sstas if (uid) { 316226031Sstas errno = EPERM; 317226031Sstas err(EX_NOPERM, "-l flag"); 318226031Sstas } 319226031Sstas preload = ultmp; 320226031Sstas break; 321226031Sstas case 'L': 322226031Sstas options |= F_NOLOOP; 323226031Sstas loop = 0; 324226031Sstas break; 325226031Sstas case 'm': /* TTL */ 326226031Sstas ultmp = strtoul(optarg, &ep, 0); 327226031Sstas if (*ep || ep == optarg || ultmp > MAXTTL) 328226031Sstas errx(EX_USAGE, "invalid TTL: `%s'", optarg); 329226031Sstas ttl = ultmp; 330226031Sstas options |= F_TTL; 331226031Sstas break; 332226031Sstas case 'M': 333226031Sstas options |= F_MASK; 334226031Sstas break; 335226031Sstas case 'n': 336226031Sstas options |= F_NUMERIC; 337226031Sstas break; 338226031Sstas case 'o': 339226031Sstas options |= F_ONCE; 340226031Sstas break; 341226031Sstas case 'p': /* fill buffer with user pattern */ 342226031Sstas options |= F_PINGFILLED; 343226031Sstas payload = optarg; 344226031Sstas break; 345226031Sstas case 'Q': 346226031Sstas options |= F_QUIET2; 347226031Sstas break; 348226031Sstas case 'q': 349226031Sstas options |= F_QUIET; 350226031Sstas break; 351226031Sstas case 'R': 352226031Sstas options |= F_RROUTE; 353226031Sstas break; 354226031Sstas case 'r': 355226031Sstas options |= F_SO_DONTROUTE; 356226031Sstas break; 357226031Sstas case 's': /* size of packet to send */ 358226031Sstas ultmp = strtoul(optarg, &ep, 0); 359226031Sstas if (*ep || ep == optarg) 360226031Sstas errx(EX_USAGE, "invalid packet size: `%s'", 361226031Sstas optarg); 362226031Sstas if (uid != 0 && ultmp > DEFDATALEN) { 363226031Sstas errno = EPERM; 364226031Sstas err(EX_NOPERM, 365226031Sstas "packet size too large: %lu > %u", 366226031Sstas ultmp, DEFDATALEN); 367226031Sstas } 368226031Sstas datalen = ultmp; 369226031Sstas break; 370226031Sstas case 'S': 371226031Sstas source = optarg; 372226031Sstas break; 373226031Sstas case 't': 374226031Sstas alarmtimeout = strtoul(optarg, &ep, 0); 375226031Sstas if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX)) 376226031Sstas errx(EX_USAGE, "invalid timeout: `%s'", 377226031Sstas optarg); 378226031Sstas if (alarmtimeout > MAXALARM) 379226031Sstas errx(EX_USAGE, "invalid timeout: `%s' > %d", 380226031Sstas optarg, MAXALARM); 381226031Sstas alarm((int)alarmtimeout); 382226031Sstas break; 383226031Sstas case 'T': /* multicast TTL */ 384226031Sstas ultmp = strtoul(optarg, &ep, 0); 385226031Sstas if (*ep || ep == optarg || ultmp > MAXTTL) 386226031Sstas errx(EX_USAGE, "invalid multicast TTL: `%s'", 387226031Sstas optarg); 388226031Sstas mttl = ultmp; 389226031Sstas options |= F_MTTL; 390226031Sstas break; 391226031Sstas case 'v': 392226031Sstas options |= F_VERBOSE; 393226031Sstas break; 394226031Sstas#ifdef IPSEC 395226031Sstas#ifdef IPSEC_POLICY_IPSEC 396226031Sstas case 'P': 397226031Sstas options |= F_POLICY; 398226031Sstas if (!strncmp("in", optarg, 2)) 399226031Sstas policy_in = strdup(optarg); 400226031Sstas else if (!strncmp("out", optarg, 3)) 401226031Sstas policy_out = strdup(optarg); 402226031Sstas else 403226031Sstas errx(1, "invalid security policy"); 404226031Sstas break; 405226031Sstas case 'z': 406226031Sstas options |= F_HDRINCL; 407226031Sstas ultmp = strtoul(optarg, &ep, 0); 408226031Sstas if (*ep || ep == optarg || ultmp > MAXTOS) 409226031Sstas errx(EX_USAGE, "invalid TOS: `%s'", optarg); 410226031Sstas tos = ultmp; 411226031Sstas break; 412226031Sstas#endif /*IPSEC_POLICY_IPSEC*/ 413226031Sstas#endif /*IPSEC*/ 414226031Sstas default: 415226031Sstas usage(); 416226031Sstas } 417226031Sstas } 418226031Sstas 419226031Sstas if (argc - optind != 1) 420226031Sstas usage(); 421226031Sstas target = argv[optind]; 422226031Sstas 423226031Sstas maxpayload = IP_MAXPACKET - sizeof(struct ip) - MINICMPLEN; 424226031Sstas if (options & F_RROUTE) 425226031Sstas maxpayload -= MAX_IPOPTLEN; 426226031Sstas if (datalen > maxpayload) 427226031Sstas errx(EX_USAGE, "packet size too large: %lu > %u", datalen, 428226031Sstas maxpayload); 429226031Sstas datap = &outpack[MINICMPLEN + PHDR_LEN]; 430226031Sstas if (options & F_PINGFILLED) { 431226031Sstas fill((char *)datap, payload); 432226031Sstas } 433226031Sstas if (source) { 434226031Sstas bzero((char *)&sin, sizeof(sin)); 435226031Sstas sin.sin_family = AF_INET; 436226031Sstas if (inet_aton(source, &sin.sin_addr) != 0) { 437226031Sstas shostname = source; 438226031Sstas } else { 439226031Sstas hp = gethostbyname2(source, AF_INET); 440226031Sstas if (!hp) 441226031Sstas errx(EX_NOHOST, "cannot resolve %s: %s", 442226031Sstas source, hstrerror(h_errno)); 443226031Sstas 444226031Sstas sin.sin_len = sizeof sin; 445226031Sstas if (hp->h_length > sizeof(sin.sin_addr) || 446226031Sstas hp->h_length < 0) 447226031Sstas errx(1, "gethostbyname2: illegal address"); 448226031Sstas memcpy(&sin.sin_addr, hp->h_addr_list[0], 449226031Sstas sizeof(sin.sin_addr)); 450226031Sstas (void)strncpy(snamebuf, hp->h_name, 451226031Sstas sizeof(snamebuf) - 1); 452226031Sstas snamebuf[sizeof(snamebuf) - 1] = '\0'; 453226031Sstas shostname = snamebuf; 454226031Sstas } 455226031Sstas if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1) 456226031Sstas err(1, "bind"); 457226031Sstas } 458226031Sstas 459226031Sstas bzero(&whereto, sizeof(whereto)); 460226031Sstas to = &whereto; 461226031Sstas to->sin_family = AF_INET; 462226031Sstas to->sin_len = sizeof *to; 463226031Sstas if (inet_aton(target, &to->sin_addr) != 0) { 464226031Sstas hostname = target; 465226031Sstas } else { 466226031Sstas hp = gethostbyname2(target, AF_INET); 467226031Sstas if (!hp) 468226031Sstas errx(EX_NOHOST, "cannot resolve %s: %s", 469226031Sstas target, hstrerror(h_errno)); 470226031Sstas 471226031Sstas if (hp->h_length > sizeof(to->sin_addr)) 472226031Sstas errx(1, "gethostbyname2 returned an illegal address"); 473226031Sstas memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr); 474226031Sstas (void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1); 475226031Sstas hnamebuf[sizeof(hnamebuf) - 1] = '\0'; 476226031Sstas hostname = hnamebuf; 477226031Sstas } 478226031Sstas 479226031Sstas if (options & F_FLOOD && options & F_INTERVAL) 480226031Sstas errx(EX_USAGE, "-f and -i: incompatible options"); 481226031Sstas 482226031Sstas if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 483226031Sstas errx(EX_USAGE, 484226031Sstas "-f flag cannot be used with multicast destination"); 485226031Sstas if (options & (F_MIF | F_NOLOOP | F_MTTL) 486226031Sstas && !IN_MULTICAST(ntohl(to->sin_addr.s_addr))) 487226031Sstas errx(EX_USAGE, 488226031Sstas "-I, -L, -T flags cannot be used with unicast destination"); 489226031Sstas 490226031Sstas if (datalen - MASKLEN >= PHDR_LEN) /* can we time transfer */ 491226031Sstas timing = 1; 492226031Sstas packlen = MAXIPLEN + MAXICMPLEN + datalen; 493226031Sstas packlen = packlen > IP_MAXPACKET ? IP_MAXPACKET : packlen; 494226031Sstas 495226031Sstas if (!(options & F_PINGFILLED)) 496226031Sstas for (i = PHDR_LEN; i < datalen; ++i) 497226031Sstas *datap++ = i; 498226031Sstas 499226031Sstas ident = getpid() & 0xFFFF; 500226031Sstas 501226031Sstas if (s < 0) { 502226031Sstas errno = sockerrno; 503226031Sstas err(EX_OSERR, "socket"); 504226031Sstas } 505226031Sstas hold = 1; 506226031Sstas if (options & F_SO_DEBUG) 507226031Sstas (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold, 508226031Sstas sizeof(hold)); 509226031Sstas if (options & F_SO_DONTROUTE) 510226031Sstas (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, 511226031Sstas sizeof(hold)); 512226031Sstas#ifdef IPSEC 513226031Sstas#ifdef IPSEC_POLICY_IPSEC 514226031Sstas if (options & F_POLICY) { 515226031Sstas char *buf; 516226031Sstas if (policy_in != NULL) { 517226031Sstas buf = ipsec_set_policy(policy_in, strlen(policy_in)); 518226031Sstas if (buf == NULL) 519226031Sstas errx(EX_CONFIG, "%s", ipsec_strerror()); 520226031Sstas if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 521226031Sstas buf, ipsec_get_policylen(buf)) < 0) 522226031Sstas err(EX_CONFIG, 523226031Sstas "ipsec policy cannot be configured"); 524226031Sstas free(buf); 525226031Sstas } 526226031Sstas 527226031Sstas if (policy_out != NULL) { 528226031Sstas buf = ipsec_set_policy(policy_out, strlen(policy_out)); 529226031Sstas if (buf == NULL) 530226031Sstas errx(EX_CONFIG, "%s", ipsec_strerror()); 531226031Sstas if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, 532226031Sstas buf, ipsec_get_policylen(buf)) < 0) 533226031Sstas err(EX_CONFIG, 534226031Sstas "ipsec policy cannot be configured"); 535226031Sstas free(buf); 536226031Sstas } 537226031Sstas } 538226031Sstas#endif /*IPSEC_POLICY_IPSEC*/ 539226031Sstas#endif /*IPSEC*/ 540226031Sstas 541226031Sstas if (options & F_HDRINCL) { 542226031Sstas ip = (struct ip*)outpackhdr; 543226031Sstas if (!(options & (F_TTL | F_MTTL))) { 544226031Sstas mib[0] = CTL_NET; 545226031Sstas mib[1] = PF_INET; 546226031Sstas mib[2] = IPPROTO_IP; 547226031Sstas mib[3] = IPCTL_DEFTTL; 548226031Sstas sz = sizeof(ttl); 549226031Sstas if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1) 550226031Sstas err(1, "sysctl(net.inet.ip.ttl)"); 551226031Sstas } 552226031Sstas setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold)); 553226031Sstas ip->ip_v = IPVERSION; 554226031Sstas ip->ip_hl = sizeof(struct ip) >> 2; 555226031Sstas ip->ip_tos = tos; 556226031Sstas ip->ip_id = 0; 557226031Sstas ip->ip_off = df ? IP_DF : 0; 558226031Sstas ip->ip_ttl = ttl; 559226031Sstas ip->ip_p = IPPROTO_ICMP; 560226031Sstas ip->ip_src.s_addr = source ? sin.sin_addr.s_addr : INADDR_ANY; 561226031Sstas ip->ip_dst = to->sin_addr; 562226031Sstas } 563226031Sstas /* record route option */ 564226031Sstas if (options & F_RROUTE) { 565226031Sstas#ifdef IP_OPTIONS 566226031Sstas bzero(rspace, sizeof(rspace)); 567226031Sstas rspace[IPOPT_OPTVAL] = IPOPT_RR; 568226031Sstas rspace[IPOPT_OLEN] = sizeof(rspace) - 1; 569226031Sstas rspace[IPOPT_OFFSET] = IPOPT_MINOFF; 570226031Sstas rspace[sizeof(rspace) - 1] = IPOPT_EOL; 571226031Sstas if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace, 572226031Sstas sizeof(rspace)) < 0) 573226031Sstas err(EX_OSERR, "setsockopt IP_OPTIONS"); 574226031Sstas#else 575226031Sstas errx(EX_UNAVAILABLE, 576226031Sstas "record route not available in this implementation"); 577226031Sstas#endif /* IP_OPTIONS */ 578226031Sstas } 579226031Sstas 580226031Sstas if (options & F_TTL) { 581226031Sstas if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl, 582226031Sstas sizeof(ttl)) < 0) { 583226031Sstas err(EX_OSERR, "setsockopt IP_TTL"); 584226031Sstas } 585226031Sstas } 586226031Sstas if (options & F_NOLOOP) { 587226031Sstas if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, 588226031Sstas sizeof(loop)) < 0) { 589226031Sstas err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP"); 590226031Sstas } 591226031Sstas } 592226031Sstas if (options & F_MTTL) { 593226031Sstas if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl, 594226031Sstas sizeof(mttl)) < 0) { 595226031Sstas err(EX_OSERR, "setsockopt IP_MULTICAST_TTL"); 596226031Sstas } 597226031Sstas } 598226031Sstas if (options & F_MIF) { 599226031Sstas if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, 600226031Sstas sizeof(ifaddr)) < 0) { 601226031Sstas err(EX_OSERR, "setsockopt IP_MULTICAST_IF"); 602226031Sstas } 603226031Sstas } 604226031Sstas#ifdef SO_TIMESTAMP 605226031Sstas { int on = 1; 606226031Sstas if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0) 607226031Sstas err(EX_OSERR, "setsockopt SO_TIMESTAMP"); 608226031Sstas } 609226031Sstas#endif 610226031Sstas 611226031Sstas /* 612226031Sstas * When pinging the broadcast address, you can get a lot of answers. 613226031Sstas * Doing something so evil is useful if you are trying to stress the 614226031Sstas * ethernet, or just want to fill the arp cache to get some stuff for 615226031Sstas * /etc/ethers. But beware: RFC 1122 allows hosts to ignore broadcast 616226031Sstas * or multicast pings if they wish. 617226031Sstas */ 618226031Sstas 619226031Sstas /* 620226031Sstas * XXX receive buffer needs undetermined space for mbuf overhead 621226031Sstas * as well. 622226031Sstas */ 623226031Sstas hold = IP_MAXPACKET + 128; 624226031Sstas (void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold, 625226031Sstas sizeof(hold)); 626226031Sstas if (uid == 0) 627226031Sstas (void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold, 628226031Sstas sizeof(hold)); 629226031Sstas 630226031Sstas if (to->sin_family == AF_INET) { 631226031Sstas (void)printf("PING %s (%s)", hostname, 632226031Sstas inet_ntoa(to->sin_addr)); 633226031Sstas if (source) 634226031Sstas (void)printf(" from %s", shostname); 635226031Sstas (void)printf(": %d data bytes\n", datalen); 636226031Sstas } else 637226031Sstas (void)printf("PING %s: %d data bytes\n", hostname, datalen); 638226031Sstas 639226031Sstas /* 640226031Sstas * Use sigaction() instead of signal() to get unambiguous semantics, 641226031Sstas * in particular with SA_RESTART not set. 642226031Sstas */ 643226031Sstas 644226031Sstas sigemptyset(&si_sa.sa_mask); 645226031Sstas si_sa.sa_flags = 0; 646226031Sstas 647226031Sstas si_sa.sa_handler = stopit; 648226031Sstas if (sigaction(SIGINT, &si_sa, 0) == -1) { 649226031Sstas err(EX_OSERR, "sigaction SIGINT"); 650226031Sstas } 651226031Sstas 652226031Sstas si_sa.sa_handler = status; 653226031Sstas if (sigaction(SIGINFO, &si_sa, 0) == -1) { 654226031Sstas err(EX_OSERR, "sigaction"); 655226031Sstas } 656226031Sstas 657226031Sstas if (alarmtimeout > 0) { 658226031Sstas si_sa.sa_handler = stopit; 659226031Sstas if (sigaction(SIGALRM, &si_sa, 0) == -1) 660226031Sstas err(EX_OSERR, "sigaction SIGALRM"); 661226031Sstas } 662226031Sstas 663226031Sstas bzero(&msg, sizeof(msg)); 664226031Sstas msg.msg_name = (caddr_t)&from; 665226031Sstas msg.msg_iov = &iov; 666226031Sstas msg.msg_iovlen = 1; 667226031Sstas#ifdef SO_TIMESTAMP 668226031Sstas msg.msg_control = (caddr_t)ctrl; 669226031Sstas#endif 670226031Sstas iov.iov_base = packet; 671226031Sstas iov.iov_len = packlen; 672226031Sstas 673226031Sstas if (tcgetattr(STDOUT_FILENO, &ts) != -1) { 674226031Sstas reset_kerninfo = !(ts.c_lflag & NOKERNINFO); 675226031Sstas ts.c_lflag |= NOKERNINFO; 676226031Sstas tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 677226031Sstas } 678226031Sstas 679226031Sstas if (preload == 0) 680226031Sstas pinger(); /* send the first ping */ 681226031Sstas else { 682226031Sstas if (npackets != 0 && preload > npackets) 683226031Sstas preload = npackets; 684226031Sstas while (preload--) /* fire off them quickies */ 685226031Sstas pinger(); 686226031Sstas } 687226031Sstas (void)gettimeofday(&last, NULL); 688226031Sstas 689226031Sstas if (options & F_FLOOD) { 690226031Sstas intvl.tv_sec = 0; 691226031Sstas intvl.tv_usec = 10000; 692226031Sstas } else { 693226031Sstas intvl.tv_sec = interval / 1000; 694226031Sstas intvl.tv_usec = interval % 1000 * 1000; 695226031Sstas } 696226031Sstas 697226031Sstas almost_done = 0; 698226031Sstas while (!finish_up) { 699226031Sstas struct timeval now, timeout; 700226031Sstas fd_set rfds; 701226031Sstas int cc, n; 702226031Sstas 703226031Sstas check_status(); 704226031Sstas if (s >= FD_SETSIZE) 705226031Sstas errx(EX_OSERR, "descriptor too large"); 706226031Sstas FD_ZERO(&rfds); 707226031Sstas FD_SET(s, &rfds); 708226031Sstas (void)gettimeofday(&now, NULL); 709226031Sstas timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec; 710226031Sstas timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec; 711226031Sstas while (timeout.tv_usec < 0) { 712226031Sstas timeout.tv_usec += 1000000; 713226031Sstas timeout.tv_sec--; 714226031Sstas } 715226031Sstas while (timeout.tv_usec >= 1000000) { 716226031Sstas timeout.tv_usec -= 1000000; 717226031Sstas timeout.tv_sec++; 718226031Sstas } 719226031Sstas if (timeout.tv_sec < 0) 720226031Sstas timeout.tv_sec = timeout.tv_usec = 0; 721226031Sstas n = select(s + 1, &rfds, NULL, NULL, &timeout); 722226031Sstas if (n < 0) 723226031Sstas continue; /* Must be EINTR. */ 724226031Sstas if (n == 1) { 725226031Sstas struct timeval *t = NULL; 726226031Sstas#ifdef SO_TIMESTAMP 727226031Sstas struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl; 728226031Sstas 729226031Sstas msg.msg_controllen = sizeof(ctrl); 730226031Sstas#endif 731226031Sstas msg.msg_namelen = sizeof(from); 732226031Sstas if ((cc = recvmsg(s, &msg, 0)) < 0) { 733226031Sstas if (errno == EINTR) 734226031Sstas continue; 735226031Sstas warn("recvmsg"); 736226031Sstas continue; 737226031Sstas } 738226031Sstas#ifdef SO_TIMESTAMP 739226031Sstas if (cmsg->cmsg_level == SOL_SOCKET && 740226031Sstas cmsg->cmsg_type == SCM_TIMESTAMP && 741226031Sstas cmsg->cmsg_len == CMSG_LEN(sizeof *t)) { 742226031Sstas /* Copy to avoid alignment problems: */ 743226031Sstas memcpy(&now, CMSG_DATA(cmsg), sizeof(now)); 744226031Sstas t = &now; 745226031Sstas } 746226031Sstas#endif 747226031Sstas if (t == NULL) { 748226031Sstas (void)gettimeofday(&now, NULL); 749226031Sstas t = &now; 750226031Sstas } 751226031Sstas pr_pack((char *)packet, cc, &from, t); 752226031Sstas if (options & F_ONCE && nreceived || 753226031Sstas npackets && nreceived >= npackets) 754226031Sstas break; 755226031Sstas } 756226031Sstas if (n == 0 || options & F_FLOOD) { 757226031Sstas if (!npackets || ntransmitted < npackets) 758226031Sstas pinger(); 759226031Sstas else { 760226031Sstas if (almost_done) 761226031Sstas break; 762226031Sstas almost_done = 1; 763226031Sstas intvl.tv_usec = 0; 764226031Sstas if (nreceived) { 765226031Sstas intvl.tv_sec = 2 * tmax / 1000; 766226031Sstas if (!intvl.tv_sec) 767226031Sstas intvl.tv_sec = 1; 768226031Sstas } else 769226031Sstas intvl.tv_sec = MAXWAIT; 770226031Sstas } 771226031Sstas (void)gettimeofday(&last, NULL); 772226031Sstas if (ntransmitted - nreceived - 1 > nmissedmax) { 773226031Sstas nmissedmax = ntransmitted - nreceived - 1; 774226031Sstas if (options & F_MISSED) 775226031Sstas (void)write(STDOUT_FILENO, &BBELL, 1); 776226031Sstas } 777226031Sstas } 778226031Sstas } 779226031Sstas finish(); 780226031Sstas /* NOTREACHED */ 781226031Sstas exit(0); /* Make the compiler happy */ 782226031Sstas} 783226031Sstas 784226031Sstas/* 785226031Sstas * stopit -- 786226031Sstas * Set the global bit that causes the main loop to quit. 787226031Sstas * Do NOT call finish() from here, since finish() does far too much 788226031Sstas * to be called from a signal handler. 789226031Sstas */ 790226031Sstasvoid 791226031Sstasstopit(sig) 792226031Sstas int sig __unused; 793226031Sstas{ 794226031Sstas 795226031Sstas finish_up = 1; 796226031Sstas} 797226031Sstas 798226031Sstas/* 799226031Sstas * pinger -- 800226031Sstas * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet 801226031Sstas * will be added on by the kernel. The ID field is our UNIX process ID, 802226031Sstas * and the sequence number is an ascending integer. The first PHDR_LEN 803226031Sstas * bytes of the data portion are used to hold a UNIX "timeval" struct in 804226031Sstas * host byte-order, to compute the round-trip time. 805226031Sstas */ 806226031Sstasstatic void 807226031Sstaspinger(void) 808226031Sstas{ 809226031Sstas struct ip *ip; 810226031Sstas struct icmp *icp; 811226031Sstas int cc, i; 812226031Sstas u_char *packet; 813226031Sstas 814226031Sstas packet = outpack; 815226031Sstas icp = (struct icmp *)outpack; 816226031Sstas if (options & F_MASK) 817226031Sstas icp->icmp_type = ICMP_MASKREQ; 818226031Sstas else 819 icp->icmp_type = ICMP_ECHO; 820 icp->icmp_code = 0; 821 icp->icmp_cksum = 0; 822 icp->icmp_seq = htons(ntransmitted); 823 icp->icmp_id = ident; /* ID */ 824 825 CLR(ntransmitted % mx_dup_ck); 826 827 if (timing) 828 (void)gettimeofday((struct timeval *)&outpack[ 829 MINICMPLEN + MASKLEN], NULL); 830 831 cc = MINICMPLEN + datalen; 832 833 /* compute ICMP checksum here */ 834 icp->icmp_cksum = in_cksum((u_short *)icp, cc); 835 836 if (options & F_HDRINCL) { 837 cc += sizeof(struct ip); 838 ip = (struct ip *)outpackhdr; 839 ip->ip_len = cc; 840 ip->ip_sum = in_cksum((u_short *)outpackhdr, cc); 841 packet = outpackhdr; 842 } 843 i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto, 844 sizeof(whereto)); 845 846 if (i < 0 || i != cc) { 847 if (i < 0) { 848 if (options & F_FLOOD && errno == ENOBUFS) { 849 usleep(FLOOD_BACKOFF); 850 return; 851 } 852 warn("sendto"); 853 } else { 854 warn("%s: partial write: %d of %d bytes", 855 hostname, i, cc); 856 } 857 } 858 ntransmitted++; 859 if (!(options & F_QUIET) && options & F_FLOOD) 860 (void)write(STDOUT_FILENO, &DOT, 1); 861} 862 863/* 864 * pr_pack -- 865 * Print out the packet, if it came from us. This logic is necessary 866 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets 867 * which arrive ('tis only fair). This permits multiple copies of this 868 * program to be run without having intermingled output (or statistics!). 869 */ 870static void 871pr_pack(buf, cc, from, tv) 872 char *buf; 873 int cc; 874 struct sockaddr_in *from; 875 struct timeval *tv; 876{ 877 struct in_addr ina; 878 u_char *cp, *dp; 879 struct icmp *icp; 880 struct ip *ip; 881 const void *tp; 882 double triptime; 883 int dupflag, hlen, i, j, seq; 884 static int old_rrlen; 885 static char old_rr[MAX_IPOPTLEN]; 886 887 /* Check the IP header */ 888 ip = (struct ip *)buf; 889 hlen = ip->ip_hl << 2; 890 if (cc < hlen + ICMP_MINLEN) { 891 if (options & F_VERBOSE) 892 warn("packet too short (%d bytes) from %s", cc, 893 inet_ntoa(from->sin_addr)); 894 return; 895 } 896 897 /* Now the ICMP part */ 898 cc -= hlen; 899 icp = (struct icmp *)(buf + hlen); 900 if ((icp->icmp_type == ICMP_ECHOREPLY) || 901 ((icp->icmp_type == ICMP_MASKREPLY) && (options & F_MASK))) { 902 if (icp->icmp_id != ident) 903 return; /* 'Twas not our ECHO */ 904 ++nreceived; 905 triptime = 0.0; 906 if (timing) { 907 struct timeval tv1; 908#ifndef icmp_data 909 tp = &icp->icmp_ip; 910#else 911 tp = icp->icmp_data; 912#endif 913 tp+=MASKLEN; 914 915 /* Copy to avoid alignment problems: */ 916 memcpy(&tv1, tp, sizeof(tv1)); 917 tvsub(tv, &tv1); 918 triptime = ((double)tv->tv_sec) * 1000.0 + 919 ((double)tv->tv_usec) / 1000.0; 920 tsum += triptime; 921 tsumsq += triptime * triptime; 922 if (triptime < tmin) 923 tmin = triptime; 924 if (triptime > tmax) 925 tmax = triptime; 926 } 927 928 seq = ntohs(icp->icmp_seq); 929 930 if (TST(seq % mx_dup_ck)) { 931 ++nrepeats; 932 --nreceived; 933 dupflag = 1; 934 } else { 935 SET(seq % mx_dup_ck); 936 dupflag = 0; 937 } 938 939 if (options & F_QUIET) 940 return; 941 942 if (options & F_FLOOD) 943 (void)write(STDOUT_FILENO, &BSPACE, 1); 944 else { 945 (void)printf("%d bytes from %s: icmp_seq=%u", cc, 946 inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr), 947 seq); 948 (void)printf(" ttl=%d", ip->ip_ttl); 949 if (timing) 950 (void)printf(" time=%.3f ms", triptime); 951 if (dupflag) 952 (void)printf(" (DUP!)"); 953 if (options & F_AUDIBLE) 954 (void)write(STDOUT_FILENO, &BBELL, 1); 955 if (options & F_MASK) { 956 /* Just prentend this cast isn't ugly */ 957 (void)printf(" mask=%s", 958 pr_addr(*(struct in_addr *)&(icp->icmp_mask))); 959 } 960 /* check the data */ 961 cp = (u_char*)&icp->icmp_data[PHDR_LEN]; 962 dp = &outpack[MINICMPLEN + PHDR_LEN]; 963 for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) { 964 if (*cp != *dp) { 965 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", 966 i, *dp, *cp); 967 (void)printf("\ncp:"); 968 cp = (u_char*)&icp->icmp_data[0]; 969 for (i = 0; i < datalen; ++i, ++cp) { 970 if ((i % 32) == 8) 971 (void)printf("\n\t"); 972 (void)printf("%x ", *cp); 973 } 974 (void)printf("\ndp:"); 975 cp = &outpack[MINICMPLEN]; 976 for (i = 0; i < datalen; ++i, ++cp) { 977 if ((i % 32) == 8) 978 (void)printf("\n\t"); 979 (void)printf("%x ", *cp); 980 } 981 break; 982 } 983 } 984 } 985 } else { 986 /* 987 * We've got something other than an ECHOREPLY. 988 * See if it's a reply to something that we sent. 989 * We can compare IP destination, protocol, 990 * and ICMP type and ID. 991 * 992 * Only print all the error messages if we are running 993 * as root to avoid leaking information not normally 994 * available to those not running as root. 995 */ 996#ifndef icmp_data 997 struct ip *oip = &icp->icmp_ip; 998#else 999 struct ip *oip = (struct ip *)icp->icmp_data; 1000#endif 1001 struct icmp *oicmp = (struct icmp *)(oip + 1); 1002 1003 if (((options & F_VERBOSE) && uid == 0) || 1004 (!(options & F_QUIET2) && 1005 (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) && 1006 (oip->ip_p == IPPROTO_ICMP) && 1007 (oicmp->icmp_type == ICMP_ECHO) && 1008 (oicmp->icmp_id == ident))) { 1009 (void)printf("%d bytes from %s: ", cc, 1010 pr_addr(from->sin_addr)); 1011 pr_icmph(icp); 1012 } else 1013 return; 1014 } 1015 1016 /* Display any IP options */ 1017 cp = (u_char *)buf + sizeof(struct ip); 1018 1019 for (; hlen > (int)sizeof(struct ip); --hlen, ++cp) 1020 switch (*cp) { 1021 case IPOPT_EOL: 1022 hlen = 0; 1023 break; 1024 case IPOPT_LSRR: 1025 case IPOPT_SSRR: 1026 (void)printf(*cp == IPOPT_LSRR ? 1027 "\nLSRR: " : "\nSSRR: "); 1028 j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1; 1029 hlen -= 2; 1030 cp += 2; 1031 if (j >= INADDR_LEN && 1032 j <= hlen - (int)sizeof(struct ip)) { 1033 for (;;) { 1034 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1035 if (ina.s_addr == 0) 1036 (void)printf("\t0.0.0.0"); 1037 else 1038 (void)printf("\t%s", 1039 pr_addr(ina)); 1040 hlen -= INADDR_LEN; 1041 cp += INADDR_LEN - 1; 1042 j -= INADDR_LEN; 1043 if (j < INADDR_LEN) 1044 break; 1045 (void)putchar('\n'); 1046 } 1047 } else 1048 (void)printf("\t(truncated route)\n"); 1049 break; 1050 case IPOPT_RR: 1051 j = cp[IPOPT_OLEN]; /* get length */ 1052 i = cp[IPOPT_OFFSET]; /* and pointer */ 1053 hlen -= 2; 1054 cp += 2; 1055 if (i > j) 1056 i = j; 1057 i = i - IPOPT_MINOFF + 1; 1058 if (i < 0 || i > (hlen - (int)sizeof(struct ip))) { 1059 old_rrlen = 0; 1060 continue; 1061 } 1062 if (i == old_rrlen 1063 && !bcmp((char *)cp, old_rr, i) 1064 && !(options & F_FLOOD)) { 1065 (void)printf("\t(same route)"); 1066 hlen -= i; 1067 cp += i; 1068 break; 1069 } 1070 old_rrlen = i; 1071 bcopy((char *)cp, old_rr, i); 1072 (void)printf("\nRR: "); 1073 if (i >= INADDR_LEN && 1074 i <= hlen - (int)sizeof(struct ip)) { 1075 for (;;) { 1076 bcopy(++cp, &ina.s_addr, INADDR_LEN); 1077 if (ina.s_addr == 0) 1078 (void)printf("\t0.0.0.0"); 1079 else 1080 (void)printf("\t%s", 1081 pr_addr(ina)); 1082 hlen -= INADDR_LEN; 1083 cp += INADDR_LEN - 1; 1084 i -= INADDR_LEN; 1085 if (i < INADDR_LEN) 1086 break; 1087 (void)putchar('\n'); 1088 } 1089 } else 1090 (void)printf("\t(truncated route)"); 1091 break; 1092 case IPOPT_NOP: 1093 (void)printf("\nNOP"); 1094 break; 1095 default: 1096 (void)printf("\nunknown option %x", *cp); 1097 break; 1098 } 1099 if (!(options & F_FLOOD)) { 1100 (void)putchar('\n'); 1101 (void)fflush(stdout); 1102 } 1103} 1104 1105/* 1106 * in_cksum -- 1107 * Checksum routine for Internet Protocol family headers (C Version) 1108 */ 1109u_short 1110in_cksum(addr, len) 1111 u_short *addr; 1112 int len; 1113{ 1114 int nleft, sum; 1115 u_short *w; 1116 union { 1117 u_short us; 1118 u_char uc[2]; 1119 } last; 1120 u_short answer; 1121 1122 nleft = len; 1123 sum = 0; 1124 w = addr; 1125 1126 /* 1127 * Our algorithm is simple, using a 32 bit accumulator (sum), we add 1128 * sequential 16 bit words to it, and at the end, fold back all the 1129 * carry bits from the top 16 bits into the lower 16 bits. 1130 */ 1131 while (nleft > 1) { 1132 sum += *w++; 1133 nleft -= 2; 1134 } 1135 1136 /* mop up an odd byte, if necessary */ 1137 if (nleft == 1) { 1138 last.uc[0] = *(u_char *)w; 1139 last.uc[1] = 0; 1140 sum += last.us; 1141 } 1142 1143 /* add back carry outs from top 16 bits to low 16 bits */ 1144 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ 1145 sum += (sum >> 16); /* add carry */ 1146 answer = ~sum; /* truncate to 16 bits */ 1147 return(answer); 1148} 1149 1150/* 1151 * tvsub -- 1152 * Subtract 2 timeval structs: out = out - in. Out is assumed to 1153 * be >= in. 1154 */ 1155static void 1156tvsub(out, in) 1157 struct timeval *out, *in; 1158{ 1159 1160 if ((out->tv_usec -= in->tv_usec) < 0) { 1161 --out->tv_sec; 1162 out->tv_usec += 1000000; 1163 } 1164 out->tv_sec -= in->tv_sec; 1165} 1166 1167/* 1168 * status -- 1169 * Print out statistics when SIGINFO is received. 1170 */ 1171 1172static void 1173status(sig) 1174 int sig __unused; 1175{ 1176 1177 siginfo_p = 1; 1178} 1179 1180static void 1181check_status() 1182{ 1183 1184 if (siginfo_p) { 1185 siginfo_p = 0; 1186 (void)fprintf(stderr, 1187 "\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n", 1188 nreceived, ntransmitted, 1189 ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0, 1190 nreceived ? tmin : 0.0, 1191 nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum, 1192 tmax); 1193 } 1194} 1195 1196/* 1197 * finish -- 1198 * Print out statistics, and give up. 1199 */ 1200static void 1201finish() 1202{ 1203 struct termios ts; 1204 1205 (void)signal(SIGINT, SIG_IGN); 1206 (void)signal(SIGALRM, SIG_IGN); 1207 (void)putchar('\n'); 1208 (void)fflush(stdout); 1209 (void)printf("--- %s ping statistics ---\n", hostname); 1210 (void)printf("%ld packets transmitted, ", ntransmitted); 1211 (void)printf("%ld packets received, ", nreceived); 1212 if (nrepeats) 1213 (void)printf("+%ld duplicates, ", nrepeats); 1214 if (ntransmitted) { 1215 if (nreceived > ntransmitted) 1216 (void)printf("-- somebody's printing up packets!"); 1217 else 1218 (void)printf("%d%% packet loss", 1219 (int)(((ntransmitted - nreceived) * 100) / 1220 ntransmitted)); 1221 } 1222 (void)putchar('\n'); 1223 if (nreceived && timing) { 1224 double n = nreceived + nrepeats; 1225 double avg = tsum / n; 1226 double vari = tsumsq / n - avg * avg; 1227 (void)printf( 1228 "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n", 1229 tmin, avg, tmax, sqrt(vari)); 1230 } 1231 if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) { 1232 ts.c_lflag &= ~NOKERNINFO; 1233 tcsetattr(STDOUT_FILENO, TCSANOW, &ts); 1234 } 1235 1236 if (nreceived) 1237 exit(0); 1238 else 1239 exit(2); 1240} 1241 1242#ifdef notdef 1243static char *ttab[] = { 1244 "Echo Reply", /* ip + seq + udata */ 1245 "Dest Unreachable", /* net, host, proto, port, frag, sr + IP */ 1246 "Source Quench", /* IP */ 1247 "Redirect", /* redirect type, gateway, + IP */ 1248 "Echo", 1249 "Time Exceeded", /* transit, frag reassem + IP */ 1250 "Parameter Problem", /* pointer + IP */ 1251 "Timestamp", /* id + seq + three timestamps */ 1252 "Timestamp Reply", /* " */ 1253 "Info Request", /* id + sq */ 1254 "Info Reply" /* " */ 1255}; 1256#endif 1257 1258/* 1259 * pr_icmph -- 1260 * Print a descriptive string about an ICMP header. 1261 */ 1262static void 1263pr_icmph(icp) 1264 struct icmp *icp; 1265{ 1266 1267 switch(icp->icmp_type) { 1268 case ICMP_ECHOREPLY: 1269 (void)printf("Echo Reply\n"); 1270 /* XXX ID + Seq + Data */ 1271 break; 1272 case ICMP_UNREACH: 1273 switch(icp->icmp_code) { 1274 case ICMP_UNREACH_NET: 1275 (void)printf("Destination Net Unreachable\n"); 1276 break; 1277 case ICMP_UNREACH_HOST: 1278 (void)printf("Destination Host Unreachable\n"); 1279 break; 1280 case ICMP_UNREACH_PROTOCOL: 1281 (void)printf("Destination Protocol Unreachable\n"); 1282 break; 1283 case ICMP_UNREACH_PORT: 1284 (void)printf("Destination Port Unreachable\n"); 1285 break; 1286 case ICMP_UNREACH_NEEDFRAG: 1287 (void)printf("frag needed and DF set (MTU %d)\n", 1288 ntohs(icp->icmp_nextmtu)); 1289 break; 1290 case ICMP_UNREACH_SRCFAIL: 1291 (void)printf("Source Route Failed\n"); 1292 break; 1293 case ICMP_UNREACH_FILTER_PROHIB: 1294 (void)printf("Communication prohibited by filter\n"); 1295 break; 1296 default: 1297 (void)printf("Dest Unreachable, Bad Code: %d\n", 1298 icp->icmp_code); 1299 break; 1300 } 1301 /* Print returned IP header information */ 1302#ifndef icmp_data 1303 pr_retip(&icp->icmp_ip); 1304#else 1305 pr_retip((struct ip *)icp->icmp_data); 1306#endif 1307 break; 1308 case ICMP_SOURCEQUENCH: 1309 (void)printf("Source Quench\n"); 1310#ifndef icmp_data 1311 pr_retip(&icp->icmp_ip); 1312#else 1313 pr_retip((struct ip *)icp->icmp_data); 1314#endif 1315 break; 1316 case ICMP_REDIRECT: 1317 switch(icp->icmp_code) { 1318 case ICMP_REDIRECT_NET: 1319 (void)printf("Redirect Network"); 1320 break; 1321 case ICMP_REDIRECT_HOST: 1322 (void)printf("Redirect Host"); 1323 break; 1324 case ICMP_REDIRECT_TOSNET: 1325 (void)printf("Redirect Type of Service and Network"); 1326 break; 1327 case ICMP_REDIRECT_TOSHOST: 1328 (void)printf("Redirect Type of Service and Host"); 1329 break; 1330 default: 1331 (void)printf("Redirect, Bad Code: %d", icp->icmp_code); 1332 break; 1333 } 1334 (void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr)); 1335#ifndef icmp_data 1336 pr_retip(&icp->icmp_ip); 1337#else 1338 pr_retip((struct ip *)icp->icmp_data); 1339#endif 1340 break; 1341 case ICMP_ECHO: 1342 (void)printf("Echo Request\n"); 1343 /* XXX ID + Seq + Data */ 1344 break; 1345 case ICMP_TIMXCEED: 1346 switch(icp->icmp_code) { 1347 case ICMP_TIMXCEED_INTRANS: 1348 (void)printf("Time to live exceeded\n"); 1349 break; 1350 case ICMP_TIMXCEED_REASS: 1351 (void)printf("Frag reassembly time exceeded\n"); 1352 break; 1353 default: 1354 (void)printf("Time exceeded, Bad Code: %d\n", 1355 icp->icmp_code); 1356 break; 1357 } 1358#ifndef icmp_data 1359 pr_retip(&icp->icmp_ip); 1360#else 1361 pr_retip((struct ip *)icp->icmp_data); 1362#endif 1363 break; 1364 case ICMP_PARAMPROB: 1365 (void)printf("Parameter problem: pointer = 0x%02x\n", 1366 icp->icmp_hun.ih_pptr); 1367#ifndef icmp_data 1368 pr_retip(&icp->icmp_ip); 1369#else 1370 pr_retip((struct ip *)icp->icmp_data); 1371#endif 1372 break; 1373 case ICMP_TSTAMP: 1374 (void)printf("Timestamp\n"); 1375 /* XXX ID + Seq + 3 timestamps */ 1376 break; 1377 case ICMP_TSTAMPREPLY: 1378 (void)printf("Timestamp Reply\n"); 1379 /* XXX ID + Seq + 3 timestamps */ 1380 break; 1381 case ICMP_IREQ: 1382 (void)printf("Information Request\n"); 1383 /* XXX ID + Seq */ 1384 break; 1385 case ICMP_IREQREPLY: 1386 (void)printf("Information Reply\n"); 1387 /* XXX ID + Seq */ 1388 break; 1389 case ICMP_MASKREQ: 1390 (void)printf("Address Mask Request\n"); 1391 break; 1392 case ICMP_MASKREPLY: 1393 (void)printf("Address Mask Reply\n"); 1394 break; 1395 case ICMP_ROUTERADVERT: 1396 (void)printf("Router Advertisement\n"); 1397 break; 1398 case ICMP_ROUTERSOLICIT: 1399 (void)printf("Router Solicitation\n"); 1400 break; 1401 default: 1402 (void)printf("Bad ICMP type: %d\n", icp->icmp_type); 1403 } 1404} 1405 1406/* 1407 * pr_iph -- 1408 * Print an IP header with options. 1409 */ 1410static void 1411pr_iph(ip) 1412 struct ip *ip; 1413{ 1414 u_char *cp; 1415 int hlen; 1416 1417 hlen = ip->ip_hl << 2; 1418 cp = (u_char *)ip + 20; /* point to options */ 1419 1420 (void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst\n"); 1421 (void)printf(" %1x %1x %02x %04x %04x", 1422 ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len), 1423 ntohs(ip->ip_id)); 1424 (void)printf(" %1lx %04lx", 1425 (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13, 1426 (u_long) ntohl(ip->ip_off) & 0x1fff); 1427 (void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, 1428 ntohs(ip->ip_sum)); 1429 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr)); 1430 (void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr)); 1431 /* dump any option bytes */ 1432 while (hlen-- > 20) { 1433 (void)printf("%02x", *cp++); 1434 } 1435 (void)putchar('\n'); 1436} 1437 1438/* 1439 * pr_addr -- 1440 * Return an ascii host address as a dotted quad and optionally with 1441 * a hostname. 1442 */ 1443static char * 1444pr_addr(ina) 1445 struct in_addr ina; 1446{ 1447 struct hostent *hp; 1448 static char buf[16 + 3 + MAXHOSTNAMELEN]; 1449 1450 if ((options & F_NUMERIC) || 1451 !(hp = gethostbyaddr((char *)&ina, 4, AF_INET))) 1452 return inet_ntoa(ina); 1453 else 1454 (void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name, 1455 inet_ntoa(ina)); 1456 return(buf); 1457} 1458 1459/* 1460 * pr_retip -- 1461 * Dump some info on a returned (via ICMP) IP packet. 1462 */ 1463static void 1464pr_retip(ip) 1465 struct ip *ip; 1466{ 1467 u_char *cp; 1468 int hlen; 1469 1470 pr_iph(ip); 1471 hlen = ip->ip_hl << 2; 1472 cp = (u_char *)ip + hlen; 1473 1474 if (ip->ip_p == 6) 1475 (void)printf("TCP: from port %u, to port %u (decimal)\n", 1476 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1477 else if (ip->ip_p == 17) 1478 (void)printf("UDP: from port %u, to port %u (decimal)\n", 1479 (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); 1480} 1481 1482static void 1483fill(bp, patp) 1484 char *bp, *patp; 1485{ 1486 char *cp; 1487 int pat[16]; 1488 u_int ii, jj, kk; 1489 1490 for (cp = patp; *cp; cp++) { 1491 if (!isxdigit(*cp)) 1492 errx(EX_USAGE, 1493 "patterns must be specified as hex digits"); 1494 1495 } 1496 ii = sscanf(patp, 1497 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", 1498 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], 1499 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], 1500 &pat[13], &pat[14], &pat[15]); 1501 1502 if (ii > 0) 1503 for (kk = 0; kk <= maxpayload - (PHDR_LEN + ii); kk += ii) 1504 for (jj = 0; jj < ii; ++jj) 1505 bp[jj + kk] = pat[jj]; 1506 if (!(options & F_QUIET)) { 1507 (void)printf("PATTERN: 0x"); 1508 for (jj = 0; jj < ii; ++jj) 1509 (void)printf("%02x", bp[jj] & 0xFF); 1510 (void)printf("\n"); 1511 } 1512} 1513 1514static void 1515usage() 1516{ 1517 (void)fprintf(stderr, "%s\n%s\n%s\n", 1518"usage: ping [-ADQRadfnoqrv] [-c count] [-i wait] [-l preload] [-m ttl]", 1519" [-p pattern] " 1520#ifdef IPSEC 1521#ifdef IPSEC_POLICY_IPSEC 1522"[-P policy] " 1523#endif 1524#endif 1525"[-s packetsize] [-S src_addr] [-t timeout]", 1526" [-z tos ] [host | [-L] [-I iface] [-T ttl] mcast-group]"); 1527 exit(EX_USAGE); 1528} 1529