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