ping.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * $Id: ping.c,v 1.56 2004/03/15 08:28:48 andersen Exp $
  4. * Mini ping implementation for busybox
  5. *
  6. * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
  7. *
  8. * Adapted from the ping in netkit-base 0.10:
  9. * Copyright (c) 1989 The Regents of the University of California.
  10. * Derived from software contributed to Berkeley by Mike Muuss.
  11. *
  12. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  13. */
  14. #include <sys/param.h>
  15. #include <sys/socket.h>
  16. #include <sys/file.h>
  17. #include <sys/times.h>
  18. #include <signal.h>
  19. #include <netinet/in.h>
  20. #include <netinet/ip.h>
  21. #include <netinet/ip_icmp.h>
  22. #include <arpa/inet.h>
  23. #include <netdb.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <errno.h>
  27. #include <unistd.h>
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include "busybox.h"
  31. enum {
  32. DEFDATALEN = 56,
  33. MAXIPLEN = 60,
  34. MAXICMPLEN = 76,
  35. MAXPACKET = 65468,
  36. MAX_DUP_CHK = (8 * 128),
  37. MAXWAIT = 10,
  38. PINGINTERVAL = 1 /* second */
  39. };
  40. static void ping(const char *host);
  41. /* common routines */
  42. static int in_cksum(unsigned short *buf, int sz)
  43. {
  44. int nleft = sz;
  45. int sum = 0;
  46. unsigned short *w = buf;
  47. unsigned short ans = 0;
  48. while (nleft > 1) {
  49. sum += *w++;
  50. nleft -= 2;
  51. }
  52. if (nleft == 1) {
  53. *(unsigned char *) (&ans) = *(unsigned char *) w;
  54. sum += ans;
  55. }
  56. sum = (sum >> 16) + (sum & 0xFFFF);
  57. sum += (sum >> 16);
  58. ans = ~sum;
  59. return ans;
  60. }
  61. #ifndef CONFIG_FEATURE_FANCY_PING
  62. /* simple version */
  63. static char *hostname;
  64. static void noresp(int ign)
  65. {
  66. printf("No response from %s\n", hostname);
  67. exit(EXIT_FAILURE);
  68. }
  69. static void ping(const char *host)
  70. {
  71. struct hostent *h;
  72. struct sockaddr_in pingaddr;
  73. struct icmp *pkt;
  74. int pingsock, c;
  75. char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
  76. pingsock = create_icmp_socket();
  77. memset(&pingaddr, 0, sizeof(struct sockaddr_in));
  78. pingaddr.sin_family = AF_INET;
  79. h = xgethostbyname(host);
  80. memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
  81. hostname = h->h_name;
  82. pkt = (struct icmp *) packet;
  83. memset(pkt, 0, sizeof(packet));
  84. pkt->icmp_type = ICMP_ECHO;
  85. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
  86. c = sendto(pingsock, packet, DEFDATALEN + ICMP_MINLEN, 0,
  87. (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
  88. if (c < 0) {
  89. if (ENABLE_FEATURE_CLEAN_UP) close(pingsock);
  90. bb_perror_msg_and_die("sendto");
  91. }
  92. signal(SIGALRM, noresp);
  93. alarm(5); /* give the host 5000ms to respond */
  94. /* listen for replies */
  95. while (1) {
  96. struct sockaddr_in from;
  97. socklen_t fromlen = sizeof(from);
  98. if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
  99. (struct sockaddr *) &from, &fromlen)) < 0) {
  100. if (errno == EINTR)
  101. continue;
  102. bb_perror_msg("recvfrom");
  103. continue;
  104. }
  105. if (c >= 76) { /* ip + icmp */
  106. struct iphdr *iphdr = (struct iphdr *) packet;
  107. pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
  108. if (pkt->icmp_type == ICMP_ECHOREPLY)
  109. break;
  110. }
  111. }
  112. if (ENABLE_FEATURE_CLEAN_UP) close(pingsock);
  113. printf("%s is alive!\n", hostname);
  114. return;
  115. }
  116. int ping_main(int argc, char **argv)
  117. {
  118. argc--;
  119. argv++;
  120. if (argc < 1)
  121. bb_show_usage();
  122. ping(*argv);
  123. return EXIT_SUCCESS;
  124. }
  125. #else /* ! CONFIG_FEATURE_FANCY_PING */
  126. /* full(er) version */
  127. #define OPT_STRING "qc:s:I:"
  128. enum {
  129. OPT_QUIET = 1 << 0,
  130. };
  131. static struct sockaddr_in pingaddr;
  132. static struct sockaddr_in sourceaddr;
  133. static int pingsock = -1;
  134. static unsigned datalen; /* intentionally uninitialized to work around gcc bug */
  135. static unsigned long ntransmitted, nreceived, nrepeats, pingcount;
  136. static int myid;
  137. static unsigned long tmin = ULONG_MAX, tmax, tsum;
  138. static char rcvd_tbl[MAX_DUP_CHK / 8];
  139. static struct hostent *hostent;
  140. static void sendping(int);
  141. static void pingstats(int);
  142. static void unpack(char *, int, struct sockaddr_in *);
  143. #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
  144. #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
  145. #define SET(bit) (A(bit) |= B(bit))
  146. #define CLR(bit) (A(bit) &= (~B(bit)))
  147. #define TST(bit) (A(bit) & B(bit))
  148. /**************************************************************************/
  149. static void pingstats(int junk)
  150. {
  151. int status;
  152. signal(SIGINT, SIG_IGN);
  153. printf("\n--- %s ping statistics ---\n", hostent->h_name);
  154. printf("%lu packets transmitted, ", ntransmitted);
  155. printf("%lu packets received, ", nreceived);
  156. if (nrepeats)
  157. printf("%lu duplicates, ", nrepeats);
  158. if (ntransmitted)
  159. printf("%lu%% packet loss\n",
  160. (ntransmitted - nreceived) * 100 / ntransmitted);
  161. if (nreceived)
  162. printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
  163. tmin / 10, tmin % 10,
  164. (tsum / (nreceived + nrepeats)) / 10,
  165. (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
  166. if (nreceived != 0)
  167. status = EXIT_SUCCESS;
  168. else
  169. status = EXIT_FAILURE;
  170. exit(status);
  171. }
  172. static void sendping(int junk)
  173. {
  174. struct icmp *pkt;
  175. int i;
  176. char packet[datalen + ICMP_MINLEN];
  177. pkt = (struct icmp *) packet;
  178. pkt->icmp_type = ICMP_ECHO;
  179. pkt->icmp_code = 0;
  180. pkt->icmp_cksum = 0;
  181. pkt->icmp_seq = htons(ntransmitted);
  182. pkt->icmp_id = myid;
  183. CLR(ntohs(pkt->icmp_seq) % MAX_DUP_CHK);
  184. ntransmitted++;
  185. gettimeofday((struct timeval *) &pkt->icmp_dun, NULL);
  186. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
  187. i = sendto(pingsock, packet, sizeof(packet), 0,
  188. (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
  189. if (i < 0)
  190. bb_perror_msg_and_die("sendto");
  191. else if ((size_t)i != sizeof(packet))
  192. bb_error_msg_and_die("ping wrote %d chars; %d expected", i,
  193. (int)sizeof(packet));
  194. signal(SIGALRM, sendping);
  195. if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
  196. alarm(PINGINTERVAL);
  197. } else { /* done, wait for the last ping to come back */
  198. /* todo, don't necessarily need to wait so long... */
  199. signal(SIGALRM, pingstats);
  200. alarm(MAXWAIT);
  201. }
  202. }
  203. static char *icmp_type_name(int id)
  204. {
  205. switch (id) {
  206. case ICMP_ECHOREPLY: return "Echo Reply";
  207. case ICMP_DEST_UNREACH: return "Destination Unreachable";
  208. case ICMP_SOURCE_QUENCH: return "Source Quench";
  209. case ICMP_REDIRECT: return "Redirect (change route)";
  210. case ICMP_ECHO: return "Echo Request";
  211. case ICMP_TIME_EXCEEDED: return "Time Exceeded";
  212. case ICMP_PARAMETERPROB: return "Parameter Problem";
  213. case ICMP_TIMESTAMP: return "Timestamp Request";
  214. case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
  215. case ICMP_INFO_REQUEST: return "Information Request";
  216. case ICMP_INFO_REPLY: return "Information Reply";
  217. case ICMP_ADDRESS: return "Address Mask Request";
  218. case ICMP_ADDRESSREPLY: return "Address Mask Reply";
  219. default: return "unknown ICMP type";
  220. }
  221. }
  222. static void unpack(char *buf, int sz, struct sockaddr_in *from)
  223. {
  224. struct icmp *icmppkt;
  225. struct iphdr *iphdr;
  226. struct timeval tv, *tp;
  227. int hlen, dupflag;
  228. unsigned long triptime;
  229. gettimeofday(&tv, NULL);
  230. /* discard if too short */
  231. if (sz < (datalen + ICMP_MINLEN))
  232. return;
  233. /* check IP header */
  234. iphdr = (struct iphdr *) buf;
  235. hlen = iphdr->ihl << 2;
  236. sz -= hlen;
  237. icmppkt = (struct icmp *) (buf + hlen);
  238. if (icmppkt->icmp_id != myid)
  239. return; /* not our ping */
  240. if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
  241. u_int16_t recv_seq = ntohs(icmppkt->icmp_seq);
  242. ++nreceived;
  243. tp = (struct timeval *) icmppkt->icmp_data;
  244. if ((tv.tv_usec -= tp->tv_usec) < 0) {
  245. --tv.tv_sec;
  246. tv.tv_usec += 1000000;
  247. }
  248. tv.tv_sec -= tp->tv_sec;
  249. triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
  250. tsum += triptime;
  251. if (triptime < tmin)
  252. tmin = triptime;
  253. if (triptime > tmax)
  254. tmax = triptime;
  255. if (TST(recv_seq % MAX_DUP_CHK)) {
  256. ++nrepeats;
  257. --nreceived;
  258. dupflag = 1;
  259. } else {
  260. SET(recv_seq % MAX_DUP_CHK);
  261. dupflag = 0;
  262. }
  263. if (option_mask32 & OPT_QUIET)
  264. return;
  265. printf("%d bytes from %s: icmp_seq=%u", sz,
  266. inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
  267. recv_seq);
  268. printf(" ttl=%d", iphdr->ttl);
  269. printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
  270. if (dupflag)
  271. printf(" (DUP!)");
  272. puts("");
  273. } else
  274. if (icmppkt->icmp_type != ICMP_ECHO)
  275. bb_error_msg("warning: got ICMP %d (%s)",
  276. icmppkt->icmp_type, icmp_type_name(icmppkt->icmp_type));
  277. fflush(stdout);
  278. }
  279. static void ping(const char *host)
  280. {
  281. char packet[datalen + MAXIPLEN + MAXICMPLEN];
  282. int sockopt;
  283. pingsock = create_icmp_socket();
  284. if (sourceaddr.sin_addr.s_addr) {
  285. xbind(pingsock, (struct sockaddr*)&sourceaddr, sizeof(sourceaddr));
  286. }
  287. memset(&pingaddr, 0, sizeof(struct sockaddr_in));
  288. pingaddr.sin_family = AF_INET;
  289. hostent = xgethostbyname(host);
  290. if (hostent->h_addrtype != AF_INET)
  291. bb_error_msg_and_die("unknown address type; only AF_INET is currently supported");
  292. memcpy(&pingaddr.sin_addr, hostent->h_addr, sizeof(pingaddr.sin_addr));
  293. /* enable broadcast pings */
  294. setsockopt_broadcast(pingsock);
  295. /* set recv buf for broadcast pings */
  296. sockopt = 48 * 1024;
  297. setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
  298. sizeof(sockopt));
  299. printf("PING %s (%s)",
  300. hostent->h_name,
  301. inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr));
  302. if (sourceaddr.sin_addr.s_addr) {
  303. printf(" from %s",
  304. inet_ntoa(*(struct in_addr *) &sourceaddr.sin_addr.s_addr));
  305. }
  306. printf(": %d data bytes\n", datalen);
  307. signal(SIGINT, pingstats);
  308. /* start the ping's going ... */
  309. sendping(0);
  310. /* listen for replies */
  311. while (1) {
  312. struct sockaddr_in from;
  313. socklen_t fromlen = (socklen_t) sizeof(from);
  314. int c;
  315. if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
  316. (struct sockaddr *) &from, &fromlen)) < 0) {
  317. if (errno == EINTR)
  318. continue;
  319. bb_perror_msg("recvfrom");
  320. continue;
  321. }
  322. unpack(packet, c, &from);
  323. if (pingcount > 0 && nreceived >= pingcount)
  324. break;
  325. }
  326. pingstats(0);
  327. }
  328. /* TODO: consolidate ether-wake.c, dnsd.c, ifupdown.c, nslookup.c
  329. * versions of below thing. BTW we have far too many "%u.%u.%u.%u" too...
  330. */
  331. static int parse_nipquad(const char *str, struct sockaddr_in* addr)
  332. {
  333. char dummy;
  334. unsigned i1, i2, i3, i4;
  335. if (sscanf(str, "%u.%u.%u.%u%c",
  336. &i1, &i2, &i3, &i4, &dummy) == 4
  337. && ( (i1|i2|i3|i4) <= 0xff )
  338. ) {
  339. uint8_t* ptr = (uint8_t*)&addr->sin_addr;
  340. ptr[0] = i1;
  341. ptr[1] = i2;
  342. ptr[2] = i3;
  343. ptr[3] = i4;
  344. return 0;
  345. }
  346. return 1; /* error */
  347. }
  348. int ping_main(int argc, char **argv)
  349. {
  350. char *opt_c, *opt_s, *opt_I;
  351. datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
  352. /* exactly one argument needed */
  353. opt_complementary = "=1";
  354. getopt32(argc, argv, OPT_STRING, &opt_c, &opt_s, &opt_I);
  355. if (option_mask32 & 2) pingcount = xatoul(opt_c); // -c
  356. if (option_mask32 & 4) datalen = xatou16(opt_s); // -s
  357. if (option_mask32 & 8) { // -I
  358. /* TODO: ping6 accepts iface too:
  359. if_index = if_nametoindex(*argv);
  360. if (!if_index) ...
  361. make it true for ping. */
  362. if (parse_nipquad(opt_I, &sourceaddr))
  363. bb_show_usage();
  364. }
  365. myid = (int16_t) getpid();
  366. ping(argv[optind]);
  367. return EXIT_SUCCESS;
  368. }
  369. #endif /* ! CONFIG_FEATURE_FANCY_PING */