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