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