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