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