xref: /freebsd/sbin/ping/ping.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Mike Muuss.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1989, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
46 #endif
47 static const char rcsid[] =
48   "$FreeBSD$";
49 #endif /* not lint */
50 
51 /*
52  *			P I N G . C
53  *
54  * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
55  * measure round-trip-delays and packet loss across network paths.
56  *
57  * Author -
58  *	Mike Muuss
59  *	U. S. Army Ballistic Research Laboratory
60  *	December, 1983
61  *
62  * Status -
63  *	Public Domain.  Distribution Unlimited.
64  * Bugs -
65  *	More statistics could always be gathered.
66  *	This program has to run SUID to ROOT to access the ICMP socket.
67  */
68 
69 #include <sys/param.h>		/* NB: we rely on this for <sys/types.h> */
70 #include <sys/socket.h>
71 #include <sys/sysctl.h>
72 #include <sys/time.h>
73 #include <sys/uio.h>
74 
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_icmp.h>
79 #include <netinet/ip_var.h>
80 #include <arpa/inet.h>
81 
82 #ifdef IPSEC
83 #include <netinet6/ipsec.h>
84 #endif /*IPSEC*/
85 
86 #include <ctype.h>
87 #include <err.h>
88 #include <errno.h>
89 #include <math.h>
90 #include <netdb.h>
91 #include <signal.h>
92 #include <stdio.h>
93 #include <stdlib.h>
94 #include <string.h>
95 #include <sysexits.h>
96 #include <termios.h>
97 #include <unistd.h>
98 
99 #define	INADDR_LEN	((int)sizeof(in_addr_t))
100 #define	TIMEVAL_LEN	((int)sizeof(struct timeval))
101 #define	MASK_LEN	(ICMP_MASKLEN - ICMP_MINLEN)
102 #define	TS_LEN		(ICMP_TSLEN - ICMP_MINLEN)
103 #define	DEFDATALEN	64		/* default data length */
104 #define	FLOOD_BACKOFF	20000		/* usecs to back off if F_FLOOD mode */
105 					/* runs out of buffer space */
106 #define	MAXIPLEN	(sizeof(struct ip) + MAX_IPOPTLEN)
107 #define	MAXICMPLEN	(ICMP_ADVLENMIN + MAX_IPOPTLEN)
108 #define	MINICMPLEN	ICMP_MINLEN
109 #define	MAXWAIT		10		/* max seconds to wait for response */
110 #define	MAXALARM	(60 * 60)	/* max seconds for alarm timeout */
111 #define	MAXTOS		255
112 
113 #define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
114 #define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
115 #define	SET(bit)	(A(bit) |= B(bit))
116 #define	CLR(bit)	(A(bit) &= (~B(bit)))
117 #define	TST(bit)	(A(bit) & B(bit))
118 
119 /* various options */
120 int options;
121 #define	F_FLOOD		0x0001
122 #define	F_INTERVAL	0x0002
123 #define	F_NUMERIC	0x0004
124 #define	F_PINGFILLED	0x0008
125 #define	F_QUIET		0x0010
126 #define	F_RROUTE	0x0020
127 #define	F_SO_DEBUG	0x0040
128 #define	F_SO_DONTROUTE	0x0080
129 #define	F_VERBOSE	0x0100
130 #define	F_QUIET2	0x0200
131 #define	F_NOLOOP	0x0400
132 #define	F_MTTL		0x0800
133 #define	F_MIF		0x1000
134 #define	F_AUDIBLE	0x2000
135 #ifdef IPSEC
136 #ifdef IPSEC_POLICY_IPSEC
137 #define F_POLICY	0x4000
138 #endif /*IPSEC_POLICY_IPSEC*/
139 #endif /*IPSEC*/
140 #define	F_TTL		0x8000
141 #define	F_MISSED	0x10000
142 #define	F_ONCE		0x20000
143 #define	F_HDRINCL	0x40000
144 #define	F_MASK		0x80000
145 #define	F_TIME		0x100000
146 
147 /*
148  * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
149  * number of received sequence numbers we can keep track of.  Change 128
150  * to 8192 for complete accuracy...
151  */
152 #define	MAX_DUP_CHK	(8 * 128)
153 int mx_dup_ck = MAX_DUP_CHK;
154 char rcvd_tbl[MAX_DUP_CHK / 8];
155 
156 struct sockaddr_in whereto;	/* who to ping */
157 long maxpayload;
158 int datalen = DEFDATALEN;
159 int s;				/* socket file descriptor */
160 u_char outpackhdr[IP_MAXPACKET], *outpack;
161 char BBELL = '\a';		/* characters written for MISSED and AUDIBLE */
162 char BSPACE = '\b';		/* characters written for flood */
163 char DOT = '.';
164 char *hostname;
165 char *shostname;
166 int ident;			/* process id to identify our packets */
167 int uid;			/* cached uid for micro-optimization */
168 u_char icmp_type = ICMP_ECHO;
169 u_char icmp_type_rsp = ICMP_ECHOREPLY;
170 int timeoffset = 0;
171 int phdr_len = 0;
172 
173 /* counters */
174 long nmissedmax;		/* max value of ntransmitted - nreceived - 1 */
175 long npackets;			/* max packets to transmit */
176 long nreceived;			/* # of packets we got back */
177 long nrepeats;			/* number of duplicates */
178 long ntransmitted;		/* sequence # for outbound packets = #sent */
179 int interval = 1000;		/* interval between packets, ms */
180 
181 /* timing */
182 int timing;			/* flag to do timing */
183 double tmin = 999999999.0;	/* minimum round trip time */
184 double tmax = 0.0;		/* maximum round trip time */
185 double tsum = 0.0;		/* sum of all times, for doing average */
186 double tsumsq = 0.0;		/* sum of all times squared, for std. dev. */
187 
188 volatile sig_atomic_t finish_up;  /* nonzero if we've been told to finish up */
189 int reset_kerninfo;
190 volatile sig_atomic_t siginfo_p;
191 
192 static void fill(char *, char *);
193 static u_short in_cksum(u_short *, int);
194 static void check_status(void);
195 static void finish(void) __dead2;
196 static void pinger(void);
197 static char *pr_addr(struct in_addr);
198 static char *pr_ntime(n_time);
199 static void pr_icmph(struct icmp *);
200 static void pr_iph(struct ip *);
201 static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
202 static void pr_retip(struct ip *);
203 static void status(int);
204 static void stopit(int);
205 static void tvsub(struct timeval *, struct timeval *);
206 static void usage(void) __dead2;
207 
208 int
209 main(argc, argv)
210 	int argc;
211 	char *const *argv;
212 {
213 	struct sockaddr_in from, sin;
214 	struct in_addr ifaddr;
215 	struct timeval last, intvl;
216 	struct iovec iov;
217 	struct ip *ip;
218 	struct msghdr msg;
219 	struct sigaction si_sa;
220 	struct termios ts;
221 	size_t sz;
222 	u_char *datap, packet[IP_MAXPACKET];
223 	char *ep, *source, *target, *payload;
224 	struct hostent *hp;
225 #ifdef IPSEC_POLICY_IPSEC
226 	char *policy_in, *policy_out;
227 #endif
228 	struct sockaddr_in *to;
229 	double t;
230 	u_long alarmtimeout, ultmp;
231 	int almost_done, ch, df, hold, i, mib[4], packlen, preload, sockerrno,
232 	    tos, ttl;
233 	char ctrl[CMSG_SPACE(sizeof(struct timeval))];
234 	char hnamebuf[MAXHOSTNAMELEN], snamebuf[MAXHOSTNAMELEN];
235 #ifdef IP_OPTIONS
236 	char rspace[MAX_IPOPTLEN];	/* record route space */
237 #endif
238 	unsigned char loop, mttl;
239 
240 	source = NULL;
241 #ifdef IPSEC_POLICY_IPSEC
242 	policy_in = policy_out = NULL;
243 #endif
244 
245 	/*
246 	 * Do the stuff that we need root priv's for *first*, and
247 	 * then drop our setuid bit.  Save error reporting for
248 	 * after arg parsing.
249 	 */
250 	s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
251 	sockerrno = errno;
252 
253 	setuid(getuid());
254 	uid = getuid();
255 
256 	alarmtimeout = df = preload = tos = 0;
257 
258 	outpack = outpackhdr + sizeof(struct ip);
259 	while ((ch = getopt(argc, argv,
260 		"Aac:DdfI:i:Ll:M:m:nop:QqRrS:s:T:t:vz:"
261 #ifdef IPSEC
262 #ifdef IPSEC_POLICY_IPSEC
263 		"P:"
264 #endif /*IPSEC_POLICY_IPSEC*/
265 #endif /*IPSEC*/
266 		)) != -1)
267 	{
268 		switch(ch) {
269 		case 'A':
270 			options |= F_MISSED;
271 			break;
272 		case 'a':
273 			options |= F_AUDIBLE;
274 			break;
275 		case 'c':
276 			ultmp = strtoul(optarg, &ep, 0);
277 			if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
278 				errx(EX_USAGE,
279 				    "invalid count of packets to transmit: `%s'",
280 				    optarg);
281 			npackets = ultmp;
282 			break;
283 		case 'D':
284 			options |= F_HDRINCL;
285 			df = 1;
286 			break;
287 		case 'd':
288 			options |= F_SO_DEBUG;
289 			break;
290 		case 'f':
291 			if (uid) {
292 				errno = EPERM;
293 				err(EX_NOPERM, "-f flag");
294 			}
295 			options |= F_FLOOD;
296 			setbuf(stdout, (char *)NULL);
297 			break;
298 		case 'I':		/* multicast interface */
299 			if (inet_aton(optarg, &ifaddr) == 0)
300 				errx(EX_USAGE,
301 				    "invalid multicast interface: `%s'",
302 				    optarg);
303 			options |= F_MIF;
304 			break;
305 		case 'i':		/* wait between sending packets */
306 			t = strtod(optarg, &ep) * 1000.0;
307 			if (*ep || ep == optarg || t > (double)INT_MAX)
308 				errx(EX_USAGE, "invalid timing interval: `%s'",
309 				    optarg);
310 			options |= F_INTERVAL;
311 			interval = (int)t;
312 			if (uid && interval < 1000) {
313 				errno = EPERM;
314 				err(EX_NOPERM, "-i interval too short");
315 			}
316 			break;
317 		case 'L':
318 			options |= F_NOLOOP;
319 			loop = 0;
320 			break;
321 		case 'l':
322 			ultmp = strtoul(optarg, &ep, 0);
323 			if (*ep || ep == optarg || ultmp > INT_MAX)
324 				errx(EX_USAGE,
325 				    "invalid preload value: `%s'", optarg);
326 			if (uid) {
327 				errno = EPERM;
328 				err(EX_NOPERM, "-l flag");
329 			}
330 			preload = ultmp;
331 			break;
332 		case 'M':
333 			switch(optarg[0]) {
334 			case 'M':
335 			case 'm':
336 				options |= F_MASK;
337 				break;
338 			case 'T':
339 			case 't':
340 				options |= F_TIME;
341 				break;
342 			default:
343 				errx(EX_USAGE, "invalid message: `%c'", optarg[0]);
344 				break;
345 			}
346 			break;
347 		case 'm':		/* TTL */
348 			ultmp = strtoul(optarg, &ep, 0);
349 			if (*ep || ep == optarg || ultmp > MAXTTL)
350 				errx(EX_USAGE, "invalid TTL: `%s'", optarg);
351 			ttl = ultmp;
352 			options |= F_TTL;
353 			break;
354 		case 'n':
355 			options |= F_NUMERIC;
356 			break;
357 		case 'o':
358 			options |= F_ONCE;
359 			break;
360 #ifdef IPSEC
361 #ifdef IPSEC_POLICY_IPSEC
362 		case 'P':
363 			options |= F_POLICY;
364 			if (!strncmp("in", optarg, 2))
365 				policy_in = strdup(optarg);
366 			else if (!strncmp("out", optarg, 3))
367 				policy_out = strdup(optarg);
368 			else
369 				errx(1, "invalid security policy");
370 			break;
371 #endif /*IPSEC_POLICY_IPSEC*/
372 #endif /*IPSEC*/
373 		case 'p':		/* fill buffer with user pattern */
374 			options |= F_PINGFILLED;
375 			payload = optarg;
376 			break;
377 		case 'Q':
378 			options |= F_QUIET2;
379 			break;
380 		case 'q':
381 			options |= F_QUIET;
382 			break;
383 		case 'R':
384 			options |= F_RROUTE;
385 			break;
386 		case 'r':
387 			options |= F_SO_DONTROUTE;
388 			break;
389 		case 'S':
390 			source = optarg;
391 			break;
392 		case 's':		/* size of packet to send */
393 			ultmp = strtoul(optarg, &ep, 0);
394 			if (*ep || ep == optarg)
395 				errx(EX_USAGE, "invalid packet size: `%s'",
396 				    optarg);
397 			if (uid != 0 && ultmp > DEFDATALEN) {
398 				errno = EPERM;
399 				err(EX_NOPERM,
400 				    "packet size too large: %lu > %u",
401 				    ultmp, DEFDATALEN);
402 			}
403 			datalen = ultmp;
404 			break;
405 		case 'T':		/* multicast TTL */
406 			ultmp = strtoul(optarg, &ep, 0);
407 			if (*ep || ep == optarg || ultmp > MAXTTL)
408 				errx(EX_USAGE, "invalid multicast TTL: `%s'",
409 				    optarg);
410 			mttl = ultmp;
411 			options |= F_MTTL;
412 			break;
413 		case 't':
414 			alarmtimeout = strtoul(optarg, &ep, 0);
415 			if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
416 				errx(EX_USAGE, "invalid timeout: `%s'",
417 				    optarg);
418 			if (alarmtimeout > MAXALARM)
419 				errx(EX_USAGE, "invalid timeout: `%s' > %d",
420 				    optarg, MAXALARM);
421 			alarm((int)alarmtimeout);
422 			break;
423 		case 'v':
424 			options |= F_VERBOSE;
425 			break;
426 		case 'z':
427 			options |= F_HDRINCL;
428 			ultmp = strtoul(optarg, &ep, 0);
429 			if (*ep || ep == optarg || ultmp > MAXTOS)
430 				errx(EX_USAGE, "invalid TOS: `%s'", optarg);
431 			tos = ultmp;
432 			break;
433 		default:
434 			usage();
435 		}
436 	}
437 
438 	if (argc - optind != 1)
439 		usage();
440 	target = argv[optind];
441 
442 	maxpayload = IP_MAXPACKET - sizeof(struct ip) - MINICMPLEN;
443 	if (options & F_MASK) {
444 		icmp_type = ICMP_MASKREQ;
445 		icmp_type_rsp = ICMP_MASKREPLY;
446 		timeoffset = MASK_LEN;
447 		datalen -= MASK_LEN;
448 		phdr_len += MASK_LEN;
449 		if (!(options & F_QUIET))
450 			(void)printf("ICMP_MASKREQ\n");
451 	}
452 	if (options & F_TIME) {
453 		icmp_type = ICMP_TSTAMP;
454 		icmp_type_rsp = ICMP_TSTAMPREPLY;
455 		timeoffset = TS_LEN;
456 		datalen -= TS_LEN;
457 		phdr_len += TS_LEN;
458 		if (!(options & F_QUIET))
459 			(void)printf("ICMP_TSTAMP\n");
460 	}
461 	if (options & F_RROUTE)
462 		maxpayload -= MAX_IPOPTLEN;
463 	if (datalen > maxpayload)
464 		errx(EX_USAGE, "packet size too large: %lu > %u", datalen,
465 		    maxpayload);
466 	datap = &outpack[MINICMPLEN + phdr_len];
467 	if (options & F_PINGFILLED) {
468 		fill((char *)datap, payload);
469 	}
470 	if (source) {
471 		bzero((char *)&sin, sizeof(sin));
472 		sin.sin_family = AF_INET;
473 		if (inet_aton(source, &sin.sin_addr) != 0) {
474 			shostname = source;
475 		} else {
476 			hp = gethostbyname2(source, AF_INET);
477 			if (!hp)
478 				errx(EX_NOHOST, "cannot resolve %s: %s",
479 				    source, hstrerror(h_errno));
480 
481 			sin.sin_len = sizeof sin;
482 			if (hp->h_length > sizeof(sin.sin_addr) ||
483 			    hp->h_length < 0)
484 				errx(1, "gethostbyname2: illegal address");
485 			memcpy(&sin.sin_addr, hp->h_addr_list[0],
486 			    sizeof(sin.sin_addr));
487 			(void)strncpy(snamebuf, hp->h_name,
488 			    sizeof(snamebuf) - 1);
489 			snamebuf[sizeof(snamebuf) - 1] = '\0';
490 			shostname = snamebuf;
491 		}
492 		if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1)
493 			err(1, "bind");
494 	}
495 
496 	bzero(&whereto, sizeof(whereto));
497 	to = &whereto;
498 	to->sin_family = AF_INET;
499 	to->sin_len = sizeof *to;
500 	if (inet_aton(target, &to->sin_addr) != 0) {
501 		hostname = target;
502 	} else {
503 		hp = gethostbyname2(target, AF_INET);
504 		if (!hp)
505 			errx(EX_NOHOST, "cannot resolve %s: %s",
506 			    target, hstrerror(h_errno));
507 
508 		if (hp->h_length > sizeof(to->sin_addr))
509 			errx(1, "gethostbyname2 returned an illegal address");
510 		memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
511 		(void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
512 		hnamebuf[sizeof(hnamebuf) - 1] = '\0';
513 		hostname = hnamebuf;
514 	}
515 
516 	if (options & F_FLOOD && options & F_INTERVAL)
517 		errx(EX_USAGE, "-f and -i: incompatible options");
518 
519 	if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
520 		errx(EX_USAGE,
521 		    "-f flag cannot be used with multicast destination");
522 	if (options & (F_MIF | F_NOLOOP | F_MTTL)
523 	    && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
524 		errx(EX_USAGE,
525 		    "-I, -L, -T flags cannot be used with unicast destination");
526 
527 	if (datalen - TIMEVAL_LEN >= TIMEVAL_LEN) {	/* can we time transfer */
528 		datalen -= TIMEVAL_LEN;
529 		phdr_len += TIMEVAL_LEN;
530 		timing = 1;
531 	}
532 	packlen = MAXIPLEN + MAXICMPLEN + datalen;
533 	packlen = packlen > IP_MAXPACKET ? IP_MAXPACKET : packlen;
534 
535 	if (!(options & F_PINGFILLED))
536 		for (i = phdr_len; i < datalen; ++i)
537 			*datap++ = i;
538 
539 	ident = getpid() & 0xFFFF;
540 
541 	if (s < 0) {
542 		errno = sockerrno;
543 		err(EX_OSERR, "socket");
544 	}
545 	hold = 1;
546 	if (options & F_SO_DEBUG)
547 		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
548 		    sizeof(hold));
549 	if (options & F_SO_DONTROUTE)
550 		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
551 		    sizeof(hold));
552 #ifdef IPSEC
553 #ifdef IPSEC_POLICY_IPSEC
554 	if (options & F_POLICY) {
555 		char *buf;
556 		if (policy_in != NULL) {
557 			buf = ipsec_set_policy(policy_in, strlen(policy_in));
558 			if (buf == NULL)
559 				errx(EX_CONFIG, "%s", ipsec_strerror());
560 			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
561 					buf, ipsec_get_policylen(buf)) < 0)
562 				err(EX_CONFIG,
563 				    "ipsec policy cannot be configured");
564 			free(buf);
565 		}
566 
567 		if (policy_out != NULL) {
568 			buf = ipsec_set_policy(policy_out, strlen(policy_out));
569 			if (buf == NULL)
570 				errx(EX_CONFIG, "%s", ipsec_strerror());
571 			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
572 					buf, ipsec_get_policylen(buf)) < 0)
573 				err(EX_CONFIG,
574 				    "ipsec policy cannot be configured");
575 			free(buf);
576 		}
577 	}
578 #endif /*IPSEC_POLICY_IPSEC*/
579 #endif /*IPSEC*/
580 
581 	if (options & F_HDRINCL) {
582 		ip = (struct ip*)outpackhdr;
583 		if (!(options & (F_TTL | F_MTTL))) {
584 			mib[0] = CTL_NET;
585 			mib[1] = PF_INET;
586 			mib[2] = IPPROTO_IP;
587 			mib[3] = IPCTL_DEFTTL;
588 			sz = sizeof(ttl);
589 			if (sysctl(mib, 4, &ttl, &sz, NULL, 0) == -1)
590 				err(1, "sysctl(net.inet.ip.ttl)");
591 		}
592 		setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hold, sizeof(hold));
593 		ip->ip_v = IPVERSION;
594 		ip->ip_hl = sizeof(struct ip) >> 2;
595 		ip->ip_tos = tos;
596 		ip->ip_id = 0;
597 		ip->ip_off = df ? IP_DF : 0;
598 		ip->ip_ttl = ttl;
599 		ip->ip_p = IPPROTO_ICMP;
600 		ip->ip_src.s_addr = source ? sin.sin_addr.s_addr : INADDR_ANY;
601 		ip->ip_dst = to->sin_addr;
602         }
603 	/* record route option */
604 	if (options & F_RROUTE) {
605 #ifdef IP_OPTIONS
606 		bzero(rspace, sizeof(rspace));
607 		rspace[IPOPT_OPTVAL] = IPOPT_RR;
608 		rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
609 		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
610 		rspace[sizeof(rspace) - 1] = IPOPT_EOL;
611 		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
612 		    sizeof(rspace)) < 0)
613 			err(EX_OSERR, "setsockopt IP_OPTIONS");
614 #else
615 		errx(EX_UNAVAILABLE,
616 		    "record route not available in this implementation");
617 #endif /* IP_OPTIONS */
618 	}
619 
620 	if (options & F_TTL) {
621 		if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl,
622 		    sizeof(ttl)) < 0) {
623 			err(EX_OSERR, "setsockopt IP_TTL");
624 		}
625 	}
626 	if (options & F_NOLOOP) {
627 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
628 		    sizeof(loop)) < 0) {
629 			err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
630 		}
631 	}
632 	if (options & F_MTTL) {
633 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &mttl,
634 		    sizeof(mttl)) < 0) {
635 			err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
636 		}
637 	}
638 	if (options & F_MIF) {
639 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
640 		    sizeof(ifaddr)) < 0) {
641 			err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
642 		}
643 	}
644 #ifdef SO_TIMESTAMP
645 	{ int on = 1;
646 	if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
647 		err(EX_OSERR, "setsockopt SO_TIMESTAMP");
648 	}
649 #endif
650 
651 	/*
652 	 * When pinging the broadcast address, you can get a lot of answers.
653 	 * Doing something so evil is useful if you are trying to stress the
654 	 * ethernet, or just want to fill the arp cache to get some stuff for
655 	 * /etc/ethers.  But beware: RFC 1122 allows hosts to ignore broadcast
656 	 * or multicast pings if they wish.
657 	 */
658 
659 	/*
660 	 * XXX receive buffer needs undetermined space for mbuf overhead
661 	 * as well.
662 	 */
663 	hold = IP_MAXPACKET + 128;
664 	(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
665 	    sizeof(hold));
666 	if (uid == 0)
667 		(void)setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&hold,
668 		    sizeof(hold));
669 
670 	if (to->sin_family == AF_INET) {
671 		(void)printf("PING %s (%s)", hostname,
672 		    inet_ntoa(to->sin_addr));
673 		if (source)
674 			(void)printf(" from %s", shostname);
675 		(void)printf(": %d data bytes\n", datalen);
676 	} else
677 		(void)printf("PING %s: %d data bytes\n", hostname, datalen);
678 
679 	/*
680 	 * Use sigaction() instead of signal() to get unambiguous semantics,
681 	 * in particular with SA_RESTART not set.
682 	 */
683 
684 	sigemptyset(&si_sa.sa_mask);
685 	si_sa.sa_flags = 0;
686 
687 	si_sa.sa_handler = stopit;
688 	if (sigaction(SIGINT, &si_sa, 0) == -1) {
689 		err(EX_OSERR, "sigaction SIGINT");
690 	}
691 
692 	si_sa.sa_handler = status;
693 	if (sigaction(SIGINFO, &si_sa, 0) == -1) {
694 		err(EX_OSERR, "sigaction");
695 	}
696 
697         if (alarmtimeout > 0) {
698 		si_sa.sa_handler = stopit;
699 		if (sigaction(SIGALRM, &si_sa, 0) == -1)
700 			err(EX_OSERR, "sigaction SIGALRM");
701         }
702 
703 	bzero(&msg, sizeof(msg));
704 	msg.msg_name = (caddr_t)&from;
705 	msg.msg_iov = &iov;
706 	msg.msg_iovlen = 1;
707 #ifdef SO_TIMESTAMP
708 	msg.msg_control = (caddr_t)ctrl;
709 #endif
710 	iov.iov_base = packet;
711 	iov.iov_len = packlen;
712 
713 	if (tcgetattr(STDOUT_FILENO, &ts) != -1) {
714 		reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
715 		ts.c_lflag |= NOKERNINFO;
716 		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
717 	}
718 
719 	if (preload == 0)
720 		pinger();		/* send the first ping */
721 	else {
722 		if (npackets != 0 && preload > npackets)
723 			preload = npackets;
724 		while (preload--)	/* fire off them quickies */
725 			pinger();
726 	}
727 	(void)gettimeofday(&last, NULL);
728 
729 	if (options & F_FLOOD) {
730 		intvl.tv_sec = 0;
731 		intvl.tv_usec = 10000;
732 	} else {
733 		intvl.tv_sec = interval / 1000;
734 		intvl.tv_usec = interval % 1000 * 1000;
735 	}
736 
737 	almost_done = 0;
738 	while (!finish_up) {
739 		struct timeval now, timeout;
740 		fd_set rfds;
741 		int cc, n;
742 
743 		check_status();
744 		if (s >= FD_SETSIZE)
745 			errx(EX_OSERR, "descriptor too large");
746 		FD_ZERO(&rfds);
747 		FD_SET(s, &rfds);
748 		(void)gettimeofday(&now, NULL);
749 		timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
750 		timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
751 		while (timeout.tv_usec < 0) {
752 			timeout.tv_usec += 1000000;
753 			timeout.tv_sec--;
754 		}
755 		while (timeout.tv_usec >= 1000000) {
756 			timeout.tv_usec -= 1000000;
757 			timeout.tv_sec++;
758 		}
759 		if (timeout.tv_sec < 0)
760 			timeout.tv_sec = timeout.tv_usec = 0;
761 		n = select(s + 1, &rfds, NULL, NULL, &timeout);
762 		if (n < 0)
763 			continue;	/* Must be EINTR. */
764 		if (n == 1) {
765 			struct timeval *t = NULL;
766 #ifdef SO_TIMESTAMP
767 			struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
768 
769 			msg.msg_controllen = sizeof(ctrl);
770 #endif
771 			msg.msg_namelen = sizeof(from);
772 			if ((cc = recvmsg(s, &msg, 0)) < 0) {
773 				if (errno == EINTR)
774 					continue;
775 				warn("recvmsg");
776 				continue;
777 			}
778 #ifdef SO_TIMESTAMP
779 			if (cmsg->cmsg_level == SOL_SOCKET &&
780 			    cmsg->cmsg_type == SCM_TIMESTAMP &&
781 			    cmsg->cmsg_len == CMSG_LEN(sizeof *t)) {
782 				/* Copy to avoid alignment problems: */
783 				memcpy(&now, CMSG_DATA(cmsg), sizeof(now));
784 				t = &now;
785 			}
786 #endif
787 			if (t == NULL) {
788 				(void)gettimeofday(&now, NULL);
789 				t = &now;
790 			}
791 			pr_pack((char *)packet, cc, &from, t);
792 			if (options & F_ONCE && nreceived ||
793 			    npackets && nreceived >= npackets)
794 				break;
795 		}
796 		if (n == 0 || options & F_FLOOD) {
797 			if (!npackets || ntransmitted < npackets)
798 				pinger();
799 			else {
800 				if (almost_done)
801 					break;
802 				almost_done = 1;
803 				intvl.tv_usec = 0;
804 				if (nreceived) {
805 					intvl.tv_sec = 2 * tmax / 1000;
806 					if (!intvl.tv_sec)
807 						intvl.tv_sec = 1;
808 				} else
809 					intvl.tv_sec = MAXWAIT;
810 			}
811 			(void)gettimeofday(&last, NULL);
812 			if (ntransmitted - nreceived - 1 > nmissedmax) {
813 				nmissedmax = ntransmitted - nreceived - 1;
814 				if (options & F_MISSED)
815 					(void)write(STDOUT_FILENO, &BBELL, 1);
816 			}
817 		}
818 	}
819 	finish();
820 	/* NOTREACHED */
821 	exit(0);	/* Make the compiler happy */
822 }
823 
824 /*
825  * stopit --
826  *	Set the global bit that causes the main loop to quit.
827  * Do NOT call finish() from here, since finish() does far too much
828  * to be called from a signal handler.
829  */
830 void
831 stopit(sig)
832 	int sig __unused;
833 {
834 
835 	finish_up = 1;
836 }
837 
838 /*
839  * pinger --
840  *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
841  * will be added on by the kernel.  The ID field is our UNIX process ID,
842  * and the sequence number is an ascending integer.  The first TIMEVAL_LEN
843  * bytes of the data portion are used to hold a UNIX "timeval" struct in
844  * host byte-order, to compute the round-trip time.
845  */
846 static void
847 pinger(void)
848 {
849 	struct timeval now;
850 	struct ip *ip;
851 	struct icmp *icp;
852 	int cc, i;
853 	u_char *packet;
854 
855 	packet = outpack;
856 	icp = (struct icmp *)outpack;
857 	icp->icmp_type = icmp_type;
858 	icp->icmp_code = 0;
859 	icp->icmp_cksum = 0;
860 	icp->icmp_seq = htons(ntransmitted);
861 	icp->icmp_id = ident;			/* ID */
862 
863 	CLR(ntransmitted % mx_dup_ck);
864 
865 	if ((options & F_TIME) || timing) {
866 		(void)gettimeofday(&now, NULL);
867 
868 		if (options & F_TIME)
869 			icp->icmp_otime = htonl((now.tv_sec % (24*60*60))
870 				* 1000 + now.tv_usec / 1000);
871 		if (timing)
872 			bcopy((void *)&now, (void *)&outpack[MINICMPLEN + timeoffset],
873 				sizeof(struct timeval));
874 	}
875 
876 	cc = MINICMPLEN + datalen + timeoffset;
877 
878 	/* compute ICMP checksum here */
879 	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
880 
881 	if (options & F_HDRINCL) {
882 		cc += sizeof(struct ip);
883 		ip = (struct ip *)outpackhdr;
884 		ip->ip_len = cc;
885 		ip->ip_sum = in_cksum((u_short *)outpackhdr, cc);
886 		packet = outpackhdr;
887 	}
888 	i = sendto(s, (char *)packet, cc, 0, (struct sockaddr *)&whereto,
889 	    sizeof(whereto));
890 
891 	if (i < 0 || i != cc)  {
892 		if (i < 0) {
893 			if (options & F_FLOOD && errno == ENOBUFS) {
894 				usleep(FLOOD_BACKOFF);
895 				return;
896 			}
897 			warn("sendto");
898 		} else {
899 			warn("%s: partial write: %d of %d bytes",
900 			     hostname, i, cc);
901 		}
902 	}
903 	ntransmitted++;
904 	if (!(options & F_QUIET) && options & F_FLOOD)
905 		(void)write(STDOUT_FILENO, &DOT, 1);
906 }
907 
908 /*
909  * pr_pack --
910  *	Print out the packet, if it came from us.  This logic is necessary
911  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
912  * which arrive ('tis only fair).  This permits multiple copies of this
913  * program to be run without having intermingled output (or statistics!).
914  */
915 static void
916 pr_pack(buf, cc, from, tv)
917 	char *buf;
918 	int cc;
919 	struct sockaddr_in *from;
920 	struct timeval *tv;
921 {
922 	struct in_addr ina;
923 	u_char *cp, *dp;
924 	struct icmp *icp;
925 	struct ip *ip;
926 	const void *tp;
927 	double triptime;
928 	int dupflag, hlen, i, j, seq;
929 	static int old_rrlen;
930 	static char old_rr[MAX_IPOPTLEN];
931 
932 	/* Check the IP header */
933 	ip = (struct ip *)buf;
934 	hlen = ip->ip_hl << 2;
935 	if (cc < hlen + ICMP_MINLEN) {
936 		if (options & F_VERBOSE)
937 			warn("packet too short (%d bytes) from %s", cc,
938 			     inet_ntoa(from->sin_addr));
939 		return;
940 	}
941 
942 	/* Now the ICMP part */
943 	cc -= hlen;
944 	icp = (struct icmp *)(buf + hlen);
945 	if (icp->icmp_type == icmp_type_rsp) {
946 		if (icp->icmp_id != ident)
947 			return;			/* 'Twas not our ECHO */
948 		++nreceived;
949 		triptime = 0.0;
950 		if (timing) {
951 			struct timeval tv1;
952 #ifndef icmp_data
953 			tp = &icp->icmp_ip;
954 #else
955 			tp = icp->icmp_data;
956 #endif
957 			tp+=timeoffset;
958 
959 			/* Copy to avoid alignment problems: */
960 			memcpy(&tv1, tp, sizeof(tv1));
961 			tvsub(tv, &tv1);
962  			triptime = ((double)tv->tv_sec) * 1000.0 +
963  			    ((double)tv->tv_usec) / 1000.0;
964 			tsum += triptime;
965 			tsumsq += triptime * triptime;
966 			if (triptime < tmin)
967 				tmin = triptime;
968 			if (triptime > tmax)
969 				tmax = triptime;
970 		}
971 
972 		seq = ntohs(icp->icmp_seq);
973 
974 		if (TST(seq % mx_dup_ck)) {
975 			++nrepeats;
976 			--nreceived;
977 			dupflag = 1;
978 		} else {
979 			SET(seq % mx_dup_ck);
980 			dupflag = 0;
981 		}
982 
983 		if (options & F_QUIET)
984 			return;
985 
986 		if (options & F_FLOOD)
987 			(void)write(STDOUT_FILENO, &BSPACE, 1);
988 		else {
989 			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
990 			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
991 			   seq);
992 			(void)printf(" ttl=%d", ip->ip_ttl);
993 			if (timing)
994 				(void)printf(" time=%.3f ms", triptime);
995 			if (dupflag)
996 				(void)printf(" (DUP!)");
997 			if (options & F_AUDIBLE)
998 				(void)write(STDOUT_FILENO, &BBELL, 1);
999 			if (options & F_MASK) {
1000 				/* Just prentend this cast isn't ugly */
1001 				(void)printf(" mask=%s",
1002 					pr_addr(*(struct in_addr *)&(icp->icmp_mask)));
1003 			}
1004 			if (options & F_TIME) {
1005 				(void)printf(" tso=%s", pr_ntime(icp->icmp_otime));
1006 				(void)printf(" tsr=%s", pr_ntime(icp->icmp_rtime));
1007 				(void)printf(" tst=%s", pr_ntime(icp->icmp_ttime));
1008 			}
1009 			/* check the data */
1010 			cp = (u_char*)&icp->icmp_data[phdr_len];
1011 			dp = &outpack[MINICMPLEN + phdr_len];
1012 			for (i = phdr_len; i < datalen; ++i, ++cp, ++dp) {
1013 				if (*cp != *dp) {
1014 	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
1015 	    i, *dp, *cp);
1016 					(void)printf("\ncp:");
1017 					cp = (u_char*)&icp->icmp_data[0];
1018 					for (i = 0; i < datalen; ++i, ++cp) {
1019 						if ((i % 32) == 8)
1020 							(void)printf("\n\t");
1021 						(void)printf("%x ", *cp);
1022 					}
1023 					(void)printf("\ndp:");
1024 					cp = &outpack[MINICMPLEN];
1025 					for (i = 0; i < datalen; ++i, ++cp) {
1026 						if ((i % 32) == 8)
1027 							(void)printf("\n\t");
1028 						(void)printf("%x ", *cp);
1029 					}
1030 					break;
1031 				}
1032 			}
1033 		}
1034 	} else {
1035 		/*
1036 		 * We've got something other than an ECHOREPLY.
1037 		 * See if it's a reply to something that we sent.
1038 		 * We can compare IP destination, protocol,
1039 		 * and ICMP type and ID.
1040 		 *
1041 		 * Only print all the error messages if we are running
1042 		 * as root to avoid leaking information not normally
1043 		 * available to those not running as root.
1044 		 */
1045 #ifndef icmp_data
1046 		struct ip *oip = &icp->icmp_ip;
1047 #else
1048 		struct ip *oip = (struct ip *)icp->icmp_data;
1049 #endif
1050 		struct icmp *oicmp = (struct icmp *)(oip + 1);
1051 
1052 		if (((options & F_VERBOSE) && uid == 0) ||
1053 		    (!(options & F_QUIET2) &&
1054 		     (oip->ip_dst.s_addr == whereto.sin_addr.s_addr) &&
1055 		     (oip->ip_p == IPPROTO_ICMP) &&
1056 		     (oicmp->icmp_type == ICMP_ECHO) &&
1057 		     (oicmp->icmp_id == ident))) {
1058 		    (void)printf("%d bytes from %s: ", cc,
1059 			pr_addr(from->sin_addr));
1060 		    pr_icmph(icp);
1061 		} else
1062 		    return;
1063 	}
1064 
1065 	/* Display any IP options */
1066 	cp = (u_char *)buf + sizeof(struct ip);
1067 
1068 	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
1069 		switch (*cp) {
1070 		case IPOPT_EOL:
1071 			hlen = 0;
1072 			break;
1073 		case IPOPT_LSRR:
1074 		case IPOPT_SSRR:
1075 			(void)printf(*cp == IPOPT_LSRR ?
1076 			    "\nLSRR: " : "\nSSRR: ");
1077 			j = cp[IPOPT_OLEN] - IPOPT_MINOFF + 1;
1078 			hlen -= 2;
1079 			cp += 2;
1080 			if (j >= INADDR_LEN &&
1081 			    j <= hlen - (int)sizeof(struct ip)) {
1082 				for (;;) {
1083 					bcopy(++cp, &ina.s_addr, INADDR_LEN);
1084 					if (ina.s_addr == 0)
1085 						(void)printf("\t0.0.0.0");
1086 					else
1087 						(void)printf("\t%s",
1088 						     pr_addr(ina));
1089 					hlen -= INADDR_LEN;
1090 					cp += INADDR_LEN - 1;
1091 					j -= INADDR_LEN;
1092 					if (j < INADDR_LEN)
1093 						break;
1094 					(void)putchar('\n');
1095 				}
1096 			} else
1097 				(void)printf("\t(truncated route)\n");
1098 			break;
1099 		case IPOPT_RR:
1100 			j = cp[IPOPT_OLEN];		/* get length */
1101 			i = cp[IPOPT_OFFSET];		/* and pointer */
1102 			hlen -= 2;
1103 			cp += 2;
1104 			if (i > j)
1105 				i = j;
1106 			i = i - IPOPT_MINOFF + 1;
1107 			if (i < 0 || i > (hlen - (int)sizeof(struct ip))) {
1108 				old_rrlen = 0;
1109 				continue;
1110 			}
1111 			if (i == old_rrlen
1112 			    && !bcmp((char *)cp, old_rr, i)
1113 			    && !(options & F_FLOOD)) {
1114 				(void)printf("\t(same route)");
1115 				hlen -= i;
1116 				cp += i;
1117 				break;
1118 			}
1119 			old_rrlen = i;
1120 			bcopy((char *)cp, old_rr, i);
1121 			(void)printf("\nRR: ");
1122 			if (i >= INADDR_LEN &&
1123 			    i <= hlen - (int)sizeof(struct ip)) {
1124 				for (;;) {
1125 					bcopy(++cp, &ina.s_addr, INADDR_LEN);
1126 					if (ina.s_addr == 0)
1127 						(void)printf("\t0.0.0.0");
1128 					else
1129 						(void)printf("\t%s",
1130 						     pr_addr(ina));
1131 					hlen -= INADDR_LEN;
1132 					cp += INADDR_LEN - 1;
1133 					i -= INADDR_LEN;
1134 					if (i < INADDR_LEN)
1135 						break;
1136 					(void)putchar('\n');
1137 				}
1138 			} else
1139 				(void)printf("\t(truncated route)");
1140 			break;
1141 		case IPOPT_NOP:
1142 			(void)printf("\nNOP");
1143 			break;
1144 		default:
1145 			(void)printf("\nunknown option %x", *cp);
1146 			break;
1147 		}
1148 	if (!(options & F_FLOOD)) {
1149 		(void)putchar('\n');
1150 		(void)fflush(stdout);
1151 	}
1152 }
1153 
1154 /*
1155  * in_cksum --
1156  *	Checksum routine for Internet Protocol family headers (C Version)
1157  */
1158 u_short
1159 in_cksum(addr, len)
1160 	u_short *addr;
1161 	int len;
1162 {
1163 	int nleft, sum;
1164 	u_short *w;
1165 	union {
1166 		u_short	us;
1167 		u_char	uc[2];
1168 	} last;
1169 	u_short answer;
1170 
1171 	nleft = len;
1172 	sum = 0;
1173 	w = addr;
1174 
1175 	/*
1176 	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1177 	 * sequential 16 bit words to it, and at the end, fold back all the
1178 	 * carry bits from the top 16 bits into the lower 16 bits.
1179 	 */
1180 	while (nleft > 1)  {
1181 		sum += *w++;
1182 		nleft -= 2;
1183 	}
1184 
1185 	/* mop up an odd byte, if necessary */
1186 	if (nleft == 1) {
1187 		last.uc[0] = *(u_char *)w;
1188 		last.uc[1] = 0;
1189 		sum += last.us;
1190 	}
1191 
1192 	/* add back carry outs from top 16 bits to low 16 bits */
1193 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
1194 	sum += (sum >> 16);			/* add carry */
1195 	answer = ~sum;				/* truncate to 16 bits */
1196 	return(answer);
1197 }
1198 
1199 /*
1200  * tvsub --
1201  *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
1202  * be >= in.
1203  */
1204 static void
1205 tvsub(out, in)
1206 	struct timeval *out, *in;
1207 {
1208 
1209 	if ((out->tv_usec -= in->tv_usec) < 0) {
1210 		--out->tv_sec;
1211 		out->tv_usec += 1000000;
1212 	}
1213 	out->tv_sec -= in->tv_sec;
1214 }
1215 
1216 /*
1217  * status --
1218  *	Print out statistics when SIGINFO is received.
1219  */
1220 
1221 static void
1222 status(sig)
1223 	int sig __unused;
1224 {
1225 
1226 	siginfo_p = 1;
1227 }
1228 
1229 static void
1230 check_status()
1231 {
1232 
1233 	if (siginfo_p) {
1234 		siginfo_p = 0;
1235 		(void)fprintf(stderr,
1236 	"\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
1237 		    nreceived, ntransmitted,
1238 		    ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
1239 		    nreceived ? tmin : 0.0,
1240 		    nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
1241 		    tmax);
1242 	}
1243 }
1244 
1245 /*
1246  * finish --
1247  *	Print out statistics, and give up.
1248  */
1249 static void
1250 finish()
1251 {
1252 	struct termios ts;
1253 
1254 	(void)signal(SIGINT, SIG_IGN);
1255 	(void)signal(SIGALRM, SIG_IGN);
1256 	(void)putchar('\n');
1257 	(void)fflush(stdout);
1258 	(void)printf("--- %s ping statistics ---\n", hostname);
1259 	(void)printf("%ld packets transmitted, ", ntransmitted);
1260 	(void)printf("%ld packets received, ", nreceived);
1261 	if (nrepeats)
1262 		(void)printf("+%ld duplicates, ", nrepeats);
1263 	if (ntransmitted) {
1264 		if (nreceived > ntransmitted)
1265 			(void)printf("-- somebody's printing up packets!");
1266 		else
1267 			(void)printf("%d%% packet loss",
1268 			    (int)(((ntransmitted - nreceived) * 100) /
1269 			    ntransmitted));
1270 	}
1271 	(void)putchar('\n');
1272 	if (nreceived && timing) {
1273 		double n = nreceived + nrepeats;
1274 		double avg = tsum / n;
1275 		double vari = tsumsq / n - avg * avg;
1276 		(void)printf(
1277 		    "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
1278 		    tmin, avg, tmax, sqrt(vari));
1279 	}
1280 	if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
1281 		ts.c_lflag &= ~NOKERNINFO;
1282 		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
1283 	}
1284 
1285 	if (nreceived)
1286 		exit(0);
1287 	else
1288 		exit(2);
1289 }
1290 
1291 #ifdef notdef
1292 static char *ttab[] = {
1293 	"Echo Reply",		/* ip + seq + udata */
1294 	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
1295 	"Source Quench",	/* IP */
1296 	"Redirect",		/* redirect type, gateway, + IP  */
1297 	"Echo",
1298 	"Time Exceeded",	/* transit, frag reassem + IP */
1299 	"Parameter Problem",	/* pointer + IP */
1300 	"Timestamp",		/* id + seq + three timestamps */
1301 	"Timestamp Reply",	/* " */
1302 	"Info Request",		/* id + sq */
1303 	"Info Reply"		/* " */
1304 };
1305 #endif
1306 
1307 /*
1308  * pr_icmph --
1309  *	Print a descriptive string about an ICMP header.
1310  */
1311 static void
1312 pr_icmph(icp)
1313 	struct icmp *icp;
1314 {
1315 
1316 	switch(icp->icmp_type) {
1317 	case ICMP_ECHOREPLY:
1318 		(void)printf("Echo Reply\n");
1319 		/* XXX ID + Seq + Data */
1320 		break;
1321 	case ICMP_UNREACH:
1322 		switch(icp->icmp_code) {
1323 		case ICMP_UNREACH_NET:
1324 			(void)printf("Destination Net Unreachable\n");
1325 			break;
1326 		case ICMP_UNREACH_HOST:
1327 			(void)printf("Destination Host Unreachable\n");
1328 			break;
1329 		case ICMP_UNREACH_PROTOCOL:
1330 			(void)printf("Destination Protocol Unreachable\n");
1331 			break;
1332 		case ICMP_UNREACH_PORT:
1333 			(void)printf("Destination Port Unreachable\n");
1334 			break;
1335 		case ICMP_UNREACH_NEEDFRAG:
1336 			(void)printf("frag needed and DF set (MTU %d)\n",
1337 					ntohs(icp->icmp_nextmtu));
1338 			break;
1339 		case ICMP_UNREACH_SRCFAIL:
1340 			(void)printf("Source Route Failed\n");
1341 			break;
1342 		case ICMP_UNREACH_FILTER_PROHIB:
1343 			(void)printf("Communication prohibited by filter\n");
1344 			break;
1345 		default:
1346 			(void)printf("Dest Unreachable, Bad Code: %d\n",
1347 			    icp->icmp_code);
1348 			break;
1349 		}
1350 		/* Print returned IP header information */
1351 #ifndef icmp_data
1352 		pr_retip(&icp->icmp_ip);
1353 #else
1354 		pr_retip((struct ip *)icp->icmp_data);
1355 #endif
1356 		break;
1357 	case ICMP_SOURCEQUENCH:
1358 		(void)printf("Source Quench\n");
1359 #ifndef icmp_data
1360 		pr_retip(&icp->icmp_ip);
1361 #else
1362 		pr_retip((struct ip *)icp->icmp_data);
1363 #endif
1364 		break;
1365 	case ICMP_REDIRECT:
1366 		switch(icp->icmp_code) {
1367 		case ICMP_REDIRECT_NET:
1368 			(void)printf("Redirect Network");
1369 			break;
1370 		case ICMP_REDIRECT_HOST:
1371 			(void)printf("Redirect Host");
1372 			break;
1373 		case ICMP_REDIRECT_TOSNET:
1374 			(void)printf("Redirect Type of Service and Network");
1375 			break;
1376 		case ICMP_REDIRECT_TOSHOST:
1377 			(void)printf("Redirect Type of Service and Host");
1378 			break;
1379 		default:
1380 			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1381 			break;
1382 		}
1383 		(void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1384 #ifndef icmp_data
1385 		pr_retip(&icp->icmp_ip);
1386 #else
1387 		pr_retip((struct ip *)icp->icmp_data);
1388 #endif
1389 		break;
1390 	case ICMP_ECHO:
1391 		(void)printf("Echo Request\n");
1392 		/* XXX ID + Seq + Data */
1393 		break;
1394 	case ICMP_TIMXCEED:
1395 		switch(icp->icmp_code) {
1396 		case ICMP_TIMXCEED_INTRANS:
1397 			(void)printf("Time to live exceeded\n");
1398 			break;
1399 		case ICMP_TIMXCEED_REASS:
1400 			(void)printf("Frag reassembly time exceeded\n");
1401 			break;
1402 		default:
1403 			(void)printf("Time exceeded, Bad Code: %d\n",
1404 			    icp->icmp_code);
1405 			break;
1406 		}
1407 #ifndef icmp_data
1408 		pr_retip(&icp->icmp_ip);
1409 #else
1410 		pr_retip((struct ip *)icp->icmp_data);
1411 #endif
1412 		break;
1413 	case ICMP_PARAMPROB:
1414 		(void)printf("Parameter problem: pointer = 0x%02x\n",
1415 		    icp->icmp_hun.ih_pptr);
1416 #ifndef icmp_data
1417 		pr_retip(&icp->icmp_ip);
1418 #else
1419 		pr_retip((struct ip *)icp->icmp_data);
1420 #endif
1421 		break;
1422 	case ICMP_TSTAMP:
1423 		(void)printf("Timestamp\n");
1424 		/* XXX ID + Seq + 3 timestamps */
1425 		break;
1426 	case ICMP_TSTAMPREPLY:
1427 		(void)printf("Timestamp Reply\n");
1428 		/* XXX ID + Seq + 3 timestamps */
1429 		break;
1430 	case ICMP_IREQ:
1431 		(void)printf("Information Request\n");
1432 		/* XXX ID + Seq */
1433 		break;
1434 	case ICMP_IREQREPLY:
1435 		(void)printf("Information Reply\n");
1436 		/* XXX ID + Seq */
1437 		break;
1438 	case ICMP_MASKREQ:
1439 		(void)printf("Address Mask Request\n");
1440 		break;
1441 	case ICMP_MASKREPLY:
1442 		(void)printf("Address Mask Reply\n");
1443 		break;
1444 	case ICMP_ROUTERADVERT:
1445 		(void)printf("Router Advertisement\n");
1446 		break;
1447 	case ICMP_ROUTERSOLICIT:
1448 		(void)printf("Router Solicitation\n");
1449 		break;
1450 	default:
1451 		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1452 	}
1453 }
1454 
1455 /*
1456  * pr_iph --
1457  *	Print an IP header with options.
1458  */
1459 static void
1460 pr_iph(ip)
1461 	struct ip *ip;
1462 {
1463 	u_char *cp;
1464 	int hlen;
1465 
1466 	hlen = ip->ip_hl << 2;
1467 	cp = (u_char *)ip + 20;		/* point to options */
1468 
1469 	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst\n");
1470 	(void)printf(" %1x  %1x  %02x %04x %04x",
1471 	    ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1472 	    ntohs(ip->ip_id));
1473 	(void)printf("   %1lx %04lx",
1474 	    (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1475 	    (u_long) ntohl(ip->ip_off) & 0x1fff);
1476 	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p,
1477 							    ntohs(ip->ip_sum));
1478 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1479 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1480 	/* dump any option bytes */
1481 	while (hlen-- > 20) {
1482 		(void)printf("%02x", *cp++);
1483 	}
1484 	(void)putchar('\n');
1485 }
1486 
1487 /*
1488  * pr_addr --
1489  *	Return an ascii host address as a dotted quad and optionally with
1490  * a hostname.
1491  */
1492 static char *
1493 pr_addr(ina)
1494 	struct in_addr ina;
1495 {
1496 	struct hostent *hp;
1497 	static char buf[16 + 3 + MAXHOSTNAMELEN];
1498 
1499 	if ((options & F_NUMERIC) ||
1500 	    !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1501 		return inet_ntoa(ina);
1502 	else
1503 		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1504 		    inet_ntoa(ina));
1505 	return(buf);
1506 }
1507 
1508 /*
1509  * pr_retip --
1510  *	Dump some info on a returned (via ICMP) IP packet.
1511  */
1512 static void
1513 pr_retip(ip)
1514 	struct ip *ip;
1515 {
1516 	u_char *cp;
1517 	int hlen;
1518 
1519 	pr_iph(ip);
1520 	hlen = ip->ip_hl << 2;
1521 	cp = (u_char *)ip + hlen;
1522 
1523 	if (ip->ip_p == 6)
1524 		(void)printf("TCP: from port %u, to port %u (decimal)\n",
1525 		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1526 	else if (ip->ip_p == 17)
1527 		(void)printf("UDP: from port %u, to port %u (decimal)\n",
1528 			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1529 }
1530 
1531 static char *
1532 pr_ntime (n_time time)
1533 {
1534 	static char buf[10];
1535 	int h, m, s;
1536 
1537 	s = ntohl(time) / 1000;
1538 	h = s / 60 / 60;
1539 	m = (s % (60 * 60)) / 60;
1540 	s = (s % (60 * 60)) % 60;
1541 
1542 	(void)snprintf(buf, sizeof(buf), "%02d:%02d:%02d", h, m, s);
1543 
1544 	return (buf);
1545 }
1546 
1547 static void
1548 fill(bp, patp)
1549 	char *bp, *patp;
1550 {
1551 	char *cp;
1552 	int pat[16];
1553 	u_int ii, jj, kk;
1554 
1555 	for (cp = patp; *cp; cp++) {
1556 		if (!isxdigit(*cp))
1557 			errx(EX_USAGE,
1558 			    "patterns must be specified as hex digits");
1559 
1560 	}
1561 	ii = sscanf(patp,
1562 	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1563 	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1564 	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1565 	    &pat[13], &pat[14], &pat[15]);
1566 
1567 	if (ii > 0)
1568 		for (kk = 0; kk <= maxpayload - (phdr_len + ii); kk += ii)
1569 			for (jj = 0; jj < ii; ++jj)
1570 				bp[jj + kk] = pat[jj];
1571 	if (!(options & F_QUIET)) {
1572 		(void)printf("PATTERN: 0x");
1573 		for (jj = 0; jj < ii; ++jj)
1574 			(void)printf("%02x", bp[jj] & 0xFF);
1575 		(void)printf("\n");
1576 	}
1577 }
1578 
1579 static void
1580 usage()
1581 {
1582 	(void)fprintf(stderr, "%s\n%s\n%s\n",
1583 "usage: ping [-AaDdfnoQqRrv] [-c count] [-i wait] [-l preload]",
1584 "            [-M mask | time] [-m ttl] [-p pattern] "
1585 #ifdef IPSEC
1586 #ifdef IPSEC_POLICY_IPSEC
1587 "[-P policy] "
1588 #endif
1589 #endif
1590 "[-S src_addr]",
1591 "            [-s packetsize] [-t timeout] [-z tos]",
1592 "            [host | [-L] [-I iface] [-T ttl] mcast-group]");
1593 	exit(EX_USAGE);
1594 }
1595