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