1 /* vi: set sw=4 ts=4: */
3 * Mini ping implementation for busybox
5 * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
7 * Adapted from the ping in netkit-base 0.10:
8 * Copyright (c) 1989 The Regents of the University of California.
11 * This code is derived from software contributed to Berkeley by
14 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
17 * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
19 * This version of ping is adapted from the ping in netkit-base 0.10,
22 * Original copyright notice is retained at the end of this file.
24 * This version is an adaptation of ping.c from busybox.
25 * The code was modified by Bart Visscher <magick@linux-fan.com>
29 #include <netinet/ip_icmp.h>
33 #include <netinet/icmp6.h>
34 /* I see RENUMBERED constants in bits/in.h - !!?
35 * What a fuck is going on with libc? Is it a glibc joke? */
36 #ifdef IPV6_2292HOPLIMIT
38 #define IPV6_HOPLIMIT IPV6_2292HOPLIMIT
47 MAX_DUP_CHK = (8 * 128),
49 PINGINTERVAL = 1, /* 1 second */
54 static int in_cksum(unsigned short *buf, int sz)
58 unsigned short *w = buf;
59 unsigned short ans = 0;
67 *(unsigned char *) (&ans) = *(unsigned char *) w;
71 sum = (sum >> 16) + (sum & 0xFFFF);
77 #if !ENABLE_FEATURE_FANCY_PING
81 static char *hostname;
83 static void noresp(int ign ATTRIBUTE_UNUSED)
85 printf("No response from %s\n", hostname);
89 static void ping4(len_and_sockaddr *lsa)
91 struct sockaddr_in pingaddr;
94 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
96 pingsock = create_icmp_socket();
99 pkt = (struct icmp *) packet;
100 memset(pkt, 0, sizeof(packet));
101 pkt->icmp_type = ICMP_ECHO;
102 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
104 c = xsendto(pingsock, packet, DEFDATALEN + ICMP_MINLEN,
105 (struct sockaddr *) &pingaddr, sizeof(pingaddr));
107 /* listen for replies */
109 struct sockaddr_in from;
110 socklen_t fromlen = sizeof(from);
112 c = recvfrom(pingsock, packet, sizeof(packet), 0,
113 (struct sockaddr *) &from, &fromlen);
116 bb_perror_msg("recvfrom");
119 if (c >= 76) { /* ip + icmp */
120 struct iphdr *iphdr = (struct iphdr *) packet;
122 pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
123 if (pkt->icmp_type == ICMP_ECHOREPLY)
127 if (ENABLE_FEATURE_CLEAN_UP)
132 static void ping6(len_and_sockaddr *lsa)
134 struct sockaddr_in6 pingaddr;
135 struct icmp6_hdr *pkt;
138 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
140 pingsock = create_icmp6_socket();
141 pingaddr = lsa->sin6;
143 pkt = (struct icmp6_hdr *) packet;
144 memset(pkt, 0, sizeof(packet));
145 pkt->icmp6_type = ICMP6_ECHO_REQUEST;
147 sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
148 setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
150 c = xsendto(pingsock, packet, DEFDATALEN + sizeof (struct icmp6_hdr),
151 (struct sockaddr *) &pingaddr, sizeof(pingaddr));
153 /* listen for replies */
155 struct sockaddr_in6 from;
156 socklen_t fromlen = sizeof(from);
158 c = recvfrom(pingsock, packet, sizeof(packet), 0,
159 (struct sockaddr *) &from, &fromlen);
162 bb_perror_msg("recvfrom");
165 if (c >= 8) { /* icmp6_hdr */
166 pkt = (struct icmp6_hdr *) packet;
167 if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
171 if (ENABLE_FEATURE_CLEAN_UP)
176 int ping_main(int argc, char **argv);
177 int ping_main(int argc, char **argv)
179 len_and_sockaddr *lsa;
181 sa_family_t af = AF_UNSPEC;
182 while (++argv[0][0] == '-') {
183 if (argv[0][1] == '4') {
187 if (argv[0][1] == '6') {
202 lsa = xhost_and_af2sockaddr(hostname, 0, af);
204 lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
206 /* Set timer _after_ DNS resolution */
207 signal(SIGALRM, noresp);
208 alarm(5); /* give the host 5000ms to respond */
211 if (lsa->sa.sa_family == AF_INET6)
216 printf("%s is alive!\n", hostname);
221 #else /* FEATURE_FANCY_PING */
224 /* full(er) version */
226 #define OPT_STRING ("qvc:s:I:4" USE_PING6("6"))
229 OPT_VERBOSE = 1 << 1,
234 OPT_IPV6 = (1 << 6) * ENABLE_PING6,
240 struct sockaddr_in sin;
242 struct sockaddr_in6 sin6;
245 static len_and_sockaddr *source_lsa;
246 static int pingsock = -1;
247 static unsigned datalen; /* intentionally uninitialized to work around gcc bug */
251 static unsigned long ntransmitted, nreceived, nrepeats, pingcount;
253 static unsigned tmin = UINT_MAX, tmax;
254 static unsigned long tsum;
255 static char rcvd_tbl[MAX_DUP_CHK / 8];
257 static const char *hostname;
258 static const char *dotted;
260 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
261 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
262 #define SET(bit) (A(bit) |= B(bit))
263 #define CLR(bit) (A(bit) &= (~B(bit)))
264 #define TST(bit) (A(bit) & B(bit))
266 /**************************************************************************/
268 static void pingstats(int junk ATTRIBUTE_UNUSED)
270 signal(SIGINT, SIG_IGN);
272 printf("\n--- %s ping statistics ---\n", hostname);
273 printf("%lu packets transmitted, ", ntransmitted);
274 printf("%lu packets received, ", nreceived);
276 printf("%lu duplicates, ", nrepeats);
278 ntransmitted = (ntransmitted - nreceived) * 100 / ntransmitted;
279 printf("%lu%% packet loss\n", ntransmitted);
280 if (tmin != UINT_MAX)
281 printf("round-trip min/avg/max = %u.%u/%lu.%lu/%u.%u ms\n",
282 tmin / 10, tmin % 10,
283 (tsum / (nreceived + nrepeats)) / 10,
284 (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
285 exit(nreceived == 0); /* (nreceived == 0) is true (1) -- 'failure' */
288 static void sendping_tail(void (*sp)(int), const void *pkt, int size_pkt)
292 CLR((uint16_t)ntransmitted % MAX_DUP_CHK);
295 /* sizeof(pingaddr) can be larger than real sa size, but I think
296 * it doesn't matter */
297 sz = xsendto(pingsock, pkt, size_pkt, &pingaddr.sa, sizeof(pingaddr));
299 bb_error_msg_and_die(bb_msg_write_error);
302 if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
304 } else { /* done, wait for the last ping to come back */
305 /* todo, don't necessarily need to wait so long... */
306 signal(SIGALRM, pingstats);
311 static void sendping4(int junk ATTRIBUTE_UNUSED)
313 struct icmp *pkt = alloca(datalen + ICMP_MINLEN);
315 pkt->icmp_type = ICMP_ECHO;
318 pkt->icmp_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
320 gettimeofday((struct timeval *) &pkt->icmp_dun, NULL);
321 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, datalen + ICMP_MINLEN);
323 sendping_tail(sendping4, pkt, datalen + ICMP_MINLEN);
326 static void sendping6(int junk ATTRIBUTE_UNUSED)
328 struct icmp6_hdr *pkt = alloca(datalen + sizeof(struct icmp6_hdr));
330 pkt->icmp6_type = ICMP6_ECHO_REQUEST;
332 pkt->icmp6_cksum = 0;
333 pkt->icmp6_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
334 pkt->icmp6_id = myid;
335 gettimeofday((struct timeval *) &pkt->icmp6_data8[4], NULL);
337 sendping_tail(sendping6, pkt, datalen + sizeof(struct icmp6_hdr));
341 static const char *icmp_type_name(int id)
344 case ICMP_ECHOREPLY: return "Echo Reply";
345 case ICMP_DEST_UNREACH: return "Destination Unreachable";
346 case ICMP_SOURCE_QUENCH: return "Source Quench";
347 case ICMP_REDIRECT: return "Redirect (change route)";
348 case ICMP_ECHO: return "Echo Request";
349 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
350 case ICMP_PARAMETERPROB: return "Parameter Problem";
351 case ICMP_TIMESTAMP: return "Timestamp Request";
352 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
353 case ICMP_INFO_REQUEST: return "Information Request";
354 case ICMP_INFO_REPLY: return "Information Reply";
355 case ICMP_ADDRESS: return "Address Mask Request";
356 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
357 default: return "unknown ICMP type";
361 /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
362 * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
363 #ifndef MLD_LISTENER_QUERY
364 # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
366 #ifndef MLD_LISTENER_REPORT
367 # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
369 #ifndef MLD_LISTENER_REDUCTION
370 # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
372 static const char *icmp6_type_name(int id)
375 case ICMP6_DST_UNREACH: return "Destination Unreachable";
376 case ICMP6_PACKET_TOO_BIG: return "Packet too big";
377 case ICMP6_TIME_EXCEEDED: return "Time Exceeded";
378 case ICMP6_PARAM_PROB: return "Parameter Problem";
379 case ICMP6_ECHO_REPLY: return "Echo Reply";
380 case ICMP6_ECHO_REQUEST: return "Echo Request";
381 case MLD_LISTENER_QUERY: return "Listener Query";
382 case MLD_LISTENER_REPORT: return "Listener Report";
383 case MLD_LISTENER_REDUCTION: return "Listener Reduction";
384 default: return "unknown ICMP type";
389 static void unpack_tail(int sz, struct timeval *tp,
390 const char *from_str,
391 uint16_t recv_seq, int ttl)
393 const char *dupmsg = " (DUP!)";
394 unsigned triptime = triptime; /* for gcc */
401 gettimeofday(&tv, NULL);
402 tv.tv_usec -= tp->tv_usec;
403 if (tv.tv_usec < 0) {
405 tv.tv_usec += 1000000;
407 tv.tv_sec -= tp->tv_sec;
409 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
417 if (TST(recv_seq % MAX_DUP_CHK)) {
421 SET(recv_seq % MAX_DUP_CHK);
425 if (option_mask32 & OPT_QUIET)
428 printf("%d bytes from %s: seq=%u ttl=%d", sz,
429 from_str, recv_seq, ttl);
431 printf(" time=%u.%u ms", triptime / 10, triptime % 10);
435 static void unpack4(char *buf, int sz, struct sockaddr_in *from)
437 struct icmp *icmppkt;
441 /* discard if too short */
442 if (sz < (datalen + ICMP_MINLEN))
445 /* check IP header */
446 iphdr = (struct iphdr *) buf;
447 hlen = iphdr->ihl << 2;
449 icmppkt = (struct icmp *) (buf + hlen);
450 if (icmppkt->icmp_id != myid)
451 return; /* not our ping */
453 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
454 uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
455 struct timeval *tp = NULL;
457 if (sz >= ICMP_MINLEN + sizeof(struct timeval))
458 tp = (struct timeval *) icmppkt->icmp_data;
460 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
461 recv_seq, iphdr->ttl);
462 } else if (icmppkt->icmp_type != ICMP_ECHO) {
463 bb_error_msg("warning: got ICMP %d (%s)",
465 icmp_type_name(icmppkt->icmp_type));
469 static void unpack6(char *packet, int sz, struct sockaddr_in6 *from, int hoplimit)
471 struct icmp6_hdr *icmppkt;
472 char buf[INET6_ADDRSTRLEN];
474 /* discard if too short */
475 if (sz < (datalen + sizeof(struct icmp6_hdr)))
478 icmppkt = (struct icmp6_hdr *) packet;
479 if (icmppkt->icmp6_id != myid)
480 return; /* not our ping */
482 if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
483 uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
484 struct timeval *tp = NULL;
486 if (sz >= sizeof(struct icmp6_hdr) + sizeof(struct timeval))
487 tp = (struct timeval *) &icmppkt->icmp6_data8[4];
489 inet_ntop(AF_INET6, &pingaddr.sin6.sin6_addr,
492 } else if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST) {
493 bb_error_msg("warning: got ICMP %d (%s)",
495 icmp6_type_name(icmppkt->icmp6_type));
500 static void ping4(len_and_sockaddr *lsa)
502 char packet[datalen + MAXIPLEN + MAXICMPLEN];
505 pingsock = create_icmp_socket();
506 pingaddr.sin = lsa->sin;
508 xbind(pingsock, &lsa->sa, lsa->len);
510 /* enable broadcast pings */
511 setsockopt_broadcast(pingsock);
513 /* set recv buf for broadcast pings */
514 sockopt = 48 * 1024; /* explain why 48k? */
515 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
517 signal(SIGINT, pingstats);
519 /* start the ping's going ... */
522 /* listen for replies */
524 struct sockaddr_in from;
525 socklen_t fromlen = (socklen_t) sizeof(from);
528 c = recvfrom(pingsock, packet, sizeof(packet), 0,
529 (struct sockaddr *) &from, &fromlen);
532 bb_perror_msg("recvfrom");
535 unpack4(packet, c, &from);
536 if (pingcount > 0 && nreceived >= pingcount)
541 extern int BUG_bad_offsetof_icmp6_cksum(void);
542 static void ping6(len_and_sockaddr *lsa)
544 char packet[datalen + MAXIPLEN + MAXICMPLEN];
547 struct sockaddr_in6 from;
549 char control_buf[CMSG_SPACE(36)];
551 pingsock = create_icmp6_socket();
552 pingaddr.sin6 = lsa->sin6;
553 /* untested whether "-I addr" really works for IPv6: */
555 xbind(pingsock, &lsa->sa, lsa->len);
559 struct icmp6_filter filt;
560 if (!(option_mask32 & OPT_VERBOSE)) {
561 ICMP6_FILTER_SETBLOCKALL(&filt);
562 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
564 ICMP6_FILTER_SETPASSALL(&filt);
566 if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
568 bb_error_msg_and_die("setsockopt(ICMP6_FILTER)");
570 #endif /*ICMP6_FILTER*/
572 /* enable broadcast pings */
573 setsockopt_broadcast(pingsock);
575 /* set recv buf for broadcast pings */
576 sockopt = 48 * 1024; /* explain why 48k? */
577 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
579 sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
580 if (offsetof(struct icmp6_hdr, icmp6_cksum) != 2)
581 BUG_bad_offsetof_icmp6_cksum();
582 setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
584 /* request ttl info to be returned in ancillary data */
585 setsockopt(pingsock, SOL_IPV6, IPV6_HOPLIMIT, &const_int_1, sizeof(const_int_1));
588 pingaddr.sin6.sin6_scope_id = if_index;
590 signal(SIGINT, pingstats);
592 /* start the ping's going ... */
595 /* listen for replies */
596 msg.msg_name = &from;
597 msg.msg_namelen = sizeof(from);
600 msg.msg_control = control_buf;
601 iov.iov_base = packet;
602 iov.iov_len = sizeof(packet);
607 msg.msg_controllen = sizeof(control_buf);
609 c = recvmsg(pingsock, &msg, 0);
612 bb_perror_msg("recvfrom");
615 for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
616 if (mp->cmsg_level == SOL_IPV6
617 && mp->cmsg_type == IPV6_HOPLIMIT
618 /* don't check len - we trust the kernel: */
619 /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
621 hoplimit = *(int*)CMSG_DATA(mp);
624 unpack6(packet, c, &from, hoplimit);
625 if (pingcount > 0 && nreceived >= pingcount)
631 static void ping(len_and_sockaddr *lsa)
633 printf("PING %s (%s)", hostname, dotted);
636 xmalloc_sockaddr2dotted_noport(&lsa->sa, lsa->len));
638 printf(": %d data bytes\n", datalen);
641 if (lsa->sa.sa_family == AF_INET6)
648 int ping_main(int argc, char **argv);
649 int ping_main(int argc, char **argv)
651 len_and_sockaddr *lsa;
652 char *opt_c, *opt_s, *opt_I;
653 USE_PING6(sa_family_t af = AF_UNSPEC;)
655 datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
657 /* exactly one argument needed, -v and -q don't mix */
658 opt_complementary = "=1:q--v:v--q";
659 getopt32(argc, argv, OPT_STRING, &opt_c, &opt_s, &opt_I);
660 if (option_mask32 & OPT_c) pingcount = xatoul(opt_c); // -c
661 if (option_mask32 & OPT_s) datalen = xatou16(opt_s); // -s
662 if (option_mask32 & OPT_I) { // -I
663 if_index = if_nametoindex(opt_I);
665 /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
666 /* (ping doesn't support source IPv6 addresses yet anyway) */
667 source_lsa = xdotted2sockaddr(opt_I, 0);
670 myid = (int16_t) getpid();
671 hostname = argv[optind];
673 if (option_mask32 & OPT_IPV4)
675 if (option_mask32 & OPT_IPV6)
677 lsa = xhost_and_af2sockaddr(hostname, 0, af);
679 lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
682 if (source_lsa && source_lsa->sa.sa_family != lsa->sa.sa_family)
683 /* leaking it here... */
686 dotted = xmalloc_sockaddr2dotted_noport(&lsa->sa, lsa->len);
691 #endif /* FEATURE_FANCY_PING */
695 int ping6_main(int argc, char **argv);
696 int ping6_main(int argc, char **argv)
698 argv[0] = (char*)"-6";
699 return ping_main(argc + 1, argv - 1);
704 * Copyright (c) 1989 The Regents of the University of California.
705 * All rights reserved.
707 * This code is derived from software contributed to Berkeley by
710 * Redistribution and use in source and binary forms, with or without
711 * modification, are permitted provided that the following conditions
713 * 1. Redistributions of source code must retain the above copyright
714 * notice, this list of conditions and the following disclaimer.
715 * 2. Redistributions in binary form must reproduce the above copyright
716 * notice, this list of conditions and the following disclaimer in the
717 * documentation and/or other materials provided with the distribution.
719 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
720 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
722 * 4. Neither the name of the University nor the names of its contributors
723 * may be used to endorse or promote products derived from this software
724 * without specific prior written permission.
726 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
727 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
728 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
729 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
730 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
731 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
732 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
733 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
734 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
735 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF