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