xref: /netbsd/sbin/ping/ping.c (revision bf9ec67e)
1 /*	$NetBSD: ping.c,v 1.63 2001/12/20 20:10:38 soren Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Mike Muuss.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 /*
40  *			P I N G . C
41  *
42  * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
43  * measure round-trip-delays and packet loss across network paths.
44  *
45  * Author -
46  *	Mike Muuss
47  *	U. S. Army Ballistic Research Laboratory
48  *	December, 1983
49  * Modified at Uc Berkeley
50  * Record Route and verbose headers - Phil Dykstra, BRL, March 1988.
51  * Multicast options (ttl, if, loop) - Steve Deering, Stanford, August 1988.
52  * ttl, duplicate detection - Cliff Frost, UCB, April 1989
53  * Pad pattern - Cliff Frost (from Tom Ferrin, UCSF), April 1989
54  *
55  * Status -
56  *	Public Domain.  Distribution Unlimited.
57  *
58  * Bugs -
59  *	More statistics could always be gathered.
60  *	This program has to run SUID to ROOT to access the ICMP socket.
61  */
62 
63 #include <sys/cdefs.h>
64 #ifndef lint
65 __RCSID("$NetBSD: ping.c,v 1.63 2001/12/20 20:10:38 soren Exp $");
66 #endif
67 
68 #include <stdio.h>
69 #include <stddef.h>
70 #include <errno.h>
71 #include <sys/time.h>
72 #include <sys/types.h>
73 #include <sys/signal.h>
74 #include <sys/param.h>
75 #include <sys/socket.h>
76 #include <sys/file.h>
77 #include <termios.h>
78 #include <stdlib.h>
79 #include <unistd.h>
80 #include <limits.h>
81 #include <math.h>
82 #include <string.h>
83 #include <err.h>
84 #ifdef sgi
85 #include <bstring.h>
86 #include <getopt.h>
87 #include <sys/prctl.h>
88 #ifndef PRE_KUDZU
89 #include <cap_net.h>
90 #else
91 #define cap_socket socket
92 #endif
93 #else
94 #define cap_socket socket
95 #include <err.h>
96 #endif
97 
98 #include <netinet/in_systm.h>
99 #include <netinet/in.h>
100 #include <netinet/ip.h>
101 #include <netinet/ip_icmp.h>
102 #include <netinet/ip_var.h>
103 #include <arpa/inet.h>
104 #include <ctype.h>
105 #include <netdb.h>
106 
107 #ifdef IPSEC
108 #include <netinet6/ipsec.h>
109 #endif /*IPSEC*/
110 
111 #define FLOOD_INTVL	0.01		/* default flood output interval */
112 #define	MAXPACKET	(IP_MAXPACKET-60-8)	/* max packet size */
113 
114 #define F_VERBOSE	0x0001
115 #define F_QUIET		0x0002		/* minimize all output */
116 #define F_SEMI_QUIET	0x0004		/* ignore our ICMP errors */
117 #define F_FLOOD		0x0008		/* flood-ping */
118 #define	F_RECORD_ROUTE	0x0010		/* record route */
119 #define F_SOURCE_ROUTE	0x0020		/* loose source route */
120 #define F_PING_FILLED	0x0040		/* is buffer filled with user data? */
121 #define F_PING_RANDOM	0x0080		/* use random data */
122 #define	F_NUMERIC	0x0100		/* do not do gethostbyaddr() calls */
123 #define F_TIMING	0x0200		/* room for a timestamp */
124 #define F_DF		0x0400		/* set IP DF bit */
125 #define F_SOURCE_ADDR	0x0800		/* set source IP address/interface */
126 #define F_ONCE		0x1000		/* exit(0) after receiving 1 reply */
127 #define F_MCAST		0x2000		/* multicast target */
128 #define F_MCAST_NOLOOP	0x4000		/* no multicast loopback */
129 #define F_AUDIBLE	0x8000		/* audible output */
130 #ifdef IPSEC
131 #ifdef IPSEC_POLICY_IPSEC
132 #define F_POLICY	0x10000
133 #else
134 #define	F_AUTHHDR	0x10000
135 #define	F_ENCRYPT	0x20000
136 #endif /*IPSEC_POLICY_IPSEC*/
137 #endif /*IPSEC*/
138 
139 
140 /* MAX_DUP_CHK is the number of bits in received table, the
141  *	maximum number of received sequence numbers we can track to check
142  *	for duplicates.
143  */
144 #define MAX_DUP_CHK     (8 * 2048)
145 u_char	rcvd_tbl[MAX_DUP_CHK/8];
146 int     nrepeats = 0;
147 #define A(seq)	rcvd_tbl[(seq/8)%sizeof(rcvd_tbl)]  /* byte in array */
148 #define B(seq)	(1 << (seq & 0x07))	/* bit in byte */
149 #define SET(seq) (A(seq) |= B(seq))
150 #define CLR(seq) (A(seq) &= (~B(seq)))
151 #define TST(seq) (A(seq) & B(seq))
152 
153 
154 
155 u_char	*packet;
156 int	packlen;
157 int	pingflags = 0, options;
158 char	*fill_pat;
159 
160 int s;					/* Socket file descriptor */
161 int sloop;				/* Socket file descriptor/loopback */
162 
163 #define PHDR_LEN sizeof(struct timeval)	/* size of timestamp header */
164 struct sockaddr_in whereto, send_addr;	/* Who to ping */
165 struct sockaddr_in src_addr;		/* from where */
166 struct sockaddr_in loc_addr;		/* 127.1 */
167 int datalen = 64-PHDR_LEN;		/* How much data */
168 
169 #ifndef __NetBSD__
170 static char *progname;
171 #define	getprogname()		(progname)
172 #define	setprogname(name)	((void)(progname = (name)))
173 #endif
174 
175 char hostname[MAXHOSTNAMELEN];
176 
177 static struct {
178 	struct ip	o_ip;
179 	char		o_opt[MAX_IPOPTLEN];
180 	union {
181 		u_char	    u_buf[MAXPACKET+offsetof(struct icmp, icmp_data)];
182 		struct icmp u_icmp;
183 	} o_u;
184 } out_pack;
185 #define	opack_icmp	out_pack.o_u.u_icmp
186 struct ip *opack_ip;
187 
188 char optspace[MAX_IPOPTLEN];		/* record route space */
189 int optlen;
190 
191 
192 int npackets;				/* total packets to send */
193 int preload;				/* number of packets to "preload" */
194 int ntransmitted;			/* output sequence # = #sent */
195 int ident;				/* our ID, in network byte order */
196 
197 int nreceived;				/* # of packets we got back */
198 
199 double interval;			/* interval between packets */
200 struct timeval interval_tv;
201 double tmin = 999999999.0;
202 double tmax = 0.0;
203 double tsum = 0.0;			/* sum of all times */
204 double tsumsq = 0.0;
205 double maxwait = 0.0;
206 
207 #ifdef SIGINFO
208 int reset_kerninfo;
209 #endif
210 
211 int bufspace = IP_MAXPACKET;
212 
213 struct timeval now, clear_cache, last_tx, next_tx, first_tx;
214 struct timeval last_rx, first_rx;
215 int lastrcvd = 1;			/* last ping sent has been received */
216 
217 static struct timeval jiggle_time;
218 static int jiggle_cnt, total_jiggled, jiggle_direction = -1;
219 
220 static void doit(void);
221 static void prefinish(int);
222 static void prtsig(int);
223 static void finish(int);
224 static void summary(int);
225 static void pinger(void);
226 static void fill(void);
227 static void rnd_fill(void);
228 static double diffsec(struct timeval *, struct timeval *);
229 static void timevaladd(struct timeval *, struct timeval *);
230 static void sec_to_timeval(const double, struct timeval *);
231 static double timeval_to_sec(const struct timeval *);
232 static void pr_pack(u_char *, int, struct sockaddr_in *);
233 static u_short in_cksum(u_short *, u_int);
234 static void pr_saddr(u_char *);
235 static char *pr_addr(struct in_addr *);
236 static void pr_iph(struct icmp *, int);
237 static void pr_retip(struct icmp *, int);
238 static int pr_icmph(struct icmp *, struct sockaddr_in *, int);
239 static void jiggle(int), jiggle_flush(int);
240 static void gethost(const char *, const char *,
241 		    struct sockaddr_in *, char *, int);
242 static void usage(void);
243 
244 
245 int
246 main(int argc, char *argv[])
247 {
248 	int c, i, on = 1, hostind = 0;
249 	long l;
250 	u_char ttl = 0;
251 	u_long tos = 0;
252 	char *p;
253 #ifdef SIGINFO
254 	struct termios ts;
255 #endif
256 #ifdef IPSEC
257 #ifdef IPSEC_POLICY_IPSEC
258 	char *policy_in = NULL;
259 	char *policy_out = NULL;
260 #endif
261 #endif
262 
263 
264 	setprogname(argv[0]);
265 
266 #ifndef IPSEC
267 #define IPSECOPT
268 #else
269 #ifdef IPSEC_POLICY_IPSEC
270 #define IPSECOPT	"E:"
271 #else
272 #define IPSECOPT	"AE"
273 #endif /*IPSEC_POLICY_IPSEC*/
274 #endif
275 	while ((c = getopt(argc, argv,
276 			   "ac:dDfg:h:i:I:l:Lnop:PqQrRs:t:T:vw:" IPSECOPT)) != -1) {
277 #undef IPSECOPT
278 		switch (c) {
279 		case 'a':
280 			pingflags |= F_AUDIBLE;
281 			break;
282 		case 'c':
283 			npackets = strtol(optarg, &p, 0);
284 			if (*p != '\0' || npackets <= 0)
285 				errx(1, "Bad/invalid number of packets");
286 			break;
287 		case 'D':
288 			pingflags |= F_DF;
289 			break;
290 		case 'd':
291 			options |= SO_DEBUG;
292 			break;
293 		case 'f':
294 			pingflags |= F_FLOOD;
295 			break;
296 		case 'h':
297 			hostind = optind-1;
298 			break;
299 		case 'i':		/* wait between sending packets */
300 			interval = strtod(optarg, &p);
301 			if (*p != '\0' || interval <= 0)
302 				errx(1, "Bad/invalid interval %s", optarg);
303 			break;
304 		case 'l':
305 			preload = strtol(optarg, &p, 0);
306 			if (*p != '\0' || preload < 0)
307 				errx(1, "Bad/invalid preload value %s",
308 				     optarg);
309 			break;
310 		case 'n':
311 			pingflags |= F_NUMERIC;
312 			break;
313 		case 'o':
314 			pingflags |= F_ONCE;
315 			break;
316 		case 'p':		/* fill buffer with user pattern */
317 			if (pingflags & F_PING_RANDOM)
318 				errx(1, "Only one of -P and -p allowed");
319 			pingflags |= F_PING_FILLED;
320 			fill_pat = optarg;
321 			break;
322 		case 'P':
323 			if (pingflags & F_PING_FILLED)
324 				errx(1, "Only one of -P and -p allowed");
325 			pingflags |= F_PING_RANDOM;
326 			break;
327 		case 'q':
328 			pingflags |= F_QUIET;
329 			break;
330 		case 'Q':
331 			pingflags |= F_SEMI_QUIET;
332 			break;
333 		case 'r':
334 			options |= SO_DONTROUTE;
335 			break;
336 		case 's':		/* size of packet to send */
337 			datalen = strtol(optarg, &p, 0);
338 			if (*p != '\0' || datalen <= 0)
339 				errx(1, "Bad/invalid packet size %s", optarg);
340 			if (datalen > MAXPACKET)
341 				errx(1, "packet size is too large");
342 			break;
343 		case 'v':
344 			pingflags |= F_VERBOSE;
345 			break;
346 		case 'R':
347 			pingflags |= F_RECORD_ROUTE;
348 			break;
349 		case 'L':
350 			pingflags |= F_MCAST_NOLOOP;
351 			break;
352 		case 't':
353 			tos = strtoul(optarg, &p, 0);
354 			if (*p != '\0' ||  tos > 0xFF)
355 				errx(1, "bad tos value: %s", optarg);
356 			break;
357 		case 'T':
358 			l = strtol(optarg, &p, 0);
359 			if (*p != '\0' || l > 255 || l <= 0)
360 				errx(1, "ttl out of range");
361 			ttl = (u_char)l;    /* cannot check >255 otherwise */
362 			break;
363 		case 'I':
364 			pingflags |= F_SOURCE_ADDR;
365 			gethost("-I", optarg, &src_addr, 0, 0);
366 			break;
367 		case 'g':
368 			pingflags |= F_SOURCE_ROUTE;
369 			gethost("-g", optarg, &send_addr, 0, 0);
370 			break;
371 		case 'w':
372 			maxwait = strtod(optarg, &p);
373 			if (*p != '\0' || maxwait <= 0)
374 				errx(1, "Bad/invalid maxwait time %s", optarg);
375 			break;
376 #ifdef IPSEC
377 #ifdef IPSEC_POLICY_IPSEC
378 		case 'E':
379 			pingflags |= F_POLICY;
380 			if (!strncmp("in", optarg, 2))
381 				policy_in = strdup(optarg);
382 			else if (!strncmp("out", optarg, 3))
383 				policy_out = strdup(optarg);
384 			else
385 				errx(1, "invalid security policy");
386 			break;
387 #else
388 		case 'A':
389 			pingflags |= F_AUTHHDR;
390 			break;
391 		case 'E':
392 			pingflags |= F_ENCRYPT;
393 			break;
394 #endif /*IPSEC_POLICY_IPSEC*/
395 #endif /*IPSEC*/
396 		default:
397 			usage();
398 			break;
399 		}
400 	}
401 
402 	if (interval == 0)
403 		interval = (pingflags & F_FLOOD) ? FLOOD_INTVL : 1.0;
404 #ifndef sgi
405 	if (pingflags & F_FLOOD && getuid())
406 		errx(1, "Must be superuser to use -f");
407 	if (interval < 1.0 && getuid())
408 		errx(1, "Must be superuser to use < 1 sec ping interval");
409 	if (preload > 0 && getuid())
410 		errx(1, "Must be superuser to use -l");
411 #endif
412 	sec_to_timeval(interval, &interval_tv);
413 
414 	if ((pingflags & (F_AUDIBLE|F_FLOOD)) == (F_AUDIBLE|F_FLOOD))
415 		warnx("Sorry, no audible output for flood pings");
416 
417 	if (npackets != 0) {
418 		npackets += preload;
419 	} else {
420 		npackets = INT_MAX;
421 	}
422 
423 	if (hostind == 0) {
424 		if (optind != argc-1)
425 			usage();
426 		else
427 			hostind = optind;
428 	}
429 	else if (hostind >= argc - 1)
430 		usage();
431 
432 	gethost("", argv[hostind], &whereto, hostname, sizeof(hostname));
433 	if (IN_MULTICAST(ntohl(whereto.sin_addr.s_addr)))
434 		pingflags |= F_MCAST;
435 	if (!(pingflags & F_SOURCE_ROUTE))
436 		(void) memcpy(&send_addr, &whereto, sizeof(send_addr));
437 
438 	loc_addr.sin_family = AF_INET;
439 	loc_addr.sin_addr.s_addr = htonl((127<<24)+1);
440 
441 	if (datalen >= PHDR_LEN)	/* can we time them? */
442 		pingflags |= F_TIMING;
443 	packlen = datalen + 60 + 76;	/* MAXIP + MAXICMP */
444 	if ((packet = (u_char *)malloc(packlen)) == NULL)
445 		err(1, "Out of memory");
446 
447 	if (pingflags & F_PING_FILLED) {
448 		fill();
449 	} else if (pingflags & F_PING_RANDOM) {
450 		rnd_fill();
451 	} else {
452 		for (i = PHDR_LEN; i < datalen; i++)
453 			opack_icmp.icmp_data[i] = i;
454 	}
455 
456 	ident = htons(getpid()) & 0xFFFF;
457 
458 	if ((s = cap_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
459 		err(1, "Cannot create socket");
460 	if (options & SO_DEBUG) {
461 		if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
462 			       (char *)&on, sizeof(on)) == -1)
463 			warn("Can't turn on socket debugging");
464 	}
465 	if (options & SO_DONTROUTE) {
466 		if (setsockopt(s, SOL_SOCKET, SO_DONTROUTE,
467 			       (char *)&on, sizeof(on)) == -1)
468 			warn("SO_DONTROUTE");
469 	}
470 
471 	if ((sloop = cap_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
472 		err(1, "Cannot create socket");
473 	if (options & SO_DEBUG) {
474 		if (setsockopt(sloop, SOL_SOCKET, SO_DEBUG,
475 			       (char *)&on, sizeof(on)) == -1)
476 			warn("Can't turn on socket debugging");
477 	}
478 	if (options & SO_DONTROUTE) {
479 		if (setsockopt(sloop, SOL_SOCKET, SO_DONTROUTE,
480 			       (char *)&on, sizeof(on)) == -1)
481 			warn("SO_DONTROUTE");
482 	}
483 
484 	if (pingflags & F_SOURCE_ROUTE) {
485 		optspace[IPOPT_OPTVAL] = IPOPT_LSRR;
486 		optspace[IPOPT_OLEN] = optlen = 7;
487 		optspace[IPOPT_OFFSET] = IPOPT_MINOFF;
488 		(void)memcpy(&optspace[IPOPT_MINOFF-1], &whereto.sin_addr,
489 			     sizeof(whereto.sin_addr));
490 		optspace[optlen++] = IPOPT_NOP;
491 	}
492 	if (pingflags & F_RECORD_ROUTE) {
493 		optspace[optlen+IPOPT_OPTVAL] = IPOPT_RR;
494 		optspace[optlen+IPOPT_OLEN] = (MAX_IPOPTLEN -1-optlen);
495 		optspace[optlen+IPOPT_OFFSET] = IPOPT_MINOFF;
496 		optlen = MAX_IPOPTLEN;
497 	}
498 	/* this leaves opack_ip 0(mod 4) aligned */
499 	opack_ip = (struct ip *)((char *)&out_pack.o_ip
500 				 + sizeof(out_pack.o_opt)
501 				 - optlen);
502 	(void) memcpy(opack_ip + 1, optspace, optlen);
503 
504 	if (setsockopt(s,IPPROTO_IP,IP_HDRINCL, (char *) &on, sizeof(on)) < 0)
505 		err(1, "Can't set special IP header");
506 
507 	opack_ip->ip_v = IPVERSION;
508 	opack_ip->ip_hl = (sizeof(struct ip)+optlen) >> 2;
509 	opack_ip->ip_tos = tos;
510 	opack_ip->ip_off = (pingflags & F_DF) ? IP_DF : 0;
511 	opack_ip->ip_ttl = ttl ? ttl : MAXTTL;
512 	opack_ip->ip_p = IPPROTO_ICMP;
513 	opack_ip->ip_src = src_addr.sin_addr;
514 	opack_ip->ip_dst = send_addr.sin_addr;
515 
516 	if (pingflags & F_MCAST) {
517 		if (pingflags & F_MCAST_NOLOOP) {
518 			u_char loop = 0;
519 			if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP,
520 			    (char *) &loop, 1) < 0)
521 				err(1, "Can't disable multicast loopback");
522 		}
523 
524 		if (ttl != 0
525 		    && setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
526 		    (char *) &ttl, 1) < 0)
527 			err(1, "Can't set multicast time-to-live");
528 
529 		if ((pingflags & F_SOURCE_ADDR)
530 		    && setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
531 				  (char *) &src_addr.sin_addr,
532 				  sizeof(src_addr.sin_addr)) < 0)
533 			err(1, "Can't set multicast source interface");
534 
535 	} else if (pingflags & F_SOURCE_ADDR) {
536 		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
537 			       (char *) &src_addr.sin_addr,
538 			       sizeof(src_addr.sin_addr)) < 0)
539 			err(1, "Can't set source interface/address");
540 	}
541 #ifdef IPSEC
542 #ifdef IPSEC_POLICY_IPSEC
543     {
544 	char *buf;
545 	if (pingflags & F_POLICY) {
546 		if (policy_in != NULL) {
547 			buf = ipsec_set_policy(policy_in, strlen(policy_in));
548 			if (buf == NULL)
549 				errx(1, "%s", ipsec_strerror());
550 			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
551 					buf, ipsec_get_policylen(buf)) < 0) {
552 				err(1, "ipsec policy cannot be configured");
553 			}
554 			free(buf);
555 		}
556 		if (policy_out != NULL) {
557 			buf = ipsec_set_policy(policy_out, strlen(policy_out));
558 			if (buf == NULL)
559 				errx(1, "%s", ipsec_strerror());
560 			if (setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY,
561 					buf, ipsec_get_policylen(buf)) < 0) {
562 				err(1, "ipsec policy cannot be configured");
563 			}
564 			free(buf);
565 		}
566 	}
567 	buf = ipsec_set_policy("out bypass", strlen("out bypass"));
568 	if (buf == NULL)
569 		errx(1, "%s", ipsec_strerror());
570 	if (setsockopt(sloop, IPPROTO_IP, IP_IPSEC_POLICY,
571 			buf, ipsec_get_policylen(buf)) < 0) {
572 #if 0
573 		warnx("ipsec is not configured");
574 #else
575 		/* ignore it, should be okay */
576 #endif
577 	}
578 	free(buf);
579     }
580 #else
581     {
582 	int optval;
583 	if (pingflags & F_AUTHHDR) {
584 		optval = IPSEC_LEVEL_REQUIRE;
585 #ifdef IP_AUTH_TRANS_LEVEL
586 		(void)setsockopt(s, IPPROTO_IP, IP_AUTH_TRANS_LEVEL,
587 			(char *)&optval, sizeof(optval));
588 #else
589 		(void)setsockopt(s, IPPROTO_IP, IP_AUTH_LEVEL,
590 			(char *)&optval, sizeof(optval));
591 #endif
592 	}
593 	if (pingflags & F_ENCRYPT) {
594 		optval = IPSEC_LEVEL_REQUIRE;
595 		(void)setsockopt(s, IPPROTO_IP, IP_ESP_TRANS_LEVEL,
596 			(char *)&optval, sizeof(optval));
597 	}
598 	optval = IPSEC_LEVEL_BYPASS;
599 #ifdef IP_AUTH_TRANS_LEVEL
600 	(void)setsockopt(sloop, IPPROTO_IP, IP_AUTH_TRANS_LEVEL,
601 		(char *)&optval, sizeof(optval));
602 #else
603 	(void)setsockopt(sloop, IPPROTO_IP, IP_AUTH_LEVEL,
604 		(char *)&optval, sizeof(optval));
605 #endif
606 	(void)setsockopt(sloop, IPPROTO_IP, IP_ESP_TRANS_LEVEL,
607 		(char *)&optval, sizeof(optval));
608     }
609 #endif /*IPSEC_POLICY_IPSEC*/
610 #endif /*IPSEC*/
611 
612 	(void)printf("PING %s (%s): %d data bytes\n", hostname,
613 		     inet_ntoa(whereto.sin_addr), datalen);
614 
615 	/* When pinging the broadcast address, you can get a lot
616 	 * of answers.  Doing something so evil is useful if you
617 	 * are trying to stress the ethernet, or just want to
618 	 * fill the arp cache to get some stuff for /etc/ethers.
619 	 */
620 	while (0 > setsockopt(s, SOL_SOCKET, SO_RCVBUF,
621 			      (char*)&bufspace, sizeof(bufspace))) {
622 		if ((bufspace -= 4096) <= 0)
623 			err(1, "Cannot set the receive buffer size");
624 	}
625 
626 	/* make it possible to send giant probes, but do not worry now
627 	 * if it fails, since we probably won't send giant probes.
628 	 */
629 	(void)setsockopt(s, SOL_SOCKET, SO_SNDBUF,
630 			 (char*)&bufspace, sizeof(bufspace));
631 
632 	(void)signal(SIGINT, prefinish);
633 
634 #if defined(SIGINFO) && defined(NOKERNINFO)
635 	if (tcgetattr (0, &ts) != -1) {
636 		reset_kerninfo = !(ts.c_lflag & NOKERNINFO);
637 		ts.c_lflag |= NOKERNINFO;
638 		tcsetattr (STDIN_FILENO, TCSANOW, &ts);
639 	}
640 #endif
641 
642 #ifdef SIGINFO
643 	(void)signal(SIGINFO, prtsig);
644 #else
645 	(void)signal(SIGQUIT, prtsig);
646 #endif
647 	(void)signal(SIGCONT, prtsig);
648 
649 	/* fire off them quickies */
650 	for (i = 0; i < preload; i++) {
651 		(void)gettimeofday(&now, 0);
652 		pinger();
653 	}
654 
655 	doit();
656 	return 0;
657 }
658 
659 
660 static void
661 doit(void)
662 {
663 	int cc;
664 	struct sockaddr_in from;
665 	int fromlen;
666 	double sec, last, d_last;
667 	struct timeval timeout;
668 	fd_set *fdmaskp;
669 	size_t nfdmask;
670 
671 	(void)gettimeofday(&clear_cache,0);
672 	if (maxwait != 0) {
673 		last = timeval_to_sec(&clear_cache) + maxwait;
674 		d_last = 0;
675 	} else {
676 		last = 0;
677 		d_last = 365*24*60*60;
678 	}
679 
680 	nfdmask = howmany(s + 1, NFDBITS) * sizeof(fd_mask);
681 	if ((fdmaskp = malloc(nfdmask)) == NULL)
682 		err(1, "malloc");
683 	memset(fdmaskp, 0, nfdmask);
684 	do {
685 		(void)gettimeofday(&now,0);
686 
687 		if (last != 0)
688 			d_last = last - timeval_to_sec(&now);
689 
690 		if (ntransmitted < npackets && d_last > 0) {
691 			/* send if within 100 usec or late for next packet */
692 			sec = diffsec(&next_tx,&now);
693 			if (sec <= 0.0001
694 			    || (lastrcvd && (pingflags & F_FLOOD))) {
695 				pinger();
696 				sec = diffsec(&next_tx,&now);
697 			}
698 			if (sec < 0.0)
699 				sec = 0.0;
700 			if (d_last < sec)
701 				sec = d_last;
702 
703 		} else {
704 			/* For the last response, wait twice as long as the
705 			 * worst case seen, or 10 times as long as the
706 			 * maximum interpacket interval, whichever is longer.
707 			 */
708 			sec = MAX(2*tmax,10*interval) - diffsec(&now,&last_tx);
709 			if (d_last < sec)
710 				sec = d_last;
711 			if (sec <= 0)
712 				break;
713 		}
714 
715 
716 		sec_to_timeval(sec, &timeout);
717 
718 		FD_SET(s, fdmaskp);
719 		cc = select(s+1, fdmaskp, 0, 0, &timeout);
720 		if (cc <= 0) {
721 			if (cc < 0) {
722 				if (errno == EINTR)
723 					continue;
724 				jiggle_flush(1);
725 				err(1, "select");
726 			}
727 			continue;
728 		}
729 
730 		fromlen  = sizeof(from);
731 		cc = recvfrom(s, (char *) packet, packlen,
732 			      0, (struct sockaddr *)&from,
733 			      &fromlen);
734 		if (cc < 0) {
735 			if (errno != EINTR) {
736 				jiggle_flush(1);
737 				warn("recvfrom");
738 				(void)fflush(stderr);
739 			}
740 			continue;
741 		}
742 		(void)gettimeofday(&now, 0);
743 		pr_pack(packet, cc, &from);
744 
745 	} while (nreceived < npackets
746 		 && (nreceived == 0 || !(pingflags & F_ONCE)));
747 	free(fdmaskp);
748 
749 	finish(0);
750 }
751 
752 
753 static void
754 jiggle_flush(int nl)			/* new line if there are dots */
755 {
756 	int serrno = errno;
757 
758 	if (jiggle_cnt > 0) {
759 		total_jiggled += jiggle_cnt;
760 		jiggle_direction = 1;
761 		do {
762 			(void)putchar('.');
763 		} while (--jiggle_cnt > 0);
764 
765 	} else if (jiggle_cnt < 0) {
766 		total_jiggled -= jiggle_cnt;
767 		jiggle_direction = -1;
768 		do {
769 			(void)putchar('\b');
770 		} while (++jiggle_cnt < 0);
771 	}
772 
773 	if (nl) {
774 		if (total_jiggled != 0)
775 			(void)putchar('\n');
776 		total_jiggled = 0;
777 		jiggle_direction = -1;
778 	}
779 
780 	(void)fflush(stdout);
781 	(void)fflush(stderr);
782 	jiggle_time = now;
783 	errno = serrno;
784 }
785 
786 
787 /* jiggle the cursor for flood-ping
788  */
789 static void
790 jiggle(int delta)
791 {
792 	double dt;
793 
794 	if (pingflags & F_QUIET)
795 		return;
796 
797 	/* do not back up into messages */
798 	if (total_jiggled+jiggle_cnt+delta < 0)
799 		return;
800 
801 	jiggle_cnt += delta;
802 
803 	/* flush the FLOOD dots when things are quiet
804 	 * or occassionally to make the cursor jiggle.
805 	 */
806 	dt = diffsec(&last_tx, &jiggle_time);
807 	if (dt > 0.2 || (dt >= 0.15 && delta*jiggle_direction < 0))
808 		jiggle_flush(0);
809 }
810 
811 
812 /*
813  * Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
814  * will be added on by the kernel.  The ID field is our UNIX process ID,
815  * and the sequence number is an ascending integer.  The first PHDR_LEN bytes
816  * of the data portion are used to hold a UNIX "timeval" struct in VAX
817  * byte-order, to compute the round-trip time.
818  */
819 static void
820 pinger(void)
821 {
822 	int i, cc, sw;
823 
824 	opack_icmp.icmp_code = 0;
825 	opack_icmp.icmp_seq = htons((u_short)(ntransmitted));
826 
827 	/* clear the cached route in the kernel after an ICMP
828 	 * response such as a Redirect is seen to stop causing
829 	 * more such packets.  Also clear the cached route
830 	 * periodically in case of routing changes that make
831 	 * black holes come and go.
832 	 */
833 	if (clear_cache.tv_sec != now.tv_sec) {
834 		opack_icmp.icmp_type = ICMP_ECHOREPLY;
835 		opack_icmp.icmp_id = ~ident;
836 		opack_icmp.icmp_cksum = 0;
837 		opack_icmp.icmp_cksum = in_cksum((u_short*)&opack_icmp,
838 						 PHDR_LEN);
839 		sw = 0;
840 		if (setsockopt(sloop,IPPROTO_IP,IP_HDRINCL,
841 			       (char *)&sw,sizeof(sw)) < 0)
842 			err(1, "Can't turn off special IP header");
843 		if (sendto(sloop, (char *) &opack_icmp, PHDR_LEN, MSG_DONTROUTE,
844 			   (struct sockaddr *)&loc_addr,
845 			   sizeof(struct sockaddr_in)) < 0) {
846 			/*
847 			 * XXX: we only report this as a warning in verbose
848 			 * mode because people get confused when they see
849 			 * this error when they are running in single user
850 			 * mode and they have not configured lo0
851 			 */
852 			if (pingflags & F_VERBOSE)
853 				warn("failed to clear cached route");
854 		}
855 		sw = 1;
856 		if (setsockopt(sloop,IPPROTO_IP,IP_HDRINCL,
857 			       (char *)&sw, sizeof(sw)) < 0)
858 			err(1, "Can't set special IP header");
859 
860 		(void)gettimeofday(&clear_cache,0);
861 	}
862 
863 	opack_icmp.icmp_type = ICMP_ECHO;
864 	opack_icmp.icmp_id = ident;
865 	if (pingflags & F_TIMING)
866 		(void) memcpy(&opack_icmp.icmp_data[0], &now, sizeof(now));
867 	cc = datalen+PHDR_LEN;
868 	opack_icmp.icmp_cksum = 0;
869 	opack_icmp.icmp_cksum = in_cksum((u_short*)&opack_icmp, cc);
870 
871 	cc += opack_ip->ip_hl<<2;
872 	opack_ip->ip_len = cc;
873 	i = sendto(s, (char *) opack_ip, cc, 0,
874 		   (struct sockaddr *)&send_addr, sizeof(struct sockaddr_in));
875 	if (i != cc) {
876 		jiggle_flush(1);
877 		if (i < 0)
878 			warn("sendto");
879 		else
880 			warnx("wrote %s %d chars, ret=%d", hostname, cc, i);
881 		(void)fflush(stderr);
882 	}
883 	lastrcvd = 0;
884 
885 	CLR(ntransmitted);
886 	ntransmitted++;
887 
888 	last_tx = now;
889 	if (next_tx.tv_sec == 0) {
890 		first_tx = now;
891 		next_tx = now;
892 	}
893 
894 	/* Transmit regularly, at always the same microsecond in the
895 	 * second when going at one packet per second.
896 	 * If we are at most 100 ms behind, send extras to get caught up.
897 	 * Otherwise, skip packets we were too slow to send.
898 	 */
899 	if (diffsec(&next_tx, &now) <= interval) {
900 		do {
901 			timevaladd(&next_tx, &interval_tv);
902 		} while (diffsec(&next_tx, &now) < -0.1);
903 	}
904 
905 	if (pingflags & F_FLOOD)
906 		jiggle(1);
907 
908 	/* While the packet is going out, ready buffer for the next
909 	 * packet. Use a fast but not very good random number generator.
910 	 */
911 	if (pingflags & F_PING_RANDOM)
912 		rnd_fill();
913 }
914 
915 
916 static void
917 pr_pack_sub(int cc,
918 	    char *addr,
919 	    int seqno,
920 	    int dupflag,
921 	    int ttl,
922 	    double triptime)
923 {
924 	jiggle_flush(1);
925 
926 	if (pingflags & F_FLOOD)
927 		return;
928 
929 	(void)printf("%d bytes from %s: icmp_seq=%u", cc, addr, seqno);
930 	if (dupflag)
931 		(void)printf(" DUP!");
932 	(void)printf(" ttl=%d", ttl);
933 	if (pingflags & F_TIMING)
934 		(void)printf(" time=%.3f ms", triptime*1000.0);
935 
936 	/*
937 	 * Send beep to stderr, since that's more likely than stdout
938 	 * to go to a terminal..
939 	 */
940 	if (pingflags & F_AUDIBLE && !dupflag)
941 		(void)fprintf(stderr,"\a");
942 }
943 
944 
945 /*
946  * Print out the packet, if it came from us.  This logic is necessary
947  * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
948  * which arrive ('tis only fair).  This permits multiple copies of this
949  * program to be run without having intermingled output (or statistics!).
950  */
951 static void
952 pr_pack(u_char *buf,
953 	int tot_len,
954 	struct sockaddr_in *from)
955 {
956 	struct ip *ip;
957 	struct icmp *icp;
958 	int i, j, net_len;
959 	u_char *cp;
960 	static int old_rrlen;
961 	static char old_rr[MAX_IPOPTLEN];
962 	int hlen, dupflag = 0, dumped;
963 	double triptime = 0.0;
964 #define PR_PACK_SUB() {if (!dumped) {			\
965 	dumped = 1;					\
966 	pr_pack_sub(net_len, inet_ntoa(from->sin_addr),	\
967 		    ntohs((u_short)icp->icmp_seq),	\
968 		    dupflag, ip->ip_ttl, triptime);}}
969 
970 	/* Check the IP header */
971 	ip = (struct ip *) buf;
972 	hlen = ip->ip_hl << 2;
973 	if (tot_len < hlen + ICMP_MINLEN) {
974 		if (pingflags & F_VERBOSE) {
975 			jiggle_flush(1);
976 			(void)printf("packet too short (%d bytes) from %s\n",
977 				     tot_len, inet_ntoa(from->sin_addr));
978 		}
979 		return;
980 	}
981 
982 	/* Now the ICMP part */
983 	dumped = 0;
984 	net_len = tot_len - hlen;
985 	icp = (struct icmp *)(buf + hlen);
986 	if (icp->icmp_type == ICMP_ECHOREPLY
987 	    && icp->icmp_id == ident) {
988 		if (icp->icmp_seq == htons((u_short)(ntransmitted-1)))
989 			lastrcvd = 1;
990 		last_rx = now;
991 		if (first_rx.tv_sec == 0)
992 			first_rx = last_rx;
993 		nreceived++;
994 		if (pingflags & F_TIMING) {
995 			struct timeval tv;
996 			(void) memcpy(&tv, icp->icmp_data, sizeof(tv));
997 			triptime = diffsec(&last_rx, &tv);
998 			tsum += triptime;
999 			tsumsq += triptime * triptime;
1000 			if (triptime < tmin)
1001 				tmin = triptime;
1002 			if (triptime > tmax)
1003 				tmax = triptime;
1004 		}
1005 
1006 		if (TST(ntohs((u_short)icp->icmp_seq))) {
1007 			nrepeats++, nreceived--;
1008 			dupflag=1;
1009 		} else {
1010 			SET(ntohs((u_short)icp->icmp_seq));
1011 		}
1012 
1013 		if (tot_len != opack_ip->ip_len) {
1014 			PR_PACK_SUB();
1015 			(void)printf("\nwrong total length %d instead of %d",
1016 				     tot_len, opack_ip->ip_len);
1017 		}
1018 
1019 		if (pingflags & F_QUIET)
1020 			return;
1021 
1022 		if (!(pingflags & F_FLOOD))
1023 			PR_PACK_SUB();
1024 
1025 		/* check the data */
1026 		if (datalen > PHDR_LEN
1027 		    && !(pingflags & F_PING_RANDOM)
1028 		    && memcmp(&icp->icmp_data[PHDR_LEN],
1029 			    &opack_icmp.icmp_data[PHDR_LEN],
1030 			    datalen-PHDR_LEN)) {
1031 			for (i=PHDR_LEN; i<datalen; i++) {
1032 				if (icp->icmp_data[i] !=
1033 				    opack_icmp.icmp_data[i])
1034 					break;
1035 			}
1036 			PR_PACK_SUB();
1037 			(void)printf("\nwrong data byte #%d should have been"
1038 				     " %#x but was %#x", i,
1039 				     (u_char)opack_icmp.icmp_data[i],
1040 				     (u_char)icp->icmp_data[i]);
1041 			for (i=PHDR_LEN; i<datalen; i++) {
1042 				if ((i%16) == PHDR_LEN)
1043 					(void)printf("\n\t");
1044 				(void)printf("%2x ",(u_char)icp->icmp_data[i]);
1045 			}
1046 		}
1047 
1048 	} else {
1049 		if (!pr_icmph(icp, from, net_len))
1050 			return;
1051 		dumped = 2;
1052 	}
1053 
1054 	/* Display any IP options */
1055 	cp = buf + sizeof(struct ip);
1056 	while (hlen > (int)sizeof(struct ip)) {
1057 		switch (*cp) {
1058 		case IPOPT_EOL:
1059 			hlen = 0;
1060 			break;
1061 		case IPOPT_LSRR:
1062 			hlen -= 2;
1063 			j = *++cp;
1064 			++cp;
1065 			j -= IPOPT_MINOFF;
1066 			if (j <= 0)
1067 				continue;
1068 			if (dumped <= 1) {
1069 				j = ((j+3)/4)*4;
1070 				hlen -= j;
1071 				cp += j;
1072 				break;
1073 			}
1074 			PR_PACK_SUB();
1075 			(void)printf("\nLSRR: ");
1076 			for (;;) {
1077 				pr_saddr(cp);
1078 				cp += 4;
1079 				hlen -= 4;
1080 				j -= 4;
1081 				if (j <= 0)
1082 					break;
1083 				(void)putchar('\n');
1084 			}
1085 			break;
1086 		case IPOPT_RR:
1087 			j = *++cp;	/* get length */
1088 			i = *++cp;	/* and pointer */
1089 			hlen -= 2;
1090 			if (i > j)
1091 				i = j;
1092 			i -= IPOPT_MINOFF;
1093 			if (i <= 0)
1094 				continue;
1095 			if (dumped <= 1) {
1096 				if (i == old_rrlen
1097 				    && !memcmp(cp, old_rr, i)) {
1098 					if (dumped)
1099 					    (void)printf("\t(same route)");
1100 					j = ((i+3)/4)*4;
1101 					hlen -= j;
1102 					cp += j;
1103 					break;
1104 				}
1105 				old_rrlen = i;
1106 				(void) memcpy(old_rr, cp, i);
1107 			}
1108 			if (!dumped) {
1109 				jiggle_flush(1);
1110 				(void)printf("RR: ");
1111 				dumped = 1;
1112 			} else {
1113 				(void)printf("\nRR: ");
1114 			}
1115 			for (;;) {
1116 				pr_saddr(cp);
1117 				cp += 4;
1118 				hlen -= 4;
1119 				i -= 4;
1120 				if (i <= 0)
1121 					break;
1122 				(void)putchar('\n');
1123 			}
1124 			break;
1125 		case IPOPT_NOP:
1126 			if (dumped <= 1)
1127 				break;
1128 			PR_PACK_SUB();
1129 			(void)printf("\nNOP");
1130 			break;
1131 #ifdef sgi
1132 		case IPOPT_SECURITY:	/* RFC 1108 RIPSO BSO */
1133 		case IPOPT_ESO:		/* RFC 1108 RIPSO ESO */
1134 		case IPOPT_CIPSO:	/* Commercial IPSO */
1135 			if ((sysconf(_SC_IP_SECOPTS)) > 0) {
1136 				i = (unsigned)cp[1];
1137 				hlen -= i - 1;
1138 				PR_PACK_SUB();
1139 				(void)printf("\nSEC:");
1140 				while (i--) {
1141 					(void)printf(" %02x", *cp++);
1142 				}
1143 				cp--;
1144 				break;
1145 			}
1146 #endif
1147 		default:
1148 			PR_PACK_SUB();
1149 			(void)printf("\nunknown option 0x%x", *cp);
1150 			break;
1151 		}
1152 		hlen--;
1153 		cp++;
1154 	}
1155 
1156 	if (dumped) {
1157 		(void)putchar('\n');
1158 		(void)fflush(stdout);
1159 	} else {
1160 		jiggle(-1);
1161 	}
1162 }
1163 
1164 
1165 /* Compute the IP checksum
1166  *	This assumes the packet is less than 32K long.
1167  */
1168 static u_short
1169 in_cksum(u_short *p,
1170 	 u_int len)
1171 {
1172 	u_int sum = 0;
1173 	int nwords = len >> 1;
1174 
1175 	while (nwords-- != 0)
1176 		sum += *p++;
1177 
1178 	if (len & 1) {
1179 		union {
1180 			u_short w;
1181 			u_char c[2];
1182 		} u;
1183 		u.c[0] = *(u_char *)p;
1184 		u.c[1] = 0;
1185 		sum += u.w;
1186 	}
1187 
1188 	/* end-around-carry */
1189 	sum = (sum >> 16) + (sum & 0xffff);
1190 	sum += (sum >> 16);
1191 	return (~sum);
1192 }
1193 
1194 
1195 /*
1196  * compute the difference of two timevals in seconds
1197  */
1198 static double
1199 diffsec(struct timeval *timenow,
1200 	struct timeval *then)
1201 {
1202 	return ((timenow->tv_sec - then->tv_sec)*1.0
1203 		+ (timenow->tv_usec - then->tv_usec)/1000000.0);
1204 }
1205 
1206 
1207 static void
1208 timevaladd(struct timeval *t1,
1209 	   struct timeval *t2)
1210 {
1211 
1212 	t1->tv_sec += t2->tv_sec;
1213 	if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
1214 		t1->tv_sec++;
1215 		t1->tv_usec -= 1000000;
1216 	}
1217 }
1218 
1219 
1220 static void
1221 sec_to_timeval(const double sec, struct timeval *tp)
1222 {
1223 	tp->tv_sec = sec;
1224 	tp->tv_usec = (sec - tp->tv_sec) * 1000000.0;
1225 }
1226 
1227 
1228 static double
1229 timeval_to_sec(const struct timeval *tp)
1230 {
1231 	return tp->tv_sec + tp->tv_usec / 1000000.0;
1232 }
1233 
1234 
1235 /*
1236  * Print statistics.
1237  * Heavily buffered STDIO is used here, so that all the statistics
1238  * will be written with 1 sys-write call.  This is nice when more
1239  * than one copy of the program is running on a terminal;  it prevents
1240  * the statistics output from becomming intermingled.
1241  */
1242 static void
1243 summary(int header)
1244 {
1245 	jiggle_flush(1);
1246 
1247 	if (header)
1248 		(void)printf("\n----%s PING Statistics----\n", hostname);
1249 	(void)printf("%d packets transmitted, ", ntransmitted);
1250 	(void)printf("%d packets received, ", nreceived);
1251 	if (nrepeats)
1252 		(void)printf("+%d duplicates, ", nrepeats);
1253 	if (ntransmitted) {
1254 		if (nreceived > ntransmitted)
1255 			(void)printf("-- somebody's printing up packets!");
1256 		else
1257 			(void)printf("%.1f%% packet loss",
1258 				     (((ntransmitted-nreceived)*100.0) /
1259 					    ntransmitted));
1260 	}
1261 	(void)printf("\n");
1262 	if (nreceived && (pingflags & F_TIMING)) {
1263 		double n = nreceived + nrepeats;
1264 		double avg = (tsum / n);
1265 		double variance = 0.0;
1266 		if (n>1)
1267 			variance = (tsumsq - n*avg*avg) /(n-1);
1268 
1269 		printf("round-trip min/avg/max/stddev = "
1270 			"%.3f/%.3f/%.3f/%.3f ms\n",
1271 			tmin * 1000.0, avg * 1000.0,
1272 			tmax * 1000.0, sqrt(variance) * 1000.0);
1273 		if (pingflags & F_FLOOD) {
1274 			double r = diffsec(&last_rx, &first_rx);
1275 			double t = diffsec(&last_tx, &first_tx);
1276 			if (r == 0)
1277 				r = 0.0001;
1278 			if (t == 0)
1279 				t = 0.0001;
1280 			(void)printf("  %.1f packets/sec sent, "
1281 				     " %.1f packets/sec received\n",
1282 				     ntransmitted/t, nreceived/r);
1283 		}
1284 	}
1285 }
1286 
1287 
1288 /*
1289  * Print statistics when SIGINFO is received.
1290  */
1291 /* ARGSUSED */
1292 static void
1293 prtsig(int dummy)
1294 {
1295 	summary(0);
1296 #ifdef SIGINFO
1297 	(void)signal(SIGINFO, prtsig);
1298 #else
1299 	(void)signal(SIGQUIT, prtsig);
1300 #endif
1301 }
1302 
1303 
1304 /*
1305  * On the first SIGINT, allow any outstanding packets to dribble in
1306  */
1307 static void
1308 prefinish(int dummy)
1309 {
1310 	if (lastrcvd			/* quit now if caught up */
1311 	    || nreceived == 0)		/* or if remote is dead */
1312 		finish(0);
1313 
1314 	(void)signal(dummy, finish);	/* do this only the 1st time */
1315 
1316 	if (npackets > ntransmitted)	/* let the normal limit work */
1317 		npackets = ntransmitted;
1318 }
1319 
1320 
1321 /*
1322  * Print statistics and give up.
1323  */
1324 /* ARGSUSED */
1325 static void
1326 finish(int dummy)
1327 {
1328 #if defined(SIGINFO) && defined(NOKERNINFO)
1329 	struct termios ts;
1330 
1331 	if (reset_kerninfo && tcgetattr (0, &ts) != -1) {
1332 		ts.c_lflag &= ~NOKERNINFO;
1333 		tcsetattr (STDIN_FILENO, TCSANOW, &ts);
1334 	}
1335 	(void)signal(SIGINFO, SIG_IGN);
1336 #else
1337 	(void)signal(SIGQUIT, SIG_DFL);
1338 #endif
1339 
1340 	summary(1);
1341 	exit(nreceived > 0 ? 0 : 2);
1342 }
1343 
1344 
1345 static int				/* 0=do not print it */
1346 ck_pr_icmph(struct icmp *icp,
1347 	    struct sockaddr_in *from,
1348 	    int cc,
1349 	    int override)		/* 1=override VERBOSE if interesting */
1350 {
1351 	int	hlen;
1352 	struct ip ipb, *ip = &ipb;
1353 	struct icmp icp2b, *icp2 = &icp2b;
1354 	int res;
1355 
1356 	if (pingflags & F_VERBOSE) {
1357 		res = 1;
1358 		jiggle_flush(1);
1359 	} else {
1360 		res = 0;
1361 	}
1362 
1363 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1364 	hlen = ip->ip_hl << 2;
1365 	if (ip->ip_p == IPPROTO_ICMP
1366 	    && hlen + 6 <= cc) {
1367 		(void) memcpy(icp2, &icp->icmp_data[hlen], sizeof(*icp2));
1368 		if (icp2->icmp_id == ident) {
1369 			/* remember to clear route cached in kernel
1370 			 * if this non-Echo-Reply ICMP message was for one
1371 			 * of our packets.
1372 			 */
1373 			clear_cache.tv_sec = 0;
1374 
1375 			if (!res && override
1376 			    && (pingflags & (F_QUIET|F_SEMI_QUIET)) == 0) {
1377 				jiggle_flush(1);
1378 				(void)printf("%d bytes from %s: ",
1379 					     cc, pr_addr(&from->sin_addr));
1380 				res = 1;
1381 			}
1382 		}
1383 	}
1384 
1385 	return res;
1386 }
1387 
1388 
1389 /*
1390  *  Print a descriptive string about an ICMP header other than an echo reply.
1391  */
1392 static int				/* 0=printed nothing */
1393 pr_icmph(struct icmp *icp,
1394 	 struct sockaddr_in *from,
1395 	 int cc)
1396 {
1397 	switch (icp->icmp_type ) {
1398 	case ICMP_UNREACH:
1399 		if (!ck_pr_icmph(icp, from, cc, 1))
1400 			return 0;
1401 		switch (icp->icmp_code) {
1402 		case ICMP_UNREACH_NET:
1403 			(void)printf("Destination Net Unreachable");
1404 			break;
1405 		case ICMP_UNREACH_HOST:
1406 			(void)printf("Destination Host Unreachable");
1407 			break;
1408 		case ICMP_UNREACH_PROTOCOL:
1409 			(void)printf("Destination Protocol Unreachable");
1410 			break;
1411 		case ICMP_UNREACH_PORT:
1412 			(void)printf("Destination Port Unreachable");
1413 			break;
1414 		case ICMP_UNREACH_NEEDFRAG:
1415 			(void)printf("frag needed and DF set.  Next MTU=%d",
1416 			       ntohs(icp->icmp_nextmtu));
1417 			break;
1418 		case ICMP_UNREACH_SRCFAIL:
1419 			(void)printf("Source Route Failed");
1420 			break;
1421 		case ICMP_UNREACH_NET_UNKNOWN:
1422 			(void)printf("Unreachable unknown net");
1423 			break;
1424 		case ICMP_UNREACH_HOST_UNKNOWN:
1425 			(void)printf("Unreachable unknown host");
1426 			break;
1427 		case ICMP_UNREACH_ISOLATED:
1428 			(void)printf("Unreachable host isolated");
1429 			break;
1430 		case ICMP_UNREACH_NET_PROHIB:
1431 			(void)printf("Net prohibited access");
1432 			break;
1433 		case ICMP_UNREACH_HOST_PROHIB:
1434 			(void)printf("Host prohibited access");
1435 			break;
1436 		case ICMP_UNREACH_TOSNET:
1437 			(void)printf("Bad TOS for net");
1438 			break;
1439 		case ICMP_UNREACH_TOSHOST:
1440 			(void)printf("Bad TOS for host");
1441 			break;
1442 		case 13:
1443 			(void)printf("Communication prohibited");
1444 			break;
1445 		case 14:
1446 			(void)printf("Host precedence violation");
1447 			break;
1448 		case 15:
1449 			(void)printf("Precedence cutoff");
1450 			break;
1451 		default:
1452 			(void)printf("Bad Destination Unreachable Code: %d",
1453 				     icp->icmp_code);
1454 			break;
1455 		}
1456 		/* Print returned IP header information */
1457 		pr_retip(icp, cc);
1458 		break;
1459 
1460 	case ICMP_SOURCEQUENCH:
1461 		if (!ck_pr_icmph(icp, from, cc, 1))
1462 			return 0;
1463 		(void)printf("Source Quench");
1464 		pr_retip(icp, cc);
1465 		break;
1466 
1467 	case ICMP_REDIRECT:
1468 		if (!ck_pr_icmph(icp, from, cc, 1))
1469 			return 0;
1470 		switch (icp->icmp_code) {
1471 		case ICMP_REDIRECT_NET:
1472 			(void)printf("Redirect Network");
1473 			break;
1474 		case ICMP_REDIRECT_HOST:
1475 			(void)printf("Redirect Host");
1476 			break;
1477 		case ICMP_REDIRECT_TOSNET:
1478 			(void)printf("Redirect Type of Service and Network");
1479 			break;
1480 		case ICMP_REDIRECT_TOSHOST:
1481 			(void)printf("Redirect Type of Service and Host");
1482 			break;
1483 		default:
1484 			(void)printf("Redirect--Bad Code: %d", icp->icmp_code);
1485 			break;
1486 		}
1487 		(void)printf(" New router addr: %s",
1488 			     pr_addr(&icp->icmp_hun.ih_gwaddr));
1489 		pr_retip(icp, cc);
1490 		break;
1491 
1492 	case ICMP_ECHO:
1493 		if (!ck_pr_icmph(icp, from, cc, 0))
1494 			return 0;
1495 		(void)printf("Echo Request: ID=%d seq=%d",
1496 			     ntohs(icp->icmp_id), ntohs(icp->icmp_seq));
1497 		break;
1498 
1499 	case ICMP_ECHOREPLY:
1500 		/* displaying other's pings is too noisey */
1501 #if 0
1502 		if (!ck_pr_icmph(icp, from, cc, 0))
1503 			return 0;
1504 		(void)printf("Echo Reply: ID=%d seq=%d",
1505 			     ntohs(icp->icmp_id), ntohs(icp->icmp_seq));
1506 		break;
1507 #else
1508 		return 0;
1509 #endif
1510 
1511 	case ICMP_ROUTERADVERT:
1512 		if (!ck_pr_icmph(icp, from, cc, 0))
1513 			return 0;
1514 		(void)printf("Router Discovery Advert");
1515 		break;
1516 
1517 	case ICMP_ROUTERSOLICIT:
1518 		if (!ck_pr_icmph(icp, from, cc, 0))
1519 			return 0;
1520 		(void)printf("Router Discovery Solicit");
1521 		break;
1522 
1523 	case ICMP_TIMXCEED:
1524 		if (!ck_pr_icmph(icp, from, cc, 1))
1525 			return 0;
1526 		switch (icp->icmp_code ) {
1527 		case ICMP_TIMXCEED_INTRANS:
1528 			(void)printf("Time To Live exceeded");
1529 			break;
1530 		case ICMP_TIMXCEED_REASS:
1531 			(void)printf("Frag reassembly time exceeded");
1532 			break;
1533 		default:
1534 			(void)printf("Time exceeded, Bad Code: %d",
1535 				     icp->icmp_code);
1536 			break;
1537 		}
1538 		pr_retip(icp, cc);
1539 		break;
1540 
1541 	case ICMP_PARAMPROB:
1542 		if (!ck_pr_icmph(icp, from, cc, 1))
1543 			return 0;
1544 		(void)printf("Parameter problem: pointer = 0x%02x",
1545 			     icp->icmp_hun.ih_pptr);
1546 		pr_retip(icp, cc);
1547 		break;
1548 
1549 	case ICMP_TSTAMP:
1550 		if (!ck_pr_icmph(icp, from, cc, 0))
1551 			return 0;
1552 		(void)printf("Timestamp");
1553 		break;
1554 
1555 	case ICMP_TSTAMPREPLY:
1556 		if (!ck_pr_icmph(icp, from, cc, 0))
1557 			return 0;
1558 		(void)printf("Timestamp Reply");
1559 		break;
1560 
1561 	case ICMP_IREQ:
1562 		if (!ck_pr_icmph(icp, from, cc, 0))
1563 			return 0;
1564 		(void)printf("Information Request");
1565 		break;
1566 
1567 	case ICMP_IREQREPLY:
1568 		if (!ck_pr_icmph(icp, from, cc, 0))
1569 			return 0;
1570 		(void)printf("Information Reply");
1571 		break;
1572 
1573 	case ICMP_MASKREQ:
1574 		if (!ck_pr_icmph(icp, from, cc, 0))
1575 			return 0;
1576 		(void)printf("Address Mask Request");
1577 		break;
1578 
1579 	case ICMP_MASKREPLY:
1580 		if (!ck_pr_icmph(icp, from, cc, 0))
1581 			return 0;
1582 		(void)printf("Address Mask Reply");
1583 		break;
1584 
1585 	default:
1586 		if (!ck_pr_icmph(icp, from, cc, 0))
1587 			return 0;
1588 		(void)printf("Bad ICMP type: %d", icp->icmp_type);
1589 		if (pingflags & F_VERBOSE)
1590 			pr_iph(icp, cc);
1591 	}
1592 
1593 	return 1;
1594 }
1595 
1596 
1597 /*
1598  *  Print an IP header with options.
1599  */
1600 static void
1601 pr_iph(struct icmp *icp,
1602        int cc)
1603 {
1604 	int	hlen;
1605 	u_char	*cp;
1606 	struct ip ipb, *ip = &ipb;
1607 
1608 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1609 
1610 	hlen = ip->ip_hl << 2;
1611 	cp = (u_char *) &icp->icmp_data[20];	/* point to options */
1612 
1613 	(void)printf("\n Vr HL TOS  Len   ID Flg  off TTL Pro  cks      Src	     Dst\n");
1614 	(void)printf("  %1x  %1x  %02x %04x %04x",
1615 		     ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
1616 	(void)printf("   %1x %04x",
1617 		     ((ip->ip_off)&0xe000)>>13, (ip->ip_off)&0x1fff);
1618 	(void)printf("  %02x  %02x %04x",
1619 		     ip->ip_ttl, ip->ip_p, ip->ip_sum);
1620 	(void)printf(" %15s ",
1621 		     inet_ntoa(*(struct in_addr *)&ip->ip_src.s_addr));
1622 	(void)printf(" %s ", inet_ntoa(*(struct in_addr *)&ip->ip_dst.s_addr));
1623 	/* dump any option bytes */
1624 	while (hlen-- > 20 && cp < (u_char*)icp+cc) {
1625 		(void)printf("%02x", *cp++);
1626 	}
1627 }
1628 
1629 /*
1630  * Print an ASCII host address starting from a string of bytes.
1631  */
1632 static void
1633 pr_saddr(u_char *cp)
1634 {
1635 	n_long l;
1636 	struct in_addr addr;
1637 
1638 	l = (u_char)*++cp;
1639 	l = (l<<8) + (u_char)*++cp;
1640 	l = (l<<8) + (u_char)*++cp;
1641 	l = (l<<8) + (u_char)*++cp;
1642 	addr.s_addr = htonl(l);
1643 	(void)printf("\t%s", (l == 0) ? "0.0.0.0" : pr_addr(&addr));
1644 }
1645 
1646 
1647 /*
1648  *  Return an ASCII host address
1649  *  as a dotted quad and optionally with a hostname
1650  */
1651 static char *
1652 pr_addr(struct in_addr *addr)		/* in network order */
1653 {
1654 	struct	hostent	*hp;
1655 	static	char buf[MAXHOSTNAMELEN+4+16+1];
1656 
1657 	if ((pingflags & F_NUMERIC)
1658 	    || !(hp = gethostbyaddr((char *)addr, sizeof(*addr), AF_INET))) {
1659 		(void)snprintf(buf, sizeof(buf), "%s", inet_ntoa(*addr));
1660 	} else {
1661 		(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
1662 		    inet_ntoa(*addr));
1663 	}
1664 
1665 	return buf;
1666 }
1667 
1668 /*
1669  *  Dump some info on a returned (via ICMP) IP packet.
1670  */
1671 static void
1672 pr_retip(struct icmp *icp,
1673 	 int cc)
1674 {
1675 	int	hlen;
1676 	u_char	*cp;
1677 	struct ip ipb, *ip = &ipb;
1678 
1679 	(void) memcpy(ip, icp->icmp_data, sizeof(*ip));
1680 
1681 	if (pingflags & F_VERBOSE)
1682 		pr_iph(icp, cc);
1683 
1684 	hlen = ip->ip_hl << 2;
1685 	cp = (u_char *) &icp->icmp_data[hlen];
1686 
1687 	if (ip->ip_p == IPPROTO_TCP) {
1688 		if (pingflags & F_VERBOSE)
1689 			(void)printf("\n  TCP: from port %u, to port %u",
1690 				     (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3)));
1691 	} else if (ip->ip_p == IPPROTO_UDP) {
1692 		if (pingflags & F_VERBOSE)
1693 			(void)printf("\n  UDP: from port %u, to port %u",
1694 				     (*cp*256+*(cp+1)), (*(cp+2)*256+*(cp+3)));
1695 	} else if (ip->ip_p == IPPROTO_ICMP) {
1696 		struct icmp icp2;
1697 		(void) memcpy(&icp2, cp, sizeof(icp2));
1698 		if (icp2.icmp_type == ICMP_ECHO) {
1699 			if (pingflags & F_VERBOSE)
1700 				(void)printf("\n  ID=%u icmp_seq=%u",
1701 					     ntohs((u_short)icp2.icmp_id),
1702 					     ntohs((u_short)icp2.icmp_seq));
1703 			else
1704 				(void)printf(" for icmp_seq=%u",
1705 					     ntohs((u_short)icp2.icmp_seq));
1706 		}
1707 	}
1708 }
1709 
1710 static void
1711 fill(void)
1712 {
1713 	int i, j, k;
1714 	char *cp;
1715 	int pat[16];
1716 
1717 	for (cp = fill_pat; *cp != '\0'; cp++) {
1718 		if (!isxdigit((unsigned char)*cp))
1719 			break;
1720 	}
1721 	if (cp == fill_pat || *cp != '\0' || (cp-fill_pat) > 16*2) {
1722 		(void)fflush(stdout);
1723 		errx(1, "\"-p %s\": patterns must be specified with"
1724 		     " 1-32 hex digits\n",
1725 		     fill_pat);
1726 	}
1727 
1728 	i = sscanf(fill_pat,
1729 		   "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
1730 		    &pat[0], &pat[1], &pat[2], &pat[3],
1731 		    &pat[4], &pat[5], &pat[6], &pat[7],
1732 		    &pat[8], &pat[9], &pat[10], &pat[11],
1733 		    &pat[12], &pat[13], &pat[14], &pat[15]);
1734 
1735 	for (k=PHDR_LEN, j = 0; k <= datalen; k++) {
1736 		opack_icmp.icmp_data[k] = pat[j];
1737 		if (++j >= i)
1738 			j = 0;
1739 	}
1740 
1741 	if (!(pingflags & F_QUIET)) {
1742 		(void)printf("PATTERN: 0x");
1743 		for (j=0; j<i; j++)
1744 			(void)printf("%02x",
1745 				     (u_char)opack_icmp.icmp_data[PHDR_LEN+j]);
1746 		(void)printf("\n");
1747 	}
1748 
1749 }
1750 
1751 
1752 static void
1753 rnd_fill(void)
1754 {
1755 	static u_int32_t rnd;
1756 	int i;
1757 
1758 	for (i = PHDR_LEN; i < datalen; i++) {
1759 		rnd = (3141592621U * rnd + 663896637U);
1760 		opack_icmp.icmp_data[i] = rnd>>24;
1761 	}
1762 }
1763 
1764 
1765 static void
1766 gethost(const char *arg,
1767 	const char *name,
1768 	struct sockaddr_in *sa,
1769 	char *realname,
1770 	int realname_len)
1771 {
1772 	struct hostent *hp;
1773 
1774 	(void)memset(sa, 0, sizeof(*sa));
1775 	sa->sin_family = AF_INET;
1776 
1777 	/* If it is an IP address, try to convert it to a name to
1778 	 * have something nice to display.
1779 	 */
1780 	if (inet_aton(name, &sa->sin_addr) != 0) {
1781 		if (realname) {
1782 			if (pingflags & F_NUMERIC)
1783 				hp = 0;
1784 			else
1785 				hp = gethostbyaddr((char *)&sa->sin_addr,
1786 						   sizeof(sa->sin_addr),
1787 						   AF_INET);
1788 			(void)strncpy(realname, hp ? hp->h_name : name,
1789 				      realname_len);
1790 			realname[realname_len-1] = '\0';
1791 		}
1792 		return;
1793 	}
1794 
1795 	hp = gethostbyname(name);
1796 	if (!hp)
1797 		errx(1, "Cannot resolve \"%s\" (%s)",name,hstrerror(h_errno));
1798 
1799 	if (hp->h_addrtype != AF_INET)
1800 		errx(1, "%s only supported with IP", arg);
1801 
1802 	(void)memcpy(&sa->sin_addr, hp->h_addr, sizeof(sa->sin_addr));
1803 
1804 	if (realname) {
1805 		(void)strncpy(realname, hp->h_name, realname_len);
1806 		realname[realname_len-1] = '\0';
1807 	}
1808 }
1809 
1810 
1811 static void
1812 usage(void)
1813 {
1814 #ifdef IPSEC
1815 #ifdef IPSEC_POLICY_IPSEC
1816 #define IPSECOPT	"\n     [-E policy] "
1817 #else
1818 #define IPSECOPT	"\n     [-AE] "
1819 #endif /*IPSEC_POLICY_IPSEC*/
1820 #else
1821 #define IPSECOPT	""
1822 #endif /*IPSEC*/
1823 
1824 	(void)fprintf(stderr, "Usage: \n"
1825 	    "%s [-adDfLnoPqQrRv] [-c count] [-g gateway] [-h host]"
1826 	    " [-i interval] [-I addr]\n"
1827 	    "     [-l preload] [-p pattern] [-s size] [-t tos] [-T ttl]"
1828 	    " [-w maxwait] " IPSECOPT "host\n",
1829 	    getprogname());
1830 	exit(1);
1831 }
1832