1 /* $KAME: ping6.c,v 1.169 2003/07/25 06:01:47 itojun Exp $ */
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
31 * @(#) Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
32 * @(#)ping.c 8.1 (Berkeley) 6/5/93
33 * $FreeBSD: src/sbin/ping6/ping6.c,v 1.30 2007/04/19 15:41:00 mtm Exp $
36 /* BSDI ping.c,v 2.3 1996/01/21 17:56:50 jch Exp */
39 * Copyright (c) 1989, 1993
40 * The Regents of the University of California. All rights reserved.
42 * This code is derived from software contributed to Berkeley by
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions
48 * 1. Redistributions of source code must retain the above copyright
49 * notice, this list of conditions and the following disclaimer.
50 * 2. Redistributions in binary form must reproduce the above copyright
51 * notice, this list of conditions and the following disclaimer in the
52 * documentation and/or other materials provided with the distribution.
53 * 3. 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.
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
71 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
72 * measure round-trip-delays and packet loss across network paths.
76 * U. S. Army Ballistic Research Laboratory
80 * Public Domain. Distribution Unlimited.
82 * More statistics could always be gathered.
83 * This program has to run SUID to ROOT to access the ICMP socket.
87 * USE_SIN6_SCOPE_ID assumes that sin6_scope_id has the same semantics
88 * as IPV6_PKTINFO. Some people object it (sin6_scope_id specifies *link*
89 * while IPV6_PKTINFO specifies *interface*. Link is defined as collection of
90 * network attached to 1 or more interfaces)
93 #include <sys/param.h>
95 #include <sys/socket.h>
99 #include <net/route.h>
101 #include <netinet/in.h>
102 #include <netinet/ip6.h>
103 #include <netinet/icmp6.h>
104 #include <arpa/inet.h>
105 #include <arpa/nameser.h>
122 #include <openssl/md5.h>
129 #define MAXPACKETLEN 131072
131 #define ICMP6ECHOLEN 8 /* icmp echo header len excluding time */
132 #define ICMP6ECHOTMLEN sizeof(struct tv32)
133 #define ICMP6_NIQLEN (ICMP6ECHOLEN + 8)
134 #define CONTROLLEN 10240 /* ancillary data buffer size RFC3542 20.1 */
135 /* FQDN case, 64 bits of nonce + 32 bits ttl */
136 #define ICMP6_NIRLEN (ICMP6ECHOLEN + 12)
137 #define EXTRA 256 /* for AH and various other headers. weird. */
138 #define DEFDATALEN ICMP6ECHOTMLEN
139 #define MAXDATALEN MAXPACKETLEN - IP6LEN - ICMP6ECHOLEN
140 #define NROUTES 9 /* number of record route slots */
142 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
143 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
144 #define SET(bit) (A(bit) |= B(bit))
145 #define CLR(bit) (A(bit) &= (~B(bit)))
146 #define TST(bit) (A(bit) & B(bit))
148 #define F_FLOOD 0x0001
149 #define F_INTERVAL 0x0002
150 #define F_PINGFILLED 0x0008
151 #define F_QUIET 0x0010
152 #define F_RROUTE 0x0020
153 #define F_SO_DEBUG 0x0040
154 #define F_VERBOSE 0x0100
155 #define F_NODEADDR 0x0800
156 #define F_FQDN 0x1000
157 #define F_INTERFACE 0x2000
158 #define F_SRCADDR 0x4000
159 #define F_HOSTNAME 0x10000
160 #define F_FQDNOLD 0x20000
161 #define F_NIGROUP 0x40000
162 #define F_SUPTYPES 0x80000
163 #define F_NOMINMTU 0x100000
164 #define F_NOUSERDATA (F_NODEADDR | F_FQDN | F_FQDNOLD | F_SUPTYPES)
167 #define IN6LEN sizeof(struct in6_addr)
168 #define SA6LEN sizeof(struct sockaddr_in6)
169 #define DUMMY_PORT 10101
171 #define SIN6(s) ((struct sockaddr_in6 *)(s))
174 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
175 * number of received sequence numbers we can keep track of. Change 128
176 * to 8192 for complete accuracy...
178 #define MAX_DUP_CHK (8 * 8192)
179 int mx_dup_ck = MAX_DUP_CHK;
180 char rcvd_tbl[MAX_DUP_CHK / 8];
182 struct addrinfo *res;
183 struct sockaddr_in6 dst; /* who to ping6 */
184 struct sockaddr_in6 src; /* src addr of this packet */
186 int datalen = DEFDATALEN;
187 int s; /* socket file descriptor */
188 u_char outpack[MAXPACKETLEN];
189 char BSPACE = '\b'; /* characters written for flood */
192 int ident; /* process id to identify our packets */
193 u_int8_t nonce[8]; /* nonce field for node information */
194 int hoplimit = -1; /* hoplimit */
195 int pathmtu = 0; /* path MTU for the destination. 0 = unspec. */
198 long npackets; /* max packets to transmit */
199 long nreceived; /* # of packets we got back */
200 long nrepeats; /* number of duplicates */
201 long ntransmitted; /* sequence # for outbound packets = #sent */
202 struct timeval interval = {1, 0}; /* interval between packets */
205 int timing; /* flag to do timing */
206 double tmin = 999999999.0; /* minimum round trip time */
207 double tmax = 0.0; /* maximum round trip time */
208 double tsum = 0.0; /* sum of all times, for doing average */
209 double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
211 /* for node addresses */
214 /* for ancillary data(advanced API) */
215 struct msghdr smsghdr;
216 struct iovec smsgiov;
219 volatile sig_atomic_t seenalrm;
220 volatile sig_atomic_t seenint;
222 volatile sig_atomic_t seeninfo;
225 void fill(char *, char *);
226 int get_hoplim(struct msghdr *);
227 #ifdef IPV6_RECVPATHMTU
228 int get_pathmtu(struct msghdr *);
230 #define get_pathmtu(mhdr) (0)
232 struct in6_pktinfo *get_rcvpktinfo(struct msghdr *);
234 void retransmit(void);
235 void onint(int) __dead2;
236 size_t pingerlen(void);
238 const char *pr_addr(struct sockaddr *, int);
239 void pr_icmph(struct icmp6_hdr *, u_char *);
240 void pr_iph(struct ip6_hdr *);
241 void pr_suptypes(struct icmp6_nodeinfo *, size_t);
242 void pr_nodeaddr(struct icmp6_nodeinfo *, int);
243 int myechoreply(const struct icmp6_hdr *);
244 int mynireply(const struct icmp6_nodeinfo *);
245 char *dnsdecode(const u_char **, const u_char *, const u_char *,
247 void pr_pack(u_char *, int, struct msghdr *);
248 void pr_exthdrs(struct msghdr *);
249 void pr_ip6opt(void *, size_t);
250 void pr_rthdr(void *, size_t);
251 int pr_bitrange(u_int32_t, int, int);
252 void pr_retip(struct ip6_hdr *, u_char *);
254 void tvsub(struct timeval *, struct timeval *);
255 int setpolicy(int, char *);
256 char *nigroup(char *);
257 void usage(void) __dead2;
260 main(int argc, char **argv)
262 struct itimerval itimer;
263 struct sockaddr_in6 from;
264 #ifndef HAVE_ARC4RANDOM
270 struct timeval timeout, *tv;
272 struct addrinfo hints;
274 struct pollfd fdmaskp[1];
280 int ch, hold, packlen, preload, optval, ret_ga;
281 u_char *datap, *packet;
282 char *e, *target, *ifname = NULL, *gateway = NULL;
284 struct cmsghdr *scmsgp = NULL;
286 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
291 struct in6_pktinfo *pktinfo = NULL;
293 struct ip6_rthdr *rthdr = NULL;
295 #ifdef IPV6_USE_MIN_MTU
300 /* just to be sure */
301 memset(&smsghdr, 0, sizeof(smsghdr));
302 memset(&smsgiov, 0, sizeof(smsgiov));
305 datap = &outpack[ICMP6ECHOLEN + ICMP6ECHOTMLEN];
306 while ((ch = getopt(argc, argv, "a:b:c:dfHg:h:I:i:l:mnNp:qS:s:tvwW")) != -1) {
312 options &= ~F_NOUSERDATA;
313 options |= F_NODEADDR;
314 for (cp = optarg; *cp != '\0'; cp++) {
317 naflags |= NI_NODEADDR_FLAG_ALL;
321 naflags |= NI_NODEADDR_FLAG_COMPAT;
325 naflags |= NI_NODEADDR_FLAG_LINKLOCAL;
329 naflags |= NI_NODEADDR_FLAG_SITELOCAL;
333 naflags |= NI_NODEADDR_FLAG_GLOBAL;
335 case 'A': /* experimental. not in the spec */
336 #ifdef NI_NODEADDR_FLAG_ANYCAST
337 naflags |= NI_NODEADDR_FLAG_ANYCAST;
341 "-a A is not supported on the platform");
352 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
355 lsockbufsize = strtoul(optarg, &e, 10);
356 sockbufsize = lsockbufsize;
357 if (errno || !*optarg || *e ||
358 sockbufsize != (long)lsockbufsize)
359 errx(1, "invalid socket buffer size");
362 "-b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported");
366 npackets = strtol(optarg, &e, 10);
367 if (npackets <= 0 || *optarg == '\0' || *e != '\0')
369 "illegal number of packets -- %s", optarg);
372 options |= F_SO_DEBUG;
377 errx(1, "Must be superuser to flood ping");
380 setbuf(stdout, NULL);
386 options |= F_HOSTNAME;
388 case 'h': /* hoplimit */
389 hoplimit = strtol(optarg, &e, 10);
390 if (*optarg == '\0' || *e != '\0')
391 errx(1, "illegal hoplimit %s", optarg);
392 if (255 < hoplimit || hoplimit < -1)
394 "illegal hoplimit -- %s", optarg);
398 options |= F_INTERFACE;
399 #ifndef USE_SIN6_SCOPE_ID
403 case 'i': /* wait between sending packets */
404 intval = strtod(optarg, &e);
405 if (*optarg == '\0' || *e != '\0')
406 errx(1, "illegal timing interval %s", optarg);
407 if (intval < 1 && getuid()) {
408 errx(1, "%s: only root may use interval < 1s",
411 interval.tv_sec = (long)intval;
413 (long)((intval - interval.tv_sec) * 1000000);
414 if (interval.tv_sec < 0)
415 errx(1, "illegal timing interval %s", optarg);
416 /* less than 1/hz does not make sense */
417 if (interval.tv_sec == 0 && interval.tv_usec < 10000) {
418 warnx("too small interval, raised to 0.01");
419 interval.tv_usec = 10000;
421 options |= F_INTERVAL;
426 errx(1, "Must be superuser to preload");
428 preload = strtol(optarg, &e, 10);
429 if (preload < 0 || *optarg == '\0' || *e != '\0')
430 errx(1, "illegal preload value -- %s", optarg);
433 #ifdef IPV6_USE_MIN_MTU
437 errx(1, "-%c is not supported on this platform", ch);
441 options &= ~F_HOSTNAME;
444 options |= F_NIGROUP;
446 case 'p': /* fill buffer with user pattern */
447 options |= F_PINGFILLED;
448 fill((char *)datap, optarg);
454 memset(&hints, 0, sizeof(struct addrinfo));
455 hints.ai_flags = AI_NUMERICHOST; /* allow hostname? */
456 hints.ai_family = AF_INET6;
457 hints.ai_socktype = SOCK_RAW;
458 hints.ai_protocol = IPPROTO_ICMPV6;
460 ret_ga = getaddrinfo(optarg, NULL, &hints, &res);
462 errx(1, "invalid source address: %s",
463 gai_strerror(ret_ga));
466 * res->ai_family must be AF_INET6 and res->ai_addrlen
467 * must be sizeof(src).
469 memcpy(&src, res->ai_addr, res->ai_addrlen);
470 srclen = res->ai_addrlen;
472 options |= F_SRCADDR;
474 case 's': /* size of packet to send */
475 datalen = strtol(optarg, &e, 10);
476 if (datalen <= 0 || *optarg == '\0' || *e != '\0')
477 errx(1, "illegal datalen value -- %s", optarg);
478 if (datalen > MAXDATALEN) {
480 "datalen value too large, maximum is %d",
485 options &= ~F_NOUSERDATA;
486 options |= F_SUPTYPES;
489 options |= F_VERBOSE;
492 options &= ~F_NOUSERDATA;
496 options &= ~F_NOUSERDATA;
497 options |= F_FQDNOLD;
513 errx(1, "too many arguments");
517 if (options & F_NIGROUP) {
518 target = nigroup(argv[argc - 1]);
519 if (target == NULL) {
524 target = argv[argc - 1];
527 memset(&hints, 0, sizeof(struct addrinfo));
528 hints.ai_flags = AI_CANONNAME;
529 hints.ai_family = AF_INET6;
530 hints.ai_socktype = SOCK_RAW;
531 hints.ai_protocol = IPPROTO_ICMPV6;
533 ret_ga = getaddrinfo(target, NULL, &hints, &res);
535 errx(1, "%s", gai_strerror(ret_ga));
536 if (res->ai_canonname)
537 hostname = res->ai_canonname;
542 errx(1, "getaddrinfo failed");
544 memcpy(&dst, res->ai_addr, res->ai_addrlen);
546 if ((s = socket(res->ai_family, res->ai_socktype,
547 res->ai_protocol)) < 0)
550 /* set the source address if specified. */
551 if ((options & F_SRCADDR) &&
552 bind(s, (struct sockaddr *)&src, srclen) != 0) {
556 /* set the gateway (next hop) if specified */
558 struct addrinfo ghints, *gres;
561 memset(&ghints, 0, sizeof(ghints));
562 ghints.ai_family = AF_INET6;
563 ghints.ai_socktype = SOCK_RAW;
564 ghints.ai_protocol = IPPROTO_ICMPV6;
566 error = getaddrinfo(gateway, NULL, &hints, &gres);
568 errx(1, "getaddrinfo for the gateway %s: %s",
569 gateway, gai_strerror(error));
571 if (gres->ai_next && (options & F_VERBOSE))
572 warnx("gateway resolves to multiple addresses");
574 if (setsockopt(s, IPPROTO_IPV6, IPV6_NEXTHOP,
575 gres->ai_addr, gres->ai_addrlen)) {
576 err(1, "setsockopt(IPV6_NEXTHOP)");
583 * let the kerel pass extension headers of incoming packets,
584 * for privileged socket options
586 if ((options & F_VERBOSE) != 0) {
589 #ifdef IPV6_RECVHOPOPTS
590 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &opton,
592 err(1, "setsockopt(IPV6_RECVHOPOPTS)");
593 #else /* old adv. API */
594 if (setsockopt(s, IPPROTO_IPV6, IPV6_HOPOPTS, &opton,
596 err(1, "setsockopt(IPV6_HOPOPTS)");
598 #ifdef IPV6_RECVDSTOPTS
599 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &opton,
601 err(1, "setsockopt(IPV6_RECVDSTOPTS)");
602 #else /* old adv. API */
603 if (setsockopt(s, IPPROTO_IPV6, IPV6_DSTOPTS, &opton,
605 err(1, "setsockopt(IPV6_DSTOPTS)");
607 #ifdef IPV6_RECVRTHDRDSTOPTS
608 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVRTHDRDSTOPTS, &opton,
610 err(1, "setsockopt(IPV6_RECVRTHDRDSTOPTS)");
614 /* revoke root privilege */
618 if ((options & F_FLOOD) && (options & F_INTERVAL))
619 errx(1, "-f and -i incompatible options");
621 if ((options & F_NOUSERDATA) == 0) {
622 if (datalen >= (int)sizeof(struct tv32)) {
623 /* we can time transfer */
627 /* in F_VERBOSE case, we may get non-echoreply packets*/
628 if (options & F_VERBOSE)
629 packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
631 packlen = datalen + IP6LEN + ICMP6ECHOLEN + EXTRA;
633 /* suppress timing for node information query */
636 packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
639 if (!(packet = (u_char *)malloc((u_int)packlen)))
640 err(1, "Unable to allocate packet");
641 if (!(options & F_PINGFILLED))
642 for (i = ICMP6ECHOLEN; i < packlen; ++i)
645 ident = getpid() & 0xFFFF;
646 #ifndef HAVE_ARC4RANDOM
647 gettimeofday(&seed, NULL);
648 srand((unsigned int)(seed.tv_sec ^ seed.tv_usec ^ (long)ident));
649 memset(nonce, 0, sizeof(nonce));
650 for (i = 0; i < (int)sizeof(nonce); i += sizeof(int))
651 *((int *)&nonce[i]) = rand();
653 memset(nonce, 0, sizeof(nonce));
654 for (i = 0; i < (int)sizeof(nonce); i += sizeof(u_int32_t))
655 *((u_int32_t *)&nonce[i]) = arc4random();
660 if (options & F_SO_DEBUG)
661 setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
663 optval = IPV6_DEFHLIM;
664 if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
665 if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
666 &optval, sizeof(optval)) == -1)
667 err(1, "IPV6_MULTICAST_HOPS");
668 #ifdef IPV6_USE_MIN_MTU
670 optval = mflag > 1 ? 0 : 1;
671 if (setsockopt(s, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
672 &optval, sizeof(optval)) == -1)
673 err(1, "setsockopt(IPV6_USE_MIN_MTU)");
675 #ifdef IPV6_RECVPATHMTU
678 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPATHMTU,
679 &optval, sizeof(optval)) == -1)
680 err(1, "setsockopt(IPV6_RECVPATHMTU)");
682 #endif /* IPV6_RECVPATHMTU */
683 #endif /* IPV6_USE_MIN_MTU */
687 struct icmp6_filter filt;
688 if (!(options & F_VERBOSE)) {
689 ICMP6_FILTER_SETBLOCKALL(&filt);
690 if ((options & F_FQDN) || (options & F_FQDNOLD) ||
691 (options & F_NODEADDR) || (options & F_SUPTYPES))
692 ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filt);
694 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
696 ICMP6_FILTER_SETPASSALL(&filt);
698 if (setsockopt(s, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
700 err(1, "setsockopt(ICMP6_FILTER)");
702 #endif /*ICMP6_FILTER*/
704 /* let the kerel pass extension headers of incoming packets */
705 if ((options & F_VERBOSE) != 0) {
708 #ifdef IPV6_RECVRTHDR
709 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVRTHDR, &opton,
711 err(1, "setsockopt(IPV6_RECVRTHDR)");
712 #else /* old adv. API */
713 if (setsockopt(s, IPPROTO_IPV6, IPV6_RTHDR, &opton,
715 err(1, "setsockopt(IPV6_RTHDR)");
721 if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
722 if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
723 &optval, sizeof(optval)) == -1)
724 err(1, "IPV6_MULTICAST_LOOP");
727 /* Specify the outgoing interface and/or the source address */
729 ip6optlen += CMSG_SPACE(sizeof(struct in6_pktinfo));
732 ip6optlen += CMSG_SPACE(sizeof(int));
734 /* set IP6 packet options */
736 if ((scmsg = (char *)malloc(ip6optlen)) == NULL)
737 errx(1, "can't allocate enough memory");
738 smsghdr.msg_control = (caddr_t)scmsg;
739 smsghdr.msg_controllen = ip6optlen;
740 scmsgp = (struct cmsghdr *)scmsg;
743 pktinfo = (struct in6_pktinfo *)(CMSG_DATA(scmsgp));
744 memset(pktinfo, 0, sizeof(*pktinfo));
745 scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
746 scmsgp->cmsg_level = IPPROTO_IPV6;
747 scmsgp->cmsg_type = IPV6_PKTINFO;
748 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
751 /* set the outgoing interface */
753 #ifndef USE_SIN6_SCOPE_ID
754 /* pktinfo must have already been allocated */
755 if ((pktinfo->ipi6_ifindex = if_nametoindex(ifname)) == 0)
756 errx(1, "%s: invalid interface name", ifname);
758 if ((dst.sin6_scope_id = if_nametoindex(ifname)) == 0)
759 errx(1, "%s: invalid interface name", ifname);
762 if (hoplimit != -1) {
763 scmsgp->cmsg_len = CMSG_LEN(sizeof(int));
764 scmsgp->cmsg_level = IPPROTO_IPV6;
765 scmsgp->cmsg_type = IPV6_HOPLIMIT;
766 *(int *)(CMSG_DATA(scmsgp)) = hoplimit;
768 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
771 if (!(options & F_SRCADDR)) {
773 * get the source address. XXX since we revoked the root
774 * privilege, we cannot use a raw socket for this.
777 socklen_t len = sizeof(src);
779 if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
780 err(1, "UDP socket");
782 src.sin6_family = AF_INET6;
783 src.sin6_addr = dst.sin6_addr;
784 src.sin6_port = ntohs(DUMMY_PORT);
785 src.sin6_scope_id = dst.sin6_scope_id;
789 setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTINFO,
790 (void *)pktinfo, sizeof(*pktinfo)))
791 err(1, "UDP setsockopt(IPV6_PKTINFO)");
792 if (hoplimit != -1 &&
793 setsockopt(dummy, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
794 (void *)&hoplimit, sizeof(hoplimit)))
795 err(1, "UDP setsockopt(IPV6_UNICAST_HOPS)");
796 if (hoplimit != -1 &&
797 setsockopt(dummy, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
798 (void *)&hoplimit, sizeof(hoplimit)))
799 err(1, "UDP setsockopt(IPV6_MULTICAST_HOPS)");
801 setsockopt(dummy, IPPROTO_IPV6, IPV6_RTHDR,
802 (void *)rthdr, (rthdr->ip6r_len + 1) << 3))
803 err(1, "UDP setsockopt(IPV6_RTHDR)");
804 #else /* old advanced API */
805 if (smsghdr.msg_control &&
806 setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTOPTIONS,
807 (void *)smsghdr.msg_control, smsghdr.msg_controllen))
808 err(1, "UDP setsockopt(IPV6_PKTOPTIONS)");
811 if (connect(dummy, (struct sockaddr *)&src, len) < 0)
812 err(1, "UDP connect");
814 if (getsockname(dummy, (struct sockaddr *)&src, &len) < 0)
815 err(1, "getsockname");
820 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
822 if (datalen > sockbufsize)
823 warnx("you need -b to increase socket buffer size");
824 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sockbufsize,
825 sizeof(sockbufsize)) < 0)
826 err(1, "setsockopt(SO_SNDBUF)");
827 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &sockbufsize,
828 sizeof(sockbufsize)) < 0)
829 err(1, "setsockopt(SO_RCVBUF)");
832 if (datalen > 8 * 1024) /*XXX*/
833 warnx("you need -b to increase socket buffer size");
835 * When pinging the broadcast address, you can get a lot of
836 * answers. Doing something so evil is useful if you are trying
837 * to stress the ethernet, or just want to fill the arp cache
838 * to get some stuff for /etc/ethers.
841 setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
847 #ifndef USE_SIN6_SCOPE_ID
848 #ifdef IPV6_RECVPKTINFO
849 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO, &optval,
851 warn("setsockopt(IPV6_RECVPKTINFO)"); /* XXX err? */
852 #else /* old adv. API */
853 if (setsockopt(s, IPPROTO_IPV6, IPV6_PKTINFO, &optval,
855 warn("setsockopt(IPV6_PKTINFO)"); /* XXX err? */
857 #endif /* USE_SIN6_SCOPE_ID */
858 #ifdef IPV6_RECVHOPLIMIT
859 if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &optval,
861 warn("setsockopt(IPV6_RECVHOPLIMIT)"); /* XXX err? */
862 #else /* old adv. API */
863 if (setsockopt(s, IPPROTO_IPV6, IPV6_HOPLIMIT, &optval,
865 warn("setsockopt(IPV6_HOPLIMIT)"); /* XXX err? */
868 printf("PING6(%lu=40+8+%lu bytes) ", (unsigned long)(40 + pingerlen()),
869 (unsigned long)(pingerlen() - 8));
870 printf("%s --> ", pr_addr((struct sockaddr *)&src, sizeof(src)));
871 printf("%s\n", pr_addr((struct sockaddr *)&dst, sizeof(dst)));
873 while (preload--) /* Fire off them quickies. */
876 signal(SIGINT, onsignal);
878 signal(SIGINFO, onsignal);
881 if ((options & F_FLOOD) == 0) {
882 signal(SIGALRM, onsignal);
883 itimer.it_interval = interval;
884 itimer.it_value = interval;
885 setitimer(ITIMER_REAL, &itimer, NULL);
886 if (ntransmitted == 0)
891 fdmasks = howmany(s + 1, NFDBITS) * sizeof(fd_mask);
892 if ((fdmaskp = malloc(fdmasks)) == NULL)
896 seenalrm = seenint = 0;
901 /* For control (ancillary) data received from recvmsg() */
902 cm = (struct cmsghdr *)malloc(CONTROLLEN);
910 /* signal handling */
929 if (options & F_FLOOD) {
935 timeout.tv_usec = 10000;
947 fdmaskp[0].events = POLLIN;
948 cc = poll(fdmaskp, 1, timeout);
950 memset(fdmaskp, 0, fdmasks);
952 cc = select(s + 1, fdmaskp, NULL, NULL, tv);
955 if (errno != EINTR) {
967 m.msg_name = (caddr_t)&from;
968 m.msg_namelen = sizeof(from);
969 memset(&iov, 0, sizeof(iov));
970 iov[0].iov_base = (caddr_t)packet;
971 iov[0].iov_len = packlen;
974 memset(cm, 0, CONTROLLEN);
975 m.msg_control = (void *)cm;
976 m.msg_controllen = CONTROLLEN;
978 cc = recvmsg(s, &m, 0);
980 if (errno != EINTR) {
985 } else if (cc == 0) {
989 * receive control messages only. Process the
990 * exceptions (currently the only possiblity is
991 * a path MTU notification.)
993 if ((mtu = get_pathmtu(&m)) > 0) {
994 if ((options & F_VERBOSE) != 0) {
995 printf("new path MTU (%d) is "
1002 * an ICMPv6 message (probably an echoreply) arrived.
1004 pr_pack(packet, cc, &m);
1006 if (npackets && nreceived >= npackets)
1010 exit(nreceived == 0);
1033 * This routine transmits another ping6.
1038 struct itimerval itimer;
1044 * If we're not transmitting any more packets, change the timer
1045 * to wait two round-trip times if we've received any packets or
1046 * ten seconds if we haven't.
1050 itimer.it_value.tv_sec = 2 * tmax / 1000;
1051 if (itimer.it_value.tv_sec == 0)
1052 itimer.it_value.tv_sec = 1;
1054 itimer.it_value.tv_sec = MAXWAIT;
1055 itimer.it_interval.tv_sec = 0;
1056 itimer.it_interval.tv_usec = 0;
1057 itimer.it_value.tv_usec = 0;
1059 signal(SIGALRM, onint);
1060 setitimer(ITIMER_REAL, &itimer, NULL);
1065 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1066 * will be added on by the kernel. The ID field is our UNIX process ID,
1067 * and the sequence number is an ascending integer. The first 8 bytes
1068 * of the data portion are used to hold a UNIX "timeval" struct in VAX
1069 * byte-order, to compute the round-trip time.
1076 if (options & F_FQDN)
1077 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1078 else if (options & F_FQDNOLD)
1080 else if (options & F_NODEADDR)
1081 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1082 else if (options & F_SUPTYPES)
1085 l = ICMP6ECHOLEN + datalen;
1093 struct icmp6_hdr *icp;
1094 struct iovec iov[2];
1096 struct icmp6_nodeinfo *nip;
1099 if (npackets && ntransmitted >= npackets)
1100 return(-1); /* no more transmission */
1102 icp = (struct icmp6_hdr *)outpack;
1103 nip = (struct icmp6_nodeinfo *)outpack;
1104 memset(icp, 0, sizeof(*icp));
1105 icp->icmp6_cksum = 0;
1106 seq = ntransmitted++;
1107 CLR(seq % mx_dup_ck);
1109 if (options & F_FQDN) {
1110 icp->icmp6_type = ICMP6_NI_QUERY;
1111 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1112 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1113 nip->ni_flags = htons(0);
1115 memcpy(nip->icmp6_ni_nonce, nonce,
1116 sizeof(nip->icmp6_ni_nonce));
1117 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1119 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1120 sizeof(dst.sin6_addr));
1121 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1123 } else if (options & F_FQDNOLD) {
1124 /* packet format in 03 draft - no Subject data on queries */
1125 icp->icmp6_type = ICMP6_NI_QUERY;
1126 icp->icmp6_code = 0; /* code field is always 0 */
1127 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1128 nip->ni_flags = htons(0);
1130 memcpy(nip->icmp6_ni_nonce, nonce,
1131 sizeof(nip->icmp6_ni_nonce));
1132 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1136 } else if (options & F_NODEADDR) {
1137 icp->icmp6_type = ICMP6_NI_QUERY;
1138 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1139 nip->ni_qtype = htons(NI_QTYPE_NODEADDR);
1140 nip->ni_flags = naflags;
1142 memcpy(nip->icmp6_ni_nonce, nonce,
1143 sizeof(nip->icmp6_ni_nonce));
1144 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1146 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1147 sizeof(dst.sin6_addr));
1148 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1150 } else if (options & F_SUPTYPES) {
1151 icp->icmp6_type = ICMP6_NI_QUERY;
1152 icp->icmp6_code = ICMP6_NI_SUBJ_FQDN; /*empty*/
1153 nip->ni_qtype = htons(NI_QTYPE_SUPTYPES);
1154 /* we support compressed bitmap */
1155 nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS;
1157 memcpy(nip->icmp6_ni_nonce, nonce,
1158 sizeof(nip->icmp6_ni_nonce));
1159 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1163 icp->icmp6_type = ICMP6_ECHO_REQUEST;
1164 icp->icmp6_code = 0;
1165 icp->icmp6_id = htons(ident);
1166 icp->icmp6_seq = ntohs(seq);
1170 gettimeofday(&tv, NULL);
1171 tv32 = (struct tv32 *)&outpack[ICMP6ECHOLEN];
1172 tv32->tv32_sec = htonl(tv.tv_sec);
1173 tv32->tv32_usec = htonl(tv.tv_usec);
1175 cc = ICMP6ECHOLEN + datalen;
1179 if (pingerlen() != cc)
1180 errx(1, "internal error; length mismatch");
1183 smsghdr.msg_name = (caddr_t)&dst;
1184 smsghdr.msg_namelen = sizeof(dst);
1185 memset(&iov, 0, sizeof(iov));
1186 iov[0].iov_base = (caddr_t)outpack;
1187 iov[0].iov_len = cc;
1188 smsghdr.msg_iov = iov;
1189 smsghdr.msg_iovlen = 1;
1191 i = sendmsg(s, &smsghdr, 0);
1193 if (i < 0 || i != cc) {
1196 printf("ping6: wrote %s %d chars, ret=%d\n", hostname, cc, i);
1198 if (!(options & F_QUIET) && options & F_FLOOD)
1199 write(STDOUT_FILENO, &DOT, 1);
1205 myechoreply(const struct icmp6_hdr *icp)
1207 if (ntohs(icp->icmp6_id) == ident)
1214 mynireply(const struct icmp6_nodeinfo *nip)
1216 if (memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t),
1217 nonce + sizeof(u_int16_t),
1218 sizeof(nonce) - sizeof(u_int16_t)) == 0)
1225 dnsdecode(const u_char **sp, const u_char *ep, const u_char *base, char *buf,
1230 char cresult[MAXDNAME + 1];
1241 if (i == 0 || cp != *sp) {
1242 if (strlcat((char *)buf, ".", bufsiz) >= bufsiz)
1243 return NULL; /*result overrun*/
1249 if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) {
1250 /* DNS compression */
1254 comp = base + (i & 0x3f);
1255 if (dnsdecode(&comp, cp, base, cresult,
1256 sizeof(cresult)) == NULL)
1258 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1259 return NULL; /*result overrun*/
1261 } else if ((i & 0x3f) == i) {
1263 return NULL; /*source overrun*/
1264 while (i-- > 0 && cp < ep) {
1265 l = snprintf(cresult, sizeof(cresult),
1266 isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff);
1267 if (l >= (int)sizeof(cresult) || l < 0)
1269 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1270 return NULL; /*result overrun*/
1274 return NULL; /*invalid label*/
1277 return NULL; /*not terminated*/
1285 * Print out the packet, if it came from us. This logic is necessary
1286 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1287 * which arrive ('tis only fair). This permits multiple copies of this
1288 * program to be run without having intermingled output (or statistics!).
1291 pr_pack(u_char *buf, int cc, struct msghdr *mhdr)
1293 #define safeputc(c) printf((isprint((c)) ? "%c" : "\\%03o"), c)
1294 struct icmp6_hdr *icp;
1295 struct icmp6_nodeinfo *ni;
1298 struct sockaddr *from;
1300 u_char *cp = NULL, *dp, *end = buf + cc;
1301 struct in6_pktinfo *pktinfo = NULL;
1302 struct timeval tv, tp;
1304 double triptime = 0;
1309 char dnsname[MAXDNAME + 1];
1311 gettimeofday(&tv, NULL);
1313 if (!mhdr || !mhdr->msg_name ||
1314 mhdr->msg_namelen != sizeof(struct sockaddr_in6) ||
1315 ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) {
1316 if (options & F_VERBOSE)
1317 warnx("invalid peername");
1320 from = (struct sockaddr *)mhdr->msg_name;
1321 fromlen = mhdr->msg_namelen;
1322 if (cc < (int)sizeof(struct icmp6_hdr)) {
1323 if (options & F_VERBOSE)
1324 warnx("packet too short (%d bytes) from %s", cc,
1325 pr_addr(from, fromlen));
1328 if (((mhdr->msg_flags & MSG_CTRUNC) != 0) &&
1329 (options & F_VERBOSE) != 0)
1330 warnx("some control data discarded, insufficient buffer size");
1331 icp = (struct icmp6_hdr *)buf;
1332 ni = (struct icmp6_nodeinfo *)buf;
1335 if ((hoplim = get_hoplim(mhdr)) == -1) {
1336 warnx("failed to get receiving hop limit");
1339 if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) {
1340 warnx("failed to get receiving packet information");
1344 if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) {
1345 seq = ntohs(icp->icmp6_seq);
1348 tpp = (struct tv32 *)(icp + 1);
1349 tp.tv_sec = ntohl(tpp->tv32_sec);
1350 tp.tv_usec = ntohl(tpp->tv32_usec);
1352 triptime = ((double)tv.tv_sec) * 1000.0 +
1353 ((double)tv.tv_usec) / 1000.0;
1355 tsumsq += triptime * triptime;
1356 if (triptime < tmin)
1358 if (triptime > tmax)
1362 if (TST(seq % mx_dup_ck)) {
1367 SET(seq % mx_dup_ck);
1371 if (options & F_QUIET)
1374 if (options & F_FLOOD)
1375 write(STDOUT_FILENO, &BSPACE, 1);
1377 printf("%d bytes from %s, icmp_seq=%u", cc,
1378 pr_addr(from, fromlen), seq);
1379 printf(" hlim=%d", hoplim);
1380 if ((options & F_VERBOSE) != 0) {
1381 struct sockaddr_in6 dstsa;
1383 memset(&dstsa, 0, sizeof(dstsa));
1384 dstsa.sin6_family = AF_INET6;
1385 dstsa.sin6_len = sizeof(dstsa);
1386 dstsa.sin6_scope_id = pktinfo->ipi6_ifindex;
1387 dstsa.sin6_addr = pktinfo->ipi6_addr;
1389 pr_addr((struct sockaddr *)&dstsa,
1393 printf(" time=%.3f ms", triptime);
1396 /* check the data */
1397 cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1398 dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1399 for (i = 8; cp < end; ++i, ++cp, ++dp) {
1401 printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp);
1406 } else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) {
1407 seq = ntohs(*(u_int16_t *)ni->icmp6_ni_nonce);
1409 if (TST(seq % mx_dup_ck)) {
1414 SET(seq % mx_dup_ck);
1418 if (options & F_QUIET)
1421 printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1423 switch (ntohs(ni->ni_code)) {
1424 case ICMP6_NI_SUCCESS:
1426 case ICMP6_NI_REFUSED:
1427 printf("refused, type 0x%x", ntohs(ni->ni_type));
1429 case ICMP6_NI_UNKNOWN:
1430 printf("unknown, type 0x%x", ntohs(ni->ni_type));
1433 printf("unknown code 0x%x, type 0x%x",
1434 ntohs(ni->ni_code), ntohs(ni->ni_type));
1438 switch (ntohs(ni->ni_qtype)) {
1440 printf("NodeInfo NOOP");
1442 case NI_QTYPE_SUPTYPES:
1443 pr_suptypes(ni, end - (u_char *)ni);
1445 case NI_QTYPE_NODEADDR:
1446 pr_nodeaddr(ni, end - (u_char *)ni);
1449 default: /* XXX: for backward compatibility */
1450 cp = (u_char *)ni + ICMP6_NIRLEN;
1451 if (buf[off + ICMP6_NIRLEN] ==
1452 cc - off - ICMP6_NIRLEN - 1)
1457 cp++; /* skip length */
1459 safeputc(*cp & 0xff);
1465 if (dnsdecode((const u_char **)(uintptr_t)&cp, end,
1466 (const u_char *)(ni + 1), dnsname,
1467 sizeof(dnsname)) == NULL) {
1472 * name-lookup special handling for
1475 if (cp + 1 <= end && !*cp &&
1476 strlen(dnsname) > 0) {
1477 dnsname[strlen(dnsname) - 1] = '\0';
1480 printf("%s%s", i > 0 ? "," : "",
1484 if (options & F_VERBOSE) {
1490 switch (ni->ni_code) {
1491 case ICMP6_NI_REFUSED:
1495 case ICMP6_NI_UNKNOWN:
1496 printf("unknown qtype");
1501 if ((end - (u_char *)ni) < ICMP6_NIRLEN) {
1502 /* case of refusion, unknown */
1507 ttl = (int32_t)ntohl(*(u_long *)&buf[off+ICMP6ECHOLEN+8]);
1510 if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) {
1511 printf("TTL=%d:meaningless",
1515 printf("TTL=%d:invalid", ttl);
1517 printf("TTL=%d", ttl);
1527 cp = (u_char *)ni + ICMP6_NIRLEN;
1536 if (buf[off + ICMP6_NIRLEN] !=
1537 cc - off - ICMP6_NIRLEN - 1 && oldfqdn) {
1540 printf("invalid namelen:%d/%lu",
1541 buf[off + ICMP6_NIRLEN],
1542 (u_long)cc - off - ICMP6_NIRLEN - 1);
1552 /* We've got something other than an ECHOREPLY */
1553 if (!(options & F_VERBOSE))
1555 printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1559 if (!(options & F_FLOOD)) {
1561 if (options & F_VERBOSE)
1569 pr_exthdrs(struct msghdr *mhdr)
1576 bufp = mhdr->msg_control;
1577 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1578 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1579 if (cm->cmsg_level != IPPROTO_IPV6)
1582 bufsize = CONTROLLEN - ((caddr_t)CMSG_DATA(cm) - (caddr_t)bufp);
1585 switch (cm->cmsg_type) {
1587 printf(" HbH Options: ");
1588 pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1591 #ifdef IPV6_RTHDRDSTOPTS
1592 case IPV6_RTHDRDSTOPTS:
1594 printf(" Dst Options: ");
1595 pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1598 printf(" Routing: ");
1599 pr_rthdr(CMSG_DATA(cm), (size_t)bufsize);
1607 pr_ip6opt(void *extbuf, size_t bufsize)
1609 struct ip6_hbh *ext;
1612 socklen_t extlen, len;
1618 ext = (struct ip6_hbh *)extbuf;
1619 extlen = (ext->ip6h_len + 1) * 8;
1620 printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt,
1621 (unsigned int)ext->ip6h_len, (unsigned long)extlen);
1624 * Bounds checking on the ancillary data buffer:
1625 * subtract the size of a cmsg structure from the buffer size.
1627 if (bufsize < (extlen + CMSG_SPACE(0))) {
1628 extlen = bufsize - CMSG_SPACE(0);
1629 warnx("options truncated, showing only %u (total=%u)",
1630 (unsigned int)(extlen / 8 - 1),
1631 (unsigned int)(ext->ip6h_len));
1636 currentlen = inet6_opt_next(extbuf, extlen, currentlen,
1637 &type, &len, &databuf);
1638 if (currentlen == -1)
1642 * Note that inet6_opt_next automatically skips any padding
1647 offset = inet6_opt_get_val(databuf, offset,
1648 &value4, sizeof(value4));
1649 printf(" Jumbo Payload Opt: Length %u\n",
1650 (u_int32_t)ntohl(value4));
1652 /* FIXME: RFC3542 option is IP6OPT_ROUTER_ALERT. */
1653 case IP6OPT_RTALERT:
1655 offset = inet6_opt_get_val(databuf, offset,
1656 &value2, sizeof(value2));
1657 printf(" Router Alert Opt: Type %u\n",
1661 printf(" Received Opt %u len %lu\n",
1662 type, (unsigned long)len);
1668 #else /* !USE_RFC3542 */
1671 pr_ip6opt(void *extbuf __unused, size_t bufsize __unused)
1676 #endif /* USE_RFC3542 */
1680 pr_rthdr(void *extbuf, size_t bufsize __unused)
1682 struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf;
1684 /* print fixed part of the header */
1685 printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt,
1686 rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type);
1687 printf("segments unknown, ");
1688 printf("%d left\n", rh->ip6r_segleft);
1693 #else /* !USE_RFC3542 */
1696 pr_rthdr(void *extbuf __unused)
1701 #endif /* USE_RFC3542 */
1704 pr_bitrange(u_int32_t v, int soff, int ii)
1711 /* shift till we have 0x01 */
1712 if ((v & 0x01) == 0) {
1714 printf("-%u", soff + off - 1);
1725 case 0x04: case 0x0c:
1736 /* we have 0x01 with us */
1737 for (i = 0; i < 32 - off; i++) {
1738 if ((v & (0x01 << i)) == 0)
1742 printf(" %u", soff + off);
1749 /* struct icmp6_nodeinfo *ni: ni->qtype must be SUPTYPES */
1751 pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen)
1755 const u_char *cp, *end;
1758 u_int16_t words; /*32bit count*/
1761 #define MAXQTYPES (1 << 16)
1765 cp = (u_char *)(ni + 1);
1766 end = ((u_char *)ni) + nilen;
1770 printf("NodeInfo Supported Qtypes");
1771 if (options & F_VERBOSE) {
1772 if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS)
1773 printf(", compressed bitmap");
1775 printf(", raw bitmap");
1779 clen = (size_t)(end - cp);
1780 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) {
1781 if (clen == 0 || clen > MAXQTYPES / 8 ||
1787 if (clen < sizeof(cbit) || clen % sizeof(v))
1789 memcpy(&cbit, cp, sizeof(cbit));
1790 if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) >
1794 clen = ntohs(cbit.words) * sizeof(v);
1795 if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 >
1800 for (off = 0; off < clen; off += sizeof(v)) {
1801 memcpy(&v, cp + off, sizeof(v));
1802 v = (u_int32_t)ntohl(v);
1803 b = pr_bitrange(v, (int)(cur + off * 8), b);
1805 /* flush the remaining bits */
1806 b = pr_bitrange(0, (int)(cur + off * 8), b);
1810 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0)
1811 cur += ntohs(cbit.skip) * 32;
1815 /* struct icmp6_nodeinfo *ni: ni->qtype must be NODEADDR */
1817 pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen)
1819 u_char *cp = (u_char *)(ni + 1);
1820 char ntop_buf[INET6_ADDRSTRLEN];
1823 nilen -= sizeof(struct icmp6_nodeinfo);
1825 if (options & F_VERBOSE) {
1826 switch (ni->ni_code) {
1827 case ICMP6_NI_REFUSED:
1830 case ICMP6_NI_UNKNOWN:
1831 printf("unknown qtype");
1834 if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE)
1835 printf(" truncated");
1839 printf(" no address\n");
1842 * In icmp-name-lookups 05 and later, TTL of each returned address
1843 * is contained in the resposne. We try to detect the version
1844 * by the length of the data, but note that the detection algorithm
1845 * is incomplete. We assume the latest draft by default.
1847 if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0)
1853 /* XXX: alignment? */
1854 ttl = (u_int32_t)ntohl(*(u_int32_t *)cp);
1855 cp += sizeof(u_int32_t);
1856 nilen -= sizeof(u_int32_t);
1859 if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) ==
1861 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
1862 printf(" %s", ntop_buf);
1864 if (ttl == 0xffffffff) {
1866 * XXX: can this convention be applied to all
1867 * type of TTL (i.e. non-ND TTL)?
1869 printf("(TTL=infty)");
1872 printf("(TTL=%u)", ttl);
1876 nilen -= sizeof(struct in6_addr);
1877 cp += sizeof(struct in6_addr);
1882 get_hoplim(struct msghdr *mhdr)
1886 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1887 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1888 if (cm->cmsg_len == 0)
1891 if (cm->cmsg_level == IPPROTO_IPV6 &&
1892 cm->cmsg_type == IPV6_HOPLIMIT &&
1893 cm->cmsg_len == CMSG_LEN(sizeof(int)))
1894 return(*(int *)CMSG_DATA(cm));
1900 struct in6_pktinfo *
1901 get_rcvpktinfo(struct msghdr *mhdr)
1905 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1906 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1907 if (cm->cmsg_len == 0)
1910 if (cm->cmsg_level == IPPROTO_IPV6 &&
1911 cm->cmsg_type == IPV6_PKTINFO &&
1912 cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo)))
1913 return((struct in6_pktinfo *)CMSG_DATA(cm));
1919 #ifdef IPV6_RECVPATHMTU
1921 get_pathmtu(struct msghdr *mhdr)
1924 struct ip6_mtuinfo *mtuctl = NULL;
1926 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1927 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1928 if (cm->cmsg_len == 0)
1931 if (cm->cmsg_level == IPPROTO_IPV6 &&
1932 cm->cmsg_type == IPV6_PATHMTU &&
1933 cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) {
1934 mtuctl = (struct ip6_mtuinfo *)CMSG_DATA(cm);
1937 * If the notified destination is different from
1938 * the one we are pinging, just ignore the info.
1939 * We check the scope ID only when both notified value
1940 * and our own value have non-0 values, because we may
1941 * have used the default scope zone ID for sending,
1942 * in which case the scope ID value is 0.
1944 if (!IN6_ARE_ADDR_EQUAL(&mtuctl->ip6m_addr.sin6_addr,
1946 (mtuctl->ip6m_addr.sin6_scope_id &&
1947 dst.sin6_scope_id &&
1948 mtuctl->ip6m_addr.sin6_scope_id !=
1949 dst.sin6_scope_id)) {
1950 if ((options & F_VERBOSE) != 0) {
1951 printf("path MTU for %s is notified. "
1953 pr_addr((struct sockaddr *)&mtuctl->ip6m_addr,
1954 sizeof(mtuctl->ip6m_addr)));
1960 * Ignore an invalid MTU. XXX: can we just believe
1963 if (mtuctl->ip6m_mtu < IPV6_MMTU)
1966 /* notification for our destination. return the MTU. */
1967 return((int)mtuctl->ip6m_mtu);
1976 * Subtract 2 timeval structs: out = out - in. Out is assumed to
1980 tvsub(struct timeval *out, struct timeval *in)
1982 if ((out->tv_usec -= in->tv_usec) < 0) {
1984 out->tv_usec += 1000000;
1986 out->tv_sec -= in->tv_sec;
1995 onint(int sig __unused)
1999 signal(SIGINT, SIG_DFL);
2000 kill(getpid(), SIGINT);
2008 * Print out statistics.
2014 printf("\n--- %s ping6 statistics ---\n", hostname);
2015 printf("%ld packets transmitted, ", ntransmitted);
2016 printf("%ld packets received, ", nreceived);
2018 printf("+%ld duplicates, ", nrepeats);
2020 if (nreceived > ntransmitted)
2021 printf("-- somebody's duplicating packets!");
2023 printf("%.1f%% packet loss",
2024 ((((double)ntransmitted - nreceived) * 100.0) /
2028 if (nreceived && timing) {
2029 /* Only display average to microseconds */
2030 double num = nreceived + nrepeats;
2031 double avg = tsum / num;
2032 double dev = sqrt(tsumsq / num - avg * avg);
2034 "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
2035 tmin, avg, tmax, dev);
2042 static const char *niqcode[] = {
2044 "DNS label", /*or empty*/
2049 static const char *nircode[] = {
2050 "Success", "Refused", "Unknown",
2056 * Print a descriptive string about an ICMP header.
2059 pr_icmph(struct icmp6_hdr *icp, u_char *end)
2061 char ntop_buf[INET6_ADDRSTRLEN];
2062 struct nd_redirect *red;
2063 struct icmp6_nodeinfo *ni;
2064 char dnsname[MAXDNAME + 1];
2068 switch (icp->icmp6_type) {
2069 case ICMP6_DST_UNREACH:
2070 switch (icp->icmp6_code) {
2071 case ICMP6_DST_UNREACH_NOROUTE:
2072 printf("No Route to Destination\n");
2074 case ICMP6_DST_UNREACH_ADMIN:
2075 printf("Destination Administratively "
2078 case ICMP6_DST_UNREACH_BEYONDSCOPE:
2079 printf("Destination Unreachable Beyond Scope\n");
2081 case ICMP6_DST_UNREACH_ADDR:
2082 printf("Destination Host Unreachable\n");
2084 case ICMP6_DST_UNREACH_NOPORT:
2085 printf("Destination Port Unreachable\n");
2088 printf("Destination Unreachable, Bad Code: %d\n",
2092 /* Print returned IP header information */
2093 pr_retip((struct ip6_hdr *)(icp + 1), end);
2095 case ICMP6_PACKET_TOO_BIG:
2096 printf("Packet too big mtu = %d\n",
2097 (int)ntohl(icp->icmp6_mtu));
2098 pr_retip((struct ip6_hdr *)(icp + 1), end);
2100 case ICMP6_TIME_EXCEEDED:
2101 switch (icp->icmp6_code) {
2102 case ICMP6_TIME_EXCEED_TRANSIT:
2103 printf("Time to live exceeded\n");
2105 case ICMP6_TIME_EXCEED_REASSEMBLY:
2106 printf("Frag reassembly time exceeded\n");
2109 printf("Time exceeded, Bad Code: %d\n",
2113 pr_retip((struct ip6_hdr *)(icp + 1), end);
2115 case ICMP6_PARAM_PROB:
2116 printf("Parameter problem: ");
2117 switch (icp->icmp6_code) {
2118 case ICMP6_PARAMPROB_HEADER:
2119 printf("Erroneous Header ");
2121 case ICMP6_PARAMPROB_NEXTHEADER:
2122 printf("Unknown Nextheader ");
2124 case ICMP6_PARAMPROB_OPTION:
2125 printf("Unrecognized Option ");
2128 printf("Bad code(%d) ", icp->icmp6_code);
2131 printf("pointer = 0x%02x\n", (u_int32_t)ntohl(icp->icmp6_pptr));
2132 pr_retip((struct ip6_hdr *)(icp + 1), end);
2134 case ICMP6_ECHO_REQUEST:
2135 printf("Echo Request");
2136 /* XXX ID + Seq + Data */
2138 case ICMP6_ECHO_REPLY:
2139 printf("Echo Reply");
2140 /* XXX ID + Seq + Data */
2142 case ICMP6_MEMBERSHIP_QUERY:
2143 printf("Listener Query");
2145 case ICMP6_MEMBERSHIP_REPORT:
2146 printf("Listener Report");
2148 case ICMP6_MEMBERSHIP_REDUCTION:
2149 printf("Listener Done");
2151 case ND_ROUTER_SOLICIT:
2152 printf("Router Solicitation");
2154 case ND_ROUTER_ADVERT:
2155 printf("Router Advertisement");
2157 case ND_NEIGHBOR_SOLICIT:
2158 printf("Neighbor Solicitation");
2160 case ND_NEIGHBOR_ADVERT:
2161 printf("Neighbor Advertisement");
2164 red = (struct nd_redirect *)icp;
2165 printf("Redirect\n");
2166 if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf,
2168 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2169 printf("Destination: %s", ntop_buf);
2170 if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf,
2172 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2173 printf(" New Target: %s", ntop_buf);
2175 case ICMP6_NI_QUERY:
2176 printf("Node Information Query");
2177 /* XXX ID + Seq + Data */
2178 ni = (struct icmp6_nodeinfo *)icp;
2179 l = end - (u_char *)(ni + 1);
2181 switch (ntohs(ni->ni_qtype)) {
2185 case NI_QTYPE_SUPTYPES:
2186 printf("Supported qtypes");
2191 case NI_QTYPE_NODEADDR:
2194 case NI_QTYPE_IPV4ADDR:
2195 printf("IPv4 nodeaddr");
2198 printf("unknown qtype");
2201 if (options & F_VERBOSE) {
2202 switch (ni->ni_code) {
2203 case ICMP6_NI_SUBJ_IPV6:
2204 if (l == sizeof(struct in6_addr) &&
2205 inet_ntop(AF_INET6, ni + 1, ntop_buf,
2206 sizeof(ntop_buf)) != NULL) {
2207 printf(", subject=%s(%s)",
2208 niqcode[ni->ni_code], ntop_buf);
2211 /* backward compat to -W */
2212 printf(", oldfqdn");
2214 printf(", invalid");
2218 case ICMP6_NI_SUBJ_FQDN:
2219 if (end == (u_char *)(ni + 1)) {
2220 printf(", no subject");
2223 printf(", subject=%s", niqcode[ni->ni_code]);
2224 cp = (const u_char *)(ni + 1);
2225 if (dnsdecode(&cp, end, NULL, dnsname,
2226 sizeof(dnsname)) != NULL)
2227 printf("(%s)", dnsname);
2229 printf("(invalid)");
2231 case ICMP6_NI_SUBJ_IPV4:
2232 if (l == sizeof(struct in_addr) &&
2233 inet_ntop(AF_INET, ni + 1, ntop_buf,
2234 sizeof(ntop_buf)) != NULL) {
2235 printf(", subject=%s(%s)",
2236 niqcode[ni->ni_code], ntop_buf);
2238 printf(", invalid");
2241 printf(", invalid");
2246 case ICMP6_NI_REPLY:
2247 printf("Node Information Reply");
2248 /* XXX ID + Seq + Data */
2249 ni = (struct icmp6_nodeinfo *)icp;
2251 switch (ntohs(ni->ni_qtype)) {
2255 case NI_QTYPE_SUPTYPES:
2256 printf("Supported qtypes");
2261 case NI_QTYPE_NODEADDR:
2264 case NI_QTYPE_IPV4ADDR:
2265 printf("IPv4 nodeaddr");
2268 printf("unknown qtype");
2271 if (options & F_VERBOSE) {
2272 if (ni->ni_code > NELEM(nircode))
2273 printf(", invalid");
2275 printf(", %s", nircode[ni->ni_code]);
2279 printf("Bad ICMP type: %d", icp->icmp6_type);
2285 * Print an IP6 header.
2288 pr_iph(struct ip6_hdr *ip6)
2290 u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
2292 char ntop_buf[INET6_ADDRSTRLEN];
2294 tc = *(&ip6->ip6_vfc + 1); /* XXX */
2295 tc = (tc >> 4) & 0x0f;
2296 tc |= (ip6->ip6_vfc << 4);
2298 printf("Vr TC Flow Plen Nxt Hlim\n");
2299 printf(" %1x %02x %05x %04x %02x %02x\n",
2300 (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow),
2301 ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim);
2302 if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf)))
2303 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2304 printf("%s->", ntop_buf);
2305 if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf)))
2306 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2307 printf("%s\n", ntop_buf);
2312 * Return an ascii host address as a dotted quad and optionally with
2316 pr_addr(struct sockaddr *addr, int addrlen)
2318 static char buf[NI_MAXHOST];
2321 if ((options & F_HOSTNAME) == 0)
2322 flag |= NI_NUMERICHOST;
2324 if (getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, flag) == 0)
2332 * Dump some info on a returned (via ICMPv6) IPv6 packet.
2335 pr_retip(struct ip6_hdr *ip6, u_char *end)
2337 u_char *cp = (u_char *)ip6, nh;
2340 if (end - (u_char *)ip6 < (int)sizeof(*ip6)) {
2345 hlen = sizeof(*ip6);
2349 while (end - cp >= 8) {
2351 case IPPROTO_HOPOPTS:
2353 hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3;
2354 nh = ((struct ip6_hbh *)cp)->ip6h_nxt;
2356 case IPPROTO_DSTOPTS:
2358 hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3;
2359 nh = ((struct ip6_dest *)cp)->ip6d_nxt;
2361 case IPPROTO_FRAGMENT:
2363 hlen = sizeof(struct ip6_frag);
2364 nh = ((struct ip6_frag *)cp)->ip6f_nxt;
2366 case IPPROTO_ROUTING:
2368 hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3;
2369 nh = ((struct ip6_rthdr *)cp)->ip6r_nxt;
2371 case IPPROTO_ICMPV6:
2372 printf("ICMP6: type = %d, code = %d\n",
2379 printf("TCP: from port %u, to port %u (decimal)\n",
2380 (*cp * 256 + *(cp + 1)),
2381 (*(cp + 2) * 256 + *(cp + 3)));
2384 printf("UDP: from port %u, to port %u (decimal)\n",
2385 (*cp * 256 + *(cp + 1)),
2386 (*(cp + 2) * 256 + *(cp + 3)));
2389 printf("Unknown Header(%d)\n", nh);
2393 if ((cp += hlen) >= end)
2408 fill(char *bp, char *patp)
2414 for (cp = patp; *cp; cp++)
2416 errx(1, "patterns must be specified as hex digits");
2418 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
2419 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
2420 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
2421 &pat[13], &pat[14], &pat[15]);
2426 kk <= MAXDATALEN - (8 + (int)sizeof(struct tv32) + ii);
2428 for (jj = 0; jj < ii; ++jj)
2429 bp[jj + kk] = pat[jj];
2430 if (!(options & F_QUIET)) {
2431 printf("PATTERN: 0x");
2432 for (jj = 0; jj < ii; ++jj)
2433 printf("%02x", bp[jj] & 0xFF);
2444 u_int8_t digest[16];
2447 char hbuf[NI_MAXHOST];
2448 struct in6_addr in6;
2450 p = strchr(name, '.');
2452 p = name + strlen(name);
2454 if (l > 63 || l > sizeof(hbuf) - 1)
2455 return NULL; /*label too long*/
2456 strncpy(hbuf, name, l);
2457 hbuf[(int)l] = '\0';
2459 for (q = name; *q; q++) {
2460 if (isupper(*(unsigned char *)q))
2461 *q = tolower(*(unsigned char *)q);
2464 /* generate 8 bytes of pseudo-random value. */
2465 memset(&ctxt, 0, sizeof(ctxt));
2468 MD5_Update(&ctxt, &c, sizeof(c));
2469 MD5_Update(&ctxt, (unsigned char *)name, l);
2470 MD5_Final(digest, &ctxt);
2472 if (inet_pton(AF_INET6, "ff02::2:0000:0000", &in6) != 1)
2473 return NULL; /*XXX*/
2474 bcopy(digest, &in6.s6_addr[12], 4);
2476 if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL)
2479 return strdup(hbuf);
2489 #ifdef IPV6_USE_MIN_MTU
2493 "[-a addrtype] [-b bufsiz] [-c count] [-g gateway]\n"
2494 " [-h hoplimit] [-I interface] [-i wait] [-l preload]"
2496 " [-p pattern] [-S sourceaddr] [-s packetsize] "
2497 "[hops ...] host\n");