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