subscribe_op.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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_SUBSCRIBE_OP_HPP
  8. #define BOOST_MQTT5_SUBSCRIBE_OP_HPP
  9. #include <boost/mqtt5/error.hpp>
  10. #include <boost/mqtt5/reason_codes.hpp>
  11. #include <boost/mqtt5/types.hpp>
  12. #include <boost/mqtt5/detail/cancellable_handler.hpp>
  13. #include <boost/mqtt5/detail/control_packet.hpp>
  14. #include <boost/mqtt5/detail/internal_types.hpp>
  15. #include <boost/mqtt5/detail/topic_validation.hpp>
  16. #include <boost/mqtt5/impl/codecs/message_decoders.hpp>
  17. #include <boost/mqtt5/impl/codecs/message_encoders.hpp>
  18. #include <boost/mqtt5/impl/disconnect_op.hpp>
  19. #include <boost/asio/associated_allocator.hpp>
  20. #include <boost/asio/associated_cancellation_slot.hpp>
  21. #include <boost/asio/associated_executor.hpp>
  22. #include <boost/asio/cancellation_type.hpp>
  23. #include <boost/asio/detached.hpp>
  24. #include <boost/asio/error.hpp>
  25. #include <boost/asio/prepend.hpp>
  26. #include <cstdint>
  27. #include <memory>
  28. #include <string>
  29. #include <vector>
  30. namespace boost::mqtt5::detail {
  31. namespace asio = boost::asio;
  32. template <typename ClientService, typename Handler>
  33. class subscribe_op {
  34. using client_service = ClientService;
  35. struct on_subscribe {};
  36. struct on_suback {};
  37. std::shared_ptr<client_service> _svc_ptr;
  38. using handler_type = cancellable_handler<
  39. Handler,
  40. typename client_service::executor_type
  41. >;
  42. handler_type _handler;
  43. size_t _num_topics { 0 };
  44. public:
  45. subscribe_op(
  46. std::shared_ptr<client_service> svc_ptr,
  47. Handler&& handler
  48. ) :
  49. _svc_ptr(std::move(svc_ptr)),
  50. _handler(std::move(handler), _svc_ptr->get_executor())
  51. {
  52. auto slot = asio::get_associated_cancellation_slot(_handler);
  53. if (slot.is_connected())
  54. slot.assign([&svc = *_svc_ptr](asio::cancellation_type_t) {
  55. svc.cancel();
  56. });
  57. }
  58. subscribe_op(subscribe_op&&) = default;
  59. subscribe_op(const subscribe_op&) = delete;
  60. subscribe_op& operator=(subscribe_op&&) = default;
  61. subscribe_op& operator=(const subscribe_op&) = delete;
  62. using allocator_type = asio::associated_allocator_t<handler_type>;
  63. allocator_type get_allocator() const noexcept {
  64. return asio::get_associated_allocator(_handler);
  65. }
  66. using executor_type = typename client_service::executor_type;
  67. executor_type get_executor() const noexcept {
  68. return _svc_ptr->get_executor();
  69. }
  70. void perform(
  71. const std::vector<subscribe_topic>& topics,
  72. const subscribe_props& props
  73. ) {
  74. _num_topics = topics.size();
  75. uint16_t packet_id = _svc_ptr->allocate_pid();
  76. if (packet_id == 0)
  77. return complete_immediate(client::error::pid_overrun, packet_id);
  78. if (_num_topics == 0)
  79. return complete_immediate(client::error::invalid_topic, packet_id);
  80. auto ec = validate_subscribe(topics, props);
  81. if (ec)
  82. return complete_immediate(ec, packet_id);
  83. auto subscribe = control_packet<allocator_type>::of(
  84. with_pid, get_allocator(),
  85. encoders::encode_subscribe, packet_id,
  86. topics, props
  87. );
  88. auto max_packet_size = _svc_ptr->connack_property(prop::maximum_packet_size)
  89. .value_or(default_max_send_size);
  90. if (subscribe.size() > max_packet_size)
  91. return complete_immediate(client::error::packet_too_large, packet_id);
  92. send_subscribe(std::move(subscribe));
  93. }
  94. void send_subscribe(control_packet<allocator_type> subscribe) {
  95. auto wire_data = subscribe.wire_data();
  96. _svc_ptr->async_send(
  97. wire_data,
  98. no_serial, send_flag::none,
  99. asio::prepend(
  100. std::move(*this), on_subscribe {}, std::move(subscribe)
  101. )
  102. );
  103. }
  104. void resend_subscribe(control_packet<allocator_type> subscribe) {
  105. if (_handler.cancelled() != asio::cancellation_type_t::none)
  106. return complete(
  107. asio::error::operation_aborted, subscribe.packet_id()
  108. );
  109. send_subscribe(std::move(subscribe));
  110. }
  111. void operator()(
  112. on_subscribe, control_packet<allocator_type> packet,
  113. error_code ec
  114. ) {
  115. if (ec == asio::error::try_again)
  116. return resend_subscribe(std::move(packet));
  117. auto packet_id = packet.packet_id();
  118. if (ec)
  119. return complete(ec, packet_id);
  120. _svc_ptr->async_wait_reply(
  121. control_code_e::suback, packet_id,
  122. asio::prepend(std::move(*this), on_suback {}, std::move(packet))
  123. );
  124. }
  125. void operator()(
  126. on_suback, control_packet<allocator_type> packet,
  127. error_code ec, byte_citer first, byte_citer last
  128. ) {
  129. if (ec == asio::error::try_again) // "resend unanswered"
  130. return resend_subscribe(std::move(packet));
  131. uint16_t packet_id = packet.packet_id();
  132. if (ec)
  133. return complete(ec, packet_id);
  134. auto suback = decoders::decode_suback(
  135. static_cast<uint32_t>(std::distance(first, last)), first
  136. );
  137. if (!suback.has_value()) {
  138. on_malformed_packet("Malformed SUBACK: cannot decode");
  139. return resend_subscribe(std::move(packet));
  140. }
  141. auto& [props, rcs] = *suback;
  142. auto reason_codes = to_reason_codes(std::move(rcs));
  143. if (reason_codes.size() != _num_topics) {
  144. on_malformed_packet(
  145. "Malformed SUBACK: does not contain a "
  146. "valid Reason Code for every Topic Filter"
  147. );
  148. return resend_subscribe(std::move(packet));
  149. }
  150. complete(
  151. ec, packet_id, std::move(reason_codes), std::move(props)
  152. );
  153. }
  154. private:
  155. error_code validate_subscribe(
  156. const std::vector<subscribe_topic>& topics, const subscribe_props& props
  157. ) const {
  158. error_code ec;
  159. for (const auto& topic: topics) {
  160. ec = validate_topic(topic);
  161. if (ec)
  162. return ec;
  163. }
  164. ec = validate_props(props);
  165. return ec;
  166. }
  167. error_code validate_topic(const subscribe_topic& topic) const {
  168. auto wildcard_available = _svc_ptr->connack_property(
  169. prop::wildcard_subscription_available
  170. ).value_or(1);
  171. auto shared_available = _svc_ptr->connack_property(
  172. prop::shared_subscription_available
  173. ).value_or(1);
  174. std::string_view topic_filter = topic.topic_filter;
  175. validation_result result = validation_result::valid;
  176. if (
  177. topic_filter.compare(0, shared_sub_prefix.size(), shared_sub_prefix) == 0
  178. ) {
  179. if (!shared_available)
  180. return client::error::shared_subscription_not_available;
  181. result = validate_shared_topic_filter(topic_filter, wildcard_available);
  182. } else
  183. result = wildcard_available ?
  184. validate_topic_filter(topic_filter) :
  185. validate_topic_name(topic_filter);
  186. if (result == validation_result::invalid)
  187. return client::error::invalid_topic;
  188. if (!wildcard_available && result != validation_result::valid)
  189. return client::error::wildcard_subscription_not_available;
  190. return error_code {};
  191. }
  192. error_code validate_props(const subscribe_props& props) const {
  193. const auto& user_properties = props[prop::user_property];
  194. for (const auto& user_property: user_properties)
  195. if (!is_valid_string_pair(user_property))
  196. return client::error::malformed_packet;
  197. const auto& sub_id = props[prop::subscription_identifier];
  198. if (!sub_id.has_value())
  199. return error_code {};
  200. auto sub_id_available = _svc_ptr->connack_property(
  201. prop::subscription_identifier_available
  202. ).value_or(1);
  203. if (!sub_id_available)
  204. return client::error::subscription_identifier_not_available;
  205. return (min_subscription_identifier <= *sub_id &&
  206. *sub_id <= max_subscription_identifier) ?
  207. error_code {} :
  208. client::error::malformed_packet;
  209. }
  210. static std::vector<reason_code> to_reason_codes(std::vector<uint8_t> codes) {
  211. std::vector<reason_code> ret;
  212. for (uint8_t code : codes) {
  213. auto rc = to_reason_code<reason_codes::category::suback>(code);
  214. if (rc)
  215. ret.push_back(*rc);
  216. }
  217. return ret;
  218. }
  219. void on_malformed_packet(const std::string& reason) {
  220. auto props = disconnect_props {};
  221. props[prop::reason_string] = reason;
  222. async_disconnect(
  223. disconnect_rc_e::malformed_packet, props, _svc_ptr,
  224. asio::detached
  225. );
  226. }
  227. void complete_immediate(error_code ec, uint16_t packet_id) {
  228. if (packet_id != 0)
  229. _svc_ptr->free_pid(packet_id);
  230. _handler.complete_immediate(
  231. ec, std::vector<reason_code>(_num_topics, reason_codes::empty),
  232. suback_props {}
  233. );
  234. }
  235. void complete(
  236. error_code ec, uint16_t packet_id,
  237. std::vector<reason_code> reason_codes = {}, suback_props props = {}
  238. ) {
  239. if (reason_codes.empty() && _num_topics)
  240. reason_codes = std::vector<reason_code>(_num_topics, reason_codes::empty);
  241. if (!_svc_ptr->subscriptions_present()) {
  242. bool has_success_rc = std::any_of(
  243. reason_codes.cbegin(), reason_codes.cend(),
  244. [](const reason_code& rc) { return !rc; }
  245. );
  246. if (has_success_rc)
  247. _svc_ptr->subscriptions_present(true);
  248. }
  249. _svc_ptr->free_pid(packet_id);
  250. _handler.complete(ec, std::move(reason_codes), std::move(props));
  251. }
  252. };
  253. template <typename ClientService>
  254. class initiate_async_subscribe {
  255. std::shared_ptr<ClientService> _svc_ptr;
  256. public:
  257. explicit initiate_async_subscribe(std::shared_ptr<ClientService> svc_ptr) :
  258. _svc_ptr(std::move(svc_ptr))
  259. {}
  260. using executor_type = typename ClientService::executor_type;
  261. executor_type get_executor() const noexcept {
  262. return _svc_ptr->get_executor();
  263. }
  264. template <typename Handler>
  265. void operator()(
  266. Handler&& handler,
  267. const std::vector<subscribe_topic>& topics, const subscribe_props& props
  268. ) {
  269. detail::subscribe_op { _svc_ptr, std::move(handler) }
  270. .perform(topics, props);
  271. }
  272. };
  273. } // end namespace boost::mqtt5::detail
  274. #endif // !BOOST_MQTT5_SUBSCRIBE_OP_HPP