ping.c 27 KB

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