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