ping.c 28 KB

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