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