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