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