xref: /freebsd/sbin/ping/ping6.c (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*	$KAME: ping6.c,v 1.169 2003/07/25 06:01:47 itojun Exp $	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*	BSDI	ping.c,v 2.3 1996/01/21 17:56:50 jch Exp	*/
35 
36 /*
37  * Copyright (c) 1989, 1993
38  *	The Regents of the University of California.  All rights reserved.
39  *
40  * This code is derived from software contributed to Berkeley by
41  * Mike Muuss.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. Neither the name of the University nor the names of its contributors
52  *    may be used to endorse or promote products derived from this software
53  *    without specific prior written permission.
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65  * SUCH DAMAGE.
66  */
67 
68 #if 0
69 #ifndef lint
70 static const char copyright[] =
71 "@(#) Copyright (c) 1989, 1993\n\
72 	The Regents of the University of California.  All rights reserved.\n";
73 #endif /* not lint */
74 
75 #ifndef lint
76 static char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
77 #endif /* not lint */
78 #endif
79 
80 #include <sys/cdefs.h>
81 /*
82  * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
83  * measure round-trip-delays and packet loss across network paths.
84  *
85  * Author -
86  *	Mike Muuss
87  *	U. S. Army Ballistic Research Laboratory
88  *	December, 1983
89  *
90  * Status -
91  *	Public Domain.  Distribution Unlimited.
92  * Bugs -
93  *	More statistics could always be gathered.
94  *	This program has to run SUID to ROOT to access the ICMP socket.
95  */
96 /*
97  * NOTE:
98  * USE_SIN6_SCOPE_ID assumes that sin6_scope_id has the same semantics
99  * as IPV6_PKTINFO.  Some people object it (sin6_scope_id specifies *link*
100  * while IPV6_PKTINFO specifies *interface*.  Link is defined as collection of
101  * network attached to 1 or more interfaces)
102  */
103 
104 #include <sys/param.h>
105 #include <sys/capsicum.h>
106 #include <sys/uio.h>
107 #include <sys/socket.h>
108 
109 #include <net/if.h>
110 #include <net/route.h>
111 
112 #include <netinet/in.h>
113 #include <netinet/ip6.h>
114 #include <netinet/icmp6.h>
115 #include <arpa/inet.h>
116 #include <arpa/nameser.h>
117 #include <netdb.h>
118 
119 #include <capsicum_helpers.h>
120 #include <casper/cap_dns.h>
121 #include <libcasper.h>
122 
123 #include <ctype.h>
124 #include <err.h>
125 #include <errno.h>
126 #include <fcntl.h>
127 #include <math.h>
128 #include <signal.h>
129 #include <stdio.h>
130 #include <stdlib.h>
131 #include <string.h>
132 #include <sysexits.h>
133 #include <time.h>
134 #include <unistd.h>
135 
136 #ifdef IPSEC
137 #include <netipsec/ah.h>
138 #include <netipsec/ipsec.h>
139 #endif
140 
141 #include <md5.h>
142 
143 #include "main.h"
144 #include "ping6.h"
145 
146 struct tv32 {
147 	u_int32_t tv32_sec;
148 	u_int32_t tv32_nsec;
149 };
150 
151 #define MAXPACKETLEN	131072
152 #define	IP6LEN		40
153 #define ICMP6ECHOLEN	8	/* icmp echo header len excluding time */
154 #define ICMP6ECHOTMLEN sizeof(struct tv32)
155 #define ICMP6_NIQLEN	(ICMP6ECHOLEN + 8)
156 # define CONTROLLEN	10240	/* ancillary data buffer size RFC3542 20.1 */
157 /* FQDN case, 64 bits of nonce + 32 bits ttl */
158 #define ICMP6_NIRLEN	(ICMP6ECHOLEN + 12)
159 #define	EXTRA		256	/* for AH and various other headers. weird. */
160 #define	DEFDATALEN	ICMP6ECHOTMLEN
161 #define MAXDATALEN	MAXPACKETLEN - IP6LEN - ICMP6ECHOLEN
162 #define	NROUTES		9		/* number of record route slots */
163 #define	MAXWAIT		10000		/* max ms to wait for response */
164 #define	MAXALARM	(60 * 60)	/* max seconds for alarm timeout */
165 
166 #define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
167 #define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
168 #define	SET(bit)	(A(bit) |= B(bit))
169 #define	CLR(bit)	(A(bit) &= (~B(bit)))
170 #define	TST(bit)	(A(bit) & B(bit))
171 
172 #define	F_FLOOD		0x0001
173 #define	F_INTERVAL	0x0002
174 #define	F_PINGFILLED	0x0008
175 #define	F_QUIET		0x0010
176 #define	F_RROUTE	0x0020
177 #define	F_SO_DEBUG	0x0040
178 #define	F_VERBOSE	0x0100
179 #ifdef IPSEC
180 #ifdef IPSEC_POLICY_IPSEC
181 #define	F_POLICY	0x0400
182 #else
183 #define F_AUTHHDR	0x0200
184 #define F_ENCRYPT	0x0400
185 #endif /*IPSEC_POLICY_IPSEC*/
186 #endif /*IPSEC*/
187 #define F_NODEADDR	0x0800
188 #define F_FQDN		0x1000
189 #define F_INTERFACE	0x2000
190 #define F_SRCADDR	0x4000
191 #define F_HOSTNAME	0x10000
192 #define F_FQDNOLD	0x20000
193 #define F_NIGROUP	0x40000
194 #define F_SUPTYPES	0x80000
195 #define F_NOMINMTU	0x100000
196 #define F_ONCE		0x200000
197 #define F_AUDIBLE	0x400000
198 #define F_MISSED	0x800000
199 #define F_DONTFRAG	0x1000000
200 #define F_NOUSERDATA	(F_NODEADDR | F_FQDN | F_FQDNOLD | F_SUPTYPES)
201 #define	F_WAITTIME	0x2000000
202 #define	F_DOT		0x4000000
203 static u_int options;
204 
205 #define IN6LEN		sizeof(struct in6_addr)
206 #define SA6LEN		sizeof(struct sockaddr_in6)
207 #define DUMMY_PORT	10101
208 
209 #define SIN6(s)	((struct sockaddr_in6 *)(s))
210 
211 /*
212  * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
213  * number of received sequence numbers we can keep track of.  Change 128
214  * to 8192 for complete accuracy...
215  */
216 #define	MAX_DUP_CHK	(8 * 8192)
217 static int mx_dup_ck = MAX_DUP_CHK;
218 static char rcvd_tbl[MAX_DUP_CHK / 8];
219 
220 static struct sockaddr_in6 dst;	/* who to ping6 */
221 static struct sockaddr_in6 src;	/* src addr of this packet */
222 static socklen_t srclen;
223 static size_t datalen = DEFDATALEN;
224 static int ssend;		/* send socket file descriptor */
225 static int srecv;		/* receive socket file descriptor */
226 static u_char outpack[MAXPACKETLEN];
227 static char BSPACE = '\b';	/* characters written for flood */
228 static char BBELL = '\a';	/* characters written for AUDIBLE */
229 static const char *DOT = ".";
230 static size_t DOTlen = 1;
231 static size_t DOTidx = 0;
232 static char *hostname;
233 static int ident;		/* process id to identify our packets */
234 static u_int8_t nonce[8];	/* nonce field for node information */
235 static int hoplimit = -1;	/* hoplimit */
236 static int tclass = -1;		/* traffic class */
237 static int pcp = -2;		/* vlan priority code point */
238 static u_char *packet = NULL;
239 static cap_channel_t *capdns;
240 
241 /* counters */
242 static long nmissedmax;		/* max value of ntransmitted - nreceived - 1 */
243 static long npackets;		/* max packets to transmit */
244 static long nreceived;		/* # of packets we got back */
245 static long nrepeats;		/* number of duplicates */
246 static long ntransmitted;	/* sequence # for outbound packets = #sent */
247 static long ntransmitfailures;	/* number of transmit failures */
248 static int interval = 1000;	/* interval between packets in ms */
249 static int waittime = MAXWAIT;	/* timeout for each packet */
250 static long nrcvtimeout = 0;	/* # of packets we got back after waittime */
251 
252 /* timing */
253 static int timing;		/* flag to do timing */
254 static double tmin = 999999999.0;	/* minimum round trip time */
255 static double tmax = 0.0;	/* maximum round trip time */
256 static double tsum = 0.0;	/* sum of all times, for doing average */
257 static double tsumsq = 0.0;	/* sum of all times squared, for std. dev. */
258 
259 /* for node addresses */
260 static u_short naflags;
261 
262 /* for ancillary data(advanced API) */
263 static struct msghdr smsghdr;
264 static struct iovec smsgiov;
265 static char *scmsg = 0;
266 
267 static volatile sig_atomic_t seenint;
268 #ifdef SIGINFO
269 static volatile sig_atomic_t seeninfo;
270 #endif
271 
272 static cap_channel_t *capdns_setup(void);
273 static void	 fill(char *, char *);
274 static int	 get_hoplim(struct msghdr *);
275 static int	 get_pathmtu(struct msghdr *);
276 static struct in6_pktinfo *get_rcvpktinfo(struct msghdr *);
277 static void	 onsignal(int);
278 static void	 onint(int);
279 static size_t	 pingerlen(void);
280 static int	 pinger(void);
281 static const char *pr_addr(struct sockaddr *, int);
282 static void	 pr_icmph(struct icmp6_hdr *, u_char *);
283 static void	 pr_iph(struct ip6_hdr *);
284 static void	 pr_suptypes(struct icmp6_nodeinfo *, size_t);
285 static void	 pr_nodeaddr(struct icmp6_nodeinfo *, int);
286 static int	 myechoreply(const struct icmp6_hdr *);
287 static int	 mynireply(const struct icmp6_nodeinfo *);
288 static const char *dnsdecode(const u_char *, const u_char *, const u_char *,
289     char *, size_t);
290 static void	 pr_pack(u_char *, int, struct msghdr *);
291 static void	 pr_exthdrs(struct msghdr *);
292 static void	 pr_ip6opt(void *, size_t);
293 static void	 pr_rthdr(void *, size_t);
294 static int	 pr_bitrange(u_int32_t, int, int);
295 static void	 pr_retip(struct ip6_hdr *, u_char *);
296 static void	 summary(void);
297 #ifdef IPSEC
298 #ifdef IPSEC_POLICY_IPSEC
299 static int	 setpolicy(int, char *);
300 #endif
301 #endif
302 static char	*nigroup(char *, int);
303 
304 int
305 ping6(int argc, char *argv[])
306 {
307 	struct timespec last, intvl;
308 	struct sockaddr_in6 from, *sin6;
309 	struct addrinfo hints, *res;
310 	struct sigaction si_sa;
311 	int cc, i;
312 	int almost_done, ch, hold, packlen, preload, optval, error;
313 	int nig_oldmcprefix = -1;
314 	u_char *datap;
315 	char *e, *target, *ifname = NULL, *gateway = NULL;
316 	int ip6optlen = 0;
317 	struct cmsghdr *scmsgp = NULL;
318 	/* For control (ancillary) data received from recvmsg() */
319 	u_char cm[CONTROLLEN];
320 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
321 	u_long lsockbufsize;
322 	int sockbufsize = 0;
323 #endif
324 	int usepktinfo = 0;
325 	struct in6_pktinfo pktinfo;
326 	char *cmsg_pktinfo = NULL;
327 	struct ip6_rthdr *rthdr = NULL;
328 #ifdef IPSEC_POLICY_IPSEC
329 	char *policy_in = NULL;
330 	char *policy_out = NULL;
331 #endif
332 	double t;
333 	u_long alarmtimeout;
334 	size_t rthlen;
335 #ifdef IPV6_USE_MIN_MTU
336 	int mflag = 0;
337 #endif
338 	cap_rights_t rights_srecv;
339 	cap_rights_t rights_ssend;
340 	cap_rights_t rights_stdin;
341 
342 	/* just to be sure */
343 	memset(&smsghdr, 0, sizeof(smsghdr));
344 	memset(&smsgiov, 0, sizeof(smsgiov));
345 	memset(&pktinfo, 0, sizeof(pktinfo));
346 
347 	intvl.tv_sec = interval / 1000;
348 	intvl.tv_nsec = interval % 1000 * 1000000;
349 
350 	alarmtimeout = preload = 0;
351 	datap = &outpack[ICMP6ECHOLEN + ICMP6ECHOTMLEN];
352 	capdns = capdns_setup();
353 
354 	while ((ch = getopt(argc, argv, PING6OPTS)) != -1) {
355 		switch (ch) {
356 		case '.':
357 			options |= F_DOT;
358 			if (optarg != NULL) {
359 				DOT = optarg;
360 				DOTlen = strlen(optarg);
361 			}
362 			break;
363 		case '6':
364 			/* This option is processed in main(). */
365 			break;
366 		case 'k':
367 		{
368 			char *cp;
369 
370 			options &= ~F_NOUSERDATA;
371 			options |= F_NODEADDR;
372 			for (cp = optarg; *cp != '\0'; cp++) {
373 				switch (*cp) {
374 				case 'a':
375 					naflags |= NI_NODEADDR_FLAG_ALL;
376 					break;
377 				case 'c':
378 				case 'C':
379 					naflags |= NI_NODEADDR_FLAG_COMPAT;
380 					break;
381 				case 'l':
382 				case 'L':
383 					naflags |= NI_NODEADDR_FLAG_LINKLOCAL;
384 					break;
385 				case 's':
386 				case 'S':
387 					naflags |= NI_NODEADDR_FLAG_SITELOCAL;
388 					break;
389 				case 'g':
390 				case 'G':
391 					naflags |= NI_NODEADDR_FLAG_GLOBAL;
392 					break;
393 				case 'A': /* experimental. not in the spec */
394 #ifdef NI_NODEADDR_FLAG_ANYCAST
395 					naflags |= NI_NODEADDR_FLAG_ANYCAST;
396 					break;
397 #else
398 					errx(1,
399 "-a A is not supported on the platform");
400 					/*NOTREACHED*/
401 #endif
402 				default:
403 					usage();
404 					/*NOTREACHED*/
405 				}
406 			}
407 			break;
408 		}
409 		case 'b':
410 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
411 			errno = 0;
412 			e = NULL;
413 			lsockbufsize = strtoul(optarg, &e, 10);
414 			sockbufsize = (int)lsockbufsize;
415 			if (errno || !*optarg || *e ||
416 			    lsockbufsize > INT_MAX)
417 				errx(1, "invalid socket buffer size");
418 #else
419 			errx(1,
420 "-b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported");
421 #endif
422 			break;
423 		case 'C':		/* vlan priority code point */
424 			pcp = strtol(optarg, &e, 10);
425 			if (*optarg == '\0' || *e != '\0')
426 				errx(1, "illegal vlan pcp %s", optarg);
427 			if (7 < pcp || pcp < -1)
428 				errx(1, "illegal vlan pcp -- %s", optarg);
429 			break;
430 		case 'c':
431 			npackets = strtol(optarg, &e, 10);
432 			if (npackets <= 0 || *optarg == '\0' || *e != '\0')
433 				errx(1,
434 				    "illegal number of packets -- %s", optarg);
435 			break;
436 		case 'D':
437 			options |= F_DONTFRAG;
438 			break;
439 		case 'd':
440 			options |= F_SO_DEBUG;
441 			break;
442 		case 'f':
443 			if (getuid()) {
444 				errno = EPERM;
445 				errx(1, "Must be superuser to flood ping");
446 			}
447 			options |= F_FLOOD;
448 			options |= F_DOT;
449 			setbuf(stdout, (char *)NULL);
450 			break;
451 		case 'e':
452 			gateway = optarg;
453 			break;
454 		case 'H':
455 			options |= F_HOSTNAME;
456 			break;
457 		case 'm':		/* hoplimit */
458 			hoplimit = strtol(optarg, &e, 10);
459 			if (*optarg == '\0' || *e != '\0')
460 				errx(1, "illegal hoplimit %s", optarg);
461 			if (255 < hoplimit || hoplimit < -1)
462 				errx(1,
463 				    "illegal hoplimit -- %s", optarg);
464 			break;
465 		case 'I':
466 			ifname = optarg;
467 			options |= F_INTERFACE;
468 #ifndef USE_SIN6_SCOPE_ID
469 			usepktinfo++;
470 #endif
471 			break;
472 		case 'i':		/* wait between sending packets */
473 			t = strtod(optarg, &e);
474 			if (*optarg == '\0' || *e != '\0')
475 				errx(1, "illegal timing interval %s", optarg);
476 			if (t < 1 && getuid()) {
477 				errx(1, "%s: only root may use interval < 1s",
478 				    strerror(EPERM));
479 			}
480 			intvl.tv_sec = (time_t)t;
481 			intvl.tv_nsec =
482 			    (long)((t - intvl.tv_sec) * 1000000000);
483 			if (intvl.tv_sec < 0)
484 				errx(1, "illegal timing interval %s", optarg);
485 			/* less than 1/hz does not make sense */
486 			if (intvl.tv_sec == 0 && intvl.tv_nsec < 1000) {
487 				warnx("too small interval, raised to .000001");
488 				intvl.tv_nsec = 1000;
489 			}
490 			options |= F_INTERVAL;
491 			break;
492 		case 'l':
493 			if (getuid()) {
494 				errno = EPERM;
495 				errx(1, "Must be superuser to preload");
496 			}
497 			preload = strtol(optarg, &e, 10);
498 			if (preload < 0 || *optarg == '\0' || *e != '\0')
499 				errx(1, "illegal preload value -- %s", optarg);
500 			break;
501 		case 'u':
502 #ifdef IPV6_USE_MIN_MTU
503 			mflag++;
504 			break;
505 #else
506 			errx(1, "-%c is not supported on this platform", ch);
507 			/*NOTREACHED*/
508 #endif
509 		case 'n':
510 			options &= ~F_HOSTNAME;
511 			break;
512 		case 'N':
513 			options |= F_NIGROUP;
514 			nig_oldmcprefix++;
515 			break;
516 		case 'o':
517 			options |= F_ONCE;
518 			break;
519 		case 'p':		/* fill buffer with user pattern */
520 			options |= F_PINGFILLED;
521 			fill((char *)datap, optarg);
522 				break;
523 		case 'q':
524 			options |= F_QUIET;
525 			break;
526 		case 'a':
527 			options |= F_AUDIBLE;
528 			break;
529 		case 'A':
530 			options |= F_MISSED;
531 			break;
532 		case 'S':
533 			memset(&hints, 0, sizeof(struct addrinfo));
534 			hints.ai_flags = AI_NUMERICHOST; /* allow hostname? */
535 			hints.ai_family = AF_INET6;
536 			hints.ai_socktype = SOCK_RAW;
537 			hints.ai_protocol = IPPROTO_ICMPV6;
538 
539 			error = cap_getaddrinfo(capdns, optarg, NULL, &hints, &res);
540 			if (error) {
541 				errx(1, "invalid source address: %s",
542 				     gai_strerror(error));
543 			}
544 			/*
545 			 * res->ai_family must be AF_INET6 and res->ai_addrlen
546 			 * must be sizeof(src).
547 			 */
548 			memcpy(&src, res->ai_addr, res->ai_addrlen);
549 			srclen = res->ai_addrlen;
550 			freeaddrinfo(res);
551 			options |= F_SRCADDR;
552 			break;
553 		case 's':		/* size of packet to send */
554 			datalen = strtol(optarg, &e, 10);
555 			if (datalen <= 0 || *optarg == '\0' || *e != '\0')
556 				errx(1, "illegal datalen value -- %s", optarg);
557 			if (datalen > MAXDATALEN) {
558 				errx(1,
559 				    "datalen value too large, maximum is %d",
560 				    MAXDATALEN);
561 			}
562 			break;
563 		case 'O':
564 			options &= ~F_NOUSERDATA;
565 			options |= F_SUPTYPES;
566 			break;
567 		case 'v':
568 			options |= F_VERBOSE;
569 			break;
570 		case 'y':
571 			options &= ~F_NOUSERDATA;
572 			options |= F_FQDN;
573 			break;
574 		case 'Y':
575 			options &= ~F_NOUSERDATA;
576 			options |= F_FQDNOLD;
577 			break;
578 		case 'W':
579 			t = strtod(optarg, &e);
580 			if (*e || e == optarg || t > (double)INT_MAX)
581 				errx(EX_USAGE, "invalid timing interval: `%s'",
582 				    optarg);
583 			options |= F_WAITTIME;
584 			waittime = (int)t;
585 			break;
586 		case 't':
587 			alarmtimeout = strtoul(optarg, &e, 0);
588 			if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
589 				errx(EX_USAGE, "invalid timeout: `%s'",
590 				    optarg);
591 			if (alarmtimeout > MAXALARM)
592 				errx(EX_USAGE, "invalid timeout: `%s' > %d",
593 				    optarg, MAXALARM);
594 			{
595 				struct itimerval itv;
596 
597 				timerclear(&itv.it_interval);
598 				timerclear(&itv.it_value);
599 				itv.it_value.tv_sec = (time_t)alarmtimeout;
600 				if (setitimer(ITIMER_REAL, &itv, NULL) != 0)
601 					err(1, "setitimer");
602 			}
603 			break;
604 		case 'z':		/* traffic class */
605 			tclass = strtol(optarg, &e, 10);
606 			if (*optarg == '\0' || *e != '\0')
607 				errx(1, "illegal traffic class %s", optarg);
608 			if (255 < tclass || tclass < -1)
609 				errx(1,
610 				    "illegal traffic class -- %s", optarg);
611 			break;
612 #ifdef IPSEC
613 #ifdef IPSEC_POLICY_IPSEC
614 		case 'P':
615 			options |= F_POLICY;
616 			if (!strncmp("in", optarg, 2)) {
617 				if ((policy_in = strdup(optarg)) == NULL)
618 					errx(1, "strdup");
619 			} else if (!strncmp("out", optarg, 3)) {
620 				if ((policy_out = strdup(optarg)) == NULL)
621 					errx(1, "strdup");
622 			} else
623 				errx(1, "invalid security policy");
624 			break;
625 #else
626 		case 'Z':
627 			options |= F_AUTHHDR;
628 			break;
629 		case 'E':
630 			options |= F_ENCRYPT;
631 			break;
632 #endif /*IPSEC_POLICY_IPSEC*/
633 #endif /*IPSEC*/
634 		default:
635 			usage();
636 			/*NOTREACHED*/
637 		}
638 	}
639 
640 	argc -= optind;
641 	argv += optind;
642 
643 	if (argc < 1) {
644 		usage();
645 		/*NOTREACHED*/
646 	}
647 
648 	if (argc > 1) {
649 #ifdef IPV6_RECVRTHDR	/* 2292bis */
650 		rthlen = CMSG_SPACE(inet6_rth_space(IPV6_RTHDR_TYPE_0,
651 		    argc - 1));
652 #else  /* RFC2292 */
653 		rthlen = inet6_rthdr_space(IPV6_RTHDR_TYPE_0, argc - 1);
654 #endif
655 		if (rthlen == 0) {
656 			errx(1, "too many intermediate hops");
657 			/*NOTREACHED*/
658 		}
659 		ip6optlen += rthlen;
660 	}
661 
662 	if (options & F_NIGROUP) {
663 		target = nigroup(argv[argc - 1], nig_oldmcprefix);
664 		if (target == NULL) {
665 			usage();
666 			/*NOTREACHED*/
667 		}
668 	} else
669 		target = argv[argc - 1];
670 
671 	/* cap_getaddrinfo */
672 	memset(&hints, 0, sizeof(struct addrinfo));
673 	hints.ai_flags = AI_CANONNAME;
674 	hints.ai_family = AF_INET6;
675 	hints.ai_socktype = SOCK_RAW;
676 	hints.ai_protocol = IPPROTO_ICMPV6;
677 
678 	error = cap_getaddrinfo(capdns, target, NULL, &hints, &res);
679 	if (error)
680 		errx(1, "%s", gai_strerror(error));
681 	if (res->ai_canonname)
682 		hostname = strdup(res->ai_canonname);
683 	else
684 		hostname = target;
685 
686 	if (!res->ai_addr)
687 		errx(1, "cap_getaddrinfo failed");
688 
689 	(void)memcpy(&dst, res->ai_addr, res->ai_addrlen);
690 
691 	if ((ssend = socket(res->ai_family, res->ai_socktype,
692 	    res->ai_protocol)) < 0)
693 		err(1, "socket ssend");
694 	if ((srecv = socket(res->ai_family, res->ai_socktype,
695 	    res->ai_protocol)) < 0)
696 		err(1, "socket srecv");
697 	freeaddrinfo(res);
698 
699 	/* set the source address if specified. */
700 	if ((options & F_SRCADDR) != 0) {
701 		/* properly fill sin6_scope_id */
702 		if (IN6_IS_ADDR_LINKLOCAL(&src.sin6_addr) && (
703 		    IN6_IS_ADDR_LINKLOCAL(&dst.sin6_addr) ||
704 		    IN6_IS_ADDR_MC_LINKLOCAL(&dst.sin6_addr) ||
705 		    IN6_IS_ADDR_MC_NODELOCAL(&dst.sin6_addr))) {
706 			if (src.sin6_scope_id == 0)
707 				src.sin6_scope_id = dst.sin6_scope_id;
708 			if (dst.sin6_scope_id == 0)
709 				dst.sin6_scope_id = src.sin6_scope_id;
710 		}
711 		if (bind(ssend, (struct sockaddr *)&src, srclen) != 0)
712 			err(1, "bind");
713 	}
714 	/* set the gateway (next hop) if specified */
715 	if (gateway) {
716 		memset(&hints, 0, sizeof(hints));
717 		hints.ai_family = AF_INET6;
718 		hints.ai_socktype = SOCK_RAW;
719 		hints.ai_protocol = IPPROTO_ICMPV6;
720 
721 		error = cap_getaddrinfo(capdns, gateway, NULL, &hints, &res);
722 		if (error) {
723 			errx(1, "cap_getaddrinfo for the gateway %s: %s",
724 			     gateway, gai_strerror(error));
725 		}
726 		if (res->ai_next && (options & F_VERBOSE))
727 			warnx("gateway resolves to multiple addresses");
728 
729 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_NEXTHOP,
730 		    res->ai_addr, res->ai_addrlen)) {
731 			err(1, "setsockopt(IPV6_NEXTHOP)");
732 		}
733 
734 		freeaddrinfo(res);
735 	}
736 
737 	/*
738 	 * let the kerel pass extension headers of incoming packets,
739 	 * for privileged socket options
740 	 */
741 	if ((options & F_VERBOSE) != 0) {
742 		int opton = 1;
743 
744 #ifdef IPV6_RECVHOPOPTS
745 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &opton,
746 		    sizeof(opton)))
747 			err(1, "setsockopt(IPV6_RECVHOPOPTS)");
748 #else  /* old adv. API */
749 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPOPTS, &opton,
750 		    sizeof(opton)))
751 			err(1, "setsockopt(IPV6_HOPOPTS)");
752 #endif
753 #ifdef IPV6_RECVDSTOPTS
754 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &opton,
755 		    sizeof(opton)))
756 			err(1, "setsockopt(IPV6_RECVDSTOPTS)");
757 #else  /* old adv. API */
758 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_DSTOPTS, &opton,
759 		    sizeof(opton)))
760 			err(1, "setsockopt(IPV6_DSTOPTS)");
761 #endif
762 #ifdef IPV6_RECVRTHDRDSTOPTS
763 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDRDSTOPTS, &opton,
764 		    sizeof(opton)))
765 			err(1, "setsockopt(IPV6_RECVRTHDRDSTOPTS)");
766 #endif
767 	}
768 
769 	/* revoke root privilege */
770 	if (seteuid(getuid()) != 0)
771 		err(1, "seteuid() failed");
772 	if (setuid(getuid()) != 0)
773 		err(1, "setuid() failed");
774 
775 	if ((options & F_FLOOD) && (options & F_INTERVAL))
776 		errx(1, "-f and -i incompatible options");
777 
778 	if ((options & F_NOUSERDATA) == 0) {
779 		if (datalen >= sizeof(struct tv32)) {
780 			/* we can time transfer */
781 			timing = 1;
782 		} else
783 			timing = 0;
784 		/* in F_VERBOSE case, we may get non-echoreply packets*/
785 		if (options & F_VERBOSE)
786 			packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
787 		else
788 			packlen = datalen + IP6LEN + ICMP6ECHOLEN + EXTRA;
789 	} else {
790 		/* suppress timing for node information query */
791 		timing = 0;
792 		datalen = 2048;
793 		packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
794 	}
795 
796 	if (!(packet = (u_char *)malloc((u_int)packlen)))
797 		err(1, "Unable to allocate packet");
798 	if (!(options & F_PINGFILLED))
799 		for (i = ICMP6ECHOLEN; i < packlen; ++i)
800 			*datap++ = i;
801 
802 	ident = getpid() & 0xFFFF;
803 	arc4random_buf(nonce, sizeof(nonce));
804 	optval = 1;
805 	if (options & F_DONTFRAG)
806 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_DONTFRAG,
807 		    &optval, sizeof(optval)) == -1)
808 			err(1, "IPV6_DONTFRAG");
809 	hold = 1;
810 
811 	if (options & F_SO_DEBUG) {
812 		(void)setsockopt(ssend, SOL_SOCKET, SO_DEBUG, (char *)&hold,
813 		    sizeof(hold));
814 		(void)setsockopt(srecv, SOL_SOCKET, SO_DEBUG, (char *)&hold,
815 		    sizeof(hold));
816 	}
817 	optval = IPV6_DEFHLIM;
818 	if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
819 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
820 		    &optval, sizeof(optval)) == -1)
821 			err(1, "IPV6_MULTICAST_HOPS");
822 #ifdef IPV6_USE_MIN_MTU
823 	if (mflag != 1) {
824 		optval = mflag > 1 ? 0 : 1;
825 
826 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
827 		    &optval, sizeof(optval)) == -1)
828 			err(1, "setsockopt(IPV6_USE_MIN_MTU)");
829 	}
830 #ifdef IPV6_RECVPATHMTU
831 	else {
832 		optval = 1;
833 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVPATHMTU,
834 		    &optval, sizeof(optval)) == -1)
835 			err(1, "setsockopt(IPV6_RECVPATHMTU)");
836 	}
837 #endif /* IPV6_RECVPATHMTU */
838 #endif /* IPV6_USE_MIN_MTU */
839 
840 #ifdef IPSEC
841 #ifdef IPSEC_POLICY_IPSEC
842 	if (options & F_POLICY) {
843 		if (setpolicy(srecv, policy_in) < 0)
844 			errx(1, "%s", ipsec_strerror());
845 		if (setpolicy(ssend, policy_out) < 0)
846 			errx(1, "%s", ipsec_strerror());
847 	}
848 #else
849 	if (options & F_AUTHHDR) {
850 		optval = IPSEC_LEVEL_REQUIRE;
851 #ifdef IPV6_AUTH_TRANS_LEVEL
852 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL,
853 		    &optval, sizeof(optval)) == -1)
854 			err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)");
855 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL,
856 		     &optval, sizeof(optval)) == -1)
857 			err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)");
858 #else /* old def */
859 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_AUTH_LEVEL,
860 		    &optval, sizeof(optval)) == -1)
861 			err(1, "setsockopt(IPV6_AUTH_LEVEL)");
862 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_AUTH_LEVEL,
863 		    &optval, sizeof(optval)) == -1)
864 			err(1, "setsockopt(IPV6_AUTH_LEVEL)");
865 #endif
866 	}
867 	if (options & F_ENCRYPT) {
868 		optval = IPSEC_LEVEL_REQUIRE;
869 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL,
870 		    &optval, sizeof(optval)) == -1)
871 			err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)");
872 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL,
873 		    &optval, sizeof(optval)) == -1)
874 			err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)");
875 	}
876 #endif /*IPSEC_POLICY_IPSEC*/
877 #endif
878 
879 #ifdef ICMP6_FILTER
880     {
881 	struct icmp6_filter filt;
882 	if (!(options & F_VERBOSE)) {
883 		ICMP6_FILTER_SETBLOCKALL(&filt);
884 		if ((options & F_FQDN) || (options & F_FQDNOLD) ||
885 		    (options & F_NODEADDR) || (options & F_SUPTYPES))
886 			ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filt);
887 		else
888 			ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
889 	} else {
890 		ICMP6_FILTER_SETPASSALL(&filt);
891 	}
892 	if (setsockopt(srecv, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
893 	    sizeof(filt)) < 0)
894 		err(1, "setsockopt(ICMP6_FILTER)");
895     }
896 #endif /*ICMP6_FILTER*/
897 
898 	/* let the kerel pass extension headers of incoming packets */
899 	if ((options & F_VERBOSE) != 0) {
900 		int opton = 1;
901 
902 #ifdef IPV6_RECVRTHDR
903 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDR, &opton,
904 		    sizeof(opton)))
905 			err(1, "setsockopt(IPV6_RECVRTHDR)");
906 #else  /* old adv. API */
907 		if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RTHDR, &opton,
908 		    sizeof(opton)))
909 			err(1, "setsockopt(IPV6_RTHDR)");
910 #endif
911 	}
912 
913 /*
914 	optval = 1;
915 	if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
916 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
917 		    &optval, sizeof(optval)) == -1)
918 			err(1, "IPV6_MULTICAST_LOOP");
919 */
920 
921 	/* Specify the outgoing interface and/or the source address */
922 	if (usepktinfo)
923 		ip6optlen += CMSG_SPACE(sizeof(struct in6_pktinfo));
924 
925 	if (hoplimit != -1)
926 		ip6optlen += CMSG_SPACE(sizeof(int));
927 
928 	/* set IP6 packet options */
929 	if (ip6optlen) {
930 		if ((scmsg = (char *)malloc(ip6optlen)) == NULL)
931 			errx(1, "can't allocate enough memory");
932 		smsghdr.msg_control = (caddr_t)scmsg;
933 		smsghdr.msg_controllen = ip6optlen;
934 		scmsgp = CMSG_FIRSTHDR(&smsghdr);
935 	}
936 	if (usepktinfo) {
937 		cmsg_pktinfo = CMSG_DATA(scmsgp);
938 		scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
939 		scmsgp->cmsg_level = IPPROTO_IPV6;
940 		scmsgp->cmsg_type = IPV6_PKTINFO;
941 		scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
942 	}
943 
944 	/* set the outgoing interface */
945 	if (ifname) {
946 #ifndef USE_SIN6_SCOPE_ID
947 		/* pktinfo must have already been allocated */
948 		if ((pktinfo.ipi6_ifindex = if_nametoindex(ifname)) == 0)
949 			errx(1, "%s: invalid interface name", ifname);
950 #else
951 		if ((dst.sin6_scope_id = if_nametoindex(ifname)) == 0)
952 			errx(1, "%s: invalid interface name", ifname);
953 #endif
954 	}
955 	if (hoplimit != -1) {
956 		scmsgp->cmsg_len = CMSG_LEN(sizeof(int));
957 		scmsgp->cmsg_level = IPPROTO_IPV6;
958 		scmsgp->cmsg_type = IPV6_HOPLIMIT;
959 		memcpy(CMSG_DATA(scmsgp), &hoplimit, sizeof(hoplimit));
960 
961 		scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
962 	}
963 
964 	if (tclass != -1) {
965 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_TCLASS,
966 		    &tclass, sizeof(tclass)) == -1)
967 			err(1, "setsockopt(IPV6_TCLASS)");
968 	}
969 
970 	if (pcp != -2) {
971 		if (setsockopt(ssend, IPPROTO_IPV6, IPV6_VLAN_PCP,
972 		    &pcp, sizeof(pcp)) == -1)
973 			err(1, "setsockopt(IPV6_VLAN_PCP)");
974 	}
975 
976 	if (argc > 1) {	/* some intermediate addrs are specified */
977 		int hops;
978 		int rthdrlen;
979 
980 		rthdrlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1);
981 		scmsgp->cmsg_len = CMSG_LEN(rthdrlen);
982 		scmsgp->cmsg_level = IPPROTO_IPV6;
983 		scmsgp->cmsg_type = IPV6_RTHDR;
984 		rthdr = (struct ip6_rthdr *)CMSG_DATA(scmsgp);
985 		rthdr = inet6_rth_init((void *)rthdr, rthdrlen,
986 		    IPV6_RTHDR_TYPE_0, argc - 1);
987 		if (rthdr == NULL)
988 			errx(1, "can't initialize rthdr");
989 
990 		for (hops = 0; hops < argc - 1; hops++) {
991 			memset(&hints, 0, sizeof(hints));
992 			hints.ai_family = AF_INET6;
993 
994 			if ((error = cap_getaddrinfo(capdns, argv[hops], NULL, &hints,
995 			    &res)))
996 				errx(1, "%s", gai_strerror(error));
997 			if (res->ai_addr->sa_family != AF_INET6)
998 				errx(1,
999 				    "bad addr family of an intermediate addr");
1000 			sin6 = (struct sockaddr_in6 *)(void *)res->ai_addr;
1001 			if (inet6_rth_add(rthdr, &sin6->sin6_addr))
1002 				errx(1, "can't add an intermediate node");
1003 			freeaddrinfo(res);
1004 		}
1005 
1006 		scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
1007 	}
1008 
1009 	/* From now on we will use only reverse DNS lookups. */
1010 #ifdef WITH_CASPER
1011 	if (capdns != NULL) {
1012 		const char *types[1];
1013 
1014 		types[0] = "ADDR2NAME";
1015 		if (cap_dns_type_limit(capdns, types, nitems(types)) < 0)
1016 			err(1, "unable to limit access to system.dns service");
1017 	}
1018 #endif
1019 	if (!(options & F_SRCADDR)) {
1020 		/*
1021 		 * get the source address. XXX since we revoked the root
1022 		 * privilege, we cannot use a raw socket for this.
1023 		 */
1024 		int dummy;
1025 		socklen_t len = sizeof(src);
1026 
1027 		if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1028 			err(1, "UDP socket");
1029 
1030 		src.sin6_family = AF_INET6;
1031 		src.sin6_addr = dst.sin6_addr;
1032 		src.sin6_port = ntohs(DUMMY_PORT);
1033 		src.sin6_scope_id = dst.sin6_scope_id;
1034 
1035 		if (usepktinfo &&
1036 		    setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTINFO,
1037 		    (void *)&pktinfo, sizeof(pktinfo)))
1038 			err(1, "UDP setsockopt(IPV6_PKTINFO)");
1039 
1040 		if (hoplimit != -1 &&
1041 		    setsockopt(dummy, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1042 		    (void *)&hoplimit, sizeof(hoplimit)))
1043 			err(1, "UDP setsockopt(IPV6_UNICAST_HOPS)");
1044 
1045 		if (hoplimit != -1 &&
1046 		    setsockopt(dummy, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1047 		    (void *)&hoplimit, sizeof(hoplimit)))
1048 			err(1, "UDP setsockopt(IPV6_MULTICAST_HOPS)");
1049 
1050 		if (rthdr &&
1051 		    setsockopt(dummy, IPPROTO_IPV6, IPV6_RTHDR,
1052 		    (void *)rthdr, (rthdr->ip6r_len + 1) << 3))
1053 			err(1, "UDP setsockopt(IPV6_RTHDR)");
1054 
1055 		if (connect(dummy, (struct sockaddr *)&src, len) < 0)
1056 			err(1, "UDP connect");
1057 
1058 		if (getsockname(dummy, (struct sockaddr *)&src, &len) < 0)
1059 			err(1, "getsockname");
1060 
1061 		close(dummy);
1062 	}
1063 
1064 	/* Save pktinfo in the ancillary data. */
1065 	if (usepktinfo)
1066 		memcpy(cmsg_pktinfo, &pktinfo, sizeof(pktinfo));
1067 
1068 	if (connect(ssend, (struct sockaddr *)&dst, sizeof(dst)) != 0)
1069 		err(1, "connect() ssend");
1070 
1071 	caph_cache_catpages();
1072 	if (caph_enter_casper() < 0)
1073 		err(1, "caph_enter_casper");
1074 
1075 	cap_rights_init(&rights_stdin);
1076 	if (caph_rights_limit(STDIN_FILENO, &rights_stdin) < 0)
1077 		err(1, "caph_rights_limit stdin");
1078 	if (caph_limit_stdout() < 0)
1079 		err(1, "caph_limit_stdout");
1080 	if (caph_limit_stderr() < 0)
1081 		err(1, "caph_limit_stderr");
1082 
1083 	cap_rights_init(&rights_srecv, CAP_RECV, CAP_EVENT, CAP_SETSOCKOPT);
1084 	if (caph_rights_limit(srecv, &rights_srecv) < 0)
1085 		err(1, "caph_rights_limit srecv");
1086 	cap_rights_init(&rights_ssend, CAP_SEND, CAP_SETSOCKOPT);
1087 	if (caph_rights_limit(ssend, &rights_ssend) < 0)
1088 		err(1, "caph_rights_limit ssend");
1089 
1090 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
1091 	if (sockbufsize) {
1092 		if (datalen > (size_t)sockbufsize)
1093 			warnx("you need -b to increase socket buffer size");
1094 		if (setsockopt(ssend, SOL_SOCKET, SO_SNDBUF, &sockbufsize,
1095 		    sizeof(sockbufsize)) < 0)
1096 			err(1, "setsockopt(SO_SNDBUF)");
1097 		if (setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, &sockbufsize,
1098 		    sizeof(sockbufsize)) < 0)
1099 			err(1, "setsockopt(SO_RCVBUF)");
1100 	}
1101 	else {
1102 		if (datalen > 8 * 1024)	/*XXX*/
1103 			warnx("you need -b to increase socket buffer size");
1104 		/*
1105 		 * When pinging the broadcast address, you can get a lot of
1106 		 * answers. Doing something so evil is useful if you are trying
1107 		 * to stress the ethernet, or just want to fill the arp cache
1108 		 * to get some stuff for /etc/ethers.
1109 		 */
1110 		hold = 48 * 1024;
1111 		setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
1112 		    sizeof(hold));
1113 	}
1114 #endif
1115 
1116 	optval = 1;
1117 #ifndef USE_SIN6_SCOPE_ID
1118 #ifdef IPV6_RECVPKTINFO
1119 	if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVPKTINFO, &optval,
1120 	    sizeof(optval)) < 0)
1121 		warn("setsockopt(IPV6_RECVPKTINFO)"); /* XXX err? */
1122 #else  /* old adv. API */
1123 	if (setsockopt(srecv, IPPROTO_IPV6, IPV6_PKTINFO, &optval,
1124 	    sizeof(optval)) < 0)
1125 		warn("setsockopt(IPV6_PKTINFO)"); /* XXX err? */
1126 #endif
1127 #endif /* USE_SIN6_SCOPE_ID */
1128 #ifdef IPV6_RECVHOPLIMIT
1129 	if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &optval,
1130 	    sizeof(optval)) < 0)
1131 		warn("setsockopt(IPV6_RECVHOPLIMIT)"); /* XXX err? */
1132 #else  /* old adv. API */
1133 	if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPLIMIT, &optval,
1134 	    sizeof(optval)) < 0)
1135 		warn("setsockopt(IPV6_HOPLIMIT)"); /* XXX err? */
1136 #endif
1137 
1138 	cap_rights_clear(&rights_srecv, CAP_SETSOCKOPT);
1139 	if (caph_rights_limit(srecv, &rights_srecv) < 0)
1140 		err(1, "caph_rights_limit srecv setsockopt");
1141 	cap_rights_clear(&rights_ssend, CAP_SETSOCKOPT);
1142 	if (caph_rights_limit(ssend, &rights_ssend) < 0)
1143 		err(1, "caph_rights_limit ssend setsockopt");
1144 
1145 	printf("PING6(%lu=40+8+%lu bytes) ", (unsigned long)(40 + pingerlen()),
1146 	    (unsigned long)(pingerlen() - 8));
1147 	printf("%s --> ", pr_addr((struct sockaddr *)&src, sizeof(src)));
1148 	printf("%s\n", pr_addr((struct sockaddr *)&dst, sizeof(dst)));
1149 
1150 	if (preload == 0)
1151 		pinger();
1152 	else {
1153 		if (npackets != 0 && preload > npackets)
1154 			preload = npackets;
1155 		while (preload--)
1156 			pinger();
1157 	}
1158 	clock_gettime(CLOCK_MONOTONIC, &last);
1159 
1160 	sigemptyset(&si_sa.sa_mask);
1161 	si_sa.sa_flags = 0;
1162 	si_sa.sa_handler = onsignal;
1163 	if (sigaction(SIGINT, &si_sa, 0) == -1)
1164 		err(EX_OSERR, "sigaction SIGINT");
1165 	seenint = 0;
1166 #ifdef SIGINFO
1167 	if (sigaction(SIGINFO, &si_sa, 0) == -1)
1168 		err(EX_OSERR, "sigaction SIGINFO");
1169 	seeninfo = 0;
1170 #endif
1171 	if (alarmtimeout > 0) {
1172 		if (sigaction(SIGALRM, &si_sa, 0) == -1)
1173 			err(EX_OSERR, "sigaction SIGALRM");
1174 	}
1175 	if (options & F_FLOOD) {
1176 		intvl.tv_sec = 0;
1177 		intvl.tv_nsec = 10000000;
1178 	}
1179 
1180 	almost_done = 0;
1181 	while (seenint == 0) {
1182 		struct timespec now, timeout;
1183 		struct msghdr m;
1184 		struct iovec iov[2];
1185 		fd_set rfds;
1186 		int n;
1187 
1188 		/* signal handling */
1189 		if (seenint)
1190 			onint(SIGINT);
1191 #ifdef SIGINFO
1192 		if (seeninfo) {
1193 			summary();
1194 			seeninfo = 0;
1195 			continue;
1196 		}
1197 #endif
1198 		FD_ZERO(&rfds);
1199 		FD_SET(srecv, &rfds);
1200 		clock_gettime(CLOCK_MONOTONIC, &now);
1201 		timespecadd(&last, &intvl, &timeout);
1202 		timespecsub(&timeout, &now, &timeout);
1203 		if (timeout.tv_sec < 0)
1204 			timespecclear(&timeout);
1205 
1206 		n = pselect(srecv + 1, &rfds, NULL, NULL, &timeout, NULL);
1207 		if (n < 0)
1208 			continue;	/* EINTR */
1209 		if (n == 1) {
1210 			m.msg_name = (caddr_t)&from;
1211 			m.msg_namelen = sizeof(from);
1212 			memset(&iov, 0, sizeof(iov));
1213 			iov[0].iov_base = (caddr_t)packet;
1214 			iov[0].iov_len = packlen;
1215 			m.msg_iov = iov;
1216 			m.msg_iovlen = 1;
1217 			memset(cm, 0, CONTROLLEN);
1218 			m.msg_control = (void *)cm;
1219 			m.msg_controllen = CONTROLLEN;
1220 
1221 			cc = recvmsg(srecv, &m, 0);
1222 			if (cc < 0) {
1223 				if (errno != EINTR) {
1224 					warn("recvmsg");
1225 					sleep(1);
1226 				}
1227 				continue;
1228 			} else if (cc == 0) {
1229 				int mtu;
1230 
1231 				/*
1232 				 * receive control messages only. Process the
1233 				 * exceptions (currently the only possibility is
1234 				 * a path MTU notification.)
1235 				 */
1236 				if ((mtu = get_pathmtu(&m)) > 0) {
1237 					if ((options & F_VERBOSE) != 0) {
1238 						printf("new path MTU (%d) is "
1239 						    "notified\n", mtu);
1240 					}
1241 				}
1242 				continue;
1243 			} else {
1244 				/*
1245 				 * an ICMPv6 message (probably an echoreply)
1246 				 * arrived.
1247 				 */
1248 				pr_pack(packet, cc, &m);
1249 			}
1250 			if (((options & F_ONCE) != 0 && nreceived > 0) ||
1251 			    (npackets > 0 && nreceived >= npackets))
1252 				break;
1253 		}
1254 		if (n == 0 || (options & F_FLOOD)) {
1255 			if (npackets == 0 || ntransmitted < npackets)
1256 				pinger();
1257 			else {
1258 				if (almost_done)
1259 					break;
1260 				almost_done = 1;
1261 			/*
1262 			 * If we're not transmitting any more packets,
1263 			 * change the timer to wait two round-trip times
1264 			 * if we've received any packets or (waittime)
1265 			 * milliseconds if we haven't.
1266 			 */
1267 				intvl.tv_nsec = 0;
1268 				if (nreceived) {
1269 					intvl.tv_sec = 2 * tmax / 1000;
1270 					if (intvl.tv_sec == 0)
1271 						intvl.tv_sec = 1;
1272 				} else {
1273 					intvl.tv_sec = waittime / 1000;
1274 					intvl.tv_nsec =
1275 						waittime % 1000 * 1000000;
1276 				}
1277 			}
1278 			clock_gettime(CLOCK_MONOTONIC, &last);
1279 			if (ntransmitted - nreceived - 1 > nmissedmax) {
1280 				nmissedmax = ntransmitted - nreceived - 1;
1281 				if (options & F_MISSED)
1282 					(void)write(STDOUT_FILENO, &BBELL, 1);
1283 			}
1284 		}
1285 	}
1286 	sigemptyset(&si_sa.sa_mask);
1287 	si_sa.sa_flags = 0;
1288 	si_sa.sa_handler = SIG_IGN;
1289 	sigaction(SIGINT, &si_sa, 0);
1290 	sigaction(SIGALRM, &si_sa, 0);
1291 	summary();
1292 
1293         if(packet != NULL)
1294                 free(packet);
1295 
1296 	if (nreceived > 0)
1297 		exit(0);
1298 	else if (ntransmitted > ntransmitfailures)
1299 		exit(2);
1300 	else
1301 		exit(EX_OSERR);
1302 }
1303 
1304 static void
1305 onsignal(int sig)
1306 {
1307 
1308 	switch (sig) {
1309 	case SIGINT:
1310 	case SIGALRM:
1311 		seenint++;
1312 		break;
1313 #ifdef SIGINFO
1314 	case SIGINFO:
1315 		seeninfo++;
1316 		break;
1317 #endif
1318 	}
1319 }
1320 
1321 /*
1322  * pinger --
1323  *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
1324  * will be added on by the kernel.  The ID field is our UNIX process ID,
1325  * and the sequence number is an ascending integer.  The first 8 bytes
1326  * of the data portion are used to hold a UNIX "timespec" struct in VAX
1327  * byte-order, to compute the round-trip time.
1328  */
1329 static size_t
1330 pingerlen(void)
1331 {
1332 	size_t l;
1333 
1334 	if (options & F_FQDN)
1335 		l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1336 	else if (options & F_FQDNOLD)
1337 		l = ICMP6_NIQLEN;
1338 	else if (options & F_NODEADDR)
1339 		l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1340 	else if (options & F_SUPTYPES)
1341 		l = ICMP6_NIQLEN;
1342 	else
1343 		l = ICMP6ECHOLEN + datalen;
1344 
1345 	return l;
1346 }
1347 
1348 static int
1349 pinger(void)
1350 {
1351 	struct icmp6_hdr *icp;
1352 	struct iovec iov[2];
1353 	int i, cc;
1354 	struct icmp6_nodeinfo *nip;
1355 	uint16_t seq;
1356 
1357 	if (npackets && ntransmitted >= npackets)
1358 		return(-1);	/* no more transmission */
1359 
1360 	icp = (struct icmp6_hdr *)outpack;
1361 	nip = (struct icmp6_nodeinfo *)outpack;
1362 	memset(icp, 0, sizeof(*icp));
1363 	icp->icmp6_cksum = 0;
1364 	seq = ntransmitted++;
1365 	CLR(seq % mx_dup_ck);
1366 
1367 	if (options & F_FQDN) {
1368 		uint16_t s;
1369 
1370 		icp->icmp6_type = ICMP6_NI_QUERY;
1371 		icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1372 		nip->ni_qtype = htons(NI_QTYPE_FQDN);
1373 		nip->ni_flags = htons(0);
1374 
1375 		memcpy(nip->icmp6_ni_nonce, nonce,
1376 		    sizeof(nip->icmp6_ni_nonce));
1377 		s = htons(seq);
1378 		memcpy(nip->icmp6_ni_nonce, &s, sizeof(s));
1379 
1380 		memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1381 		    sizeof(dst.sin6_addr));
1382 		cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1383 		datalen = 0;
1384 	} else if (options & F_FQDNOLD) {
1385 		uint16_t s;
1386 		/* packet format in 03 draft - no Subject data on queries */
1387 		icp->icmp6_type = ICMP6_NI_QUERY;
1388 		icp->icmp6_code = 0;	/* code field is always 0 */
1389 		nip->ni_qtype = htons(NI_QTYPE_FQDN);
1390 		nip->ni_flags = htons(0);
1391 
1392 		memcpy(nip->icmp6_ni_nonce, nonce,
1393 		    sizeof(nip->icmp6_ni_nonce));
1394 		s = htons(seq);
1395 		memcpy(nip->icmp6_ni_nonce, &s, sizeof(s));
1396 
1397 		cc = ICMP6_NIQLEN;
1398 		datalen = 0;
1399 	} else if (options & F_NODEADDR) {
1400 		uint16_t s;
1401 
1402 		icp->icmp6_type = ICMP6_NI_QUERY;
1403 		icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1404 		nip->ni_qtype = htons(NI_QTYPE_NODEADDR);
1405 		nip->ni_flags = naflags;
1406 
1407 		memcpy(nip->icmp6_ni_nonce, nonce,
1408 		    sizeof(nip->icmp6_ni_nonce));
1409 		s = htons(seq);
1410 		memcpy(nip->icmp6_ni_nonce, &s, sizeof(s));
1411 
1412 		memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1413 		    sizeof(dst.sin6_addr));
1414 		cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1415 		datalen = 0;
1416 	} else if (options & F_SUPTYPES) {
1417 		uint16_t s;
1418 
1419 		icp->icmp6_type = ICMP6_NI_QUERY;
1420 		icp->icmp6_code = ICMP6_NI_SUBJ_FQDN;	/*empty*/
1421 		nip->ni_qtype = htons(NI_QTYPE_SUPTYPES);
1422 		/* we support compressed bitmap */
1423 		nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS;
1424 
1425 		memcpy(nip->icmp6_ni_nonce, nonce,
1426 		    sizeof(nip->icmp6_ni_nonce));
1427 		s = htons(seq);
1428 		memcpy(nip->icmp6_ni_nonce, &s, sizeof(s));
1429 
1430 		cc = ICMP6_NIQLEN;
1431 		datalen = 0;
1432 	} else {
1433 		icp->icmp6_type = ICMP6_ECHO_REQUEST;
1434 		icp->icmp6_code = 0;
1435 		icp->icmp6_id = htons(ident);
1436 		icp->icmp6_seq = htons(seq);
1437 		if (timing) {
1438 			struct timespec tv;
1439 			struct tv32 tv32;
1440 			(void)clock_gettime(CLOCK_MONOTONIC, &tv);
1441 			/*
1442 			 * Truncate seconds down to 32 bits in order
1443 			 * to fit the timestamp within 8 bytes of the
1444 			 * packet. We're only concerned with
1445 			 * durations, not absolute times.
1446 			 */
1447 			tv32.tv32_sec = (uint32_t)htonl(tv.tv_sec);
1448 			tv32.tv32_nsec = (uint32_t)htonl(tv.tv_nsec);
1449 			memcpy(&outpack[ICMP6ECHOLEN], &tv32, sizeof(tv32));
1450 		}
1451 		cc = ICMP6ECHOLEN + datalen;
1452 	}
1453 
1454 #ifdef DIAGNOSTIC
1455 	if (pingerlen() != cc)
1456 		errx(1, "internal error; length mismatch");
1457 #endif
1458 
1459 	memset(&iov, 0, sizeof(iov));
1460 	iov[0].iov_base = (caddr_t)outpack;
1461 	iov[0].iov_len = cc;
1462 	smsghdr.msg_iov = iov;
1463 	smsghdr.msg_iovlen = 1;
1464 
1465 	i = sendmsg(ssend, &smsghdr, 0);
1466 
1467 	if (i < 0 || i != cc)  {
1468 		if (i < 0) {
1469 			ntransmitfailures++;
1470 			warn("sendmsg");
1471 		}
1472 		(void)printf("ping6: wrote %s %d chars, ret=%d\n",
1473 		    hostname, cc, i);
1474 	}
1475 	if (!(options & F_QUIET) && options & F_DOT)
1476 		(void)write(STDOUT_FILENO, &DOT[DOTidx++ % DOTlen], 1);
1477 
1478 	return(0);
1479 }
1480 
1481 static int
1482 myechoreply(const struct icmp6_hdr *icp)
1483 {
1484 	if (ntohs(icp->icmp6_id) == ident)
1485 		return 1;
1486 	else
1487 		return 0;
1488 }
1489 
1490 static int
1491 mynireply(const struct icmp6_nodeinfo *nip)
1492 {
1493 	if (memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t),
1494 	    nonce + sizeof(u_int16_t),
1495 	    sizeof(nonce) - sizeof(u_int16_t)) == 0)
1496 		return 1;
1497 	else
1498 		return 0;
1499 }
1500 
1501 /*
1502  * Decode a name from a DNS message.
1503  *
1504  * Format of the message is described in RFC 1035 subsection 4.1.4.
1505  *
1506  * Arguments:
1507  *   sp     - Pointer to a DNS pointer octet or to the first octet of a label
1508  *            in the message.
1509  *   ep     - Pointer to the end of the message (one step past the last octet).
1510  *   base   - Pointer to the beginning of the message.
1511  *   buf    - Buffer into which the decoded name will be saved.
1512  *   bufsiz - Size of the buffer 'buf'.
1513  *
1514  * Return value:
1515  *   Pointer to an octet immediately following the ending zero octet
1516  *   of the decoded label, or NULL if an error occurred.
1517  */
1518 static const char *
1519 dnsdecode(const u_char *sp, const u_char *ep, const u_char *base, char *buf,
1520 	size_t bufsiz)
1521 {
1522 	int i;
1523 	const u_char *cp;
1524 	char cresult[MAXDNAME + 1];
1525 	const u_char *comp;
1526 	int l;
1527 
1528 	cp = sp;
1529 	*buf = '\0';
1530 
1531 	if (cp >= ep)
1532 		return NULL;
1533 	while (cp < ep) {
1534 		i = *cp;
1535 		if (i == 0 || cp != sp) {
1536 			if (strlcat((char *)buf, ".", bufsiz) >= bufsiz)
1537 				return NULL;	/*result overrun*/
1538 		}
1539 		if (i == 0)
1540 			break;
1541 		cp++;
1542 
1543 		if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) {
1544 			/* DNS compression */
1545 			if (!base)
1546 				return NULL;
1547 
1548 			comp = base + (i & 0x3f);
1549 			if (dnsdecode(comp, cp, base, cresult,
1550 			    sizeof(cresult)) == NULL)
1551 				return NULL;
1552 			if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1553 				return NULL;	/*result overrun*/
1554 			break;
1555 		} else if ((i & 0x3f) == i) {
1556 			if (i > ep - cp)
1557 				return NULL;	/*source overrun*/
1558 			while (i-- > 0 && cp < ep) {
1559 				l = snprintf(cresult, sizeof(cresult),
1560 				    isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff);
1561 				if ((size_t)l >= sizeof(cresult) || l < 0)
1562 					return NULL;
1563 				if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1564 					return NULL;	/*result overrun*/
1565 				cp++;
1566 			}
1567 		} else
1568 			return NULL;	/*invalid label*/
1569 	}
1570 	if (i != 0)
1571 		return NULL;	/*not terminated*/
1572 	cp++;
1573 	return cp;
1574 }
1575 
1576 /*
1577  * pr_pack --
1578  *	Print out the packet, if it came from us.  This logic is necessary
1579  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1580  * which arrive ('tis only fair).  This permits multiple copies of this
1581  * program to be run without having intermingled output (or statistics!).
1582  */
1583 static void
1584 pr_pack(u_char *buf, int cc, struct msghdr *mhdr)
1585 {
1586 #define safeputc(c)	printf((isprint((c)) ? "%c" : "\\%03o"), c)
1587 	struct icmp6_hdr *icp;
1588 	struct icmp6_nodeinfo *ni;
1589 	int i;
1590 	int hoplim;
1591 	struct sockaddr *from;
1592 	int fromlen;
1593 	const u_char *cp = NULL;
1594 	u_char *dp, *end = buf + cc;
1595 	struct in6_pktinfo *pktinfo = NULL;
1596 	struct timespec tv, tp;
1597 	struct tv32 tpp;
1598 	double triptime = 0;
1599 	int dupflag;
1600 	size_t off;
1601 	int oldfqdn;
1602 	u_int16_t seq;
1603 	char dnsname[MAXDNAME + 1];
1604 
1605 	(void)clock_gettime(CLOCK_MONOTONIC, &tv);
1606 
1607 	if (!mhdr || !mhdr->msg_name ||
1608 	    mhdr->msg_namelen != sizeof(struct sockaddr_in6) ||
1609 	    ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) {
1610 		if (options & F_VERBOSE)
1611 			warnx("invalid peername");
1612 		return;
1613 	}
1614 	from = (struct sockaddr *)mhdr->msg_name;
1615 	fromlen = mhdr->msg_namelen;
1616 	if (cc < (int)sizeof(struct icmp6_hdr)) {
1617 		if (options & F_VERBOSE)
1618 			warnx("packet too short (%d bytes) from %s", cc,
1619 			    pr_addr(from, fromlen));
1620 		return;
1621 	}
1622 	if (((mhdr->msg_flags & MSG_CTRUNC) != 0) &&
1623 	    (options & F_VERBOSE) != 0)
1624 		warnx("some control data discarded, insufficient buffer size");
1625 	icp = (struct icmp6_hdr *)buf;
1626 	ni = (struct icmp6_nodeinfo *)buf;
1627 	off = 0;
1628 
1629 	if ((hoplim = get_hoplim(mhdr)) == -1) {
1630 		warnx("failed to get receiving hop limit");
1631 		return;
1632 	}
1633 	if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) {
1634 		warnx("failed to get receiving packet information");
1635 		return;
1636 	}
1637 
1638 	if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) {
1639 		seq = ntohs(icp->icmp6_seq);
1640 		++nreceived;
1641 		if (timing) {
1642 			memcpy(&tpp, icp + 1, sizeof(tpp));
1643 			tp.tv_sec = ntohl(tpp.tv32_sec);
1644 			tp.tv_nsec = ntohl(tpp.tv32_nsec);
1645 			timespecsub(&tv, &tp, &tv);
1646 			triptime = ((double)tv.tv_sec) * 1000.0 +
1647 			    ((double)tv.tv_nsec) / 1000000.0;
1648 			tsum += triptime;
1649 			tsumsq += triptime * triptime;
1650 			if (triptime < tmin)
1651 				tmin = triptime;
1652 			if (triptime > tmax)
1653 				tmax = triptime;
1654 		}
1655 
1656 		if (TST(seq % mx_dup_ck)) {
1657 			++nrepeats;
1658 			--nreceived;
1659 			dupflag = 1;
1660 		} else {
1661 			SET(seq % mx_dup_ck);
1662 			dupflag = 0;
1663 		}
1664 
1665 		if (options & F_QUIET)
1666 			return;
1667 
1668 		if (options & F_WAITTIME && triptime > waittime) {
1669 			++nrcvtimeout;
1670 			return;
1671 		}
1672 
1673 		if (options & F_DOT)
1674 			(void)write(STDOUT_FILENO, &BSPACE, 1);
1675 		else {
1676 			if (options & F_AUDIBLE)
1677 				(void)write(STDOUT_FILENO, &BBELL, 1);
1678 			(void)printf("%d bytes from %s, icmp_seq=%u", cc,
1679 			    pr_addr(from, fromlen), seq);
1680 			(void)printf(" hlim=%d", hoplim);
1681 			if ((options & F_VERBOSE) != 0) {
1682 				struct sockaddr_in6 dstsa;
1683 
1684 				memset(&dstsa, 0, sizeof(dstsa));
1685 				dstsa.sin6_family = AF_INET6;
1686 				dstsa.sin6_len = sizeof(dstsa);
1687 				dstsa.sin6_scope_id = pktinfo->ipi6_ifindex;
1688 				dstsa.sin6_addr = pktinfo->ipi6_addr;
1689 				(void)printf(" dst=%s",
1690 				    pr_addr((struct sockaddr *)&dstsa,
1691 				    sizeof(dstsa)));
1692 			}
1693 			if (timing)
1694 				(void)printf(" time=%.3f ms", triptime);
1695 			if (dupflag)
1696 				(void)printf("(DUP!)");
1697 			/* check the data */
1698 			cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1699 			dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1700 			for (i = 8; cp < end; ++i, ++cp, ++dp) {
1701 				if (*cp != *dp) {
1702 					(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp);
1703 					break;
1704 				}
1705 			}
1706 		}
1707 	} else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) {
1708 		memcpy(&seq, ni->icmp6_ni_nonce, sizeof(seq));
1709 		seq = ntohs(seq);
1710 		++nreceived;
1711 		if (TST(seq % mx_dup_ck)) {
1712 			++nrepeats;
1713 			--nreceived;
1714 			dupflag = 1;
1715 		} else {
1716 			SET(seq % mx_dup_ck);
1717 			dupflag = 0;
1718 		}
1719 
1720 		if (options & F_QUIET)
1721 			return;
1722 
1723 		(void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1724 
1725 		switch (ntohs(ni->ni_code)) {
1726 		case ICMP6_NI_SUCCESS:
1727 			break;
1728 		case ICMP6_NI_REFUSED:
1729 			printf("refused, type 0x%x", ntohs(ni->ni_type));
1730 			goto fqdnend;
1731 		case ICMP6_NI_UNKNOWN:
1732 			printf("unknown, type 0x%x", ntohs(ni->ni_type));
1733 			goto fqdnend;
1734 		default:
1735 			printf("unknown code 0x%x, type 0x%x",
1736 			    ntohs(ni->ni_code), ntohs(ni->ni_type));
1737 			goto fqdnend;
1738 		}
1739 
1740 		switch (ntohs(ni->ni_qtype)) {
1741 		case NI_QTYPE_NOOP:
1742 			printf("NodeInfo NOOP");
1743 			break;
1744 		case NI_QTYPE_SUPTYPES:
1745 			pr_suptypes(ni, end - (u_char *)ni);
1746 			break;
1747 		case NI_QTYPE_NODEADDR:
1748 			pr_nodeaddr(ni, end - (u_char *)ni);
1749 			break;
1750 		case NI_QTYPE_FQDN:
1751 		default:	/* XXX: for backward compatibility */
1752 			cp = (u_char *)ni + ICMP6_NIRLEN;
1753 			if (buf[off + ICMP6_NIRLEN] ==
1754 			    cc - off - ICMP6_NIRLEN - 1)
1755 				oldfqdn = 1;
1756 			else
1757 				oldfqdn = 0;
1758 			if (oldfqdn) {
1759 				cp++;	/* skip length */
1760 				while (cp < end) {
1761 					safeputc(*cp & 0xff);
1762 					cp++;
1763 				}
1764 			} else {
1765 				i = 0;
1766 				while (cp < end) {
1767 					cp = dnsdecode((const u_char *)cp, end,
1768 					    (const u_char *)(ni + 1), dnsname,
1769 					    sizeof(dnsname));
1770 					if (cp == NULL) {
1771 						printf("???");
1772 						break;
1773 					}
1774 					/*
1775 					 * name-lookup special handling for
1776 					 * truncated name
1777 					 */
1778 					if (cp + 1 <= end && !*cp &&
1779 					    strlen(dnsname) > 0) {
1780 						dnsname[strlen(dnsname) - 1] = '\0';
1781 						cp++;
1782 					}
1783 					printf("%s%s", i > 0 ? "," : "",
1784 					    dnsname);
1785 				}
1786 			}
1787 			if (options & F_VERBOSE) {
1788 				u_long t;
1789 				int32_t ttl;
1790 				int comma = 0;
1791 
1792 				(void)printf(" (");	/*)*/
1793 
1794 				switch (ni->ni_code) {
1795 				case ICMP6_NI_REFUSED:
1796 					(void)printf("refused");
1797 					comma++;
1798 					break;
1799 				case ICMP6_NI_UNKNOWN:
1800 					(void)printf("unknown qtype");
1801 					comma++;
1802 					break;
1803 				}
1804 
1805 				if ((end - (u_char *)ni) < ICMP6_NIRLEN) {
1806 					/* case of refusion, unknown */
1807 					/*(*/
1808 					putchar(')');
1809 					goto fqdnend;
1810 				}
1811 				memcpy(&t, &buf[off+ICMP6ECHOLEN+8], sizeof(t));
1812 				ttl = (int32_t)ntohl(t);
1813 				if (comma)
1814 					printf(",");
1815 				if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) {
1816 					(void)printf("TTL=%d:meaningless",
1817 					    (int)ttl);
1818 				} else {
1819 					if (ttl < 0) {
1820 						(void)printf("TTL=%d:invalid",
1821 						   ttl);
1822 					} else
1823 						(void)printf("TTL=%d", ttl);
1824 				}
1825 				comma++;
1826 
1827 				if (oldfqdn) {
1828 					if (comma)
1829 						printf(",");
1830 					printf("03 draft");
1831 					comma++;
1832 				} else {
1833 					cp = (u_char *)ni + ICMP6_NIRLEN;
1834 					if (cp == end) {
1835 						if (comma)
1836 							printf(",");
1837 						printf("no name");
1838 						comma++;
1839 					}
1840 				}
1841 
1842 				if (buf[off + ICMP6_NIRLEN] !=
1843 				    cc - off - ICMP6_NIRLEN - 1 && oldfqdn) {
1844 					if (comma)
1845 						printf(",");
1846 					(void)printf("invalid namelen:%d/%lu",
1847 					    buf[off + ICMP6_NIRLEN],
1848 					    (u_long)cc - off - ICMP6_NIRLEN - 1);
1849 					comma++;
1850 				}
1851 				/*(*/
1852 				putchar(')');
1853 			}
1854 		fqdnend:
1855 			;
1856 		}
1857 	} else {
1858 		/* We've got something other than an ECHOREPLY */
1859 		if (!(options & F_VERBOSE))
1860 			return;
1861 		(void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1862 		pr_icmph(icp, end);
1863 	}
1864 
1865 	if (!(options & F_DOT)) {
1866 		(void)putchar('\n');
1867 		if (options & F_VERBOSE)
1868 			pr_exthdrs(mhdr);
1869 		(void)fflush(stdout);
1870 	}
1871 #undef safeputc
1872 }
1873 
1874 static void
1875 pr_exthdrs(struct msghdr *mhdr)
1876 {
1877 	ssize_t	bufsize;
1878 	void	*bufp;
1879 	struct cmsghdr *cm;
1880 
1881 	bufsize = 0;
1882 	bufp = mhdr->msg_control;
1883 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1884 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1885 		if (cm->cmsg_level != IPPROTO_IPV6)
1886 			continue;
1887 
1888 		bufsize = CONTROLLEN - ((caddr_t)CMSG_DATA(cm) - (caddr_t)bufp);
1889 		if (bufsize <= 0)
1890 			continue;
1891 		switch (cm->cmsg_type) {
1892 		case IPV6_HOPOPTS:
1893 			printf("  HbH Options: ");
1894 			pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1895 			break;
1896 		case IPV6_DSTOPTS:
1897 #ifdef IPV6_RTHDRDSTOPTS
1898 		case IPV6_RTHDRDSTOPTS:
1899 #endif
1900 			printf("  Dst Options: ");
1901 			pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1902 			break;
1903 		case IPV6_RTHDR:
1904 			printf("  Routing: ");
1905 			pr_rthdr(CMSG_DATA(cm), (size_t)bufsize);
1906 			break;
1907 		}
1908 	}
1909 }
1910 
1911 static void
1912 pr_ip6opt(void *extbuf, size_t bufsize)
1913 {
1914 	struct ip6_hbh *ext;
1915 	int currentlen;
1916 	u_int8_t type;
1917 	socklen_t extlen, len;
1918 	void *databuf;
1919 	size_t offset;
1920 	u_int16_t value2;
1921 	u_int32_t value4;
1922 
1923 	ext = (struct ip6_hbh *)extbuf;
1924 	extlen = (ext->ip6h_len + 1) * 8;
1925 	printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt,
1926 	    (unsigned int)ext->ip6h_len, (unsigned long)extlen);
1927 
1928 	/*
1929 	 * Bounds checking on the ancillary data buffer:
1930 	 *     subtract the size of a cmsg structure from the buffer size.
1931 	 */
1932 	if (bufsize < (extlen  + CMSG_SPACE(0))) {
1933 		extlen = bufsize - CMSG_SPACE(0);
1934 		warnx("options truncated, showing only %u (total=%u)",
1935 		    (unsigned int)(extlen / 8 - 1),
1936 		    (unsigned int)(ext->ip6h_len));
1937 	}
1938 
1939 	currentlen = 0;
1940 	while (1) {
1941 		currentlen = inet6_opt_next(extbuf, extlen, currentlen,
1942 		    &type, &len, &databuf);
1943 		if (currentlen == -1)
1944 			break;
1945 		switch (type) {
1946 		/*
1947 		 * Note that inet6_opt_next automatically skips any padding
1948 		 * optins.
1949 		 */
1950 		case IP6OPT_JUMBO:
1951 			offset = 0;
1952 			offset = inet6_opt_get_val(databuf, offset,
1953 			    &value4, sizeof(value4));
1954 			printf("    Jumbo Payload Opt: Length %u\n",
1955 			    (u_int32_t)ntohl(value4));
1956 			break;
1957 		case IP6OPT_ROUTER_ALERT:
1958 			offset = 0;
1959 			offset = inet6_opt_get_val(databuf, offset,
1960 						   &value2, sizeof(value2));
1961 			printf("    Router Alert Opt: Type %u\n",
1962 			    ntohs(value2));
1963 			break;
1964 		default:
1965 			printf("    Received Opt %u len %lu\n",
1966 			    type, (unsigned long)len);
1967 			break;
1968 		}
1969 	}
1970 	return;
1971 }
1972 
1973 static void
1974 pr_rthdr(void *extbuf, size_t bufsize)
1975 {
1976 	struct in6_addr *in6;
1977 	char ntopbuf[INET6_ADDRSTRLEN];
1978 	struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf;
1979 	int i, segments, origsegs, rthsize, size0, size1;
1980 
1981 	/* print fixed part of the header */
1982 	printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt,
1983 	    rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type);
1984 	if ((segments = inet6_rth_segments(extbuf)) >= 0) {
1985 		printf("%d segments, ", segments);
1986 		printf("%d left\n", rh->ip6r_segleft);
1987 	} else {
1988 		printf("segments unknown, ");
1989 		printf("%d left\n", rh->ip6r_segleft);
1990 		return;
1991 	}
1992 
1993 	/*
1994 	 * Bounds checking on the ancillary data buffer. When calculating
1995 	 * the number of items to show keep in mind:
1996 	 *	- The size of the cmsg structure
1997 	 *	- The size of one segment (the size of a Type 0 routing header)
1998 	 *	- When dividing add a fudge factor of one in case the
1999 	 *	  dividend is not evenly divisible by the divisor
2000 	 */
2001 	rthsize = (rh->ip6r_len + 1) * 8;
2002 	if (bufsize < (rthsize + CMSG_SPACE(0))) {
2003 		origsegs = segments;
2004 		size0 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 0);
2005 		size1 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 1);
2006 		segments -= (rthsize - (bufsize - CMSG_SPACE(0))) /
2007 		    (size1 - size0) + 1;
2008 		warnx("segments truncated, showing only %d (total=%d)",
2009 		    segments, origsegs);
2010 	}
2011 
2012 	for (i = 0; i < segments; i++) {
2013 		in6 = inet6_rth_getaddr(extbuf, i);
2014 		if (in6 == NULL)
2015 			printf("   [%d]<NULL>\n", i);
2016 		else {
2017 			if (!inet_ntop(AF_INET6, in6, ntopbuf,
2018 			    sizeof(ntopbuf)))
2019 				strlcpy(ntopbuf, "?", sizeof(ntopbuf));
2020 			printf("   [%d]%s\n", i, ntopbuf);
2021 		}
2022 	}
2023 
2024 	return;
2025 
2026 }
2027 
2028 static int
2029 pr_bitrange(u_int32_t v, int soff, int ii)
2030 {
2031 	int off;
2032 	int i;
2033 
2034 	off = 0;
2035 	while (off < 32) {
2036 		/* shift till we have 0x01 */
2037 		if ((v & 0x01) == 0) {
2038 			if (ii > 1)
2039 				printf("-%u", soff + off - 1);
2040 			ii = 0;
2041 			switch (v & 0x0f) {
2042 			case 0x00:
2043 				v >>= 4;
2044 				off += 4;
2045 				continue;
2046 			case 0x08:
2047 				v >>= 3;
2048 				off += 3;
2049 				continue;
2050 			case 0x04: case 0x0c:
2051 				v >>= 2;
2052 				off += 2;
2053 				continue;
2054 			default:
2055 				v >>= 1;
2056 				off += 1;
2057 				continue;
2058 			}
2059 		}
2060 
2061 		/* we have 0x01 with us */
2062 		for (i = 0; i < 32 - off; i++) {
2063 			if ((v & (0x01 << i)) == 0)
2064 				break;
2065 		}
2066 		if (!ii)
2067 			printf(" %u", soff + off);
2068 		ii += i;
2069 		v >>= i; off += i;
2070 	}
2071 	return ii;
2072 }
2073 
2074 static void
2075 pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen)
2076 	/* ni->qtype must be SUPTYPES */
2077 {
2078 	size_t clen;
2079 	u_int32_t v;
2080 	const u_char *cp, *end;
2081 	u_int16_t cur;
2082 	struct cbit {
2083 		u_int16_t words;	/*32bit count*/
2084 		u_int16_t skip;
2085 	} cbit;
2086 #define MAXQTYPES	(1 << 16)
2087 	size_t off;
2088 	int b;
2089 
2090 	cp = (u_char *)(ni + 1);
2091 	end = ((u_char *)ni) + nilen;
2092 	cur = 0;
2093 	b = 0;
2094 
2095 	printf("NodeInfo Supported Qtypes");
2096 	if (options & F_VERBOSE) {
2097 		if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS)
2098 			printf(", compressed bitmap");
2099 		else
2100 			printf(", raw bitmap");
2101 	}
2102 
2103 	while (cp < end) {
2104 		clen = (size_t)(end - cp);
2105 		if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) {
2106 			if (clen == 0 || clen > MAXQTYPES / 8 ||
2107 			    clen % sizeof(v)) {
2108 				printf("???");
2109 				return;
2110 			}
2111 		} else {
2112 			if (clen < sizeof(cbit) || clen % sizeof(v))
2113 				return;
2114 			memcpy(&cbit, cp, sizeof(cbit));
2115 			if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) >
2116 			    clen)
2117 				return;
2118 			cp += sizeof(cbit);
2119 			clen = ntohs(cbit.words) * sizeof(v);
2120 			if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 >
2121 			    MAXQTYPES)
2122 				return;
2123 		}
2124 
2125 		for (off = 0; off < clen; off += sizeof(v)) {
2126 			memcpy(&v, cp + off, sizeof(v));
2127 			v = (u_int32_t)ntohl(v);
2128 			b = pr_bitrange(v, (int)(cur + off * 8), b);
2129 		}
2130 		/* flush the remaining bits */
2131 		b = pr_bitrange(0, (int)(cur + off * 8), b);
2132 
2133 		cp += clen;
2134 		cur += clen * 8;
2135 		if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0)
2136 			cur += ntohs(cbit.skip) * 32;
2137 	}
2138 }
2139 
2140 static void
2141 pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen)
2142 	/* ni->qtype must be NODEADDR */
2143 {
2144 	u_char *cp = (u_char *)(ni + 1);
2145 	char ntop_buf[INET6_ADDRSTRLEN];
2146 	int withttl = 0;
2147 
2148 	nilen -= sizeof(struct icmp6_nodeinfo);
2149 
2150 	if (options & F_VERBOSE) {
2151 		switch (ni->ni_code) {
2152 		case ICMP6_NI_REFUSED:
2153 			(void)printf("refused");
2154 			break;
2155 		case ICMP6_NI_UNKNOWN:
2156 			(void)printf("unknown qtype");
2157 			break;
2158 		}
2159 		if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE)
2160 			(void)printf(" truncated");
2161 	}
2162 	putchar('\n');
2163 	if (nilen <= 0)
2164 		printf("  no address\n");
2165 
2166 	/*
2167 	 * In icmp-name-lookups 05 and later, TTL of each returned address
2168 	 * is contained in the resposne. We try to detect the version
2169 	 * by the length of the data, but note that the detection algorithm
2170 	 * is incomplete. We assume the latest draft by default.
2171 	 */
2172 	if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0)
2173 		withttl = 1;
2174 	while (nilen > 0) {
2175 		u_int32_t ttl = 0;
2176 
2177 		if (withttl) {
2178 			uint32_t t;
2179 
2180 			memcpy(&t, cp, sizeof(t));
2181 			ttl = (u_int32_t)ntohl(t);
2182 			cp += sizeof(u_int32_t);
2183 			nilen -= sizeof(u_int32_t);
2184 		}
2185 
2186 		if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) ==
2187 		    NULL)
2188 			strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2189 		printf("  %s", ntop_buf);
2190 		if (withttl) {
2191 			if (ttl == 0xffffffff) {
2192 				/*
2193 				 * XXX: can this convention be applied to all
2194 				 * type of TTL (i.e. non-ND TTL)?
2195 				 */
2196 				printf("(TTL=infty)");
2197 			}
2198 			else
2199 				printf("(TTL=%u)", ttl);
2200 		}
2201 		putchar('\n');
2202 
2203 		nilen -= sizeof(struct in6_addr);
2204 		cp += sizeof(struct in6_addr);
2205 	}
2206 }
2207 
2208 static int
2209 get_hoplim(struct msghdr *mhdr)
2210 {
2211 	struct cmsghdr *cm;
2212 
2213 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2214 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2215 		if (cm->cmsg_len == 0)
2216 			return(-1);
2217 
2218 		if (cm->cmsg_level == IPPROTO_IPV6 &&
2219 		    cm->cmsg_type == IPV6_HOPLIMIT &&
2220 		    cm->cmsg_len == CMSG_LEN(sizeof(int))) {
2221 			int r;
2222 
2223 			memcpy(&r, CMSG_DATA(cm), sizeof(r));
2224 			return(r);
2225 		}
2226 	}
2227 
2228 	return(-1);
2229 }
2230 
2231 static struct in6_pktinfo *
2232 get_rcvpktinfo(struct msghdr *mhdr)
2233 {
2234 	static struct in6_pktinfo pi;
2235 	struct cmsghdr *cm;
2236 
2237 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2238 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2239 		if (cm->cmsg_len == 0)
2240 			return(NULL);
2241 
2242 		if (cm->cmsg_level == IPPROTO_IPV6 &&
2243 		    cm->cmsg_type == IPV6_PKTINFO &&
2244 		    cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) {
2245 			memcpy(&pi, CMSG_DATA(cm), sizeof(pi));
2246 			return(&pi);
2247 		}
2248 	}
2249 
2250 	return(NULL);
2251 }
2252 
2253 static int
2254 get_pathmtu(struct msghdr *mhdr)
2255 {
2256 #ifdef IPV6_RECVPATHMTU
2257 	struct cmsghdr *cm;
2258 	struct ip6_mtuinfo mtuctl;
2259 
2260 	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2261 	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2262 		if (cm->cmsg_len == 0)
2263 			return(0);
2264 
2265 		if (cm->cmsg_level == IPPROTO_IPV6 &&
2266 		    cm->cmsg_type == IPV6_PATHMTU &&
2267 		    cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) {
2268 			memcpy(&mtuctl, CMSG_DATA(cm), sizeof(mtuctl));
2269 
2270 			/*
2271 			 * If the notified destination is different from
2272 			 * the one we are pinging, just ignore the info.
2273 			 * We check the scope ID only when both notified value
2274 			 * and our own value have non-0 values, because we may
2275 			 * have used the default scope zone ID for sending,
2276 			 * in which case the scope ID value is 0.
2277 			 */
2278 			if (!IN6_ARE_ADDR_EQUAL(&mtuctl.ip6m_addr.sin6_addr,
2279 						&dst.sin6_addr) ||
2280 			    (mtuctl.ip6m_addr.sin6_scope_id &&
2281 			     dst.sin6_scope_id &&
2282 			     mtuctl.ip6m_addr.sin6_scope_id !=
2283 			     dst.sin6_scope_id)) {
2284 				if ((options & F_VERBOSE) != 0) {
2285 					printf("path MTU for %s is notified. "
2286 					       "(ignored)\n",
2287 					   pr_addr((struct sockaddr *)&mtuctl.ip6m_addr,
2288 					   sizeof(mtuctl.ip6m_addr)));
2289 				}
2290 				return(0);
2291 			}
2292 
2293 			/*
2294 			 * Ignore an invalid MTU. XXX: can we just believe
2295 			 * the kernel check?
2296 			 */
2297 			if (mtuctl.ip6m_mtu < IPV6_MMTU)
2298 				return(0);
2299 
2300 			/* notification for our destination. return the MTU. */
2301 			return((int)mtuctl.ip6m_mtu);
2302 		}
2303 	}
2304 #endif
2305 	return(0);
2306 }
2307 
2308 /*
2309  * onint --
2310  *	SIGINT handler.
2311  */
2312 /* ARGSUSED */
2313 static void
2314 onint(int notused __unused)
2315 {
2316 	/*
2317 	 * When doing reverse DNS lookups, the seenint flag might not
2318 	 * be noticed for a while.  Just exit if we get a second SIGINT.
2319 	 */
2320 	if ((options & F_HOSTNAME) && seenint != 0)
2321 		_exit(nreceived ? 0 : 2);
2322 }
2323 
2324 /*
2325  * summary --
2326  *	Print out statistics.
2327  */
2328 static void
2329 summary(void)
2330 {
2331 
2332 	(void)printf("\n--- %s ping6 statistics ---\n", hostname);
2333 	(void)printf("%ld packets transmitted, ", ntransmitted);
2334 	(void)printf("%ld packets received, ", nreceived);
2335 	if (nrepeats)
2336 		(void)printf("+%ld duplicates, ", nrepeats);
2337 	if (ntransmitted) {
2338 		if (nreceived > ntransmitted)
2339 			(void)printf("-- somebody's duplicating packets!");
2340 		else
2341 			(void)printf("%.1f%% packet loss",
2342 			    ((((double)ntransmitted - nreceived) * 100.0) /
2343 			    ntransmitted));
2344 	}
2345 	if (nrcvtimeout)
2346 		printf(", %ld packets out of wait time", nrcvtimeout);
2347 	(void)putchar('\n');
2348 	if (nreceived && timing) {
2349 		/* Only display average to microseconds */
2350 		double num = nreceived + nrepeats;
2351 		double avg = tsum / num;
2352 		double dev = sqrt(tsumsq / num - avg * avg);
2353 		(void)printf(
2354 		    "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
2355 		    tmin, avg, tmax, dev);
2356 		(void)fflush(stdout);
2357 	}
2358 	(void)fflush(stdout);
2359 }
2360 
2361 /*subject type*/
2362 static const char *niqcode[] = {
2363 	"IPv6 address",
2364 	"DNS label",	/*or empty*/
2365 	"IPv4 address",
2366 };
2367 
2368 /*result code*/
2369 static const char *nircode[] = {
2370 	"Success", "Refused", "Unknown",
2371 };
2372 
2373 
2374 /*
2375  * pr_icmph --
2376  *	Print a descriptive string about an ICMP header.
2377  */
2378 static void
2379 pr_icmph(struct icmp6_hdr *icp, u_char *end)
2380 {
2381 	char ntop_buf[INET6_ADDRSTRLEN];
2382 	struct nd_redirect *red;
2383 	struct icmp6_nodeinfo *ni;
2384 	char dnsname[MAXDNAME + 1];
2385 	const u_char *cp;
2386 	size_t l;
2387 
2388 	switch (icp->icmp6_type) {
2389 	case ICMP6_DST_UNREACH:
2390 		switch (icp->icmp6_code) {
2391 		case ICMP6_DST_UNREACH_NOROUTE:
2392 			(void)printf("No Route to Destination\n");
2393 			break;
2394 		case ICMP6_DST_UNREACH_ADMIN:
2395 			(void)printf("Destination Administratively "
2396 			    "Unreachable\n");
2397 			break;
2398 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
2399 			(void)printf("Destination Unreachable Beyond Scope\n");
2400 			break;
2401 		case ICMP6_DST_UNREACH_ADDR:
2402 			(void)printf("Destination Host Unreachable\n");
2403 			break;
2404 		case ICMP6_DST_UNREACH_NOPORT:
2405 			(void)printf("Destination Port Unreachable\n");
2406 			break;
2407 		default:
2408 			(void)printf("Destination Unreachable, Bad Code: %d\n",
2409 			    icp->icmp6_code);
2410 			break;
2411 		}
2412 		/* Print returned IP header information */
2413 		pr_retip((struct ip6_hdr *)(icp + 1), end);
2414 		break;
2415 	case ICMP6_PACKET_TOO_BIG:
2416 		(void)printf("Packet too big mtu = %d\n",
2417 		    (int)ntohl(icp->icmp6_mtu));
2418 		pr_retip((struct ip6_hdr *)(icp + 1), end);
2419 		break;
2420 	case ICMP6_TIME_EXCEEDED:
2421 		switch (icp->icmp6_code) {
2422 		case ICMP6_TIME_EXCEED_TRANSIT:
2423 			(void)printf("Time to live exceeded\n");
2424 			break;
2425 		case ICMP6_TIME_EXCEED_REASSEMBLY:
2426 			(void)printf("Frag reassembly time exceeded\n");
2427 			break;
2428 		default:
2429 			(void)printf("Time exceeded, Bad Code: %d\n",
2430 			    icp->icmp6_code);
2431 			break;
2432 		}
2433 		pr_retip((struct ip6_hdr *)(icp + 1), end);
2434 		break;
2435 	case ICMP6_PARAM_PROB:
2436 		(void)printf("Parameter problem: ");
2437 		switch (icp->icmp6_code) {
2438 		case ICMP6_PARAMPROB_HEADER:
2439 			(void)printf("Erroneous Header ");
2440 			break;
2441 		case ICMP6_PARAMPROB_NEXTHEADER:
2442 			(void)printf("Unknown Nextheader ");
2443 			break;
2444 		case ICMP6_PARAMPROB_OPTION:
2445 			(void)printf("Unrecognized Option ");
2446 			break;
2447 		default:
2448 			(void)printf("Bad code(%d) ", icp->icmp6_code);
2449 			break;
2450 		}
2451 		(void)printf("pointer = 0x%02x\n",
2452 		    (u_int32_t)ntohl(icp->icmp6_pptr));
2453 		pr_retip((struct ip6_hdr *)(icp + 1), end);
2454 		break;
2455 	case ICMP6_ECHO_REQUEST:
2456 		(void)printf("Echo Request");
2457 		/* XXX ID + Seq + Data */
2458 		break;
2459 	case ICMP6_ECHO_REPLY:
2460 		(void)printf("Echo Reply");
2461 		/* XXX ID + Seq + Data */
2462 		break;
2463 	case ICMP6_MEMBERSHIP_QUERY:
2464 		(void)printf("Listener Query");
2465 		break;
2466 	case ICMP6_MEMBERSHIP_REPORT:
2467 		(void)printf("Listener Report");
2468 		break;
2469 	case ICMP6_MEMBERSHIP_REDUCTION:
2470 		(void)printf("Listener Done");
2471 		break;
2472 	case ND_ROUTER_SOLICIT:
2473 		(void)printf("Router Solicitation");
2474 		break;
2475 	case ND_ROUTER_ADVERT:
2476 		(void)printf("Router Advertisement");
2477 		break;
2478 	case ND_NEIGHBOR_SOLICIT:
2479 		(void)printf("Neighbor Solicitation");
2480 		break;
2481 	case ND_NEIGHBOR_ADVERT:
2482 		(void)printf("Neighbor Advertisement");
2483 		break;
2484 	case ND_REDIRECT:
2485 		red = (struct nd_redirect *)icp;
2486 		(void)printf("Redirect\n");
2487 		if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf,
2488 		    sizeof(ntop_buf)))
2489 			strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2490 		(void)printf("Destination: %s", ntop_buf);
2491 		if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf,
2492 		    sizeof(ntop_buf)))
2493 			strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2494 		(void)printf(" New Target: %s", ntop_buf);
2495 		break;
2496 	case ICMP6_NI_QUERY:
2497 		(void)printf("Node Information Query");
2498 		/* XXX ID + Seq + Data */
2499 		ni = (struct icmp6_nodeinfo *)icp;
2500 		l = end - (u_char *)(ni + 1);
2501 		printf(", ");
2502 		switch (ntohs(ni->ni_qtype)) {
2503 		case NI_QTYPE_NOOP:
2504 			(void)printf("NOOP");
2505 			break;
2506 		case NI_QTYPE_SUPTYPES:
2507 			(void)printf("Supported qtypes");
2508 			break;
2509 		case NI_QTYPE_FQDN:
2510 			(void)printf("DNS name");
2511 			break;
2512 		case NI_QTYPE_NODEADDR:
2513 			(void)printf("nodeaddr");
2514 			break;
2515 		case NI_QTYPE_IPV4ADDR:
2516 			(void)printf("IPv4 nodeaddr");
2517 			break;
2518 		default:
2519 			(void)printf("unknown qtype");
2520 			break;
2521 		}
2522 		if (options & F_VERBOSE) {
2523 			switch (ni->ni_code) {
2524 			case ICMP6_NI_SUBJ_IPV6:
2525 				if (l == sizeof(struct in6_addr) &&
2526 				    inet_ntop(AF_INET6, ni + 1, ntop_buf,
2527 				    sizeof(ntop_buf)) != NULL) {
2528 					(void)printf(", subject=%s(%s)",
2529 					    niqcode[ni->ni_code], ntop_buf);
2530 				} else {
2531 #if 1
2532 					/* backward compat to -W */
2533 					(void)printf(", oldfqdn");
2534 #else
2535 					(void)printf(", invalid");
2536 #endif
2537 				}
2538 				break;
2539 			case ICMP6_NI_SUBJ_FQDN:
2540 				if (end == (u_char *)(ni + 1)) {
2541 					(void)printf(", no subject");
2542 					break;
2543 				}
2544 				printf(", subject=%s", niqcode[ni->ni_code]);
2545 				cp = (const u_char *)(ni + 1);
2546 				cp = dnsdecode(cp, end, NULL, dnsname,
2547 				    sizeof(dnsname));
2548 				if (cp != NULL)
2549 					printf("(%s)", dnsname);
2550 				else
2551 					printf("(invalid)");
2552 				break;
2553 			case ICMP6_NI_SUBJ_IPV4:
2554 				if (l == sizeof(struct in_addr) &&
2555 				    inet_ntop(AF_INET, ni + 1, ntop_buf,
2556 				    sizeof(ntop_buf)) != NULL) {
2557 					(void)printf(", subject=%s(%s)",
2558 					    niqcode[ni->ni_code], ntop_buf);
2559 				} else
2560 					(void)printf(", invalid");
2561 				break;
2562 			default:
2563 				(void)printf(", invalid");
2564 				break;
2565 			}
2566 		}
2567 		break;
2568 	case ICMP6_NI_REPLY:
2569 		(void)printf("Node Information Reply");
2570 		/* XXX ID + Seq + Data */
2571 		ni = (struct icmp6_nodeinfo *)icp;
2572 		printf(", ");
2573 		switch (ntohs(ni->ni_qtype)) {
2574 		case NI_QTYPE_NOOP:
2575 			(void)printf("NOOP");
2576 			break;
2577 		case NI_QTYPE_SUPTYPES:
2578 			(void)printf("Supported qtypes");
2579 			break;
2580 		case NI_QTYPE_FQDN:
2581 			(void)printf("DNS name");
2582 			break;
2583 		case NI_QTYPE_NODEADDR:
2584 			(void)printf("nodeaddr");
2585 			break;
2586 		case NI_QTYPE_IPV4ADDR:
2587 			(void)printf("IPv4 nodeaddr");
2588 			break;
2589 		default:
2590 			(void)printf("unknown qtype");
2591 			break;
2592 		}
2593 		if (options & F_VERBOSE) {
2594 			if (ni->ni_code > nitems(nircode))
2595 				printf(", invalid");
2596 			else
2597 				printf(", %s", nircode[ni->ni_code]);
2598 		}
2599 		break;
2600 	default:
2601 		(void)printf("Bad ICMP type: %d", icp->icmp6_type);
2602 	}
2603 }
2604 
2605 /*
2606  * pr_iph --
2607  *	Print an IP6 header.
2608  */
2609 static void
2610 pr_iph(struct ip6_hdr *ip6)
2611 {
2612 	u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
2613 	u_int8_t tc;
2614 	char ntop_buf[INET6_ADDRSTRLEN];
2615 
2616 	tc = *(&ip6->ip6_vfc + 1); /* XXX */
2617 	tc = (tc >> 4) & 0x0f;
2618 	tc |= (ip6->ip6_vfc << 4);
2619 
2620 	printf("Vr TC  Flow Plen Nxt Hlim\n");
2621 	printf(" %1x %02x %05x %04x  %02x   %02x\n",
2622 	    (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow),
2623 	    ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim);
2624 	if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf)))
2625 		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2626 	printf("%s->", ntop_buf);
2627 	if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf)))
2628 		strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2629 	printf("%s\n", ntop_buf);
2630 }
2631 
2632 /*
2633  * pr_addr --
2634  *	Return an ascii host address as a dotted quad and optionally with
2635  * a hostname.
2636  */
2637 static const char *
2638 pr_addr(struct sockaddr *addr, int addrlen)
2639 {
2640 	static char buf[NI_MAXHOST];
2641 	int flag = 0;
2642 
2643 	if ((options & F_HOSTNAME) == 0)
2644 		flag |= NI_NUMERICHOST;
2645 
2646 	if (cap_getnameinfo(capdns, addr, addrlen, buf, sizeof(buf), NULL, 0,
2647 		flag) == 0)
2648 		return (buf);
2649 	else
2650 		return "?";
2651 }
2652 
2653 /*
2654  * pr_retip --
2655  *	Dump some info on a returned (via ICMPv6) IPv6 packet.
2656  */
2657 static void
2658 pr_retip(struct ip6_hdr *ip6, u_char *end)
2659 {
2660 	u_char *cp = (u_char *)ip6, nh;
2661 	int hlen;
2662 
2663 	if ((size_t)(end - (u_char *)ip6) < sizeof(*ip6)) {
2664 		printf("IP6");
2665 		goto trunc;
2666 	}
2667 	pr_iph(ip6);
2668 	hlen = sizeof(*ip6);
2669 
2670 	nh = ip6->ip6_nxt;
2671 	cp += hlen;
2672 	while (end - cp >= 8) {
2673 #ifdef IPSEC
2674 		struct ah ah;
2675 #endif
2676 
2677 		switch (nh) {
2678 		case IPPROTO_HOPOPTS:
2679 			printf("HBH ");
2680 			hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3;
2681 			nh = ((struct ip6_hbh *)cp)->ip6h_nxt;
2682 			break;
2683 		case IPPROTO_DSTOPTS:
2684 			printf("DSTOPT ");
2685 			hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3;
2686 			nh = ((struct ip6_dest *)cp)->ip6d_nxt;
2687 			break;
2688 		case IPPROTO_FRAGMENT:
2689 			printf("FRAG ");
2690 			hlen = sizeof(struct ip6_frag);
2691 			nh = ((struct ip6_frag *)cp)->ip6f_nxt;
2692 			break;
2693 		case IPPROTO_ROUTING:
2694 			printf("RTHDR ");
2695 			hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3;
2696 			nh = ((struct ip6_rthdr *)cp)->ip6r_nxt;
2697 			break;
2698 #ifdef IPSEC
2699 		case IPPROTO_AH:
2700 			printf("AH ");
2701 			memcpy(&ah, cp, sizeof(ah));
2702 			hlen = (ah.ah_len+2) << 2;
2703 			nh = ah.ah_nxt;
2704 			break;
2705 #endif
2706 		case IPPROTO_ICMPV6:
2707 			printf("ICMP6: type = %d, code = %d\n",
2708 			    *cp, *(cp + 1));
2709 			return;
2710 		case IPPROTO_ESP:
2711 			printf("ESP\n");
2712 			return;
2713 		case IPPROTO_TCP:
2714 			printf("TCP: from port %u, to port %u (decimal)\n",
2715 			    (*cp * 256 + *(cp + 1)),
2716 			    (*(cp + 2) * 256 + *(cp + 3)));
2717 			return;
2718 		case IPPROTO_UDP:
2719 			printf("UDP: from port %u, to port %u (decimal)\n",
2720 			    (*cp * 256 + *(cp + 1)),
2721 			    (*(cp + 2) * 256 + *(cp + 3)));
2722 			return;
2723 		default:
2724 			printf("Unknown Header(%d)\n", nh);
2725 			return;
2726 		}
2727 
2728 		if ((cp += hlen) >= end)
2729 			goto trunc;
2730 	}
2731 	if (end - cp < 8)
2732 		goto trunc;
2733 
2734 	putchar('\n');
2735 	return;
2736 
2737   trunc:
2738 	printf("...\n");
2739 	return;
2740 }
2741 
2742 static void
2743 fill(char *bp, char *patp)
2744 {
2745 	int ii, jj, kk;
2746 	int pat[16];
2747 	char *cp;
2748 
2749 	for (cp = patp; *cp; cp++)
2750 		if (!isxdigit(*cp))
2751 			errx(1, "patterns must be specified as hex digits");
2752 	ii = sscanf(patp,
2753 	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
2754 	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
2755 	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
2756 	    &pat[13], &pat[14], &pat[15]);
2757 
2758 /* xxx */
2759 	if (ii > 0)
2760 		for (kk = 0;
2761 		    (size_t)kk <= MAXDATALEN - 8 + sizeof(struct tv32) + ii;
2762 		    kk += ii)
2763 			for (jj = 0; jj < ii; ++jj)
2764 				bp[jj + kk] = pat[jj];
2765 	if (!(options & F_QUIET)) {
2766 		(void)printf("PATTERN: 0x");
2767 		for (jj = 0; jj < ii; ++jj)
2768 			(void)printf("%02x", bp[jj] & 0xFF);
2769 		(void)printf("\n");
2770 	}
2771 }
2772 
2773 #ifdef IPSEC
2774 #ifdef IPSEC_POLICY_IPSEC
2775 static int
2776 setpolicy(int so __unused, char *policy)
2777 {
2778 	char *buf;
2779 
2780 	if (policy == NULL)
2781 		return 0;	/* ignore */
2782 
2783 	buf = ipsec_set_policy(policy, strlen(policy));
2784 	if (buf == NULL)
2785 		errx(1, "%s", ipsec_strerror());
2786 	if (setsockopt(ssend, IPPROTO_IPV6, IPV6_IPSEC_POLICY, buf,
2787 	    ipsec_get_policylen(buf)) < 0)
2788 		warnx("Unable to set IPsec policy");
2789 	free(buf);
2790 
2791 	return 0;
2792 }
2793 #endif
2794 #endif
2795 
2796 static char *
2797 nigroup(char *name, int nig_oldmcprefix)
2798 {
2799 	char *p;
2800 	char *q;
2801 	MD5_CTX ctxt;
2802 	u_int8_t digest[16];
2803 	u_int8_t c;
2804 	size_t l;
2805 	char hbuf[NI_MAXHOST];
2806 	struct in6_addr in6;
2807 	int valid;
2808 
2809 	p = strchr(name, '.');
2810 	if (!p)
2811 		p = name + strlen(name);
2812 	l = p - name;
2813 	if (l > 63 || l > sizeof(hbuf) - 1)
2814 		return NULL;	/*label too long*/
2815 	strncpy(hbuf, name, l);
2816 	hbuf[(int)l] = '\0';
2817 
2818 	for (q = name; *q; q++) {
2819 		if (isupper(*(unsigned char *)q))
2820 			*q = tolower(*(unsigned char *)q);
2821 	}
2822 
2823 	/* generate 16 bytes of pseudo-random value. */
2824 	memset(&ctxt, 0, sizeof(ctxt));
2825 	MD5Init(&ctxt);
2826 	c = l & 0xff;
2827 	MD5Update(&ctxt, &c, sizeof(c));
2828 	MD5Update(&ctxt, (unsigned char *)name, l);
2829 	MD5Final(digest, &ctxt);
2830 
2831 	if (nig_oldmcprefix) {
2832 		/* draft-ietf-ipngwg-icmp-name-lookup */
2833 		valid = inet_pton(AF_INET6, "ff02::2:0000:0000", &in6);
2834 	} else {
2835 		/* RFC 4620 */
2836 		valid = inet_pton(AF_INET6, "ff02::2:ff00:0000", &in6);
2837 	}
2838 	if (valid != 1)
2839 		return NULL;	/*XXX*/
2840 
2841 	if (nig_oldmcprefix) {
2842 		/* draft-ietf-ipngwg-icmp-name-lookup */
2843 		bcopy(digest, &in6.s6_addr[12], 4);
2844 	} else {
2845 		/* RFC 4620 */
2846 		bcopy(digest, &in6.s6_addr[13], 3);
2847 	}
2848 
2849 	if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL)
2850 		return NULL;
2851 
2852 	return strdup(hbuf);
2853 }
2854 
2855 static cap_channel_t *
2856 capdns_setup(void)
2857 {
2858 	cap_channel_t *capcas, *capdnsloc;
2859 #ifdef WITH_CASPER
2860 	const char *types[2];
2861 	int families[1];
2862 #endif
2863 	capcas = cap_init();
2864 	if (capcas == NULL)
2865 		err(1, "unable to create casper process");
2866 	capdnsloc = cap_service_open(capcas, "system.dns");
2867 	/* Casper capability no longer needed. */
2868 	cap_close(capcas);
2869 	if (capdnsloc == NULL)
2870 		err(1, "unable to open system.dns service");
2871 #ifdef WITH_CASPER
2872 	types[0] = "NAME2ADDR";
2873 	types[1] = "ADDR2NAME";
2874 	if (cap_dns_type_limit(capdnsloc, types, nitems(types)) < 0)
2875 		err(1, "unable to limit access to system.dns service");
2876 	families[0] = AF_INET6;
2877 	if (cap_dns_family_limit(capdnsloc, families, nitems(families)) < 0)
2878 		err(1, "unable to limit access to system.dns service");
2879 #endif
2880 	return (capdnsloc);
2881 }
2882