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