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
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#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		if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
364			if (errno == EACCES) {
365				if (broadcast_pings == 0) {
366					fprintf(stderr, "Do you want to ping broadcast? Then -b\n");
367					exit(2);
368				}
369				fprintf(stderr, "WARNING: pinging broadcast address\n");
370				if (setsockopt(probe_fd, SOL_SOCKET, SO_BROADCAST,
371					       &broadcast_pings, sizeof(broadcast_pings)) < 0) {
372					perror ("can't set broadcasting");
373					exit(2);
374				}
375				if (connect(probe_fd, (struct sockaddr*)&dst, sizeof(dst)) == -1) {
376					perror("connect");
377					exit(2);
378				}
379			} else {
380				perror("connect");
381				exit(2);
382			}
383		}
384		alen = sizeof(source);
385		if (getsockname(probe_fd, (struct sockaddr*)&source, &alen) == -1) {
386			perror("getsockname");
387			exit(2);
388		}
389		source.sin_port = 0;
390
391#ifndef WITHOUT_IFADDRS
392		if (device) {
393			struct ifaddrs *ifa0, *ifa;
394			int ret;
395
396			ret = getifaddrs(&ifa0);
397			if (ret) {
398				fprintf(stderr, "gatifaddrs() failed.\n");
399				exit(2);
400			}
401			for (ifa = ifa0; ifa; ifa = ifa->ifa_next) {
402				if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET)
403					continue;
404				if (!strncmp(ifa->ifa_name, device, sizeof(device) - 1) &&
405				    !memcmp(&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
406					    &source.sin_addr, sizeof(source.sin_addr)))
407					break;
408			}
409			freeifaddrs(ifa0);
410			if (!ifa)
411				fprintf(stderr, "ping: Warning: source address might be selected on device other than %s.\n", device);
412		}
413#endif
414		close(probe_fd);
415	} while (0);
416
417	if (whereto.sin_addr.s_addr == 0)
418		whereto.sin_addr.s_addr = source.sin_addr.s_addr;
419
420	if (icmp_sock < 0) {
421		errno = socket_errno;
422		perror("ping: icmp open socket");
423		exit(2);
424	}
425
426	if (device) {
427		struct ifreq ifr;
428
429		memset(&ifr, 0, sizeof(ifr));
430		strncpy(ifr.ifr_name, device, IFNAMSIZ-1);
431		if (ioctl(icmp_sock, SIOCGIFINDEX, &ifr) < 0) {
432			fprintf(stderr, "ping: unknown iface %s\n", device);
433			exit(2);
434		}
435		cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
436		cmsg_len = sizeof(cmsg);
437	}
438
439	if (broadcast_pings || IN_MULTICAST(ntohl(whereto.sin_addr.s_addr))) {
440		if (uid) {
441			if (interval < 1000) {
442				fprintf(stderr, "ping: broadcast ping with too short interval.\n");
443				exit(2);
444			}
445			if (pmtudisc >= 0 && pmtudisc != IP_PMTUDISC_DO) {
446				fprintf(stderr, "ping: broadcast ping does not fragment.\n");
447				exit(2);
448			}
449		}
450		if (pmtudisc < 0)
451			pmtudisc = IP_PMTUDISC_DO;
452	}
453
454	if (pmtudisc >= 0) {
455		if (setsockopt(icmp_sock, SOL_IP, IP_MTU_DISCOVER, &pmtudisc, sizeof(pmtudisc)) == -1) {
456			perror("ping: IP_MTU_DISCOVER");
457			exit(2);
458		}
459	}
460
461	if ((options&F_STRICTSOURCE) &&
462	    bind(icmp_sock, (struct sockaddr*)&source, sizeof(source)) == -1) {
463		perror("bind");
464		exit(2);
465	}
466
467	if (!using_ping_socket) {
468		struct icmp_filter filt;
469		filt.data = ~((1<<ICMP_SOURCE_QUENCH)|
470			      (1<<ICMP_DEST_UNREACH)|
471			      (1<<ICMP_TIME_EXCEEDED)|
472			      (1<<ICMP_PARAMETERPROB)|
473			      (1<<ICMP_REDIRECT)|
474			      (1<<ICMP_ECHOREPLY));
475		if (setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, (char*)&filt, sizeof(filt)) == -1)
476			perror("WARNING: setsockopt(ICMP_FILTER)");
477	}
478
479	hold = 1;
480	if (setsockopt(icmp_sock, SOL_IP, IP_RECVERR, (char *)&hold, sizeof(hold)))
481		fprintf(stderr, "WARNING: your kernel is veeery old. No problems.\n");
482	if (using_ping_socket) {
483		if (setsockopt(icmp_sock, SOL_IP, IP_RECVTTL, (char *)&hold, sizeof(hold)))
484			perror("WARNING: setsockopt(IP_RECVTTL)");
485		if (setsockopt(icmp_sock, SOL_IP, IP_RETOPTS, (char *)&hold, sizeof(hold)))
486			perror("WARNING: setsockopt(IP_RETOPTS)");
487	}
488
489	/* record route option */
490	if (options & F_RROUTE) {
491		memset(rspace, 0, sizeof(rspace));
492		rspace[0] = IPOPT_NOP;
493		rspace[1+IPOPT_OPTVAL] = IPOPT_RR;
494		rspace[1+IPOPT_OLEN] = sizeof(rspace)-1;
495		rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
496		optlen = 40;
497		if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, sizeof(rspace)) < 0) {
498			perror("ping: record route");
499			exit(2);
500		}
501	}
502	if (options & F_TIMESTAMP) {
503		memset(rspace, 0, sizeof(rspace));
504		rspace[0] = IPOPT_TIMESTAMP;
505		rspace[1] = (ts_type==IPOPT_TS_TSONLY ? 40 : 36);
506		rspace[2] = 5;
507		rspace[3] = ts_type;
508		if (ts_type == IPOPT_TS_PRESPEC) {
509			int i;
510			rspace[1] = 4+nroute*8;
511			for (i=0; i<nroute; i++)
512				*(__u32*)&rspace[4+i*8] = route[i];
513		}
514		if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
515			rspace[3] = 2;
516			if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, rspace[1]) < 0) {
517				perror("ping: ts option");
518				exit(2);
519			}
520		}
521		optlen = 40;
522	}
523	if (options & F_SOURCEROUTE) {
524		int i;
525		memset(rspace, 0, sizeof(rspace));
526		rspace[0] = IPOPT_NOOP;
527		rspace[1+IPOPT_OPTVAL] = (options & F_SO_DONTROUTE) ? IPOPT_SSRR
528			: IPOPT_LSRR;
529		rspace[1+IPOPT_OLEN] = 3 + nroute*4;
530		rspace[1+IPOPT_OFFSET] = IPOPT_MINOFF;
531		for (i=0; i<nroute; i++)
532			*(__u32*)&rspace[4+i*4] = route[i];
533
534		if (setsockopt(icmp_sock, IPPROTO_IP, IP_OPTIONS, rspace, 4 + nroute*4) < 0) {
535			perror("ping: record route");
536			exit(2);
537		}
538		optlen = 40;
539	}
540
541	/* Estimate memory eaten by single packet. It is rough estimate.
542	 * Actually, for small datalen's it depends on kernel side a lot. */
543	hold = datalen + 8;
544	hold += ((hold+511)/512)*(optlen + 20 + 16 + 64 + 160);
545	sock_setbufs(icmp_sock, hold);
546
547	if (broadcast_pings) {
548		if (setsockopt(icmp_sock, SOL_SOCKET, SO_BROADCAST,
549			       &broadcast_pings, sizeof(broadcast_pings)) < 0) {
550			perror ("ping: can't set broadcasting");
551			exit(2);
552		}
553	}
554
555	if (options & F_NOLOOP) {
556		int loop = 0;
557		if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_LOOP,
558							&loop, 1) == -1) {
559			perror ("ping: can't disable multicast loopback");
560			exit(2);
561		}
562	}
563	if (options & F_TTL) {
564		int ittl = ttl;
565		if (setsockopt(icmp_sock, IPPROTO_IP, IP_MULTICAST_TTL,
566							&ttl, 1) == -1) {
567			perror ("ping: can't set multicast time-to-live");
568			exit(2);
569		}
570		if (setsockopt(icmp_sock, IPPROTO_IP, IP_TTL,
571							&ittl, sizeof(ittl)) == -1) {
572			perror ("ping: can't set unicast time-to-live");
573			exit(2);
574		}
575	}
576
577	if (datalen > 0xFFFF - 8 - optlen - 20) {
578		if (uid || datalen > sizeof(outpack)-8) {
579			fprintf(stderr, "Error: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
580			exit(2);
581		}
582		/* Allow small oversize to root yet. It will cause EMSGSIZE. */
583		fprintf(stderr, "WARNING: packet size %d is too large. Maximum is %d\n", datalen, 0xFFFF-8-20-optlen);
584	}
585
586	if (datalen >= sizeof(struct timeval))	/* can we time transfer */
587		timing = 1;
588	packlen = datalen + MAXIPLEN + MAXICMPLEN;
589	if (!(packet = (u_char *)malloc((u_int)packlen))) {
590		fprintf(stderr, "ping: out of memory.\n");
591		exit(2);
592	}
593
594	printf("PING %s (%s) ", hostname, inet_ntoa(whereto.sin_addr));
595	if (device || (options&F_STRICTSOURCE))
596		printf("from %s %s: ", inet_ntoa(source.sin_addr), device ?: "");
597	printf("%d(%d) bytes of data.\n", datalen, datalen+8+optlen+20);
598
599	setup(icmp_sock);
600
601	main_loop(icmp_sock, packet, packlen);
602}
603
604
605int receive_error_msg()
606{
607	int res;
608	char cbuf[512];
609	struct iovec  iov;
610	struct msghdr msg;
611	struct cmsghdr *cmsg;
612	struct sock_extended_err *e;
613	struct icmphdr icmph;
614	struct sockaddr_in target;
615	int net_errors = 0;
616	int local_errors = 0;
617	int saved_errno = errno;
618
619	iov.iov_base = &icmph;
620	iov.iov_len = sizeof(icmph);
621	msg.msg_name = (void*)&target;
622	msg.msg_namelen = sizeof(target);
623	msg.msg_iov = &iov;
624	msg.msg_iovlen = 1;
625	msg.msg_flags = 0;
626	msg.msg_control = cbuf;
627	msg.msg_controllen = sizeof(cbuf);
628
629	res = recvmsg(icmp_sock, &msg, MSG_ERRQUEUE|MSG_DONTWAIT);
630	if (res < 0)
631		goto out;
632
633	e = NULL;
634	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
635		if (cmsg->cmsg_level == SOL_IP) {
636			if (cmsg->cmsg_type == IP_RECVERR)
637				e = (struct sock_extended_err *)CMSG_DATA(cmsg);
638		}
639	}
640	if (e == NULL)
641		abort();
642
643	if (e->ee_origin == SO_EE_ORIGIN_LOCAL) {
644		local_errors++;
645		if (options & F_QUIET)
646			goto out;
647		if (options & F_FLOOD)
648			write_stdout("E", 1);
649		else if (e->ee_errno != EMSGSIZE)
650			fprintf(stderr, "ping: local error: %s\n", strerror(e->ee_errno));
651		else
652			fprintf(stderr, "ping: local error: Message too long, mtu=%u\n", e->ee_info);
653		nerrors++;
654	} else if (e->ee_origin == SO_EE_ORIGIN_ICMP) {
655		struct sockaddr_in *sin = (struct sockaddr_in*)(e+1);
656		int error_pkt;
657
658		if (res < sizeof(icmph) ||
659		    target.sin_addr.s_addr != whereto.sin_addr.s_addr ||
660		    icmph.type != ICMP_ECHO ||
661		    !is_ours(icmph.un.echo.id)) {
662			/* Not our error, not an error at all. Clear. */
663			saved_errno = 0;
664			goto out;
665		}
666
667		error_pkt = (e->ee_type != ICMP_REDIRECT &&
668			     e->ee_type != ICMP_SOURCE_QUENCH);
669		if (error_pkt) {
670			acknowledge(ntohs(icmph.un.echo.sequence));
671			net_errors++;
672			nerrors++;
673		}
674		else {
675			saved_errno = 0;
676		}
677
678		if (!using_ping_socket && !working_recverr) {
679			struct icmp_filter filt;
680			working_recverr = 1;
681			/* OK, it works. Add stronger filter. */
682			filt.data = ~((1<<ICMP_SOURCE_QUENCH)|
683				      (1<<ICMP_REDIRECT)|
684				      (1<<ICMP_ECHOREPLY));
685			if (setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, (char*)&filt, sizeof(filt)) == -1)
686				perror("\rWARNING: setsockopt(ICMP_FILTER)");
687		}
688
689		if (options & F_QUIET)
690			goto out;
691		if (options & F_FLOOD) {
692			if (error_pkt)
693				write_stdout("\bE", 2);
694		} else {
695			print_timestamp();
696			printf("From %s: icmp_seq=%u ", pr_addr(sin->sin_addr.s_addr), 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}
1429