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