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