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