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