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