/* $USAGI: ping6.c,v 1.124 2001/11/09 10:59:22 yoshfuji Exp $ */

/*
 * Copyright (C)2000 Hideaki YOSHIFUJI / USAGI Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the author, project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR, PROJECT AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR, PROJECT OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 *
 *	Modified for AF_INET6 by Pedro Roque
 *
 *	<roque@di.fc.ul.pt>
 *
 *	Original copyright notice included bellow
 */

/*
 * Copyright (c) 1989 The Regents of the University of California.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Mike Muuss.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef lint
char copyright[] =
"@(#) Copyright (c) 1989 The Regents of the University of California.\n\
 All rights reserved.\n";
#endif /* not lint */

/*
 *			P I N G . C
 *
 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
 * measure round-trip-delays and packet loss across network paths.
 *
 * Author -
 *	Mike Muuss
 *	U. S. Army Ballistic Research Laboratory
 *	December, 1983
 *
 * Status -
 *	Public Domain.  Distribution Unlimited.
 * Bugs -
 *	More statistics could always be gathered.
 *	This program has to run SUID to ROOT to access the ICMP socket.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <unistd.h>
#ifdef HAVE_GETOPT_H
#define _GNU_SOURCE
#include <getopt.h>
#endif
#include <stdlib.h>
#include <err.h>
#include <string.h>
#include <sys/param.h>
#include <sys/socket.h>
#ifndef HAVE_CMSG_NXTHDR
#include "sys/socket_cmsg.h"
#endif
#include <sys/file.h>
#include <sys/time.h>
#include <sys/signal.h>
#include <sys/uio.h>
#include <sys/poll.h>
#include <sys/ioctl.h>
#include <net/if.h>

#include <netinet/in.h>
#ifndef HAVE_INET6_RTHDR_INIT
#include "netinet/in_rthdr.h"
#endif
#include <netinet/ip6.h>
#ifndef IPV6_FLOWLABEL_MASK
#define IPV6_FLOWLABEL_MASK	htonl(0x000fffff)
#endif
#ifndef IPV6_VERSION_MASK
#define IPV6_VERSION_MASK	0xf0
#endif
#include <arpa/inet.h>
#include <netinet/icmp6.h>
#ifndef ICMP6_DST_UNREACH_BEYONDSCOPE
#define	ICMP6_DST_UNREACH_BEYONDSCOPE	ICMP6_DST_UNREACH_NOTNEIGHBOR
#endif
#ifndef HAVE_STRUCT_ICMP6_NODEINFO
#include "netinet/icmp6_ni.h"
#endif

#ifndef	IPV6_RECVHOPLIMIT	/* without RFC2292bis */
#ifndef USE_RFC2292
#define	USE_RFC2292
#endif
#endif

#ifdef USE_RFC2292
#ifndef	IPV6_2292HOPLIMIT
#define	IPV6_2292HOPLIMIT	IPV6_HOPLIMIT
#endif
#endif

#ifdef IPSEC
#include <netinet/ah.h>
#include <netinet/ipsec.h>
#endif

#define MAX_IPOPTLEN	4096
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <values.h>
#include <errno.h>
#include <string.h>
#ifdef HAVE_MD5_H
#include <md5.h>
#else
#include "md5.h"
#endif

#include "SNAPSHOT.h"

#define ICMP6_HDRLEN	8			/* sizeof(struct icmp6_hdr) */
#define ICMP6_NILEN	(ICMP6_HDRLEN + 8)	/* sizeof(struct icmp6_nodeinfo) */
#define ICMP_MINLEN	28

#define	DEFDATALEN	(64 - 8)	/* default data length */
#define	MAXIPLEN	60
#define	MAXICMPLEN	76
#define	MAXPACKET	128000		/* max packet size */
#define	MAXWAIT		10		/* max seconds to wait for response */
#define	NROUTES		9		/* number of record route slots */
#define	EXTRA		256	/* for AH and various other headers. weird. */

#define MAXNIQTYPE	(1 << 16)
#define MAXNIQTYPEBMP	(MAXNIQTYPE / CHAR_BIT)

#define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
#define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
#define	SET(bit)	(A(bit) |= B(bit))
#define	CLR(bit)	(A(bit) &= (~B(bit)))
#define	TST(bit)	(A(bit) & B(bit))

/* various options */
#define	F_FLOOD		0x00000001
#define	F_INTERVAL	0x00000002
#define	F_NUMERIC	0x00000004
#define	F_PINGFILLED	0x00000008
#define	F_QUIET		0x00000010
#define	F_RROUTE	0x00000020
#define	F_SO_DEBUG	0x00000040
#define	F_SO_DONTROUTE	0x00000080
#define	F_VERBOSE	0x00000100
#define	F_INTERFACE	0x00002000
#define	F_FLOWINFO	0x00020000
#define	F_TCLASS	0x00040000
#define	F_MC_NOLOOP	0x00080000
#define	F_HOPLIMIT	0x00100000
#define	F_FLOOD_POLL	0x00200000
#define	F_LATENCY	0x00400000
int options = F_NUMERIC;

/* NI options */
#define	F_FQDNOLD	0x001
#define	F_SUPTYPES	0x002
#define	F_FQDN		0x004
#define	F_NODEADDR	0x008
#define	F_IPV4ADDR	0x010
#define	F_NIGROUP	0x020
#define	F_NISUBJADDR	0x040
#define	F_NISUBJNAME	0x080
#define	F_NIFLAGS	(F_FQDNOLD|F_SUPTYPES|F_FQDN|F_NODEADDR|F_IPV4ADDR)
int ni_opts, naflags;

/* ipsec options */
#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
#define	F_POLICY	0x001
#else
#define F_AUTHHDR	0x002
#define F_ENCRYPT	0x004
#endif /*IPSEC_POLICY_IPSEC*/
int ipsec_opts;
#endif /*IPSEC*/

u_int32_t flowlabel;
u_int32_t tclass;
struct cmsghdr *cm;

static struct {
  char		shortopt;
  char		*longopt;
  char		*arg;
  char		*help;
  size_t	len;
} optionlist[] = {
  {'?', "help",         NULL,               "Help"},
  {'c', "count",        "count",            "Stop after sending (and receiving) count packets"},
  {'d', "debug",        NULL,               "Set SO_DEBUG"},
  {'f', "flood",        NULL,               "Flood ping"},
  {'F', "flowinfo",     "flowinfo",         "Flowinfo"},
  {'h', "hoplimit",     "hlim",             "(Multicast) hoplimit"},
  {'H', "hostname",     NULL,               "Try to do reverse-lookup"},
  {'i', "interval",     "time",             "Interval time between sending packets"},
  {'I', "interface",    "interface",        "Outgoing interface"},
  {'l', "preload",      "preload",          "Send preload packets"},
  {'L', "no-loopback",  NULL,               "Disable multicast loopback"},
  {'M', "pmtudisc",     "{do,dont,want}"    "Control path mtu discovery"},
  {'n', "numeric",      NULL,               "Numeric output only"},
  {'p', "pattern",      "pattern",          "Pad to fill out the packet"},
  {'q', "quiet",        NULL,               "Quiet mode"},
  {'r', "dont-route",   NULL,               "Bypass normal routing; send directly to the host"},
  {'R', "record-route", NULL,               "Record route"},
  {'s', "size",         "size",             "Number of data bytes to be sent"},
  {'T', "tclass",       "traffic-class",    "Traffic class"},
  {'U', "user-to-user",	NULL,               "User-to-user latency"},
  {'v', "verbose",      NULL,               "Verbose output"},
  {'V', "version",	NULL,               "Version information"},
  {'w', "wait",         "time",             "Wait time"},
  {'t', "ni-qtypes",    NULL,               "NI query for supported Qtypes"},
  {'W', "ni-fqdn",      NULL,               "NI query for FQDN"},
  {'a', "ni-addr",      "[-aclsgA]",        NULL},
  {'6', "ni-v6addr",    "[-aclsgA]",        "NI query for addresses; "
                                            "all,compat,link,site,global"
#ifdef NI_NODEADDR_FLAG_ANYCAST
                                            ",anycast"
#endif
                                            },
  {'4', "ni-v4addr",    "[-a]",             "NI query for ipv4 addresses; all"},
  {'N', "nigroup",      NULL,               "Use NI group address"},
  {'j', "nisubjaddr",   "addr",             "Set NI subject address"},
  {'J', "nisubjname",	"name",             "Set NI subject name"},
#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
  {'P', "ipsec-policy", "policy",           "Policy-based IPsec"},
#else
  {'A', "ipsec-ah",     NULL,               "IPsec (AH)"},
  {'E', "ipsec-esp",    NULL,               "IPsec (ESP)"},
#endif
#endif
  { 0,  NULL,           NULL,               NULL}
};
#ifdef HAVE_GETOPT_LONG
static struct option long_options[sizeof(optionlist)/sizeof(optionlist[0])];
#else
#define getopt_long(c,v,os,lo,li) getopt(c,v,os)
#endif
static char short_options[2*(sizeof(optionlist)/sizeof(optionlist[0]))];

/*
 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
 * number of received sequence numbers we can keep track of.  Change 128
 * to 8192 for complete accuracy...
 */
#define	MAX_DUP_CHK	(8 * 128)
int mx_dup_ck = MAX_DUP_CHK;
char rcvd_tbl[MAX_DUP_CHK / 8];

struct sockaddr_in6 whereto;	/* who to ping */
socklen_t wheretolen;
int datalen = DEFDATALEN;
u_char outpack[MAXPACKET];
char BSPACE = '\b';		/* characters written for flood */
char DOT = '.';
uid_t uid;
char *hostname;
int ident;			/* process id to identify our packets */
char nonce[8];			/* process nonce */

/* counters */
long npackets;			/* max packets to transmit */
long nreceived;			/* # of packets we got back */
long nchecksum;			/* replies with bad checksum */
long nerrors;			/* icmp errors */
long nrepeats;			/* number of duplicates */
long ntransmitted;		/* sequence # for outbound packets = #sent */
struct timeval interval = {1,0};/* interval between packets */
int deadline;
time_t starttime;
int confirm = 0;

#ifndef MSG_CONFIRM
#define MSG_CONFIRM 0
#endif

int confirm_flag = MSG_CONFIRM;

/* timing */
int timing;			/* flag to do timing */
double tmin = DBL_MAX;		/* minimum round trip time */
double tmax;			/* maximum round trip time */
double tsum;			/* sum of all times, for doing average */
double tsumsq;			/* sum of all times squared, for std. dev. */

static unsigned char cmsgbuf[4096];
static int cmsglen = 0;

static const char * pr_addr(struct sockaddr_in6 *addr, socklen_t addrlen);
static int pr_icmph(struct icmp6_hdr *icp, u_char *end);
static void pr_iph(struct ip6_hdr *iph);
static void catcher(int);
static void finish(int) __attribute__((noreturn));
static void usage(void) __attribute((noreturn));
static void usage_long(void) __attribute((noreturn));
static void pinger(void);
static int myechoreply(const struct icmp6_hdr *icp);
static int mynireply(const struct icmp6_nodeinfo *nip);
static int pr_pack(char *buf, int cc, struct sockaddr_in6 *from, socklen_t addrlen, int hops, struct timeval *tv);
static void pr_retip (struct ip6_hdr *iph, u_char *end);
static void fill(char *patp);
static char *nigroup(char *name);
static int pr_bitrange(u_int32_t v, u_int32_t s, int ii);
static void pr_suptypes(struct icmp6_nodeinfo *ni, int nilen);
static void pr_fqdn    (struct icmp6_nodeinfo *ni, int nilen);
static void pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen);
static void pr_ipv4addr(struct icmp6_nodeinfo *ni, int nilen);
static int get_hoplim(struct msghdr *msghdr);
#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
static int setpolicy (int sock, char *policy);
#endif
#endif

struct sockaddr_in6 source;
socklen_t sourcelen;
char *device;
int pmtudisc=-1;
void *subject = NULL;
int subjectlen = 0;
int subjecttype = ICMP6_NI_SUBJ_IPV6;

static int icmp_sock;


/*
 * tvsub --
 *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
 * be >= in.
 */
static __inline__ void tvsub(struct timeval *out, struct timeval *in)
{
	if ((out->tv_usec -= in->tv_usec) < 0) {
		--out->tv_sec;
		out->tv_usec += 1000000;
	}
	out->tv_sec -= in->tv_sec;
}

void set_signal(int signo, void (*handler)(int))
{
	struct sigaction sa;

	memset(&sa, 0, sizeof(sa));

	sa.sa_handler = (void (*)(int))handler;
#ifdef SA_INTERRUPT
	sa.sa_flags = SA_INTERRUPT;
#endif
	sigaction(signo, &sa, NULL);
}


int main(int argc, char *argv[])
{
	extern int errno, optind;
	extern char *optarg;
	int i,j;
	int ch, hold, packlen, preload;
	u_char *packet;
	char *target;
	struct sockaddr_in6 firsthop;
	int hlim, loop;
	int socket_errno;
	struct icmp6_filter filter;
	int csum_offset, sz_opt;
	struct iovec iov;
	struct timeval t;
	struct addrinfo hints, *res0;
	int gai;
#ifdef IPSEC_POLICY_IPSEC
	char *policy_in = NULL, *policy_out = NULL
#endif

	icmp_sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
	socket_errno = errno;

	uid = getuid();
	setuid(uid);

	source.sin6_family = AF_INET6;
	sourcelen = sizeof(source);
	memset(&firsthop, 0, sizeof(firsthop));
	firsthop.sin6_family = AF_INET6;

	preload = 0;

	/* generate option list */
	for (i=j=0; i < sizeof(optionlist)/sizeof(optionlist[0]); i++){
#ifdef HAVE_GETOPT_LONG
	  long_options[i].name = optionlist[i].longopt;
	  long_options[i].has_arg = optionlist[i].arg ? 1 : 0;
	  long_options[i].flag = NULL;
	  long_options[i].val = optionlist[i].shortopt;
#endif
	  short_options[j++] = optionlist[i].shortopt;
	  if (optionlist[i].arg)
	    short_options[j++] = ':';
	}

	while ((ch = getopt_long(argc, argv, short_options, long_options, NULL)) != EOF){
		switch(ch) {
		case 'c':
			npackets = atoi(optarg);
			if (npackets <= 0)
				errx(2, "bad number of packets to transmit.");
			break;
		case 'd':
			options |= F_SO_DEBUG;
			break;
		case 'f':
			if (uid)
				errx(2, "%s", strerror(EPERM));
			options |= F_FLOOD;
			setbuf(stdout, (char *)NULL);
			break;
		case 'F':
			sscanf(optarg, "%x", &flowlabel);
			options |= F_FLOWINFO;
			break;
		case 'H':
			options &= ~F_NUMERIC;
			break;
		case 'T':
			sscanf(optarg, "%x", &tclass);
			options |= F_TCLASS;
			break;
		case 'i':		/* wait between sending packets */
		{
			char *e;
			double intval = strtod(optarg, &e);
			if (*optarg == '\0' || *e != '\0')
				errx(2, "illegal timing interval %s", optarg);
			if (intval < 1 && uid) 
				errx(2, "%s: only root may use interval < 1s",
					strerror(EPERM));
			interval.tv_sec = (long)intval;
			interval.tv_usec =
				(long)((intval - interval.tv_sec) * 1000000);
			if (interval.tv_sec < 0)
				errx(2, "illegal timing interval %s", optarg);
			/* less than 1/hz does not make sense */
			if (interval.tv_sec == 0 && interval.tv_usec < 10000) {
				warnx("too small interval, raised to 0.1");
				interval.tv_usec = 10000;
			}
			options |= F_INTERVAL;
			break;
		}
		case 'w':
			deadline = atoi(optarg);
			if (deadline < 0)
				errx(2, "wait time.");
			break;
		case 'l':
			preload = atoi(optarg);
			if (preload < 0)
				errx(2, "bad preload value.");
			if (uid)
				errx(2, "%s", strerror(EPERM));
			break;
		case 'n':
			options |= F_NUMERIC;
			break;
		case 'p':		/* fill buffer with user pattern */
			options |= F_PINGFILLED;
			fill(optarg);
			break;
		case 'q':
			options |= F_QUIET;
			break;
		case 'R':
			options |= F_RROUTE;
			break;
		case 'r':
			options |= F_SO_DONTROUTE;
			break;
		case 's':		/* size of packet to send */
			datalen = atoi(optarg);
			if (datalen > MAXPACKET-8)
				if (uid)
					errx(2, "packet size too large.");
				else
					warnx("packet size too large.");
			if (datalen < 0)
				errx(2, "illegal packet size.");
			break;
		case 'v':
			options |= F_VERBOSE;
			break;
		case 'L':
			options |= F_MC_NOLOOP;
			loop = 0;
			break;
		case 'h':
			options |= F_HOPLIMIT;
			i = atoi(optarg);
			if (i < 0 || i > 255)
				printf("hoplimit %u out of range\n", i);
			hlim = i;
			break;
		case 'I':
			options |= F_INTERFACE;
			if (strchr(optarg, ':')) {
				if (inet_pton(AF_INET6, optarg, (char*)&source.sin6_addr) <= 0)
					errx(2, "Invalid source address %s", optarg);
			} else
				device = optarg;
			break;
		case 't':
			ni_opts &= ~F_NIFLAGS;
			ni_opts |= F_SUPTYPES;
			break;
		case 'U':
			options |= F_LATENCY;
			break;
		case 'M':
			if (strcmp(optarg, "do") == 0)
				pmtudisc = IPV6_PMTUDISC_DO;
			else if (strcmp(optarg, "dont") == 0)
				pmtudisc = IPV6_PMTUDISC_DONT;
			else if (strcmp(optarg, "want") == 0)
				pmtudisc = IPV6_PMTUDISC_WANT;
			else
				errx(2, "wrong value for -M: do, dont, want are valid ones.");
			break;
		case 'V':
			fprintf(stderr, "ping6 utility, iputils-ss%s\n", SNAPSHOT);
			exit(0);
		case 'W':
			ni_opts &= ~F_NIFLAGS;
			ni_opts |= F_FQDN;
			break;
		case 'a':
			fprintf(stderr, 
				"-a option is obsolete; use -6 instead.\n");
		case '6':
		    {
			char *cp;

			ni_opts &= ~F_NIFLAGS;
			naflags = 0;
			ni_opts |= F_NODEADDR;
			datalen = 2048; /* XXX: enough? */
			for (cp = optarg; *cp != '\0'; cp++) {
				switch(*cp) {
				case '-':
					break;
				case 'a':
					naflags |= NI_NODEADDR_FLAG_ALL;
					break;
				case 'c':
				case 'C':
					naflags |= NI_NODEADDR_FLAG_COMPAT;
					break;
				case 'l':
				case 'L':
					naflags |= NI_NODEADDR_FLAG_LINKLOCAL;
					break;
				case 's':
				case 'S':
					naflags |= NI_NODEADDR_FLAG_SITELOCAL;
					break;
				case 'g':
				case 'G':
					naflags |= NI_NODEADDR_FLAG_GLOBAL;
					break;
#ifdef NI_NODEADDR_FLAG_ANYCAST
				case 'A': /* experimental. not in the spec */
					naflags |= NI_NODEADDR_FLAG_ANYCAST;
					break;
#endif
				default:
					usage();
					/*NOTREACHED*/
				}
			}
			break;
		    }
		case '4':
		    {
			char *cp;
			ni_opts &= ~F_NIFLAGS;
			naflags = 0;
			ni_opts |= F_IPV4ADDR;
			datalen = 2048;	/* XXX: enough? */
			for (cp = optarg; *cp != '\0'; cp++) {
				switch(*cp) {
				case '-':
					break;
				case 'a':
					naflags |= NI_IPV4ADDR_FLAG_ALL;
					break;
				default:
					usage();
					/*NOTREACHED*/
				}
			}
			break;
		    }
		case 'N':
			ni_opts |= F_NIGROUP;
			break;
		case 'j':
		    {
			struct addrinfo hints, *ai;
			memset(&hints, 0, sizeof(hints));
			hints.ai_family = PF_UNSPEC;
#ifdef GAI_OK_WITH_RAW_ICMPV6
			hints.ai_socktype = SOCK_RAW;
#endif
			gai = getaddrinfo(optarg, NULL, &hints, &ai);
			if (gai)
				errx(2, "Unknown subject address %s: %s\n",
					optarg, gai_strerror(gai));
			if (subject)
				free(subject);
			switch(ai->ai_addr->sa_family){
			case AF_INET6:
				if (subject)
					free(subject);
				subject = malloc(sizeof(struct in6_addr));
				if (!subject)
					err(2, "Cannot alloc memory for subject");
				memcpy(subject, &((struct sockaddr_in6*)ai->ai_addr)->sin6_addr,
					sizeof(struct in6_addr));
				subjecttype = ICMP6_NI_SUBJ_IPV6;
				subjectlen = sizeof(struct in6_addr);
				break;
			case AF_INET:
				if (subject) 
					free(subject);
				subject = malloc(sizeof(struct in_addr));
				if (!subject)
					err(2, "Cannot alloc memory for subject");
				memcpy(subject, &((struct sockaddr_in*)ai->ai_addr)->sin_addr, 
					sizeof(struct in_addr));
				subjecttype = ICMP6_NI_SUBJ_IPV4;
				subjectlen = sizeof(struct in_addr);
				break;
			default:
				errx(2,"Unsupported address family for subject\n");
			}
			freeaddrinfo(ai);
			break;
		    }
		case 'J':
		    {
			char *buf;
			int fqdn = 0;
			char *p, *q;
			int slen = 0;
			buf = malloc(strlen(optarg) + 3);
			if (!optarg)
				err(2, "Cannot alloc memory for subject");
			for (p = optarg, q = buf + 1; *p; p++)
				*q++ = isupper(*p) ? tolower(*p) : *p;
			if (*(buf + 1 + strlen(buf + 1) - 1) == '.'){
				fqdn = 1;
				*(buf + 1 + strlen(buf + 1) - 1) = '\0';
			}
			*q = '\0';
			p = buf;
			while(p){
				size_t l;
				q = strchr(p + 1, '.');
				l = q ? ((size_t)(q - (p + 1))) : strlen(p + 1);
				if (l >= 0x40)
					errx(2, "length of single component of subject name (%d) is too large", l);
				if (slen + l + 1 + 1 > 255)
					errx(2, "length of subject name is too large");
				*p = (char)l;
				slen += l + 1;
				p = q;
			}
			if (slen > 0)
				slen++;
			if (!fqdn){
				buf[slen] = '\0';
				slen++;
			}
			if (subject)
				free(subject);
			subject = buf;
			subjectlen = slen;
			subjecttype = ICMP6_NI_SUBJ_FQDN;
			break;
		    }
#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
		case 'P':
			ipsec_opts |= F_POLICY;
			if (strncmp("in", optarg, 2) == 0)
				policy_in = strdup(optarg);
			else if (strncmp("out", optarg, 3) == 0)
				policy_out = strdup(optarg);
			else
				errx(2, "invalid security policy");
			break;
#else
		case 'A':
			ipsec_opts |= F_AUTHHDR;
			break;
		case 'E':
			ipsec_opts |= F_ENCRYPT;
			break;
#endif /*IPSEC_POLICY_IPSEC*/
#endif /*IPSEC*/
		case '?':
			usage_long();
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

        if (options & F_FLOOD && options & F_INTERVAL)
		errx(2, "-f and -i incompatible options.");

	while (argc > 1)
	{
#ifndef USE_RFC2292
		struct ip6_rthdr *rth = NULL;
#endif
		if (cm == NULL)
		{
			int space;
#ifndef USE_RFC2292
			space = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1);
			if (space == 0)
				warnx("inet6_rth_space() failed");
			if (cmsglen + CMSG_LEN(space) > sizeof(cmsgbuf))
				errx(2, "no room for options");
			cm = (struct cmsghdr*)(cmsgbuf+cmsglen);
			cm->cmsg_len = CMSG_LEN(space);
			cm->cmsg_level = IPPROTO_IPV6;
			cm->cmsg_type = IPV6_RTHDR;
			rth = (struct ip6_rthdr *)CMSG_DATA(cm);
			rth = inet6_rth_init((void*)rth, space, 
						IPV6_RTHDR_TYPE_0, argc - 1);
			if (rth == NULL)
				errx(2, "can't initialize rthdr");
#else
			space = inet6_rthdr_space(IPV6_RTHDR_TYPE_0, argc - 1);

			if (space == 0)
				warnx("rthdr_space failed");
			if (space + cmsglen > sizeof(cmsgbuf))
				errx(2, "no room for options");

			cm = (struct cmsghdr*)(cmsgbuf+cmsglen);
			cmsglen += CMSG_ALIGN(space);
			inet6_rthdr_init(cm, IPV6_RTHDR_TYPE_0);
#endif
		}

		target = *argv;

		memset(&hints, 0, sizeof(hints));
		hints.ai_family = PF_INET6;
#ifdef GAI_OK_WITH_RAW_ICMPV6
		hints.ai_socktype = SOCK_RAW;
#endif
		gai = getaddrinfo(target, NULL, &hints, &res0);
		if (gai)
			errx(2, "%s: %s", gai_strerror(gai), target);
		if (!res0->ai_addr || res0->ai_addr->sa_family != AF_INET6)
			errx(2, "getaddrinfo() failed: %s", target);
		if (res0->ai_addrlen > sizeof(struct sockaddr_in6))
			errx(2, "getaddrinfo failed: returned sockaddr_in6{} is too large.");
#ifndef USE_RFC2292
		inet6_rth_add(rth, &((struct sockaddr_in6*)res0->ai_addr)->sin6_addr);
#else
		inet6_rthdr_add(cm, &((struct sockaddr_in6*)res0->ai_addr)->sin6_addr, IPV6_RTHDR_LOOSE);
#endif
		if (IN6_IS_ADDR_UNSPECIFIED(&firsthop.sin6_addr))
			memcpy(&firsthop, res0->ai_addr, res0->ai_addrlen);
		freeaddrinfo(res0);

		argv++;
		argc--;
	}

	if (argc != 1)
		usage();

	if (ni_opts & F_NIGROUP) {
		target = nigroup(*argv);
		if (target == NULL) {
			usage();
			/*NOTREACHED*/
		}
	} else
		target = *argv;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = PF_INET6;
#ifdef GAI_OK_WITH_RAW_ICMPV6
	hints.ai_socktype = SOCK_RAW;
	hints.ai_protocol = IPPROTO_ICMPV6;
#endif
	hints.ai_flags = (options & F_NUMERIC) ? 0 : AI_CANONNAME;

	gai = getaddrinfo(target, NULL, &hints, &res0);
	if (gai)
		errx(2, "%s", gai_strerror(gai));
	if (!res0->ai_addr || res0->ai_addr->sa_family != AF_INET6)
		errx(2, "getaddrinfo failed");
	if (res0->ai_canonname){
		hostname = strdup(res0->ai_canonname);
		if (!hostname)
			errx(2, "strdup failed");
	}
	else
		hostname = target;

	if (res0->ai_addrlen > sizeof(whereto))
		errx(2, "getaddrinfo failed: returned sockaddr_in6{} is too large.");
        memcpy(&whereto, res0->ai_addr, res0->ai_addrlen);
	wheretolen = res0->ai_addrlen;
#ifndef GAI_OK_WITH_RAW_ICMPV6
	whereto.sin6_port = htons(IPPROTO_ICMPV6);
#endif
	freeaddrinfo(res0);

	if (IN6_IS_ADDR_UNSPECIFIED(&firsthop.sin6_addr))
		memcpy(&firsthop, &whereto, sizeof(firsthop));

	if (IN6_IS_ADDR_UNSPECIFIED(&source.sin6_addr)) {
		int probe_fd = socket(AF_INET6, SOCK_DGRAM, 0);

		if (probe_fd < 0)
			err(2, "socket");
		if (device) {
			struct ifreq ifr;
			strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
#if 0
			if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) == -1) {
				if (IN6_IS_ADDR_LINKLOCAL(&firsthop.sin6_addr) ||
				    IN6_IS_ADDR_MC_LINKLOCAL(&firsthop.sin6_addr)){
					if (ioctl(probe_fd, SIOCGIFINDEX, &ifr) < 0)
						errx(2, "ping6: unknown iface %s\n", device);
					firsthop.sin6_scope_id = ifr.ifr_ifindex;
				} else
					warn("interface is ignored");
			}
#else
			if (setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) == -1)
				warn("interface is ignored");
#endif
		}
		firsthop.sin6_port = htons(1025);
		if (connect(probe_fd, (struct sockaddr*)&firsthop, sizeof(firsthop)) == -1)
			err(2, "connect");
		sourcelen = sizeof(source);
		if (getsockname(probe_fd, (struct sockaddr*)&source, &sourcelen) == -1)
			err(2, "getsockname");
		source.sin6_port = 0;
		close(probe_fd);
	}

	if (icmp_sock < 0) {  
		errno = socket_errno;
		err(2, "icmp open socket");
	}

	if (device) {
		struct ifreq ifr;
		struct cmsghdr *cmsg;
		struct in6_pktinfo *ipi;

		memset(&ifr, 0, sizeof(ifr));
		strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
		if (ioctl(icmp_sock, SIOCGIFINDEX, &ifr) < 0)
			errx(2, "unknown iface %s", device);
		cmsg = (struct cmsghdr*)cmsgbuf;
		cmsglen += CMSG_SPACE(sizeof(*ipi));
		cmsg->cmsg_len = CMSG_LEN(sizeof(*ipi));
		cmsg->cmsg_level = SOL_IPV6;
		cmsg->cmsg_type = IPV6_PKTINFO;

		ipi = (struct in6_pktinfo*)CMSG_DATA(cmsg);
		memset(ipi, 0, sizeof(*ipi));
		ipi->ipi6_ifindex = ifr.ifr_ifindex;
	}

	if (IN6_IS_ADDR_MULTICAST(&whereto.sin6_addr)) {
		if (uid) {
			if (interval.tv_sec < 1)
				errx(2, "multicast ping with too short interval.");
			if (pmtudisc >= 0 && pmtudisc != IPV6_PMTUDISC_DO)
				errx(2, "multicast ping does not fragment.");
		}
		if (pmtudisc < 0)
			pmtudisc = IPV6_PMTUDISC_DO;
	}

	if (bind(icmp_sock, (struct sockaddr*)&source, sizeof(source)) == -1)
		err(2, "bind icmp socket");

	if ((!(ni_opts & F_NIFLAGS)) && (datalen >= sizeof(struct timeval)))	/* can we time transfer */
		timing = 1;
	else
		timing = 0;
	packlen = datalen + MAXIPLEN + MAXICMPLEN + EXTRA;
	if (!(packet = (u_char *)malloc((u_int)packlen)))
		errx(2, "out of memory.");

	if (!(options & F_PINGFILLED)) {
		char *datap = outpack+8+sizeof(struct timeval);

		for (i = sizeof(struct timeval); i < datalen; ++i)
			*datap++ = i;
	}

	ident = getpid() & 0xFFFF;
	gettimeofday(&t, NULL);
	srand((unsigned int)(t.tv_sec ^ t.tv_usec ^ (long)ident));

	hold = 1;
	if (options & F_SO_DEBUG)
		setsockopt(icmp_sock, SOL_SOCKET, SO_DEBUG, (char *)&hold, sizeof(hold));
	if (options & F_SO_DONTROUTE)
		setsockopt(icmp_sock, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, sizeof(hold));

	hold = datalen+8;
	hold += ((hold+511)/512)*(40+128);
	setsockopt(icmp_sock, SOL_SOCKET, SO_SNDBUF, (char *)&hold, sizeof(hold));

	hold = 65535;
	setsockopt(icmp_sock, SOL_SOCKET, SO_RCVBUF, (char *)&hold, sizeof(hold));

	csum_offset = 2;
	sz_opt = sizeof(int);

	if (setsockopt(icmp_sock, SOL_RAW, IPV6_CHECKSUM, &csum_offset, sz_opt) < 0)
		err(2, "setsockopt(RAW_CHECKSUM)");

	/*
	 *	select icmp echo reply as icmp type to receive
	 */

	ICMP6_FILTER_SETBLOCKALL(&filter);

	ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &filter);
	ICMP6_FILTER_SETPASS(ICMP6_PACKET_TOO_BIG, &filter);
	ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &filter);
	ICMP6_FILTER_SETPASS(ICMP6_PARAM_PROB, &filter);

	if (ni_opts & (F_SUPTYPES|F_FQDN|F_NODEADDR|F_IPV4ADDR))
		ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filter);
	else
		ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filter);

	if (setsockopt(icmp_sock, SOL_ICMPV6, ICMP6_FILTER, &filter,
			sizeof(struct icmp6_filter)) < 0)
		err(2, "setsockopt(ICMP6_FILTER)");

	if (options & F_MC_NOLOOP) {
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
							&loop, sizeof(loop)) == -1)
			err(2, "can't disable multicast loopback");
	}
	if (options & F_HOPLIMIT) {
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
							&hlim, sizeof(hlim)) == -1)
			err(2, "can't set multicast hop limit");
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
							&hlim, sizeof(hlim)) == -1)
			err(2, "can't set unicast hop limit");
	}

#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
	if (ipsec_opts & F_POLICY) {
		if (setpolicy(icmp_sock, policy_in) < 0)
			errx(2, "%s", ipsec_strerror());
		if (setpolicy(icmp_sock, policy_out) < 0)
			errx(2, "%s", ipsec_strerror());
	}
#else
	if (ipsec_opts & F_AUTHHDR) {
		optval = IPSEC_LEVEL_REQUIRE;
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL,
				&optval, sizeof(optval)) == -1){
			warnx("setsockopt(IPV6_AUTH_TRANS_LEVEL)");
		}
	}
	if (ipsec_opts & F_ENCRYPT) {
		optval = IPSEC_LEVEL_REQUIRE;
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL,
				&optval, sizeof(optval)) == -1){
			warnx("setsockopt(IPV6_ESP_TRANS_LEVEL)");
		}
	}
#endif /*IPSEC_POLICY_IPSEC*/
#endif

	if (1) {
		int on = 1;
#ifndef USE_RFC2292
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
			       &on, sizeof(on)) == -1)
			err(2, "can't receive hop limit");
#else
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_2292HOPLIMIT,
				&on, sizeof(on)) == -1)
			err(2, "can't receive hop limit");
#endif
	}

	if (options&F_FLOWINFO) {
#ifdef IPV6_FLOWLABEL_MGR
		char freq_buf[CMSG_ALIGN(sizeof(struct in6_flowlabel_req)) + cmsglen];
		struct in6_flowlabel_req *freq = (struct in6_flowlabel_req *)freq_buf;
		int freq_len = sizeof(*freq);
		if (cm)
			freq_len = CMSG_ALIGN(sizeof(*freq)) + cm->cmsg_len;
		memset(freq, 0, sizeof(*freq));
		freq->flr_label = htonl(flowlabel&0xFFFFF);
		freq->flr_action = IPV6_FL_A_GET;
		freq->flr_flags = IPV6_FL_F_CREATE;
		freq->flr_share = IPV6_FL_S_EXCL;
		memcpy(&freq->flr_dst, whereto.sin6_addr, 16);
		if (cm)
			memcpy(freq_buf + CMSG_ALIGN(sizeof(*freq)), cm, cm->cmsg_len);
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_FLOWLABEL_MGR,
			       freq, freq_len) == -1)
			err(2, "can't set flowlabel");
		flowlabel = freq->flr_label;
		if (cm) {
			cmsglen = (char*)cm - (char*)cmsgbuf;
			cm = NULL;
		}
#else
		errx(2, "Flow labels are not supported.");
#endif
	}
	if (options&(F_FLOWINFO|F_TCLASS)) {
#ifdef IPV6_FLOWINFO_SEND
		int on = 1;
		whereto.sin6_flowinfo = flowlabel | htonl((tclass&0xFF)<<20);
		if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_FLOWINFO_SEND,
			       &on, sizeof(on)) == -1)
			err(2, "can't send flowinfo");
#else
		errx(2, "Flowinfo is not supported.");
#endif
	}
#ifdef SO_TIMESTAMP
	if (!(options&F_LATENCY)) {
		int on = 1;
		if (setsockopt(icmp_sock, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)))
			warnx("no SO_TIMESTAMP support, falling back to SIOCGSTAMP");
	}
#endif
	if (1) {
		struct timeval tv;
		tv.tv_sec = 1;
		tv.tv_usec = 0;
		if (interval.tv_sec < 1)
			tv = interval;
		setsockopt(icmp_sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv));
	}	

	printf("PING %s(%s) ", hostname, pr_addr(&whereto, wheretolen));
	if (flowlabel)
		printf(", flow 0x%05x, ", (unsigned)ntohl(flowlabel));
	printf("from %s %s: ",
	       pr_addr(&source, sourcelen), device ? : "");
	printf("%d data bytes\n", datalen);

	set_signal(SIGINT, finish);
	set_signal(SIGALRM, catcher);

	while (preload--)		/* fire off them quickies */
		pinger();

	if ((options & F_FLOOD) == 0) {
		catcher(0);		/* start things going */
	} else {
		struct timeval tv;
		tv.tv_usec = 20000;
		tv.tv_sec = 0;
		if (setsockopt(icmp_sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv))) {
			fprintf(stderr, "Warning: no SO_RCVTIMEO support, falling back to poll\n");
			options |= F_FLOOD_POLL;
		}
	}
	starttime = time(NULL);
	iov.iov_base = (char *)packet;

	for (;;) {
		char ans_data[128];
		struct sockaddr_in6 from;
		struct msghdr msg = {
			(void*)&from, sizeof(from),
			&iov, 1,
			ans_data, sizeof(ans_data),
		};
		int cc;
		int hops = -1;

		if (npackets && nreceived >= npackets)
			break;
		if (deadline && (nerrors ||
				 (int)(time(NULL) - starttime) > deadline))
			break;

		if (options & F_FLOOD)
			pinger();

reselect:

		if (options & F_FLOOD_POLL) {
			struct pollfd pset;

			pset.fd = icmp_sock;
			pset.events = POLLIN|POLLERR;
			pset.revents = 0;
			if (poll(&pset, 1, 20) < 1 || !(pset.revents&(POLLIN|POLLERR)))
				continue;
		}

		iov.iov_len = packlen;

		if ((cc = recvmsg(icmp_sock, &msg, 0)) < 0) {
			if (errno != EINTR && errno != EWOULDBLOCK)
				warn("recvmsg");
		} else {
			struct timeval *recv_timep = NULL;
			struct timeval recv_time;
			if ((options&F_LATENCY) ||
			    ioctl(icmp_sock, SIOCGSTAMP, &recv_time))
				gettimeofday(&recv_time, NULL);

			for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) {
#ifdef SO_TIMESTAMP
				if (cm->cmsg_level == SOL_SOCKET &&
				    cm->cmsg_type == SO_TIMESTAMP &&
				    cm->cmsg_len >= CMSG_LEN(sizeof(struct timeval))) {
					recv_timep = (struct timeval*)CMSG_DATA(cm);
					continue;
				}
				else
#endif
				if (cm->cmsg_level == SOL_IPV6 &&
#ifdef USE_RFC2292
				    cm->cmsg_type == IPV6_2292HOPLIMIT &&
#else
				    cm->cmsg_type == IPV6_HOPLIMIT &&
#endif
				    cm->cmsg_len == CMSG_LEN(sizeof(int))){
					hops = *(int *)CMSG_DATA(cm);
					continue;
				}
			}

			if ((options&F_LATENCY) || recv_timep==NULL) {
				if ((options&F_LATENCY) ||
				    ioctl(icmp_sock, SIOCGSTAMP, &recv_time))
					gettimeofday(&recv_time, NULL);
				recv_timep = &recv_time;
			}
			if (pr_pack((char *)packet, cc, &from, msg.msg_namelen, hops, recv_timep)) {
				if (options & F_FLOOD)
					goto reselect;
			}
		}
	}
	finish(0);
	/* NOTREACHED */
}

/*
 * catcher --
 *	This routine causes another PING to be transmitted, and then
 * schedules another SIGALRM for 'interval' millisecond from now.
 * 
 * bug --
 *	Our sense of time will slowly skew (i.e., packets will not be
 * launched exactly at given intervals).  This does not affect the
 * quality of the delay and loss statistics.
 */
void catcher(int sig)
{
	static int slop = 10;
	static struct timeval prev;
	struct timeval now;
	double delta = 0.;
	struct timeval waittime;
	int saved_errno = errno;

	gettimeofday(&now, NULL);

	if (sig) {
		delta = (double)(now.tv_sec - prev.tv_sec);
		delta += ((double)(now.tv_usec - prev.tv_usec)) / 1000000.;
		if (delta >= (interval.tv_sec - slop))
			sig = 0;
	}

	if (sig == 0) {
		pinger();
		prev = now;
	}

	if (!npackets || ntransmitted < npackets || deadline) {
		waittime = interval;
	} else {
		if (nreceived) {
			waittime.tv_sec = 2 * tmax / 1000;
			if (waittime.tv_sec == 0)
				waittime.tv_sec = 1;
		} else
			waittime.tv_sec = MAXWAIT;
		waittime.tv_usec = 0;
	}

	do {
		struct itimerval it;

		it.it_interval.tv_sec = 0;
		it.it_interval.tv_usec = 0;
		it.it_value = waittime;
		setitimer(ITIMER_REAL, &it, NULL);
	} while (0);

	errno = saved_errno;
}

/*
 * pinger --
 * 	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
 * will be added on by the kernel.  The ID field is our UNIX process ID,
 * and the sequence number is an ascending integer.  The first 8 bytes
 * of the data portion are used to hold a UNIX "timeval" struct in VAX
 * byte-order, to compute the round-trip time.
 */
void pinger(void)
{
	struct icmp6_hdr *icp;
	struct msghdr smsghdr;
	struct iovec iov;
	struct icmp6_nodeinfo *nip;
	register int i, cc;
	int seq;

	icp = (struct icmp6_hdr *)outpack;
	nip = (struct icmp6_nodeinfo *)icp;
	memset(icp, 0, sizeof(*icp));
	icp->icmp6_cksum = 0;
	seq = ntransmitted++;
	CLR(seq % mx_dup_ck);

	if (ni_opts & F_NIFLAGS) {
		icp->icmp6_type = ICMP6_NI_QUERY;
		cc = sizeof(*nip);
		datalen = 0;
		switch(ni_opts & F_NIFLAGS){
		case F_SUPTYPES:
			icp->icmp6_code = ICMP6_NI_SUBJ_FQDN;	/*empty*/
			nip->ni_qtype = htons(NI_QTYPE_SUPTYPES);
			nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS; /* XXX: set by option? */
			break;
		case F_FQDN:
			if (!subject){
				subject = &whereto.sin6_addr;
				subjectlen = sizeof(whereto.sin6_addr);
				subjecttype = ICMP6_NI_SUBJ_IPV6;
			}
			icp->icmp6_code = subjecttype;
			nip->ni_qtype = htons(NI_QTYPE_FQDN);
			nip->ni_flags = htons(0);
			memcpy((void *)(nip+1), subject, subjectlen);
			cc += subjectlen;
			break;
		case F_NODEADDR:
			if (!subject){
				subject = &whereto.sin6_addr;
				subjectlen = sizeof(whereto.sin6_addr);
				subjecttype = ICMP6_NI_SUBJ_IPV6;
			}
			icp->icmp6_code = subjecttype;
			((struct icmp6_nodeinfo *)icp)->ni_qtype =
			  htons(NI_QTYPE_NODEADDR);
			((struct icmp6_nodeinfo *)icp)->ni_flags = naflags;
			memcpy((void *)(nip+1), subject, subjectlen);
			cc += subjectlen;
			break;
		case F_IPV4ADDR:
			if (!subject){
				subject = &whereto.sin6_addr;
				subjectlen = sizeof(whereto.sin6_addr);
				subjecttype = ICMP6_NI_SUBJ_IPV6;
			}
			icp->icmp6_code = subjecttype;       
			((struct icmp6_nodeinfo *)icp)->ni_qtype =
			  htons(NI_QTYPE_IPV4ADDR);
			((struct icmp6_nodeinfo *)icp)->ni_flags = naflags;
			memcpy((void *)(nip+1), subject, subjectlen);
			cc += subjectlen;
		}
		*(u_int16_t*)&nip->icmp6_ni_nonce[0] = htons(seq);
		*(u_int16_t*)&nip->icmp6_ni_nonce[2] = rand() & 0xffff;
		*(u_int16_t*)&nip->icmp6_ni_nonce[4] = rand() & 0xffff;
		*(u_int16_t*)&nip->icmp6_ni_nonce[6] = rand() & 0xffff;
		memcpy(nonce, nip->icmp6_ni_nonce,
		       sizeof(nip->icmp6_ni_nonce));
	} else {
		icp->icmp6_type = ICMP6_ECHO_REQUEST;
		icp->icmp6_seq = htons(seq);
		icp->icmp6_id = htons(ident);
		cc = sizeof(struct icmp6_hdr) + datalen;
		if (timing)
			gettimeofday((struct timeval *)(icp+1), NULL);
	}

resend:
	smsghdr.msg_name = &whereto;
	smsghdr.msg_namelen = wheretolen;
	memset(&iov, 0, sizeof(iov));
	iov.iov_base = outpack;
	iov.iov_len  = cc;
	smsghdr.msg_iov = &iov;
	smsghdr.msg_iovlen = 1;
	smsghdr.msg_control = cmsgbuf;
	smsghdr.msg_controllen = cmsglen;

	i = sendmsg(icmp_sock, &smsghdr, confirm);

	confirm = 0;

	if (i < 0 && confirm_flag) {
		confirm_flag = 0;
		goto resend;
	}

	if (i < 0 || i != cc)  {
		if (i < 0) {
			if (errno == EAGAIN) {
				ntransmitted--;
			} else {
				warn("sendmsg");
			}
		} else {
			printf("ping6: wrote %s %d chars, ret=%d\n",
			       hostname, cc, i);
		}
	}
	else if (!(options & F_QUIET) && options & F_FLOOD)
		write(STDOUT_FILENO, &DOT, 1);
}

int myechoreply(const struct icmp6_hdr *icp){
	return (ntohs(icp->icmp6_id) == ident ? 1 : 0);
}
int mynireply(const struct icmp6_nodeinfo *nip){
	return ((memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t),
			nonce + sizeof(u_int16_t),
			sizeof(nonce) - sizeof(u_int16_t)) == 0) ? 1 : 0);
}

/*
 * pr_pack --
 *	Print out the packet, if it came from us.  This logic is necessary
 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
 * which arrive ('tis only fair).  This permits multiple copies of this
 * program to be run without having intermingled output (or statistics!).
 */
int pr_pack(char *buf, int cc, struct sockaddr_in6 *from, socklen_t fromlen, int hops, struct timeval *tv)
{
	struct icmp6_hdr *icp;
	u_char *cp,*dp,*end = buf + cc;
	struct timeval *tp;
	double triptime = 0;
	int dupflag = 0;

	/* Now the ICMP part */

	icp = (struct icmp6_hdr *) buf;
	if (cc < 8) {
		if (options & F_VERBOSE)
			warnx("packet too short (%d bytes)", cc);
		return 1;
	}

	if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) {
		++nreceived;
		if (timing && cc >= 8+sizeof(struct timeval)) {
			tp = (struct timeval *)((u_char *)icp + ICMP6_HDRLEN);

restamp:
			tvsub(tv, tp);
			triptime = ((double)tv->tv_sec) * 1000.0 + 
				((double)tv->tv_usec) / 1000.0;
			if (triptime < 0) {
				warnx("time of day goes back, taking countermeasures.");
				triptime = 0.;
				if (!(options & F_LATENCY)) {
					gettimeofday(tv, NULL);
					options |= F_LATENCY;
					goto restamp;
				}
			}
			tsum += triptime;
			tsumsq += triptime * triptime;
			if (triptime < tmin)
				tmin = triptime;
			if (triptime > tmax)
				tmax = triptime;
		}

		if (TST(ntohs(icp->icmp6_seq) % mx_dup_ck)) {
			++nrepeats;
			--nreceived;
			dupflag = 1;
		} else {
			SET(ntohs(icp->icmp6_seq) % mx_dup_ck);
			dupflag = 0;
		}
		confirm = confirm_flag;

		if (options & F_QUIET)
			return 0;

		if (options & F_FLOOD)
			write(STDOUT_FILENO, &BSPACE, 1);
		else {
			int i;
			printf("%d bytes from %s: icmp_seq=%u", cc,
				     pr_addr(from, fromlen),
				     ntohs(icp->icmp6_seq));

			if (hops >= 0)
				printf(" hops=%d", hops);

			if (cc < datalen+8) {
				printf(" (truncated)");
				return 1;
			}

			if (timing) {
				if (triptime > 100000.0) {
					printf(" time=%.3f sec", triptime / 1000.0);
				} else if (triptime > 100.0) {
					printf(" time=%.3f msec", triptime);
				} else {
					printf(" time=%.3f usec", triptime * 1000.0);
				}
			}
			if (dupflag)
				printf(" (DUP!)");

			/* check the data */
			cp = (u_char*)icp + ICMP6_HDRLEN + sizeof(struct timeval);
			dp = &outpack[8 + sizeof(struct timeval)];
			for (i = sizeof(struct timeval); i < datalen; ++i, ++cp, ++dp) {
				if (*cp != *dp) {
					printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
					       i, *dp, *cp);
					cp = (u_char*)icp + ICMP6_HDRLEN;
					for (i = sizeof(struct timeval); i < datalen; ++i, ++cp) {
						if ((i % 32) == sizeof(struct timeval))
							printf("\n#%d\t", i);
						printf("%x ", *cp);
					}
					break;
				}
			}
		}
	} else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply((struct icmp6_nodeinfo*)icp)) { /* ICMP6_NI_REPLY */
		struct icmp6_nodeinfo *ni = (struct icmp6_nodeinfo *)(buf);
		++nreceived;
		if (TST(ntohs(*(u_int16_t*)&ni->icmp6_ni_nonce[6]) % mx_dup_ck)) {
			++nrepeats;
			--nreceived;
			dupflag = 1;
		} else {
			SET(ntohs(*(u_int16_t*)&ni->icmp6_ni_nonce[6]) % mx_dup_ck);
			dupflag = 0;
		}
		printf("%d bytes from %s: ", cc,
			     pr_addr(from, fromlen));

		switch(ntohs(ni->ni_qtype)) {
		case NI_QTYPE_NOOP:
			printf("NodeInfo NOOP");
			break;
		case NI_QTYPE_SUPTYPES:
			printf("NodeInfo Supported Qtypes");
			pr_suptypes(ni, end - (u_char *)ni);
			break;
		case NI_QTYPE_FQDN:
			pr_fqdn(ni, end - (u_char *)ni);
			break;
		case NI_QTYPE_NODEADDR:
			pr_nodeaddr(ni, end - (u_char *)ni);
			 break;
		case NI_QTYPE_IPV4ADDR:
			pr_ipv4addr(ni, end - (u_char *)ni);
			 break;
		default:
			/* XXX: for backward compatibility */
			pr_fqdn(ni, end - (u_char *)ni);
			break;
		}
	} else {
		struct ip6_hdr *iph1 = (struct ip6_hdr*)(icp+1);

		if (cc < 8+sizeof(struct ip6_hdr)+8)
			return 1;

		if (memcmp(&iph1->ip6_dst, &whereto.sin6_addr, 16))
			return 1;

		if (iph1->ip6_nxt == IPPROTO_ICMPV6) {
			struct icmp6_hdr *icp1 = (struct icmp6_hdr *)(iph1+1);
			if (icp1->icmp6_type == ICMP6_ECHO_REQUEST) {
				if (!myechoreply(icp1))
					return 1;
			}
			else if (icp1->icmp6_type == ICMP6_NI_QUERY) {
				if (!mynireply((struct icmp6_nodeinfo*)icp1))
					return 1;
			}
			nerrors++;
			if (options & F_FLOOD) {
				write(STDOUT_FILENO, "E", 1);
				return 0;
			}
			printf("From %s: ", pr_addr(from, fromlen));
		} else {
			/* We've got something other than an ECHOREPLY */
			if (!(options & F_VERBOSE) || uid)
				return 1;
			printf("From %s: ",
				     pr_addr(from, fromlen));
		}
		pr_icmph(icp, end);
	}

	if (!(options & F_FLOOD)) {
		putchar('\n');
		fflush(stdout);
	}
	return 0;
}


int pr_icmph(struct icmp6_hdr *icp, u_char *end)
{
	switch(icp->icmp6_type) {
	case ICMP6_DST_UNREACH:
		nerrors++;
		if (!(options & F_VERBOSE))
			break;
		printf("Destination unreachable: ");
		switch (icp->icmp6_code) {
		case ICMP6_DST_UNREACH_NOROUTE:
			printf("No route");
			break;
		case ICMP6_DST_UNREACH_ADMIN:
			printf("Administratively prohibited");
			break;
		case ICMP6_DST_UNREACH_BEYONDSCOPE:
			printf("beyond scope");
			break;
		case ICMP6_DST_UNREACH_ADDR:
			printf("Address unreachable");
			break;
		case ICMP6_DST_UNREACH_NOPORT:
			printf("Port unreachable");
			break;
		default:	
			printf("Unknown code %d", icp->icmp6_code);
			break;
		}
		printf("\n");
		pr_retip((struct ip6_hdr *)(icp + 1), end);
		break;
	case ICMP6_PACKET_TOO_BIG:
		nerrors++;
		if (!(options & F_VERBOSE))
			break;
		printf("Packet too big: mtu=%u", 
			(unsigned int)ntohl(icp->icmp6_mtu));
		switch (icp->icmp6_code) {
		case 0:
			break;
		default:
			printf(", code=%d", icp->icmp6_code);
		}
		printf("\n");
		pr_retip((struct ip6_hdr *)(icp + 1), end);
		break;
	case ICMP6_TIME_EXCEEDED:
		nerrors++;
		if (!(options & F_VERBOSE))
			break;
		printf("Time exceeded: ");
		switch (icp->icmp6_code) {
		case ICMP6_TIME_EXCEED_TRANSIT:
			printf("Hop limit");
			break;
		case ICMP6_TIME_EXCEED_REASSEMBLY:
			printf("Defragmentation failure");
			break;
		default:
			printf("code %d", icp->icmp6_code);
		}
		printf("\n");
		pr_retip((struct ip6_hdr *)(icp + 1), end);
		break;
	case ICMP6_PARAM_PROB:
		nerrors++;
		if (!(options & F_VERBOSE))
			break;
		printf("Parameter problem: ");
		switch (icp->icmp6_code) {
		case ICMP6_PARAMPROB_HEADER:
			printf("Wrong header field ");
			break;
		case ICMP6_PARAMPROB_NEXTHEADER:
			printf("Unknown header ");
			break;
		case ICMP6_PARAMPROB_OPTION:
			printf("Unknown option ");
			break;
		default:
			printf("code %d ", icp->icmp6_code);
		}
		printf ("at %u", (unsigned int)ntohl(icp->icmp6_pptr));
		printf("\n");
		pr_retip((struct ip6_hdr *)(icp + 1), end);
		break;
	case ICMP6_ECHO_REQUEST:
		printf("Echo request");
		break;
	case ICMP6_ECHO_REPLY:
		printf("Echo reply");
		break;
	case ICMP6_MEMBERSHIP_QUERY:
		printf("MLD Query");
		break;
	case ICMP6_MEMBERSHIP_REPORT:
		printf("MLD Report");
		break;
	case ICMP6_MEMBERSHIP_REDUCTION:
		printf("MLD Reduction");
		break;
	case ND_ROUTER_SOLICIT:
		printf("Router Solicitation");
		break;
	case ND_ROUTER_ADVERT:
		printf("Router Advertisement");
		break;
	case ND_NEIGHBOR_SOLICIT:
		printf("Neighbor Solicitation");
		break;
	case ND_NEIGHBOR_ADVERT:
		printf("Neighbor Advertisement");
		break;
	case ND_REDIRECT:
	    {
		struct nd_redirect *ndr = (struct nd_redirect *)icp;
		char addrbuf[128];
		printf("Redirect\n");
		if (!inet_ntop(AF_INET6, &ndr->nd_rd_dst, addrbuf,
			       sizeof(addrbuf)))
			strncpy(addrbuf, "?", sizeof(addrbuf));
		printf("Destination: %s", addrbuf);
		if (!inet_ntop(AF_INET6, &ndr->nd_rd_target, addrbuf, sizeof(addrbuf)))
			strncpy(addrbuf, "?", sizeof(addrbuf));
		printf("New Target: %s", addrbuf);
		break;
	    }
	case ICMP6_NI_QUERY:
		printf("Node Information Query");
		break;
	case ICMP6_NI_REPLY:
		printf("Node Information Reply");
		break;
	default:
		printf("unknown icmp type: %d", icp->icmp6_type);
		pr_retip((struct ip6_hdr *)(icp + 1), end);
	}
	return 0;
}

/*
 * finish --
 *	Print out statistics, and give up.
 */
void finish(int sig)
{
	set_signal(SIGALRM, SIG_IGN);

	putchar('\n');
	fflush(stdout);
	printf("--- %s ping statistics ---\n", hostname);
	printf("%ld packets transmitted, ", ntransmitted);
	printf("%ld packets received, ", nreceived);
	if (nrepeats)
		printf("+%ld duplicates, ", nrepeats);
	if (nchecksum)
		printf("+%ld corrupted, ", nchecksum);
	if (nerrors)
		printf("+%ld errors, ", nerrors);
	if (ntransmitted) {
		if (nreceived > ntransmitted)
			printf("-- somebody's printing up packets!");
		else
			printf("%d%% packet loss",
			    (int) (((ntransmitted - nreceived) * 100) /
			    ntransmitted));
	}
	putchar('\n');
	if (nreceived && timing && !(ni_opts & (F_FQDN|F_NODEADDR))){
		double num = nreceived + nrepeats;
		double avg = tsum / num;
		double dev = sqrt(tsumsq / num - avg * avg);
		printf("round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
			tmin, avg, tmax, dev);
	}
	exit(deadline ? nreceived < npackets : nreceived==0);
}

static int pr_bitrange(u_int32_t v, u_int32_t s, int ii) {
	u_int32_t off = 0;
	int i;

	while (off < 32) {
		/* shift till we have 0x01 */
		if ((v & 0x01) == 0) {
			if (ii > 1)
				printf("-%u", s + off - 1);
			ii = 0;
			switch (v & 0x0f) {
			case 0x00:
				v >>= 4; off += 4; continue;
			case 0x08:
				v >>= 3; off += 3; continue;
			case 0x04: case 0x0c:
				v >>= 2; off += 2; continue;
			default:
				v >>= 1; off += 1; continue;
			}
		}
		/* we have 0x01 with us */
		for (i = 0; i < 32 - off; i++) {
			if ((v & (0x01 << i)) == 0)
				break;
		}
		if (!ii)
			printf(" %u", s + off);
		ii += i;
		v >>= i; off += i;
	}
	return ii;
}

static void pr_suptypes(struct icmp6_nodeinfo *ni, int nilen)
{
	const u_char *cp  = (const u_char *)ni + ICMP6_NILEN;
	const u_char *end = (const u_char *)ni + nilen;
	u_int16_t nword = 0, nskip = 0;
	u_int32_t qoff = 0;
	int compressed = (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS);

	nilen -= ICMP6_NILEN;

	if (compressed) {
		printf(", compressed bitmap");
		if (nilen == 0 || nilen % sizeof(u_int32_t)){
			printf(", invalid length(%u)", nilen);
			return;
		}
	}
	else {
		printf(", raw bitmap");
		if (nilen == 0 || nilen > MAXNIQTYPEBMP ||
		    nilen % sizeof(u_int32_t)){
			printf(", invalid length(%u)", nilen);
			return;
		}
	}
	while (cp < end) {
		int b = 0;
		int i;
		if (compressed) {
			if (nilen < sizeof(u_int16_t) * 2) {
				printf(", overrun");
				return;
			}
			nword = ntohs(*(u_int16_t *) cp);
			nskip = ntohs(*(u_int16_t *)(cp + sizeof(u_int16_t)));
			cp += sizeof(u_int16_t) * 2;
			if (cp + sizeof(u_int32_t) * nword > end ||
			    qoff + sizeof(u_int32_t) * CHAR_BIT * (nword + nskip) > MAXNIQTYPEBMP) {
				printf(", invalid(overrun)");
				return;
			}
		}
		else{
			nword = (end - cp) / sizeof(u_int32_t);
			nskip = 0;
		}
		for (i = 0; i < nword; i++){
			u_int32_t v = *(u_int32_t *)(cp + i * sizeof(u_int32_t));
			b = pr_bitrange(ntohl(v), qoff, b);
			qoff += CHAR_BIT * sizeof(u_int32_t);
		}
		b = pr_bitrange(0, qoff, b);
		cp += sizeof(u_int32_t) * nword;
		qoff += CHAR_BIT * sizeof(u_int32_t) * (nskip + nword);
	}
	if (compressed && nskip) {
		printf(", invalid(last nSkip != 0)");
		return;
	}
}

static void pr_fqdn(struct icmp6_nodeinfo *ni, int nilen)
{
	u_char *cp = (u_char *)ni, *end = cp + nilen;
	int oldfqdn = 0;
	int i;
	cp += ICMP6_NILEN + sizeof(int32_t);	/* int32_t: TTL */
	if (*((u_char*)ni + ICMP6_NILEN + sizeof(int32_t)) == nilen - (ICMP6_NILEN + sizeof(int32_t)) - 1)	/* int32_t: TTL */
		oldfqdn = 1;
	else
		oldfqdn = 0;
	if (oldfqdn) {
		cp++;
		while (cp < end) {
			putchar(*cp & 0xff);
			cp++;
		}
	} else {
		u_char *nextcp = NULL; /* for DNS compression*/
		int giveup = 0;
		while (cp < end) {
			i = *cp++;
			if (i) {
			    switch(i & 0xc0){
			    case 0x00:
				if (i > end - cp) {
					printf("???");
					break;
				}
				while (i-- && cp < end) {
					putchar(*cp & 0xff);
					cp++;
				}
				if (cp + 1 < end && *cp)
					printf(".");
				break;
			    case 0xc0: /* DNS compression */
				if (cp > end){
					printf("???(dns compression truncated)");
					giveup++;
					break;
				}
				else{
					int coff = ((i & 0x3f) << 8) | (((int)*cp) & 0xff);
					cp++;
					if (coff < sizeof(int32_t) || coff > end - ((u_char *)ni + ICMP6_NILEN)){
						printf("???(invalid dns compression; offset is invalid): %d", coff);
						giveup++;
						break;
					}
					else{
						if (nextcp == cp){
							printf("???(invalid dns compression; recursive)");
							giveup++;
							break;
						}
						if (!nextcp)
							nextcp = cp;
						cp = (u_char *)ni + ICMP6_NILEN + coff;
					}
				}
				break;
			    default:
				printf("???(invalid dns wire format): %x", i & 0xff);
				giveup++;
				break;
			    }
			    if (giveup)
				break;
			} else {
				/* end of name */
				int nofqdn = 0;
				if (cp < end && *cp == '\0'){
					cp++;
					nofqdn++;
				}
				if (!nofqdn)
					printf(".");	/* FQDN */
				if (nextcp){
					cp = nextcp;
					nextcp = NULL;
				}
				if (cp != end){
					printf(",");	/* we have next */
					continue;
				}
				break;
			}
		}
	}
	if (options & F_VERBOSE) {
		int32_t ttl;
		int comma = 0;

		printf(" (");	/*)*/
		switch(ni->ni_code) {
		case ICMP6_NI_REFUSED:
			printf("refused");
			comma++;
			break;
		case ICMP6_NI_UNKNOWN:
			printf("unknwon qtype");
			comma++;
			break;
		}

		if ((end - (u_char *)ni) < ICMP6_NILEN + sizeof(ttl)) {
			/* case of refusion, unknown */
			/*(*/
			putchar(')');
			goto fqdnend;
		}
		ttl = (int32_t)ntohl(*(u_long *)((u_char*)ni + ICMP6_NILEN));
		if (comma)
			printf(",");
		if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL))
			printf("TTL=%d:meaningless",
				     (int)ttl);
		else {
			if (ttl < 0) {
				printf("TTL=%d:invalid",
				    ttl);
			} else
				printf("TTL=%d", ttl);
		}
		comma++;

		if (oldfqdn) {
			if (comma)
				printf(",");
			printf("03 draft");
			comma++;
		} else {
			cp = (u_char *)ni + ICMP6_NILEN + sizeof(int32_t);	/* TTL */
			if (cp == end) {
				if (comma)
					printf(",");
				printf("no name");
				comma++;
			}
		}

		if (*((u_char *)ni + ICMP6_NILEN + sizeof(ttl)) != 
		    nilen - (ICMP6_NILEN + sizeof(int32_t)) - 1 && oldfqdn) {
			if (comma)
				printf(",");
			printf("invalid namelen:%d/%lu",
				     *((u_char *)ni + ICMP6_NILEN + sizeof(ttl)),
				     (u_long)(nilen - sizeof(int32_t) -1));
			comma++;
		}
		/*(*/
		putchar(')');
	}
 fqdnend:
	;
}

static void pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen)
{
	u_char *cp = (u_char *)ni + ICMP6_NILEN;
	char ntop_buf[INET6_ADDRSTRLEN];

	nilen -= ICMP6_NILEN;

	if (options & F_VERBOSE) {
		switch(ni->ni_code) {
		 case ICMP6_NI_REFUSED:
			 printf("refused");
			 break;
		 case ICMP6_NI_UNKNOWN:
			 printf("unknown qtype");
			 break;
		}
		if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE)
			printf(" truncated");
	}
	putchar('\n');
	if (nilen <= 0){
		printf("  no address\n");
		return;
	}
	if (nilen % (sizeof(int32_t) + sizeof(struct in6_addr))){
		printf("  invalid length(%u)\n", nilen);
		return;
	}
	while(nilen > 0){
		int ttl = ntohl(*(int32_t*)cp);
		if (!inet_ntop(AF_INET6, cp + sizeof(int32_t), ntop_buf, sizeof(ntop_buf)))
			strncpy(ntop_buf, "?", sizeof(ntop_buf));
		printf("  %s(TTL=%d", ntop_buf, ttl);
		if (ttl < 0)
			printf(":invalid");
		/*(*/
		printf(")\n");
		nilen -= sizeof(int32_t) + sizeof(struct in6_addr);
		cp += sizeof(int32_t) + sizeof(struct in6_addr);
	}
}

static void pr_ipv4addr(struct icmp6_nodeinfo *ni, int nilen)
{
	u_char *cp = (u_char *)ni + ICMP6_NILEN;
	char ntop_buf[INET_ADDRSTRLEN];
	nilen -= ICMP6_NILEN;
	if (options & F_VERBOSE) {
		switch(ni->ni_code) {
		case ICMP6_NI_REFUSED:
			printf("refused");
			break;
		case ICMP6_NI_UNKNOWN:
			printf("unknown qtype");
			break;
		}
		if (ni->ni_flags & NI_IPV4ADDR_FLAG_TRUNCATE)
			printf(" truncated");   
	}
	putchar('\n');
	if (nilen <= 0){
		printf("  no address\n");
		return;
	}
	if (nilen % (sizeof(int32_t) + sizeof(struct in_addr))){
		printf("  invalid length(%u)\n", nilen);
		return;
	}
	while(nilen > 0){
		int ttl = ntohl(*(int32_t*)cp);
		if (!inet_ntop(AF_INET, cp + sizeof(int32_t), ntop_buf, sizeof(ntop_buf)))
			strncpy(ntop_buf, "?", sizeof(ntop_buf));
		printf("  %s(TTL=%d", ntop_buf, ttl);
		if (ttl < 0)
			printf(":invalid");
		/*(*/
		printf(")\n");
		nilen -= sizeof(int32_t) + sizeof(struct in_addr);
		cp += sizeof(int32_t) + sizeof(struct in_addr);
	}
}

int get_hoplim(struct msghdr *mhdr){
	struct cmsghdr *cm;
	for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
	     cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
		if (cm->cmsg_level == SOL_IPV6 &&
#ifdef USE_RFC2292
		    cm->cmsg_type == IPV6_2292HOPLIMIT &&
#else
		    cm->cmsg_type == IPV6_HOPLIMIT &&
#endif
		    cm->cmsg_len == CMSG_LEN(sizeof(int)))
			return(*(int *)CMSG_DATA(cm));
	}
	return(-1);
}

/*
 * pr_iph --
 *      Print an IP6 header.
 */
void pr_iph(struct ip6_hdr *ip6){
	u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
	u_int8_t tc;
	char ntop_buf[INET6_ADDRSTRLEN];

	tc = *(&ip6->ip6_vfc + 1); /* XXX */
	tc = (tc >> 4) & 0x0f;
	tc |= (ip6->ip6_vfc << 4);

	printf("Vr TC  Flow Plen Nxt Hlim\n");
	printf(" %1x %02x %05x %04x  %02x   %02x\n",
	       (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (int)ntohl(flow),
	       ntohs(ip6->ip6_plen),
	       ip6->ip6_nxt, ip6->ip6_hlim);
	if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf)))
		strncpy(ntop_buf, "?", sizeof(ntop_buf));
	printf("%s->", ntop_buf);
	if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf)))
		strncpy(ntop_buf, "?", sizeof(ntop_buf));
	printf("%s\n", ntop_buf);
}

/*
 * pr_addr --
 *	Return an ascii host address as a dotted quad and optionally with
 * a hostname.
 */
static const char * pr_addr(struct sockaddr_in6 *addr, socklen_t addrlen)
{
	static char buf[NI_MAXHOST];
	int flag = (options & F_NUMERIC) ? NI_NUMERICHOST : 0;
#ifdef NI_WITHSCOPEID
	flag |= NI_WITHSCOPEID;
#endif
	if (getnameinfo((struct sockaddr*)addr, addrlen,
			buf, sizeof(buf), NULL, 0,
			flag))
		strcpy(buf, "???");
	return buf;
}

/*
 * pr_retip --
 *      Dump some info on a returned (via ICMPv6) IPv6 packet.
 */
void pr_retip(struct ip6_hdr *ip6, u_char *end){
	u_char *cp = (u_char *)ip6, nh;
	int hlen;

	if (end - (u_char *)ip6 < sizeof(*ip6)) {
		printf("IP6");
		goto trunc;
	}
	pr_iph(ip6);
	hlen = sizeof(*ip6);

	nh = ip6->ip6_nxt;
	cp += hlen;
	while (end - cp >= 8) {
		switch (nh) {
		case IPPROTO_HOPOPTS:
			printf("HBH ");
			hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3;
			nh = ((struct ip6_hbh *)cp)->ip6h_nxt;
			break;
		case IPPROTO_DSTOPTS:
			printf("DSTOPT ");
			hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3;
			nh = ((struct ip6_dest *)cp)->ip6d_nxt;
			break;
		case IPPROTO_FRAGMENT:
			printf("FRAG ");
			hlen = sizeof(struct ip6_frag);
			nh = ((struct ip6_frag *)cp)->ip6f_nxt;
			break;
		case IPPROTO_ROUTING:
			printf("RTHDR ");
			hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3;
			nh = ((struct ip6_rthdr *)cp)->ip6r_nxt;
			break;
#ifdef IPSEC
		case IPPROTO_AH:
			printf("AH ");
			hlen = (((struct ah *)cp)->ah_len+2) << 2;
			nh = ((struct ah *)cp)->ah_nxt;
			break;
#endif
		case IPPROTO_ICMPV6:
			printf("ICMP6: type = %d, code = %d\n", *cp, *(cp + 1));
			return;
		case IPPROTO_ESP:
			printf("ESP\n");
			return;
		case IPPROTO_TCP:
			printf("TCP: from port %u, to port %u (decimal)\n",
			       (*cp * 256 + *(cp + 1)),
			       (*(cp + 2) * 256 + *(cp + 3)));
			return;
		case IPPROTO_UDP:
			printf("UDP: from port %u, to port %u (decimal)\n",
			       (*cp * 256 + *(cp + 1)),
			       (*(cp + 2) * 256 + *(cp + 3)));
			return;
		default:
			printf("Unknown Header(%d)\n", nh);
			return;
		}
		
		if ((cp += hlen) >= end)
			goto trunc;
	}
	if (end - cp < 8)
		goto trunc;
	
	putchar('\n');
	return;
	
 trunc:
	printf("...\n");
	return;
}


void fill(char *patp)
{
	int ii, jj, kk;
	int pat[16];
	char *cp;
	char *bp = outpack+8;

	for (cp = patp; *cp; cp++)
		if (!isxdigit(*cp))
			errx(2, "patterns must be specified as hex digits.");
	ii = sscanf(patp,
		    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
		    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
		    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
		    &pat[13], &pat[14], &pat[15]);

	if (ii > 0) {
		for (kk = 0; 
		     kk <= MAXPACKET - (8 + sizeof(struct timeval) + ii); 
		     kk += ii)
			for (jj = 0; jj < ii; ++jj)
				bp[jj + kk] = pat[jj];
	}
	if (!(options & F_QUIET)) {
		printf("PATTERN: 0x");
		for (jj = 0; jj < ii; ++jj)
			printf("%02x", bp[jj] & 0xFF);
		printf("\n");
	}
}

#ifdef IPSEC
#ifdef IPSEC_POLICY_IPSEC
static int setpolicy(int so, char *policy)
{
	char *buf;
	if (!policy)
		return 0;	/* ignore */
	if (!(buf = ipsec_set_policy(policy, strlen(policy))))
		return -1;
	if (setsockopt(so, IPPROTO_IPV6, IPV6_IPSEC_POLICY,
			buf, ipsec_get_policylen(buf)) < 0)
		warnx("Unable to set IPsec policy");
	free(buf);
	return 0;
}
#endif
#endif

static char *nigroup(char *name)
{
	char *p;
	MD5_CTX ctxt;
	u_int8_t digest[16];
	char hbuf[NI_MAXHOST];
	struct in6_addr in6;
	int len;

	for (p = name, len = 0; p && *p && *p != '.'; p++)
		hbuf[1 + len++] = isupper(*p) ? tolower(*p) : *p;
	if (len >= 0x40)
		return NULL;	/*label too long*/
	hbuf[0] = (char)len;

	/* generate 8 bytes of pseudo-random value. */
	bzero(&ctxt, sizeof(ctxt));
	MD5Init(&ctxt);
	MD5Update(&ctxt, hbuf, 1 + len);
	MD5Final(digest, &ctxt);

	bzero(&in6, sizeof(in6));
	in6.s6_addr[0] = 0xff;
	in6.s6_addr[1] = 0x02;
	in6.s6_addr[11] = 0x02;
	bcopy(digest, &in6.s6_addr[12], 4);

	if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL)
		return NULL;

	return strdup(hbuf);
}

void usage(void)
{
	int i;
	fprintf(stderr, "Usage: ping6 [-");
	for (i=0; (optionlist[i].shortopt||optionlist[i].longopt); i++){
		if (!optionlist[i].arg && optionlist[i].help)
			fprintf(stderr, "%c", optionlist[i].shortopt);
	}
	fprintf(stderr,"]");
	for (i=0; (optionlist[i].shortopt||optionlist[i].longopt); i++){
        	if (optionlist[i].arg && optionlist[i].help)
        		fprintf(stderr, " [-%c %s]", optionlist[i].shortopt, optionlist[i].arg);
        }
	fprintf(stderr, "\n");
	exit(1);
}
void usage_long(void)
{
	int i, j;
	int len, maxlen = 0;

	for (i=0; (optionlist[i].shortopt||optionlist[i].longopt); i++){
		if (!optionlist[i].help)
			continue;
		len = 3;
#ifdef HAVE_GETOPT_LONG
		len += optionlist[i].longopt ? (2 + strlen(optionlist[i].longopt)) : 0;
#endif
		len += optionlist[i].arg ? (1 + strlen(optionlist[i].arg)) : 0;
		optionlist[i].len = len;
		if (len > maxlen)
			maxlen = len;
	}

	fprintf(stderr, 
		"Usage: ping6 [options...] [hops...] host\n\n"
		"options:\n"
		);
	for (i=0; (optionlist[i].shortopt||optionlist[i].longopt); i++){
		if (!optionlist[i].help)
 			continue;
		fprintf(stderr, "\t");
		if (!optionlist[i].shortopt)
			fprintf(stderr, "  ");
		else
			fprintf(stderr, "-%c", optionlist[i].shortopt);
#ifdef HAVE_GETOPT_LONG
		if (optionlist[i].longopt)
			fprintf(stderr, "%s--%s",
				(optionlist[i].shortopt ? "|" : ""),
				optionlist[i].longopt);
#endif
		if (optionlist[i].arg)
			fprintf(stderr, " %s",
				optionlist[i].arg);
		for(j=0; j < maxlen - optionlist[i].len; j++)
			fputc(' ', stderr);
		fprintf(stderr, "  %s\n", optionlist[i].help ? optionlist[i].help : "");
	}
	exit(1);
}
