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