ping.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini ping implementation for busybox
  4. *
  5. * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
  6. *
  7. * Adapted from the ping in netkit-base 0.10:
  8. * Copyright (c) 1989 The Regents of the University of California.
  9. * All rights reserved.
  10. *
  11. * This code is derived from software contributed to Berkeley by
  12. * Mike Muuss.
  13. *
  14. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  15. */
  16. /* from ping6.c:
  17. * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
  18. *
  19. * This version of ping is adapted from the ping in netkit-base 0.10,
  20. * which is:
  21. *
  22. * Original copyright notice is retained at the end of this file.
  23. *
  24. * This version is an adaptation of ping.c from busybox.
  25. * The code was modified by Bart Visscher <magick@linux-fan.com>
  26. */
  27. #include <net/if.h>
  28. #include <netinet/ip_icmp.h>
  29. #include "libbb.h"
  30. #if ENABLE_PING6
  31. #include <netinet/icmp6.h>
  32. /* I see RENUMBERED constants in bits/in.h - !!?
  33. * What a fuck is going on with libc? Is it a glibc joke? */
  34. #ifdef IPV6_2292HOPLIMIT
  35. #undef IPV6_HOPLIMIT
  36. #define IPV6_HOPLIMIT IPV6_2292HOPLIMIT
  37. #endif
  38. #endif
  39. enum {
  40. DEFDATALEN = 56,
  41. MAXIPLEN = 60,
  42. MAXICMPLEN = 76,
  43. MAXPACKET = 65468,
  44. MAX_DUP_CHK = (8 * 128),
  45. MAXWAIT = 10,
  46. PINGINTERVAL = 1, /* 1 second */
  47. };
  48. /* common routines */
  49. static int in_cksum(unsigned short *buf, int sz)
  50. {
  51. int nleft = sz;
  52. int sum = 0;
  53. unsigned short *w = buf;
  54. unsigned short ans = 0;
  55. while (nleft > 1) {
  56. sum += *w++;
  57. nleft -= 2;
  58. }
  59. if (nleft == 1) {
  60. *(unsigned char *) (&ans) = *(unsigned char *) w;
  61. sum += ans;
  62. }
  63. sum = (sum >> 16) + (sum & 0xFFFF);
  64. sum += (sum >> 16);
  65. ans = ~sum;
  66. return ans;
  67. }
  68. #if !ENABLE_FEATURE_FANCY_PING
  69. /* simple version */
  70. static char *hostname;
  71. static void noresp(int ign UNUSED_PARAM)
  72. {
  73. printf("No response from %s\n", hostname);
  74. exit(EXIT_FAILURE);
  75. }
  76. static void ping4(len_and_sockaddr *lsa)
  77. {
  78. struct sockaddr_in pingaddr;
  79. struct icmp *pkt;
  80. int pingsock, c;
  81. char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
  82. pingsock = create_icmp_socket();
  83. pingaddr = lsa->u.sin;
  84. pkt = (struct icmp *) packet;
  85. memset(pkt, 0, sizeof(packet));
  86. pkt->icmp_type = ICMP_ECHO;
  87. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
  88. c = xsendto(pingsock, packet, DEFDATALEN + ICMP_MINLEN,
  89. (struct sockaddr *) &pingaddr, sizeof(pingaddr));
  90. /* listen for replies */
  91. while (1) {
  92. struct sockaddr_in from;
  93. socklen_t fromlen = sizeof(from);
  94. c = recvfrom(pingsock, packet, sizeof(packet), 0,
  95. (struct sockaddr *) &from, &fromlen);
  96. if (c < 0) {
  97. if (errno != EINTR)
  98. bb_perror_msg("recvfrom");
  99. continue;
  100. }
  101. if (c >= 76) { /* ip + icmp */
  102. struct iphdr *iphdr = (struct iphdr *) packet;
  103. pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
  104. if (pkt->icmp_type == ICMP_ECHOREPLY)
  105. break;
  106. }
  107. }
  108. if (ENABLE_FEATURE_CLEAN_UP)
  109. close(pingsock);
  110. }
  111. #if ENABLE_PING6
  112. static void ping6(len_and_sockaddr *lsa)
  113. {
  114. struct sockaddr_in6 pingaddr;
  115. struct icmp6_hdr *pkt;
  116. int pingsock, c;
  117. int sockopt;
  118. char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
  119. pingsock = create_icmp6_socket();
  120. pingaddr = lsa->u.sin6;
  121. pkt = (struct icmp6_hdr *) packet;
  122. memset(pkt, 0, sizeof(packet));
  123. pkt->icmp6_type = ICMP6_ECHO_REQUEST;
  124. sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
  125. setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
  126. c = xsendto(pingsock, packet, DEFDATALEN + sizeof (struct icmp6_hdr),
  127. (struct sockaddr *) &pingaddr, sizeof(pingaddr));
  128. /* listen for replies */
  129. while (1) {
  130. struct sockaddr_in6 from;
  131. socklen_t fromlen = sizeof(from);
  132. c = recvfrom(pingsock, packet, sizeof(packet), 0,
  133. (struct sockaddr *) &from, &fromlen);
  134. if (c < 0) {
  135. if (errno != EINTR)
  136. bb_perror_msg("recvfrom");
  137. continue;
  138. }
  139. if (c >= 8) { /* icmp6_hdr */
  140. pkt = (struct icmp6_hdr *) packet;
  141. if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
  142. break;
  143. }
  144. }
  145. if (ENABLE_FEATURE_CLEAN_UP)
  146. close(pingsock);
  147. }
  148. #endif
  149. int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  150. int ping_main(int argc UNUSED_PARAM, char **argv)
  151. {
  152. len_and_sockaddr *lsa;
  153. #if ENABLE_PING6
  154. sa_family_t af = AF_UNSPEC;
  155. while ((++argv)[0] && argv[0][0] == '-') {
  156. if (argv[0][1] == '4') {
  157. af = AF_INET;
  158. continue;
  159. }
  160. if (argv[0][1] == '6') {
  161. af = AF_INET6;
  162. continue;
  163. }
  164. bb_show_usage();
  165. }
  166. #else
  167. argv++;
  168. #endif
  169. hostname = *argv;
  170. if (!hostname)
  171. bb_show_usage();
  172. #if ENABLE_PING6
  173. lsa = xhost_and_af2sockaddr(hostname, 0, af);
  174. #else
  175. lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
  176. #endif
  177. /* Set timer _after_ DNS resolution */
  178. signal(SIGALRM, noresp);
  179. alarm(5); /* give the host 5000ms to respond */
  180. #if ENABLE_PING6
  181. if (lsa->u.sa.sa_family == AF_INET6)
  182. ping6(lsa);
  183. else
  184. #endif
  185. ping4(lsa);
  186. printf("%s is alive!\n", hostname);
  187. return EXIT_SUCCESS;
  188. }
  189. #else /* FEATURE_FANCY_PING */
  190. /* full(er) version */
  191. #define OPT_STRING ("qvc:s:w:W:I:4" USE_PING6("6"))
  192. enum {
  193. OPT_QUIET = 1 << 0,
  194. OPT_VERBOSE = 1 << 1,
  195. OPT_c = 1 << 2,
  196. OPT_s = 1 << 3,
  197. OPT_w = 1 << 4,
  198. OPT_W = 1 << 5,
  199. OPT_I = 1 << 6,
  200. OPT_IPV4 = 1 << 7,
  201. OPT_IPV6 = (1 << 8) * ENABLE_PING6,
  202. };
  203. struct globals {
  204. int pingsock;
  205. int if_index;
  206. char *opt_I;
  207. len_and_sockaddr *source_lsa;
  208. unsigned datalen;
  209. unsigned long ntransmitted, nreceived, nrepeats, pingcount;
  210. uint16_t myid;
  211. unsigned tmin, tmax; /* in us */
  212. unsigned long long tsum; /* in us, sum of all times */
  213. unsigned deadline;
  214. unsigned timeout;
  215. unsigned total_secs;
  216. const char *hostname;
  217. const char *dotted;
  218. union {
  219. struct sockaddr sa;
  220. struct sockaddr_in sin;
  221. #if ENABLE_PING6
  222. struct sockaddr_in6 sin6;
  223. #endif
  224. } pingaddr;
  225. char rcvd_tbl[MAX_DUP_CHK / 8];
  226. };
  227. #define G (*(struct globals*)&bb_common_bufsiz1)
  228. #define pingsock (G.pingsock )
  229. #define if_index (G.if_index )
  230. #define source_lsa (G.source_lsa )
  231. #define opt_I (G.opt_I )
  232. #define datalen (G.datalen )
  233. #define ntransmitted (G.ntransmitted)
  234. #define nreceived (G.nreceived )
  235. #define nrepeats (G.nrepeats )
  236. #define pingcount (G.pingcount )
  237. #define myid (G.myid )
  238. #define tmin (G.tmin )
  239. #define tmax (G.tmax )
  240. #define tsum (G.tsum )
  241. #define deadline (G.deadline )
  242. #define timeout (G.timeout )
  243. #define total_secs (G.total_secs )
  244. #define hostname (G.hostname )
  245. #define dotted (G.dotted )
  246. #define pingaddr (G.pingaddr )
  247. #define rcvd_tbl (G.rcvd_tbl )
  248. void BUG_ping_globals_too_big(void);
  249. #define INIT_G() do { \
  250. if (sizeof(G) > COMMON_BUFSIZE) \
  251. BUG_ping_globals_too_big(); \
  252. pingsock = -1; \
  253. datalen = DEFDATALEN; \
  254. timeout = MAXWAIT; \
  255. tmin = UINT_MAX; \
  256. } while (0)
  257. #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
  258. #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
  259. #define SET(bit) (A(bit) |= B(bit))
  260. #define CLR(bit) (A(bit) &= (~B(bit)))
  261. #define TST(bit) (A(bit) & B(bit))
  262. /**************************************************************************/
  263. static void print_stats_and_exit(int junk) NORETURN;
  264. static void print_stats_and_exit(int junk UNUSED_PARAM)
  265. {
  266. signal(SIGINT, SIG_IGN);
  267. printf("\n--- %s ping statistics ---\n", hostname);
  268. printf("%lu packets transmitted, ", ntransmitted);
  269. printf("%lu packets received, ", nreceived);
  270. if (nrepeats)
  271. printf("%lu duplicates, ", nrepeats);
  272. if (ntransmitted)
  273. ntransmitted = (ntransmitted - nreceived) * 100 / ntransmitted;
  274. printf("%lu%% packet loss\n", ntransmitted);
  275. if (tmin != UINT_MAX) {
  276. unsigned tavg = tsum / (nreceived + nrepeats);
  277. printf("round-trip min/avg/max = %u.%03u/%u.%03u/%u.%03u ms\n",
  278. tmin / 1000, tmin % 1000,
  279. tavg / 1000, tavg % 1000,
  280. tmax / 1000, tmax % 1000);
  281. }
  282. /* if condition is true, exit with 1 -- 'failure' */
  283. exit(nreceived == 0 || (deadline && nreceived < pingcount));
  284. }
  285. static void sendping_tail(void (*sp)(int), const void *pkt, int size_pkt)
  286. {
  287. int sz;
  288. CLR((uint16_t)ntransmitted % MAX_DUP_CHK);
  289. ntransmitted++;
  290. /* sizeof(pingaddr) can be larger than real sa size, but I think
  291. * it doesn't matter */
  292. sz = xsendto(pingsock, pkt, size_pkt, &pingaddr.sa, sizeof(pingaddr));
  293. if (sz != size_pkt)
  294. bb_error_msg_and_die(bb_msg_write_error);
  295. if (pingcount == 0 || deadline || ntransmitted < pingcount) {
  296. /* Didn't send all pings yet - schedule next in 1s */
  297. signal(SIGALRM, sp);
  298. if (deadline) {
  299. total_secs += PINGINTERVAL;
  300. if (total_secs >= deadline)
  301. signal(SIGALRM, print_stats_and_exit);
  302. }
  303. alarm(PINGINTERVAL);
  304. } else { /* -c NN, and all NN are sent (and no deadline) */
  305. /* Wait for the last ping to come back.
  306. * -W timeout: wait for a response in seconds.
  307. * Affects only timeout in absense of any responses,
  308. * otherwise ping waits for two RTTs. */
  309. unsigned expire = timeout;
  310. if (nreceived) {
  311. /* approx. 2*tmax, in seconds (2 RTT) */
  312. expire = tmax / (512*1024);
  313. if (expire == 0)
  314. expire = 1;
  315. }
  316. signal(SIGALRM, print_stats_and_exit);
  317. alarm(expire);
  318. }
  319. }
  320. static void sendping4(int junk UNUSED_PARAM)
  321. {
  322. /* +4 reserves a place for timestamp, which may end up sitting
  323. * *after* packet. Saves one if() */
  324. struct icmp *pkt = alloca(datalen + ICMP_MINLEN + 4);
  325. memset(pkt, 0, datalen + ICMP_MINLEN + 4);
  326. pkt->icmp_type = ICMP_ECHO;
  327. /*pkt->icmp_code = 0;*/
  328. /*pkt->icmp_cksum = 0;*/
  329. pkt->icmp_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
  330. pkt->icmp_id = myid;
  331. /* We don't do hton, because we will read it back on the same machine */
  332. /*if (datalen >= 4)*/
  333. *(uint32_t*)&pkt->icmp_dun = monotonic_us();
  334. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, datalen + ICMP_MINLEN);
  335. sendping_tail(sendping4, pkt, datalen + ICMP_MINLEN);
  336. }
  337. #if ENABLE_PING6
  338. static void sendping6(int junk UNUSED_PARAM)
  339. {
  340. struct icmp6_hdr *pkt = alloca(datalen + sizeof(struct icmp6_hdr) + 4);
  341. memset(pkt, 0, datalen + sizeof(struct icmp6_hdr) + 4);
  342. pkt->icmp6_type = ICMP6_ECHO_REQUEST;
  343. /*pkt->icmp6_code = 0;*/
  344. /*pkt->icmp6_cksum = 0;*/
  345. pkt->icmp6_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
  346. pkt->icmp6_id = myid;
  347. /*if (datalen >= 4)*/
  348. *(uint32_t*)(&pkt->icmp6_data8[4]) = monotonic_us();
  349. sendping_tail(sendping6, pkt, datalen + sizeof(struct icmp6_hdr));
  350. }
  351. #endif
  352. static const char *icmp_type_name(int id)
  353. {
  354. switch (id) {
  355. case ICMP_ECHOREPLY: return "Echo Reply";
  356. case ICMP_DEST_UNREACH: return "Destination Unreachable";
  357. case ICMP_SOURCE_QUENCH: return "Source Quench";
  358. case ICMP_REDIRECT: return "Redirect (change route)";
  359. case ICMP_ECHO: return "Echo Request";
  360. case ICMP_TIME_EXCEEDED: return "Time Exceeded";
  361. case ICMP_PARAMETERPROB: return "Parameter Problem";
  362. case ICMP_TIMESTAMP: return "Timestamp Request";
  363. case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
  364. case ICMP_INFO_REQUEST: return "Information Request";
  365. case ICMP_INFO_REPLY: return "Information Reply";
  366. case ICMP_ADDRESS: return "Address Mask Request";
  367. case ICMP_ADDRESSREPLY: return "Address Mask Reply";
  368. default: return "unknown ICMP type";
  369. }
  370. }
  371. #if ENABLE_PING6
  372. /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
  373. * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
  374. #ifndef MLD_LISTENER_QUERY
  375. # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
  376. #endif
  377. #ifndef MLD_LISTENER_REPORT
  378. # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
  379. #endif
  380. #ifndef MLD_LISTENER_REDUCTION
  381. # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
  382. #endif
  383. static const char *icmp6_type_name(int id)
  384. {
  385. switch (id) {
  386. case ICMP6_DST_UNREACH: return "Destination Unreachable";
  387. case ICMP6_PACKET_TOO_BIG: return "Packet too big";
  388. case ICMP6_TIME_EXCEEDED: return "Time Exceeded";
  389. case ICMP6_PARAM_PROB: return "Parameter Problem";
  390. case ICMP6_ECHO_REPLY: return "Echo Reply";
  391. case ICMP6_ECHO_REQUEST: return "Echo Request";
  392. case MLD_LISTENER_QUERY: return "Listener Query";
  393. case MLD_LISTENER_REPORT: return "Listener Report";
  394. case MLD_LISTENER_REDUCTION: return "Listener Reduction";
  395. default: return "unknown ICMP type";
  396. }
  397. }
  398. #endif
  399. static void unpack_tail(int sz, uint32_t *tp,
  400. const char *from_str,
  401. uint16_t recv_seq, int ttl)
  402. {
  403. const char *dupmsg = " (DUP!)";
  404. unsigned triptime = triptime; /* for gcc */
  405. ++nreceived;
  406. if (tp) {
  407. /* (int32_t) cast is for hypothetical 64-bit unsigned */
  408. /* (doesn't hurt 32-bit real-world anyway) */
  409. triptime = (int32_t) ((uint32_t)monotonic_us() - *tp);
  410. tsum += triptime;
  411. if (triptime < tmin)
  412. tmin = triptime;
  413. if (triptime > tmax)
  414. tmax = triptime;
  415. }
  416. if (TST(recv_seq % MAX_DUP_CHK)) {
  417. ++nrepeats;
  418. --nreceived;
  419. } else {
  420. SET(recv_seq % MAX_DUP_CHK);
  421. dupmsg += 7;
  422. }
  423. if (option_mask32 & OPT_QUIET)
  424. return;
  425. printf("%d bytes from %s: seq=%u ttl=%d", sz,
  426. from_str, recv_seq, ttl);
  427. if (tp)
  428. printf(" time=%u.%03u ms", triptime / 1000, triptime % 1000);
  429. puts(dupmsg);
  430. fflush(stdout);
  431. }
  432. static void unpack4(char *buf, int sz, struct sockaddr_in *from)
  433. {
  434. struct icmp *icmppkt;
  435. struct iphdr *iphdr;
  436. int hlen;
  437. /* discard if too short */
  438. if (sz < (datalen + ICMP_MINLEN))
  439. return;
  440. /* check IP header */
  441. iphdr = (struct iphdr *) buf;
  442. hlen = iphdr->ihl << 2;
  443. sz -= hlen;
  444. icmppkt = (struct icmp *) (buf + hlen);
  445. if (icmppkt->icmp_id != myid)
  446. return; /* not our ping */
  447. if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
  448. uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
  449. uint32_t *tp = NULL;
  450. if (sz >= ICMP_MINLEN + sizeof(uint32_t))
  451. tp = (uint32_t *) icmppkt->icmp_data;
  452. unpack_tail(sz, tp,
  453. inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
  454. recv_seq, iphdr->ttl);
  455. } else if (icmppkt->icmp_type != ICMP_ECHO) {
  456. bb_error_msg("warning: got ICMP %d (%s)",
  457. icmppkt->icmp_type,
  458. icmp_type_name(icmppkt->icmp_type));
  459. }
  460. }
  461. #if ENABLE_PING6
  462. static void unpack6(char *packet, int sz, /*struct sockaddr_in6 *from,*/ int hoplimit)
  463. {
  464. struct icmp6_hdr *icmppkt;
  465. char buf[INET6_ADDRSTRLEN];
  466. /* discard if too short */
  467. if (sz < (datalen + sizeof(struct icmp6_hdr)))
  468. return;
  469. icmppkt = (struct icmp6_hdr *) packet;
  470. if (icmppkt->icmp6_id != myid)
  471. return; /* not our ping */
  472. if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
  473. uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
  474. uint32_t *tp = NULL;
  475. if (sz >= sizeof(struct icmp6_hdr) + sizeof(uint32_t))
  476. tp = (uint32_t *) &icmppkt->icmp6_data8[4];
  477. unpack_tail(sz, tp,
  478. inet_ntop(AF_INET6, &pingaddr.sin6.sin6_addr,
  479. buf, sizeof(buf)),
  480. recv_seq, hoplimit);
  481. } else if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST) {
  482. bb_error_msg("warning: got ICMP %d (%s)",
  483. icmppkt->icmp6_type,
  484. icmp6_type_name(icmppkt->icmp6_type));
  485. }
  486. }
  487. #endif
  488. static void ping4(len_and_sockaddr *lsa)
  489. {
  490. char packet[datalen + MAXIPLEN + MAXICMPLEN];
  491. int sockopt;
  492. pingsock = create_icmp_socket();
  493. pingaddr.sin = lsa->u.sin;
  494. if (source_lsa) {
  495. if (setsockopt(pingsock, IPPROTO_IP, IP_MULTICAST_IF,
  496. &source_lsa->u.sa, source_lsa->len))
  497. bb_error_msg_and_die("can't set multicast source interface");
  498. xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
  499. }
  500. if (opt_I)
  501. setsockopt(pingsock, SOL_SOCKET, SO_BINDTODEVICE, opt_I, strlen(opt_I) + 1);
  502. /* enable broadcast pings */
  503. setsockopt_broadcast(pingsock);
  504. /* set recv buf for broadcast pings */
  505. sockopt = 48 * 1024; /* explain why 48k? */
  506. setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
  507. signal(SIGINT, print_stats_and_exit);
  508. /* start the ping's going ... */
  509. sendping4(0);
  510. /* listen for replies */
  511. while (1) {
  512. struct sockaddr_in from;
  513. socklen_t fromlen = (socklen_t) sizeof(from);
  514. int c;
  515. c = recvfrom(pingsock, packet, sizeof(packet), 0,
  516. (struct sockaddr *) &from, &fromlen);
  517. if (c < 0) {
  518. if (errno != EINTR)
  519. bb_perror_msg("recvfrom");
  520. continue;
  521. }
  522. unpack4(packet, c, &from);
  523. if (pingcount && nreceived >= pingcount)
  524. break;
  525. }
  526. }
  527. #if ENABLE_PING6
  528. extern int BUG_bad_offsetof_icmp6_cksum(void);
  529. static void ping6(len_and_sockaddr *lsa)
  530. {
  531. char packet[datalen + MAXIPLEN + MAXICMPLEN];
  532. int sockopt;
  533. struct msghdr msg;
  534. struct sockaddr_in6 from;
  535. struct iovec iov;
  536. char control_buf[CMSG_SPACE(36)];
  537. pingsock = create_icmp6_socket();
  538. pingaddr.sin6 = lsa->u.sin6;
  539. /* untested whether "-I addr" really works for IPv6: */
  540. if (source_lsa)
  541. xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
  542. if (opt_I)
  543. setsockopt(pingsock, SOL_SOCKET, SO_BINDTODEVICE, opt_I, strlen(opt_I) + 1);
  544. #ifdef ICMP6_FILTER
  545. {
  546. struct icmp6_filter filt;
  547. if (!(option_mask32 & OPT_VERBOSE)) {
  548. ICMP6_FILTER_SETBLOCKALL(&filt);
  549. ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
  550. } else {
  551. ICMP6_FILTER_SETPASSALL(&filt);
  552. }
  553. if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
  554. sizeof(filt)) < 0)
  555. bb_error_msg_and_die("setsockopt(ICMP6_FILTER)");
  556. }
  557. #endif /*ICMP6_FILTER*/
  558. /* enable broadcast pings */
  559. setsockopt_broadcast(pingsock);
  560. /* set recv buf for broadcast pings */
  561. sockopt = 48 * 1024; /* explain why 48k? */
  562. setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
  563. sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
  564. if (offsetof(struct icmp6_hdr, icmp6_cksum) != 2)
  565. BUG_bad_offsetof_icmp6_cksum();
  566. setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
  567. /* request ttl info to be returned in ancillary data */
  568. setsockopt(pingsock, SOL_IPV6, IPV6_HOPLIMIT, &const_int_1, sizeof(const_int_1));
  569. if (if_index)
  570. pingaddr.sin6.sin6_scope_id = if_index;
  571. signal(SIGINT, print_stats_and_exit);
  572. /* start the ping's going ... */
  573. sendping6(0);
  574. /* listen for replies */
  575. msg.msg_name = &from;
  576. msg.msg_namelen = sizeof(from);
  577. msg.msg_iov = &iov;
  578. msg.msg_iovlen = 1;
  579. msg.msg_control = control_buf;
  580. iov.iov_base = packet;
  581. iov.iov_len = sizeof(packet);
  582. while (1) {
  583. int c;
  584. struct cmsghdr *mp;
  585. int hoplimit = -1;
  586. msg.msg_controllen = sizeof(control_buf);
  587. c = recvmsg(pingsock, &msg, 0);
  588. if (c < 0) {
  589. if (errno != EINTR)
  590. bb_perror_msg("recvfrom");
  591. continue;
  592. }
  593. for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
  594. if (mp->cmsg_level == SOL_IPV6
  595. && mp->cmsg_type == IPV6_HOPLIMIT
  596. /* don't check len - we trust the kernel: */
  597. /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
  598. ) {
  599. hoplimit = *(int*)CMSG_DATA(mp);
  600. }
  601. }
  602. unpack6(packet, c, /*&from,*/ hoplimit);
  603. if (pingcount && nreceived >= pingcount)
  604. break;
  605. }
  606. }
  607. #endif
  608. static void ping(len_and_sockaddr *lsa)
  609. {
  610. printf("PING %s (%s)", hostname, dotted);
  611. if (source_lsa) {
  612. printf(" from %s",
  613. xmalloc_sockaddr2dotted_noport(&source_lsa->u.sa));
  614. }
  615. printf(": %d data bytes\n", datalen);
  616. #if ENABLE_PING6
  617. if (lsa->u.sa.sa_family == AF_INET6)
  618. ping6(lsa);
  619. else
  620. #endif
  621. ping4(lsa);
  622. }
  623. int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  624. int ping_main(int argc UNUSED_PARAM, char **argv)
  625. {
  626. len_and_sockaddr *lsa;
  627. char *opt_c, *opt_s;
  628. USE_PING6(sa_family_t af = AF_UNSPEC;)
  629. INIT_G();
  630. /* exactly one argument needed; -v and -q don't mix; -w NUM, -W NUM */
  631. opt_complementary = "=1:q--v:v--q:w+:W+";
  632. getopt32(argv, OPT_STRING, &opt_c, &opt_s, &deadline, &timeout, &opt_I);
  633. if (option_mask32 & OPT_c)
  634. pingcount = xatoul(opt_c); // -c
  635. if (option_mask32 & OPT_s)
  636. datalen = xatou16(opt_s); // -s
  637. if (option_mask32 & OPT_I) { // -I
  638. if_index = if_nametoindex(opt_I);
  639. if (!if_index) {
  640. /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
  641. source_lsa = xdotted2sockaddr(opt_I, 0);
  642. opt_I = NULL; /* don't try to bind to device later */
  643. }
  644. }
  645. myid = (uint16_t) getpid();
  646. hostname = argv[optind];
  647. #if ENABLE_PING6
  648. if (option_mask32 & OPT_IPV4)
  649. af = AF_INET;
  650. if (option_mask32 & OPT_IPV6)
  651. af = AF_INET6;
  652. lsa = xhost_and_af2sockaddr(hostname, 0, af);
  653. #else
  654. lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
  655. #endif
  656. if (source_lsa && source_lsa->u.sa.sa_family != lsa->u.sa.sa_family)
  657. /* leaking it here... */
  658. source_lsa = NULL;
  659. dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
  660. ping(lsa);
  661. print_stats_and_exit(EXIT_SUCCESS);
  662. /*return EXIT_SUCCESS;*/
  663. }
  664. #endif /* FEATURE_FANCY_PING */
  665. #if ENABLE_PING6
  666. int ping6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  667. int ping6_main(int argc, char **argv)
  668. {
  669. argv[0] = (char*)"-6";
  670. return ping_main(argc + 1, argv - 1);
  671. }
  672. #endif
  673. /* from ping6.c:
  674. * Copyright (c) 1989 The Regents of the University of California.
  675. * All rights reserved.
  676. *
  677. * This code is derived from software contributed to Berkeley by
  678. * Mike Muuss.
  679. *
  680. * Redistribution and use in source and binary forms, with or without
  681. * modification, are permitted provided that the following conditions
  682. * are met:
  683. * 1. Redistributions of source code must retain the above copyright
  684. * notice, this list of conditions and the following disclaimer.
  685. * 2. Redistributions in binary form must reproduce the above copyright
  686. * notice, this list of conditions and the following disclaimer in the
  687. * documentation and/or other materials provided with the distribution.
  688. *
  689. * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
  690. * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
  691. *
  692. * 4. Neither the name of the University nor the names of its contributors
  693. * may be used to endorse or promote products derived from this software
  694. * without specific prior written permission.
  695. *
  696. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  697. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  698. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  699. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  700. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  701. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  702. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  703. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  704. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  705. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  706. * SUCH DAMAGE.
  707. */