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 = sendto(pingsock, packet, DEFDATALEN + ICMP_MINLEN, 0,
105 (struct sockaddr *) &pingaddr, sizeof(pingaddr));
108 if (ENABLE_FEATURE_CLEAN_UP)
110 bb_perror_msg_and_die("sendto");
113 /* listen for replies */
115 struct sockaddr_in from;
116 socklen_t fromlen = sizeof(from);
118 c = recvfrom(pingsock, packet, sizeof(packet), 0,
119 (struct sockaddr *) &from, &fromlen);
122 bb_perror_msg("recvfrom");
125 if (c >= 76) { /* ip + icmp */
126 struct iphdr *iphdr = (struct iphdr *) packet;
128 pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
129 if (pkt->icmp_type == ICMP_ECHOREPLY)
133 if (ENABLE_FEATURE_CLEAN_UP)
138 static void ping6(len_and_sockaddr *lsa)
140 struct sockaddr_in6 pingaddr;
141 struct icmp6_hdr *pkt;
144 char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
146 pingsock = create_icmp6_socket();
147 pingaddr = lsa->sin6;
149 pkt = (struct icmp6_hdr *) packet;
150 memset(pkt, 0, sizeof(packet));
151 pkt->icmp6_type = ICMP6_ECHO_REQUEST;
153 sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
154 setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
156 c = sendto(pingsock, packet, DEFDATALEN + sizeof (struct icmp6_hdr), 0,
157 (struct sockaddr *) &pingaddr, sizeof(pingaddr));
160 if (ENABLE_FEATURE_CLEAN_UP)
162 bb_perror_msg_and_die("sendto");
165 /* listen for replies */
167 struct sockaddr_in6 from;
168 socklen_t fromlen = sizeof(from);
170 c = recvfrom(pingsock, packet, sizeof(packet), 0,
171 (struct sockaddr *) &from, &fromlen);
174 bb_perror_msg("recvfrom");
177 if (c >= 8) { /* icmp6_hdr */
178 pkt = (struct icmp6_hdr *) packet;
179 if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
183 if (ENABLE_FEATURE_CLEAN_UP)
188 int ping_main(int argc, char **argv);
189 int ping_main(int argc, char **argv)
191 len_and_sockaddr *lsa;
193 sa_family_t af = AF_UNSPEC;
194 while (++argv[0][0] == '-') {
195 if (argv[0][1] == '4') {
199 if (argv[0][1] == '6') {
214 lsa = xhost_and_af2sockaddr(hostname, 0, af);
216 lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
218 /* Set timer _after_ DNS resolution */
219 signal(SIGALRM, noresp);
220 alarm(5); /* give the host 5000ms to respond */
223 if (lsa->sa.sa_family == AF_INET6)
228 printf("%s is alive!\n", hostname);
233 #else /* FEATURE_FANCY_PING */
236 /* full(er) version */
238 #define OPT_STRING ("qvc:s:I:4" USE_PING6("6"))
241 OPT_VERBOSE = 1 << 1,
246 OPT_IPV6 = (1 << 6) * ENABLE_PING6,
252 struct sockaddr_in sin;
254 struct sockaddr_in6 sin6;
257 static struct sockaddr_in sourceaddr;
258 static int pingsock = -1;
259 static unsigned datalen; /* intentionally uninitialized to work around gcc bug */
263 static unsigned long ntransmitted, nreceived, nrepeats, pingcount;
265 static unsigned long tmin = ULONG_MAX, tmax, tsum;
266 static char rcvd_tbl[MAX_DUP_CHK / 8];
268 static const char *hostname;
269 static const char *dotted;
271 #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
272 #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
273 #define SET(bit) (A(bit) |= B(bit))
274 #define CLR(bit) (A(bit) &= (~B(bit)))
275 #define TST(bit) (A(bit) & B(bit))
277 /**************************************************************************/
279 static void pingstats(int junk ATTRIBUTE_UNUSED)
283 signal(SIGINT, SIG_IGN);
285 printf("\n--- %s ping statistics ---\n", hostname);
286 printf("%lu packets transmitted, ", ntransmitted);
287 printf("%lu packets received, ", nreceived);
289 printf("%lu duplicates, ", nrepeats);
291 ntransmitted = (ntransmitted - nreceived) * 100 / ntransmitted;
292 printf("%lu%% packet loss\n", ntransmitted);
294 printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
295 tmin / 10, tmin % 10,
296 (tsum / (nreceived + nrepeats)) / 10,
297 (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
299 status = EXIT_SUCCESS;
301 status = EXIT_FAILURE;
305 static void sendping_tail(void (*sp)(int), int sz, int sizeof_packet)
308 bb_perror_msg_and_die("sendto");
309 if (sz != sizeof_packet)
310 bb_error_msg_and_die("ping wrote %d chars; %d expected", sz,
314 if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
316 } else { /* done, wait for the last ping to come back */
317 /* todo, don't necessarily need to wait so long... */
318 signal(SIGALRM, pingstats);
323 static void sendping4(int junk ATTRIBUTE_UNUSED)
327 char packet[datalen + ICMP_MINLEN];
329 pkt = (struct icmp *) packet;
331 pkt->icmp_type = ICMP_ECHO;
334 pkt->icmp_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
336 CLR((uint16_t)ntransmitted % MAX_DUP_CHK);
339 gettimeofday((struct timeval *) &pkt->icmp_dun, NULL);
340 pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
342 i = sendto(pingsock, packet, sizeof(packet), 0,
343 &pingaddr.sa, sizeof(pingaddr.sin));
345 sendping_tail(sendping4, i, sizeof(packet));
348 static void sendping6(int junk ATTRIBUTE_UNUSED)
350 struct icmp6_hdr *pkt;
352 char packet[datalen + sizeof (struct icmp6_hdr)];
354 pkt = (struct icmp6_hdr *) packet;
356 pkt->icmp6_type = ICMP6_ECHO_REQUEST;
358 pkt->icmp6_cksum = 0;
359 pkt->icmp6_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
360 pkt->icmp6_id = myid;
361 CLR((uint16_t)ntransmitted % MAX_DUP_CHK);
364 gettimeofday((struct timeval *) &pkt->icmp6_data8[4], NULL);
366 i = sendto(pingsock, packet, sizeof(packet), 0,
367 &pingaddr.sa, sizeof(pingaddr.sin6));
369 sendping_tail(sendping6, i, sizeof(packet));
373 static const char *icmp_type_name(int id)
376 case ICMP_ECHOREPLY: return "Echo Reply";
377 case ICMP_DEST_UNREACH: return "Destination Unreachable";
378 case ICMP_SOURCE_QUENCH: return "Source Quench";
379 case ICMP_REDIRECT: return "Redirect (change route)";
380 case ICMP_ECHO: return "Echo Request";
381 case ICMP_TIME_EXCEEDED: return "Time Exceeded";
382 case ICMP_PARAMETERPROB: return "Parameter Problem";
383 case ICMP_TIMESTAMP: return "Timestamp Request";
384 case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
385 case ICMP_INFO_REQUEST: return "Information Request";
386 case ICMP_INFO_REPLY: return "Information Reply";
387 case ICMP_ADDRESS: return "Address Mask Request";
388 case ICMP_ADDRESSREPLY: return "Address Mask Reply";
389 default: return "unknown ICMP type";
393 /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
394 * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
395 #ifndef MLD_LISTENER_QUERY
396 # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
398 #ifndef MLD_LISTENER_REPORT
399 # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
401 #ifndef MLD_LISTENER_REDUCTION
402 # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
404 static const char *icmp6_type_name(int id)
407 case ICMP6_DST_UNREACH: return "Destination Unreachable";
408 case ICMP6_PACKET_TOO_BIG: return "Packet too big";
409 case ICMP6_TIME_EXCEEDED: return "Time Exceeded";
410 case ICMP6_PARAM_PROB: return "Parameter Problem";
411 case ICMP6_ECHO_REPLY: return "Echo Reply";
412 case ICMP6_ECHO_REQUEST: return "Echo Request";
413 case MLD_LISTENER_QUERY: return "Listener Query";
414 case MLD_LISTENER_REPORT: return "Listener Report";
415 case MLD_LISTENER_REDUCTION: return "Listener Reduction";
416 default: return "unknown ICMP type";
421 static void unpack4(char *buf, int sz, struct sockaddr_in *from)
423 struct icmp *icmppkt;
425 struct timeval tv, *tp;
427 unsigned long triptime;
429 gettimeofday(&tv, NULL);
431 /* discard if too short */
432 if (sz < (datalen + ICMP_MINLEN))
435 /* check IP header */
436 iphdr = (struct iphdr *) buf;
437 hlen = iphdr->ihl << 2;
439 icmppkt = (struct icmp *) (buf + hlen);
440 if (icmppkt->icmp_id != myid)
441 return; /* not our ping */
443 if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
444 uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
446 tp = (struct timeval *) icmppkt->icmp_data;
448 if ((tv.tv_usec -= tp->tv_usec) < 0) {
450 tv.tv_usec += 1000000;
452 tv.tv_sec -= tp->tv_sec;
454 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
461 if (TST(recv_seq % MAX_DUP_CHK)) {
466 SET(recv_seq % MAX_DUP_CHK);
470 if (option_mask32 & OPT_QUIET)
473 printf("%d bytes from %s: icmp_seq=%u", sz,
474 inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
476 printf(" ttl=%d", iphdr->ttl);
477 printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
482 if (icmppkt->icmp_type != ICMP_ECHO)
483 bb_error_msg("warning: got ICMP %d (%s)",
485 icmp_type_name(icmppkt->icmp_type));
490 static void unpack6(char *packet, int sz, struct sockaddr_in6 *from, int hoplimit)
492 struct icmp6_hdr *icmppkt;
493 struct timeval tv, *tp;
495 unsigned long triptime;
496 char buf[INET6_ADDRSTRLEN];
498 gettimeofday(&tv, NULL);
500 /* discard if too short */
501 if (sz < (datalen + sizeof(struct icmp6_hdr)))
504 icmppkt = (struct icmp6_hdr *) packet;
505 if (icmppkt->icmp6_id != myid)
506 return; /* not our ping */
508 if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
509 uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
511 tp = (struct timeval *) &icmppkt->icmp6_data8[4];
513 if ((tv.tv_usec -= tp->tv_usec) < 0) {
515 tv.tv_usec += 1000000;
517 tv.tv_sec -= tp->tv_sec;
519 triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
526 if (TST(recv_seq % MAX_DUP_CHK)) {
531 SET(recv_seq % MAX_DUP_CHK);
535 if (option_mask32 & OPT_QUIET)
538 printf("%d bytes from %s: icmp6_seq=%u", sz,
539 inet_ntop(AF_INET6, &pingaddr.sin6.sin6_addr,
542 printf(" ttl=%d time=%lu.%lu ms", hoplimit,
543 triptime / 10, triptime % 10);
548 if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST)
549 bb_error_msg("warning: got ICMP %d (%s)",
551 icmp6_type_name(icmppkt->icmp6_type));
557 static void ping4(len_and_sockaddr *lsa)
559 char packet[datalen + MAXIPLEN + MAXICMPLEN];
562 pingsock = create_icmp_socket();
563 pingaddr.sin = lsa->sin;
564 if (sourceaddr.sin_addr.s_addr) {
565 xbind(pingsock, (struct sockaddr*)&sourceaddr, sizeof(sourceaddr));
568 /* enable broadcast pings */
569 setsockopt_broadcast(pingsock);
571 /* set recv buf for broadcast pings */
572 sockopt = 48 * 1024; /* explain why 48k? */
573 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
575 printf("PING %s (%s)", hostname, dotted);
576 if (sourceaddr.sin_addr.s_addr) {
578 inet_ntoa(*(struct in_addr *) &sourceaddr.sin_addr.s_addr));
580 printf(": %d data bytes\n", datalen);
582 signal(SIGINT, pingstats);
584 /* start the ping's going ... */
587 /* listen for replies */
589 struct sockaddr_in from;
590 socklen_t fromlen = (socklen_t) sizeof(from);
593 c = recvfrom(pingsock, packet, sizeof(packet), 0,
594 (struct sockaddr *) &from, &fromlen);
597 bb_perror_msg("recvfrom");
600 unpack4(packet, c, &from);
601 if (pingcount > 0 && nreceived >= pingcount)
606 extern int BUG_bad_offsetof_icmp6_cksum(void);
607 static void ping6(len_and_sockaddr *lsa)
609 char packet[datalen + MAXIPLEN + MAXICMPLEN];
612 struct sockaddr_in6 from;
614 char control_buf[CMSG_SPACE(36)];
616 pingsock = create_icmp6_socket();
617 pingaddr.sin6 = lsa->sin6;
618 //if (sourceaddr.sin_addr.s_addr) {
619 // xbind(pingsock, (struct sockaddr*)&sourceaddr, sizeof(sourceaddr));
624 struct icmp6_filter filt;
625 if (!(option_mask32 & OPT_VERBOSE)) {
626 ICMP6_FILTER_SETBLOCKALL(&filt);
627 ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
629 ICMP6_FILTER_SETPASSALL(&filt);
631 if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
633 bb_error_msg_and_die("setsockopt(ICMP6_FILTER)");
635 #endif /*ICMP6_FILTER*/
637 /* enable broadcast pings */
638 setsockopt_broadcast(pingsock);
640 /* set recv buf for broadcast pings */
641 sockopt = 48 * 1024; /* explain why 48k? */
642 setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
644 sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
645 if (offsetof(struct icmp6_hdr, icmp6_cksum) != 2)
646 BUG_bad_offsetof_icmp6_cksum();
647 setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
649 /* request ttl info to be returned in ancillary data */
650 setsockopt(pingsock, SOL_IPV6, IPV6_HOPLIMIT, &const_int_1, sizeof(const_int_1));
653 pingaddr.sin6.sin6_scope_id = if_index;
655 printf("PING %s (%s): %d data bytes\n", hostname, dotted, datalen);
657 signal(SIGINT, pingstats);
659 /* start the ping's going ... */
662 /* listen for replies */
663 msg.msg_name = &from;
664 msg.msg_namelen = sizeof(from);
667 msg.msg_control = control_buf;
668 iov.iov_base = packet;
669 iov.iov_len = sizeof(packet);
674 msg.msg_controllen = sizeof(control_buf);
676 c = recvmsg(pingsock, &msg, 0);
679 bb_perror_msg("recvfrom");
682 for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
683 if (mp->cmsg_level == SOL_IPV6
684 && mp->cmsg_type == IPV6_HOPLIMIT
685 /* don't check len - we trust the kernel: */
686 /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
688 hoplimit = *(int*)CMSG_DATA(mp);
691 unpack6(packet, c, &from, hoplimit);
692 if (pingcount > 0 && nreceived >= pingcount)
698 /* TODO: consolidate ether-wake.c, dnsd.c, ifupdown.c, nslookup.c
699 * versions of below thing. BTW we have far too many "%u.%u.%u.%u" too...
701 static int parse_nipquad(const char *str, struct sockaddr_in* addr)
704 unsigned i1, i2, i3, i4;
705 if (sscanf(str, "%u.%u.%u.%u%c",
706 &i1, &i2, &i3, &i4, &dummy) == 4
707 && ( (i1|i2|i3|i4) <= 0xff )
709 uint8_t* ptr = (uint8_t*)&addr->sin_addr;
716 return 1; /* error */
719 int ping_main(int argc, char **argv);
720 int ping_main(int argc, char **argv)
722 len_and_sockaddr *lsa;
723 char *opt_c, *opt_s, *opt_I;
724 USE_PING6(sa_family_t af = AF_UNSPEC;)
726 datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
728 /* exactly one argument needed, -v and -q don't mix */
729 opt_complementary = "=1:q--v:v--q";
730 getopt32(argc, argv, OPT_STRING, &opt_c, &opt_s, &opt_I);
731 if (option_mask32 & OPT_c) pingcount = xatoul(opt_c); // -c
732 if (option_mask32 & OPT_s) datalen = xatou16(opt_s); // -s
733 if (option_mask32 & OPT_I) { // -I
734 if_index = if_nametoindex(opt_I);
736 if (parse_nipquad(opt_I, &sourceaddr))
739 myid = (int16_t) getpid();
740 hostname = argv[optind];
742 if (option_mask32 & OPT_IPV4)
744 if (option_mask32 & OPT_IPV6)
746 lsa = xhost_and_af2sockaddr(hostname, 0, af);
748 lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
750 dotted = xmalloc_sockaddr2dotted_noport(&lsa->sa, lsa->len);
752 if (lsa->sa.sa_family == AF_INET6)
760 #endif /* FEATURE_FANCY_PING */
764 int ping6_main(int argc, char **argv);
765 int ping6_main(int argc, char **argv)
767 argv[0] = (char*)"-6";
768 return ping_main(argc + 1, argv - 1);
773 * Copyright (c) 1989 The Regents of the University of California.
774 * All rights reserved.
776 * This code is derived from software contributed to Berkeley by
779 * Redistribution and use in source and binary forms, with or without
780 * modification, are permitted provided that the following conditions
782 * 1. Redistributions of source code must retain the above copyright
783 * notice, this list of conditions and the following disclaimer.
784 * 2. Redistributions in binary form must reproduce the above copyright
785 * notice, this list of conditions and the following disclaimer in the
786 * documentation and/or other materials provided with the distribution.
788 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
789 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
791 * 4. Neither the name of the University nor the names of its contributors
792 * may be used to endorse or promote products derived from this software
793 * without specific prior written permission.
795 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
796 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
797 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
798 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
799 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
800 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
801 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
802 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
803 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
804 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF