ping.c 10 KB

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