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