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