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