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