source: rtems-libbsd/freebsd/sbin/ping6/ping6.c @ 4eb2502

55-freebsd-126-freebsd-12
Last change on this file since 4eb2502 was 0237319, checked in by Sebastian Huber <sebastian.huber@…>, on 05/23/17 at 11:18:31

Update due to Newlib 2017-06-07 changes

The following files are now provided by Newlib:

  • arpa/inet.h
  • net/if.h
  • netinet/in.h
  • netinet/tcp.h
  • sys/socket.h
  • sys/uio.h
  • sys/un.h

The <sys/param.h> and <sys/cpuset.h> are now compatible enough to be
used directly.

Update #2833.

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