3
0

ping.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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. #ifdef __BIONIC__
  31. /* should be in netinet/ip_icmp.h */
  32. # define ICMP_DEST_UNREACH 3 /* Destination Unreachable */
  33. # define ICMP_SOURCE_QUENCH 4 /* Source Quench */
  34. # define ICMP_REDIRECT 5 /* Redirect (change route) */
  35. # define ICMP_ECHO 8 /* Echo Request */
  36. # define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */
  37. # define ICMP_PARAMETERPROB 12 /* Parameter Problem */
  38. # define ICMP_TIMESTAMP 13 /* Timestamp Request */
  39. # define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */
  40. # define ICMP_INFO_REQUEST 15 /* Information Request */
  41. # define ICMP_INFO_REPLY 16 /* Information Reply */
  42. # define ICMP_ADDRESS 17 /* Address Mask Request */
  43. # define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */
  44. #endif
  45. //config:config PING
  46. //config: bool "ping"
  47. //config: default y
  48. //config: select PLATFORM_LINUX
  49. //config: help
  50. //config: ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to
  51. //config: elicit an ICMP ECHO_RESPONSE from a host or gateway.
  52. //config:
  53. //config:config PING6
  54. //config: bool "ping6"
  55. //config: default y
  56. //config: depends on FEATURE_IPV6 && PING
  57. //config: help
  58. //config: This will give you a ping that can talk IPv6.
  59. //config:
  60. //config:config FEATURE_FANCY_PING
  61. //config: bool "Enable fancy ping output"
  62. //config: default y
  63. //config: depends on PING
  64. //config: help
  65. //config: Make the output from the ping applet include statistics, and at the
  66. //config: same time provide full support for ICMP packets.
  67. /* Needs socket(AF_INET, SOCK_RAW, IPPROTO_ICMP), therefore BB_SUID_MAYBE: */
  68. //applet:IF_PING(APPLET(ping, BB_DIR_BIN, BB_SUID_MAYBE))
  69. //applet:IF_PING6(APPLET(ping6, BB_DIR_BIN, BB_SUID_MAYBE))
  70. //kbuild:lib-$(CONFIG_PING) += ping.o
  71. //kbuild:lib-$(CONFIG_PING6) += ping.o
  72. //usage:#if !ENABLE_FEATURE_FANCY_PING
  73. //usage:# define ping_trivial_usage
  74. //usage: "HOST"
  75. //usage:# define ping_full_usage "\n\n"
  76. //usage: "Send ICMP ECHO_REQUEST packets to network hosts"
  77. //usage:# define ping6_trivial_usage
  78. //usage: "HOST"
  79. //usage:# define ping6_full_usage "\n\n"
  80. //usage: "Send ICMP ECHO_REQUEST packets to network hosts"
  81. //usage:#else
  82. //usage:# define ping_trivial_usage
  83. //usage: "[OPTIONS] HOST"
  84. //usage:# define ping_full_usage "\n\n"
  85. //usage: "Send ICMP ECHO_REQUEST packets to network hosts\n"
  86. //usage: IF_PING6(
  87. //usage: "\n -4,-6 Force IP or IPv6 name resolution"
  88. //usage: )
  89. //usage: "\n -c CNT Send only CNT pings"
  90. //usage: "\n -s SIZE Send SIZE data bytes in packets (default:56)"
  91. //usage: "\n -t TTL Set TTL"
  92. //usage: "\n -I IFACE/IP Use interface or IP address as source"
  93. //usage: "\n -W SEC Seconds to wait for the first response (default:10)"
  94. //usage: "\n (after all -c CNT packets are sent)"
  95. //usage: "\n -w SEC Seconds until ping exits (default:infinite)"
  96. //usage: "\n (can exit earlier with -c CNT)"
  97. //usage: "\n -q Quiet, only display output at start"
  98. //usage: "\n and when finished"
  99. //usage: "\n -p Pattern to use for payload"
  100. //usage:
  101. //usage:# define ping6_trivial_usage
  102. //usage: "[OPTIONS] HOST"
  103. //usage:# define ping6_full_usage "\n\n"
  104. //usage: "Send ICMP ECHO_REQUEST packets to network hosts\n"
  105. //usage: "\n -c CNT Send only CNT pings"
  106. //usage: "\n -s SIZE Send SIZE data bytes in packets (default:56)"
  107. //usage: "\n -I IFACE/IP Use interface or IP address as source"
  108. //usage: "\n -q Quiet, only display output at start"
  109. //usage: "\n and when finished"
  110. //usage: "\n -p Pattern to use for payload"
  111. //usage:
  112. //usage:#endif
  113. //usage:
  114. //usage:#define ping_example_usage
  115. //usage: "$ ping localhost\n"
  116. //usage: "PING slag (127.0.0.1): 56 data bytes\n"
  117. //usage: "64 bytes from 127.0.0.1: icmp_seq=0 ttl=255 time=20.1 ms\n"
  118. //usage: "\n"
  119. //usage: "--- debian ping statistics ---\n"
  120. //usage: "1 packets transmitted, 1 packets received, 0% packet loss\n"
  121. //usage: "round-trip min/avg/max = 20.1/20.1/20.1 ms\n"
  122. //usage:#define ping6_example_usage
  123. //usage: "$ ping6 ip6-localhost\n"
  124. //usage: "PING ip6-localhost (::1): 56 data bytes\n"
  125. //usage: "64 bytes from ::1: icmp6_seq=0 ttl=64 time=20.1 ms\n"
  126. //usage: "\n"
  127. //usage: "--- ip6-localhost ping statistics ---\n"
  128. //usage: "1 packets transmitted, 1 packets received, 0% packet loss\n"
  129. //usage: "round-trip min/avg/max = 20.1/20.1/20.1 ms\n"
  130. #if ENABLE_PING6
  131. # include <netinet/icmp6.h>
  132. /* I see RENUMBERED constants in bits/in.h - !!?
  133. * What a fuck is going on with libc? Is it a glibc joke? */
  134. # ifdef IPV6_2292HOPLIMIT
  135. # undef IPV6_HOPLIMIT
  136. # define IPV6_HOPLIMIT IPV6_2292HOPLIMIT
  137. # endif
  138. #endif
  139. enum {
  140. DEFDATALEN = 56,
  141. MAXIPLEN = 60,
  142. MAXICMPLEN = 76,
  143. MAX_DUP_CHK = (8 * 128),
  144. MAXWAIT = 10,
  145. PINGINTERVAL = 1, /* 1 second */
  146. pingsock = 0,
  147. };
  148. static void
  149. #if ENABLE_PING6
  150. create_icmp_socket(len_and_sockaddr *lsa)
  151. #else
  152. create_icmp_socket(void)
  153. #define create_icmp_socket(lsa) create_icmp_socket()
  154. #endif
  155. {
  156. int sock;
  157. #if ENABLE_PING6
  158. if (lsa->u.sa.sa_family == AF_INET6)
  159. sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
  160. else
  161. #endif
  162. sock = socket(AF_INET, SOCK_RAW, 1); /* 1 == ICMP */
  163. if (sock < 0) {
  164. if (errno == EPERM)
  165. bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
  166. bb_perror_msg_and_die(bb_msg_can_not_create_raw_socket);
  167. }
  168. xmove_fd(sock, pingsock);
  169. }
  170. #if !ENABLE_FEATURE_FANCY_PING
  171. /* Simple version */
  172. struct globals {
  173. char *hostname;
  174. char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
  175. } FIX_ALIASING;
  176. #define G (*(struct globals*)&bb_common_bufsiz1)
  177. #define INIT_G() do { } while (0)
  178. static void noresp(int ign UNUSED_PARAM)
  179. {
  180. printf("No response from %s\n", G.hostname);
  181. exit(EXIT_FAILURE);
  182. }
  183. static void ping4(len_and_sockaddr *lsa)
  184. {
  185. struct icmp *pkt;
  186. int c;
  187. pkt = (struct icmp *) G.packet;
  188. /*memset(pkt, 0, sizeof(G.packet)); already is */
  189. pkt->icmp_type = ICMP_ECHO;
  190. pkt->icmp_cksum = inet_cksum((uint16_t *) pkt, sizeof(G.packet));
  191. xsendto(pingsock, G.packet, DEFDATALEN + ICMP_MINLEN, &lsa->u.sa, lsa->len);
  192. /* listen for replies */
  193. while (1) {
  194. #if 0
  195. struct sockaddr_in from;
  196. socklen_t fromlen = sizeof(from);
  197. c = recvfrom(pingsock, G.packet, sizeof(G.packet), 0,
  198. (struct sockaddr *) &from, &fromlen);
  199. #else
  200. c = recv(pingsock, G.packet, sizeof(G.packet), 0);
  201. #endif
  202. if (c < 0) {
  203. if (errno != EINTR)
  204. bb_perror_msg("recvfrom");
  205. continue;
  206. }
  207. if (c >= 76) { /* ip + icmp */
  208. struct iphdr *iphdr = (struct iphdr *) G.packet;
  209. pkt = (struct icmp *) (G.packet + (iphdr->ihl << 2)); /* skip ip hdr */
  210. if (pkt->icmp_type == ICMP_ECHOREPLY)
  211. break;
  212. }
  213. }
  214. if (ENABLE_FEATURE_CLEAN_UP)
  215. close(pingsock);
  216. }
  217. #if ENABLE_PING6
  218. static void ping6(len_and_sockaddr *lsa)
  219. {
  220. struct icmp6_hdr *pkt;
  221. int c;
  222. int sockopt;
  223. pkt = (struct icmp6_hdr *) G.packet;
  224. /*memset(pkt, 0, sizeof(G.packet)); already is */
  225. pkt->icmp6_type = ICMP6_ECHO_REQUEST;
  226. sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
  227. setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
  228. xsendto(pingsock, G.packet, DEFDATALEN + sizeof(struct icmp6_hdr), &lsa->u.sa, lsa->len);
  229. /* listen for replies */
  230. while (1) {
  231. #if 0
  232. struct sockaddr_in6 from;
  233. socklen_t fromlen = sizeof(from);
  234. c = recvfrom(pingsock, G.packet, sizeof(G.packet), 0,
  235. (struct sockaddr *) &from, &fromlen);
  236. #else
  237. c = recv(pingsock, G.packet, sizeof(G.packet), 0);
  238. #endif
  239. if (c < 0) {
  240. if (errno != EINTR)
  241. bb_perror_msg("recvfrom");
  242. continue;
  243. }
  244. if (c >= ICMP_MINLEN) { /* icmp6_hdr */
  245. if (pkt->icmp6_type == ICMP6_ECHO_REPLY)
  246. break;
  247. }
  248. }
  249. if (ENABLE_FEATURE_CLEAN_UP)
  250. close(pingsock);
  251. }
  252. #endif
  253. #if !ENABLE_PING6
  254. # define common_ping_main(af, argv) common_ping_main(argv)
  255. #endif
  256. static int common_ping_main(sa_family_t af, char **argv)
  257. {
  258. len_and_sockaddr *lsa;
  259. INIT_G();
  260. #if ENABLE_PING6
  261. while ((++argv)[0] && argv[0][0] == '-') {
  262. if (argv[0][1] == '4') {
  263. af = AF_INET;
  264. continue;
  265. }
  266. if (argv[0][1] == '6') {
  267. af = AF_INET6;
  268. continue;
  269. }
  270. bb_show_usage();
  271. }
  272. #else
  273. argv++;
  274. #endif
  275. G.hostname = *argv;
  276. if (!G.hostname)
  277. bb_show_usage();
  278. #if ENABLE_PING6
  279. lsa = xhost_and_af2sockaddr(G.hostname, 0, af);
  280. #else
  281. lsa = xhost_and_af2sockaddr(G.hostname, 0, AF_INET);
  282. #endif
  283. /* Set timer _after_ DNS resolution */
  284. signal(SIGALRM, noresp);
  285. alarm(5); /* give the host 5000ms to respond */
  286. create_icmp_socket(lsa);
  287. #if ENABLE_PING6
  288. if (lsa->u.sa.sa_family == AF_INET6)
  289. ping6(lsa);
  290. else
  291. #endif
  292. ping4(lsa);
  293. printf("%s is alive!\n", G.hostname);
  294. return EXIT_SUCCESS;
  295. }
  296. #else /* FEATURE_FANCY_PING */
  297. /* Full(er) version */
  298. #define OPT_STRING ("qvc:s:t:w:W:I:np:4" IF_PING6("6"))
  299. enum {
  300. OPT_QUIET = 1 << 0,
  301. OPT_VERBOSE = 1 << 1,
  302. OPT_c = 1 << 2,
  303. OPT_s = 1 << 3,
  304. OPT_t = 1 << 4,
  305. OPT_w = 1 << 5,
  306. OPT_W = 1 << 6,
  307. OPT_I = 1 << 7,
  308. /*OPT_n = 1 << 8, - ignored */
  309. OPT_p = 1 << 9,
  310. OPT_IPV4 = 1 << 10,
  311. OPT_IPV6 = (1 << 11) * ENABLE_PING6,
  312. };
  313. struct globals {
  314. int if_index;
  315. char *str_I;
  316. len_and_sockaddr *source_lsa;
  317. unsigned datalen;
  318. unsigned pingcount; /* must be int-sized */
  319. unsigned opt_ttl;
  320. unsigned long ntransmitted, nreceived, nrepeats;
  321. uint16_t myid;
  322. uint8_t pattern;
  323. unsigned tmin, tmax; /* in us */
  324. unsigned long long tsum; /* in us, sum of all times */
  325. unsigned deadline;
  326. unsigned timeout;
  327. unsigned total_secs;
  328. unsigned sizeof_rcv_packet;
  329. char *rcv_packet; /* [datalen + MAXIPLEN + MAXICMPLEN] */
  330. void *snd_packet; /* [datalen + ipv4/ipv6_const] */
  331. const char *hostname;
  332. const char *dotted;
  333. union {
  334. struct sockaddr sa;
  335. struct sockaddr_in sin;
  336. #if ENABLE_PING6
  337. struct sockaddr_in6 sin6;
  338. #endif
  339. } pingaddr;
  340. unsigned char rcvd_tbl[MAX_DUP_CHK / 8];
  341. } FIX_ALIASING;
  342. #define G (*(struct globals*)&bb_common_bufsiz1)
  343. #define if_index (G.if_index )
  344. #define source_lsa (G.source_lsa )
  345. #define str_I (G.str_I )
  346. #define datalen (G.datalen )
  347. #define pingcount (G.pingcount )
  348. #define opt_ttl (G.opt_ttl )
  349. #define myid (G.myid )
  350. #define tmin (G.tmin )
  351. #define tmax (G.tmax )
  352. #define tsum (G.tsum )
  353. #define deadline (G.deadline )
  354. #define timeout (G.timeout )
  355. #define total_secs (G.total_secs )
  356. #define hostname (G.hostname )
  357. #define dotted (G.dotted )
  358. #define pingaddr (G.pingaddr )
  359. #define rcvd_tbl (G.rcvd_tbl )
  360. void BUG_ping_globals_too_big(void);
  361. #define INIT_G() do { \
  362. if (sizeof(G) > COMMON_BUFSIZE) \
  363. BUG_ping_globals_too_big(); \
  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(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
  627. if (opt_ttl != 0) {
  628. setsockopt(pingsock, IPPROTO_IP, IP_TTL, &opt_ttl, sizeof(opt_ttl));
  629. /* above doesnt affect packets sent to bcast IP, so... */
  630. setsockopt(pingsock, IPPROTO_IP, IP_MULTICAST_TTL, &opt_ttl, sizeof(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. extern int BUG_bad_offsetof_icmp6_cksum(void);
  654. static void ping6(len_and_sockaddr *lsa)
  655. {
  656. int sockopt;
  657. struct msghdr msg;
  658. struct sockaddr_in6 from;
  659. struct iovec iov;
  660. char control_buf[CMSG_SPACE(36)];
  661. pingaddr.sin6 = lsa->u.sin6;
  662. if (source_lsa)
  663. xbind(pingsock, &source_lsa->u.sa, source_lsa->len);
  664. #ifdef ICMP6_FILTER
  665. {
  666. struct icmp6_filter filt;
  667. if (!(option_mask32 & OPT_VERBOSE)) {
  668. ICMP6_FILTER_SETBLOCKALL(&filt);
  669. ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt);
  670. } else {
  671. ICMP6_FILTER_SETPASSALL(&filt);
  672. }
  673. if (setsockopt(pingsock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt,
  674. sizeof(filt)) < 0)
  675. bb_error_msg_and_die("setsockopt(ICMP6_FILTER)");
  676. }
  677. #endif /*ICMP6_FILTER*/
  678. /* enable broadcast pings */
  679. setsockopt_broadcast(pingsock);
  680. /* set recv buf (needed if we can get lots of responses: flood ping,
  681. * broadcast ping etc) */
  682. sockopt = (datalen * 2) + 7 * 1024; /* giving it a bit of extra room */
  683. setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof(sockopt));
  684. sockopt = offsetof(struct icmp6_hdr, icmp6_cksum);
  685. if (offsetof(struct icmp6_hdr, icmp6_cksum) != 2)
  686. BUG_bad_offsetof_icmp6_cksum();
  687. setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt));
  688. /* request ttl info to be returned in ancillary data */
  689. setsockopt(pingsock, SOL_IPV6, IPV6_HOPLIMIT, &const_int_1, sizeof(const_int_1));
  690. if (if_index)
  691. pingaddr.sin6.sin6_scope_id = if_index;
  692. signal(SIGINT, print_stats_and_exit);
  693. /* start the ping's going ... */
  694. sendping6(0);
  695. /* listen for replies */
  696. msg.msg_name = &from;
  697. msg.msg_namelen = sizeof(from);
  698. msg.msg_iov = &iov;
  699. msg.msg_iovlen = 1;
  700. msg.msg_control = control_buf;
  701. iov.iov_base = G.rcv_packet;
  702. iov.iov_len = G.sizeof_rcv_packet;
  703. while (1) {
  704. int c;
  705. struct cmsghdr *mp;
  706. int hoplimit = -1;
  707. msg.msg_controllen = sizeof(control_buf);
  708. c = recvmsg(pingsock, &msg, 0);
  709. if (c < 0) {
  710. if (errno != EINTR)
  711. bb_perror_msg("recvfrom");
  712. continue;
  713. }
  714. for (mp = CMSG_FIRSTHDR(&msg); mp; mp = CMSG_NXTHDR(&msg, mp)) {
  715. if (mp->cmsg_level == SOL_IPV6
  716. && mp->cmsg_type == IPV6_HOPLIMIT
  717. /* don't check len - we trust the kernel: */
  718. /* && mp->cmsg_len >= CMSG_LEN(sizeof(int)) */
  719. ) {
  720. /*hoplimit = *(int*)CMSG_DATA(mp); - unaligned access */
  721. move_from_unaligned_int(hoplimit, CMSG_DATA(mp));
  722. }
  723. }
  724. unpack6(G.rcv_packet, c, &from, hoplimit);
  725. if (pingcount && G.nreceived >= pingcount)
  726. break;
  727. }
  728. }
  729. #endif
  730. static void ping(len_and_sockaddr *lsa)
  731. {
  732. printf("PING %s (%s)", hostname, dotted);
  733. if (source_lsa) {
  734. printf(" from %s",
  735. xmalloc_sockaddr2dotted_noport(&source_lsa->u.sa));
  736. }
  737. printf(": %d data bytes\n", datalen);
  738. create_icmp_socket(lsa);
  739. /* untested whether "-I addr" really works for IPv6: */
  740. if (str_I)
  741. setsockopt_bindtodevice(pingsock, str_I);
  742. G.sizeof_rcv_packet = datalen + MAXIPLEN + MAXICMPLEN;
  743. G.rcv_packet = xzalloc(G.sizeof_rcv_packet);
  744. #if ENABLE_PING6
  745. if (lsa->u.sa.sa_family == AF_INET6) {
  746. /* +4 reserves a place for timestamp, which may end up sitting
  747. * _after_ packet. Saves one if() - see sendping4/6() */
  748. G.snd_packet = xzalloc(datalen + sizeof(struct icmp6_hdr) + 4);
  749. ping6(lsa);
  750. } else
  751. #endif
  752. {
  753. G.snd_packet = xzalloc(datalen + ICMP_MINLEN + 4);
  754. ping4(lsa);
  755. }
  756. }
  757. static int common_ping_main(int opt, char **argv)
  758. {
  759. len_and_sockaddr *lsa;
  760. char *str_s, *str_p;
  761. INIT_G();
  762. /* exactly one argument needed; -v and -q don't mix; -c NUM, -t NUM, -w NUM, -W NUM */
  763. opt_complementary = "=1:q--v:v--q:c+:t+:w+:W+";
  764. opt |= getopt32(argv, OPT_STRING, &pingcount, &str_s, &opt_ttl, &deadline, &timeout, &str_I, &str_p);
  765. if (opt & OPT_s)
  766. datalen = xatou16(str_s); // -s
  767. if (opt & OPT_I) { // -I
  768. if_index = if_nametoindex(str_I);
  769. if (!if_index) {
  770. /* TODO: I'm not sure it takes IPv6 unless in [XX:XX..] format */
  771. source_lsa = xdotted2sockaddr(str_I, 0);
  772. str_I = NULL; /* don't try to bind to device later */
  773. }
  774. }
  775. if (opt & OPT_p)
  776. G.pattern = xstrtou_range(str_p, 16, 0, 255);
  777. myid = (uint16_t) getpid();
  778. hostname = argv[optind];
  779. #if ENABLE_PING6
  780. {
  781. sa_family_t af = AF_UNSPEC;
  782. if (opt & OPT_IPV4)
  783. af = AF_INET;
  784. if (opt & OPT_IPV6)
  785. af = AF_INET6;
  786. lsa = xhost_and_af2sockaddr(hostname, 0, af);
  787. }
  788. #else
  789. lsa = xhost_and_af2sockaddr(hostname, 0, AF_INET);
  790. #endif
  791. if (source_lsa && source_lsa->u.sa.sa_family != lsa->u.sa.sa_family)
  792. /* leaking it here... */
  793. source_lsa = NULL;
  794. dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
  795. ping(lsa);
  796. print_stats_and_exit(EXIT_SUCCESS);
  797. /*return EXIT_SUCCESS;*/
  798. }
  799. #endif /* FEATURE_FANCY_PING */
  800. int ping_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  801. int ping_main(int argc UNUSED_PARAM, char **argv)
  802. {
  803. #if !ENABLE_FEATURE_FANCY_PING
  804. return common_ping_main(AF_UNSPEC, argv);
  805. #else
  806. return common_ping_main(0, argv);
  807. #endif
  808. }
  809. #if ENABLE_PING6
  810. int ping6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  811. int ping6_main(int argc UNUSED_PARAM, char **argv)
  812. {
  813. # if !ENABLE_FEATURE_FANCY_PING
  814. return common_ping_main(AF_INET6, argv);
  815. # else
  816. return common_ping_main(OPT_IPV6, argv);
  817. # endif
  818. }
  819. #endif
  820. /* from ping6.c:
  821. * Copyright (c) 1989 The Regents of the University of California.
  822. * All rights reserved.
  823. *
  824. * This code is derived from software contributed to Berkeley by
  825. * Mike Muuss.
  826. *
  827. * Redistribution and use in source and binary forms, with or without
  828. * modification, are permitted provided that the following conditions
  829. * are met:
  830. * 1. Redistributions of source code must retain the above copyright
  831. * notice, this list of conditions and the following disclaimer.
  832. * 2. Redistributions in binary form must reproduce the above copyright
  833. * notice, this list of conditions and the following disclaimer in the
  834. * documentation and/or other materials provided with the distribution.
  835. *
  836. * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
  837. * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
  838. *
  839. * 4. Neither the name of the University nor the names of its contributors
  840. * may be used to endorse or promote products derived from this software
  841. * without specific prior written permission.
  842. *
  843. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  844. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  845. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  846. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  847. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  848. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  849. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  850. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  851. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  852. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  853. * SUCH DAMAGE.
  854. */