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