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