ping.c 28 KB

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