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