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