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