blob: 22b3a33ddb9a077e9b33828e48e6859a078b41fd [file] [log] [blame]
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001/*
2 *
3 * Modified for AF_INET6 by Pedro Roque
4 *
5 * <roque@di.fc.ul.pt>
6 *
7 * Original copyright notice included bellow
8 */
9
10/*
11 * Copyright (c) 1989 The Regents of the University of California.
12 * All rights reserved.
13 *
14 * This code is derived from software contributed to Berkeley by
15 * Mike Muuss.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 * 3. All advertising materials mentioning features or use of this software
26 * must display the following acknowledgement:
27 * This product includes software developed by the University of
28 * California, Berkeley and its contributors.
29 * 4. Neither the name of the University nor the names of its contributors
30 * may be used to endorse or promote products derived from this software
31 * without specific prior written permission.
32 *
33 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * SUCH DAMAGE.
44 */
45
46#ifndef lint
47char copyright[] =
48"@(#) Copyright (c) 1989 The Regents of the University of California.\n\
49 All rights reserved.\n";
50#endif /* not lint */
51
52/*
53 * P I N G . C
54 *
55 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
56 * measure round-trip-delays and packet loss across network paths.
57 *
58 * Author -
59 * Mike Muuss
60 * U. S. Army Ballistic Research Laboratory
61 * December, 1983
62 *
63 * Status -
64 * Public Domain. Distribution Unlimited.
65 * Bugs -
66 * More statistics could always be gathered.
67 * This program has to run SUID to ROOT to access the ICMP socket.
68 */
69#include "ping_common.h"
70
71#include <linux/filter.h>
72#include <netinet/ip6.h>
73#include <netinet/icmp6.h>
74#include <resolv.h>
75#ifndef WITHOUT_IFADDRS
76#include <ifaddrs.h>
77#endif
78
79#ifdef USE_IDN
80#include <stringprep.h>
81#endif
82
83#include "ping6_niquery.h"
Maciej Żenczykowskicd8741b2019-10-15 17:31:31 -070084/* The in6_flowlabel.h file in the iputils distribution exists to provide
85 * kernel flowlabel API definitions that are not in the userspace headers
86 * because they are linux-specific. It's not needed on Android because Android
87 * exposes the kernel definitions to userspace directly.
88 * #include "in6_flowlabel.h"
89 */
Lorenzo Colitti313379e2013-07-11 01:07:11 +090090
91#ifndef SOL_IPV6
92#define SOL_IPV6 IPPROTO_IPV6
93#endif
94
95#ifndef SOL_ICMPV6
96#define SOL_ICMPV6 IPPROTO_ICMPV6
97#endif
98
99/* RFC3542 */
100#ifndef ICMP6_DST_UNREACH_BEYONDSCOPE
101#define ICMP6_DST_UNREACH_BEYONDSCOPE ICMP6_DST_UNREACH_NOTNEIGHBOR
102#endif
103
104#if defined(ENABLE_PING6_RTHDR) && !defined(ENABLE_PING6_RTHDR_RFC3542)
105#ifndef IPV6_SRCRT_TYPE_0
106#define IPV6_SRCRT_TYPE_0 0
107#endif
108#endif
109
110#ifndef MLD_LISTENER_QUERY
111#define MLD_LISTENER_QUERY 130
112#define MLD_LISTENER_REPORT 131
113#define MLD_LISTENER_REDUCTION 132
114#endif
115
116#define BIT_CLEAR(nr, addr) do { ((__u32 *)(addr))[(nr) >> 5] &= ~(1U << ((nr) & 31)); } while(0)
117#define BIT_SET(nr, addr) do { ((__u32 *)(addr))[(nr) >> 5] |= (1U << ((nr) & 31)); } while(0)
118#define BIT_TEST(nr, addr) do { (__u32 *)(addr))[(nr) >> 5] & (1U << ((nr) & 31)); } while(0)
119
120#ifndef ICMP6_FILTER_WILLPASS
121#define ICMP6_FILTER_WILLPASS(type, filterp) \
122 (BIT_TEST((type), filterp) == 0)
123
124#define ICMP6_FILTER_WILLBLOCK(type, filterp) \
125 BIT_TEST((type), filterp)
126
127#define ICMP6_FILTER_SETPASS(type, filterp) \
128 BIT_CLEAR((type), filterp)
129
130#define ICMP6_FILTER_SETBLOCK(type, filterp) \
131 BIT_SET((type), filterp)
132
133#define ICMP6_FILTER_SETPASSALL(filterp) \
134 memset(filterp, 0, sizeof(struct icmp6_filter));
135
136#define ICMP6_FILTER_SETBLOCKALL(filterp) \
137 memset(filterp, 0xFF, sizeof(struct icmp6_filter));
138#endif
139
140#define MAXPACKET 128000 /* max packet size */
141
142#ifdef SO_TIMESTAMP
143#define HAVE_SIN6_SCOPEID 1
144#endif
145
146#ifndef SCOPE_DELIMITER
147# define SCOPE_DELIMITER '%'
148#endif
149
150__u32 flowlabel;
151__u32 tclass;
152#ifdef ENABLE_PING6_RTHDR
153struct cmsghdr *srcrt;
154#endif
155
156struct sockaddr_in6 whereto; /* who to ping */
157u_char outpack[MAXPACKET];
158int maxpacket = sizeof(outpack);
159
160static unsigned char cmsgbuf[4096];
161static int cmsglen = 0;
162
163static char * pr_addr(struct in6_addr *addr);
164static char * pr_addr_n(struct in6_addr *addr);
165static int pr_icmph(__u8 type, __u8 code, __u32 info);
166static void usage(void) __attribute((noreturn));
167
168struct sockaddr_in6 source;
169char *device;
170int pmtudisc=-1;
171
172static int icmp_sock;
173
174#ifdef USE_GNUTLS
175# include <gnutls/openssl.h>
176#else
177# include <openssl/md5.h>
178#endif
179
180/* Node Information query */
181int ni_query = -1;
182int ni_flag = 0;
183void *ni_subject = NULL;
184int ni_subject_len = 0;
185int ni_subject_type = -1;
186char *ni_group;
187
188static inline int ntohsp(__u16 *p)
189{
190 __u16 v;
191 memcpy(&v, p, sizeof(v));
192 return ntohs(v);
193}
194
195#if defined(ENABLE_PING6_RTHDR) && !defined(ENABLE_PING6_RTHDR_RFC3542)
196size_t inet6_srcrt_space(int type, int segments)
197{
198 if (type != 0 || segments > 24)
199 return 0;
200
201 return (sizeof(struct cmsghdr) + sizeof(struct ip6_rthdr0) +
202 segments * sizeof(struct in6_addr));
203}
204
205extern struct cmsghdr * inet6_srcrt_init(void *bp, int type)
206{
207 struct cmsghdr *cmsg;
208
209 if (type)
210 return NULL;
211
212 memset(bp, 0, sizeof(struct cmsghdr) + sizeof(struct ip6_rthdr0));
213 cmsg = (struct cmsghdr *) bp;
214
215 cmsg->cmsg_len = sizeof(struct cmsghdr) + sizeof(struct ip6_rthdr0);
216 cmsg->cmsg_level = SOL_IPV6;
217 cmsg->cmsg_type = IPV6_RTHDR;
218
219 return cmsg;
220}
221
222int inet6_srcrt_add(struct cmsghdr *cmsg, const struct in6_addr *addr)
223{
224 struct ip6_rthdr0 *hdr;
225
226 hdr = (struct ip6_rthdr0 *) CMSG_DATA(cmsg);
227
228 cmsg->cmsg_len += sizeof(struct in6_addr);
229 hdr->ip6r0_len += sizeof(struct in6_addr) / 8;
230
231 memcpy(&hdr->ip6r0_addr[hdr->ip6r0_segleft++], addr,
232 sizeof(struct in6_addr));
233
234 return 0;
235}
236#endif
237
238unsigned int if_name2index(const char *ifname)
239{
240 unsigned int i = if_nametoindex(ifname);
241 if (!i) {
242 fprintf(stderr, "ping: unknown iface %s\n", ifname);
243 exit(2);
244 }
245 return i;
246}
247
248struct niquery_option {
249 char *name;
250 int namelen;
251 int has_arg;
252 int data;
253 int (*handler)(int index, const char *arg);
254};
255
256#define NIQUERY_OPTION(_name, _has_arg, _data, _handler) \
257 { \
258 .name = _name, \
259 .namelen = sizeof(_name) - 1, \
260 .has_arg = _has_arg, \
261 .data = _data, \
262 .handler = _handler \
263 }
264
265static int niquery_option_name_handler(int index, const char *arg);
266static int niquery_option_ipv6_handler(int index, const char *arg);
267static int niquery_option_ipv6_flag_handler(int index, const char *arg);
268static int niquery_option_ipv4_handler(int index, const char *arg);
269static int niquery_option_ipv4_flag_handler(int index, const char *arg);
270static int niquery_option_subject_addr_handler(int index, const char *arg);
271static int niquery_option_subject_name_handler(int index, const char *arg);
272static int niquery_option_help_handler(int index, const char *arg);
273
274struct niquery_option niquery_options[] = {
275 NIQUERY_OPTION("name", 0, 0, niquery_option_name_handler),
276 NIQUERY_OPTION("fqdn", 0, 0, niquery_option_name_handler),
277 NIQUERY_OPTION("ipv6", 0, 0, niquery_option_ipv6_handler),
278 NIQUERY_OPTION("ipv6-all", 0, NI_IPV6ADDR_F_ALL, niquery_option_ipv6_flag_handler),
279 NIQUERY_OPTION("ipv6-compatible", 0, NI_IPV6ADDR_F_COMPAT, niquery_option_ipv6_flag_handler),
280 NIQUERY_OPTION("ipv6-linklocal", 0, NI_IPV6ADDR_F_LINKLOCAL, niquery_option_ipv6_flag_handler),
281 NIQUERY_OPTION("ipv6-sitelocal", 0, NI_IPV6ADDR_F_SITELOCAL, niquery_option_ipv6_flag_handler),
282 NIQUERY_OPTION("ipv6-global", 0, NI_IPV6ADDR_F_GLOBAL, niquery_option_ipv6_flag_handler),
283 NIQUERY_OPTION("ipv4", 0, 0, niquery_option_ipv4_handler),
284 NIQUERY_OPTION("ipv4-all", 0, NI_IPV4ADDR_F_ALL, niquery_option_ipv4_flag_handler),
285 NIQUERY_OPTION("subject-ipv6", 1, NI_SUBJ_IPV6, niquery_option_subject_addr_handler),
286 NIQUERY_OPTION("subject-ipv4", 1, NI_SUBJ_IPV4, niquery_option_subject_addr_handler),
287 NIQUERY_OPTION("subject-name", 1, 0, niquery_option_subject_name_handler),
288 NIQUERY_OPTION("subject-fqdn", 1, -1, niquery_option_subject_name_handler),
289 NIQUERY_OPTION("help", 0, 0, niquery_option_help_handler),
290 {},
291};
292
293static inline int niquery_is_enabled(void)
294{
295 return ni_query >= 0;
296}
297
298#if PING6_NONCE_MEMORY
299__u8 *ni_nonce_ptr;
300#else
301struct {
302 struct timeval tv;
303 pid_t pid;
304} ni_nonce_secret;
305#endif
306
307static void niquery_init_nonce(void)
308{
309#if PING6_NONCE_MEMORY
310 struct timeval tv;
311 unsigned long seed;
312
313 seed = (unsigned long)getpid();
314 if (!gettimeofday(&tv, NULL))
315 seed ^= tv.tv_usec;
316 srand(seed);
317
318 ni_nonce_ptr = calloc(NI_NONCE_SIZE, MAX_DUP_CHK);
319 if (!ni_nonce_ptr) {
320 perror("ping6: calloc");
321 exit(2);
322 }
323
324 ni_nonce_ptr[0] = ~0;
325#else
326 gettimeofday(&ni_nonce_secret.tv, NULL);
327 ni_nonce_secret.pid = getpid();
328#endif
329}
330
331#if !PING6_NONCE_MEMORY
332static int niquery_nonce(__u8 *nonce, int fill)
333{
334 static __u8 digest[MD5_DIGEST_LENGTH];
335 static int seq = -1;
336
337 if (fill || seq != *(__u16 *)nonce || seq < 0) {
338 MD5_CTX ctxt;
339
340 MD5_Init(&ctxt);
341 MD5_Update(&ctxt, &ni_nonce_secret, sizeof(ni_nonce_secret));
342 MD5_Update(&ctxt, nonce, sizeof(__u16));
343 MD5_Final(digest, &ctxt);
344
345 seq = *(__u16 *)nonce;
346 }
347
348 if (fill) {
349 memcpy(nonce + sizeof(__u16), digest, NI_NONCE_SIZE - sizeof(__u16));
350 return 0;
351 } else {
352 if (memcmp(nonce + sizeof(__u16), digest, NI_NONCE_SIZE - sizeof(__u16)))
353 return -1;
354 return ntohsp((__u16 *)nonce);
355 }
356}
357#endif
358
359static inline void niquery_fill_nonce(__u16 seq, __u8 *nonce)
360{
361 __u16 v = htons(seq);
362#if PING6_NONCE_MEMORY
363 int i;
364
365 memcpy(&ni_nonce_ptr[NI_NONCE_SIZE * (seq % MAX_DUP_CHK)], &v, sizeof(v));
366
367 for (i = sizeof(v); i < NI_NONCE_SIZE; i++)
368 ni_nonce_ptr[NI_NONCE_SIZE * (seq % MAX_DUP_CHK) + i] = 0x100 * (rand() / (RAND_MAX + 1.0));
369
370 memcpy(nonce, &ni_nonce_ptr[NI_NONCE_SIZE * (seq % MAX_DUP_CHK)], NI_NONCE_SIZE);
371#else
372 memcpy(nonce, &v, sizeof(v));
373 niquery_nonce(nonce, 1);
374#endif
375}
376
377static inline int niquery_check_nonce(__u8 *nonce)
378{
379#if PING6_NONCE_MEMORY
380 __u16 seq = ntohsp((__u16 *)nonce);
381 if (memcmp(nonce, &ni_nonce_ptr[NI_NONCE_SIZE * (seq % MAX_DUP_CHK)], NI_NONCE_SIZE))
382 return -1;
383 return seq;
384#else
385 return niquery_nonce(nonce, 0);
386#endif
387}
388
389static int niquery_set_qtype(int type)
390{
391 if (niquery_is_enabled() && ni_query != type) {
392 printf("Qtype conflict\n");
393 return -1;
394 }
395 ni_query = type;
396 return 0;
397}
398
399static int niquery_option_name_handler(int index, const char *arg)
400{
401 if (niquery_set_qtype(NI_QTYPE_NAME) < 0)
402 return -1;
403 return 0;
404}
405
406static int niquery_option_ipv6_handler(int index, const char *arg)
407{
408 if (niquery_set_qtype(NI_QTYPE_IPV6ADDR) < 0)
409 return -1;
410 return 0;
411}
412
413static int niquery_option_ipv6_flag_handler(int index, const char *arg)
414{
415 if (niquery_set_qtype(NI_QTYPE_IPV6ADDR) < 0)
416 return -1;
417 ni_flag |= niquery_options[index].data;
418 return 0;
419}
420
421static int niquery_option_ipv4_handler(int index, const char *arg)
422{
423 if (niquery_set_qtype(NI_QTYPE_IPV4ADDR) < 0)
424 return -1;
425 return 0;
426}
427
428static int niquery_option_ipv4_flag_handler(int index, const char *arg)
429{
430 if (niquery_set_qtype(NI_QTYPE_IPV4ADDR) < 0)
431 return -1;
432 ni_flag |= niquery_options[index].data;
433 return 0;
434}
435
436static inline int niquery_is_subject_valid(void)
437{
438 return ni_subject_type >= 0 && ni_subject;
439}
440
441static int niquery_set_subject_type(int type)
442{
443 if (niquery_is_subject_valid() && ni_subject_type != type) {
444 printf("Subject type conflict\n");
445 return -1;
446 }
447 ni_subject_type = type;
448 return 0;
449}
450
451#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
452#define OFFSET_OF(type,elem) ((size_t)&((type *)0)->elem)
453
454static int niquery_option_subject_addr_handler(int index, const char *arg)
455{
456 struct addrinfo hints, *ai0, *ai;
457 int offset;
458 int gai;
459
460 if (niquery_set_subject_type(niquery_options[index].data) < 0)
461 return -1;
462
463 ni_subject_type = niquery_options[index].data;
464
465 memset(&hints, 0, sizeof(hints));
466
467 switch (niquery_options[index].data) {
468 case NI_SUBJ_IPV6:
469 ni_subject_len = sizeof(struct in6_addr);
470 offset = OFFSET_OF(struct sockaddr_in6, sin6_addr);
471 hints.ai_family = AF_INET6;
472 break;
473 case NI_SUBJ_IPV4:
474 ni_subject_len = sizeof(struct in_addr);
475 offset = OFFSET_OF(struct sockaddr_in, sin_addr);
476 hints.ai_family = AF_INET;
477 break;
478 default:
479 /* should not happen. */
480 offset = -1;
481 }
482
483 hints.ai_socktype = SOCK_DGRAM;
484#ifdef USE_IDN
485 hints.ai_flags = AI_IDN;
486#endif
487
488 gai = getaddrinfo(arg, 0, &hints, &ai0);
489 if (gai) {
490 fprintf(stderr, "Unknown host: %s\n", arg);
491 return -1;
492 }
493
494 for (ai = ai0; ai; ai = ai->ai_next) {
495 void *p = malloc(ni_subject_len);
496 if (!p)
497 continue;
498 memcpy(p, (__u8 *)ai->ai_addr + offset, ni_subject_len);
499 free(ni_subject);
500 ni_subject = p;
501 break;
502 }
503 freeaddrinfo(ai0);
504
505 return 0;
506}
507
508static int niquery_option_subject_name_handler(int index, const char *arg)
509{
510 static char nigroup_buf[INET6_ADDRSTRLEN + 1 + IFNAMSIZ];
511 unsigned char *dnptrs[2], **dpp, **lastdnptr;
512 int n;
513 int i;
514 char *name, *p;
515 char *canonname = NULL, *idn = NULL;
516 unsigned char *buf = NULL;
517 size_t namelen;
518 size_t buflen;
519 int dots, fqdn = niquery_options[index].data;
520 MD5_CTX ctxt;
521 __u8 digest[MD5_DIGEST_LENGTH];
522#ifdef USE_IDN
523 int rc;
524#endif
525
526 if (niquery_set_subject_type(NI_SUBJ_NAME) < 0)
527 return -1;
528
529#ifdef USE_IDN
530 name = stringprep_locale_to_utf8(arg);
531 if (!name) {
532 fprintf(stderr, "ping6: IDN support failed.\n");
533 exit(2);
534 }
535#else
536 name = strdup(arg);
537 if (!name)
538 goto oomexit;
539#endif
540
541 p = strchr(name, SCOPE_DELIMITER);
542 if (p) {
543 *p = '\0';
544 if (strlen(p + 1) >= IFNAMSIZ) {
545 fprintf(stderr, "ping6: too long scope name.\n");
546 exit(1);
547 }
548 }
549
550#ifdef USE_IDN
551 rc = idna_to_ascii_8z(name, &idn, 0);
552 if (rc) {
553 fprintf(stderr, "ping6: IDN encoding error: %s\n",
554 idna_strerror(rc));
555 exit(2);
556 }
557#else
558 idn = strdup(name);
559 if (!idn)
560 goto oomexit;
561#endif
562
563 namelen = strlen(idn);
564 canonname = malloc(namelen + 1);
565 if (!canonname)
566 goto oomexit;
567
568 dots = 0;
569 for (i = 0; i < namelen + 1; i++) {
570 canonname[i] = isupper(idn[i]) ? tolower(idn[i]) : idn[i];
571 if (idn[i] == '.')
572 dots++;
573 }
574
575 if (fqdn == 0) {
576 /* guess if hostname is FQDN */
577 fqdn = dots ? 1 : -1;
578 }
579
580 buflen = namelen + 3 + 1; /* dn_comp() requrires strlen() + 3,
581 plus non-fqdn indicator. */
582 buf = malloc(buflen);
583 if (!buf) {
584 fprintf(stderr, "ping6: out of memory.\n");
585 goto errexit;
586 }
587
588 dpp = dnptrs;
589 lastdnptr = &dnptrs[ARRAY_SIZE(dnptrs)];
590
591 *dpp++ = (unsigned char *)buf;
592 *dpp++ = NULL;
593
594 n = dn_comp(canonname, (unsigned char *)buf, buflen, dnptrs, lastdnptr);
595 if (n < 0) {
596 fprintf(stderr, "ping6: Inappropriate subject name: %s\n", canonname);
597 goto errexit;
598 } else if (n >= buflen) {
599 fprintf(stderr, "ping6: dn_comp() returned too long result.\n");
600 goto errexit;
601 }
602
603 MD5_Init(&ctxt);
604 MD5_Update(&ctxt, buf, buf[0]);
605 MD5_Final(digest, &ctxt);
606
607 sprintf(nigroup_buf, "ff02::2:%02x%02x:%02x%02x%s%s",
608 digest[0], digest[1], digest[2], digest[3],
609 p ? "%" : "",
610 p ? p + 1 : "");
611
612 if (fqdn < 0)
613 buf[n] = 0;
614
615 free(ni_subject);
616
617 ni_group = nigroup_buf;
618 ni_subject = buf;
619 ni_subject_len = n + (fqdn < 0);
620 ni_group = nigroup_buf;
621
622 free(canonname);
623 free(idn);
624 free(name);
625
626 return 0;
627oomexit:
628 fprintf(stderr, "ping6: out of memory.\n");
629errexit:
630 free(buf);
631 free(canonname);
632 free(idn);
633 free(name);
634 exit(1);
635}
636
637int niquery_option_help_handler(int index, const char *arg)
638{
639 fprintf(stderr, "ping6 -N suboptions\n"
640 "\tHelp:\n"
641 "\t\thelp\n"
642 "\tQuery:\n"
643 "\t\tname,\n"
644 "\t\tipv6,ipv6-all,ipv6-compatible,ipv6-linklocal,ipv6-sitelocal,ipv6-global,\n"
645 "\t\tipv4,ipv4-all,\n"
646 "\tSubject:\n"
647 "\t\tsubject-ipv6=addr,subject-ipv4=addr,subject-name=name,subject-fqdn=name,\n"
648 );
649 exit(2);
650}
651
652int niquery_option_handler(const char *opt_arg)
653{
654 struct niquery_option *p;
655 int i;
656 int ret = -1;
657 for (i = 0, p = niquery_options; p->name; i++, p++) {
658 if (strncmp(p->name, opt_arg, p->namelen))
659 continue;
660 if (!p->has_arg) {
661 if (opt_arg[p->namelen] == '\0') {
662 ret = p->handler(i, NULL);
663 if (ret >= 0)
664 break;
665 }
666 } else {
667 if (opt_arg[p->namelen] == '=') {
668 ret = p->handler(i, &opt_arg[p->namelen] + 1);
669 if (ret >= 0)
670 break;
671 }
672 }
673 }
674 if (!p->name)
675 ret = niquery_option_help_handler(0, NULL);
676 return ret;
677}
678
679static int hextoui(const char *str)
680{
681 unsigned long val;
682 char *ep;
683
684 errno = 0;
685 val = strtoul(str, &ep, 16);
686 if (*ep) {
687 if (!errno)
688 errno = EINVAL;
689 return -1;
690 }
691
692 if (val > UINT_MAX) {
693 errno = ERANGE;
694 return UINT_MAX;
695 }
696
697 return val;
698}
699
700int main(int argc, char *argv[])
701{
702 int ch, hold, packlen;
703 u_char *packet;
704 char *target;
705 struct addrinfo hints, *ai;
706 int gai;
707 struct sockaddr_in6 firsthop;
Lorenzo Colitti105a2c72013-07-09 18:13:02 +0900708 int socket_errno = 0;
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900709 struct icmp6_filter filter;
710 int err;
711#ifdef __linux__
712 int csum_offset, sz_opt;
713#endif
714 static uint32_t scope_id = 0;
715
Lorenzo Colitti105a2c72013-07-09 18:13:02 +0900716#ifdef ANDROID
717 android_check_security();
718#endif
719
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900720 limit_capabilities();
721
722#ifdef USE_IDN
723 setlocale(LC_ALL, "");
724#endif
725
Lorenzo Colitti105a2c72013-07-09 18:13:02 +0900726 icmp_sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6);
727 if (icmp_sock < 0) {
728 enable_capability_raw();
729 icmp_sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
730 socket_errno = errno;
731 disable_capability_raw();
732 using_ping_socket = 0;
733 }
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900734
735 source.sin6_family = AF_INET6;
736 memset(&firsthop, 0, sizeof(firsthop));
737 firsthop.sin6_family = AF_INET6;
738
739 preload = 1;
740 while ((ch = getopt(argc, argv, COMMON_OPTSTR "F:N:")) != EOF) {
741 switch(ch) {
742 case 'F':
743 flowlabel = hextoui(optarg);
744 if (errno || (flowlabel & ~IPV6_FLOWINFO_FLOWLABEL)) {
745 fprintf(stderr, "ping: Invalid flowinfo %s\n", optarg);
746 exit(2);
747 }
748 options |= F_FLOWINFO;
749 break;
750 case 'Q':
751 tclass = hextoui(optarg);
752 if (errno || (tclass & ~0xff)) {
753 fprintf(stderr, "ping: Invalid tclass %s\n", optarg);
754 exit(2);
755 }
756 options |= F_TCLASS;
757 break;
758 case 'I':
759 if (strchr(optarg, ':')) {
760 char *p, *addr = strdup(optarg);
761
762 if (!addr) {
763 fprintf(stderr, "ping: out of memory\n");
764 exit(2);
765 }
766
767 p = strchr(addr, SCOPE_DELIMITER);
768 if (p) {
769 *p = '\0';
770 device = optarg + (p - addr) + 1;
771 }
772
773 if (inet_pton(AF_INET6, addr, (char*)&source.sin6_addr) <= 0) {
774 fprintf(stderr, "ping: invalid source address %s\n", optarg);
775 exit(2);
776 }
777
778 options |= F_STRICTSOURCE;
779
780 free(addr);
781 } else {
782 device = optarg;
783 }
784 break;
785 case 'M':
786 if (strcmp(optarg, "do") == 0)
787 pmtudisc = IPV6_PMTUDISC_DO;
788 else if (strcmp(optarg, "dont") == 0)
789 pmtudisc = IPV6_PMTUDISC_DONT;
790 else if (strcmp(optarg, "want") == 0)
791 pmtudisc = IPV6_PMTUDISC_WANT;
792 else {
793 fprintf(stderr, "ping: wrong value for -M: do, dont, want are valid ones.\n");
794 exit(2);
795 }
796 break;
797 case 'V':
798 printf("ping6 utility, iputils-%s\n", SNAPSHOT);
799 exit(0);
800 case 'N':
Lorenzo Colitti105a2c72013-07-09 18:13:02 +0900801 if (using_ping_socket) {
802 fprintf(stderr, "ping: -N requires raw socket permissions\n");
803 exit(2);
804 }
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900805 if (niquery_option_handler(optarg) < 0) {
806 usage();
807 break;
808 }
809 break;
810 COMMON_OPTIONS
811 common_options(ch);
812 break;
813 default:
814 usage();
815 }
816 }
817 argc -= optind;
818 argv += optind;
819
820#ifdef ENABLE_PING6_RTHDR
821 while (argc > 1) {
822 struct in6_addr *addr;
823
824 if (srcrt == NULL) {
825 int space;
826
827 fprintf(stderr, "ping6: Warning: "
828 "Source routing is deprecated by RFC5095.\n");
829
830#ifdef ENABLE_PING6_RTHDR_RFC3542
831 space = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1);
832#else
833 space = inet6_srcrt_space(IPV6_SRCRT_TYPE_0, argc - 1);
834#endif
835 if (space == 0) {
836 fprintf(stderr, "srcrt_space failed\n");
837 exit(2);
838 }
839#ifdef ENABLE_PING6_RTHDR_RFC3542
840 if (cmsglen + CMSG_SPACE(space) > sizeof(cmsgbuf)) {
841 fprintf(stderr, "no room for options\n");
842 exit(2);
843 }
844#else
845 if (space + cmsglen > sizeof(cmsgbuf)) {
846 fprintf(stderr, "no room for options\n");
847 exit(2);
848 }
849#endif
850 srcrt = (struct cmsghdr*)(cmsgbuf+cmsglen);
851#ifdef ENABLE_PING6_RTHDR_RFC3542
852 memset(srcrt, 0, CMSG_SPACE(0));
853 srcrt->cmsg_len = CMSG_LEN(space);
854 srcrt->cmsg_level = IPPROTO_IPV6;
855 srcrt->cmsg_type = IPV6_RTHDR;
856 inet6_rth_init(CMSG_DATA(srcrt), space, IPV6_RTHDR_TYPE_0, argc - 1);
857 cmsglen += CMSG_SPACE(space);
858#else
859 cmsglen += CMSG_ALIGN(space);
860 inet6_srcrt_init(srcrt, IPV6_SRCRT_TYPE_0);
861#endif
862 }
863
864 target = *argv;
865
866 memset(&hints, 0, sizeof(hints));
867 hints.ai_family = AF_INET6;
868#ifdef USE_IDN
869 hints.ai_flags = AI_IDN;
870#endif
871 gai = getaddrinfo(target, NULL, &hints, &ai);
872 if (gai) {
873 fprintf(stderr, "unknown host\n");
874 exit(2);
875 }
876 addr = &((struct sockaddr_in6 *)(ai->ai_addr))->sin6_addr;
877#ifdef ENABLE_PING6_RTHDR_RFC3542
878 inet6_rth_add(CMSG_DATA(srcrt), addr);
879#else
880 inet6_srcrt_add(srcrt, addr);
881#endif
882 if (IN6_IS_ADDR_UNSPECIFIED(&firsthop.sin6_addr)) {
883 memcpy(&firsthop.sin6_addr, addr, 16);
884#ifdef HAVE_SIN6_SCOPEID
885 firsthop.sin6_scope_id = ((struct sockaddr_in6 *)(ai->ai_addr))->sin6_scope_id;
886 /* Verify scope_id is the same as previous nodes */
887 if (firsthop.sin6_scope_id && scope_id && firsthop.sin6_scope_id != scope_id) {
888 fprintf(stderr, "scope discrepancy among the nodes\n");
889 exit(2);
890 } else if (!scope_id) {
891 scope_id = firsthop.sin6_scope_id;
892 }
893#endif
894 }
895 freeaddrinfo(ai);
896
897 argv++;
898 argc--;
899 }
900#endif
901
902 if (niquery_is_enabled()) {
903 niquery_init_nonce();
904
905 if (!niquery_is_subject_valid()) {
906 ni_subject = &whereto.sin6_addr;
907 ni_subject_len = sizeof(whereto.sin6_addr);
908 ni_subject_type = NI_SUBJ_IPV6;
909 }
910 }
911
912 if (argc > 1) {
913#ifndef ENABLE_PING6_RTHDR
914 fprintf(stderr, "ping6: Source routing is deprecated by RFC5095.\n");
915#endif
916 usage();
917 } else if (argc == 1) {
918 target = *argv;
919 } else {
920 if (ni_query < 0 && ni_subject_type != NI_SUBJ_NAME)
921 usage();
922 target = ni_group;
923 }
924
925 memset(&hints, 0, sizeof(hints));
926 hints.ai_family = AF_INET6;
927#ifdef USE_IDN
928 hints.ai_flags = AI_IDN;
929#endif
930 gai = getaddrinfo(target, NULL, &hints, &ai);
931 if (gai) {
932 fprintf(stderr, "unknown host\n");
933 exit(2);
934 }
935
936 memcpy(&whereto, ai->ai_addr, sizeof(whereto));
937 whereto.sin6_port = htons(IPPROTO_ICMPV6);
938
939 if (memchr(target, ':', strlen(target)))
940 options |= F_NUMERIC;
941
942 freeaddrinfo(ai);
943
944 if (IN6_IS_ADDR_UNSPECIFIED(&firsthop.sin6_addr)) {
945 memcpy(&firsthop.sin6_addr, &whereto.sin6_addr, 16);
946#ifdef HAVE_SIN6_SCOPEID
947 firsthop.sin6_scope_id = whereto.sin6_scope_id;
948 /* Verify scope_id is the same as intermediate nodes */
949 if (firsthop.sin6_scope_id && scope_id && firsthop.sin6_scope_id != scope_id) {
950 fprintf(stderr, "scope discrepancy among the nodes\n");
951 exit(2);
952 } else if (!scope_id) {
953 scope_id = firsthop.sin6_scope_id;
954 }
955#endif
956 }
957
958 hostname = target;
959
960 if (IN6_IS_ADDR_UNSPECIFIED(&source.sin6_addr)) {
961 socklen_t alen;
962 int probe_fd = socket(AF_INET6, SOCK_DGRAM, 0);
963
964 if (probe_fd < 0) {
965 perror("socket");
966 exit(2);
967 }
968 if (device) {
969#if defined(IPV6_RECVPKTINFO) || defined(HAVE_SIN6_SCOPEID)
970 unsigned int iface = if_name2index(device);
971#endif
972#ifdef IPV6_RECVPKTINFO
973 struct in6_pktinfo ipi;
974
975 memset(&ipi, 0, sizeof(ipi));
976 ipi.ipi6_ifindex = iface;
977#endif
978
979#ifdef HAVE_SIN6_SCOPEID
980 if (IN6_IS_ADDR_LINKLOCAL(&firsthop.sin6_addr) ||
981 IN6_IS_ADDR_MC_LINKLOCAL(&firsthop.sin6_addr))
982 firsthop.sin6_scope_id = iface;
983#endif
984 enable_capability_raw();
985 if (
986#ifdef IPV6_RECVPKTINFO
987 setsockopt(probe_fd, IPPROTO_IPV6, IPV6_PKTINFO, &ipi, sizeof(ipi)) == -1 &&
988#endif
989 setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1) == -1) {
990 perror("setsockopt(SO_BINDTODEVICE)");
991 exit(2);
992 }
993 disable_capability_raw();
994 }
995 firsthop.sin6_port = htons(1025);
Lorenzo Colitti3d667cc2014-05-30 23:39:50 +0900996
997 sock_setmark(probe_fd);
998
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900999 if (connect(probe_fd, (struct sockaddr*)&firsthop, sizeof(firsthop)) == -1) {
1000 perror("connect");
1001 exit(2);
1002 }
1003 alen = sizeof(source);
1004 if (getsockname(probe_fd, (struct sockaddr*)&source, &alen) == -1) {
1005 perror("getsockname");
1006 exit(2);
1007 }
1008 source.sin6_port = 0;
1009 close(probe_fd);
1010
1011#ifndef WITHOUT_IFADDRS
1012 if (device) {
1013 struct ifaddrs *ifa0, *ifa;
1014
1015 if (getifaddrs(&ifa0)) {
1016 perror("getifaddrs");
1017 exit(2);
1018 }
1019
1020 for (ifa = ifa0; ifa; ifa = ifa->ifa_next) {
1021 if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET6)
1022 continue;
1023 if (!strncmp(ifa->ifa_name, device, sizeof(device) - 1) &&
1024 IN6_ARE_ADDR_EQUAL(&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr,
1025 &source.sin6_addr))
1026 break;
1027 }
1028 if (!ifa)
1029 fprintf(stderr, "ping6: Warning: source address might be selected on device other than %s.\n", device);
1030
1031 freeifaddrs(ifa0);
1032 }
1033#endif
1034 }
1035#ifdef HAVE_SIN6_SCOPEID
1036 else if (device && (IN6_IS_ADDR_LINKLOCAL(&source.sin6_addr) ||
1037 IN6_IS_ADDR_MC_LINKLOCAL(&source.sin6_addr)))
1038 source.sin6_scope_id = if_name2index(device);
1039#endif
1040
1041 if (icmp_sock < 0) {
1042 errno = socket_errno;
1043 perror("ping: icmp open socket");
1044 exit(2);
1045 }
1046
1047 if (device) {
1048 struct cmsghdr *cmsg;
1049 struct in6_pktinfo *ipi;
1050
1051 cmsg = (struct cmsghdr*)(cmsgbuf+cmsglen);
1052 cmsglen += CMSG_SPACE(sizeof(*ipi));
1053 cmsg->cmsg_len = CMSG_LEN(sizeof(*ipi));
1054 cmsg->cmsg_level = SOL_IPV6;
1055 cmsg->cmsg_type = IPV6_PKTINFO;
1056
1057 ipi = (struct in6_pktinfo*)CMSG_DATA(cmsg);
1058 memset(ipi, 0, sizeof(*ipi));
1059 ipi->ipi6_ifindex = if_name2index(device);
1060 }
1061
1062 if ((whereto.sin6_addr.s6_addr16[0]&htons(0xff00)) == htons (0xff00)) {
1063 if (uid) {
1064 if (interval < 1000) {
1065 fprintf(stderr, "ping: multicast ping with too short interval.\n");
1066 exit(2);
1067 }
1068 if (pmtudisc >= 0 && pmtudisc != IPV6_PMTUDISC_DO) {
1069 fprintf(stderr, "ping: multicast ping does not fragment.\n");
1070 exit(2);
1071 }
1072 }
1073 if (pmtudisc < 0)
1074 pmtudisc = IPV6_PMTUDISC_DO;
1075 }
1076
1077 if (pmtudisc >= 0) {
1078 if (setsockopt(icmp_sock, SOL_IPV6, IPV6_MTU_DISCOVER, &pmtudisc, sizeof(pmtudisc)) == -1) {
1079 perror("ping: IPV6_MTU_DISCOVER");
1080 exit(2);
1081 }
1082 }
1083
1084 if ((options&F_STRICTSOURCE) &&
1085 bind(icmp_sock, (struct sockaddr*)&source, sizeof(source)) == -1) {
1086 perror("ping: bind icmp socket");
1087 exit(2);
1088 }
1089
1090 if (datalen >= sizeof(struct timeval) && (ni_query < 0)) {
1091 /* can we time transfer */
1092 timing = 1;
1093 }
1094 packlen = datalen + 8 + 4096 + 40 + 8; /* 4096 for rthdr */
1095 if (!(packet = (u_char *)malloc((u_int)packlen))) {
1096 fprintf(stderr, "ping: out of memory.\n");
1097 exit(2);
1098 }
1099
1100 working_recverr = 1;
1101 hold = 1;
1102 if (setsockopt(icmp_sock, SOL_IPV6, IPV6_RECVERR, (char *)&hold, sizeof(hold))) {
1103 fprintf(stderr, "WARNING: your kernel is veeery old. No problems.\n");
1104 working_recverr = 0;
1105 }
1106
1107 /* Estimate memory eaten by single packet. It is rough estimate.
1108 * Actually, for small datalen's it depends on kernel side a lot. */
1109 hold = datalen+8;
1110 hold += ((hold+511)/512)*(40+16+64+160);
1111 sock_setbufs(icmp_sock, hold);
1112
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001113 if (!using_ping_socket) {
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001114#ifdef __linux__
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001115 csum_offset = 2;
1116 sz_opt = sizeof(int);
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001117
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001118 err = setsockopt(icmp_sock, SOL_RAW, IPV6_CHECKSUM,
1119 &csum_offset, sz_opt);
1120 if (err < 0) {
1121 /* checksum should be enabled by default and setting
1122 * this option might fail anyway.
1123 */
1124 fprintf(stderr, "setsockopt(RAW_CHECKSUM) failed"
1125 " - try to continue.");
1126 }
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001127#endif
1128
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001129 /*
1130 * select icmp echo reply as icmp type to receive
1131 */
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001132
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001133 ICMP6_FILTER_SETBLOCKALL(&filter);
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001134
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001135 if (!working_recverr) {
1136 ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &filter);
1137 ICMP6_FILTER_SETPASS(ICMP6_PACKET_TOO_BIG, &filter);
1138 ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &filter);
1139 ICMP6_FILTER_SETPASS(ICMP6_PARAM_PROB, &filter);
1140 }
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001141
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001142 if (niquery_is_enabled())
1143 ICMP6_FILTER_SETPASS(ICMPV6_NI_REPLY, &filter);
1144 else
1145 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filter);
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001146
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001147 err = setsockopt(icmp_sock, IPPROTO_ICMPV6, ICMP6_FILTER,
1148 &filter, sizeof(struct icmp6_filter));
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001149
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001150 if (err < 0) {
1151 perror("setsockopt(ICMP6_FILTER)");
1152 exit(2);
1153 }
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001154 }
1155
1156 if (options & F_NOLOOP) {
1157 int loop = 0;
1158 if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
Lorenzo Colitti105a2c72013-07-09 18:13:02 +09001159 &loop, sizeof(loop)) == -1) {
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001160 perror ("can't disable multicast loopback");
1161 exit(2);
1162 }
1163 }
1164 if (options & F_TTL) {
1165 if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1166 &ttl, sizeof(ttl)) == -1) {
1167 perror ("can't set multicast hop limit");
1168 exit(2);
1169 }
1170 if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1171 &ttl, sizeof(ttl)) == -1) {
1172 perror ("can't set unicast hop limit");
1173 exit(2);
1174 }
1175 }
1176
1177 if (1) {
1178 int on = 1;
1179 if (
1180#ifdef IPV6_RECVHOPLIMIT
1181 setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
1182 &on, sizeof(on)) == -1 &&
1183 setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_2292HOPLIMIT,
1184 &on, sizeof(on)) == -1
1185#else
1186 setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_HOPLIMIT,
1187 &on, sizeof(on)) == -1
1188#endif
1189 ){
1190 perror ("can't receive hop limit");
1191 exit(2);
1192 }
1193 }
1194
1195 if (options & F_TCLASS) {
1196#ifdef IPV6_TCLASS
1197 if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_TCLASS,
1198 &tclass, sizeof(tclass)) == -1) {
1199 perror ("setsockopt(IPV6_TCLASS)");
1200 exit(2);
1201 }
1202#else
1203 fprintf(stderr, "Traffic class is not supported.\n");
1204#endif
1205 }
1206
1207 if (options&F_FLOWINFO) {
1208#ifdef IPV6_FLOWINFO_SEND
1209 int on = 1;
1210#endif
1211#ifdef IPV6_FLOWLABEL_MGR
1212 char freq_buf[CMSG_ALIGN(sizeof(struct in6_flowlabel_req)) + cmsglen];
1213 struct in6_flowlabel_req *freq = (struct in6_flowlabel_req *)freq_buf;
1214 int freq_len = sizeof(*freq);
1215#ifdef ENABLE_PING6_RTHDR
1216 if (srcrt)
1217 freq_len = CMSG_ALIGN(sizeof(*freq)) + srcrt->cmsg_len;
1218#endif
1219 memset(freq, 0, sizeof(*freq));
1220 freq->flr_label = htonl(flowlabel & IPV6_FLOWINFO_FLOWLABEL);
1221 freq->flr_action = IPV6_FL_A_GET;
1222 freq->flr_flags = IPV6_FL_F_CREATE;
1223 freq->flr_share = IPV6_FL_S_EXCL;
1224 memcpy(&freq->flr_dst, &whereto.sin6_addr, 16);
1225#ifdef ENABLE_PING6_RTHDR
1226 if (srcrt)
1227 memcpy(freq_buf + CMSG_ALIGN(sizeof(*freq)), srcrt, srcrt->cmsg_len);
1228#endif
1229 if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_FLOWLABEL_MGR,
1230 freq, freq_len) == -1) {
1231 perror ("can't set flowlabel");
1232 exit(2);
1233 }
1234 flowlabel = freq->flr_label;
1235#ifdef ENABLE_PING6_RTHDR
1236 if (srcrt) {
1237 cmsglen = (char*)srcrt - (char*)cmsgbuf;
1238 srcrt = NULL;
1239 }
1240#endif
1241#else
1242 fprintf(stderr, "Flow labels are not supported.\n");
1243 exit(2);
1244#endif
1245
1246#ifdef IPV6_FLOWINFO_SEND
1247 whereto.sin6_flowinfo = flowlabel;
1248 if (setsockopt(icmp_sock, IPPROTO_IPV6, IPV6_FLOWINFO_SEND,
1249 &on, sizeof(on)) == -1) {
1250 perror ("can't send flowinfo");
1251 exit(2);
1252 }
1253#else
1254 fprintf(stderr, "Flowinfo is not supported.\n");
1255 exit(2);
1256#endif
1257 }
1258
1259 printf("PING %s(%s) ", hostname, pr_addr(&whereto.sin6_addr));
1260 if (flowlabel)
1261 printf(", flow 0x%05x, ", (unsigned)ntohl(flowlabel));
1262 if (device || (options&F_STRICTSOURCE)) {
1263 printf("from %s %s: ",
1264 pr_addr_n(&source.sin6_addr), device ? : "");
1265 }
1266 printf("%d data bytes\n", datalen);
1267
1268 setup(icmp_sock);
1269
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001270 main_loop(icmp_sock, packet, packlen);
1271}
1272
1273int receive_error_msg()
1274{
1275 int res;
1276 char cbuf[512];
1277 struct iovec iov;
1278 struct msghdr msg;
1279 struct cmsghdr *cmsg;
1280 struct sock_extended_err *e;
1281 struct icmp6_hdr icmph;
1282 struct sockaddr_in6 target;
1283 int net_errors = 0;
1284 int local_errors = 0;
1285 int saved_errno = errno;
1286
1287 iov.iov_base = &icmph;
1288 iov.iov_len = sizeof(icmph);
1289 msg.msg_name = (void*)&target;
1290 msg.msg_namelen = sizeof(target);
1291 msg.msg_iov = &iov;
1292 msg.msg_iovlen = 1;
1293 msg.msg_flags = 0;
1294 msg.msg_control = cbuf;
1295 msg.msg_controllen = sizeof(cbuf);
1296
1297 res = recvmsg(icmp_sock, &msg, MSG_ERRQUEUE|MSG_DONTWAIT);
1298 if (res < 0)
1299 goto out;
1300
1301 e = NULL;
1302 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1303 if (cmsg->cmsg_level == SOL_IPV6) {
1304 if (cmsg->cmsg_type == IPV6_RECVERR)
1305 e = (struct sock_extended_err *)CMSG_DATA(cmsg);
1306 }
1307 }
1308 if (e == NULL)
1309 abort();
1310
1311 if (e->ee_origin == SO_EE_ORIGIN_LOCAL) {
1312 local_errors++;
1313 if (options & F_QUIET)
1314 goto out;
1315 if (options & F_FLOOD)
1316 write_stdout("E", 1);
1317 else if (e->ee_errno != EMSGSIZE)
1318 fprintf(stderr, "ping: local error: %s\n", strerror(e->ee_errno));
1319 else
1320 fprintf(stderr, "ping: local error: Message too long, mtu=%u\n", e->ee_info);
1321 nerrors++;
1322 } else if (e->ee_origin == SO_EE_ORIGIN_ICMP6) {
1323 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)(e+1);
1324
1325 if (res < sizeof(icmph) ||
1326 memcmp(&target.sin6_addr, &whereto.sin6_addr, 16) ||
1327 icmph.icmp6_type != ICMP6_ECHO_REQUEST ||
Lorenzo Colittice2d2d02013-07-09 17:58:13 +09001328 !is_ours(icmph.icmp6_id)) {
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001329 /* Not our error, not an error at all. Clear. */
1330 saved_errno = 0;
1331 goto out;
1332 }
1333
1334 net_errors++;
1335 nerrors++;
1336 if (options & F_QUIET)
1337 goto out;
1338 if (options & F_FLOOD) {
1339 write_stdout("\bE", 2);
1340 } else {
1341 print_timestamp();
1342 printf("From %s icmp_seq=%u ", pr_addr(&sin6->sin6_addr), ntohs(icmph.icmp6_seq));
1343 pr_icmph(e->ee_type, e->ee_code, e->ee_info);
1344 putchar('\n');
1345 fflush(stdout);
1346 }
1347 }
1348
1349out:
1350 errno = saved_errno;
1351 return net_errors ? : -local_errors;
1352}
1353
1354/*
1355 * pinger --
1356 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1357 * will be added on by the kernel. The ID field is our UNIX process ID,
1358 * and the sequence number is an ascending integer. The first 8 bytes
1359 * of the data portion are used to hold a UNIX "timeval" struct in VAX
1360 * byte-order, to compute the round-trip time.
1361 */
1362int build_echo(__u8 *_icmph)
1363{
1364 struct icmp6_hdr *icmph;
1365 int cc;
1366
1367 icmph = (struct icmp6_hdr *)_icmph;
1368 icmph->icmp6_type = ICMP6_ECHO_REQUEST;
1369 icmph->icmp6_code = 0;
1370 icmph->icmp6_cksum = 0;
1371 icmph->icmp6_seq = htons(ntransmitted+1);
1372 icmph->icmp6_id = ident;
1373
1374 if (timing)
1375 gettimeofday((struct timeval *)&outpack[8],
1376 (struct timezone *)NULL);
1377
1378 cc = datalen + 8; /* skips ICMP portion */
1379
1380 return cc;
1381}
1382
1383
1384int build_niquery(__u8 *_nih)
1385{
1386 struct ni_hdr *nih;
1387 int cc;
1388
1389 nih = (struct ni_hdr *)_nih;
1390 nih->ni_cksum = 0;
1391
1392 nih->ni_type = ICMPV6_NI_QUERY;
1393 cc = sizeof(*nih);
1394 datalen = 0;
1395
1396 niquery_fill_nonce(ntransmitted + 1, nih->ni_nonce);
1397 nih->ni_code = ni_subject_type;
1398 nih->ni_qtype = htons(ni_query);
1399 nih->ni_flags = ni_flag;
1400 memcpy(nih + 1, ni_subject, ni_subject_len);
1401 cc += ni_subject_len;
1402
1403 return cc;
1404}
1405
1406int send_probe(void)
1407{
1408 int len, cc;
1409
1410 rcvd_clear(ntransmitted + 1);
1411
1412 if (niquery_is_enabled())
1413 len = build_niquery(outpack);
1414 else
1415 len = build_echo(outpack);
1416
1417 if (cmsglen == 0) {
1418 cc = sendto(icmp_sock, (char *)outpack, len, confirm,
1419 (struct sockaddr *) &whereto,
1420 sizeof(struct sockaddr_in6));
1421 } else {
1422 struct msghdr mhdr;
1423 struct iovec iov;
1424
1425 iov.iov_len = len;
1426 iov.iov_base = outpack;
1427
1428 memset(&mhdr, 0, sizeof(mhdr));
1429 mhdr.msg_name = &whereto;
1430 mhdr.msg_namelen = sizeof(struct sockaddr_in6);
1431 mhdr.msg_iov = &iov;
1432 mhdr.msg_iovlen = 1;
1433 mhdr.msg_control = cmsgbuf;
1434 mhdr.msg_controllen = cmsglen;
1435
1436 cc = sendmsg(icmp_sock, &mhdr, confirm);
1437 }
1438 confirm = 0;
1439
1440 return (cc == len ? 0 : cc);
1441}
1442
1443void pr_echo_reply(__u8 *_icmph, int cc)
1444{
1445 struct icmp6_hdr *icmph = (struct icmp6_hdr *) _icmph;
1446 printf(" icmp_seq=%u", ntohs(icmph->icmp6_seq));
1447};
1448
1449static void putchar_safe(char c)
1450{
1451 if (isprint(c))
1452 putchar(c);
1453 else
1454 printf("\\%03o", c);
1455}
1456
1457void pr_niquery_reply_name(struct ni_hdr *nih, int len)
1458{
1459 __u8 *h = (__u8 *)(nih + 1);
1460 __u8 *p = h + 4;
1461 __u8 *end = (__u8 *)nih + len;
1462 int continued = 0;
1463 char buf[1024];
1464 int ret;
1465
1466 len -= sizeof(struct ni_hdr) + 4;
1467
1468 if (len < 0) {
1469 printf(" parse error (too short)");
1470 return;
1471 }
1472 while (p < end) {
1473 int fqdn = 1;
1474 int i;
1475
1476 memset(buf, 0xff, sizeof(buf));
1477
1478 if (continued)
1479 putchar(',');
1480
1481 ret = dn_expand(h, end, p, buf, sizeof(buf));
1482 if (ret < 0) {
1483 printf(" parse error (truncated)");
1484 break;
1485 }
1486 if (p + ret < end && *(p + ret) == '\0')
1487 fqdn = 0;
1488
1489 putchar(' ');
1490 for (i = 0; i < strlen(buf); i++)
1491 putchar_safe(buf[i]);
1492 if (fqdn)
1493 putchar('.');
1494
1495 p += ret + !fqdn;
1496
1497 continued = 1;
1498 }
1499}
1500
1501void pr_niquery_reply_addr(struct ni_hdr *nih, int len)
1502{
1503 __u8 *h = (__u8 *)(nih + 1);
1504 __u8 *p = h + 4;
1505 __u8 *end = (__u8 *)nih + len;
1506 int af;
1507 int aflen;
1508 int continued = 0;
1509 int truncated;
1510 char buf[1024];
1511
1512 switch (ntohs(nih->ni_qtype)) {
1513 case NI_QTYPE_IPV4ADDR:
1514 af = AF_INET;
1515 aflen = sizeof(struct in_addr);
1516 truncated = nih->ni_flags & NI_IPV6ADDR_F_TRUNCATE;
1517 break;
1518 case NI_QTYPE_IPV6ADDR:
1519 af = AF_INET6;
1520 aflen = sizeof(struct in6_addr);
1521 truncated = nih->ni_flags & NI_IPV4ADDR_F_TRUNCATE;
1522 break;
1523 default:
1524 /* should not happen */
1525 af = aflen = truncated = 0;
1526 }
1527 p = h;
1528 if (len < 0) {
1529 printf(" parse error (too short)");
1530 return;
1531 }
1532
1533 while (p < end) {
1534 if (continued)
1535 putchar(',');
1536
1537 if (p + sizeof(__u32) + aflen > end) {
1538 printf(" parse error (truncated)");
1539 break;
1540 }
1541 if (!inet_ntop(af, p + sizeof(__u32), buf, sizeof(buf)))
1542 printf(" unexpeced error in inet_ntop(%s)",
1543 strerror(errno));
1544 else
1545 printf(" %s", buf);
1546 p += sizeof(__u32) + aflen;
1547
1548 continued = 1;
1549 }
1550 if (truncated)
1551 printf(" (truncated)");
1552}
1553
1554void pr_niquery_reply(__u8 *_nih, int len)
1555{
1556 struct ni_hdr *nih = (struct ni_hdr *)_nih;
1557
1558 switch (nih->ni_code) {
1559 case NI_SUCCESS:
1560 switch (ntohs(nih->ni_qtype)) {
1561 case NI_QTYPE_NAME:
1562 pr_niquery_reply_name(nih, len);
1563 break;
1564 case NI_QTYPE_IPV4ADDR:
1565 case NI_QTYPE_IPV6ADDR:
1566 pr_niquery_reply_addr(nih, len);
1567 break;
1568 default:
1569 printf(" unknown qtype(0x%02x)", ntohs(nih->ni_qtype));
1570 }
1571 break;
1572 case NI_REFUSED:
1573 printf(" refused");
1574 break;
1575 case NI_UNKNOWN:
1576 printf(" unknown");
1577 break;
1578 default:
1579 printf(" unknown code(%02x)", ntohs(nih->ni_code));
1580 }
1581 printf("; seq=%u;", ntohsp((__u16*)nih->ni_nonce));
1582}
1583
1584/*
1585 * parse_reply --
1586 * Print out the packet, if it came from us. This logic is necessary
1587 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1588 * which arrive ('tis only fair). This permits multiple copies of this
1589 * program to be run without having intermingled output (or statistics!).
1590 */
1591int
1592parse_reply(struct msghdr *msg, int cc, void *addr, struct timeval *tv)
1593{
1594 struct sockaddr_in6 *from = addr;
1595 __u8 *buf = msg->msg_iov->iov_base;
1596 struct cmsghdr *c;
1597 struct icmp6_hdr *icmph;
1598 int hops = -1;
1599
1600 for (c = CMSG_FIRSTHDR(msg); c; c = CMSG_NXTHDR(msg, c)) {
1601 if (c->cmsg_level != SOL_IPV6)
1602 continue;
1603 switch(c->cmsg_type) {
1604 case IPV6_HOPLIMIT:
1605#ifdef IPV6_2292HOPLIMIT
1606 case IPV6_2292HOPLIMIT:
1607#endif
1608 if (c->cmsg_len < CMSG_LEN(sizeof(int)))
1609 continue;
1610 memcpy(&hops, CMSG_DATA(c), sizeof(hops));
1611 }
1612 }
1613
1614
1615 /* Now the ICMP part */
1616
1617 icmph = (struct icmp6_hdr *) buf;
1618 if (cc < 8) {
1619 if (options & F_VERBOSE)
1620 fprintf(stderr, "ping: packet too short (%d bytes)\n", cc);
1621 return 1;
1622 }
1623
1624 if (icmph->icmp6_type == ICMP6_ECHO_REPLY) {
Lorenzo Colittice2d2d02013-07-09 17:58:13 +09001625 if (!is_ours(icmph->icmp6_id))
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001626 return 1;
1627 if (gather_statistics((__u8*)icmph, sizeof(*icmph), cc,
1628 ntohs(icmph->icmp6_seq),
1629 hops, 0, tv, pr_addr(&from->sin6_addr),
1630 pr_echo_reply))
1631 return 0;
1632 } else if (icmph->icmp6_type == ICMPV6_NI_REPLY) {
1633 struct ni_hdr *nih = (struct ni_hdr *)icmph;
1634 int seq = niquery_check_nonce(nih->ni_nonce);
1635 if (seq < 0)
1636 return 1;
1637 if (gather_statistics((__u8*)icmph, sizeof(*icmph), cc,
1638 seq,
1639 hops, 0, tv, pr_addr(&from->sin6_addr),
1640 pr_niquery_reply))
1641 return 0;
1642 } else {
1643 int nexthdr;
1644 struct ip6_hdr *iph1 = (struct ip6_hdr*)(icmph+1);
1645 struct icmp6_hdr *icmph1 = (struct icmp6_hdr *)(iph1+1);
1646
1647 /* We must not ever fall here. All the messages but
1648 * echo reply are blocked by filter and error are
1649 * received with IPV6_RECVERR. Ugly code is preserved
1650 * however, just to remember what crap we avoided
1651 * using RECVRERR. :-)
1652 */
1653
1654 if (cc < 8+sizeof(struct ip6_hdr)+8)
1655 return 1;
1656
1657 if (memcmp(&iph1->ip6_dst, &whereto.sin6_addr, 16))
1658 return 1;
1659
1660 nexthdr = iph1->ip6_nxt;
1661
1662 if (nexthdr == 44) {
1663 nexthdr = *(__u8*)icmph1;
1664 icmph1++;
1665 }
1666 if (nexthdr == IPPROTO_ICMPV6) {
1667 if (icmph1->icmp6_type != ICMP6_ECHO_REQUEST ||
Lorenzo Colittice2d2d02013-07-09 17:58:13 +09001668 !is_ours(icmph1->icmp6_id))
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001669 return 1;
1670 acknowledge(ntohs(icmph1->icmp6_seq));
1671 if (working_recverr)
1672 return 0;
1673 nerrors++;
1674 if (options & F_FLOOD) {
1675 write_stdout("\bE", 2);
1676 return 0;
1677 }
1678 print_timestamp();
1679 printf("From %s: icmp_seq=%u ", pr_addr(&from->sin6_addr), ntohs(icmph1->icmp6_seq));
1680 } else {
1681 /* We've got something other than an ECHOREPLY */
1682 if (!(options & F_VERBOSE) || uid)
1683 return 1;
1684 print_timestamp();
1685 printf("From %s: ", pr_addr(&from->sin6_addr));
1686 }
1687 pr_icmph(icmph->icmp6_type, icmph->icmp6_code, ntohl(icmph->icmp6_mtu));
1688 }
1689
1690 if (!(options & F_FLOOD)) {
1691 if (options & F_AUDIBLE)
1692 putchar('\a');
1693 putchar('\n');
1694 fflush(stdout);
1695 } else {
1696 putchar('\a');
1697 fflush(stdout);
1698 }
1699 return 0;
1700}
1701
1702
1703int pr_icmph(__u8 type, __u8 code, __u32 info)
1704{
1705 switch(type) {
1706 case ICMP6_DST_UNREACH:
1707 printf("Destination unreachable: ");
1708 switch (code) {
1709 case ICMP6_DST_UNREACH_NOROUTE:
1710 printf("No route");
1711 break;
1712 case ICMP6_DST_UNREACH_ADMIN:
1713 printf("Administratively prohibited");
1714 break;
1715 case ICMP6_DST_UNREACH_BEYONDSCOPE:
1716 printf("Beyond scope of source address");
1717 break;
1718 case ICMP6_DST_UNREACH_ADDR:
1719 printf("Address unreachable");
1720 break;
1721 case ICMP6_DST_UNREACH_NOPORT:
1722 printf("Port unreachable");
1723 break;
1724 default:
1725 printf("Unknown code %d", code);
1726 break;
1727 }
1728 break;
1729 case ICMP6_PACKET_TOO_BIG:
1730 printf("Packet too big: mtu=%u", info);
1731 if (code)
1732 printf(", code=%d", code);
1733 break;
1734 case ICMP6_TIME_EXCEEDED:
1735 printf("Time exceeded: ");
1736 if (code == ICMP6_TIME_EXCEED_TRANSIT)
1737 printf("Hop limit");
1738 else if (code == ICMP6_TIME_EXCEED_REASSEMBLY)
1739 printf("Defragmentation failure");
1740 else
1741 printf("code %d", code);
1742 break;
1743 case ICMP6_PARAM_PROB:
1744 printf("Parameter problem: ");
1745 if (code == ICMP6_PARAMPROB_HEADER)
1746 printf("Wrong header field ");
1747 else if (code == ICMP6_PARAMPROB_NEXTHEADER)
1748 printf("Unknown header ");
1749 else if (code == ICMP6_PARAMPROB_OPTION)
1750 printf("Unknown option ");
1751 else
1752 printf("code %d ", code);
1753 printf ("at %u", info);
1754 break;
1755 case ICMP6_ECHO_REQUEST:
1756 printf("Echo request");
1757 break;
1758 case ICMP6_ECHO_REPLY:
1759 printf("Echo reply");
1760 break;
1761 case MLD_LISTENER_QUERY:
1762 printf("MLD Query");
1763 break;
1764 case MLD_LISTENER_REPORT:
1765 printf("MLD Report");
1766 break;
1767 case MLD_LISTENER_REDUCTION:
1768 printf("MLD Reduction");
1769 break;
1770 default:
1771 printf("unknown icmp type: %u", type);
1772
1773 }
1774 return 0;
1775}
1776
1777#include <linux/filter.h>
1778
1779void install_filter(void)
1780{
1781 static int once;
1782 static struct sock_filter insns[] = {
1783 BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 4), /* Load icmp echo ident */
1784 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xAAAA, 0, 1), /* Ours? */
1785 BPF_STMT(BPF_RET|BPF_K, ~0U), /* Yes, it passes. */
1786 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 0), /* Load icmp type */
1787 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ICMP6_ECHO_REPLY, 1, 0), /* Echo? */
1788 BPF_STMT(BPF_RET|BPF_K, ~0U), /* No. It passes. This must not happen. */
1789 BPF_STMT(BPF_RET|BPF_K, 0), /* Echo with wrong ident. Reject. */
1790 };
1791 static struct sock_fprog filter = {
1792 sizeof insns / sizeof(insns[0]),
1793 insns
1794 };
1795
1796 if (once)
1797 return;
1798 once = 1;
1799
1800 /* Patch bpflet for current identifier. */
1801 insns[1] = (struct sock_filter)BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, htons(ident), 0, 1);
1802
1803 if (setsockopt(icmp_sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)))
1804 perror("WARNING: failed to install socket filter\n");
1805}
1806
1807
1808/*
1809 * pr_addr --
1810 * Return an ascii host address as a dotted quad and optionally with
1811 * a hostname.
1812 */
1813char * pr_addr(struct in6_addr *addr)
1814{
1815 struct hostent *hp = NULL;
1816 static char *s;
1817
1818#ifdef USE_IDN
1819 free(s);
1820#endif
1821
1822 in_pr_addr = !setjmp(pr_addr_jmp);
1823
1824 if (!(exiting || options&F_NUMERIC))
1825 hp = gethostbyaddr((__u8*)addr, sizeof(struct in6_addr), AF_INET6);
1826
1827 in_pr_addr = 0;
1828
1829 if (!hp
1830#ifdef USE_IDN
1831 || idna_to_unicode_lzlz(hp->h_name, &s, 0) != IDNA_SUCCESS
1832#endif
1833 )
1834 s = NULL;
1835
1836 return hp ? (s ? s : hp->h_name) : pr_addr_n(addr);
1837}
1838
1839char * pr_addr_n(struct in6_addr *addr)
1840{
1841 static char str[64];
1842 inet_ntop(AF_INET6, addr, str, sizeof(str));
1843 return str;
1844}
1845
1846#define USAGE_NEWLINE "\n "
1847
1848void usage(void)
1849{
1850 fprintf(stderr,
1851 "Usage: ping6"
1852 " [-"
1853 "aAbBdDfhLnOqrRUvV"
1854 "]"
1855 " [-c count]"
1856 " [-i interval]"
1857 " [-I interface]"
1858 USAGE_NEWLINE
1859 " [-l preload]"
1860 " [-m mark]"
1861 " [-M pmtudisc_option]"
1862 USAGE_NEWLINE
1863 " [-N nodeinfo_option]"
1864 " [-p pattern]"
1865 " [-Q tclass]"
1866 " [-s packetsize]"
1867 USAGE_NEWLINE
1868 " [-S sndbuf]"
1869 " [-t ttl]"
1870 " [-T timestamp_option]"
1871 " [-w deadline]"
1872 USAGE_NEWLINE
1873 " [-W timeout]"
1874#ifdef ENABLE_PING6_RTHDR
1875 " [hop1 ...]"
1876#endif
1877 " destination"
1878 "\n"
1879 );
1880 exit(2);
1881}