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