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