mqtt.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. * Copyright (C) Björn Stenberg, <bjorn@haxx.se>
  10. *
  11. * This software is licensed as described in the file COPYING, which
  12. * you should have received as part of this distribution. The terms
  13. * are also available at https://curl.se/docs/copyright.html.
  14. *
  15. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  16. * copies of the Software, and permit persons to whom the Software is
  17. * furnished to do so, under the terms of the COPYING file.
  18. *
  19. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  20. * KIND, either express or implied.
  21. *
  22. * SPDX-License-Identifier: curl
  23. *
  24. ***************************************************************************/
  25. #include "curl_setup.h"
  26. #ifndef CURL_DISABLE_MQTT
  27. #include "urldata.h"
  28. #include <curl/curl.h>
  29. #include "transfer.h"
  30. #include "sendf.h"
  31. #include "progress.h"
  32. #include "mqtt.h"
  33. #include "select.h"
  34. #include "strdup.h"
  35. #include "url.h"
  36. #include "escape.h"
  37. #include "warnless.h"
  38. #include "curl_printf.h"
  39. #include "curl_memory.h"
  40. #include "multiif.h"
  41. #include "rand.h"
  42. /* The last #include file should be: */
  43. #include "memdebug.h"
  44. #define MQTT_MSG_CONNECT 0x10
  45. #define MQTT_MSG_CONNACK 0x20
  46. #define MQTT_MSG_PUBLISH 0x30
  47. #define MQTT_MSG_SUBSCRIBE 0x82
  48. #define MQTT_MSG_SUBACK 0x90
  49. #define MQTT_MSG_DISCONNECT 0xe0
  50. #define MQTT_CONNACK_LEN 2
  51. #define MQTT_SUBACK_LEN 3
  52. #define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */
  53. /*
  54. * Forward declarations.
  55. */
  56. static CURLcode mqtt_do(struct Curl_easy *data, bool *done);
  57. static CURLcode mqtt_done(struct Curl_easy *data,
  58. CURLcode status, bool premature);
  59. static CURLcode mqtt_doing(struct Curl_easy *data, bool *done);
  60. static int mqtt_getsock(struct Curl_easy *data, struct connectdata *conn,
  61. curl_socket_t *sock);
  62. static CURLcode mqtt_setup_conn(struct Curl_easy *data,
  63. struct connectdata *conn);
  64. /*
  65. * MQTT protocol handler.
  66. */
  67. const struct Curl_handler Curl_handler_mqtt = {
  68. "mqtt", /* scheme */
  69. mqtt_setup_conn, /* setup_connection */
  70. mqtt_do, /* do_it */
  71. mqtt_done, /* done */
  72. ZERO_NULL, /* do_more */
  73. ZERO_NULL, /* connect_it */
  74. ZERO_NULL, /* connecting */
  75. mqtt_doing, /* doing */
  76. ZERO_NULL, /* proto_getsock */
  77. mqtt_getsock, /* doing_getsock */
  78. ZERO_NULL, /* domore_getsock */
  79. ZERO_NULL, /* perform_getsock */
  80. ZERO_NULL, /* disconnect */
  81. ZERO_NULL, /* write_resp */
  82. ZERO_NULL, /* write_resp_hd */
  83. ZERO_NULL, /* connection_check */
  84. ZERO_NULL, /* attach connection */
  85. PORT_MQTT, /* defport */
  86. CURLPROTO_MQTT, /* protocol */
  87. CURLPROTO_MQTT, /* family */
  88. PROTOPT_NONE /* flags */
  89. };
  90. static CURLcode mqtt_setup_conn(struct Curl_easy *data,
  91. struct connectdata *conn)
  92. {
  93. /* allocate the HTTP-specific struct for the Curl_easy, only to survive
  94. during this request */
  95. struct MQTT *mq;
  96. (void)conn;
  97. DEBUGASSERT(data->req.p.mqtt == NULL);
  98. mq = calloc(1, sizeof(struct MQTT));
  99. if(!mq)
  100. return CURLE_OUT_OF_MEMORY;
  101. Curl_dyn_init(&mq->recvbuf, DYN_MQTT_RECV);
  102. data->req.p.mqtt = mq;
  103. return CURLE_OK;
  104. }
  105. static CURLcode mqtt_send(struct Curl_easy *data,
  106. char *buf, size_t len)
  107. {
  108. CURLcode result = CURLE_OK;
  109. struct MQTT *mq = data->req.p.mqtt;
  110. size_t n;
  111. result = Curl_xfer_send(data, buf, len, &n);
  112. if(result)
  113. return result;
  114. Curl_debug(data, CURLINFO_HEADER_OUT, buf, (size_t)n);
  115. if(len != n) {
  116. size_t nsend = len - n;
  117. char *sendleftovers = Curl_memdup(&buf[n], nsend);
  118. if(!sendleftovers)
  119. return CURLE_OUT_OF_MEMORY;
  120. mq->sendleftovers = sendleftovers;
  121. mq->nsend = nsend;
  122. }
  123. else {
  124. mq->sendleftovers = NULL;
  125. mq->nsend = 0;
  126. }
  127. return result;
  128. }
  129. /* Generic function called by the multi interface to figure out what socket(s)
  130. to wait for and for what actions during the DOING and PROTOCONNECT
  131. states */
  132. static int mqtt_getsock(struct Curl_easy *data,
  133. struct connectdata *conn,
  134. curl_socket_t *sock)
  135. {
  136. (void)data;
  137. sock[0] = conn->sock[FIRSTSOCKET];
  138. return GETSOCK_READSOCK(FIRSTSOCKET);
  139. }
  140. static int mqtt_encode_len(char *buf, size_t len)
  141. {
  142. int i;
  143. for(i = 0; (len > 0) && (i<4); i++) {
  144. unsigned char encoded;
  145. encoded = len % 0x80;
  146. len /= 0x80;
  147. if(len)
  148. encoded |= 0x80;
  149. buf[i] = (char)encoded;
  150. }
  151. return i;
  152. }
  153. /* add the passwd to the CONNECT packet */
  154. static int add_passwd(const char *passwd, const size_t plen,
  155. char *pkt, const size_t start, int remain_pos)
  156. {
  157. /* magic number that need to be set properly */
  158. const size_t conn_flags_pos = remain_pos + 8;
  159. if(plen > 0xffff)
  160. return 1;
  161. /* set password flag */
  162. pkt[conn_flags_pos] |= 0x40;
  163. /* length of password provided */
  164. pkt[start] = (char)((plen >> 8) & 0xFF);
  165. pkt[start + 1] = (char)(plen & 0xFF);
  166. memcpy(&pkt[start + 2], passwd, plen);
  167. return 0;
  168. }
  169. /* add user to the CONNECT packet */
  170. static int add_user(const char *username, const size_t ulen,
  171. unsigned char *pkt, const size_t start, int remain_pos)
  172. {
  173. /* magic number that need to be set properly */
  174. const size_t conn_flags_pos = remain_pos + 8;
  175. if(ulen > 0xffff)
  176. return 1;
  177. /* set username flag */
  178. pkt[conn_flags_pos] |= 0x80;
  179. /* length of username provided */
  180. pkt[start] = (unsigned char)((ulen >> 8) & 0xFF);
  181. pkt[start + 1] = (unsigned char)(ulen & 0xFF);
  182. memcpy(&pkt[start + 2], username, ulen);
  183. return 0;
  184. }
  185. /* add client ID to the CONNECT packet */
  186. static int add_client_id(const char *client_id, const size_t client_id_len,
  187. char *pkt, const size_t start)
  188. {
  189. if(client_id_len != MQTT_CLIENTID_LEN)
  190. return 1;
  191. pkt[start] = 0x00;
  192. pkt[start + 1] = MQTT_CLIENTID_LEN;
  193. memcpy(&pkt[start + 2], client_id, MQTT_CLIENTID_LEN);
  194. return 0;
  195. }
  196. /* Set initial values of CONNECT packet */
  197. static int init_connpack(char *packet, char *remain, int remain_pos)
  198. {
  199. /* Fixed header starts */
  200. /* packet type */
  201. packet[0] = MQTT_MSG_CONNECT;
  202. /* remaining length field */
  203. memcpy(&packet[1], remain, remain_pos);
  204. /* Fixed header ends */
  205. /* Variable header starts */
  206. /* protocol length */
  207. packet[remain_pos + 1] = 0x00;
  208. packet[remain_pos + 2] = 0x04;
  209. /* protocol name */
  210. packet[remain_pos + 3] = 'M';
  211. packet[remain_pos + 4] = 'Q';
  212. packet[remain_pos + 5] = 'T';
  213. packet[remain_pos + 6] = 'T';
  214. /* protocol level */
  215. packet[remain_pos + 7] = 0x04;
  216. /* CONNECT flag: CleanSession */
  217. packet[remain_pos + 8] = 0x02;
  218. /* keep-alive 0 = disabled */
  219. packet[remain_pos + 9] = 0x00;
  220. packet[remain_pos + 10] = 0x3c;
  221. /* end of variable header */
  222. return remain_pos + 10;
  223. }
  224. static CURLcode mqtt_connect(struct Curl_easy *data)
  225. {
  226. CURLcode result = CURLE_OK;
  227. int pos = 0;
  228. int rc = 0;
  229. /* remain length */
  230. int remain_pos = 0;
  231. char remain[4] = {0};
  232. size_t packetlen = 0;
  233. size_t payloadlen = 0;
  234. size_t start_user = 0;
  235. size_t start_pwd = 0;
  236. char client_id[MQTT_CLIENTID_LEN + 1] = "curl";
  237. const size_t clen = strlen("curl");
  238. char *packet = NULL;
  239. /* extracting username from request */
  240. const char *username = data->state.aptr.user ?
  241. data->state.aptr.user : "";
  242. const size_t ulen = strlen(username);
  243. /* extracting password from request */
  244. const char *passwd = data->state.aptr.passwd ?
  245. data->state.aptr.passwd : "";
  246. const size_t plen = strlen(passwd);
  247. payloadlen = ulen + plen + MQTT_CLIENTID_LEN + 2;
  248. /* The plus 2 are for the MSB and LSB describing the length of the string to
  249. * be added on the payload. Refer to spec 1.5.2 and 1.5.4 */
  250. if(ulen)
  251. payloadlen += 2;
  252. if(plen)
  253. payloadlen += 2;
  254. /* getting how much occupy the remain length */
  255. remain_pos = mqtt_encode_len(remain, payloadlen + 10);
  256. /* 10 length of variable header and 1 the first byte of the fixed header */
  257. packetlen = payloadlen + 10 + remain_pos + 1;
  258. /* allocating packet */
  259. if(packetlen > 268435455)
  260. return CURLE_WEIRD_SERVER_REPLY;
  261. packet = malloc(packetlen);
  262. if(!packet)
  263. return CURLE_OUT_OF_MEMORY;
  264. memset(packet, 0, packetlen);
  265. /* set initial values for the CONNECT packet */
  266. pos = init_connpack(packet, remain, remain_pos);
  267. result = Curl_rand_alnum(data, (unsigned char *)&client_id[clen],
  268. MQTT_CLIENTID_LEN - clen + 1);
  269. /* add client id */
  270. rc = add_client_id(client_id, strlen(client_id), packet, pos + 1);
  271. if(rc) {
  272. failf(data, "Client ID length mismatched: [%zu]", strlen(client_id));
  273. result = CURLE_WEIRD_SERVER_REPLY;
  274. goto end;
  275. }
  276. infof(data, "Using client id '%s'", client_id);
  277. /* position where starts the user payload */
  278. start_user = pos + 3 + MQTT_CLIENTID_LEN;
  279. /* position where starts the password payload */
  280. start_pwd = start_user + ulen;
  281. /* if user name was provided, add it to the packet */
  282. if(ulen) {
  283. start_pwd += 2;
  284. rc = add_user(username, ulen,
  285. (unsigned char *)packet, start_user, remain_pos);
  286. if(rc) {
  287. failf(data, "Username is too large: [%zu]", ulen);
  288. result = CURLE_WEIRD_SERVER_REPLY;
  289. goto end;
  290. }
  291. }
  292. /* if passwd was provided, add it to the packet */
  293. if(plen) {
  294. rc = add_passwd(passwd, plen, packet, start_pwd, remain_pos);
  295. if(rc) {
  296. failf(data, "Password is too large: [%zu]", plen);
  297. result = CURLE_WEIRD_SERVER_REPLY;
  298. goto end;
  299. }
  300. }
  301. if(!result)
  302. result = mqtt_send(data, packet, packetlen);
  303. end:
  304. if(packet)
  305. free(packet);
  306. Curl_safefree(data->state.aptr.user);
  307. Curl_safefree(data->state.aptr.passwd);
  308. return result;
  309. }
  310. static CURLcode mqtt_disconnect(struct Curl_easy *data)
  311. {
  312. CURLcode result = CURLE_OK;
  313. struct MQTT *mq = data->req.p.mqtt;
  314. result = mqtt_send(data, (char *)"\xe0\x00", 2);
  315. Curl_safefree(mq->sendleftovers);
  316. Curl_dyn_free(&mq->recvbuf);
  317. return result;
  318. }
  319. static CURLcode mqtt_recv_atleast(struct Curl_easy *data, size_t nbytes)
  320. {
  321. struct MQTT *mq = data->req.p.mqtt;
  322. size_t rlen = Curl_dyn_len(&mq->recvbuf);
  323. CURLcode result;
  324. if(rlen < nbytes) {
  325. unsigned char readbuf[1024];
  326. ssize_t nread;
  327. DEBUGASSERT(nbytes - rlen < sizeof(readbuf));
  328. result = Curl_xfer_recv(data, (char *)readbuf, nbytes - rlen, &nread);
  329. if(result)
  330. return result;
  331. DEBUGASSERT(nread >= 0);
  332. if(Curl_dyn_addn(&mq->recvbuf, readbuf, (size_t)nread))
  333. return CURLE_OUT_OF_MEMORY;
  334. rlen = Curl_dyn_len(&mq->recvbuf);
  335. }
  336. return (rlen >= nbytes)? CURLE_OK : CURLE_AGAIN;
  337. }
  338. static void mqtt_recv_consume(struct Curl_easy *data, size_t nbytes)
  339. {
  340. struct MQTT *mq = data->req.p.mqtt;
  341. size_t rlen = Curl_dyn_len(&mq->recvbuf);
  342. if(rlen <= nbytes)
  343. Curl_dyn_reset(&mq->recvbuf);
  344. else
  345. Curl_dyn_tail(&mq->recvbuf, rlen - nbytes);
  346. }
  347. static CURLcode mqtt_verify_connack(struct Curl_easy *data)
  348. {
  349. struct MQTT *mq = data->req.p.mqtt;
  350. CURLcode result;
  351. char *ptr;
  352. result = mqtt_recv_atleast(data, MQTT_CONNACK_LEN);
  353. if(result)
  354. goto fail;
  355. /* verify CONNACK */
  356. DEBUGASSERT(Curl_dyn_len(&mq->recvbuf) >= MQTT_CONNACK_LEN);
  357. ptr = Curl_dyn_ptr(&mq->recvbuf);
  358. Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_CONNACK_LEN);
  359. if(ptr[0] != 0x00 || ptr[1] != 0x00) {
  360. failf(data, "Expected %02x%02x but got %02x%02x",
  361. 0x00, 0x00, ptr[0], ptr[1]);
  362. Curl_dyn_reset(&mq->recvbuf);
  363. result = CURLE_WEIRD_SERVER_REPLY;
  364. goto fail;
  365. }
  366. mqtt_recv_consume(data, MQTT_CONNACK_LEN);
  367. fail:
  368. return result;
  369. }
  370. static CURLcode mqtt_get_topic(struct Curl_easy *data,
  371. char **topic, size_t *topiclen)
  372. {
  373. char *path = data->state.up.path;
  374. CURLcode result = CURLE_URL_MALFORMAT;
  375. if(strlen(path) > 1) {
  376. result = Curl_urldecode(path + 1, 0, topic, topiclen, REJECT_NADA);
  377. if(!result && (*topiclen > 0xffff)) {
  378. failf(data, "Too long MQTT topic");
  379. result = CURLE_URL_MALFORMAT;
  380. }
  381. }
  382. else
  383. failf(data, "No MQTT topic found. Forgot to URL encode it?");
  384. return result;
  385. }
  386. static CURLcode mqtt_subscribe(struct Curl_easy *data)
  387. {
  388. CURLcode result = CURLE_OK;
  389. char *topic = NULL;
  390. size_t topiclen;
  391. unsigned char *packet = NULL;
  392. size_t packetlen;
  393. char encodedsize[4];
  394. size_t n;
  395. struct connectdata *conn = data->conn;
  396. result = mqtt_get_topic(data, &topic, &topiclen);
  397. if(result)
  398. goto fail;
  399. conn->proto.mqtt.packetid++;
  400. packetlen = topiclen + 5; /* packetid + topic (has a two byte length field)
  401. + 2 bytes topic length + QoS byte */
  402. n = mqtt_encode_len((char *)encodedsize, packetlen);
  403. packetlen += n + 1; /* add one for the control packet type byte */
  404. packet = malloc(packetlen);
  405. if(!packet) {
  406. result = CURLE_OUT_OF_MEMORY;
  407. goto fail;
  408. }
  409. packet[0] = MQTT_MSG_SUBSCRIBE;
  410. memcpy(&packet[1], encodedsize, n);
  411. packet[1 + n] = (conn->proto.mqtt.packetid >> 8) & 0xff;
  412. packet[2 + n] = conn->proto.mqtt.packetid & 0xff;
  413. packet[3 + n] = (topiclen >> 8) & 0xff;
  414. packet[4 + n ] = topiclen & 0xff;
  415. memcpy(&packet[5 + n], topic, topiclen);
  416. packet[5 + n + topiclen] = 0; /* QoS zero */
  417. result = mqtt_send(data, (char *)packet, packetlen);
  418. fail:
  419. free(topic);
  420. free(packet);
  421. return result;
  422. }
  423. /*
  424. * Called when the first byte was already read.
  425. */
  426. static CURLcode mqtt_verify_suback(struct Curl_easy *data)
  427. {
  428. struct MQTT *mq = data->req.p.mqtt;
  429. struct connectdata *conn = data->conn;
  430. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  431. CURLcode result;
  432. char *ptr;
  433. result = mqtt_recv_atleast(data, MQTT_SUBACK_LEN);
  434. if(result)
  435. goto fail;
  436. /* verify SUBACK */
  437. DEBUGASSERT(Curl_dyn_len(&mq->recvbuf) >= MQTT_SUBACK_LEN);
  438. ptr = Curl_dyn_ptr(&mq->recvbuf);
  439. Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_SUBACK_LEN);
  440. if(((unsigned char)ptr[0]) != ((mqtt->packetid >> 8) & 0xff) ||
  441. ((unsigned char)ptr[1]) != (mqtt->packetid & 0xff) ||
  442. ptr[2] != 0x00) {
  443. Curl_dyn_reset(&mq->recvbuf);
  444. result = CURLE_WEIRD_SERVER_REPLY;
  445. goto fail;
  446. }
  447. mqtt_recv_consume(data, MQTT_SUBACK_LEN);
  448. fail:
  449. return result;
  450. }
  451. static CURLcode mqtt_publish(struct Curl_easy *data)
  452. {
  453. CURLcode result;
  454. char *payload = data->set.postfields;
  455. size_t payloadlen;
  456. char *topic = NULL;
  457. size_t topiclen;
  458. unsigned char *pkt = NULL;
  459. size_t i = 0;
  460. size_t remaininglength;
  461. size_t encodelen;
  462. char encodedbytes[4];
  463. curl_off_t postfieldsize = data->set.postfieldsize;
  464. if(!payload) {
  465. DEBUGF(infof(data, "mqtt_publish without payload, return bad arg"));
  466. return CURLE_BAD_FUNCTION_ARGUMENT;
  467. }
  468. if(postfieldsize < 0)
  469. payloadlen = strlen(payload);
  470. else
  471. payloadlen = (size_t)postfieldsize;
  472. result = mqtt_get_topic(data, &topic, &topiclen);
  473. if(result)
  474. goto fail;
  475. remaininglength = payloadlen + 2 + topiclen;
  476. encodelen = mqtt_encode_len(encodedbytes, remaininglength);
  477. /* add the control byte and the encoded remaining length */
  478. pkt = malloc(remaininglength + 1 + encodelen);
  479. if(!pkt) {
  480. result = CURLE_OUT_OF_MEMORY;
  481. goto fail;
  482. }
  483. /* assemble packet */
  484. pkt[i++] = MQTT_MSG_PUBLISH;
  485. memcpy(&pkt[i], encodedbytes, encodelen);
  486. i += encodelen;
  487. pkt[i++] = (topiclen >> 8) & 0xff;
  488. pkt[i++] = (topiclen & 0xff);
  489. memcpy(&pkt[i], topic, topiclen);
  490. i += topiclen;
  491. memcpy(&pkt[i], payload, payloadlen);
  492. i += payloadlen;
  493. result = mqtt_send(data, (char *)pkt, i);
  494. fail:
  495. free(pkt);
  496. free(topic);
  497. return result;
  498. }
  499. static size_t mqtt_decode_len(unsigned char *buf,
  500. size_t buflen, size_t *lenbytes)
  501. {
  502. size_t len = 0;
  503. size_t mult = 1;
  504. size_t i;
  505. unsigned char encoded = 128;
  506. for(i = 0; (i < buflen) && (encoded & 128); i++) {
  507. encoded = buf[i];
  508. len += (encoded & 127) * mult;
  509. mult *= 128;
  510. }
  511. if(lenbytes)
  512. *lenbytes = i;
  513. return len;
  514. }
  515. #ifdef DEBUGBUILD
  516. static const char *statenames[]={
  517. "MQTT_FIRST",
  518. "MQTT_REMAINING_LENGTH",
  519. "MQTT_CONNACK",
  520. "MQTT_SUBACK",
  521. "MQTT_SUBACK_COMING",
  522. "MQTT_PUBWAIT",
  523. "MQTT_PUB_REMAIN",
  524. "NOT A STATE"
  525. };
  526. #endif
  527. /* The only way to change state */
  528. static void mqstate(struct Curl_easy *data,
  529. enum mqttstate state,
  530. enum mqttstate nextstate) /* used if state == FIRST */
  531. {
  532. struct connectdata *conn = data->conn;
  533. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  534. #ifdef DEBUGBUILD
  535. infof(data, "%s (from %s) (next is %s)",
  536. statenames[state],
  537. statenames[mqtt->state],
  538. (state == MQTT_FIRST)? statenames[nextstate] : "");
  539. #endif
  540. mqtt->state = state;
  541. if(state == MQTT_FIRST)
  542. mqtt->nextstate = nextstate;
  543. }
  544. static CURLcode mqtt_read_publish(struct Curl_easy *data, bool *done)
  545. {
  546. CURLcode result = CURLE_OK;
  547. struct connectdata *conn = data->conn;
  548. ssize_t nread;
  549. size_t remlen;
  550. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  551. struct MQTT *mq = data->req.p.mqtt;
  552. unsigned char packet;
  553. switch(mqtt->state) {
  554. MQTT_SUBACK_COMING:
  555. case MQTT_SUBACK_COMING:
  556. result = mqtt_verify_suback(data);
  557. if(result)
  558. break;
  559. mqstate(data, MQTT_FIRST, MQTT_PUBWAIT);
  560. break;
  561. case MQTT_SUBACK:
  562. case MQTT_PUBWAIT:
  563. /* we are expecting PUBLISH or SUBACK */
  564. packet = mq->firstbyte & 0xf0;
  565. if(packet == MQTT_MSG_PUBLISH)
  566. mqstate(data, MQTT_PUB_REMAIN, MQTT_NOSTATE);
  567. else if(packet == MQTT_MSG_SUBACK) {
  568. mqstate(data, MQTT_SUBACK_COMING, MQTT_NOSTATE);
  569. goto MQTT_SUBACK_COMING;
  570. }
  571. else if(packet == MQTT_MSG_DISCONNECT) {
  572. infof(data, "Got DISCONNECT");
  573. *done = TRUE;
  574. goto end;
  575. }
  576. else {
  577. result = CURLE_WEIRD_SERVER_REPLY;
  578. goto end;
  579. }
  580. /* -- switched state -- */
  581. remlen = mq->remaining_length;
  582. infof(data, "Remaining length: %zu bytes", remlen);
  583. if(data->set.max_filesize &&
  584. (curl_off_t)remlen > data->set.max_filesize) {
  585. failf(data, "Maximum file size exceeded");
  586. result = CURLE_FILESIZE_EXCEEDED;
  587. goto end;
  588. }
  589. Curl_pgrsSetDownloadSize(data, remlen);
  590. data->req.bytecount = 0;
  591. data->req.size = remlen;
  592. mq->npacket = remlen; /* get this many bytes */
  593. FALLTHROUGH();
  594. case MQTT_PUB_REMAIN: {
  595. /* read rest of packet, but no more. Cap to buffer size */
  596. char buffer[4*1024];
  597. size_t rest = mq->npacket;
  598. if(rest > sizeof(buffer))
  599. rest = sizeof(buffer);
  600. result = Curl_xfer_recv(data, buffer, rest, &nread);
  601. if(result) {
  602. if(CURLE_AGAIN == result) {
  603. infof(data, "EEEE AAAAGAIN");
  604. }
  605. goto end;
  606. }
  607. if(!nread) {
  608. infof(data, "server disconnected");
  609. result = CURLE_PARTIAL_FILE;
  610. goto end;
  611. }
  612. /* if QoS is set, message contains packet id */
  613. result = Curl_client_write(data, CLIENTWRITE_BODY, buffer, nread);
  614. if(result)
  615. goto end;
  616. mq->npacket -= nread;
  617. if(!mq->npacket)
  618. /* no more PUBLISH payload, back to subscribe wait state */
  619. mqstate(data, MQTT_FIRST, MQTT_PUBWAIT);
  620. break;
  621. }
  622. default:
  623. DEBUGASSERT(NULL); /* illegal state */
  624. result = CURLE_WEIRD_SERVER_REPLY;
  625. goto end;
  626. }
  627. end:
  628. return result;
  629. }
  630. static CURLcode mqtt_do(struct Curl_easy *data, bool *done)
  631. {
  632. CURLcode result = CURLE_OK;
  633. *done = FALSE; /* unconditionally */
  634. result = mqtt_connect(data);
  635. if(result) {
  636. failf(data, "Error %d sending MQTT CONNECT request", result);
  637. return result;
  638. }
  639. mqstate(data, MQTT_FIRST, MQTT_CONNACK);
  640. return CURLE_OK;
  641. }
  642. static CURLcode mqtt_done(struct Curl_easy *data,
  643. CURLcode status, bool premature)
  644. {
  645. struct MQTT *mq = data->req.p.mqtt;
  646. (void)status;
  647. (void)premature;
  648. Curl_safefree(mq->sendleftovers);
  649. Curl_dyn_free(&mq->recvbuf);
  650. return CURLE_OK;
  651. }
  652. static CURLcode mqtt_doing(struct Curl_easy *data, bool *done)
  653. {
  654. CURLcode result = CURLE_OK;
  655. struct connectdata *conn = data->conn;
  656. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  657. struct MQTT *mq = data->req.p.mqtt;
  658. ssize_t nread;
  659. unsigned char byte;
  660. *done = FALSE;
  661. if(mq->nsend) {
  662. /* send the remainder of an outgoing packet */
  663. char *ptr = mq->sendleftovers;
  664. result = mqtt_send(data, mq->sendleftovers, mq->nsend);
  665. free(ptr);
  666. if(result)
  667. return result;
  668. }
  669. infof(data, "mqtt_doing: state [%d]", (int) mqtt->state);
  670. switch(mqtt->state) {
  671. case MQTT_FIRST:
  672. /* Read the initial byte only */
  673. result = Curl_xfer_recv(data, (char *)&mq->firstbyte, 1, &nread);
  674. if(result)
  675. break;
  676. else if(!nread) {
  677. failf(data, "Connection disconnected");
  678. *done = TRUE;
  679. result = CURLE_RECV_ERROR;
  680. break;
  681. }
  682. Curl_debug(data, CURLINFO_HEADER_IN, (char *)&mq->firstbyte, 1);
  683. /* remember the first byte */
  684. mq->npacket = 0;
  685. mqstate(data, MQTT_REMAINING_LENGTH, MQTT_NOSTATE);
  686. FALLTHROUGH();
  687. case MQTT_REMAINING_LENGTH:
  688. do {
  689. result = Curl_xfer_recv(data, (char *)&byte, 1, &nread);
  690. if(result || !nread)
  691. break;
  692. Curl_debug(data, CURLINFO_HEADER_IN, (char *)&byte, 1);
  693. mq->pkt_hd[mq->npacket++] = byte;
  694. } while((byte & 0x80) && (mq->npacket < 4));
  695. if(!result && nread && (byte & 0x80))
  696. /* MQTT supports up to 127 * 128^0 + 127 * 128^1 + 127 * 128^2 +
  697. 127 * 128^3 bytes. server tried to send more */
  698. result = CURLE_WEIRD_SERVER_REPLY;
  699. if(result)
  700. break;
  701. mq->remaining_length = mqtt_decode_len(mq->pkt_hd, mq->npacket, NULL);
  702. mq->npacket = 0;
  703. if(mq->remaining_length) {
  704. mqstate(data, mqtt->nextstate, MQTT_NOSTATE);
  705. break;
  706. }
  707. mqstate(data, MQTT_FIRST, MQTT_FIRST);
  708. if(mq->firstbyte == MQTT_MSG_DISCONNECT) {
  709. infof(data, "Got DISCONNECT");
  710. *done = TRUE;
  711. }
  712. break;
  713. case MQTT_CONNACK:
  714. result = mqtt_verify_connack(data);
  715. if(result)
  716. break;
  717. if(data->state.httpreq == HTTPREQ_POST) {
  718. result = mqtt_publish(data);
  719. if(!result) {
  720. result = mqtt_disconnect(data);
  721. *done = TRUE;
  722. }
  723. mqtt->nextstate = MQTT_FIRST;
  724. }
  725. else {
  726. result = mqtt_subscribe(data);
  727. if(!result) {
  728. mqstate(data, MQTT_FIRST, MQTT_SUBACK);
  729. }
  730. }
  731. break;
  732. case MQTT_SUBACK:
  733. case MQTT_PUBWAIT:
  734. case MQTT_PUB_REMAIN:
  735. result = mqtt_read_publish(data, done);
  736. break;
  737. default:
  738. failf(data, "State not handled yet");
  739. *done = TRUE;
  740. break;
  741. }
  742. if(result == CURLE_AGAIN)
  743. result = CURLE_OK;
  744. return result;
  745. }
  746. #endif /* CURL_DISABLE_MQTT */