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