ping.c 30 KB

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