mqtt_transport_socket.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /**
  2. * Copyright (c) 2016 - 2019, Nordic Semiconductor ASA
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Nordic
  13. * Semiconductor ASA integrated circuit in a product or a software update for
  14. * such product, must reproduce the above copyright notice, this list of
  15. * conditions and the following disclaimer in the documentation and/or other
  16. * materials provided with the distribution.
  17. *
  18. * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19. * contributors may be used to endorse or promote products derived from this
  20. * software without specific prior written permission.
  21. *
  22. * 4. This software, with or without modification, must only be used with a
  23. * Nordic Semiconductor ASA integrated circuit.
  24. *
  25. * 5. Any software provided in binary form under this license must not be reverse
  26. * engineered, decompiled, modified and/or disassembled.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *
  39. */
  40. /** @file
  41. *
  42. * @brief MQTT Client Implementation over BSD Socket API on nRF.
  43. *
  44. * This file contains the source code for MQTT Protocol over BSD Socket API for a nRF device.
  45. * The implementation is limited to MQTT Client role only.
  46. */
  47. #include <unistd.h>
  48. #include <sys/socket.h>
  49. #include <netinet/in.h>
  50. #include "mem_manager.h"
  51. #include "mqtt_transport.h"
  52. #include "mqtt_internal.h"
  53. #include "mqtt_rx.h"
  54. #if MQTT_CONFIG_LOG_ENABLED
  55. #define NRF_LOG_MODULE_NAME mqtt_soc
  56. #define NRF_LOG_LEVEL MQTT_CONFIG_LOG_LEVEL
  57. #define NRF_LOG_INFO_COLOR MQTT_CONFIG_INFO_COLOR
  58. #define NRF_LOG_DEBUG_COLOR MQTT_CONFIG_DEBUG_COLOR
  59. #include "nrf_log.h"
  60. NRF_LOG_MODULE_REGISTER();
  61. #define MQTT_TRC NRF_LOG_DEBUG /**< Used for getting trace of execution in the module. */
  62. #define MQTT_ERR NRF_LOG_ERROR /**< Used for logging errors in the module. */
  63. #define MQTT_DUMP NRF_LOG_HEXDUMP_DEBUG /**< Used for dumping octet information to get details of bond information etc. */
  64. #define MQTT_ENTRY() MQTT_TRC(">> %s", __func__)
  65. #define MQTT_EXIT() MQTT_TRC("<< %s", __func__)
  66. #else // MQTT_CONFIG_LOG_ENABLED
  67. #define MQTT_TRC(...) /**< Disables traces. */
  68. #define MQTT_DUMP(...) /**< Disables dumping of octet streams. */
  69. #define MQTT_ERR(...) /**< Disables error logs. */
  70. #define MQTT_ENTRY(...)
  71. #define MQTT_EXIT(...)
  72. #endif // MQTT_CONFIG_LOG_ENABLED
  73. void disconnect_event_notify(mqtt_client_t * p_client, uint32_t result);
  74. /**@brief Close TCP connection and clean up client instance.
  75. *
  76. * @param[in] p_client Identifies the client for which the procedure is requested.
  77. */
  78. static void tcp_close_connection(const mqtt_client_t * p_client)
  79. {
  80. MQTT_TRC("Closing socket %d", p_client->socket_fd);
  81. UNUSED_VARIABLE(close(p_client->socket_fd));
  82. }
  83. uint32_t mqtt_client_tcp_write(mqtt_client_t * p_client, uint8_t const * data, uint32_t datalen)
  84. {
  85. uint32_t err_code = (NRF_ERROR_BUSY | IOT_MQTT_ERR_BASE);
  86. if (MQTT_VERIFY_STATE(p_client, MQTT_STATE_PENDING_WRITE))
  87. {
  88. err_code = (NRF_ERROR_BUSY | IOT_MQTT_ERR_BASE);
  89. }
  90. else if (MQTT_VERIFY_STATE(p_client, MQTT_STATE_TCP_CONNECTED))
  91. {
  92. MQTT_TRC("[%p]: TCP writing %d bytes.", p_client, datalen);
  93. MQTT_SET_STATE(p_client, MQTT_STATE_PENDING_WRITE);
  94. MQTT_MUTEX_UNLOCK();
  95. ssize_t nbytes = send(p_client->socket_fd, data, datalen, 0);
  96. MQTT_MUTEX_LOCK();
  97. MQTT_RESET_STATE(p_client, MQTT_STATE_PENDING_WRITE);
  98. if (nbytes == datalen)
  99. {
  100. MQTT_TRC("[%p]: TCP write complete.", p_client);
  101. UNUSED_VARIABLE(iot_timer_wall_clock_get(&p_client->last_activity));
  102. err_code = NRF_SUCCESS;
  103. }
  104. else
  105. {
  106. MQTT_TRC("TCP write failed, errno = %d, closing connection", errno);
  107. tcp_close_connection(p_client);
  108. disconnect_event_notify(p_client, MQTT_ERR_TRANSPORT_CLOSED);
  109. err_code = (NRF_ERROR_INTERNAL | IOT_MQTT_ERR_BASE);
  110. }
  111. }
  112. else
  113. {
  114. err_code = MQTT_ERR_NOT_CONNECTED;
  115. }
  116. return err_code;
  117. }
  118. uint32_t mqtt_client_tcp_read(mqtt_client_t * p_client, uint8_t * p_data, uint32_t datalen)
  119. {
  120. return mqtt_handle_rx_data(p_client, p_data, datalen);
  121. }
  122. uint32_t mqtt_client_tcp_connect(mqtt_client_t * p_client)
  123. {
  124. uint32_t err_code;
  125. connect_request_encode(p_client, &p_client->p_pending_packet, &p_client->pending_packetlen);
  126. // Send MQTT identification message to broker.
  127. MQTT_SET_STATE(p_client, MQTT_STATE_PENDING_WRITE);
  128. MQTT_MUTEX_UNLOCK();
  129. ssize_t nbytes = send(p_client->socket_fd,
  130. p_client->p_pending_packet,
  131. p_client->pending_packetlen,
  132. 0);
  133. MQTT_MUTEX_LOCK();
  134. MQTT_RESET_STATE(p_client, MQTT_STATE_PENDING_WRITE);
  135. if (nbytes == p_client->pending_packetlen)
  136. {
  137. UNUSED_VARIABLE(iot_timer_wall_clock_get(&p_client->last_activity));
  138. p_client->p_pending_packet = NULL;
  139. p_client->pending_packetlen = 0;
  140. err_code = NRF_SUCCESS;
  141. }
  142. else
  143. {
  144. mqtt_client_tcp_abort(p_client);
  145. err_code = (NRF_ERROR_INTERNAL | IOT_MQTT_ERR_BASE);
  146. }
  147. return err_code;
  148. }
  149. void mqtt_client_tcp_abort(mqtt_client_t * p_client)
  150. {
  151. tcp_close_connection(p_client);
  152. disconnect_event_notify(p_client, MQTT_ERR_TCP_PROC_FAILED);
  153. }
  154. uint32_t tcp_receive_packet(mqtt_client_t * p_client, uint32_t timeout)
  155. {
  156. if (timeout != 0)
  157. {
  158. // TODO: Implement support for timeout.
  159. return NRF_ERROR_NOT_SUPPORTED | IOT_MQTT_ERR_BASE;
  160. }
  161. uint8_t * p_packet = nrf_malloc(MQTT_MAX_PACKET_LENGTH);
  162. if (p_packet == NULL)
  163. {
  164. return NRF_ERROR_NO_MEM | IOT_MQTT_ERR_BASE;
  165. }
  166. MQTT_MUTEX_UNLOCK();
  167. ssize_t p_len = recv(p_client->socket_fd, p_packet, MQTT_MAX_PACKET_LENGTH, 0);
  168. MQTT_MUTEX_LOCK();
  169. uint32_t err_code;
  170. if (p_len > 0)
  171. {
  172. err_code = mqtt_transport_read(p_client, p_packet, p_len);
  173. MQTT_TRC("Received %d bytes from %d: 0x%08x",
  174. p_len, p_client->socket_fd, err_code);
  175. }
  176. else if (p_len == 0)
  177. {
  178. // Receiving 0 bytes indicates an orderly shutdown.
  179. MQTT_TRC("Received end of stream, closing connection");
  180. tcp_close_connection(p_client);
  181. disconnect_event_notify(p_client, MQTT_ERR_TRANSPORT_CLOSED);
  182. err_code = NRF_SUCCESS;
  183. }
  184. else
  185. {
  186. MQTT_TRC("Error receiving data, errno = %d, closing connection", errno);
  187. mqtt_client_tcp_abort(p_client);
  188. err_code = (NRF_ERROR_INVALID_DATA | IOT_MQTT_ERR_BASE);
  189. }
  190. nrf_free(p_packet);
  191. return err_code;
  192. }
  193. uint32_t tcp_request_connection(mqtt_client_t * p_client)
  194. {
  195. uint32_t err_code = NRF_SUCCESS;
  196. p_client->socket_fd = socket(AF_INET6, SOCK_STREAM, 0);
  197. MQTT_TRC("Created socket %d", p_client->socket_fd);
  198. if (p_client->socket_fd < 0)
  199. {
  200. err_code = (NRF_ERROR_INTERNAL | IOT_MQTT_ERR_BASE);
  201. }
  202. if (err_code == NRF_SUCCESS)
  203. {
  204. struct sockaddr_in6 dest;
  205. memset(&dest, 0, sizeof(dest));
  206. dest.sin6_family = AF_INET6;
  207. dest.sin6_port = htons(p_client->broker_port);
  208. memcpy(&dest.sin6_addr, p_client->broker_addr.u8, sizeof(dest.sin6_addr));
  209. int ret = connect(p_client->socket_fd, (struct sockaddr *)&dest, sizeof(dest));
  210. if (ret == 0)
  211. {
  212. MQTT_SET_STATE(p_client, MQTT_STATE_TCP_CONNECTED);
  213. err_code = mqtt_transport_connect(p_client);
  214. MQTT_TRC("Sent connect %d: 0x%08x", p_client->socket_fd, err_code);
  215. }
  216. else
  217. {
  218. mqtt_client_tcp_abort(p_client);
  219. err_code = (NRF_ERROR_INTERNAL | IOT_MQTT_ERR_BASE);
  220. }
  221. }
  222. while (!MQTT_VERIFY_STATE(p_client, MQTT_STATE_CONNECTED) && err_code == NRF_SUCCESS)
  223. {
  224. // Receive until connected.
  225. MQTT_TRC("Receive until connected");
  226. err_code = tcp_receive_packet(p_client, 0);
  227. }
  228. MQTT_TRC("Connect completed");
  229. return err_code;
  230. }
  231. uint32_t mqtt_client_tcp_disconnect(mqtt_client_t * p_client)
  232. {
  233. uint32_t err_code;
  234. if (MQTT_VERIFY_STATE(p_client, MQTT_STATE_CONNECTED))
  235. {
  236. const uint8_t packet[] = {MQTT_PKT_TYPE_DISCONNECT, 0x00};
  237. MQTT_SET_STATE(p_client, MQTT_STATE_PENDING_WRITE);
  238. MQTT_MUTEX_UNLOCK();
  239. UNUSED_VARIABLE(send(p_client->socket_fd, (void *)packet, sizeof(packet), 0));
  240. MQTT_MUTEX_LOCK();
  241. MQTT_RESET_STATE(p_client, MQTT_STATE_PENDING_WRITE);
  242. tcp_close_connection(p_client);
  243. err_code = NRF_SUCCESS;
  244. }
  245. else if (MQTT_VERIFY_STATE(p_client, MQTT_STATE_TCP_CONNECTED))
  246. {
  247. tcp_close_connection(p_client);
  248. err_code = NRF_SUCCESS;
  249. }
  250. else
  251. {
  252. err_code = (NRF_ERROR_INVALID_STATE | IOT_MQTT_ERR_BASE);
  253. }
  254. return err_code;
  255. }