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