ping.c 27 KB

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