blob: 25bbc3c058bd0a04abbeb213b4df805bef690917 [file] [log] [blame]
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001/*
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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38char copyright[] =
39"@(#) Copyright (c) 1989 The Regents of the University of California.\n\
40 All rights reserved.\n";
41#endif /* not lint */
42
43/*
44 * P I N G . C
45 *
46 * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
47 * measure round-trip-delays and packet loss across network paths.
48 *
49 * Author -
50 * Mike Muuss
51 * U. S. Army Ballistic Research Laboratory
52 * December, 1983
53 *
54 * Status -
55 * Public Domain. Distribution Unlimited.
56 * Bugs -
57 * More statistics could always be gathered.
58 * This program has to run SUID to ROOT to access the ICMP socket.
59 */
60
61#include "ping_common.h"
62
63#include <netinet/ip.h>
64#include <netinet/ip_icmp.h>
65#ifndef WITHOUT_IFADDRS
66#include <ifaddrs.h>
67#endif
68
69#ifndef ICMP_FILTER
70#define ICMP_FILTER 1
71struct icmp_filter {
72 __u32 data;
73};
74#endif
75
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +090076#ifdef ANDROID
77#include <sys/auxv.h>
78#define bcmp(a, b, c) memcmp(a, b, c)
79#endif
Lorenzo Colitti313379e2013-07-11 01:07:11 +090080
81#define MAXIPLEN 60
82#define MAXICMPLEN 76
83#define NROUTES 9 /* number of record route slots */
84#define TOS_MAX 255 /* 8-bit TOS field */
85#define MAX_HOSTNAMELEN NI_MAXHOST
86
87
88static int ts_type;
89static int nroute = 0;
90static __u32 route[10];
91
92
93
94struct sockaddr_in whereto; /* who to ping */
95int optlen = 0;
96int settos = 0; /* Set TOS, Precendence or other QOS options */
97int icmp_sock; /* socket file descriptor */
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +090098int using_ping_socket = 0;
Lorenzo Colitti313379e2013-07-11 01:07:11 +090099u_char outpack[0x10000];
100int maxpacket = sizeof(outpack);
101
102static int broadcast_pings = 0;
103
104static char *pr_addr(__u32);
105static void pr_options(unsigned char * cp, int hlen);
106static void pr_iph(struct iphdr *ip);
107static void usage(void) __attribute__((noreturn));
108static u_short in_cksum(const u_short *addr, int len, u_short salt);
109static void pr_icmph(__u8 type, __u8 code, __u32 info, struct icmphdr *icp);
110static int parsetos(char *str);
111
112static struct {
113 struct cmsghdr cm;
114 struct in_pktinfo ipi;
115} cmsg = { {sizeof(struct cmsghdr) + sizeof(struct in_pktinfo), SOL_IP, IP_PKTINFO},
116 {0, }};
117int cmsg_len;
118
119struct sockaddr_in source;
120char *device;
121int pmtudisc = -1;
122
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900123int
124main(int argc, char **argv)
125{
126 struct hostent *hp;
127 int ch, hold, packlen;
128 int socket_errno;
129 u_char *packet;
130 char *target;
131#ifdef USE_IDN
132 char *hnamebuf = NULL;
133#else
134 char hnamebuf[MAX_HOSTNAMELEN];
135#endif
136 char rspace[3 + 4 * NROUTES + 1]; /* record route space */
137
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900138#ifdef ANDROID
139 if (getauxval(AT_SECURE) != 0) {
140 fprintf(stderr, "This version of ping should NOT run with privileges. Aborting\n");
141 exit(1);
142 }
143#endif
144
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900145 limit_capabilities();
146
147#ifdef USE_IDN
148 setlocale(LC_ALL, "");
149#endif
150
151 enable_capability_raw();
152
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900153 icmp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
154 if (icmp_sock != -1)
155 using_ping_socket = 1;
156 else
157 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900158 socket_errno = errno;
159
160 disable_capability_raw();
161
162 source.sin_family = AF_INET;
163
164 preload = 1;
165 while ((ch = getopt(argc, argv, COMMON_OPTSTR "bRT:")) != EOF) {
166 switch(ch) {
167 case 'b':
168 broadcast_pings = 1;
169 break;
170 case 'Q':
171 settos = parsetos(optarg);
172 if (settos &&
173 (setsockopt(icmp_sock, IPPROTO_IP, IP_TOS,
174 (char *)&settos, sizeof(int)) < 0)) {
175 perror("ping: error setting QOS sockopts");
176 exit(2);
177 }
178 break;
179 case 'R':
180 if (options & F_TIMESTAMP) {
181 fprintf(stderr, "Only one of -T or -R may be used\n");
182 exit(2);
183 }
184 options |= F_RROUTE;
185 break;
186 case 'T':
187 if (options & F_RROUTE) {
188 fprintf(stderr, "Only one of -T or -R may be used\n");
189 exit(2);
190 }
191 options |= F_TIMESTAMP;
192 if (strcmp(optarg, "tsonly") == 0)
193 ts_type = IPOPT_TS_TSONLY;
194 else if (strcmp(optarg, "tsandaddr") == 0)
195 ts_type = IPOPT_TS_TSANDADDR;
196 else if (strcmp(optarg, "tsprespec") == 0)
197 ts_type = IPOPT_TS_PRESPEC;
198 else {
199 fprintf(stderr, "Invalid timestamp type\n");
200 exit(2);
201 }
202 break;
203 case 'I':
204 {
205#if 0
206 char dummy;
207 int i1, i2, i3, i4;
208
209 if (sscanf(optarg, "%u.%u.%u.%u%c",
210 &i1, &i2, &i3, &i4, &dummy) == 4) {
211 __u8 *ptr;
212 ptr = (__u8*)&source.sin_addr;
213 ptr[0] = i1;
214 ptr[1] = i2;
215 ptr[2] = i3;
216 ptr[3] = i4;
217 options |= F_STRICTSOURCE;
218 } else {
219 device = optarg;
220 }
221#else
222 if (inet_pton(AF_INET, optarg, &source.sin_addr) > 0)
223 options |= F_STRICTSOURCE;
224 else
225 device = optarg;
226#endif
227 break;
228 }
229 case 'M':
230 if (strcmp(optarg, "do") == 0)
231 pmtudisc = IP_PMTUDISC_DO;
232 else if (strcmp(optarg, "dont") == 0)
233 pmtudisc = IP_PMTUDISC_DONT;
234 else if (strcmp(optarg, "want") == 0)
235 pmtudisc = IP_PMTUDISC_WANT;
236 else {
237 fprintf(stderr, "ping: wrong value for -M: do, dont, want are valid ones.\n");
238 exit(2);
239 }
240 break;
241 case 'V':
242 printf("ping utility, iputils-%s\n", SNAPSHOT);
243 exit(0);
244 COMMON_OPTIONS
245 common_options(ch);
246 break;
247 default:
248 usage();
249 }
250 }
251 argc -= optind;
252 argv += optind;
253
254 if (argc == 0)
255 usage();
256 if (argc > 1) {
257 if (options & F_RROUTE)
258 usage();
259 else if (options & F_TIMESTAMP) {
260 if (ts_type != IPOPT_TS_PRESPEC)
261 usage();
262 if (argc > 5)
263 usage();
264 } else {
265 if (argc > 10)
266 usage();
267 options |= F_SOURCEROUTE;
268 }
269 }
270 while (argc > 0) {
271 target = *argv;
272
273 memset((char *)&whereto, 0, sizeof(whereto));
274 whereto.sin_family = AF_INET;
275 if (inet_aton(target, &whereto.sin_addr) == 1) {
276 hostname = target;
277 if (argc == 1)
278 options |= F_NUMERIC;
279 } else {
280 char *idn;
281#ifdef USE_IDN
282 int rc;
283
284 if (hnamebuf) {
285 free(hnamebuf);
286 hnamebuf = NULL;
287 }
288
289 rc = idna_to_ascii_lz(target, &idn, 0);
290 if (rc != IDNA_SUCCESS) {
291 fprintf(stderr, "ping: IDN encoding failed: %s\n", idna_strerror(rc));
292 exit(2);
293 }
294#else
295 idn = target;
296#endif
297 hp = gethostbyname(idn);
298 if (!hp) {
299 fprintf(stderr, "ping: unknown host %s\n", target);
300 exit(2);
301 }
302#ifdef USE_IDN
303 free(idn);
304#endif
305 memcpy(&whereto.sin_addr, hp->h_addr, 4);
306#ifdef USE_IDN
307 if (idna_to_unicode_lzlz(hp->h_name, &hnamebuf, 0) != IDNA_SUCCESS) {
308 hnamebuf = strdup(hp->h_name);
309 if (!hnamebuf) {
310 perror("ping: strdup");
311 exit(-1);
312 }
313 }
314#else
315 strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
316 hnamebuf[sizeof(hnamebuf) - 1] = 0;
317#endif
318 hostname = hnamebuf;
319 }
320 if (argc > 1)
321 route[nroute++] = whereto.sin_addr.s_addr;
322 argc--;
323 argv++;
324 }
325
326 if (source.sin_addr.s_addr == 0) {
327 socklen_t alen;
328 struct sockaddr_in dst = whereto;
329 int probe_fd = socket(AF_INET, SOCK_DGRAM, 0);
330
331 if (probe_fd < 0) {
332 perror("socket");
333 exit(2);
334 }
335 if (device) {
336 struct ifreq ifr;
337 int rc;
338
339 memset(&ifr, 0, sizeof(ifr));
340 strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
341
342 enable_capability_raw();
343 rc = setsockopt(probe_fd, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)+1);
344 disable_capability_raw();
345
346 if (rc == -1) {
347 if (IN_MULTICAST(ntohl(dst.sin_addr.s_addr))) {
348 struct ip_mreqn imr;
349 if (ioctl(probe_fd, SIOCGIFINDEX, &ifr) < 0) {
350 fprintf(stderr, "ping: unknown iface %s\n", device);
351 exit(2);
352 }
353 memset(&imr, 0, sizeof(imr));
354 imr.imr_ifindex = ifr.ifr_ifindex;
355 if (setsockopt(probe_fd, SOL_IP, IP_MULTICAST_IF, &imr, sizeof(imr)) == -1) {
356 perror("ping: IP_MULTICAST_IF");
357 exit(2);
358 }
359 } else {
360 perror("ping: SO_BINDTODEVICE");
361 exit(2);
362 }
363 }
364 }
365
366 if (settos &&
367 setsockopt(probe_fd, IPPROTO_IP, IP_TOS, (char *)&settos, sizeof(int)) < 0)
368 perror("Warning: error setting QOS sockopts");
369
370 dst.sin_port = htons(1025);
371 if (nroute)
372 dst.sin_addr.s_addr = route[0];
373 if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
374 if (errno == EACCES) {
375 if (broadcast_pings == 0) {
376 fprintf(stderr, "Do you want to ping broadcast? Then -b\n");
377 exit(2);
378 }
379 fprintf(stderr, "WARNING: pinging broadcast address\n");
380 if (setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
381 &broadcast_pings, sizeof(broadcast_pings)) < 0) {
382 perror ("can't set broadcasting");
383 exit(2);
384 }
385 if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
386 perror("connect");
387 exit(2);
388 }
389 } else {
390 perror("connect");
391 exit(2);
392 }
393 }
394 alen = sizeof(source);
395 if (getsockname(probe_fd, (struct sockaddr*)&source, &alen) == -1) {
396 perror("getsockname");
397 exit(2);
398 }
399 source.sin_port = 0;
400
401#ifndef WITHOUT_IFADDRS
402 if (device) {
403 struct ifaddrs *ifa0, *ifa;
404 int ret;
405
406 ret = getifaddrs(&ifa0);
407 if (ret) {
408 fprintf(stderr, "gatifaddrs() failed.\n");
409 exit(2);
410 }
411 for (ifa = ifa0; ifa; ifa = ifa->ifa_next) {
412 if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET)
413 continue;
414 if (!strncmp(ifa->ifa_name, device, sizeof(device) - 1) &&
415 !memcmp(&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
416 &source.sin_addr, sizeof(source.sin_addr)))
417 break;
418 }
419 freeifaddrs(ifa0);
420 if (!ifa)
421 fprintf(stderr, "ping: Warning: source address might be selected on device other than %s.\n", device);
422 }
423#endif
424 close(probe_fd);
425 } while (0);
426
427 if (whereto.sin_addr.s_addr == 0)
428 whereto.sin_addr.s_addr = source.sin_addr.s_addr;
429
430 if (icmp_sock < 0) {
431 errno = socket_errno;
432 perror("ping: icmp open socket");
433 exit(2);
434 }
435
436 if (device) {
437 struct ifreq ifr;
438
439 memset(&ifr, 0, sizeof(ifr));
440 strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
441 if (ioctl(icmp_sock, SIOCGIFINDEX, &ifr) < 0) {
442 fprintf(stderr, "ping: unknown iface %s\n", device);
443 exit(2);
444 }
445 cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
446 cmsg_len = sizeof(cmsg);
447 }
448
449 if (broadcast_pings || IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) {
450 if (uid) {
451 if (interval < 1000) {
452 fprintf(stderr, "ping: broadcast ping with too short interval.\n");
453 exit(2);
454 }
455 if (pmtudisc >= 0 && pmtudisc != IP_PMTUDISC_DO) {
456 fprintf(stderr, "ping: broadcast ping does not fragment.\n");
457 exit(2);
458 }
459 }
460 if (pmtudisc < 0)
461 pmtudisc = IP_PMTUDISC_DO;
462 }
463
464 if (pmtudisc >= 0) {
465 if (setsockopt(icmp_sock, SOL_IP, IP_MTU_DISCOVER, &pmtudisc, sizeof(pmtudisc)) == -1) {
466 perror("ping: IP_MTU_DISCOVER");
467 exit(2);
468 }
469 }
470
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900471 if (!using_ping_socket) {
472 if ((options&F_STRICTSOURCE) &&
473 bind(icmp_sock, (struct sockaddr*)&source, sizeof(source)) == -1) {
474 perror("bind");
475 exit(2);
476 }
477 } else {
478 struct sockaddr_in sa;
479 socklen_t sl;
480
481 sa.sin_family = AF_INET;
482 sa.sin_port = 0;
483 sa.sin_addr.s_addr = (options&F_STRICTSOURCE) ?
484 source.sin_addr.s_addr : 0;
485 sl = sizeof(sa);
486
487 if (bind(icmp_sock, (struct sockaddr *) &sa, sl) == -1) {
488 perror("bind");
489 exit(2);
490 }
491
492 if (getsockname(icmp_sock, (struct sockaddr *) &sa, &sl) == -1) {
493 perror("getsockname");
494 exit(2);
495 }
496 ident = sa.sin_port;
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900497 }
498
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900499 if (!using_ping_socket) {
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900500 struct icmp_filter filt;
501 filt.data = ~((1<<ICMP_SOURCE_QUENCH)|
502 (1<<ICMP_DEST_UNREACH)|
503 (1<<ICMP_TIME_EXCEEDED)|
504 (1<<ICMP_PARAMETERPROB)|
505 (1<<ICMP_REDIRECT)|
506 (1<<ICMP_ECHOREPLY));
507 if (setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, (char*)&filt, sizeof(filt)) == -1)
508 perror("WARNING: setsockopt(ICMP_FILTER)");
509 }
510
511 hold = 1;
512 if (setsockopt(icmp_sock, SOL_IP, IP_RECVERR, (char *)&hold, sizeof(hold)))
513 fprintf(stderr, "WARNING: your kernel is veeery old. No problems.\n");
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900514 if (using_ping_socket) {
515 if (setsockopt(icmp_sock, SOL_IP, IP_RECVTTL, (char *)&hold, sizeof(hold)))
516 perror("WARNING: setsockopt(IP_RECVTTL)");
517 if (setsockopt(icmp_sock, SOL_IP, IP_RETOPTS, (char *)&hold, sizeof(hold)))
518 perror("WARNING: setsockopt(IP_RETOPTS)");
519 }
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900520
521 /* record route option */
522 if (options & F_RROUTE) {
523 memset(rspace, 0, sizeof(rspace));
524 rspace[0] = IPOPT_NOP;
525 rspace[1+IPOPT_OPTVAL] = IPOPT_RR;
526 rspace[1+IPOPT_OLEN] = sizeof(rspace)-1;
527 rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
528 optlen = 40;
529 if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, sizeof(rspace)) < 0) {
530 perror("ping: record route");
531 exit(2);
532 }
533 }
534 if (options & F_TIMESTAMP) {
535 memset(rspace, 0, sizeof(rspace));
536 rspace[0] = IPOPT_TIMESTAMP;
537 rspace[1] = (ts_type==IPOPT_TS_TSONLY ? 40 : 36);
538 rspace[2] = 5;
539 rspace[3] = ts_type;
540 if (ts_type == IPOPT_TS_PRESPEC) {
541 int i;
542 rspace[1] = 4+nroute*8;
543 for (i=0; i<nroute; i++)
544 *(__u32*)&rspace[4+i*8] = route[i];
545 }
546 if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
547 rspace[3] = 2;
548 if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
549 perror("ping: ts option");
550 exit(2);
551 }
552 }
553 optlen = 40;
554 }
555 if (options & F_SOURCEROUTE) {
556 int i;
557 memset(rspace, 0, sizeof(rspace));
558 rspace[0] = IPOPT_NOOP;
559 rspace[1+IPOPT_OPTVAL] = (options & F_SO_DONTROUTE) ? IPOPT_SSRR
560 : IPOPT_LSRR;
561 rspace[1+IPOPT_OLEN] = 3 + nroute*4;
562 rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
563 for (i=0; i<nroute; i++)
564 *(__u32*)&rspace[4+i*4] = route[i];
565
566 if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, 4 + nroute*4) < 0) {
567 perror("ping: record route");
568 exit(2);
569 }
570 optlen = 40;
571 }
572
573 /* Estimate memory eaten by single packet. It is rough estimate.
574 * Actually, for small datalen's it depends on kernel side a lot. */
575 hold = datalen + 8;
576 hold += ((hold+511)/512)*(optlen + 20 + 16 + 64 + 160);
577 sock_setbufs(icmp_sock, hold);
578
579 if (broadcast_pings) {
580 if (setsockopt(icmp_sock, SOL_SOCKET, SO_BROADCAST,
581 &broadcast_pings, sizeof(broadcast_pings)) < 0) {
582 perror ("ping: can't set broadcasting");
583 exit(2);
584 }
585 }
586
587 if (options & F_NOLOOP) {
588 int loop = 0;
589 if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_LOOP,
590 &loop, 1) == -1) {
591 perror ("ping: can't disable multicast loopback");
592 exit(2);
593 }
594 }
595 if (options & F_TTL) {
596 int ittl = ttl;
597 if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_TTL,
598 &ttl, 1) == -1) {
599 perror ("ping: can't set multicast time-to-live");
600 exit(2);
601 }
602 if (setsockopt(icmp_sock, IPPROTO_IP, IP_TTL,
603 &ittl, sizeof(ittl)) == -1) {
604 perror ("ping: can't set unicast time-to-live");
605 exit(2);
606 }
607 }
608
609 if (datalen > 0xFFFF - 8 - optlen - 20) {
610 if (uid || datalen > sizeof(outpack)-8) {
611 fprintf(stderr, "Error: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
612 exit(2);
613 }
614 /* Allow small oversize to root yet. It will cause EMSGSIZE. */
615 fprintf(stderr, "WARNING: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
616 }
617
618 if (datalen >= sizeof(struct timeval)) /* can we time transfer */
619 timing = 1;
620 packlen = datalen + MAXIPLEN + MAXICMPLEN;
621 if (!(packet = (u_char *)malloc((u_int)packlen))) {
622 fprintf(stderr, "ping: out of memory.\n");
623 exit(2);
624 }
625
626 printf("PING %s (%s) ", hostname, inet_ntoa(whereto.sin_addr));
627 if (device || (options&F_STRICTSOURCE))
628 printf("from %s %s: ", inet_ntoa(source.sin_addr), device ?: "");
629 printf("%d(%d) bytes of data.\n", datalen, datalen+8+optlen+20);
630
631 setup(icmp_sock);
632
633 main_loop(icmp_sock, packet, packlen);
634}
635
636
637int receive_error_msg()
638{
639 int res;
640 char cbuf[512];
641 struct iovec iov;
642 struct msghdr msg;
643 struct cmsghdr *cmsg;
644 struct sock_extended_err *e;
645 struct icmphdr icmph;
646 struct sockaddr_in target;
647 int net_errors = 0;
648 int local_errors = 0;
649 int saved_errno = errno;
650
651 iov.iov_base = &icmph;
652 iov.iov_len = sizeof(icmph);
653 msg.msg_name = (void*)&target;
654 msg.msg_namelen = sizeof(target);
655 msg.msg_iov = &iov;
656 msg.msg_iovlen = 1;
657 msg.msg_flags = 0;
658 msg.msg_control = cbuf;
659 msg.msg_controllen = sizeof(cbuf);
660
661 res = recvmsg(icmp_sock, &msg, MSG_ERRQUEUE|MSG_DONTWAIT);
662 if (res < 0)
663 goto out;
664
665 e = NULL;
666 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
667 if (cmsg->cmsg_level == SOL_IP) {
668 if (cmsg->cmsg_type == IP_RECVERR)
669 e = (struct sock_extended_err *)CMSG_DATA(cmsg);
670 }
671 }
672 if (e == NULL)
673 abort();
674
675 if (e->ee_origin == SO_EE_ORIGIN_LOCAL) {
676 local_errors++;
677 if (options & F_QUIET)
678 goto out;
679 if (options & F_FLOOD)
680 write_stdout("E", 1);
681 else if (e->ee_errno != EMSGSIZE)
682 fprintf(stderr, "ping: local error: %s\n", strerror(e->ee_errno));
683 else
684 fprintf(stderr, "ping: local error: Message too long, mtu=%u\n", e->ee_info);
685 nerrors++;
686 } else if (e->ee_origin == SO_EE_ORIGIN_ICMP) {
687 struct sockaddr_in *sin = (struct sockaddr_in*)(e+1);
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900688 int error_pkt;
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900689
690 if (res < sizeof(icmph) ||
691 target.sin_addr.s_addr != whereto.sin_addr.s_addr ||
692 icmph.type != ICMP_ECHO ||
693 icmph.un.echo.id != ident) {
694 /* Not our error, not an error at all. Clear. */
695 saved_errno = 0;
696 goto out;
697 }
698
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900699 error_pkt = (e->ee_type != ICMP_REDIRECT &&
700 e->ee_type != ICMP_SOURCE_QUENCH);
701 if (error_pkt) {
702 acknowledge(ntohs(icmph.un.echo.sequence));
703 net_errors++;
704 nerrors++;
705 }
706 else {
707 saved_errno = 0;
708 }
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900709
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900710 if (!using_ping_socket && !working_recverr) {
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900711 struct icmp_filter filt;
712 working_recverr = 1;
713 /* OK, it works. Add stronger filter. */
714 filt.data = ~((1<<ICMP_SOURCE_QUENCH)|
715 (1<<ICMP_REDIRECT)|
716 (1<<ICMP_ECHOREPLY));
717 if (setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, (char*)&filt, sizeof(filt)) == -1)
718 perror("\rWARNING: setsockopt(ICMP_FILTER)");
719 }
720
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900721 if (options & F_QUIET)
722 goto out;
723 if (options & F_FLOOD) {
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900724 if (error_pkt)
725 write_stdout("\bE", 2);
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900726 } else {
727 print_timestamp();
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900728 printf("From %s: icmp_seq=%u ", pr_addr(sin->sin_addr.s_addr), ntohs(icmph.un.echo.sequence));
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900729 pr_icmph(e->ee_type, e->ee_code, e->ee_info, NULL);
730 fflush(stdout);
731 }
732 }
733
734out:
735 errno = saved_errno;
736 return net_errors ? : -local_errors;
737}
738
739/*
740 * pinger --
741 * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
742 * will be added on by the kernel. The ID field is our UNIX process ID,
743 * and the sequence number is an ascending integer. The first 8 bytes
744 * of the data portion are used to hold a UNIX "timeval" struct in VAX
745 * byte-order, to compute the round-trip time.
746 */
747int send_probe()
748{
749 struct icmphdr *icp;
750 int cc;
751 int i;
752
753 icp = (struct icmphdr *)outpack;
754 icp->type = ICMP_ECHO;
755 icp->code = 0;
756 icp->checksum = 0;
757 icp->un.echo.sequence = htons(ntransmitted+1);
758 icp->un.echo.id = ident; /* ID */
759
760 rcvd_clear(ntransmitted+1);
761
762 if (timing) {
763 if (options&F_LATENCY) {
764 struct timeval tmp_tv;
765 gettimeofday(&tmp_tv, NULL);
766 memcpy(icp+1, &tmp_tv, sizeof(tmp_tv));
767 } else {
768 memset(icp+1, 0, sizeof(struct timeval));
769 }
770 }
771
772 cc = datalen + 8; /* skips ICMP portion */
773
774 /* compute ICMP checksum here */
775 icp->checksum = in_cksum((u_short *)icp, cc, 0);
776
777 if (timing && !(options&F_LATENCY)) {
778 struct timeval tmp_tv;
779 gettimeofday(&tmp_tv, NULL);
780 memcpy(icp+1, &tmp_tv, sizeof(tmp_tv));
781 icp->checksum = in_cksum((u_short *)&tmp_tv, sizeof(tmp_tv), ~icp->checksum);
782 }
783
784 do {
785 static struct iovec iov = {outpack, 0};
786 static struct msghdr m = { &whereto, sizeof(whereto),
787 &iov, 1, &cmsg, 0, 0 };
788 m.msg_controllen = cmsg_len;
789 iov.iov_len = cc;
790
791 i = sendmsg(icmp_sock, &m, confirm);
792 confirm = 0;
793 } while (0);
794
795 return (cc == i ? 0 : i);
796}
797
798/*
799 * parse_reply --
800 * Print out the packet, if it came from us. This logic is necessary
801 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
802 * which arrive ('tis only fair). This permits multiple copies of this
803 * program to be run without having intermingled output (or statistics!).
804 */
805void pr_echo_reply(__u8 *_icp, int len)
806{
807 struct icmphdr *icp = (struct icmphdr *)_icp;
808 printf(" icmp_seq=%u", ntohs(icp->un.echo.sequence));
809}
810
811int
812parse_reply(struct msghdr *msg, int cc, void *addr, struct timeval *tv)
813{
814 struct sockaddr_in *from = addr;
815 __u8 *buf = msg->msg_iov->iov_base;
816 struct icmphdr *icp;
817 struct iphdr *ip;
818 int hlen;
819 int csfailed;
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900820 struct cmsghdr *cmsg;
821 int ttl;
822 __u8 *opts;
823 int optlen;
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900824
825 /* Check the IP header */
826 ip = (struct iphdr *)buf;
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900827 if (!using_ping_socket) {
828 hlen = ip->ihl*4;
829 if (cc < hlen + 8 || ip->ihl < 5) {
830 if (options & F_VERBOSE)
831 fprintf(stderr, "ping: packet too short (%d bytes) from %s\n", cc,
832 pr_addr(from->sin_addr.s_addr));
833 return 1;
834 }
835 ttl = ip->ttl;
836 opts = buf + sizeof(struct iphdr);
837 optlen = hlen - sizeof(struct iphdr);
838 } else {
839 hlen = 0;
840 ttl = 0;
841 opts = buf;
842 optlen = 0;
843 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
844 if (cmsg->cmsg_level != SOL_IP)
845 continue;
846 if (cmsg->cmsg_type == IP_TTL) {
847 if (cmsg->cmsg_len < sizeof(int))
848 continue;
849 ttl = *(int *) CMSG_DATA(cmsg);
850 } else if (cmsg->cmsg_type == IP_RETOPTS) {
851 opts = (__u8 *) CMSG_DATA(cmsg);
852 optlen = cmsg->cmsg_len;
853 }
854 }
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900855 }
856
857 /* Now the ICMP part */
858 cc -= hlen;
859 icp = (struct icmphdr *)(buf + hlen);
860 csfailed = in_cksum((u_short *)icp, cc, 0);
861
862 if (icp->type == ICMP_ECHOREPLY) {
863 if (icp->un.echo.id != ident)
864 return 1; /* 'Twas not our ECHO */
865 if (gather_statistics((__u8*)icp, sizeof(*icp), cc,
866 ntohs(icp->un.echo.sequence),
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900867 ttl, 0, tv, pr_addr(from->sin_addr.s_addr),
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900868 pr_echo_reply))
869 return 0;
870 } else {
871 /* We fall here when a redirect or source quench arrived.
872 * Also this branch processes icmp errors, when IP_RECVERR
873 * is broken. */
874
875 switch (icp->type) {
876 case ICMP_ECHO:
877 /* MUST NOT */
878 return 1;
879 case ICMP_SOURCE_QUENCH:
880 case ICMP_REDIRECT:
881 case ICMP_DEST_UNREACH:
882 case ICMP_TIME_EXCEEDED:
883 case ICMP_PARAMETERPROB:
884 {
885 struct iphdr * iph = (struct iphdr *)(&icp[1]);
886 struct icmphdr *icp1 = (struct icmphdr*)((unsigned char *)iph + iph->ihl*4);
887 int error_pkt;
888 if (cc < 8+sizeof(struct iphdr)+8 ||
889 cc < 8+iph->ihl*4+8)
890 return 1;
891 if (icp1->type != ICMP_ECHO ||
892 iph->daddr != whereto.sin_addr.s_addr ||
893 icp1->un.echo.id != ident)
894 return 1;
895 error_pkt = (icp->type != ICMP_REDIRECT &&
896 icp->type != ICMP_SOURCE_QUENCH);
897 if (error_pkt) {
898 acknowledge(ntohs(icp1->un.echo.sequence));
899 if (working_recverr) {
900 return 0;
901 } else {
902 static int once;
903 /* Sigh, IP_RECVERR for raw socket
904 * was broken until 2.4.9. So, we ignore
905 * the first error and warn on the second.
906 */
907 if (once++ == 1)
908 fprintf(stderr, "\rWARNING: kernel is not very fresh, upgrade is recommended.\n");
909 if (once == 1)
910 return 0;
911 }
912 }
913 nerrors+=error_pkt;
914 if (options&F_QUIET)
915 return !error_pkt;
916 if (options & F_FLOOD) {
917 if (error_pkt)
918 write_stdout("\bE", 2);
919 return !error_pkt;
920 }
921 print_timestamp();
922 printf("From %s: icmp_seq=%u ",
923 pr_addr(from->sin_addr.s_addr),
924 ntohs(icp1->un.echo.sequence));
925 if (csfailed)
926 printf("(BAD CHECKSUM)");
927 pr_icmph(icp->type, icp->code, ntohl(icp->un.gateway), icp);
928 return !error_pkt;
929 }
930 default:
931 /* MUST NOT */
932 break;
933 }
934 if ((options & F_FLOOD) && !(options & (F_VERBOSE|F_QUIET))) {
935 if (!csfailed)
936 write_stdout("!E", 2);
937 else
938 write_stdout("!EC", 3);
939 return 0;
940 }
941 if (!(options & F_VERBOSE) || uid)
942 return 0;
943 if (options & F_PTIMEOFDAY) {
944 struct timeval recv_time;
945 gettimeofday(&recv_time, NULL);
946 printf("%lu.%06lu ", (unsigned long)recv_time.tv_sec, (unsigned long)recv_time.tv_usec);
947 }
948 printf("From %s: ", pr_addr(from->sin_addr.s_addr));
949 if (csfailed) {
950 printf("(BAD CHECKSUM)\n");
951 return 0;
952 }
953 pr_icmph(icp->type, icp->code, ntohl(icp->un.gateway), icp);
954 return 0;
955 }
956
957 if (!(options & F_FLOOD)) {
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +0900958 pr_options(opts, optlen + sizeof(struct iphdr));
Lorenzo Colitti313379e2013-07-11 01:07:11 +0900959
960 if (options & F_AUDIBLE)
961 putchar('\a');
962 putchar('\n');
963 fflush(stdout);
964 } else {
965 putchar('\a');
966 fflush(stdout);
967 }
968 return 0;
969}
970
971
972#if BYTE_ORDER == LITTLE_ENDIAN
973# define ODDBYTE(v) (v)
974#elif BYTE_ORDER == BIG_ENDIAN
975# define ODDBYTE(v) ((u_short)(v) << 8)
976#else
977# define ODDBYTE(v) htons((u_short)(v) << 8)
978#endif
979
980u_short
981in_cksum(const u_short *addr, register int len, u_short csum)
982{
983 register int nleft = len;
984 const u_short *w = addr;
985 register u_short answer;
986 register int sum = csum;
987
988 /*
989 * Our algorithm is simple, using a 32 bit accumulator (sum),
990 * we add sequential 16 bit words to it, and at the end, fold
991 * back all the carry bits from the top 16 bits into the lower
992 * 16 bits.
993 */
994 while (nleft > 1) {
995 sum += *w++;
996 nleft -= 2;
997 }
998
999 /* mop up an odd byte, if necessary */
1000 if (nleft == 1)
1001 sum += ODDBYTE(*(u_char *)w); /* le16toh() may be unavailable on old systems */
1002
1003 /*
1004 * add back carry outs from top 16 bits to low 16 bits
1005 */
1006 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1007 sum += (sum >> 16); /* add carry */
1008 answer = ~sum; /* truncate to 16 bits */
1009 return (answer);
1010}
1011
1012/*
1013 * pr_icmph --
1014 * Print a descriptive string about an ICMP header.
1015 */
1016void pr_icmph(__u8 type, __u8 code, __u32 info, struct icmphdr *icp)
1017{
1018 switch(type) {
1019 case ICMP_ECHOREPLY:
1020 printf("Echo Reply\n");
1021 /* XXX ID + Seq + Data */
1022 break;
1023 case ICMP_DEST_UNREACH:
1024 switch(code) {
1025 case ICMP_NET_UNREACH:
1026 printf("Destination Net Unreachable\n");
1027 break;
1028 case ICMP_HOST_UNREACH:
1029 printf("Destination Host Unreachable\n");
1030 break;
1031 case ICMP_PROT_UNREACH:
1032 printf("Destination Protocol Unreachable\n");
1033 break;
1034 case ICMP_PORT_UNREACH:
1035 printf("Destination Port Unreachable\n");
1036 break;
1037 case ICMP_FRAG_NEEDED:
1038 printf("Frag needed and DF set (mtu = %u)\n", info);
1039 break;
1040 case ICMP_SR_FAILED:
1041 printf("Source Route Failed\n");
1042 break;
1043 case ICMP_NET_UNKNOWN:
1044 printf("Destination Net Unknown\n");
1045 break;
1046 case ICMP_HOST_UNKNOWN:
1047 printf("Destination Host Unknown\n");
1048 break;
1049 case ICMP_HOST_ISOLATED:
1050 printf("Source Host Isolated\n");
1051 break;
1052 case ICMP_NET_ANO:
1053 printf("Destination Net Prohibited\n");
1054 break;
1055 case ICMP_HOST_ANO:
1056 printf("Destination Host Prohibited\n");
1057 break;
1058 case ICMP_NET_UNR_TOS:
1059 printf("Destination Net Unreachable for Type of Service\n");
1060 break;
1061 case ICMP_HOST_UNR_TOS:
1062 printf("Destination Host Unreachable for Type of Service\n");
1063 break;
1064 case ICMP_PKT_FILTERED:
1065 printf("Packet filtered\n");
1066 break;
1067 case ICMP_PREC_VIOLATION:
1068 printf("Precedence Violation\n");
1069 break;
1070 case ICMP_PREC_CUTOFF:
1071 printf("Precedence Cutoff\n");
1072 break;
1073 default:
1074 printf("Dest Unreachable, Bad Code: %d\n", code);
1075 break;
1076 }
1077 if (icp && (options & F_VERBOSE))
1078 pr_iph((struct iphdr*)(icp + 1));
1079 break;
1080 case ICMP_SOURCE_QUENCH:
1081 printf("Source Quench\n");
1082 if (icp && (options & F_VERBOSE))
1083 pr_iph((struct iphdr*)(icp + 1));
1084 break;
1085 case ICMP_REDIRECT:
1086 switch(code) {
1087 case ICMP_REDIR_NET:
1088 printf("Redirect Network");
1089 break;
1090 case ICMP_REDIR_HOST:
1091 printf("Redirect Host");
1092 break;
1093 case ICMP_REDIR_NETTOS:
1094 printf("Redirect Type of Service and Network");
1095 break;
1096 case ICMP_REDIR_HOSTTOS:
1097 printf("Redirect Type of Service and Host");
1098 break;
1099 default:
1100 printf("Redirect, Bad Code: %d", code);
1101 break;
1102 }
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +09001103 printf("(New nexthop: %s)\n", pr_addr(icp ? icp->un.gateway : info));
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001104 if (icp && (options & F_VERBOSE))
1105 pr_iph((struct iphdr*)(icp + 1));
1106 break;
1107 case ICMP_ECHO:
1108 printf("Echo Request\n");
1109 /* XXX ID + Seq + Data */
1110 break;
1111 case ICMP_TIME_EXCEEDED:
1112 switch(code) {
1113 case ICMP_EXC_TTL:
1114 printf("Time to live exceeded\n");
1115 break;
1116 case ICMP_EXC_FRAGTIME:
1117 printf("Frag reassembly time exceeded\n");
1118 break;
1119 default:
1120 printf("Time exceeded, Bad Code: %d\n", code);
1121 break;
1122 }
1123 if (icp && (options & F_VERBOSE))
1124 pr_iph((struct iphdr*)(icp + 1));
1125 break;
1126 case ICMP_PARAMETERPROB:
1127 printf("Parameter problem: pointer = %u\n", icp ? (ntohl(icp->un.gateway)>>24) : info);
1128 if (icp && (options & F_VERBOSE))
1129 pr_iph((struct iphdr*)(icp + 1));
1130 break;
1131 case ICMP_TIMESTAMP:
1132 printf("Timestamp\n");
1133 /* XXX ID + Seq + 3 timestamps */
1134 break;
1135 case ICMP_TIMESTAMPREPLY:
1136 printf("Timestamp Reply\n");
1137 /* XXX ID + Seq + 3 timestamps */
1138 break;
1139 case ICMP_INFO_REQUEST:
1140 printf("Information Request\n");
1141 /* XXX ID + Seq */
1142 break;
1143 case ICMP_INFO_REPLY:
1144 printf("Information Reply\n");
1145 /* XXX ID + Seq */
1146 break;
1147#ifdef ICMP_MASKREQ
1148 case ICMP_MASKREQ:
1149 printf("Address Mask Request\n");
1150 break;
1151#endif
1152#ifdef ICMP_MASKREPLY
1153 case ICMP_MASKREPLY:
1154 printf("Address Mask Reply\n");
1155 break;
1156#endif
1157 default:
1158 printf("Bad ICMP type: %d\n", type);
1159 }
1160}
1161
1162void pr_options(unsigned char * cp, int hlen)
1163{
1164 int i, j;
1165 int optlen, totlen;
1166 unsigned char * optptr;
1167 static int old_rrlen;
1168 static char old_rr[MAX_IPOPTLEN];
1169
1170 totlen = hlen-sizeof(struct iphdr);
1171 optptr = cp;
1172
1173 while (totlen > 0) {
1174 if (*optptr == IPOPT_EOL)
1175 break;
1176 if (*optptr == IPOPT_NOP) {
1177 totlen--;
1178 optptr++;
1179 printf("\nNOP");
1180 continue;
1181 }
1182 cp = optptr;
1183 optlen = optptr[1];
1184 if (optlen < 2 || optlen > totlen)
1185 break;
1186
1187 switch (*cp) {
1188 case IPOPT_SSRR:
1189 case IPOPT_LSRR:
1190 printf("\n%cSRR: ", *cp==IPOPT_SSRR ? 'S' : 'L');
1191 j = *++cp;
1192 i = *++cp;
1193 i -= 4;
1194 cp++;
1195 if (j > IPOPT_MINOFF) {
1196 for (;;) {
1197 __u32 address;
1198 memcpy(&address, cp, 4);
1199 cp += 4;
1200 if (address == 0)
1201 printf("\t0.0.0.0");
1202 else
1203 printf("\t%s", pr_addr(address));
1204 j -= 4;
1205 putchar('\n');
1206 if (j <= IPOPT_MINOFF)
1207 break;
1208 }
1209 }
1210 break;
1211 case IPOPT_RR:
1212 j = *++cp; /* get length */
1213 i = *++cp; /* and pointer */
1214 if (i > j)
1215 i = j;
1216 i -= IPOPT_MINOFF;
1217 if (i <= 0)
1218 break;
1219 if (i == old_rrlen
1220 && !memcmp(cp, old_rr, i)
1221 && !(options & F_FLOOD)) {
1222 printf("\t(same route)");
1223 i = ((i + 3) / 4) * 4;
1224 cp += i;
1225 break;
1226 }
1227 old_rrlen = i;
1228 memcpy(old_rr, (char *)cp, i);
1229 printf("\nRR: ");
1230 cp++;
1231 for (;;) {
1232 __u32 address;
1233 memcpy(&address, cp, 4);
1234 cp += 4;
1235 if (address == 0)
1236 printf("\t0.0.0.0");
1237 else
1238 printf("\t%s", pr_addr(address));
1239 i -= 4;
1240 putchar('\n');
1241 if (i <= 0)
1242 break;
1243 }
1244 break;
1245 case IPOPT_TS:
1246 {
1247 int stdtime = 0, nonstdtime = 0;
1248 __u8 flags;
1249 j = *++cp; /* get length */
1250 i = *++cp; /* and pointer */
1251 if (i > j)
1252 i = j;
1253 i -= 5;
1254 if (i <= 0)
1255 break;
1256 flags = *++cp;
1257 printf("\nTS: ");
1258 cp++;
1259 for (;;) {
1260 long l;
1261
1262 if ((flags&0xF) != IPOPT_TS_TSONLY) {
1263 __u32 address;
1264 memcpy(&address, cp, 4);
1265 cp += 4;
1266 if (address == 0)
1267 printf("\t0.0.0.0");
1268 else
1269 printf("\t%s", pr_addr(address));
1270 i -= 4;
1271 if (i <= 0)
1272 break;
1273 }
1274 l = *cp++;
1275 l = (l<<8) + *cp++;
1276 l = (l<<8) + *cp++;
1277 l = (l<<8) + *cp++;
1278
1279 if (l & 0x80000000) {
1280 if (nonstdtime==0)
1281 printf("\t%ld absolute not-standard", l&0x7fffffff);
1282 else
1283 printf("\t%ld not-standard", (l&0x7fffffff) - nonstdtime);
1284 nonstdtime = l&0x7fffffff;
1285 } else {
1286 if (stdtime==0)
1287 printf("\t%ld absolute", l);
1288 else
1289 printf("\t%ld", l - stdtime);
1290 stdtime = l;
1291 }
1292 i -= 4;
1293 putchar('\n');
1294 if (i <= 0)
1295 break;
1296 }
1297 if (flags>>4)
1298 printf("Unrecorded hops: %d\n", flags>>4);
1299 break;
1300 }
1301 default:
1302 printf("\nunknown option %x", *cp);
1303 break;
1304 }
1305 totlen -= optlen;
1306 optptr += optlen;
1307 }
1308}
1309
1310
1311/*
1312 * pr_iph --
1313 * Print an IP header with options.
1314 */
1315void pr_iph(struct iphdr *ip)
1316{
1317 int hlen;
1318 u_char *cp;
1319
1320 hlen = ip->ihl << 2;
1321 cp = (u_char *)ip + 20; /* point to options */
1322
1323 printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst Data\n");
1324 printf(" %1x %1x %02x %04x %04x",
1325 ip->version, ip->ihl, ip->tos, ip->tot_len, ip->id);
1326 printf(" %1x %04x", ((ip->frag_off) & 0xe000) >> 13,
1327 (ip->frag_off) & 0x1fff);
1328 printf(" %02x %02x %04x", ip->ttl, ip->protocol, ip->check);
1329 printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->saddr));
1330 printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->daddr));
1331 printf("\n");
1332 pr_options(cp, hlen);
1333}
1334
1335/*
1336 * pr_addr --
1337 * Return an ascii host address as a dotted quad and optionally with
1338 * a hostname.
1339 */
1340char *
1341pr_addr(__u32 addr)
1342{
1343 struct hostent *hp;
1344 static char buf[4096];
1345
1346 in_pr_addr = !setjmp(pr_addr_jmp);
1347
1348 if (exiting || (options & F_NUMERIC) ||
1349 !(hp = gethostbyaddr((char *)&addr, 4, AF_INET)))
1350 sprintf(buf, "%s", inet_ntoa(*(struct in_addr *)&addr));
1351 else {
1352 char *s;
1353#if USE_IDN
1354 if (idna_to_unicode_lzlz(hp->h_name, &s, 0) != IDNA_SUCCESS)
1355 s = NULL;
1356#else
1357 s = NULL;
1358#endif
1359 snprintf(buf, sizeof(buf), "%s (%s)", s ? s : hp->h_name,
1360 inet_ntoa(*(struct in_addr *)&addr));
1361#if USE_IDN
1362 free(s);
1363#endif
1364 }
1365
1366 in_pr_addr = 0;
1367
1368 return(buf);
1369}
1370
1371
1372/* Set Type of Service (TOS) and other Quality of Service relating bits */
1373int parsetos(char *str)
1374{
1375 const char *cp;
1376 int tos;
1377 char *ep;
1378
1379 /* handle both hex and decimal values */
1380 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
1381 cp = str + 2;
1382 tos = (int)strtol(cp, &ep, 16);
1383 } else
1384 tos = (int)strtol(str, &ep, 10);
1385
1386 /* doesn't look like decimal or hex, eh? */
1387 if (*ep != '\0') {
1388 fprintf(stderr, "ping: \"%s\" bad value for TOS\n", str);
1389 exit(2);
1390 }
1391
1392 if (tos > TOS_MAX) {
1393 fprintf(stderr, "ping: the decimal value of TOS bits must be 0-254 (or zero)\n");
1394 exit(2);
1395 }
1396 return(tos);
1397}
1398
1399#include <linux/filter.h>
1400
1401void install_filter(void)
1402{
1403 static int once;
1404 static struct sock_filter insns[] = {
1405 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* Skip IP header. F..g BSD... Look into ping6. */
1406 BPF_STMT(BPF_LD|BPF_H|BPF_IND, 4), /* Load icmp echo ident */
1407 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xAAAA, 0, 1), /* Ours? */
1408 BPF_STMT(BPF_RET|BPF_K, ~0U), /* Yes, it passes. */
1409 BPF_STMT(BPF_LD|BPF_B|BPF_IND, 0), /* Load icmp type */
1410 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ICMP_ECHOREPLY, 1, 0), /* Echo? */
1411 BPF_STMT(BPF_RET|BPF_K, 0xFFFFFFF), /* No. It passes. */
1412 BPF_STMT(BPF_RET|BPF_K, 0) /* Echo with wrong ident. Reject. */
1413 };
1414 static struct sock_fprog filter = {
1415 sizeof insns / sizeof(insns[0]),
1416 insns
1417 };
1418
Lorenzo Colitti5df1daf2013-07-09 17:28:09 +09001419 if (once || using_ping_socket)
Lorenzo Colitti313379e2013-07-11 01:07:11 +09001420 return;
1421 once = 1;
1422
1423 /* Patch bpflet for current identifier. */
1424 insns[2] = (struct sock_filter)BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, htons(ident), 0, 1);
1425
1426 if (setsockopt(icmp_sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)))
1427 perror("WARNING: failed to install socket filter\n");
1428}
1429
1430#define USAGE_NEWLINE "\n "
1431
1432void usage(void)
1433{
1434 fprintf(stderr,
1435 "Usage: ping"
1436 " [-"
1437 "aAbBdDfhLnOqrRUvV"
1438 "]"
1439 " [-c count]"
1440 " [-i interval]"
1441 " [-I interface]"
1442 USAGE_NEWLINE
1443 " [-m mark]"
1444 " [-M pmtudisc_option]"
1445 " [-l preload]"
1446 " [-p pattern]"
1447 " [-Q tos]"
1448 USAGE_NEWLINE
1449 " [-s packetsize]"
1450 " [-S sndbuf]"
1451 " [-t ttl]"
1452 " [-T timestamp_option]"
1453 USAGE_NEWLINE
1454 " [-w deadline]"
1455 " [-W timeout]"
1456 " [hop1 ...] destination"
1457 "\n"
1458 );
1459 exit(2);
1460}