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
70 static const char copyright[] =
71 "@(#) Copyright (c) 1989, 1993\n\
72 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>
112 #include <net/route.h>
114 #include <netinet/in.h>
115 #include <netinet/ip6.h>
116 #include <netinet/icmp6.h>
117 #include <arpa/inet.h>
118 #include <arpa/nameser.h>
121 #include <capsicum_helpers.h>
122 #include <casper/cap_dns.h>
123 #include <libcasper.h>
134 #include <sysexits.h>
139 #include <netipsec/ah.h>
140 #include <netipsec/ipsec.h>
153 #define MAXPACKETLEN 131072
155 #define ICMP6ECHOLEN 8 /* icmp echo header len excluding time */
156 #define ICMP6ECHOTMLEN sizeof(struct tv32)
157 #define ICMP6_NIQLEN (ICMP6ECHOLEN + 8)
158 # define CONTROLLEN 10240 /* ancillary data buffer size RFC3542 20.1 */
159 /* FQDN case, 64 bits of nonce + 32 bits ttl */
160 #define ICMP6_NIRLEN (ICMP6ECHOLEN + 12)
161 #define EXTRA 256 /* for AH and various other headers. weird. */
162 #define DEFDATALEN ICMP6ECHOTMLEN
163 #define MAXDATALEN MAXPACKETLEN - IP6LEN - ICMP6ECHOLEN
164 #define NROUTES 9 /* number of record route slots */
165 #define MAXWAIT 10000 /* max ms to wait for response */
166 #define MAXALARM (60 * 60) /* max seconds for alarm timeout */
168 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
169 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
170 #define SET(bit) (A(bit) |= B(bit))
171 #define CLR(bit) (A(bit) &= (~B(bit)))
172 #define TST(bit) (A(bit) & B(bit))
174 #define F_FLOOD 0x0001
175 #define F_INTERVAL 0x0002
176 #define F_PINGFILLED 0x0008
177 #define F_QUIET 0x0010
178 #define F_RROUTE 0x0020
179 #define F_SO_DEBUG 0x0040
180 #define F_VERBOSE 0x0100
182 #ifdef IPSEC_POLICY_IPSEC
183 #define F_POLICY 0x0400
185 #define F_AUTHHDR 0x0200
186 #define F_ENCRYPT 0x0400
187 #endif /*IPSEC_POLICY_IPSEC*/
189 #define F_NODEADDR 0x0800
190 #define F_FQDN 0x1000
191 #define F_INTERFACE 0x2000
192 #define F_SRCADDR 0x4000
193 #define F_HOSTNAME 0x10000
194 #define F_FQDNOLD 0x20000
195 #define F_NIGROUP 0x40000
196 #define F_SUPTYPES 0x80000
197 #define F_NOMINMTU 0x100000
198 #define F_ONCE 0x200000
199 #define F_AUDIBLE 0x400000
200 #define F_MISSED 0x800000
201 #define F_DONTFRAG 0x1000000
202 #define F_NOUSERDATA (F_NODEADDR | F_FQDN | F_FQDNOLD | F_SUPTYPES)
203 #define F_WAITTIME 0x2000000
204 static u_int options;
206 #define IN6LEN sizeof(struct in6_addr)
207 #define SA6LEN sizeof(struct sockaddr_in6)
208 #define DUMMY_PORT 10101
210 #define SIN6(s) ((struct sockaddr_in6 *)(s))
213 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
214 * number of received sequence numbers we can keep track of. Change 128
215 * to 8192 for complete accuracy...
217 #define MAX_DUP_CHK (8 * 8192)
218 static int mx_dup_ck = MAX_DUP_CHK;
219 static char rcvd_tbl[MAX_DUP_CHK / 8];
221 static struct sockaddr_in6 dst; /* who to ping6 */
222 static struct sockaddr_in6 src; /* src addr of this packet */
223 static socklen_t srclen;
224 static size_t datalen = DEFDATALEN;
225 static int ssend; /* send socket file descriptor */
226 static int srecv; /* receive socket file descriptor */
227 static u_char outpack[MAXPACKETLEN];
228 static char BSPACE = '\b'; /* characters written for flood */
229 static char BBELL = '\a'; /* characters written for AUDIBLE */
230 static char DOT = '.';
231 static char *hostname;
232 static int ident; /* process id to identify our packets */
233 static u_int8_t nonce[8]; /* nonce field for node information */
234 static int hoplimit = -1; /* hoplimit */
235 static int tclass = -1; /* traffic class */
236 static int pcp = -2; /* vlan priority code point */
237 static u_char *packet = NULL;
238 static cap_channel_t *capdns;
241 static long nmissedmax; /* max value of ntransmitted - nreceived - 1 */
242 static long npackets; /* max packets to transmit */
243 static long nreceived; /* # of packets we got back */
244 static long nrepeats; /* number of duplicates */
245 static long ntransmitted; /* sequence # for outbound packets = #sent */
246 static long ntransmitfailures; /* number of transmit failures */
247 static int interval = 1000; /* interval between packets in ms */
248 static int waittime = MAXWAIT; /* timeout for each packet */
249 static long nrcvtimeout = 0; /* # of packets we got back after waittime */
252 static int timing; /* flag to do timing */
253 static double tmin = 999999999.0; /* minimum round trip time */
254 static double tmax = 0.0; /* maximum round trip time */
255 static double tsum = 0.0; /* sum of all times, for doing average */
256 static double tsumsq = 0.0; /* sum of all times squared, for std. dev. */
258 /* for node addresses */
259 static u_short naflags;
261 /* for ancillary data(advanced API) */
262 static struct msghdr smsghdr;
263 static struct iovec smsgiov;
264 static char *scmsg = 0;
266 static volatile sig_atomic_t seenint;
268 static volatile sig_atomic_t seeninfo;
271 static cap_channel_t *capdns_setup(void);
272 static void fill(char *, char *);
273 static int get_hoplim(struct msghdr *);
274 static int get_pathmtu(struct msghdr *);
275 static struct in6_pktinfo *get_rcvpktinfo(struct msghdr *);
276 static void onsignal(int);
277 static void onint(int);
278 static size_t pingerlen(void);
279 static int pinger(void);
280 static const char *pr_addr(struct sockaddr *, int);
281 static void pr_icmph(struct icmp6_hdr *, u_char *);
282 static void pr_iph(struct ip6_hdr *);
283 static void pr_suptypes(struct icmp6_nodeinfo *, size_t);
284 static void pr_nodeaddr(struct icmp6_nodeinfo *, int);
285 static int myechoreply(const struct icmp6_hdr *);
286 static int mynireply(const struct icmp6_nodeinfo *);
287 static const char *dnsdecode(const u_char *, const u_char *, const u_char *,
289 static void pr_pack(u_char *, int, struct msghdr *);
290 static void pr_exthdrs(struct msghdr *);
291 static void pr_ip6opt(void *, size_t);
292 static void pr_rthdr(void *, size_t);
293 static int pr_bitrange(u_int32_t, int, int);
294 static void pr_retip(struct ip6_hdr *, u_char *);
295 static void summary(void);
296 static int setpolicy(int, char *);
297 static char *nigroup(char *, int);
300 ping6(int argc, char *argv[])
302 struct timespec last, intvl;
303 struct sockaddr_in6 from, *sin6;
304 struct addrinfo hints, *res;
305 struct sigaction si_sa;
307 int almost_done, ch, hold, packlen, preload, optval, error;
308 int nig_oldmcprefix = -1;
310 char *e, *target, *ifname = NULL, *gateway = NULL;
312 struct cmsghdr *scmsgp = NULL;
313 /* For control (ancillary) data received from recvmsg() */
314 u_char cm[CONTROLLEN];
315 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
320 struct in6_pktinfo pktinfo;
321 char *cmsg_pktinfo = NULL;
322 struct ip6_rthdr *rthdr = NULL;
323 #ifdef IPSEC_POLICY_IPSEC
324 char *policy_in = NULL;
325 char *policy_out = NULL;
330 #ifdef IPV6_USE_MIN_MTU
333 cap_rights_t rights_srecv;
334 cap_rights_t rights_ssend;
335 cap_rights_t rights_stdin;
337 /* just to be sure */
338 memset(&smsghdr, 0, sizeof(smsghdr));
339 memset(&smsgiov, 0, sizeof(smsgiov));
340 memset(&pktinfo, 0, sizeof(pktinfo));
342 intvl.tv_sec = interval / 1000;
343 intvl.tv_nsec = interval % 1000 * 1000000;
345 alarmtimeout = preload = 0;
346 datap = &outpack[ICMP6ECHOLEN + ICMP6ECHOTMLEN];
347 capdns = capdns_setup();
351 #ifdef IPSEC_POLICY_IPSEC
355 #endif /*IPSEC_POLICY_IPSEC*/
357 while ((ch = getopt(argc, argv,
358 "6k:b:C:c:DdfHe:m:I:i:l:unNop:qaAS:s:OvyYW:t:z:" ADDOPTS)) != -1) {
362 /* This option is processed in main(). */
368 options &= ~F_NOUSERDATA;
369 options |= F_NODEADDR;
370 for (cp = optarg; *cp != '\0'; cp++) {
373 naflags |= NI_NODEADDR_FLAG_ALL;
377 naflags |= NI_NODEADDR_FLAG_COMPAT;
381 naflags |= NI_NODEADDR_FLAG_LINKLOCAL;
385 naflags |= NI_NODEADDR_FLAG_SITELOCAL;
389 naflags |= NI_NODEADDR_FLAG_GLOBAL;
391 case 'A': /* experimental. not in the spec */
392 #ifdef NI_NODEADDR_FLAG_ANYCAST
393 naflags |= NI_NODEADDR_FLAG_ANYCAST;
397 "-a A is not supported on the platform");
408 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
411 lsockbufsize = strtoul(optarg, &e, 10);
412 sockbufsize = (int)lsockbufsize;
413 if (errno || !*optarg || *e ||
414 lsockbufsize > INT_MAX)
415 errx(1, "invalid socket buffer size");
418 "-b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported");
421 case 'C': /* vlan priority code point */
422 pcp = strtol(optarg, &e, 10);
423 if (*optarg == '\0' || *e != '\0')
424 errx(1, "illegal vlan pcp %s", optarg);
425 if (7 < pcp || pcp < -1)
426 errx(1, "illegal vlan pcp -- %s", optarg);
429 npackets = strtol(optarg, &e, 10);
430 if (npackets <= 0 || *optarg == '\0' || *e != '\0')
432 "illegal number of packets -- %s", optarg);
435 options |= F_DONTFRAG;
438 options |= F_SO_DEBUG;
443 errx(1, "Must be superuser to flood ping");
446 setbuf(stdout, (char *)NULL);
452 options |= F_HOSTNAME;
454 case 'm': /* hoplimit */
455 hoplimit = strtol(optarg, &e, 10);
456 if (*optarg == '\0' || *e != '\0')
457 errx(1, "illegal hoplimit %s", optarg);
458 if (255 < hoplimit || hoplimit < -1)
460 "illegal hoplimit -- %s", optarg);
464 options |= F_INTERFACE;
465 #ifndef USE_SIN6_SCOPE_ID
469 case 'i': /* wait between sending packets */
470 t = strtod(optarg, &e);
471 if (*optarg == '\0' || *e != '\0')
472 errx(1, "illegal timing interval %s", optarg);
473 if (t < 1 && getuid()) {
474 errx(1, "%s: only root may use interval < 1s",
477 intvl.tv_sec = (time_t)t;
479 (long)((t - intvl.tv_sec) * 1000000000);
480 if (intvl.tv_sec < 0)
481 errx(1, "illegal timing interval %s", optarg);
482 /* less than 1/hz does not make sense */
483 if (intvl.tv_sec == 0 && intvl.tv_nsec < 1000) {
484 warnx("too small interval, raised to .000001");
485 intvl.tv_nsec = 1000;
487 options |= F_INTERVAL;
492 errx(1, "Must be superuser to preload");
494 preload = strtol(optarg, &e, 10);
495 if (preload < 0 || *optarg == '\0' || *e != '\0')
496 errx(1, "illegal preload value -- %s", optarg);
499 #ifdef IPV6_USE_MIN_MTU
503 errx(1, "-%c is not supported on this platform", ch);
507 options &= ~F_HOSTNAME;
510 options |= F_NIGROUP;
516 case 'p': /* fill buffer with user pattern */
517 options |= F_PINGFILLED;
518 fill((char *)datap, optarg);
524 options |= F_AUDIBLE;
530 memset(&hints, 0, sizeof(struct addrinfo));
531 hints.ai_flags = AI_NUMERICHOST; /* allow hostname? */
532 hints.ai_family = AF_INET6;
533 hints.ai_socktype = SOCK_RAW;
534 hints.ai_protocol = IPPROTO_ICMPV6;
536 error = cap_getaddrinfo(capdns, optarg, NULL, &hints, &res);
538 errx(1, "invalid source address: %s",
539 gai_strerror(error));
542 * res->ai_family must be AF_INET6 and res->ai_addrlen
543 * must be sizeof(src).
545 memcpy(&src, res->ai_addr, res->ai_addrlen);
546 srclen = res->ai_addrlen;
548 options |= F_SRCADDR;
550 case 's': /* size of packet to send */
551 datalen = strtol(optarg, &e, 10);
552 if (datalen <= 0 || *optarg == '\0' || *e != '\0')
553 errx(1, "illegal datalen value -- %s", optarg);
554 if (datalen > MAXDATALEN) {
556 "datalen value too large, maximum is %d",
561 options &= ~F_NOUSERDATA;
562 options |= F_SUPTYPES;
565 options |= F_VERBOSE;
568 options &= ~F_NOUSERDATA;
572 options &= ~F_NOUSERDATA;
573 options |= F_FQDNOLD;
576 t = strtod(optarg, &e);
577 if (*e || e == optarg || t > (double)INT_MAX)
578 err(EX_USAGE, "invalid timing interval: `%s'",
580 options |= F_WAITTIME;
584 alarmtimeout = strtoul(optarg, &e, 0);
585 if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX))
586 errx(EX_USAGE, "invalid timeout: `%s'",
588 if (alarmtimeout > MAXALARM)
589 errx(EX_USAGE, "invalid timeout: `%s' > %d",
592 struct itimerval itv;
594 timerclear(&itv.it_interval);
595 timerclear(&itv.it_value);
596 itv.it_value.tv_sec = (time_t)alarmtimeout;
597 if (setitimer(ITIMER_REAL, &itv, NULL) != 0)
601 case 'z': /* traffic class */
602 tclass = strtol(optarg, &e, 10);
603 if (*optarg == '\0' || *e != '\0')
604 errx(1, "illegal traffic class %s", optarg);
605 if (255 < tclass || tclass < -1)
607 "illegal traffic class -- %s", optarg);
610 #ifdef IPSEC_POLICY_IPSEC
613 if (!strncmp("in", optarg, 2)) {
614 if ((policy_in = strdup(optarg)) == NULL)
616 } else if (!strncmp("out", optarg, 3)) {
617 if ((policy_out = strdup(optarg)) == NULL)
620 errx(1, "invalid security policy");
624 options |= F_AUTHHDR;
627 options |= F_ENCRYPT;
629 #endif /*IPSEC_POLICY_IPSEC*/
646 #ifdef IPV6_RECVRTHDR /* 2292bis */
647 rthlen = CMSG_SPACE(inet6_rth_space(IPV6_RTHDR_TYPE_0,
650 rthlen = inet6_rthdr_space(IPV6_RTHDR_TYPE_0, argc - 1);
653 errx(1, "too many intermediate hops");
659 if (options & F_NIGROUP) {
660 target = nigroup(argv[argc - 1], nig_oldmcprefix);
661 if (target == NULL) {
666 target = argv[argc - 1];
668 /* cap_getaddrinfo */
669 memset(&hints, 0, sizeof(struct addrinfo));
670 hints.ai_flags = AI_CANONNAME;
671 hints.ai_family = AF_INET6;
672 hints.ai_socktype = SOCK_RAW;
673 hints.ai_protocol = IPPROTO_ICMPV6;
675 error = cap_getaddrinfo(capdns, target, NULL, &hints, &res);
677 errx(1, "%s", gai_strerror(error));
678 if (res->ai_canonname)
679 hostname = strdup(res->ai_canonname);
684 errx(1, "cap_getaddrinfo failed");
686 (void)memcpy(&dst, res->ai_addr, res->ai_addrlen);
688 if ((ssend = socket(res->ai_family, res->ai_socktype,
689 res->ai_protocol)) < 0)
690 err(1, "socket ssend");
691 if ((srecv = socket(res->ai_family, res->ai_socktype,
692 res->ai_protocol)) < 0)
693 err(1, "socket srecv");
696 /* set the source address if specified. */
697 if ((options & F_SRCADDR) != 0) {
698 /* properly fill sin6_scope_id */
699 if (IN6_IS_ADDR_LINKLOCAL(&src.sin6_addr) && (
700 IN6_IS_ADDR_LINKLOCAL(&dst.sin6_addr) ||
701 IN6_IS_ADDR_MC_LINKLOCAL(&dst.sin6_addr) ||
702 IN6_IS_ADDR_MC_NODELOCAL(&dst.sin6_addr))) {
703 if (src.sin6_scope_id == 0)
704 src.sin6_scope_id = dst.sin6_scope_id;
705 if (dst.sin6_scope_id == 0)
706 dst.sin6_scope_id = src.sin6_scope_id;
708 if (bind(ssend, (struct sockaddr *)&src, srclen) != 0)
711 /* set the gateway (next hop) if specified */
713 memset(&hints, 0, sizeof(hints));
714 hints.ai_family = AF_INET6;
715 hints.ai_socktype = SOCK_RAW;
716 hints.ai_protocol = IPPROTO_ICMPV6;
718 error = cap_getaddrinfo(capdns, gateway, NULL, &hints, &res);
720 errx(1, "cap_getaddrinfo for the gateway %s: %s",
721 gateway, gai_strerror(error));
723 if (res->ai_next && (options & F_VERBOSE))
724 warnx("gateway resolves to multiple addresses");
726 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_NEXTHOP,
727 res->ai_addr, res->ai_addrlen)) {
728 err(1, "setsockopt(IPV6_NEXTHOP)");
735 * let the kerel pass extension headers of incoming packets,
736 * for privileged socket options
738 if ((options & F_VERBOSE) != 0) {
741 #ifdef IPV6_RECVHOPOPTS
742 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &opton,
744 err(1, "setsockopt(IPV6_RECVHOPOPTS)");
745 #else /* old adv. API */
746 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPOPTS, &opton,
748 err(1, "setsockopt(IPV6_HOPOPTS)");
750 #ifdef IPV6_RECVDSTOPTS
751 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &opton,
753 err(1, "setsockopt(IPV6_RECVDSTOPTS)");
754 #else /* old adv. API */
755 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_DSTOPTS, &opton,
757 err(1, "setsockopt(IPV6_DSTOPTS)");
759 #ifdef IPV6_RECVRTHDRDSTOPTS
760 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDRDSTOPTS, &opton,
762 err(1, "setsockopt(IPV6_RECVRTHDRDSTOPTS)");
766 /* revoke root privilege */
767 if (seteuid(getuid()) != 0)
768 err(1, "seteuid() failed");
769 if (setuid(getuid()) != 0)
770 err(1, "setuid() failed");
772 if ((options & F_FLOOD) && (options & F_INTERVAL))
773 errx(1, "-f and -i incompatible options");
775 if ((options & F_NOUSERDATA) == 0) {
776 if (datalen >= sizeof(struct tv32)) {
777 /* we can time transfer */
781 /* in F_VERBOSE case, we may get non-echoreply packets*/
782 if (options & F_VERBOSE)
783 packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
785 packlen = datalen + IP6LEN + ICMP6ECHOLEN + EXTRA;
787 /* suppress timing for node information query */
790 packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA;
793 if (!(packet = (u_char *)malloc((u_int)packlen)))
794 err(1, "Unable to allocate packet");
795 if (!(options & F_PINGFILLED))
796 for (i = ICMP6ECHOLEN; i < packlen; ++i)
799 ident = getpid() & 0xFFFF;
800 arc4random_buf(nonce, sizeof(nonce));
802 if (options & F_DONTFRAG)
803 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_DONTFRAG,
804 &optval, sizeof(optval)) == -1)
805 err(1, "IPV6_DONTFRAG");
808 if (options & F_SO_DEBUG) {
809 (void)setsockopt(ssend, SOL_SOCKET, SO_DEBUG, (char *)&hold,
811 (void)setsockopt(srecv, SOL_SOCKET, SO_DEBUG, (char *)&hold,
814 optval = IPV6_DEFHLIM;
815 if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
816 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
817 &optval, sizeof(optval)) == -1)
818 err(1, "IPV6_MULTICAST_HOPS");
819 #ifdef IPV6_USE_MIN_MTU
821 optval = mflag > 1 ? 0 : 1;
823 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
824 &optval, sizeof(optval)) == -1)
825 err(1, "setsockopt(IPV6_USE_MIN_MTU)");
827 #ifdef IPV6_RECVPATHMTU
830 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVPATHMTU,
831 &optval, sizeof(optval)) == -1)
832 err(1, "setsockopt(IPV6_RECVPATHMTU)");
834 #endif /* IPV6_RECVPATHMTU */
835 #endif /* IPV6_USE_MIN_MTU */
838 #ifdef IPSEC_POLICY_IPSEC
839 if (options & F_POLICY) {
840 if (setpolicy(srecv, policy_in) < 0)
841 errx(1, "%s", ipsec_strerror());
842 if (setpolicy(ssend, policy_out) < 0)
843 errx(1, "%s", ipsec_strerror());
846 if (options & F_AUTHHDR) {
847 optval = IPSEC_LEVEL_REQUIRE;
848 #ifdef IPV6_AUTH_TRANS_LEVEL
849 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL,
850 &optval, sizeof(optval)) == -1)
851 err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)");
852 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL,
853 &optval, sizeof(optval)) == -1)
854 err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)");
856 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_AUTH_LEVEL,
857 &optval, sizeof(optval)) == -1)
858 err(1, "setsockopt(IPV6_AUTH_LEVEL)");
859 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_AUTH_LEVEL,
860 &optval, sizeof(optval)) == -1)
861 err(1, "setsockopt(IPV6_AUTH_LEVEL)");
864 if (options & F_ENCRYPT) {
865 optval = IPSEC_LEVEL_REQUIRE;
866 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL,
867 &optval, sizeof(optval)) == -1)
868 err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)");
869 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL,
870 &optval, sizeof(optval)) == -1)
871 err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)");
873 #endif /*IPSEC_POLICY_IPSEC*/
878 struct icmp6_filter filt;
879 if (!(options & F_VERBOSE)) {
880 ICMP6_FILTER_SETBLOCKALL(&filt);
881 if ((options & F_FQDN) || (options & F_FQDNOLD) ||
882 (options & F_NODEADDR) || (options & F_SUPTYPES))
883 ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filt);
885 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
887 ICMP6_FILTER_SETPASSALL(&filt);
889 if (setsockopt(srecv, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
891 err(1, "setsockopt(ICMP6_FILTER)");
893 #endif /*ICMP6_FILTER*/
895 /* let the kerel pass extension headers of incoming packets */
896 if ((options & F_VERBOSE) != 0) {
899 #ifdef IPV6_RECVRTHDR
900 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDR, &opton,
902 err(1, "setsockopt(IPV6_RECVRTHDR)");
903 #else /* old adv. API */
904 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RTHDR, &opton,
906 err(1, "setsockopt(IPV6_RTHDR)");
912 if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr))
913 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
914 &optval, sizeof(optval)) == -1)
915 err(1, "IPV6_MULTICAST_LOOP");
918 /* Specify the outgoing interface and/or the source address */
920 ip6optlen += CMSG_SPACE(sizeof(struct in6_pktinfo));
923 ip6optlen += CMSG_SPACE(sizeof(int));
925 /* set IP6 packet options */
927 if ((scmsg = (char *)malloc(ip6optlen)) == NULL)
928 errx(1, "can't allocate enough memory");
929 smsghdr.msg_control = (caddr_t)scmsg;
930 smsghdr.msg_controllen = ip6optlen;
931 scmsgp = CMSG_FIRSTHDR(&smsghdr);
934 cmsg_pktinfo = CMSG_DATA(scmsgp);
935 scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
936 scmsgp->cmsg_level = IPPROTO_IPV6;
937 scmsgp->cmsg_type = IPV6_PKTINFO;
938 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
941 /* set the outgoing interface */
943 #ifndef USE_SIN6_SCOPE_ID
944 /* pktinfo must have already been allocated */
945 if ((pktinfo.ipi6_ifindex = if_nametoindex(ifname)) == 0)
946 errx(1, "%s: invalid interface name", ifname);
948 if ((dst.sin6_scope_id = if_nametoindex(ifname)) == 0)
949 errx(1, "%s: invalid interface name", ifname);
952 if (hoplimit != -1) {
953 scmsgp->cmsg_len = CMSG_LEN(sizeof(int));
954 scmsgp->cmsg_level = IPPROTO_IPV6;
955 scmsgp->cmsg_type = IPV6_HOPLIMIT;
956 memcpy(CMSG_DATA(scmsgp), &hoplimit, sizeof(hoplimit));
958 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
962 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_TCLASS,
963 &tclass, sizeof(tclass)) == -1)
964 err(1, "setsockopt(IPV6_TCLASS)");
968 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_VLAN_PCP,
969 &pcp, sizeof(pcp)) == -1)
970 err(1, "setsockopt(IPV6_VLAN_PCP)");
973 if (argc > 1) { /* some intermediate addrs are specified */
977 rthdrlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1);
978 scmsgp->cmsg_len = CMSG_LEN(rthdrlen);
979 scmsgp->cmsg_level = IPPROTO_IPV6;
980 scmsgp->cmsg_type = IPV6_RTHDR;
981 rthdr = (struct ip6_rthdr *)CMSG_DATA(scmsgp);
982 rthdr = inet6_rth_init((void *)rthdr, rthdrlen,
983 IPV6_RTHDR_TYPE_0, argc - 1);
985 errx(1, "can't initialize rthdr");
987 for (hops = 0; hops < argc - 1; hops++) {
988 memset(&hints, 0, sizeof(hints));
989 hints.ai_family = AF_INET6;
991 if ((error = cap_getaddrinfo(capdns, argv[hops], NULL, &hints,
993 errx(1, "%s", gai_strerror(error));
994 if (res->ai_addr->sa_family != AF_INET6)
996 "bad addr family of an intermediate addr");
997 sin6 = (struct sockaddr_in6 *)(void *)res->ai_addr;
998 if (inet6_rth_add(rthdr, &sin6->sin6_addr))
999 errx(1, "can't add an intermediate node");
1003 scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp);
1006 /* From now on we will use only reverse DNS lookups. */
1008 if (capdns != NULL) {
1009 const char *types[1];
1011 types[0] = "ADDR2NAME";
1012 if (cap_dns_type_limit(capdns, types, nitems(types)) < 0)
1013 err(1, "unable to limit access to system.dns service");
1016 if (!(options & F_SRCADDR)) {
1018 * get the source address. XXX since we revoked the root
1019 * privilege, we cannot use a raw socket for this.
1022 socklen_t len = sizeof(src);
1024 if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1025 err(1, "UDP socket");
1027 src.sin6_family = AF_INET6;
1028 src.sin6_addr = dst.sin6_addr;
1029 src.sin6_port = ntohs(DUMMY_PORT);
1030 src.sin6_scope_id = dst.sin6_scope_id;
1033 setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTINFO,
1034 (void *)&pktinfo, sizeof(pktinfo)))
1035 err(1, "UDP setsockopt(IPV6_PKTINFO)");
1037 if (hoplimit != -1 &&
1038 setsockopt(dummy, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1039 (void *)&hoplimit, sizeof(hoplimit)))
1040 err(1, "UDP setsockopt(IPV6_UNICAST_HOPS)");
1042 if (hoplimit != -1 &&
1043 setsockopt(dummy, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1044 (void *)&hoplimit, sizeof(hoplimit)))
1045 err(1, "UDP setsockopt(IPV6_MULTICAST_HOPS)");
1048 setsockopt(dummy, IPPROTO_IPV6, IPV6_RTHDR,
1049 (void *)rthdr, (rthdr->ip6r_len + 1) << 3))
1050 err(1, "UDP setsockopt(IPV6_RTHDR)");
1052 if (connect(dummy, (struct sockaddr *)&src, len) < 0)
1053 err(1, "UDP connect");
1055 if (getsockname(dummy, (struct sockaddr *)&src, &len) < 0)
1056 err(1, "getsockname");
1061 /* Save pktinfo in the ancillary data. */
1063 memcpy(cmsg_pktinfo, &pktinfo, sizeof(pktinfo));
1065 if (connect(ssend, (struct sockaddr *)&dst, sizeof(dst)) != 0)
1066 err(1, "connect() ssend");
1068 caph_cache_catpages();
1069 if (caph_enter_casper() < 0)
1070 err(1, "caph_enter_casper");
1072 cap_rights_init(&rights_stdin);
1073 if (caph_rights_limit(STDIN_FILENO, &rights_stdin) < 0)
1074 err(1, "caph_rights_limit stdin");
1075 if (caph_limit_stdout() < 0)
1076 err(1, "caph_limit_stdout");
1077 if (caph_limit_stderr() < 0)
1078 err(1, "caph_limit_stderr");
1080 cap_rights_init(&rights_srecv, CAP_RECV, CAP_EVENT, CAP_SETSOCKOPT);
1081 if (caph_rights_limit(srecv, &rights_srecv) < 0)
1082 err(1, "caph_rights_limit srecv");
1083 cap_rights_init(&rights_ssend, CAP_SEND, CAP_SETSOCKOPT);
1084 if (caph_rights_limit(ssend, &rights_ssend) < 0)
1085 err(1, "caph_rights_limit ssend");
1087 #if defined(SO_SNDBUF) && defined(SO_RCVBUF)
1089 if (datalen > (size_t)sockbufsize)
1090 warnx("you need -b to increase socket buffer size");
1091 if (setsockopt(ssend, SOL_SOCKET, SO_SNDBUF, &sockbufsize,
1092 sizeof(sockbufsize)) < 0)
1093 err(1, "setsockopt(SO_SNDBUF)");
1094 if (setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, &sockbufsize,
1095 sizeof(sockbufsize)) < 0)
1096 err(1, "setsockopt(SO_RCVBUF)");
1099 if (datalen > 8 * 1024) /*XXX*/
1100 warnx("you need -b to increase socket buffer size");
1102 * When pinging the broadcast address, you can get a lot of
1103 * answers. Doing something so evil is useful if you are trying
1104 * to stress the ethernet, or just want to fill the arp cache
1105 * to get some stuff for /etc/ethers.
1108 setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
1114 #ifndef USE_SIN6_SCOPE_ID
1115 #ifdef IPV6_RECVPKTINFO
1116 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVPKTINFO, &optval,
1117 sizeof(optval)) < 0)
1118 warn("setsockopt(IPV6_RECVPKTINFO)"); /* XXX err? */
1119 #else /* old adv. API */
1120 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_PKTINFO, &optval,
1121 sizeof(optval)) < 0)
1122 warn("setsockopt(IPV6_PKTINFO)"); /* XXX err? */
1124 #endif /* USE_SIN6_SCOPE_ID */
1125 #ifdef IPV6_RECVHOPLIMIT
1126 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &optval,
1127 sizeof(optval)) < 0)
1128 warn("setsockopt(IPV6_RECVHOPLIMIT)"); /* XXX err? */
1129 #else /* old adv. API */
1130 if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPLIMIT, &optval,
1131 sizeof(optval)) < 0)
1132 warn("setsockopt(IPV6_HOPLIMIT)"); /* XXX err? */
1135 cap_rights_clear(&rights_srecv, CAP_SETSOCKOPT);
1136 if (caph_rights_limit(srecv, &rights_srecv) < 0)
1137 err(1, "caph_rights_limit srecv setsockopt");
1138 cap_rights_clear(&rights_ssend, CAP_SETSOCKOPT);
1139 if (caph_rights_limit(ssend, &rights_ssend) < 0)
1140 err(1, "caph_rights_limit ssend setsockopt");
1142 printf("PING6(%lu=40+8+%lu bytes) ", (unsigned long)(40 + pingerlen()),
1143 (unsigned long)(pingerlen() - 8));
1144 printf("%s --> ", pr_addr((struct sockaddr *)&src, sizeof(src)));
1145 printf("%s\n", pr_addr((struct sockaddr *)&dst, sizeof(dst)));
1150 if (npackets != 0 && preload > npackets)
1155 clock_gettime(CLOCK_MONOTONIC, &last);
1157 sigemptyset(&si_sa.sa_mask);
1159 si_sa.sa_handler = onsignal;
1160 if (sigaction(SIGINT, &si_sa, 0) == -1)
1161 err(EX_OSERR, "sigaction SIGINT");
1164 if (sigaction(SIGINFO, &si_sa, 0) == -1)
1165 err(EX_OSERR, "sigaction SIGINFO");
1168 if (alarmtimeout > 0) {
1169 if (sigaction(SIGALRM, &si_sa, 0) == -1)
1170 err(EX_OSERR, "sigaction SIGALRM");
1172 if (options & F_FLOOD) {
1174 intvl.tv_nsec = 10000000;
1178 while (seenint == 0) {
1179 struct timespec now, timeout;
1181 struct iovec iov[2];
1185 /* signal handling */
1196 FD_SET(srecv, &rfds);
1197 clock_gettime(CLOCK_MONOTONIC, &now);
1198 timespecadd(&last, &intvl, &timeout);
1199 timespecsub(&timeout, &now, &timeout);
1200 if (timeout.tv_sec < 0)
1201 timespecclear(&timeout);
1203 n = pselect(srecv + 1, &rfds, NULL, NULL, &timeout, NULL);
1205 continue; /* EINTR */
1207 m.msg_name = (caddr_t)&from;
1208 m.msg_namelen = sizeof(from);
1209 memset(&iov, 0, sizeof(iov));
1210 iov[0].iov_base = (caddr_t)packet;
1211 iov[0].iov_len = packlen;
1214 memset(cm, 0, CONTROLLEN);
1215 m.msg_control = (void *)cm;
1216 m.msg_controllen = CONTROLLEN;
1218 cc = recvmsg(srecv, &m, 0);
1220 if (errno != EINTR) {
1225 } else if (cc == 0) {
1229 * receive control messages only. Process the
1230 * exceptions (currently the only possibility is
1231 * a path MTU notification.)
1233 if ((mtu = get_pathmtu(&m)) > 0) {
1234 if ((options & F_VERBOSE) != 0) {
1235 printf("new path MTU (%d) is "
1242 * an ICMPv6 message (probably an echoreply)
1245 pr_pack(packet, cc, &m);
1247 if (((options & F_ONCE) != 0 && nreceived > 0) ||
1248 (npackets > 0 && nreceived >= npackets))
1251 if (n == 0 || (options & F_FLOOD)) {
1252 if (npackets == 0 || ntransmitted < npackets)
1259 * If we're not transmitting any more packets,
1260 * change the timer to wait two round-trip times
1261 * if we've received any packets or (waittime)
1262 * milliseconds if we haven't.
1266 intvl.tv_sec = 2 * tmax / 1000;
1267 if (intvl.tv_sec == 0)
1270 intvl.tv_sec = waittime / 1000;
1272 waittime % 1000 * 1000000;
1275 clock_gettime(CLOCK_MONOTONIC, &last);
1276 if (ntransmitted - nreceived - 1 > nmissedmax) {
1277 nmissedmax = ntransmitted - nreceived - 1;
1278 if (options & F_MISSED)
1279 (void)write(STDOUT_FILENO, &BBELL, 1);
1283 sigemptyset(&si_sa.sa_mask);
1285 si_sa.sa_handler = SIG_IGN;
1286 sigaction(SIGINT, &si_sa, 0);
1287 sigaction(SIGALRM, &si_sa, 0);
1295 else if (ntransmitted > ntransmitfailures)
1320 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1321 * will be added on by the kernel. The ID field is our UNIX process ID,
1322 * and the sequence number is an ascending integer. The first 8 bytes
1323 * of the data portion are used to hold a UNIX "timespec" struct in VAX
1324 * byte-order, to compute the round-trip time.
1331 if (options & F_FQDN)
1332 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1333 else if (options & F_FQDNOLD)
1335 else if (options & F_NODEADDR)
1336 l = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1337 else if (options & F_SUPTYPES)
1340 l = ICMP6ECHOLEN + datalen;
1348 struct icmp6_hdr *icp;
1349 struct iovec iov[2];
1351 struct icmp6_nodeinfo *nip;
1354 if (npackets && ntransmitted >= npackets)
1355 return(-1); /* no more transmission */
1357 icp = (struct icmp6_hdr *)outpack;
1358 nip = (struct icmp6_nodeinfo *)outpack;
1359 memset(icp, 0, sizeof(*icp));
1360 icp->icmp6_cksum = 0;
1361 seq = ntransmitted++;
1362 CLR(seq % mx_dup_ck);
1364 if (options & F_FQDN) {
1367 icp->icmp6_type = ICMP6_NI_QUERY;
1368 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1369 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1370 nip->ni_flags = htons(0);
1372 memcpy(nip->icmp6_ni_nonce, nonce,
1373 sizeof(nip->icmp6_ni_nonce));
1375 memcpy(nip->icmp6_ni_nonce, &s, sizeof(s));
1377 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1378 sizeof(dst.sin6_addr));
1379 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1381 } else if (options & F_FQDNOLD) {
1383 /* packet format in 03 draft - no Subject data on queries */
1384 icp->icmp6_type = ICMP6_NI_QUERY;
1385 icp->icmp6_code = 0; /* code field is always 0 */
1386 nip->ni_qtype = htons(NI_QTYPE_FQDN);
1387 nip->ni_flags = htons(0);
1389 memcpy(nip->icmp6_ni_nonce, nonce,
1390 sizeof(nip->icmp6_ni_nonce));
1392 memcpy(nip->icmp6_ni_nonce, &s, sizeof(s));
1396 } else if (options & F_NODEADDR) {
1399 icp->icmp6_type = ICMP6_NI_QUERY;
1400 icp->icmp6_code = ICMP6_NI_SUBJ_IPV6;
1401 nip->ni_qtype = htons(NI_QTYPE_NODEADDR);
1402 nip->ni_flags = naflags;
1404 memcpy(nip->icmp6_ni_nonce, nonce,
1405 sizeof(nip->icmp6_ni_nonce));
1407 memcpy(nip->icmp6_ni_nonce, &s, sizeof(s));
1409 memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr,
1410 sizeof(dst.sin6_addr));
1411 cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr);
1413 } else if (options & F_SUPTYPES) {
1416 icp->icmp6_type = ICMP6_NI_QUERY;
1417 icp->icmp6_code = ICMP6_NI_SUBJ_FQDN; /*empty*/
1418 nip->ni_qtype = htons(NI_QTYPE_SUPTYPES);
1419 /* we support compressed bitmap */
1420 nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS;
1422 memcpy(nip->icmp6_ni_nonce, nonce,
1423 sizeof(nip->icmp6_ni_nonce));
1425 memcpy(nip->icmp6_ni_nonce, &s, sizeof(s));
1430 icp->icmp6_type = ICMP6_ECHO_REQUEST;
1431 icp->icmp6_code = 0;
1432 icp->icmp6_id = htons(ident);
1433 icp->icmp6_seq = htons(seq);
1437 (void)clock_gettime(CLOCK_MONOTONIC, &tv);
1439 * Truncate seconds down to 32 bits in order
1440 * to fit the timestamp within 8 bytes of the
1441 * packet. We're only concerned with
1442 * durations, not absolute times.
1444 tv32.tv32_sec = (uint32_t)htonl(tv.tv_sec);
1445 tv32.tv32_nsec = (uint32_t)htonl(tv.tv_nsec);
1446 memcpy(&outpack[ICMP6ECHOLEN], &tv32, sizeof(tv32));
1448 cc = ICMP6ECHOLEN + datalen;
1452 if (pingerlen() != cc)
1453 errx(1, "internal error; length mismatch");
1456 memset(&iov, 0, sizeof(iov));
1457 iov[0].iov_base = (caddr_t)outpack;
1458 iov[0].iov_len = cc;
1459 smsghdr.msg_iov = iov;
1460 smsghdr.msg_iovlen = 1;
1462 i = sendmsg(ssend, &smsghdr, 0);
1464 if (i < 0 || i != cc) {
1466 ntransmitfailures++;
1469 (void)printf("ping6: wrote %s %d chars, ret=%d\n",
1472 if (!(options & F_QUIET) && options & F_FLOOD)
1473 (void)write(STDOUT_FILENO, &DOT, 1);
1479 myechoreply(const struct icmp6_hdr *icp)
1481 if (ntohs(icp->icmp6_id) == ident)
1488 mynireply(const struct icmp6_nodeinfo *nip)
1490 if (memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t),
1491 nonce + sizeof(u_int16_t),
1492 sizeof(nonce) - sizeof(u_int16_t)) == 0)
1499 * Decode a name from a DNS message.
1501 * Format of the message is described in RFC 1035 subsection 4.1.4.
1504 * sp - Pointer to a DNS pointer octet or to the first octet of a label
1506 * ep - Pointer to the end of the message (one step past the last octet).
1507 * base - Pointer to the beginning of the message.
1508 * buf - Buffer into which the decoded name will be saved.
1509 * bufsiz - Size of the buffer 'buf'.
1512 * Pointer to an octet immediately following the ending zero octet
1513 * of the decoded label, or NULL if an error occured.
1516 dnsdecode(const u_char *sp, const u_char *ep, const u_char *base, char *buf,
1521 char cresult[MAXDNAME + 1];
1532 if (i == 0 || cp != sp) {
1533 if (strlcat((char *)buf, ".", bufsiz) >= bufsiz)
1534 return NULL; /*result overrun*/
1540 if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) {
1541 /* DNS compression */
1545 comp = base + (i & 0x3f);
1546 if (dnsdecode(comp, cp, base, cresult,
1547 sizeof(cresult)) == NULL)
1549 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1550 return NULL; /*result overrun*/
1552 } else if ((i & 0x3f) == i) {
1554 return NULL; /*source overrun*/
1555 while (i-- > 0 && cp < ep) {
1556 l = snprintf(cresult, sizeof(cresult),
1557 isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff);
1558 if ((size_t)l >= sizeof(cresult) || l < 0)
1560 if (strlcat(buf, cresult, bufsiz) >= bufsiz)
1561 return NULL; /*result overrun*/
1565 return NULL; /*invalid label*/
1568 return NULL; /*not terminated*/
1575 * Print out the packet, if it came from us. This logic is necessary
1576 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1577 * which arrive ('tis only fair). This permits multiple copies of this
1578 * program to be run without having intermingled output (or statistics!).
1581 pr_pack(u_char *buf, int cc, struct msghdr *mhdr)
1583 #define safeputc(c) printf((isprint((c)) ? "%c" : "\\%03o"), c)
1584 struct icmp6_hdr *icp;
1585 struct icmp6_nodeinfo *ni;
1588 struct sockaddr *from;
1590 const u_char *cp = NULL;
1591 u_char *dp, *end = buf + cc;
1592 struct in6_pktinfo *pktinfo = NULL;
1593 struct timespec tv, tp;
1595 double triptime = 0;
1600 char dnsname[MAXDNAME + 1];
1602 (void)clock_gettime(CLOCK_MONOTONIC, &tv);
1604 if (!mhdr || !mhdr->msg_name ||
1605 mhdr->msg_namelen != sizeof(struct sockaddr_in6) ||
1606 ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) {
1607 if (options & F_VERBOSE)
1608 warnx("invalid peername");
1611 from = (struct sockaddr *)mhdr->msg_name;
1612 fromlen = mhdr->msg_namelen;
1613 if (cc < (int)sizeof(struct icmp6_hdr)) {
1614 if (options & F_VERBOSE)
1615 warnx("packet too short (%d bytes) from %s", cc,
1616 pr_addr(from, fromlen));
1619 if (((mhdr->msg_flags & MSG_CTRUNC) != 0) &&
1620 (options & F_VERBOSE) != 0)
1621 warnx("some control data discarded, insufficient buffer size");
1622 icp = (struct icmp6_hdr *)buf;
1623 ni = (struct icmp6_nodeinfo *)buf;
1626 if ((hoplim = get_hoplim(mhdr)) == -1) {
1627 warnx("failed to get receiving hop limit");
1630 if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) {
1631 warnx("failed to get receiving packet information");
1635 if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) {
1636 seq = ntohs(icp->icmp6_seq);
1639 memcpy(&tpp, icp + 1, sizeof(tpp));
1640 tp.tv_sec = ntohl(tpp.tv32_sec);
1641 tp.tv_nsec = ntohl(tpp.tv32_nsec);
1642 timespecsub(&tv, &tp, &tv);
1643 triptime = ((double)tv.tv_sec) * 1000.0 +
1644 ((double)tv.tv_nsec) / 1000000.0;
1646 tsumsq += triptime * triptime;
1647 if (triptime < tmin)
1649 if (triptime > tmax)
1653 if (TST(seq % mx_dup_ck)) {
1658 SET(seq % mx_dup_ck);
1662 if (options & F_QUIET)
1665 if (options & F_WAITTIME && triptime > waittime) {
1670 if (options & F_FLOOD)
1671 (void)write(STDOUT_FILENO, &BSPACE, 1);
1673 if (options & F_AUDIBLE)
1674 (void)write(STDOUT_FILENO, &BBELL, 1);
1675 (void)printf("%d bytes from %s, icmp_seq=%u", cc,
1676 pr_addr(from, fromlen), seq);
1677 (void)printf(" hlim=%d", hoplim);
1678 if ((options & F_VERBOSE) != 0) {
1679 struct sockaddr_in6 dstsa;
1681 memset(&dstsa, 0, sizeof(dstsa));
1682 dstsa.sin6_family = AF_INET6;
1683 dstsa.sin6_len = sizeof(dstsa);
1684 dstsa.sin6_scope_id = pktinfo->ipi6_ifindex;
1685 dstsa.sin6_addr = pktinfo->ipi6_addr;
1686 (void)printf(" dst=%s",
1687 pr_addr((struct sockaddr *)&dstsa,
1691 (void)printf(" time=%.3f ms", triptime);
1693 (void)printf("(DUP!)");
1694 /* check the data */
1695 cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1696 dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN;
1697 for (i = 8; cp < end; ++i, ++cp, ++dp) {
1699 (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp);
1704 } else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) {
1705 memcpy(&seq, ni->icmp6_ni_nonce, sizeof(seq));
1708 if (TST(seq % mx_dup_ck)) {
1713 SET(seq % mx_dup_ck);
1717 if (options & F_QUIET)
1720 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1722 switch (ntohs(ni->ni_code)) {
1723 case ICMP6_NI_SUCCESS:
1725 case ICMP6_NI_REFUSED:
1726 printf("refused, type 0x%x", ntohs(ni->ni_type));
1728 case ICMP6_NI_UNKNOWN:
1729 printf("unknown, type 0x%x", ntohs(ni->ni_type));
1732 printf("unknown code 0x%x, type 0x%x",
1733 ntohs(ni->ni_code), ntohs(ni->ni_type));
1737 switch (ntohs(ni->ni_qtype)) {
1739 printf("NodeInfo NOOP");
1741 case NI_QTYPE_SUPTYPES:
1742 pr_suptypes(ni, end - (u_char *)ni);
1744 case NI_QTYPE_NODEADDR:
1745 pr_nodeaddr(ni, end - (u_char *)ni);
1748 default: /* XXX: for backward compatibility */
1749 cp = (u_char *)ni + ICMP6_NIRLEN;
1750 if (buf[off + ICMP6_NIRLEN] ==
1751 cc - off - ICMP6_NIRLEN - 1)
1756 cp++; /* skip length */
1758 safeputc(*cp & 0xff);
1764 cp = dnsdecode((const u_char *)cp, end,
1765 (const u_char *)(ni + 1), dnsname,
1772 * name-lookup special handling for
1775 if (cp + 1 <= end && !*cp &&
1776 strlen(dnsname) > 0) {
1777 dnsname[strlen(dnsname) - 1] = '\0';
1780 printf("%s%s", i > 0 ? "," : "",
1784 if (options & F_VERBOSE) {
1789 (void)printf(" ("); /*)*/
1791 switch (ni->ni_code) {
1792 case ICMP6_NI_REFUSED:
1793 (void)printf("refused");
1796 case ICMP6_NI_UNKNOWN:
1797 (void)printf("unknown qtype");
1802 if ((end - (u_char *)ni) < ICMP6_NIRLEN) {
1803 /* case of refusion, unknown */
1808 memcpy(&t, &buf[off+ICMP6ECHOLEN+8], sizeof(t));
1809 ttl = (int32_t)ntohl(t);
1812 if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) {
1813 (void)printf("TTL=%d:meaningless",
1817 (void)printf("TTL=%d:invalid",
1820 (void)printf("TTL=%d", ttl);
1830 cp = (u_char *)ni + ICMP6_NIRLEN;
1839 if (buf[off + ICMP6_NIRLEN] !=
1840 cc - off - ICMP6_NIRLEN - 1 && oldfqdn) {
1843 (void)printf("invalid namelen:%d/%lu",
1844 buf[off + ICMP6_NIRLEN],
1845 (u_long)cc - off - ICMP6_NIRLEN - 1);
1855 /* We've got something other than an ECHOREPLY */
1856 if (!(options & F_VERBOSE))
1858 (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen));
1862 if (!(options & F_FLOOD)) {
1863 (void)putchar('\n');
1864 if (options & F_VERBOSE)
1866 (void)fflush(stdout);
1872 pr_exthdrs(struct msghdr *mhdr)
1879 bufp = mhdr->msg_control;
1880 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
1881 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
1882 if (cm->cmsg_level != IPPROTO_IPV6)
1885 bufsize = CONTROLLEN - ((caddr_t)CMSG_DATA(cm) - (caddr_t)bufp);
1888 switch (cm->cmsg_type) {
1890 printf(" HbH Options: ");
1891 pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1894 #ifdef IPV6_RTHDRDSTOPTS
1895 case IPV6_RTHDRDSTOPTS:
1897 printf(" Dst Options: ");
1898 pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize);
1901 printf(" Routing: ");
1902 pr_rthdr(CMSG_DATA(cm), (size_t)bufsize);
1909 pr_ip6opt(void *extbuf, size_t bufsize)
1911 struct ip6_hbh *ext;
1914 socklen_t extlen, len;
1920 ext = (struct ip6_hbh *)extbuf;
1921 extlen = (ext->ip6h_len + 1) * 8;
1922 printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt,
1923 (unsigned int)ext->ip6h_len, (unsigned long)extlen);
1926 * Bounds checking on the ancillary data buffer:
1927 * subtract the size of a cmsg structure from the buffer size.
1929 if (bufsize < (extlen + CMSG_SPACE(0))) {
1930 extlen = bufsize - CMSG_SPACE(0);
1931 warnx("options truncated, showing only %u (total=%u)",
1932 (unsigned int)(extlen / 8 - 1),
1933 (unsigned int)(ext->ip6h_len));
1938 currentlen = inet6_opt_next(extbuf, extlen, currentlen,
1939 &type, &len, &databuf);
1940 if (currentlen == -1)
1944 * Note that inet6_opt_next automatically skips any padding
1949 offset = inet6_opt_get_val(databuf, offset,
1950 &value4, sizeof(value4));
1951 printf(" Jumbo Payload Opt: Length %u\n",
1952 (u_int32_t)ntohl(value4));
1954 case IP6OPT_ROUTER_ALERT:
1956 offset = inet6_opt_get_val(databuf, offset,
1957 &value2, sizeof(value2));
1958 printf(" Router Alert Opt: Type %u\n",
1962 printf(" Received Opt %u len %lu\n",
1963 type, (unsigned long)len);
1971 pr_rthdr(void *extbuf, size_t bufsize)
1973 struct in6_addr *in6;
1974 char ntopbuf[INET6_ADDRSTRLEN];
1975 struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf;
1976 int i, segments, origsegs, rthsize, size0, size1;
1978 /* print fixed part of the header */
1979 printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt,
1980 rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type);
1981 if ((segments = inet6_rth_segments(extbuf)) >= 0) {
1982 printf("%d segments, ", segments);
1983 printf("%d left\n", rh->ip6r_segleft);
1985 printf("segments unknown, ");
1986 printf("%d left\n", rh->ip6r_segleft);
1991 * Bounds checking on the ancillary data buffer. When calculating
1992 * the number of items to show keep in mind:
1993 * - The size of the cmsg structure
1994 * - The size of one segment (the size of a Type 0 routing header)
1995 * - When dividing add a fudge factor of one in case the
1996 * dividend is not evenly divisible by the divisor
1998 rthsize = (rh->ip6r_len + 1) * 8;
1999 if (bufsize < (rthsize + CMSG_SPACE(0))) {
2000 origsegs = segments;
2001 size0 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 0);
2002 size1 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 1);
2003 segments -= (rthsize - (bufsize - CMSG_SPACE(0))) /
2004 (size1 - size0) + 1;
2005 warnx("segments truncated, showing only %d (total=%d)",
2006 segments, origsegs);
2009 for (i = 0; i < segments; i++) {
2010 in6 = inet6_rth_getaddr(extbuf, i);
2012 printf(" [%d]<NULL>\n", i);
2014 if (!inet_ntop(AF_INET6, in6, ntopbuf,
2016 strlcpy(ntopbuf, "?", sizeof(ntopbuf));
2017 printf(" [%d]%s\n", i, ntopbuf);
2026 pr_bitrange(u_int32_t v, int soff, int ii)
2033 /* shift till we have 0x01 */
2034 if ((v & 0x01) == 0) {
2036 printf("-%u", soff + off - 1);
2047 case 0x04: case 0x0c:
2058 /* we have 0x01 with us */
2059 for (i = 0; i < 32 - off; i++) {
2060 if ((v & (0x01 << i)) == 0)
2064 printf(" %u", soff + off);
2072 pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen)
2073 /* ni->qtype must be SUPTYPES */
2077 const u_char *cp, *end;
2080 u_int16_t words; /*32bit count*/
2083 #define MAXQTYPES (1 << 16)
2087 cp = (u_char *)(ni + 1);
2088 end = ((u_char *)ni) + nilen;
2092 printf("NodeInfo Supported Qtypes");
2093 if (options & F_VERBOSE) {
2094 if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS)
2095 printf(", compressed bitmap");
2097 printf(", raw bitmap");
2101 clen = (size_t)(end - cp);
2102 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) {
2103 if (clen == 0 || clen > MAXQTYPES / 8 ||
2109 if (clen < sizeof(cbit) || clen % sizeof(v))
2111 memcpy(&cbit, cp, sizeof(cbit));
2112 if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) >
2116 clen = ntohs(cbit.words) * sizeof(v);
2117 if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 >
2122 for (off = 0; off < clen; off += sizeof(v)) {
2123 memcpy(&v, cp + off, sizeof(v));
2124 v = (u_int32_t)ntohl(v);
2125 b = pr_bitrange(v, (int)(cur + off * 8), b);
2127 /* flush the remaining bits */
2128 b = pr_bitrange(0, (int)(cur + off * 8), b);
2132 if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0)
2133 cur += ntohs(cbit.skip) * 32;
2138 pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen)
2139 /* ni->qtype must be NODEADDR */
2141 u_char *cp = (u_char *)(ni + 1);
2142 char ntop_buf[INET6_ADDRSTRLEN];
2145 nilen -= sizeof(struct icmp6_nodeinfo);
2147 if (options & F_VERBOSE) {
2148 switch (ni->ni_code) {
2149 case ICMP6_NI_REFUSED:
2150 (void)printf("refused");
2152 case ICMP6_NI_UNKNOWN:
2153 (void)printf("unknown qtype");
2156 if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE)
2157 (void)printf(" truncated");
2161 printf(" no address\n");
2164 * In icmp-name-lookups 05 and later, TTL of each returned address
2165 * is contained in the resposne. We try to detect the version
2166 * by the length of the data, but note that the detection algorithm
2167 * is incomplete. We assume the latest draft by default.
2169 if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0)
2177 memcpy(&t, cp, sizeof(t));
2178 ttl = (u_int32_t)ntohl(t);
2179 cp += sizeof(u_int32_t);
2180 nilen -= sizeof(u_int32_t);
2183 if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) ==
2185 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2186 printf(" %s", ntop_buf);
2188 if (ttl == 0xffffffff) {
2190 * XXX: can this convention be applied to all
2191 * type of TTL (i.e. non-ND TTL)?
2193 printf("(TTL=infty)");
2196 printf("(TTL=%u)", ttl);
2200 nilen -= sizeof(struct in6_addr);
2201 cp += sizeof(struct in6_addr);
2206 get_hoplim(struct msghdr *mhdr)
2210 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2211 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2212 if (cm->cmsg_len == 0)
2215 if (cm->cmsg_level == IPPROTO_IPV6 &&
2216 cm->cmsg_type == IPV6_HOPLIMIT &&
2217 cm->cmsg_len == CMSG_LEN(sizeof(int))) {
2220 memcpy(&r, CMSG_DATA(cm), sizeof(r));
2228 static struct in6_pktinfo *
2229 get_rcvpktinfo(struct msghdr *mhdr)
2231 static struct in6_pktinfo pi;
2234 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2235 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2236 if (cm->cmsg_len == 0)
2239 if (cm->cmsg_level == IPPROTO_IPV6 &&
2240 cm->cmsg_type == IPV6_PKTINFO &&
2241 cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) {
2242 memcpy(&pi, CMSG_DATA(cm), sizeof(pi));
2251 get_pathmtu(struct msghdr *mhdr)
2253 #ifdef IPV6_RECVPATHMTU
2255 struct ip6_mtuinfo mtuctl;
2257 for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm;
2258 cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) {
2259 if (cm->cmsg_len == 0)
2262 if (cm->cmsg_level == IPPROTO_IPV6 &&
2263 cm->cmsg_type == IPV6_PATHMTU &&
2264 cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) {
2265 memcpy(&mtuctl, CMSG_DATA(cm), sizeof(mtuctl));
2268 * If the notified destination is different from
2269 * the one we are pinging, just ignore the info.
2270 * We check the scope ID only when both notified value
2271 * and our own value have non-0 values, because we may
2272 * have used the default scope zone ID for sending,
2273 * in which case the scope ID value is 0.
2275 if (!IN6_ARE_ADDR_EQUAL(&mtuctl.ip6m_addr.sin6_addr,
2277 (mtuctl.ip6m_addr.sin6_scope_id &&
2278 dst.sin6_scope_id &&
2279 mtuctl.ip6m_addr.sin6_scope_id !=
2280 dst.sin6_scope_id)) {
2281 if ((options & F_VERBOSE) != 0) {
2282 printf("path MTU for %s is notified. "
2284 pr_addr((struct sockaddr *)&mtuctl.ip6m_addr,
2285 sizeof(mtuctl.ip6m_addr)));
2291 * Ignore an invalid MTU. XXX: can we just believe
2294 if (mtuctl.ip6m_mtu < IPV6_MMTU)
2297 /* notification for our destination. return the MTU. */
2298 return((int)mtuctl.ip6m_mtu);
2311 onint(int notused __unused)
2314 * When doing reverse DNS lookups, the seenint flag might not
2315 * be noticed for a while. Just exit if we get a second SIGINT.
2317 if ((options & F_HOSTNAME) && seenint != 0)
2318 _exit(nreceived ? 0 : 2);
2323 * Print out statistics.
2329 (void)printf("\n--- %s ping6 statistics ---\n", hostname);
2330 (void)printf("%ld packets transmitted, ", ntransmitted);
2331 (void)printf("%ld packets received, ", nreceived);
2333 (void)printf("+%ld duplicates, ", nrepeats);
2335 if (nreceived > ntransmitted)
2336 (void)printf("-- somebody's duplicating packets!");
2338 (void)printf("%.1f%% packet loss",
2339 ((((double)ntransmitted - nreceived) * 100.0) /
2343 printf(", %ld packets out of wait time", nrcvtimeout);
2344 (void)putchar('\n');
2345 if (nreceived && timing) {
2346 /* Only display average to microseconds */
2347 double num = nreceived + nrepeats;
2348 double avg = tsum / num;
2349 double dev = sqrt(tsumsq / num - avg * avg);
2351 "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
2352 tmin, avg, tmax, dev);
2353 (void)fflush(stdout);
2355 (void)fflush(stdout);
2359 static const char *niqcode[] = {
2361 "DNS label", /*or empty*/
2366 static const char *nircode[] = {
2367 "Success", "Refused", "Unknown",
2373 * Print a descriptive string about an ICMP header.
2376 pr_icmph(struct icmp6_hdr *icp, u_char *end)
2378 char ntop_buf[INET6_ADDRSTRLEN];
2379 struct nd_redirect *red;
2380 struct icmp6_nodeinfo *ni;
2381 char dnsname[MAXDNAME + 1];
2385 switch (icp->icmp6_type) {
2386 case ICMP6_DST_UNREACH:
2387 switch (icp->icmp6_code) {
2388 case ICMP6_DST_UNREACH_NOROUTE:
2389 (void)printf("No Route to Destination\n");
2391 case ICMP6_DST_UNREACH_ADMIN:
2392 (void)printf("Destination Administratively "
2395 case ICMP6_DST_UNREACH_BEYONDSCOPE:
2396 (void)printf("Destination Unreachable Beyond Scope\n");
2398 case ICMP6_DST_UNREACH_ADDR:
2399 (void)printf("Destination Host Unreachable\n");
2401 case ICMP6_DST_UNREACH_NOPORT:
2402 (void)printf("Destination Port Unreachable\n");
2405 (void)printf("Destination Unreachable, Bad Code: %d\n",
2409 /* Print returned IP header information */
2410 pr_retip((struct ip6_hdr *)(icp + 1), end);
2412 case ICMP6_PACKET_TOO_BIG:
2413 (void)printf("Packet too big mtu = %d\n",
2414 (int)ntohl(icp->icmp6_mtu));
2415 pr_retip((struct ip6_hdr *)(icp + 1), end);
2417 case ICMP6_TIME_EXCEEDED:
2418 switch (icp->icmp6_code) {
2419 case ICMP6_TIME_EXCEED_TRANSIT:
2420 (void)printf("Time to live exceeded\n");
2422 case ICMP6_TIME_EXCEED_REASSEMBLY:
2423 (void)printf("Frag reassembly time exceeded\n");
2426 (void)printf("Time exceeded, Bad Code: %d\n",
2430 pr_retip((struct ip6_hdr *)(icp + 1), end);
2432 case ICMP6_PARAM_PROB:
2433 (void)printf("Parameter problem: ");
2434 switch (icp->icmp6_code) {
2435 case ICMP6_PARAMPROB_HEADER:
2436 (void)printf("Erroneous Header ");
2438 case ICMP6_PARAMPROB_NEXTHEADER:
2439 (void)printf("Unknown Nextheader ");
2441 case ICMP6_PARAMPROB_OPTION:
2442 (void)printf("Unrecognized Option ");
2445 (void)printf("Bad code(%d) ", icp->icmp6_code);
2448 (void)printf("pointer = 0x%02x\n",
2449 (u_int32_t)ntohl(icp->icmp6_pptr));
2450 pr_retip((struct ip6_hdr *)(icp + 1), end);
2452 case ICMP6_ECHO_REQUEST:
2453 (void)printf("Echo Request");
2454 /* XXX ID + Seq + Data */
2456 case ICMP6_ECHO_REPLY:
2457 (void)printf("Echo Reply");
2458 /* XXX ID + Seq + Data */
2460 case ICMP6_MEMBERSHIP_QUERY:
2461 (void)printf("Listener Query");
2463 case ICMP6_MEMBERSHIP_REPORT:
2464 (void)printf("Listener Report");
2466 case ICMP6_MEMBERSHIP_REDUCTION:
2467 (void)printf("Listener Done");
2469 case ND_ROUTER_SOLICIT:
2470 (void)printf("Router Solicitation");
2472 case ND_ROUTER_ADVERT:
2473 (void)printf("Router Advertisement");
2475 case ND_NEIGHBOR_SOLICIT:
2476 (void)printf("Neighbor Solicitation");
2478 case ND_NEIGHBOR_ADVERT:
2479 (void)printf("Neighbor Advertisement");
2482 red = (struct nd_redirect *)icp;
2483 (void)printf("Redirect\n");
2484 if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf,
2486 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2487 (void)printf("Destination: %s", ntop_buf);
2488 if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf,
2490 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2491 (void)printf(" New Target: %s", ntop_buf);
2493 case ICMP6_NI_QUERY:
2494 (void)printf("Node Information Query");
2495 /* XXX ID + Seq + Data */
2496 ni = (struct icmp6_nodeinfo *)icp;
2497 l = end - (u_char *)(ni + 1);
2499 switch (ntohs(ni->ni_qtype)) {
2501 (void)printf("NOOP");
2503 case NI_QTYPE_SUPTYPES:
2504 (void)printf("Supported qtypes");
2507 (void)printf("DNS name");
2509 case NI_QTYPE_NODEADDR:
2510 (void)printf("nodeaddr");
2512 case NI_QTYPE_IPV4ADDR:
2513 (void)printf("IPv4 nodeaddr");
2516 (void)printf("unknown qtype");
2519 if (options & F_VERBOSE) {
2520 switch (ni->ni_code) {
2521 case ICMP6_NI_SUBJ_IPV6:
2522 if (l == sizeof(struct in6_addr) &&
2523 inet_ntop(AF_INET6, ni + 1, ntop_buf,
2524 sizeof(ntop_buf)) != NULL) {
2525 (void)printf(", subject=%s(%s)",
2526 niqcode[ni->ni_code], ntop_buf);
2529 /* backward compat to -W */
2530 (void)printf(", oldfqdn");
2532 (void)printf(", invalid");
2536 case ICMP6_NI_SUBJ_FQDN:
2537 if (end == (u_char *)(ni + 1)) {
2538 (void)printf(", no subject");
2541 printf(", subject=%s", niqcode[ni->ni_code]);
2542 cp = (const u_char *)(ni + 1);
2543 cp = dnsdecode(cp, end, NULL, dnsname,
2546 printf("(%s)", dnsname);
2548 printf("(invalid)");
2550 case ICMP6_NI_SUBJ_IPV4:
2551 if (l == sizeof(struct in_addr) &&
2552 inet_ntop(AF_INET, ni + 1, ntop_buf,
2553 sizeof(ntop_buf)) != NULL) {
2554 (void)printf(", subject=%s(%s)",
2555 niqcode[ni->ni_code], ntop_buf);
2557 (void)printf(", invalid");
2560 (void)printf(", invalid");
2565 case ICMP6_NI_REPLY:
2566 (void)printf("Node Information Reply");
2567 /* XXX ID + Seq + Data */
2568 ni = (struct icmp6_nodeinfo *)icp;
2570 switch (ntohs(ni->ni_qtype)) {
2572 (void)printf("NOOP");
2574 case NI_QTYPE_SUPTYPES:
2575 (void)printf("Supported qtypes");
2578 (void)printf("DNS name");
2580 case NI_QTYPE_NODEADDR:
2581 (void)printf("nodeaddr");
2583 case NI_QTYPE_IPV4ADDR:
2584 (void)printf("IPv4 nodeaddr");
2587 (void)printf("unknown qtype");
2590 if (options & F_VERBOSE) {
2591 if (ni->ni_code > nitems(nircode))
2592 printf(", invalid");
2594 printf(", %s", nircode[ni->ni_code]);
2598 (void)printf("Bad ICMP type: %d", icp->icmp6_type);
2604 * Print an IP6 header.
2607 pr_iph(struct ip6_hdr *ip6)
2609 u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
2611 char ntop_buf[INET6_ADDRSTRLEN];
2613 tc = *(&ip6->ip6_vfc + 1); /* XXX */
2614 tc = (tc >> 4) & 0x0f;
2615 tc |= (ip6->ip6_vfc << 4);
2617 printf("Vr TC Flow Plen Nxt Hlim\n");
2618 printf(" %1x %02x %05x %04x %02x %02x\n",
2619 (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow),
2620 ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim);
2621 if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf)))
2622 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2623 printf("%s->", ntop_buf);
2624 if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf)))
2625 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2626 printf("%s\n", ntop_buf);
2631 * Return an ascii host address as a dotted quad and optionally with
2635 pr_addr(struct sockaddr *addr, int addrlen)
2637 static char buf[NI_MAXHOST];
2640 if ((options & F_HOSTNAME) == 0)
2641 flag |= NI_NUMERICHOST;
2643 if (cap_getnameinfo(capdns, addr, addrlen, buf, sizeof(buf), NULL, 0,
2652 * Dump some info on a returned (via ICMPv6) IPv6 packet.
2655 pr_retip(struct ip6_hdr *ip6, u_char *end)
2657 u_char *cp = (u_char *)ip6, nh;
2660 if ((size_t)(end - (u_char *)ip6) < sizeof(*ip6)) {
2665 hlen = sizeof(*ip6);
2669 while (end - cp >= 8) {
2673 case IPPROTO_HOPOPTS:
2675 hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3;
2676 nh = ((struct ip6_hbh *)cp)->ip6h_nxt;
2678 case IPPROTO_DSTOPTS:
2680 hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3;
2681 nh = ((struct ip6_dest *)cp)->ip6d_nxt;
2683 case IPPROTO_FRAGMENT:
2685 hlen = sizeof(struct ip6_frag);
2686 nh = ((struct ip6_frag *)cp)->ip6f_nxt;
2688 case IPPROTO_ROUTING:
2690 hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3;
2691 nh = ((struct ip6_rthdr *)cp)->ip6r_nxt;
2696 memcpy(&ah, cp, sizeof(ah));
2697 hlen = (ah.ah_len+2) << 2;
2701 case IPPROTO_ICMPV6:
2702 printf("ICMP6: type = %d, code = %d\n",
2709 printf("TCP: from port %u, to port %u (decimal)\n",
2710 (*cp * 256 + *(cp + 1)),
2711 (*(cp + 2) * 256 + *(cp + 3)));
2714 printf("UDP: from port %u, to port %u (decimal)\n",
2715 (*cp * 256 + *(cp + 1)),
2716 (*(cp + 2) * 256 + *(cp + 3)));
2719 printf("Unknown Header(%d)\n", nh);
2723 if ((cp += hlen) >= end)
2738 fill(char *bp, char *patp)
2744 for (cp = patp; *cp; cp++)
2746 errx(1, "patterns must be specified as hex digits");
2748 "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
2749 &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
2750 &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
2751 &pat[13], &pat[14], &pat[15]);
2756 (size_t)kk <= MAXDATALEN - 8 + sizeof(struct tv32) + ii;
2758 for (jj = 0; jj < ii; ++jj)
2759 bp[jj + kk] = pat[jj];
2760 if (!(options & F_QUIET)) {
2761 (void)printf("PATTERN: 0x");
2762 for (jj = 0; jj < ii; ++jj)
2763 (void)printf("%02x", bp[jj] & 0xFF);
2769 #ifdef IPSEC_POLICY_IPSEC
2771 setpolicy(int so __unused, char *policy)
2776 return 0; /* ignore */
2778 buf = ipsec_set_policy(policy, strlen(policy));
2780 errx(1, "%s", ipsec_strerror());
2781 if (setsockopt(ssend, IPPROTO_IPV6, IPV6_IPSEC_POLICY, buf,
2782 ipsec_get_policylen(buf)) < 0)
2783 warnx("Unable to set IPsec policy");
2792 nigroup(char *name, int nig_oldmcprefix)
2797 u_int8_t digest[16];
2800 char hbuf[NI_MAXHOST];
2801 struct in6_addr in6;
2804 p = strchr(name, '.');
2806 p = name + strlen(name);
2808 if (l > 63 || l > sizeof(hbuf) - 1)
2809 return NULL; /*label too long*/
2810 strncpy(hbuf, name, l);
2811 hbuf[(int)l] = '\0';
2813 for (q = name; *q; q++) {
2814 if (isupper(*(unsigned char *)q))
2815 *q = tolower(*(unsigned char *)q);
2818 /* generate 16 bytes of pseudo-random value. */
2819 memset(&ctxt, 0, sizeof(ctxt));
2822 MD5Update(&ctxt, &c, sizeof(c));
2823 MD5Update(&ctxt, (unsigned char *)name, l);
2824 MD5Final(digest, &ctxt);
2826 if (nig_oldmcprefix) {
2827 /* draft-ietf-ipngwg-icmp-name-lookup */
2828 valid = inet_pton(AF_INET6, "ff02::2:0000:0000", &in6);
2831 valid = inet_pton(AF_INET6, "ff02::2:ff00:0000", &in6);
2834 return NULL; /*XXX*/
2836 if (nig_oldmcprefix) {
2837 /* draft-ietf-ipngwg-icmp-name-lookup */
2838 bcopy(digest, &in6.s6_addr[12], 4);
2841 bcopy(digest, &in6.s6_addr[13], 3);
2844 if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL)
2847 return strdup(hbuf);
2850 static cap_channel_t *
2853 cap_channel_t *capcas, *capdnsloc;
2855 const char *types[2];
2858 capcas = cap_init();
2860 err(1, "unable to create casper process");
2861 capdnsloc = cap_service_open(capcas, "system.dns");
2862 /* Casper capability no longer needed. */
2864 if (capdnsloc == NULL)
2865 err(1, "unable to open system.dns service");
2867 types[0] = "NAME2ADDR";
2868 types[1] = "ADDR2NAME";
2869 if (cap_dns_type_limit(capdnsloc, types, nitems(types)) < 0)
2870 err(1, "unable to limit access to system.dns service");
2871 families[0] = AF_INET6;
2872 if (cap_dns_family_limit(capdnsloc, families, nitems(families)) < 0)
2873 err(1, "unable to limit access to system.dns service");