aop_connect.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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_MQTT_AOP_CONNECT_HPP__
  11. #define __ASIO2_MQTT_AOP_CONNECT_HPP__
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. #pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <asio2/base/iopool.hpp>
  16. #include <asio2/base/detail/function_traits.hpp>
  17. #include <asio2/base/detail/util.hpp>
  18. #include <asio2/mqtt/message.hpp>
  19. namespace asio2::detail
  20. {
  21. template<class caller_t, class args_t>
  22. class mqtt_aop_connect
  23. {
  24. friend caller_t;
  25. protected:
  26. template<class Response>
  27. inline void _set_connack_reason_code_with_invalid_id(error_code& ec, Response& rep)
  28. {
  29. using response_type = typename detail::remove_cvref_t<Response>;
  30. ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid);
  31. if constexpr /**/ (std::is_same_v<response_type, mqtt::v3::connack>)
  32. {
  33. rep.reason_code(mqtt::v3::connect_reason_code::identifier_rejected);
  34. }
  35. else if constexpr (std::is_same_v<response_type, mqtt::v4::connack>)
  36. {
  37. rep.reason_code(mqtt::v4::connect_reason_code::identifier_rejected);
  38. }
  39. else if constexpr (std::is_same_v<response_type, mqtt::v5::connack>)
  40. {
  41. rep.reason_code(mqtt::error::client_identifier_not_valid);
  42. }
  43. else
  44. {
  45. static_assert(detail::always_false_v<Response>);
  46. }
  47. }
  48. template<class Response>
  49. inline void _set_connack_reason_code_with_bad_user_name_or_password(error_code& ec, Response& rep)
  50. {
  51. using response_type = typename detail::remove_cvref_t<Response>;
  52. ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password);
  53. if constexpr /**/ (std::is_same_v<response_type, mqtt::v3::connack>)
  54. {
  55. rep.reason_code(mqtt::v3::connect_reason_code::bad_user_name_or_password);
  56. }
  57. else if constexpr (std::is_same_v<response_type, mqtt::v4::connack>)
  58. {
  59. rep.reason_code(mqtt::v4::connect_reason_code::bad_user_name_or_password);
  60. }
  61. else if constexpr (std::is_same_v<response_type, mqtt::v5::connack>)
  62. {
  63. rep.reason_code(mqtt::error::bad_user_name_or_password);
  64. }
  65. else
  66. {
  67. static_assert(detail::always_false_v<Response>);
  68. }
  69. }
  70. template<class Response>
  71. inline void _set_connack_reason_code_with_not_authorized(error_code& ec, Response& rep)
  72. {
  73. using response_type = typename detail::remove_cvref_t<Response>;
  74. ec = mqtt::make_error_code(mqtt::error::not_authorized);
  75. if constexpr /**/ (std::is_same_v<response_type, mqtt::v3::connack>)
  76. {
  77. rep.reason_code(mqtt::v3::connect_reason_code::not_authorized);
  78. }
  79. else if constexpr (std::is_same_v<response_type, mqtt::v4::connack>)
  80. {
  81. rep.reason_code(mqtt::v4::connect_reason_code::not_authorized);
  82. }
  83. else if constexpr (std::is_same_v<response_type, mqtt::v5::connack>)
  84. {
  85. rep.reason_code(mqtt::error::not_authorized);
  86. }
  87. else
  88. {
  89. static_assert(detail::always_false_v<Response>);
  90. }
  91. }
  92. template<class Message, class Response>
  93. inline void _check_connect_client_id(error_code& ec, caller_t* caller, Message& msg, Response& rep)
  94. {
  95. using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
  96. using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
  97. std::string_view client_id = msg.client_id();
  98. if constexpr /**/ (std::is_same_v<response_type, mqtt::v3::connack>)
  99. {
  100. // The first UTF-encoded string. The Client Identifier (Client ID) is between 1 and 23
  101. // characters long, and uniquely identifies the client to the server. It must be unique
  102. // across all clients connecting to a single server, and is the key in handling Message
  103. // IDs messages with QoS levels 1 and 2. If the Client ID contains more than 23 characters,
  104. // the server responds to the CONNECT message with a CONNACK return code 2: Identifier Rejected.
  105. if (client_id.size() < static_cast<std::string_view::size_type>(1) ||
  106. client_id.size() > static_cast<std::string_view::size_type>(23))
  107. return _set_connack_reason_code_with_invalid_id(ec, rep);
  108. }
  109. else if constexpr (std::is_same_v<response_type, mqtt::v4::connack>)
  110. {
  111. // If the Client supplies a zero-byte ClientId, the Client MUST also set CleanSession
  112. // to 1[MQTT-3.1.3-7].
  113. // If the Client supplies a zero-byte ClientId with CleanSession set to 0, the Server
  114. // MUST respond to the CONNECT Packet with a CONNACK return code 0x02 (Identifier rejected)
  115. // and then close the Network Connection[MQTT-3.1.3-8].
  116. // If the Server rejects the ClientId it MUST respond to the CONNECT Packet with a CONNACK
  117. // return code 0x02 (Identifier rejected) and then close the Network Connection[MQTT-3.1.3-9].
  118. if (client_id.empty())
  119. {
  120. if (msg.clean_session() == false)
  121. return _set_connack_reason_code_with_invalid_id(ec, rep);
  122. // assign a unique ClientId to that Client.
  123. msg.client_id(std::to_string(reinterpret_cast<std::size_t>(caller)));
  124. }
  125. }
  126. else if constexpr (std::is_same_v<response_type, mqtt::v5::connack>)
  127. {
  128. // and MUST return the Assigned Client Identifier in the CONNACK packet [MQTT-3.1.3-7].
  129. if (client_id.empty())
  130. {
  131. // assign a unique ClientId to that Client.
  132. msg.client_id(std::to_string(reinterpret_cast<std::size_t>(caller)));
  133. rep.properties().add(mqtt::v5::assigned_client_identifier(msg.client_id()));
  134. }
  135. }
  136. else
  137. {
  138. static_assert(detail::always_false_v<Response>);
  139. }
  140. // check whether uniquely identifier
  141. }
  142. // must be server
  143. template<class Message, class Response, bool IsClient = args_t::is_client>
  144. inline std::enable_if_t<!IsClient, void>
  145. _before_connect_callback(
  146. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  147. Message& msg, Response& rep)
  148. {
  149. detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
  150. using message_type [[maybe_unused]] = typename detail::remove_cvref_t<Message>;
  151. using response_type [[maybe_unused]] = typename detail::remove_cvref_t<Response>;
  152. // if started already and recvd connect message again, disconnect
  153. state_t expected = state_t::started;
  154. if (caller->state_.compare_exchange_strong(expected, state_t::started))
  155. {
  156. ec = mqtt::make_error_code(mqtt::error::malformed_packet);
  157. rep.set_send_flag(false);
  158. return;
  159. }
  160. // mqtt auth
  161. if (caller->security().enabled())
  162. {
  163. std::optional<std::string> username;
  164. if (caller->get_preauthed_username())
  165. {
  166. if (caller->security().login_cert(caller->get_preauthed_username().value()))
  167. {
  168. username = caller->get_preauthed_username();
  169. }
  170. }
  171. else if (msg.has_username() && msg.has_password())
  172. {
  173. username = caller->security().login(msg.username(), msg.password());
  174. }
  175. else
  176. {
  177. username = caller->security().login_anonymous();
  178. }
  179. // If login fails, try the unauthenticated user
  180. if (!username)
  181. {
  182. username = caller->security().login_unauthenticated();
  183. }
  184. if (!username)
  185. {
  186. ASIO2_LOG_TRACE("User failed to login: {}",
  187. (msg.has_username() ? msg.username() : "anonymous user"));
  188. if (msg.has_username() && msg.has_password())
  189. return _set_connack_reason_code_with_bad_user_name_or_password(ec, rep);
  190. return _set_connack_reason_code_with_not_authorized(ec, rep);
  191. }
  192. }
  193. // check client id
  194. if (_check_connect_client_id(ec, caller, msg, rep); ec)
  195. return;
  196. // set keepalive timeout
  197. // If the Keep Alive value is non-zero and the Server does not receive a Control Packet from
  198. // the Client within one and a half times the Keep Alive time period, it MUST disconnect the
  199. // Network Connection to the Client as if the network had failed [MQTT-3.1.2-24].
  200. // A Keep Alive value of zero (0) has the effect of turning off the keep alive mechanism.
  201. // This means that, in this case, the Server is not required to disconnect the Client on the
  202. // grounds of inactivity. Note that a Server is permitted to disconnect a Client that it
  203. // determines to be inactive or non-responsive at any time, regardless of the Keep Alive value
  204. // provided by that Client.
  205. mqtt::two_byte_integer::value_type keepalive = msg.keep_alive();
  206. if (keepalive == 0)
  207. {
  208. caller->set_silence_timeout(std::chrono::milliseconds(detail::tcp_silence_timeout));
  209. }
  210. else
  211. {
  212. caller->set_silence_timeout(std::chrono::milliseconds(keepalive * 1500));
  213. }
  214. // fill the reason code with 0.
  215. rep.reason_code(0);
  216. caller->connect_message_ = msg;
  217. // If a client with the same Client ID is already connected to the server, the "older" client
  218. // must be disconnected by the server before completing the CONNECT flow of the new client.
  219. // If CleanSession is set to 0, the Server MUST resume communications with the Client based on state
  220. // from the current Session (as identified by the Client identifier).
  221. // If there is no Session associated with the Client identifier the Server MUST create a new Session.
  222. // The Client and Server MUST store the Session after the Client and Server are disconnected [MQTT-3.1.2-4].
  223. // After the disconnection of a Session that had CleanSession set to 0, the Server MUST store further
  224. // QoS 1 and QoS 2 messages that match any subscriptions that the client had at the time of disconnection
  225. // as part of the Session state [MQTT-3.1.2-5]. It MAY also store QoS 0 messages that meet the same criteria.
  226. // If CleanSession is set to 1, the Client and Server MUST discard any previous Session and start a new one.
  227. // This Session lasts as long as the Network Connection.State data associated with this Session MUST NOT be
  228. // reused in any subsequent Session[MQTT-3.1.2-6].
  229. // If a CONNECT packet is received with Clean Start is set to 1, the Client and Server MUST discard any
  230. // existing Session and start a new Session [MQTT-3.1.2-4]. Consequently, the Session Present flag in
  231. // CONNACK is always set to 0 if Clean Start is set to 1.
  232. // If a CONNECT packet is received with Clean Start set to 0 and there is a Session associated with the
  233. // Client Identifier, the Server MUST resume communications with the Client based on state from the existing
  234. // Session[MQTT-3.1.2-5].If a CONNECT packet is received with Clean Start set to 0 and there is no Session
  235. // associated with the Client Identifier, the Server MUST create a new Session[MQTT-3.1.2-6].
  236. std::shared_ptr<caller_t> session_ptr = caller->mqtt_sessions().find_mqtt_session(caller->client_id());
  237. // If the Server accepts a connection with Clean Start set to 1, the Server MUST set Session
  238. // Present to 0 in the CONNACK packet in addition to setting a 0x00 (Success) Reason Code in
  239. // the CONNACK packet [MQTT-3.2.2-2].
  240. if (msg.clean_session())
  241. rep.session_present(false);
  242. // If the Server accepts a connection with Clean Start set to 0 and the Server has Session
  243. // State for the ClientID, it MUST set Session Present to 1 in the CONNACK packet, otherwise
  244. // it MUST set Session Present to 0 in the CONNACK packet. In both cases it MUST set a 0x00
  245. // (Success) Reason Code in the CONNACK packet [MQTT-3.2.2-3].
  246. else
  247. rep.session_present(session_ptr != nullptr);
  248. if (session_ptr == nullptr)
  249. {
  250. caller->mqtt_sessions().push_mqtt_session(caller->client_id(), caller_ptr);
  251. session_ptr = caller_ptr;
  252. }
  253. else
  254. {
  255. if (session_ptr->is_started())
  256. {
  257. // send will message
  258. if (!session_ptr->connect_message_.empty())
  259. {
  260. auto f = [caller_ptr, caller](auto& conn) mutable
  261. {
  262. if (!conn.has_will())
  263. return;
  264. // note : why v5 ?
  265. mqtt::v5::publish pub;
  266. pub.qos(conn.will_qos());
  267. pub.retain(conn.will_retain());
  268. pub.topic_name(conn.will_topic());
  269. pub.payload(conn.will_payload());
  270. caller->push_event(
  271. [caller_ptr, caller, pub = std::move(pub)]
  272. (event_queue_guard<caller_t> g) mutable
  273. {
  274. detail::ignore_unused(g);
  275. caller->_multicast_publish(caller_ptr, caller, std::move(pub), std::string{});
  276. });
  277. };
  278. if /**/ (std::holds_alternative<mqtt::v3::connect>(session_ptr->connect_message_.base()))
  279. {
  280. mqtt::v3::connect* p = session_ptr->connect_message_.template get_if<mqtt::v3::connect>();
  281. f(*p);
  282. }
  283. else if (std::holds_alternative<mqtt::v4::connect>(session_ptr->connect_message_.base()))
  284. {
  285. mqtt::v4::connect* p = session_ptr->connect_message_.template get_if<mqtt::v4::connect>();
  286. f(*p);
  287. }
  288. else if (std::holds_alternative<mqtt::v5::connect>(session_ptr->connect_message_.base()))
  289. {
  290. mqtt::v5::connect* p = session_ptr->connect_message_.template get_if<mqtt::v5::connect>();
  291. f(*p);
  292. }
  293. }
  294. // disconnect session
  295. // In previous versions, the mutex is a global variable, when code reached here,
  296. // the mutex status is locked already, so if we call session_ptr->stop()
  297. // directly, the stop maybe blocked forever, beacuse the session1 stop maybe
  298. // called in the session2 thread, and in the handle disconnect funcion of mqtt
  299. // session, the global mutex is required to lock again, so it caused deaklock,
  300. // to solve this problem, we can use session->post([](){session->stop()}).
  301. // but now, we change the mutex from global variable to member variable for each
  302. // mqtt class, so now, it won't caused deaklock, even we only use session->stop,
  303. // but we still use session->post([](){session->stop()}), to enhanced stability.
  304. session_ptr->post([session_ptr]() mutable { session_ptr->stop(); });
  305. //
  306. bool clean_session = false;
  307. if /**/ (std::holds_alternative<mqtt::v3::connect>(session_ptr->connect_message_.base()))
  308. {
  309. clean_session = session_ptr->connect_message_.template get_if<mqtt::v3::connect>()->clean_session();
  310. }
  311. else if (std::holds_alternative<mqtt::v4::connect>(session_ptr->connect_message_.base()))
  312. {
  313. clean_session = session_ptr->connect_message_.template get_if<mqtt::v4::connect>()->clean_session();
  314. }
  315. else if (std::holds_alternative<mqtt::v5::connect>(session_ptr->connect_message_.base()))
  316. {
  317. clean_session = session_ptr->connect_message_.template get_if<mqtt::v5::connect>()->clean_session();
  318. }
  319. if (clean_session)
  320. {
  321. }
  322. else
  323. {
  324. }
  325. if (msg.clean_session())
  326. {
  327. }
  328. else
  329. {
  330. // copy session state from old session to new session
  331. }
  332. }
  333. else
  334. {
  335. }
  336. // replace old session to new session
  337. session_ptr = caller_ptr;
  338. }
  339. }
  340. template<class Message, class Response, bool IsClient = args_t::is_client>
  341. inline std::enable_if_t<IsClient, void>
  342. _before_connect_callback(
  343. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  344. Message& msg, Response& rep)
  345. {
  346. detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
  347. ASIO2_ASSERT(false && "client should't recv the connect message");
  348. }
  349. // must be server
  350. inline void _before_user_callback_impl(
  351. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  352. mqtt::v3::connect& msg, mqtt::v3::connack& rep)
  353. {
  354. if (_before_connect_callback(ec, caller_ptr, caller, om, msg, rep); ec)
  355. return;
  356. }
  357. // must be server
  358. inline void _before_user_callback_impl(
  359. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  360. mqtt::v4::connect& msg, mqtt::v4::connack& rep)
  361. {
  362. if (_before_connect_callback(ec, caller_ptr, caller, om, msg, rep); ec)
  363. return;
  364. }
  365. // must be server
  366. inline void _before_user_callback_impl(
  367. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  368. mqtt::v5::connect& msg, mqtt::v5::connack& rep)
  369. {
  370. if (_before_connect_callback(ec, caller_ptr, caller, om, msg, rep); ec)
  371. return;
  372. }
  373. // must be server
  374. inline void _before_user_callback_impl(
  375. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  376. mqtt::v5::connect& msg, mqtt::v5::auth& rep)
  377. {
  378. detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
  379. //if constexpr (caller_t::is_session())
  380. //{
  381. // // if started already and recvd connect message again, disconnect
  382. // state_t expected = state_t::started;
  383. // if (caller->state_.compare_exchange_strong(expected, state_t::started))
  384. // {
  385. // ec = mqtt::make_error_code(mqtt::error::malformed_packet);
  386. // rep.set_send_flag(false);
  387. // return;
  388. // }
  389. // caller->connect_message_ = msg;
  390. // std::shared_ptr<caller_t> session_ptr = caller->mqtt_sessions().find_mqtt_session(msg.client_id());
  391. // if (session_ptr != nullptr)
  392. // {
  393. // }
  394. //}
  395. //else
  396. //{
  397. // std::ignore = true;
  398. //}
  399. }
  400. inline void _after_user_callback_impl(
  401. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  402. mqtt::v3::connect& msg, mqtt::v3::connack& rep)
  403. {
  404. detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
  405. // if already has error, return
  406. if (ec)
  407. return;
  408. // If a client with the same Client ID is already connected to the server, the "older" client
  409. // must be disconnected by the server before completing the CONNECT flow of the new client.
  410. switch(rep.reason_code())
  411. {
  412. case mqtt::v3::connect_reason_code::success : ec = mqtt::make_error_code(mqtt::error::success ); break;
  413. case mqtt::v3::connect_reason_code::unacceptable_protocol_version : ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version); break;
  414. case mqtt::v3::connect_reason_code::identifier_rejected : ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid ); break;
  415. case mqtt::v3::connect_reason_code::server_unavailable : ec = mqtt::make_error_code(mqtt::error::server_unavailable ); break;
  416. case mqtt::v3::connect_reason_code::bad_user_name_or_password : ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password ); break;
  417. case mqtt::v3::connect_reason_code::not_authorized : ec = mqtt::make_error_code(mqtt::error::not_authorized ); break;
  418. default : ec = mqtt::make_error_code(mqtt::error::malformed_packet ); break;
  419. }
  420. }
  421. inline void _after_user_callback_impl(
  422. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  423. mqtt::v4::connect& msg, mqtt::v4::connack& rep)
  424. {
  425. detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
  426. // if already has error, return
  427. if (ec)
  428. return;
  429. switch(rep.reason_code())
  430. {
  431. case mqtt::v4::connect_reason_code::success : ec = mqtt::make_error_code(mqtt::error::success ); break;
  432. case mqtt::v4::connect_reason_code::unacceptable_protocol_version : ec = mqtt::make_error_code(mqtt::error::unsupported_protocol_version); break;
  433. case mqtt::v4::connect_reason_code::identifier_rejected : ec = mqtt::make_error_code(mqtt::error::client_identifier_not_valid ); break;
  434. case mqtt::v4::connect_reason_code::server_unavailable : ec = mqtt::make_error_code(mqtt::error::server_unavailable ); break;
  435. case mqtt::v4::connect_reason_code::bad_user_name_or_password : ec = mqtt::make_error_code(mqtt::error::bad_user_name_or_password ); break;
  436. case mqtt::v4::connect_reason_code::not_authorized : ec = mqtt::make_error_code(mqtt::error::not_authorized ); break;
  437. default : ec = mqtt::make_error_code(mqtt::error::malformed_packet ); break;
  438. }
  439. }
  440. inline void _after_user_callback_impl(
  441. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  442. mqtt::v5::connect& msg, mqtt::v5::connack& rep)
  443. {
  444. detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
  445. // if already has error, return
  446. if (ec)
  447. return;
  448. ec = mqtt::make_error_code(static_cast<mqtt::error>(rep.reason_code()));
  449. if (!ec)
  450. {
  451. if (rep.properties().has<mqtt::v5::topic_alias_maximum>() == false)
  452. rep.properties().add(mqtt::v5::topic_alias_maximum{ caller->topic_alias_maximum() });
  453. }
  454. }
  455. inline void _after_user_callback_impl(
  456. error_code& ec, std::shared_ptr<caller_t>& caller_ptr, caller_t* caller, mqtt::message& om,
  457. mqtt::v5::connect& msg, mqtt::v5::auth& rep)
  458. {
  459. detail::ignore_unused(ec, caller_ptr, caller, om, msg, rep);
  460. // if already has error, return
  461. if (ec)
  462. return;
  463. }
  464. };
  465. }
  466. #endif // !__ASIO2_MQTT_AOP_CONNECT_HPP__