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