1 /* $KAME: ping6.c,v 1.169 2003/07/25 06:01:47 itojun Exp $ */
4 * SPDX-License-Identifier: BSD-3-Clause
6 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the project nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 /* BSDI ping.c,v 2.3 1996/01/21 17:56:50 jch Exp */
37 * Copyright (c) 1989, 1993
38 * The Regents of the University of California. All rights reserved.
40 * This code is derived from software contributed to Berkeley by
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 static const char copyright[] =
70 "@(#) Copyright (c) 1989, 1993\n\
71 The Regents of the University of California. All rights reserved.\n";
76 static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93";
80 #include <sys/cdefs.h>
81 __FBSDID("$FreeBSD$");
84 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
85 * measure round-trip-delays and packet loss across network paths.
89 * U. S. Army Ballistic Research Laboratory
93 * Public Domain. Distribution Unlimited.
95 * More statistics could always be gathered.
96 * This program has to run SUID to ROOT to access the ICMP socket.
100 * USE_SIN6_SCOPE_ID assumes that sin6_scope_id has the same semantics
101 * as IPV6_PKTINFO. Some people object it (sin6_scope_id specifies *link*
102 * while IPV6_PKTINFO specifies *interface*. Link is defined as collection of
103 * network attached to 1 or more interfaces)
106 #include <sys/param.h>
107 #include <sys/capsicum.h>
109 #include <sys/socket.h>
110 #include <sys/time.h>
113 #include <net/route.h>
115 #include <netinet/in.h>
116 #include <netinet/ip6.h>
117 #include <netinet/icmp6.h>
118 #include <arpa/inet.h>
119 #include <arpa/nameser.h>
122 #include <capsicum_helpers.h>
123 #include <casper/cap_dns.h>
124 #include <libcasper.h>
135 #include <sysexits.h>
139 #include <netipsec/ah.h>
140 #include <netipsec/ipsec.h>
150 #define MAXPACKETLEN 131072
152 #define ICMP6ECHOLEN 8 /* icmp echo header len excluding time */
153 #define ICMP6ECHOTMLEN sizeof(struct tv32)
154 #define ICMP6_NIQLEN (ICMP6ECHOLEN + 8)
155 # define CONTROLLEN 10240 /* ancillary data buffer size RFC3542 20.1 */
156 /* FQDN case, 64 bits of nonce + 32 bits ttl */
157 #define ICMP6_NIRLEN (ICMP6ECHOLEN + 12)
158 #define EXTRA 256 /* for AH and various other headers. weird. */
159 #define DEFDATALEN ICMP6ECHOTMLEN
160 #define MAXDATALEN MAXPACKETLEN - IP6LEN - ICMP6ECHOLEN
161 #define NROUTES 9 /* number of record route slots */
162 #define MAXWAIT 10000 /* max ms to wait for response */
163 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */
165 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
166 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
167 #define SET(bit) (A(bit) |= B(bit))
168 #define CLR(bit) (A(bit) &= (~B(bit)))
169 #define TST(bit) (A(bit) & B(bit))
171 #define F_FLOOD 0x0001
172 #define F_INTERVAL 0x0002
173 #define F_PINGFILLED 0x0008
174 #define F_QUIET 0x0010
175 #define F_RROUTE 0x0020
176 #define F_SO_DEBUG 0x0040
177 #define F_VERBOSE 0x0100
179 #ifdef IPSEC_POLICY_IPSEC
180 #define F_POLICY 0x0400
182 #define F_AUTHHDR 0x0200
183 #define F_ENCRYPT 0x0400
184 #endif /*IPSEC_POLICY_IPSEC*/
186 #define F_NODEADDR 0x0800
187 #define F_FQDN 0x1000
188 #define F_INTERFACE 0x2000
189 #define F_SRCADDR 0x4000
190 #define F_HOSTNAME 0x10000
191 #define F_FQDNOLD 0x20000
192 #define F_NIGROUP 0x40000
193 #define F_SUPTYPES 0x80000
194 #define F_NOMINMTU 0x100000
195 #define F_ONCE 0x200000
196 #define F_AUDIBLE 0x400000
197 #define F_MISSED 0x800000
198 #define F_DONTFRAG 0x1000000
199 #define F_NOUSERDATA (F_NODEADDR | F_FQDN | F_FQDNOLD | F_SUPTYPES)
200 #define F_WAITTIME 0x2000000
201 static u_int options;
203 #define IN6LEN sizeof(struct in6_addr)
204 #define SA6LEN sizeof(struct sockaddr_in6)
205 #define DUMMY_PORT 10101
207 #define SIN6(s) ((struct sockaddr_in6 *)(s))
210 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
211 * number of received sequence numbers we can keep track of. Change 128
212 * to 8192 for complete accuracy...
214 #define MAX_DUP_CHK (8 * 8192)
215 static int mx_dup_ck = MAX_DUP_CHK;
216 static char rcvd_tbl[MAX_DUP_CHK / 8];
218 static struct sockaddr_in6 dst; /* who to ping6 */
219 static struct sockaddr_in6 src; /* src addr of this packet */
220 static socklen_t srclen;
221 static size_t datalen = DEFDATALEN;
222 static int ssend; /* send socket file descriptor */
223 static int srecv; /* receive socket file descriptor */
224 static u_char outpack[MAXPACKETLEN];
225 static char BSPACE = '\b'; /* characters written for flood */
226 static char BBELL = '\a'; /* characters written for AUDIBLE */
227 static char DOT = '.';
228 static char *hostname;
229 static int ident; /* process id to identify our packets */
230 static u_int8_t nonce[8]; /* nonce field for node information */
231 static int hoplimit = -1; /* hoplimit */
232 static u_char *packet = NULL;
233 static cap_channel_t *capdns;
236 static long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
237 static long npackets; /* max packets to transmit */
238 static long nreceived; /* # of packets we got back */
239 static long nrepeats; /* number of duplicates */
240 static long ntransmitted; /* sequence # for outbound packets = #sent */
241 static int interval = 1000; /* interval between packets in ms */
242 static int waittime = MAXWAIT; /* timeout for each packet */
243 static long nrcvtimeout = 0; /* # of packets we got back after waittime */
246 static int timing; /* flag to do timing */
247 static double tmin = 999999999.0; /* minimum round trip time */
248 static double tmax = 0.0; /* maximum round trip time */
249 static double tsum = 0.0; /* sum of all times, for doing average */
250 static double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
252 /* for node addresses */
253 static u_short naflags;
255 /* for ancillary data(advanced API) */
256 static struct msghdr smsghdr;
257 static struct iovec smsgiov;
258 static char *scmsg = 0;
260 static volatile sig_atomic_t seenint;
262 static volatile sig_atomic_t seeninfo;
265 int main(int, char *[]);
266 static cap_channel_t *capdns_setup(void);
267 static void fill(char *, char *);
268 static int get_hoplim(struct msghdr *);
269 static int get_pathmtu(struct msghdr *);
270 static struct in6_pktinfo *get_rcvpktinfo(struct msghdr *);
271 static void onsignal(int);
272 static void onint(int);
273 static size_t pingerlen(void);
274 static int pinger(void);
275 static const char *pr_addr(struct sockaddr *, int);
276 static void pr_icmph(struct icmp6_hdr *, u_char *);
277 static void pr_iph(struct ip6_hdr *);
278 static void pr_suptypes(struct icmp6_nodeinfo *, size_t);
279 static void pr_nodeaddr(struct icmp6_nodeinfo *, int);
280 static int myechoreply(const struct icmp6_hdr *);
281 static int mynireply(const struct icmp6_nodeinfo *);
282 static const char *dnsdecode(const u_char *, const u_char *, const u_char *,
284 static void pr_pack(u_char *, int, struct msghdr *);
285 static void pr_exthdrs(struct msghdr *);
286 static void pr_ip6opt(void *, size_t);
287 static void pr_rthdr(void *, size_t);
288 static int pr_bitrange(u_int32_t, int, int);
289 static void pr_retip(struct ip6_hdr *, u_char *);
290 static void summary(void);
291 static void tvsub(struct timeval *, struct timeval *);
292 static int setpolicy(int, char *);
293 static char *nigroup(char *, int);
294 static void usage(void);
297 main(int argc, char *argv[])
299 struct timeval last, intvl;
300 struct sockaddr_in6 from, *sin6;
301 struct addrinfo hints, *res;
302 struct sigaction si_sa;
304 int almost_done, ch, hold, packlen, preload, optval, error;
305 int nig_oldmcprefix = -1;
307 char *e, *target, *ifname = NULL, *gateway = NULL;
309 struct cmsghdr *scmsgp = NULL;
310 /* For control (ancillary) data received from recvmsg() */
311 struct cmsghdr cm[CONTROLLEN];
312 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
317 struct in6_pktinfo *pktinfo = NULL;
318 struct ip6_rthdr *rthdr = NULL;
319 #ifdef IPSEC_POLICY_IPSEC
320 char *policy_in = NULL;
321 char *policy_out = NULL;
326 #ifdef IPV6_USE_MIN_MTU
329 cap_rights_t rights_srecv;
330 cap_rights_t rights_ssend;
331 cap_rights_t rights_stdin;
333 /* just to be sure */
334 memset(&smsghdr, 0, sizeof(smsghdr));
335 memset(&smsgiov, 0, sizeof(smsgiov));
337 alarmtimeout = preload = 0;
338 datap = &outpack[ICMP6ECHOLEN + ICMP6ECHOTMLEN];
339 capdns = capdns_setup();
343 #ifdef IPSEC_POLICY_IPSEC
347 #endif /*IPSEC_POLICY_IPSEC*/
349 while ((ch = getopt(argc, argv,
350 "a:b:c:DdfHg:h:I:i:l:mnNop:qrRS:s:tvwWx:X:" ADDOPTS)) != -1) {
357 options &= ~F_NOUSERDATA;
358 options |= F_NODEADDR;
359 for (cp = optarg; *cp != '\0'; cp++) {
362 naflags |= NI_NODEADDR_FLAG_ALL;
366 naflags |= NI_NODEADDR_FLAG_COMPAT;
370 naflags |= NI_NODEADDR_FLAG_LINKLOCAL;
374 naflags |= NI_NODEADDR_FLAG_SITELOCAL;
378 naflags |= NI_NODEADDR_FLAG_GLOBAL;
380 case 'A': /* experimental. not in the spec */
381 #ifdef NI_NODEADDR_FLAG_ANYCAST
382 naflags |= NI_NODEADDR_FLAG_ANYCAST;
386 "-a A is not supported on the platform");
397 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
400 lsockbufsize = strtoul(optarg, &e, 10);
401 sockbufsize = (int)lsockbufsize;
402 if (errno || !*optarg || *e ||
403 lsockbufsize > INT_MAX)
404 errx(1, "invalid socket buffer size");
407 "-b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported");
411 npackets = strtol(optarg, &e, 10);
412 if (npackets <= 0 || *optarg == '\0' || *e != '\0')
414 "illegal number of packets -- %s", optarg);
417 options |= F_DONTFRAG;
420 options |= F_SO_DEBUG;
425 errx(1, "Must be superuser to flood ping");
428 setbuf(stdout, (char *)NULL);
434 options |= F_HOSTNAME;
436 case 'h': /* hoplimit */
437 hoplimit = strtol(optarg, &e, 10);
438 if (*optarg == '\0' || *e != '\0')
439 errx(1, "illegal hoplimit %s", optarg);
440 if (255 < hoplimit || hoplimit < -1)
442 "illegal hoplimit -- %s", optarg);
446 options |= F_INTERFACE;
447 #ifndef USE_SIN6_SCOPE_ID
451 case 'i': /* wait between sending packets */
452 t = strtod(optarg, &e);
453 if (*optarg == '\0' || *e != '\0')
454 errx(1, "illegal timing interval %s", optarg);
455 if (t < 1 && getuid()) {
456 errx(1, "%s: only root may use interval < 1s",
459 intvl.tv_sec = (long)t;
461 (long)((t - intvl.tv_sec) * 1000000);
462 if (intvl.tv_sec < 0)
463 errx(1, "illegal timing interval %s", optarg);
464 /* less than 1/hz does not make sense */
465 if (intvl.tv_sec == 0 && intvl.tv_usec < 1) {
466 warnx("too small interval, raised to .000001");
469 options |= F_INTERVAL;
474 errx(1, "Must be superuser to preload");
476 preload = strtol(optarg, &e, 10);
477 if (preload < 0 || *optarg == '\0' || *e != '\0')
478 errx(1, "illegal preload value -- %s", optarg);
481 #ifdef IPV6_USE_MIN_MTU
485 errx(1, "-%c is not supported on this platform", ch);
489 options &= ~F_HOSTNAME;
492 options |= F_NIGROUP;
498 case 'p': /* fill buffer with user pattern */
499 options |= F_PINGFILLED;
500 fill((char *)datap, optarg);
506 options |= F_AUDIBLE;
512 memset(&hints, 0, sizeof(struct addrinfo));
513 hints.ai_flags = AI_NUMERICHOST; /* allow hostname? */
514 hints.ai_family = AF_INET6;
515 hints.ai_socktype = SOCK_RAW;
516 hints.ai_protocol = IPPROTO_ICMPV6;
518 error = cap_getaddrinfo(capdns, optarg, NULL, &hints, &res);
520 errx(1, "invalid source address: %s",
521 gai_strerror(error));
524 * res->ai_family must be AF_INET6 and res->ai_addrlen
525 * must be sizeof(src).
527 memcpy(&src, res->ai_addr, res->ai_addrlen);
528 srclen = res->ai_addrlen;
530 options |= F_SRCADDR;
532 case 's': /* size of packet to send */
533 datalen = strtol(optarg, &e, 10);
534 if (datalen <= 0 || *optarg == '\0' || *e != '\0')
535 errx(1, "illegal datalen value -- %s", optarg);
536 if (datalen > MAXDATALEN) {
538 "datalen value too large, maximum is %d",
543 options &= ~F_NOUSERDATA;
544 options |= F_SUPTYPES;
547 options |= F_VERBOSE;
550 options &= ~F_NOUSERDATA;
554 options &= ~F_NOUSERDATA;
555 options |= F_FQDNOLD;
558 t = strtod(optarg, &e);
559 if (*e || e == optarg || t > (double)INT_MAX)
560 err(EX_USAGE, "invalid timing interval: `%s'",
562 options |= F_WAITTIME;
566 alarmtimeout = strtoul(optarg, &e, 0);
567 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
568 errx(EX_USAGE, "invalid timeout: `%s'",
570 if (alarmtimeout > MAXALARM)
571 errx(EX_USAGE, "invalid timeout: `%s' > %d",
573 alarm((int)alarmtimeout);
576 #ifdef IPSEC_POLICY_IPSEC
579 if (!strncmp("in", optarg, 2)) {
580 if ((policy_in = strdup(optarg)) == NULL)
582 } else if (!strncmp("out", optarg, 3)) {
583 if ((policy_out = strdup(optarg)) == NULL)
586 errx(1, "invalid security policy");
590 options |= F_AUTHHDR;
593 options |= F_ENCRYPT;
595 #endif /*IPSEC_POLICY_IPSEC*/
612 #ifdef IPV6_RECVRTHDR /* 2292bis */
613 rthlen = CMSG_SPACE(inet6_rth_space(IPV6_RTHDR_TYPE_0,
616 rthlen = inet6_rthdr_space(IPV6_RTHDR_TYPE_0, argc - 1);
619 errx(1, "too many intermediate hops");
625 if (options & F_NIGROUP) {
626 target = nigroup(argv[argc - 1], nig_oldmcprefix);
627 if (target == NULL) {
632 target = argv[argc - 1];
634 /* cap_getaddrinfo */
635 memset(&hints, 0, sizeof(struct addrinfo));
636 hints.ai_flags = AI_CANONNAME;
637 hints.ai_family = AF_INET6;
638 hints.ai_socktype = SOCK_RAW;
639 hints.ai_protocol = IPPROTO_ICMPV6;
641 error = cap_getaddrinfo(capdns, target, NULL, &hints, &res);
643 errx(1, "%s", gai_strerror(error));
644 if (res->ai_canonname)
645 hostname = strdup(res->ai_canonname);
650 errx(1, "cap_getaddrinfo failed");
652 (void)memcpy(&dst, res->ai_addr, res->ai_addrlen);
654 if ((ssend = socket(res->ai_family, res->ai_socktype,
655 res->ai_protocol)) < 0)
656 err(1, "socket ssend");
657 if ((srecv = socket(res->ai_family, res->ai_socktype,
658 res->ai_protocol)) < 0)
659 err(1, "socket srecv");
662 /* set the source address if specified. */
663 if ((options & F_SRCADDR) != 0) {
664 /* properly fill sin6_scope_id */
665 if (IN6_IS_ADDR_LINKLOCAL(&src.sin6_addr) && (
666 IN6_IS_ADDR_LINKLOCAL(&dst.sin6_addr) ||
667 IN6_IS_ADDR_MC_LINKLOCAL(&dst.sin6_addr) ||
668 IN6_IS_ADDR_MC_NODELOCAL(&dst.sin6_addr))) {
669 if (src.sin6_scope_id == 0)
670 src.sin6_scope_id = dst.sin6_scope_id;
671 if (dst.sin6_scope_id == 0)
672 dst.sin6_scope_id = src.sin6_scope_id;
674 if (bind(ssend, (struct sockaddr *)&src, srclen) != 0)
677 /* set the gateway (next hop) if specified */
679 memset(&hints, 0, sizeof(hints));
680 hints.ai_family = AF_INET6;
681 hints.ai_socktype = SOCK_RAW;
682 hints.ai_protocol = IPPROTO_ICMPV6;
684 error = cap_getaddrinfo(capdns, gateway, NULL, &hints, &res);
686 errx(1, "cap_getaddrinfo for the gateway %s: %s",
687 gateway, gai_strerror(error));
689 if (res->ai_next && (options & F_VERBOSE))
690 warnx("gateway resolves to multiple addresses");
692 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_NEXTHOP,
693 res->ai_addr, res->ai_addrlen)) {
694 err(1, "setsockopt(IPV6_NEXTHOP)");
701 * let the kerel pass extension headers of incoming packets,
702 * for privileged socket options
704 if ((options & F_VERBOSE) != 0) {
707 #ifdef IPV6_RECVHOPOPTS
708 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &opton,
710 err(1, "setsockopt(IPV6_RECVHOPOPTS)");
711 #else /* old adv. API */
712 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPOPTS, &opton,
714 err(1, "setsockopt(IPV6_HOPOPTS)");
716 #ifdef IPV6_RECVDSTOPTS
717 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &opton,
719 err(1, "setsockopt(IPV6_RECVDSTOPTS)");
720 #else /* old adv. API */
721 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_DSTOPTS, &opton,
723 err(1, "setsockopt(IPV6_DSTOPTS)");
725 #ifdef IPV6_RECVRTHDRDSTOPTS
726 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDRDSTOPTS, &opton,
728 err(1, "setsockopt(IPV6_RECVRTHDRDSTOPTS)");
732 /* revoke root privilege */
733 if (seteuid(getuid()) != 0)
734 err(1, "seteuid() failed");
735 if (setuid(getuid()) != 0)
736 err(1, "setuid() failed");
738 if ((options & F_FLOOD) && (options & F_INTERVAL))
739 errx(1, "-f and -i incompatible options");
741 if ((options & F_NOUSERDATA) == 0) {
742 if (datalen >= sizeof(struct tv32)) {
743 /* we can time transfer */
747 /* in F_VERBOSE case, we may get non-echoreply packets*/
748 if (options & F_VERBOSE)
749 packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
751 packlen = datalen + IP6LEN + ICMP6ECHOLEN + EXTRA;
753 /* suppress timing for node information query */
756 packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
759 if (!(packet = (u_char *)malloc((u_int)packlen)))
760 err(1, "Unable to allocate packet");
761 if (!(options & F_PINGFILLED))
762 for (i = ICMP6ECHOLEN; i < packlen; ++i)
765 ident = getpid() & 0xFFFF;
766 arc4random_buf(nonce, sizeof(nonce));
768 if (options & F_DONTFRAG)
769 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_DONTFRAG,
770 &optval, sizeof(optval)) == -1)
771 err(1, "IPV6_DONTFRAG");
774 if (options & F_SO_DEBUG) {
775 (void)setsockopt(ssend, SOL_SOCKET, SO_DEBUG, (char *)&hold,
777 (void)setsockopt(srecv, SOL_SOCKET, SO_DEBUG, (char *)&hold,
780 optval = IPV6_DEFHLIM;
781 if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
782 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
783 &optval, sizeof(optval)) == -1)
784 err(1, "IPV6_MULTICAST_HOPS");
785 #ifdef IPV6_USE_MIN_MTU
787 optval = mflag > 1 ? 0 : 1;
789 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
790 &optval, sizeof(optval)) == -1)
791 err(1, "setsockopt(IPV6_USE_MIN_MTU)");
793 #ifdef IPV6_RECVPATHMTU
796 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVPATHMTU,
797 &optval, sizeof(optval)) == -1)
798 err(1, "setsockopt(IPV6_RECVPATHMTU)");
800 #endif /* IPV6_RECVPATHMTU */
801 #endif /* IPV6_USE_MIN_MTU */
804 #ifdef IPSEC_POLICY_IPSEC
805 if (options & F_POLICY) {
806 if (setpolicy(srecv, policy_in) < 0)
807 errx(1, "%s", ipsec_strerror());
808 if (setpolicy(ssend, policy_out) < 0)
809 errx(1, "%s", ipsec_strerror());
812 if (options & F_AUTHHDR) {
813 optval = IPSEC_LEVEL_REQUIRE;
814 #ifdef IPV6_AUTH_TRANS_LEVEL
815 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL,
816 &optval, sizeof(optval)) == -1)
817 err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)");
818 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL,
819 &optval, sizeof(optval)) == -1)
820 err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)");
822 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_AUTH_LEVEL,
823 &optval, sizeof(optval)) == -1)
824 err(1, "setsockopt(IPV6_AUTH_LEVEL)");
825 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_AUTH_LEVEL,
826 &optval, sizeof(optval)) == -1)
827 err(1, "setsockopt(IPV6_AUTH_LEVEL)");
830 if (options & F_ENCRYPT) {
831 optval = IPSEC_LEVEL_REQUIRE;
832 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL,
833 &optval, sizeof(optval)) == -1)
834 err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)");
835 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL,
836 &optval, sizeof(optval)) == -1)
837 err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)");
839 #endif /*IPSEC_POLICY_IPSEC*/
844 struct icmp6_filter filt;
845 if (!(options & F_VERBOSE)) {
846 ICMP6_FILTER_SETBLOCKALL(&filt);
847 if ((options & F_FQDN) || (options & F_FQDNOLD) ||
848 (options & F_NODEADDR) || (options & F_SUPTYPES))
849 ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filt);
851 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
853 ICMP6_FILTER_SETPASSALL(&filt);
855 if (setsockopt(srecv, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
857 err(1, "setsockopt(ICMP6_FILTER)");
859 #endif /*ICMP6_FILTER*/
861 /* let the kerel pass extension headers of incoming packets */
862 if ((options & F_VERBOSE) != 0) {
865 #ifdef IPV6_RECVRTHDR
866 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDR, &opton,
868 err(1, "setsockopt(IPV6_RECVRTHDR)");
869 #else /* old adv. API */
870 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RTHDR, &opton,
872 err(1, "setsockopt(IPV6_RTHDR)");
878 if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
879 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
880 &optval, sizeof(optval)) == -1)
881 err(1, "IPV6_MULTICAST_LOOP");
884 /* Specify the outgoing interface and/or the source address */
886 ip6optlen += CMSG_SPACE(sizeof(struct in6_pktinfo));
889 ip6optlen += CMSG_SPACE(sizeof(int));
891 /* set IP6 packet options */
893 if ((scmsg = (char *)malloc(ip6optlen)) == NULL)
894 errx(1, "can't allocate enough memory");
895 smsghdr.msg_control = (caddr_t)scmsg;
896 smsghdr.msg_controllen = ip6optlen;
897 scmsgp = (struct cmsghdr *)scmsg;
900 pktinfo = (struct in6_pktinfo *)(CMSG_DATA(scmsgp));
901 memset(pktinfo, 0, sizeof(*pktinfo));
902 scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
903 scmsgp->cmsg_level = IPPROTO_IPV6;
904 scmsgp->cmsg_type = IPV6_PKTINFO;
905 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
908 /* set the outgoing interface */
910 #ifndef USE_SIN6_SCOPE_ID
911 /* pktinfo must have already been allocated */
912 if ((pktinfo->ipi6_ifindex = if_nametoindex(ifname)) == 0)
913 errx(1, "%s: invalid interface name", ifname);
915 if ((dst.sin6_scope_id = if_nametoindex(ifname)) == 0)
916 errx(1, "%s: invalid interface name", ifname);
919 if (hoplimit != -1) {
920 scmsgp->cmsg_len = CMSG_LEN(sizeof(int));
921 scmsgp->cmsg_level = IPPROTO_IPV6;
922 scmsgp->cmsg_type = IPV6_HOPLIMIT;
923 *(int *)(CMSG_DATA(scmsgp)) = hoplimit;
925 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
928 if (argc > 1) { /* some intermediate addrs are specified */
932 rthdrlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1);
933 scmsgp->cmsg_len = CMSG_LEN(rthdrlen);
934 scmsgp->cmsg_level = IPPROTO_IPV6;
935 scmsgp->cmsg_type = IPV6_RTHDR;
936 rthdr = (struct ip6_rthdr *)CMSG_DATA(scmsgp);
937 rthdr = inet6_rth_init((void *)rthdr, rthdrlen,
938 IPV6_RTHDR_TYPE_0, argc - 1);
940 errx(1, "can't initialize rthdr");
942 for (hops = 0; hops < argc - 1; hops++) {
943 memset(&hints, 0, sizeof(hints));
944 hints.ai_family = AF_INET6;
946 if ((error = cap_getaddrinfo(capdns, argv[hops], NULL, &hints,
948 errx(1, "%s", gai_strerror(error));
949 if (res->ai_addr->sa_family != AF_INET6)
951 "bad addr family of an intermediate addr");
952 sin6 = (struct sockaddr_in6 *)(void *)res->ai_addr;
953 if (inet6_rth_add(rthdr, &sin6->sin6_addr))
954 errx(1, "can't add an intermediate node");
958 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
961 /* From now on we will use only reverse DNS lookups. */
962 if (capdns != NULL) {
963 const char *types[1];
965 types[0] = "ADDR2NAME";
966 if (cap_dns_type_limit(capdns, types, nitems(types)) < 0)
967 err(1, "unable to limit access to system.dns service");
970 if (!(options & F_SRCADDR)) {
972 * get the source address. XXX since we revoked the root
973 * privilege, we cannot use a raw socket for this.
976 socklen_t len = sizeof(src);
978 if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
979 err(1, "UDP socket");
981 src.sin6_family = AF_INET6;
982 src.sin6_addr = dst.sin6_addr;
983 src.sin6_port = ntohs(DUMMY_PORT);
984 src.sin6_scope_id = dst.sin6_scope_id;
987 setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTINFO,
988 (void *)pktinfo, sizeof(*pktinfo)))
989 err(1, "UDP setsockopt(IPV6_PKTINFO)");
991 if (hoplimit != -1 &&
992 setsockopt(dummy, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
993 (void *)&hoplimit, sizeof(hoplimit)))
994 err(1, "UDP setsockopt(IPV6_UNICAST_HOPS)");
996 if (hoplimit != -1 &&
997 setsockopt(dummy, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
998 (void *)&hoplimit, sizeof(hoplimit)))
999 err(1, "UDP setsockopt(IPV6_MULTICAST_HOPS)");
1002 setsockopt(dummy, IPPROTO_IPV6, IPV6_RTHDR,
1003 (void *)rthdr, (rthdr->ip6r_len + 1) << 3))
1004 err(1, "UDP setsockopt(IPV6_RTHDR)");
1006 if (connect(dummy, (struct sockaddr *)&src, len) < 0)
1007 err(1, "UDP connect");
1009 if (getsockname(dummy, (struct sockaddr *)&src, &len) < 0)
1010 err(1, "getsockname");
1015 if (connect(ssend, (struct sockaddr *)&dst, sizeof(dst)) != 0)
1016 err(1, "connect() ssend");
1018 caph_cache_catpages();
1019 if (caph_enter_casper() < 0)
1020 err(1, "caph_enter_casper");
1022 cap_rights_init(&rights_stdin);
1023 if (cap_rights_limit(STDIN_FILENO, &rights_stdin) < 0)
1024 err(1, "cap_rights_limit stdin");
1025 if (caph_limit_stdout() < 0)
1026 err(1, "caph_limit_stdout");
1027 if (caph_limit_stderr() < 0)
1028 err(1, "caph_limit_stderr");
1030 cap_rights_init(&rights_srecv, CAP_RECV, CAP_EVENT, CAP_SETSOCKOPT);
1031 if (caph_rights_limit(srecv, &rights_srecv) < 0)
1032 err(1, "cap_rights_limit srecv");
1033 cap_rights_init(&rights_ssend, CAP_SEND, CAP_SETSOCKOPT);
1034 if (caph_rights_limit(ssend, &rights_ssend) < 0)
1035 err(1, "cap_rights_limit ssend");
1037 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
1039 if (datalen > (size_t)sockbufsize)
1040 warnx("you need -b to increase socket buffer size");
1041 if (setsockopt(ssend, SOL_SOCKET, SO_SNDBUF, &sockbufsize,
1042 sizeof(sockbufsize)) < 0)
1043 err(1, "setsockopt(SO_SNDBUF)");
1044 if (setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, &sockbufsize,
1045 sizeof(sockbufsize)) < 0)
1046 err(1, "setsockopt(SO_RCVBUF)");
1049 if (datalen > 8 * 1024) /*XXX*/
1050 warnx("you need -b to increase socket buffer size");
1052 * When pinging the broadcast address, you can get a lot of
1053 * answers. Doing something so evil is useful if you are trying
1054 * to stress the ethernet, or just want to fill the arp cache
1055 * to get some stuff for /etc/ethers.
1058 setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
1064 #ifndef USE_SIN6_SCOPE_ID
1065 #ifdef IPV6_RECVPKTINFO
1066 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVPKTINFO, &optval,
1067 sizeof(optval)) < 0)
1068 warn("setsockopt(IPV6_RECVPKTINFO)"); /* XXX err? */
1069 #else /* old adv. API */
1070 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_PKTINFO, &optval,
1071 sizeof(optval)) < 0)
1072 warn("setsockopt(IPV6_PKTINFO)"); /* XXX err? */
1074 #endif /* USE_SIN6_SCOPE_ID */
1075 #ifdef IPV6_RECVHOPLIMIT
1076 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &optval,
1077 sizeof(optval)) < 0)
1078 warn("setsockopt(IPV6_RECVHOPLIMIT)"); /* XXX err? */
1079 #else /* old adv. API */
1080 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPLIMIT, &optval,
1081 sizeof(optval)) < 0)
1082 warn("setsockopt(IPV6_HOPLIMIT)"); /* XXX err? */
1085 cap_rights_clear(&rights_srecv, CAP_SETSOCKOPT);
1086 if (caph_rights_limit(srecv, &rights_srecv) < 0)
1087 err(1, "cap_rights_limit srecv setsockopt");
1088 cap_rights_clear(&rights_ssend, CAP_SETSOCKOPT);
1089 if (caph_rights_limit(ssend, &rights_ssend) < 0)
1090 err(1, "cap_rights_limit ssend setsockopt");
1092 printf("PING6(%lu=40+8+%lu bytes) ", (unsigned long)(40 + pingerlen()),
1093 (unsigned long)(pingerlen() - 8));
1094 printf("%s --> ", pr_addr((struct sockaddr *)&src, sizeof(src)));
1095 printf("%s\n", pr_addr((struct sockaddr *)&dst, sizeof(dst)));
1100 if (npackets != 0 && preload > npackets)
1105 gettimeofday(&last, NULL);
1107 sigemptyset(&si_sa.sa_mask);
1109 si_sa.sa_handler = onsignal;
1110 if (sigaction(SIGINT, &si_sa, 0) == -1)
1111 err(EX_OSERR, "sigaction SIGINT");
1114 if (sigaction(SIGINFO, &si_sa, 0) == -1)
1115 err(EX_OSERR, "sigaction SIGINFO");
1118 if (alarmtimeout > 0) {
1119 if (sigaction(SIGALRM, &si_sa, 0) == -1)
1120 err(EX_OSERR, "sigaction SIGALRM");
1122 if (options & F_FLOOD) {
1124 intvl.tv_usec = 10000;
1125 } else if ((options & F_INTERVAL) == 0) {
1126 intvl.tv_sec = interval / 1000;
1127 intvl.tv_usec = interval % 1000 * 1000;
1131 while (seenint == 0) {
1132 struct timeval now, timeout;
1134 struct iovec iov[2];
1138 /* signal handling */
1149 FD_SET(srecv, &rfds);
1150 gettimeofday(&now, NULL);
1151 timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
1152 timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
1153 while (timeout.tv_usec < 0) {
1154 timeout.tv_usec += 1000000;
1157 while (timeout.tv_usec > 1000000) {
1158 timeout.tv_usec -= 1000000;
1161 if (timeout.tv_sec < 0)
1162 timeout.tv_sec = timeout.tv_usec = 0;
1164 n = select(srecv + 1, &rfds, NULL, NULL, &timeout);
1166 continue; /* EINTR */
1168 m.msg_name = (caddr_t)&from;
1169 m.msg_namelen = sizeof(from);
1170 memset(&iov, 0, sizeof(iov));
1171 iov[0].iov_base = (caddr_t)packet;
1172 iov[0].iov_len = packlen;
1175 memset(cm, 0, CONTROLLEN);
1176 m.msg_control = (void *)cm;
1177 m.msg_controllen = CONTROLLEN;
1179 cc = recvmsg(srecv, &m, 0);
1181 if (errno != EINTR) {
1186 } else if (cc == 0) {
1190 * receive control messages only. Process the
1191 * exceptions (currently the only possibility is
1192 * a path MTU notification.)
1194 if ((mtu = get_pathmtu(&m)) > 0) {
1195 if ((options & F_VERBOSE) != 0) {
1196 printf("new path MTU (%d) is "
1203 * an ICMPv6 message (probably an echoreply)
1206 pr_pack(packet, cc, &m);
1208 if (((options & F_ONCE) != 0 && nreceived > 0) ||
1209 (npackets > 0 && nreceived >= npackets))
1212 if (n == 0 || (options & F_FLOOD)) {
1213 if (npackets == 0 || ntransmitted < npackets)
1220 * If we're not transmitting any more packets,
1221 * change the timer to wait two round-trip times
1222 * if we've received any packets or (waittime)
1223 * milliseconds if we haven't.
1227 intvl.tv_sec = 2 * tmax / 1000;
1228 if (intvl.tv_sec == 0)
1231 intvl.tv_sec = waittime / 1000;
1232 intvl.tv_usec = waittime % 1000 * 1000;
1235 gettimeofday(&last, NULL);
1236 if (ntransmitted - nreceived - 1 > nmissedmax) {
1237 nmissedmax = ntransmitted - nreceived - 1;
1238 if (options & F_MISSED)
1239 (void)write(STDOUT_FILENO, &BBELL, 1);
1243 sigemptyset(&si_sa.sa_mask);
1245 si_sa.sa_handler = SIG_IGN;
1246 sigaction(SIGINT, &si_sa, 0);
1247 sigaction(SIGALRM, &si_sa, 0);
1253 exit(nreceived == 0 ? 2 : 0);
1275 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1276 * will be added on by the kernel. The ID field is our UNIX process ID,
1277 * and the sequence number is an ascending integer. The first 8 bytes
1278 * of the data portion are used to hold a UNIX "timeval" struct in VAX
1279 * byte-order, to compute the round-trip time.
1286 if (options & F_FQDN)
1287 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1288 else if (options & F_FQDNOLD)
1290 else if (options & F_NODEADDR)
1291 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1292 else if (options & F_SUPTYPES)
1295 l = ICMP6ECHOLEN + datalen;
1303 struct icmp6_hdr *icp;
1304 struct iovec iov[2];
1306 struct icmp6_nodeinfo *nip;
1309 if (npackets && ntransmitted >= npackets)
1310 return(-1); /* no more transmission */
1312 icp = (struct icmp6_hdr *)outpack;
1313 nip = (struct icmp6_nodeinfo *)outpack;
1314 memset(icp, 0, sizeof(*icp));
1315 icp->icmp6_cksum = 0;
1316 seq = ntransmitted++;
1317 CLR(seq % mx_dup_ck);
1319 if (options & F_FQDN) {
1320 icp->icmp6_type = ICMP6_NI_QUERY;
1321 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1322 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1323 nip->ni_flags = htons(0);
1325 memcpy(nip->icmp6_ni_nonce, nonce,
1326 sizeof(nip->icmp6_ni_nonce));
1327 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1329 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1330 sizeof(dst.sin6_addr));
1331 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1333 } else if (options & F_FQDNOLD) {
1334 /* packet format in 03 draft - no Subject data on queries */
1335 icp->icmp6_type = ICMP6_NI_QUERY;
1336 icp->icmp6_code = 0; /* code field is always 0 */
1337 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1338 nip->ni_flags = htons(0);
1340 memcpy(nip->icmp6_ni_nonce, nonce,
1341 sizeof(nip->icmp6_ni_nonce));
1342 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1346 } else if (options & F_NODEADDR) {
1347 icp->icmp6_type = ICMP6_NI_QUERY;
1348 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1349 nip->ni_qtype = htons(NI_QTYPE_NODEADDR);
1350 nip->ni_flags = naflags;
1352 memcpy(nip->icmp6_ni_nonce, nonce,
1353 sizeof(nip->icmp6_ni_nonce));
1354 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1356 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1357 sizeof(dst.sin6_addr));
1358 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1360 } else if (options & F_SUPTYPES) {
1361 icp->icmp6_type = ICMP6_NI_QUERY;
1362 icp->icmp6_code = ICMP6_NI_SUBJ_FQDN; /*empty*/
1363 nip->ni_qtype = htons(NI_QTYPE_SUPTYPES);
1364 /* we support compressed bitmap */
1365 nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS;
1367 memcpy(nip->icmp6_ni_nonce, nonce,
1368 sizeof(nip->icmp6_ni_nonce));
1369 *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq);
1373 icp->icmp6_type = ICMP6_ECHO_REQUEST;
1374 icp->icmp6_code = 0;
1375 icp->icmp6_id = htons(ident);
1376 icp->icmp6_seq = ntohs(seq);
1380 (void)gettimeofday(&tv, NULL);
1381 tv32 = (struct tv32 *)&outpack[ICMP6ECHOLEN];
1382 tv32->tv32_sec = htonl(tv.tv_sec);
1383 tv32->tv32_usec = htonl(tv.tv_usec);
1385 cc = ICMP6ECHOLEN + datalen;
1389 if (pingerlen() != cc)
1390 errx(1, "internal error; length mismatch");
1393 memset(&iov, 0, sizeof(iov));
1394 iov[0].iov_base = (caddr_t)outpack;
1395 iov[0].iov_len = cc;
1396 smsghdr.msg_iov = iov;
1397 smsghdr.msg_iovlen = 1;
1399 i = sendmsg(ssend, &smsghdr, 0);
1401 if (i < 0 || i != cc) {
1404 (void)printf("ping6: wrote %s %d chars, ret=%d\n",
1407 if (!(options & F_QUIET) && options & F_FLOOD)
1408 (void)write(STDOUT_FILENO, &DOT, 1);
1414 myechoreply(const struct icmp6_hdr *icp)
1416 if (ntohs(icp->icmp6_id) == ident)
1423 mynireply(const struct icmp6_nodeinfo *nip)
1425 if (memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t),
1426 nonce + sizeof(u_int16_t),
1427 sizeof(nonce) - sizeof(u_int16_t)) == 0)
1434 * Decode a name from a DNS message.
1436 * Format of the message is described in RFC 1035 subsection 4.1.4.
1439 * sp - Pointer to a DNS pointer octet or to the first octet of a label
1441 * ep - Pointer to the end of the message (one step past the last octet).
1442 * base - Pointer to the beginning of the message.
1443 * buf - Buffer into which the decoded name will be saved.
1444 * bufsiz - Size of the buffer 'buf'.
1447 * Pointer to an octet immediately following the ending zero octet
1448 * of the decoded label, or NULL if an error occured.
1451 dnsdecode(const u_char *sp, const u_char *ep, const u_char *base, char *buf,
1456 char cresult[MAXDNAME + 1];
1467 if (i == 0 || cp != sp) {
1468 if (strlcat((char *)buf, ".", bufsiz) >= bufsiz)
1469 return NULL; /*result overrun*/
1475 if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) {
1476 /* DNS compression */
1480 comp = base + (i & 0x3f);
1481 if (dnsdecode(comp, cp, base, cresult,
1482 sizeof(cresult)) == NULL)
1484 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1485 return NULL; /*result overrun*/
1487 } else if ((i & 0x3f) == i) {
1489 return NULL; /*source overrun*/
1490 while (i-- > 0 && cp < ep) {
1491 l = snprintf(cresult, sizeof(cresult),
1492 isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff);
1493 if ((size_t)l >= sizeof(cresult) || l < 0)
1495 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1496 return NULL; /*result overrun*/
1500 return NULL; /*invalid label*/
1503 return NULL; /*not terminated*/
1510 * Print out the packet, if it came from us. This logic is necessary
1511 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1512 * which arrive ('tis only fair). This permits multiple copies of this
1513 * program to be run without having intermingled output (or statistics!).
1516 pr_pack(u_char *buf, int cc, struct msghdr *mhdr)
1518 #define safeputc(c) printf((isprint((c)) ? "%c" : "\\%03o"), c)
1519 struct icmp6_hdr *icp;
1520 struct icmp6_nodeinfo *ni;
1523 struct sockaddr *from;
1525 const u_char *cp = NULL;
1526 u_char *dp, *end = buf + cc;
1527 struct in6_pktinfo *pktinfo = NULL;
1528 struct timeval tv, tp;
1530 double triptime = 0;
1535 char dnsname[MAXDNAME + 1];
1537 (void)gettimeofday(&tv, NULL);
1539 if (!mhdr || !mhdr->msg_name ||
1540 mhdr->msg_namelen != sizeof(struct sockaddr_in6) ||
1541 ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) {
1542 if (options & F_VERBOSE)
1543 warnx("invalid peername");
1546 from = (struct sockaddr *)mhdr->msg_name;
1547 fromlen = mhdr->msg_namelen;
1548 if (cc < (int)sizeof(struct icmp6_hdr)) {
1549 if (options & F_VERBOSE)
1550 warnx("packet too short (%d bytes) from %s", cc,
1551 pr_addr(from, fromlen));
1554 if (((mhdr->msg_flags & MSG_CTRUNC) != 0) &&
1555 (options & F_VERBOSE) != 0)
1556 warnx("some control data discarded, insufficient buffer size");
1557 icp = (struct icmp6_hdr *)buf;
1558 ni = (struct icmp6_nodeinfo *)buf;
1561 if ((hoplim = get_hoplim(mhdr)) == -1) {
1562 warnx("failed to get receiving hop limit");
1565 if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) {
1566 warnx("failed to get receiving packet information");
1570 if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) {
1571 seq = ntohs(icp->icmp6_seq);
1574 tpp = (struct tv32 *)(icp + 1);
1575 tp.tv_sec = ntohl(tpp->tv32_sec);
1576 tp.tv_usec = ntohl(tpp->tv32_usec);
1578 triptime = ((double)tv.tv_sec) * 1000.0 +
1579 ((double)tv.tv_usec) / 1000.0;
1581 tsumsq += triptime * triptime;
1582 if (triptime < tmin)
1584 if (triptime > tmax)
1588 if (TST(seq % mx_dup_ck)) {
1593 SET(seq % mx_dup_ck);
1597 if (options & F_QUIET)
1600 if (options & F_WAITTIME && triptime > waittime) {
1605 if (options & F_FLOOD)
1606 (void)write(STDOUT_FILENO, &BSPACE, 1);
1608 if (options & F_AUDIBLE)
1609 (void)write(STDOUT_FILENO, &BBELL, 1);
1610 (void)printf("%d bytes from %s, icmp_seq=%u", cc,
1611 pr_addr(from, fromlen), seq);
1612 (void)printf(" hlim=%d", hoplim);
1613 if ((options & F_VERBOSE) != 0) {
1614 struct sockaddr_in6 dstsa;
1616 memset(&dstsa, 0, sizeof(dstsa));
1617 dstsa.sin6_family = AF_INET6;
1618 dstsa.sin6_len = sizeof(dstsa);
1619 dstsa.sin6_scope_id = pktinfo->ipi6_ifindex;
1620 dstsa.sin6_addr = pktinfo->ipi6_addr;
1621 (void)printf(" dst=%s",
1622 pr_addr((struct sockaddr *)&dstsa,
1626 (void)printf(" time=%.3f ms", triptime);
1628 (void)printf("(DUP!)");
1629 /* check the data */
1630 cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1631 dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1632 for (i = 8; cp < end; ++i, ++cp, ++dp) {
1634 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp);
1639 } else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) {
1640 seq = ntohs(*(u_int16_t *)ni->icmp6_ni_nonce);
1642 if (TST(seq % mx_dup_ck)) {
1647 SET(seq % mx_dup_ck);
1651 if (options & F_QUIET)
1654 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1656 switch (ntohs(ni->ni_code)) {
1657 case ICMP6_NI_SUCCESS:
1659 case ICMP6_NI_REFUSED:
1660 printf("refused, type 0x%x", ntohs(ni->ni_type));
1662 case ICMP6_NI_UNKNOWN:
1663 printf("unknown, type 0x%x", ntohs(ni->ni_type));
1666 printf("unknown code 0x%x, type 0x%x",
1667 ntohs(ni->ni_code), ntohs(ni->ni_type));
1671 switch (ntohs(ni->ni_qtype)) {
1673 printf("NodeInfo NOOP");
1675 case NI_QTYPE_SUPTYPES:
1676 pr_suptypes(ni, end - (u_char *)ni);
1678 case NI_QTYPE_NODEADDR:
1679 pr_nodeaddr(ni, end - (u_char *)ni);
1682 default: /* XXX: for backward compatibility */
1683 cp = (u_char *)ni + ICMP6_NIRLEN;
1684 if (buf[off + ICMP6_NIRLEN] ==
1685 cc - off - ICMP6_NIRLEN - 1)
1690 cp++; /* skip length */
1692 safeputc(*cp & 0xff);
1698 cp = dnsdecode((const u_char *)cp, end,
1699 (const u_char *)(ni + 1), dnsname,
1706 * name-lookup special handling for
1709 if (cp + 1 <= end && !*cp &&
1710 strlen(dnsname) > 0) {
1711 dnsname[strlen(dnsname) - 1] = '\0';
1714 printf("%s%s", i > 0 ? "," : "",
1718 if (options & F_VERBOSE) {
1722 (void)printf(" ("); /*)*/
1724 switch (ni->ni_code) {
1725 case ICMP6_NI_REFUSED:
1726 (void)printf("refused");
1729 case ICMP6_NI_UNKNOWN:
1730 (void)printf("unknown qtype");
1735 if ((end - (u_char *)ni) < ICMP6_NIRLEN) {
1736 /* case of refusion, unknown */
1741 ttl = (int32_t)ntohl(*(u_long *)&buf[off+ICMP6ECHOLEN+8]);
1744 if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) {
1745 (void)printf("TTL=%d:meaningless",
1749 (void)printf("TTL=%d:invalid",
1752 (void)printf("TTL=%d", ttl);
1762 cp = (u_char *)ni + ICMP6_NIRLEN;
1771 if (buf[off + ICMP6_NIRLEN] !=
1772 cc - off - ICMP6_NIRLEN - 1 && oldfqdn) {
1775 (void)printf("invalid namelen:%d/%lu",
1776 buf[off + ICMP6_NIRLEN],
1777 (u_long)cc - off - ICMP6_NIRLEN - 1);
1787 /* We've got something other than an ECHOREPLY */
1788 if (!(options & F_VERBOSE))
1790 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1794 if (!(options & F_FLOOD)) {
1795 (void)putchar('\n');
1796 if (options & F_VERBOSE)
1798 (void)fflush(stdout);
1804 pr_exthdrs(struct msghdr *mhdr)
1811 bufp = mhdr->msg_control;
1812 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1813 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1814 if (cm->cmsg_level != IPPROTO_IPV6)
1817 bufsize = CONTROLLEN - ((caddr_t)CMSG_DATA(cm) - (caddr_t)bufp);
1820 switch (cm->cmsg_type) {
1822 printf(" HbH Options: ");
1823 pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1826 #ifdef IPV6_RTHDRDSTOPTS
1827 case IPV6_RTHDRDSTOPTS:
1829 printf(" Dst Options: ");
1830 pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1833 printf(" Routing: ");
1834 pr_rthdr(CMSG_DATA(cm), (size_t)bufsize);
1841 pr_ip6opt(void *extbuf, size_t bufsize)
1843 struct ip6_hbh *ext;
1846 socklen_t extlen, len;
1852 ext = (struct ip6_hbh *)extbuf;
1853 extlen = (ext->ip6h_len + 1) * 8;
1854 printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt,
1855 (unsigned int)ext->ip6h_len, (unsigned long)extlen);
1858 * Bounds checking on the ancillary data buffer:
1859 * subtract the size of a cmsg structure from the buffer size.
1861 if (bufsize < (extlen + CMSG_SPACE(0))) {
1862 extlen = bufsize - CMSG_SPACE(0);
1863 warnx("options truncated, showing only %u (total=%u)",
1864 (unsigned int)(extlen / 8 - 1),
1865 (unsigned int)(ext->ip6h_len));
1870 currentlen = inet6_opt_next(extbuf, extlen, currentlen,
1871 &type, &len, &databuf);
1872 if (currentlen == -1)
1876 * Note that inet6_opt_next automatically skips any padding
1881 offset = inet6_opt_get_val(databuf, offset,
1882 &value4, sizeof(value4));
1883 printf(" Jumbo Payload Opt: Length %u\n",
1884 (u_int32_t)ntohl(value4));
1886 case IP6OPT_ROUTER_ALERT:
1888 offset = inet6_opt_get_val(databuf, offset,
1889 &value2, sizeof(value2));
1890 printf(" Router Alert Opt: Type %u\n",
1894 printf(" Received Opt %u len %lu\n",
1895 type, (unsigned long)len);
1903 pr_rthdr(void *extbuf, size_t bufsize)
1905 struct in6_addr *in6;
1906 char ntopbuf[INET6_ADDRSTRLEN];
1907 struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf;
1908 int i, segments, origsegs, rthsize, size0, size1;
1910 /* print fixed part of the header */
1911 printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt,
1912 rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type);
1913 if ((segments = inet6_rth_segments(extbuf)) >= 0) {
1914 printf("%d segments, ", segments);
1915 printf("%d left\n", rh->ip6r_segleft);
1917 printf("segments unknown, ");
1918 printf("%d left\n", rh->ip6r_segleft);
1923 * Bounds checking on the ancillary data buffer. When calculating
1924 * the number of items to show keep in mind:
1925 * - The size of the cmsg structure
1926 * - The size of one segment (the size of a Type 0 routing header)
1927 * - When dividing add a fudge factor of one in case the
1928 * dividend is not evenly divisible by the divisor
1930 rthsize = (rh->ip6r_len + 1) * 8;
1931 if (bufsize < (rthsize + CMSG_SPACE(0))) {
1932 origsegs = segments;
1933 size0 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 0);
1934 size1 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 1);
1935 segments -= (rthsize - (bufsize - CMSG_SPACE(0))) /
1936 (size1 - size0) + 1;
1937 warnx("segments truncated, showing only %d (total=%d)",
1938 segments, origsegs);
1941 for (i = 0; i < segments; i++) {
1942 in6 = inet6_rth_getaddr(extbuf, i);
1944 printf(" [%d]<NULL>\n", i);
1946 if (!inet_ntop(AF_INET6, in6, ntopbuf,
1948 strlcpy(ntopbuf, "?", sizeof(ntopbuf));
1949 printf(" [%d]%s\n", i, ntopbuf);
1958 pr_bitrange(u_int32_t v, int soff, int ii)
1965 /* shift till we have 0x01 */
1966 if ((v & 0x01) == 0) {
1968 printf("-%u", soff + off - 1);
1979 case 0x04: case 0x0c:
1990 /* we have 0x01 with us */
1991 for (i = 0; i < 32 - off; i++) {
1992 if ((v & (0x01 << i)) == 0)
1996 printf(" %u", soff + off);
2004 pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen)
2005 /* ni->qtype must be SUPTYPES */
2009 const u_char *cp, *end;
2012 u_int16_t words; /*32bit count*/
2015 #define MAXQTYPES (1 << 16)
2019 cp = (u_char *)(ni + 1);
2020 end = ((u_char *)ni) + nilen;
2024 printf("NodeInfo Supported Qtypes");
2025 if (options & F_VERBOSE) {
2026 if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS)
2027 printf(", compressed bitmap");
2029 printf(", raw bitmap");
2033 clen = (size_t)(end - cp);
2034 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) {
2035 if (clen == 0 || clen > MAXQTYPES / 8 ||
2041 if (clen < sizeof(cbit) || clen % sizeof(v))
2043 memcpy(&cbit, cp, sizeof(cbit));
2044 if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) >
2048 clen = ntohs(cbit.words) * sizeof(v);
2049 if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 >
2054 for (off = 0; off < clen; off += sizeof(v)) {
2055 memcpy(&v, cp + off, sizeof(v));
2056 v = (u_int32_t)ntohl(v);
2057 b = pr_bitrange(v, (int)(cur + off * 8), b);
2059 /* flush the remaining bits */
2060 b = pr_bitrange(0, (int)(cur + off * 8), b);
2064 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0)
2065 cur += ntohs(cbit.skip) * 32;
2070 pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen)
2071 /* ni->qtype must be NODEADDR */
2073 u_char *cp = (u_char *)(ni + 1);
2074 char ntop_buf[INET6_ADDRSTRLEN];
2077 nilen -= sizeof(struct icmp6_nodeinfo);
2079 if (options & F_VERBOSE) {
2080 switch (ni->ni_code) {
2081 case ICMP6_NI_REFUSED:
2082 (void)printf("refused");
2084 case ICMP6_NI_UNKNOWN:
2085 (void)printf("unknown qtype");
2088 if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE)
2089 (void)printf(" truncated");
2093 printf(" no address\n");
2096 * In icmp-name-lookups 05 and later, TTL of each returned address
2097 * is contained in the resposne. We try to detect the version
2098 * by the length of the data, but note that the detection algorithm
2099 * is incomplete. We assume the latest draft by default.
2101 if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0)
2107 /* XXX: alignment? */
2108 ttl = (u_int32_t)ntohl(*(u_int32_t *)cp);
2109 cp += sizeof(u_int32_t);
2110 nilen -= sizeof(u_int32_t);
2113 if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) ==
2115 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2116 printf(" %s", ntop_buf);
2118 if (ttl == 0xffffffff) {
2120 * XXX: can this convention be applied to all
2121 * type of TTL (i.e. non-ND TTL)?
2123 printf("(TTL=infty)");
2126 printf("(TTL=%u)", ttl);
2130 nilen -= sizeof(struct in6_addr);
2131 cp += sizeof(struct in6_addr);
2136 get_hoplim(struct msghdr *mhdr)
2140 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2141 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2142 if (cm->cmsg_len == 0)
2145 if (cm->cmsg_level == IPPROTO_IPV6 &&
2146 cm->cmsg_type == IPV6_HOPLIMIT &&
2147 cm->cmsg_len == CMSG_LEN(sizeof(int)))
2148 return(*(int *)CMSG_DATA(cm));
2154 static struct in6_pktinfo *
2155 get_rcvpktinfo(struct msghdr *mhdr)
2159 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2160 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2161 if (cm->cmsg_len == 0)
2164 if (cm->cmsg_level == IPPROTO_IPV6 &&
2165 cm->cmsg_type == IPV6_PKTINFO &&
2166 cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo)))
2167 return((struct in6_pktinfo *)CMSG_DATA(cm));
2174 get_pathmtu(struct msghdr *mhdr)
2176 #ifdef IPV6_RECVPATHMTU
2178 struct ip6_mtuinfo *mtuctl = NULL;
2180 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2181 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2182 if (cm->cmsg_len == 0)
2185 if (cm->cmsg_level == IPPROTO_IPV6 &&
2186 cm->cmsg_type == IPV6_PATHMTU &&
2187 cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) {
2188 mtuctl = (struct ip6_mtuinfo *)CMSG_DATA(cm);
2191 * If the notified destination is different from
2192 * the one we are pinging, just ignore the info.
2193 * We check the scope ID only when both notified value
2194 * and our own value have non-0 values, because we may
2195 * have used the default scope zone ID for sending,
2196 * in which case the scope ID value is 0.
2198 if (!IN6_ARE_ADDR_EQUAL(&mtuctl->ip6m_addr.sin6_addr,
2200 (mtuctl->ip6m_addr.sin6_scope_id &&
2201 dst.sin6_scope_id &&
2202 mtuctl->ip6m_addr.sin6_scope_id !=
2203 dst.sin6_scope_id)) {
2204 if ((options & F_VERBOSE) != 0) {
2205 printf("path MTU for %s is notified. "
2207 pr_addr((struct sockaddr *)&mtuctl->ip6m_addr,
2208 sizeof(mtuctl->ip6m_addr)));
2214 * Ignore an invalid MTU. XXX: can we just believe
2217 if (mtuctl->ip6m_mtu < IPV6_MMTU)
2220 /* notification for our destination. return the MTU. */
2221 return((int)mtuctl->ip6m_mtu);
2230 * Subtract 2 timeval structs: out = out - in. Out is assumed to
2234 tvsub(struct timeval *out, struct timeval *in)
2236 if ((out->tv_usec -= in->tv_usec) < 0) {
2238 out->tv_usec += 1000000;
2240 out->tv_sec -= in->tv_sec;
2249 onint(int notused __unused)
2252 * When doing reverse DNS lookups, the seenint flag might not
2253 * be noticed for a while. Just exit if we get a second SIGINT.
2255 if ((options & F_HOSTNAME) && seenint != 0)
2256 _exit(nreceived ? 0 : 2);
2261 * Print out statistics.
2267 (void)printf("\n--- %s ping6 statistics ---\n", hostname);
2268 (void)printf("%ld packets transmitted, ", ntransmitted);
2269 (void)printf("%ld packets received, ", nreceived);
2271 (void)printf("+%ld duplicates, ", nrepeats);
2273 if (nreceived > ntransmitted)
2274 (void)printf("-- somebody's duplicating packets!");
2276 (void)printf("%.1f%% packet loss",
2277 ((((double)ntransmitted - nreceived) * 100.0) /
2281 printf(", %ld packets out of wait time", nrcvtimeout);
2282 (void)putchar('\n');
2283 if (nreceived && timing) {
2284 /* Only display average to microseconds */
2285 double num = nreceived + nrepeats;
2286 double avg = tsum / num;
2287 double dev = sqrt(tsumsq / num - avg * avg);
2289 "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
2290 tmin, avg, tmax, dev);
2291 (void)fflush(stdout);
2293 (void)fflush(stdout);
2297 static const char *niqcode[] = {
2299 "DNS label", /*or empty*/
2304 static const char *nircode[] = {
2305 "Success", "Refused", "Unknown",
2311 * Print a descriptive string about an ICMP header.
2314 pr_icmph(struct icmp6_hdr *icp, u_char *end)
2316 char ntop_buf[INET6_ADDRSTRLEN];
2317 struct nd_redirect *red;
2318 struct icmp6_nodeinfo *ni;
2319 char dnsname[MAXDNAME + 1];
2323 switch (icp->icmp6_type) {
2324 case ICMP6_DST_UNREACH:
2325 switch (icp->icmp6_code) {
2326 case ICMP6_DST_UNREACH_NOROUTE:
2327 (void)printf("No Route to Destination\n");
2329 case ICMP6_DST_UNREACH_ADMIN:
2330 (void)printf("Destination Administratively "
2333 case ICMP6_DST_UNREACH_BEYONDSCOPE:
2334 (void)printf("Destination Unreachable Beyond Scope\n");
2336 case ICMP6_DST_UNREACH_ADDR:
2337 (void)printf("Destination Host Unreachable\n");
2339 case ICMP6_DST_UNREACH_NOPORT:
2340 (void)printf("Destination Port Unreachable\n");
2343 (void)printf("Destination Unreachable, Bad Code: %d\n",
2347 /* Print returned IP header information */
2348 pr_retip((struct ip6_hdr *)(icp + 1), end);
2350 case ICMP6_PACKET_TOO_BIG:
2351 (void)printf("Packet too big mtu = %d\n",
2352 (int)ntohl(icp->icmp6_mtu));
2353 pr_retip((struct ip6_hdr *)(icp + 1), end);
2355 case ICMP6_TIME_EXCEEDED:
2356 switch (icp->icmp6_code) {
2357 case ICMP6_TIME_EXCEED_TRANSIT:
2358 (void)printf("Time to live exceeded\n");
2360 case ICMP6_TIME_EXCEED_REASSEMBLY:
2361 (void)printf("Frag reassembly time exceeded\n");
2364 (void)printf("Time exceeded, Bad Code: %d\n",
2368 pr_retip((struct ip6_hdr *)(icp + 1), end);
2370 case ICMP6_PARAM_PROB:
2371 (void)printf("Parameter problem: ");
2372 switch (icp->icmp6_code) {
2373 case ICMP6_PARAMPROB_HEADER:
2374 (void)printf("Erroneous Header ");
2376 case ICMP6_PARAMPROB_NEXTHEADER:
2377 (void)printf("Unknown Nextheader ");
2379 case ICMP6_PARAMPROB_OPTION:
2380 (void)printf("Unrecognized Option ");
2383 (void)printf("Bad code(%d) ", icp->icmp6_code);
2386 (void)printf("pointer = 0x%02x\n",
2387 (u_int32_t)ntohl(icp->icmp6_pptr));
2388 pr_retip((struct ip6_hdr *)(icp + 1), end);
2390 case ICMP6_ECHO_REQUEST:
2391 (void)printf("Echo Request");
2392 /* XXX ID + Seq + Data */
2394 case ICMP6_ECHO_REPLY:
2395 (void)printf("Echo Reply");
2396 /* XXX ID + Seq + Data */
2398 case ICMP6_MEMBERSHIP_QUERY:
2399 (void)printf("Listener Query");
2401 case ICMP6_MEMBERSHIP_REPORT:
2402 (void)printf("Listener Report");
2404 case ICMP6_MEMBERSHIP_REDUCTION:
2405 (void)printf("Listener Done");
2407 case ND_ROUTER_SOLICIT:
2408 (void)printf("Router Solicitation");
2410 case ND_ROUTER_ADVERT:
2411 (void)printf("Router Advertisement");
2413 case ND_NEIGHBOR_SOLICIT:
2414 (void)printf("Neighbor Solicitation");
2416 case ND_NEIGHBOR_ADVERT:
2417 (void)printf("Neighbor Advertisement");
2420 red = (struct nd_redirect *)icp;
2421 (void)printf("Redirect\n");
2422 if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf,
2424 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2425 (void)printf("Destination: %s", ntop_buf);
2426 if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf,
2428 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2429 (void)printf(" New Target: %s", ntop_buf);
2431 case ICMP6_NI_QUERY:
2432 (void)printf("Node Information Query");
2433 /* XXX ID + Seq + Data */
2434 ni = (struct icmp6_nodeinfo *)icp;
2435 l = end - (u_char *)(ni + 1);
2437 switch (ntohs(ni->ni_qtype)) {
2439 (void)printf("NOOP");
2441 case NI_QTYPE_SUPTYPES:
2442 (void)printf("Supported qtypes");
2445 (void)printf("DNS name");
2447 case NI_QTYPE_NODEADDR:
2448 (void)printf("nodeaddr");
2450 case NI_QTYPE_IPV4ADDR:
2451 (void)printf("IPv4 nodeaddr");
2454 (void)printf("unknown qtype");
2457 if (options & F_VERBOSE) {
2458 switch (ni->ni_code) {
2459 case ICMP6_NI_SUBJ_IPV6:
2460 if (l == sizeof(struct in6_addr) &&
2461 inet_ntop(AF_INET6, ni + 1, ntop_buf,
2462 sizeof(ntop_buf)) != NULL) {
2463 (void)printf(", subject=%s(%s)",
2464 niqcode[ni->ni_code], ntop_buf);
2467 /* backward compat to -W */
2468 (void)printf(", oldfqdn");
2470 (void)printf(", invalid");
2474 case ICMP6_NI_SUBJ_FQDN:
2475 if (end == (u_char *)(ni + 1)) {
2476 (void)printf(", no subject");
2479 printf(", subject=%s", niqcode[ni->ni_code]);
2480 cp = (const u_char *)(ni + 1);
2481 cp = dnsdecode(cp, end, NULL, dnsname,
2484 printf("(%s)", dnsname);
2486 printf("(invalid)");
2488 case ICMP6_NI_SUBJ_IPV4:
2489 if (l == sizeof(struct in_addr) &&
2490 inet_ntop(AF_INET, ni + 1, ntop_buf,
2491 sizeof(ntop_buf)) != NULL) {
2492 (void)printf(", subject=%s(%s)",
2493 niqcode[ni->ni_code], ntop_buf);
2495 (void)printf(", invalid");
2498 (void)printf(", invalid");
2503 case ICMP6_NI_REPLY:
2504 (void)printf("Node Information Reply");
2505 /* XXX ID + Seq + Data */
2506 ni = (struct icmp6_nodeinfo *)icp;
2508 switch (ntohs(ni->ni_qtype)) {
2510 (void)printf("NOOP");
2512 case NI_QTYPE_SUPTYPES:
2513 (void)printf("Supported qtypes");
2516 (void)printf("DNS name");
2518 case NI_QTYPE_NODEADDR:
2519 (void)printf("nodeaddr");
2521 case NI_QTYPE_IPV4ADDR:
2522 (void)printf("IPv4 nodeaddr");
2525 (void)printf("unknown qtype");
2528 if (options & F_VERBOSE) {
2529 if (ni->ni_code > nitems(nircode))
2530 printf(", invalid");
2532 printf(", %s", nircode[ni->ni_code]);
2536 (void)printf("Bad ICMP type: %d", icp->icmp6_type);
2542 * Print an IP6 header.
2545 pr_iph(struct ip6_hdr *ip6)
2547 u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
2549 char ntop_buf[INET6_ADDRSTRLEN];
2551 tc = *(&ip6->ip6_vfc + 1); /* XXX */
2552 tc = (tc >> 4) & 0x0f;
2553 tc |= (ip6->ip6_vfc << 4);
2555 printf("Vr TC Flow Plen Nxt Hlim\n");
2556 printf(" %1x %02x %05x %04x %02x %02x\n",
2557 (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow),
2558 ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim);
2559 if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf)))
2560 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2561 printf("%s->", ntop_buf);
2562 if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf)))
2563 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2564 printf("%s\n", ntop_buf);
2569 * Return an ascii host address as a dotted quad and optionally with
2573 pr_addr(struct sockaddr *addr, int addrlen)
2575 static char buf[NI_MAXHOST];
2578 if ((options & F_HOSTNAME) == 0)
2579 flag |= NI_NUMERICHOST;
2581 if (cap_getnameinfo(capdns, addr, addrlen, buf, sizeof(buf), NULL, 0,
2590 * Dump some info on a returned (via ICMPv6) IPv6 packet.
2593 pr_retip(struct ip6_hdr *ip6, u_char *end)
2595 u_char *cp = (u_char *)ip6, nh;
2598 if ((size_t)(end - (u_char *)ip6) < sizeof(*ip6)) {
2603 hlen = sizeof(*ip6);
2607 while (end - cp >= 8) {
2609 case IPPROTO_HOPOPTS:
2611 hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3;
2612 nh = ((struct ip6_hbh *)cp)->ip6h_nxt;
2614 case IPPROTO_DSTOPTS:
2616 hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3;
2617 nh = ((struct ip6_dest *)cp)->ip6d_nxt;
2619 case IPPROTO_FRAGMENT:
2621 hlen = sizeof(struct ip6_frag);
2622 nh = ((struct ip6_frag *)cp)->ip6f_nxt;
2624 case IPPROTO_ROUTING:
2626 hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3;
2627 nh = ((struct ip6_rthdr *)cp)->ip6r_nxt;
2632 hlen = (((struct ah *)cp)->ah_len+2) << 2;
2633 nh = ((struct ah *)cp)->ah_nxt;
2636 case IPPROTO_ICMPV6:
2637 printf("ICMP6: type = %d, code = %d\n",
2644 printf("TCP: from port %u, to port %u (decimal)\n",
2645 (*cp * 256 + *(cp + 1)),
2646 (*(cp + 2) * 256 + *(cp + 3)));
2649 printf("UDP: from port %u, to port %u (decimal)\n",
2650 (*cp * 256 + *(cp + 1)),
2651 (*(cp + 2) * 256 + *(cp + 3)));
2654 printf("Unknown Header(%d)\n", nh);
2658 if ((cp += hlen) >= end)
2673 fill(char *bp, char *patp)
2679 for (cp = patp; *cp; cp++)
2681 errx(1, "patterns must be specified as hex digits");
2683 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
2684 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
2685 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
2686 &pat[13], &pat[14], &pat[15]);
2691 (size_t)kk <= MAXDATALEN - 8 + sizeof(struct tv32) + ii;
2693 for (jj = 0; jj < ii; ++jj)
2694 bp[jj + kk] = pat[jj];
2695 if (!(options & F_QUIET)) {
2696 (void)printf("PATTERN: 0x");
2697 for (jj = 0; jj < ii; ++jj)
2698 (void)printf("%02x", bp[jj] & 0xFF);
2704 #ifdef IPSEC_POLICY_IPSEC
2706 setpolicy(int so __unused, char *policy)
2711 return 0; /* ignore */
2713 buf = ipsec_set_policy(policy, strlen(policy));
2715 errx(1, "%s", ipsec_strerror());
2716 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_IPSEC_POLICY, buf,
2717 ipsec_get_policylen(buf)) < 0)
2718 warnx("Unable to set IPsec policy");
2727 nigroup(char *name, int nig_oldmcprefix)
2732 u_int8_t digest[16];
2735 char hbuf[NI_MAXHOST];
2736 struct in6_addr in6;
2739 p = strchr(name, '.');
2741 p = name + strlen(name);
2743 if (l > 63 || l > sizeof(hbuf) - 1)
2744 return NULL; /*label too long*/
2745 strncpy(hbuf, name, l);
2746 hbuf[(int)l] = '\0';
2748 for (q = name; *q; q++) {
2749 if (isupper(*(unsigned char *)q))
2750 *q = tolower(*(unsigned char *)q);
2753 /* generate 16 bytes of pseudo-random value. */
2754 memset(&ctxt, 0, sizeof(ctxt));
2757 MD5Update(&ctxt, &c, sizeof(c));
2758 MD5Update(&ctxt, (unsigned char *)name, l);
2759 MD5Final(digest, &ctxt);
2761 if (nig_oldmcprefix) {
2762 /* draft-ietf-ipngwg-icmp-name-lookup */
2763 valid = inet_pton(AF_INET6, "ff02::2:0000:0000", &in6);
2766 valid = inet_pton(AF_INET6, "ff02::2:ff00:0000", &in6);
2769 return NULL; /*XXX*/
2771 if (nig_oldmcprefix) {
2772 /* draft-ietf-ipngwg-icmp-name-lookup */
2773 bcopy(digest, &in6.s6_addr[12], 4);
2776 bcopy(digest, &in6.s6_addr[13], 3);
2779 if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL)
2782 return strdup(hbuf);
2788 (void)fprintf(stderr,
2789 #if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
2794 #if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
2798 #ifdef IPV6_USE_MIN_MTU
2802 "[-a addrtype] [-b bufsiz] [-c count] [-g gateway]\n"
2803 " [-h hoplimit] [-I interface] [-i wait] [-l preload]"
2804 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
2808 " [-p pattern] [-S sourceaddr] [-s packetsize] "
2810 " [-X timeout] [hops ...] host\n");
2814 static cap_channel_t *
2817 cap_channel_t *capcas, *capdnsloc;
2818 const char *types[2];
2821 capcas = cap_init();
2823 err(1, "unable to create casper process");
2824 capdnsloc = cap_service_open(capcas, "system.dns");
2825 /* Casper capability no longer needed. */
2827 if (capdnsloc == NULL)
2828 err(1, "unable to open system.dns service");
2829 types[0] = "NAME2ADDR";
2830 types[1] = "ADDR2NAME";
2831 if (cap_dns_type_limit(capdnsloc, types, nitems(types)) < 0)
2832 err(1, "unable to limit access to system.dns service");
2833 families[0] = AF_INET6;
2834 if (cap_dns_family_limit(capdnsloc, families, nitems(families)) < 0)
2835 err(1, "unable to limit access to system.dns service");