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

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

PING6(8): Fix resource leaks

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