]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/ping6/ping6.c
Bring down 0.4.5 vendor files and other catchups with the distribution tarball.
[FreeBSD/FreeBSD.git] / sbin / ping6 / ping6.c
1 /*      $KAME: ping6.c,v 1.169 2003/07/25 06:01:47 itojun Exp $ */
2
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 /*      BSDI    ping.c,v 2.3 1996/01/21 17:56:50 jch Exp        */
33
34 /*
35  * Copyright (c) 1989, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * This code is derived from software contributed to Berkeley by
39  * Mike Muuss.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  */
65
66 #ifndef lint
67 static const char copyright[] =
68 "@(#) Copyright (c) 1989, 1993\n\
69         The Regents of the University of California.  All rights reserved.\n";
70 #endif /* not lint */
71
72 #ifndef lint
73 #if 0
74 static char sccsid[] = "@(#)ping.c      8.1 (Berkeley) 6/5/93";
75 #endif
76 #endif /* not lint */
77
78 #include <sys/cdefs.h>
79 __FBSDID("$FreeBSD$");
80
81 /*
82  * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
83  * measure round-trip-delays and packet loss across network paths.
84  *
85  * Author -
86  *      Mike Muuss
87  *      U. S. Army Ballistic Research Laboratory
88  *      December, 1983
89  *
90  * Status -
91  *      Public Domain.  Distribution Unlimited.
92  * Bugs -
93  *      More statistics could always be gathered.
94  *      This program has to run SUID to ROOT to access the ICMP socket.
95  */
96 /*
97  * NOTE:
98  * USE_SIN6_SCOPE_ID assumes that sin6_scope_id has the same semantics
99  * as IPV6_PKTINFO.  Some people object it (sin6_scope_id specifies *link*
100  * while IPV6_PKTINFO specifies *interface*.  Link is defined as collection of
101  * network attached to 1 or more interfaces)
102  */
103
104 #include <sys/param.h>
105 #include <sys/uio.h>
106 #include <sys/socket.h>
107 #include <sys/time.h>
108
109 #include <net/if.h>
110 #include <net/route.h>
111
112 #include <netinet/in.h>
113 #include <netinet/ip6.h>
114 #include <netinet/icmp6.h>
115 #include <arpa/inet.h>
116 #include <arpa/nameser.h>
117 #include <netdb.h>
118
119 #include <ctype.h>
120 #include <err.h>
121 #include <errno.h>
122 #include <fcntl.h>
123 #include <math.h>
124 #include <signal.h>
125 #include <stdio.h>
126 #include <stdlib.h>
127 #include <string.h>
128 #include <sysexits.h>
129 #include <unistd.h>
130
131 #ifdef IPSEC
132 #include <netipsec/ah.h>
133 #include <netipsec/ipsec.h>
134 #endif
135
136 #include <md5.h>
137
138 struct tv32 {
139         u_int32_t tv32_sec;
140         u_int32_t tv32_usec;
141 };
142
143 #define MAXPACKETLEN    131072
144 #define IP6LEN          40
145 #define ICMP6ECHOLEN    8       /* icmp echo header len excluding time */
146 #define ICMP6ECHOTMLEN sizeof(struct tv32)
147 #define ICMP6_NIQLEN    (ICMP6ECHOLEN + 8)
148 # define CONTROLLEN     10240   /* ancillary data buffer size RFC3542 20.1 */
149 /* FQDN case, 64 bits of nonce + 32 bits ttl */
150 #define ICMP6_NIRLEN    (ICMP6ECHOLEN + 12)
151 #define EXTRA           256     /* for AH and various other headers. weird. */
152 #define DEFDATALEN      ICMP6ECHOTMLEN
153 #define MAXDATALEN      MAXPACKETLEN - IP6LEN - ICMP6ECHOLEN
154 #define NROUTES         9               /* number of record route slots */
155 #define MAXWAIT         10000           /* max ms to wait for response */
156 #define MAXALARM        (60 * 60)       /* max seconds for alarm timeout */
157
158 #define A(bit)          rcvd_tbl[(bit)>>3]      /* identify byte in array */
159 #define B(bit)          (1 << ((bit) & 0x07))   /* identify bit in byte */
160 #define SET(bit)        (A(bit) |= B(bit))
161 #define CLR(bit)        (A(bit) &= (~B(bit)))
162 #define TST(bit)        (A(bit) & B(bit))
163
164 #define F_FLOOD         0x0001
165 #define F_INTERVAL      0x0002
166 #define F_PINGFILLED    0x0008
167 #define F_QUIET         0x0010
168 #define F_RROUTE        0x0020
169 #define F_SO_DEBUG      0x0040
170 #define F_VERBOSE       0x0100
171 #ifdef IPSEC
172 #ifdef IPSEC_POLICY_IPSEC
173 #define F_POLICY        0x0400
174 #else
175 #define F_AUTHHDR       0x0200
176 #define F_ENCRYPT       0x0400
177 #endif /*IPSEC_POLICY_IPSEC*/
178 #endif /*IPSEC*/
179 #define F_NODEADDR      0x0800
180 #define F_FQDN          0x1000
181 #define F_INTERFACE     0x2000
182 #define F_SRCADDR       0x4000
183 #define F_HOSTNAME      0x10000
184 #define F_FQDNOLD       0x20000
185 #define F_NIGROUP       0x40000
186 #define F_SUPTYPES      0x80000
187 #define F_NOMINMTU      0x100000
188 #define F_ONCE          0x200000
189 #define F_AUDIBLE       0x400000
190 #define F_MISSED        0x800000
191 #define F_DONTFRAG      0x1000000
192 #define F_NOUSERDATA    (F_NODEADDR | F_FQDN | F_FQDNOLD | F_SUPTYPES)
193 #define F_WAITTIME      0x2000000
194 u_int options;
195
196 #define IN6LEN          sizeof(struct in6_addr)
197 #define SA6LEN          sizeof(struct sockaddr_in6)
198 #define DUMMY_PORT      10101
199
200 #define SIN6(s) ((struct sockaddr_in6 *)(s))
201
202 /*
203  * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
204  * number of received sequence numbers we can keep track of.  Change 128
205  * to 8192 for complete accuracy...
206  */
207 #define MAX_DUP_CHK     (8 * 8192)
208 static int mx_dup_ck = MAX_DUP_CHK;
209 static char rcvd_tbl[MAX_DUP_CHK / 8];
210
211 static struct sockaddr_in6 dst; /* who to ping6 */
212 static struct sockaddr_in6 src; /* src addr of this packet */
213 static socklen_t srclen;
214 static size_t datalen = DEFDATALEN;
215 static int s;                   /* socket file descriptor */
216 static u_char outpack[MAXPACKETLEN];
217 static char BSPACE = '\b';      /* characters written for flood */
218 static char BBELL = '\a';       /* characters written for AUDIBLE */
219 static char DOT = '.';
220 static char *hostname;
221 static int ident;               /* process id to identify our packets */
222 static u_int8_t nonce[8];       /* nonce field for node information */
223 static int hoplimit = -1;       /* hoplimit */
224 static u_char *packet = NULL;
225
226 /* counters */
227 static long nmissedmax;         /* max value of ntransmitted - nreceived - 1 */
228 static long npackets;           /* max packets to transmit */
229 static long nreceived;          /* # of packets we got back */
230 static long nrepeats;           /* number of duplicates */
231 static long ntransmitted;       /* sequence # for outbound packets = #sent */
232 static int interval = 1000;     /* interval between packets in ms */
233 static int waittime = MAXWAIT;  /* timeout for each packet */
234 static long nrcvtimeout = 0;    /* # of packets we got back after waittime */
235
236 /* timing */
237 static int timing;              /* flag to do timing */
238 static double tmin = 999999999.0;       /* minimum round trip time */
239 static double tmax = 0.0;       /* maximum round trip time */
240 static double tsum = 0.0;       /* sum of all times, for doing average */
241 static double tsumsq = 0.0;     /* sum of all times squared, for std. dev. */
242
243 /* for node addresses */
244 static u_short naflags;
245
246 /* for ancillary data(advanced API) */
247 static struct msghdr smsghdr;
248 static struct iovec smsgiov;
249 static char *scmsg = 0;
250
251 static volatile sig_atomic_t seenint;
252 #ifdef SIGINFO
253 static volatile sig_atomic_t seeninfo;
254 #endif
255
256 int      main(int, char *[]);
257 static void      fill(char *, char *);
258 static int       get_hoplim(struct msghdr *);
259 static int       get_pathmtu(struct msghdr *);
260 static struct in6_pktinfo *get_rcvpktinfo(struct msghdr *);
261 static void      onsignal(int);
262 static void      onint(int);
263 static size_t    pingerlen(void);
264 static int       pinger(void);
265 static const char *pr_addr(struct sockaddr *, int);
266 static void      pr_icmph(struct icmp6_hdr *, u_char *);
267 static void      pr_iph(struct ip6_hdr *);
268 static void      pr_suptypes(struct icmp6_nodeinfo *, size_t);
269 static void      pr_nodeaddr(struct icmp6_nodeinfo *, int);
270 static int       myechoreply(const struct icmp6_hdr *);
271 static int       mynireply(const struct icmp6_nodeinfo *);
272 static char *dnsdecode(const u_char **, const u_char *, const u_char *,
273     char *, size_t);
274 static void      pr_pack(u_char *, int, struct msghdr *);
275 static void      pr_exthdrs(struct msghdr *);
276 static void      pr_ip6opt(void *, size_t);
277 static void      pr_rthdr(void *, size_t);
278 static int       pr_bitrange(u_int32_t, int, int);
279 static void      pr_retip(struct ip6_hdr *, u_char *);
280 static void      summary(void);
281 static void      tvsub(struct timeval *, struct timeval *);
282 static int       setpolicy(int, char *);
283 static char     *nigroup(char *, int);
284 static void      usage(void);
285
286 int
287 main(int argc, char *argv[])
288 {
289         struct timeval last, intvl;
290         struct sockaddr_in6 from, *sin6;
291         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                         res = NULL;
519                         options |= F_SRCADDR;
520                         break;
521                 case 's':               /* size of packet to send */
522                         datalen = strtol(optarg, &e, 10);
523                         if (datalen <= 0 || *optarg == '\0' || *e != '\0')
524                                 errx(1, "illegal datalen value -- %s", optarg);
525                         if (datalen > MAXDATALEN) {
526                                 errx(1,
527                                     "datalen value too large, maximum is %d",
528                                     MAXDATALEN);
529                         }
530                         break;
531                 case 't':
532                         options &= ~F_NOUSERDATA;
533                         options |= F_SUPTYPES;
534                         break;
535                 case 'v':
536                         options |= F_VERBOSE;
537                         break;
538                 case 'w':
539                         options &= ~F_NOUSERDATA;
540                         options |= F_FQDN;
541                         break;
542                 case 'W':
543                         options &= ~F_NOUSERDATA;
544                         options |= F_FQDNOLD;
545                         break;
546                 case 'x':
547                         t = strtod(optarg, &e);
548                         if (*e || e == optarg || t > (double)INT_MAX)
549                                 err(EX_USAGE, "invalid timing interval: `%s'",
550                                     optarg);
551                         options |= F_WAITTIME;
552                         waittime = (int)t;
553                         break;
554                 case 'X':
555                         alarmtimeout = strtoul(optarg, &e, 0);
556                         if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
557                                 errx(EX_USAGE, "invalid timeout: `%s'",
558                                     optarg);
559                         if (alarmtimeout > MAXALARM)
560                                 errx(EX_USAGE, "invalid timeout: `%s' > %d",
561                                     optarg, MAXALARM);
562                         alarm((int)alarmtimeout);
563                         break;
564 #ifdef IPSEC
565 #ifdef IPSEC_POLICY_IPSEC
566                 case 'P':
567                         options |= F_POLICY;
568                         if (!strncmp("in", optarg, 2)) {
569                                 if ((policy_in = strdup(optarg)) == NULL)
570                                         errx(1, "strdup");
571                         } else if (!strncmp("out", optarg, 3)) {
572                                 if ((policy_out = strdup(optarg)) == NULL)
573                                         errx(1, "strdup");
574                         } else
575                                 errx(1, "invalid security policy");
576                         break;
577 #else
578                 case 'A':
579                         options |= F_AUTHHDR;
580                         break;
581                 case 'E':
582                         options |= F_ENCRYPT;
583                         break;
584 #endif /*IPSEC_POLICY_IPSEC*/
585 #endif /*IPSEC*/
586                 default:
587                         usage();
588                         /*NOTREACHED*/
589                 }
590         }
591
592         argc -= optind;
593         argv += optind;
594
595         if (argc < 1) {
596                 usage();
597                 /*NOTREACHED*/
598         }
599
600         if (argc > 1) {
601 #ifdef IPV6_RECVRTHDR   /* 2292bis */
602                 rthlen = CMSG_SPACE(inet6_rth_space(IPV6_RTHDR_TYPE_0,
603                     argc - 1));
604 #else  /* RFC2292 */
605                 rthlen = inet6_rthdr_space(IPV6_RTHDR_TYPE_0, argc - 1);
606 #endif
607                 if (rthlen == 0) {
608                         errx(1, "too many intermediate hops");
609                         /*NOTREACHED*/
610                 }
611                 ip6optlen += rthlen;
612         }
613
614         if (options & F_NIGROUP) {
615                 target = nigroup(argv[argc - 1], nig_oldmcprefix);
616                 if (target == NULL) {
617                         usage();
618                         /*NOTREACHED*/
619                 }
620         } else
621                 target = argv[argc - 1];
622
623         /* getaddrinfo */
624         memset(&hints, 0, sizeof(struct addrinfo));
625         hints.ai_flags = AI_CANONNAME;
626         hints.ai_family = AF_INET6;
627         hints.ai_socktype = SOCK_RAW;
628         hints.ai_protocol = IPPROTO_ICMPV6;
629
630         error = getaddrinfo(target, NULL, &hints, &res);
631         if (error)
632                 errx(1, "%s", gai_strerror(error));
633         if (res->ai_canonname)
634                 hostname = res->ai_canonname;
635         else
636                 hostname = target;
637
638         if (!res->ai_addr)
639                 errx(1, "getaddrinfo failed");
640
641         (void)memcpy(&dst, res->ai_addr, res->ai_addrlen);
642
643         if ((s = socket(res->ai_family, res->ai_socktype,
644             res->ai_protocol)) < 0)
645                 err(1, "socket");
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)) == 0)
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)) == 0)
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 (res != NULL)
1212                 freeaddrinfo(res);
1213
1214         if(packet != NULL)
1215                 free(packet);
1216
1217         exit(nreceived == 0 ? 2 : 0);
1218 }
1219
1220 static void
1221 onsignal(int sig)
1222 {
1223
1224         switch (sig) {
1225         case SIGINT:
1226         case SIGALRM:
1227                 seenint++;
1228                 break;
1229 #ifdef SIGINFO
1230         case SIGINFO:
1231                 seeninfo++;
1232                 break;
1233 #endif
1234         }
1235 }
1236
1237 /*
1238  * pinger --
1239  *      Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
1240  * will be added on by the kernel.  The ID field is our UNIX process ID,
1241  * and the sequence number is an ascending integer.  The first 8 bytes
1242  * of the data portion are used to hold a UNIX "timeval" struct in VAX
1243  * byte-order, to compute the round-trip time.
1244  */
1245 static size_t
1246 pingerlen(void)
1247 {
1248         size_t l;
1249
1250         if (options & F_FQDN)
1251                 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1252         else if (options & F_FQDNOLD)
1253                 l = ICMP6_NIQLEN;
1254         else if (options & F_NODEADDR)
1255                 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1256         else if (options & F_SUPTYPES)
1257                 l = ICMP6_NIQLEN;
1258         else
1259                 l = ICMP6ECHOLEN + datalen;
1260
1261         return l;
1262 }
1263
1264 static int
1265 pinger(void)
1266 {
1267         struct icmp6_hdr *icp;
1268         struct iovec iov[2];
1269         int i, cc;
1270         struct icmp6_nodeinfo *nip;
1271         int seq;
1272
1273         if (npackets && ntransmitted >= npackets)
1274                 return(-1);     /* no more transmission */
1275
1276         icp = (struct icmp6_hdr *)outpack;
1277         nip = (struct icmp6_nodeinfo *)outpack;
1278         memset(icp, 0, sizeof(*icp));
1279         icp->icmp6_cksum = 0;
1280         seq = ntransmitted++;
1281         CLR(seq % mx_dup_ck);
1282
1283         if (options & F_FQDN) {
1284                 icp->icmp6_type = ICMP6_NI_QUERY;
1285                 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1286                 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1287                 nip->ni_flags = htons(0);
1288
1289                 memcpy(nip->icmp6_ni_nonce, nonce,
1290                     sizeof(nip->icmp6_ni_nonce));
1291                 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1292
1293                 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1294                     sizeof(dst.sin6_addr));
1295                 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1296                 datalen = 0;
1297         } else if (options & F_FQDNOLD) {
1298                 /* packet format in 03 draft - no Subject data on queries */
1299                 icp->icmp6_type = ICMP6_NI_QUERY;
1300                 icp->icmp6_code = 0;    /* code field is always 0 */
1301                 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1302                 nip->ni_flags = htons(0);
1303
1304                 memcpy(nip->icmp6_ni_nonce, nonce,
1305                     sizeof(nip->icmp6_ni_nonce));
1306                 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1307
1308                 cc = ICMP6_NIQLEN;
1309                 datalen = 0;
1310         } else if (options & F_NODEADDR) {
1311                 icp->icmp6_type = ICMP6_NI_QUERY;
1312                 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1313                 nip->ni_qtype = htons(NI_QTYPE_NODEADDR);
1314                 nip->ni_flags = naflags;
1315
1316                 memcpy(nip->icmp6_ni_nonce, nonce,
1317                     sizeof(nip->icmp6_ni_nonce));
1318                 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1319
1320                 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1321                     sizeof(dst.sin6_addr));
1322                 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1323                 datalen = 0;
1324         } else if (options & F_SUPTYPES) {
1325                 icp->icmp6_type = ICMP6_NI_QUERY;
1326                 icp->icmp6_code = ICMP6_NI_SUBJ_FQDN;   /*empty*/
1327                 nip->ni_qtype = htons(NI_QTYPE_SUPTYPES);
1328                 /* we support compressed bitmap */
1329                 nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS;
1330
1331                 memcpy(nip->icmp6_ni_nonce, nonce,
1332                     sizeof(nip->icmp6_ni_nonce));
1333                 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1334                 cc = ICMP6_NIQLEN;
1335                 datalen = 0;
1336         } else {
1337                 icp->icmp6_type = ICMP6_ECHO_REQUEST;
1338                 icp->icmp6_code = 0;
1339                 icp->icmp6_id = htons(ident);
1340                 icp->icmp6_seq = ntohs(seq);
1341                 if (timing) {
1342                         struct timeval tv;
1343                         struct tv32 *tv32;
1344                         (void)gettimeofday(&tv, NULL);
1345                         tv32 = (struct tv32 *)&outpack[ICMP6ECHOLEN];
1346                         tv32->tv32_sec = htonl(tv.tv_sec);
1347                         tv32->tv32_usec = htonl(tv.tv_usec);
1348                 }
1349                 cc = ICMP6ECHOLEN + datalen;
1350         }
1351
1352 #ifdef DIAGNOSTIC
1353         if (pingerlen() != cc)
1354                 errx(1, "internal error; length mismatch");
1355 #endif
1356
1357         smsghdr.msg_name = (caddr_t)&dst;
1358         smsghdr.msg_namelen = sizeof(dst);
1359         memset(&iov, 0, sizeof(iov));
1360         iov[0].iov_base = (caddr_t)outpack;
1361         iov[0].iov_len = cc;
1362         smsghdr.msg_iov = iov;
1363         smsghdr.msg_iovlen = 1;
1364
1365         i = sendmsg(s, &smsghdr, 0);
1366
1367         if (i < 0 || i != cc)  {
1368                 if (i < 0)
1369                         warn("sendmsg");
1370                 (void)printf("ping6: wrote %s %d chars, ret=%d\n",
1371                     hostname, cc, i);
1372         }
1373         if (!(options & F_QUIET) && options & F_FLOOD)
1374                 (void)write(STDOUT_FILENO, &DOT, 1);
1375
1376         return(0);
1377 }
1378
1379 static int
1380 myechoreply(const struct icmp6_hdr *icp)
1381 {
1382         if (ntohs(icp->icmp6_id) == ident)
1383                 return 1;
1384         else
1385                 return 0;
1386 }
1387
1388 static int
1389 mynireply(const struct icmp6_nodeinfo *nip)
1390 {
1391         if (memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t),
1392             nonce + sizeof(u_int16_t),
1393             sizeof(nonce) - sizeof(u_int16_t)) == 0)
1394                 return 1;
1395         else
1396                 return 0;
1397 }
1398
1399 static char *
1400 dnsdecode(const u_char **sp, const u_char *ep, const u_char *base, char *buf,
1401         size_t bufsiz)
1402         /*base for compressed name*/
1403 {
1404         int i;
1405         const u_char *cp;
1406         char cresult[MAXDNAME + 1];
1407         const u_char *comp;
1408         int l;
1409
1410         cp = *sp;
1411         *buf = '\0';
1412
1413         if (cp >= ep)
1414                 return NULL;
1415         while (cp < ep) {
1416                 i = *cp;
1417                 if (i == 0 || cp != *sp) {
1418                         if (strlcat((char *)buf, ".", bufsiz) >= bufsiz)
1419                                 return NULL;    /*result overrun*/
1420                 }
1421                 if (i == 0)
1422                         break;
1423                 cp++;
1424
1425                 if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) {
1426                         /* DNS compression */
1427                         if (!base)
1428                                 return NULL;
1429
1430                         comp = base + (i & 0x3f);
1431                         if (dnsdecode(&comp, cp, base, cresult,
1432                             sizeof(cresult)) == NULL)
1433                                 return NULL;
1434                         if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1435                                 return NULL;    /*result overrun*/
1436                         break;
1437                 } else if ((i & 0x3f) == i) {
1438                         if (i > ep - cp)
1439                                 return NULL;    /*source overrun*/
1440                         while (i-- > 0 && cp < ep) {
1441                                 l = snprintf(cresult, sizeof(cresult),
1442                                     isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff);
1443                                 if ((size_t)l >= sizeof(cresult) || l < 0)
1444                                         return NULL;
1445                                 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1446                                         return NULL;    /*result overrun*/
1447                                 cp++;
1448                         }
1449                 } else
1450                         return NULL;    /*invalid label*/
1451         }
1452         if (i != 0)
1453                 return NULL;    /*not terminated*/
1454         cp++;
1455         *sp = cp;
1456         return buf;
1457 }
1458
1459 /*
1460  * pr_pack --
1461  *      Print out the packet, if it came from us.  This logic is necessary
1462  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1463  * which arrive ('tis only fair).  This permits multiple copies of this
1464  * program to be run without having intermingled output (or statistics!).
1465  */
1466 static void
1467 pr_pack(u_char *buf, int cc, struct msghdr *mhdr)
1468 {
1469 #define safeputc(c)     printf((isprint((c)) ? "%c" : "\\%03o"), c)
1470         struct icmp6_hdr *icp;
1471         struct icmp6_nodeinfo *ni;
1472         int i;
1473         int hoplim;
1474         struct sockaddr *from;
1475         int fromlen;
1476         u_char *cp = NULL, *dp, *end = buf + cc;
1477         struct in6_pktinfo *pktinfo = NULL;
1478         struct timeval tv, tp;
1479         struct tv32 *tpp;
1480         double triptime = 0;
1481         int dupflag;
1482         size_t off;
1483         int oldfqdn;
1484         u_int16_t seq;
1485         char dnsname[MAXDNAME + 1];
1486
1487         (void)gettimeofday(&tv, NULL);
1488
1489         if (!mhdr || !mhdr->msg_name ||
1490             mhdr->msg_namelen != sizeof(struct sockaddr_in6) ||
1491             ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) {
1492                 if (options & F_VERBOSE)
1493                         warnx("invalid peername");
1494                 return;
1495         }
1496         from = (struct sockaddr *)mhdr->msg_name;
1497         fromlen = mhdr->msg_namelen;
1498         if (cc < (int)sizeof(struct icmp6_hdr)) {
1499                 if (options & F_VERBOSE)
1500                         warnx("packet too short (%d bytes) from %s", cc,
1501                             pr_addr(from, fromlen));
1502                 return;
1503         }
1504         if (((mhdr->msg_flags & MSG_CTRUNC) != 0) &&
1505             (options & F_VERBOSE) != 0)
1506                 warnx("some control data discarded, insufficient buffer size");
1507         icp = (struct icmp6_hdr *)buf;
1508         ni = (struct icmp6_nodeinfo *)buf;
1509         off = 0;
1510
1511         if ((hoplim = get_hoplim(mhdr)) == -1) {
1512                 warnx("failed to get receiving hop limit");
1513                 return;
1514         }
1515         if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) {
1516                 warnx("failed to get receiving packet information");
1517                 return;
1518         }
1519
1520         if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) {
1521                 seq = ntohs(icp->icmp6_seq);
1522                 ++nreceived;
1523                 if (timing) {
1524                         tpp = (struct tv32 *)(icp + 1);
1525                         tp.tv_sec = ntohl(tpp->tv32_sec);
1526                         tp.tv_usec = ntohl(tpp->tv32_usec);
1527                         tvsub(&tv, &tp);
1528                         triptime = ((double)tv.tv_sec) * 1000.0 +
1529                             ((double)tv.tv_usec) / 1000.0;
1530                         tsum += triptime;
1531                         tsumsq += triptime * triptime;
1532                         if (triptime < tmin)
1533                                 tmin = triptime;
1534                         if (triptime > tmax)
1535                                 tmax = triptime;
1536                 }
1537
1538                 if (TST(seq % mx_dup_ck)) {
1539                         ++nrepeats;
1540                         --nreceived;
1541                         dupflag = 1;
1542                 } else {
1543                         SET(seq % mx_dup_ck);
1544                         dupflag = 0;
1545                 }
1546
1547                 if (options & F_QUIET)
1548                         return;
1549
1550                 if (options & F_WAITTIME && triptime > waittime) {
1551                         ++nrcvtimeout;
1552                         return;
1553                 }
1554
1555                 if (options & F_FLOOD)
1556                         (void)write(STDOUT_FILENO, &BSPACE, 1);
1557                 else {
1558                         if (options & F_AUDIBLE)
1559                                 (void)write(STDOUT_FILENO, &BBELL, 1);
1560                         (void)printf("%d bytes from %s, icmp_seq=%u", cc,
1561                             pr_addr(from, fromlen), seq);
1562                         (void)printf(" hlim=%d", hoplim);
1563                         if ((options & F_VERBOSE) != 0) {
1564                                 struct sockaddr_in6 dstsa;
1565
1566                                 memset(&dstsa, 0, sizeof(dstsa));
1567                                 dstsa.sin6_family = AF_INET6;
1568                                 dstsa.sin6_len = sizeof(dstsa);
1569                                 dstsa.sin6_scope_id = pktinfo->ipi6_ifindex;
1570                                 dstsa.sin6_addr = pktinfo->ipi6_addr;
1571                                 (void)printf(" dst=%s",
1572                                     pr_addr((struct sockaddr *)&dstsa,
1573                                     sizeof(dstsa)));
1574                         }
1575                         if (timing)
1576                                 (void)printf(" time=%.3f ms", triptime);
1577                         if (dupflag)
1578                                 (void)printf("(DUP!)");
1579                         /* check the data */
1580                         cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1581                         dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1582                         for (i = 8; cp < end; ++i, ++cp, ++dp) {
1583                                 if (*cp != *dp) {
1584                                         (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp);
1585                                         break;
1586                                 }
1587                         }
1588                 }
1589         } else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) {
1590                 seq = ntohs(*(u_int16_t *)ni->icmp6_ni_nonce);
1591                 ++nreceived;
1592                 if (TST(seq % mx_dup_ck)) {
1593                         ++nrepeats;
1594                         --nreceived;
1595                         dupflag = 1;
1596                 } else {
1597                         SET(seq % mx_dup_ck);
1598                         dupflag = 0;
1599                 }
1600
1601                 if (options & F_QUIET)
1602                         return;
1603
1604                 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1605
1606                 switch (ntohs(ni->ni_code)) {
1607                 case ICMP6_NI_SUCCESS:
1608                         break;
1609                 case ICMP6_NI_REFUSED:
1610                         printf("refused, type 0x%x", ntohs(ni->ni_type));
1611                         goto fqdnend;
1612                 case ICMP6_NI_UNKNOWN:
1613                         printf("unknown, type 0x%x", ntohs(ni->ni_type));
1614                         goto fqdnend;
1615                 default:
1616                         printf("unknown code 0x%x, type 0x%x",
1617                             ntohs(ni->ni_code), ntohs(ni->ni_type));
1618                         goto fqdnend;
1619                 }
1620
1621                 switch (ntohs(ni->ni_qtype)) {
1622                 case NI_QTYPE_NOOP:
1623                         printf("NodeInfo NOOP");
1624                         break;
1625                 case NI_QTYPE_SUPTYPES:
1626                         pr_suptypes(ni, end - (u_char *)ni);
1627                         break;
1628                 case NI_QTYPE_NODEADDR:
1629                         pr_nodeaddr(ni, end - (u_char *)ni);
1630                         break;
1631                 case NI_QTYPE_FQDN:
1632                 default:        /* XXX: for backward compatibility */
1633                         cp = (u_char *)ni + ICMP6_NIRLEN;
1634                         if (buf[off + ICMP6_NIRLEN] ==
1635                             cc - off - ICMP6_NIRLEN - 1)
1636                                 oldfqdn = 1;
1637                         else
1638                                 oldfqdn = 0;
1639                         if (oldfqdn) {
1640                                 cp++;   /* skip length */
1641                                 while (cp < end) {
1642                                         safeputc(*cp & 0xff);
1643                                         cp++;
1644                                 }
1645                         } else {
1646                                 i = 0;
1647                                 while (cp < end) {
1648                                         if (dnsdecode((const u_char **)&cp, end,
1649                                             (const u_char *)(ni + 1), dnsname,
1650                                             sizeof(dnsname)) == NULL) {
1651                                                 printf("???");
1652                                                 break;
1653                                         }
1654                                         /*
1655                                          * name-lookup special handling for
1656                                          * truncated name
1657                                          */
1658                                         if (cp + 1 <= end && !*cp &&
1659                                             strlen(dnsname) > 0) {
1660                                                 dnsname[strlen(dnsname) - 1] = '\0';
1661                                                 cp++;
1662                                         }
1663                                         printf("%s%s", i > 0 ? "," : "",
1664                                             dnsname);
1665                                 }
1666                         }
1667                         if (options & F_VERBOSE) {
1668                                 int32_t ttl;
1669                                 int comma = 0;
1670
1671                                 (void)printf(" (");     /*)*/
1672
1673                                 switch (ni->ni_code) {
1674                                 case ICMP6_NI_REFUSED:
1675                                         (void)printf("refused");
1676                                         comma++;
1677                                         break;
1678                                 case ICMP6_NI_UNKNOWN:
1679                                         (void)printf("unknown qtype");
1680                                         comma++;
1681                                         break;
1682                                 }
1683
1684                                 if ((end - (u_char *)ni) < ICMP6_NIRLEN) {
1685                                         /* case of refusion, unknown */
1686                                         /*(*/
1687                                         putchar(')');
1688                                         goto fqdnend;
1689                                 }
1690                                 ttl = (int32_t)ntohl(*(u_long *)&buf[off+ICMP6ECHOLEN+8]);
1691                                 if (comma)
1692                                         printf(",");
1693                                 if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) {
1694                                         (void)printf("TTL=%d:meaningless",
1695                                             (int)ttl);
1696                                 } else {
1697                                         if (ttl < 0) {
1698                                                 (void)printf("TTL=%d:invalid",
1699                                                    ttl);
1700                                         } else
1701                                                 (void)printf("TTL=%d", ttl);
1702                                 }
1703                                 comma++;
1704
1705                                 if (oldfqdn) {
1706                                         if (comma)
1707                                                 printf(",");
1708                                         printf("03 draft");
1709                                         comma++;
1710                                 } else {
1711                                         cp = (u_char *)ni + ICMP6_NIRLEN;
1712                                         if (cp == end) {
1713                                                 if (comma)
1714                                                         printf(",");
1715                                                 printf("no name");
1716                                                 comma++;
1717                                         }
1718                                 }
1719
1720                                 if (buf[off + ICMP6_NIRLEN] !=
1721                                     cc - off - ICMP6_NIRLEN - 1 && oldfqdn) {
1722                                         if (comma)
1723                                                 printf(",");
1724                                         (void)printf("invalid namelen:%d/%lu",
1725                                             buf[off + ICMP6_NIRLEN],
1726                                             (u_long)cc - off - ICMP6_NIRLEN - 1);
1727                                         comma++;
1728                                 }
1729                                 /*(*/
1730                                 putchar(')');
1731                         }
1732                 fqdnend:
1733                         ;
1734                 }
1735         } else {
1736                 /* We've got something other than an ECHOREPLY */
1737                 if (!(options & F_VERBOSE))
1738                         return;
1739                 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1740                 pr_icmph(icp, end);
1741         }
1742
1743         if (!(options & F_FLOOD)) {
1744                 (void)putchar('\n');
1745                 if (options & F_VERBOSE)
1746                         pr_exthdrs(mhdr);
1747                 (void)fflush(stdout);
1748         }
1749 #undef safeputc
1750 }
1751
1752 static void
1753 pr_exthdrs(struct msghdr *mhdr)
1754 {
1755         ssize_t bufsize;
1756         void    *bufp;
1757         struct cmsghdr *cm;
1758
1759         bufsize = 0;
1760         bufp = mhdr->msg_control;
1761         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1762              cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1763                 if (cm->cmsg_level != IPPROTO_IPV6)
1764                         continue;
1765
1766                 bufsize = CONTROLLEN - ((caddr_t)CMSG_DATA(cm) - (caddr_t)bufp);
1767                 if (bufsize <= 0)
1768                         continue; 
1769                 switch (cm->cmsg_type) {
1770                 case IPV6_HOPOPTS:
1771                         printf("  HbH Options: ");
1772                         pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1773                         break;
1774                 case IPV6_DSTOPTS:
1775 #ifdef IPV6_RTHDRDSTOPTS
1776                 case IPV6_RTHDRDSTOPTS:
1777 #endif
1778                         printf("  Dst Options: ");
1779                         pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1780                         break;
1781                 case IPV6_RTHDR:
1782                         printf("  Routing: ");
1783                         pr_rthdr(CMSG_DATA(cm), (size_t)bufsize);
1784                         break;
1785                 }
1786         }
1787 }
1788
1789 #ifdef USE_RFC2292BIS
1790 static void
1791 pr_ip6opt(void *extbuf, size_t bufsize)
1792 {
1793         struct ip6_hbh *ext;
1794         int currentlen;
1795         u_int8_t type;
1796         socklen_t extlen, len;
1797         void *databuf;
1798         size_t offset;
1799         u_int16_t value2;
1800         u_int32_t value4;
1801
1802         ext = (struct ip6_hbh *)extbuf;
1803         extlen = (ext->ip6h_len + 1) * 8;
1804         printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt,
1805             (unsigned int)ext->ip6h_len, (unsigned long)extlen);
1806
1807         /*
1808          * Bounds checking on the ancillary data buffer:
1809          *     subtract the size of a cmsg structure from the buffer size.
1810          */
1811         if (bufsize < (extlen  + CMSG_SPACE(0))) {
1812                 extlen = bufsize - CMSG_SPACE(0);
1813                 warnx("options truncated, showing only %u (total=%u)",
1814                     (unsigned int)(extlen / 8 - 1),
1815                     (unsigned int)(ext->ip6h_len));
1816         }
1817
1818         currentlen = 0;
1819         while (1) {
1820                 currentlen = inet6_opt_next(extbuf, extlen, currentlen,
1821                     &type, &len, &databuf);
1822                 if (currentlen == -1)
1823                         break;
1824                 switch (type) {
1825                 /*
1826                  * Note that inet6_opt_next automatically skips any padding
1827                  * optins.
1828                  */
1829                 case IP6OPT_JUMBO:
1830                         offset = 0;
1831                         offset = inet6_opt_get_val(databuf, offset,
1832                             &value4, sizeof(value4));
1833                         printf("    Jumbo Payload Opt: Length %u\n",
1834                             (u_int32_t)ntohl(value4));
1835                         break;
1836                 case IP6OPT_ROUTER_ALERT:
1837                         offset = 0;
1838                         offset = inet6_opt_get_val(databuf, offset,
1839                                                    &value2, sizeof(value2));
1840                         printf("    Router Alert Opt: Type %u\n",
1841                             ntohs(value2));
1842                         break;
1843                 default:
1844                         printf("    Received Opt %u len %lu\n",
1845                             type, (unsigned long)len);
1846                         break;
1847                 }
1848         }
1849         return;
1850 }
1851 #else  /* !USE_RFC2292BIS */
1852 /* ARGSUSED */
1853 static void
1854 pr_ip6opt(void *extbuf, size_t bufsize __unused)
1855 {
1856         putchar('\n');
1857         return;
1858 }
1859 #endif /* USE_RFC2292BIS */
1860
1861 #ifdef USE_RFC2292BIS
1862 static void
1863 pr_rthdr(void *extbuf, size_t bufsize)
1864 {
1865         struct in6_addr *in6;
1866         char ntopbuf[INET6_ADDRSTRLEN];
1867         struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf;
1868         int i, segments, origsegs, rthsize, size0, size1;
1869
1870         /* print fixed part of the header */
1871         printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt,
1872             rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type);
1873         if ((segments = inet6_rth_segments(extbuf)) >= 0) {
1874                 printf("%d segments, ", segments);
1875                 printf("%d left\n", rh->ip6r_segleft);
1876         } else {
1877                 printf("segments unknown, ");
1878                 printf("%d left\n", rh->ip6r_segleft);
1879                 return;
1880         }
1881
1882         /*
1883          * Bounds checking on the ancillary data buffer. When calculating
1884          * the number of items to show keep in mind:
1885          *      - The size of the cmsg structure
1886          *      - The size of one segment (the size of a Type 0 routing header)
1887          *      - When dividing add a fudge factor of one in case the
1888          *        dividend is not evenly divisible by the divisor
1889          */
1890         rthsize = (rh->ip6r_len + 1) * 8;
1891         if (bufsize < (rthsize + CMSG_SPACE(0))) {
1892                 origsegs = segments;
1893                 size0 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 0);
1894                 size1 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 1);
1895                 segments -= (rthsize - (bufsize - CMSG_SPACE(0))) /
1896                     (size1 - size0) + 1;
1897                 warnx("segments truncated, showing only %d (total=%d)",
1898                     segments, origsegs);
1899         }
1900
1901         for (i = 0; i < segments; i++) {
1902                 in6 = inet6_rth_getaddr(extbuf, i);
1903                 if (in6 == NULL)
1904                         printf("   [%d]<NULL>\n", i);
1905                 else {
1906                         if (!inet_ntop(AF_INET6, in6, ntopbuf,
1907                             sizeof(ntopbuf)))
1908                                 strlcpy(ntopbuf, "?", sizeof(ntopbuf));
1909                         printf("   [%d]%s\n", i, ntopbuf);
1910                 }
1911         }
1912
1913         return;
1914
1915 }
1916
1917 #else  /* !USE_RFC2292BIS */
1918 /* ARGSUSED */
1919 static void
1920 pr_rthdr(void *extbuf, size_t bufsize __unused)
1921 {
1922         putchar('\n');
1923         return;
1924 }
1925 #endif /* USE_RFC2292BIS */
1926
1927 static int
1928 pr_bitrange(u_int32_t v, int soff, int ii)
1929 {
1930         int off;
1931         int i;
1932
1933         off = 0;
1934         while (off < 32) {
1935                 /* shift till we have 0x01 */
1936                 if ((v & 0x01) == 0) {
1937                         if (ii > 1)
1938                                 printf("-%u", soff + off - 1);
1939                         ii = 0;
1940                         switch (v & 0x0f) {
1941                         case 0x00:
1942                                 v >>= 4;
1943                                 off += 4;
1944                                 continue;
1945                         case 0x08:
1946                                 v >>= 3;
1947                                 off += 3;
1948                                 continue;
1949                         case 0x04: case 0x0c:
1950                                 v >>= 2;
1951                                 off += 2;
1952                                 continue;
1953                         default:
1954                                 v >>= 1;
1955                                 off += 1;
1956                                 continue;
1957                         }
1958                 }
1959
1960                 /* we have 0x01 with us */
1961                 for (i = 0; i < 32 - off; i++) {
1962                         if ((v & (0x01 << i)) == 0)
1963                                 break;
1964                 }
1965                 if (!ii)
1966                         printf(" %u", soff + off);
1967                 ii += i;
1968                 v >>= i; off += i;
1969         }
1970         return ii;
1971 }
1972
1973 static void
1974 pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen)
1975         /* ni->qtype must be SUPTYPES */
1976 {
1977         size_t clen;
1978         u_int32_t v;
1979         const u_char *cp, *end;
1980         u_int16_t cur;
1981         struct cbit {
1982                 u_int16_t words;        /*32bit count*/
1983                 u_int16_t skip;
1984         } cbit;
1985 #define MAXQTYPES       (1 << 16)
1986         size_t off;
1987         int b;
1988
1989         cp = (u_char *)(ni + 1);
1990         end = ((u_char *)ni) + nilen;
1991         cur = 0;
1992         b = 0;
1993
1994         printf("NodeInfo Supported Qtypes");
1995         if (options & F_VERBOSE) {
1996                 if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS)
1997                         printf(", compressed bitmap");
1998                 else
1999                         printf(", raw bitmap");
2000         }
2001
2002         while (cp < end) {
2003                 clen = (size_t)(end - cp);
2004                 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) {
2005                         if (clen == 0 || clen > MAXQTYPES / 8 ||
2006                             clen % sizeof(v)) {
2007                                 printf("???");
2008                                 return;
2009                         }
2010                 } else {
2011                         if (clen < sizeof(cbit) || clen % sizeof(v))
2012                                 return;
2013                         memcpy(&cbit, cp, sizeof(cbit));
2014                         if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) >
2015                             clen)
2016                                 return;
2017                         cp += sizeof(cbit);
2018                         clen = ntohs(cbit.words) * sizeof(v);
2019                         if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 >
2020                             MAXQTYPES)
2021                                 return;
2022                 }
2023
2024                 for (off = 0; off < clen; off += sizeof(v)) {
2025                         memcpy(&v, cp + off, sizeof(v));
2026                         v = (u_int32_t)ntohl(v);
2027                         b = pr_bitrange(v, (int)(cur + off * 8), b);
2028                 }
2029                 /* flush the remaining bits */
2030                 b = pr_bitrange(0, (int)(cur + off * 8), b);
2031
2032                 cp += clen;
2033                 cur += clen * 8;
2034                 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0)
2035                         cur += ntohs(cbit.skip) * 32;
2036         }
2037 }
2038
2039 static void
2040 pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen)
2041         /* ni->qtype must be NODEADDR */
2042 {
2043         u_char *cp = (u_char *)(ni + 1);
2044         char ntop_buf[INET6_ADDRSTRLEN];
2045         int withttl = 0;
2046
2047         nilen -= sizeof(struct icmp6_nodeinfo);
2048
2049         if (options & F_VERBOSE) {
2050                 switch (ni->ni_code) {
2051                 case ICMP6_NI_REFUSED:
2052                         (void)printf("refused");
2053                         break;
2054                 case ICMP6_NI_UNKNOWN:
2055                         (void)printf("unknown qtype");
2056                         break;
2057                 }
2058                 if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE)
2059                         (void)printf(" truncated");
2060         }
2061         putchar('\n');
2062         if (nilen <= 0)
2063                 printf("  no address\n");
2064
2065         /*
2066          * In icmp-name-lookups 05 and later, TTL of each returned address
2067          * is contained in the resposne. We try to detect the version
2068          * by the length of the data, but note that the detection algorithm
2069          * is incomplete. We assume the latest draft by default.
2070          */
2071         if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0)
2072                 withttl = 1;
2073         while (nilen > 0) {
2074                 u_int32_t ttl;
2075
2076                 if (withttl) {
2077                         /* XXX: alignment? */
2078                         ttl = (u_int32_t)ntohl(*(u_int32_t *)cp);
2079                         cp += sizeof(u_int32_t);
2080                         nilen -= sizeof(u_int32_t);
2081                 }
2082
2083                 if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) ==
2084                     NULL)
2085                         strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2086                 printf("  %s", ntop_buf);
2087                 if (withttl) {
2088                         if (ttl == 0xffffffff) {
2089                                 /*
2090                                  * XXX: can this convention be applied to all
2091                                  * type of TTL (i.e. non-ND TTL)?
2092                                  */
2093                                 printf("(TTL=infty)");
2094                         }
2095                         else
2096                                 printf("(TTL=%u)", ttl);
2097                 }
2098                 putchar('\n');
2099
2100                 nilen -= sizeof(struct in6_addr);
2101                 cp += sizeof(struct in6_addr);
2102         }
2103 }
2104
2105 static int
2106 get_hoplim(struct msghdr *mhdr)
2107 {
2108         struct cmsghdr *cm;
2109
2110         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2111              cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2112                 if (cm->cmsg_len == 0)
2113                         return(-1);
2114
2115                 if (cm->cmsg_level == IPPROTO_IPV6 &&
2116                     cm->cmsg_type == IPV6_HOPLIMIT &&
2117                     cm->cmsg_len == CMSG_LEN(sizeof(int)))
2118                         return(*(int *)CMSG_DATA(cm));
2119         }
2120
2121         return(-1);
2122 }
2123
2124 static struct in6_pktinfo *
2125 get_rcvpktinfo(struct msghdr *mhdr)
2126 {
2127         struct cmsghdr *cm;
2128
2129         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2130              cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2131                 if (cm->cmsg_len == 0)
2132                         return(NULL);
2133
2134                 if (cm->cmsg_level == IPPROTO_IPV6 &&
2135                     cm->cmsg_type == IPV6_PKTINFO &&
2136                     cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo)))
2137                         return((struct in6_pktinfo *)CMSG_DATA(cm));
2138         }
2139
2140         return(NULL);
2141 }
2142
2143 static int
2144 get_pathmtu(struct msghdr *mhdr)
2145 {
2146 #ifdef IPV6_RECVPATHMTU
2147         struct cmsghdr *cm;
2148         struct ip6_mtuinfo *mtuctl = NULL;
2149
2150         for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2151              cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2152                 if (cm->cmsg_len == 0)
2153                         return(0);
2154
2155                 if (cm->cmsg_level == IPPROTO_IPV6 &&
2156                     cm->cmsg_type == IPV6_PATHMTU &&
2157                     cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) {
2158                         mtuctl = (struct ip6_mtuinfo *)CMSG_DATA(cm);
2159
2160                         /*
2161                          * If the notified destination is different from
2162                          * the one we are pinging, just ignore the info.
2163                          * We check the scope ID only when both notified value
2164                          * and our own value have non-0 values, because we may
2165                          * have used the default scope zone ID for sending,
2166                          * in which case the scope ID value is 0.
2167                          */
2168                         if (!IN6_ARE_ADDR_EQUAL(&mtuctl->ip6m_addr.sin6_addr,
2169                                                 &dst.sin6_addr) ||
2170                             (mtuctl->ip6m_addr.sin6_scope_id &&
2171                              dst.sin6_scope_id &&
2172                              mtuctl->ip6m_addr.sin6_scope_id !=
2173                              dst.sin6_scope_id)) {
2174                                 if ((options & F_VERBOSE) != 0) {
2175                                         printf("path MTU for %s is notified. "
2176                                                "(ignored)\n",
2177                                            pr_addr((struct sockaddr *)&mtuctl->ip6m_addr,
2178                                            sizeof(mtuctl->ip6m_addr)));
2179                                 }
2180                                 return(0);
2181                         }
2182
2183                         /*
2184                          * Ignore an invalid MTU. XXX: can we just believe
2185                          * the kernel check?
2186                          */
2187                         if (mtuctl->ip6m_mtu < IPV6_MMTU)
2188                                 return(0);
2189
2190                         /* notification for our destination. return the MTU. */
2191                         return((int)mtuctl->ip6m_mtu);
2192                 }
2193         }
2194 #endif
2195         return(0);
2196 }
2197
2198 /*
2199  * tvsub --
2200  *      Subtract 2 timeval structs:  out = out - in.  Out is assumed to
2201  * be >= in.
2202  */
2203 static void
2204 tvsub(struct timeval *out, struct timeval *in)
2205 {
2206         if ((out->tv_usec -= in->tv_usec) < 0) {
2207                 --out->tv_sec;
2208                 out->tv_usec += 1000000;
2209         }
2210         out->tv_sec -= in->tv_sec;
2211 }
2212
2213 /*
2214  * onint --
2215  *      SIGINT handler.
2216  */
2217 /* ARGSUSED */
2218 static void
2219 onint(int notused __unused)
2220 {
2221         /*
2222          * When doing reverse DNS lookups, the seenint flag might not
2223          * be noticed for a while.  Just exit if we get a second SIGINT.
2224          */
2225         if ((options & F_HOSTNAME) && seenint != 0)
2226                 _exit(nreceived ? 0 : 2);
2227 }
2228
2229 /*
2230  * summary --
2231  *      Print out statistics.
2232  */
2233 static void
2234 summary(void)
2235 {
2236
2237         (void)printf("\n--- %s ping6 statistics ---\n", hostname);
2238         (void)printf("%ld packets transmitted, ", ntransmitted);
2239         (void)printf("%ld packets received, ", nreceived);
2240         if (nrepeats)
2241                 (void)printf("+%ld duplicates, ", nrepeats);
2242         if (ntransmitted) {
2243                 if (nreceived > ntransmitted)
2244                         (void)printf("-- somebody's duplicating packets!");
2245                 else
2246                         (void)printf("%.1f%% packet loss",
2247                             ((((double)ntransmitted - nreceived) * 100.0) /
2248                             ntransmitted));
2249         }
2250         if (nrcvtimeout)
2251                 printf(", %ld packets out of wait time", nrcvtimeout);
2252         (void)putchar('\n');
2253         if (nreceived && timing) {
2254                 /* Only display average to microseconds */
2255                 double num = nreceived + nrepeats;
2256                 double avg = tsum / num;
2257                 double dev = sqrt(tsumsq / num - avg * avg);
2258                 (void)printf(
2259                     "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
2260                     tmin, avg, tmax, dev);
2261                 (void)fflush(stdout);
2262         }
2263         (void)fflush(stdout);
2264 }
2265
2266 /*subject type*/
2267 static const char *niqcode[] = {
2268         "IPv6 address",
2269         "DNS label",    /*or empty*/
2270         "IPv4 address",
2271 };
2272
2273 /*result code*/
2274 static const char *nircode[] = {
2275         "Success", "Refused", "Unknown",
2276 };
2277
2278
2279 /*
2280  * pr_icmph --
2281  *      Print a descriptive string about an ICMP header.
2282  */
2283 static void
2284 pr_icmph(struct icmp6_hdr *icp, u_char *end)
2285 {
2286         char ntop_buf[INET6_ADDRSTRLEN];
2287         struct nd_redirect *red;
2288         struct icmp6_nodeinfo *ni;
2289         char dnsname[MAXDNAME + 1];
2290         const u_char *cp;
2291         size_t l;
2292
2293         switch (icp->icmp6_type) {
2294         case ICMP6_DST_UNREACH:
2295                 switch (icp->icmp6_code) {
2296                 case ICMP6_DST_UNREACH_NOROUTE:
2297                         (void)printf("No Route to Destination\n");
2298                         break;
2299                 case ICMP6_DST_UNREACH_ADMIN:
2300                         (void)printf("Destination Administratively "
2301                             "Unreachable\n");
2302                         break;
2303                 case ICMP6_DST_UNREACH_BEYONDSCOPE:
2304                         (void)printf("Destination Unreachable Beyond Scope\n");
2305                         break;
2306                 case ICMP6_DST_UNREACH_ADDR:
2307                         (void)printf("Destination Host Unreachable\n");
2308                         break;
2309                 case ICMP6_DST_UNREACH_NOPORT:
2310                         (void)printf("Destination Port Unreachable\n");
2311                         break;
2312                 default:
2313                         (void)printf("Destination Unreachable, Bad Code: %d\n",
2314                             icp->icmp6_code);
2315                         break;
2316                 }
2317                 /* Print returned IP header information */
2318                 pr_retip((struct ip6_hdr *)(icp + 1), end);
2319                 break;
2320         case ICMP6_PACKET_TOO_BIG:
2321                 (void)printf("Packet too big mtu = %d\n",
2322                     (int)ntohl(icp->icmp6_mtu));
2323                 pr_retip((struct ip6_hdr *)(icp + 1), end);
2324                 break;
2325         case ICMP6_TIME_EXCEEDED:
2326                 switch (icp->icmp6_code) {
2327                 case ICMP6_TIME_EXCEED_TRANSIT:
2328                         (void)printf("Time to live exceeded\n");
2329                         break;
2330                 case ICMP6_TIME_EXCEED_REASSEMBLY:
2331                         (void)printf("Frag reassembly time exceeded\n");
2332                         break;
2333                 default:
2334                         (void)printf("Time exceeded, Bad Code: %d\n",
2335                             icp->icmp6_code);
2336                         break;
2337                 }
2338                 pr_retip((struct ip6_hdr *)(icp + 1), end);
2339                 break;
2340         case ICMP6_PARAM_PROB:
2341                 (void)printf("Parameter problem: ");
2342                 switch (icp->icmp6_code) {
2343                 case ICMP6_PARAMPROB_HEADER:
2344                         (void)printf("Erroneous Header ");
2345                         break;
2346                 case ICMP6_PARAMPROB_NEXTHEADER:
2347                         (void)printf("Unknown Nextheader ");
2348                         break;
2349                 case ICMP6_PARAMPROB_OPTION:
2350                         (void)printf("Unrecognized Option ");
2351                         break;
2352                 default:
2353                         (void)printf("Bad code(%d) ", icp->icmp6_code);
2354                         break;
2355                 }
2356                 (void)printf("pointer = 0x%02x\n",
2357                     (u_int32_t)ntohl(icp->icmp6_pptr));
2358                 pr_retip((struct ip6_hdr *)(icp + 1), end);
2359                 break;
2360         case ICMP6_ECHO_REQUEST:
2361                 (void)printf("Echo Request");
2362                 /* XXX ID + Seq + Data */
2363                 break;
2364         case ICMP6_ECHO_REPLY:
2365                 (void)printf("Echo Reply");
2366                 /* XXX ID + Seq + Data */
2367                 break;
2368         case ICMP6_MEMBERSHIP_QUERY:
2369                 (void)printf("Listener Query");
2370                 break;
2371         case ICMP6_MEMBERSHIP_REPORT:
2372                 (void)printf("Listener Report");
2373                 break;
2374         case ICMP6_MEMBERSHIP_REDUCTION:
2375                 (void)printf("Listener Done");
2376                 break;
2377         case ND_ROUTER_SOLICIT:
2378                 (void)printf("Router Solicitation");
2379                 break;
2380         case ND_ROUTER_ADVERT:
2381                 (void)printf("Router Advertisement");
2382                 break;
2383         case ND_NEIGHBOR_SOLICIT:
2384                 (void)printf("Neighbor Solicitation");
2385                 break;
2386         case ND_NEIGHBOR_ADVERT:
2387                 (void)printf("Neighbor Advertisement");
2388                 break;
2389         case ND_REDIRECT:
2390                 red = (struct nd_redirect *)icp;
2391                 (void)printf("Redirect\n");
2392                 if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf,
2393                     sizeof(ntop_buf)))
2394                         strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2395                 (void)printf("Destination: %s", ntop_buf);
2396                 if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf,
2397                     sizeof(ntop_buf)))
2398                         strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2399                 (void)printf(" New Target: %s", ntop_buf);
2400                 break;
2401         case ICMP6_NI_QUERY:
2402                 (void)printf("Node Information Query");
2403                 /* XXX ID + Seq + Data */
2404                 ni = (struct icmp6_nodeinfo *)icp;
2405                 l = end - (u_char *)(ni + 1);
2406                 printf(", ");
2407                 switch (ntohs(ni->ni_qtype)) {
2408                 case NI_QTYPE_NOOP:
2409                         (void)printf("NOOP");
2410                         break;
2411                 case NI_QTYPE_SUPTYPES:
2412                         (void)printf("Supported qtypes");
2413                         break;
2414                 case NI_QTYPE_FQDN:
2415                         (void)printf("DNS name");
2416                         break;
2417                 case NI_QTYPE_NODEADDR:
2418                         (void)printf("nodeaddr");
2419                         break;
2420                 case NI_QTYPE_IPV4ADDR:
2421                         (void)printf("IPv4 nodeaddr");
2422                         break;
2423                 default:
2424                         (void)printf("unknown qtype");
2425                         break;
2426                 }
2427                 if (options & F_VERBOSE) {
2428                         switch (ni->ni_code) {
2429                         case ICMP6_NI_SUBJ_IPV6:
2430                                 if (l == sizeof(struct in6_addr) &&
2431                                     inet_ntop(AF_INET6, ni + 1, ntop_buf,
2432                                     sizeof(ntop_buf)) != NULL) {
2433                                         (void)printf(", subject=%s(%s)",
2434                                             niqcode[ni->ni_code], ntop_buf);
2435                                 } else {
2436 #if 1
2437                                         /* backward compat to -W */
2438                                         (void)printf(", oldfqdn");
2439 #else
2440                                         (void)printf(", invalid");
2441 #endif
2442                                 }
2443                                 break;
2444                         case ICMP6_NI_SUBJ_FQDN:
2445                                 if (end == (u_char *)(ni + 1)) {
2446                                         (void)printf(", no subject");
2447                                         break;
2448                                 }
2449                                 printf(", subject=%s", niqcode[ni->ni_code]);
2450                                 cp = (const u_char *)(ni + 1);
2451                                 if (dnsdecode(&cp, end, NULL, dnsname,
2452                                     sizeof(dnsname)) != NULL)
2453                                         printf("(%s)", dnsname);
2454                                 else
2455                                         printf("(invalid)");
2456                                 break;
2457                         case ICMP6_NI_SUBJ_IPV4:
2458                                 if (l == sizeof(struct in_addr) &&
2459                                     inet_ntop(AF_INET, ni + 1, ntop_buf,
2460                                     sizeof(ntop_buf)) != NULL) {
2461                                         (void)printf(", subject=%s(%s)",
2462                                             niqcode[ni->ni_code], ntop_buf);
2463                                 } else
2464                                         (void)printf(", invalid");
2465                                 break;
2466                         default:
2467                                 (void)printf(", invalid");
2468                                 break;
2469                         }
2470                 }
2471                 break;
2472         case ICMP6_NI_REPLY:
2473                 (void)printf("Node Information Reply");
2474                 /* XXX ID + Seq + Data */
2475                 ni = (struct icmp6_nodeinfo *)icp;
2476                 printf(", ");
2477                 switch (ntohs(ni->ni_qtype)) {
2478                 case NI_QTYPE_NOOP:
2479                         (void)printf("NOOP");
2480                         break;
2481                 case NI_QTYPE_SUPTYPES:
2482                         (void)printf("Supported qtypes");
2483                         break;
2484                 case NI_QTYPE_FQDN:
2485                         (void)printf("DNS name");
2486                         break;
2487                 case NI_QTYPE_NODEADDR:
2488                         (void)printf("nodeaddr");
2489                         break;
2490                 case NI_QTYPE_IPV4ADDR:
2491                         (void)printf("IPv4 nodeaddr");
2492                         break;
2493                 default:
2494                         (void)printf("unknown qtype");
2495                         break;
2496                 }
2497                 if (options & F_VERBOSE) {
2498                         if (ni->ni_code > sizeof(nircode) / sizeof(nircode[0]))
2499                                 printf(", invalid");
2500                         else
2501                                 printf(", %s", nircode[ni->ni_code]);
2502                 }
2503                 break;
2504         default:
2505                 (void)printf("Bad ICMP type: %d", icp->icmp6_type);
2506         }
2507 }
2508
2509 /*
2510  * pr_iph --
2511  *      Print an IP6 header.
2512  */
2513 static void
2514 pr_iph(struct ip6_hdr *ip6)
2515 {
2516         u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
2517         u_int8_t tc;
2518         char ntop_buf[INET6_ADDRSTRLEN];
2519
2520         tc = *(&ip6->ip6_vfc + 1); /* XXX */
2521         tc = (tc >> 4) & 0x0f;
2522         tc |= (ip6->ip6_vfc << 4);
2523
2524         printf("Vr TC  Flow Plen Nxt Hlim\n");
2525         printf(" %1x %02x %05x %04x  %02x   %02x\n",
2526             (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow),
2527             ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim);
2528         if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf)))
2529                 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2530         printf("%s->", ntop_buf);
2531         if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf)))
2532                 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2533         printf("%s\n", ntop_buf);
2534 }
2535
2536 /*
2537  * pr_addr --
2538  *      Return an ascii host address as a dotted quad and optionally with
2539  * a hostname.
2540  */
2541 static const char *
2542 pr_addr(struct sockaddr *addr, int addrlen)
2543 {
2544         static char buf[NI_MAXHOST];
2545         int flag = 0;
2546
2547         if ((options & F_HOSTNAME) == 0)
2548                 flag |= NI_NUMERICHOST;
2549
2550         if (getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, flag) == 0)
2551                 return (buf);
2552         else
2553                 return "?";
2554 }
2555
2556 /*
2557  * pr_retip --
2558  *      Dump some info on a returned (via ICMPv6) IPv6 packet.
2559  */
2560 static void
2561 pr_retip(struct ip6_hdr *ip6, u_char *end)
2562 {
2563         u_char *cp = (u_char *)ip6, nh;
2564         int hlen;
2565
2566         if ((size_t)(end - (u_char *)ip6) < sizeof(*ip6)) {
2567                 printf("IP6");
2568                 goto trunc;
2569         }
2570         pr_iph(ip6);
2571         hlen = sizeof(*ip6);
2572
2573         nh = ip6->ip6_nxt;
2574         cp += hlen;
2575         while (end - cp >= 8) {
2576                 switch (nh) {
2577                 case IPPROTO_HOPOPTS:
2578                         printf("HBH ");
2579                         hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3;
2580                         nh = ((struct ip6_hbh *)cp)->ip6h_nxt;
2581                         break;
2582                 case IPPROTO_DSTOPTS:
2583                         printf("DSTOPT ");
2584                         hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3;
2585                         nh = ((struct ip6_dest *)cp)->ip6d_nxt;
2586                         break;
2587                 case IPPROTO_FRAGMENT:
2588                         printf("FRAG ");
2589                         hlen = sizeof(struct ip6_frag);
2590                         nh = ((struct ip6_frag *)cp)->ip6f_nxt;
2591                         break;
2592                 case IPPROTO_ROUTING:
2593                         printf("RTHDR ");
2594                         hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3;
2595                         nh = ((struct ip6_rthdr *)cp)->ip6r_nxt;
2596                         break;
2597 #ifdef IPSEC
2598                 case IPPROTO_AH:
2599                         printf("AH ");
2600                         hlen = (((struct ah *)cp)->ah_len+2) << 2;
2601                         nh = ((struct ah *)cp)->ah_nxt;
2602                         break;
2603 #endif
2604                 case IPPROTO_ICMPV6:
2605                         printf("ICMP6: type = %d, code = %d\n",
2606                             *cp, *(cp + 1));
2607                         return;
2608                 case IPPROTO_ESP:
2609                         printf("ESP\n");
2610                         return;
2611                 case IPPROTO_TCP:
2612                         printf("TCP: from port %u, to port %u (decimal)\n",
2613                             (*cp * 256 + *(cp + 1)),
2614                             (*(cp + 2) * 256 + *(cp + 3)));
2615                         return;
2616                 case IPPROTO_UDP:
2617                         printf("UDP: from port %u, to port %u (decimal)\n",
2618                             (*cp * 256 + *(cp + 1)),
2619                             (*(cp + 2) * 256 + *(cp + 3)));
2620                         return;
2621                 default:
2622                         printf("Unknown Header(%d)\n", nh);
2623                         return;
2624                 }
2625
2626                 if ((cp += hlen) >= end)
2627                         goto trunc;
2628         }
2629         if (end - cp < 8)
2630                 goto trunc;
2631
2632         putchar('\n');
2633         return;
2634
2635   trunc:
2636         printf("...\n");
2637         return;
2638 }
2639
2640 static void
2641 fill(char *bp, char *patp)
2642 {
2643         int ii, jj, kk;
2644         int pat[16];
2645         char *cp;
2646
2647         for (cp = patp; *cp; cp++)
2648                 if (!isxdigit(*cp))
2649                         errx(1, "patterns must be specified as hex digits");
2650         ii = sscanf(patp,
2651             "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
2652             &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
2653             &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
2654             &pat[13], &pat[14], &pat[15]);
2655
2656 /* xxx */
2657         if (ii > 0)
2658                 for (kk = 0;
2659                     (size_t)kk <= MAXDATALEN - 8 + sizeof(struct tv32) + ii;
2660                     kk += ii)
2661                         for (jj = 0; jj < ii; ++jj)
2662                                 bp[jj + kk] = pat[jj];
2663         if (!(options & F_QUIET)) {
2664                 (void)printf("PATTERN: 0x");
2665                 for (jj = 0; jj < ii; ++jj)
2666                         (void)printf("%02x", bp[jj] & 0xFF);
2667                 (void)printf("\n");
2668         }
2669 }
2670
2671 #ifdef IPSEC
2672 #ifdef IPSEC_POLICY_IPSEC
2673 static int
2674 setpolicy(int so __unused, char *policy)
2675 {
2676         char *buf;
2677
2678         if (policy == NULL)
2679                 return 0;       /* ignore */
2680
2681         buf = ipsec_set_policy(policy, strlen(policy));
2682         if (buf == NULL)
2683                 errx(1, "%s", ipsec_strerror());
2684         if (setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, buf,
2685             ipsec_get_policylen(buf)) < 0)
2686                 warnx("Unable to set IPsec policy");
2687         free(buf);
2688
2689         return 0;
2690 }
2691 #endif
2692 #endif
2693
2694 static char *
2695 nigroup(char *name, int nig_oldmcprefix)
2696 {
2697         char *p;
2698         char *q;
2699         MD5_CTX ctxt;
2700         u_int8_t digest[16];
2701         u_int8_t c;
2702         size_t l;
2703         char hbuf[NI_MAXHOST];
2704         struct in6_addr in6;
2705         int valid;
2706
2707         p = strchr(name, '.');
2708         if (!p)
2709                 p = name + strlen(name);
2710         l = p - name;
2711         if (l > 63 || l > sizeof(hbuf) - 1)
2712                 return NULL;    /*label too long*/
2713         strncpy(hbuf, name, l);
2714         hbuf[(int)l] = '\0';
2715
2716         for (q = name; *q; q++) {
2717                 if (isupper(*(unsigned char *)q))
2718                         *q = tolower(*(unsigned char *)q);
2719         }
2720
2721         /* generate 16 bytes of pseudo-random value. */
2722         memset(&ctxt, 0, sizeof(ctxt));
2723         MD5Init(&ctxt);
2724         c = l & 0xff;
2725         MD5Update(&ctxt, &c, sizeof(c));
2726         MD5Update(&ctxt, (unsigned char *)name, l);
2727         MD5Final(digest, &ctxt);
2728
2729         if (nig_oldmcprefix) {
2730                 /* draft-ietf-ipngwg-icmp-name-lookup */
2731                 valid = inet_pton(AF_INET6, "ff02::2:0000:0000", &in6);
2732         } else {
2733                 /* RFC 4620 */
2734                 valid = inet_pton(AF_INET6, "ff02::2:ff00:0000", &in6);
2735         }
2736         if (valid != 1)
2737                 return NULL;    /*XXX*/
2738         
2739         if (nig_oldmcprefix) {
2740                 /* draft-ietf-ipngwg-icmp-name-lookup */
2741                 bcopy(digest, &in6.s6_addr[12], 4);
2742         } else {
2743                 /* RFC 4620 */
2744                 bcopy(digest, &in6.s6_addr[13], 3);
2745         }
2746
2747         if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL)
2748                 return NULL;
2749
2750         return strdup(hbuf);
2751 }
2752
2753 static void
2754 usage(void)
2755 {
2756         (void)fprintf(stderr,
2757 #if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
2758             "A"
2759 #endif
2760             "usage: ping6 [-"
2761             "Dd"
2762 #if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
2763             "E"
2764 #endif
2765             "fH"
2766 #ifdef IPV6_USE_MIN_MTU
2767             "m"
2768 #endif
2769             "nNoqrRtvwW] "
2770             "[-a addrtype] [-b bufsiz] [-c count] [-g gateway]\n"
2771             "             [-h hoplimit] [-I interface] [-i wait] [-l preload]"
2772 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
2773             " [-P policy]"
2774 #endif
2775             "\n"
2776             "             [-p pattern] [-S sourceaddr] [-s packetsize] "
2777             "[-x waittime]\n"
2778             "             [-X timeout] [hops ...] host\n");
2779         exit(1);
2780 }