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