mqtt.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. * Copyright (C) 2019, 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. ***************************************************************************/
  23. #include "curl_setup.h"
  24. #ifndef CURL_DISABLE_MQTT
  25. #include "urldata.h"
  26. #include <curl/curl.h>
  27. #include "transfer.h"
  28. #include "sendf.h"
  29. #include "progress.h"
  30. #include "mqtt.h"
  31. #include "select.h"
  32. #include "strdup.h"
  33. #include "url.h"
  34. #include "escape.h"
  35. #include "warnless.h"
  36. #include "curl_printf.h"
  37. #include "curl_memory.h"
  38. #include "multiif.h"
  39. #include "rand.h"
  40. /* The last #include file should be: */
  41. #include "memdebug.h"
  42. #define MQTT_MSG_CONNECT 0x10
  43. #define MQTT_MSG_CONNACK 0x20
  44. #define MQTT_MSG_PUBLISH 0x30
  45. #define MQTT_MSG_SUBSCRIBE 0x82
  46. #define MQTT_MSG_SUBACK 0x90
  47. #define MQTT_MSG_DISCONNECT 0xe0
  48. #define MQTT_CONNACK_LEN 2
  49. #define MQTT_SUBACK_LEN 3
  50. #define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */
  51. /*
  52. * Forward declarations.
  53. */
  54. static CURLcode mqtt_do(struct connectdata *conn, bool *done);
  55. static CURLcode mqtt_doing(struct connectdata *conn, bool *done);
  56. static int mqtt_getsock(struct connectdata *conn, curl_socket_t *sock);
  57. static CURLcode mqtt_setup_conn(struct connectdata *conn);
  58. /*
  59. * MQTT protocol handler.
  60. */
  61. const struct Curl_handler Curl_handler_mqtt = {
  62. "MQTT", /* scheme */
  63. mqtt_setup_conn, /* setup_connection */
  64. mqtt_do, /* do_it */
  65. ZERO_NULL, /* done */
  66. ZERO_NULL, /* do_more */
  67. ZERO_NULL, /* connect_it */
  68. ZERO_NULL, /* connecting */
  69. mqtt_doing, /* doing */
  70. ZERO_NULL, /* proto_getsock */
  71. mqtt_getsock, /* doing_getsock */
  72. ZERO_NULL, /* domore_getsock */
  73. ZERO_NULL, /* perform_getsock */
  74. ZERO_NULL, /* disconnect */
  75. ZERO_NULL, /* readwrite */
  76. ZERO_NULL, /* connection_check */
  77. PORT_MQTT, /* defport */
  78. CURLPROTO_MQTT, /* protocol */
  79. CURLPROTO_MQTT, /* family */
  80. PROTOPT_NONE /* flags */
  81. };
  82. static CURLcode mqtt_setup_conn(struct connectdata *conn)
  83. {
  84. /* allocate the HTTP-specific struct for the Curl_easy, only to survive
  85. during this request */
  86. struct MQTT *mq;
  87. struct Curl_easy *data = conn->data;
  88. DEBUGASSERT(data->req.p.mqtt == NULL);
  89. mq = calloc(1, sizeof(struct MQTT));
  90. if(!mq)
  91. return CURLE_OUT_OF_MEMORY;
  92. data->req.p.mqtt = mq;
  93. return CURLE_OK;
  94. }
  95. static CURLcode mqtt_send(struct connectdata *conn,
  96. char *buf, size_t len)
  97. {
  98. CURLcode result = CURLE_OK;
  99. curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
  100. struct Curl_easy *data = conn->data;
  101. struct MQTT *mq = data->req.p.mqtt;
  102. ssize_t n;
  103. result = Curl_write(conn, sockfd, buf, len, &n);
  104. if(!result)
  105. Curl_debug(data, CURLINFO_HEADER_OUT, buf, (size_t)n);
  106. if(len != (size_t)n) {
  107. size_t nsend = len - n;
  108. char *sendleftovers = Curl_memdup(&buf[n], nsend);
  109. if(!sendleftovers)
  110. return CURLE_OUT_OF_MEMORY;
  111. mq->sendleftovers = sendleftovers;
  112. mq->nsend = nsend;
  113. }
  114. return result;
  115. }
  116. /* Generic function called by the multi interface to figure out what socket(s)
  117. to wait for and for what actions during the DOING and PROTOCONNECT
  118. states */
  119. static int mqtt_getsock(struct connectdata *conn,
  120. curl_socket_t *sock)
  121. {
  122. sock[0] = conn->sock[FIRSTSOCKET];
  123. return GETSOCK_READSOCK(FIRSTSOCKET);
  124. }
  125. static CURLcode mqtt_connect(struct connectdata *conn)
  126. {
  127. CURLcode result = CURLE_OK;
  128. const size_t client_id_offset = 14;
  129. const size_t packetlen = client_id_offset + MQTT_CLIENTID_LEN;
  130. char client_id[MQTT_CLIENTID_LEN + 1] = "curl";
  131. const size_t clen = strlen("curl");
  132. char packet[32] = {
  133. MQTT_MSG_CONNECT, /* packet type */
  134. 0x00, /* remaining length */
  135. 0x00, 0x04, /* protocol length */
  136. 'M','Q','T','T', /* protocol name */
  137. 0x04, /* protocol level */
  138. 0x02, /* CONNECT flag: CleanSession */
  139. 0x00, 0x3c, /* keep-alive 0 = disabled */
  140. 0x00, 0x00 /* payload1 length */
  141. };
  142. packet[1] = (packetlen - 2) & 0x7f;
  143. packet[client_id_offset - 1] = MQTT_CLIENTID_LEN;
  144. result = Curl_rand_hex(conn->data, (unsigned char *)&client_id[clen],
  145. MQTT_CLIENTID_LEN - clen + 1);
  146. memcpy(&packet[client_id_offset], client_id, MQTT_CLIENTID_LEN);
  147. infof(conn->data, "Using client id '%s'\n", client_id);
  148. if(!result)
  149. result = mqtt_send(conn, packet, packetlen);
  150. return result;
  151. }
  152. static CURLcode mqtt_disconnect(struct connectdata *conn)
  153. {
  154. CURLcode result = CURLE_OK;
  155. result = mqtt_send(conn, (char *)"\xe0\x00", 2);
  156. return result;
  157. }
  158. static CURLcode mqtt_verify_connack(struct connectdata *conn)
  159. {
  160. CURLcode result;
  161. curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
  162. unsigned char readbuf[MQTT_CONNACK_LEN];
  163. ssize_t nread;
  164. struct Curl_easy *data = conn->data;
  165. result = Curl_read(conn, sockfd, (char *)readbuf, MQTT_CONNACK_LEN, &nread);
  166. if(result)
  167. goto fail;
  168. Curl_debug(data, CURLINFO_HEADER_IN, (char *)readbuf, (size_t)nread);
  169. /* fixme */
  170. if(nread < MQTT_CONNACK_LEN) {
  171. result = CURLE_WEIRD_SERVER_REPLY;
  172. goto fail;
  173. }
  174. /* verify CONNACK */
  175. if(readbuf[0] != 0x00 || readbuf[1] != 0x00) {
  176. failf(data, "Expected %02x%02x but got %02x%02x",
  177. 0x00, 0x00, readbuf[0], readbuf[1]);
  178. result = CURLE_WEIRD_SERVER_REPLY;
  179. }
  180. fail:
  181. return result;
  182. }
  183. static CURLcode mqtt_get_topic(struct connectdata *conn,
  184. char **topic, size_t *topiclen)
  185. {
  186. CURLcode result = CURLE_OK;
  187. char *path = conn->data->state.up.path;
  188. if(strlen(path) > 1) {
  189. result = Curl_urldecode(conn->data, path + 1, 0, topic, topiclen,
  190. REJECT_NADA);
  191. }
  192. else {
  193. failf(conn->data, "Error: No topic specified.");
  194. result = CURLE_URL_MALFORMAT;
  195. }
  196. return result;
  197. }
  198. static int mqtt_encode_len(char *buf, size_t len)
  199. {
  200. unsigned char encoded;
  201. int i;
  202. for(i = 0; (len > 0) && (i<4); i++) {
  203. encoded = len % 0x80;
  204. len /= 0x80;
  205. if(len)
  206. encoded |= 0x80;
  207. buf[i] = encoded;
  208. }
  209. return i;
  210. }
  211. static CURLcode mqtt_subscribe(struct connectdata *conn)
  212. {
  213. CURLcode result = CURLE_OK;
  214. char *topic = NULL;
  215. size_t topiclen;
  216. unsigned char *packet = NULL;
  217. size_t packetlen;
  218. char encodedsize[4];
  219. size_t n;
  220. result = mqtt_get_topic(conn, &topic, &topiclen);
  221. if(result)
  222. goto fail;
  223. conn->proto.mqtt.packetid++;
  224. packetlen = topiclen + 5; /* packetid + topic (has a two byte length field)
  225. + 2 bytes topic length + QoS byte */
  226. n = mqtt_encode_len((char *)encodedsize, packetlen);
  227. packetlen += n + 1; /* add one for the control packet type byte */
  228. packet = malloc(packetlen);
  229. if(!packet) {
  230. result = CURLE_OUT_OF_MEMORY;
  231. goto fail;
  232. }
  233. packet[0] = MQTT_MSG_SUBSCRIBE;
  234. memcpy(&packet[1], encodedsize, n);
  235. packet[1 + n] = (conn->proto.mqtt.packetid >> 8) & 0xff;
  236. packet[2 + n] = conn->proto.mqtt.packetid & 0xff;
  237. packet[3 + n] = (topiclen >> 8) & 0xff;
  238. packet[4 + n ] = topiclen & 0xff;
  239. memcpy(&packet[5 + n], topic, topiclen);
  240. packet[5 + n + topiclen] = 0; /* QoS zero */
  241. result = mqtt_send(conn, (char *)packet, packetlen);
  242. fail:
  243. free(topic);
  244. free(packet);
  245. return result;
  246. }
  247. /*
  248. * Called when the first byte was already read.
  249. */
  250. static CURLcode mqtt_verify_suback(struct connectdata *conn)
  251. {
  252. CURLcode result;
  253. curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
  254. unsigned char readbuf[MQTT_SUBACK_LEN];
  255. ssize_t nread;
  256. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  257. result = Curl_read(conn, sockfd, (char *)readbuf, MQTT_SUBACK_LEN, &nread);
  258. if(result)
  259. goto fail;
  260. Curl_debug(conn->data, CURLINFO_HEADER_IN, (char *)readbuf, (size_t)nread);
  261. /* fixme */
  262. if(nread < MQTT_SUBACK_LEN) {
  263. result = CURLE_WEIRD_SERVER_REPLY;
  264. goto fail;
  265. }
  266. /* verify SUBACK */
  267. if(readbuf[0] != ((mqtt->packetid >> 8) & 0xff) ||
  268. readbuf[1] != (mqtt->packetid & 0xff) ||
  269. readbuf[2] != 0x00)
  270. result = CURLE_WEIRD_SERVER_REPLY;
  271. fail:
  272. return result;
  273. }
  274. static CURLcode mqtt_publish(struct connectdata *conn)
  275. {
  276. CURLcode result;
  277. char *payload = conn->data->set.postfields;
  278. size_t payloadlen = (size_t)conn->data->set.postfieldsize;
  279. char *topic = NULL;
  280. size_t topiclen;
  281. unsigned char *pkt = NULL;
  282. size_t i = 0;
  283. size_t remaininglength;
  284. size_t encodelen;
  285. char encodedbytes[4];
  286. result = mqtt_get_topic(conn, &topic, &topiclen);
  287. if(result)
  288. goto fail;
  289. remaininglength = payloadlen + 2 + topiclen;
  290. encodelen = mqtt_encode_len(encodedbytes, remaininglength);
  291. /* add the control byte and the encoded remaining length */
  292. pkt = malloc(remaininglength + 1 + encodelen);
  293. if(!pkt) {
  294. result = CURLE_OUT_OF_MEMORY;
  295. goto fail;
  296. }
  297. /* assemble packet */
  298. pkt[i++] = MQTT_MSG_PUBLISH;
  299. memcpy(&pkt[i], encodedbytes, encodelen);
  300. i += encodelen;
  301. pkt[i++] = (topiclen >> 8) & 0xff;
  302. pkt[i++] = (topiclen & 0xff);
  303. memcpy(&pkt[i], topic, topiclen);
  304. i += topiclen;
  305. memcpy(&pkt[i], payload, payloadlen);
  306. i += payloadlen;
  307. result = mqtt_send(conn, (char *)pkt, i);
  308. fail:
  309. free(pkt);
  310. free(topic);
  311. return result;
  312. }
  313. static size_t mqtt_decode_len(unsigned char *buf,
  314. size_t buflen, size_t *lenbytes)
  315. {
  316. size_t len = 0;
  317. size_t mult = 1;
  318. size_t i;
  319. unsigned char encoded = 128;
  320. for(i = 0; (i < buflen) && (encoded & 128); i++) {
  321. encoded = buf[i];
  322. len += (encoded & 127) * mult;
  323. mult *= 128;
  324. }
  325. if(lenbytes)
  326. *lenbytes = i;
  327. return len;
  328. }
  329. #ifdef CURLDEBUG
  330. static const char *statenames[]={
  331. "MQTT_FIRST",
  332. "MQTT_REMAINING_LENGTH",
  333. "MQTT_CONNACK",
  334. "MQTT_SUBACK",
  335. "MQTT_SUBACK_COMING",
  336. "MQTT_PUBWAIT",
  337. "MQTT_PUB_REMAIN",
  338. "NOT A STATE"
  339. };
  340. #endif
  341. /* The only way to change state */
  342. static void mqstate(struct connectdata *conn,
  343. enum mqttstate state,
  344. enum mqttstate nextstate) /* used if state == FIRST */
  345. {
  346. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  347. #ifdef CURLDEBUG
  348. infof(conn->data, "%s (from %s) (next is %s)\n",
  349. statenames[state],
  350. statenames[mqtt->state],
  351. (state == MQTT_FIRST)? statenames[nextstate] : "");
  352. #endif
  353. mqtt->state = state;
  354. if(state == MQTT_FIRST)
  355. mqtt->nextstate = nextstate;
  356. }
  357. /* for the publish packet */
  358. #define MQTT_HEADER_LEN 5 /* max 5 bytes */
  359. static CURLcode mqtt_read_publish(struct connectdata *conn,
  360. bool *done)
  361. {
  362. CURLcode result = CURLE_OK;
  363. curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
  364. ssize_t nread;
  365. struct Curl_easy *data = conn->data;
  366. unsigned char *pkt = (unsigned char *)data->state.buffer;
  367. size_t remlen;
  368. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  369. struct MQTT *mq = data->req.p.mqtt;
  370. unsigned char packet;
  371. switch(mqtt->state) {
  372. MQTT_SUBACK_COMING:
  373. case MQTT_SUBACK_COMING:
  374. result = mqtt_verify_suback(conn);
  375. if(result)
  376. break;
  377. mqstate(conn, MQTT_FIRST, MQTT_PUBWAIT);
  378. break;
  379. case MQTT_SUBACK:
  380. case MQTT_PUBWAIT:
  381. /* we are expecting PUBLISH or SUBACK */
  382. packet = mq->firstbyte & 0xf0;
  383. if(packet == MQTT_MSG_PUBLISH)
  384. mqstate(conn, MQTT_PUB_REMAIN, MQTT_NOSTATE);
  385. else if(packet == MQTT_MSG_SUBACK) {
  386. mqstate(conn, MQTT_SUBACK_COMING, MQTT_NOSTATE);
  387. goto MQTT_SUBACK_COMING;
  388. }
  389. else if(packet == MQTT_MSG_DISCONNECT) {
  390. infof(data, "Got DISCONNECT\n");
  391. *done = TRUE;
  392. goto end;
  393. }
  394. else {
  395. result = CURLE_WEIRD_SERVER_REPLY;
  396. goto end;
  397. }
  398. /* -- switched state -- */
  399. remlen = mq->remaining_length;
  400. infof(data, "Remaining length: %zd bytes\n", remlen);
  401. Curl_pgrsSetDownloadSize(data, remlen);
  402. data->req.bytecount = 0;
  403. data->req.size = remlen;
  404. mq->npacket = remlen; /* get this many bytes */
  405. /* FALLTHROUGH */
  406. case MQTT_PUB_REMAIN: {
  407. /* read rest of packet, but no more. Cap to buffer size */
  408. struct SingleRequest *k = &data->req;
  409. size_t rest = mq->npacket;
  410. if(rest > (size_t)data->set.buffer_size)
  411. rest = (size_t)data->set.buffer_size;
  412. result = Curl_read(conn, sockfd, (char *)pkt, rest, &nread);
  413. if(result) {
  414. if(CURLE_AGAIN == result) {
  415. infof(data, "EEEE AAAAGAIN\n");
  416. }
  417. goto end;
  418. }
  419. if(!nread) {
  420. infof(data, "server disconnected\n");
  421. result = CURLE_PARTIAL_FILE;
  422. goto end;
  423. }
  424. Curl_debug(data, CURLINFO_DATA_IN, (char *)pkt, (size_t)nread);
  425. mq->npacket -= nread;
  426. k->bytecount += nread;
  427. Curl_pgrsSetDownloadCounter(data, k->bytecount);
  428. /* if QoS is set, message contains packet id */
  429. result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)pkt, nread);
  430. if(result)
  431. goto end;
  432. if(!mq->npacket)
  433. /* no more PUBLISH payload, back to subscribe wait state */
  434. mqstate(conn, MQTT_FIRST, MQTT_PUBWAIT);
  435. break;
  436. }
  437. default:
  438. DEBUGASSERT(NULL); /* illegal state */
  439. result = CURLE_WEIRD_SERVER_REPLY;
  440. goto end;
  441. }
  442. end:
  443. return result;
  444. }
  445. static CURLcode mqtt_do(struct connectdata *conn, bool *done)
  446. {
  447. CURLcode result = CURLE_OK;
  448. struct Curl_easy *data = conn->data;
  449. *done = FALSE; /* unconditionally */
  450. result = mqtt_connect(conn);
  451. if(result) {
  452. failf(data, "Error %d sending MQTT CONN request", result);
  453. return result;
  454. }
  455. mqstate(conn, MQTT_FIRST, MQTT_CONNACK);
  456. return CURLE_OK;
  457. }
  458. static CURLcode mqtt_doing(struct connectdata *conn, bool *done)
  459. {
  460. CURLcode result = CURLE_OK;
  461. struct mqtt_conn *mqtt = &conn->proto.mqtt;
  462. struct Curl_easy *data = conn->data;
  463. struct MQTT *mq = data->req.p.mqtt;
  464. ssize_t nread;
  465. curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
  466. unsigned char *pkt = (unsigned char *)data->state.buffer;
  467. unsigned char byte;
  468. *done = FALSE;
  469. if(mq->nsend) {
  470. /* send the remainder of an outgoing packet */
  471. char *ptr = mq->sendleftovers;
  472. result = mqtt_send(conn, mq->sendleftovers, mq->nsend);
  473. free(ptr);
  474. if(result)
  475. return result;
  476. }
  477. infof(data, "mqtt_doing: state [%d]\n", (int) mqtt->state);
  478. switch(mqtt->state) {
  479. case MQTT_FIRST:
  480. /* Read the initial byte only */
  481. result = Curl_read(conn, sockfd, (char *)&mq->firstbyte, 1, &nread);
  482. if(result)
  483. break;
  484. Curl_debug(data, CURLINFO_HEADER_IN, (char *)&mq->firstbyte, 1);
  485. /* remember the first byte */
  486. mq->npacket = 0;
  487. mqstate(conn, MQTT_REMAINING_LENGTH, MQTT_NOSTATE);
  488. /* FALLTHROUGH */
  489. case MQTT_REMAINING_LENGTH:
  490. do {
  491. result = Curl_read(conn, sockfd, (char *)&byte, 1, &nread);
  492. if(result)
  493. break;
  494. Curl_debug(data, CURLINFO_HEADER_IN, (char *)&byte, 1);
  495. pkt[mq->npacket++] = byte;
  496. } while((byte & 0x80) && (mq->npacket < 4));
  497. if(result)
  498. break;
  499. mq->remaining_length = mqtt_decode_len(&pkt[0], mq->npacket, NULL);
  500. mq->npacket = 0;
  501. if(mq->remaining_length) {
  502. mqstate(conn, mqtt->nextstate, MQTT_NOSTATE);
  503. break;
  504. }
  505. mqstate(conn, MQTT_FIRST, MQTT_FIRST);
  506. if(mq->firstbyte == MQTT_MSG_DISCONNECT) {
  507. infof(data, "Got DISCONNECT\n");
  508. *done = TRUE;
  509. }
  510. break;
  511. case MQTT_CONNACK:
  512. result = mqtt_verify_connack(conn);
  513. if(result)
  514. break;
  515. if(conn->data->state.httpreq == HTTPREQ_POST) {
  516. result = mqtt_publish(conn);
  517. if(!result) {
  518. result = mqtt_disconnect(conn);
  519. *done = TRUE;
  520. }
  521. mqtt->nextstate = MQTT_FIRST;
  522. }
  523. else {
  524. result = mqtt_subscribe(conn);
  525. if(!result) {
  526. mqstate(conn, MQTT_FIRST, MQTT_SUBACK);
  527. }
  528. }
  529. break;
  530. case MQTT_SUBACK:
  531. case MQTT_PUBWAIT:
  532. case MQTT_PUB_REMAIN:
  533. result = mqtt_read_publish(conn, done);
  534. break;
  535. default:
  536. failf(conn->data, "State not handled yet");
  537. *done = TRUE;
  538. break;
  539. }
  540. if(result == CURLE_AGAIN)
  541. result = CURLE_OK;
  542. return result;
  543. }
  544. #endif /* CURL_DISABLE_MQTT */