ping.c 27 KB

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