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