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