ping.c 23 KB

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