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