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