disconnect_op.hpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. //
  2. // Copyright (c) 2023-2025 Ivica Siladic, Bruno Iljazovic, Korina Simicevic
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BOOST_MQTT5_DISCONNECT_OP_HPP
  8. #define BOOST_MQTT5_DISCONNECT_OP_HPP
  9. #include <boost/mqtt5/types.hpp>
  10. #include <boost/mqtt5/detail/cancellable_handler.hpp>
  11. #include <boost/mqtt5/detail/control_packet.hpp>
  12. #include <boost/mqtt5/detail/internal_types.hpp>
  13. #include <boost/mqtt5/detail/topic_validation.hpp>
  14. #include <boost/mqtt5/detail/utf8_mqtt.hpp>
  15. #include <boost/mqtt5/impl/codecs/message_encoders.hpp>
  16. #include <boost/asio/any_completion_handler.hpp>
  17. #include <boost/asio/associated_allocator.hpp>
  18. #include <boost/asio/associated_cancellation_slot.hpp>
  19. #include <boost/asio/associated_executor.hpp>
  20. #include <boost/asio/async_result.hpp>
  21. #include <boost/asio/consign.hpp>
  22. #include <boost/asio/deferred.hpp>
  23. #include <boost/asio/error.hpp>
  24. #include <boost/asio/experimental/parallel_group.hpp>
  25. #include <boost/asio/prepend.hpp>
  26. #include <boost/asio/steady_timer.hpp>
  27. #include <cstdint>
  28. #include <memory>
  29. namespace boost::mqtt5::detail {
  30. namespace asio = boost::asio;
  31. template <
  32. typename ClientService,
  33. typename DisconnectContext
  34. >
  35. class disconnect_op {
  36. using client_service = ClientService;
  37. struct on_disconnect {};
  38. struct on_shutdown {};
  39. std::shared_ptr<client_service> _svc_ptr;
  40. DisconnectContext _context;
  41. using handler_type = cancellable_handler<
  42. asio::any_completion_handler<void (error_code)>,
  43. typename ClientService::executor_type
  44. >;
  45. handler_type _handler;
  46. public:
  47. template <typename Handler>
  48. disconnect_op(
  49. std::shared_ptr<client_service> svc_ptr,
  50. DisconnectContext&& context, Handler&& handler
  51. ) :
  52. _svc_ptr(std::move(svc_ptr)), _context(std::move(context)),
  53. _handler(std::move(handler), _svc_ptr->get_executor())
  54. {
  55. auto slot = asio::get_associated_cancellation_slot(_handler);
  56. if (slot.is_connected())
  57. slot.assign([&svc = *_svc_ptr](asio::cancellation_type_t) {
  58. svc.cancel();
  59. });
  60. }
  61. disconnect_op(disconnect_op&&) = default;
  62. disconnect_op(const disconnect_op&) = delete;
  63. disconnect_op& operator=(disconnect_op&&) = default;
  64. disconnect_op& operator=(const disconnect_op&) = delete;
  65. using allocator_type = asio::associated_allocator_t<handler_type>;
  66. allocator_type get_allocator() const noexcept {
  67. return asio::get_associated_allocator(_handler);
  68. }
  69. using executor_type = typename client_service::executor_type;
  70. executor_type get_executor() const noexcept {
  71. return _svc_ptr->get_executor();
  72. }
  73. void perform() {
  74. error_code ec = validate_disconnect(_context.props);
  75. if (ec)
  76. return complete_immediate(ec);
  77. auto disconnect = control_packet<allocator_type>::of(
  78. no_pid, get_allocator(),
  79. encoders::encode_disconnect,
  80. static_cast<uint8_t>(_context.reason_code), _context.props
  81. );
  82. auto max_packet_size = _svc_ptr->connack_property(prop::maximum_packet_size)
  83. .value_or(default_max_send_size);
  84. if (disconnect.size() > max_packet_size)
  85. // drop properties
  86. return send_disconnect(control_packet<allocator_type>::of(
  87. no_pid, get_allocator(),
  88. encoders::encode_disconnect,
  89. static_cast<uint8_t>(_context.reason_code), disconnect_props {}
  90. ));
  91. send_disconnect(std::move(disconnect));
  92. }
  93. void send_disconnect(control_packet<allocator_type> disconnect) {
  94. auto wire_data = disconnect.wire_data();
  95. _svc_ptr->async_send(
  96. wire_data,
  97. no_serial, send_flag::terminal,
  98. asio::prepend(
  99. std::move(*this),
  100. on_disconnect {}, std::move(disconnect)
  101. )
  102. );
  103. }
  104. void operator()(
  105. on_disconnect,
  106. control_packet<allocator_type> disconnect, error_code ec
  107. ) {
  108. // The connection must be closed even
  109. // if we failed to send the DISCONNECT packet
  110. // with Reason Code of 0x80 or greater.
  111. if (
  112. ec == asio::error::operation_aborted ||
  113. ec == asio::error::no_recovery
  114. )
  115. return complete(asio::error::operation_aborted);
  116. if (ec == asio::error::try_again) {
  117. if (_context.terminal)
  118. return send_disconnect(std::move(disconnect));
  119. return complete(error_code {});
  120. }
  121. return _svc_ptr->async_shutdown(
  122. asio::prepend(std::move(*this), on_shutdown {})
  123. );
  124. }
  125. void operator()(on_shutdown, error_code ec) {
  126. if (_context.terminal)
  127. _svc_ptr->cancel();
  128. complete(ec);
  129. }
  130. private:
  131. static error_code validate_disconnect(const disconnect_props& props) {
  132. const auto& reason_string = props[prop::reason_string];
  133. if (
  134. reason_string &&
  135. validate_mqtt_utf8(*reason_string) != validation_result::valid
  136. )
  137. return client::error::malformed_packet;
  138. const auto& user_properties = props[prop::user_property];
  139. for (const auto& user_property: user_properties)
  140. if (!is_valid_string_pair(user_property))
  141. return client::error::malformed_packet;
  142. return error_code {};
  143. }
  144. void complete(error_code ec) {
  145. _handler.complete(ec);
  146. }
  147. void complete_immediate(error_code ec) {
  148. _handler.complete_immediate(ec);
  149. }
  150. };
  151. template <typename ClientService, typename Handler>
  152. class terminal_disconnect_op {
  153. using client_service = ClientService;
  154. static constexpr uint8_t seconds = 5;
  155. std::shared_ptr<client_service> _svc_ptr;
  156. std::unique_ptr<asio::steady_timer> _timer;
  157. using handler_type = Handler;
  158. handler_type _handler;
  159. public:
  160. terminal_disconnect_op(
  161. std::shared_ptr<client_service> svc_ptr,
  162. Handler&& handler
  163. ) :
  164. _svc_ptr(std::move(svc_ptr)),
  165. _timer(new asio::steady_timer(_svc_ptr->get_executor())),
  166. _handler(std::move(handler))
  167. {}
  168. terminal_disconnect_op(terminal_disconnect_op&&) = default;
  169. terminal_disconnect_op(const terminal_disconnect_op&) = delete;
  170. terminal_disconnect_op& operator=(terminal_disconnect_op&&) = default;
  171. terminal_disconnect_op& operator=(const terminal_disconnect_op&) = delete;
  172. using allocator_type = asio::associated_allocator_t<handler_type>;
  173. allocator_type get_allocator() const noexcept {
  174. return asio::get_associated_allocator(_handler);
  175. }
  176. using cancellation_slot_type = asio::associated_cancellation_slot_t<handler_type>;
  177. cancellation_slot_type get_cancellation_slot() const noexcept {
  178. return asio::get_associated_cancellation_slot(_handler);
  179. }
  180. using executor_type = asio::associated_executor_t<handler_type>;
  181. executor_type get_executor() const noexcept {
  182. return asio::get_associated_executor(_handler);
  183. }
  184. template <typename DisconnectContext>
  185. void perform(DisconnectContext&& context) {
  186. namespace asioex = boost::asio::experimental;
  187. auto init_disconnect = [](
  188. auto handler, disconnect_ctx ctx,
  189. std::shared_ptr<ClientService> svc_ptr
  190. ) {
  191. disconnect_op {
  192. std::move(svc_ptr), std::move(ctx), std::move(handler)
  193. }.perform();
  194. };
  195. _timer->expires_after(std::chrono::seconds(seconds));
  196. auto timed_disconnect = asioex::make_parallel_group(
  197. asio::async_initiate<const asio::deferred_t, void (error_code)>(
  198. init_disconnect, asio::deferred,
  199. std::forward<DisconnectContext>(context), _svc_ptr
  200. ),
  201. _timer->async_wait(asio::deferred)
  202. );
  203. timed_disconnect.async_wait(
  204. asioex::wait_for_one(), std::move(*this)
  205. );
  206. }
  207. void operator()(
  208. std::array<std::size_t, 2> /* ord */,
  209. error_code disconnect_ec, error_code /* timer_ec */
  210. ) {
  211. std::move(_handler)(disconnect_ec);
  212. }
  213. };
  214. template <typename ClientService, bool terminal>
  215. class initiate_async_disconnect {
  216. std::shared_ptr<ClientService> _svc_ptr;
  217. public:
  218. explicit initiate_async_disconnect(std::shared_ptr<ClientService> svc_ptr) :
  219. _svc_ptr(std::move(svc_ptr))
  220. {}
  221. using executor_type = typename ClientService::executor_type;
  222. executor_type get_executor() const noexcept {
  223. return _svc_ptr->get_executor();
  224. }
  225. template <typename Handler>
  226. void operator()(
  227. Handler&& handler,
  228. disconnect_rc_e rc, const disconnect_props& props
  229. ) {
  230. auto ctx = disconnect_ctx { rc, props, terminal };
  231. if constexpr (terminal)
  232. terminal_disconnect_op { _svc_ptr, std::move(handler) }
  233. .perform(std::move(ctx));
  234. else
  235. disconnect_op { _svc_ptr, std::move(ctx), std::move(handler) }
  236. .perform();
  237. }
  238. };
  239. template <typename ClientService, typename CompletionToken>
  240. decltype(auto) async_disconnect(
  241. disconnect_rc_e reason_code, const disconnect_props& props,
  242. std::shared_ptr<ClientService> svc_ptr,
  243. CompletionToken&& token
  244. ) {
  245. using Signature = void (error_code);
  246. return asio::async_initiate<CompletionToken, Signature>(
  247. initiate_async_disconnect<ClientService, false>(std::move(svc_ptr)), token,
  248. reason_code, props
  249. );
  250. }
  251. template <typename ClientService, typename CompletionToken>
  252. decltype(auto) async_terminal_disconnect(
  253. disconnect_rc_e reason_code, const disconnect_props& props,
  254. std::shared_ptr<ClientService> svc_ptr,
  255. CompletionToken&& token
  256. ) {
  257. using Signature = void (error_code);
  258. return asio::async_initiate<CompletionToken, Signature>(
  259. initiate_async_disconnect<ClientService, true>(std::move(svc_ptr)), token,
  260. reason_code, props
  261. );
  262. }
  263. } // end namespace boost::mqtt5::detail
  264. #endif // !BOOST_MQTT5_DISCONNECT_HPP