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