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