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