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 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 /* revoke root privilege */
663 if (seteuid(getuid()) != 0)
664 err(1, "seteuid() failed");
665 if (setuid(getuid()) != 0)
666 err(1, "setuid() failed");
668 /* set the source address if specified. */
669 if ((options & F_SRCADDR) != 0) {
670 /* properly fill sin6_scope_id */
671 if (IN6_IS_ADDR_LINKLOCAL(&src.sin6_addr) && (
672 IN6_IS_ADDR_LINKLOCAL(&dst.sin6_addr) ||
673 IN6_IS_ADDR_MC_LINKLOCAL(&dst.sin6_addr) ||
674 IN6_IS_ADDR_MC_NODELOCAL(&dst.sin6_addr))) {
675 if (src.sin6_scope_id == 0)
676 src.sin6_scope_id = dst.sin6_scope_id;
677 if (dst.sin6_scope_id == 0)
678 dst.sin6_scope_id = src.sin6_scope_id;
680 if (bind(ssend, (struct sockaddr *)&src, srclen) != 0)
683 /* set the gateway (next hop) if specified */
685 memset(&hints, 0, sizeof(hints));
686 hints.ai_family = AF_INET6;
687 hints.ai_socktype = SOCK_RAW;
688 hints.ai_protocol = IPPROTO_ICMPV6;
690 error = cap_getaddrinfo(capdns, gateway, NULL, &hints, &res);
692 errx(1, "cap_getaddrinfo for the gateway %s: %s",
693 gateway, gai_strerror(error));
695 if (res->ai_next && (options & F_VERBOSE))
696 warnx("gateway resolves to multiple addresses");
698 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_NEXTHOP,
699 res->ai_addr, res->ai_addrlen)) {
700 err(1, "setsockopt(IPV6_NEXTHOP)");
707 * let the kerel pass extension headers of incoming packets,
708 * for privileged socket options
710 if ((options & F_VERBOSE) != 0) {
713 #ifdef IPV6_RECVHOPOPTS
714 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &opton,
716 err(1, "setsockopt(IPV6_RECVHOPOPTS)");
717 #else /* old adv. API */
718 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPOPTS, &opton,
720 err(1, "setsockopt(IPV6_HOPOPTS)");
722 #ifdef IPV6_RECVDSTOPTS
723 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &opton,
725 err(1, "setsockopt(IPV6_RECVDSTOPTS)");
726 #else /* old adv. API */
727 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_DSTOPTS, &opton,
729 err(1, "setsockopt(IPV6_DSTOPTS)");
731 #ifdef IPV6_RECVRTHDRDSTOPTS
732 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDRDSTOPTS, &opton,
734 err(1, "setsockopt(IPV6_RECVRTHDRDSTOPTS)");
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 = htons(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 = htons(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 = htons(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 = htons(seq);
1373 icp->icmp6_type = ICMP6_ECHO_REQUEST;
1374 icp->icmp6_code = 0;
1375 icp->icmp6_id = htons(ident);
1376 icp->icmp6_seq = htons(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 dnsdecode(const u_char *sp, const u_char *ep, const u_char *base, char *buf,
1436 /*base for compressed name*/
1440 char cresult[MAXDNAME + 1];
1451 if (i == 0 || cp != sp) {
1452 if (strlcat((char *)buf, ".", bufsiz) >= bufsiz)
1453 return NULL; /*result overrun*/
1459 if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) {
1460 /* DNS compression */
1464 comp = base + (i & 0x3f);
1465 if (dnsdecode(comp, cp, base, cresult,
1466 sizeof(cresult)) == NULL)
1468 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1469 return NULL; /*result overrun*/
1471 } else if ((i & 0x3f) == i) {
1473 return NULL; /*source overrun*/
1474 while (i-- > 0 && cp < ep) {
1475 l = snprintf(cresult, sizeof(cresult),
1476 isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff);
1477 if ((size_t)l >= sizeof(cresult) || l < 0)
1479 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1480 return NULL; /*result overrun*/
1484 return NULL; /*invalid label*/
1487 return NULL; /*not terminated*/
1495 * Print out the packet, if it came from us. This logic is necessary
1496 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1497 * which arrive ('tis only fair). This permits multiple copies of this
1498 * program to be run without having intermingled output (or statistics!).
1501 pr_pack(u_char *buf, int cc, struct msghdr *mhdr)
1503 #define safeputc(c) printf((isprint((c)) ? "%c" : "\\%03o"), c)
1504 struct icmp6_hdr *icp;
1505 struct icmp6_nodeinfo *ni;
1508 struct sockaddr *from;
1510 u_char *cp = NULL, *dp, *end = buf + cc;
1511 struct in6_pktinfo *pktinfo = NULL;
1512 struct timeval tv, tp;
1514 double triptime = 0;
1519 char dnsname[MAXDNAME + 1];
1521 (void)gettimeofday(&tv, NULL);
1523 if (!mhdr || !mhdr->msg_name ||
1524 mhdr->msg_namelen != sizeof(struct sockaddr_in6) ||
1525 ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) {
1526 if (options & F_VERBOSE)
1527 warnx("invalid peername");
1530 from = (struct sockaddr *)mhdr->msg_name;
1531 fromlen = mhdr->msg_namelen;
1532 if (cc < (int)sizeof(struct icmp6_hdr)) {
1533 if (options & F_VERBOSE)
1534 warnx("packet too short (%d bytes) from %s", cc,
1535 pr_addr(from, fromlen));
1538 if (((mhdr->msg_flags & MSG_CTRUNC) != 0) &&
1539 (options & F_VERBOSE) != 0)
1540 warnx("some control data discarded, insufficient buffer size");
1541 icp = (struct icmp6_hdr *)buf;
1542 ni = (struct icmp6_nodeinfo *)buf;
1545 if ((hoplim = get_hoplim(mhdr)) == -1) {
1546 warnx("failed to get receiving hop limit");
1549 if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) {
1550 warnx("failed to get receiving packet information");
1554 if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) {
1555 seq = ntohs(icp->icmp6_seq);
1558 tpp = (struct tv32 *)(icp + 1);
1559 tp.tv_sec = ntohl(tpp->tv32_sec);
1560 tp.tv_usec = ntohl(tpp->tv32_usec);
1562 triptime = ((double)tv.tv_sec) * 1000.0 +
1563 ((double)tv.tv_usec) / 1000.0;
1565 tsumsq += triptime * triptime;
1566 if (triptime < tmin)
1568 if (triptime > tmax)
1572 if (TST(seq % mx_dup_ck)) {
1577 SET(seq % mx_dup_ck);
1581 if (options & F_QUIET)
1584 if (options & F_WAITTIME && triptime > waittime) {
1589 if (options & F_FLOOD)
1590 (void)write(STDOUT_FILENO, &BSPACE, 1);
1592 if (options & F_AUDIBLE)
1593 (void)write(STDOUT_FILENO, &BBELL, 1);
1594 (void)printf("%d bytes from %s, icmp_seq=%u", cc,
1595 pr_addr(from, fromlen), seq);
1596 (void)printf(" hlim=%d", hoplim);
1597 if ((options & F_VERBOSE) != 0) {
1598 struct sockaddr_in6 dstsa;
1600 memset(&dstsa, 0, sizeof(dstsa));
1601 dstsa.sin6_family = AF_INET6;
1602 dstsa.sin6_len = sizeof(dstsa);
1603 dstsa.sin6_scope_id = pktinfo->ipi6_ifindex;
1604 dstsa.sin6_addr = pktinfo->ipi6_addr;
1605 (void)printf(" dst=%s",
1606 pr_addr((struct sockaddr *)&dstsa,
1610 (void)printf(" time=%.3f ms", triptime);
1612 (void)printf("(DUP!)");
1613 /* check the data */
1614 cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1615 dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1616 for (i = 8; cp < end; ++i, ++cp, ++dp) {
1618 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp);
1623 } else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) {
1624 seq = ntohs(*(u_int16_t *)ni->icmp6_ni_nonce);
1626 if (TST(seq % mx_dup_ck)) {
1631 SET(seq % mx_dup_ck);
1635 if (options & F_QUIET)
1638 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1640 switch (ntohs(ni->ni_code)) {
1641 case ICMP6_NI_SUCCESS:
1643 case ICMP6_NI_REFUSED:
1644 printf("refused, type 0x%x", ntohs(ni->ni_type));
1646 case ICMP6_NI_UNKNOWN:
1647 printf("unknown, type 0x%x", ntohs(ni->ni_type));
1650 printf("unknown code 0x%x, type 0x%x",
1651 ntohs(ni->ni_code), ntohs(ni->ni_type));
1655 switch (ntohs(ni->ni_qtype)) {
1657 printf("NodeInfo NOOP");
1659 case NI_QTYPE_SUPTYPES:
1660 pr_suptypes(ni, end - (u_char *)ni);
1662 case NI_QTYPE_NODEADDR:
1663 pr_nodeaddr(ni, end - (u_char *)ni);
1666 default: /* XXX: for backward compatibility */
1667 cp = (u_char *)ni + ICMP6_NIRLEN;
1668 if (buf[off + ICMP6_NIRLEN] ==
1669 cc - off - ICMP6_NIRLEN - 1)
1674 cp++; /* skip length */
1676 safeputc(*cp & 0xff);
1682 if (dnsdecode((const u_char *)cp, end,
1683 (const u_char *)(ni + 1), dnsname,
1684 sizeof(dnsname)) == NULL) {
1689 * name-lookup special handling for
1692 if (cp + 1 <= end && !*cp &&
1693 strlen(dnsname) > 0) {
1694 dnsname[strlen(dnsname) - 1] = '\0';
1697 printf("%s%s", i > 0 ? "," : "",
1701 if (options & F_VERBOSE) {
1705 (void)printf(" ("); /*)*/
1707 switch (ni->ni_code) {
1708 case ICMP6_NI_REFUSED:
1709 (void)printf("refused");
1712 case ICMP6_NI_UNKNOWN:
1713 (void)printf("unknown qtype");
1718 if ((end - (u_char *)ni) < ICMP6_NIRLEN) {
1719 /* case of refusion, unknown */
1724 ttl = (int32_t)ntohl(*(u_long *)&buf[off+ICMP6ECHOLEN+8]);
1727 if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) {
1728 (void)printf("TTL=%d:meaningless",
1732 (void)printf("TTL=%d:invalid",
1735 (void)printf("TTL=%d", ttl);
1745 cp = (u_char *)ni + ICMP6_NIRLEN;
1754 if (buf[off + ICMP6_NIRLEN] !=
1755 cc - off - ICMP6_NIRLEN - 1 && oldfqdn) {
1758 (void)printf("invalid namelen:%d/%lu",
1759 buf[off + ICMP6_NIRLEN],
1760 (u_long)cc - off - ICMP6_NIRLEN - 1);
1770 /* We've got something other than an ECHOREPLY */
1771 if (!(options & F_VERBOSE))
1773 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1777 if (!(options & F_FLOOD)) {
1778 (void)putchar('\n');
1779 if (options & F_VERBOSE)
1781 (void)fflush(stdout);
1787 pr_exthdrs(struct msghdr *mhdr)
1794 bufp = mhdr->msg_control;
1795 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1796 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1797 if (cm->cmsg_level != IPPROTO_IPV6)
1800 bufsize = CONTROLLEN - ((caddr_t)CMSG_DATA(cm) - (caddr_t)bufp);
1803 switch (cm->cmsg_type) {
1805 printf(" HbH Options: ");
1806 pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1809 #ifdef IPV6_RTHDRDSTOPTS
1810 case IPV6_RTHDRDSTOPTS:
1812 printf(" Dst Options: ");
1813 pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1816 printf(" Routing: ");
1817 pr_rthdr(CMSG_DATA(cm), (size_t)bufsize);
1824 pr_ip6opt(void *extbuf, size_t bufsize)
1826 struct ip6_hbh *ext;
1829 socklen_t extlen, len;
1835 ext = (struct ip6_hbh *)extbuf;
1836 extlen = (ext->ip6h_len + 1) * 8;
1837 printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt,
1838 (unsigned int)ext->ip6h_len, (unsigned long)extlen);
1841 * Bounds checking on the ancillary data buffer:
1842 * subtract the size of a cmsg structure from the buffer size.
1844 if (bufsize < (extlen + CMSG_SPACE(0))) {
1845 extlen = bufsize - CMSG_SPACE(0);
1846 warnx("options truncated, showing only %u (total=%u)",
1847 (unsigned int)(extlen / 8 - 1),
1848 (unsigned int)(ext->ip6h_len));
1853 currentlen = inet6_opt_next(extbuf, extlen, currentlen,
1854 &type, &len, &databuf);
1855 if (currentlen == -1)
1859 * Note that inet6_opt_next automatically skips any padding
1864 offset = inet6_opt_get_val(databuf, offset,
1865 &value4, sizeof(value4));
1866 printf(" Jumbo Payload Opt: Length %u\n",
1867 (u_int32_t)ntohl(value4));
1869 case IP6OPT_ROUTER_ALERT:
1871 offset = inet6_opt_get_val(databuf, offset,
1872 &value2, sizeof(value2));
1873 printf(" Router Alert Opt: Type %u\n",
1877 printf(" Received Opt %u len %lu\n",
1878 type, (unsigned long)len);
1886 pr_rthdr(void *extbuf, size_t bufsize)
1888 struct in6_addr *in6;
1889 char ntopbuf[INET6_ADDRSTRLEN];
1890 struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf;
1891 int i, segments, origsegs, rthsize, size0, size1;
1893 /* print fixed part of the header */
1894 printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt,
1895 rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type);
1896 if ((segments = inet6_rth_segments(extbuf)) >= 0) {
1897 printf("%d segments, ", segments);
1898 printf("%d left\n", rh->ip6r_segleft);
1900 printf("segments unknown, ");
1901 printf("%d left\n", rh->ip6r_segleft);
1906 * Bounds checking on the ancillary data buffer. When calculating
1907 * the number of items to show keep in mind:
1908 * - The size of the cmsg structure
1909 * - The size of one segment (the size of a Type 0 routing header)
1910 * - When dividing add a fudge factor of one in case the
1911 * dividend is not evenly divisible by the divisor
1913 rthsize = (rh->ip6r_len + 1) * 8;
1914 if (bufsize < (rthsize + CMSG_SPACE(0))) {
1915 origsegs = segments;
1916 size0 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 0);
1917 size1 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 1);
1918 segments -= (rthsize - (bufsize - CMSG_SPACE(0))) /
1919 (size1 - size0) + 1;
1920 warnx("segments truncated, showing only %d (total=%d)",
1921 segments, origsegs);
1924 for (i = 0; i < segments; i++) {
1925 in6 = inet6_rth_getaddr(extbuf, i);
1927 printf(" [%d]<NULL>\n", i);
1929 if (!inet_ntop(AF_INET6, in6, ntopbuf,
1931 strlcpy(ntopbuf, "?", sizeof(ntopbuf));
1932 printf(" [%d]%s\n", i, ntopbuf);
1941 pr_bitrange(u_int32_t v, int soff, int ii)
1948 /* shift till we have 0x01 */
1949 if ((v & 0x01) == 0) {
1951 printf("-%u", soff + off - 1);
1962 case 0x04: case 0x0c:
1973 /* we have 0x01 with us */
1974 for (i = 0; i < 32 - off; i++) {
1975 if ((v & (0x01 << i)) == 0)
1979 printf(" %u", soff + off);
1987 pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen)
1988 /* ni->qtype must be SUPTYPES */
1992 const u_char *cp, *end;
1995 u_int16_t words; /*32bit count*/
1998 #define MAXQTYPES (1 << 16)
2002 cp = (u_char *)(ni + 1);
2003 end = ((u_char *)ni) + nilen;
2007 printf("NodeInfo Supported Qtypes");
2008 if (options & F_VERBOSE) {
2009 if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS)
2010 printf(", compressed bitmap");
2012 printf(", raw bitmap");
2016 clen = (size_t)(end - cp);
2017 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) {
2018 if (clen == 0 || clen > MAXQTYPES / 8 ||
2024 if (clen < sizeof(cbit) || clen % sizeof(v))
2026 memcpy(&cbit, cp, sizeof(cbit));
2027 if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) >
2031 clen = ntohs(cbit.words) * sizeof(v);
2032 if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 >
2037 for (off = 0; off < clen; off += sizeof(v)) {
2038 memcpy(&v, cp + off, sizeof(v));
2039 v = (u_int32_t)ntohl(v);
2040 b = pr_bitrange(v, (int)(cur + off * 8), b);
2042 /* flush the remaining bits */
2043 b = pr_bitrange(0, (int)(cur + off * 8), b);
2047 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0)
2048 cur += ntohs(cbit.skip) * 32;
2053 pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen)
2054 /* ni->qtype must be NODEADDR */
2056 u_char *cp = (u_char *)(ni + 1);
2057 char ntop_buf[INET6_ADDRSTRLEN];
2060 nilen -= sizeof(struct icmp6_nodeinfo);
2062 if (options & F_VERBOSE) {
2063 switch (ni->ni_code) {
2064 case ICMP6_NI_REFUSED:
2065 (void)printf("refused");
2067 case ICMP6_NI_UNKNOWN:
2068 (void)printf("unknown qtype");
2071 if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE)
2072 (void)printf(" truncated");
2076 printf(" no address\n");
2079 * In icmp-name-lookups 05 and later, TTL of each returned address
2080 * is contained in the resposne. We try to detect the version
2081 * by the length of the data, but note that the detection algorithm
2082 * is incomplete. We assume the latest draft by default.
2084 if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0)
2090 /* XXX: alignment? */
2091 ttl = (u_int32_t)ntohl(*(u_int32_t *)cp);
2092 cp += sizeof(u_int32_t);
2093 nilen -= sizeof(u_int32_t);
2096 if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) ==
2098 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2099 printf(" %s", ntop_buf);
2101 if (ttl == 0xffffffff) {
2103 * XXX: can this convention be applied to all
2104 * type of TTL (i.e. non-ND TTL)?
2106 printf("(TTL=infty)");
2109 printf("(TTL=%u)", ttl);
2113 nilen -= sizeof(struct in6_addr);
2114 cp += sizeof(struct in6_addr);
2119 get_hoplim(struct msghdr *mhdr)
2123 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2124 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2125 if (cm->cmsg_len == 0)
2128 if (cm->cmsg_level == IPPROTO_IPV6 &&
2129 cm->cmsg_type == IPV6_HOPLIMIT &&
2130 cm->cmsg_len == CMSG_LEN(sizeof(int)))
2131 return(*(int *)CMSG_DATA(cm));
2137 static struct in6_pktinfo *
2138 get_rcvpktinfo(struct msghdr *mhdr)
2142 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2143 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2144 if (cm->cmsg_len == 0)
2147 if (cm->cmsg_level == IPPROTO_IPV6 &&
2148 cm->cmsg_type == IPV6_PKTINFO &&
2149 cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo)))
2150 return((struct in6_pktinfo *)CMSG_DATA(cm));
2157 get_pathmtu(struct msghdr *mhdr)
2159 #ifdef IPV6_RECVPATHMTU
2161 struct ip6_mtuinfo *mtuctl = NULL;
2163 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2164 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2165 if (cm->cmsg_len == 0)
2168 if (cm->cmsg_level == IPPROTO_IPV6 &&
2169 cm->cmsg_type == IPV6_PATHMTU &&
2170 cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) {
2171 mtuctl = (struct ip6_mtuinfo *)CMSG_DATA(cm);
2174 * If the notified destination is different from
2175 * the one we are pinging, just ignore the info.
2176 * We check the scope ID only when both notified value
2177 * and our own value have non-0 values, because we may
2178 * have used the default scope zone ID for sending,
2179 * in which case the scope ID value is 0.
2181 if (!IN6_ARE_ADDR_EQUAL(&mtuctl->ip6m_addr.sin6_addr,
2183 (mtuctl->ip6m_addr.sin6_scope_id &&
2184 dst.sin6_scope_id &&
2185 mtuctl->ip6m_addr.sin6_scope_id !=
2186 dst.sin6_scope_id)) {
2187 if ((options & F_VERBOSE) != 0) {
2188 printf("path MTU for %s is notified. "
2190 pr_addr((struct sockaddr *)&mtuctl->ip6m_addr,
2191 sizeof(mtuctl->ip6m_addr)));
2197 * Ignore an invalid MTU. XXX: can we just believe
2200 if (mtuctl->ip6m_mtu < IPV6_MMTU)
2203 /* notification for our destination. return the MTU. */
2204 return((int)mtuctl->ip6m_mtu);
2213 * Subtract 2 timeval structs: out = out - in. Out is assumed to
2217 tvsub(struct timeval *out, struct timeval *in)
2219 if ((out->tv_usec -= in->tv_usec) < 0) {
2221 out->tv_usec += 1000000;
2223 out->tv_sec -= in->tv_sec;
2232 onint(int notused __unused)
2235 * When doing reverse DNS lookups, the seenint flag might not
2236 * be noticed for a while. Just exit if we get a second SIGINT.
2238 if ((options & F_HOSTNAME) && seenint != 0)
2239 _exit(nreceived ? 0 : 2);
2244 * Print out statistics.
2250 (void)printf("\n--- %s ping6 statistics ---\n", hostname);
2251 (void)printf("%ld packets transmitted, ", ntransmitted);
2252 (void)printf("%ld packets received, ", nreceived);
2254 (void)printf("+%ld duplicates, ", nrepeats);
2256 if (nreceived > ntransmitted)
2257 (void)printf("-- somebody's duplicating packets!");
2259 (void)printf("%.1f%% packet loss",
2260 ((((double)ntransmitted - nreceived) * 100.0) /
2264 printf(", %ld packets out of wait time", nrcvtimeout);
2265 (void)putchar('\n');
2266 if (nreceived && timing) {
2267 /* Only display average to microseconds */
2268 double num = nreceived + nrepeats;
2269 double avg = tsum / num;
2270 double dev = sqrt(tsumsq / num - avg * avg);
2272 "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
2273 tmin, avg, tmax, dev);
2274 (void)fflush(stdout);
2276 (void)fflush(stdout);
2280 static const char *niqcode[] = {
2282 "DNS label", /*or empty*/
2287 static const char *nircode[] = {
2288 "Success", "Refused", "Unknown",
2294 * Print a descriptive string about an ICMP header.
2297 pr_icmph(struct icmp6_hdr *icp, u_char *end)
2299 char ntop_buf[INET6_ADDRSTRLEN];
2300 struct nd_redirect *red;
2301 struct icmp6_nodeinfo *ni;
2302 char dnsname[MAXDNAME + 1];
2306 switch (icp->icmp6_type) {
2307 case ICMP6_DST_UNREACH:
2308 switch (icp->icmp6_code) {
2309 case ICMP6_DST_UNREACH_NOROUTE:
2310 (void)printf("No Route to Destination\n");
2312 case ICMP6_DST_UNREACH_ADMIN:
2313 (void)printf("Destination Administratively "
2316 case ICMP6_DST_UNREACH_BEYONDSCOPE:
2317 (void)printf("Destination Unreachable Beyond Scope\n");
2319 case ICMP6_DST_UNREACH_ADDR:
2320 (void)printf("Destination Host Unreachable\n");
2322 case ICMP6_DST_UNREACH_NOPORT:
2323 (void)printf("Destination Port Unreachable\n");
2326 (void)printf("Destination Unreachable, Bad Code: %d\n",
2330 /* Print returned IP header information */
2331 pr_retip((struct ip6_hdr *)(icp + 1), end);
2333 case ICMP6_PACKET_TOO_BIG:
2334 (void)printf("Packet too big mtu = %d\n",
2335 (int)ntohl(icp->icmp6_mtu));
2336 pr_retip((struct ip6_hdr *)(icp + 1), end);
2338 case ICMP6_TIME_EXCEEDED:
2339 switch (icp->icmp6_code) {
2340 case ICMP6_TIME_EXCEED_TRANSIT:
2341 (void)printf("Time to live exceeded\n");
2343 case ICMP6_TIME_EXCEED_REASSEMBLY:
2344 (void)printf("Frag reassembly time exceeded\n");
2347 (void)printf("Time exceeded, Bad Code: %d\n",
2351 pr_retip((struct ip6_hdr *)(icp + 1), end);
2353 case ICMP6_PARAM_PROB:
2354 (void)printf("Parameter problem: ");
2355 switch (icp->icmp6_code) {
2356 case ICMP6_PARAMPROB_HEADER:
2357 (void)printf("Erroneous Header ");
2359 case ICMP6_PARAMPROB_NEXTHEADER:
2360 (void)printf("Unknown Nextheader ");
2362 case ICMP6_PARAMPROB_OPTION:
2363 (void)printf("Unrecognized Option ");
2366 (void)printf("Bad code(%d) ", icp->icmp6_code);
2369 (void)printf("pointer = 0x%02x\n",
2370 (u_int32_t)ntohl(icp->icmp6_pptr));
2371 pr_retip((struct ip6_hdr *)(icp + 1), end);
2373 case ICMP6_ECHO_REQUEST:
2374 (void)printf("Echo Request");
2375 /* XXX ID + Seq + Data */
2377 case ICMP6_ECHO_REPLY:
2378 (void)printf("Echo Reply");
2379 /* XXX ID + Seq + Data */
2381 case ICMP6_MEMBERSHIP_QUERY:
2382 (void)printf("Listener Query");
2384 case ICMP6_MEMBERSHIP_REPORT:
2385 (void)printf("Listener Report");
2387 case ICMP6_MEMBERSHIP_REDUCTION:
2388 (void)printf("Listener Done");
2390 case ND_ROUTER_SOLICIT:
2391 (void)printf("Router Solicitation");
2393 case ND_ROUTER_ADVERT:
2394 (void)printf("Router Advertisement");
2396 case ND_NEIGHBOR_SOLICIT:
2397 (void)printf("Neighbor Solicitation");
2399 case ND_NEIGHBOR_ADVERT:
2400 (void)printf("Neighbor Advertisement");
2403 red = (struct nd_redirect *)icp;
2404 (void)printf("Redirect\n");
2405 if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf,
2407 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2408 (void)printf("Destination: %s", ntop_buf);
2409 if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf,
2411 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2412 (void)printf(" New Target: %s", ntop_buf);
2414 case ICMP6_NI_QUERY:
2415 (void)printf("Node Information Query");
2416 /* XXX ID + Seq + Data */
2417 ni = (struct icmp6_nodeinfo *)icp;
2418 l = end - (u_char *)(ni + 1);
2420 switch (ntohs(ni->ni_qtype)) {
2422 (void)printf("NOOP");
2424 case NI_QTYPE_SUPTYPES:
2425 (void)printf("Supported qtypes");
2428 (void)printf("DNS name");
2430 case NI_QTYPE_NODEADDR:
2431 (void)printf("nodeaddr");
2433 case NI_QTYPE_IPV4ADDR:
2434 (void)printf("IPv4 nodeaddr");
2437 (void)printf("unknown qtype");
2440 if (options & F_VERBOSE) {
2441 switch (ni->ni_code) {
2442 case ICMP6_NI_SUBJ_IPV6:
2443 if (l == sizeof(struct in6_addr) &&
2444 inet_ntop(AF_INET6, ni + 1, ntop_buf,
2445 sizeof(ntop_buf)) != NULL) {
2446 (void)printf(", subject=%s(%s)",
2447 niqcode[ni->ni_code], ntop_buf);
2450 /* backward compat to -W */
2451 (void)printf(", oldfqdn");
2453 (void)printf(", invalid");
2457 case ICMP6_NI_SUBJ_FQDN:
2458 if (end == (u_char *)(ni + 1)) {
2459 (void)printf(", no subject");
2462 printf(", subject=%s", niqcode[ni->ni_code]);
2463 cp = (const u_char *)(ni + 1);
2464 if (dnsdecode(cp, end, NULL, dnsname,
2465 sizeof(dnsname)) != NULL)
2466 printf("(%s)", dnsname);
2468 printf("(invalid)");
2470 case ICMP6_NI_SUBJ_IPV4:
2471 if (l == sizeof(struct in_addr) &&
2472 inet_ntop(AF_INET, ni + 1, ntop_buf,
2473 sizeof(ntop_buf)) != NULL) {
2474 (void)printf(", subject=%s(%s)",
2475 niqcode[ni->ni_code], ntop_buf);
2477 (void)printf(", invalid");
2480 (void)printf(", invalid");
2485 case ICMP6_NI_REPLY:
2486 (void)printf("Node Information Reply");
2487 /* XXX ID + Seq + Data */
2488 ni = (struct icmp6_nodeinfo *)icp;
2490 switch (ntohs(ni->ni_qtype)) {
2492 (void)printf("NOOP");
2494 case NI_QTYPE_SUPTYPES:
2495 (void)printf("Supported qtypes");
2498 (void)printf("DNS name");
2500 case NI_QTYPE_NODEADDR:
2501 (void)printf("nodeaddr");
2503 case NI_QTYPE_IPV4ADDR:
2504 (void)printf("IPv4 nodeaddr");
2507 (void)printf("unknown qtype");
2510 if (options & F_VERBOSE) {
2511 if (ni->ni_code > nitems(nircode))
2512 printf(", invalid");
2514 printf(", %s", nircode[ni->ni_code]);
2518 (void)printf("Bad ICMP type: %d", icp->icmp6_type);
2524 * Print an IP6 header.
2527 pr_iph(struct ip6_hdr *ip6)
2529 u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
2531 char ntop_buf[INET6_ADDRSTRLEN];
2533 tc = *(&ip6->ip6_vfc + 1); /* XXX */
2534 tc = (tc >> 4) & 0x0f;
2535 tc |= (ip6->ip6_vfc << 4);
2537 printf("Vr TC Flow Plen Nxt Hlim\n");
2538 printf(" %1x %02x %05x %04x %02x %02x\n",
2539 (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow),
2540 ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim);
2541 if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf)))
2542 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2543 printf("%s->", ntop_buf);
2544 if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf)))
2545 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2546 printf("%s\n", ntop_buf);
2551 * Return an ascii host address as a dotted quad and optionally with
2555 pr_addr(struct sockaddr *addr, int addrlen)
2557 static char buf[NI_MAXHOST];
2560 if ((options & F_HOSTNAME) == 0)
2561 flag |= NI_NUMERICHOST;
2563 if (cap_getnameinfo(capdns, addr, addrlen, buf, sizeof(buf), NULL, 0,
2572 * Dump some info on a returned (via ICMPv6) IPv6 packet.
2575 pr_retip(struct ip6_hdr *ip6, u_char *end)
2577 u_char *cp = (u_char *)ip6, nh;
2580 if ((size_t)(end - (u_char *)ip6) < sizeof(*ip6)) {
2585 hlen = sizeof(*ip6);
2589 while (end - cp >= 8) {
2591 case IPPROTO_HOPOPTS:
2593 hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3;
2594 nh = ((struct ip6_hbh *)cp)->ip6h_nxt;
2596 case IPPROTO_DSTOPTS:
2598 hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3;
2599 nh = ((struct ip6_dest *)cp)->ip6d_nxt;
2601 case IPPROTO_FRAGMENT:
2603 hlen = sizeof(struct ip6_frag);
2604 nh = ((struct ip6_frag *)cp)->ip6f_nxt;
2606 case IPPROTO_ROUTING:
2608 hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3;
2609 nh = ((struct ip6_rthdr *)cp)->ip6r_nxt;
2614 hlen = (((struct ah *)cp)->ah_len+2) << 2;
2615 nh = ((struct ah *)cp)->ah_nxt;
2618 case IPPROTO_ICMPV6:
2619 printf("ICMP6: type = %d, code = %d\n",
2626 printf("TCP: from port %u, to port %u (decimal)\n",
2627 (*cp * 256 + *(cp + 1)),
2628 (*(cp + 2) * 256 + *(cp + 3)));
2631 printf("UDP: from port %u, to port %u (decimal)\n",
2632 (*cp * 256 + *(cp + 1)),
2633 (*(cp + 2) * 256 + *(cp + 3)));
2636 printf("Unknown Header(%d)\n", nh);
2640 if ((cp += hlen) >= end)
2655 fill(char *bp, char *patp)
2661 for (cp = patp; *cp; cp++)
2663 errx(1, "patterns must be specified as hex digits");
2665 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
2666 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
2667 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
2668 &pat[13], &pat[14], &pat[15]);
2673 (size_t)kk <= MAXDATALEN - 8 + sizeof(struct tv32) + ii;
2675 for (jj = 0; jj < ii; ++jj)
2676 bp[jj + kk] = pat[jj];
2677 if (!(options & F_QUIET)) {
2678 (void)printf("PATTERN: 0x");
2679 for (jj = 0; jj < ii; ++jj)
2680 (void)printf("%02x", bp[jj] & 0xFF);
2686 #ifdef IPSEC_POLICY_IPSEC
2688 setpolicy(int so __unused, char *policy)
2693 return 0; /* ignore */
2695 buf = ipsec_set_policy(policy, strlen(policy));
2697 errx(1, "%s", ipsec_strerror());
2698 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_IPSEC_POLICY, buf,
2699 ipsec_get_policylen(buf)) < 0)
2700 warnx("Unable to set IPsec policy");
2709 nigroup(char *name, int nig_oldmcprefix)
2714 u_int8_t digest[16];
2717 char hbuf[NI_MAXHOST];
2718 struct in6_addr in6;
2721 p = strchr(name, '.');
2723 p = name + strlen(name);
2725 if (l > 63 || l > sizeof(hbuf) - 1)
2726 return NULL; /*label too long*/
2727 strncpy(hbuf, name, l);
2728 hbuf[(int)l] = '\0';
2730 for (q = name; *q; q++) {
2731 if (isupper(*(unsigned char *)q))
2732 *q = tolower(*(unsigned char *)q);
2735 /* generate 16 bytes of pseudo-random value. */
2736 memset(&ctxt, 0, sizeof(ctxt));
2739 MD5Update(&ctxt, &c, sizeof(c));
2740 MD5Update(&ctxt, (unsigned char *)name, l);
2741 MD5Final(digest, &ctxt);
2743 if (nig_oldmcprefix) {
2744 /* draft-ietf-ipngwg-icmp-name-lookup */
2745 valid = inet_pton(AF_INET6, "ff02::2:0000:0000", &in6);
2748 valid = inet_pton(AF_INET6, "ff02::2:ff00:0000", &in6);
2751 return NULL; /*XXX*/
2753 if (nig_oldmcprefix) {
2754 /* draft-ietf-ipngwg-icmp-name-lookup */
2755 bcopy(digest, &in6.s6_addr[12], 4);
2758 bcopy(digest, &in6.s6_addr[13], 3);
2761 if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL)
2764 return strdup(hbuf);
2770 (void)fprintf(stderr,
2771 #if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
2776 #if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC)
2780 #ifdef IPV6_USE_MIN_MTU
2784 "[-a addrtype] [-b bufsiz] [-c count] [-g gateway]\n"
2785 " [-h hoplimit] [-I interface] [-i wait] [-l preload]"
2786 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
2790 " [-p pattern] [-S sourceaddr] [-s packetsize] "
2792 " [-X timeout] [hops ...] host\n");
2796 static cap_channel_t *
2799 cap_channel_t *capcas, *capdnsloc;
2800 const char *types[2];
2803 capcas = cap_init();
2805 err(1, "unable to create casper process");
2806 capdnsloc = cap_service_open(capcas, "system.dns");
2807 /* Casper capability no longer needed. */
2809 if (capdnsloc == NULL)
2810 err(1, "unable to open system.dns service");
2811 types[0] = "NAME2ADDR";
2812 types[1] = "ADDR2NAME";
2813 if (cap_dns_type_limit(capdnsloc, types, nitems(types)) < 0)
2814 err(1, "unable to limit access to system.dns service");
2815 families[0] = AF_INET6;
2816 if (cap_dns_family_limit(capdnsloc, families, nitems(families)) < 0)
2817 err(1, "unable to limit access to system.dns service");