MqttClient.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  4. */
  5. #include <aws/iot/MqttClient.h>
  6. #include <aws/crt/Api.h>
  7. #include <aws/crt/auth/Credentials.h>
  8. #include <aws/crt/auth/Sigv4Signing.h>
  9. #include <aws/crt/http/HttpRequestResponse.h>
  10. #if !BYO_CRYPTO
  11. namespace Aws
  12. {
  13. namespace Iot
  14. {
  15. MqttClientConnectionConfig::MqttClientConnectionConfig(int lastError) noexcept
  16. : m_port(0), m_lastError(lastError)
  17. {
  18. }
  19. MqttClientConnectionConfig MqttClientConnectionConfig::CreateInvalid(int lastError) noexcept
  20. {
  21. return MqttClientConnectionConfig(lastError);
  22. }
  23. MqttClientConnectionConfig::MqttClientConnectionConfig(
  24. const Crt::String &endpoint,
  25. uint16_t port,
  26. const Crt::Io::SocketOptions &socketOptions,
  27. Crt::Io::TlsContext &&tlsContext)
  28. : m_endpoint(endpoint), m_port(port), m_context(std::move(tlsContext)), m_socketOptions(socketOptions),
  29. m_lastError(0)
  30. {
  31. }
  32. MqttClientConnectionConfig::MqttClientConnectionConfig(
  33. const Crt::String &endpoint,
  34. uint16_t port,
  35. const Crt::Io::SocketOptions &socketOptions,
  36. Crt::Io::TlsContext &&tlsContext,
  37. Crt::Mqtt::OnWebSocketHandshakeIntercept &&interceptor,
  38. const Crt::Optional<Crt::Http::HttpClientConnectionProxyOptions> &proxyOptions)
  39. : m_endpoint(endpoint), m_port(port), m_context(std::move(tlsContext)), m_socketOptions(socketOptions),
  40. m_webSocketInterceptor(std::move(interceptor)), m_proxyOptions(proxyOptions), m_lastError(0)
  41. {
  42. }
  43. MqttClientConnectionConfig::MqttClientConnectionConfig(
  44. const Crt::String &endpoint,
  45. uint16_t port,
  46. const Crt::Io::SocketOptions &socketOptions,
  47. Crt::Io::TlsContext &&tlsContext,
  48. const Crt::Optional<Crt::Http::HttpClientConnectionProxyOptions> &proxyOptions)
  49. : m_endpoint(endpoint), m_port(port), m_context(std::move(tlsContext)), m_socketOptions(socketOptions),
  50. m_proxyOptions(proxyOptions), m_lastError(0)
  51. {
  52. }
  53. MqttClientConnectionConfigBuilder::MqttClientConnectionConfigBuilder()
  54. : MqttClientConnectionConfigBuilder(Crt::ApiAllocator())
  55. {
  56. m_lastError = AWS_ERROR_INVALID_STATE;
  57. }
  58. // Common setup shared by all valid constructors
  59. MqttClientConnectionConfigBuilder::MqttClientConnectionConfigBuilder(Crt::Allocator *allocator) noexcept
  60. : m_allocator(allocator), m_portOverride(0),
  61. # ifdef AWS_IOT_SDK_VERSION
  62. m_sdkVersion(AWS_IOT_SDK_VERSION),
  63. # else
  64. m_sdkVersion(AWS_CRT_CPP_VERSION),
  65. # endif
  66. m_lastError(0)
  67. {
  68. m_socketOptions.SetConnectTimeoutMs(3000);
  69. }
  70. MqttClientConnectionConfigBuilder::MqttClientConnectionConfigBuilder(
  71. const char *certPath,
  72. const char *pkeyPath,
  73. Crt::Allocator *allocator) noexcept
  74. : MqttClientConnectionConfigBuilder(allocator)
  75. {
  76. m_contextOptions = Crt::Io::TlsContextOptions::InitClientWithMtls(certPath, pkeyPath, allocator);
  77. if (!m_contextOptions)
  78. {
  79. m_lastError = m_contextOptions.LastError();
  80. return;
  81. }
  82. }
  83. MqttClientConnectionConfigBuilder::MqttClientConnectionConfigBuilder(
  84. const Crt::ByteCursor &cert,
  85. const Crt::ByteCursor &pkey,
  86. Crt::Allocator *allocator) noexcept
  87. : MqttClientConnectionConfigBuilder(allocator)
  88. {
  89. m_contextOptions = Crt::Io::TlsContextOptions::InitClientWithMtls(cert, pkey, allocator);
  90. if (!m_contextOptions)
  91. {
  92. m_lastError = m_contextOptions.LastError();
  93. return;
  94. }
  95. }
  96. MqttClientConnectionConfigBuilder::MqttClientConnectionConfigBuilder(
  97. const Crt::Io::TlsContextPkcs11Options &pkcs11Options,
  98. Crt::Allocator *allocator) noexcept
  99. : MqttClientConnectionConfigBuilder(allocator)
  100. {
  101. m_contextOptions = Crt::Io::TlsContextOptions::InitClientWithMtlsPkcs11(pkcs11Options, allocator);
  102. if (!m_contextOptions)
  103. {
  104. m_lastError = m_contextOptions.LastError();
  105. return;
  106. }
  107. }
  108. MqttClientConnectionConfigBuilder::MqttClientConnectionConfigBuilder(
  109. const char *windowsCertStorePath,
  110. Crt::Allocator *allocator) noexcept
  111. : MqttClientConnectionConfigBuilder(allocator)
  112. {
  113. m_contextOptions =
  114. Crt::Io::TlsContextOptions::InitClientWithMtlsSystemPath(windowsCertStorePath, allocator);
  115. if (!m_contextOptions)
  116. {
  117. m_lastError = m_contextOptions.LastError();
  118. return;
  119. }
  120. }
  121. MqttClientConnectionConfigBuilder::MqttClientConnectionConfigBuilder(
  122. const WebsocketConfig &config,
  123. Crt::Allocator *allocator) noexcept
  124. : MqttClientConnectionConfigBuilder(allocator)
  125. {
  126. m_contextOptions = Crt::Io::TlsContextOptions::InitDefaultClient(allocator);
  127. if (!m_contextOptions)
  128. {
  129. m_lastError = m_contextOptions.LastError();
  130. return;
  131. }
  132. m_websocketConfig = config;
  133. }
  134. MqttClientConnectionConfigBuilder MqttClientConnectionConfigBuilder::NewDefaultBuilder() noexcept
  135. {
  136. MqttClientConnectionConfigBuilder return_value =
  137. MqttClientConnectionConfigBuilder(Aws::Crt::ApiAllocator());
  138. return_value.m_contextOptions = Crt::Io::TlsContextOptions::InitDefaultClient();
  139. return return_value;
  140. }
  141. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithEndpoint(const Crt::String &endpoint)
  142. {
  143. m_endpoint = endpoint;
  144. return *this;
  145. }
  146. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithEndpoint(Crt::String &&endpoint)
  147. {
  148. m_endpoint = std::move(endpoint);
  149. return *this;
  150. }
  151. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithMetricsCollection(bool enabled)
  152. {
  153. m_enableMetricsCollection = enabled;
  154. return *this;
  155. }
  156. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithSdkName(const Crt::String &sdkName)
  157. {
  158. m_sdkName = sdkName;
  159. return *this;
  160. }
  161. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithSdkVersion(
  162. const Crt::String &sdkVersion)
  163. {
  164. m_sdkVersion = sdkVersion;
  165. return *this;
  166. }
  167. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithPortOverride(uint16_t port) noexcept
  168. {
  169. m_portOverride = port;
  170. return *this;
  171. }
  172. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithCertificateAuthority(
  173. const char *caPath) noexcept
  174. {
  175. if (m_contextOptions)
  176. {
  177. if (!m_contextOptions.OverrideDefaultTrustStore(nullptr, caPath))
  178. {
  179. m_lastError = m_contextOptions.LastError();
  180. }
  181. }
  182. return *this;
  183. }
  184. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithCertificateAuthority(
  185. const Crt::ByteCursor &cert) noexcept
  186. {
  187. if (m_contextOptions)
  188. {
  189. if (!m_contextOptions.OverrideDefaultTrustStore(cert))
  190. {
  191. m_lastError = m_contextOptions.LastError();
  192. }
  193. }
  194. return *this;
  195. }
  196. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithTcpKeepAlive() noexcept
  197. {
  198. m_socketOptions.SetKeepAlive(true);
  199. return *this;
  200. }
  201. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithTcpConnectTimeout(
  202. uint32_t connectTimeoutMs) noexcept
  203. {
  204. m_socketOptions.SetConnectTimeoutMs(connectTimeoutMs);
  205. return *this;
  206. }
  207. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithTcpKeepAliveTimeout(
  208. uint16_t keepAliveTimeoutSecs) noexcept
  209. {
  210. m_socketOptions.SetKeepAliveTimeoutSec(keepAliveTimeoutSecs);
  211. return *this;
  212. }
  213. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithTcpKeepAliveInterval(
  214. uint16_t keepAliveIntervalSecs) noexcept
  215. {
  216. m_socketOptions.SetKeepAliveIntervalSec(keepAliveIntervalSecs);
  217. return *this;
  218. }
  219. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithTcpKeepAliveMaxProbes(
  220. uint16_t maxProbes) noexcept
  221. {
  222. m_socketOptions.SetKeepAliveMaxFailedProbes(maxProbes);
  223. return *this;
  224. }
  225. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithMinimumTlsVersion(
  226. aws_tls_versions minimumTlsVersion) noexcept
  227. {
  228. m_contextOptions.SetMinimumTlsVersion(minimumTlsVersion);
  229. return *this;
  230. }
  231. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithHttpProxyOptions(
  232. const Crt::Http::HttpClientConnectionProxyOptions &proxyOptions) noexcept
  233. {
  234. m_proxyOptions = proxyOptions;
  235. return *this;
  236. }
  237. Crt::String MqttClientConnectionConfigBuilder::AddToUsernameParameter(
  238. Crt::String currentUsername,
  239. Crt::String parameterValue,
  240. Crt::String parameterPreText)
  241. {
  242. Crt::String return_string = currentUsername;
  243. if (return_string.find("?") != Crt::String::npos)
  244. {
  245. return_string += "&";
  246. }
  247. else
  248. {
  249. return_string += "?";
  250. }
  251. if (parameterValue.find(parameterPreText) != Crt::String::npos)
  252. {
  253. return return_string + parameterValue;
  254. }
  255. else
  256. {
  257. return return_string + parameterPreText + parameterValue;
  258. }
  259. }
  260. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithCustomAuthorizer(
  261. const Crt::String &username,
  262. const Crt::String &authorizerName,
  263. const Crt::String &authorizerSignature,
  264. const Crt::String &password) noexcept
  265. {
  266. if (!m_contextOptions.IsAlpnSupported())
  267. {
  268. m_lastError = AWS_ERROR_INVALID_STATE;
  269. return *this;
  270. }
  271. m_isUsingCustomAuthorizer = true;
  272. Crt::String usernameString = "";
  273. if (username.empty())
  274. {
  275. if (!m_username.empty())
  276. {
  277. usernameString += m_username;
  278. }
  279. }
  280. else
  281. {
  282. usernameString += username;
  283. }
  284. if (!authorizerName.empty())
  285. {
  286. usernameString = AddToUsernameParameter(usernameString, authorizerName, "x-amz-customauthorizer-name=");
  287. }
  288. if (!authorizerSignature.empty())
  289. {
  290. usernameString =
  291. AddToUsernameParameter(usernameString, authorizerSignature, "x-amz-customauthorizer-signature=");
  292. }
  293. m_username = usernameString;
  294. m_password = password;
  295. if (!m_websocketConfig)
  296. {
  297. if (!m_contextOptions.SetAlpnList("mqtt"))
  298. {
  299. m_lastError = m_contextOptions.LastError();
  300. }
  301. m_portOverride = 443;
  302. }
  303. return *this;
  304. }
  305. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithUsername(
  306. const Crt::String &username) noexcept
  307. {
  308. m_username = username;
  309. return *this;
  310. }
  311. MqttClientConnectionConfigBuilder &MqttClientConnectionConfigBuilder::WithPassword(
  312. const Crt::String &password) noexcept
  313. {
  314. m_password = password;
  315. return *this;
  316. }
  317. MqttClientConnectionConfig MqttClientConnectionConfigBuilder::Build() noexcept
  318. {
  319. if (m_lastError != 0)
  320. {
  321. return MqttClientConnectionConfig::CreateInvalid(m_lastError);
  322. }
  323. uint16_t port = m_portOverride;
  324. if (!m_portOverride)
  325. {
  326. if (m_websocketConfig || Crt::Io::TlsContextOptions::IsAlpnSupported())
  327. {
  328. port = 443;
  329. }
  330. else
  331. {
  332. port = 8883;
  333. }
  334. }
  335. Crt::String username = m_username;
  336. Crt::String password = m_password;
  337. // Check to see if a custom authorizer is being used but not through the builder
  338. if (!m_isUsingCustomAuthorizer)
  339. {
  340. if (!m_username.empty())
  341. {
  342. if (m_username.find_first_of("x-amz-customauthorizer-name=") != Crt::String::npos ||
  343. m_username.find_first_of("x-amz-customauthorizer-signature=") != Crt::String::npos)
  344. {
  345. m_isUsingCustomAuthorizer = true;
  346. }
  347. }
  348. }
  349. if (port == 443 && !m_websocketConfig && Crt::Io::TlsContextOptions::IsAlpnSupported() &&
  350. !m_isUsingCustomAuthorizer)
  351. {
  352. if (!m_contextOptions.SetAlpnList("x-amzn-mqtt-ca"))
  353. {
  354. return MqttClientConnectionConfig::CreateInvalid(m_contextOptions.LastError());
  355. }
  356. }
  357. // Is the user trying to connect using a custom authorizer?
  358. if (m_isUsingCustomAuthorizer)
  359. {
  360. if (port != 443)
  361. {
  362. AWS_LOGF_WARN(
  363. AWS_LS_MQTT_GENERAL,
  364. "Attempting to connect to authorizer with unsupported port. Port is not 443...");
  365. }
  366. }
  367. // add metrics string to username (if metrics enabled)
  368. if (m_enableMetricsCollection)
  369. {
  370. if (username.find('?') != Crt::String::npos)
  371. {
  372. username += "&";
  373. }
  374. else
  375. {
  376. username += "?";
  377. }
  378. username += "SDK=";
  379. username += m_sdkName;
  380. username += "&Version=";
  381. username += m_sdkVersion;
  382. }
  383. auto tlsContext = Crt::Io::TlsContext(m_contextOptions, Crt::Io::TlsMode::CLIENT, m_allocator);
  384. if (!tlsContext)
  385. {
  386. return MqttClientConnectionConfig::CreateInvalid(tlsContext.GetInitializationError());
  387. }
  388. if (!m_websocketConfig)
  389. {
  390. auto config = MqttClientConnectionConfig(
  391. m_endpoint, port, m_socketOptions, std::move(tlsContext), m_proxyOptions);
  392. config.m_username = username;
  393. config.m_password = password;
  394. return config;
  395. }
  396. auto websocketConfig = m_websocketConfig.value();
  397. auto signerTransform = [websocketConfig](
  398. std::shared_ptr<Crt::Http::HttpRequest> req,
  399. const Crt::Mqtt::OnWebSocketHandshakeInterceptComplete &onComplete) {
  400. // it is only a very happy coincidence that these function signatures match. This is the callback
  401. // for signing to be complete. It invokes the callback for websocket handshake to be complete.
  402. auto signingComplete =
  403. [onComplete](const std::shared_ptr<Aws::Crt::Http::HttpRequest> &req1, int errorCode) {
  404. onComplete(req1, errorCode);
  405. };
  406. auto signerConfig = websocketConfig.CreateSigningConfigCb();
  407. websocketConfig.Signer->SignRequest(req, *signerConfig, signingComplete);
  408. };
  409. bool useWebsocketProxyOptions = m_websocketConfig->ProxyOptions.has_value() && !m_proxyOptions.has_value();
  410. auto config = MqttClientConnectionConfig(
  411. m_endpoint,
  412. port,
  413. m_socketOptions,
  414. std::move(tlsContext),
  415. signerTransform,
  416. useWebsocketProxyOptions ? m_websocketConfig->ProxyOptions : m_proxyOptions);
  417. config.m_username = username;
  418. config.m_password = password;
  419. return config;
  420. }
  421. MqttClient::MqttClient(Crt::Io::ClientBootstrap &bootstrap, Crt::Allocator *allocator) noexcept
  422. : m_client(bootstrap, allocator), m_lastError(0)
  423. {
  424. if (!m_client)
  425. {
  426. m_lastError = m_client.LastError();
  427. }
  428. }
  429. MqttClient::MqttClient(Crt::Allocator *allocator) noexcept
  430. : MqttClient(*Crt::ApiHandle::GetOrCreateStaticDefaultClientBootstrap(), allocator)
  431. {
  432. }
  433. std::shared_ptr<Crt::Mqtt::MqttConnection> MqttClient::NewConnection(
  434. const MqttClientConnectionConfig &config) noexcept
  435. {
  436. if (!config)
  437. {
  438. m_lastError = config.LastError();
  439. return nullptr;
  440. }
  441. bool useWebsocket = config.m_webSocketInterceptor.operator bool();
  442. auto newConnection = m_client.NewConnection(
  443. config.m_endpoint.c_str(), config.m_port, config.m_socketOptions, config.m_context, useWebsocket);
  444. if (!newConnection)
  445. {
  446. m_lastError = m_client.LastError();
  447. return nullptr;
  448. }
  449. if (!(*newConnection))
  450. {
  451. m_lastError = newConnection->LastError();
  452. return nullptr;
  453. }
  454. if (!config.m_username.empty() || !config.m_password.empty())
  455. {
  456. if (!newConnection->SetLogin(config.m_username.c_str(), config.m_password.c_str()))
  457. {
  458. m_lastError = newConnection->LastError();
  459. return nullptr;
  460. }
  461. }
  462. if (useWebsocket)
  463. {
  464. newConnection->WebsocketInterceptor = config.m_webSocketInterceptor;
  465. }
  466. if (config.m_proxyOptions)
  467. {
  468. newConnection->SetHttpProxyOptions(config.m_proxyOptions.value());
  469. }
  470. return newConnection;
  471. }
  472. } // namespace Iot
  473. } // namespace Aws
  474. #endif // !BYO_CRYPTO