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