]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sbin/ping6/ping6.c
MFC r270433:
[FreeBSD/stable/9.git] / sbin / ping6 / ping6.c
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
67 static 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
74 static 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$");
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
140 struct 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)
193 u_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)
207 int mx_dup_ck = MAX_DUP_CHK;
208 char rcvd_tbl[MAX_DUP_CHK / 8];
209
210 struct addrinfo *res = NULL;
211 struct sockaddr_in6 dst;        /* who to ping6 */
212 struct sockaddr_in6 src;        /* src addr of this packet */
213 socklen_t srclen;
214 int datalen = DEFDATALEN;
215 int s;                          /* socket file descriptor */
216 u_char outpack[MAXPACKETLEN];
217 char BSPACE = '\b';             /* characters written for flood */
218 char BBELL = '\a';              /* characters written for AUDIBLE */
219 char DOT = '.';
220 char *hostname;
221 int ident;                      /* process id to identify our packets */
222 u_int8_t nonce[8];              /* nonce field for node information */
223 int hoplimit = -1;              /* hoplimit */
224 int pathmtu = 0;                /* path MTU for the destination.  0 = unspec. */
225 u_char *packet = NULL;
226 #ifdef HAVE_POLL_H
227 struct pollfd fdmaskp[1];
228 #else
229 fd_set *fdmaskp = NULL;
230 int fdmasks;
231 #endif
232
233 /* counters */
234 long nmissedmax;                /* max value of ntransmitted - nreceived - 1 */
235 long npackets;                  /* max packets to transmit */
236 long nreceived;                 /* # of packets we got back */
237 long nrepeats;                  /* number of duplicates */
238 long ntransmitted;              /* sequence # for outbound packets = #sent */
239 struct timeval interval = {1, 0}; /* interval between packets */
240
241 /* timing */
242 int timing;                     /* flag to do timing */
243 double tmin = 999999999.0;      /* minimum round trip time */
244 double tmax = 0.0;              /* maximum round trip time */
245 double tsum = 0.0;              /* sum of all times, for doing average */
246 double tsumsq = 0.0;            /* sum of all times squared, for std. dev. */
247
248 /* for node addresses */
249 u_short naflags;
250
251 /* for ancillary data(advanced API) */
252 struct msghdr smsghdr;
253 struct iovec smsgiov;
254 char *scmsg = 0;
255
256 volatile sig_atomic_t seenalrm;
257 volatile sig_atomic_t seenint;
258 #ifdef SIGINFO
259 volatile sig_atomic_t seeninfo;
260 #endif
261
262 int      main(int, char *[]);
263 void     fill(char *, char *);
264 int      get_hoplim(struct msghdr *);
265 int      get_pathmtu(struct msghdr *);
266 struct in6_pktinfo *get_rcvpktinfo(struct msghdr *);
267 void     onsignal(int);
268 void     retransmit(void);
269 void     onint(int);
270 size_t   pingerlen(void);
271 int      pinger(void);
272 const char *pr_addr(struct sockaddr *, int);
273 void     pr_icmph(struct icmp6_hdr *, u_char *);
274 void     pr_iph(struct ip6_hdr *);
275 void     pr_suptypes(struct icmp6_nodeinfo *, size_t);
276 void     pr_nodeaddr(struct icmp6_nodeinfo *, int);
277 int      myechoreply(const struct icmp6_hdr *);
278 int      mynireply(const struct icmp6_nodeinfo *);
279 char *dnsdecode(const u_char **, const u_char *, const u_char *,
280         char *, size_t);
281 void     pr_pack(u_char *, int, struct msghdr *);
282 void     pr_exthdrs(struct msghdr *);
283 void     pr_ip6opt(void *, size_t);
284 void     pr_rthdr(void *, size_t);
285 int      pr_bitrange(u_int32_t, int, int);
286 void     pr_retip(struct ip6_hdr *, u_char *);
287 void     summary(void);
288 void     tvsub(struct timeval *, struct timeval *);
289 int      setpolicy(int, char *);
290 char    *nigroup(char *, int);
291 void     usage(void);
292
293 int
294 main(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         seteuid(getuid());
708         setuid(getuid());
709
710         if ((options & F_FLOOD) && (options & F_INTERVAL))
711                 errx(1, "-f and -i incompatible options");
712
713         if ((options & F_NOUSERDATA) == 0) {
714                 if (datalen >= sizeof(struct tv32)) {
715                         /* we can time transfer */
716                         timing = 1;
717                 } else
718                         timing = 0;
719                 /* in F_VERBOSE case, we may get non-echoreply packets*/
720                 if (options & F_VERBOSE)
721                         packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
722                 else
723                         packlen = datalen + IP6LEN + ICMP6ECHOLEN + EXTRA;
724         } else {
725                 /* suppress timing for node information query */
726                 timing = 0;
727                 datalen = 2048;
728                 packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
729         }
730
731         if (!(packet = (u_char *)malloc((u_int)packlen)))
732                 err(1, "Unable to allocate packet");
733         if (!(options & F_PINGFILLED))
734                 for (i = ICMP6ECHOLEN; i < packlen; ++i)
735                         *datap++ = i;
736
737         ident = getpid() & 0xFFFF;
738 #ifndef HAVE_ARC4RANDOM
739         gettimeofday(&seed, NULL);
740         srand((unsigned int)(seed.tv_sec ^ seed.tv_usec ^ (long)ident));
741         memset(nonce, 0, sizeof(nonce));
742         for (i = 0; i < sizeof(nonce); i += sizeof(int))
743                 *((int *)&nonce[i]) = rand();
744 #else
745         memset(nonce, 0, sizeof(nonce));
746         for (i = 0; i < sizeof(nonce); i += sizeof(u_int32_t))
747                 *((u_int32_t *)&nonce[i]) = arc4random();
748 #endif
749         optval = 1;
750         if (options & F_DONTFRAG)
751                 if (setsockopt(s, IPPROTO_IPV6, IPV6_DONTFRAG,
752                     &optval, sizeof(optval)) == -1)
753                         err(1, "IPV6_DONTFRAG");
754         hold = 1;
755
756         if (options & F_SO_DEBUG)
757                 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
758                     sizeof(hold));
759         optval = IPV6_DEFHLIM;
760         if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
761                 if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
762                     &optval, sizeof(optval)) == -1)
763                         err(1, "IPV6_MULTICAST_HOPS");
764 #ifdef IPV6_USE_MIN_MTU
765         if (mflag != 1) {
766                 optval = mflag > 1 ? 0 : 1;
767
768                 if (setsockopt(s, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
769                     &optval, sizeof(optval)) == -1)
770                         err(1, "setsockopt(IPV6_USE_MIN_MTU)");
771         }
772 #ifdef IPV6_RECVPATHMTU
773         else {
774                 optval = 1;
775                 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPATHMTU,
776                     &optval, sizeof(optval)) == -1)
777                         err(1, "setsockopt(IPV6_RECVPATHMTU)");
778         }
779 #endif /* IPV6_RECVPATHMTU */
780 #endif /* IPV6_USE_MIN_MTU */
781
782 #ifdef IPSEC
783 #ifdef IPSEC_POLICY_IPSEC
784         if (options & F_POLICY) {
785                 if (setpolicy(s, policy_in) < 0)
786                         errx(1, "%s", ipsec_strerror());
787                 if (setpolicy(s, policy_out) < 0)
788                         errx(1, "%s", ipsec_strerror());
789         }
790 #else
791         if (options & F_AUTHHDR) {
792                 optval = IPSEC_LEVEL_REQUIRE;
793 #ifdef IPV6_AUTH_TRANS_LEVEL
794                 if (setsockopt(s, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL,
795                     &optval, sizeof(optval)) == -1)
796                         err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)");
797 #else /* old def */
798                 if (setsockopt(s, IPPROTO_IPV6, IPV6_AUTH_LEVEL,
799                     &optval, sizeof(optval)) == -1)
800                         err(1, "setsockopt(IPV6_AUTH_LEVEL)");
801 #endif
802         }
803         if (options & F_ENCRYPT) {
804                 optval = IPSEC_LEVEL_REQUIRE;
805                 if (setsockopt(s, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL,
806                     &optval, sizeof(optval)) == -1)
807                         err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)");
808         }
809 #endif /*IPSEC_POLICY_IPSEC*/
810 #endif
811
812 #ifdef ICMP6_FILTER
813     {
814         struct icmp6_filter filt;
815         if (!(options & F_VERBOSE)) {
816                 ICMP6_FILTER_SETBLOCKALL(&filt);
817                 if ((options & F_FQDN) || (options & F_FQDNOLD) ||
818                     (options & F_NODEADDR) || (options & F_SUPTYPES))
819                         ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filt);
820                 else
821                         ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
822         } else {
823                 ICMP6_FILTER_SETPASSALL(&filt);
824         }
825         if (setsockopt(s, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
826             sizeof(filt)) < 0)
827                 err(1, "setsockopt(ICMP6_FILTER)");
828     }
829 #endif /*ICMP6_FILTER*/
830
831         /* let the kerel pass extension headers of incoming packets */
832         if ((options & F_VERBOSE) != 0) {
833                 int opton = 1;
834
835 #ifdef IPV6_RECVRTHDR
836                 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVRTHDR, &opton,
837                     sizeof(opton)))
838                         err(1, "setsockopt(IPV6_RECVRTHDR)");
839 #else  /* old adv. API */
840                 if (setsockopt(s, IPPROTO_IPV6, IPV6_RTHDR, &opton,
841                     sizeof(opton)))
842                         err(1, "setsockopt(IPV6_RTHDR)");
843 #endif
844         }
845
846 /*
847         optval = 1;
848         if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
849                 if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
850                     &optval, sizeof(optval)) == -1)
851                         err(1, "IPV6_MULTICAST_LOOP");
852 */
853
854         /* Specify the outgoing interface and/or the source address */
855         if (usepktinfo)
856                 ip6optlen += CMSG_SPACE(sizeof(struct in6_pktinfo));
857
858         if (hoplimit != -1)
859                 ip6optlen += CMSG_SPACE(sizeof(int));
860
861         /* set IP6 packet options */
862         if (ip6optlen) {
863                 if ((scmsg = (char *)malloc(ip6optlen)) == 0)
864                         errx(1, "can't allocate enough memory");
865                 smsghdr.msg_control = (caddr_t)scmsg;
866                 smsghdr.msg_controllen = ip6optlen;
867                 scmsgp = (struct cmsghdr *)scmsg;
868         }
869         if (usepktinfo) {
870                 pktinfo = (struct in6_pktinfo *)(CMSG_DATA(scmsgp));
871                 memset(pktinfo, 0, sizeof(*pktinfo));
872                 scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
873                 scmsgp->cmsg_level = IPPROTO_IPV6;
874                 scmsgp->cmsg_type = IPV6_PKTINFO;
875                 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
876         }
877
878         /* set the outgoing interface */
879         if (ifname) {
880 #ifndef USE_SIN6_SCOPE_ID
881                 /* pktinfo must have already been allocated */
882                 if ((pktinfo->ipi6_ifindex = if_nametoindex(ifname)) == 0)
883                         errx(1, "%s: invalid interface name", ifname);
884 #else
885                 if ((dst.sin6_scope_id = if_nametoindex(ifname)) == 0)
886                         errx(1, "%s: invalid interface name", ifname);
887 #endif
888         }
889         if (hoplimit != -1) {
890                 scmsgp->cmsg_len = CMSG_LEN(sizeof(int));
891                 scmsgp->cmsg_level = IPPROTO_IPV6;
892                 scmsgp->cmsg_type = IPV6_HOPLIMIT;
893                 *(int *)(CMSG_DATA(scmsgp)) = hoplimit;
894
895                 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
896         }
897
898         if (argc > 1) { /* some intermediate addrs are specified */
899                 int hops, error;
900 #ifdef USE_RFC2292BIS
901                 int rthdrlen;
902 #endif
903
904 #ifdef USE_RFC2292BIS
905                 rthdrlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1);
906                 scmsgp->cmsg_len = CMSG_LEN(rthdrlen);
907                 scmsgp->cmsg_level = IPPROTO_IPV6;
908                 scmsgp->cmsg_type = IPV6_RTHDR;
909                 rthdr = (struct ip6_rthdr *)CMSG_DATA(scmsgp);
910                 rthdr = inet6_rth_init((void *)rthdr, rthdrlen,
911                     IPV6_RTHDR_TYPE_0, argc - 1);
912                 if (rthdr == NULL)
913                         errx(1, "can't initialize rthdr");
914 #else  /* old advanced API */
915                 if ((scmsgp = (struct cmsghdr *)inet6_rthdr_init(scmsgp,
916                     IPV6_RTHDR_TYPE_0)) == 0)
917                         errx(1, "can't initialize rthdr");
918 #endif /* USE_RFC2292BIS */
919
920                 for (hops = 0; hops < argc - 1; hops++) {
921                         struct addrinfo *iaip;
922
923                         if ((error = getaddrinfo(argv[hops], NULL, &hints,
924                             &iaip)))
925                                 errx(1, "%s", gai_strerror(error));
926                         if (SIN6(iaip->ai_addr)->sin6_family != AF_INET6)
927                                 errx(1,
928                                     "bad addr family of an intermediate addr");
929
930 #ifdef USE_RFC2292BIS
931                         if (inet6_rth_add(rthdr,
932                             &(SIN6(iaip->ai_addr))->sin6_addr))
933                                 errx(1, "can't add an intermediate node");
934 #else  /* old advanced API */
935                         if (inet6_rthdr_add(scmsgp,
936                             &(SIN6(iaip->ai_addr))->sin6_addr,
937                             IPV6_RTHDR_LOOSE))
938                                 errx(1, "can't add an intermediate node");
939 #endif /* USE_RFC2292BIS */
940                         freeaddrinfo(iaip);
941                 }
942
943 #ifndef USE_RFC2292BIS
944                 if (inet6_rthdr_lasthop(scmsgp, IPV6_RTHDR_LOOSE))
945                         errx(1, "can't set the last flag");
946 #endif
947
948                 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
949         }
950
951         if (!(options & F_SRCADDR)) {
952                 /*
953                  * get the source address. XXX since we revoked the root
954                  * privilege, we cannot use a raw socket for this.
955                  */
956                 int dummy;
957                 socklen_t len = sizeof(src);
958
959                 if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
960                         err(1, "UDP socket");
961
962                 src.sin6_family = AF_INET6;
963                 src.sin6_addr = dst.sin6_addr;
964                 src.sin6_port = ntohs(DUMMY_PORT);
965                 src.sin6_scope_id = dst.sin6_scope_id;
966
967 #ifdef USE_RFC2292BIS
968                 if (pktinfo &&
969                     setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTINFO,
970                     (void *)pktinfo, sizeof(*pktinfo)))
971                         err(1, "UDP setsockopt(IPV6_PKTINFO)");
972
973                 if (hoplimit != -1 &&
974                     setsockopt(dummy, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
975                     (void *)&hoplimit, sizeof(hoplimit)))
976                         err(1, "UDP setsockopt(IPV6_UNICAST_HOPS)");
977
978                 if (hoplimit != -1 &&
979                     setsockopt(dummy, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
980                     (void *)&hoplimit, sizeof(hoplimit)))
981                         err(1, "UDP setsockopt(IPV6_MULTICAST_HOPS)");
982
983                 if (rthdr &&
984                     setsockopt(dummy, IPPROTO_IPV6, IPV6_RTHDR,
985                     (void *)rthdr, (rthdr->ip6r_len + 1) << 3))
986                         err(1, "UDP setsockopt(IPV6_RTHDR)");
987 #else  /* old advanced API */
988                 if (smsghdr.msg_control &&
989                     setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTOPTIONS,
990                     (void *)smsghdr.msg_control, smsghdr.msg_controllen))
991                         err(1, "UDP setsockopt(IPV6_PKTOPTIONS)");
992 #endif
993
994                 if (connect(dummy, (struct sockaddr *)&src, len) < 0)
995                         err(1, "UDP connect");
996
997                 if (getsockname(dummy, (struct sockaddr *)&src, &len) < 0)
998                         err(1, "getsockname");
999
1000                 close(dummy);
1001         }
1002
1003 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
1004         if (sockbufsize) {
1005                 if (datalen > sockbufsize)
1006                         warnx("you need -b to increase socket buffer size");
1007                 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sockbufsize,
1008                     sizeof(sockbufsize)) < 0)
1009                         err(1, "setsockopt(SO_SNDBUF)");
1010                 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &sockbufsize,
1011                     sizeof(sockbufsize)) < 0)
1012                         err(1, "setsockopt(SO_RCVBUF)");
1013         }
1014         else {
1015                 if (datalen > 8 * 1024) /*XXX*/
1016                         warnx("you need -b to increase socket buffer size");
1017                 /*
1018                  * When pinging the broadcast address, you can get a lot of
1019                  * answers. Doing something so evil is useful if you are trying
1020                  * to stress the ethernet, or just want to fill the arp cache
1021                  * to get some stuff for /etc/ethers.
1022                  */
1023                 hold = 48 * 1024;
1024                 setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
1025                     sizeof(hold));
1026         }
1027 #endif
1028
1029         optval = 1;
1030 #ifndef USE_SIN6_SCOPE_ID
1031 #ifdef IPV6_RECVPKTINFO
1032         if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO, &optval,
1033             sizeof(optval)) < 0)
1034                 warn("setsockopt(IPV6_RECVPKTINFO)"); /* XXX err? */
1035 #else  /* old adv. API */
1036         if (setsockopt(s, IPPROTO_IPV6, IPV6_PKTINFO, &optval,
1037             sizeof(optval)) < 0)
1038                 warn("setsockopt(IPV6_PKTINFO)"); /* XXX err? */
1039 #endif
1040 #endif /* USE_SIN6_SCOPE_ID */
1041 #ifdef IPV6_RECVHOPLIMIT
1042         if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &optval,
1043             sizeof(optval)) < 0)
1044                 warn("setsockopt(IPV6_RECVHOPLIMIT)"); /* XXX err? */
1045 #else  /* old adv. API */
1046         if (setsockopt(s, IPPROTO_IPV6, IPV6_HOPLIMIT, &optval,
1047             sizeof(optval)) < 0)
1048                 warn("setsockopt(IPV6_HOPLIMIT)"); /* XXX err? */
1049 #endif
1050
1051         printf("PING6(%lu=40+8+%lu bytes) ", (unsigned long)(40 + pingerlen()),
1052             (unsigned long)(pingerlen() - 8));
1053         printf("%s --> ", pr_addr((struct sockaddr *)&src, sizeof(src)));
1054         printf("%s\n", pr_addr((struct sockaddr *)&dst, sizeof(dst)));
1055
1056         while (preload--)               /* Fire off them quickies. */
1057                 (void)pinger();
1058
1059         (void)signal(SIGINT, onsignal);
1060 #ifdef SIGINFO
1061         (void)signal(SIGINFO, onsignal);
1062 #endif
1063
1064         if ((options & F_FLOOD) == 0) {
1065                 (void)signal(SIGALRM, onsignal);
1066                 itimer.it_interval = interval;
1067                 itimer.it_value = interval;
1068                 (void)setitimer(ITIMER_REAL, &itimer, NULL);
1069                 if (ntransmitted == 0)
1070                         retransmit();
1071         }
1072
1073 #ifndef HAVE_POLL_H
1074         fdmasks = howmany(s + 1, NFDBITS) * sizeof(fd_mask);
1075         if ((fdmaskp = malloc(fdmasks)) == NULL)
1076                 err(1, "malloc");
1077 #endif
1078
1079         seenalrm = seenint = 0;
1080 #ifdef SIGINFO
1081         seeninfo = 0;
1082 #endif
1083
1084         for (;;) {
1085                 struct msghdr m;
1086                 struct iovec iov[2];
1087
1088                 /* signal handling */
1089                 if (seenalrm) {
1090                         /* last packet sent, timeout reached? */
1091                         if (npackets && ntransmitted >= npackets) {
1092                                 struct timeval zerotime = {0, 0};
1093                                 itimer.it_value = zerotime;
1094                                 itimer.it_interval = zerotime;
1095                                 (void)setitimer(ITIMER_REAL, &itimer, NULL);
1096                                 seenalrm = 0;   /* clear flag */
1097                                 continue;
1098                         }
1099                         retransmit();
1100                         seenalrm = 0;
1101                         continue;
1102                 }
1103                 if (seenint) {
1104                         onint(SIGINT);
1105                         seenint = 0;
1106                         continue;
1107                 }
1108 #ifdef SIGINFO
1109                 if (seeninfo) {
1110                         summary();
1111                         seeninfo = 0;
1112                         continue;
1113                 }
1114 #endif
1115
1116                 if (options & F_FLOOD) {
1117                         (void)pinger();
1118 #ifdef HAVE_POLL_H
1119                         timeout = 10;
1120 #else
1121                         timeout.tv_sec = 0;
1122                         timeout.tv_usec = 10000;
1123                         tv = &timeout;
1124 #endif
1125                 } else {
1126 #ifdef HAVE_POLL_H
1127                         timeout = INFTIM;
1128 #else
1129                         tv = NULL;
1130 #endif
1131                 }
1132 #ifdef HAVE_POLL_H
1133                 fdmaskp[0].fd = s;
1134                 fdmaskp[0].events = POLLIN;
1135                 cc = poll(fdmaskp, 1, timeout);
1136 #else
1137                 memset(fdmaskp, 0, fdmasks);
1138                 FD_SET(s, fdmaskp);
1139                 cc = select(s + 1, fdmaskp, NULL, NULL, tv);
1140 #endif
1141                 if (cc < 0) {
1142                         if (errno != EINTR) {
1143 #ifdef HAVE_POLL_H
1144                                 warn("poll");
1145 #else
1146                                 warn("select");
1147 #endif
1148                                 sleep(1);
1149                         }
1150                         continue;
1151                 } else if (cc == 0)
1152                         continue;
1153
1154                 m.msg_name = (caddr_t)&from;
1155                 m.msg_namelen = sizeof(from);
1156                 memset(&iov, 0, sizeof(iov));
1157                 iov[0].iov_base = (caddr_t)packet;
1158                 iov[0].iov_len = packlen;
1159                 m.msg_iov = iov;
1160                 m.msg_iovlen = 1;
1161                 memset(cm, 0, CONTROLLEN);
1162                 m.msg_control = (void *)cm;
1163                 m.msg_controllen = CONTROLLEN;
1164
1165                 cc = recvmsg(s, &m, 0);
1166                 if (cc < 0) {
1167                         if (errno != EINTR) {
1168                                 warn("recvmsg");
1169                                 sleep(1);
1170                         }
1171                         continue;
1172                 } else if (cc == 0) {
1173                         int mtu;
1174
1175                         /*
1176                          * receive control messages only. Process the
1177                          * exceptions (currently the only possiblity is
1178                          * a path MTU notification.)
1179                          */
1180                         if ((mtu = get_pathmtu(&m)) > 0) {
1181                                 if ((options & F_VERBOSE) != 0) {
1182                                         printf("new path MTU (%d) is "
1183                                             "notified\n", mtu);
1184                                 }
1185                         }
1186                         continue;
1187                 } else {
1188                         /*
1189                          * an ICMPv6 message (probably an echoreply) arrived.
1190                          */
1191                         pr_pack(packet, cc, &m);
1192                 }
1193                 if (((options & F_ONCE) != 0 && nreceived > 0) ||
1194                     (npackets > 0 && nreceived >= npackets))
1195                         break;
1196                 if (ntransmitted - nreceived - 1 > nmissedmax) {
1197                         nmissedmax = ntransmitted - nreceived - 1;
1198                         if (options & F_MISSED)
1199                                 (void)write(STDOUT_FILENO, &BBELL, 1);
1200                 }
1201         }
1202         summary();
1203
1204         if (res != NULL)
1205                 freeaddrinfo(res);
1206
1207         if(packet != NULL)
1208                 free(packet);
1209
1210 #ifndef HAVE_POLL_H
1211         if(fdmaskp != NULL)
1212                 free(fdmaskp);
1213 #endif
1214
1215         exit(nreceived == 0 ? 2 : 0);
1216 }
1217
1218 void
1219 onsignal(int sig)
1220 {
1221
1222         switch (sig) {
1223         case SIGALRM:
1224                 seenalrm++;
1225                 break;
1226         case SIGINT:
1227                 seenint++;
1228                 break;
1229 #ifdef SIGINFO
1230         case SIGINFO:
1231                 seeninfo++;
1232                 break;
1233 #endif
1234         }
1235 }
1236
1237 /*
1238  * retransmit --
1239  *      This routine transmits another ping6.
1240  */
1241 void
1242 retransmit(void)
1243 {
1244         struct itimerval itimer;
1245
1246         if (pinger() == 0)
1247                 return;
1248
1249         /*
1250          * If we're not transmitting any more packets, change the timer
1251          * to wait two round-trip times if we've received any packets or
1252          * ten seconds if we haven't.
1253          */
1254 #define MAXWAIT         10
1255         if (nreceived) {
1256                 itimer.it_value.tv_sec =  2 * tmax / 1000;
1257                 if (itimer.it_value.tv_sec == 0)
1258                         itimer.it_value.tv_sec = 1;
1259         } else
1260                 itimer.it_value.tv_sec = MAXWAIT;
1261         itimer.it_interval.tv_sec = 0;
1262         itimer.it_interval.tv_usec = 0;
1263         itimer.it_value.tv_usec = 0;
1264
1265         (void)signal(SIGALRM, onsignal);
1266         (void)setitimer(ITIMER_REAL, &itimer, NULL);
1267 }
1268
1269 /*
1270  * pinger --
1271  *      Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
1272  * will be added on by the kernel.  The ID field is our UNIX process ID,
1273  * and the sequence number is an ascending integer.  The first 8 bytes
1274  * of the data portion are used to hold a UNIX "timeval" struct in VAX
1275  * byte-order, to compute the round-trip time.
1276  */
1277 size_t
1278 pingerlen(void)
1279 {
1280         size_t l;
1281
1282         if (options & F_FQDN)
1283                 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1284         else if (options & F_FQDNOLD)
1285                 l = ICMP6_NIQLEN;
1286         else if (options & F_NODEADDR)
1287                 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1288         else if (options & F_SUPTYPES)
1289                 l = ICMP6_NIQLEN;
1290         else
1291                 l = ICMP6ECHOLEN + datalen;
1292
1293         return l;
1294 }
1295
1296 int
1297 pinger(void)
1298 {
1299         struct icmp6_hdr *icp;
1300         struct iovec iov[2];
1301         int i, cc;
1302         struct icmp6_nodeinfo *nip;
1303         int seq;
1304
1305         if (npackets && ntransmitted >= npackets)
1306                 return(-1);     /* no more transmission */
1307
1308         icp = (struct icmp6_hdr *)outpack;
1309         nip = (struct icmp6_nodeinfo *)outpack;
1310         memset(icp, 0, sizeof(*icp));
1311         icp->icmp6_cksum = 0;
1312         seq = ntransmitted++;
1313         CLR(seq % mx_dup_ck);
1314
1315         if (options & F_FQDN) {
1316                 icp->icmp6_type = ICMP6_NI_QUERY;
1317                 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1318                 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1319                 nip->ni_flags = htons(0);
1320
1321                 memcpy(nip->icmp6_ni_nonce, nonce,
1322                     sizeof(nip->icmp6_ni_nonce));
1323                 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1324
1325                 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1326                     sizeof(dst.sin6_addr));
1327                 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1328                 datalen = 0;
1329         } else if (options & F_FQDNOLD) {
1330                 /* packet format in 03 draft - no Subject data on queries */
1331                 icp->icmp6_type = ICMP6_NI_QUERY;
1332                 icp->icmp6_code = 0;    /* code field is always 0 */
1333                 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1334                 nip->ni_flags = htons(0);
1335
1336                 memcpy(nip->icmp6_ni_nonce, nonce,
1337                     sizeof(nip->icmp6_ni_nonce));
1338                 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1339
1340                 cc = ICMP6_NIQLEN;
1341                 datalen = 0;
1342         } else if (options & F_NODEADDR) {
1343                 icp->icmp6_type = ICMP6_NI_QUERY;
1344                 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1345                 nip->ni_qtype = htons(NI_QTYPE_NODEADDR);
1346                 nip->ni_flags = naflags;
1347
1348                 memcpy(nip->icmp6_ni_nonce, nonce,
1349                     sizeof(nip->icmp6_ni_nonce));
1350                 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1351
1352                 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1353                     sizeof(dst.sin6_addr));
1354                 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1355                 datalen = 0;
1356         } else if (options & F_SUPTYPES) {
1357                 icp->icmp6_type = ICMP6_NI_QUERY;
1358                 icp->icmp6_code = ICMP6_NI_SUBJ_FQDN;   /*empty*/
1359                 nip->ni_qtype = htons(NI_QTYPE_SUPTYPES);
1360                 /* we support compressed bitmap */
1361                 nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS;
1362
1363                 memcpy(nip->icmp6_ni_nonce, nonce,
1364                     sizeof(nip->icmp6_ni_nonce));
1365                 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1366                 cc = ICMP6_NIQLEN;
1367                 datalen = 0;
1368         } else {
1369                 icp->icmp6_type = ICMP6_ECHO_REQUEST;
1370                 icp->icmp6_code = 0;
1371                 icp->icmp6_id = htons(ident);
1372                 icp->icmp6_seq = ntohs(seq);
1373                 if (timing) {
1374                         struct timeval tv;
1375                         struct tv32 *tv32;
1376                         (void)gettimeofday(&tv, NULL);
1377                         tv32 = (struct tv32 *)&outpack[ICMP6ECHOLEN];
1378                         tv32->tv32_sec = htonl(tv.tv_sec);
1379                         tv32->tv32_usec = htonl(tv.tv_usec);
1380                 }
1381                 cc = ICMP6ECHOLEN + datalen;
1382         }
1383
1384 #ifdef DIAGNOSTIC
1385         if (pingerlen() != cc)
1386                 errx(1, "internal error; length mismatch");
1387 #endif
1388
1389         smsghdr.msg_name = (caddr_t)&dst;
1390         smsghdr.msg_namelen = sizeof(dst);
1391         memset(&iov, 0, sizeof(iov));
1392         iov[0].iov_base = (caddr_t)outpack;
1393         iov[0].iov_len = cc;
1394         smsghdr.msg_iov = iov;
1395         smsghdr.msg_iovlen = 1;
1396
1397         i = sendmsg(s, &smsghdr, 0);
1398
1399         if (i < 0 || i != cc)  {
1400                 if (i < 0)
1401                         warn("sendmsg");
1402                 (void)printf("ping6: wrote %s %d chars, ret=%d\n",
1403                     hostname, cc, i);
1404         }
1405         if (!(options & F_QUIET) && options & F_FLOOD)
1406                 (void)write(STDOUT_FILENO, &DOT, 1);
1407
1408         return(0);
1409 }
1410
1411 int
1412 myechoreply(const struct icmp6_hdr *icp)
1413 {
1414         if (ntohs(icp->icmp6_id) == ident)
1415                 return 1;
1416         else
1417                 return 0;
1418 }
1419
1420 int
1421 mynireply(const struct icmp6_nodeinfo *nip)
1422 {
1423         if (memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t),
1424             nonce + sizeof(u_int16_t),
1425             sizeof(nonce) - sizeof(u_int16_t)) == 0)
1426                 return 1;
1427         else
1428                 return 0;
1429 }
1430
1431 char *
1432 dnsdecode(const u_char **sp, const u_char *ep, const u_char *base, char *buf,
1433         size_t bufsiz)
1434         /*base for compressed name*/
1435 {
1436         int i;
1437         const u_char *cp;
1438         char cresult[MAXDNAME + 1];
1439         const u_char *comp;
1440         int l;
1441
1442         cp = *sp;
1443         *buf = '\0';
1444
1445         if (cp >= ep)
1446                 return NULL;
1447         while (cp < ep) {
1448                 i = *cp;
1449                 if (i == 0 || cp != *sp) {
1450                         if (strlcat((char *)buf, ".", bufsiz) >= bufsiz)
1451                                 return NULL;    /*result overrun*/
1452                 }
1453                 if (i == 0)
1454                         break;
1455                 cp++;
1456
1457                 if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) {
1458                         /* DNS compression */
1459                         if (!base)
1460                                 return NULL;
1461
1462                         comp = base + (i & 0x3f);
1463                         if (dnsdecode(&comp, cp, base, cresult,
1464                             sizeof(cresult)) == NULL)
1465                                 return NULL;
1466                         if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1467                                 return NULL;    /*result overrun*/
1468                         break;
1469                 } else if ((i & 0x3f) == i) {
1470                         if (i > ep - cp)
1471                                 return NULL;    /*source overrun*/
1472                         while (i-- > 0 && cp < ep) {
1473                                 l = snprintf(cresult, sizeof(cresult),
1474                                     isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff);
1475                                 if (l >= sizeof(cresult) || l < 0)
1476                                         return NULL;
1477                                 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1478                                         return NULL;    /*result overrun*/
1479                                 cp++;
1480                         }
1481                 } else
1482                         return NULL;    /*invalid label*/
1483         }
1484         if (i != 0)
1485                 return NULL;    /*not terminated*/
1486         cp++;
1487         *sp = cp;
1488         return buf;
1489 }
1490
1491 /*
1492  * pr_pack --
1493  *      Print out the packet, if it came from us.  This logic is necessary
1494  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1495  * which arrive ('tis only fair).  This permits multiple copies of this
1496  * program to be run without having intermingled output (or statistics!).
1497  */
1498 void
1499 pr_pack(u_char *buf, int cc, struct msghdr *mhdr)
1500 {
1501 #define safeputc(c)     printf((isprint((c)) ? "%c" : "\\%03o"), c)
1502         struct icmp6_hdr *icp;
1503         struct icmp6_nodeinfo *ni;
1504         int i;
1505         int hoplim;
1506         struct sockaddr *from;
1507         int fromlen;
1508         u_char *cp = NULL, *dp, *end = buf + cc;
1509         struct in6_pktinfo *pktinfo = NULL;
1510         struct timeval tv, tp;
1511         struct tv32 *tpp;
1512         double triptime = 0;
1513         int dupflag;
1514         size_t off;
1515         int oldfqdn;
1516         u_int16_t seq;
1517         char dnsname[MAXDNAME + 1];
1518
1519         (void)gettimeofday(&tv, NULL);
1520
1521         if (!mhdr || !mhdr->msg_name ||
1522             mhdr->msg_namelen != sizeof(struct sockaddr_in6) ||
1523             ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) {
1524                 if (options & F_VERBOSE)
1525                         warnx("invalid peername");
1526                 return;
1527         }
1528         from = (struct sockaddr *)mhdr->msg_name;
1529         fromlen = mhdr->msg_namelen;
1530         if (cc < sizeof(struct icmp6_hdr)) {
1531                 if (options & F_VERBOSE)
1532                         warnx("packet too short (%d bytes) from %s", cc,
1533                             pr_addr(from, fromlen));
1534                 return;
1535         }
1536         if (((mhdr->msg_flags & MSG_CTRUNC) != 0) &&
1537             (options & F_VERBOSE) != 0)
1538                 warnx("some control data discarded, insufficient buffer size");
1539         icp = (struct icmp6_hdr *)buf;
1540         ni = (struct icmp6_nodeinfo *)buf;
1541         off = 0;
1542
1543         if ((hoplim = get_hoplim(mhdr)) == -1) {
1544                 warnx("failed to get receiving hop limit");
1545                 return;
1546         }
1547         if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) {
1548                 warnx("failed to get receiving packet information");
1549                 return;
1550         }
1551
1552         if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) {
1553                 seq = ntohs(icp->icmp6_seq);
1554                 ++nreceived;
1555                 if (timing) {
1556                         tpp = (struct tv32 *)(icp + 1);
1557                         tp.tv_sec = ntohl(tpp->tv32_sec);
1558                         tp.tv_usec = ntohl(tpp->tv32_usec);
1559                         tvsub(&tv, &tp);
1560                         triptime = ((double)tv.tv_sec) * 1000.0 +
1561                             ((double)tv.tv_usec) / 1000.0;
1562                         tsum += triptime;
1563                         tsumsq += triptime * triptime;
1564                         if (triptime < tmin)
1565                                 tmin = triptime;
1566                         if (triptime > tmax)
1567                                 tmax = triptime;
1568                 }
1569
1570                 if (TST(seq % mx_dup_ck)) {
1571                         ++nrepeats;
1572                         --nreceived;
1573                         dupflag = 1;
1574                 } else {
1575                         SET(seq % mx_dup_ck);
1576                         dupflag = 0;
1577                 }
1578
1579                 if (options & F_QUIET)
1580                         return;
1581
1582                 if (options & F_FLOOD)
1583                         (void)write(STDOUT_FILENO, &BSPACE, 1);
1584                 else {
1585                         if (options & F_AUDIBLE)
1586                                 (void)write(STDOUT_FILENO, &BBELL, 1);
1587                         (void)printf("%d bytes from %s, icmp_seq=%u", cc,
1588                             pr_addr(from, fromlen), seq);
1589                         (void)printf(" hlim=%d", hoplim);
1590                         if ((options & F_VERBOSE) != 0) {
1591                                 struct sockaddr_in6 dstsa;
1592
1593                                 memset(&dstsa, 0, sizeof(dstsa));
1594                                 dstsa.sin6_family = AF_INET6;
1595                                 dstsa.sin6_len = sizeof(dstsa);
1596                                 dstsa.sin6_scope_id = pktinfo->ipi6_ifindex;
1597                                 dstsa.sin6_addr = pktinfo->ipi6_addr;
1598                                 (void)printf(" dst=%s",
1599                                     pr_addr((struct sockaddr *)&dstsa,
1600                                     sizeof(dstsa)));
1601                         }
1602                         if (timing)
1603                                 (void)printf(" time=%.3f ms", triptime);
1604                         if (dupflag)
1605                                 (void)printf("(DUP!)");
1606                         /* check the data */
1607                         cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1608                         dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1609                         for (i = 8; cp < end; ++i, ++cp, ++dp) {
1610                                 if (*cp != *dp) {
1611                                         (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp);
1612                                         break;
1613                                 }
1614                         }
1615                 }
1616         } else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) {
1617                 seq = ntohs(*(u_int16_t *)ni->icmp6_ni_nonce);
1618                 ++nreceived;
1619                 if (TST(seq % mx_dup_ck)) {
1620                         ++nrepeats;
1621                         --nreceived;
1622                         dupflag = 1;
1623                 } else {
1624                         SET(seq % mx_dup_ck);
1625                         dupflag = 0;
1626                 }
1627
1628                 if (options & F_QUIET)
1629                         return;
1630
1631                 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1632
1633                 switch (ntohs(ni->ni_code)) {
1634                 case ICMP6_NI_SUCCESS:
1635                         break;
1636                 case ICMP6_NI_REFUSED:
1637                         printf("refused, type 0x%x", ntohs(ni->ni_type));
1638                         goto fqdnend;
1639                 case ICMP6_NI_UNKNOWN:
1640                         printf("unknown, type 0x%x", ntohs(ni->ni_type));
1641                         goto fqdnend;
1642                 default:
1643                         printf("unknown code 0x%x, type 0x%x",
1644                             ntohs(ni->ni_code), ntohs(ni->ni_type));
1645                         goto fqdnend;
1646                 }
1647
1648                 switch (ntohs(ni->ni_qtype)) {
1649                 case NI_QTYPE_NOOP:
1650                         printf("NodeInfo NOOP");
1651                         break;
1652                 case NI_QTYPE_SUPTYPES:
1653                         pr_suptypes(ni, end - (u_char *)ni);
1654                         break;
1655                 case NI_QTYPE_NODEADDR:
1656                         pr_nodeaddr(ni, end - (u_char *)ni);
1657                         break;
1658                 case NI_QTYPE_FQDN:
1659                 default:        /* XXX: for backward compatibility */
1660                         cp = (u_char *)ni + ICMP6_NIRLEN;
1661                         if (buf[off + ICMP6_NIRLEN] ==
1662                             cc - off - ICMP6_NIRLEN - 1)
1663                                 oldfqdn = 1;
1664                         else
1665                                 oldfqdn = 0;
1666                         if (oldfqdn) {
1667                                 cp++;   /* skip length */
1668                                 while (cp < end) {
1669                                         safeputc(*cp & 0xff);
1670                                         cp++;
1671                                 }
1672                         } else {
1673                                 i = 0;
1674                                 while (cp < end) {
1675                                         if (dnsdecode((const u_char **)&cp, end,
1676                                             (const u_char *)(ni + 1), dnsname,
1677                                             sizeof(dnsname)) == NULL) {
1678                                                 printf("???");
1679                                                 break;
1680                                         }
1681                                         /*
1682                                          * name-lookup special handling for
1683                                          * truncated name
1684                                          */
1685                                         if (cp + 1 <= end && !*cp &&
1686                                             strlen(dnsname) > 0) {
1687                                                 dnsname[strlen(dnsname) - 1] = '\0';
1688                                                 cp++;
1689                                         }
1690                                         printf("%s%s", i > 0 ? "," : "",
1691                                             dnsname);
1692                                 }
1693                         }
1694                         if (options & F_VERBOSE) {
1695                                 int32_t ttl;
1696                                 int comma = 0;
1697
1698                                 (void)printf(" (");     /*)*/
1699
1700                                 switch (ni->ni_code) {
1701                                 case ICMP6_NI_REFUSED:
1702                                         (void)printf("refused");
1703                                         comma++;
1704                                         break;
1705                                 case ICMP6_NI_UNKNOWN:
1706                                         (void)printf("unknown qtype");
1707                                         comma++;
1708                                         break;
1709                                 }
1710
1711                                 if ((end - (u_char *)ni) < ICMP6_NIRLEN) {
1712                                         /* case of refusion, unknown */
1713                                         /*(*/
1714                                         putchar(')');
1715                                         goto fqdnend;
1716                                 }
1717                                 ttl = (int32_t)ntohl(*(u_long *)&buf[off+ICMP6ECHOLEN+8]);
1718                                 if (comma)
1719                                         printf(",");
1720                                 if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) {
1721                                         (void)printf("TTL=%d:meaningless",
1722                                             (int)ttl);
1723                                 } else {
1724                                         if (ttl < 0) {
1725                                                 (void)printf("TTL=%d:invalid",
1726                                                    ttl);
1727                                         } else
1728                                                 (void)printf("TTL=%d", ttl);
1729                                 }
1730                                 comma++;
1731
1732                                 if (oldfqdn) {
1733                                         if (comma)
1734                                                 printf(",");
1735                                         printf("03 draft");
1736                                         comma++;
1737                                 } else {
1738                                         cp = (u_char *)ni + ICMP6_NIRLEN;
1739                                         if (cp == end) {
1740                                                 if (comma)
1741                                                         printf(",");
1742                                                 printf("no name");
1743                                                 comma++;
1744                                         }
1745                                 }
1746
1747                                 if (buf[off + ICMP6_NIRLEN] !=
1748                                     cc - off - ICMP6_NIRLEN - 1 && oldfqdn) {
1749                                         if (comma)
1750                                                 printf(",");
1751                                         (void)printf("invalid namelen:%d/%lu",
1752                                             buf[off + ICMP6_NIRLEN],
1753                                             (u_long)cc - off - ICMP6_NIRLEN - 1);
1754                                         comma++;
1755                                 }
1756                                 /*(*/
1757                                 putchar(')');
1758                         }
1759                 fqdnend:
1760                         ;
1761                 }
1762         } else {
1763                 /* We've got something other than an ECHOREPLY */
1764                 if (!(options & F_VERBOSE))
1765                         return;
1766                 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1767                 pr_icmph(icp, end);
1768         }
1769
1770         if (!(options & F_FLOOD)) {
1771                 (void)putchar('\n');
1772                 if (options & F_VERBOSE)
1773                         pr_exthdrs(mhdr);
1774                 (void)fflush(stdout);
1775         }
1776 #undef safeputc
1777 }
1778
1779 void
1780 pr_exthdrs(struct msghdr *mhdr)
1781 {
1782         ssize_t bufsize;
1783         void    *bufp;
1784         struct cmsghdr *cm;
1785
1786         bufsize = 0;
1787         bufp = mhdr->msg_control;
1788         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1789              cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1790                 if (cm->cmsg_level != IPPROTO_IPV6)
1791                         continue;
1792
1793                 bufsize = CONTROLLEN - ((caddr_t)CMSG_DATA(cm) - (caddr_t)bufp);
1794                 if (bufsize <= 0)
1795                         continue; 
1796                 switch (cm->cmsg_type) {
1797                 case IPV6_HOPOPTS:
1798                         printf("  HbH Options: ");
1799                         pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1800                         break;
1801                 case IPV6_DSTOPTS:
1802 #ifdef IPV6_RTHDRDSTOPTS
1803                 case IPV6_RTHDRDSTOPTS:
1804 #endif
1805                         printf("  Dst Options: ");
1806                         pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1807                         break;
1808                 case IPV6_RTHDR:
1809                         printf("  Routing: ");
1810                         pr_rthdr(CMSG_DATA(cm), (size_t)bufsize);
1811                         break;
1812                 }
1813         }
1814 }
1815
1816 #ifdef USE_RFC2292BIS
1817 void
1818 pr_ip6opt(void *extbuf, size_t bufsize)
1819 {
1820         struct ip6_hbh *ext;
1821         int currentlen;
1822         u_int8_t type;
1823         socklen_t extlen, len;
1824         void *databuf;
1825         size_t offset;
1826         u_int16_t value2;
1827         u_int32_t value4;
1828
1829         ext = (struct ip6_hbh *)extbuf;
1830         extlen = (ext->ip6h_len + 1) * 8;
1831         printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt,
1832             (unsigned int)ext->ip6h_len, (unsigned long)extlen);
1833
1834         /*
1835          * Bounds checking on the ancillary data buffer:
1836          *     subtract the size of a cmsg structure from the buffer size.
1837          */
1838         if (bufsize < (extlen  + CMSG_SPACE(0))) {
1839                 extlen = bufsize - CMSG_SPACE(0);
1840                 warnx("options truncated, showing only %u (total=%u)",
1841                     (unsigned int)(extlen / 8 - 1),
1842                     (unsigned int)(ext->ip6h_len));
1843         }
1844
1845         currentlen = 0;
1846         while (1) {
1847                 currentlen = inet6_opt_next(extbuf, extlen, currentlen,
1848                     &type, &len, &databuf);
1849                 if (currentlen == -1)
1850                         break;
1851                 switch (type) {
1852                 /*
1853                  * Note that inet6_opt_next automatically skips any padding
1854                  * optins.
1855                  */
1856                 case IP6OPT_JUMBO:
1857                         offset = 0;
1858                         offset = inet6_opt_get_val(databuf, offset,
1859                             &value4, sizeof(value4));
1860                         printf("    Jumbo Payload Opt: Length %u\n",
1861                             (u_int32_t)ntohl(value4));
1862                         break;
1863                 case IP6OPT_ROUTER_ALERT:
1864                         offset = 0;
1865                         offset = inet6_opt_get_val(databuf, offset,
1866                                                    &value2, sizeof(value2));
1867                         printf("    Router Alert Opt: Type %u\n",
1868                             ntohs(value2));
1869                         break;
1870                 default:
1871                         printf("    Received Opt %u len %lu\n",
1872                             type, (unsigned long)len);
1873                         break;
1874                 }
1875         }
1876         return;
1877 }
1878 #else  /* !USE_RFC2292BIS */
1879 /* ARGSUSED */
1880 void
1881 pr_ip6opt(void *extbuf, size_t bufsize __unused)
1882 {
1883         putchar('\n');
1884         return;
1885 }
1886 #endif /* USE_RFC2292BIS */
1887
1888 #ifdef USE_RFC2292BIS
1889 void
1890 pr_rthdr(void *extbuf, size_t bufsize)
1891 {
1892         struct in6_addr *in6;
1893         char ntopbuf[INET6_ADDRSTRLEN];
1894         struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf;
1895         int i, segments, origsegs, rthsize, size0, size1;
1896
1897         /* print fixed part of the header */
1898         printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt,
1899             rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type);
1900         if ((segments = inet6_rth_segments(extbuf)) >= 0) {
1901                 printf("%d segments, ", segments);
1902                 printf("%d left\n", rh->ip6r_segleft);
1903         } else {
1904                 printf("segments unknown, ");
1905                 printf("%d left\n", rh->ip6r_segleft);
1906                 return;
1907         }
1908
1909         /*
1910          * Bounds checking on the ancillary data buffer. When calculating
1911          * the number of items to show keep in mind:
1912          *      - The size of the cmsg structure
1913          *      - The size of one segment (the size of a Type 0 routing header)
1914          *      - When dividing add a fudge factor of one in case the
1915          *        dividend is not evenly divisible by the divisor
1916          */
1917         rthsize = (rh->ip6r_len + 1) * 8;
1918         if (bufsize < (rthsize + CMSG_SPACE(0))) {
1919                 origsegs = segments;
1920                 size0 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 0);
1921                 size1 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 1);
1922                 segments -= (rthsize - (bufsize - CMSG_SPACE(0))) /
1923                     (size1 - size0) + 1;
1924                 warnx("segments truncated, showing only %d (total=%d)",
1925                     segments, origsegs);
1926         }
1927
1928         for (i = 0; i < segments; i++) {
1929                 in6 = inet6_rth_getaddr(extbuf, i);
1930                 if (in6 == NULL)
1931                         printf("   [%d]<NULL>\n", i);
1932                 else {
1933                         if (!inet_ntop(AF_INET6, in6, ntopbuf,
1934                             sizeof(ntopbuf)))
1935                                 strlcpy(ntopbuf, "?", sizeof(ntopbuf));
1936                         printf("   [%d]%s\n", i, ntopbuf);
1937                 }
1938         }
1939
1940         return;
1941
1942 }
1943
1944 #else  /* !USE_RFC2292BIS */
1945 /* ARGSUSED */
1946 void
1947 pr_rthdr(void *extbuf, size_t bufsize __unused)
1948 {
1949         putchar('\n');
1950         return;
1951 }
1952 #endif /* USE_RFC2292BIS */
1953
1954 int
1955 pr_bitrange(u_int32_t v, int soff, int ii)
1956 {
1957         int off;
1958         int i;
1959
1960         off = 0;
1961         while (off < 32) {
1962                 /* shift till we have 0x01 */
1963                 if ((v & 0x01) == 0) {
1964                         if (ii > 1)
1965                                 printf("-%u", soff + off - 1);
1966                         ii = 0;
1967                         switch (v & 0x0f) {
1968                         case 0x00:
1969                                 v >>= 4;
1970                                 off += 4;
1971                                 continue;
1972                         case 0x08:
1973                                 v >>= 3;
1974                                 off += 3;
1975                                 continue;
1976                         case 0x04: case 0x0c:
1977                                 v >>= 2;
1978                                 off += 2;
1979                                 continue;
1980                         default:
1981                                 v >>= 1;
1982                                 off += 1;
1983                                 continue;
1984                         }
1985                 }
1986
1987                 /* we have 0x01 with us */
1988                 for (i = 0; i < 32 - off; i++) {
1989                         if ((v & (0x01 << i)) == 0)
1990                                 break;
1991                 }
1992                 if (!ii)
1993                         printf(" %u", soff + off);
1994                 ii += i;
1995                 v >>= i; off += i;
1996         }
1997         return ii;
1998 }
1999
2000 void
2001 pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen)
2002         /* ni->qtype must be SUPTYPES */
2003 {
2004         size_t clen;
2005         u_int32_t v;
2006         const u_char *cp, *end;
2007         u_int16_t cur;
2008         struct cbit {
2009                 u_int16_t words;        /*32bit count*/
2010                 u_int16_t skip;
2011         } cbit;
2012 #define MAXQTYPES       (1 << 16)
2013         size_t off;
2014         int b;
2015
2016         cp = (u_char *)(ni + 1);
2017         end = ((u_char *)ni) + nilen;
2018         cur = 0;
2019         b = 0;
2020
2021         printf("NodeInfo Supported Qtypes");
2022         if (options & F_VERBOSE) {
2023                 if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS)
2024                         printf(", compressed bitmap");
2025                 else
2026                         printf(", raw bitmap");
2027         }
2028
2029         while (cp < end) {
2030                 clen = (size_t)(end - cp);
2031                 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) {
2032                         if (clen == 0 || clen > MAXQTYPES / 8 ||
2033                             clen % sizeof(v)) {
2034                                 printf("???");
2035                                 return;
2036                         }
2037                 } else {
2038                         if (clen < sizeof(cbit) || clen % sizeof(v))
2039                                 return;
2040                         memcpy(&cbit, cp, sizeof(cbit));
2041                         if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) >
2042                             clen)
2043                                 return;
2044                         cp += sizeof(cbit);
2045                         clen = ntohs(cbit.words) * sizeof(v);
2046                         if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 >
2047                             MAXQTYPES)
2048                                 return;
2049                 }
2050
2051                 for (off = 0; off < clen; off += sizeof(v)) {
2052                         memcpy(&v, cp + off, sizeof(v));
2053                         v = (u_int32_t)ntohl(v);
2054                         b = pr_bitrange(v, (int)(cur + off * 8), b);
2055                 }
2056                 /* flush the remaining bits */
2057                 b = pr_bitrange(0, (int)(cur + off * 8), b);
2058
2059                 cp += clen;
2060                 cur += clen * 8;
2061                 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0)
2062                         cur += ntohs(cbit.skip) * 32;
2063         }
2064 }
2065
2066 void
2067 pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen)
2068         /* ni->qtype must be NODEADDR */
2069 {
2070         u_char *cp = (u_char *)(ni + 1);
2071         char ntop_buf[INET6_ADDRSTRLEN];
2072         int withttl = 0;
2073
2074         nilen -= sizeof(struct icmp6_nodeinfo);
2075
2076         if (options & F_VERBOSE) {
2077                 switch (ni->ni_code) {
2078                 case ICMP6_NI_REFUSED:
2079                         (void)printf("refused");
2080                         break;
2081                 case ICMP6_NI_UNKNOWN:
2082                         (void)printf("unknown qtype");
2083                         break;
2084                 }
2085                 if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE)
2086                         (void)printf(" truncated");
2087         }
2088         putchar('\n');
2089         if (nilen <= 0)
2090                 printf("  no address\n");
2091
2092         /*
2093          * In icmp-name-lookups 05 and later, TTL of each returned address
2094          * is contained in the resposne. We try to detect the version
2095          * by the length of the data, but note that the detection algorithm
2096          * is incomplete. We assume the latest draft by default.
2097          */
2098         if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0)
2099                 withttl = 1;
2100         while (nilen > 0) {
2101                 u_int32_t ttl;
2102
2103                 if (withttl) {
2104                         /* XXX: alignment? */
2105                         ttl = (u_int32_t)ntohl(*(u_int32_t *)cp);
2106                         cp += sizeof(u_int32_t);
2107                         nilen -= sizeof(u_int32_t);
2108                 }
2109
2110                 if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) ==
2111                     NULL)
2112                         strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2113                 printf("  %s", ntop_buf);
2114                 if (withttl) {
2115                         if (ttl == 0xffffffff) {
2116                                 /*
2117                                  * XXX: can this convention be applied to all
2118                                  * type of TTL (i.e. non-ND TTL)?
2119                                  */
2120                                 printf("(TTL=infty)");
2121                         }
2122                         else
2123                                 printf("(TTL=%u)", ttl);
2124                 }
2125                 putchar('\n');
2126
2127                 nilen -= sizeof(struct in6_addr);
2128                 cp += sizeof(struct in6_addr);
2129         }
2130 }
2131
2132 int
2133 get_hoplim(struct msghdr *mhdr)
2134 {
2135         struct cmsghdr *cm;
2136
2137         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2138              cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2139                 if (cm->cmsg_len == 0)
2140                         return(-1);
2141
2142                 if (cm->cmsg_level == IPPROTO_IPV6 &&
2143                     cm->cmsg_type == IPV6_HOPLIMIT &&
2144                     cm->cmsg_len == CMSG_LEN(sizeof(int)))
2145                         return(*(int *)CMSG_DATA(cm));
2146         }
2147
2148         return(-1);
2149 }
2150
2151 struct in6_pktinfo *
2152 get_rcvpktinfo(struct msghdr *mhdr)
2153 {
2154         struct cmsghdr *cm;
2155
2156         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2157              cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2158                 if (cm->cmsg_len == 0)
2159                         return(NULL);
2160
2161                 if (cm->cmsg_level == IPPROTO_IPV6 &&
2162                     cm->cmsg_type == IPV6_PKTINFO &&
2163                     cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo)))
2164                         return((struct in6_pktinfo *)CMSG_DATA(cm));
2165         }
2166
2167         return(NULL);
2168 }
2169
2170 int
2171 get_pathmtu(struct msghdr *mhdr)
2172 {
2173 #ifdef IPV6_RECVPATHMTU
2174         struct cmsghdr *cm;
2175         struct ip6_mtuinfo *mtuctl = NULL;
2176
2177         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2178              cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2179                 if (cm->cmsg_len == 0)
2180                         return(0);
2181
2182                 if (cm->cmsg_level == IPPROTO_IPV6 &&
2183                     cm->cmsg_type == IPV6_PATHMTU &&
2184                     cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) {
2185                         mtuctl = (struct ip6_mtuinfo *)CMSG_DATA(cm);
2186
2187                         /*
2188                          * If the notified destination is different from
2189                          * the one we are pinging, just ignore the info.
2190                          * We check the scope ID only when both notified value
2191                          * and our own value have non-0 values, because we may
2192                          * have used the default scope zone ID for sending,
2193                          * in which case the scope ID value is 0.
2194                          */
2195                         if (!IN6_ARE_ADDR_EQUAL(&mtuctl->ip6m_addr.sin6_addr,
2196                                                 &dst.sin6_addr) ||
2197                             (mtuctl->ip6m_addr.sin6_scope_id &&
2198                              dst.sin6_scope_id &&
2199                              mtuctl->ip6m_addr.sin6_scope_id !=
2200                              dst.sin6_scope_id)) {
2201                                 if ((options & F_VERBOSE) != 0) {
2202                                         printf("path MTU for %s is notified. "
2203                                                "(ignored)\n",
2204                                            pr_addr((struct sockaddr *)&mtuctl->ip6m_addr,
2205                                            sizeof(mtuctl->ip6m_addr)));
2206                                 }
2207                                 return(0);
2208                         }
2209
2210                         /*
2211                          * Ignore an invalid MTU. XXX: can we just believe
2212                          * the kernel check?
2213                          */
2214                         if (mtuctl->ip6m_mtu < IPV6_MMTU)
2215                                 return(0);
2216
2217                         /* notification for our destination. return the MTU. */
2218                         return((int)mtuctl->ip6m_mtu);
2219                 }
2220         }
2221 #endif
2222         return(0);
2223 }
2224
2225 /*
2226  * tvsub --
2227  *      Subtract 2 timeval structs:  out = out - in.  Out is assumed to
2228  * be >= in.
2229  */
2230 void
2231 tvsub(struct timeval *out, struct timeval *in)
2232 {
2233         if ((out->tv_usec -= in->tv_usec) < 0) {
2234                 --out->tv_sec;
2235                 out->tv_usec += 1000000;
2236         }
2237         out->tv_sec -= in->tv_sec;
2238 }
2239
2240 /*
2241  * onint --
2242  *      SIGINT handler.
2243  */
2244 /* ARGSUSED */
2245 void
2246 onint(int notused __unused)
2247 {
2248         summary();
2249
2250         if (res != NULL)
2251                 freeaddrinfo(res);
2252
2253         if(packet != NULL)
2254                 free(packet);
2255
2256 #ifndef HAVE_POLL_H
2257         if(fdmaskp != NULL)
2258                 free(fdmaskp);
2259 #endif
2260
2261         (void)signal(SIGINT, SIG_DFL);
2262         (void)kill(getpid(), SIGINT);
2263
2264         /* NOTREACHED */
2265         exit(1);
2266 }
2267
2268 /*
2269  * summary --
2270  *      Print out statistics.
2271  */
2272 void
2273 summary(void)
2274 {
2275
2276         (void)printf("\n--- %s ping6 statistics ---\n", hostname);
2277         (void)printf("%ld packets transmitted, ", ntransmitted);
2278         (void)printf("%ld packets received, ", nreceived);
2279         if (nrepeats)
2280                 (void)printf("+%ld duplicates, ", nrepeats);
2281         if (ntransmitted) {
2282                 if (nreceived > ntransmitted)
2283                         (void)printf("-- somebody's duplicating packets!");
2284                 else
2285                         (void)printf("%.1f%% packet loss",
2286                             ((((double)ntransmitted - nreceived) * 100.0) /
2287                             ntransmitted));
2288         }
2289         (void)putchar('\n');
2290         if (nreceived && timing) {
2291                 /* Only display average to microseconds */
2292                 double num = nreceived + nrepeats;
2293                 double avg = tsum / num;
2294                 double dev = sqrt(tsumsq / num - avg * avg);
2295                 (void)printf(
2296                     "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
2297                     tmin, avg, tmax, dev);
2298                 (void)fflush(stdout);
2299         }
2300         (void)fflush(stdout);
2301 }
2302
2303 /*subject type*/
2304 static const char *niqcode[] = {
2305         "IPv6 address",
2306         "DNS label",    /*or empty*/
2307         "IPv4 address",
2308 };
2309
2310 /*result code*/
2311 static const char *nircode[] = {
2312         "Success", "Refused", "Unknown",
2313 };
2314
2315
2316 /*
2317  * pr_icmph --
2318  *      Print a descriptive string about an ICMP header.
2319  */
2320 void
2321 pr_icmph(struct icmp6_hdr *icp, u_char *end)
2322 {
2323         char ntop_buf[INET6_ADDRSTRLEN];
2324         struct nd_redirect *red;
2325         struct icmp6_nodeinfo *ni;
2326         char dnsname[MAXDNAME + 1];
2327         const u_char *cp;
2328         size_t l;
2329
2330         switch (icp->icmp6_type) {
2331         case ICMP6_DST_UNREACH:
2332                 switch (icp->icmp6_code) {
2333                 case ICMP6_DST_UNREACH_NOROUTE:
2334                         (void)printf("No Route to Destination\n");
2335                         break;
2336                 case ICMP6_DST_UNREACH_ADMIN:
2337                         (void)printf("Destination Administratively "
2338                             "Unreachable\n");
2339                         break;
2340                 case ICMP6_DST_UNREACH_BEYONDSCOPE:
2341                         (void)printf("Destination Unreachable Beyond Scope\n");
2342                         break;
2343                 case ICMP6_DST_UNREACH_ADDR:
2344                         (void)printf("Destination Host Unreachable\n");
2345                         break;
2346                 case ICMP6_DST_UNREACH_NOPORT:
2347                         (void)printf("Destination Port Unreachable\n");
2348                         break;
2349                 default:
2350                         (void)printf("Destination Unreachable, Bad Code: %d\n",
2351                             icp->icmp6_code);
2352                         break;
2353                 }
2354                 /* Print returned IP header information */
2355                 pr_retip((struct ip6_hdr *)(icp + 1), end);
2356                 break;
2357         case ICMP6_PACKET_TOO_BIG:
2358                 (void)printf("Packet too big mtu = %d\n",
2359                     (int)ntohl(icp->icmp6_mtu));
2360                 pr_retip((struct ip6_hdr *)(icp + 1), end);
2361                 break;
2362         case ICMP6_TIME_EXCEEDED:
2363                 switch (icp->icmp6_code) {
2364                 case ICMP6_TIME_EXCEED_TRANSIT:
2365                         (void)printf("Time to live exceeded\n");
2366                         break;
2367                 case ICMP6_TIME_EXCEED_REASSEMBLY:
2368                         (void)printf("Frag reassembly time exceeded\n");
2369                         break;
2370                 default:
2371                         (void)printf("Time exceeded, Bad Code: %d\n",
2372                             icp->icmp6_code);
2373                         break;
2374                 }
2375                 pr_retip((struct ip6_hdr *)(icp + 1), end);
2376                 break;
2377         case ICMP6_PARAM_PROB:
2378                 (void)printf("Parameter problem: ");
2379                 switch (icp->icmp6_code) {
2380                 case ICMP6_PARAMPROB_HEADER:
2381                         (void)printf("Erroneous Header ");
2382                         break;
2383                 case ICMP6_PARAMPROB_NEXTHEADER:
2384                         (void)printf("Unknown Nextheader ");
2385                         break;
2386                 case ICMP6_PARAMPROB_OPTION:
2387                         (void)printf("Unrecognized Option ");
2388                         break;
2389                 default:
2390                         (void)printf("Bad code(%d) ", icp->icmp6_code);
2391                         break;
2392                 }
2393                 (void)printf("pointer = 0x%02x\n",
2394                     (u_int32_t)ntohl(icp->icmp6_pptr));
2395                 pr_retip((struct ip6_hdr *)(icp + 1), end);
2396                 break;
2397         case ICMP6_ECHO_REQUEST:
2398                 (void)printf("Echo Request");
2399                 /* XXX ID + Seq + Data */
2400                 break;
2401         case ICMP6_ECHO_REPLY:
2402                 (void)printf("Echo Reply");
2403                 /* XXX ID + Seq + Data */
2404                 break;
2405         case ICMP6_MEMBERSHIP_QUERY:
2406                 (void)printf("Listener Query");
2407                 break;
2408         case ICMP6_MEMBERSHIP_REPORT:
2409                 (void)printf("Listener Report");
2410                 break;
2411         case ICMP6_MEMBERSHIP_REDUCTION:
2412                 (void)printf("Listener Done");
2413                 break;
2414         case ND_ROUTER_SOLICIT:
2415                 (void)printf("Router Solicitation");
2416                 break;
2417         case ND_ROUTER_ADVERT:
2418                 (void)printf("Router Advertisement");
2419                 break;
2420         case ND_NEIGHBOR_SOLICIT:
2421                 (void)printf("Neighbor Solicitation");
2422                 break;
2423         case ND_NEIGHBOR_ADVERT:
2424                 (void)printf("Neighbor Advertisement");
2425                 break;
2426         case ND_REDIRECT:
2427                 red = (struct nd_redirect *)icp;
2428                 (void)printf("Redirect\n");
2429                 if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf,
2430                     sizeof(ntop_buf)))
2431                         strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2432                 (void)printf("Destination: %s", ntop_buf);
2433                 if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf,
2434                     sizeof(ntop_buf)))
2435                         strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2436                 (void)printf(" New Target: %s", ntop_buf);
2437                 break;
2438         case ICMP6_NI_QUERY:
2439                 (void)printf("Node Information Query");
2440                 /* XXX ID + Seq + Data */
2441                 ni = (struct icmp6_nodeinfo *)icp;
2442                 l = end - (u_char *)(ni + 1);
2443                 printf(", ");
2444                 switch (ntohs(ni->ni_qtype)) {
2445                 case NI_QTYPE_NOOP:
2446                         (void)printf("NOOP");
2447                         break;
2448                 case NI_QTYPE_SUPTYPES:
2449                         (void)printf("Supported qtypes");
2450                         break;
2451                 case NI_QTYPE_FQDN:
2452                         (void)printf("DNS name");
2453                         break;
2454                 case NI_QTYPE_NODEADDR:
2455                         (void)printf("nodeaddr");
2456                         break;
2457                 case NI_QTYPE_IPV4ADDR:
2458                         (void)printf("IPv4 nodeaddr");
2459                         break;
2460                 default:
2461                         (void)printf("unknown qtype");
2462                         break;
2463                 }
2464                 if (options & F_VERBOSE) {
2465                         switch (ni->ni_code) {
2466                         case ICMP6_NI_SUBJ_IPV6:
2467                                 if (l == sizeof(struct in6_addr) &&
2468                                     inet_ntop(AF_INET6, ni + 1, ntop_buf,
2469                                     sizeof(ntop_buf)) != NULL) {
2470                                         (void)printf(", subject=%s(%s)",
2471                                             niqcode[ni->ni_code], ntop_buf);
2472                                 } else {
2473 #if 1
2474                                         /* backward compat to -W */
2475                                         (void)printf(", oldfqdn");
2476 #else
2477                                         (void)printf(", invalid");
2478 #endif
2479                                 }
2480                                 break;
2481                         case ICMP6_NI_SUBJ_FQDN:
2482                                 if (end == (u_char *)(ni + 1)) {
2483                                         (void)printf(", no subject");
2484                                         break;
2485                                 }
2486                                 printf(", subject=%s", niqcode[ni->ni_code]);
2487                                 cp = (const u_char *)(ni + 1);
2488                                 if (dnsdecode(&cp, end, NULL, dnsname,
2489                                     sizeof(dnsname)) != NULL)
2490                                         printf("(%s)", dnsname);
2491                                 else
2492                                         printf("(invalid)");
2493                                 break;
2494                         case ICMP6_NI_SUBJ_IPV4:
2495                                 if (l == sizeof(struct in_addr) &&
2496                                     inet_ntop(AF_INET, ni + 1, ntop_buf,
2497                                     sizeof(ntop_buf)) != NULL) {
2498                                         (void)printf(", subject=%s(%s)",
2499                                             niqcode[ni->ni_code], ntop_buf);
2500                                 } else
2501                                         (void)printf(", invalid");
2502                                 break;
2503                         default:
2504                                 (void)printf(", invalid");
2505                                 break;
2506                         }
2507                 }
2508                 break;
2509         case ICMP6_NI_REPLY:
2510                 (void)printf("Node Information Reply");
2511                 /* XXX ID + Seq + Data */
2512                 ni = (struct icmp6_nodeinfo *)icp;
2513                 printf(", ");
2514                 switch (ntohs(ni->ni_qtype)) {
2515                 case NI_QTYPE_NOOP:
2516                         (void)printf("NOOP");
2517                         break;
2518                 case NI_QTYPE_SUPTYPES:
2519                         (void)printf("Supported qtypes");
2520                         break;
2521                 case NI_QTYPE_FQDN:
2522                         (void)printf("DNS name");
2523                         break;
2524                 case NI_QTYPE_NODEADDR:
2525                         (void)printf("nodeaddr");
2526                         break;
2527                 case NI_QTYPE_IPV4ADDR:
2528                         (void)printf("IPv4 nodeaddr");
2529                         break;
2530                 default:
2531                         (void)printf("unknown qtype");
2532                         break;
2533                 }
2534                 if (options & F_VERBOSE) {
2535                         if (ni->ni_code > sizeof(nircode) / sizeof(nircode[0]))
2536                                 printf(", invalid");
2537                         else
2538                                 printf(", %s", nircode[ni->ni_code]);
2539                 }
2540                 break;
2541         default:
2542                 (void)printf("Bad ICMP type: %d", icp->icmp6_type);
2543         }
2544 }
2545
2546 /*
2547  * pr_iph --
2548  *      Print an IP6 header.
2549  */
2550 void
2551 pr_iph(struct ip6_hdr *ip6)
2552 {
2553         u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
2554         u_int8_t tc;
2555         char ntop_buf[INET6_ADDRSTRLEN];
2556
2557         tc = *(&ip6->ip6_vfc + 1); /* XXX */
2558         tc = (tc >> 4) & 0x0f;
2559         tc |= (ip6->ip6_vfc << 4);
2560
2561         printf("Vr TC  Flow Plen Nxt Hlim\n");
2562         printf(" %1x %02x %05x %04x  %02x   %02x\n",
2563             (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow),
2564             ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim);
2565         if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf)))
2566                 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2567         printf("%s->", ntop_buf);
2568         if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf)))
2569                 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2570         printf("%s\n", ntop_buf);
2571 }
2572
2573 /*
2574  * pr_addr --
2575  *      Return an ascii host address as a dotted quad and optionally with
2576  * a hostname.
2577  */
2578 const char *
2579 pr_addr(struct sockaddr *addr, int addrlen)
2580 {
2581         static char buf[NI_MAXHOST];
2582         int flag = 0;
2583
2584         if ((options & F_HOSTNAME) == 0)
2585                 flag |= NI_NUMERICHOST;
2586
2587         if (getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, flag) == 0)
2588                 return (buf);
2589         else
2590                 return "?";
2591 }
2592
2593 /*
2594  * pr_retip --
2595  *      Dump some info on a returned (via ICMPv6) IPv6 packet.
2596  */
2597 void
2598 pr_retip(struct ip6_hdr *ip6, u_char *end)
2599 {
2600         u_char *cp = (u_char *)ip6, nh;
2601         int hlen;
2602
2603         if (end - (u_char *)ip6 < sizeof(*ip6)) {
2604                 printf("IP6");
2605                 goto trunc;
2606         }
2607         pr_iph(ip6);
2608         hlen = sizeof(*ip6);
2609
2610         nh = ip6->ip6_nxt;
2611         cp += hlen;
2612         while (end - cp >= 8) {
2613                 switch (nh) {
2614                 case IPPROTO_HOPOPTS:
2615                         printf("HBH ");
2616                         hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3;
2617                         nh = ((struct ip6_hbh *)cp)->ip6h_nxt;
2618                         break;
2619                 case IPPROTO_DSTOPTS:
2620                         printf("DSTOPT ");
2621                         hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3;
2622                         nh = ((struct ip6_dest *)cp)->ip6d_nxt;
2623                         break;
2624                 case IPPROTO_FRAGMENT:
2625                         printf("FRAG ");
2626                         hlen = sizeof(struct ip6_frag);
2627                         nh = ((struct ip6_frag *)cp)->ip6f_nxt;
2628                         break;
2629                 case IPPROTO_ROUTING:
2630                         printf("RTHDR ");
2631                         hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3;
2632                         nh = ((struct ip6_rthdr *)cp)->ip6r_nxt;
2633                         break;
2634 #ifdef IPSEC
2635                 case IPPROTO_AH:
2636                         printf("AH ");
2637                         hlen = (((struct ah *)cp)->ah_len+2) << 2;
2638                         nh = ((struct ah *)cp)->ah_nxt;
2639                         break;
2640 #endif
2641                 case IPPROTO_ICMPV6:
2642                         printf("ICMP6: type = %d, code = %d\n",
2643                             *cp, *(cp + 1));
2644                         return;
2645                 case IPPROTO_ESP:
2646                         printf("ESP\n");
2647                         return;
2648                 case IPPROTO_TCP:
2649                         printf("TCP: from port %u, to port %u (decimal)\n",
2650                             (*cp * 256 + *(cp + 1)),
2651                             (*(cp + 2) * 256 + *(cp + 3)));
2652                         return;
2653                 case IPPROTO_UDP:
2654                         printf("UDP: from port %u, to port %u (decimal)\n",
2655                             (*cp * 256 + *(cp + 1)),
2656                             (*(cp + 2) * 256 + *(cp + 3)));
2657                         return;
2658                 default:
2659                         printf("Unknown Header(%d)\n", nh);
2660                         return;
2661                 }
2662
2663                 if ((cp += hlen) >= end)
2664                         goto trunc;
2665         }
2666         if (end - cp < 8)
2667                 goto trunc;
2668
2669         putchar('\n');
2670         return;
2671
2672   trunc:
2673         printf("...\n");
2674         return;
2675 }
2676
2677 void
2678 fill(char *bp, char *patp)
2679 {
2680         int ii, jj, kk;
2681         int pat[16];
2682         char *cp;
2683
2684         for (cp = patp; *cp; cp++)
2685                 if (!isxdigit(*cp))
2686                         errx(1, "patterns must be specified as hex digits");
2687         ii = sscanf(patp,
2688             "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
2689             &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
2690             &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
2691             &pat[13], &pat[14], &pat[15]);
2692
2693 /* xxx */
2694         if (ii > 0)
2695                 for (kk = 0;
2696                     kk <= MAXDATALEN - (8 + sizeof(struct tv32) + ii);
2697                     kk += ii)
2698                         for (jj = 0; jj < ii; ++jj)
2699                                 bp[jj + kk] = pat[jj];
2700         if (!(options & F_QUIET)) {
2701                 (void)printf("PATTERN: 0x");
2702                 for (jj = 0; jj < ii; ++jj)
2703                         (void)printf("%02x", bp[jj] & 0xFF);
2704                 (void)printf("\n");
2705         }
2706 }
2707
2708 #ifdef IPSEC
2709 #ifdef IPSEC_POLICY_IPSEC
2710 int
2711 setpolicy(int so __unused, char *policy)
2712 {
2713         char *buf;
2714
2715         if (policy == NULL)
2716                 return 0;       /* ignore */
2717
2718         buf = ipsec_set_policy(policy, strlen(policy));
2719         if (buf == NULL)
2720                 errx(1, "%s", ipsec_strerror());
2721         if (setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, buf,
2722             ipsec_get_policylen(buf)) < 0)
2723                 warnx("Unable to set IPsec policy");
2724         free(buf);
2725
2726         return 0;
2727 }
2728 #endif
2729 #endif
2730
2731 char *
2732 nigroup(char *name, int nig_oldmcprefix)
2733 {
2734         char *p;
2735         char *q;
2736         MD5_CTX ctxt;
2737         u_int8_t digest[16];
2738         u_int8_t c;
2739         size_t l;
2740         char hbuf[NI_MAXHOST];
2741         struct in6_addr in6;
2742         int valid;
2743
2744         p = strchr(name, '.');
2745         if (!p)
2746                 p = name + strlen(name);
2747         l = p - name;
2748         if (l > 63 || l > sizeof(hbuf) - 1)
2749                 return NULL;    /*label too long*/
2750         strncpy(hbuf, name, l);
2751         hbuf[(int)l] = '\0';
2752
2753         for (q = name; *q; q++) {
2754                 if (isupper(*(unsigned char *)q))
2755                         *q = tolower(*(unsigned char *)q);
2756         }
2757
2758         /* generate 16 bytes of pseudo-random value. */
2759         memset(&ctxt, 0, sizeof(ctxt));
2760         MD5Init(&ctxt);
2761         c = l & 0xff;
2762         MD5Update(&ctxt, &c, sizeof(c));
2763         MD5Update(&ctxt, (unsigned char *)name, l);
2764         MD5Final(digest, &ctxt);
2765
2766         if (nig_oldmcprefix) {
2767                 /* draft-ietf-ipngwg-icmp-name-lookup */
2768                 valid = inet_pton(AF_INET6, "ff02::2:0000:0000", &in6);
2769         } else {
2770                 /* RFC 4620 */
2771                 valid = inet_pton(AF_INET6, "ff02::2:ff00:0000", &in6);
2772         }
2773         if (valid != 1)
2774                 return NULL;    /*XXX*/
2775         
2776         if (nig_oldmcprefix) {
2777                 /* draft-ietf-ipngwg-icmp-name-lookup */
2778                 bcopy(digest, &in6.s6_addr[12], 4);
2779         } else {
2780                 /* RFC 4620 */
2781                 bcopy(digest, &in6.s6_addr[13], 3);
2782         }
2783
2784         if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL)
2785                 return NULL;
2786
2787         return strdup(hbuf);
2788 }
2789
2790 void
2791 usage(void)
2792 {
2793         (void)fprintf(stderr,
2794 #if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
2795             "A"
2796 #endif
2797             "usage: ping6 [-"
2798             "Dd"
2799 #if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
2800             "E"
2801 #endif
2802             "fH"
2803 #ifdef IPV6_USE_MIN_MTU
2804             "m"
2805 #endif
2806             "nNoqrRtvwW] "
2807             "[-a addrtype] [-b bufsiz] [-c count] [-g gateway]\n"
2808             "             [-h hoplimit] [-I interface] [-i wait] [-l preload]"
2809 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
2810             " [-P policy]"
2811 #endif
2812             "\n"
2813             "             [-p pattern] [-S sourceaddr] [-s packetsize] "
2814             "[hops ...] host\n");
2815         exit(1);
2816 }