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