MQTTPacket.c 28 KB

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