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