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