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