3
0

ping.c 29 KB

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