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