3
0

ping.c 29 KB

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