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