MQTTProtocolClient.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  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 - fix for bug 413429 - connectionLost not called
  16. * Ian Craggs - fix for bug 421103 - trying to write to same socket, in retry
  17. * Rong Xiang, Ian Craggs - C++ compatibility
  18. * Ian Craggs - turn off DUP flag for PUBREL - MQTT 3.1.1
  19. * Ian Craggs - ensure that acks are not sent if write is outstanding on socket
  20. * Ian Craggs - MQTT 5.0 support
  21. *******************************************************************************/
  22. /**
  23. * @file
  24. * \brief Functions dealing with the MQTT protocol exchanges
  25. *
  26. * Some other related functions are in the MQTTProtocolOut module
  27. * */
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include "MQTTProtocolClient.h"
  32. #if !defined(NO_PERSISTENCE)
  33. #include "MQTTPersistence.h"
  34. #endif
  35. #include "Socket.h"
  36. #include "SocketBuffer.h"
  37. #include "StackTrace.h"
  38. #include "Heap.h"
  39. #if !defined(min)
  40. #define min(A,B) ( (A) < (B) ? (A):(B))
  41. #endif
  42. extern MQTTProtocol state;
  43. extern ClientStates* bstate;
  44. static void MQTTProtocol_storeQoS0(Clients* pubclient, Publish* publish);
  45. static int MQTTProtocol_startPublishCommon(
  46. Clients* pubclient,
  47. Publish* publish,
  48. int qos,
  49. int retained);
  50. static void MQTTProtocol_retries(START_TIME_TYPE now, Clients* client, int regardless);
  51. static int MQTTProtocol_queueAck(Clients* client, int ackType, int msgId);
  52. typedef struct {
  53. int messageId;
  54. int ackType;
  55. } AckRequest;
  56. /**
  57. * List callback function for comparing Message structures by message id
  58. * @param a first integer value
  59. * @param b second integer value
  60. * @return boolean indicating whether a and b are equal
  61. */
  62. int messageIDCompare(void* a, void* b)
  63. {
  64. Messages* msg = (Messages*)a;
  65. return msg->msgid == *(int*)b;
  66. }
  67. /**
  68. * Assign a new message id for a client. Make sure it isn't already being used and does
  69. * not exceed the maximum.
  70. * @param client a client structure
  71. * @return the next message id to use, or 0 if none available
  72. */
  73. int MQTTProtocol_assignMsgId(Clients* client)
  74. {
  75. int start_msgid = client->msgID;
  76. int msgid = start_msgid;
  77. FUNC_ENTRY;
  78. msgid = (msgid == MAX_MSG_ID) ? 1 : msgid + 1;
  79. while (ListFindItem(client->outboundMsgs, &msgid, messageIDCompare) != NULL)
  80. {
  81. msgid = (msgid == MAX_MSG_ID) ? 1 : msgid + 1;
  82. if (msgid == start_msgid)
  83. { /* we've tried them all - none free */
  84. msgid = 0;
  85. break;
  86. }
  87. }
  88. if (msgid != 0)
  89. client->msgID = msgid;
  90. FUNC_EXIT_RC(msgid);
  91. return msgid;
  92. }
  93. static void MQTTProtocol_storeQoS0(Clients* pubclient, Publish* publish)
  94. {
  95. int len;
  96. pending_write* pw = NULL;
  97. FUNC_ENTRY;
  98. /* store the publication until the write is finished */
  99. if ((pw = malloc(sizeof(pending_write))) == NULL)
  100. goto exit;
  101. Log(TRACE_MIN, 12, NULL);
  102. if ((pw->p = MQTTProtocol_storePublication(publish, &len)) == NULL)
  103. {
  104. free(pw);
  105. goto exit;
  106. }
  107. pw->socket = pubclient->net.socket;
  108. if (!ListAppend(&(state.pending_writes), pw, sizeof(pending_write)+len))
  109. {
  110. free(pw->p);
  111. free(pw);
  112. goto exit;
  113. }
  114. /* we don't copy QoS 0 messages unless we have to, so now we have to tell the socket buffer where
  115. the saved copy is */
  116. if (SocketBuffer_updateWrite(pw->socket, pw->p->topic, pw->p->payload) == NULL)
  117. Log(LOG_SEVERE, 0, "Error updating write");
  118. publish->payload = publish->topic = NULL;
  119. exit:
  120. FUNC_EXIT;
  121. }
  122. /**
  123. * Utility function to start a new publish exchange.
  124. * @param pubclient the client to send the publication to
  125. * @param publish the publication data
  126. * @param qos the MQTT QoS to use
  127. * @param retained boolean - whether to set the MQTT retained flag
  128. * @return the completion code
  129. */
  130. static int MQTTProtocol_startPublishCommon(Clients* pubclient, Publish* publish, int qos, int retained)
  131. {
  132. int rc = TCPSOCKET_COMPLETE;
  133. FUNC_ENTRY;
  134. rc = MQTTPacket_send_publish(publish, 0, qos, retained, &pubclient->net, pubclient->clientID);
  135. if (qos == 0 && rc == TCPSOCKET_INTERRUPTED)
  136. MQTTProtocol_storeQoS0(pubclient, publish);
  137. FUNC_EXIT_RC(rc);
  138. return rc;
  139. }
  140. /**
  141. * Start a new publish exchange. Store any state necessary and try to send the packet
  142. * @param pubclient the client to send the publication to
  143. * @param publish the publication data
  144. * @param qos the MQTT QoS to use
  145. * @param retained boolean - whether to set the MQTT retained flag
  146. * @param mm - pointer to the message to send
  147. * @return the completion code
  148. */
  149. int MQTTProtocol_startPublish(Clients* pubclient, Publish* publish, int qos, int retained, Messages** mm)
  150. {
  151. Publish qos12pub = *publish;
  152. int rc = 0;
  153. FUNC_ENTRY;
  154. if (qos > 0)
  155. {
  156. *mm = MQTTProtocol_createMessage(publish, mm, qos, retained, 0);
  157. ListAppend(pubclient->outboundMsgs, *mm, (*mm)->len);
  158. /* we change these pointers to the saved message location just in case the packet could not be written
  159. entirely; the socket buffer will use these locations to finish writing the packet */
  160. qos12pub.payload = (*mm)->publish->payload;
  161. qos12pub.topic = (*mm)->publish->topic;
  162. qos12pub.properties = (*mm)->properties;
  163. qos12pub.MQTTVersion = (*mm)->MQTTVersion;
  164. publish = &qos12pub;
  165. }
  166. rc = MQTTProtocol_startPublishCommon(pubclient, publish, qos, retained);
  167. if (qos > 0)
  168. memcpy((*mm)->publish->mask, publish->mask, sizeof((*mm)->publish->mask));
  169. FUNC_EXIT_RC(rc);
  170. return rc;
  171. }
  172. /**
  173. * Copy and store message data for retries
  174. * @param publish the publication data
  175. * @param mm - pointer to the message data to store
  176. * @param qos the MQTT QoS to use
  177. * @param retained boolean - whether to set the MQTT retained flag
  178. * @param allocatePayload boolean - whether or not to malloc payload
  179. * @return pointer to the message data stored
  180. */
  181. Messages* MQTTProtocol_createMessage(Publish* publish, Messages **mm, int qos, int retained, int allocatePayload)
  182. {
  183. Messages* m = malloc(sizeof(Messages));
  184. FUNC_ENTRY;
  185. if (!m)
  186. goto exit;
  187. m->len = sizeof(Messages);
  188. if (*mm == NULL || (*mm)->publish == NULL)
  189. {
  190. int len1;
  191. *mm = m;
  192. if ((m->publish = MQTTProtocol_storePublication(publish, &len1)) == NULL)
  193. {
  194. free(m);
  195. goto exit;
  196. }
  197. m->len += len1;
  198. if (allocatePayload)
  199. {
  200. char *temp = m->publish->payload;
  201. if ((m->publish->payload = malloc(m->publish->payloadlen)) == NULL)
  202. {
  203. free(m);
  204. goto exit;
  205. }
  206. memcpy(m->publish->payload, temp, m->publish->payloadlen);
  207. }
  208. }
  209. else /* this is now never used, I think */
  210. {
  211. ++(((*mm)->publish)->refcount);
  212. m->publish = (*mm)->publish;
  213. }
  214. m->msgid = publish->msgId;
  215. m->qos = qos;
  216. m->retain = retained;
  217. m->MQTTVersion = publish->MQTTVersion;
  218. if (m->MQTTVersion >= 5)
  219. m->properties = MQTTProperties_copy(&publish->properties);
  220. m->lastTouch = MQTTTime_now();
  221. if (qos == 2)
  222. m->nextMessageType = PUBREC;
  223. exit:
  224. FUNC_EXIT;
  225. return m;
  226. }
  227. /**
  228. * Store message data for possible retry
  229. * @param publish the publication data
  230. * @param len returned length of the data stored
  231. * @return the publication stored
  232. */
  233. Publications* MQTTProtocol_storePublication(Publish* publish, int* len)
  234. {
  235. Publications* p = malloc(sizeof(Publications));
  236. FUNC_ENTRY;
  237. if (!p)
  238. goto exit;
  239. p->refcount = 1;
  240. *len = (int)strlen(publish->topic)+1;
  241. p->topic = publish->topic;
  242. publish->topic = NULL;
  243. *len += sizeof(Publications);
  244. p->topiclen = publish->topiclen;
  245. p->payloadlen = publish->payloadlen;
  246. p->payload = publish->payload;
  247. publish->payload = NULL;
  248. *len += publish->payloadlen;
  249. memcpy(p->mask, publish->mask, sizeof(p->mask));
  250. if ((ListAppend(&(state.publications), p, *len)) == NULL)
  251. {
  252. free(p);
  253. p = NULL;
  254. }
  255. exit:
  256. FUNC_EXIT;
  257. return p;
  258. }
  259. /**
  260. * Remove stored message data. Opposite of storePublication
  261. * @param p stored publication to remove
  262. */
  263. void MQTTProtocol_removePublication(Publications* p)
  264. {
  265. FUNC_ENTRY;
  266. if (p && --(p->refcount) == 0)
  267. {
  268. if (p->payload)
  269. {
  270. free(p->payload);
  271. p->payload = NULL;
  272. }
  273. if (p->topic)
  274. {
  275. free(p->topic);
  276. p->topic = NULL;
  277. }
  278. ListRemove(&(state.publications), p);
  279. }
  280. FUNC_EXIT;
  281. }
  282. /**
  283. * Process an incoming publish packet for a socket
  284. * The payload field of the packet has not been transferred to another buffer at this point.
  285. * If it's needed beyond the scope of this function, it has to be copied.
  286. * @param pack pointer to the publish packet
  287. * @param sock the socket on which the packet was received
  288. * @return completion code
  289. */
  290. int MQTTProtocol_handlePublishes(void* pack, SOCKET sock)
  291. {
  292. Publish* publish = (Publish*)pack;
  293. Clients* client = NULL;
  294. char* clientid = NULL;
  295. int rc = TCPSOCKET_COMPLETE;
  296. int socketHasPendingWrites = 0;
  297. FUNC_ENTRY;
  298. client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
  299. clientid = client->clientID;
  300. Log(LOG_PROTOCOL, 11, NULL, sock, clientid, publish->msgId, publish->header.bits.qos,
  301. publish->header.bits.retain, publish->payloadlen, min(20, publish->payloadlen), publish->payload);
  302. if (publish->header.bits.qos == 0)
  303. {
  304. Protocol_processPublication(publish, client, 1);
  305. goto exit;
  306. }
  307. socketHasPendingWrites = !Socket_noPendingWrites(sock);
  308. if (publish->header.bits.qos == 1)
  309. {
  310. Protocol_processPublication(publish, client, 1);
  311. if (socketHasPendingWrites)
  312. rc = MQTTProtocol_queueAck(client, PUBACK, publish->msgId);
  313. else
  314. rc = MQTTPacket_send_puback(publish->MQTTVersion, publish->msgId, &client->net, client->clientID);
  315. }
  316. else if (publish->header.bits.qos == 2)
  317. {
  318. /* store publication in inbound list */
  319. int len;
  320. int already_received = 0;
  321. ListElement* listElem = NULL;
  322. Messages* m = malloc(sizeof(Messages));
  323. Publications* p = NULL;
  324. if (!m)
  325. {
  326. rc = PAHO_MEMORY_ERROR;
  327. goto exit;
  328. }
  329. p = MQTTProtocol_storePublication(publish, &len);
  330. m->publish = p;
  331. m->msgid = publish->msgId;
  332. m->qos = publish->header.bits.qos;
  333. m->retain = publish->header.bits.retain;
  334. m->MQTTVersion = publish->MQTTVersion;
  335. if (m->MQTTVersion >= MQTTVERSION_5)
  336. m->properties = MQTTProperties_copy(&publish->properties);
  337. m->nextMessageType = PUBREL;
  338. if ((listElem = ListFindItem(client->inboundMsgs, &(m->msgid), messageIDCompare)) != NULL)
  339. { /* discard queued publication with same msgID that the current incoming message */
  340. Messages* msg = (Messages*)(listElem->content);
  341. MQTTProtocol_removePublication(msg->publish);
  342. if (msg->MQTTVersion >= MQTTVERSION_5)
  343. MQTTProperties_free(&msg->properties);
  344. ListInsert(client->inboundMsgs, m, sizeof(Messages) + len, listElem);
  345. ListRemove(client->inboundMsgs, msg);
  346. already_received = 1;
  347. } else
  348. ListAppend(client->inboundMsgs, m, sizeof(Messages) + len);
  349. if (m->MQTTVersion >= MQTTVERSION_5 && already_received == 0)
  350. {
  351. Publish publish1;
  352. publish1.header.bits.qos = m->qos;
  353. publish1.header.bits.retain = m->retain;
  354. publish1.msgId = m->msgid;
  355. publish1.topic = m->publish->topic;
  356. publish1.topiclen = m->publish->topiclen;
  357. publish1.payload = m->publish->payload;
  358. publish1.payloadlen = m->publish->payloadlen;
  359. publish1.MQTTVersion = m->MQTTVersion;
  360. publish1.properties = m->properties;
  361. Protocol_processPublication(&publish1, client, 1);
  362. ListRemove(&(state.publications), m->publish);
  363. m->publish = NULL;
  364. } else
  365. { /* allocate and copy payload data as it's needed for pubrel.
  366. For other cases, it's done in Protocol_processPublication */
  367. char *temp = m->publish->payload;
  368. if ((m->publish->payload = malloc(m->publish->payloadlen)) == NULL)
  369. {
  370. rc = PAHO_MEMORY_ERROR;
  371. goto exit;
  372. }
  373. memcpy(m->publish->payload, temp, m->publish->payloadlen);
  374. }
  375. if (socketHasPendingWrites)
  376. rc = MQTTProtocol_queueAck(client, PUBREC, publish->msgId);
  377. else
  378. rc = MQTTPacket_send_pubrec(publish->MQTTVersion, publish->msgId, &client->net, client->clientID);
  379. publish->topic = NULL;
  380. }
  381. exit:
  382. MQTTPacket_freePublish(publish);
  383. FUNC_EXIT_RC(rc);
  384. return rc;
  385. }
  386. /**
  387. * Process an incoming puback packet for a socket
  388. * @param pack pointer to the publish packet
  389. * @param sock the socket on which the packet was received
  390. * @return completion code
  391. */
  392. int MQTTProtocol_handlePubacks(void* pack, SOCKET sock, Publications** pubToRemove)
  393. {
  394. Puback* puback = (Puback*)pack;
  395. Clients* client = NULL;
  396. int rc = TCPSOCKET_COMPLETE;
  397. FUNC_ENTRY;
  398. client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
  399. Log(LOG_PROTOCOL, 14, NULL, sock, client->clientID, puback->msgId);
  400. /* look for the message by message id in the records of outbound messages for this client */
  401. if (ListFindItem(client->outboundMsgs, &(puback->msgId), messageIDCompare) == NULL)
  402. Log(TRACE_MIN, 3, NULL, "PUBACK", client->clientID, puback->msgId);
  403. else
  404. {
  405. Messages* m = (Messages*)(client->outboundMsgs->current->content);
  406. if (m->qos != 1)
  407. Log(TRACE_MIN, 4, NULL, "PUBACK", client->clientID, puback->msgId, m->qos);
  408. else
  409. {
  410. Log(TRACE_MIN, 6, NULL, "PUBACK", client->clientID, puback->msgId);
  411. #if !defined(NO_PERSISTENCE)
  412. rc = MQTTPersistence_remove(client,
  413. (m->MQTTVersion >= MQTTVERSION_5) ? PERSISTENCE_V5_PUBLISH_SENT : PERSISTENCE_PUBLISH_SENT,
  414. m->qos, puback->msgId);
  415. #endif
  416. if (pubToRemove != NULL)
  417. *pubToRemove = m->publish;
  418. else
  419. MQTTProtocol_removePublication(m->publish);
  420. if (m->MQTTVersion >= MQTTVERSION_5)
  421. MQTTProperties_free(&m->properties);
  422. ListRemove(client->outboundMsgs, m);
  423. }
  424. }
  425. if (puback->MQTTVersion >= MQTTVERSION_5)
  426. MQTTProperties_free(&puback->properties);
  427. free(pack);
  428. FUNC_EXIT_RC(rc);
  429. return rc;
  430. }
  431. /**
  432. * Process an incoming pubrec packet for a socket
  433. * @param pack pointer to the publish packet
  434. * @param sock the socket on which the packet was received
  435. * @return completion code
  436. */
  437. int MQTTProtocol_handlePubrecs(void* pack, SOCKET sock, Publications** pubToRemove)
  438. {
  439. Pubrec* pubrec = (Pubrec*)pack;
  440. Clients* client = NULL;
  441. int rc = TCPSOCKET_COMPLETE;
  442. int send_pubrel = 1; /* boolean to send PUBREL or not */
  443. FUNC_ENTRY;
  444. client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
  445. Log(LOG_PROTOCOL, 15, NULL, sock, client->clientID, pubrec->msgId);
  446. /* look for the message by message id in the records of outbound messages for this client */
  447. client->outboundMsgs->current = NULL;
  448. if (ListFindItem(client->outboundMsgs, &(pubrec->msgId), messageIDCompare) == NULL)
  449. {
  450. if (pubrec->header.bits.dup == 0)
  451. Log(TRACE_MIN, 3, NULL, "PUBREC", client->clientID, pubrec->msgId);
  452. }
  453. else
  454. {
  455. Messages* m = (Messages*)(client->outboundMsgs->current->content);
  456. if (m->qos != 2)
  457. {
  458. if (pubrec->header.bits.dup == 0)
  459. Log(TRACE_MIN, 4, NULL, "PUBREC", client->clientID, pubrec->msgId, m->qos);
  460. }
  461. else if (m->nextMessageType != PUBREC)
  462. {
  463. if (pubrec->header.bits.dup == 0)
  464. Log(TRACE_MIN, 5, NULL, "PUBREC", client->clientID, pubrec->msgId);
  465. }
  466. else
  467. {
  468. if (pubrec->MQTTVersion >= MQTTVERSION_5 && pubrec->rc >= MQTTREASONCODE_UNSPECIFIED_ERROR)
  469. {
  470. Log(TRACE_MIN, -1, "Pubrec error %d received for client %s msgid %d, not sending PUBREL",
  471. pubrec->rc, client->clientID, pubrec->msgId);
  472. #if !defined(NO_PERSISTENCE)
  473. rc = MQTTPersistence_remove(client,
  474. (pubrec->MQTTVersion >= MQTTVERSION_5) ? PERSISTENCE_V5_PUBLISH_SENT : PERSISTENCE_PUBLISH_SENT,
  475. m->qos, pubrec->msgId);
  476. #endif
  477. if (pubToRemove != NULL)
  478. *pubToRemove = m->publish;
  479. else
  480. MQTTProtocol_removePublication(m->publish);
  481. if (m->MQTTVersion >= MQTTVERSION_5)
  482. MQTTProperties_free(&m->properties);
  483. ListRemove(client->outboundMsgs, m);
  484. (++state.msgs_sent);
  485. send_pubrel = 0; /* in MQTT v5, stop the exchange if there is an error reported */
  486. }
  487. else
  488. {
  489. m->nextMessageType = PUBCOMP;
  490. m->lastTouch = MQTTTime_now();
  491. }
  492. }
  493. }
  494. if (!send_pubrel)
  495. ; /* only don't send ack on MQTT v5 PUBREC error, otherwise send ack under all circumstances because MQTT state can get out of step */
  496. else if (!Socket_noPendingWrites(sock))
  497. rc = MQTTProtocol_queueAck(client, PUBREL, pubrec->msgId);
  498. else
  499. rc = MQTTPacket_send_pubrel(pubrec->MQTTVersion, pubrec->msgId, 0, &client->net, client->clientID);
  500. if (pubrec->MQTTVersion >= MQTTVERSION_5)
  501. MQTTProperties_free(&pubrec->properties);
  502. free(pack);
  503. FUNC_EXIT_RC(rc);
  504. return rc;
  505. }
  506. /**
  507. * Process an incoming pubrel packet for a socket
  508. * @param pack pointer to the publish packet
  509. * @param sock the socket on which the packet was received
  510. * @return completion code
  511. */
  512. int MQTTProtocol_handlePubrels(void* pack, SOCKET sock)
  513. {
  514. Pubrel* pubrel = (Pubrel*)pack;
  515. Clients* client = NULL;
  516. int rc = TCPSOCKET_COMPLETE;
  517. FUNC_ENTRY;
  518. client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
  519. Log(LOG_PROTOCOL, 17, NULL, sock, client->clientID, pubrel->msgId);
  520. /* look for the message by message id in the records of inbound messages for this client */
  521. if (ListFindItem(client->inboundMsgs, &(pubrel->msgId), messageIDCompare) == NULL)
  522. {
  523. if (pubrel->header.bits.dup == 0)
  524. Log(TRACE_MIN, 3, NULL, "PUBREL", client->clientID, pubrel->msgId);
  525. }
  526. else
  527. {
  528. Messages* m = (Messages*)(client->inboundMsgs->current->content);
  529. if (m->qos != 2)
  530. Log(TRACE_MIN, 4, NULL, "PUBREL", client->clientID, pubrel->msgId, m->qos);
  531. else if (m->nextMessageType != PUBREL)
  532. Log(TRACE_MIN, 5, NULL, "PUBREL", client->clientID, pubrel->msgId);
  533. else
  534. {
  535. Publish publish;
  536. memset(&publish, '\0', sizeof(publish));
  537. publish.header.bits.qos = m->qos;
  538. publish.header.bits.retain = m->retain;
  539. publish.msgId = m->msgid;
  540. if (m->publish)
  541. {
  542. publish.topic = m->publish->topic;
  543. publish.topiclen = m->publish->topiclen;
  544. publish.payload = m->publish->payload;
  545. publish.payloadlen = m->publish->payloadlen;
  546. }
  547. publish.MQTTVersion = m->MQTTVersion;
  548. if (publish.MQTTVersion >= MQTTVERSION_5)
  549. publish.properties = m->properties;
  550. else
  551. Protocol_processPublication(&publish, client, 0); /* only for 3.1.1 and lower */
  552. #if !defined(NO_PERSISTENCE)
  553. rc += MQTTPersistence_remove(client,
  554. (m->MQTTVersion >= MQTTVERSION_5) ? PERSISTENCE_V5_PUBLISH_RECEIVED : PERSISTENCE_PUBLISH_RECEIVED,
  555. m->qos, pubrel->msgId);
  556. #endif
  557. if (m->MQTTVersion >= MQTTVERSION_5)
  558. MQTTProperties_free(&m->properties);
  559. if (m->publish)
  560. ListRemove(&(state.publications), m->publish);
  561. ListRemove(client->inboundMsgs, m);
  562. ++(state.msgs_received);
  563. }
  564. }
  565. /* Send ack under all circumstances because MQTT state can get out of step - this standard also says to do this */
  566. if (!Socket_noPendingWrites(sock))
  567. rc = MQTTProtocol_queueAck(client, PUBCOMP, pubrel->msgId);
  568. else
  569. rc = MQTTPacket_send_pubcomp(pubrel->MQTTVersion, pubrel->msgId, &client->net, client->clientID);
  570. if (pubrel->MQTTVersion >= MQTTVERSION_5)
  571. MQTTProperties_free(&pubrel->properties);
  572. free(pack);
  573. FUNC_EXIT_RC(rc);
  574. return rc;
  575. }
  576. /**
  577. * Process an incoming pubcomp packet for a socket
  578. * @param pack pointer to the publish packet
  579. * @param sock the socket on which the packet was received
  580. * @return completion code
  581. */
  582. int MQTTProtocol_handlePubcomps(void* pack, SOCKET sock, Publications** pubToRemove)
  583. {
  584. Pubcomp* pubcomp = (Pubcomp*)pack;
  585. Clients* client = NULL;
  586. int rc = TCPSOCKET_COMPLETE;
  587. FUNC_ENTRY;
  588. client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
  589. Log(LOG_PROTOCOL, 19, NULL, sock, client->clientID, pubcomp->msgId);
  590. /* look for the message by message id in the records of outbound messages for this client */
  591. if (ListFindItem(client->outboundMsgs, &(pubcomp->msgId), messageIDCompare) == NULL)
  592. {
  593. if (pubcomp->header.bits.dup == 0)
  594. Log(TRACE_MIN, 3, NULL, "PUBCOMP", client->clientID, pubcomp->msgId);
  595. }
  596. else
  597. {
  598. Messages* m = (Messages*)(client->outboundMsgs->current->content);
  599. if (m->qos != 2)
  600. Log(TRACE_MIN, 4, NULL, "PUBCOMP", client->clientID, pubcomp->msgId, m->qos);
  601. else
  602. {
  603. if (m->nextMessageType != PUBCOMP)
  604. Log(TRACE_MIN, 5, NULL, "PUBCOMP", client->clientID, pubcomp->msgId);
  605. else
  606. {
  607. Log(TRACE_MIN, 6, NULL, "PUBCOMP", client->clientID, pubcomp->msgId);
  608. #if !defined(NO_PERSISTENCE)
  609. rc = MQTTPersistence_remove(client,
  610. (m->MQTTVersion >= MQTTVERSION_5) ? PERSISTENCE_V5_PUBLISH_SENT : PERSISTENCE_PUBLISH_SENT,
  611. m->qos, pubcomp->msgId);
  612. if (rc != 0)
  613. Log(LOG_ERROR, -1, "Error removing PUBCOMP for client id %s msgid %d from persistence", client->clientID, pubcomp->msgId);
  614. #endif
  615. if (pubToRemove != NULL)
  616. *pubToRemove = m->publish;
  617. else
  618. MQTTProtocol_removePublication(m->publish);
  619. if (m->MQTTVersion >= MQTTVERSION_5)
  620. MQTTProperties_free(&m->properties);
  621. ListRemove(client->outboundMsgs, m);
  622. (++state.msgs_sent);
  623. }
  624. }
  625. }
  626. if (pubcomp->MQTTVersion >= MQTTVERSION_5)
  627. MQTTProperties_free(&pubcomp->properties);
  628. free(pack);
  629. FUNC_EXIT_RC(rc);
  630. return rc;
  631. }
  632. /**
  633. * MQTT protocol keepAlive processing. Sends PINGREQ packets as required.
  634. * @param now current time
  635. */
  636. void MQTTProtocol_keepalive(START_TIME_TYPE now)
  637. {
  638. ListElement* current = NULL;
  639. FUNC_ENTRY;
  640. ListNextElement(bstate->clients, &current);
  641. while (current)
  642. {
  643. Clients* client = (Clients*)(current->content);
  644. ListNextElement(bstate->clients, &current);
  645. if (client->connected == 0 || client->keepAliveInterval == 0)
  646. continue;
  647. if (client->ping_outstanding == 1)
  648. {
  649. if (MQTTTime_difftime(now, client->net.lastPing) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1500) &&
  650. /* if last received is more recent, we could be receiving a large packet */
  651. MQTTTime_difftime(now, client->net.lastReceived) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1500))
  652. {
  653. Log(TRACE_PROTOCOL, -1, "PINGRESP not received in keepalive interval for client %s on socket %d, disconnecting", client->clientID, client->net.socket);
  654. MQTTProtocol_closeSession(client, 1);
  655. }
  656. }
  657. else if (client->ping_due == 1 &&
  658. (MQTTTime_difftime(now, client->ping_due_time) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1500)))
  659. {
  660. /* if the last received time is more recent than the ping due time, we could be receiving a large packet,
  661. * preventing the PINGRESP being received */
  662. if (MQTTTime_difftime(now, client->ping_due_time) <= MQTTTime_difftime(now, client->net.lastReceived))
  663. {
  664. /* ping still outstanding after keep alive interval, so close session */
  665. Log(TRACE_PROTOCOL, -1, "PINGREQ still outstanding for client %s on socket %d, disconnecting", client->clientID, client->net.socket);
  666. MQTTProtocol_closeSession(client, 1);
  667. }
  668. }
  669. else if (MQTTTime_difftime(now, client->net.lastSent) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1000))
  670. /* the time since we last sent a packet, or part of a packet has exceeded the keep alive, so we need to send a ping */
  671. {
  672. if (Socket_noPendingWrites(client->net.socket))
  673. {
  674. if (MQTTPacket_send_pingreq(&client->net, client->clientID) != TCPSOCKET_COMPLETE)
  675. {
  676. Log(TRACE_PROTOCOL, -1, "Error sending PINGREQ for client %s on socket %d, disconnecting", client->clientID, client->net.socket);
  677. MQTTProtocol_closeSession(client, 1);
  678. }
  679. else
  680. {
  681. client->ping_due = 0;
  682. client->net.lastPing = now;
  683. client->ping_outstanding = 1;
  684. }
  685. }
  686. else if (client->ping_due == 0)
  687. {
  688. Log(TRACE_PROTOCOL, -1, "Couldn't send PINGREQ for client %s on socket %d, noting",
  689. client->clientID, client->net.socket);
  690. client->ping_due = 1;
  691. client->ping_due_time = now;
  692. }
  693. }
  694. else if (MQTTTime_difftime(now, client->net.lastReceived) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1000))
  695. /* the time since we last received any data has exceeded the keep alive, so we can send a ping to see if the server is alive */
  696. {
  697. /* Check that no writes are pending for the socket. If there are, forget about it, as this PING use is optional */
  698. if (Socket_noPendingWrites(client->net.socket))
  699. {
  700. if (MQTTPacket_send_pingreq(&client->net, client->clientID) != TCPSOCKET_COMPLETE)
  701. {
  702. Log(TRACE_PROTOCOL, -1, "Error sending PINGREQ for client %s on socket %d, disconnecting", client->clientID, client->net.socket);
  703. MQTTProtocol_closeSession(client, 1);
  704. }
  705. else
  706. {
  707. client->ping_due = 0;
  708. client->net.lastPing = now;
  709. client->ping_outstanding = 1;
  710. }
  711. }
  712. }
  713. }
  714. FUNC_EXIT;
  715. }
  716. /**
  717. * MQTT retry processing per client
  718. * @param now current time
  719. * @param client - the client to which to apply the retry processing
  720. * @param regardless boolean - retry packets regardless of retry interval (used on reconnect)
  721. */
  722. static void MQTTProtocol_retries(START_TIME_TYPE now, Clients* client, int regardless)
  723. {
  724. ListElement* outcurrent = NULL;
  725. FUNC_ENTRY;
  726. if (!regardless && client->retryInterval <= 0 && /* 0 or -ive retryInterval turns off retry except on reconnect */
  727. client->connect_sent == client->connect_count)
  728. goto exit;
  729. if (regardless)
  730. client->connect_count = client->outboundMsgs->count; /* remember the number of messages to retry on connect */
  731. else if (client->connect_sent < client->connect_count) /* continue a connect retry which didn't complete first time around */
  732. regardless = 1;
  733. while (client && ListNextElement(client->outboundMsgs, &outcurrent) &&
  734. client->connected && client->good && /* client is connected and has no errors */
  735. Socket_noPendingWrites(client->net.socket)) /* there aren't any previous packets still stacked up on the socket */
  736. {
  737. Messages* m = (Messages*)(outcurrent->content);
  738. if (regardless || MQTTTime_difftime(now, m->lastTouch) > (DIFF_TIME_TYPE)(max(client->retryInterval, 10) * 1000))
  739. {
  740. if (regardless)
  741. ++client->connect_sent;
  742. if (m->qos == 1 || (m->qos == 2 && m->nextMessageType == PUBREC))
  743. {
  744. Publish publish;
  745. int rc;
  746. Log(TRACE_MIN, 7, NULL, "PUBLISH", client->clientID, client->net.socket, m->msgid);
  747. publish.msgId = m->msgid;
  748. publish.topic = m->publish->topic;
  749. publish.payload = m->publish->payload;
  750. publish.payloadlen = m->publish->payloadlen;
  751. publish.properties = m->properties;
  752. publish.MQTTVersion = m->MQTTVersion;
  753. memcpy(publish.mask, m->publish->mask, sizeof(publish.mask));
  754. rc = MQTTPacket_send_publish(&publish, 1, m->qos, m->retain, &client->net, client->clientID);
  755. memcpy(m->publish->mask, publish.mask, sizeof(m->publish->mask)); /* store websocket mask used in send */
  756. if (rc == SOCKET_ERROR)
  757. {
  758. client->good = 0;
  759. Log(TRACE_PROTOCOL, 29, NULL, client->clientID, client->net.socket,
  760. Socket_getpeer(client->net.socket));
  761. MQTTProtocol_closeSession(client, 1);
  762. client = NULL;
  763. }
  764. else
  765. {
  766. if (m->qos == 0 && rc == TCPSOCKET_INTERRUPTED)
  767. MQTTProtocol_storeQoS0(client, &publish);
  768. m->lastTouch = MQTTTime_now();
  769. }
  770. }
  771. else if (m->qos && m->nextMessageType == PUBCOMP)
  772. {
  773. Log(TRACE_MIN, 7, NULL, "PUBREL", client->clientID, client->net.socket, m->msgid);
  774. if (MQTTPacket_send_pubrel(m->MQTTVersion, m->msgid, 0, &client->net, client->clientID) != TCPSOCKET_COMPLETE)
  775. {
  776. client->good = 0;
  777. Log(TRACE_PROTOCOL, 29, NULL, client->clientID, client->net.socket,
  778. Socket_getpeer(client->net.socket));
  779. MQTTProtocol_closeSession(client, 1);
  780. client = NULL;
  781. }
  782. else
  783. m->lastTouch = MQTTTime_now();
  784. }
  785. }
  786. }
  787. exit:
  788. FUNC_EXIT;
  789. }
  790. /**
  791. * Queue an ack message. This is used when the socket is full (e.g. SSL_ERROR_WANT_WRITE).
  792. * To be completed/cleared when the socket is no longer full
  793. * @param client the client that received the published message
  794. * @param ackType the type of ack to send
  795. * @param msgId the msg id of the message we are acknowledging
  796. * @return the completion code
  797. */
  798. int MQTTProtocol_queueAck(Clients* client, int ackType, int msgId)
  799. {
  800. int rc = 0;
  801. AckRequest* ackReq = NULL;
  802. FUNC_ENTRY;
  803. ackReq = malloc(sizeof(AckRequest));
  804. if (!ackReq)
  805. rc = PAHO_MEMORY_ERROR;
  806. else
  807. {
  808. ackReq->messageId = msgId;
  809. ackReq->ackType = ackType;
  810. ListAppend(client->outboundQueue, ackReq, sizeof(AckRequest));
  811. }
  812. FUNC_EXIT_RC(rc);
  813. return rc;
  814. }
  815. /**
  816. * MQTT retry protocol and socket pending writes processing.
  817. * @param now current time
  818. * @param doRetry boolean - retries as well as pending writes?
  819. * @param regardless boolean - retry packets regardless of retry interval (used on reconnect)
  820. */
  821. void MQTTProtocol_retry(START_TIME_TYPE now, int doRetry, int regardless)
  822. {
  823. ListElement* current = NULL;
  824. FUNC_ENTRY;
  825. ListNextElement(bstate->clients, &current);
  826. /* look through the outbound message list of each client, checking to see if a retry is necessary */
  827. while (current)
  828. {
  829. Clients* client = (Clients*)(current->content);
  830. ListNextElement(bstate->clients, &current);
  831. if (client->connected == 0)
  832. continue;
  833. if (client->good == 0)
  834. {
  835. MQTTProtocol_closeSession(client, 1);
  836. continue;
  837. }
  838. if (Socket_noPendingWrites(client->net.socket) == 0)
  839. continue;
  840. if (doRetry)
  841. MQTTProtocol_retries(now, client, regardless);
  842. }
  843. FUNC_EXIT;
  844. }
  845. /**
  846. * Free a client structure
  847. * @param client the client data to free
  848. */
  849. void MQTTProtocol_freeClient(Clients* client)
  850. {
  851. FUNC_ENTRY;
  852. /* free up pending message lists here, and any other allocated data */
  853. MQTTProtocol_freeMessageList(client->outboundMsgs);
  854. MQTTProtocol_freeMessageList(client->inboundMsgs);
  855. ListFree(client->messageQueue);
  856. ListFree(client->outboundQueue);
  857. free(client->clientID);
  858. client->clientID = NULL;
  859. if (client->will)
  860. {
  861. free(client->will->payload);
  862. free(client->will->topic);
  863. free(client->will);
  864. client->will = NULL;
  865. }
  866. if (client->username)
  867. free((void*)client->username);
  868. if (client->password)
  869. free((void*)client->password);
  870. if (client->httpProxy)
  871. free(client->httpProxy);
  872. if (client->httpsProxy)
  873. free(client->httpsProxy);
  874. if (client->net.http_proxy_auth)
  875. free(client->net.http_proxy_auth);
  876. #if defined(OPENSSL)
  877. if (client->net.https_proxy_auth)
  878. free(client->net.https_proxy_auth);
  879. if (client->sslopts)
  880. {
  881. if (client->sslopts->trustStore)
  882. free((void*)client->sslopts->trustStore);
  883. if (client->sslopts->keyStore)
  884. free((void*)client->sslopts->keyStore);
  885. if (client->sslopts->privateKey)
  886. free((void*)client->sslopts->privateKey);
  887. if (client->sslopts->privateKeyPassword)
  888. free((void*)client->sslopts->privateKeyPassword);
  889. if (client->sslopts->enabledCipherSuites)
  890. free((void*)client->sslopts->enabledCipherSuites);
  891. if (client->sslopts->struct_version >= 2)
  892. {
  893. if (client->sslopts->CApath)
  894. free((void*)client->sslopts->CApath);
  895. }
  896. if (client->sslopts->struct_version >= 5)
  897. {
  898. if (client->sslopts->protos)
  899. free((void*)client->sslopts->protos);
  900. }
  901. free(client->sslopts);
  902. client->sslopts = NULL;
  903. }
  904. #endif
  905. /* don't free the client structure itself... this is done elsewhere */
  906. FUNC_EXIT;
  907. }
  908. /**
  909. * Empty a message list, leaving it able to accept new messages
  910. * @param msgList the message list to empty
  911. */
  912. void MQTTProtocol_emptyMessageList(List* msgList)
  913. {
  914. ListElement* current = NULL;
  915. FUNC_ENTRY;
  916. while (ListNextElement(msgList, &current))
  917. {
  918. Messages* m = (Messages*)(current->content);
  919. MQTTProtocol_removePublication(m->publish);
  920. if (m->MQTTVersion >= MQTTVERSION_5)
  921. MQTTProperties_free(&m->properties);
  922. }
  923. ListEmpty(msgList);
  924. FUNC_EXIT;
  925. }
  926. /**
  927. * Empty and free up all storage used by a message list
  928. * @param msgList the message list to empty and free
  929. */
  930. void MQTTProtocol_freeMessageList(List* msgList)
  931. {
  932. FUNC_ENTRY;
  933. MQTTProtocol_emptyMessageList(msgList);
  934. ListFree(msgList);
  935. FUNC_EXIT;
  936. }
  937. /**
  938. * Callback that is invoked when the socket is available for writing.
  939. * This is the last attempt made to acknowledge a message. Failures that
  940. * occur here are ignored.
  941. * @param socket the socket that is available for writing
  942. */
  943. void MQTTProtocol_writeAvailable(SOCKET socket)
  944. {
  945. Clients* client = NULL;
  946. ListElement* current = NULL;
  947. int rc = 0;
  948. FUNC_ENTRY;
  949. client = (Clients*)(ListFindItem(bstate->clients, &socket, clientSocketCompare)->content);
  950. current = NULL;
  951. while (ListNextElement(client->outboundQueue, &current) && rc == 0)
  952. {
  953. AckRequest* ackReq = (AckRequest*)(current->content);
  954. switch (ackReq->ackType)
  955. {
  956. case PUBACK:
  957. rc = MQTTPacket_send_puback(client->MQTTVersion, ackReq->messageId, &client->net, client->clientID);
  958. break;
  959. case PUBREC:
  960. rc = MQTTPacket_send_pubrec(client->MQTTVersion, ackReq->messageId, &client->net, client->clientID);
  961. break;
  962. case PUBREL:
  963. rc = MQTTPacket_send_pubrel(client->MQTTVersion, ackReq->messageId, 0, &client->net, client->clientID);
  964. break;
  965. case PUBCOMP:
  966. rc = MQTTPacket_send_pubcomp(client->MQTTVersion, ackReq->messageId, &client->net, client->clientID);
  967. break;
  968. default:
  969. Log(LOG_ERROR, -1, "unknown ACK type %d, dropping msg", ackReq->ackType);
  970. break;
  971. }
  972. }
  973. ListEmpty(client->outboundQueue);
  974. FUNC_EXIT_RC(rc);
  975. }
  976. /**
  977. * Copy no more than dest_size -1 characters from the string pointed to by src to the array pointed to by dest.
  978. * The destination string will always be null-terminated.
  979. * @param dest the array which characters copy to
  980. * @param src the source string which characters copy from
  981. * @param dest_size the size of the memory pointed to by dest: copy no more than this -1 (allow for null). Must be >= 1
  982. * @return the destination string pointer
  983. */
  984. char* MQTTStrncpy(char *dest, const char *src, size_t dest_size)
  985. {
  986. size_t count = dest_size;
  987. char *temp = dest;
  988. FUNC_ENTRY;
  989. if (dest_size < strlen(src))
  990. Log(TRACE_MIN, -1, "the src string is truncated");
  991. /* We must copy only the first (dest_size - 1) bytes */
  992. while (count > 1 && (*temp++ = *src++))
  993. count--;
  994. *temp = '\0';
  995. FUNC_EXIT;
  996. return dest;
  997. }
  998. /**
  999. * Duplicate a string, safely, allocating space on the heap
  1000. * @param src the source string which characters copy from
  1001. * @return the duplicated, allocated string
  1002. */
  1003. char* MQTTStrdup(const char* src)
  1004. {
  1005. size_t mlen = strlen(src) + 1;
  1006. char* temp = malloc(mlen);
  1007. if (temp)
  1008. MQTTStrncpy(temp, src, mlen);
  1009. else
  1010. Log(LOG_ERROR, -1, "memory allocation error in MQTTStrdup");
  1011. return temp;
  1012. }