mqtt.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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, /* readwrite */
  82. ZERO_NULL, /* connection_check */
  83. ZERO_NULL, /* attach connection */
  84. PORT_MQTT, /* defport */
  85. CURLPROTO_MQTT, /* protocol */
  86. CURLPROTO_MQTT, /* family */
  87. PROTOPT_NONE /* flags */
  88. };
  89. static CURLcode mqtt_setup_conn(struct Curl_easy *data,
  90. struct connectdata *conn)
  91. {
  92. /* allocate the HTTP-specific struct for the Curl_easy, only to survive
  93. during this request */
  94. struct MQTT *mq;
  95. (void)conn;
  96. DEBUGASSERT(data->req.p.mqtt == NULL);
  97. mq = calloc(1, sizeof(struct MQTT));
  98. if(!mq)
  99. return CURLE_OUT_OF_MEMORY;
  100. Curl_dyn_init(&mq->recvbuf, DYN_MQTT_RECV);
  101. data->req.p.mqtt = mq;
  102. return CURLE_OK;
  103. }
  104. static CURLcode mqtt_send(struct Curl_easy *data,
  105. char *buf, size_t len)
  106. {
  107. CURLcode result = CURLE_OK;
  108. struct MQTT *mq = data->req.p.mqtt;
  109. ssize_t n;
  110. result = Curl_nwrite(data, FIRSTSOCKET, buf, len, &n);
  111. if(result)
  112. return result;
  113. Curl_debug(data, CURLINFO_HEADER_OUT, buf, (size_t)n);
  114. if(len != (size_t)n) {
  115. size_t nsend = len - n;
  116. char *sendleftovers = Curl_memdup(&buf[n], nsend);
  117. if(!sendleftovers)
  118. return CURLE_OUT_OF_MEMORY;
  119. mq->sendleftovers = sendleftovers;
  120. mq->nsend = nsend;
  121. }
  122. else {
  123. mq->sendleftovers = NULL;
  124. mq->nsend = 0;
  125. }
  126. return result;
  127. }
  128. /* Generic function called by the multi interface to figure out what socket(s)
  129. to wait for and for what actions during the DOING and PROTOCONNECT
  130. states */
  131. static int mqtt_getsock(struct Curl_easy *data,
  132. struct connectdata *conn,
  133. curl_socket_t *sock)
  134. {
  135. (void)data;
  136. sock[0] = conn->sock[FIRSTSOCKET];
  137. return GETSOCK_READSOCK(FIRSTSOCKET);
  138. }
  139. static int mqtt_encode_len(char *buf, size_t len)
  140. {
  141. unsigned char encoded;
  142. int i;
  143. for(i = 0; (len > 0) && (i<4); i++) {
  144. encoded = len % 0x80;
  145. len /= 0x80;
  146. if(len)
  147. encoded |= 0x80;
  148. buf[i] = encoded;
  149. }
  150. return i;
  151. }
  152. /* add the passwd to the CONNECT packet */
  153. static int add_passwd(const char *passwd, const size_t plen,
  154. char *pkt, const size_t start, int remain_pos)
  155. {
  156. /* magic number that need to be set properly */
  157. const size_t conn_flags_pos = remain_pos + 8;
  158. if(plen > 0xffff)
  159. return 1;
  160. /* set password flag */
  161. pkt[conn_flags_pos] |= 0x40;
  162. /* length of password provided */
  163. pkt[start] = (char)((plen >> 8) & 0xFF);
  164. pkt[start + 1] = (char)(plen & 0xFF);
  165. memcpy(&pkt[start + 2], passwd, plen);
  166. return 0;
  167. }
  168. /* add user to the CONNECT packet */
  169. static int add_user(const char *username, const size_t ulen,
  170. unsigned char *pkt, const size_t start, int remain_pos)
  171. {
  172. /* magic number that need to be set properly */
  173. const size_t conn_flags_pos = remain_pos + 8;
  174. if(ulen > 0xffff)
  175. return 1;
  176. /* set username flag */
  177. pkt[conn_flags_pos] |= 0x80;
  178. /* length of username provided */
  179. pkt[start] = (unsigned char)((ulen >> 8) & 0xFF);
  180. pkt[start + 1] = (unsigned char)(ulen & 0xFF);
  181. memcpy(&pkt[start + 2], username, ulen);
  182. return 0;
  183. }
  184. /* add client ID to the CONNECT packet */
  185. static int add_client_id(const char *client_id, const size_t client_id_len,
  186. char *pkt, const size_t start)
  187. {
  188. if(client_id_len != MQTT_CLIENTID_LEN)
  189. return 1;
  190. pkt[start] = 0x00;
  191. pkt[start + 1] = MQTT_CLIENTID_LEN;
  192. memcpy(&pkt[start + 2], client_id, MQTT_CLIENTID_LEN);
  193. return 0;
  194. }
  195. /* Set initial values of CONNECT packet */
  196. static int init_connpack(char *packet, char *remain, int remain_pos)
  197. {
  198. /* Fixed header starts */
  199. /* packet type */
  200. packet[0] = MQTT_MSG_CONNECT;
  201. /* remaining length field */
  202. memcpy(&packet[1], remain, remain_pos);
  203. /* Fixed header ends */
  204. /* Variable header starts */
  205. /* protocol length */
  206. packet[remain_pos + 1] = 0x00;
  207. packet[remain_pos + 2] = 0x04;
  208. /* protocol name */
  209. packet[remain_pos + 3] = 'M';
  210. packet[remain_pos + 4] = 'Q';
  211. packet[remain_pos + 5] = 'T';
  212. packet[remain_pos + 6] = 'T';
  213. /* protocol level */
  214. packet[remain_pos + 7] = 0x04;
  215. /* CONNECT flag: CleanSession */
  216. packet[remain_pos + 8] = 0x02;
  217. /* keep-alive 0 = disabled */
  218. packet[remain_pos + 9] = 0x00;
  219. packet[remain_pos + 10] = 0x3c;
  220. /* end of variable header */
  221. return remain_pos + 10;
  222. }
  223. static CURLcode mqtt_connect(struct Curl_easy *data)
  224. {
  225. CURLcode result = CURLE_OK;
  226. int pos = 0;
  227. int rc = 0;
  228. /* remain length */
  229. int remain_pos = 0;
  230. char remain[4] = {0};
  231. size_t packetlen = 0;
  232. size_t payloadlen = 0;
  233. size_t start_user = 0;
  234. size_t start_pwd = 0;
  235. char client_id[MQTT_CLIENTID_LEN + 1] = "curl";
  236. const size_t clen = strlen("curl");
  237. char *packet = NULL;
  238. /* extracting username from request */
  239. const char *username = data->state.aptr.user ?
  240. data->state.aptr.user : "";
  241. const size_t ulen = strlen(username);
  242. /* extracting password from request */
  243. const char *passwd = data->state.aptr.passwd ?
  244. data->state.aptr.passwd : "";
  245. const size_t plen = strlen(passwd);
  246. payloadlen = ulen + plen + MQTT_CLIENTID_LEN + 2;
  247. /* The plus 2 are for the MSB and LSB describing the length of the string to
  248. * be added on the payload. Refer to spec 1.5.2 and 1.5.4 */
  249. if(ulen)
  250. payloadlen += 2;
  251. if(plen)
  252. payloadlen += 2;
  253. /* getting how much occupy the remain length */
  254. remain_pos = mqtt_encode_len(remain, payloadlen + 10);
  255. /* 10 length of variable header and 1 the first byte of the fixed header */
  256. packetlen = payloadlen + 10 + remain_pos + 1;
  257. /* allocating packet */
  258. if(packetlen > 268435455)
  259. return CURLE_WEIRD_SERVER_REPLY;
  260. packet = malloc(packetlen);
  261. if(!packet)
  262. return CURLE_OUT_OF_MEMORY;
  263. memset(packet, 0, packetlen);
  264. /* set initial values for the CONNECT packet */
  265. pos = init_connpack(packet, remain, remain_pos);
  266. result = Curl_rand_alnum(data, (unsigned char *)&client_id[clen],
  267. MQTT_CLIENTID_LEN - clen + 1);
  268. /* add client id */
  269. rc = add_client_id(client_id, strlen(client_id), packet, pos + 1);
  270. if(rc) {
  271. failf(data, "Client ID length mismatched: [%zu]", strlen(client_id));
  272. result = CURLE_WEIRD_SERVER_REPLY;
  273. goto end;
  274. }
  275. infof(data, "Using client id '%s'", client_id);
  276. /* position where starts the user payload */
  277. start_user = pos + 3 + MQTT_CLIENTID_LEN;
  278. /* position where starts the password payload */
  279. start_pwd = start_user + ulen;
  280. /* if user name was provided, add it to the packet */
  281. if(ulen) {
  282. start_pwd += 2;
  283. rc = add_user(username, ulen,
  284. (unsigned char *)packet, start_user, remain_pos);
  285. if(rc) {
  286. failf(data, "Username is too large: [%zu]", ulen);
  287. result = CURLE_WEIRD_SERVER_REPLY;
  288. goto end;
  289. }
  290. }
  291. /* if passwd was provided, add it to the packet */
  292. if(plen) {
  293. rc = add_passwd(passwd, plen, packet, start_pwd, remain_pos);
  294. if(rc) {
  295. failf(data, "Password is too large: [%zu]", plen);
  296. result = CURLE_WEIRD_SERVER_REPLY;
  297. goto end;
  298. }
  299. }
  300. if(!result)
  301. result = mqtt_send(data, packet, packetlen);
  302. end:
  303. if(packet)
  304. free(packet);
  305. Curl_safefree(data->state.aptr.user);
  306. Curl_safefree(data->state.aptr.passwd);
  307. return result;
  308. }
  309. static CURLcode mqtt_disconnect(struct Curl_easy *data)
  310. {
  311. CURLcode result = CURLE_OK;
  312. struct MQTT *mq = data->req.p.mqtt;
  313. result = mqtt_send(data, (char *)"\xe0\x00", 2);
  314. Curl_safefree(mq->sendleftovers);
  315. Curl_dyn_free(&mq->recvbuf);
  316. return result;
  317. }
  318. static CURLcode mqtt_recv_atleast(struct Curl_easy *data, size_t nbytes)
  319. {
  320. struct MQTT *mq = data->req.p.mqtt;
  321. size_t rlen = Curl_dyn_len(&mq->recvbuf);
  322. CURLcode result;
  323. if(rlen < nbytes) {
  324. unsigned char readbuf[1024];
  325. ssize_t nread;
  326. DEBUGASSERT(nbytes - rlen < sizeof(readbuf));
  327. result = Curl_read(data, data->conn->sock[FIRSTSOCKET],
  328. (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. return CURLE_BAD_FUNCTION_ARGUMENT;
  466. if(postfieldsize < 0)
  467. payloadlen = strlen(payload);
  468. else
  469. payloadlen = (size_t)postfieldsize;
  470. result = mqtt_get_topic(data, &topic, &topiclen);
  471. if(result)
  472. goto fail;
  473. remaininglength = payloadlen + 2 + topiclen;
  474. encodelen = mqtt_encode_len(encodedbytes, remaininglength);
  475. /* add the control byte and the encoded remaining length */
  476. pkt = malloc(remaininglength + 1 + encodelen);
  477. if(!pkt) {
  478. result = CURLE_OUT_OF_MEMORY;
  479. goto fail;
  480. }
  481. /* assemble packet */
  482. pkt[i++] = MQTT_MSG_PUBLISH;
  483. memcpy(&pkt[i], encodedbytes, encodelen);
  484. i += encodelen;
  485. pkt[i++] = (topiclen >> 8) & 0xff;
  486. pkt[i++] = (topiclen & 0xff);
  487. memcpy(&pkt[i], topic, topiclen);
  488. i += topiclen;
  489. memcpy(&pkt[i], payload, payloadlen);
  490. i += payloadlen;
  491. result = mqtt_send(data, (char *)pkt, i);
  492. fail:
  493. free(pkt);
  494. free(topic);
  495. return result;
  496. }
  497. static size_t mqtt_decode_len(unsigned char *buf,
  498. size_t buflen, size_t *lenbytes)
  499. {
  500. size_t len = 0;
  501. size_t mult = 1;
  502. size_t i;
  503. unsigned char encoded = 128;
  504. for(i = 0; (i < buflen) && (encoded & 128); i++) {
  505. encoded = buf[i];
  506. len += (encoded & 127) * mult;
  507. mult *= 128;
  508. }
  509. if(lenbytes)
  510. *lenbytes = i;
  511. return len;
  512. }
  513. #ifdef CURLDEBUG
  514. static const char *statenames[]={
  515. "MQTT_FIRST",
  516. "MQTT_REMAINING_LENGTH",
  517. "MQTT_CONNACK",
  518. "MQTT_SUBACK",
  519. "MQTT_SUBACK_COMING",
  520. "MQTT_PUBWAIT",
  521. "MQTT_PUB_REMAIN",
  522. "NOT A STATE"
  523. };
  524. #endif
  525. /* The only way to change state */
  526. static void mqstate(struct Curl_easy *data,
  527. enum mqttstate state,
  528. enum mqttstate nextstate) /* used if state == FIRST */
  529. {
  530. struct connectdata *conn = data->conn;
  531. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  532. #ifdef CURLDEBUG
  533. infof(data, "%s (from %s) (next is %s)",
  534. statenames[state],
  535. statenames[mqtt->state],
  536. (state == MQTT_FIRST)? statenames[nextstate] : "");
  537. #endif
  538. mqtt->state = state;
  539. if(state == MQTT_FIRST)
  540. mqtt->nextstate = nextstate;
  541. }
  542. static CURLcode mqtt_read_publish(struct Curl_easy *data, bool *done)
  543. {
  544. CURLcode result = CURLE_OK;
  545. struct connectdata *conn = data->conn;
  546. curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
  547. ssize_t nread;
  548. unsigned char *pkt = (unsigned char *)data->state.buffer;
  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. size_t rest = mq->npacket;
  597. if(rest > (size_t)data->set.buffer_size)
  598. rest = (size_t)data->set.buffer_size;
  599. result = Curl_read(data, sockfd, (char *)pkt, rest, &nread);
  600. if(result) {
  601. if(CURLE_AGAIN == result) {
  602. infof(data, "EEEE AAAAGAIN");
  603. }
  604. goto end;
  605. }
  606. if(!nread) {
  607. infof(data, "server disconnected");
  608. result = CURLE_PARTIAL_FILE;
  609. goto end;
  610. }
  611. mq->npacket -= nread;
  612. /* if QoS is set, message contains packet id */
  613. result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)pkt, nread);
  614. if(result)
  615. goto end;
  616. if(!mq->npacket)
  617. /* no more PUBLISH payload, back to subscribe wait state */
  618. mqstate(data, MQTT_FIRST, MQTT_PUBWAIT);
  619. break;
  620. }
  621. default:
  622. DEBUGASSERT(NULL); /* illegal state */
  623. result = CURLE_WEIRD_SERVER_REPLY;
  624. goto end;
  625. }
  626. end:
  627. return result;
  628. }
  629. static CURLcode mqtt_do(struct Curl_easy *data, bool *done)
  630. {
  631. CURLcode result = CURLE_OK;
  632. *done = FALSE; /* unconditionally */
  633. result = mqtt_connect(data);
  634. if(result) {
  635. failf(data, "Error %d sending MQTT CONNECT request", result);
  636. return result;
  637. }
  638. mqstate(data, MQTT_FIRST, MQTT_CONNACK);
  639. return CURLE_OK;
  640. }
  641. static CURLcode mqtt_done(struct Curl_easy *data,
  642. CURLcode status, bool premature)
  643. {
  644. struct MQTT *mq = data->req.p.mqtt;
  645. (void)status;
  646. (void)premature;
  647. Curl_safefree(mq->sendleftovers);
  648. Curl_dyn_free(&mq->recvbuf);
  649. return CURLE_OK;
  650. }
  651. static CURLcode mqtt_doing(struct Curl_easy *data, bool *done)
  652. {
  653. CURLcode result = CURLE_OK;
  654. struct connectdata *conn = data->conn;
  655. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  656. struct MQTT *mq = data->req.p.mqtt;
  657. ssize_t nread;
  658. curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
  659. unsigned char *pkt = (unsigned char *)data->state.buffer;
  660. unsigned char byte;
  661. *done = FALSE;
  662. if(mq->nsend) {
  663. /* send the remainder of an outgoing packet */
  664. char *ptr = mq->sendleftovers;
  665. result = mqtt_send(data, mq->sendleftovers, mq->nsend);
  666. free(ptr);
  667. if(result)
  668. return result;
  669. }
  670. infof(data, "mqtt_doing: state [%d]", (int) mqtt->state);
  671. switch(mqtt->state) {
  672. case MQTT_FIRST:
  673. /* Read the initial byte only */
  674. result = Curl_read(data, sockfd, (char *)&mq->firstbyte, 1, &nread);
  675. if(result)
  676. break;
  677. else if(!nread) {
  678. failf(data, "Connection disconnected");
  679. *done = TRUE;
  680. result = CURLE_RECV_ERROR;
  681. break;
  682. }
  683. Curl_debug(data, CURLINFO_HEADER_IN, (char *)&mq->firstbyte, 1);
  684. /* remember the first byte */
  685. mq->npacket = 0;
  686. mqstate(data, MQTT_REMAINING_LENGTH, MQTT_NOSTATE);
  687. FALLTHROUGH();
  688. case MQTT_REMAINING_LENGTH:
  689. do {
  690. result = Curl_read(data, sockfd, (char *)&byte, 1, &nread);
  691. if(!nread)
  692. break;
  693. Curl_debug(data, CURLINFO_HEADER_IN, (char *)&byte, 1);
  694. pkt[mq->npacket++] = byte;
  695. } while((byte & 0x80) && (mq->npacket < 4));
  696. if(nread && (byte & 0x80))
  697. /* MQTT supports up to 127 * 128^0 + 127 * 128^1 + 127 * 128^2 +
  698. 127 * 128^3 bytes. server tried to send more */
  699. result = CURLE_WEIRD_SERVER_REPLY;
  700. if(result)
  701. break;
  702. mq->remaining_length = mqtt_decode_len(&pkt[0], mq->npacket, NULL);
  703. mq->npacket = 0;
  704. if(mq->remaining_length) {
  705. mqstate(data, mqtt->nextstate, MQTT_NOSTATE);
  706. break;
  707. }
  708. mqstate(data, MQTT_FIRST, MQTT_FIRST);
  709. if(mq->firstbyte == MQTT_MSG_DISCONNECT) {
  710. infof(data, "Got DISCONNECT");
  711. *done = TRUE;
  712. }
  713. break;
  714. case MQTT_CONNACK:
  715. result = mqtt_verify_connack(data);
  716. if(result)
  717. break;
  718. if(data->state.httpreq == HTTPREQ_POST) {
  719. result = mqtt_publish(data);
  720. if(!result) {
  721. result = mqtt_disconnect(data);
  722. *done = TRUE;
  723. }
  724. mqtt->nextstate = MQTT_FIRST;
  725. }
  726. else {
  727. result = mqtt_subscribe(data);
  728. if(!result) {
  729. mqstate(data, MQTT_FIRST, MQTT_SUBACK);
  730. }
  731. }
  732. break;
  733. case MQTT_SUBACK:
  734. case MQTT_PUBWAIT:
  735. case MQTT_PUB_REMAIN:
  736. result = mqtt_read_publish(data, done);
  737. break;
  738. default:
  739. failf(data, "State not handled yet");
  740. *done = TRUE;
  741. break;
  742. }
  743. if(result == CURLE_AGAIN)
  744. result = CURLE_OK;
  745. return result;
  746. }
  747. #endif /* CURL_DISABLE_MQTT */