ping.c revision 46643
1/*
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  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
38static const char copyright[] =
39"@(#) Copyright (c) 1989, 1993\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44#if 0
45static char sccsid[] = "@(#)ping.c	8.1 (Berkeley) 6/5/93";
46#endif
47static const char rcsid[] =
48	"$Id: ping.c,v 1.43 1999/04/25 22:33:30 imp Exp $";
49#endif /* not lint */
50
51/*
52 *			P I N G . C
53 *
54 * Using the Internet Control Message Protocol (ICMP) "ECHO" facility,
55 * measure round-trip-delays and packet loss across network paths.
56 *
57 * Author -
58 *	Mike Muuss
59 *	U. S. Army Ballistic Research Laboratory
60 *	December, 1983
61 *
62 * Status -
63 *	Public Domain.  Distribution Unlimited.
64 * Bugs -
65 *	More statistics could always be gathered.
66 *	This program has to run SUID to ROOT to access the ICMP socket.
67 */
68
69#include <sys/param.h>		/* NB: we rely on this for <sys/types.h> */
70
71#include <ctype.h>
72#include <err.h>
73#include <errno.h>
74#include <math.h>
75#include <netdb.h>
76#include <signal.h>
77#include <stdio.h>
78#include <stdlib.h>
79#include <string.h>
80#include <sysexits.h>
81#include <termios.h>
82#include <unistd.h>
83
84#include <sys/socket.h>
85#include <sys/time.h>
86#include <sys/uio.h>
87
88#include <netinet/in.h>
89#include <netinet/in_systm.h>
90#include <netinet/ip.h>
91#include <netinet/ip_icmp.h>
92#include <netinet/ip_var.h>
93#include <arpa/inet.h>
94
95#define	PHDR_LEN	sizeof(struct timeval)
96#define	DEFDATALEN	(64 - PHDR_LEN)	/* default data length */
97#define	FLOOD_BACKOFF	20000		/* usecs to back off if F_FLOOD mode */
98					/* runs out of buffer space */
99#define	MAXIPLEN	60
100#define	MAXICMPLEN	76
101#define	MAXPACKET	(65536 - 60 - 8)/* max packet size */
102#define	MAXWAIT		10		/* max seconds to wait for response */
103#define	NROUTES		9		/* number of record route slots */
104
105#define	A(bit)		rcvd_tbl[(bit)>>3]	/* identify byte in array */
106#define	B(bit)		(1 << ((bit) & 0x07))	/* identify bit in byte */
107#define	SET(bit)	(A(bit) |= B(bit))
108#define	CLR(bit)	(A(bit) &= (~B(bit)))
109#define	TST(bit)	(A(bit) & B(bit))
110
111/* various options */
112int options;
113#define	F_FLOOD		0x0001
114#define	F_INTERVAL	0x0002
115#define	F_NUMERIC	0x0004
116#define	F_PINGFILLED	0x0008
117#define	F_QUIET		0x0010
118#define	F_RROUTE	0x0020
119#define	F_SO_DEBUG	0x0040
120#define	F_SO_DONTROUTE	0x0080
121#define	F_VERBOSE	0x0100
122#define	F_QUIET2	0x0200
123#define	F_NOLOOP	0x0400
124#define	F_MTTL		0x0800
125#define	F_MIF		0x1000
126#define	F_AUDIBLE	0x2000
127
128/*
129 * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
130 * number of received sequence numbers we can keep track of.  Change 128
131 * to 8192 for complete accuracy...
132 */
133#define	MAX_DUP_CHK	(8 * 128)
134int mx_dup_ck = MAX_DUP_CHK;
135char rcvd_tbl[MAX_DUP_CHK / 8];
136
137struct sockaddr whereto;	/* who to ping */
138int datalen = DEFDATALEN;
139int s;				/* socket file descriptor */
140u_char outpack[MAXPACKET];
141char BSPACE = '\b';		/* characters written for flood */
142char DOT = '.';
143char *hostname;
144char *shostname;
145int ident;			/* process id to identify our packets */
146int uid;			/* cached uid for micro-optimization */
147
148/* counters */
149long npackets;			/* max packets to transmit */
150long nreceived;			/* # of packets we got back */
151long nrepeats;			/* number of duplicates */
152long ntransmitted;		/* sequence # for outbound packets = #sent */
153int interval = 1000;		/* interval between packets, ms */
154
155/* timing */
156int timing;			/* flag to do timing */
157double tmin = 999999999.0;	/* minimum round trip time */
158double tmax = 0.0;		/* maximum round trip time */
159double tsum = 0.0;		/* sum of all times, for doing average */
160double tsumsq = 0.0;		/* sum of all times squared, for std. dev. */
161
162volatile sig_atomic_t finish_up;  /* nonzero if we've been told to finish up */
163int reset_kerninfo;
164volatile sig_atomic_t siginfo_p;
165
166static void fill(char *, char *);
167static u_short in_cksum(u_short *, int);
168static void check_status(void);
169static void finish(void) __dead2;
170static void pinger(void);
171static char *pr_addr(struct in_addr);
172static void pr_icmph(struct icmp *);
173static void pr_iph(struct ip *);
174static void pr_pack(char *, int, struct sockaddr_in *, struct timeval *);
175static void pr_retip(struct ip *);
176static void status(int);
177static void stopit(int);
178static void tvsub(struct timeval *, struct timeval *);
179static void usage(void) __dead2;
180
181int
182main(argc, argv)
183	int argc;
184	char *const *argv;
185{
186	struct timeval last, intvl;
187	struct hostent *hp;
188	struct sockaddr_in *to, sin;
189	struct termios ts;
190	register int i;
191	int ch, hold, packlen, preload, sockerrno, almost_done = 0;
192	struct in_addr ifaddr;
193	unsigned char ttl, loop;
194	u_char *datap, *packet;
195	char *source = NULL, *target, hnamebuf[MAXHOSTNAMELEN];
196	char snamebuf[MAXHOSTNAMELEN];
197	char *ep;
198	u_long ultmp;
199#ifdef IP_OPTIONS
200	char rspace[3 + 4 * NROUTES + 1];	/* record route space */
201#endif
202	struct sigaction si_sa;
203	struct iovec iov;
204	struct msghdr msg;
205	struct sockaddr_in from;
206	char ctrl[sizeof(struct cmsghdr) + sizeof(struct timeval)];
207
208	/*
209	 * Do the stuff that we need root priv's for *first*, and
210	 * then drop our setuid bit.  Save error reporting for
211	 * after arg parsing.
212	 */
213	s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
214	sockerrno = errno;
215
216	setuid(getuid());
217	uid = getuid();
218
219	preload = 0;
220
221	datap = &outpack[8 + PHDR_LEN];
222	while ((ch = getopt(argc, argv, "I:LQRS:T:c:adfi:l:np:qrs:v")) != -1) {
223		switch(ch) {
224		case 'a':
225			options |= F_AUDIBLE;
226			break;
227		case 'c':
228			ultmp = strtoul(optarg, &ep, 0);
229			if (*ep || ep == optarg || ultmp > LONG_MAX || !ultmp)
230				errx(EX_USAGE,
231				    "invalid count of packets to transmit: `%s'",
232				    optarg);
233			npackets = ultmp;
234			break;
235		case 'd':
236			options |= F_SO_DEBUG;
237			break;
238		case 'f':
239			if (uid) {
240				errno = EPERM;
241				err(EX_NOPERM, "-f flag");
242			}
243			options |= F_FLOOD;
244			setbuf(stdout, (char *)NULL);
245			break;
246		case 'i':		/* wait between sending packets */
247			{
248			    double t = strtod(optarg, &ep) * 1000.0;
249
250			    if (*ep || ep == optarg || t > (double)INT_MAX) {
251				    errx(
252					    EX_USAGE,
253					     "invalid timing interval: `%s'",
254					     optarg
255				    );
256			    }
257			    options |= F_INTERVAL;
258			    interval = (int)t;
259			    if (uid && interval < 1000) {
260				    errno = EPERM;
261				    err(EX_NOPERM, "-i interval too short");
262			    }
263			}
264			break;
265		case 'I':		/* multicast interface */
266			if (inet_aton(optarg, &ifaddr) == 0)
267				errx(EX_USAGE,
268				     "invalid multicast interface: `%s'",
269				     optarg);
270			options |= F_MIF;
271			break;
272		case 'l':
273			ultmp = strtoul(optarg, &ep, 0);
274			if (*ep || ep == optarg || ultmp > INT_MAX)
275				errx(EX_USAGE,
276				     "invalid preload value: `%s'", optarg);
277			if (uid) {
278				errno = EPERM;
279				err(EX_NOPERM, "-l flag");
280			}
281			preload = ultmp;
282			break;
283		case 'L':
284			options |= F_NOLOOP;
285			loop = 0;
286			break;
287		case 'n':
288			options |= F_NUMERIC;
289			break;
290		case 'p':		/* fill buffer with user pattern */
291			options |= F_PINGFILLED;
292			fill((char *)datap, optarg);
293				break;
294		case 'Q':
295			options |= F_QUIET2;
296			break;
297		case 'q':
298			options |= F_QUIET;
299			break;
300		case 'R':
301			options |= F_RROUTE;
302			break;
303		case 'r':
304			options |= F_SO_DONTROUTE;
305			break;
306		case 's':		/* size of packet to send */
307			if (uid) {
308				errno = EPERM;
309				err(EX_NOPERM, "-s flag");
310			}
311			ultmp = strtoul(optarg, &ep, 0);
312			if (ultmp > MAXPACKET)
313				errx(EX_USAGE, "packet size too large: %lu",
314				     ultmp);
315			if (*ep || ep == optarg || !ultmp)
316				errx(EX_USAGE, "invalid packet size: `%s'",
317				     optarg);
318			datalen = ultmp;
319			break;
320		case 'S':
321			source = optarg;
322			break;
323		case 'T':		/* multicast TTL */
324			ultmp = strtoul(optarg, &ep, 0);
325			if (*ep || ep == optarg || ultmp > 255)
326				errx(EX_USAGE, "invalid multicast TTL: `%s'",
327				     optarg);
328			ttl = ultmp;
329			options |= F_MTTL;
330			break;
331		case 'v':
332			options |= F_VERBOSE;
333			break;
334		default:
335			usage();
336		}
337	}
338
339	if (argc - optind != 1)
340		usage();
341	target = argv[optind];
342
343	if (source) {
344		bzero((char *)&sin, sizeof(sin));
345		sin.sin_family = AF_INET;
346		if (inet_aton(source, &sin.sin_addr) != 0) {
347			shostname = source;
348		} else {
349			hp = gethostbyname2(source, AF_INET);
350			if (!hp)
351				errx(EX_NOHOST, "cannot resolve %s: %s",
352				     source, hstrerror(h_errno));
353
354			sin.sin_len = sizeof sin;
355			if (hp->h_length > sizeof(sin.sin_addr))
356				errx(1,"gethostbyname2: illegal address");
357			memcpy(&sin.sin_addr, hp->h_addr_list[0],
358				sizeof (sin.sin_addr));
359			(void)strncpy(snamebuf, hp->h_name,
360				sizeof(snamebuf) - 1);
361			snamebuf[sizeof(snamebuf) - 1] = '\0';
362			shostname = snamebuf;
363		}
364		if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1)
365			err(1, "bind");
366	}
367
368	bzero((char *)&whereto, sizeof(struct sockaddr));
369	to = (struct sockaddr_in *)&whereto;
370	to->sin_family = AF_INET;
371	if (inet_aton(target, &to->sin_addr) != 0) {
372		hostname = target;
373	} else {
374		hp = gethostbyname2(target, AF_INET);
375		if (!hp)
376			errx(EX_NOHOST, "cannot resolve %s: %s",
377			     target, hstrerror(h_errno));
378
379		to->sin_len = sizeof *to;
380		if (hp->h_length > sizeof(to->sin_addr))
381			errx(1,"gethostbyname2 returned an illegal address");
382		memcpy(&to->sin_addr, hp->h_addr_list[0], sizeof to->sin_addr);
383		(void)strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
384		hnamebuf[sizeof(hnamebuf) - 1] = '\0';
385		hostname = hnamebuf;
386	}
387
388	if (options & F_FLOOD && options & F_INTERVAL)
389		errx(EX_USAGE, "-f and -i: incompatible options");
390
391	if (options & F_FLOOD && IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
392		errx(EX_USAGE,
393		     "-f flag cannot be used with multicast destination");
394	if (options & (F_MIF | F_NOLOOP | F_MTTL)
395	    && !IN_MULTICAST(ntohl(to->sin_addr.s_addr)))
396		errx(EX_USAGE,
397		     "-I, -L, -T flags cannot be used with unicast destination");
398
399	if (datalen >= PHDR_LEN)	/* can we time transfer */
400		timing = 1;
401	packlen = datalen + MAXIPLEN + MAXICMPLEN;
402	if (!(packet = (u_char *)malloc((size_t)packlen)))
403		err(EX_UNAVAILABLE, "malloc");
404
405	if (!(options & F_PINGFILLED))
406		for (i = PHDR_LEN; i < datalen; ++i)
407			*datap++ = i;
408
409	ident = getpid() & 0xFFFF;
410
411	if (s < 0) {
412		errno = sockerrno;
413		err(EX_OSERR, "socket");
414	}
415	hold = 1;
416	if (options & F_SO_DEBUG)
417		(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
418		    sizeof(hold));
419	if (options & F_SO_DONTROUTE)
420		(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
421		    sizeof(hold));
422
423	/* record route option */
424	if (options & F_RROUTE) {
425#ifdef IP_OPTIONS
426		bzero(rspace, sizeof(rspace));
427		rspace[IPOPT_OPTVAL] = IPOPT_RR;
428		rspace[IPOPT_OLEN] = sizeof(rspace) - 1;
429		rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
430		rspace[sizeof(rspace) - 1] = IPOPT_EOL;
431		if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
432		    sizeof(rspace)) < 0)
433			err(EX_OSERR, "setsockopt IP_OPTIONS");
434#else
435		errx(EX_UNAVAILABLE,
436		  "record route not available in this implementation");
437#endif /* IP_OPTIONS */
438	}
439
440	if (options & F_NOLOOP) {
441		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop,
442		    sizeof(loop)) < 0) {
443			err(EX_OSERR, "setsockopt IP_MULTICAST_LOOP");
444		}
445	}
446	if (options & F_MTTL) {
447		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
448		    sizeof(ttl)) < 0) {
449			err(EX_OSERR, "setsockopt IP_MULTICAST_TTL");
450		}
451	}
452	if (options & F_MIF) {
453		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr,
454		    sizeof(ifaddr)) < 0) {
455			err(EX_OSERR, "setsockopt IP_MULTICAST_IF");
456		}
457	}
458#ifdef SO_TIMESTAMP
459	{ int on = 1;
460	if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)) < 0)
461		err(EX_OSERR, "setsockopt SO_TIMESTAMP");
462	}
463#endif
464
465	/*
466	 * When pinging the broadcast address, you can get a lot of answers.
467	 * Doing something so evil is useful if you are trying to stress the
468	 * ethernet, or just want to fill the arp cache to get some stuff for
469	 * /etc/ethers.  But beware: RFC 1122 allows hosts to ignore broadcast
470	 * or multicast pings if they wish.
471	 */
472	hold = 48 * 1024;
473	(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
474	    sizeof(hold));
475
476	if (to->sin_family == AF_INET) {
477		(void)printf("PING %s (%s)", hostname,
478		    inet_ntoa(to->sin_addr));
479		if (source)
480			(void)printf(" from %s", shostname);
481		(void)printf(": %d data bytes\n", datalen);
482	} else
483		(void)printf("PING %s: %d data bytes\n", hostname, datalen);
484
485	/*
486	 * Use sigaction() instead of signal() to get unambiguous semantics,
487	 * in particular with SA_RESTART not set.
488	 */
489
490	sigemptyset(&si_sa.sa_mask);
491	si_sa.sa_flags = 0;
492
493	si_sa.sa_handler = stopit;
494	if (sigaction(SIGINT, &si_sa, 0) == -1) {
495		err(EX_OSERR, "sigaction SIGINT");
496	}
497
498	si_sa.sa_handler = status;
499	if (sigaction(SIGINFO, &si_sa, 0) == -1) {
500		err(EX_OSERR, "sigaction");
501	}
502
503	bzero(&msg, sizeof(msg));
504	msg.msg_name = (caddr_t)&from;
505	msg.msg_iov = &iov;
506	msg.msg_iovlen = 1;
507#ifdef SO_TIMESTAMP
508	msg.msg_control = (caddr_t)ctrl;
509#endif
510	iov.iov_base = packet;
511	iov.iov_len = packlen;
512
513	if (tcgetattr(STDOUT_FILENO, &ts) != -1) {
514		reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
515		ts.c_lflag |= NOKERNINFO;
516		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
517	}
518
519	while (preload--)		/* fire off them quickies */
520		pinger();
521
522	if (options & F_FLOOD) {
523		intvl.tv_sec = 0;
524		intvl.tv_usec = 10000;
525	} else {
526		intvl.tv_sec = interval / 1000;
527		intvl.tv_usec = interval % 1000 * 1000;
528	}
529
530	pinger();			/* send the first ping */
531	(void)gettimeofday(&last, NULL);
532
533	while (!finish_up) {
534		register int cc;
535		int n;
536		struct timeval timeout, now;
537		fd_set rfds;
538
539		check_status();
540		FD_ZERO(&rfds);
541		FD_SET(s, &rfds);
542		(void)gettimeofday(&now, NULL);
543		timeout.tv_sec = last.tv_sec + intvl.tv_sec - now.tv_sec;
544		timeout.tv_usec = last.tv_usec + intvl.tv_usec - now.tv_usec;
545		while (timeout.tv_usec < 0) {
546			timeout.tv_usec += 1000000;
547			timeout.tv_sec--;
548		}
549		while (timeout.tv_usec >= 1000000) {
550			timeout.tv_usec -= 1000000;
551			timeout.tv_sec++;
552		}
553		if (timeout.tv_sec < 0)
554			timeout.tv_sec = timeout.tv_usec = 0;
555		n = select(s + 1, &rfds, NULL, NULL, &timeout);
556		if (n < 0)
557			continue;	/* Must be EINTR. */
558		if (n == 1) {
559			struct timeval *t = 0;
560#ifdef SO_TIMESTAMP
561			struct cmsghdr *cmsg = (struct cmsghdr *)&ctrl;
562
563			msg.msg_controllen = sizeof(ctrl);
564#endif
565			msg.msg_namelen = sizeof(from);
566			if ((cc = recvmsg(s, &msg, 0)) < 0) {
567				if (errno == EINTR)
568					continue;
569				warn("recvmsg");
570				continue;
571			}
572#ifdef SO_TIMESTAMP
573			if (cmsg->cmsg_level == SOL_SOCKET &&
574			    cmsg->cmsg_type == SCM_TIMESTAMP &&
575			    cmsg->cmsg_len == (sizeof *cmsg + sizeof *t)) {
576				/* Copy to avoid alignment problems: */
577				memcpy(&now,CMSG_DATA(cmsg),sizeof(now));
578				t = &now;
579			}
580#endif
581			if (t == 0) {
582				(void)gettimeofday(&now, NULL);
583				t = &now;
584			}
585			pr_pack((char *)packet, cc, &from, t);
586			if (npackets && nreceived >= npackets)
587				break;
588		}
589		if (n == 0 || options & F_FLOOD) {
590			if (!npackets || ntransmitted < npackets)
591				pinger();
592			else {
593				if (almost_done)
594					break;
595				almost_done = 1;
596				intvl.tv_usec = 0;
597				if (nreceived) {
598					intvl.tv_sec = 2 * tmax / 1000;
599					if (!intvl.tv_sec)
600						intvl.tv_sec = 1;
601				} else
602					intvl.tv_sec = MAXWAIT;
603			}
604			(void)gettimeofday(&last, NULL);
605		}
606	}
607	finish();
608	/* NOTREACHED */
609	exit(0);	/* Make the compiler happy */
610}
611
612/*
613 * stopit --
614 *	Set the global bit that causes the main loop to quit.
615 * Do NOT call finish() from here, since finish() does far too much
616 * to be called from a signal handler.
617 */
618void
619stopit(sig)
620	int sig;
621{
622	finish_up = 1;
623}
624
625/*
626 * pinger --
627 *	Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
628 * will be added on by the kernel.  The ID field is our UNIX process ID,
629 * and the sequence number is an ascending integer.  The first 8 bytes
630 * of the data portion are used to hold a UNIX "timeval" struct in host
631 * byte-order, to compute the round-trip time.
632 */
633static void
634pinger(void)
635{
636	register struct icmp *icp;
637	register int cc;
638	int i;
639
640	icp = (struct icmp *)outpack;
641	icp->icmp_type = ICMP_ECHO;
642	icp->icmp_code = 0;
643	icp->icmp_cksum = 0;
644	icp->icmp_seq = ntransmitted;
645	icp->icmp_id = ident;			/* ID */
646
647	CLR(icp->icmp_seq % mx_dup_ck);
648
649	if (timing)
650		(void)gettimeofday((struct timeval *)&outpack[8],
651		    (struct timezone *)NULL);
652
653	cc = datalen + PHDR_LEN;		/* skips ICMP portion */
654
655	/* compute ICMP checksum here */
656	icp->icmp_cksum = in_cksum((u_short *)icp, cc);
657
658	i = sendto(s, (char *)outpack, cc, 0, &whereto,
659	    sizeof(struct sockaddr));
660
661	if (i < 0 || i != cc)  {
662		if (i < 0) {
663			if (options & F_FLOOD && errno == ENOBUFS) {
664				usleep(FLOOD_BACKOFF);
665				return;
666			}
667			warn("sendto");
668		} else {
669			warn("%s: partial write: %d of %d bytes",
670			     hostname, i, cc);
671		}
672	}
673	ntransmitted++;
674	if (!(options & F_QUIET) && options & F_FLOOD)
675		(void)write(STDOUT_FILENO, &DOT, 1);
676}
677
678/*
679 * pr_pack --
680 *	Print out the packet, if it came from us.  This logic is necessary
681 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
682 * which arrive ('tis only fair).  This permits multiple copies of this
683 * program to be run without having intermingled output (or statistics!).
684 */
685static void
686pr_pack(buf, cc, from, tv)
687	char *buf;
688	int cc;
689	struct sockaddr_in *from;
690	struct timeval *tv;
691{
692	register struct icmp *icp;
693	register u_long l;
694	register int i, j;
695	register u_char *cp,*dp;
696	static int old_rrlen;
697	static char old_rr[MAX_IPOPTLEN];
698	struct ip *ip;
699	struct timeval *tp;
700	double triptime;
701	int hlen, dupflag;
702
703	/* Check the IP header */
704	ip = (struct ip *)buf;
705	hlen = ip->ip_hl << 2;
706	if (cc < hlen + ICMP_MINLEN) {
707		if (options & F_VERBOSE)
708			warn("packet too short (%d bytes) from %s", cc,
709			     inet_ntoa(from->sin_addr));
710		return;
711	}
712
713	/* Now the ICMP part */
714	cc -= hlen;
715	icp = (struct icmp *)(buf + hlen);
716	if (icp->icmp_type == ICMP_ECHOREPLY) {
717		if (icp->icmp_id != ident)
718			return;			/* 'Twas not our ECHO */
719		++nreceived;
720		triptime = 0.0;
721		if (timing) {
722			struct timeval tv1;
723#ifndef icmp_data
724			tp = (struct timeval *)&icp->icmp_ip;
725#else
726			tp = (struct timeval *)icp->icmp_data;
727#endif
728			/* Avoid unaligned data: */
729			memcpy(&tv1,tp,sizeof(tv1));
730			tvsub(tv, &tv1);
731 			triptime = ((double)tv->tv_sec) * 1000.0 +
732 			    ((double)tv->tv_usec) / 1000.0;
733			tsum += triptime;
734			tsumsq += triptime * triptime;
735			if (triptime < tmin)
736				tmin = triptime;
737			if (triptime > tmax)
738				tmax = triptime;
739		}
740
741		if (TST(icp->icmp_seq % mx_dup_ck)) {
742			++nrepeats;
743			--nreceived;
744			dupflag = 1;
745		} else {
746			SET(icp->icmp_seq % mx_dup_ck);
747			dupflag = 0;
748		}
749
750		if (options & F_QUIET)
751			return;
752
753		if (options & F_FLOOD)
754			(void)write(STDOUT_FILENO, &BSPACE, 1);
755		else {
756			(void)printf("%d bytes from %s: icmp_seq=%u", cc,
757			   inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
758			   icp->icmp_seq);
759			(void)printf(" ttl=%d", ip->ip_ttl);
760			if (timing)
761				(void)printf(" time=%.3f ms", triptime);
762			if (dupflag)
763				(void)printf(" (DUP!)");
764			if (options & F_AUDIBLE)
765				(void)printf("\a");
766			/* check the data */
767			cp = (u_char*)&icp->icmp_data[PHDR_LEN];
768			dp = &outpack[8 + PHDR_LEN];
769			for (i = PHDR_LEN; i < datalen; ++i, ++cp, ++dp) {
770				if (*cp != *dp) {
771	(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
772	    i, *dp, *cp);
773					printf("\ncp:");
774					cp = (u_char*)&icp->icmp_data[0];
775					for (i = 0; i < datalen; ++i, ++cp) {
776						if ((i % 32) == 8)
777							(void)printf("\n\t");
778						(void)printf("%x ", *cp);
779					}
780					printf("\ndp:");
781					cp = &outpack[8];
782					for (i = 0; i < datalen; ++i, ++cp) {
783						if ((i % 32) == 8)
784							(void)printf("\n\t");
785						(void)printf("%x ", *cp);
786					}
787					break;
788				}
789			}
790		}
791	} else {
792		/*
793		 * We've got something other than an ECHOREPLY.
794		 * See if it's a reply to something that we sent.
795		 * We can compare IP destination, protocol,
796		 * and ICMP type and ID.
797		 *
798		 * Only print all the error messages if we are running
799		 * as root to avoid leaking information not normally
800		 * available to those not running as root.
801		 */
802#ifndef icmp_data
803		struct ip *oip = &icp->icmp_ip;
804#else
805		struct ip *oip = (struct ip *)icp->icmp_data;
806#endif
807		struct icmp *oicmp = (struct icmp *)(oip + 1);
808
809		if (((options & F_VERBOSE) && uid == 0) ||
810		    (!(options & F_QUIET2) &&
811		     (oip->ip_dst.s_addr ==
812			 ((struct sockaddr_in *)&whereto)->sin_addr.s_addr) &&
813		     (oip->ip_p == IPPROTO_ICMP) &&
814		     (oicmp->icmp_type == ICMP_ECHO) &&
815		     (oicmp->icmp_id == ident))) {
816		    (void)printf("%d bytes from %s: ", cc,
817			pr_addr(from->sin_addr));
818		    pr_icmph(icp);
819		} else
820		    return;
821	}
822
823	/* Display any IP options */
824	cp = (u_char *)buf + sizeof(struct ip);
825
826	for (; hlen > (int)sizeof(struct ip); --hlen, ++cp)
827		switch (*cp) {
828		case IPOPT_EOL:
829			hlen = 0;
830			break;
831		case IPOPT_LSRR:
832			(void)printf("\nLSRR: ");
833			hlen -= 2;
834			j = *++cp;
835			++cp;
836			if (j > IPOPT_MINOFF)
837				for (;;) {
838					l = *++cp;
839					l = (l<<8) + *++cp;
840					l = (l<<8) + *++cp;
841					l = (l<<8) + *++cp;
842					if (l == 0) {
843						printf("\t0.0.0.0");
844					} else {
845						struct in_addr ina;
846						ina.s_addr = ntohl(l);
847						printf("\t%s", pr_addr(ina));
848					}
849				hlen -= 4;
850				j -= 4;
851				if (j <= IPOPT_MINOFF)
852					break;
853				(void)putchar('\n');
854			}
855			break;
856		case IPOPT_RR:
857			j = *++cp;		/* get length */
858			i = *++cp;		/* and pointer */
859			hlen -= 2;
860			if (i > j)
861				i = j;
862			i -= IPOPT_MINOFF;
863			if (i <= 0)
864				continue;
865			if (i == old_rrlen
866			    && cp == (u_char *)buf + sizeof(struct ip) + 2
867			    && !bcmp((char *)cp, old_rr, i)
868			    && !(options & F_FLOOD)) {
869				(void)printf("\t(same route)");
870				i = ((i + 3) / 4) * 4;
871				hlen -= i;
872				cp += i;
873				break;
874			}
875			if (i < MAX_IPOPTLEN) {
876				old_rrlen = i;
877				bcopy((char *)cp, old_rr, i);
878			} else
879				old_rrlen = 0;
880
881			(void)printf("\nRR: ");
882			j = 0;
883			for (;;) {
884				l = *++cp;
885				l = (l<<8) + *++cp;
886				l = (l<<8) + *++cp;
887				l = (l<<8) + *++cp;
888				if (l == 0) {
889					printf("\t0.0.0.0");
890				} else {
891					struct in_addr ina;
892					ina.s_addr = ntohl(l);
893					printf("\t%s", pr_addr(ina));
894				}
895				hlen -= 4;
896				i -= 4;
897				j += 4;
898				if (i <= 0)
899					break;
900				if (j >= MAX_IPOPTLEN) {
901					(void) printf("\t(truncated route)");
902					break;
903				}
904				(void)putchar('\n');
905			}
906			break;
907		case IPOPT_NOP:
908			(void)printf("\nNOP");
909			break;
910		default:
911			(void)printf("\nunknown option %x", *cp);
912			break;
913		}
914	if (!(options & F_FLOOD)) {
915		(void)putchar('\n');
916		(void)fflush(stdout);
917	}
918}
919
920/*
921 * in_cksum --
922 *	Checksum routine for Internet Protocol family headers (C Version)
923 */
924u_short
925in_cksum(addr, len)
926	u_short *addr;
927	int len;
928{
929	register int nleft = len;
930	register u_short *w = addr;
931	register int sum = 0;
932	u_short answer = 0;
933
934	/*
935	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
936	 * sequential 16 bit words to it, and at the end, fold back all the
937	 * carry bits from the top 16 bits into the lower 16 bits.
938	 */
939	while (nleft > 1)  {
940		sum += *w++;
941		nleft -= 2;
942	}
943
944	/* mop up an odd byte, if necessary */
945	if (nleft == 1) {
946		*(u_char *)(&answer) = *(u_char *)w ;
947		sum += answer;
948	}
949
950	/* add back carry outs from top 16 bits to low 16 bits */
951	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
952	sum += (sum >> 16);			/* add carry */
953	answer = ~sum;				/* truncate to 16 bits */
954	return(answer);
955}
956
957/*
958 * tvsub --
959 *	Subtract 2 timeval structs:  out = out - in.  Out is assumed to
960 * be >= in.
961 */
962static void
963tvsub(out, in)
964	register struct timeval *out, *in;
965{
966	if ((out->tv_usec -= in->tv_usec) < 0) {
967		--out->tv_sec;
968		out->tv_usec += 1000000;
969	}
970	out->tv_sec -= in->tv_sec;
971}
972
973/*
974 * status --
975 *	Print out statistics when SIGINFO is received.
976 */
977
978static void
979status(sig)
980	int sig;
981{
982	siginfo_p = 1;
983}
984
985static void
986check_status()
987{
988	if (siginfo_p) {
989		siginfo_p = 0;
990		(void)fprintf(stderr,
991	"\r%ld/%ld packets received (%.0f%%) %.3f min / %.3f avg / %.3f max\n",
992		    nreceived, ntransmitted,
993		    ntransmitted ? nreceived * 100.0 / ntransmitted : 0.0,
994		    nreceived ? tmin : 0.0,
995		    nreceived + nrepeats ? tsum / (nreceived + nrepeats) : tsum,
996		    tmax);
997	}
998}
999
1000/*
1001 * finish --
1002 *	Print out statistics, and give up.
1003 */
1004static void
1005finish()
1006{
1007	struct termios ts;
1008
1009	(void)signal(SIGINT, SIG_IGN);
1010	(void)signal(SIGALRM, SIG_IGN);
1011	(void)putchar('\n');
1012	(void)fflush(stdout);
1013	(void)printf("--- %s ping statistics ---\n", hostname);
1014	(void)printf("%ld packets transmitted, ", ntransmitted);
1015	(void)printf("%ld packets received, ", nreceived);
1016	if (nrepeats)
1017		(void)printf("+%ld duplicates, ", nrepeats);
1018	if (ntransmitted) {
1019		if (nreceived > ntransmitted)
1020			(void)printf("-- somebody's printing up packets!");
1021		else
1022			(void)printf("%d%% packet loss",
1023			    (int) (((ntransmitted - nreceived) * 100) /
1024			    ntransmitted));
1025	}
1026	(void)putchar('\n');
1027	if (nreceived && timing) {
1028		double n = nreceived + nrepeats;
1029		double avg = tsum / n;
1030		double vari = tsumsq / n - avg * avg;
1031		printf("round-trip min/avg/max/stddev = "
1032		       "%.3f/%.3f/%.3f/%.3f ms\n",
1033		    tmin, avg, tmax, sqrt(vari));
1034	}
1035	if (reset_kerninfo && tcgetattr(STDOUT_FILENO, &ts) != -1) {
1036		ts.c_lflag &= ~NOKERNINFO;
1037		tcsetattr(STDOUT_FILENO, TCSANOW, &ts);
1038	}
1039
1040	if (nreceived)
1041		exit(0);
1042	else
1043		exit(2);
1044}
1045
1046#ifdef notdef
1047static char *ttab[] = {
1048	"Echo Reply",		/* ip + seq + udata */
1049	"Dest Unreachable",	/* net, host, proto, port, frag, sr + IP */
1050	"Source Quench",	/* IP */
1051	"Redirect",		/* redirect type, gateway, + IP  */
1052	"Echo",
1053	"Time Exceeded",	/* transit, frag reassem + IP */
1054	"Parameter Problem",	/* pointer + IP */
1055	"Timestamp",		/* id + seq + three timestamps */
1056	"Timestamp Reply",	/* " */
1057	"Info Request",		/* id + sq */
1058	"Info Reply"		/* " */
1059};
1060#endif
1061
1062/*
1063 * pr_icmph --
1064 *	Print a descriptive string about an ICMP header.
1065 */
1066static void
1067pr_icmph(icp)
1068	struct icmp *icp;
1069{
1070	switch(icp->icmp_type) {
1071	case ICMP_ECHOREPLY:
1072		(void)printf("Echo Reply\n");
1073		/* XXX ID + Seq + Data */
1074		break;
1075	case ICMP_UNREACH:
1076		switch(icp->icmp_code) {
1077		case ICMP_UNREACH_NET:
1078			(void)printf("Destination Net Unreachable\n");
1079			break;
1080		case ICMP_UNREACH_HOST:
1081			(void)printf("Destination Host Unreachable\n");
1082			break;
1083		case ICMP_UNREACH_PROTOCOL:
1084			(void)printf("Destination Protocol Unreachable\n");
1085			break;
1086		case ICMP_UNREACH_PORT:
1087			(void)printf("Destination Port Unreachable\n");
1088			break;
1089		case ICMP_UNREACH_NEEDFRAG:
1090			(void)printf("frag needed and DF set (MTU %d)\n",
1091					ntohs(icp->icmp_nextmtu));
1092			break;
1093		case ICMP_UNREACH_SRCFAIL:
1094			(void)printf("Source Route Failed\n");
1095			break;
1096		case ICMP_UNREACH_FILTER_PROHIB:
1097			(void)printf("Communication prohibited by filter\n");
1098			break;
1099		default:
1100			(void)printf("Dest Unreachable, Bad Code: %d\n",
1101			    icp->icmp_code);
1102			break;
1103		}
1104		/* Print returned IP header information */
1105#ifndef icmp_data
1106		pr_retip(&icp->icmp_ip);
1107#else
1108		pr_retip((struct ip *)icp->icmp_data);
1109#endif
1110		break;
1111	case ICMP_SOURCEQUENCH:
1112		(void)printf("Source Quench\n");
1113#ifndef icmp_data
1114		pr_retip(&icp->icmp_ip);
1115#else
1116		pr_retip((struct ip *)icp->icmp_data);
1117#endif
1118		break;
1119	case ICMP_REDIRECT:
1120		switch(icp->icmp_code) {
1121		case ICMP_REDIRECT_NET:
1122			(void)printf("Redirect Network");
1123			break;
1124		case ICMP_REDIRECT_HOST:
1125			(void)printf("Redirect Host");
1126			break;
1127		case ICMP_REDIRECT_TOSNET:
1128			(void)printf("Redirect Type of Service and Network");
1129			break;
1130		case ICMP_REDIRECT_TOSHOST:
1131			(void)printf("Redirect Type of Service and Host");
1132			break;
1133		default:
1134			(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
1135			break;
1136		}
1137		(void)printf("(New addr: %s)\n", inet_ntoa(icp->icmp_gwaddr));
1138#ifndef icmp_data
1139		pr_retip(&icp->icmp_ip);
1140#else
1141		pr_retip((struct ip *)icp->icmp_data);
1142#endif
1143		break;
1144	case ICMP_ECHO:
1145		(void)printf("Echo Request\n");
1146		/* XXX ID + Seq + Data */
1147		break;
1148	case ICMP_TIMXCEED:
1149		switch(icp->icmp_code) {
1150		case ICMP_TIMXCEED_INTRANS:
1151			(void)printf("Time to live exceeded\n");
1152			break;
1153		case ICMP_TIMXCEED_REASS:
1154			(void)printf("Frag reassembly time exceeded\n");
1155			break;
1156		default:
1157			(void)printf("Time exceeded, Bad Code: %d\n",
1158			    icp->icmp_code);
1159			break;
1160		}
1161#ifndef icmp_data
1162		pr_retip(&icp->icmp_ip);
1163#else
1164		pr_retip((struct ip *)icp->icmp_data);
1165#endif
1166		break;
1167	case ICMP_PARAMPROB:
1168		(void)printf("Parameter problem: pointer = 0x%02x\n",
1169		    icp->icmp_hun.ih_pptr);
1170#ifndef icmp_data
1171		pr_retip(&icp->icmp_ip);
1172#else
1173		pr_retip((struct ip *)icp->icmp_data);
1174#endif
1175		break;
1176	case ICMP_TSTAMP:
1177		(void)printf("Timestamp\n");
1178		/* XXX ID + Seq + 3 timestamps */
1179		break;
1180	case ICMP_TSTAMPREPLY:
1181		(void)printf("Timestamp Reply\n");
1182		/* XXX ID + Seq + 3 timestamps */
1183		break;
1184	case ICMP_IREQ:
1185		(void)printf("Information Request\n");
1186		/* XXX ID + Seq */
1187		break;
1188	case ICMP_IREQREPLY:
1189		(void)printf("Information Reply\n");
1190		/* XXX ID + Seq */
1191		break;
1192	case ICMP_MASKREQ:
1193		(void)printf("Address Mask Request\n");
1194		break;
1195	case ICMP_MASKREPLY:
1196		(void)printf("Address Mask Reply\n");
1197		break;
1198	case ICMP_ROUTERADVERT:
1199		(void)printf("Router Advertisement\n");
1200		break;
1201	case ICMP_ROUTERSOLICIT:
1202		(void)printf("Router Solicitation\n");
1203		break;
1204	default:
1205		(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
1206	}
1207}
1208
1209/*
1210 * pr_iph --
1211 *	Print an IP header with options.
1212 */
1213static void
1214pr_iph(ip)
1215	struct ip *ip;
1216{
1217	int hlen;
1218	u_char *cp;
1219
1220	hlen = ip->ip_hl << 2;
1221	cp = (u_char *)ip + 20;		/* point to options */
1222
1223	(void)printf("Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src      Dst\n");
1224	(void)printf(" %1x  %1x  %02x %04x %04x",
1225	    ip->ip_v, ip->ip_hl, ip->ip_tos, ntohs(ip->ip_len),
1226	    ntohs(ip->ip_id));
1227	(void)printf("   %1lx %04lx",
1228	    (u_long) (ntohl(ip->ip_off) & 0xe000) >> 13,
1229	    (u_long) ntohl(ip->ip_off) & 0x1fff);
1230	(void)printf("  %02x  %02x %04x", ip->ip_ttl, ip->ip_p,
1231							    ntohs(ip->ip_sum));
1232	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1233	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1234	/* dump any option bytes */
1235	while (hlen-- > 20) {
1236		(void)printf("%02x", *cp++);
1237	}
1238	(void)putchar('\n');
1239}
1240
1241/*
1242 * pr_addr --
1243 *	Return an ascii host address as a dotted quad and optionally with
1244 * a hostname.
1245 */
1246static char *
1247pr_addr(ina)
1248	struct in_addr ina;
1249{
1250	struct hostent *hp;
1251	static char buf[16 + 3 + MAXHOSTNAMELEN];
1252
1253	if ((options & F_NUMERIC) ||
1254	    !(hp = gethostbyaddr((char *)&ina, 4, AF_INET)))
1255		return inet_ntoa(ina);
1256	else
1257		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1258		    inet_ntoa(ina));
1259	return(buf);
1260}
1261
1262/*
1263 * pr_retip --
1264 *	Dump some info on a returned (via ICMP) IP packet.
1265 */
1266static void
1267pr_retip(ip)
1268	struct ip *ip;
1269{
1270	int hlen;
1271	u_char *cp;
1272
1273	pr_iph(ip);
1274	hlen = ip->ip_hl << 2;
1275	cp = (u_char *)ip + hlen;
1276
1277	if (ip->ip_p == 6)
1278		(void)printf("TCP: from port %u, to port %u (decimal)\n",
1279		    (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1280	else if (ip->ip_p == 17)
1281		(void)printf("UDP: from port %u, to port %u (decimal)\n",
1282			(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
1283}
1284
1285static void
1286fill(bp, patp)
1287	char *bp, *patp;
1288{
1289	register int ii, jj, kk;
1290	int pat[16];
1291	char *cp;
1292
1293	for (cp = patp; *cp; cp++) {
1294		if (!isxdigit(*cp))
1295			errx(EX_USAGE,
1296			     "patterns must be specified as hex digits");
1297
1298	}
1299	ii = sscanf(patp,
1300	    "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1301	    &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
1302	    &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
1303	    &pat[13], &pat[14], &pat[15]);
1304
1305	if (ii > 0)
1306		for (kk = 0;
1307		    kk <= MAXPACKET - (8 + PHDR_LEN + ii);
1308		    kk += ii)
1309			for (jj = 0; jj < ii; ++jj)
1310				bp[jj + kk] = pat[jj];
1311	if (!(options & F_QUIET)) {
1312		(void)printf("PATTERN: 0x");
1313		for (jj = 0; jj < ii; ++jj)
1314			(void)printf("%02x", bp[jj] & 0xFF);
1315		(void)printf("\n");
1316	}
1317}
1318
1319static void
1320usage()
1321{
1322	fprintf(stderr, "%s\n%s\n%s\n",
1323"usage: ping [-QRadfnqrv] [-c count] [-i wait] [-l preload] [-p pattern]",
1324"            [-s packetsize] [-S src_addr]",
1325"            [host | [-L] [-I iface] [-T ttl] mcast-group]");
1326	exit(EX_USAGE);
1327}
1328