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