ping.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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 *str_I;
  207. len_and_sockaddr *source_lsa;
  208. unsigned datalen;
  209. unsigned pingcount; /* must be int-sized */
  210. unsigned long ntransmitted, nreceived, nrepeats;
  211. uint16_t myid;
  212. unsigned tmin, tmax; /* in us */
  213. unsigned long long tsum; /* in us, sum of all times */
  214. unsigned deadline;
  215. unsigned timeout;
  216. unsigned total_secs;
  217. const char *hostname;
  218. const char *dotted;
  219. union {
  220. struct sockaddr sa;
  221. struct sockaddr_in sin;
  222. #if ENABLE_PING6
  223. struct sockaddr_in6 sin6;
  224. #endif
  225. } pingaddr;
  226. char rcvd_tbl[MAX_DUP_CHK / 8];
  227. };
  228. #define G (*(struct globals*)&bb_common_bufsiz1)
  229. #define pingsock (G.pingsock )
  230. #define if_index (G.if_index )
  231. #define source_lsa (G.source_lsa )
  232. #define str_I (G.str_I )
  233. #define datalen (G.datalen )
  234. #define ntransmitted (G.ntransmitted)
  235. #define nreceived (G.nreceived )
  236. #define nrepeats (G.nrepeats )
  237. #define pingcount (G.pingcount )
  238. #define myid (G.myid )
  239. #define tmin (G.tmin )
  240. #define tmax (G.tmax )
  241. #define tsum (G.tsum )
  242. #define deadline (G.deadline )
  243. #define timeout (G.timeout )
  244. #define total_secs (G.total_secs )
  245. #define hostname (G.hostname )
  246. #define dotted (G.dotted )
  247. #define pingaddr (G.pingaddr )
  248. #define rcvd_tbl (G.rcvd_tbl )
  249. void BUG_ping_globals_too_big(void);
  250. #define INIT_G() do { \
  251. if (sizeof(G) > COMMON_BUFSIZE) \
  252. BUG_ping_globals_too_big(); \
  253. pingsock = -1; \
  254. datalen = DEFDATALEN; \
  255. timeout = MAXWAIT; \
  256. tmin = UINT_MAX; \
  257. } while (0)
  258. #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
  259. #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
  260. #define SET(bit) (A(bit) |= B(bit))
  261. #define CLR(bit) (A(bit) &= (~B(bit)))
  262. #define TST(bit) (A(bit) & B(bit))
  263. /**************************************************************************/
  264. static void print_stats_and_exit(int junk) NORETURN;
  265. static void print_stats_and_exit(int junk UNUSED_PARAM)
  266. {
  267. signal(SIGINT, SIG_IGN);
  268. printf("\n--- %s ping statistics ---\n", hostname);
  269. printf("%lu packets transmitted, ", ntransmitted);
  270. printf("%lu packets received, ", nreceived);
  271. if (nrepeats)
  272. printf("%lu duplicates, ", nrepeats);
  273. if (ntransmitted)
  274. ntransmitted = (ntransmitted - nreceived) * 100 / ntransmitted;
  275. printf("%lu%% packet loss\n", ntransmitted);
  276. if (tmin != UINT_MAX) {
  277. unsigned tavg = tsum / (nreceived + nrepeats);
  278. printf("round-trip min/avg/max = %u.%03u/%u.%03u/%u.%03u ms\n",
  279. tmin / 1000, tmin % 1000,
  280. tavg / 1000, tavg % 1000,
  281. tmax / 1000, tmax % 1000);
  282. }
  283. /* if condition is true, exit with 1 -- 'failure' */
  284. exit(nreceived == 0 || (deadline && nreceived < pingcount));
  285. }
  286. static void sendping_tail(void (*sp)(int), const void *pkt, int size_pkt)
  287. {
  288. int sz;
  289. CLR((uint16_t)ntransmitted % MAX_DUP_CHK);
  290. ntransmitted++;
  291. /* sizeof(pingaddr) can be larger than real sa size, but I think
  292. * it doesn't matter */
  293. sz = xsendto(pingsock, pkt, size_pkt, &pingaddr.sa, sizeof(pingaddr));
  294. if (sz != size_pkt)
  295. bb_error_msg_and_die(bb_msg_write_error);
  296. if (pingcount == 0 || deadline || ntransmitted < pingcount) {
  297. /* Didn't send all pings yet - schedule next in 1s */
  298. signal(SIGALRM, sp);
  299. if (deadline) {
  300. total_secs += PINGINTERVAL;
  301. if (total_secs >= deadline)
  302. signal(SIGALRM, print_stats_and_exit);
  303. }
  304. alarm(PINGINTERVAL);
  305. } else { /* -c NN, and all NN are sent (and no deadline) */
  306. /* Wait for the last ping to come back.
  307. * -W timeout: wait for a response in seconds.
  308. * Affects only timeout in absense of any responses,
  309. * otherwise ping waits for two RTTs. */
  310. unsigned expire = timeout;
  311. if (nreceived) {
  312. /* approx. 2*tmax, in seconds (2 RTT) */
  313. expire = tmax / (512*1024);
  314. if (expire == 0)
  315. expire = 1;
  316. }
  317. signal(SIGALRM, print_stats_and_exit);
  318. alarm(expire);
  319. }
  320. }
  321. static void sendping4(int junk UNUSED_PARAM)
  322. {
  323. /* +4 reserves a place for timestamp, which may end up sitting
  324. * *after* packet. Saves one if() */
  325. struct icmp *pkt = alloca(datalen + ICMP_MINLEN + 4);
  326. memset(pkt, 0, datalen + ICMP_MINLEN + 4);
  327. pkt->icmp_type = ICMP_ECHO;
  328. /*pkt->icmp_code = 0;*/
  329. /*pkt->icmp_cksum = 0;*/
  330. pkt->icmp_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
  331. pkt->icmp_id = myid;
  332. /* We don't do hton, because we will read it back on the same machine */
  333. /*if (datalen >= 4)*/
  334. *(uint32_t*)&pkt->icmp_dun = monotonic_us();
  335. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, datalen + ICMP_MINLEN);
  336. sendping_tail(sendping4, pkt, datalen + ICMP_MINLEN);
  337. }
  338. #if ENABLE_PING6
  339. static void sendping6(int junk UNUSED_PARAM)
  340. {
  341. struct icmp6_hdr *pkt = alloca(datalen + sizeof(struct icmp6_hdr) + 4);
  342. memset(pkt, 0, datalen + sizeof(struct icmp6_hdr) + 4);
  343. pkt->icmp6_type = ICMP6_ECHO_REQUEST;
  344. /*pkt->icmp6_code = 0;*/
  345. /*pkt->icmp6_cksum = 0;*/
  346. pkt->icmp6_seq = htons(ntransmitted); /* don't ++ here, it can be a macro */
  347. pkt->icmp6_id = myid;
  348. /*if (datalen >= 4)*/
  349. *(uint32_t*)(&pkt->icmp6_data8[4]) = monotonic_us();
  350. sendping_tail(sendping6, pkt, datalen + sizeof(struct icmp6_hdr));
  351. }
  352. #endif
  353. static const char *icmp_type_name(int id)
  354. {
  355. switch (id) {
  356. case ICMP_ECHOREPLY: return "Echo Reply";
  357. case ICMP_DEST_UNREACH: return "Destination Unreachable";
  358. case ICMP_SOURCE_QUENCH: return "Source Quench";
  359. case ICMP_REDIRECT: return "Redirect (change route)";
  360. case ICMP_ECHO: return "Echo Request";
  361. case ICMP_TIME_EXCEEDED: return "Time Exceeded";
  362. case ICMP_PARAMETERPROB: return "Parameter Problem";
  363. case ICMP_TIMESTAMP: return "Timestamp Request";
  364. case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
  365. case ICMP_INFO_REQUEST: return "Information Request";
  366. case ICMP_INFO_REPLY: return "Information Reply";
  367. case ICMP_ADDRESS: return "Address Mask Request";
  368. case ICMP_ADDRESSREPLY: return "Address Mask Reply";
  369. default: return "unknown ICMP type";
  370. }
  371. }
  372. #if ENABLE_PING6
  373. /* RFC3542 changed some definitions from RFC2292 for no good reason, whee!
  374. * the newer 3542 uses a MLD_ prefix where as 2292 uses ICMP6_ prefix */
  375. #ifndef MLD_LISTENER_QUERY
  376. # define MLD_LISTENER_QUERY ICMP6_MEMBERSHIP_QUERY
  377. #endif
  378. #ifndef MLD_LISTENER_REPORT
  379. # define MLD_LISTENER_REPORT ICMP6_MEMBERSHIP_REPORT
  380. #endif
  381. #ifndef MLD_LISTENER_REDUCTION
  382. # define MLD_LISTENER_REDUCTION ICMP6_MEMBERSHIP_REDUCTION
  383. #endif
  384. static const char *icmp6_type_name(int id)
  385. {
  386. switch (id) {
  387. case ICMP6_DST_UNREACH: return "Destination Unreachable";
  388. case ICMP6_PACKET_TOO_BIG: return "Packet too big";
  389. case ICMP6_TIME_EXCEEDED: return "Time Exceeded";
  390. case ICMP6_PARAM_PROB: return "Parameter Problem";
  391. case ICMP6_ECHO_REPLY: return "Echo Reply";
  392. case ICMP6_ECHO_REQUEST: return "Echo Request";
  393. case MLD_LISTENER_QUERY: return "Listener Query";
  394. case MLD_LISTENER_REPORT: return "Listener Report";
  395. case MLD_LISTENER_REDUCTION: return "Listener Reduction";
  396. default: return "unknown ICMP type";
  397. }
  398. }
  399. #endif
  400. static void unpack_tail(int sz, uint32_t *tp,
  401. const char *from_str,
  402. uint16_t recv_seq, int ttl)
  403. {
  404. const char *dupmsg = " (DUP!)";
  405. unsigned triptime = triptime; /* for gcc */
  406. ++nreceived;
  407. if (tp) {
  408. /* (int32_t) cast is for hypothetical 64-bit unsigned */
  409. /* (doesn't hurt 32-bit real-world anyway) */
  410. triptime = (int32_t) ((uint32_t)monotonic_us() - *tp);
  411. tsum += triptime;
  412. if (triptime < tmin)
  413. tmin = triptime;
  414. if (triptime > tmax)
  415. tmax = triptime;
  416. }
  417. if (TST(recv_seq % MAX_DUP_CHK)) {
  418. ++nrepeats;
  419. --nreceived;
  420. } else {
  421. SET(recv_seq % MAX_DUP_CHK);
  422. dupmsg += 7;
  423. }
  424. if (option_mask32 & OPT_QUIET)
  425. return;
  426. printf("%d bytes from %s: seq=%u ttl=%d", sz,
  427. from_str, recv_seq, ttl);
  428. if (tp)
  429. printf(" time=%u.%03u ms", triptime / 1000, triptime % 1000);
  430. puts(dupmsg);
  431. fflush(stdout);
  432. }
  433. static void unpack4(char *buf, int sz, struct sockaddr_in *from)
  434. {
  435. struct icmp *icmppkt;
  436. struct iphdr *iphdr;
  437. int hlen;
  438. /* discard if too short */
  439. if (sz < (datalen + ICMP_MINLEN))
  440. return;
  441. /* check IP header */
  442. iphdr = (struct iphdr *) buf;
  443. hlen = iphdr->ihl << 2;
  444. sz -= hlen;
  445. icmppkt = (struct icmp *) (buf + hlen);
  446. if (icmppkt->icmp_id != myid)
  447. return; /* not our ping */
  448. if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
  449. uint16_t recv_seq = ntohs(icmppkt->icmp_seq);
  450. uint32_t *tp = NULL;
  451. if (sz >= ICMP_MINLEN + sizeof(uint32_t))
  452. tp = (uint32_t *) icmppkt->icmp_data;
  453. unpack_tail(sz, tp,
  454. inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
  455. recv_seq, iphdr->ttl);
  456. } else if (icmppkt->icmp_type != ICMP_ECHO) {
  457. bb_error_msg("warning: got ICMP %d (%s)",
  458. icmppkt->icmp_type,
  459. icmp_type_name(icmppkt->icmp_type));
  460. }
  461. }
  462. #if ENABLE_PING6
  463. static void unpack6(char *packet, int sz, /*struct sockaddr_in6 *from,*/ int hoplimit)
  464. {
  465. struct icmp6_hdr *icmppkt;
  466. char buf[INET6_ADDRSTRLEN];
  467. /* discard if too short */
  468. if (sz < (datalen + sizeof(struct icmp6_hdr)))
  469. return;
  470. icmppkt = (struct icmp6_hdr *) packet;
  471. if (icmppkt->icmp6_id != myid)
  472. return; /* not our ping */
  473. if (icmppkt->icmp6_type == ICMP6_ECHO_REPLY) {
  474. uint16_t recv_seq = ntohs(icmppkt->icmp6_seq);
  475. uint32_t *tp = NULL;
  476. if (sz >= sizeof(struct icmp6_hdr) + sizeof(uint32_t))
  477. tp = (uint32_t *) &icmppkt->icmp6_data8[4];
  478. unpack_tail(sz, tp,
  479. inet_ntop(AF_INET6, &pingaddr.sin6.sin6_addr,
  480. buf, sizeof(buf)),
  481. recv_seq, hoplimit);
  482. } else if (icmppkt->icmp6_type != ICMP6_ECHO_REQUEST) {
  483. bb_error_msg("warning: got ICMP %d (%s)",
  484. icmppkt->icmp6_type,
  485. icmp6_type_name(icmppkt->icmp6_type));
  486. }
  487. }
  488. #endif
  489. static void ping4(len_and_sockaddr *lsa)
  490. {
  491. char packet[datalen + MAXIPLEN + MAXICMPLEN];
  492. int sockopt;
  493. pingsock = create_icmp_socket();
  494. pingaddr.sin = lsa->u.sin;
  495. if (source_lsa) {
  496. if (setsockopt(pingsock, IPPROTO_IP, IP_MULTICAST_IF,
  497. &source_lsa->u.sa, source_lsa->len))
  498. bb_error_msg_and_die("can't set multicast source interface");
  499. xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
  500. }
  501. if (str_I)
  502. setsockopt_bindtodevice(pingsock, str_I);
  503. /* enable broadcast pings */
  504. setsockopt_broadcast(pingsock);
  505. /* set recv buf (needed if we can get lots of responses: flood ping,
  506. * broadcast ping etc) */
  507. sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
  508. setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
  509. signal(SIGINT, print_stats_and_exit);
  510. /* start the ping's going ... */
  511. sendping4(0);
  512. /* listen for replies */
  513. while (1) {
  514. struct sockaddr_in from;
  515. socklen_t fromlen = (socklen_t) sizeof(from);
  516. int c;
  517. c = recvfrom(pingsock, packet, sizeof(packet), 0,
  518. (struct sockaddr *) &from, &fromlen);
  519. if (c < 0) {
  520. if (errno != EINTR)
  521. bb_perror_msg("recvfrom");
  522. continue;
  523. }
  524. unpack4(packet, c, &from);
  525. if (pingcount && nreceived >= pingcount)
  526. break;
  527. }
  528. }
  529. #if ENABLE_PING6
  530. extern int BUG_bad_offsetof_icmp6_cksum(void);
  531. static void ping6(len_and_sockaddr *lsa)
  532. {
  533. char packet[datalen + MAXIPLEN + MAXICMPLEN];
  534. int sockopt;
  535. struct msghdr msg;
  536. struct sockaddr_in6 from;
  537. struct iovec iov;
  538. char control_buf[CMSG_SPACE(36)];
  539. pingsock = create_icmp6_socket();
  540. pingaddr.sin6 = lsa->u.sin6;
  541. /* untested whether "-I addr" really works for IPv6: */
  542. if (source_lsa)
  543. xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
  544. if (str_I)
  545. setsockopt_bindtodevice(pingsock, str_I);
  546. #ifdef ICMP6_FILTER
  547. {
  548. struct icmp6_filter filt;
  549. if (!(option_mask32 & OPT_VERBOSE)) {
  550. ICMP6_FILTER_SETBLOCKALL(&filt);
  551. ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
  552. } else {
  553. ICMP6_FILTER_SETPASSALL(&filt);
  554. }
  555. if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
  556. sizeof(filt)) < 0)
  557. bb_error_msg_and_die("setsockopt(ICMP6_FILTER)");
  558. }
  559. #endif /*ICMP6_FILTER*/
  560. /* enable broadcast pings */
  561. setsockopt_broadcast(pingsock);
  562. /* set recv buf (needed if we can get lots of responses: flood ping,
  563. * broadcast ping etc) */
  564. sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
  565. setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
  566. sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
  567. if (offsetof(struct icmp6_hdr, icmp6_cksum) != 2)
  568. BUG_bad_offsetof_icmp6_cksum();
  569. setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
  570. /* request ttl info to be returned in ancillary data */
  571. setsockopt(pingsock, SOL_IPV6, IPV6_HOPLIMIT, &const_int_1, sizeof(const_int_1));
  572. if (if_index)
  573. pingaddr.sin6.sin6_scope_id = if_index;
  574. signal(SIGINT, print_stats_and_exit);
  575. /* start the ping's going ... */
  576. sendping6(0);
  577. /* listen for replies */
  578. msg.msg_name = &from;
  579. msg.msg_namelen = sizeof(from);
  580. msg.msg_iov = &iov;
  581. msg.msg_iovlen = 1;
  582. msg.msg_control = control_buf;
  583. iov.iov_base = packet;
  584. iov.iov_len = sizeof(packet);
  585. while (1) {
  586. int c;
  587. struct cmsghdr *mp;
  588. int hoplimit = -1;
  589. msg.msg_controllen = sizeof(control_buf);
  590. c = recvmsg(pingsock, &msg, 0);
  591. if (c < 0) {
  592. if (errno != EINTR)
  593. bb_perror_msg("recvfrom");
  594. continue;
  595. }
  596. for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
  597. if (mp->cmsg_level == SOL_IPV6
  598. && mp->cmsg_type == IPV6_HOPLIMIT
  599. /* don't check len - we trust the kernel: */
  600. /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
  601. ) {
  602. hoplimit = *(int*)CMSG_DATA(mp);
  603. }
  604. }
  605. unpack6(packet, c, /*&from,*/ hoplimit);
  606. if (pingcount && nreceived >= pingcount)
  607. break;
  608. }
  609. }
  610. #endif
  611. static void ping(len_and_sockaddr *lsa)
  612. {
  613. printf("PING %s (%s)", hostname, dotted);
  614. if (source_lsa) {
  615. printf(" from %s",
  616. xmalloc_sockaddr2dotted_noport(&source_lsa->u.sa));
  617. }
  618. printf(": %d data bytes\n", datalen);
  619. #if ENABLE_PING6
  620. if (lsa->u.sa.sa_family == AF_INET6)
  621. ping6(lsa);
  622. else
  623. #endif
  624. ping4(lsa);
  625. }
  626. int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  627. int ping_main(int argc UNUSED_PARAM, char **argv)
  628. {
  629. len_and_sockaddr *lsa;
  630. char *str_s;
  631. int opt;
  632. INIT_G();
  633. /* exactly one argument needed; -v and -q don't mix; -c NUM, -w NUM, -W NUM */
  634. opt_complementary = "=1:q--v:v--q:c+:w+:W+";
  635. opt = getopt32(argv, OPT_STRING, &pingcount, &str_s, &deadline, &timeout, &str_I);
  636. if (opt & OPT_s)
  637. datalen = xatou16(str_s); // -s
  638. if (opt & OPT_I) { // -I
  639. if_index = if_nametoindex(str_I);
  640. if (!if_index) {
  641. /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
  642. source_lsa = xdotted2sockaddr(str_I, 0);
  643. str_I = NULL; /* don't try to bind to device later */
  644. }
  645. }
  646. myid = (uint16_t) getpid();
  647. hostname = argv[optind];
  648. #if ENABLE_PING6
  649. {
  650. sa_family_t af = AF_UNSPEC;
  651. if (opt & OPT_IPV4)
  652. af = AF_INET;
  653. if (opt & OPT_IPV6)
  654. af = AF_INET6;
  655. lsa = xhost_and_af2sockaddr(hostname, 0, af);
  656. }
  657. #else
  658. lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
  659. #endif
  660. if (source_lsa && source_lsa->u.sa.sa_family != lsa->u.sa.sa_family)
  661. /* leaking it here... */
  662. source_lsa = NULL;
  663. dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
  664. ping(lsa);
  665. print_stats_and_exit(EXIT_SUCCESS);
  666. /*return EXIT_SUCCESS;*/
  667. }
  668. #endif /* FEATURE_FANCY_PING */
  669. #if ENABLE_PING6
  670. int ping6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  671. int ping6_main(int argc UNUSED_PARAM, char **argv)
  672. {
  673. argv[0] = (char*)"-6";
  674. return ping_main(0 /* argc+1 - but it's unused anyway */,
  675. argv - 1);
  676. }
  677. #endif
  678. /* from ping6.c:
  679. * Copyright (c) 1989 The Regents of the University of California.
  680. * All rights reserved.
  681. *
  682. * This code is derived from software contributed to Berkeley by
  683. * Mike Muuss.
  684. *
  685. * Redistribution and use in source and binary forms, with or without
  686. * modification, are permitted provided that the following conditions
  687. * are met:
  688. * 1. Redistributions of source code must retain the above copyright
  689. * notice, this list of conditions and the following disclaimer.
  690. * 2. Redistributions in binary form must reproduce the above copyright
  691. * notice, this list of conditions and the following disclaimer in the
  692. * documentation and/or other materials provided with the distribution.
  693. *
  694. * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
  695. * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
  696. *
  697. * 4. Neither the name of the University nor the names of its contributors
  698. * may be used to endorse or promote products derived from this software
  699. * without specific prior written permission.
  700. *
  701. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  702. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  703. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  704. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  705. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  706. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  707. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  708. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  709. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  710. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  711. * SUCH DAMAGE.
  712. */