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