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