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