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