source: rtems-libbsd/freebsd/sbin/ping6/ping6.c @ 66659ff

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 66659ff was 66659ff, checked in by Sebastian Huber <sebastian.huber@…>, on 11/06/13 at 15:20:21

Update to FreeBSD 9.2

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