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