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