source: rtems-libbsd/freebsd/sbin/ping6/ping6.c @ 30ff989

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 30ff989 was 30ff989, checked in by Sebastian Huber <sebastian.huber@…>, on 10/31/13 at 09:13:55

PING6(8): Delete unused variable

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