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