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