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