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