ping.hpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. /*
  2. * Copyright (c) 2017-2023 zhllxt
  3. *
  4. * author : zhllxt
  5. * email : 37792738@qq.com
  6. *
  7. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. */
  10. #ifndef __ASIO2_PING_HPP__
  11. #define __ASIO2_PING_HPP__
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. #pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <asio2/base/detail/push_options.hpp>
  16. #include <cstdint>
  17. #include <memory>
  18. #include <chrono>
  19. #include <functional>
  20. #include <atomic>
  21. #include <string>
  22. #include <string_view>
  23. #include <queue>
  24. #include <any>
  25. #include <future>
  26. #include <tuple>
  27. #include <asio2/base/iopool.hpp>
  28. #include <asio2/base/listener.hpp>
  29. #include <asio2/base/define.hpp>
  30. #include <asio2/base/detail/object.hpp>
  31. #include <asio2/base/detail/allocator.hpp>
  32. #include <asio2/base/detail/util.hpp>
  33. #include <asio2/base/detail/buffer_wrap.hpp>
  34. #include <asio2/base/impl/thread_id_cp.hpp>
  35. #include <asio2/base/impl/user_data_cp.hpp>
  36. #include <asio2/base/impl/socket_cp.hpp>
  37. #include <asio2/base/impl/user_timer_cp.hpp>
  38. #include <asio2/base/impl/post_cp.hpp>
  39. #include <asio2/base/impl/event_queue_cp.hpp>
  40. #include <asio2/base/impl/condition_event_cp.hpp>
  41. #include <asio2/icmp/detail/icmp_header.hpp>
  42. #include <asio2/icmp/detail/ipv4_header.hpp>
  43. #include <asio2/icmp/detail/ipv6_header.hpp>
  44. namespace asio2
  45. {
  46. class icmp_rep : public detail::ipv4_header, /*public detail::ipv6_header,*/ public detail::icmp_header
  47. {
  48. public:
  49. std::chrono::steady_clock::duration lag{ std::chrono::steady_clock::duration(-1) };
  50. inline bool is_timeout() const noexcept { return (this->lag.count() == -1); }
  51. inline auto get_milliseconds() const noexcept
  52. {
  53. return this->lag.count() == -1 ? -1 :
  54. std::chrono::duration_cast<std::chrono::milliseconds>(this->lag).count();
  55. }
  56. inline auto milliseconds() const noexcept
  57. {
  58. return this->get_milliseconds();
  59. }
  60. detail::ipv4_header& base_ipv4() noexcept { return static_cast<detail::ipv4_header&>(*this); }
  61. //detail::ipv6_header& base_ipv6() noexcept { return static_cast<detail::ipv6_header&>(*this); }
  62. detail::icmp_header& base_icmp() noexcept { return static_cast<detail::icmp_header&>(*this); }
  63. detail::ipv4_header const& base_ipv4() const noexcept { return static_cast<detail::ipv4_header const&>(*this); }
  64. //detail::ipv6_header const& base_ipv6() const noexcept { return static_cast<detail::ipv6_header&>(*this); }
  65. detail::icmp_header const& base_icmp() const noexcept { return static_cast<detail::icmp_header const&>(*this); }
  66. protected:
  67. };
  68. }
  69. namespace asio2::detail
  70. {
  71. struct template_args_icmp
  72. {
  73. using socket_t = asio::ip::icmp::socket;
  74. using buffer_t = asio::streambuf;
  75. static constexpr std::size_t allocator_storage_size = 256;
  76. };
  77. ASIO2_CLASS_FORWARD_DECLARE_BASE;
  78. template<class derived_t, class args_t = template_args_icmp>
  79. class ping_impl_t
  80. : public object_t <derived_t >
  81. , public iopool_cp <derived_t, args_t>
  82. , public thread_id_cp <derived_t, args_t>
  83. , public user_data_cp <derived_t, args_t>
  84. , public user_timer_cp <derived_t, args_t>
  85. , public post_cp <derived_t, args_t>
  86. , public condition_event_cp<derived_t, args_t>
  87. {
  88. ASIO2_CLASS_FRIEND_DECLARE_BASE;
  89. public:
  90. using super = object_t <derived_t >;
  91. using self = ping_impl_t<derived_t, args_t>;
  92. using iopoolcp = iopool_cp<derived_t, args_t>;
  93. using args_type = args_t;
  94. using socket_type = typename args_t::socket_t;
  95. using buffer_type = typename args_t::buffer_t;
  96. /**
  97. * @brief constructor
  98. * @param send_count - Total number of echo packets you want to send,
  99. * send_count equals -1 for infinite send,
  100. * Other parameters should use default values.
  101. */
  102. explicit ping_impl_t(
  103. std::size_t send_count = -1,
  104. std::size_t init_buf_size = 64 * 1024, // We prepare the buffer to receive up to 64KB.
  105. std::size_t max_buf_size = max_buffer_size,
  106. std::size_t concurrency = 1
  107. )
  108. : super()
  109. , iopool_cp <derived_t, args_t>(concurrency)
  110. , user_data_cp <derived_t, args_t>()
  111. , user_timer_cp <derived_t, args_t>()
  112. , post_cp <derived_t, args_t>()
  113. , condition_event_cp <derived_t, args_t>()
  114. , rallocator_()
  115. , wallocator_()
  116. , listener_ ()
  117. , io_ (iopoolcp::_get_io(0))
  118. , buffer_ (init_buf_size, max_buf_size)
  119. , socket_ (std::make_shared<socket_type>(iopoolcp::_get_io(0)->context()))
  120. , timer_ (std::make_unique<asio::steady_timer>(iopoolcp::_get_io(0)->context()))
  121. , ncount_ (send_count)
  122. {
  123. }
  124. template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
  125. explicit ping_impl_t(
  126. std::size_t send_count,
  127. std::size_t init_buf_size,
  128. std::size_t max_buf_size,
  129. Scheduler&& scheduler
  130. )
  131. : super()
  132. , iopool_cp <derived_t, args_t>(std::forward<Scheduler>(scheduler))
  133. , user_data_cp <derived_t, args_t>()
  134. , user_timer_cp <derived_t, args_t>()
  135. , post_cp <derived_t, args_t>()
  136. , condition_event_cp <derived_t, args_t>()
  137. , rallocator_()
  138. , wallocator_()
  139. , listener_ ()
  140. , io_ (iopoolcp::_get_io(0))
  141. , buffer_ (init_buf_size, max_buf_size)
  142. , socket_ (std::make_shared<socket_type>(iopoolcp::_get_io(0)->context()))
  143. , timer_ (std::make_unique<asio::steady_timer>(iopoolcp::_get_io(0)->context()))
  144. , ncount_ (send_count)
  145. {
  146. }
  147. template<class Scheduler, std::enable_if_t<!std::is_integral_v<detail::remove_cvref_t<Scheduler>>, int> = 0>
  148. explicit ping_impl_t(Scheduler&& scheduler)
  149. : ping_impl_t(std::size_t(-1), 64 * 1024, max_buffer_size, std::forward<Scheduler>(scheduler))
  150. {
  151. }
  152. /**
  153. * @brief destructor
  154. */
  155. ~ping_impl_t()
  156. {
  157. this->stop();
  158. }
  159. /**
  160. * @brief start
  161. * @param host - A string identifying a location. May be a descriptive name or
  162. * a numeric address string. example : "151.101.193.69" or "www.google.com"
  163. */
  164. template<typename String>
  165. inline bool start(String&& host)
  166. {
  167. return this->derived()._do_start(std::forward<String>(host));
  168. }
  169. /**
  170. * @brief stop
  171. */
  172. inline void stop()
  173. {
  174. if (this->is_iopool_stopped())
  175. return;
  176. derived_t& derive = this->derived();
  177. derive.io_->unregobj(&derive);
  178. derive.dispatch([&derive]() mutable
  179. {
  180. derive._do_stop(asio::error::operation_aborted, derive.selfptr());
  181. });
  182. this->stop_iopool();
  183. }
  184. /**
  185. * @brief destroy the content of all member variables, this is used for solve the memory leaks.
  186. * After this function is called, this class object cannot be used again.
  187. */
  188. inline void destroy()
  189. {
  190. derived_t& derive = this->derived();
  191. derive.timer_.reset();
  192. derive.socket_.reset();
  193. derive.io_.reset();
  194. derive.listener_.clear();
  195. derive.destroy_iopool();
  196. }
  197. /**
  198. * @brief check whether the client is started
  199. */
  200. inline bool is_started() const
  201. {
  202. return (this->state_ == state_t::started && this->socket_->is_open());
  203. }
  204. /**
  205. * @brief check whether the client is stopped
  206. */
  207. inline bool is_stopped() const
  208. {
  209. return (this->state_ == state_t::stopped && !this->socket_->is_open());
  210. }
  211. public:
  212. /**
  213. * @brief sync ping the host, and return the response directly.
  214. * if some error occurs, call asio2::get_last_error(); to get the error info.
  215. */
  216. template<class Rep, class Period>
  217. static inline icmp_rep execute(
  218. std::string_view host, std::chrono::duration<Rep, Period> timeout, std::string body)
  219. {
  220. icmp_rep rep;
  221. // First assign default value timed_out to last error
  222. set_last_error(asio::error::timed_out);
  223. // The io_context is required for all I/O
  224. asio::io_context ioc;
  225. // These objects perform our I/O
  226. asio::ip::icmp::resolver resolver{ ioc };
  227. asio::ip::icmp::socket socket{ ioc };
  228. asio::streambuf request_buffer;
  229. asio::streambuf reply_buffer;
  230. std::ostream os(std::addressof(request_buffer));
  231. std::istream is(std::addressof(reply_buffer));
  232. icmp_header echo_request;
  233. unsigned short id = static_cast<unsigned short>(0);
  234. unsigned short sequence_number = static_cast<unsigned short>(0);
  235. decltype(std::chrono::steady_clock::now()) time_sent;
  236. // Look up the domain name
  237. resolver.async_resolve(host, "",
  238. [&](const error_code& ec1, const asio::ip::icmp::resolver::results_type& endpoints) mutable
  239. {
  240. if (ec1) { set_last_error(ec1); return; }
  241. for (auto& dest : endpoints)
  242. {
  243. struct socket_guard
  244. {
  245. socket_guard(asio::ip::icmp::socket& s) : socket(s)
  246. {
  247. error_code ec_ignore{};
  248. socket.cancel(ec_ignore);
  249. socket.close(ec_ignore);
  250. }
  251. ~socket_guard()
  252. {
  253. error_code ec_ignore{};
  254. // Gracefully close the socket
  255. socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec_ignore);
  256. socket.cancel(ec_ignore);
  257. socket.close(ec_ignore);
  258. }
  259. asio::ip::icmp::socket& socket;
  260. };
  261. std::unique_ptr<socket_guard> guarder = std::make_unique<socket_guard>(socket);
  262. error_code ec_open{};
  263. socket.open(dest.endpoint().protocol(), ec_open);
  264. if (ec_open) { set_last_error(ec_open); return; }
  265. // Create an ICMP header for an echo request.
  266. echo_request.type(icmp_header::echo_request);
  267. echo_request.code(0);
  268. id = (unsigned short)(std::size_t(guarder.get()));
  269. echo_request.identifier(id);
  270. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  271. std::chrono::steady_clock::now().time_since_epoch()).count();
  272. sequence_number = static_cast<unsigned short>(ms % (std::numeric_limits<unsigned short>::max)());
  273. echo_request.sequence_number(sequence_number);
  274. compute_checksum(echo_request, body.begin(), body.end());
  275. // Encode the request packet.
  276. os << echo_request << body;
  277. // Send the request.
  278. time_sent = std::chrono::steady_clock::now();
  279. socket.async_send_to(request_buffer.data(), dest, [&, guarder = std::move(guarder)]
  280. (const error_code& ec2, std::size_t) mutable
  281. {
  282. if (ec2) { set_last_error(ec2); return; }
  283. // Discard any data already in the buffer.
  284. reply_buffer.consume(reply_buffer.size());
  285. std::size_t length = sizeof(ipv4_header) + sizeof(icmp_header) + body.size();
  286. // Wait for a reply. We prepare the buffer to receive up to 64KB.
  287. socket.async_receive(reply_buffer.prepare(length), [&, guarder = std::move(guarder)]
  288. (const error_code& ec3, std::size_t bytes_recvd) mutable
  289. {
  290. set_last_error(ec3);
  291. // The actual number of bytes received is committed to the buffer so that we
  292. // can extract it using a std::istream object.
  293. reply_buffer.commit(bytes_recvd);
  294. // Decode the reply packet.
  295. ipv4_header& ipv4_hdr = rep.base_ipv4();
  296. icmp_header& icmp_hdr = rep.base_icmp();
  297. is >> ipv4_hdr >> icmp_hdr;
  298. ASIO2_ASSERT(ipv4_hdr.total_length() == bytes_recvd);
  299. // We can receive all ICMP packets received by the host, so we need to
  300. // filter out only the echo replies that match the our identifier and
  301. // expected sequence number.
  302. if (is && icmp_hdr.type() == icmp_header::echo_reply
  303. && icmp_hdr.identifier() == id
  304. && icmp_hdr.sequence_number() == sequence_number)
  305. {
  306. // Print out some information about the reply packet.
  307. rep.lag = std::chrono::steady_clock::now() - time_sent;
  308. }
  309. });
  310. });
  311. break;
  312. }
  313. });
  314. // timedout run
  315. ioc.run_for(timeout);
  316. error_code ec_ignore{};
  317. // Gracefully close the socket
  318. socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec_ignore);
  319. socket.cancel(ec_ignore);
  320. socket.close(ec_ignore);
  321. return rep;
  322. }
  323. /**
  324. * @brief sync ping the host, and return the response directly.
  325. * if some error occurs, call asio2::get_last_error(); to get the error info.
  326. */
  327. template<class Rep, class Period>
  328. static inline icmp_rep execute(std::string_view host, std::chrono::duration<Rep, Period> timeout)
  329. {
  330. return derived_t::execute(host, timeout, R"("Hello!" from Asio ping.)");
  331. }
  332. /**
  333. * @brief sync ping the host, and return the response directly.
  334. * if some error occurs, call asio2::get_last_error(); to get the error info.
  335. */
  336. static inline icmp_rep execute(std::string_view host)
  337. {
  338. return derived_t::execute(host, std::chrono::milliseconds(icmp_execute_timeout), R"("Hello!" from Asio ping.)");
  339. }
  340. public:
  341. /**
  342. * @brief bind recv listener
  343. * @param fun - a user defined callback function.
  344. * @li void on_recv(asio2::icmp_rep& rep){...}
  345. * or a lumbda function like this :
  346. * [&](asio2::icmp_rep& rep){...}
  347. */
  348. template<class F, class ...C>
  349. inline derived_t & bind_recv(F&& fun, C&&... obj)
  350. {
  351. this->listener_.bind(event_type::recv,
  352. observer_t<icmp_rep&>(std::forward<F>(fun), std::forward<C>(obj)...));
  353. return (this->derived());
  354. }
  355. /**
  356. * @brief bind init listener,we should set socket options at here
  357. * @param fun - a user defined callback function.
  358. * @li This notification is called after the socket is opened.
  359. * You can set the socket option in this notification.
  360. * Function signature : void()
  361. */
  362. template<class F, class ...C>
  363. inline derived_t & bind_init(F&& fun, C&&... obj)
  364. {
  365. this->listener_.bind(event_type::init,
  366. observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
  367. return (this->derived());
  368. }
  369. /**
  370. * @brief bind start listener
  371. * @param fun - a user defined callback function.
  372. * @li This notification is called after the server starts up, whether successful or unsuccessful
  373. * Function signature : void()
  374. */
  375. template<class F, class ...C>
  376. inline derived_t & bind_start(F&& fun, C&&... obj)
  377. {
  378. this->listener_.bind(event_type::start,
  379. observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
  380. return (this->derived());
  381. }
  382. /**
  383. * @brief bind stop listener
  384. * @param fun - a user defined callback function.
  385. * @li This notification is called before the server is ready to stop
  386. * Function signature : void()
  387. */
  388. template<class F, class ...C>
  389. inline derived_t & bind_stop(F&& fun, C&&... obj)
  390. {
  391. this->listener_.bind(event_type::stop,
  392. observer_t<>(std::forward<F>(fun), std::forward<C>(obj)...));
  393. return (this->derived());
  394. }
  395. public:
  396. /**
  397. * @brief get the socket object reference
  398. */
  399. inline socket_type & socket() noexcept { return *(this->socket_); }
  400. /**
  401. * @brief get the socket object reference
  402. */
  403. inline const socket_type & socket() const noexcept { return *(this->socket_); }
  404. /**
  405. * @brief get the stream object reference
  406. */
  407. inline socket_type & stream() noexcept { return *(this->socket_); }
  408. /**
  409. * @brief get the stream object reference
  410. */
  411. inline const socket_type & stream() const noexcept { return *(this->socket_); }
  412. public:
  413. /**
  414. * @brief set icmp protocol identifier
  415. */
  416. template<class Integer>
  417. inline derived_t & set_identifier(Integer id) noexcept
  418. {
  419. this->identifier_ = (unsigned short)(std::size_t(id));
  420. return (this->derived());
  421. }
  422. /**
  423. * @brief get icmp protocol identifier
  424. */
  425. inline unsigned short get_identifier() const noexcept
  426. {
  427. return this->identifier_;
  428. }
  429. /**
  430. * @brief set reply timeout duration value
  431. */
  432. template<class Rep, class Period>
  433. inline derived_t & set_timeout(std::chrono::duration<Rep, Period> duration) noexcept
  434. {
  435. this->timeout_ = duration;
  436. return (this->derived());
  437. }
  438. /**
  439. * @brief set reply timeout duration value, same as set_timeout
  440. */
  441. template<class Rep, class Period>
  442. inline derived_t & timeout(std::chrono::duration<Rep, Period> duration) noexcept
  443. {
  444. return this->set_timeout(std::move(duration));
  445. }
  446. /**
  447. * @brief get reply timeout duration value
  448. */
  449. inline std::chrono::steady_clock::duration get_timeout() const noexcept
  450. {
  451. return this->timeout_;
  452. }
  453. /**
  454. * @brief get reply timeout duration value, same as get_timeout
  455. */
  456. inline std::chrono::steady_clock::duration timeout() const noexcept
  457. {
  458. return this->get_timeout();
  459. }
  460. /**
  461. * @brief set send interval duration value
  462. */
  463. template<class Rep, class Period>
  464. inline derived_t & set_interval(std::chrono::duration<Rep, Period> duration) noexcept
  465. {
  466. this->interval_ = duration;
  467. return (this->derived());
  468. }
  469. /**
  470. * @brief set send interval duration value, same as set_interval
  471. */
  472. template<class Rep, class Period>
  473. inline derived_t & interval(std::chrono::duration<Rep, Period> duration) noexcept
  474. {
  475. return this->set_interval(std::move(duration));
  476. }
  477. /**
  478. * @brief get send interval duration value
  479. */
  480. inline std::chrono::steady_clock::duration get_interval() const noexcept
  481. {
  482. return this->interval_;
  483. }
  484. /**
  485. * @brief get send interval duration value, same as get_interval
  486. */
  487. inline std::chrono::steady_clock::duration interval() const noexcept
  488. {
  489. return this->interval_;
  490. }
  491. /**
  492. * @brief set icmp payload body
  493. * This function is the same as the "payload()" function
  494. */
  495. inline derived_t & set_body(std::string_view body)
  496. {
  497. this->body_ = body;
  498. if (this->body_.size() > 65500)
  499. this->body_.resize(65500);
  500. return (this->derived());
  501. }
  502. /**
  503. * @brief set icmp payload body, same as set_body
  504. * This function is the same as the "payload()" function
  505. */
  506. inline derived_t & body(std::string_view body)
  507. {
  508. return this->set_body(std::move(body));
  509. }
  510. /**
  511. * @brief set icmp payload body
  512. * This function is the same as the "body()" function
  513. */
  514. inline derived_t & set_payload(std::string_view body)
  515. {
  516. return this->derived().body(std::move(body));
  517. }
  518. /**
  519. * @brief set icmp payload body, same as set_payload
  520. * This function is the same as the "body()" function
  521. */
  522. inline derived_t & payload(std::string_view body)
  523. {
  524. return this->set_payload(std::move(body));
  525. }
  526. /**
  527. * @brief get the resolved host ip
  528. */
  529. inline std::string get_host_ip() const { return this->destination_.address().to_string(); }
  530. /**
  531. * @brief get the resolved host ip, same as get_host_ip
  532. */
  533. inline std::string host_ip() const { return this->get_host_ip(); }
  534. /**
  535. * @brief Set the total number of echo packets you want to send
  536. */
  537. inline derived_t & set_ncount(std::size_t send_count) noexcept
  538. {
  539. this->ncount_ = send_count;
  540. return (this->derived());
  541. }
  542. /**
  543. * @brief Set the total number of echo packets you want to send, same as set_ncount
  544. */
  545. inline derived_t & ncount(std::size_t send_count) noexcept
  546. {
  547. return this->set_ncount(send_count);
  548. }
  549. /**
  550. * @brief Get the total number of echo packets has sent, same as get_total_send
  551. */
  552. inline std::size_t total_send() const noexcept { return this->total_send_; }
  553. /**
  554. * @brief Get the total number of reply packets has recved, same as get_total_recv
  555. */
  556. inline std::size_t total_recv() const noexcept { return this->total_recv_; }
  557. /**
  558. * @brief Get the total number of echo packets has sent
  559. */
  560. inline std::size_t get_total_send() const noexcept { return this->total_send_; }
  561. /**
  562. * @brief Get the total number of reply packets has recved
  563. */
  564. inline std::size_t get_total_recv() const noexcept { return this->total_recv_; }
  565. /**
  566. * @brief Get the packet loss probability (loss rate)
  567. */
  568. inline double get_plp() const noexcept
  569. {
  570. if (this->total_send_ == static_cast<std::size_t>(0))
  571. return 0.0;
  572. return (((double)(total_send_ - total_recv_)) / (double)total_send_ * 100.0);
  573. }
  574. /**
  575. * @brief Get the packet loss probability (loss rate), same as get_plp
  576. */
  577. inline double plp() const noexcept
  578. {
  579. return this->get_plp();
  580. }
  581. /**
  582. * @brief Get the average duration of elapsed when recved reply packets
  583. */
  584. inline std::chrono::steady_clock::duration get_avg_lag() const noexcept
  585. {
  586. if (this->total_recv_ == static_cast<std::size_t>(0))
  587. return std::chrono::steady_clock::duration(0);
  588. return std::chrono::steady_clock::duration(
  589. long((double)this->total_time_.count() / (double)this->total_recv_));
  590. }
  591. /**
  592. * @brief Get the average duration of elapsed when recved reply packets, same as get_avg_lag
  593. */
  594. inline std::chrono::steady_clock::duration avg_lag() const noexcept
  595. {
  596. return this->get_avg_lag();
  597. }
  598. protected:
  599. template<typename String>
  600. bool _do_start(String&& host)
  601. {
  602. derived_t& derive = this->derived();
  603. // if log is enabled, init the log first, otherwise when "Too many open files" error occurs,
  604. // the log file will be created failed too.
  605. #if defined(ASIO2_ENABLE_LOG)
  606. asio2::detail::get_logger();
  607. #endif
  608. this->start_iopool();
  609. if (!this->is_iopool_started())
  610. {
  611. set_last_error(asio::error::operation_aborted);
  612. return false;
  613. }
  614. asio::dispatch(derive.io_->context(), [&derive, this_ptr = derive.selfptr()]() mutable
  615. {
  616. detail::ignore_unused(this_ptr);
  617. // init the running thread id
  618. derive.io_->init_thread_id();
  619. });
  620. // use promise to get the result of async accept
  621. std::promise<error_code> promise;
  622. std::future<error_code> future = promise.get_future();
  623. // use derfer to ensure the promise's value must be seted.
  624. detail::defer_event pg
  625. {
  626. [promise = std::move(promise)]() mutable
  627. {
  628. promise.set_value(get_last_error());
  629. }
  630. };
  631. derive.post(
  632. [this, this_ptr = derive.selfptr(), host = std::forward<String>(host), pg = std::move(pg)]
  633. () mutable
  634. {
  635. derived_t& derive = this->derived();
  636. state_t expected = state_t::stopped;
  637. if (!this->state_.compare_exchange_strong(expected, state_t::starting))
  638. {
  639. // if the state is not stopped, set the last error to already_started
  640. set_last_error(asio::error::already_started);
  641. return;
  642. }
  643. error_code ec, ec_ignore;
  644. derive.io_->regobj(&derive);
  645. #if defined(_DEBUG) || defined(DEBUG)
  646. this->is_stop_called_ = false;
  647. #endif
  648. expected = state_t::starting;
  649. if (!this->state_.compare_exchange_strong(expected, state_t::starting))
  650. {
  651. ASIO2_ASSERT(false);
  652. derive._handle_start(asio::error::operation_aborted, std::move(this_ptr));
  653. return;
  654. }
  655. this->seq_ = 0;
  656. this->total_send_ = 0;
  657. this->total_recv_ = 0;
  658. this->total_time_ = std::chrono::steady_clock::duration{ 0 };
  659. asio::ip::icmp::resolver resolver(this->io_->context());
  660. auto results = resolver.resolve(host, "", ec);
  661. if (ec)
  662. {
  663. derive._handle_start(ec, std::move(this_ptr));
  664. return;
  665. }
  666. if (results.empty())
  667. {
  668. derive._handle_start(asio::error::host_not_found, std::move(this_ptr));
  669. return;
  670. }
  671. this->destination_ = *results.begin();
  672. this->socket_->cancel(ec_ignore);
  673. this->socket_->close(ec_ignore);
  674. this->socket_->open(this->destination_.protocol(), ec);
  675. if (ec)
  676. {
  677. derive._handle_start(ec, std::move(this_ptr));
  678. return;
  679. }
  680. clear_last_error();
  681. derive._fire_init();
  682. derive._handle_start(ec, std::move(this_ptr));
  683. });
  684. if (!derive.io_->running_in_this_thread())
  685. {
  686. set_last_error(future.get());
  687. return static_cast<bool>(!get_last_error());
  688. }
  689. else
  690. {
  691. set_last_error(asio::error::in_progress);
  692. }
  693. // if the state is stopped , the return value is "is_started()".
  694. // if the state is stopping, the return value is false, the last error is already_started
  695. // if the state is starting, the return value is false, the last error is already_started
  696. // if the state is started , the return value is true , the last error is already_started
  697. return derive.is_started();
  698. }
  699. void _handle_start(error_code ec, std::shared_ptr<derived_t> this_ptr)
  700. {
  701. ASIO2_ASSERT(this->derived().io_->running_in_this_thread());
  702. // Whether the startup succeeds or fails, always call fire_start notification
  703. state_t expected = state_t::starting;
  704. if (!ec)
  705. if (!this->state_.compare_exchange_strong(expected, state_t::started))
  706. ec = asio::error::operation_aborted;
  707. set_last_error(ec);
  708. this->derived()._fire_start();
  709. expected = state_t::started;
  710. if (!ec)
  711. if (!this->state_.compare_exchange_strong(expected, state_t::started))
  712. ec = asio::error::operation_aborted;
  713. if (ec)
  714. {
  715. this->derived()._do_stop(ec, std::move(this_ptr));
  716. return;
  717. }
  718. this->buffer_.consume(this->buffer_.size());
  719. this->derived()._post_send(this_ptr);
  720. this->derived()._post_recv(std::move(this_ptr));
  721. }
  722. inline void _do_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
  723. {
  724. ASIO2_ASSERT(this->derived().io_->running_in_this_thread());
  725. state_t expected = state_t::starting;
  726. if (this->state_.compare_exchange_strong(expected, state_t::stopping))
  727. return this->derived()._post_stop(ec, std::move(this_ptr), expected);
  728. expected = state_t::started;
  729. if (this->state_.compare_exchange_strong(expected, state_t::stopping))
  730. return this->derived()._post_stop(ec, std::move(this_ptr), expected);
  731. }
  732. inline void _post_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr, state_t old_state)
  733. {
  734. // asio don't allow operate the same socket in multi thread,
  735. // if you close socket in one thread and another thread is
  736. // calling socket's async_... function,it will crash.so we
  737. // must care for operate the socket.when need close the
  738. // socket ,we use the io_context to post a event,make sure the
  739. // socket's close operation is in the same thread.
  740. asio::dispatch(this->io_->context(), make_allocator(this->derived().wallocator(),
  741. [this, ec, this_ptr = std::move(this_ptr), old_state]() mutable
  742. {
  743. detail::ignore_unused(old_state);
  744. set_last_error(ec);
  745. state_t expected = state_t::stopping;
  746. if (this->state_.compare_exchange_strong(expected, state_t::stopped))
  747. {
  748. this->derived()._fire_stop();
  749. // call CRTP polymorphic stop
  750. this->derived()._handle_stop(ec, std::move(this_ptr));
  751. }
  752. else
  753. {
  754. ASIO2_ASSERT(false);
  755. }
  756. }));
  757. }
  758. inline void _handle_stop(const error_code& ec, std::shared_ptr<derived_t> this_ptr)
  759. {
  760. ASIO2_ASSERT(this->derived().io_->running_in_this_thread());
  761. detail::ignore_unused(ec, this_ptr);
  762. error_code ec_ignore{};
  763. // close user custom timers
  764. this->_dispatch_stop_all_timers();
  765. // close all posted timed tasks
  766. this->_dispatch_stop_all_timed_events();
  767. // close all async_events
  768. this->notify_all_condition_events();
  769. detail::cancel_timer(*(this->timer_));
  770. this->socket_->cancel(ec_ignore);
  771. // Call close,otherwise the _handle_recv will never return
  772. this->socket_->close(ec_ignore);
  773. // clear recv buffer
  774. this->buffer().consume(this->buffer().size());
  775. // destroy user data, maybe the user data is self shared_ptr,
  776. // if don't destroy it, will cause loop reference.
  777. this->user_data_.reset();
  778. }
  779. void _post_send(std::shared_ptr<derived_t> this_ptr)
  780. {
  781. // if ncount_ is equal to max, infinite send
  782. if (this->ncount_ != std::size_t(-1))
  783. {
  784. if (this->total_send_ >= this->ncount_)
  785. {
  786. this->derived()._do_stop(asio::error::eof, std::move(this_ptr));
  787. return;
  788. }
  789. }
  790. // Create an ICMP header for an echo request.
  791. icmp_header req;
  792. req.type(icmp_header::echo_request);
  793. req.code(0);
  794. req.identifier(this->identifier_);
  795. req.sequence_number(++seq_);
  796. compute_checksum(req, this->body_.begin(), this->body_.end());
  797. // Encode the request packet.
  798. asio::streambuf buffer;
  799. std::ostream os(std::addressof(buffer));
  800. os << req << this->body_;
  801. #if defined(_DEBUG) || defined(DEBUG)
  802. ASIO2_ASSERT(this->derived().post_send_counter_.load() == 0);
  803. this->derived().post_send_counter_++;
  804. #endif
  805. // Send the request.
  806. error_code ec;
  807. this->time_sent_ = std::chrono::steady_clock::now();
  808. this->socket_->send_to(buffer.data(), this->destination_, 0, ec);
  809. set_last_error(ec);
  810. if (!ec)
  811. this->total_send_++;
  812. #if defined(_DEBUG) || defined(DEBUG)
  813. this->derived().post_send_counter_--;
  814. #endif
  815. // Wait up to five seconds for a reply.
  816. this->replies_ = 0;
  817. if (this->is_started())
  818. {
  819. this->timer_->expires_after(this->timeout_);
  820. this->timer_->async_wait(
  821. [this, this_ptr = std::move(this_ptr)](const error_code & ec) mutable
  822. {
  823. this->derived()._handle_timer(ec, std::move(this_ptr));
  824. });
  825. }
  826. }
  827. void _handle_timer(const error_code & ec, std::shared_ptr<derived_t> this_ptr)
  828. {
  829. detail::ignore_unused(ec);
  830. set_last_error(ec);
  831. if (this->replies_ == 0)
  832. {
  833. this->rep_.lag = std::chrono::steady_clock::duration(-1);
  834. if (!ec && this->is_started())
  835. {
  836. this->derived()._fire_recv(this->rep_);
  837. }
  838. }
  839. // Requests must be sent no less than one second apart.
  840. if (this->is_started())
  841. {
  842. this->timer_->expires_after(this->interval_);
  843. this->timer_->async_wait(
  844. [this, this_ptr = std::move(this_ptr)](const error_code & ec) mutable
  845. {
  846. detail::ignore_unused(ec);
  847. this->derived()._post_send(std::move(this_ptr));
  848. });
  849. }
  850. }
  851. void _post_recv(std::shared_ptr<derived_t> this_ptr)
  852. {
  853. if (!this->is_started())
  854. {
  855. if (this->derived().state_ == state_t::started)
  856. {
  857. this->derived()._do_stop(asio2::get_last_error(), std::move(this_ptr));
  858. }
  859. return;
  860. }
  861. #if defined(_DEBUG) || defined(DEBUG)
  862. ASIO2_ASSERT(this->derived().post_recv_counter_.load() == 0);
  863. this->derived().post_recv_counter_++;
  864. #endif
  865. // Wait for a reply. We prepare the buffer to receive up to 64KB.
  866. this->socket_->async_receive(this->buffer_.prepare(this->buffer_.pre_size()),
  867. make_allocator(this->rallocator_,
  868. [this, this_ptr = std::move(this_ptr)]
  869. (const error_code& ec, std::size_t bytes_recvd) mutable
  870. {
  871. #if defined(_DEBUG) || defined(DEBUG)
  872. this->derived().post_recv_counter_--;
  873. #endif
  874. this->derived()._handle_recv(ec, bytes_recvd, std::move(this_ptr));
  875. }));
  876. }
  877. void _handle_recv(const error_code& ec, std::size_t bytes_recvd, std::shared_ptr<derived_t> this_ptr)
  878. {
  879. set_last_error(ec);
  880. if (!this->is_started())
  881. {
  882. if (this->derived().state_ == state_t::started)
  883. {
  884. this->derived()._do_stop(ec, std::move(this_ptr));
  885. }
  886. return;
  887. }
  888. if (ec == asio::error::operation_aborted)
  889. {
  890. this->derived()._do_stop(ec, std::move(this_ptr));
  891. return;
  892. }
  893. if (ec && bytes_recvd == 0)
  894. {
  895. this->derived()._do_stop(ec, std::move(this_ptr));
  896. return;
  897. }
  898. // The actual number of bytes received is committed to the buffer so that we
  899. // can extract it using a std::istream object.
  900. this->buffer_.commit(bytes_recvd);
  901. // Decode the reply packet.
  902. std::istream is(std::addressof(this->buffer_));
  903. ipv4_header& ipv4_hdr = this->rep_.base_ipv4();
  904. icmp_header& icmp_hdr = this->rep_.base_icmp();
  905. is >> ipv4_hdr >> icmp_hdr;
  906. ASIO2_ASSERT(ipv4_hdr.total_length() == bytes_recvd);
  907. // We can receive all ICMP packets received by the host, so we need to
  908. // filter out only the echo replies that match the our identifier and
  909. // expected sequence number.
  910. if (is
  911. && icmp_hdr.type() == icmp_header::echo_reply
  912. && icmp_hdr.identifier() == this->identifier_
  913. && icmp_hdr.sequence_number() == this->seq_)
  914. {
  915. // If this is the first reply, interrupt the five second timeout.
  916. if (this->replies_++ == 0)
  917. {
  918. detail::cancel_timer(*(this->timer_));
  919. }
  920. this->total_recv_++;
  921. this->rep_.lag = std::chrono::steady_clock::now() - this->time_sent_;
  922. this->total_time_ += this->rep_.lag;
  923. this->derived()._fire_recv(this->rep_);
  924. }
  925. // Discard any data already in the buffer.
  926. this->buffer_.consume(this->buffer_.size());
  927. this->derived()._post_recv(std::move(this_ptr));
  928. }
  929. inline void _fire_init()
  930. {
  931. // the _fire_init must be executed in the thread 0.
  932. ASIO2_ASSERT(this->derived().io_->running_in_this_thread());
  933. ASIO2_ASSERT(!get_last_error());
  934. this->listener_.notify(event_type::init);
  935. }
  936. inline void _fire_start()
  937. {
  938. // the _fire_start must be executed in the thread 0.
  939. ASIO2_ASSERT(this->derived().io_->running_in_this_thread());
  940. #if defined(_DEBUG) || defined(DEBUG)
  941. ASIO2_ASSERT(this->is_stop_called_ == false);
  942. #endif
  943. this->listener_.notify(event_type::start);
  944. }
  945. inline void _fire_stop()
  946. {
  947. // the _fire_stop must be executed in the thread 0.
  948. ASIO2_ASSERT(this->derived().io_->running_in_this_thread());
  949. #if defined(_DEBUG) || defined(DEBUG)
  950. this->is_stop_called_ = true;
  951. #endif
  952. this->listener_.notify(event_type::stop);
  953. }
  954. inline void _fire_recv(icmp_rep& rep)
  955. {
  956. this->listener_.notify(event_type::recv, rep);
  957. }
  958. public:
  959. /**
  960. * @brief get the buffer object reference
  961. */
  962. inline buffer_wrap<buffer_type> & buffer() noexcept { return this->buffer_; }
  963. /**
  964. * @brief get the io object reference
  965. */
  966. inline io_t & io() noexcept { return *(this->io_); }
  967. /**
  968. * @brief get the io object reference
  969. */
  970. inline io_t const& io() const noexcept { return *(this->io_); }
  971. protected:
  972. /**
  973. * @brief get the recv/read allocator object reference
  974. */
  975. inline auto & rallocator() noexcept { return this->rallocator_; }
  976. /**
  977. * @brief get the timer/post allocator object reference
  978. */
  979. inline auto & wallocator() noexcept { return this->wallocator_; }
  980. protected:
  981. /// The memory to use for handler-based custom memory allocation. used fo recv/read.
  982. handler_memory<std::true_type , assizer<args_t>> rallocator_;
  983. /// The memory to use for handler-based custom memory allocation. used fo timer/post.
  984. handler_memory<std::false_type, assizer<args_t>> wallocator_;
  985. /// listener
  986. listener_t listener_;
  987. /// The io_context wrapper used to handle the accept event.
  988. std::shared_ptr<io_t> io_;
  989. /// buffer
  990. buffer_wrap<buffer_type> buffer_;
  991. /// state
  992. std::atomic<state_t> state_ = state_t::stopped;
  993. /// socket, shoule be destroyed before io_context
  994. std::shared_ptr<socket_type> socket_;
  995. std::unique_ptr<asio::steady_timer> timer_;
  996. std::string body_{ R"("Hello!" from Asio ping.)" };
  997. unsigned short seq_ = 0;
  998. std::size_t replies_ = 0;
  999. icmp_rep rep_;
  1000. asio::ip::icmp::endpoint destination_;
  1001. unsigned short identifier_ = (unsigned short)(std::size_t(this));
  1002. std::size_t ncount_ { std::size_t(-1) };
  1003. std::size_t total_send_{ 0 };
  1004. std::size_t total_recv_{ 0 };
  1005. std::chrono::steady_clock::duration total_time_{ 0 };
  1006. std::chrono::steady_clock::duration timeout_ = std::chrono::milliseconds(icmp_execute_timeout);
  1007. std::chrono::steady_clock::duration interval_ = std::chrono::milliseconds(1000);
  1008. std::chrono::steady_clock::time_point time_sent_;
  1009. #if defined(_DEBUG) || defined(DEBUG)
  1010. bool is_stop_called_ = false;
  1011. std::atomic<int> post_send_counter_ = 0;
  1012. std::atomic<int> post_recv_counter_ = 0;
  1013. #endif
  1014. };
  1015. }
  1016. namespace asio2
  1017. {
  1018. template<class derived_t>
  1019. class ping_t : public detail::ping_impl_t<derived_t, detail::template_args_icmp>
  1020. {
  1021. public:
  1022. using detail::ping_impl_t<derived_t, detail::template_args_icmp>::ping_impl_t;
  1023. };
  1024. /**
  1025. * @brief constructor Parameter description
  1026. * @param send_count - Total number of echo packets you want to send,
  1027. * send_count equals -1 for infinite send,
  1028. * Other parameters should use default values.
  1029. * If this object is created as a shared_ptr like std::shared_ptr<asio2::ping> ping;
  1030. * you must call the ping->stop() manual when exit, otherwise maybe cause memory leaks.
  1031. */
  1032. class ping : public ping_t<ping>
  1033. {
  1034. public:
  1035. using ping_t<ping>::ping_t;
  1036. };
  1037. }
  1038. #include <asio2/base/detail/pop_options.hpp>
  1039. #endif // !__ASIO2_PING_HPP__