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