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