ping.c 27 KB

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