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