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