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