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