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