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