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