client-mqtt.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010 - 2020 Andy Green <[email protected]>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to
  8. * deal in the Software without restriction, including without limitation the
  9. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  10. * sell copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  21. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  22. * IN THE SOFTWARE.
  23. */
  24. /*
  25. * You can leave buf NULL, if so it will be allocated on the heap once the
  26. * actual length is known. nf should be 0, it will be set at allocation time.
  27. *
  28. * Or you can ensure no allocation and use an external buffer by setting buf
  29. * and lim. But buf must be in the ep context somehow, since it may have to
  30. * survive returns to the event loop unchanged. Set nf to 0 in this case.
  31. *
  32. * Or you can set buf to an externally allocated buffer, in which case you may
  33. * set nf so it will be freed when the string is "freed".
  34. */
  35. #include "private-lib-core.h"
  36. /* #include "lws-mqtt.h" */
  37. /* 3.1.3.1-5: MUST allow... that contain only the characters... */
  38. static const uint8_t *code = (const uint8_t *)
  39. "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  40. static int
  41. lws_mqtt_generate_id(struct lws* wsi, lws_mqtt_str_t **ms, const char *client_id)
  42. {
  43. struct lws_context *context = wsi->a.context;
  44. uint16_t ran[24]; /* 16-bit so wrap bias from %62 diluted by ~1000 */
  45. size_t n, len;
  46. uint8_t *buf;
  47. if (client_id)
  48. len = strlen(client_id);
  49. else
  50. len = 23;
  51. if (len > 23) /* 3.1.3.1-5: Server MUST... between 1 and 23 chars... */
  52. return 1;
  53. *ms = lws_mqtt_str_create((uint16_t)(len + 1));
  54. if (!*ms)
  55. return 1;
  56. buf = lws_mqtt_str_next(*ms, NULL);
  57. if (client_id) {
  58. lws_strnncpy((char *)buf, client_id, len, len + 1);
  59. lwsl_notice("%s: User space provided a client ID '%s'\n",
  60. __func__, (const char *)buf);
  61. } else {
  62. lwsl_notice("%s: generating random client id\n", __func__);
  63. n = len * sizeof(ran[0]);
  64. if (lws_get_random(context, ran, n) != n) {
  65. lws_mqtt_str_free(ms);
  66. return 1;
  67. }
  68. for (n = 0; n < len; n++)
  69. buf[n] = code[ran[n] % 62];
  70. buf[len] = '\0';
  71. }
  72. if (lws_mqtt_str_advance(*ms, (uint16_t)len)) {
  73. lws_mqtt_str_free(ms);
  74. return 1;
  75. }
  76. return 0;
  77. }
  78. int
  79. lws_read_mqtt(struct lws *wsi, unsigned char *buf, lws_filepos_t len)
  80. {
  81. lws_mqttc_t *c = &wsi->mqtt->client;
  82. return _lws_mqtt_rx_parser(wsi, &c->par, buf, len);
  83. }
  84. int
  85. lws_create_client_mqtt_object(const struct lws_client_connect_info *i,
  86. struct lws *wsi)
  87. {
  88. lws_mqttc_t *c;
  89. const lws_mqtt_client_connect_param_t *cp = i->mqtt_cp;
  90. /* allocate the ws struct for the wsi */
  91. wsi->mqtt = lws_zalloc(sizeof(*wsi->mqtt), "client mqtt struct");
  92. if (!wsi->mqtt)
  93. goto oom;
  94. wsi->mqtt->wsi = wsi;
  95. c = &wsi->mqtt->client;
  96. if (lws_mqtt_generate_id(wsi, &c->id, cp->client_id)) {
  97. lwsl_err("%s: Error generating client ID\n", __func__);
  98. return 1;
  99. }
  100. lwsl_info("%s: using client id '%.*s'\n", __func__, c->id->len,
  101. (const char *)c->id->buf);
  102. if (cp->clean_start || !cp->client_id[0])
  103. c->conn_flags = LMQCFT_CLEAN_START;
  104. c->keep_alive_secs = cp->keep_alive;
  105. if (cp->will_param.topic &&
  106. *cp->will_param.topic) {
  107. c->will.topic = lws_mqtt_str_create_cstr_dup(
  108. cp->will_param.topic, 0);
  109. if (!c->will.topic)
  110. goto oom1;
  111. c->conn_flags |= LMQCFT_WILL_FLAG;
  112. if (cp->will_param.message) {
  113. c->will.message = lws_mqtt_str_create_cstr_dup(
  114. cp->will_param.message, 0);
  115. if (!c->will.message)
  116. goto oom2;
  117. }
  118. c->conn_flags |= (cp->will_param.qos << 3) & LMQCFT_WILL_QOS_MASK;
  119. c->conn_flags |= (!!cp->will_param.retain) * LMQCFT_WILL_RETAIN;
  120. }
  121. if (cp->username &&
  122. *cp->username) {
  123. c->username = lws_mqtt_str_create_cstr_dup(cp->username, 0);
  124. if (!c->username)
  125. goto oom3;
  126. c->conn_flags |= LMQCFT_USERNAME;
  127. if (cp->password) {
  128. c->password =
  129. lws_mqtt_str_create_cstr_dup(cp->password, 0);
  130. if (!c->password)
  131. goto oom4;
  132. c->conn_flags |= LMQCFT_PASSWORD;
  133. }
  134. }
  135. return 0;
  136. oom4:
  137. lws_mqtt_str_free(&c->username);
  138. oom3:
  139. lws_mqtt_str_free(&c->will.message);
  140. oom2:
  141. lws_mqtt_str_free(&c->will.topic);
  142. oom1:
  143. lws_mqtt_str_free(&c->id);
  144. oom:
  145. lwsl_err("%s: OOM!\n", __func__);
  146. return 1;
  147. }
  148. int
  149. lws_mqtt_client_socket_service(struct lws *wsi, struct lws_pollfd *pollfd,
  150. struct lws *wsi_conn)
  151. {
  152. struct lws_context *context = wsi->a.context;
  153. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  154. int n = 0, m = 0;
  155. struct lws_tokens ebuf;
  156. int buffered = 0;
  157. char pending = 0;
  158. #if defined(LWS_WITH_TLS)
  159. char erbuf[128];
  160. #endif
  161. const char *cce = NULL;
  162. switch (lwsi_state(wsi)) {
  163. #if defined(LWS_WITH_SOCKS5)
  164. /* SOCKS Greeting Reply */
  165. case LRS_WAITING_SOCKS_GREETING_REPLY:
  166. case LRS_WAITING_SOCKS_AUTH_REPLY:
  167. case LRS_WAITING_SOCKS_CONNECT_REPLY:
  168. switch (lws_socks5c_handle_state(wsi, pollfd, &cce)) {
  169. case LW5CHS_RET_RET0:
  170. return 0;
  171. case LW5CHS_RET_BAIL3:
  172. goto bail3;
  173. case LW5CHS_RET_STARTHS:
  174. /*
  175. * Now we got the socks5 connection, we need to go down
  176. * the tls path on it if that's what we want
  177. */
  178. if (!(wsi->tls.use_ssl & LCCSCF_USE_SSL))
  179. goto start_ws_handshake;
  180. switch (lws_client_create_tls(wsi, &cce, 0)) {
  181. case 0:
  182. break;
  183. case 1:
  184. return 0;
  185. default:
  186. goto bail3;
  187. }
  188. break;
  189. default:
  190. break;
  191. }
  192. break;
  193. #endif
  194. case LRS_WAITING_DNS:
  195. /*
  196. * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
  197. * timeout protection set in client-handshake.c
  198. */
  199. if (!lws_client_connect_2_dnsreq(wsi)) {
  200. /* closed */
  201. lwsl_client("closed\n");
  202. return -1;
  203. }
  204. /* either still pending connection, or changed mode */
  205. return 0;
  206. case LRS_WAITING_CONNECT:
  207. /*
  208. * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
  209. * timeout protection set in client-handshake.c
  210. */
  211. if (pollfd->revents & LWS_POLLOUT)
  212. lws_client_connect_3_connect(wsi, NULL, NULL, 0, NULL);
  213. break;
  214. #if defined(LWS_WITH_TLS)
  215. case LRS_WAITING_SSL:
  216. if (wsi->tls.use_ssl & LCCSCF_USE_SSL) {
  217. n = lws_ssl_client_connect2(wsi, erbuf, sizeof(erbuf));
  218. if (!n)
  219. return 0;
  220. if (n < 0) {
  221. cce = erbuf;
  222. goto bail3;
  223. }
  224. } else
  225. wsi->tls.ssl = NULL;
  226. #endif /* LWS_WITH_TLS */
  227. #if defined(LWS_WITH_DETAILED_LATENCY)
  228. if (context->detailed_latency_cb) {
  229. wsi->detlat.type = LDLT_TLS_NEG_CLIENT;
  230. wsi->detlat.latencies[LAT_DUR_PROXY_CLIENT_REQ_TO_WRITE] =
  231. lws_now_usecs() -
  232. wsi->detlat.earliest_write_req_pre_write;
  233. wsi->detlat.latencies[LAT_DUR_USERCB] = 0;
  234. lws_det_lat_cb(wsi->a.context, &wsi->detlat);
  235. }
  236. #endif
  237. #if 0
  238. if (wsi->client_h2_alpn) {
  239. /*
  240. * We connected to the server and set up tls, and
  241. * negotiated "h2".
  242. *
  243. * So this is it, we are an h2 master client connection
  244. * now, not an h1 client connection.
  245. */
  246. #if defined(LWS_WITH_TLS)
  247. lws_tls_server_conn_alpn(wsi);
  248. #endif
  249. /* send the H2 preface to legitimize the connection */
  250. if (lws_h2_issue_preface(wsi)) {
  251. cce = "error sending h2 preface";
  252. goto bail3;
  253. }
  254. break;
  255. }
  256. #endif
  257. /* fallthru */
  258. #if defined(LWS_WITH_SOCKS5)
  259. start_ws_handshake:
  260. #endif
  261. lwsi_set_state(wsi, LRS_MQTTC_IDLE);
  262. lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
  263. context->timeout_secs);
  264. /* fallthru */
  265. case LRS_MQTTC_IDLE:
  266. /*
  267. * we should be ready to send out MQTT CONNECT
  268. */
  269. lwsl_info("%s: wsi %p: Transport established, send out CONNECT\n",
  270. __func__, wsi);
  271. if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
  272. return -1;
  273. if (!lws_mqtt_client_send_connect(wsi)) {
  274. lwsl_err("%s: Unable to send MQTT CONNECT\n", __func__);
  275. return -1;
  276. }
  277. if (lws_change_pollfd(wsi, 0, LWS_POLLIN))
  278. return -1;
  279. lwsi_set_state(wsi, LRS_MQTTC_AWAIT_CONNACK);
  280. return 0;
  281. case LRS_ESTABLISHED:
  282. case LRS_MQTTC_AWAIT_CONNACK:
  283. buffered = 0;
  284. ebuf.token = pt->serv_buf;
  285. ebuf.len = wsi->a.context->pt_serv_buf_size;
  286. if ((unsigned int)ebuf.len > wsi->a.context->pt_serv_buf_size)
  287. ebuf.len = wsi->a.context->pt_serv_buf_size;
  288. if ((int)pending > ebuf.len)
  289. pending = ebuf.len;
  290. ebuf.len = lws_ssl_capable_read(wsi, ebuf.token,
  291. pending ? (int)pending :
  292. ebuf.len);
  293. switch (ebuf.len) {
  294. case 0:
  295. lwsl_info("%s: zero length read\n",
  296. __func__);
  297. goto fail;
  298. case LWS_SSL_CAPABLE_MORE_SERVICE:
  299. lwsl_info("SSL Capable more service\n");
  300. return 0;
  301. case LWS_SSL_CAPABLE_ERROR:
  302. lwsl_info("%s: LWS_SSL_CAPABLE_ERROR\n",
  303. __func__);
  304. goto fail;
  305. }
  306. if (ebuf.len < 0)
  307. n = -1;
  308. else
  309. n = lws_read_mqtt(wsi, ebuf.token, ebuf.len);
  310. if (n < 0) {
  311. lwsl_err("%s: Parsing packet failed\n", __func__);
  312. goto fail;
  313. }
  314. m = ebuf.len - n;
  315. // lws_buflist_describe(&wsi->buflist, wsi, __func__);
  316. lwsl_debug("%s: consuming %d / %d\n", __func__, n, ebuf.len);
  317. if (lws_buflist_aware_finished_consuming(wsi, &ebuf, m,
  318. buffered,
  319. __func__))
  320. return -1;
  321. return 0;
  322. #if defined(LWS_WITH_TLS) || defined(LWS_WITH_SOCKS5)
  323. bail3:
  324. #endif
  325. lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
  326. if (cce)
  327. lwsl_info("reason: %s\n", cce);
  328. lws_inform_client_conn_fail(wsi, (void *)cce, strlen(cce));
  329. lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "cbail3");
  330. return -1;
  331. default:
  332. break;
  333. }
  334. return 0;
  335. fail:
  336. lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "mqtt svc fail");
  337. return LWS_HPI_RET_WSI_ALREADY_DIED;
  338. }