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