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