MQTTPacket.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2019 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Ian Craggs - initial API and implementation and/or initial documentation
  15. * Ian Craggs, Allan Stockdill-Mander - SSL updates
  16. * Ian Craggs - MQTT 3.1.1 support
  17. * Ian Craggs - fix for issue 453
  18. * Ian Craggs - MQTT 5.0 support
  19. *******************************************************************************/
  20. /**
  21. * @file
  22. * \brief functions to deal with reading and writing of MQTT packets from and to sockets
  23. *
  24. * Some other related functions are in the MQTTPacketOut module
  25. */
  26. #include "MQTTPacket.h"
  27. #include "Log.h"
  28. #if !defined(NO_PERSISTENCE)
  29. #include "MQTTPersistence.h"
  30. #endif
  31. #include "Messages.h"
  32. #include "StackTrace.h"
  33. #include "WebSocket.h"
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include "Heap.h"
  37. #if !defined(min)
  38. #define min(A,B) ( (A) < (B) ? (A):(B))
  39. #endif
  40. /**
  41. * List of the predefined MQTT v3/v5 packet names.
  42. */
  43. static const char *packet_names[] =
  44. {
  45. "RESERVED", "CONNECT", "CONNACK", "PUBLISH", "PUBACK", "PUBREC", "PUBREL",
  46. "PUBCOMP", "SUBSCRIBE", "SUBACK", "UNSUBSCRIBE", "UNSUBACK",
  47. "PINGREQ", "PINGRESP", "DISCONNECT", "AUTH"
  48. };
  49. const char** MQTTClient_packet_names = packet_names;
  50. /**
  51. * Converts an MQTT packet code into its name
  52. * @param ptype packet code
  53. * @return the corresponding string, or "UNKNOWN"
  54. */
  55. const char* MQTTPacket_name(int ptype)
  56. {
  57. return (ptype >= 0 && ptype <= AUTH) ? packet_names[ptype] : "UNKNOWN";
  58. }
  59. /**
  60. * Array of functions to build packets, indexed according to packet code
  61. */
  62. pf new_packets[] =
  63. {
  64. NULL, /**< reserved */
  65. NULL, /**< MQTTPacket_connect*/
  66. MQTTPacket_connack, /**< CONNACK */
  67. MQTTPacket_publish, /**< PUBLISH */
  68. MQTTPacket_ack, /**< PUBACK */
  69. MQTTPacket_ack, /**< PUBREC */
  70. MQTTPacket_ack, /**< PUBREL */
  71. MQTTPacket_ack, /**< PUBCOMP */
  72. NULL, /**< MQTTPacket_subscribe*/
  73. MQTTPacket_suback, /**< SUBACK */
  74. NULL, /**< MQTTPacket_unsubscribe*/
  75. MQTTPacket_unsuback, /**< UNSUBACK */
  76. MQTTPacket_header_only, /**< PINGREQ */
  77. MQTTPacket_header_only, /**< PINGRESP */
  78. MQTTPacket_ack, /**< DISCONNECT */
  79. MQTTPacket_ack /**< AUTH */
  80. };
  81. static char* readUTFlen(char** pptr, char* enddata, int* len);
  82. static int MQTTPacket_send_ack(int MQTTVersion, int type, int msgid, int dup, networkHandles *net);
  83. /**
  84. * Reads one MQTT packet from a socket.
  85. * @param socket a socket from which to read an MQTT packet
  86. * @param error pointer to the error code which is completed if no packet is returned
  87. * @return the packet structure or NULL if there was an error
  88. */
  89. void* MQTTPacket_Factory(int MQTTVersion, networkHandles* net, int* error)
  90. {
  91. char* data = NULL;
  92. static Header header;
  93. size_t remaining_length;
  94. int ptype;
  95. void* pack = NULL;
  96. size_t actual_len = 0;
  97. FUNC_ENTRY;
  98. *error = SOCKET_ERROR; /* indicate whether an error occurred, or not */
  99. /* read the packet data from the socket */
  100. *error = WebSocket_getch(net, &header.byte);
  101. if (*error != TCPSOCKET_COMPLETE) /* first byte is the header byte */
  102. goto exit; /* packet not read, *error indicates whether SOCKET_ERROR occurred */
  103. /* now read the remaining length, so we know how much more to read */
  104. if ((*error = MQTTPacket_decode(net, &remaining_length)) != TCPSOCKET_COMPLETE)
  105. goto exit; /* packet not read, *error indicates whether SOCKET_ERROR occurred */
  106. /* now read the rest, the variable header and payload */
  107. data = WebSocket_getdata(net, remaining_length, &actual_len);
  108. if (data == NULL)
  109. {
  110. *error = SOCKET_ERROR;
  111. goto exit; /* socket error */
  112. }
  113. if (actual_len != remaining_length)
  114. *error = TCPSOCKET_INTERRUPTED;
  115. else
  116. {
  117. ptype = header.bits.type;
  118. if (ptype < CONNECT || (MQTTVersion < MQTTVERSION_5 && ptype >= DISCONNECT) ||
  119. (MQTTVersion >= MQTTVERSION_5 && ptype > AUTH) ||
  120. new_packets[ptype] == NULL)
  121. Log(TRACE_MIN, 2, NULL, ptype);
  122. else
  123. {
  124. if ((pack = (*new_packets[ptype])(MQTTVersion, header.byte, data, remaining_length)) == NULL)
  125. {
  126. *error = SOCKET_ERROR; // was BAD_MQTT_PACKET;
  127. Log(LOG_ERROR, -1, "Bad MQTT packet, type %d", ptype);
  128. }
  129. #if !defined(NO_PERSISTENCE)
  130. else if (header.bits.type == PUBLISH && header.bits.qos == 2)
  131. {
  132. int buf0len;
  133. char *buf = malloc(10);
  134. buf[0] = header.byte;
  135. buf0len = 1 + MQTTPacket_encode(&buf[1], remaining_length);
  136. *error = MQTTPersistence_put(net->socket, buf, buf0len, 1,
  137. &data, &remaining_length, header.bits.type, ((Publish *)pack)->msgId, 1, MQTTVersion);
  138. free(buf);
  139. }
  140. #endif
  141. }
  142. }
  143. if (pack)
  144. time(&(net->lastReceived));
  145. exit:
  146. FUNC_EXIT_RC(*error);
  147. return pack;
  148. }
  149. /**
  150. * Sends an MQTT packet in one system call write
  151. * @param socket the socket to which to write the data
  152. * @param header the one-byte MQTT header
  153. * @param buffer the rest of the buffer to write (not including remaining length)
  154. * @param buflen the length of the data in buffer to be written
  155. * @param MQTTVersion the version of MQTT being used
  156. * @return the completion code (TCPSOCKET_COMPLETE etc)
  157. */
  158. int MQTTPacket_send(networkHandles* net, Header header, char* buffer, size_t buflen, int freeData,
  159. int MQTTVersion)
  160. {
  161. int rc;
  162. size_t buf0len;
  163. size_t ws_header;
  164. char *buf;
  165. int count = 0;
  166. FUNC_ENTRY;
  167. ws_header = WebSocket_calculateFrameHeaderSize(net, 1, buflen + 10);
  168. buf = malloc(10 + ws_header);
  169. if ( !buf ) return -1;
  170. buf[ws_header] = header.byte;
  171. buf0len = 1 + MQTTPacket_encode(&buf[ws_header + 1], buflen);
  172. if (buffer != NULL)
  173. count = 1;
  174. #if !defined(NO_PERSISTENCE)
  175. if (header.bits.type == PUBREL)
  176. {
  177. char* ptraux = buffer;
  178. int msgId = readInt(&ptraux);
  179. rc = MQTTPersistence_put(net->socket, &buf[ws_header], buf0len, count, &buffer, &buflen,
  180. header.bits.type, msgId, 0, MQTTVersion);
  181. }
  182. #endif
  183. rc = WebSocket_putdatas(net, &buf[ws_header], buf0len, count, &buffer, &buflen, &freeData);
  184. if (rc == TCPSOCKET_COMPLETE)
  185. time(&(net->lastSent));
  186. if (rc != TCPSOCKET_INTERRUPTED)
  187. free(buf);
  188. FUNC_EXIT_RC(rc);
  189. return rc;
  190. }
  191. /**
  192. * Sends an MQTT packet from multiple buffers in one system call write
  193. * @param socket the socket to which to write the data
  194. * @param header the one-byte MQTT header
  195. * @param count the number of buffers
  196. * @param buffers the rest of the buffers to write (not including remaining length)
  197. * @param buflens the lengths of the data in the array of buffers to be written
  198. * @param the MQTT version being used
  199. * @return the completion code (TCPSOCKET_COMPLETE etc)
  200. */
  201. int MQTTPacket_sends(networkHandles* net, Header header, int count, char** buffers, size_t* buflens,
  202. int* frees, int MQTTVersion)
  203. {
  204. int i, rc;
  205. size_t buf0len, total = 0;
  206. size_t ws_header;
  207. char *buf;
  208. FUNC_ENTRY;
  209. for (i = 0; i < count; i++)
  210. total += buflens[i];
  211. ws_header = WebSocket_calculateFrameHeaderSize(net, 1, total + 10);
  212. buf = malloc(10 + ws_header);
  213. if ( !buf ) return -1;
  214. buf[ws_header] = header.byte;
  215. buf0len = 1 + MQTTPacket_encode(&buf[ws_header + 1], total);
  216. #if !defined(NO_PERSISTENCE)
  217. if (header.bits.type == PUBLISH && header.bits.qos != 0)
  218. { /* persist PUBLISH QoS1 and Qo2 */
  219. char *ptraux = buffers[2];
  220. int msgId = readInt(&ptraux);
  221. rc = MQTTPersistence_put(net->socket, &buf[ws_header], buf0len, count, buffers, buflens,
  222. header.bits.type, msgId, 0, MQTTVersion);
  223. }
  224. #endif
  225. rc = WebSocket_putdatas(net, &buf[ws_header], buf0len, count, buffers, buflens, frees);
  226. if (rc == TCPSOCKET_COMPLETE)
  227. time(&(net->lastSent));
  228. if (rc != TCPSOCKET_INTERRUPTED)
  229. free(buf);
  230. FUNC_EXIT_RC(rc);
  231. return rc;
  232. }
  233. /**
  234. * Encodes the message length according to the MQTT algorithm
  235. * @param buf the buffer into which the encoded data is written
  236. * @param length the length to be encoded
  237. * @return the number of bytes written to buffer
  238. */
  239. int MQTTPacket_encode(char* buf, size_t length)
  240. {
  241. int rc = 0;
  242. FUNC_ENTRY;
  243. do
  244. {
  245. char d = length % 128;
  246. length /= 128;
  247. /* if there are more digits to encode, set the top bit of this digit */
  248. if (length > 0)
  249. d |= 0x80;
  250. buf[rc++] = d;
  251. } while (length > 0);
  252. FUNC_EXIT_RC(rc);
  253. return rc;
  254. }
  255. /**
  256. * Decodes the message length according to the MQTT algorithm
  257. * @param socket the socket from which to read the bytes
  258. * @param value the decoded length returned
  259. * @return the number of bytes read from the socket
  260. */
  261. int MQTTPacket_decode(networkHandles* net, size_t* value)
  262. {
  263. int rc = SOCKET_ERROR;
  264. char c;
  265. int multiplier = 1;
  266. int len = 0;
  267. #define MAX_NO_OF_REMAINING_LENGTH_BYTES 4
  268. FUNC_ENTRY;
  269. *value = 0;
  270. do
  271. {
  272. if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES)
  273. {
  274. rc = SOCKET_ERROR; /* bad data */
  275. goto exit;
  276. }
  277. rc = WebSocket_getch(net, &c);
  278. if (rc != TCPSOCKET_COMPLETE)
  279. goto exit;
  280. *value += (c & 127) * multiplier;
  281. multiplier *= 128;
  282. } while ((c & 128) != 0);
  283. exit:
  284. FUNC_EXIT_RC(rc);
  285. return rc;
  286. }
  287. /**
  288. * Calculates an integer from two bytes read from the input buffer
  289. * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
  290. * @return the integer value calculated
  291. */
  292. int readInt(char** pptr)
  293. {
  294. char* ptr = *pptr;
  295. int len = 256*((unsigned char)(*ptr)) + (unsigned char)(*(ptr+1));
  296. *pptr += 2;
  297. return len;
  298. }
  299. /**
  300. * Reads a "UTF" string from the input buffer. UTF as in the MQTT v3 spec which really means
  301. * a length delimited string. So it reads the two byte length then the data according to
  302. * that length. The end of the buffer is provided too, so we can prevent buffer overruns caused
  303. * by an incorrect length.
  304. * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
  305. * @param enddata pointer to the end of the buffer not to be read beyond
  306. * @param len returns the calculcated value of the length bytes read
  307. * @return an allocated C string holding the characters read, or NULL if the length read would
  308. * have caused an overrun.
  309. *
  310. */
  311. static char* readUTFlen(char** pptr, char* enddata, int* len)
  312. {
  313. char* string = NULL;
  314. FUNC_ENTRY;
  315. if (enddata - (*pptr) > 1) /* enough length to read the integer? */
  316. {
  317. *len = readInt(pptr);
  318. if (&(*pptr)[*len] <= enddata)
  319. {
  320. string = malloc(*len+1);
  321. memcpy(string, *pptr, *len);
  322. string[*len] = '\0';
  323. *pptr += *len;
  324. }
  325. }
  326. FUNC_EXIT;
  327. return string;
  328. }
  329. /**
  330. * Reads a "UTF" string from the input buffer. UTF as in the MQTT v3 spec which really means
  331. * a length delimited string. So it reads the two byte length then the data according to
  332. * that length. The end of the buffer is provided too, so we can prevent buffer overruns caused
  333. * by an incorrect length.
  334. * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
  335. * @param enddata pointer to the end of the buffer not to be read beyond
  336. * @return an allocated C string holding the characters read, or NULL if the length read would
  337. * have caused an overrun.
  338. */
  339. char* readUTF(char** pptr, char* enddata)
  340. {
  341. int len;
  342. return readUTFlen(pptr, enddata, &len);
  343. }
  344. /**
  345. * Reads one character from the input buffer.
  346. * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
  347. * @return the character read
  348. */
  349. unsigned char readChar(char** pptr)
  350. {
  351. unsigned char c = **pptr;
  352. (*pptr)++;
  353. return c;
  354. }
  355. /**
  356. * Writes one character to an output buffer.
  357. * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
  358. * @param c the character to write
  359. */
  360. void writeChar(char** pptr, char c)
  361. {
  362. **pptr = c;
  363. (*pptr)++;
  364. }
  365. /**
  366. * Writes an integer as 2 bytes to an output buffer.
  367. * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
  368. * @param anInt the integer to write
  369. */
  370. void writeInt(char** pptr, int anInt)
  371. {
  372. **pptr = (char)(anInt / 256);
  373. (*pptr)++;
  374. **pptr = (char)(anInt % 256);
  375. (*pptr)++;
  376. }
  377. /**
  378. * Writes a "UTF" string to an output buffer. Converts C string to length-delimited.
  379. * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
  380. * @param string the C string to write
  381. */
  382. void writeUTF(char** pptr, const char* string)
  383. {
  384. size_t len = strlen(string);
  385. writeInt(pptr, (int)len);
  386. memcpy(*pptr, string, len);
  387. *pptr += len;
  388. }
  389. /**
  390. * Writes length delimited data to an output buffer
  391. * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
  392. * @param data the data to write
  393. * @param datalen the length of the data to write
  394. */
  395. void writeData(char** pptr, const void* data, int datalen)
  396. {
  397. writeInt(pptr, datalen);
  398. memcpy(*pptr, data, datalen);
  399. *pptr += datalen;
  400. }
  401. /**
  402. * Function used in the new packets table to create packets which have only a header.
  403. * @param MQTTVersion the version of MQTT
  404. * @param aHeader the MQTT header byte
  405. * @param data the rest of the packet
  406. * @param datalen the length of the rest of the packet
  407. * @return pointer to the packet structure
  408. */
  409. void* MQTTPacket_header_only(int MQTTVersion, unsigned char aHeader, char* data, size_t datalen)
  410. {
  411. static unsigned char header = 0;
  412. header = aHeader;
  413. return &header;
  414. }
  415. /**
  416. * Send an MQTT disconnect packet down a socket.
  417. * @param socket the open socket to send the data to
  418. * @return the completion code (e.g. TCPSOCKET_COMPLETE)
  419. */
  420. int MQTTPacket_send_disconnect(Clients* client, enum MQTTReasonCodes reason, MQTTProperties* props)
  421. {
  422. Header header;
  423. int rc = 0;
  424. FUNC_ENTRY;
  425. header.byte = 0;
  426. header.bits.type = DISCONNECT;
  427. if (client->MQTTVersion >= 5 && (props || reason != MQTTREASONCODE_SUCCESS))
  428. {
  429. size_t buflen = 1 + ((props == NULL) ? 0 : MQTTProperties_len(props));
  430. char *buf = malloc(buflen), *ptr = NULL;
  431. ptr = buf;
  432. writeChar(&ptr, reason);
  433. if (props)
  434. MQTTProperties_write(&ptr, props);
  435. if ((rc = MQTTPacket_send(&client->net, header, buf, buflen, 1,
  436. client->MQTTVersion)) != TCPSOCKET_INTERRUPTED)
  437. free(buf);
  438. }
  439. else
  440. rc = MQTTPacket_send(&client->net, header, NULL, 0, 0, client->MQTTVersion);
  441. Log(LOG_PROTOCOL, 28, NULL, client->net.socket, client->clientID, rc);
  442. FUNC_EXIT_RC(rc);
  443. return rc;
  444. }
  445. /**
  446. * Function used in the new packets table to create publish packets.
  447. * @param MQTTVersion
  448. * @param aHeader the MQTT header byte
  449. * @param data the rest of the packet
  450. * @param datalen the length of the rest of the packet
  451. * @return pointer to the packet structure
  452. */
  453. void* MQTTPacket_publish(int MQTTVersion, unsigned char aHeader, char* data, size_t datalen)
  454. {
  455. Publish* pack = NULL;
  456. char* curdata = data;
  457. char* enddata = &data[datalen];
  458. FUNC_ENTRY;
  459. if ((pack = malloc(sizeof(Publish))) == NULL)
  460. goto exit;
  461. memset(pack, '\0', sizeof(Publish));
  462. pack->MQTTVersion = MQTTVersion;
  463. pack->header.byte = aHeader;
  464. if ((pack->topic = readUTFlen(&curdata, enddata, &pack->topiclen)) == NULL) /* Topic name on which to publish */
  465. {
  466. free(pack);
  467. pack = NULL;
  468. goto exit;
  469. }
  470. if (pack->header.bits.qos > 0) /* Msgid only exists for QoS 1 or 2 */
  471. pack->msgId = readInt(&curdata);
  472. else
  473. pack->msgId = 0;
  474. if (MQTTVersion >= MQTTVERSION_5)
  475. {
  476. MQTTProperties props = MQTTProperties_initializer;
  477. pack->properties = props;
  478. if (MQTTProperties_read(&pack->properties, &curdata, enddata) != 1)
  479. {
  480. if (pack->properties.array)
  481. free(pack->properties.array);
  482. if (pack)
  483. free(pack);
  484. pack = NULL; /* signal protocol error */
  485. goto exit;
  486. }
  487. }
  488. pack->payload = curdata;
  489. pack->payloadlen = (int)(datalen-(curdata-data));
  490. exit:
  491. FUNC_EXIT;
  492. return pack;
  493. }
  494. /**
  495. * Free allocated storage for a publish packet.
  496. * @param pack pointer to the publish packet structure
  497. */
  498. void MQTTPacket_freePublish(Publish* pack)
  499. {
  500. FUNC_ENTRY;
  501. if (pack->topic != NULL)
  502. free(pack->topic);
  503. if (pack->MQTTVersion >= MQTTVERSION_5)
  504. MQTTProperties_free(&pack->properties);
  505. free(pack);
  506. FUNC_EXIT;
  507. }
  508. /**
  509. * Free allocated storage for an ack packet.
  510. * @param pack pointer to the publish packet structure
  511. */
  512. void MQTTPacket_freeAck(Ack* pack)
  513. {
  514. FUNC_ENTRY;
  515. if (pack->MQTTVersion >= MQTTVERSION_5)
  516. MQTTProperties_free(&pack->properties);
  517. free(pack);
  518. FUNC_EXIT;
  519. }
  520. /**
  521. * Send an MQTT acknowledgement packet down a socket.
  522. * @param MQTTVersion the version of MQTT being used
  523. * @param type the MQTT packet type e.g. SUBACK
  524. * @param msgid the MQTT message id to use
  525. * @param dup boolean - whether to set the MQTT DUP flag
  526. * @param net the network handle to send the data to
  527. * @return the completion code (e.g. TCPSOCKET_COMPLETE)
  528. */
  529. static int MQTTPacket_send_ack(int MQTTVersion, int type, int msgid, int dup, networkHandles *net)
  530. {
  531. Header header;
  532. int rc;
  533. char *buf = malloc(2);
  534. char *ptr = buf;
  535. FUNC_ENTRY;
  536. header.byte = 0;
  537. header.bits.type = type;
  538. header.bits.dup = dup;
  539. if (type == PUBREL)
  540. header.bits.qos = 1;
  541. writeInt(&ptr, msgid);
  542. if ((rc = MQTTPacket_send(net, header, buf, 2, 1, MQTTVersion)) != TCPSOCKET_INTERRUPTED)
  543. free(buf);
  544. FUNC_EXIT_RC(rc);
  545. return rc;
  546. }
  547. /**
  548. * Send an MQTT PUBACK packet down a socket.
  549. * @param MQTTVersion the version of MQTT being used
  550. * @param msgid the MQTT message id to use
  551. * @param socket the open socket to send the data to
  552. * @param clientID the string client identifier, only used for tracing
  553. * @return the completion code (e.g. TCPSOCKET_COMPLETE)
  554. */
  555. int MQTTPacket_send_puback(int MQTTVersion, int msgid, networkHandles* net, const char* clientID)
  556. {
  557. int rc = 0;
  558. FUNC_ENTRY;
  559. rc = MQTTPacket_send_ack(MQTTVersion, PUBACK, msgid, 0, net);
  560. Log(LOG_PROTOCOL, 12, NULL, net->socket, clientID, msgid, rc);
  561. FUNC_EXIT_RC(rc);
  562. return rc;
  563. }
  564. /**
  565. * Free allocated storage for a suback packet.
  566. * @param pack pointer to the suback packet structure
  567. */
  568. void MQTTPacket_freeSuback(Suback* pack)
  569. {
  570. FUNC_ENTRY;
  571. if (pack->MQTTVersion >= MQTTVERSION_5)
  572. MQTTProperties_free(&pack->properties);
  573. if (pack->qoss != NULL)
  574. ListFree(pack->qoss);
  575. free(pack);
  576. FUNC_EXIT;
  577. }
  578. /**
  579. * Free allocated storage for a suback packet.
  580. * @param pack pointer to the suback packet structure
  581. */
  582. void MQTTPacket_freeUnsuback(Unsuback* pack)
  583. {
  584. FUNC_ENTRY;
  585. if (pack->MQTTVersion >= MQTTVERSION_5)
  586. {
  587. MQTTProperties_free(&pack->properties);
  588. if (pack->reasonCodes != NULL)
  589. ListFree(pack->reasonCodes);
  590. }
  591. free(pack);
  592. FUNC_EXIT;
  593. }
  594. /**
  595. * Send an MQTT PUBREC packet down a socket.
  596. * @param MQTTVersion the version of MQTT being used
  597. * @param msgid the MQTT message id to use
  598. * @param socket the open socket to send the data to
  599. * @param clientID the string client identifier, only used for tracing
  600. * @return the completion code (e.g. TCPSOCKET_COMPLETE)
  601. */
  602. int MQTTPacket_send_pubrec(int MQTTVersion, int msgid, networkHandles* net, const char* clientID)
  603. {
  604. int rc = 0;
  605. FUNC_ENTRY;
  606. rc = MQTTPacket_send_ack(MQTTVersion, PUBREC, msgid, 0, net);
  607. Log(LOG_PROTOCOL, 13, NULL, net->socket, clientID, msgid, rc);
  608. FUNC_EXIT_RC(rc);
  609. return rc;
  610. }
  611. /**
  612. * Send an MQTT PUBREL packet down a socket.
  613. * @param MQTTVersion the version of MQTT being used
  614. * @param msgid the MQTT message id to use
  615. * @param dup boolean - whether to set the MQTT DUP flag
  616. * @param socket the open socket to send the data to
  617. * @param clientID the string client identifier, only used for tracing
  618. * @return the completion code (e.g. TCPSOCKET_COMPLETE)
  619. */
  620. int MQTTPacket_send_pubrel(int MQTTVersion, int msgid, int dup, networkHandles* net, const char* clientID)
  621. {
  622. int rc = 0;
  623. FUNC_ENTRY;
  624. rc = MQTTPacket_send_ack(MQTTVersion, PUBREL, msgid, dup, net);
  625. Log(LOG_PROTOCOL, 16, NULL, net->socket, clientID, msgid, rc);
  626. FUNC_EXIT_RC(rc);
  627. return rc;
  628. }
  629. /**
  630. * Send an MQTT PUBCOMP packet down a socket.
  631. * @param MQTTVersion the version of MQTT being used
  632. * @param msgid the MQTT message id to use
  633. * @param socket the open socket to send the data to
  634. * @param clientID the string client identifier, only used for tracing
  635. * @return the completion code (e.g. TCPSOCKET_COMPLETE)
  636. */
  637. int MQTTPacket_send_pubcomp(int MQTTVersion, int msgid, networkHandles* net, const char* clientID)
  638. {
  639. int rc = 0;
  640. FUNC_ENTRY;
  641. rc = MQTTPacket_send_ack(MQTTVersion, PUBCOMP, msgid, 0, net);
  642. Log(LOG_PROTOCOL, 18, NULL, net->socket, clientID, msgid, rc);
  643. FUNC_EXIT_RC(rc);
  644. return rc;
  645. }
  646. /**
  647. * Function used in the new packets table to create acknowledgement packets.
  648. * @param MQTTVersion the version of MQTT being used
  649. * @param aHeader the MQTT header byte
  650. * @param data the rest of the packet
  651. * @param datalen the length of the rest of the packet
  652. * @return pointer to the packet structure
  653. */
  654. void* MQTTPacket_ack(int MQTTVersion, unsigned char aHeader, char* data, size_t datalen)
  655. {
  656. Ack* pack = NULL;
  657. char* curdata = data;
  658. char* enddata = &data[datalen];
  659. FUNC_ENTRY;
  660. if ((pack = malloc(sizeof(Ack))) == NULL)
  661. goto exit;
  662. pack->MQTTVersion = MQTTVersion;
  663. pack->header.byte = aHeader;
  664. if (pack->header.bits.type != DISCONNECT)
  665. pack->msgId = readInt(&curdata);
  666. if (MQTTVersion >= MQTTVERSION_5)
  667. {
  668. MQTTProperties props = MQTTProperties_initializer;
  669. pack->rc = MQTTREASONCODE_SUCCESS;
  670. pack->properties = props;
  671. if (datalen > 2)
  672. pack->rc = readChar(&curdata); /* reason code */
  673. if (datalen > 3)
  674. {
  675. if (MQTTProperties_read(&pack->properties, &curdata, enddata) != 1)
  676. {
  677. if (pack->properties.array)
  678. free(pack->properties.array);
  679. if (pack)
  680. free(pack);
  681. pack = NULL; /* signal protocol error */
  682. goto exit;
  683. }
  684. }
  685. }
  686. exit:
  687. FUNC_EXIT;
  688. return pack;
  689. }
  690. /**
  691. * Send an MQTT PUBLISH packet down a socket.
  692. * @param pack a structure from which to get some values to use, e.g topic, payload
  693. * @param dup boolean - whether to set the MQTT DUP flag
  694. * @param qos the value to use for the MQTT QoS setting
  695. * @param retained boolean - whether to set the MQTT retained flag
  696. * @param socket the open socket to send the data to
  697. * @param clientID the string client identifier, only used for tracing
  698. * @return the completion code (e.g. TCPSOCKET_COMPLETE)
  699. */
  700. int MQTTPacket_send_publish(Publish* pack, int dup, int qos, int retained, networkHandles* net, const char* clientID)
  701. {
  702. Header header;
  703. char *topiclen;
  704. int rc = -1;
  705. FUNC_ENTRY;
  706. topiclen = malloc(2);
  707. header.bits.type = PUBLISH;
  708. header.bits.dup = dup;
  709. header.bits.qos = qos;
  710. header.bits.retain = retained;
  711. if (qos > 0 || pack->MQTTVersion >= 5)
  712. {
  713. int buflen = ((qos > 0) ? 2 : 0) + ((pack->MQTTVersion >= 5) ? MQTTProperties_len(&pack->properties) : 0);
  714. char *ptr = NULL;
  715. char* bufs[4] = {topiclen, pack->topic, NULL, pack->payload};
  716. size_t lens[4] = {2, strlen(pack->topic), buflen, pack->payloadlen};
  717. int frees[4] = {1, 0, 1, 0};
  718. bufs[2] = ptr = malloc(buflen);
  719. if (qos > 0)
  720. writeInt(&ptr, pack->msgId);
  721. if (pack->MQTTVersion >= 5)
  722. MQTTProperties_write(&ptr, &pack->properties);
  723. ptr = topiclen;
  724. writeInt(&ptr, (int)lens[1]);
  725. rc = MQTTPacket_sends(net, header, 4, bufs, lens, frees, pack->MQTTVersion);
  726. if (rc != TCPSOCKET_INTERRUPTED)
  727. free(bufs[2]);
  728. }
  729. else
  730. {
  731. char* ptr = topiclen;
  732. char* bufs[3] = {topiclen, pack->topic, pack->payload};
  733. size_t lens[3] = {2, strlen(pack->topic), pack->payloadlen};
  734. int frees[3] = {1, 0, 0};
  735. writeInt(&ptr, (int)lens[1]);
  736. rc = MQTTPacket_sends(net, header, 3, bufs, lens, frees, pack->MQTTVersion);
  737. }
  738. if (rc != TCPSOCKET_INTERRUPTED)
  739. free(topiclen);
  740. if (qos == 0)
  741. Log(LOG_PROTOCOL, 27, NULL, net->socket, clientID, retained, rc);
  742. else
  743. Log(LOG_PROTOCOL, 10, NULL, net->socket, clientID, pack->msgId, qos, retained, rc,
  744. min(20, pack->payloadlen), pack->payload);
  745. FUNC_EXIT_RC(rc);
  746. return rc;
  747. }
  748. /**
  749. * Free allocated storage for a various packet tyoes
  750. * @param pack pointer to the suback packet structure
  751. */
  752. void MQTTPacket_free_packet(MQTTPacket* pack)
  753. {
  754. FUNC_ENTRY;
  755. if (pack->header.bits.type == PUBLISH)
  756. MQTTPacket_freePublish((Publish*)pack);
  757. /*else if (pack->header.type == SUBSCRIBE)
  758. MQTTPacket_freeSubscribe((Subscribe*)pack, 1);
  759. else if (pack->header.type == UNSUBSCRIBE)
  760. MQTTPacket_freeUnsubscribe((Unsubscribe*)pack);*/
  761. else
  762. free(pack);
  763. FUNC_EXIT;
  764. }
  765. /**
  766. * Writes an integer as 4 bytes to an output buffer.
  767. * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
  768. * @param anInt the integer to write
  769. */
  770. void writeInt4(char** pptr, int anInt)
  771. {
  772. **pptr = (char)(anInt / 16777216);
  773. (*pptr)++;
  774. anInt %= 16777216;
  775. **pptr = (char)(anInt / 65536);
  776. (*pptr)++;
  777. anInt %= 65536;
  778. **pptr = (char)(anInt / 256);
  779. (*pptr)++;
  780. **pptr = (char)(anInt % 256);
  781. (*pptr)++;
  782. }
  783. /**
  784. * Calculates an integer from two bytes read from the input buffer
  785. * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
  786. * @return the integer value calculated
  787. */
  788. int readInt4(char** pptr)
  789. {
  790. unsigned char* ptr = (unsigned char*)*pptr;
  791. int value = 16777216*(*ptr) + 65536*(*(ptr+1)) + 256*(*(ptr+2)) + (*(ptr+3));
  792. *pptr += 4;
  793. return value;
  794. }
  795. void writeMQTTLenString(char** pptr, MQTTLenString lenstring)
  796. {
  797. writeInt(pptr, lenstring.len);
  798. memcpy(*pptr, lenstring.data, lenstring.len);
  799. *pptr += lenstring.len;
  800. }
  801. int MQTTLenStringRead(MQTTLenString* lenstring, char** pptr, char* enddata)
  802. {
  803. int len = 0;
  804. /* the first two bytes are the length of the string */
  805. if (enddata - (*pptr) > 1) /* enough length to read the integer? */
  806. {
  807. lenstring->len = readInt(pptr); /* increments pptr to point past length */
  808. if (&(*pptr)[lenstring->len] <= enddata)
  809. {
  810. lenstring->data = (char*)*pptr;
  811. *pptr += lenstring->len;
  812. len = 2 + lenstring->len;
  813. }
  814. }
  815. return len;
  816. }
  817. /*
  818. if (prop->value.integer4 >= 0 && prop->value.integer4 <= 127)
  819. len = 1;
  820. else if (prop->value.integer4 >= 128 && prop->value.integer4 <= 16383)
  821. len = 2;
  822. else if (prop->value.integer4 >= 16384 && prop->value.integer4 < 2097151)
  823. len = 3;
  824. else if (prop->value.integer4 >= 2097152 && prop->value.integer4 < 268435455)
  825. len = 4;
  826. */
  827. int MQTTPacket_VBIlen(int rem_len)
  828. {
  829. int rc = 0;
  830. if (rem_len < 128)
  831. rc = 1;
  832. else if (rem_len < 16384)
  833. rc = 2;
  834. else if (rem_len < 2097152)
  835. rc = 3;
  836. else
  837. rc = 4;
  838. return rc;
  839. }
  840. /**
  841. * Decodes the message length according to the MQTT algorithm
  842. * @param getcharfn pointer to function to read the next character from the data source
  843. * @param value the decoded length returned
  844. * @return the number of bytes read from the socket
  845. */
  846. int MQTTPacket_VBIdecode(int (*getcharfn)(char*, int), unsigned int* value)
  847. {
  848. char c;
  849. int multiplier = 1;
  850. int len = 0;
  851. #define MAX_NO_OF_REMAINING_LENGTH_BYTES 4
  852. *value = 0;
  853. do
  854. {
  855. int rc = MQTTPACKET_READ_ERROR;
  856. if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES)
  857. {
  858. rc = MQTTPACKET_READ_ERROR; /* bad data */
  859. goto exit;
  860. }
  861. rc = (*getcharfn)(&c, 1);
  862. if (rc != 1)
  863. goto exit;
  864. *value += (c & 127) * multiplier;
  865. multiplier *= 128;
  866. } while ((c & 128) != 0);
  867. exit:
  868. return len;
  869. }
  870. static char* bufptr;
  871. int bufchar(char* c, int count)
  872. {
  873. int i;
  874. for (i = 0; i < count; ++i)
  875. *c = *bufptr++;
  876. return count;
  877. }
  878. int MQTTPacket_decodeBuf(char* buf, unsigned int* value)
  879. {
  880. bufptr = buf;
  881. return MQTTPacket_VBIdecode(bufchar, value);
  882. }