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