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