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