Debian Codegraph @

ping/ping.c

raw
1 /*
2 * Copyright (c) 1989 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Mike Muuss.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32 /*
33 * P I N G . C
34 *
35 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
36 * measure round-trip-delays and packet loss across network paths.
37 *
38 * Author -
39 * Mike Muuss
40 * U. S. Army Ballistic Research Laboratory
41 * December, 1983
42 *
43 * Status -
44 * Public Domain. Distribution Unlimited.
45 * Bugs -
46 * More statistics could always be gathered.
47 * If kernel does not support ICMP datagram sockets,
48 * this program has to run SUID to ROOT or with
49 * net_cap_raw enabled.
50 */
51
52 #define _GNU_SOURCE
53
54 #include "ping.h"
55
56 #include <assert.h>
57 #include <netinet/ip.h>
58 #include <netinet/ip_icmp.h>
59 #include <ifaddrs.h>
60 #include <math.h>
61 #include <locale.h>
62 #include <sys/param.h>
63
64 /* FIXME: global_rts will be removed in future */
65 struct ping_rts *global_rts;
66
67 char *_pr_addr(struct ping_rts *rts, void *sa, socklen_t salen, int resolve_name);
68
69 #ifndef ICMP_FILTER
70 #define ICMP_FILTER 1
71 struct icmp_filter {
72 uint32_t data;
73 };
74 #endif
75
76 ping_func_set_st ping4_func_set = {
77 .send_probe = ping4_send_probe,
78 .receive_error_msg = ping4_receive_error_msg,
79 .parse_reply = ping4_parse_reply,
80 .install_filter = ping4_install_filter
81 };
82
83 #define MAXIPLEN 60
84 #define MAXICMPLEN 76
85 #define NROUTES 9 /* number of record route slots */
86 #define TOS_MAX 255 /* 8-bit TOS field */
87
88 /* max. IPv4 packet size - IPv4 header size - ICMP header size */
89 #define ICMP_MAX_DATALEN (MAXPACKET - 20 - 8)
90
91 /* max. IPv6 payload size - ICMPv6 Echo Reply Header */
92 #define ICMPV6_MAX_DATALEN (MAXPACKET - sizeof (struct icmp6_hdr))
93
94 #define CASE_TYPE(x) case x: return #x;
95
96 static char *str_family(int family)
97 {
98 switch (family) {
99 CASE_TYPE(AF_UNSPEC)
100 CASE_TYPE(AF_INET)
101 CASE_TYPE(AF_INET6)
102 default:
103 error(2, 0, _("unknown protocol family: %d"), family);
104 }
105
106 return "";
107 }
108
109 static char *str_socktype(int socktype)
110 {
111 if (!socktype)
112 return "0";
113
114 switch (socktype) {
115 CASE_TYPE(SOCK_DGRAM)
116 CASE_TYPE(SOCK_RAW)
117 default:
118 error(2, 0, _("unknown sock type: %d"), socktype);
119 }
120
121 return "";
122 }
123
124 static int get_ipv4_optlen(struct ping_rts *rts)
125 {
126 if (rts->opt_rroute || rts->opt_timestamp || rts->opt_sourceroute)
127 return 40;
128
129 return 0;
130 }
131
132 static void create_socket(struct ping_rts *rts, socket_st *sock, int family,
133 int socktype, int protocol, int requisite)
134 {
135 int do_fallback = 0;
136
137 errno = 0;
138
139 assert(sock->fd == -1);
140 assert(socktype == SOCK_DGRAM || socktype == SOCK_RAW);
141
142 /* Attempt to create a ping socket if requested. Attempt to create a raw
143 * socket otherwise or as a fallback. Well known errno values follow.
144 *
145 * 1) EACCES
146 *
147 * Kernel returns EACCES for all ping socket creation attempts when the
148 * user isn't allowed to use ping socket. A range of group ids is
149 * configured using the `net.ipv4.ping_group_range` sysctl. Fallback
150 * to raw socket is necessary.
151 *
152 * Kernel returns EACCES for all raw socket creation attempts when the
153 * process doesn't have the `CAP_NET_RAW` capability.
154 *
155 * 2) EAFNOSUPPORT
156 *
157 * Kernel returns EAFNOSUPPORT for IPv6 ping or raw socket creation
158 * attempts when run with IPv6 support disabled (e.g. via `ipv6.disable=1`
159 * kernel command-line option.
160 *
161 * https://github.com/iputils/iputils/issues/32
162 *
163 * OpenVZ 2.6.32-042stab113.11 and possibly other older kernels return
164 * EAFNOSUPPORT for all IPv4 ping socket creation attempts due to lack
165 * of support in the kernel. Fallback to raw socket is necessary.
166 *
167 * https://github.com/iputils/iputils/issues/54
168 *
169 * 3) EPROTONOSUPPORT
170 *
171 * OpenVZ 2.6.32-042stab113.11 and possibly other older kernels return
172 * EPROTONOSUPPORT for all IPv6 ping socket creation attempts due to lack
173 * of support in the kernel [1]. Debian 9.5 based container with kernel 4.10
174 * returns EPROTONOSUPPORT also for IPv4 [2]. Fallback to raw socket is
175 * necessary.
176 *
177 * [1] https://github.com/iputils/iputils/issues/54
178 * [2] https://github.com/iputils/iputils/issues/129
179 */
180 if (socktype == SOCK_DGRAM)
181 sock->fd = socket(family, socktype, protocol);
182
183 /* Kernel doesn't support ping sockets. */
184 if (sock->fd == -1 && errno == EAFNOSUPPORT && family == AF_INET)
185 do_fallback = 1;
186 if (sock->fd == -1 && errno == EPROTONOSUPPORT)
187 do_fallback = 1;
188
189 /* User is not allowed to use ping sockets. */
190 if (sock->fd == -1 && errno == EACCES)
191 do_fallback = 1;
192
193 if (socktype == SOCK_RAW || do_fallback) {
194 socktype = SOCK_RAW;
195 sock->fd = socket(family, SOCK_RAW, protocol);
196 }
197
198 sock->socktype = socktype;
199
200 /* valid socket */
201 if (sock->fd != -1)
202 return;
203
204 /* failed to create socket */
205
206 if (requisite || rts->opt_verbose) {
207 error(0, 0, "socktype: %s", str_socktype(socktype));
208 error(0, errno, "socket");
209 }
210
211 if (requisite) {
212 if (socktype == SOCK_RAW && geteuid() != 0)
213 error(0, 0, _("=> missing cap_net_raw+p capability or setuid?"));
214
215 exit(2);
216 }
217 }
218
219 static void set_socket_option(socket_st *sock, int level, int optname,
220 const void *optval, socklen_t olen)
221 {
222 if (sock->fd == -1)
223 return;
224
225 if (setsockopt(sock->fd, level, optname, optval, olen) == -1)
226 error(2, errno, "setsockopt");
227 }
228
229 /* Much like strtod(3), but will fails if str is not valid number. */
230 static double ping_strtod(const char *str, const char *err_msg)
231 {
232 double num;
233 char *end = NULL;
234 int strtod_errno = 0;
235
236 if (str == NULL || *str == '\0')
237 goto err;
238 errno = 0;
239
240 /*
241 * Here we always want to use locale regardless USE_IDN or ENABLE_NLS,
242 * because it handles decimal point of -i/-W input options.
243 */
244 setlocale(LC_ALL, "C");
245 num = strtod(str, &end);
246 strtod_errno = errno;
247 setlocale(LC_ALL, "");
248 /* Ignore setlocale() errno (e.g. invalid locale in env). */
249 errno = strtod_errno;
250
251 if (errno || str == end || (end && *end)) {
252 error(0, 0, _("option argument contains garbage: %s"), end);
253 error(0, 0, _("this will become fatal error in the future"));
254 }
255 switch (fpclassify(num)) {
256 case FP_NORMAL:
257 case FP_ZERO:
258 break;
259 default:
260 errno = ERANGE;
261 goto err;
262 }
263 return num;
264 err:
265 error(2, errno, "%s: %s", err_msg, str);
266 abort(); /* cannot be reached, above error() will exit */
267
268 return 0.0;
269 }
270
271 static int parseflow(char *str)
272 {
273 const char *cp;
274 unsigned long val;
275 char *ep;
276
277 /* handle both hex and decimal values */
278 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
279 cp = str + 2;
280 val = (int)strtoul(cp, &ep, 16);
281 } else {
282 val = (int)strtoul(str, &ep, 10);
283 }
284
285 /* doesn't look like decimal or hex, eh? */
286 if (*ep != '\0')
287 error(2, 0, _("bad value for flowinfo: %s"), str);
288
289 if (val & ~IPV6_FLOWINFO_FLOWLABEL)
290 error(2, 0, _("flow value is greater than 20 bits: %s"), str);
291
292 return (val);
293 }
294
295 /* Set Type of Service (TOS) and other Quality of Service relating bits */
296 static int parsetos(char *str)
297 {
298 const char *cp;
299 int tos;
300 char *ep;
301
302 /* handle both hex and decimal values */
303 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
304 cp = str + 2;
305 tos = (int)strtol(cp, &ep, 16);
306 } else {
307 tos = (int)strtol(str, &ep, 10);
308 }
309
310 /* doesn't look like decimal or hex, eh? */
311 if (*ep != '\0')
312 error(2, 0, _("bad TOS value: %s"), str);
313
314 if (tos > TOS_MAX)
315 error(2, 0, _("the decimal value of TOS bits must be in range 0-255: %d"), tos);
316
317 return (tos);
318 }
319
320 int
321 main(int argc, char **argv)
322 {
323 struct addrinfo hints = {
324 .ai_family = AF_UNSPEC,
325 .ai_protocol = IPPROTO_UDP,
326 .ai_socktype = SOCK_DGRAM,
327 .ai_flags = getaddrinfo_flags
328 };
329 struct addrinfo *result, *ai;
330 int ret_val;
331 int ch;
332 socket_st sock4 = { .fd = -1 };
333 socket_st sock6 = { .fd = -1 };
334 char *target;
335 static struct ping_rts rts = {
336 .interval = 1000,
337 .preload = 1,
338 .lingertime = MAXWAIT * 1000000,
339 .confirm_flag = MSG_CONFIRM,
340 .tmin = LONG_MAX,
341 .pipesize = -1,
342 .datalen = DEFDATALEN,
343 .ident = -1,
344 .screen_width = INT_MAX,
345 #ifdef HAVE_LIBCAP
346 .cap_raw = CAP_NET_RAW,
347 .cap_admin = CAP_NET_ADMIN,
348 #endif
349 .pmtudisc = -1,
350 .source.sin_family = AF_INET,
351 .source6.sin6_family = AF_INET6,
352 .ni.query = -1,
353 .ni.subject_type = -1,
354 };
355 unsigned char buf[sizeof(struct in6_addr)];
356
357 /* FIXME: global_rts will be removed in future */
358 global_rts = &rts;
359
360 atexit(close_stdout);
361 limit_capabilities(&rts);
362
363 #if defined(USE_IDN) || defined(ENABLE_NLS)
364 setlocale(LC_ALL, "");
365 #if defined(USE_IDN)
366 if (!strcmp(setlocale(LC_ALL, NULL), "C"))
367 hints.ai_flags &= ~ AI_CANONIDN;
368 #endif
369 #ifdef ENABLE_NLS
370 bindtextdomain (PACKAGE_NAME, LOCALEDIR);
371 textdomain (PACKAGE_NAME);
372 #endif
373 #endif
374
375 /* Support being called using `ping4` or `ping6` symlinks */
376 if (argv[0][strlen(argv[0]) - 1] == '4')
377 hints.ai_family = AF_INET;
378 else if (argv[0][strlen(argv[0]) - 1] == '6')
379 hints.ai_family = AF_INET6;
380
381 /*
382 * Optionally disable reverse DNS resolution (PTR lookup) by default.
383 * -n/-H override the variable. Warn below if disabled due this.
384 */
385 char *env = getenv("IPUTILS_PING_PTR_LOOKUP");
386 int force_numeric = 0;
387 if (env && !strcmp(env, "0")) {
388 rts.opt_numeric = 1;
389 force_numeric = 1;
390 }
391
392 /* Parse command line options */
393 while ((ch = getopt(argc, argv, "h?" "4bRT:" "6F:N:" "3aABc:CdDe:fHi:I:l:Lm:M:nOp:qQ:rs:S:t:UvVw:W:")) != EOF) {
394 switch(ch) {
395 /* IPv4 specific options */
396 case '4':
397 if (hints.ai_family == AF_INET6)
398 error(2, 0, _("only one -4 or -6 option may be specified"));
399 hints.ai_family = AF_INET;
400 break;
401 case '3':
402 rts.opt_rtt_precision = 1;
403 break;
404 case 'b':
405 rts.broadcast_pings = 1;
406 break;
407 case 'e':
408 rts.ident = htons(strtoul_or_err(optarg, _("invalid argument"),
409 0, IDENTIFIER_MAX));
410 break;
411 case 'R':
412 if (rts.opt_timestamp)
413 error(2, 0, _("only one of -T or -R may be used"));
414 rts.opt_rroute = 1;
415 break;
416 case 'T':
417 if (rts.opt_rroute)
418 error(2, 0, _("only one of -T or -R may be used"));
419 rts.opt_timestamp = 1;
420 if (strcmp(optarg, "tsonly") == 0)
421 rts.ts_type = IPOPT_TS_TSONLY;
422 else if (strcmp(optarg, "tsandaddr") == 0)
423 rts.ts_type = IPOPT_TS_TSANDADDR;
424 else if (strcmp(optarg, "tsprespec") == 0)
425 rts.ts_type = IPOPT_TS_PRESPEC;
426 else
427 error(2, 0, _("invalid timestamp type: %s"), optarg);
428 break;
429 /* IPv6 specific options */
430 case '6':
431 if (hints.ai_family == AF_INET)
432 error(2, 0, _("only one -4 or -6 option may be specified"));
433 hints.ai_family = AF_INET6;
434 break;
435 case 'F':
436 rts.flowlabel = parseflow(optarg);
437 rts.opt_flowinfo = 1;
438 break;
439 case 'N':
440 if (niquery_option_handler(&rts.ni, optarg) < 0)
441 usage();
442 hints.ai_socktype = SOCK_RAW;
443 break;
444 /* Common options */
445 case 'a':
446 rts.opt_audible = 1;
447 break;
448 case 'A':
449 rts.opt_adaptive = 1;
450 break;
451 case 'B':
452 rts.opt_strictsource = 1;
453 break;
454 case 'c':
455 rts.npackets = strtol_or_err(optarg, _("invalid argument"), 1, LONG_MAX);
456 break;
457 case 'C':
458 rts.opt_connect_sk = 1;
459 break;
460 case 'd':
461 rts.opt_so_debug = 1;
462 break;
463 case 'D':
464 rts.opt_ptimeofday = 1;
465 break;
466 case 'H':
467 rts.opt_force_lookup = 1;
468 break;
469 case 'i':
470 {
471 double optval;
472
473 optval = ping_strtod(optarg, _("bad timing interval"));
474 if (isless(optval, 0) || isgreater(optval, (double)INT_MAX / 1000))
475 error(2, 0, _("bad timing interval: %s"), optarg);
476 rts.interval = (int)(optval * 1000);
477 rts.opt_interval = 1;
478 }
479 break;
480 case 'I':
481 /* IPv6 */
482 if (strchr(optarg, ':')) {
483 char *p, *addr = strdup(optarg);
484
485 if (!addr)
486 error(2, errno, _("cannot copy: %s"), optarg);
487
488 p = strchr(addr, SCOPE_DELIMITER);
489 if (p) {
490 *p = '\0';
491 rts.device = optarg + (p - addr) + 1;
492 }
493
494 if (inet_pton(AF_INET6, addr, (char *)&rts.source6.sin6_addr) <= 0)
495 error(2, 0, _("invalid source address: %s"), optarg);
496
497 rts.opt_strictsource = 1;
498
499 free(addr);
500 } else if (inet_pton(AF_INET, optarg, &rts.source.sin_addr) > 0) {
501 rts.opt_strictsource = 1;
502 } else {
503 rts.device = optarg;
504 }
505 break;
506 case 'l':
507 rts.preload = strtol_or_err(optarg, _("invalid argument"), 1, MAX_DUP_CHK);
508 if (rts.uid && rts.preload > 3)
509 error(2, 0, _("cannot set preload to value greater than 3: %d"), rts.preload);
510 break;
511 case 'L':
512 rts.opt_noloop = 1;
513 break;
514 case 'm':
515 rts.mark = strtoul_or_err(optarg, _("invalid argument"), 0, UINT_MAX);
516 rts.opt_mark = 1;
517 break;
518 case 'M':
519 if (strcmp(optarg, "do") == 0)
520 rts.pmtudisc = IP_PMTUDISC_DO;
521 else if (strcmp(optarg, "dont") == 0)
522 rts.pmtudisc = IP_PMTUDISC_DONT;
523 else if (strcmp(optarg, "want") == 0)
524 rts.pmtudisc = IP_PMTUDISC_WANT;
525 else if (strcmp(optarg, "probe") == 0)
526 rts.pmtudisc = IP_PMTUDISC_PROBE;
527 else
528 error(2, 0, _("invalid -M argument: %s"), optarg);
529 break;
530 case 'n':
531 rts.opt_numeric = 1;
532 rts.opt_force_lookup = 0;
533 break;
534 case 'O':
535 rts.opt_outstanding = 1;
536 break;
537 case 'f':
538 rts.opt_flood = 1;
539 /* avoid `getaddrinfo()` during flood */
540 rts.opt_numeric = 1;
541 setbuf(stdout, (char *)NULL);
542 break;
543 case 'p':
544 rts.opt_pingfilled = 1;
545 fill(&rts, optarg, rts.outpack, sizeof(rts.outpack));
546 break;
547 case 'q':
548 rts.opt_quiet = 1;
549 break;
550 case 'Q':
551 rts.settos = parsetos(optarg); /* IPv4 */
552 rts.tclass = rts.settos; /* IPv6 */
553 break;
554 case 'r':
555 rts.opt_so_dontroute = 1;
556 break;
557 case 's':
558 /* real validation is done later */
559 rts.datalen = strtol_or_err(optarg, _("invalid argument"), 0, INT_MAX);
560 break;
561 case 'S':
562 rts.sndbuf = strtol_or_err(optarg, _("invalid argument"), 1, INT_MAX);
563 break;
564 case 't':
565 rts.ttl = strtol_or_err(optarg, _("invalid argument"), 0, 255);
566 rts.opt_ttl = 1;
567 break;
568 case 'U':
569 rts.opt_latency = 1;
570 break;
571 case 'v':
572 rts.opt_verbose = 1;
573 break;
574 case 'V':
575 printf(IPUTILS_VERSION("ping"));
576 print_config();
577 exit(0);
578 case 'w':
579 rts.deadline = strtol_or_err(optarg, _("invalid argument"), 0, INT_MAX);
580 break;
581 case 'W':
582 {
583 double optval;
584
585 optval = ping_strtod(optarg, _("bad linger time"));
586 if (isless(optval, 0) || isgreater(optval, (double)UINT_MAX / 1000000))
587 error(2, 0, _("bad linger time: %s"), optarg);
588
589 rts.lingertime = (uint32_t)(optval * 1000000);
590 }
591 break;
592 default:
593 usage();
594 break;
595 }
596 }
597
598 if (rts.opt_numeric && force_numeric && !rts.opt_quiet)
599 error(0, 0, _("WARNING: reverse DNS resolution (PTR lookup) disabled, enforce with -H"));
600
601 argc -= optind;
602 argv += optind;
603
604 if (!argc)
605 error(2, EDESTADDRREQ, "usage error");
606
607 target = argv[argc - 1];
608
609 /* Create sockets */
610 enable_capability_raw();
611
612 /*
613 * Current Linux kernel 6.0 doesn't support on SOCK_DGRAM setting
614 * ident == 0
615 */
616 if (!rts.ident) {
617 if (rts.opt_verbose)
618 error(0, 0, _("WARNING: ident 0 => forcing raw socket"));
619
620 hints.ai_socktype = SOCK_RAW;
621 }
622
623 if (hints.ai_family != AF_INET6) {
624 create_socket(&rts, &sock4, AF_INET, hints.ai_socktype, IPPROTO_ICMP,
625 hints.ai_family == AF_INET);
626 }
627
628 if (hints.ai_family != AF_INET) {
629 create_socket(&rts, &sock6, AF_INET6, hints.ai_socktype, IPPROTO_ICMPV6, sock4.fd == -1);
630
631 /* This may not be needed if both protocol versions always had the same value, but
632 * since I don't know that, it's better to be safe than sorry. */
633 rts.pmtudisc = rts.pmtudisc == IP_PMTUDISC_DO ? IPV6_PMTUDISC_DO :
634 rts.pmtudisc == IP_PMTUDISC_DONT ? IPV6_PMTUDISC_DONT :
635 rts.pmtudisc == IP_PMTUDISC_WANT ? IPV6_PMTUDISC_WANT :
636 rts.pmtudisc == IP_PMTUDISC_PROBE? IPV6_PMTUDISC_PROBE: rts.pmtudisc;
637 }
638
639 disable_capability_raw();
640
641 /* Limit address family on single-protocol systems */
642 if (hints.ai_family == AF_UNSPEC) {
643 if (sock4.fd == -1)
644 hints.ai_family = AF_INET6;
645 else if (sock6.fd == -1)
646 hints.ai_family = AF_INET;
647 }
648
649 int max_s = MAX(ICMP_MAX_DATALEN, ICMPV6_MAX_DATALEN);
650
651 /* Detect based on -4 / -6 */
652 if (hints.ai_family == AF_INET)
653 max_s = ICMP_MAX_DATALEN - get_ipv4_optlen(&rts);
654 else if (hints.ai_family == AF_INET6)
655 max_s = ICMPV6_MAX_DATALEN;
656
657 /* Force limit on IPv4/IPv6 adresses */
658 if (inet_pton(AF_INET, target, buf))
659 max_s = ICMP_MAX_DATALEN - get_ipv4_optlen(&rts);
660 else if (inet_pton(AF_INET6, target, buf))
661 max_s = ICMPV6_MAX_DATALEN;
662
663 if (rts.datalen > max_s)
664 error(EXIT_FAILURE, 0, _("invalid -s value: '%d': out of range: 0 <= value <= %d"),
665 rts.datalen, max_s);
666
667 if (rts.opt_verbose)
668 error(0, 0, "sock4.fd: %d (socktype: %s), sock6.fd: %d (socktype: %s),"
669 " hints.ai_family: %s",
670 sock4.fd, str_socktype(sock4.socktype),
671 sock6.fd, str_socktype(sock6.socktype),
672 str_family(hints.ai_family));
673
674 /* Set socket options */
675 if (rts.settos)
676 set_socket_option(&sock4, IPPROTO_IP, IP_TOS, &rts.settos, sizeof(rts.settos));
677 if (rts.tclass)
678 set_socket_option(&sock6, IPPROTO_IPV6, IPV6_TCLASS, &rts.tclass, sizeof(rts.tclass));
679
680 /* getaddrinfo fails to indicate a scopeid when not used in dual-stack mode.
681 * Work around by always using dual-stack name resolution.
682 *
683 * https://github.com/iputils/iputils/issues/252
684 */
685 int target_ai_family = hints.ai_family;
686 hints.ai_family = AF_UNSPEC;
687
688 if (!strchr(target, '%') && sock6.socktype == SOCK_DGRAM &&
689 inet_pton(AF_INET6, target, buf) > 0 &&
690 (IN6_IS_ADDR_LINKLOCAL(buf) || IN6_IS_ADDR_MC_LINKLOCAL(buf))) {
691 error(0, 0, _(
692 "Warning: IPv6 link-local address on ICMP datagram socket may require ifname or scope-id"
693 " => use: address%%<ifname|scope-id>"));
694 }
695
696 ret_val = getaddrinfo(target, NULL, &hints, &result);
697 if (ret_val)
698 error(2, 0, "%s: %s", target, gai_strerror(ret_val));
699
700 for (ai = result; ai; ai = ai->ai_next) {
701 if (rts.opt_verbose)
702 error(0, 0, "ai->ai_family: %s, ai->ai_canonname: '%s'",
703 str_family(ai->ai_family),
704 ai->ai_canonname ? ai->ai_canonname : "");
705
706 if (target_ai_family != AF_UNSPEC &&
707 target_ai_family != ai->ai_family) {
708 if (!ai->ai_next) {
709 /* An address was found, but not of the family we really want.
710 * Throw the appropriate gai error.
711 */
712 error(2, 0, "%s: %s", target, gai_strerror(EAI_ADDRFAMILY));
713 }
714 continue;
715 }
716 switch (ai->ai_family) {
717 case AF_INET:
718 ret_val = ping4_run(&rts, argc, argv, ai, &sock4);
719 break;
720 case AF_INET6:
721 ret_val = ping6_run(&rts, argc, argv, ai, &sock6);
722 break;
723 default:
724 error(2, 0, _("unknown protocol family: %d"), ai->ai_family);
725 }
726
727 if (ret_val >= 0)
728 break;
729 /* ret_val < 0 means to go on to next addrinfo result, there
730 * better be one. */
731 assert(ai->ai_next);
732 }
733
734 freeaddrinfo(result);
735
736 return ret_val;
737 }
738
739 static int iface_name2index(struct ping_rts *rts, int fd)
740 {
741 struct ifreq ifr;
742
743 memset(&ifr, 0, sizeof(ifr));
744 strncpy(ifr.ifr_name, rts->device, IFNAMSIZ - 1);
745
746 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0)
747 error(2, 0, _("unknown iface: %s"), rts->device);
748
749 return ifr.ifr_ifindex;
750 }
751
752 static void bind_to_device(struct ping_rts *rts, int fd, in_addr_t addr)
753 {
754 int rc;
755 int errno_save;
756
757 enable_capability_raw();
758 rc = setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, rts->device,
759 strlen(rts->device) + 1);
760 errno_save = errno;
761 disable_capability_raw();
762
763 if (rc != -1)
764 return;
765
766 if (IN_MULTICAST(ntohl(addr))) {
767 struct ip_mreqn imr;
768
769 memset(&imr, 0, sizeof(imr));
770 imr.imr_ifindex = iface_name2index(rts, fd);
771
772 if (setsockopt(fd, SOL_IP, IP_MULTICAST_IF, &imr, sizeof(imr)) == -1)
773 error(2, errno, "IP_MULTICAST_IF");
774 } else {
775 error(2, errno_save, "SO_BINDTODEVICE %s", rts->device);
776 }
777 }
778
779 /* return >= 0: exit with this code, < 0: go on to next addrinfo result */
780 int ping4_run(struct ping_rts *rts, int argc, char **argv, struct addrinfo *ai,
781 socket_st *sock)
782 {
783 static const struct addrinfo hints = {
784 .ai_family = AF_INET,
785 .ai_protocol = IPPROTO_UDP,
786 .ai_flags = getaddrinfo_flags
787 };
788 int hold, packlen;
789 unsigned char *packet;
790 char *target;
791 char hnamebuf[NI_MAXHOST];
792 unsigned char rspace[3 + 4 * NROUTES + 1]; /* record route space */
793 uint32_t *tmp_rspace;
794 struct sockaddr_in dst;
795 int ret;
796
797 if (argc > 1) {
798 if (rts->opt_rroute)
799 usage();
800 else if (rts->opt_timestamp) {
801 if (rts->ts_type != IPOPT_TS_PRESPEC)
802 usage();
803 if (argc > 5)
804 usage();
805 } else {
806 if (argc > 10)
807 usage();
808 rts->opt_sourceroute = 1;
809 }
810 }
811 while (argc > 0) {
812 target = *argv;
813
814 memset((char *)&rts->whereto, 0, sizeof(rts->whereto));
815 rts->whereto.sin_family = AF_INET;
816 if (inet_aton(target, &rts->whereto.sin_addr) == 1) {
817 rts->hostname = target;
818 if (argc == 1)
819 rts->opt_numeric = 1;
820 } else {
821 struct addrinfo *result = ai;
822 int ret_val;
823
824 if (argc > 1) {
825 ret_val = getaddrinfo(target, NULL, &hints, &result);
826 if (ret_val)
827 error(2, 0, "%s: %s", target, gai_strerror(ret_val));
828 }
829
830 memcpy(&rts->whereto, result->ai_addr, sizeof rts->whereto);
831 memset(hnamebuf, 0, sizeof hnamebuf);
832
833 /*
834 * On certain network setup getaddrinfo() can return empty
835 * ai_canonname. Instead of printing nothing in "PING"
836 * line use the target.
837 */
838 if (result->ai_canonname)
839 strncpy(hnamebuf, result->ai_canonname, sizeof hnamebuf - 1);
840 else
841 strncpy(hnamebuf, target, sizeof hnamebuf - 1);
842
843 rts->hostname = hnamebuf;
844
845 if (argc > 1)
846 freeaddrinfo(result);
847 }
848 if (argc > 1)
849 rts->route[rts->nroute++] = rts->whereto.sin_addr.s_addr;
850 argc--;
851 argv++;
852 }
853
854 if (rts->source.sin_addr.s_addr == 0) {
855 socklen_t alen;
856 int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
857 dst = rts->whereto;
858
859 if (probe_fd < 0)
860 error(2, errno, "socket");
861
862 if (rts->device) {
863 bind_to_device(rts, probe_fd, dst.sin_addr.s_addr);
864 bind_to_device(rts, sock->fd, dst.sin_addr.s_addr);
865 }
866
867 if (rts->settos &&
868 setsockopt(probe_fd, IPPROTO_IP, IP_TOS, (char *)&rts->settos, sizeof(int)) < 0)
869 error(0, errno, _("warning: QOS sockopts"));
870
871 sock_setmark(rts, probe_fd);
872
873 dst.sin_port = htons(1025);
874 if (rts->nroute)
875 dst.sin_addr.s_addr = rts->route[0];
876 if (connect(probe_fd, (struct sockaddr *)&dst, sizeof(dst)) == -1) {
877 if (errno == EACCES) {
878 if (rts->broadcast_pings == 0)
879 error(2, 0,
880 _("Do you want to ping broadcast? Then -b. If not, check your local firewall rules"));
881 fprintf(stderr, _("WARNING: pinging broadcast address\n"));
882 if (setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
883 &rts->broadcast_pings, sizeof(rts->broadcast_pings)) < 0)
884 error(2, errno, _("cannot set broadcasting"));
885 if (connect(probe_fd, (struct sockaddr *)&dst, sizeof(dst)) == -1)
886 error(2, errno, "connect");
887 } else if ((errno == EHOSTUNREACH || errno == ENETUNREACH) && ai->ai_next) {
888 close(probe_fd);
889 return -1;
890 } else {
891 error(2, errno, "connect");
892 }
893 }
894 alen = sizeof(rts->source);
895 if (getsockname(probe_fd, (struct sockaddr *)&rts->source, &alen) == -1)
896 error(2, errno, "getsockname");
897 rts->source.sin_port = 0;
898
899 if (rts->device) {
900 struct ifaddrs *ifa0, *ifa;
901 int ret;
902
903 ret = getifaddrs(&ifa0);
904 if (ret)
905 error(2, errno, _("gatifaddrs failed"));
906 for (ifa = ifa0; ifa; ifa = ifa->ifa_next) {
907 if (!ifa->ifa_name || !ifa->ifa_addr ||
908 ifa->ifa_addr->sa_family != AF_INET)
909 continue;
910 if (!strcmp(ifa->ifa_name, rts->device) &&
911 !memcmp(&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
912 &rts->source.sin_addr, sizeof(rts->source.sin_addr)))
913 break;
914 }
915 freeifaddrs(ifa0);
916 if (!ifa)
917 error(0, 0, _("Warning: source address might be selected on device other than: %s"), rts->device);
918 }
919 close(probe_fd);
920
921 } else if (rts->device) {
922 bind_to_device(rts, sock->fd, rts->whereto.sin_addr.s_addr);
923 }
924
925 if (rts->whereto.sin_addr.s_addr == 0)
926 rts->whereto.sin_addr.s_addr = rts->source.sin_addr.s_addr;
927
928 if (rts->broadcast_pings || IN_MULTICAST(ntohl(rts->whereto.sin_addr.s_addr))) {
929 rts->multicast = 1;
930
931 if (rts->uid) {
932 if (rts->interval < MIN_MULTICAST_USER_INTERVAL_MS)
933 error(2, 0, _("minimal interval for broadcast ping for user must be >= %d ms, use -i %s (or higher)"),
934 MIN_MULTICAST_USER_INTERVAL_MS,
935 str_interval(MIN_MULTICAST_USER_INTERVAL_MS));
936
937 if (rts->pmtudisc >= 0 && rts->pmtudisc != IP_PMTUDISC_DO)
938 error(2, 0, _("broadcast ping does not fragment"));
939 }
940
941 if (rts->pmtudisc < 0)
942 rts->pmtudisc = IP_PMTUDISC_DO;
943 }
944
945 if (rts->pmtudisc >= 0) {
946 if (setsockopt(sock->fd, SOL_IP, IP_MTU_DISCOVER, &rts->pmtudisc, sizeof rts->pmtudisc) == -1)
947 error(2, errno, "IP_MTU_DISCOVER");
948 }
949
950 int set_ident = rts->ident > 0 && sock->socktype == SOCK_DGRAM;
951 if (set_ident)
952 rts->source.sin_port = rts->ident;
953
954 if (rts->opt_strictsource || set_ident) {
955 if (bind(sock->fd, (struct sockaddr *)&rts->source, sizeof rts->source) == -1)
956 error(2, errno, "bind");
957 }
958
959 if (sock->socktype == SOCK_RAW) {
960 struct icmp_filter filt;
961 filt.data = ~((1 << ICMP_SOURCE_QUENCH) |
962 (1 << ICMP_DEST_UNREACH) |
963 (1 << ICMP_TIME_EXCEEDED) |
964 (1 << ICMP_PARAMETERPROB) |
965 (1 << ICMP_REDIRECT) |
966 (1 << ICMP_ECHOREPLY));
967 if (setsockopt(sock->fd, SOL_RAW, ICMP_FILTER, &filt, sizeof filt) == -1)
968 error(0, errno, _("WARNING: setsockopt(ICMP_FILTER)"));
969 }
970
971 hold = 1;
972 if (setsockopt(sock->fd, SOL_IP, IP_RECVERR, &hold, sizeof hold))
973 error(0, 0, _("WARNING: your kernel is veeery old. No problems."));
974
975 if (sock->socktype == SOCK_DGRAM) {
976 if (setsockopt(sock->fd, SOL_IP, IP_RECVTTL, &hold, sizeof hold))
977 error(0, errno, _("WARNING: setsockopt(IP_RECVTTL)"));
978 if (setsockopt(sock->fd, SOL_IP, IP_RETOPTS, &hold, sizeof hold))
979 error(0, errno, _("WARNING: setsockopt(IP_RETOPTS)"));
980 }
981
982 /* record route option */
983 if (rts->opt_rroute) {
984 memset(rspace, 0, sizeof(rspace));
985 rspace[0] = IPOPT_NOP;
986 rspace[1 + IPOPT_OPTVAL] = IPOPT_RR;
987 rspace[1 + IPOPT_OLEN] = sizeof(rspace) - 1;
988 rspace[1 + IPOPT_OFFSET] = IPOPT_MINOFF;
989 if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, sizeof rspace) < 0)
990 error(2, errno, "record route");
991 }
992 if (rts->opt_timestamp) {
993 memset(rspace, 0, sizeof(rspace));
994 rspace[0] = IPOPT_TIMESTAMP;
995 rspace[1] = (rts->ts_type == IPOPT_TS_TSONLY ? 40 : 36);
996 rspace[2] = 5;
997 rspace[3] = rts->ts_type;
998 if (rts->ts_type == IPOPT_TS_PRESPEC) {
999 int i;
1000 rspace[1] = 4 + rts->nroute * 8;
1001 for (i = 0; i < rts->nroute; i++) {
1002 tmp_rspace = (uint32_t *)&rspace[4 + i * 8];
1003 *tmp_rspace = rts->route[i];
1004 }
1005 }
1006 if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
1007 rspace[3] = 2;
1008 if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0)
1009 error(2, errno, "ts option");
1010 }
1011 }
1012 if (rts->opt_sourceroute) {
1013 int i;
1014 memset(rspace, 0, sizeof(rspace));
1015 rspace[0] = IPOPT_NOOP;
1016 rspace[1 + IPOPT_OPTVAL] = rts->opt_so_dontroute ? IPOPT_SSRR : IPOPT_LSRR;
1017 rspace[1 + IPOPT_OLEN] = 3 + rts->nroute * 4;
1018 rspace[1 + IPOPT_OFFSET] = IPOPT_MINOFF;
1019 for (i = 0; i < rts->nroute; i++) {
1020 tmp_rspace = (uint32_t *)&rspace[4 + i * 4];
1021 *tmp_rspace = rts->route[i];
1022 }
1023
1024 if (setsockopt(sock->fd, IPPROTO_IP, IP_OPTIONS, rspace, 4 + rts->nroute * 4) < 0)
1025 error(2, errno, "record route");
1026 }
1027
1028 rts->optlen = get_ipv4_optlen(rts);
1029
1030 /* Estimate memory eaten by single packet. It is rough estimate.
1031 * Actually, for small datalen's it depends on kernel side a lot. */
1032 hold = rts->datalen + 8;
1033 hold += ((hold + 511) / 512) * (rts->optlen + 20 + 16 + 64 + 160);
1034 sock_setbufs(rts, sock, hold);
1035
1036 if (rts->broadcast_pings) {
1037 if (setsockopt(sock->fd, SOL_SOCKET, SO_BROADCAST, &rts->broadcast_pings,
1038 sizeof rts->broadcast_pings) < 0)
1039 error(2, errno, _("cannot set broadcasting"));
1040 }
1041
1042 if (rts->opt_noloop) {
1043 int loop = 0;
1044 if (setsockopt(sock->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof loop) == -1)
1045 error(2, errno, _("cannot disable multicast loopback"));
1046 }
1047 if (rts->opt_ttl) {
1048 int ittl = rts->ttl;
1049 if (setsockopt(sock->fd, IPPROTO_IP, IP_MULTICAST_TTL, &rts->ttl, sizeof rts->ttl) == -1)
1050 error(2, errno, _("cannot set multicast time-to-live"));
1051 if (setsockopt(sock->fd, IPPROTO_IP, IP_TTL, &ittl, sizeof ittl) == -1)
1052 error(2, errno, _("cannot set unicast time-to-live"));
1053 }
1054
1055 if (rts->datalen >= (int)sizeof(struct timeval)) /* can we time transfer */
1056 rts->timing = 1;
1057 packlen = rts->datalen + MAXIPLEN + MAXICMPLEN;
1058 if (!(packet = (unsigned char *)malloc((unsigned int)packlen)))
1059 error(2, errno, _("memory allocation failed"));
1060
1061 printf(_("PING %s (%s) "), rts->hostname, inet_ntoa(rts->whereto.sin_addr));
1062 if (rts->device || rts->opt_strictsource)
1063 printf(_("from %s %s: "), inet_ntoa(rts->source.sin_addr), rts->device ? rts->device : "");
1064 printf(_("%d(%d) bytes of data.\n"), rts->datalen, rts->datalen + 8 + rts->optlen + 20);
1065
1066 setup(rts, sock);
1067 if (rts->opt_connect_sk &&
1068 connect(sock->fd, (struct sockaddr *)&dst, sizeof(dst)) == -1)
1069 error(2, errno, "connect failed");
1070
1071 drop_capabilities();
1072
1073 ret = main_loop(rts, &ping4_func_set, sock, packet, packlen);
1074 free(packet);
1075
1076 return ret;
1077 }
1078
1079 static void pr_options(struct ping_rts *rts, unsigned char *cp, int hlen)
1080 {
1081 int i, j;
1082 int olen, totlen;
1083 unsigned char *optptr;
1084 static int old_rrlen;
1085 static char old_rr[MAX_IPOPTLEN];
1086
1087 totlen = hlen - sizeof(struct iphdr);
1088 optptr = cp;
1089
1090 while (totlen > 0) {
1091 if (*optptr == IPOPT_EOL)
1092 break;
1093 if (*optptr == IPOPT_NOP) {
1094 totlen--;
1095 optptr++;
1096 printf(_("\nNOP"));
1097 continue;
1098 }
1099 cp = optptr;
1100 olen = optptr[1];
1101 if (olen < 2 || olen > totlen)
1102 break;
1103
1104 switch (*cp) {
1105 case IPOPT_SSRR:
1106 case IPOPT_LSRR:
1107 printf(_("\n%cSRR: "), *cp == IPOPT_SSRR ? 'S' : 'L');
1108 j = *++cp;
1109 cp++;
1110 if (j > IPOPT_MINOFF) {
1111 for (;;) {
1112 uint32_t address;
1113 memcpy(&address, cp, 4);
1114 cp += 4;
1115 if (address == 0)
1116 printf("\t0.0.0.0");
1117 else {
1118 struct sockaddr_in sin = {
1119 .sin_family = AF_INET,
1120 .sin_addr = {
1121 address
1122 }
1123 };
1124
1125 printf("\t%s", pr_addr(rts, &sin, sizeof sin));
1126 }
1127 j -= 4;
1128 putchar('\n');
1129 if (j <= IPOPT_MINOFF)
1130 break;
1131 }
1132 }
1133 break;
1134 case IPOPT_RR:
1135 j = *++cp; /* get length */
1136 i = *++cp; /* and pointer */
1137 if (i > j)
1138 i = j;
1139 i -= IPOPT_MINOFF;
1140 if (i <= 0)
1141 break;
1142 if (i == old_rrlen
1143 && !memcmp(cp, old_rr, i)
1144 && !rts->opt_flood) {
1145 printf(_("\t(same route)"));
1146 break;
1147 }
1148 old_rrlen = i;
1149 memcpy(old_rr, (char *)cp, i);
1150 printf(_("\nRR: "));
1151 cp++;
1152 for (;;) {
1153 uint32_t address;
1154 memcpy(&address, cp, 4);
1155 cp += 4;
1156 if (address == 0)
1157 printf("\t0.0.0.0");
1158 else {
1159 struct sockaddr_in sin = {
1160 .sin_family = AF_INET,
1161 .sin_addr = {
1162 address
1163 }
1164 };
1165
1166 printf("\t%s", pr_addr(rts, &sin, sizeof sin));
1167 }
1168 i -= 4;
1169 putchar('\n');
1170 if (i <= 0)
1171 break;
1172 }
1173 break;
1174 case IPOPT_TS:
1175 {
1176 int stdtime = 0, nonstdtime = 0;
1177 uint8_t flags;
1178 j = *++cp; /* get length */
1179 i = *++cp; /* and pointer */
1180 if (i > j)
1181 i = j;
1182 i -= 5;
1183 if (i <= 0)
1184 break;
1185 flags = *++cp;
1186 printf(_("\nTS: "));
1187 cp++;
1188 for (;;) {
1189 long l;
1190
1191 if ((flags & 0xF) != IPOPT_TS_TSONLY) {
1192 uint32_t address;
1193 memcpy(&address, cp, 4);
1194 cp += 4;
1195 if (address == 0)
1196 printf("\t0.0.0.0");
1197 else {
1198 struct sockaddr_in sin = {
1199 .sin_family = AF_INET,
1200 .sin_addr = {
1201 address
1202 }
1203 };
1204
1205 printf("\t%s", pr_addr(rts, &sin, sizeof sin));
1206 }
1207 i -= 4;
1208 if (i <= 0)
1209 break;
1210 }
1211 l = *cp++;
1212 l = (l << 8) + *cp++;
1213 l = (l << 8) + *cp++;
1214 l = (l << 8) + *cp++;
1215
1216 if (l & 0x80000000) {
1217 if (nonstdtime == 0)
1218 printf(_("\t%ld absolute not-standard"), l & 0x7fffffff);
1219 else
1220 printf(_("\t%ld not-standard"), (l & 0x7fffffff) - nonstdtime);
1221 nonstdtime = l & 0x7fffffff;
1222 } else {
1223 if (stdtime == 0)
1224 printf(_("\t%ld absolute"), l);
1225 else
1226 printf("\t%ld", l - stdtime);
1227 stdtime = l;
1228 }
1229 i -= 4;
1230 putchar('\n');
1231 if (i <= 0)
1232 break;
1233 }
1234 if (flags >> 4)
1235 printf(_("Unrecorded hops: %d\n"), flags >> 4);
1236 break;
1237 }
1238 default:
1239 printf(_("\nunknown option %x"), *cp);
1240 break;
1241 }
1242 totlen -= olen;
1243 optptr += olen;
1244 }
1245 }
1246
1247 /*
1248 * pr_iph --
1249 * Print an IP header with options.
1250 */
1251 static void pr_iph(struct ping_rts *rts, struct iphdr *ip)
1252 {
1253 int hlen;
1254 unsigned char *cp;
1255
1256 hlen = ip->ihl << 2;
1257 cp = (unsigned char *)ip + 20; /* point to options */
1258
1259 printf(_("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst Data\n"));
1260 printf(_(" %1x %1x %02x %04x %04x"),
1261 ip->version, ip->ihl, ip->tos, ip->tot_len, ip->id);
1262 printf(_(" %1x %04x"), ((ip->frag_off) & 0xe000) >> 13,
1263 (ip->frag_off) & 0x1fff);
1264 printf(_(" %02x %02x %04x"), ip->ttl, ip->protocol, ip->check);
1265 printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->saddr));
1266 printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->daddr));
1267 printf("\n");
1268 pr_options(rts, cp, hlen);
1269 }
1270
1271 /*
1272 * pr_icmph --
1273 * Print a descriptive string about an ICMP header.
1274 */
1275 static void pr_icmph(struct ping_rts *rts, uint8_t type, uint8_t code,
1276 uint32_t info, struct icmphdr *icp)
1277 {
1278 switch (type) {
1279 case ICMP_ECHOREPLY:
1280 printf(_("Echo Reply\n"));
1281 /* XXX ID + Seq + Data */
1282 break;
1283 case ICMP_DEST_UNREACH:
1284 switch (code) {
1285 case ICMP_NET_UNREACH:
1286 printf(_("Destination Net Unreachable\n"));
1287 break;
1288 case ICMP_HOST_UNREACH:
1289 printf(_("Destination Host Unreachable\n"));
1290 break;
1291 case ICMP_PROT_UNREACH:
1292 printf(_("Destination Protocol Unreachable\n"));
1293 break;
1294 case ICMP_PORT_UNREACH:
1295 printf(_("Destination Port Unreachable\n"));
1296 break;
1297 case ICMP_FRAG_NEEDED:
1298 printf(_("Frag needed and DF set (mtu = %u)\n"), info);
1299 break;
1300 case ICMP_SR_FAILED:
1301 printf(_("Source Route Failed\n"));
1302 break;
1303 case ICMP_NET_UNKNOWN:
1304 printf(_("Destination Net Unknown\n"));
1305 break;
1306 case ICMP_HOST_UNKNOWN:
1307 printf(_("Destination Host Unknown\n"));
1308 break;
1309 case ICMP_HOST_ISOLATED:
1310 printf(_("Source Host Isolated\n"));
1311 break;
1312 case ICMP_NET_ANO:
1313 printf(_("Destination Net Prohibited\n"));
1314 break;
1315 case ICMP_HOST_ANO:
1316 printf(_("Destination Host Prohibited\n"));
1317 break;
1318 case ICMP_NET_UNR_TOS:
1319 printf(_("Destination Net Unreachable for Type of Service\n"));
1320 break;
1321 case ICMP_HOST_UNR_TOS:
1322 printf(_("Destination Host Unreachable for Type of Service\n"));
1323 break;
1324 case ICMP_PKT_FILTERED:
1325 printf(_("Packet filtered\n"));
1326 break;
1327 case ICMP_PREC_VIOLATION:
1328 printf(_("Precedence Violation\n"));
1329 break;
1330 case ICMP_PREC_CUTOFF:
1331 printf(_("Precedence Cutoff\n"));
1332 break;
1333 default:
1334 printf(_("Dest Unreachable, Bad Code: %d\n"), code);
1335 break;
1336 }
1337 if (icp && rts->opt_verbose)
1338 pr_iph(rts, (struct iphdr *)(icp + 1));
1339 break;
1340 case ICMP_SOURCE_QUENCH:
1341 printf(_("Source Quench\n"));
1342 if (icp && rts->opt_verbose)
1343 pr_iph(rts, (struct iphdr *)(icp + 1));
1344 break;
1345 case ICMP_REDIRECT:
1346 switch (code) {
1347 case ICMP_REDIR_NET:
1348 printf(_("Redirect Network"));
1349 break;
1350 case ICMP_REDIR_HOST:
1351 printf(_("Redirect Host"));
1352 break;
1353 case ICMP_REDIR_NETTOS:
1354 printf(_("Redirect Type of Service and Network"));
1355 break;
1356 case ICMP_REDIR_HOSTTOS:
1357 printf(_("Redirect Type of Service and Host"));
1358 break;
1359 default:
1360 printf(_("Redirect, Bad Code: %d"), code);
1361 break;
1362 }
1363 {
1364 struct sockaddr_in sin = {
1365 .sin_family = AF_INET,
1366 .sin_addr = {
1367 icp ? icp->un.gateway : htonl(info)
1368 }
1369 };
1370
1371 printf(_("(New nexthop: %s)\n"), pr_addr(rts, &sin, sizeof sin));
1372 }
1373 if (icp && rts->opt_verbose)
1374 pr_iph(rts, (struct iphdr *)(icp + 1));
1375 break;
1376 case ICMP_ECHO:
1377 printf(_("Echo Request\n"));
1378 /* XXX ID + Seq + Data */
1379 break;
1380 case ICMP_TIME_EXCEEDED:
1381 switch(code) {
1382 case ICMP_EXC_TTL:
1383 printf(_("Time to live exceeded\n"));
1384 break;
1385 case ICMP_EXC_FRAGTIME:
1386 printf(_("Frag reassembly time exceeded\n"));
1387 break;
1388 default:
1389 printf(_("Time exceeded, Bad Code: %d\n"), code);
1390 break;
1391 }
1392 if (icp && rts->opt_verbose)
1393 pr_iph(rts, (struct iphdr *)(icp + 1));
1394 break;
1395 case ICMP_PARAMETERPROB:
1396 printf(_("Parameter problem: pointer = %u\n"),
1397 icp ? (ntohl(icp->un.gateway) >> 24) : info);
1398 if (icp && rts->opt_verbose)
1399 pr_iph(rts, (struct iphdr *)(icp + 1));
1400 break;
1401 case ICMP_TIMESTAMP:
1402 printf(_("Timestamp\n"));
1403 /* XXX ID + Seq + 3 timestamps */
1404 break;
1405 case ICMP_TIMESTAMPREPLY:
1406 printf(_("Timestamp Reply\n"));
1407 /* XXX ID + Seq + 3 timestamps */
1408 break;
1409 case ICMP_INFO_REQUEST:
1410 printf(_("Information Request\n"));
1411 /* XXX ID + Seq */
1412 break;
1413 case ICMP_INFO_REPLY:
1414 printf(_("Information Reply\n"));
1415 /* XXX ID + Seq */
1416 break;
1417 #ifdef ICMP_MASKREQ
1418 case ICMP_MASKREQ:
1419 printf(_("Address Mask Request\n"));
1420 break;
1421 #endif
1422 #ifdef ICMP_MASKREPLY
1423 case ICMP_MASKREPLY:
1424 printf(_("Address Mask Reply\n"));
1425 break;
1426 #endif
1427 default:
1428 printf(_("Bad ICMP type: %d\n"), type);
1429 }
1430 }
1431
1432 int ping4_receive_error_msg(struct ping_rts *rts, socket_st *sock)
1433 {
1434 ssize_t res;
1435 char cbuf[512];
1436 struct iovec iov;
1437 struct msghdr msg;
1438 struct cmsghdr *cmsgh;
1439 struct sock_extended_err *e;
1440 struct icmphdr icmph;
1441 struct sockaddr_in target;
1442 int net_errors = 0;
1443 int local_errors = 0;
1444 int saved_errno = errno;
1445
1446 iov.iov_base = &icmph;
1447 iov.iov_len = sizeof(icmph);
1448 msg.msg_name = (void *)&target;
1449 msg.msg_namelen = sizeof(target);
1450 msg.msg_iov = &iov;
1451 msg.msg_iovlen = 1;
1452 msg.msg_flags = 0;
1453 msg.msg_control = cbuf;
1454 msg.msg_controllen = sizeof(cbuf);
1455
1456 res = recvmsg(sock->fd, &msg, MSG_ERRQUEUE | MSG_DONTWAIT);
1457 if (res < 0) {
1458 if (errno == EAGAIN || errno == EINTR)
1459 local_errors++;
1460 goto out;
1461 }
1462
1463 e = NULL;
1464 for (cmsgh = CMSG_FIRSTHDR(&msg); cmsgh; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
1465 if (cmsgh->cmsg_level == SOL_IP) {
1466 if (cmsgh->cmsg_type == IP_RECVERR)
1467 e = (struct sock_extended_err *)CMSG_DATA(cmsgh);
1468 }
1469 }
1470 if (e == NULL)
1471 abort();
1472
1473 if (e->ee_origin == SO_EE_ORIGIN_LOCAL) {
1474 local_errors++;
1475 if (rts->opt_quiet)
1476 goto out;
1477 if (rts->opt_flood)
1478 write_stdout("E", 1);
1479 else if (e->ee_errno != EMSGSIZE)
1480 error(0, e->ee_errno, _("local error"));
1481 else
1482 error(0, 0, _("local error: message too long, mtu=%u"), e->ee_info);
1483 rts->nerrors++;
1484 } else if (e->ee_origin == SO_EE_ORIGIN_ICMP) {
1485 struct sockaddr_in *sin = (struct sockaddr_in *)(e + 1);
1486
1487 if (res < (ssize_t) sizeof(icmph) ||
1488 target.sin_addr.s_addr != rts->whereto.sin_addr.s_addr ||
1489 icmph.type != ICMP_ECHO ||
1490 !is_ours(rts, sock, icmph.un.echo.id)) {
1491 /* Not our error, not an error at all. Clear. */
1492 saved_errno = 0;
1493 goto out;
1494 }
1495
1496 acknowledge(rts, ntohs(icmph.un.echo.sequence));
1497
1498 if (sock->socktype == SOCK_RAW) {
1499 struct icmp_filter filt;
1500
1501 filt.data = ~((1 << ICMP_SOURCE_QUENCH) |
1502 (1 << ICMP_REDIRECT) |
1503 (1 << ICMP_ECHOREPLY));
1504 if (setsockopt(sock->fd, SOL_RAW, ICMP_FILTER, (const void *)&filt,
1505 sizeof(filt)) == -1)
1506 error(2, errno, "setsockopt(ICMP_FILTER)");
1507 }
1508 net_errors++;
1509 rts->nerrors++;
1510 if (rts->opt_quiet)
1511 goto out;
1512 if (rts->opt_flood) {
1513 write_stdout("\bE", 2);
1514 } else {
1515 print_timestamp(rts);
1516 printf(_("From %s icmp_seq=%u "), pr_addr(rts, sin, sizeof *sin), ntohs(icmph.un.echo.sequence));
1517 pr_icmph(rts, e->ee_type, e->ee_code, e->ee_info, NULL);
1518 fflush(stdout);
1519 }
1520 }
1521
1522 out:
1523 errno = saved_errno;
1524 return net_errors ? net_errors : -local_errors;
1525 }
1526
1527 #if BYTE_ORDER == LITTLE_ENDIAN
1528 # define ODDBYTE(v) (v)
1529 #elif BYTE_ORDER == BIG_ENDIAN
1530 # define ODDBYTE(v) ((unsigned short)(v) << 8)
1531 #else
1532 # define ODDBYTE(v) htons((unsigned short)(v) << 8)
1533 #endif
1534
1535 static unsigned short
1536 in_cksum(const unsigned short *addr, int len, unsigned short csum)
1537 {
1538 int nleft = len;
1539 const unsigned short *w = addr;
1540 unsigned short answer;
1541 int sum = csum;
1542
1543 /*
1544 * Our algorithm is simple, using a 32 bit accumulator (sum),
1545 * we add sequential 16 bit words to it, and at the end, fold
1546 * back all the carry bits from the top 16 bits into the lower
1547 * 16 bits.
1548 */
1549 while (nleft > 1) {
1550 sum += *w++;
1551 nleft -= 2;
1552 }
1553
1554 /* mop up an odd byte, if necessary */
1555 if (nleft == 1)
1556 sum += ODDBYTE(*(unsigned char *)w); /* le16toh() may be unavailable on old systems */
1557
1558 /*
1559 * add back carry outs from top 16 bits to low 16 bits
1560 */
1561 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1562 sum += (sum >> 16); /* add carry */
1563 answer = ~sum; /* truncate to 16 bits */
1564 return (answer);
1565 }
1566
1567 /*
1568 * pinger --
1569 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
1570 * will be added on by the kernel. The ID field is our UNIX process ID,
1571 * and the sequence number is an ascending integer. The first several bytes
1572 * of the data portion are used to hold a UNIX "timeval" struct in VAX
1573 * byte-order, to compute the round-trip time.
1574 */
1575 int ping4_send_probe(struct ping_rts *rts, socket_st *sock, void *packet,
1576 unsigned packet_size __attribute__((__unused__)))
1577 {
1578 struct icmphdr *icp;
1579 int cc;
1580 int i;
1581
1582 icp = (struct icmphdr *)packet;
1583 icp->type = ICMP_ECHO;
1584 icp->code = 0;
1585 icp->checksum = 0;
1586 icp->un.echo.sequence = htons(rts->ntransmitted + 1);
1587 icp->un.echo.id = rts->ident; /* ID */
1588
1589 rcvd_clear(rts, rts->ntransmitted + 1);
1590
1591 if (rts->timing) {
1592 if (rts->opt_latency) {
1593 struct timeval tmp_tv;
1594 gettimeofday(&tmp_tv, NULL);
1595 memcpy(icp + 1, &tmp_tv, sizeof(tmp_tv));
1596 } else {
1597 memset(icp + 1, 0, sizeof(struct timeval));
1598 }
1599 }
1600
1601 cc = rts->datalen + 8; /* skips ICMP portion */
1602
1603 /* compute ICMP checksum here */
1604 icp->checksum = in_cksum((unsigned short *)icp, cc, 0);
1605
1606 if (rts->timing && !rts->opt_latency) {
1607 struct timeval tmp_tv;
1608 gettimeofday(&tmp_tv, NULL);
1609 memcpy(icp + 1, &tmp_tv, sizeof(tmp_tv));
1610 icp->checksum = in_cksum((unsigned short *)&tmp_tv, sizeof(tmp_tv), ~icp->checksum);
1611 }
1612
1613 i = sendto(sock->fd, icp, cc, 0, (struct sockaddr *)&rts->whereto, sizeof(rts->whereto));
1614
1615 return (cc == i ? 0 : i);
1616 }
1617
1618 /*
1619 * parse_reply --
1620 * Print out the packet, if it came from us. This logic is necessary
1621 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
1622 * which arrive ('tis only fair). This permits multiple copies of this
1623 * program to be run without having intermingled output (or statistics!).
1624 */
1625 static
1626 void pr_echo_reply(uint8_t *_icp, int len __attribute__((__unused__)))
1627 {
1628 struct icmphdr *icp = (struct icmphdr *)_icp;
1629
1630 printf(_(" icmp_seq=%u"), ntohs(icp->un.echo.sequence));
1631 }
1632
1633 int ping4_parse_reply(struct ping_rts *rts, struct socket_st *sock,
1634 struct msghdr *msg, int cc, void *addr,
1635 struct timeval *tv)
1636 {
1637 struct sockaddr_in *from = addr;
1638 uint8_t *buf = msg->msg_iov->iov_base;
1639 struct icmphdr *icp;
1640 struct iphdr *ip;
1641 int hlen;
1642 int csfailed;
1643 struct cmsghdr *cmsgh;
1644 int reply_ttl;
1645 uint8_t *opts;
1646 int olen;
1647 int wrong_source = 0;
1648
1649 /* Check the IP header */
1650 ip = (struct iphdr *)buf;
1651 if (sock->socktype == SOCK_RAW) {
1652 hlen = ip->ihl * 4;
1653 if (cc < hlen + 8 || ip->ihl < 5) {
1654 if (rts->opt_verbose)
1655 error(0, 0, _("packet too short (%d bytes) from %s"), cc,
1656 pr_addr(rts,from, sizeof *from));
1657 return 1;
1658 }
1659 reply_ttl = ip->ttl;
1660 opts = buf + sizeof(struct iphdr);
1661 olen = hlen - sizeof(struct iphdr);
1662 } else {
1663 hlen = 0;
1664 reply_ttl = 0;
1665 opts = buf;
1666 olen = 0;
1667 for (cmsgh = CMSG_FIRSTHDR(msg); cmsgh; cmsgh = CMSG_NXTHDR(msg, cmsgh)) {
1668 if (cmsgh->cmsg_level != SOL_IP)
1669 continue;
1670 if (cmsgh->cmsg_type == IP_TTL) {
1671 if (cmsgh->cmsg_len < sizeof(int))
1672 continue;
1673 memcpy(&reply_ttl, CMSG_DATA(cmsgh), sizeof(reply_ttl));
1674 } else if (cmsgh->cmsg_type == IP_RETOPTS) {
1675 opts = (uint8_t *)CMSG_DATA(cmsgh);
1676 olen = cmsgh->cmsg_len;
1677 }
1678 }
1679 }
1680
1681 /* Now the ICMP part */
1682 cc -= hlen;
1683 icp = (struct icmphdr *)(buf + hlen);
1684 csfailed = in_cksum((unsigned short *)icp, cc, 0);
1685
1686 if (icp->type == ICMP_ECHOREPLY) {
1687 if (!is_ours(rts, sock, icp->un.echo.id))
1688 return 1; /* 'Twas not our ECHO */
1689
1690 if (!rts->broadcast_pings && !rts->multicast &&
1691 from->sin_addr.s_addr != rts->whereto.sin_addr.s_addr)
1692 wrong_source = 1;
1693 if (gather_statistics(rts, (uint8_t *)icp, sizeof(*icp), cc,
1694 ntohs(icp->un.echo.sequence),
1695 reply_ttl, csfailed, tv, pr_addr(rts, from, sizeof *from),
1696 pr_echo_reply, rts->multicast, wrong_source)) {
1697 fflush(stdout);
1698 return 0;
1699 }
1700 } else {
1701 /* We fall here when a redirect or source quench arrived. */
1702
1703 switch (icp->type) {
1704 case ICMP_ECHO:
1705 /* MUST NOT */
1706 return 1;
1707 case ICMP_SOURCE_QUENCH:
1708 case ICMP_REDIRECT:
1709 case ICMP_DEST_UNREACH:
1710 case ICMP_TIME_EXCEEDED:
1711 case ICMP_PARAMETERPROB:
1712 {
1713 struct iphdr *iph = (struct iphdr *)(&icp[1]);
1714 struct icmphdr *icp1 = (struct icmphdr *)
1715 ((unsigned char *)iph + iph->ihl * 4);
1716 int error_pkt;
1717 if (cc < (int)(8 + sizeof(struct iphdr) + 8) ||
1718 cc < 8 + iph->ihl * 4 + 8)
1719 return 1;
1720 if (icp1->type != ICMP_ECHO ||
1721 iph->daddr != rts->whereto.sin_addr.s_addr ||
1722 !is_ours(rts, sock, icp1->un.echo.id))
1723 return 1;
1724 error_pkt = (icp->type != ICMP_REDIRECT &&
1725 icp->type != ICMP_SOURCE_QUENCH);
1726 if (error_pkt) {
1727 acknowledge(rts, ntohs(icp1->un.echo.sequence));
1728 return 0;
1729 }
1730 if (rts->opt_quiet || rts->opt_flood)
1731 return 1;
1732 print_timestamp(rts);
1733 printf(_("From %s: icmp_seq=%u "), pr_addr(rts, from, sizeof *from),
1734 ntohs(icp1->un.echo.sequence));
1735 if (csfailed)
1736 printf(_("(BAD CHECKSUM)"));
1737 pr_icmph(rts, icp->type, icp->code, ntohl(icp->un.gateway), icp);
1738 return 1;
1739 }
1740 default:
1741 /* MUST NOT */
1742 break;
1743 }
1744 if (rts->opt_flood && !(rts->opt_verbose || rts->opt_quiet)) {
1745 if (!csfailed)
1746 write_stdout("!E", 2);
1747 else
1748 write_stdout("!EC", 3);
1749 return 0;
1750 }
1751 if (!rts->opt_verbose || rts->uid)
1752 return 0;
1753 if (rts->opt_ptimeofday) {
1754 struct timeval recv_time;
1755 gettimeofday(&recv_time, NULL);
1756 printf("%lu.%06lu ", (unsigned long)recv_time.tv_sec, (unsigned long)recv_time.tv_usec);
1757 }
1758 printf(_("From %s: "), pr_addr(rts, from, sizeof *from));
1759 if (csfailed) {
1760 printf(_("(BAD CHECKSUM)\n"));
1761 return 0;
1762 }
1763 pr_icmph(rts, icp->type, icp->code, ntohl(icp->un.gateway), icp);
1764 return 0;
1765 }
1766
1767 if (rts->opt_audible) {
1768 putchar('\a');
1769 if (rts->opt_flood)
1770 fflush(stdout);
1771 }
1772 if (!rts->opt_flood) {
1773 pr_options(rts, opts, olen + sizeof(struct iphdr));
1774
1775 putchar('\n');
1776 fflush(stdout);
1777 }
1778 return 0;
1779 }
1780
1781 /*
1782 * pr_addr --
1783 *
1784 * Return an ascii host address with reverse name resolution.
1785 */
1786 char *pr_addr(struct ping_rts *rts, void *sa, socklen_t salen)
1787 {
1788 return _pr_addr(rts, sa, salen, 1);
1789 }
1790
1791 /*
1792 * pr_raw_addr --
1793 *
1794 * Return an ascii host address. Reverse name resolution is not performed.
1795 */
1796
1797 char *pr_raw_addr(struct ping_rts *rts, void *sa, socklen_t salen)
1798 {
1799 return _pr_addr(rts, sa, salen, 0);
1800 }
1801
1802 /*
1803 * _pr_addr --
1804 *
1805 * Return an ascii host address optionally with a hostname.
1806 */
1807 char *_pr_addr(struct ping_rts *rts, void *sa, socklen_t salen, int resolve_name)
1808 {
1809 static char buffer[4096] = "";
1810 static struct sockaddr_storage last_sa = {0};
1811 static socklen_t last_salen = 0;
1812 char name[NI_MAXHOST] = "";
1813 char address[NI_MAXHOST] = "";
1814
1815 if (salen == last_salen && !memcmp(sa, &last_sa, salen))
1816 return buffer;
1817
1818 memcpy(&last_sa, sa, (last_salen = salen));
1819
1820 rts->in_pr_addr = !setjmp(rts->pr_addr_jmp);
1821
1822 getnameinfo(sa, salen, address, sizeof address, NULL, 0, getnameinfo_flags | NI_NUMERICHOST);
1823 if (!rts->exiting && resolve_name && (rts->opt_force_lookup || !rts->opt_numeric))
1824 getnameinfo(sa, salen, name, sizeof name, NULL, 0, getnameinfo_flags);
1825
1826 if (*name && strncmp(name, address, NI_MAXHOST))
1827 snprintf(buffer, sizeof buffer, "%s (%s)", name, address);
1828 else
1829 snprintf(buffer, sizeof buffer, "%s", address);
1830
1831 rts->in_pr_addr = 0;
1832
1833 return (buffer);
1834 }
1835
1836
1837 void ping4_install_filter(struct ping_rts *rts, socket_st *sock)
1838 {
1839 static int once;
1840 static struct sock_filter insns[] = {
1841 BPF_STMT(BPF_LDX | BPF_B | BPF_MSH, 0), /* Skip IP header due BSD, see ping6. */
1842 BPF_STMT(BPF_LD | BPF_H | BPF_IND, 4), /* Load icmp echo ident */
1843 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA, 0, 1), /* Ours? */
1844 BPF_STMT(BPF_RET | BPF_K, ~0U), /* Yes, it passes. */
1845 BPF_STMT(BPF_LD | BPF_B | BPF_IND, 0), /* Load icmp type */
1846 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ICMP_ECHOREPLY, 1, 0), /* Echo? */
1847 BPF_STMT(BPF_RET | BPF_K, 0xFFFFFFF), /* No. It passes. */
1848 BPF_STMT(BPF_RET | BPF_K, 0) /* Echo with wrong ident. Reject. */
1849 };
1850 static struct sock_fprog filter = {
1851 sizeof insns / sizeof(insns[0]),
1852 insns
1853 };
1854
1855 if (once)
1856 return;
1857 once = 1;
1858
1859 /* Patch bpflet for current identifier. */
1860 insns[2] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(rts->ident), 0, 1);
1861
1862 if (setsockopt(sock->fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)))
1863 error(0, errno, _("WARNING: failed to install socket filter"));
1864 }