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