ping.c 27 KB

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