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