Home | History | Annotate | Line # | Download | only in ping
ping.c revision 1.53
      1 /*	$NetBSD: ping.c,v 1.53 1999/07/04 15:24:35 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.53 1999/07/04 15:24:35 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, "ipsec policy cannot be configured");
    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 #if 0
    560 		warnx("ipsec is not configured");
    561 #else
    562 		/* ignore it, should be okay */
    563 #endif
    564 	}
    565 	free(buf);
    566     }
    567 #else
    568     {
    569 	int optval;
    570 	if (pingflags & F_AUTHHDR) {
    571 		optval = IPSEC_LEVEL_REQUIRE;
    572 #ifdef IP_AUTH_TRANS_LEVEL
    573 		(void)setsockopt(s, IPPROTO_IP, IP_AUTH_TRANS_LEVEL,
    574 			(char *)&optval, sizeof(optval));
    575 #else
    576 		(void)setsockopt(s, IPPROTO_IP, IP_AUTH_LEVEL,
    577 			(char *)&optval, sizeof(optval));
    578 #endif
    579 	}
    580 	if (pingflags & F_ENCRYPT) {
    581 		optval = IPSEC_LEVEL_REQUIRE;
    582 		(void)setsockopt(s, IPPROTO_IP, IP_ESP_TRANS_LEVEL,
    583 			(char *)&optval, sizeof(optval));
    584 	}
    585 	optval = IPSEC_LEVEL_BYPASS;
    586 #ifdef IP_AUTH_TRANS_LEVEL
    587 	(void)setsockopt(sloop, IPPROTO_IP, IP_AUTH_TRANS_LEVEL,
    588 		(char *)&optval, sizeof(optval));
    589 #else
    590 	(void)setsockopt(sloop, IPPROTO_IP, IP_AUTH_LEVEL,
    591 		(char *)&optval, sizeof(optval));
    592 #endif
    593 	(void)setsockopt(sloop, IPPROTO_IP, IP_ESP_TRANS_LEVEL,
    594 		(char *)&optval, sizeof(optval));
    595     }
    596 #endif /*IPSEC_POLICY_IPSEC*/
    597 #endif /*IPSEC*/
    598 
    599 	(void)printf("PING %s (%s): %d data bytes\n", hostname,
    600 		     inet_ntoa(whereto.sin_addr), datalen);
    601 
    602 	/* When pinging the broadcast address, you can get a lot
    603 	 * of answers.  Doing something so evil is useful if you
    604 	 * are trying to stress the ethernet, or just want to
    605 	 * fill the arp cache to get some stuff for /etc/ethers.
    606 	 */
    607 	while (0 > setsockopt(s, SOL_SOCKET, SO_RCVBUF,
    608 			      (char*)&bufspace, sizeof(bufspace))) {
    609 		if ((bufspace -= 4096) == 0)
    610 			err(1, "Cannot set the receive buffer size");
    611 	}
    612 
    613 	/* make it possible to send giant probes, but do not worry now
    614 	 * if it fails, since we probably won't send giant probes.
    615 	 */
    616 	(void)setsockopt(s, SOL_SOCKET, SO_SNDBUF,
    617 			 (char*)&bufspace, sizeof(bufspace));
    618 
    619 	(void)signal(SIGINT, prefinish);
    620 
    621 #if defined(SIGINFO) && defined(NOKERNINFO)
    622 	if (tcgetattr (0, &ts) != -1) {
    623 		reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
    624 		ts.c_lflag |= NOKERNINFO;
    625 		tcsetattr (STDIN_FILENO, TCSANOW, &ts);
    626 	}
    627 #endif
    628 
    629 #ifdef SIGINFO
    630 	(void)signal(SIGINFO, prtsig);
    631 #else
    632 	(void)signal(SIGQUIT, prtsig);
    633 #endif
    634 	(void)signal(SIGCONT, prtsig);
    635 
    636 	/* fire off them quickies */
    637 	for (i = 0; i < preload; i++) {
    638 		(void)gettimeofday(&now, 0);
    639 		pinger();
    640 	}
    641 
    642 	doit();
    643 	return 0;
    644 }
    645 
    646 
    647 static void
    648 doit(void)
    649 {
    650 	int cc;
    651 	struct sockaddr_in from;
    652 	int fromlen;
    653 	double sec, last, d_last;
    654 	struct timeval timeout;
    655 	fd_set fdmask;
    656 
    657 
    658 	(void)gettimeofday(&clear_cache,0);
    659 	if (maxwait != 0) {
    660 		last = timeval_to_sec(&clear_cache) + maxwait;
    661 		d_last = 0;
    662 	} else {
    663 		last = 0;
    664 		d_last = 365*24*60*60;
    665 	}
    666 
    667 	FD_ZERO(&fdmask);
    668 	do {
    669 		(void)gettimeofday(&now,0);
    670 
    671 		if (last != 0)
    672 			d_last = last - timeval_to_sec(&now);
    673 
    674 		if (ntransmitted < npackets && d_last > 0) {
    675 			/* send if within 100 usec or late for next packet */
    676 			sec = diffsec(&next_tx,&now);
    677 			if (sec <= 0.0001
    678 			    || (lastrcvd && (pingflags & F_FLOOD))) {
    679 				pinger();
    680 				sec = diffsec(&next_tx,&now);
    681 			}
    682 			if (sec < 0.0)
    683 				sec = 0.0;
    684 			if (d_last < sec)
    685 				sec = d_last;
    686 
    687 		} else {
    688 			/* For the last response, wait twice as long as the
    689 			 * worst case seen, or 10 times as long as the
    690 			 * maximum interpacket interval, whichever is longer.
    691 			 */
    692 			sec = MAX(2*tmax,10*interval) - diffsec(&now,&last_tx);
    693 			if (d_last < sec)
    694 				sec = d_last;
    695 			if (sec <= 0)
    696 				break;
    697 		}
    698 
    699 
    700 		sec_to_timeval(sec, &timeout);
    701 
    702 		FD_SET(s, &fdmask);
    703 		cc = select(s+1, &fdmask, 0, 0, &timeout);
    704 		if (cc <= 0) {
    705 			if (cc < 0) {
    706 				if (errno == EINTR)
    707 					continue;
    708 				jiggle_flush(1);
    709 				err(1, "select");
    710 			}
    711 			continue;
    712 		}
    713 
    714 		fromlen  = sizeof(from);
    715 		cc = recvfrom(s, (char *) packet, packlen,
    716 			      0, (struct sockaddr *)&from,
    717 			      &fromlen);
    718 		if (cc < 0) {
    719 			if (errno != EINTR) {
    720 				jiggle_flush(1);
    721 				warn("recvfrom");
    722 				(void)fflush(stderr);
    723 			}
    724 			continue;
    725 		}
    726 		(void)gettimeofday(&now, 0);
    727 		pr_pack(packet, cc, &from);
    728 
    729 	} while (nreceived < npackets
    730 		 && (nreceived == 0 || !(pingflags & F_ONCE)));
    731 
    732 	finish(0);
    733 }
    734 
    735 
    736 static void
    737 jiggle_flush(int nl)			/* new line if there are dots */
    738 {
    739 	int serrno = errno;
    740 
    741 	if (jiggle_cnt > 0) {
    742 		total_jiggled += jiggle_cnt;
    743 		jiggle_direction = 1;
    744 		do {
    745 			(void)putchar('.');
    746 		} while (--jiggle_cnt > 0);
    747 
    748 	} else if (jiggle_cnt < 0) {
    749 		total_jiggled -= jiggle_cnt;
    750 		jiggle_direction = -1;
    751 		do {
    752 			(void)putchar('\b');
    753 		} while (++jiggle_cnt < 0);
    754 	}
    755 
    756 	if (nl) {
    757 		if (total_jiggled != 0)
    758 			(void)putchar('\n');
    759 		total_jiggled = 0;
    760 		jiggle_direction = -1;
    761 	}
    762 
    763 	(void)fflush(stdout);
    764 	(void)fflush(stderr);
    765 	jiggle_time = now;
    766 	errno = serrno;
    767 }
    768 
    769 
    770 /* jiggle the cursor for flood-ping
    771  */
    772 static void
    773 jiggle(int delta)
    774 {
    775 	double dt;
    776 
    777 	if (pingflags & F_QUIET)
    778 		return;
    779 
    780 	/* do not back up into messages */
    781 	if (total_jiggled+jiggle_cnt+delta < 0)
    782 		return;
    783 
    784 	jiggle_cnt += delta;
    785 
    786 	/* flush the FLOOD dots when things are quiet
    787 	 * or occassionally to make the cursor jiggle.
    788 	 */
    789 	dt = diffsec(&last_tx, &jiggle_time);
    790 	if (dt > 0.2 || (dt >= 0.15 && delta*jiggle_direction < 0))
    791 		jiggle_flush(0);
    792 }
    793 
    794 
    795 /*
    796  * Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
    797  * will be added on by the kernel.  The ID field is our UNIX process ID,
    798  * and the sequence number is an ascending integer.  The first PHDR_LEN bytes
    799  * of the data portion are used to hold a UNIX "timeval" struct in VAX
    800  * byte-order, to compute the round-trip time.
    801  */
    802 static void
    803 pinger(void)
    804 {
    805 	int i, cc, sw;
    806 
    807 	opack_icmp.icmp_code = 0;
    808 	opack_icmp.icmp_seq = htons((u_short)(ntransmitted));
    809 
    810 	/* clear the cached route in the kernel after an ICMP
    811 	 * response such as a Redirect is seen to stop causing
    812 	 * more such packets.  Also clear the cached route
    813 	 * periodically in case of routing changes that make
    814 	 * black holes come and go.
    815 	 */
    816 	if (clear_cache.tv_sec != now.tv_sec) {
    817 		opack_icmp.icmp_type = ICMP_ECHOREPLY;
    818 		opack_icmp.icmp_id = ~ident;
    819 		opack_icmp.icmp_cksum = 0;
    820 		opack_icmp.icmp_cksum = in_cksum((u_short*)&opack_icmp,
    821 						 PHDR_LEN);
    822 		sw = 0;
    823 		if (setsockopt(sloop,IPPROTO_IP,IP_HDRINCL,
    824 			       (char *)&sw,sizeof(sw)) < 0)
    825 			err(1, "Can't turn off special IP header");
    826 		if (sendto(sloop, (char *) &opack_icmp, PHDR_LEN, MSG_DONTROUTE,
    827 			   (struct sockaddr *)&loc_addr,
    828 			   sizeof(struct sockaddr_in)) < 0) {
    829 			/*
    830 			 * XXX: we only report this as a warning in verbose
    831 			 * mode because people get confused when they see
    832 			 * this error when they are running in single user
    833 			 * mode and they have not configured lo0
    834 			 */
    835 			if (pingflags & F_VERBOSE)
    836 				warn("failed to clear cached route");
    837 		}
    838 		sw = 1;
    839 		if (setsockopt(sloop,IPPROTO_IP,IP_HDRINCL,
    840 			       (char *)&sw, sizeof(sw)) < 0)
    841 			err(1, "Can't set special IP header");
    842 
    843 		(void)gettimeofday(&clear_cache,0);
    844 	}
    845 
    846 	opack_icmp.icmp_type = ICMP_ECHO;
    847 	opack_icmp.icmp_id = ident;
    848 	if (pingflags & F_TIMING)
    849 		(void) memcpy(&opack_icmp.icmp_data[0], &now, sizeof(now));
    850 	cc = datalen+PHDR_LEN;
    851 	opack_icmp.icmp_cksum = 0;
    852 	opack_icmp.icmp_cksum = in_cksum((u_short*)&opack_icmp, cc);
    853 
    854 	cc += opack_ip->ip_hl<<2;
    855 	opack_ip->ip_len = cc;
    856 	i = sendto(s, (char *) opack_ip, cc, 0,
    857 		   (struct sockaddr *)&send_addr, sizeof(struct sockaddr_in));
    858 	if (i != cc) {
    859 		jiggle_flush(1);
    860 		if (i < 0)
    861 			warn("sendto");
    862 		else
    863 			warnx("wrote %s %d chars, ret=%d", hostname, cc, i);
    864 		(void)fflush(stderr);
    865 	}
    866 	lastrcvd = 0;
    867 
    868 	CLR(ntransmitted);
    869 	ntransmitted++;
    870 
    871 	last_tx = now;
    872 	if (next_tx.tv_sec == 0) {
    873 		first_tx = now;
    874 		next_tx = now;
    875 	}
    876 
    877 	/* Transmit regularly, at always the same microsecond in the
    878 	 * second when going at one packet per second.
    879 	 * If we are at most 100 ms behind, send extras to get caught up.
    880 	 * Otherwise, skip packets we were too slow to send.
    881 	 */
    882 	if (diffsec(&next_tx, &now) <= interval) {
    883 		do {
    884 			timevaladd(&next_tx, &interval_tv);
    885 		} while (diffsec(&next_tx, &now) < -0.1);
    886 	}
    887 
    888 	if (pingflags & F_FLOOD)
    889 		jiggle(1);
    890 
    891 	/* While the packet is going out, ready buffer for the next
    892 	 * packet. Use a fast but not very good random number generator.
    893 	 */
    894 	if (pingflags & F_PING_RANDOM)
    895 		rnd_fill();
    896 }
    897 
    898 
    899 static void
    900 pr_pack_sub(int cc,
    901 	    char *addr,
    902 	    int seqno,
    903 	    int dupflag,
    904 	    int ttl,
    905 	    double triptime)
    906 {
    907 	jiggle_flush(1);
    908 
    909 	if (pingflags & F_FLOOD)
    910 		return;
    911 
    912 	(void)printf("%d bytes from %s: icmp_seq=%u", cc, addr, seqno);
    913 	if (dupflag)
    914 		(void)printf(" DUP!");
    915 	(void)printf(" ttl=%d", ttl);
    916 	if (pingflags & F_TIMING)
    917 		(void)printf(" time=%.3f ms", triptime*1000.0);
    918 
    919 	/*
    920 	 * Send beep to stderr, since that's more likely than stdout
    921 	 * to go to a terminal..
    922 	 */
    923 	if (pingflags & F_AUDIBLE && !dupflag)
    924 		(void)fprintf(stderr,"\a");
    925 }
    926 
    927 
    928 /*
    929  * Print out the packet, if it came from us.  This logic is necessary
    930  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
    931  * which arrive ('tis only fair).  This permits multiple copies of this
    932  * program to be run without having intermingled output (or statistics!).
    933  */
    934 static void
    935 pr_pack(u_char *buf,
    936 	int tot_len,
    937 	struct sockaddr_in *from)
    938 {
    939 	struct ip *ip;
    940 	struct icmp *icp;
    941 	int i, j, net_len;
    942 	u_char *cp;
    943 	static int old_rrlen;
    944 	static char old_rr[MAX_IPOPTLEN];
    945 	int hlen, dupflag = 0, dumped;
    946 	double triptime = 0.0;
    947 #define PR_PACK_SUB() {if (!dumped) {			\
    948 	dumped = 1;					\
    949 	pr_pack_sub(net_len, inet_ntoa(from->sin_addr),	\
    950 		    ntohs((u_short)icp->icmp_seq),	\
    951 		    dupflag, ip->ip_ttl, triptime);}}
    952 
    953 	/* Check the IP header */
    954 	ip = (struct ip *) buf;
    955 	hlen = ip->ip_hl << 2;
    956 	if (tot_len < hlen + ICMP_MINLEN) {
    957 		if (pingflags & F_VERBOSE) {
    958 			jiggle_flush(1);
    959 			(void)printf("packet too short (%d bytes) from %s\n",
    960 				     tot_len, inet_ntoa(from->sin_addr));
    961 		}
    962 		return;
    963 	}
    964 
    965 	/* Now the ICMP part */
    966 	dumped = 0;
    967 	net_len = tot_len - hlen;
    968 	icp = (struct icmp *)(buf + hlen);
    969 	if (icp->icmp_type == ICMP_ECHOREPLY
    970 	    && icp->icmp_id == ident) {
    971 		if (icp->icmp_seq == htons((u_short)(ntransmitted-1)))
    972 			lastrcvd = 1;
    973 		last_rx = now;
    974 		if (first_rx.tv_sec == 0)
    975 			first_rx = last_rx;
    976 		nreceived++;
    977 		if (pingflags & F_TIMING) {
    978 			struct timeval tv;
    979 			(void) memcpy(&tv, icp->icmp_data, sizeof(tv));
    980 			triptime = diffsec(&last_rx, &tv);
    981 			tsum += triptime;
    982 			tsumsq += triptime * triptime;
    983 			if (triptime < tmin)
    984 				tmin = triptime;
    985 			if (triptime > tmax)
    986 				tmax = triptime;
    987 		}
    988 
    989 		if (TST(ntohs((u_short)icp->icmp_seq))) {
    990 			nrepeats++, nreceived--;
    991 			dupflag=1;
    992 		} else {
    993 			SET(ntohs((u_short)icp->icmp_seq));
    994 		}
    995 
    996 		if (tot_len != opack_ip->ip_len) {
    997 			PR_PACK_SUB();
    998 			(void)printf("\nwrong total length %d instead of %d",
    999 				     tot_len, opack_ip->ip_len);
   1000 		}
   1001 
   1002 		if (pingflags & F_QUIET)
   1003 			return;
   1004 
   1005 		if (!(pingflags & F_FLOOD))
   1006 			PR_PACK_SUB();
   1007 
   1008 		/* check the data */
   1009 		if (datalen > PHDR_LEN
   1010 		    && !(pingflags & F_PING_RANDOM)
   1011 		    && memcmp(&icp->icmp_data[PHDR_LEN],
   1012 			    &opack_icmp.icmp_data[PHDR_LEN],
   1013 			    datalen-PHDR_LEN)) {
   1014 			for (i=PHDR_LEN; i<datalen; i++) {
   1015 				if (icp->icmp_data[PHDR_LEN+i]
   1016 				    != opack_icmp.icmp_data[PHDR_LEN+i])
   1017 					break;
   1018 			}
   1019 			PR_PACK_SUB();
   1020 			(void)printf("\nwrong data byte #%d should have been"
   1021 				     " %#x but was %#x",
   1022 				     i, (u_char)opack_icmp.icmp_data[i],
   1023 				     (u_char)icp->icmp_data[i]);
   1024 			for (i=PHDR_LEN; i<datalen; i++) {
   1025 				if ((i%16) == PHDR_LEN)
   1026 					(void)printf("\n\t");
   1027 				(void)printf("%2x ",(u_char)icp->icmp_data[i]);
   1028 			}
   1029 		}
   1030 
   1031 	} else {
   1032 		if (!pr_icmph(icp, from, net_len))
   1033 			return;
   1034 		dumped = 2;
   1035 	}
   1036 
   1037 	/* Display any IP options */
   1038 	cp = buf + sizeof(struct ip);
   1039 	while (hlen > (int)sizeof(struct ip)) {
   1040 		switch (*cp) {
   1041 		case IPOPT_EOL:
   1042 			hlen = 0;
   1043 			break;
   1044 		case IPOPT_LSRR:
   1045 			hlen -= 2;
   1046 			j = *++cp;
   1047 			++cp;
   1048 			j -= IPOPT_MINOFF;
   1049 			if (j <= 0)
   1050 				continue;
   1051 			if (dumped <= 1) {
   1052 				j = ((j+3)/4)*4;
   1053 				hlen -= j;
   1054 				cp += j;
   1055 				break;
   1056 			}
   1057 			PR_PACK_SUB();
   1058 			(void)printf("\nLSRR: ");
   1059 			for (;;) {
   1060 				pr_saddr("\t%s", cp);
   1061 				cp += 4;
   1062 				hlen -= 4;
   1063 				j -= 4;
   1064 				if (j <= 0)
   1065 					break;
   1066 				(void)putchar('\n');
   1067 			}
   1068 			break;
   1069 		case IPOPT_RR:
   1070 			j = *++cp;	/* get length */
   1071 			i = *++cp;	/* and pointer */
   1072 			hlen -= 2;
   1073 			if (i > j)
   1074 				i = j;
   1075 			i -= IPOPT_MINOFF;
   1076 			if (i <= 0)
   1077 				continue;
   1078 			if (dumped <= 1) {
   1079 				if (i == old_rrlen
   1080 				    && !memcmp(cp, old_rr, i)) {
   1081 					if (dumped)
   1082 					    (void)printf("\t(same route)");
   1083 					j = ((i+3)/4)*4;
   1084 					hlen -= j;
   1085 					cp += j;
   1086 					break;
   1087 				}
   1088 				old_rrlen = i;
   1089 				(void) memcpy(old_rr, cp, i);
   1090 			}
   1091 			if (!dumped) {
   1092 				jiggle_flush(1);
   1093 				(void)printf("RR: ");
   1094 				dumped = 1;
   1095 			} else {
   1096 				(void)printf("\nRR: ");
   1097 			}
   1098 			for (;;) {
   1099 				pr_saddr("\t%s", cp);
   1100 				cp += 4;
   1101 				hlen -= 4;
   1102 				i -= 4;
   1103 				if (i <= 0)
   1104 					break;
   1105 				(void)putchar('\n');
   1106 			}
   1107 			break;
   1108 		case IPOPT_NOP:
   1109 			if (dumped <= 1)
   1110 				break;
   1111 			PR_PACK_SUB();
   1112 			(void)printf("\nNOP");
   1113 			break;
   1114 #ifdef sgi
   1115 		case IPOPT_SECURITY:	/* RFC 1108 RIPSO BSO */
   1116 		case IPOPT_ESO:		/* RFC 1108 RIPSO ESO */
   1117 		case IPOPT_CIPSO:	/* Commercial IPSO */
   1118 			if ((sysconf(_SC_IP_SECOPTS)) > 0) {
   1119 				i = (unsigned)cp[1];
   1120 				hlen -= i - 1;
   1121 				PR_PACK_SUB();
   1122 				(void)printf("\nSEC:");
   1123 				while (i--) {
   1124 					(void)printf(" %02x", *cp++);
   1125 				}
   1126 				cp--;
   1127 				break;
   1128 			}
   1129 #endif
   1130 		default:
   1131 			PR_PACK_SUB();
   1132 			(void)printf("\nunknown option 0x%x", *cp);
   1133 			break;
   1134 		}
   1135 		hlen--;
   1136 		cp++;
   1137 	}
   1138 
   1139 	if (dumped) {
   1140 		(void)putchar('\n');
   1141 		(void)fflush(stdout);
   1142 	} else {
   1143 		jiggle(-1);
   1144 	}
   1145 }
   1146 
   1147 
   1148 /* Compute the IP checksum
   1149  *	This assumes the packet is less than 32K long.
   1150  */
   1151 static u_short
   1152 in_cksum(u_short *p,
   1153 	 u_int len)
   1154 {
   1155 	u_int sum = 0;
   1156 	int nwords = len >> 1;
   1157 
   1158 	while (nwords-- != 0)
   1159 		sum += *p++;
   1160 
   1161 	if (len & 1) {
   1162 		union {
   1163 			u_short w;
   1164 			u_char c[2];
   1165 		} u;
   1166 		u.c[0] = *(u_char *)p;
   1167 		u.c[1] = 0;
   1168 		sum += u.w;
   1169 	}
   1170 
   1171 	/* end-around-carry */
   1172 	sum = (sum >> 16) + (sum & 0xffff);
   1173 	sum += (sum >> 16);
   1174 	return (~sum);
   1175 }
   1176 
   1177 
   1178 /*
   1179  * compute the difference of two timevals in seconds
   1180  */
   1181 static double
   1182 diffsec(struct timeval *now,
   1183 	struct timeval *then)
   1184 {
   1185 	return ((now->tv_sec - then->tv_sec)*1.0
   1186 		+ (now->tv_usec - then->tv_usec)/1000000.0);
   1187 }
   1188 
   1189 
   1190 static void
   1191 timevaladd(struct timeval *t1,
   1192 	   struct timeval *t2)
   1193 {
   1194 
   1195 	t1->tv_sec += t2->tv_sec;
   1196 	if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
   1197 		t1->tv_sec++;
   1198 		t1->tv_usec -= 1000000;
   1199 	}
   1200 }
   1201 
   1202 
   1203 static void
   1204 sec_to_timeval(const double sec, struct timeval *tp)
   1205 {
   1206 	tp->tv_sec = sec;
   1207 	tp->tv_usec = (sec - tp->tv_sec) * 1000000.0;
   1208 }
   1209 
   1210 
   1211 static double
   1212 timeval_to_sec(const struct timeval *tp)
   1213 {
   1214 	return tp->tv_sec + tp->tv_usec / 1000000.0;
   1215 }
   1216 
   1217 
   1218 /*
   1219  * Print statistics.
   1220  * Heavily buffered STDIO is used here, so that all the statistics
   1221  * will be written with 1 sys-write call.  This is nice when more
   1222  * than one copy of the program is running on a terminal;  it prevents
   1223  * the statistics output from becomming intermingled.
   1224  */
   1225 static void
   1226 summary(int header)
   1227 {
   1228 	jiggle_flush(1);
   1229 
   1230 	if (header)
   1231 		(void)printf("\n----%s PING Statistics----\n", hostname);
   1232 	(void)printf("%d packets transmitted, ", ntransmitted);
   1233 	(void)printf("%d packets received, ", nreceived);
   1234 	if (nrepeats)
   1235 		(void)printf("+%d duplicates, ", nrepeats);
   1236 	if (ntransmitted) {
   1237 		if (nreceived > ntransmitted)
   1238 			(void)printf("-- somebody's printing up packets!");
   1239 		else
   1240 			(void)printf("%.1f%% packet loss",
   1241 				     (((ntransmitted-nreceived)*100.0) /
   1242 					    ntransmitted));
   1243 	}
   1244 	(void)printf("\n");
   1245 	if (nreceived && (pingflags & F_TIMING)) {
   1246 		double n = nreceived + nrepeats;
   1247 		double avg = (tsum / n);
   1248 		double variance = 0.0;
   1249 		if (n>1)
   1250 			variance = (tsumsq - n*avg*avg) /(n-1);
   1251 
   1252 		printf("round-trip min/avg/max/stddev = "
   1253 			"%.3f/%.3f/%.3f/%.3f ms\n",
   1254 			tmin * 1000.0, avg * 1000.0,
   1255 			tmax * 1000.0, sqrt(variance) * 1000.0);
   1256 		if (pingflags & F_FLOOD) {
   1257 			double r = diffsec(&last_rx, &first_rx);
   1258 			double t = diffsec(&last_tx, &first_tx);
   1259 			if (r == 0)
   1260 				r = 0.0001;
   1261 			if (t == 0)
   1262 				t = 0.0001;
   1263 			(void)printf("  %.1f packets/sec sent, "
   1264 				     " %.1f packets/sec received\n",
   1265 				     ntransmitted/t, nreceived/r);
   1266 		}
   1267 	}
   1268 }
   1269 
   1270 
   1271 /*
   1272  * Print statistics when SIGINFO is received.
   1273  */
   1274 /* ARGSUSED */
   1275 static void
   1276 prtsig(int s)
   1277 {
   1278 	summary(0);
   1279 #ifdef SIGINFO
   1280 	(void)signal(SIGINFO, prtsig);
   1281 #else
   1282 	(void)signal(SIGQUIT, prtsig);
   1283 #endif
   1284 }
   1285 
   1286 
   1287 /*
   1288  * On the first SIGINT, allow any outstanding packets to dribble in
   1289  */
   1290 static void
   1291 prefinish(int s)
   1292 {
   1293 	if (lastrcvd			/* quit now if caught up */
   1294 	    || nreceived == 0)		/* or if remote is dead */
   1295 		finish(0);
   1296 
   1297 	(void)signal(s, finish);	/* do this only the 1st time */
   1298 
   1299 	if (npackets > ntransmitted)	/* let the normal limit work */
   1300 		npackets = ntransmitted;
   1301 }
   1302 
   1303 
   1304 /*
   1305  * Print statistics and give up.
   1306  */
   1307 /* ARGSUSED */
   1308 static void
   1309 finish(int s)
   1310 {
   1311 #if defined(SIGINFO) && defined(NOKERNINFO)
   1312 	struct termios ts;
   1313 
   1314 	if (reset_kerninfo && tcgetattr (0, &ts) != -1) {
   1315 		ts.c_lflag &= ~NOKERNINFO;
   1316 		tcsetattr (STDIN_FILENO, TCSANOW, &ts);
   1317 	}
   1318 	(void)signal(SIGINFO, SIG_IGN);
   1319 #else
   1320 	(void)signal(SIGQUIT, SIG_DFL);
   1321 #endif
   1322 
   1323 	summary(1);
   1324 	exit(nreceived > 0 ? 0 : 2);
   1325 }
   1326 
   1327 
   1328 static int				/* 0=do not print it */
   1329 ck_pr_icmph(struct icmp *icp,
   1330 	    struct sockaddr_in *from,
   1331 	    int cc,
   1332 	    int override)		/* 1=override VERBOSE if interesting */
   1333 {
   1334 	int	hlen;
   1335 	struct ip ipb, *ip = &ipb;
   1336 	struct icmp icp2b, *icp2 = &icp2b;
   1337 	int res;
   1338 
   1339 	if (pingflags & F_VERBOSE) {
   1340 		res = 1;
   1341 		jiggle_flush(1);
   1342 	} else {
   1343 		res = 0;
   1344 	}
   1345 
   1346 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
   1347 	hlen = ip->ip_hl << 2;
   1348 	if (ip->ip_p == IPPROTO_ICMP
   1349 	    && hlen + 6 <= cc) {
   1350 		(void) memcpy(icp2, &icp->icmp_data[hlen], sizeof(*icp2));
   1351 		if (icp2->icmp_id == ident) {
   1352 			/* remember to clear route cached in kernel
   1353 			 * if this non-Echo-Reply ICMP message was for one
   1354 			 * of our packets.
   1355 			 */
   1356 			clear_cache.tv_sec = 0;
   1357 
   1358 			if (!res && override
   1359 			    && (pingflags & (F_QUIET|F_SEMI_QUIET)) == 0) {
   1360 				jiggle_flush(1);
   1361 				(void)printf("%d bytes from %s: ",
   1362 					     cc, pr_addr(&from->sin_addr));
   1363 				res = 1;
   1364 			}
   1365 		}
   1366 	}
   1367 
   1368 	return res;
   1369 }
   1370 
   1371 
   1372 /*
   1373  *  Print a descriptive string about an ICMP header other than an echo reply.
   1374  */
   1375 static int				/* 0=printed nothing */
   1376 pr_icmph(struct icmp *icp,
   1377 	 struct sockaddr_in *from,
   1378 	 int cc)
   1379 {
   1380 	switch (icp->icmp_type ) {
   1381 	case ICMP_UNREACH:
   1382 		if (!ck_pr_icmph(icp, from, cc, 1))
   1383 			return 0;
   1384 		switch (icp->icmp_code) {
   1385 		case ICMP_UNREACH_NET:
   1386 			(void)printf("Destination Net Unreachable");
   1387 			break;
   1388 		case ICMP_UNREACH_HOST:
   1389 			(void)printf("Destination Host Unreachable");
   1390 			break;
   1391 		case ICMP_UNREACH_PROTOCOL:
   1392 			(void)printf("Destination Protocol Unreachable");
   1393 			break;
   1394 		case ICMP_UNREACH_PORT:
   1395 			(void)printf("Destination Port Unreachable");
   1396 			break;
   1397 		case ICMP_UNREACH_NEEDFRAG:
   1398 			(void)printf("frag needed and DF set.  Next MTU=%d",
   1399 			       ntohs(icp->icmp_nextmtu));
   1400 			break;
   1401 		case ICMP_UNREACH_SRCFAIL:
   1402 			(void)printf("Source Route Failed");
   1403 			break;
   1404 		case ICMP_UNREACH_NET_UNKNOWN:
   1405 			(void)printf("Unreachable unknown net");
   1406 			break;
   1407 		case ICMP_UNREACH_HOST_UNKNOWN:
   1408 			(void)printf("Unreachable unknown host");
   1409 			break;
   1410 		case ICMP_UNREACH_ISOLATED:
   1411 			(void)printf("Unreachable host isolated");
   1412 			break;
   1413 		case ICMP_UNREACH_NET_PROHIB:
   1414 			(void)printf("Net prohibited access");
   1415 			break;
   1416 		case ICMP_UNREACH_HOST_PROHIB:
   1417 			(void)printf("Host prohibited access");
   1418 			break;
   1419 		case ICMP_UNREACH_TOSNET:
   1420 			(void)printf("Bad TOS for net");
   1421 			break;
   1422 		case ICMP_UNREACH_TOSHOST:
   1423 			(void)printf("Bad TOS for host");
   1424 			break;
   1425 		case 13:
   1426 			(void)printf("Communication prohibited");
   1427 			break;
   1428 		case 14:
   1429 			(void)printf("Host precedence violation");
   1430 			break;
   1431 		case 15:
   1432 			(void)printf("Precedence cutoff");
   1433 			break;
   1434 		default:
   1435 			(void)printf("Bad Destination Unreachable Code: %d",
   1436 				     icp->icmp_code);
   1437 			break;
   1438 		}
   1439 		/* Print returned IP header information */
   1440 		pr_retip(icp, cc);
   1441 		break;
   1442 
   1443 	case ICMP_SOURCEQUENCH:
   1444 		if (!ck_pr_icmph(icp, from, cc, 1))
   1445 			return 0;
   1446 		(void)printf("Source Quench");
   1447 		pr_retip(icp, cc);
   1448 		break;
   1449 
   1450 	case ICMP_REDIRECT:
   1451 		if (!ck_pr_icmph(icp, from, cc, 1))
   1452 			return 0;
   1453 		switch (icp->icmp_code) {
   1454 		case ICMP_REDIRECT_NET:
   1455 			(void)printf("Redirect Network");
   1456 			break;
   1457 		case ICMP_REDIRECT_HOST:
   1458 			(void)printf("Redirect Host");
   1459 			break;
   1460 		case ICMP_REDIRECT_TOSNET:
   1461 			(void)printf("Redirect Type of Service and Network");
   1462 			break;
   1463 		case ICMP_REDIRECT_TOSHOST:
   1464 			(void)printf("Redirect Type of Service and Host");
   1465 			break;
   1466 		default:
   1467 			(void)printf("Redirect--Bad Code: %d", icp->icmp_code);
   1468 			break;
   1469 		}
   1470 		(void)printf(" New router addr: %s",
   1471 			     pr_addr(&icp->icmp_hun.ih_gwaddr));
   1472 		pr_retip(icp, cc);
   1473 		break;
   1474 
   1475 	case ICMP_ECHO:
   1476 		if (!ck_pr_icmph(icp, from, cc, 0))
   1477 			return 0;
   1478 		(void)printf("Echo Request: ID=%d seq=%d",
   1479 			     ntohs(icp->icmp_id), ntohs(icp->icmp_seq));
   1480 		break;
   1481 
   1482 	case ICMP_ECHOREPLY:
   1483 		/* displaying other's pings is too noisey */
   1484 #if 0
   1485 		if (!ck_pr_icmph(icp, from, cc, 0))
   1486 			return 0;
   1487 		(void)printf("Echo Reply: ID=%d seq=%d",
   1488 			     ntohs(icp->icmp_id), ntohs(icp->icmp_seq));
   1489 		break;
   1490 #else
   1491 		return 0;
   1492 #endif
   1493 
   1494 	case ICMP_ROUTERADVERT:
   1495 		if (!ck_pr_icmph(icp, from, cc, 0))
   1496 			return 0;
   1497 		(void)printf("Router Discovery Advert");
   1498 		break;
   1499 
   1500 	case ICMP_ROUTERSOLICIT:
   1501 		if (!ck_pr_icmph(icp, from, cc, 0))
   1502 			return 0;
   1503 		(void)printf("Router Discovery Solicit");
   1504 		break;
   1505 
   1506 	case ICMP_TIMXCEED:
   1507 		if (!ck_pr_icmph(icp, from, cc, 1))
   1508 			return 0;
   1509 		switch (icp->icmp_code ) {
   1510 		case ICMP_TIMXCEED_INTRANS:
   1511 			(void)printf("Time To Live exceeded");
   1512 			break;
   1513 		case ICMP_TIMXCEED_REASS:
   1514 			(void)printf("Frag reassembly time exceeded");
   1515 			break;
   1516 		default:
   1517 			(void)printf("Time exceeded, Bad Code: %d",
   1518 				     icp->icmp_code);
   1519 			break;
   1520 		}
   1521 		pr_retip(icp, cc);
   1522 		break;
   1523 
   1524 	case ICMP_PARAMPROB:
   1525 		if (!ck_pr_icmph(icp, from, cc, 1))
   1526 			return 0;
   1527 		(void)printf("Parameter problem: pointer = 0x%02x",
   1528 			     icp->icmp_hun.ih_pptr);
   1529 		pr_retip(icp, cc);
   1530 		break;
   1531 
   1532 	case ICMP_TSTAMP:
   1533 		if (!ck_pr_icmph(icp, from, cc, 0))
   1534 			return 0;
   1535 		(void)printf("Timestamp");
   1536 		break;
   1537 
   1538 	case ICMP_TSTAMPREPLY:
   1539 		if (!ck_pr_icmph(icp, from, cc, 0))
   1540 			return 0;
   1541 		(void)printf("Timestamp Reply");
   1542 		break;
   1543 
   1544 	case ICMP_IREQ:
   1545 		if (!ck_pr_icmph(icp, from, cc, 0))
   1546 			return 0;
   1547 		(void)printf("Information Request");
   1548 		break;
   1549 
   1550 	case ICMP_IREQREPLY:
   1551 		if (!ck_pr_icmph(icp, from, cc, 0))
   1552 			return 0;
   1553 		(void)printf("Information Reply");
   1554 		break;
   1555 
   1556 	case ICMP_MASKREQ:
   1557 		if (!ck_pr_icmph(icp, from, cc, 0))
   1558 			return 0;
   1559 		(void)printf("Address Mask Request");
   1560 		break;
   1561 
   1562 	case ICMP_MASKREPLY:
   1563 		if (!ck_pr_icmph(icp, from, cc, 0))
   1564 			return 0;
   1565 		(void)printf("Address Mask Reply");
   1566 		break;
   1567 
   1568 	default:
   1569 		if (!ck_pr_icmph(icp, from, cc, 0))
   1570 			return 0;
   1571 		(void)printf("Bad ICMP type: %d", icp->icmp_type);
   1572 		if (pingflags & F_VERBOSE)
   1573 			pr_iph(icp, cc);
   1574 	}
   1575 
   1576 	return 1;
   1577 }
   1578 
   1579 
   1580 /*
   1581  *  Print an IP header with options.
   1582  */
   1583 static void
   1584 pr_iph(struct icmp *icp,
   1585        int cc)
   1586 {
   1587 	int	hlen;
   1588 	u_char	*cp;
   1589 	struct ip ipb, *ip = &ipb;
   1590 
   1591 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
   1592 
   1593 	hlen = ip->ip_hl << 2;
   1594 	cp = (u_char *) &icp->icmp_data[20];	/* point to options */
   1595 
   1596 	(void)printf("\n Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src	     Dst\n");
   1597 	(void)printf("  %1x  %1x  %02x %04x %04x",
   1598 		     ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
   1599 	(void)printf("   %1x %04x",
   1600 		     ((ip->ip_off)&0xe000)>>13, (ip->ip_off)&0x1fff);
   1601 	(void)printf("  %02x  %02x %04x",
   1602 		     ip->ip_ttl, ip->ip_p, ip->ip_sum);
   1603 	(void)printf(" %15s ",
   1604 		     inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
   1605 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
   1606 	/* dump any option bytes */
   1607 	while (hlen-- > 20 && cp < (u_char*)icp+cc) {
   1608 		(void)printf("%02x", *cp++);
   1609 	}
   1610 }
   1611 
   1612 /*
   1613  * Print an ASCII host address starting from a string of bytes.
   1614  */
   1615 static void
   1616 pr_saddr(char *pat,
   1617 	 u_char *cp)
   1618 {
   1619 	n_long l;
   1620 	struct in_addr addr;
   1621 
   1622 	l = (u_char)*++cp;
   1623 	l = (l<<8) + (u_char)*++cp;
   1624 	l = (l<<8) + (u_char)*++cp;
   1625 	l = (l<<8) + (u_char)*++cp;
   1626 	addr.s_addr = htonl(l);
   1627 	(void)printf(pat, (l == 0) ? "0.0.0.0" : pr_addr(&addr));
   1628 }
   1629 
   1630 
   1631 /*
   1632  *  Return an ASCII host address
   1633  *  as a dotted quad and optionally with a hostname
   1634  */
   1635 static char *
   1636 pr_addr(struct in_addr *addr)		/* in network order */
   1637 {
   1638 	struct	hostent	*hp;
   1639 	static	char buf[MAXHOSTNAMELEN+4+16+1];
   1640 
   1641 	if ((pingflags & F_NUMERIC)
   1642 	    || !(hp = gethostbyaddr((char *)addr, sizeof(*addr), AF_INET))) {
   1643 		(void)snprintf(buf, sizeof(buf), "%s", inet_ntoa(*addr));
   1644 	} else {
   1645 		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
   1646 		    inet_ntoa(*addr));
   1647 	}
   1648 
   1649 	return buf;
   1650 }
   1651 
   1652 /*
   1653  *  Dump some info on a returned (via ICMP) IP packet.
   1654  */
   1655 static void
   1656 pr_retip(struct icmp *icp,
   1657 	 int cc)
   1658 {
   1659 	int	hlen;
   1660 	u_char	*cp;
   1661 	struct ip ipb, *ip = &ipb;
   1662 
   1663 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
   1664 
   1665 	if (pingflags & F_VERBOSE)
   1666 		pr_iph(icp, cc);
   1667 
   1668 	hlen = ip->ip_hl << 2;
   1669 	cp = (u_char *) &icp->icmp_data[hlen];
   1670 
   1671 	if (ip->ip_p == IPPROTO_TCP) {
   1672 		if (pingflags & F_VERBOSE)
   1673 			(void)printf("\n  TCP: from port %u, to port %u",
   1674 				     (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3)));
   1675 	} else if (ip->ip_p == IPPROTO_UDP) {
   1676 		if (pingflags & F_VERBOSE)
   1677 			(void)printf("\n  UDP: from port %u, to port %u",
   1678 				     (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3)));
   1679 	} else if (ip->ip_p == IPPROTO_ICMP) {
   1680 		struct icmp icp2;
   1681 		(void) memcpy(&icp2, cp, sizeof(icp2));
   1682 		if (icp2.icmp_type == ICMP_ECHO) {
   1683 			if (pingflags & F_VERBOSE)
   1684 				(void)printf("\n  ID=%u icmp_seq=%u",
   1685 					     ntohs((u_short)icp2.icmp_id),
   1686 					     ntohs((u_short)icp2.icmp_seq));
   1687 			else
   1688 				(void)printf(" for icmp_seq=%u",
   1689 					     ntohs((u_short)icp2.icmp_seq));
   1690 		}
   1691 	}
   1692 }
   1693 
   1694 static void
   1695 fill(void)
   1696 {
   1697 	int i, j, k;
   1698 	char *cp;
   1699 	int pat[16];
   1700 
   1701 	for (cp = fill_pat; *cp != '\0'; cp++) {
   1702 		if (!isxdigit((unsigned char)*cp))
   1703 			break;
   1704 	}
   1705 	if (cp == fill_pat || *cp != '\0' || (cp-fill_pat) > 16*2) {
   1706 		(void)fflush(stdout);
   1707 		errx(1, "\"-p %s\": patterns must be specified with"
   1708 		     " 1-32 hex digits\n",
   1709 		     fill_pat);
   1710 	}
   1711 
   1712 	i = sscanf(fill_pat,
   1713 		   "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
   1714 		    &pat[0], &pat[1], &pat[2], &pat[3],
   1715 		    &pat[4], &pat[5], &pat[6], &pat[7],
   1716 		    &pat[8], &pat[9], &pat[10], &pat[11],
   1717 		    &pat[12], &pat[13], &pat[14], &pat[15]);
   1718 
   1719 	for (k=PHDR_LEN, j = 0; k <= datalen; k++) {
   1720 		opack_icmp.icmp_data[k] = pat[j];
   1721 		if (++j >= i)
   1722 			j = 0;
   1723 	}
   1724 
   1725 	if (!(pingflags & F_QUIET)) {
   1726 		(void)printf("PATTERN: 0x");
   1727 		for (j=0; j<i; j++)
   1728 			(void)printf("%02x",
   1729 				     (u_char)opack_icmp.icmp_data[PHDR_LEN+j]);
   1730 		(void)printf("\n");
   1731 	}
   1732 
   1733 }
   1734 
   1735 
   1736 static void
   1737 rnd_fill(void)
   1738 {
   1739 	static u_int32_t rnd;
   1740 	int i;
   1741 
   1742 	for (i = PHDR_LEN; i < datalen; i++) {
   1743 		rnd = (3141592621U * rnd + 663896637U);
   1744 		opack_icmp.icmp_data[i] = rnd>>24;
   1745 	}
   1746 }
   1747 
   1748 
   1749 static void
   1750 gethost(const char *arg,
   1751 	const char *name,
   1752 	struct sockaddr_in *sa,
   1753 	char *realname,
   1754 	int realname_len)
   1755 {
   1756 	struct hostent *hp;
   1757 
   1758 	(void)memset(sa, 0, sizeof(*sa));
   1759 	sa->sin_family = AF_INET;
   1760 
   1761 	/* If it is an IP address, try to convert it to a name to
   1762 	 * have something nice to display.
   1763 	 */
   1764 	if (inet_aton(name, &sa->sin_addr) != 0) {
   1765 		if (realname) {
   1766 			if (pingflags & F_NUMERIC)
   1767 				hp = 0;
   1768 			else
   1769 				hp = gethostbyaddr((char *)&sa->sin_addr,
   1770 						   sizeof(sa->sin_addr),
   1771 						   AF_INET);
   1772 			(void)strncpy(realname, hp ? hp->h_name : name,
   1773 				      realname_len);
   1774 			realname[realname_len-1] = '\0';
   1775 		}
   1776 		return;
   1777 	}
   1778 
   1779 	hp = gethostbyname(name);
   1780 	if (!hp)
   1781 		errx(1, "Cannot resolve \"%s\" (%s)",name,hstrerror(h_errno));
   1782 
   1783 	if (hp->h_addrtype != AF_INET)
   1784 		errx(1, "%s only supported with IP", arg);
   1785 
   1786 	(void)memcpy(&sa->sin_addr, hp->h_addr, sizeof(sa->sin_addr));
   1787 
   1788 	if (realname) {
   1789 		(void)strncpy(realname, hp->h_name, realname_len);
   1790 		realname[realname_len-1] = '\0';
   1791 	}
   1792 }
   1793 
   1794 
   1795 static void
   1796 usage(void)
   1797 {
   1798 #ifdef IPSEC
   1799 #ifdef IPSEC_POLICY_IPSEC
   1800 #define IPSECOPT	"\n     [-E policy] "
   1801 #else
   1802 #define IPSECOPT	"\n     [-AE] "
   1803 #endif /*IPSEC_POLICY_IPSEC*/
   1804 #else
   1805 #define IPSECOPT	""
   1806 #endif /*IPSEC*/
   1807 
   1808 	(void)fprintf(stderr, "Usage: \n"
   1809 	    "%s [-dDfLnoPqQrRv] [-c count] [-g gateway] [-h host]"
   1810 	    " [-i interval] [-I addr]\n"
   1811 	    "     [-l preload] [-p pattern] [-s size] [-t tos] [-T ttl]"
   1812 	    " [-w maxwait] " IPSECOPT "host\n",
   1813 	    __progname);
   1814 	exit(1);
   1815 }
   1816