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