MQTTAsyncUtils.c 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2022 IBM Corp., Ian Craggs and others
  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 implementation and documentation
  15. * Sven Gambel - add generic proxy support
  16. *******************************************************************************/
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #if !defined(_WIN32) && !defined(_WIN64)
  20. #include <sys/time.h>
  21. #endif
  22. #if !defined(NO_PERSISTENCE)
  23. #include "MQTTPersistence.h"
  24. #endif
  25. #include "MQTTAsync.h"
  26. #include "MQTTAsyncUtils.h"
  27. #include "utf-8.h"
  28. #include "MQTTProtocol.h"
  29. #include "MQTTProtocolOut.h"
  30. #include "Thread.h"
  31. #include "SocketBuffer.h"
  32. #include "StackTrace.h"
  33. #include "Heap.h"
  34. #include "OsWrapper.h"
  35. #include "WebSocket.h"
  36. #include "Proxy.h"
  37. static int clientSockCompare(void* a, void* b);
  38. static int MQTTAsync_checkConn(MQTTAsync_command* command, MQTTAsyncs* client);
  39. #if !defined(NO_PERSISTENCE)
  40. static int MQTTAsync_unpersistCommand(MQTTAsync_queuedCommand* qcmd);
  41. static int MQTTAsync_persistCommand(MQTTAsync_queuedCommand* qcmd);
  42. static MQTTAsync_queuedCommand* MQTTAsync_restoreCommand(char* buffer, int buflen, int MQTTVersion, MQTTAsync_queuedCommand*);
  43. #endif
  44. static void MQTTAsync_startConnectRetry(MQTTAsyncs* m);
  45. static void MQTTAsync_checkDisconnect(MQTTAsync handle, MQTTAsync_command* command);
  46. static void MQTTProtocol_checkPendingWrites(void);
  47. static void MQTTAsync_freeCommand1(MQTTAsync_queuedCommand *command);
  48. static void MQTTAsync_freeCommand(MQTTAsync_queuedCommand *command);
  49. static int MQTTAsync_processCommand(void);
  50. static void MQTTAsync_checkTimeouts(void);
  51. static int MQTTAsync_completeConnection(MQTTAsyncs* m, Connack* connack);
  52. static void MQTTAsync_stop(void);
  53. static void MQTTAsync_closeOnly(Clients* client, enum MQTTReasonCodes reasonCode, MQTTProperties* props);
  54. static int clientStructCompare(void* a, void* b);
  55. static int MQTTAsync_cleanSession(Clients* client);
  56. static int MQTTAsync_deliverMessage(MQTTAsyncs* m, char* topicName, size_t topicLen, MQTTAsync_message* mm);
  57. static int MQTTAsync_disconnect_internal(MQTTAsync handle, int timeout);
  58. static int cmdMessageIDCompare(void* a, void* b);
  59. static void MQTTAsync_retry(void);
  60. static MQTTPacket* MQTTAsync_cycle(SOCKET* sock, unsigned long timeout, int* rc);
  61. static int MQTTAsync_connecting(MQTTAsyncs* m);
  62. extern MQTTProtocol state; /* defined in MQTTAsync.c */
  63. extern ClientStates* bstate; /* defined in MQTTAsync.c */
  64. extern enum MQTTAsync_threadStates sendThread_state;
  65. extern enum MQTTAsync_threadStates receiveThread_state;
  66. extern thread_id_type sendThread_id,
  67. receiveThread_id;
  68. extern volatile int global_initialized;
  69. extern List* MQTTAsync_handles;
  70. extern List* MQTTAsync_commands;
  71. extern int MQTTAsync_tostop;
  72. #if defined(_WIN32) || defined(_WIN64)
  73. #if defined(_MSC_VER) && _MSC_VER < 1900
  74. #define snprintf _snprintf
  75. #endif
  76. extern mutex_type mqttasync_mutex;
  77. extern mutex_type socket_mutex;
  78. extern mutex_type mqttcommand_mutex;
  79. extern sem_type send_sem;
  80. #if !defined(NO_HEAP_TRACKING)
  81. extern mutex_type stack_mutex;
  82. extern mutex_type heap_mutex;
  83. #endif
  84. extern mutex_type log_mutex;
  85. #else
  86. extern mutex_type mqttasync_mutex;
  87. extern mutex_type socket_mutex;
  88. extern mutex_type mqttcommand_mutex;
  89. extern cond_type send_cond;
  90. #endif
  91. #if !defined(min)
  92. #define min(a, b) (((a) < (b)) ? (a) : (b))
  93. #endif
  94. void MQTTAsync_sleep(long milliseconds)
  95. {
  96. FUNC_ENTRY;
  97. #if defined(_WIN32) || defined(_WIN64)
  98. Sleep(milliseconds);
  99. #else
  100. usleep(milliseconds*1000);
  101. #endif
  102. FUNC_EXIT;
  103. }
  104. /* Add random amount of jitter for exponential backoff on retry
  105. Jitter value will be +/- 20% of "base" interval, including max interval
  106. https://www.awsarchitectureblog.com/2015/03/backoff.html
  107. http://ee.lbl.gov/papers/sync_94.pdf */
  108. int MQTTAsync_randomJitter(int currentIntervalBase, int minInterval, int maxInterval)
  109. {
  110. const int max_sleep = (int)(min(maxInterval, currentIntervalBase) * 1.2); // (e.g. 72 if base > 60)
  111. const int min_sleep = (int)(max(minInterval, currentIntervalBase) / 1.2); // (e.g. 48 if base > 60)
  112. if (min_sleep >= max_sleep) // shouldn't happen, but just in case
  113. {
  114. return min_sleep;
  115. }
  116. {
  117. /* random_between(min_sleep, max_sleep)
  118. http://stackoverflow.com/questions/2509679/how-to-generate-a-random-number-from-within-a-range */
  119. int r;
  120. int range = max_sleep - min_sleep + 1;
  121. const int buckets = RAND_MAX / range;
  122. const int limit = buckets * range;
  123. /* Create equal size buckets all in a row, then fire randomly towards
  124. * the buckets until you land in one of them. All buckets are equally
  125. * likely. If you land off the end of the line of buckets, try again. */
  126. do
  127. {
  128. r = rand();
  129. } while (r >= limit);
  130. {
  131. const int randResult = r / buckets;
  132. return min_sleep + randResult;
  133. }
  134. }
  135. }
  136. /**
  137. * List callback function for comparing clients by socket
  138. * @param a first integer value
  139. * @param b second integer value
  140. * @return boolean indicating whether a and b are equal
  141. */
  142. static int clientSockCompare(void* a, void* b)
  143. {
  144. MQTTAsyncs* m = (MQTTAsyncs*)a;
  145. return m->c->net.socket == *(int*)b;
  146. }
  147. void MQTTAsync_lock_mutex(mutex_type amutex)
  148. {
  149. int rc = Thread_lock_mutex(amutex);
  150. if (rc != 0)
  151. Log(LOG_ERROR, 0, "Error %s locking mutex", strerror(rc));
  152. }
  153. void MQTTAsync_unlock_mutex(mutex_type amutex)
  154. {
  155. int rc = Thread_unlock_mutex(amutex);
  156. if (rc != 0)
  157. Log(LOG_ERROR, 0, "Error %s unlocking mutex", strerror(rc));
  158. }
  159. /*
  160. Check whether there are any more connect options. If not then we are finished
  161. with connect attempts.
  162. */
  163. static int MQTTAsync_checkConn(MQTTAsync_command* command, MQTTAsyncs* client)
  164. {
  165. int rc;
  166. FUNC_ENTRY;
  167. rc = command->details.conn.currentURI + 1 < client->serverURIcount ||
  168. (command->details.conn.MQTTVersion == 4 && client->c->MQTTVersion == MQTTVERSION_DEFAULT);
  169. FUNC_EXIT_RC(rc);
  170. return rc;
  171. }
  172. void MQTTAsync_terminate(void)
  173. {
  174. FUNC_ENTRY;
  175. MQTTAsync_stop();
  176. /* don't destroy global data if a new client was created while waiting for background threads to terminate */
  177. if (global_initialized && bstate->clients->count == 0)
  178. {
  179. ListElement* elem = NULL;
  180. ListFree(bstate->clients);
  181. ListFree(MQTTAsync_handles);
  182. while (ListNextElement(MQTTAsync_commands, &elem))
  183. MQTTAsync_freeCommand1((MQTTAsync_queuedCommand*)(elem->content));
  184. ListFree(MQTTAsync_commands);
  185. MQTTAsync_handles = NULL;
  186. WebSocket_terminate();
  187. #if !defined(NO_HEAP_TRACKING)
  188. Heap_terminate();
  189. #endif
  190. Log_terminate();
  191. global_initialized = 0;
  192. }
  193. FUNC_EXIT;
  194. }
  195. #if !defined(NO_PERSISTENCE)
  196. static int MQTTAsync_unpersistCommand(MQTTAsync_queuedCommand* qcmd)
  197. {
  198. int rc = 0;
  199. char key[PERSISTENCE_MAX_KEY_LENGTH + 1];
  200. int chars = 0;
  201. FUNC_ENTRY;
  202. if (qcmd->client->c->MQTTVersion >= MQTTVERSION_5)
  203. chars = snprintf(key, sizeof(key), "%s%u", PERSISTENCE_V5_COMMAND_KEY, qcmd->seqno);
  204. else
  205. chars = snprintf(key, sizeof(key), "%s%u", PERSISTENCE_COMMAND_KEY, qcmd->seqno);
  206. if (chars >= sizeof(key))
  207. {
  208. rc = MQTTASYNC_PERSISTENCE_ERROR;
  209. Log(LOG_ERROR, 0, "Error writing %d chars with snprintf", chars);
  210. }
  211. else if ((rc = qcmd->client->c->persistence->premove(qcmd->client->c->phandle, key)) != 0)
  212. Log(LOG_ERROR, 0, "Error %d removing command from persistence", rc);
  213. FUNC_EXIT_RC(rc);
  214. return rc;
  215. }
  216. static int MQTTAsync_persistCommand(MQTTAsync_queuedCommand* qcmd)
  217. {
  218. int rc = 0;
  219. MQTTAsyncs* aclient = qcmd->client;
  220. MQTTAsync_command* command = &qcmd->command;
  221. int* lens = NULL;
  222. void** bufs = NULL;
  223. int bufindex = 0, i, nbufs = 0;
  224. char key[PERSISTENCE_MAX_KEY_LENGTH + 1];
  225. int chars = 0; /* number of chars from snprintf */
  226. int props_allocated = 0;
  227. int process = 1;
  228. int multiplier = 2; /* default value 2 for MQTTVERSION < 5 */
  229. FUNC_ENTRY;
  230. switch (command->type)
  231. {
  232. case SUBSCRIBE:
  233. multiplier = (aclient->c->MQTTVersion >= MQTTVERSION_5) ? 3 : 2;
  234. nbufs = ((aclient->c->MQTTVersion >= MQTTVERSION_5) ? 4 : 3) +
  235. (command->details.sub.count * multiplier);
  236. if (((lens = (int*)malloc(nbufs * sizeof(int))) == NULL) ||
  237. ((bufs = malloc(nbufs * sizeof(char *))) == NULL))
  238. {
  239. rc = PAHO_MEMORY_ERROR;
  240. goto exit;
  241. }
  242. bufs[bufindex] = &command->type;
  243. lens[bufindex++] = sizeof(command->type);
  244. bufs[bufindex] = &command->token;
  245. lens[bufindex++] = sizeof(command->token);
  246. bufs[bufindex] = &command->details.sub.count;
  247. lens[bufindex++] = sizeof(command->details.sub.count);
  248. for (i = 0; i < command->details.sub.count; ++i)
  249. {
  250. bufs[bufindex] = command->details.sub.topics[i];
  251. lens[bufindex++] = (int)strlen(command->details.sub.topics[i]) + 1;
  252. bufs[bufindex] = &command->details.sub.qoss[i];
  253. lens[bufindex++] = sizeof(command->details.sub.qoss[i]);
  254. if (aclient->c->MQTTVersion >= MQTTVERSION_5)
  255. {
  256. if (command->details.sub.count == 1)
  257. {
  258. bufs[bufindex] = &command->details.sub.opts;
  259. lens[bufindex++] = sizeof(command->details.sub.opts);
  260. }
  261. else
  262. {
  263. bufs[bufindex] = &command->details.sub.optlist[i];
  264. lens[bufindex++] = sizeof(command->details.sub.optlist[i]);
  265. }
  266. }
  267. }
  268. break;
  269. case UNSUBSCRIBE:
  270. nbufs = ((aclient->c->MQTTVersion >= MQTTVERSION_5) ? 4 : 3) +
  271. command->details.unsub.count;
  272. if (((lens = (int*)malloc(nbufs * sizeof(int))) == NULL) ||
  273. ((bufs = malloc(nbufs * sizeof(char *))) == NULL))
  274. {
  275. rc = PAHO_MEMORY_ERROR;
  276. goto exit;
  277. }
  278. bufs[bufindex] = &command->type;
  279. lens[bufindex++] = sizeof(command->type);
  280. bufs[bufindex] = &command->token;
  281. lens[bufindex++] = sizeof(command->token);
  282. bufs[bufindex] = &command->details.unsub.count;
  283. lens[bufindex++] = sizeof(command->details.unsub.count);
  284. for (i = 0; i < command->details.unsub.count; ++i)
  285. {
  286. bufs[bufindex] = command->details.unsub.topics[i];
  287. lens[bufindex++] = (int)strlen(command->details.unsub.topics[i]) + 1;
  288. }
  289. break;
  290. case PUBLISH:
  291. nbufs = (aclient->c->MQTTVersion >= MQTTVERSION_5) ? 8 : 7;
  292. if (((lens = (int*)malloc(nbufs * sizeof(int))) == NULL) ||
  293. ((bufs = malloc(nbufs * sizeof(char *))) == NULL))
  294. {
  295. rc = PAHO_MEMORY_ERROR;
  296. goto exit;
  297. }
  298. bufs[bufindex] = &command->type;
  299. lens[bufindex++] = sizeof(command->type);
  300. bufs[bufindex] = &command->token;
  301. lens[bufindex++] = sizeof(command->token);
  302. bufs[bufindex] = command->details.pub.destinationName;
  303. lens[bufindex++] = (int)strlen(command->details.pub.destinationName) + 1;
  304. bufs[bufindex] = &command->details.pub.payloadlen;
  305. lens[bufindex++] = sizeof(command->details.pub.payloadlen);
  306. bufs[bufindex] = command->details.pub.payload;
  307. lens[bufindex++] = command->details.pub.payloadlen;
  308. bufs[bufindex] = &command->details.pub.qos;
  309. lens[bufindex++] = sizeof(command->details.pub.qos);
  310. bufs[bufindex] = &command->details.pub.retained;
  311. lens[bufindex++] = sizeof(command->details.pub.retained);
  312. break;
  313. default:
  314. process = 0;
  315. break;
  316. }
  317. /*
  318. * Increment the command sequence number. Don't exceed the maximum value allowed
  319. * by the value PERSISTENCE_MAX_KEY_LENGTH minus the max prefix string length
  320. */
  321. if (++aclient->command_seqno == PERSISTENCE_SEQNO_LIMIT)
  322. aclient->command_seqno = 0;
  323. if (aclient->c->MQTTVersion >= MQTTVERSION_5 && process) /* persist properties */
  324. {
  325. int temp_len = 0;
  326. char* ptr = NULL;
  327. temp_len = MQTTProperties_len(&command->properties);
  328. if ((ptr = bufs[bufindex] = malloc(temp_len)) == NULL)
  329. {
  330. rc = PAHO_MEMORY_ERROR;
  331. goto exit;
  332. }
  333. props_allocated = bufindex;
  334. rc = MQTTProperties_write(&ptr, &command->properties);
  335. lens[bufindex++] = temp_len;
  336. chars = snprintf(key, sizeof(key), "%s%u", PERSISTENCE_V5_COMMAND_KEY, aclient->command_seqno);
  337. }
  338. else
  339. chars = snprintf(key, sizeof(key), "%s%u", PERSISTENCE_COMMAND_KEY, aclient->command_seqno);
  340. if (chars >= sizeof(key))
  341. {
  342. Log(LOG_ERROR, 0, "Error writing %d chars with snprintf", chars);
  343. goto exit;
  344. }
  345. if (nbufs > 0)
  346. {
  347. if (aclient->c->beforeWrite)
  348. rc = aclient->c->beforeWrite(aclient->c->beforeWrite_context, nbufs, (char**)bufs, lens);
  349. if ((rc = aclient->c->persistence->pput(aclient->c->phandle, key, nbufs, (char**)bufs, lens)) != 0)
  350. Log(LOG_ERROR, 0, "Error persisting command, rc %d", rc);
  351. qcmd->seqno = aclient->command_seqno;
  352. }
  353. exit:
  354. if (props_allocated > 0)
  355. free(bufs[props_allocated]);
  356. if (lens)
  357. free(lens);
  358. if (bufs)
  359. free(bufs);
  360. FUNC_EXIT_RC(rc);
  361. return rc;
  362. }
  363. static MQTTAsync_queuedCommand* MQTTAsync_restoreCommand(char* buffer, int buflen, int MQTTVersion, MQTTAsync_queuedCommand* qcommand)
  364. {
  365. MQTTAsync_command* command = NULL;
  366. char* ptr = buffer;
  367. int i;
  368. size_t data_size;
  369. char* endpos = &buffer[buflen];
  370. FUNC_ENTRY;
  371. if (buflen == 0)
  372. {
  373. qcommand = NULL;
  374. goto exit;
  375. }
  376. if (qcommand == NULL)
  377. {
  378. if ((qcommand = malloc(sizeof(MQTTAsync_queuedCommand))) == NULL)
  379. goto exit;
  380. memset(qcommand, '\0', sizeof(MQTTAsync_queuedCommand));
  381. qcommand->not_restored = 1; /* don't restore all the command on the first call */
  382. }
  383. else
  384. qcommand->not_restored = 0;
  385. command = &qcommand->command;
  386. if (&ptr[sizeof(int) + sizeof(MQTTAsync_token)] > endpos)
  387. goto error_exit;
  388. command->type = *(int*)ptr;
  389. ptr += sizeof(int);
  390. command->token = *(MQTTAsync_token*)ptr;
  391. ptr += sizeof(MQTTAsync_token);
  392. switch (command->type)
  393. {
  394. case SUBSCRIBE:
  395. if (qcommand->not_restored == 1)
  396. break;
  397. if (&ptr[sizeof(int)] > endpos)
  398. goto error_exit;
  399. command->details.sub.count = *(int*)ptr;
  400. ptr += sizeof(int);
  401. if (command->details.sub.count > 0)
  402. {
  403. if ((command->details.sub.topics = (char **)malloc(sizeof(char *) * command->details.sub.count)) == NULL)
  404. goto error_exit;
  405. if ((command->details.sub.qoss = (int *)malloc(sizeof(int) * command->details.sub.count)) == NULL)
  406. goto error_exit;
  407. if ((MQTTVersion >= MQTTVERSION_5))
  408. {
  409. if (command->details.sub.count > 1)
  410. {
  411. command->details.sub.optlist = (MQTTSubscribe_options*)malloc(sizeof(MQTTSubscribe_options) * command->details.sub.count);
  412. if (command->details.sub.optlist == NULL)
  413. goto error_exit;
  414. }
  415. }
  416. }
  417. for (i = 0; i < command->details.sub.count; ++i)
  418. {
  419. data_size = strnlen(ptr, endpos - ptr) + 1;
  420. if (data_size == endpos - ptr)
  421. goto error_exit; /* no null found */
  422. if ((command->details.sub.topics[i] = malloc(data_size)) == NULL)
  423. goto error_exit;
  424. strcpy(command->details.sub.topics[i], ptr);
  425. ptr += data_size;
  426. if (&ptr[sizeof(int)] > endpos)
  427. goto error_exit;
  428. command->details.sub.qoss[i] = *(int*)ptr;
  429. ptr += sizeof(int);
  430. if (MQTTVersion >= MQTTVERSION_5)
  431. {
  432. if (&ptr[sizeof(MQTTSubscribe_options)] > endpos)
  433. goto error_exit;
  434. if (command->details.sub.count == 1)
  435. {
  436. command->details.sub.opts = *(MQTTSubscribe_options*)ptr;
  437. ptr += sizeof(MQTTSubscribe_options);
  438. }
  439. else
  440. {
  441. command->details.sub.optlist[i] = *(MQTTSubscribe_options*)ptr;
  442. ptr += sizeof(MQTTSubscribe_options);
  443. }
  444. }
  445. }
  446. break;
  447. case UNSUBSCRIBE:
  448. if (qcommand->not_restored == 1)
  449. break;
  450. if (&ptr[sizeof(int)] > endpos)
  451. goto error_exit;
  452. command->details.unsub.count = *(int*)ptr;
  453. ptr += sizeof(int);
  454. if (command->details.unsub.count > 0)
  455. {
  456. command->details.unsub.topics = (char **)malloc(sizeof(char *) * command->details.unsub.count);
  457. if (command->details.unsub.topics == NULL)
  458. goto error_exit;
  459. }
  460. for (i = 0; i < command->details.unsub.count; ++i)
  461. {
  462. data_size = strnlen(ptr, endpos - ptr) + 1;
  463. if (data_size == endpos - ptr)
  464. goto error_exit; /* no null found */
  465. if ((command->details.unsub.topics[i] = malloc(data_size)) == NULL)
  466. goto error_exit;
  467. strcpy(command->details.unsub.topics[i], ptr);
  468. ptr += data_size;
  469. }
  470. break;
  471. case PUBLISH:
  472. data_size = strnlen(ptr, endpos - ptr) + 1;
  473. if (data_size == endpos - ptr)
  474. goto error_exit; /* no null found */
  475. if (qcommand->not_restored == 0)
  476. {
  477. if ((command->details.pub.destinationName = malloc(data_size)) == NULL)
  478. goto error_exit;
  479. strcpy(command->details.pub.destinationName, ptr);
  480. }
  481. ptr += data_size;
  482. if (&ptr[sizeof(int)] > endpos)
  483. goto error_exit;
  484. command->details.pub.payloadlen = *(int*)ptr;
  485. ptr += sizeof(int);
  486. data_size = command->details.pub.payloadlen;
  487. if (&ptr[data_size] > endpos)
  488. goto error_exit;
  489. if (qcommand->not_restored == 0)
  490. {
  491. if ((command->details.pub.payload = malloc(data_size)) == NULL)
  492. goto error_exit;
  493. memcpy(command->details.pub.payload, ptr, data_size);
  494. }
  495. ptr += data_size;
  496. if (&ptr[sizeof(int)*2] > endpos)
  497. goto error_exit;
  498. command->details.pub.qos = *(int*)ptr;
  499. ptr += sizeof(int);
  500. command->details.pub.retained = *(int*)ptr;
  501. ptr += sizeof(int);
  502. break;
  503. default:
  504. goto error_exit;
  505. }
  506. if (qcommand != NULL && qcommand->not_restored == 0 && MQTTVersion >= MQTTVERSION_5 &&
  507. MQTTProperties_read(&command->properties, &ptr, buffer + buflen) != 1)
  508. {
  509. Log(LOG_ERROR, -1, "Error restoring properties from persistence");
  510. free(qcommand);
  511. qcommand = NULL;
  512. }
  513. goto exit;
  514. error_exit:
  515. free(qcommand);
  516. qcommand = NULL;
  517. exit:
  518. FUNC_EXIT;
  519. return qcommand;
  520. }
  521. static int cmpkeys(const void *p1, const void *p2)
  522. {
  523. int key1 = atoi(strchr(*(char * const *)p1, '-') + 1);
  524. int key2 = atoi(strchr(*(char * const *)p2, '-') + 1);
  525. return (key1 == key2) ? 0 : ((key1 < key2) ? -1 : 1);
  526. }
  527. int MQTTAsync_restoreCommands(MQTTAsyncs* client)
  528. {
  529. int rc = 0;
  530. char **msgkeys;
  531. int nkeys;
  532. int i = 0;
  533. Clients* c = client->c;
  534. int commands_restored = 0;
  535. FUNC_ENTRY;
  536. if (c->persistence && (rc = c->persistence->pkeys(c->phandle, &msgkeys, &nkeys)) == 0 && nkeys > 0)
  537. {
  538. /* let's have the sequence number array sorted */
  539. qsort(msgkeys, (size_t)nkeys, sizeof(char*), cmpkeys);
  540. while (rc == 0 && i < nkeys)
  541. {
  542. char *buffer = NULL;
  543. int buflen;
  544. if (strncmp(msgkeys[i], PERSISTENCE_COMMAND_KEY, strlen(PERSISTENCE_COMMAND_KEY)) != 0 &&
  545. strncmp(msgkeys[i], PERSISTENCE_V5_COMMAND_KEY, strlen(PERSISTENCE_V5_COMMAND_KEY)) != 0)
  546. {
  547. ;
  548. }
  549. else
  550. {
  551. MQTTAsync_queuedCommand* cmd = NULL;
  552. if ((rc = c->persistence->pget(c->phandle, msgkeys[i], &buffer, &buflen)) == 0 &&
  553. (c->afterRead == NULL || (rc = c->afterRead(c->afterRead_context, &buffer, &buflen)) == 0))
  554. {
  555. int MQTTVersion = (strncmp(msgkeys[i], PERSISTENCE_V5_COMMAND_KEY, strlen(PERSISTENCE_V5_COMMAND_KEY)) == 0)
  556. ? MQTTVERSION_5 : MQTTVERSION_3_1_1;
  557. cmd = MQTTAsync_restoreCommand(buffer, buflen, MQTTVersion, NULL);
  558. }
  559. if (cmd)
  560. {
  561. /* As the entire command is not restored on the first read to save memory, we temporarily store
  562. * the filename of the persisted command to be used when restoreCommand is called the second time.
  563. */
  564. cmd->key = malloc(strlen(msgkeys[i])+1);
  565. strcpy(cmd->key, msgkeys[i]);
  566. cmd->client = client;
  567. cmd->seqno = atoi(strchr(msgkeys[i], '-')+1); /* key format is tag'-'seqno */
  568. /* we can just append the commands to the list as they've already been sorted */
  569. ListAppend(MQTTAsync_commands, cmd, sizeof(MQTTAsync_queuedCommand));
  570. client->command_seqno = max(client->command_seqno, cmd->seqno);
  571. commands_restored++;
  572. if (cmd->command.type == PUBLISH)
  573. client->noBufferedMessages++;
  574. }
  575. }
  576. if (buffer)
  577. free(buffer);
  578. if (msgkeys[i])
  579. free(msgkeys[i]);
  580. i++;
  581. }
  582. if (msgkeys != NULL)
  583. free(msgkeys);
  584. }
  585. Log(TRACE_MINIMUM, -1, "%d commands restored for client %s", commands_restored, c->clientID);
  586. FUNC_EXIT_RC(rc);
  587. return rc;
  588. }
  589. int MQTTAsync_unpersistCommandsAndMessages(Clients* c)
  590. {
  591. int rc = 0;
  592. char **msgkeys;
  593. int nkeys;
  594. int i = 0;
  595. int messages_deleted = 0;
  596. FUNC_ENTRY;
  597. if (c->persistence && (rc = c->persistence->pkeys(c->phandle, &msgkeys, &nkeys)) == 0)
  598. {
  599. while (rc == 0 && i < nkeys)
  600. {
  601. if (strncmp(msgkeys[i], PERSISTENCE_COMMAND_KEY, strlen(PERSISTENCE_COMMAND_KEY)) == 0 ||
  602. strncmp(msgkeys[i], PERSISTENCE_V5_COMMAND_KEY, strlen(PERSISTENCE_V5_COMMAND_KEY)) == 0 ||
  603. strncmp(msgkeys[i], PERSISTENCE_QUEUE_KEY, strlen(PERSISTENCE_QUEUE_KEY)) == 0 ||
  604. strncmp(msgkeys[i], PERSISTENCE_V5_QUEUE_KEY, strlen(PERSISTENCE_V5_QUEUE_KEY)) == 0)
  605. {
  606. if ((rc = c->persistence->premove(c->phandle, msgkeys[i])) == 0)
  607. messages_deleted++;
  608. else
  609. Log(LOG_ERROR, 0, "Error %d removing queued message from persistence", rc);
  610. }
  611. if (msgkeys[i])
  612. free(msgkeys[i]);
  613. i++;
  614. }
  615. if (msgkeys != NULL)
  616. free(msgkeys);
  617. }
  618. Log(TRACE_MINIMUM, -1, "%d queued messages deleted for client %s", messages_deleted, c->clientID);
  619. FUNC_EXIT_RC(rc);
  620. return rc;
  621. }
  622. static int MQTTAsync_unpersistInflightMessages(Clients* c)
  623. {
  624. int rc = 0;
  625. char **msgkeys;
  626. int nkeys;
  627. int i = 0;
  628. int messages_deleted = 0;
  629. FUNC_ENTRY;
  630. if (c->persistence && (rc = c->persistence->pkeys(c->phandle, &msgkeys, &nkeys)) == 0)
  631. {
  632. while (rc == 0 && i < nkeys)
  633. {
  634. if (strncmp(msgkeys[i], PERSISTENCE_PUBLISH_SENT, strlen(PERSISTENCE_PUBLISH_SENT)) == 0 ||
  635. strncmp(msgkeys[i], PERSISTENCE_V5_PUBLISH_SENT, strlen(PERSISTENCE_V5_PUBLISH_SENT)) == 0 ||
  636. strncmp(msgkeys[i], PERSISTENCE_PUBREL, strlen(PERSISTENCE_PUBREL)) == 0 ||
  637. strncmp(msgkeys[i], PERSISTENCE_V5_PUBREL, strlen(PERSISTENCE_V5_PUBREL)) == 0 ||
  638. strncmp(msgkeys[i], PERSISTENCE_PUBLISH_RECEIVED, strlen(PERSISTENCE_PUBLISH_RECEIVED)) == 0 ||
  639. strncmp(msgkeys[i], PERSISTENCE_V5_PUBLISH_RECEIVED, strlen(PERSISTENCE_V5_PUBLISH_RECEIVED)) == 0)
  640. {
  641. if ((rc = c->persistence->premove(c->phandle, msgkeys[i])) == 0)
  642. messages_deleted++;
  643. else
  644. Log(LOG_ERROR, 0, "Error %d removing inflight message from persistence", rc);
  645. }
  646. if (msgkeys[i])
  647. free(msgkeys[i]);
  648. i++;
  649. }
  650. if (msgkeys != NULL)
  651. free(msgkeys);
  652. }
  653. Log(TRACE_MINIMUM, -1, "%d inflight messages deleted for client %s", messages_deleted, c->clientID);
  654. FUNC_EXIT_RC(rc);
  655. return rc;
  656. }
  657. #endif
  658. #if 0
  659. /**
  660. * List callback function for comparing client handles and command types being CONNECT or DISCONNECT
  661. * @param a first MQTTAsync_queuedCommand pointer
  662. * @param b second MQTTAsync_queuedCommand pointer
  663. * @return boolean indicating whether a and b are equal
  664. */
  665. static int clientCompareConnectCommand(void* a, void* b)
  666. {
  667. MQTTAsync_queuedCommand* cmd1 = (MQTTAsync_queuedCommand*)a;
  668. MQTTAsync_queuedCommand* cmd2 = (MQTTAsync_queuedCommand*)b;
  669. if (cmd1->client == cmd2->client)
  670. {
  671. if (cmd1->command.type == cmd2->command.type)
  672. {
  673. if (cmd1->command.type == CONNECT || cmd1->command.type == DISCONNECT)
  674. {
  675. return 1; //Item found in the list
  676. }
  677. }
  678. }
  679. return 0; //Item NOT found in the list
  680. }
  681. #endif
  682. int MQTTAsync_addCommand(MQTTAsync_queuedCommand* command, int command_size)
  683. {
  684. int rc = MQTTASYNC_SUCCESS;
  685. int rc1 = 0;
  686. FUNC_ENTRY;
  687. MQTTAsync_lock_mutex(mqttcommand_mutex);
  688. /* Don't set start time if the connect command is already in process #218 */
  689. if ((command->command.type != CONNECT) || (command->client->c->connect_state == NOT_IN_PROGRESS))
  690. command->command.start_time = MQTTTime_start_clock();
  691. if (command->command.type == CONNECT ||
  692. (command->command.type == DISCONNECT && command->command.details.dis.internal))
  693. {
  694. MQTTAsync_queuedCommand* head = NULL;
  695. ListElement* current = MQTTAsync_commands->first;
  696. /* Look for any connect or disconnect command belonging to this client. All the connects/disconnects
  697. * are at the head of the list, so we don't search any further if we meet anything other than a
  698. * connect or disconnect for any client.
  699. */
  700. while (current)
  701. {
  702. MQTTAsync_queuedCommand* cur_cmd = (MQTTAsync_queuedCommand*)(current->content);
  703. if (cur_cmd->command.type != CONNECT && cur_cmd->command.type != DISCONNECT)
  704. break; /* end search if we meet anything other than connect or disconnect */
  705. if (cur_cmd->client == command->client)
  706. {
  707. head = cur_cmd;
  708. break;
  709. }
  710. current = current->prev;
  711. }
  712. if (head)
  713. {
  714. MQTTAsync_freeCommand(command); /* ignore duplicate connect or disconnect command */
  715. rc = MQTTASYNC_COMMAND_IGNORED;
  716. }
  717. else
  718. ListInsert(MQTTAsync_commands, command, command_size, MQTTAsync_commands->first); /* add to the head of the list */
  719. }
  720. else
  721. {
  722. ListAppend(MQTTAsync_commands, command, command_size);
  723. #if !defined(NO_PERSISTENCE)
  724. if (command->client->c->persistence)
  725. {
  726. if (command->command.type == PUBLISH &&
  727. command->client->createOptions && command->client->createOptions->struct_version >= 2 &&
  728. command->client->createOptions->persistQoS0 == 0 && command->command.details.pub.qos == 0)
  729. ; /* don't persist QoS0 if that create option is set to 0 */
  730. else
  731. {
  732. int rc = MQTTAsync_persistCommand(command);
  733. if (command->command.type == PUBLISH && rc == 0)
  734. {
  735. char key[PERSISTENCE_MAX_KEY_LENGTH + 1];
  736. int chars = 0;
  737. command->not_restored = 1;
  738. if (command->client->c->MQTTVersion >= MQTTVERSION_5)
  739. chars = snprintf(key, sizeof(key), "%s%u", PERSISTENCE_V5_COMMAND_KEY, command->seqno);
  740. else
  741. chars = snprintf(key, sizeof(key), "%s%u", PERSISTENCE_COMMAND_KEY, command->seqno);
  742. if (chars >= sizeof(key))
  743. {
  744. rc = MQTTASYNC_PERSISTENCE_ERROR;
  745. Log(LOG_ERROR, 0, "Error writing %d chars with snprintf", chars);
  746. goto exit;
  747. }
  748. command->key = malloc(strlen(key)+1);
  749. strcpy(command->key, key);
  750. free(command->command.details.pub.payload);
  751. command->command.details.pub.payload = NULL;
  752. free(command->command.details.pub.destinationName);
  753. command->command.details.pub.destinationName = NULL;
  754. MQTTProperties_free(&command->command.properties);
  755. }
  756. }
  757. }
  758. #endif
  759. if (command->command.type == PUBLISH)
  760. {
  761. /* delete oldest message if buffer is full. We wouldn't be here if delete newest was in operation */
  762. if (command->client->createOptions && (command->client->noBufferedMessages >= command->client->createOptions->maxBufferedMessages))
  763. {
  764. MQTTAsync_queuedCommand* first_publish = NULL;
  765. ListElement* current = NULL;
  766. /* Find first publish command for this client and detach it */
  767. while (ListNextElement(MQTTAsync_commands, &current))
  768. {
  769. MQTTAsync_queuedCommand* cmd = (MQTTAsync_queuedCommand*)(current->content);
  770. if (cmd->client == command->client && cmd->command.type == PUBLISH)
  771. {
  772. first_publish = cmd;
  773. break;
  774. }
  775. }
  776. if (first_publish)
  777. {
  778. ListDetach(MQTTAsync_commands, first_publish);
  779. #if !defined(NO_PERSISTENCE)
  780. if (command->client->c->persistence)
  781. MQTTAsync_unpersistCommand(first_publish);
  782. #endif
  783. MQTTAsync_freeCommand(first_publish);
  784. }
  785. }
  786. else
  787. command->client->noBufferedMessages++;
  788. }
  789. }
  790. exit:
  791. MQTTAsync_unlock_mutex(mqttcommand_mutex);
  792. #if !defined(_WIN32) && !defined(_WIN64)
  793. if ((rc1 = Thread_signal_cond(send_cond)) != 0)
  794. Log(LOG_ERROR, 0, "Error %d from signal cond", rc1);
  795. #else
  796. if ((rc1 = Thread_post_sem(send_sem)) != 0)
  797. Log(LOG_ERROR, 0, "Error %d from signal cond", rc1);
  798. #endif
  799. FUNC_EXIT_RC(rc);
  800. return rc;
  801. }
  802. void MQTTAsync_startConnectRetry(MQTTAsyncs* m)
  803. {
  804. if (m->automaticReconnect && m->shouldBeConnected)
  805. {
  806. m->lastConnectionFailedTime = MQTTTime_start_clock();
  807. if (m->retrying)
  808. {
  809. m->currentIntervalBase = min(m->currentIntervalBase * 2, m->maxRetryInterval);
  810. }
  811. else
  812. {
  813. m->currentIntervalBase = m->minRetryInterval;
  814. m->retrying = 1;
  815. }
  816. m->currentInterval = MQTTAsync_randomJitter(m->currentIntervalBase, m->minRetryInterval, m->maxRetryInterval);
  817. }
  818. }
  819. void MQTTAsync_checkDisconnect(MQTTAsync handle, MQTTAsync_command* command)
  820. {
  821. MQTTAsyncs* m = handle;
  822. FUNC_ENTRY;
  823. /* wait for all inflight message flows to finish, up to timeout */;
  824. if (m->c->outboundMsgs->count == 0 || MQTTTime_elapsed(command->start_time) >= (ELAPSED_TIME_TYPE)command->details.dis.timeout)
  825. {
  826. int was_connected = m->c->connected;
  827. MQTTAsync_closeSession(m->c, command->details.dis.reasonCode, &command->properties);
  828. if (command->details.dis.internal)
  829. {
  830. if (m->cl && was_connected)
  831. {
  832. Log(TRACE_MIN, -1, "Calling connectionLost for client %s", m->c->clientID);
  833. (*(m->cl))(m->clContext, NULL);
  834. }
  835. MQTTAsync_startConnectRetry(m);
  836. }
  837. else if (command->onSuccess)
  838. {
  839. MQTTAsync_successData data;
  840. memset(&data, '\0', sizeof(data));
  841. Log(TRACE_MIN, -1, "Calling disconnect complete for client %s", m->c->clientID);
  842. (*(command->onSuccess))(command->context, &data);
  843. }
  844. else if (command->onSuccess5)
  845. {
  846. MQTTAsync_successData5 data = MQTTAsync_successData5_initializer;
  847. data.reasonCode = MQTTASYNC_SUCCESS;
  848. Log(TRACE_MIN, -1, "Calling disconnect complete for client %s", m->c->clientID);
  849. (*(command->onSuccess5))(command->context, &data);
  850. }
  851. }
  852. FUNC_EXIT;
  853. }
  854. /**
  855. * Call Socket_noPendingWrites(int socket) with protection by socket_mutex, see https://github.com/eclipse/paho.mqtt.c/issues/385
  856. */
  857. static int MQTTAsync_Socket_noPendingWrites(SOCKET socket)
  858. {
  859. int rc;
  860. MQTTAsync_lock_mutex(socket_mutex);
  861. rc = Socket_noPendingWrites(socket);
  862. MQTTAsync_unlock_mutex(socket_mutex);
  863. return rc;
  864. }
  865. /**
  866. * See if any pending writes have been completed, and cleanup if so.
  867. * Cleaning up means removing any publication data that was stored because the write did
  868. * not originally complete.
  869. */
  870. static void MQTTProtocol_checkPendingWrites(void)
  871. {
  872. FUNC_ENTRY;
  873. if (state.pending_writes.count > 0)
  874. {
  875. ListElement* le = state.pending_writes.first;
  876. while (le)
  877. {
  878. if (Socket_noPendingWrites(((pending_write*)(le->content))->socket))
  879. {
  880. MQTTProtocol_removePublication(((pending_write*)(le->content))->p);
  881. state.pending_writes.current = le;
  882. ListRemove(&(state.pending_writes), le->content); /* does NextElement itself */
  883. le = state.pending_writes.current;
  884. }
  885. else
  886. ListNextElement(&(state.pending_writes), &le);
  887. }
  888. }
  889. FUNC_EXIT;
  890. }
  891. static void MQTTAsync_freeCommand1(MQTTAsync_queuedCommand *command)
  892. {
  893. if (command->command.type == SUBSCRIBE)
  894. {
  895. int i;
  896. for (i = 0; i < command->command.details.sub.count; i++)
  897. free(command->command.details.sub.topics[i]);
  898. free(command->command.details.sub.topics);
  899. command->command.details.sub.topics = NULL;
  900. free(command->command.details.sub.qoss);
  901. command->command.details.sub.qoss = NULL;
  902. }
  903. else if (command->command.type == UNSUBSCRIBE)
  904. {
  905. int i;
  906. for (i = 0; i < command->command.details.unsub.count; i++)
  907. free(command->command.details.unsub.topics[i]);
  908. free(command->command.details.unsub.topics);
  909. command->command.details.unsub.topics = NULL;
  910. }
  911. else if (command->command.type == PUBLISH)
  912. {
  913. /* qos 1 and 2 topics are freed in the protocol code when the flows are completed */
  914. if (command->command.details.pub.destinationName)
  915. free(command->command.details.pub.destinationName);
  916. command->command.details.pub.destinationName = NULL;
  917. if (command->command.details.pub.payload)
  918. free(command->command.details.pub.payload);
  919. command->command.details.pub.payload = NULL;
  920. }
  921. MQTTProperties_free(&command->command.properties);
  922. if (command->not_restored && command->key)
  923. free(command->key);
  924. }
  925. static void MQTTAsync_freeCommand(MQTTAsync_queuedCommand *command)
  926. {
  927. MQTTAsync_freeCommand1(command);
  928. free(command);
  929. }
  930. void MQTTAsync_writeContinue(SOCKET socket)
  931. {
  932. ListElement* found = NULL;
  933. if ((found = ListFindItem(MQTTAsync_handles, &socket, clientSockCompare)) != NULL)
  934. {
  935. MQTTAsyncs* m = (MQTTAsyncs*)(found->content);
  936. m->c->net.lastSent = MQTTTime_now();
  937. }
  938. }
  939. void MQTTAsync_writeComplete(SOCKET socket, int rc)
  940. {
  941. ListElement* found = NULL;
  942. FUNC_ENTRY;
  943. /* a partial write is now complete for a socket - this will be on a publish*/
  944. MQTTAsync_lock_mutex(mqttasync_mutex);
  945. MQTTProtocol_checkPendingWrites();
  946. /* find the client using this socket */
  947. if ((found = ListFindItem(MQTTAsync_handles, &socket, clientSockCompare)) != NULL)
  948. {
  949. MQTTAsyncs* m = (MQTTAsyncs*)(found->content);
  950. m->c->net.lastSent = MQTTTime_now();
  951. /* see if there is a pending write flagged */
  952. if (m->pending_write)
  953. {
  954. ListElement* cur_response = NULL;
  955. MQTTAsync_command* command = m->pending_write;
  956. MQTTAsync_queuedCommand* com = NULL;
  957. cur_response = NULL;
  958. while (ListNextElement(m->responses, &cur_response))
  959. {
  960. com = (MQTTAsync_queuedCommand*)(cur_response->content);
  961. if (&com->command == m->pending_write)
  962. break;
  963. }
  964. if (cur_response) /* we found a response */
  965. {
  966. if (command->type == PUBLISH)
  967. {
  968. if (rc == 1 && command->details.pub.qos == 0)
  969. {
  970. if (command->onSuccess)
  971. {
  972. MQTTAsync_successData data;
  973. data.token = command->token;
  974. data.alt.pub.destinationName = command->details.pub.destinationName;
  975. data.alt.pub.message.payload = command->details.pub.payload;
  976. data.alt.pub.message.payloadlen = command->details.pub.payloadlen;
  977. data.alt.pub.message.qos = command->details.pub.qos;
  978. data.alt.pub.message.retained = command->details.pub.retained;
  979. Log(TRACE_MIN, -1, "Calling publish success for client %s", m->c->clientID);
  980. (*(command->onSuccess))(command->context, &data);
  981. }
  982. else if (command->onSuccess5)
  983. {
  984. MQTTAsync_successData5 data = MQTTAsync_successData5_initializer;
  985. data.token = command->token;
  986. data.alt.pub.destinationName = command->details.pub.destinationName;
  987. data.alt.pub.message.payload = command->details.pub.payload;
  988. data.alt.pub.message.payloadlen = command->details.pub.payloadlen;
  989. data.alt.pub.message.qos = command->details.pub.qos;
  990. data.alt.pub.message.retained = command->details.pub.retained;
  991. data.properties = command->properties;
  992. Log(TRACE_MIN, -1, "Calling publish success for client %s", m->c->clientID);
  993. (*(command->onSuccess5))(command->context, &data);
  994. }
  995. }
  996. else if (rc == -1)
  997. {
  998. if (command->onFailure)
  999. {
  1000. MQTTAsync_failureData data;
  1001. data.token = command->token;
  1002. data.code = rc;
  1003. data.message = NULL;
  1004. Log(TRACE_MIN, -1, "Calling publish failure for client %s", m->c->clientID);
  1005. (*(command->onFailure))(command->context, &data);
  1006. }
  1007. else if (command->onFailure5)
  1008. {
  1009. MQTTAsync_failureData5 data;
  1010. data.token = command->token;
  1011. data.code = rc;
  1012. data.message = NULL;
  1013. data.packet_type = PUBLISH;
  1014. Log(TRACE_MIN, -1, "Calling publish failure for client %s", m->c->clientID);
  1015. (*(command->onFailure5))(command->context, &data);
  1016. }
  1017. }
  1018. else
  1019. com = NULL; /* Don't delete response we haven't acknowledged */
  1020. /* QoS 0 payloads are freed elsewhere after a write complete,
  1021. * so we should indicate that.
  1022. */
  1023. if (command->details.pub.qos == 0)
  1024. command->details.pub.payload = NULL;
  1025. }
  1026. if (com)
  1027. {
  1028. Log(TRACE_PROTOCOL, -1, "writeComplete: Removing response for msgid %d", com->command.token);
  1029. ListDetach(m->responses, com);
  1030. MQTTAsync_freeCommand(com);
  1031. }
  1032. } /* if cur_response */
  1033. m->pending_write = NULL;
  1034. } /* if pending_write */
  1035. }
  1036. MQTTAsync_unlock_mutex(mqttasync_mutex);
  1037. FUNC_EXIT;
  1038. }
  1039. static int MQTTAsync_processCommand(void)
  1040. {
  1041. int rc = 0;
  1042. MQTTAsync_queuedCommand* command = NULL;
  1043. ListElement* cur_command = NULL;
  1044. List* ignored_clients = NULL;
  1045. FUNC_ENTRY;
  1046. MQTTAsync_lock_mutex(mqttasync_mutex);
  1047. MQTTAsync_lock_mutex(mqttcommand_mutex);
  1048. /* only the first command in the list must be processed for any particular client, so if we skip
  1049. a command for a client, we must skip all following commands for that client. Use a list of
  1050. ignored clients to keep track
  1051. */
  1052. ignored_clients = ListInitialize();
  1053. /* don't try a command until there isn't a pending write for that client, and we are not connecting */
  1054. while (ListNextElement(MQTTAsync_commands, &cur_command))
  1055. {
  1056. MQTTAsync_queuedCommand* cmd = (MQTTAsync_queuedCommand*)(cur_command->content);
  1057. if (ListFind(ignored_clients, cmd->client))
  1058. continue;
  1059. if (cmd->command.type == CONNECT || cmd->command.type == DISCONNECT || (cmd->client->c->connected &&
  1060. cmd->client->c->connect_state == NOT_IN_PROGRESS && MQTTAsync_Socket_noPendingWrites(cmd->client->c->net.socket)))
  1061. {
  1062. if ((cmd->command.type == PUBLISH || cmd->command.type == SUBSCRIBE || cmd->command.type == UNSUBSCRIBE) &&
  1063. cmd->client->c->outboundMsgs->count >= MAX_MSG_ID - 1)
  1064. {
  1065. ; /* no more message ids available */
  1066. }
  1067. else if (((cmd->command.type == PUBLISH && cmd->command.details.pub.qos > 0) ||
  1068. cmd->command.type == SUBSCRIBE || cmd->command.type == UNSUBSCRIBE) &&
  1069. (cmd->client->c->outboundMsgs->count >= cmd->client->c->maxInflightMessages))
  1070. {
  1071. Log(TRACE_MIN, -1, "Blocking on server receive maximum for client %s",
  1072. cmd->client->c->clientID); /* flow control */
  1073. }
  1074. else
  1075. {
  1076. command = cmd;
  1077. break;
  1078. }
  1079. }
  1080. ListAppend(ignored_clients, cmd->client, sizeof(cmd->client));
  1081. }
  1082. ListFreeNoContent(ignored_clients);
  1083. if (command)
  1084. {
  1085. if (command->command.type == PUBLISH)
  1086. command->client->noBufferedMessages--;
  1087. ListDetach(MQTTAsync_commands, command);
  1088. #if !defined(NO_PERSISTENCE)
  1089. /*printf("outboundmsgs count %d max inflight %d qos %d %d %d\n", command->client->c->outboundMsgs->count, command->client->c->maxInflightMessages,
  1090. command->command.details.pub.qos, command->client->c->MQTTVersion, command->command.type);*/
  1091. if (command->client->c->persistence)
  1092. {
  1093. if (command->not_restored)
  1094. {
  1095. char* buffer = NULL;
  1096. int buflen = 0;
  1097. if ((rc = command->client->c->persistence->pget(command->client->c->phandle, command->key, &buffer, &buflen)) == 0
  1098. && (command->client->c->afterRead == NULL ||
  1099. (rc = command->client->c->afterRead(command->client->c->afterRead_context, &buffer, &buflen)) == 0))
  1100. {
  1101. int MQTTVersion = (strncmp(command->key, PERSISTENCE_V5_COMMAND_KEY, strlen(PERSISTENCE_V5_COMMAND_KEY)) == 0)
  1102. ? MQTTVERSION_5 : MQTTVERSION_3_1_1;
  1103. free(command->key);
  1104. command->key = NULL;
  1105. command = MQTTAsync_restoreCommand(buffer, buflen, MQTTVersion, command);
  1106. }
  1107. else
  1108. Log(LOG_ERROR, -1, "Error restoring command: rc %d from pget\n", rc);
  1109. if (buffer)
  1110. free(buffer);
  1111. }
  1112. MQTTAsync_unpersistCommand(command);
  1113. }
  1114. #endif
  1115. }
  1116. MQTTAsync_unlock_mutex(mqttcommand_mutex);
  1117. if (!command)
  1118. goto exit; /* nothing to do */
  1119. if (command->command.type == CONNECT)
  1120. {
  1121. if (command->client->c->connect_state != NOT_IN_PROGRESS || command->client->c->connected)
  1122. rc = 0;
  1123. else
  1124. {
  1125. char* serverURI = command->client->serverURI;
  1126. if (command->client->serverURIcount > 0)
  1127. {
  1128. if (command->command.details.conn.currentURI < command->client->serverURIcount)
  1129. {
  1130. serverURI = command->client->serverURIs[command->command.details.conn.currentURI];
  1131. if (strncmp(URI_TCP, serverURI, strlen(URI_TCP)) == 0)
  1132. serverURI += strlen(URI_TCP);
  1133. else if (strncmp(URI_MQTT, serverURI, strlen(URI_MQTT)) == 0)
  1134. serverURI += strlen(URI_MQTT);
  1135. else if (strncmp(URI_WS, serverURI, strlen(URI_WS)) == 0)
  1136. {
  1137. serverURI += strlen(URI_WS);
  1138. command->client->websocket = 1;
  1139. }
  1140. #if defined(OPENSSL)
  1141. else if (strncmp(URI_SSL, serverURI, strlen(URI_SSL)) == 0)
  1142. {
  1143. serverURI += strlen(URI_SSL);
  1144. command->client->ssl = 1;
  1145. }
  1146. else if (strncmp(URI_MQTTS, serverURI, strlen(URI_MQTTS)) == 0)
  1147. {
  1148. serverURI += strlen(URI_MQTTS);
  1149. command->client->ssl = 1;
  1150. }
  1151. else if (strncmp(URI_WSS, serverURI, strlen(URI_WSS)) == 0)
  1152. {
  1153. serverURI += strlen(URI_WSS);
  1154. command->client->ssl = 1;
  1155. command->client->websocket = 1;
  1156. }
  1157. #endif
  1158. }
  1159. }
  1160. if (command->client->c->MQTTVersion == MQTTVERSION_DEFAULT)
  1161. {
  1162. if (command->command.details.conn.MQTTVersion == MQTTVERSION_DEFAULT)
  1163. command->command.details.conn.MQTTVersion = MQTTVERSION_3_1_1;
  1164. else if (command->command.details.conn.MQTTVersion == MQTTVERSION_3_1_1)
  1165. command->command.details.conn.MQTTVersion = MQTTVERSION_3_1;
  1166. }
  1167. else
  1168. command->command.details.conn.MQTTVersion = command->client->c->MQTTVersion;
  1169. Log(TRACE_PROTOCOL, -1, "Connecting to serverURI %s with MQTT version %d", serverURI, command->command.details.conn.MQTTVersion);
  1170. #if defined(OPENSSL)
  1171. #if defined(__GNUC__) && defined(__linux__)
  1172. rc = MQTTProtocol_connect(serverURI, command->client->c, command->client->ssl, command->client->websocket,
  1173. command->command.details.conn.MQTTVersion, command->client->connectProps, command->client->willProps, 100);
  1174. #else
  1175. rc = MQTTProtocol_connect(serverURI, command->client->c, command->client->ssl, command->client->websocket,
  1176. command->command.details.conn.MQTTVersion, command->client->connectProps, command->client->willProps);
  1177. #endif
  1178. #else
  1179. #if defined(__GNUC__) && defined(__linux__)
  1180. rc = MQTTProtocol_connect(serverURI, command->client->c, command->client->websocket,
  1181. command->command.details.conn.MQTTVersion, command->client->connectProps, command->client->willProps, 100);
  1182. #else
  1183. rc = MQTTProtocol_connect(serverURI, command->client->c, command->client->websocket,
  1184. command->command.details.conn.MQTTVersion, command->client->connectProps, command->client->willProps);
  1185. #endif
  1186. #endif
  1187. if (command->client->c->connect_state == NOT_IN_PROGRESS)
  1188. rc = SOCKET_ERROR;
  1189. /* if the TCP connect is pending, then we must call select to determine when the connect has completed,
  1190. which is indicated by the socket being ready *either* for reading *or* writing. The next couple of lines
  1191. make sure we check for writeability as well as readability, otherwise we wait around longer than we need to
  1192. in Socket_getReadySocket() */
  1193. if (rc == EINPROGRESS)
  1194. Socket_addPendingWrite(command->client->c->net.socket);
  1195. }
  1196. }
  1197. else if (command->command.type == SUBSCRIBE)
  1198. {
  1199. List* topics = ListInitialize();
  1200. List* qoss = ListInitialize();
  1201. MQTTProperties* props = NULL;
  1202. MQTTSubscribe_options* subopts = NULL;
  1203. int i;
  1204. for (i = 0; i < command->command.details.sub.count; i++)
  1205. {
  1206. ListAppend(topics, command->command.details.sub.topics[i], strlen(command->command.details.sub.topics[i]));
  1207. ListAppend(qoss, &command->command.details.sub.qoss[i], sizeof(int));
  1208. }
  1209. if (command->client->c->MQTTVersion >= MQTTVERSION_5)
  1210. {
  1211. props = &command->command.properties;
  1212. if (command->command.details.sub.count > 1)
  1213. subopts = command->command.details.sub.optlist;
  1214. else
  1215. subopts = &command->command.details.sub.opts;
  1216. }
  1217. rc = MQTTProtocol_subscribe(command->client->c, topics, qoss, command->command.token, subopts, props);
  1218. ListFreeNoContent(topics);
  1219. ListFreeNoContent(qoss);
  1220. if (command->client->c->MQTTVersion >= MQTTVERSION_5 && command->command.details.sub.count > 1)
  1221. free(command->command.details.sub.optlist);
  1222. }
  1223. else if (command->command.type == UNSUBSCRIBE)
  1224. {
  1225. List* topics = ListInitialize();
  1226. MQTTProperties* props = NULL;
  1227. int i;
  1228. for (i = 0; i < command->command.details.unsub.count; i++)
  1229. ListAppend(topics, command->command.details.unsub.topics[i], strlen(command->command.details.unsub.topics[i]));
  1230. if (command->client->c->MQTTVersion >= MQTTVERSION_5)
  1231. props = &command->command.properties;
  1232. rc = MQTTProtocol_unsubscribe(command->client->c, topics, command->command.token, props);
  1233. ListFreeNoContent(topics);
  1234. }
  1235. else if (command->command.type == PUBLISH)
  1236. {
  1237. Messages* msg = NULL;
  1238. Publish* p = NULL;
  1239. MQTTProperties initialized = MQTTProperties_initializer;
  1240. if ((p = malloc(sizeof(Publish))) == NULL)
  1241. {
  1242. rc = PAHO_MEMORY_ERROR;
  1243. goto exit;
  1244. }
  1245. /* Initialize the mask */
  1246. memset(p->mask, 0, sizeof(p->mask));
  1247. p->payload = command->command.details.pub.payload;
  1248. p->payloadlen = command->command.details.pub.payloadlen;
  1249. p->topic = command->command.details.pub.destinationName;
  1250. p->msgId = command->command.token;
  1251. p->MQTTVersion = command->client->c->MQTTVersion;
  1252. p->properties = initialized;
  1253. if (p->MQTTVersion >= MQTTVERSION_5)
  1254. p->properties = command->command.properties;
  1255. rc = MQTTProtocol_startPublish(command->client->c, p, command->command.details.pub.qos, command->command.details.pub.retained, &msg);
  1256. if (command->command.details.pub.qos == 0)
  1257. {
  1258. if (rc == TCPSOCKET_COMPLETE)
  1259. {
  1260. if (command->command.onSuccess)
  1261. {
  1262. MQTTAsync_successData data;
  1263. data.token = command->command.token;
  1264. data.alt.pub.destinationName = command->command.details.pub.destinationName;
  1265. data.alt.pub.message.payload = command->command.details.pub.payload;
  1266. data.alt.pub.message.payloadlen = command->command.details.pub.payloadlen;
  1267. data.alt.pub.message.qos = command->command.details.pub.qos;
  1268. data.alt.pub.message.retained = command->command.details.pub.retained;
  1269. Log(TRACE_MIN, -1, "Calling publish success for client %s", command->client->c->clientID);
  1270. (*(command->command.onSuccess))(command->command.context, &data);
  1271. }
  1272. else if (command->command.onSuccess5)
  1273. {
  1274. MQTTAsync_successData5 data = MQTTAsync_successData5_initializer;
  1275. data.token = command->command.token;
  1276. data.alt.pub.destinationName = command->command.details.pub.destinationName;
  1277. data.alt.pub.message.payload = command->command.details.pub.payload;
  1278. data.alt.pub.message.payloadlen = command->command.details.pub.payloadlen;
  1279. data.alt.pub.message.qos = command->command.details.pub.qos;
  1280. data.alt.pub.message.retained = command->command.details.pub.retained;
  1281. data.properties = command->command.properties;
  1282. Log(TRACE_MIN, -1, "Calling publish success for client %s", command->client->c->clientID);
  1283. (*(command->command.onSuccess5))(command->command.context, &data);
  1284. }
  1285. }
  1286. else
  1287. {
  1288. if (rc != SOCKET_ERROR)
  1289. {
  1290. command->command.details.pub.payload = NULL; /* this will be freed by the protocol code */
  1291. command->command.details.pub.destinationName = NULL; /* this will be freed by the protocol code */
  1292. }
  1293. command->client->pending_write = &command->command;
  1294. }
  1295. }
  1296. free(p); /* should this be done if the write isn't complete? */
  1297. }
  1298. else if (command->command.type == DISCONNECT)
  1299. {
  1300. if (command->client->c->connect_state != NOT_IN_PROGRESS || command->client->c->connected != 0)
  1301. {
  1302. if (command->client->c->connect_state != NOT_IN_PROGRESS)
  1303. {
  1304. if (command->client->connect.onFailure)
  1305. {
  1306. MQTTAsync_failureData data;
  1307. data.token = 0;
  1308. data.code = MQTTASYNC_OPERATION_INCOMPLETE;
  1309. data.message = NULL;
  1310. Log(TRACE_MIN, -1, "Calling connect failure for client %s", command->client->c->clientID);
  1311. (*(command->client->connect.onFailure))(command->client->connect.context, &data);
  1312. /* Null out callback pointers so they aren't accidentally called again */
  1313. command->client->connect.onFailure = NULL;
  1314. command->client->connect.onSuccess = NULL;
  1315. }
  1316. else if (command->client->connect.onFailure5)
  1317. {
  1318. MQTTAsync_failureData5 data;
  1319. data.token = 0;
  1320. data.code = MQTTASYNC_OPERATION_INCOMPLETE;
  1321. data.message = NULL;
  1322. Log(TRACE_MIN, -1, "Calling connect failure for client %s", command->client->c->clientID);
  1323. (*(command->client->connect.onFailure5))(command->client->connect.context, &data);
  1324. /* Null out callback pointers so they aren't accidentally called again */
  1325. command->client->connect.onFailure5 = NULL;
  1326. command->client->connect.onSuccess5 = NULL;
  1327. }
  1328. }
  1329. command->client->c->connect_state = DISCONNECTING;
  1330. MQTTAsync_checkDisconnect(command->client, &command->command);
  1331. }
  1332. }
  1333. if (command->command.type == CONNECT && rc != SOCKET_ERROR && rc != MQTTASYNC_PERSISTENCE_ERROR)
  1334. {
  1335. command->client->connect = command->command;
  1336. MQTTAsync_freeCommand(command);
  1337. }
  1338. else if (command->command.type == DISCONNECT)
  1339. {
  1340. command->client->disconnect = command->command;
  1341. MQTTAsync_freeCommand(command);
  1342. }
  1343. else if (command->command.type == PUBLISH && command->command.details.pub.qos == 0 &&
  1344. rc != SOCKET_ERROR && rc != MQTTASYNC_PERSISTENCE_ERROR)
  1345. {
  1346. if (rc == TCPSOCKET_INTERRUPTED)
  1347. ListAppend(command->client->responses, command, sizeof(command));
  1348. else
  1349. MQTTAsync_freeCommand(command);
  1350. }
  1351. else if (rc == SOCKET_ERROR || rc == MQTTASYNC_PERSISTENCE_ERROR)
  1352. {
  1353. if (command->command.type == CONNECT)
  1354. {
  1355. MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
  1356. MQTTAsync_disconnect(command->client, &opts); /* not "internal" because we don't want to call connection lost */
  1357. command->client->shouldBeConnected = 1; /* as above call is not "internal" we need to reset this */
  1358. }
  1359. else
  1360. MQTTAsync_disconnect_internal(command->client, 0);
  1361. if (command->command.type == CONNECT
  1362. && MQTTAsync_checkConn(&command->command, command->client))
  1363. {
  1364. Log(TRACE_MIN, -1, "Connect failed, more to try");
  1365. if (command->client->c->MQTTVersion == MQTTVERSION_DEFAULT)
  1366. {
  1367. if (command->command.details.conn.MQTTVersion == MQTTVERSION_3_1)
  1368. {
  1369. command->command.details.conn.currentURI++;
  1370. command->command.details.conn.MQTTVersion = MQTTVERSION_DEFAULT;
  1371. }
  1372. } else
  1373. command->command.details.conn.currentURI++; /* Here currentURI becomes larger than command->client->serverURIcount. This needs to be handled to avoid segmentation faults! */
  1374. /* put the connect command back to the head of the command queue, using the next serverURI */
  1375. rc = MQTTAsync_addCommand(command,
  1376. sizeof(command->command.details.conn));
  1377. } else
  1378. {
  1379. if (command->command.onFailure)
  1380. {
  1381. MQTTAsync_failureData data;
  1382. data.token = 0;
  1383. data.code = rc;
  1384. data.message = NULL;
  1385. Log(TRACE_MIN, -1, "Calling command failure for client %s", command->client->c->clientID);
  1386. (*(command->command.onFailure))(command->command.context, &data);
  1387. }
  1388. else if (command->command.onFailure5)
  1389. {
  1390. MQTTAsync_failureData5 data = MQTTAsync_failureData5_initializer;
  1391. data.code = rc;
  1392. Log(TRACE_MIN, -1, "Calling command failure for client %s", command->client->c->clientID);
  1393. (*(command->command.onFailure5))(command->command.context, &data);
  1394. }
  1395. if (command->command.type == CONNECT)
  1396. {
  1397. command->client->connect = command->command;
  1398. MQTTAsync_startConnectRetry(command->client);
  1399. }
  1400. MQTTAsync_freeCommand(command); /* free up the command if necessary */
  1401. }
  1402. }
  1403. else /* put the command into a waiting for response queue for each client, indexed by msgid */
  1404. ListAppend(command->client->responses, command, sizeof(command));
  1405. exit:
  1406. MQTTAsync_unlock_mutex(mqttasync_mutex);
  1407. rc = (command != NULL);
  1408. FUNC_EXIT_RC(rc);
  1409. return rc;
  1410. }
  1411. static void nextOrClose(MQTTAsyncs* m, int rc, char* message)
  1412. {
  1413. int was_connected = m->c->connected;
  1414. int more_to_try = 0;
  1415. int connectionLost_called = 0;
  1416. FUNC_ENTRY;
  1417. more_to_try = MQTTAsync_checkConn(&m->connect, m);
  1418. if (more_to_try)
  1419. {
  1420. MQTTAsync_queuedCommand* conn;
  1421. MQTTAsync_closeOnly(m->c, MQTTREASONCODE_SUCCESS, NULL);
  1422. if (m->cl && was_connected)
  1423. {
  1424. Log(TRACE_MIN, -1, "Calling connectionLost for client %s", m->c->clientID);
  1425. (*(m->cl))(m->clContext, NULL);
  1426. connectionLost_called = 1;
  1427. }
  1428. /* put the connect command back to the head of the command queue, using the next serverURI */
  1429. if ((conn = malloc(sizeof(MQTTAsync_queuedCommand))) == NULL)
  1430. goto exit;
  1431. memset(conn, '\0', sizeof(MQTTAsync_queuedCommand));
  1432. conn->client = m;
  1433. conn->command = m->connect;
  1434. Log(TRACE_MIN, -1, "Connect failed, more to try");
  1435. if (conn->client->c->MQTTVersion == MQTTVERSION_DEFAULT)
  1436. {
  1437. if (conn->command.details.conn.MQTTVersion == MQTTVERSION_3_1)
  1438. {
  1439. conn->command.details.conn.currentURI++;
  1440. conn->command.details.conn.MQTTVersion = MQTTVERSION_DEFAULT;
  1441. }
  1442. }
  1443. else
  1444. conn->command.details.conn.currentURI++;
  1445. if (MQTTAsync_addCommand(conn, sizeof(m->connect)) != MQTTASYNC_SUCCESS)
  1446. more_to_try = 0; /* go into retry mode if CONNECT command add fails */
  1447. }
  1448. if (!more_to_try)
  1449. {
  1450. MQTTAsync_closeSession(m->c, MQTTREASONCODE_SUCCESS, NULL);
  1451. if (connectionLost_called == 0 && m->cl && was_connected)
  1452. {
  1453. Log(TRACE_MIN, -1, "Calling connectionLost for client %s", m->c->clientID);
  1454. (*(m->cl))(m->clContext, NULL);
  1455. }
  1456. if (m->connect.onFailure)
  1457. {
  1458. MQTTAsync_failureData data;
  1459. data.token = 0;
  1460. data.code = rc;
  1461. data.message = message;
  1462. Log(TRACE_MIN, -1, "Calling connect failure for client %s", m->c->clientID);
  1463. (*(m->connect.onFailure))(m->connect.context, &data);
  1464. /* Null out callback pointers so they aren't accidentally called again */
  1465. m->connect.onFailure = NULL;
  1466. m->connect.onSuccess = NULL;
  1467. }
  1468. else if (m->connect.onFailure5)
  1469. {
  1470. MQTTAsync_failureData5 data = MQTTAsync_failureData5_initializer;
  1471. data.token = 0;
  1472. data.code = rc;
  1473. data.message = message;
  1474. Log(TRACE_MIN, -1, "Calling connect failure for client %s", m->c->clientID);
  1475. (*(m->connect.onFailure5))(m->connect.context, &data);
  1476. /* Null out callback pointers so they aren't accidentally called again */
  1477. m->connect.onFailure5 = NULL;
  1478. m->connect.onSuccess5 = NULL;
  1479. }
  1480. MQTTAsync_startConnectRetry(m);
  1481. }
  1482. exit:
  1483. FUNC_EXIT;
  1484. }
  1485. static void MQTTAsync_checkTimeouts(void)
  1486. {
  1487. ListElement* current = NULL;
  1488. static START_TIME_TYPE last = START_TIME_ZERO;
  1489. START_TIME_TYPE now;
  1490. FUNC_ENTRY;
  1491. MQTTAsync_lock_mutex(mqttasync_mutex);
  1492. now = MQTTTime_now();
  1493. if (MQTTTime_difftime(now, last) < (DIFF_TIME_TYPE)3000)
  1494. goto exit;
  1495. last = now;
  1496. while (ListNextElement(MQTTAsync_handles, &current)) /* for each client */
  1497. {
  1498. MQTTAsyncs* m = (MQTTAsyncs*)(current->content);
  1499. /* check disconnect timeout */
  1500. if (m->c->connect_state == DISCONNECTING)
  1501. MQTTAsync_checkDisconnect(m, &m->disconnect);
  1502. /* check connect timeout */
  1503. if (m->c->connect_state != NOT_IN_PROGRESS && MQTTTime_elapsed(m->connect.start_time) > (ELAPSED_TIME_TYPE)(m->connectTimeout * 1000))
  1504. {
  1505. nextOrClose(m, MQTTASYNC_FAILURE, "TCP connect timeout");
  1506. continue;
  1507. }
  1508. /* There was a section here that removed timed-out responses. But if the command had completed and
  1509. * there was a response, then we may as well report it, no?
  1510. *
  1511. * In any case, that section was disabled when automatic reconnect was implemented.
  1512. */
  1513. if (m->automaticReconnect && m->retrying)
  1514. {
  1515. if (m->reconnectNow || MQTTTime_elapsed(m->lastConnectionFailedTime) > (ELAPSED_TIME_TYPE)(m->currentInterval * 1000))
  1516. {
  1517. /* to reconnect put the connect command to the head of the command queue */
  1518. MQTTAsync_queuedCommand* conn = malloc(sizeof(MQTTAsync_queuedCommand));
  1519. if (!conn)
  1520. goto exit;
  1521. memset(conn, '\0', sizeof(MQTTAsync_queuedCommand));
  1522. conn->client = m;
  1523. conn->command = m->connect;
  1524. /* make sure that the version attempts are restarted */
  1525. if (m->c->MQTTVersion == MQTTVERSION_DEFAULT)
  1526. conn->command.details.conn.MQTTVersion = 0;
  1527. if (m->updateConnectOptions)
  1528. {
  1529. MQTTAsync_connectData connectData = MQTTAsync_connectData_initializer;
  1530. int callback_rc = MQTTASYNC_SUCCESS;
  1531. connectData.username = m->c->username;
  1532. connectData.binarypwd.data = m->c->password;
  1533. connectData.binarypwd.len = m->c->passwordlen;
  1534. Log(TRACE_MIN, -1, "Calling updateConnectOptions for client %s", m->c->clientID);
  1535. callback_rc = (*(m->updateConnectOptions))(m->updateConnectOptions_context, &connectData);
  1536. if (callback_rc)
  1537. {
  1538. if (connectData.username != m->c->username)
  1539. {
  1540. if (m->c->username)
  1541. free((void*)m->c->username);
  1542. if (connectData.username)
  1543. m->c->username = connectData.username; /* must be allocated by MQTTAsync_malloc in the callback */
  1544. else
  1545. m->c->username = NULL;
  1546. }
  1547. if (connectData.binarypwd.data != m->c->password)
  1548. {
  1549. if (m->c->password)
  1550. free((void*)m->c->password);
  1551. if (connectData.binarypwd.data)
  1552. {
  1553. m->c->passwordlen = connectData.binarypwd.len;
  1554. m->c->password = connectData.binarypwd.data; /* must be allocated by MQTTAsync_malloc in the callback */
  1555. }
  1556. else
  1557. {
  1558. m->c->password = NULL;
  1559. m->c->passwordlen = 0;
  1560. }
  1561. }
  1562. }
  1563. }
  1564. Log(TRACE_MIN, -1, "Automatically attempting to reconnect");
  1565. MQTTAsync_addCommand(conn, sizeof(m->connect));
  1566. m->reconnectNow = 0;
  1567. }
  1568. }
  1569. }
  1570. exit:
  1571. MQTTAsync_unlock_mutex(mqttasync_mutex);
  1572. FUNC_EXIT;
  1573. }
  1574. thread_return_type WINAPI MQTTAsync_sendThread(void* n)
  1575. {
  1576. int timeout = 10; /* first time in we have a small timeout. Gets things started more quickly */
  1577. FUNC_ENTRY;
  1578. Thread_set_name("MQTTAsync_send");
  1579. MQTTAsync_lock_mutex(mqttasync_mutex);
  1580. sendThread_state = RUNNING;
  1581. sendThread_id = Thread_getid();
  1582. MQTTAsync_unlock_mutex(mqttasync_mutex);
  1583. while (!MQTTAsync_tostop)
  1584. {
  1585. int rc;
  1586. int command_count = 0;
  1587. MQTTAsync_lock_mutex(mqttcommand_mutex);
  1588. command_count = MQTTAsync_commands->count;
  1589. MQTTAsync_unlock_mutex(mqttcommand_mutex);
  1590. while (command_count > 0)
  1591. {
  1592. if (MQTTAsync_processCommand() == 0)
  1593. break; /* no commands were processed, so go into a wait */
  1594. MQTTAsync_lock_mutex(mqttcommand_mutex);
  1595. command_count = MQTTAsync_commands->count;
  1596. MQTTAsync_unlock_mutex(mqttcommand_mutex);
  1597. }
  1598. #if !defined(_WIN32) && !defined(_WIN64)
  1599. if ((rc = Thread_wait_cond(send_cond, timeout)) != 0 && rc != ETIMEDOUT)
  1600. Log(LOG_ERROR, -1, "Error %d waiting for condition variable", rc);
  1601. #else
  1602. if ((rc = Thread_wait_sem(send_sem, timeout)) != 0 && rc != ETIMEDOUT)
  1603. Log(LOG_ERROR, -1, "Error %d waiting for semaphore", rc);
  1604. #endif
  1605. timeout = 1000; /* 1 second for follow on waits */
  1606. MQTTAsync_checkTimeouts();
  1607. }
  1608. sendThread_state = STOPPING;
  1609. MQTTAsync_lock_mutex(mqttasync_mutex);
  1610. sendThread_state = STOPPED;
  1611. sendThread_id = 0;
  1612. MQTTAsync_unlock_mutex(mqttasync_mutex);
  1613. FUNC_EXIT;
  1614. #if defined(_WIN32) || defined(_WIN64)
  1615. ExitThread(0);
  1616. #endif
  1617. return 0;
  1618. }
  1619. void MQTTAsync_emptyMessageQueue(Clients* client)
  1620. {
  1621. FUNC_ENTRY;
  1622. /* empty message queue */
  1623. if (client->messageQueue->count > 0)
  1624. {
  1625. ListElement* current = NULL;
  1626. while (ListNextElement(client->messageQueue, &current))
  1627. {
  1628. qEntry* qe = (qEntry*)(current->content);
  1629. free(qe->topicName);
  1630. free(qe->msg->payload);
  1631. free(qe->msg);
  1632. }
  1633. ListEmpty(client->messageQueue);
  1634. }
  1635. FUNC_EXIT;
  1636. }
  1637. void MQTTAsync_freeResponses(MQTTAsyncs* m)
  1638. {
  1639. int count = 0;
  1640. FUNC_ENTRY;
  1641. if (m->responses)
  1642. {
  1643. ListElement* cur_response = NULL;
  1644. while (ListNextElement(m->responses, &cur_response))
  1645. {
  1646. MQTTAsync_queuedCommand* command = (MQTTAsync_queuedCommand*)(cur_response->content);
  1647. if (command->command.onFailure)
  1648. {
  1649. MQTTAsync_failureData data;
  1650. data.token = command->command.token;
  1651. data.code = MQTTASYNC_OPERATION_INCOMPLETE; /* interrupted return code */
  1652. data.message = NULL;
  1653. Log(TRACE_MIN, -1, "Calling %s failure for client %s",
  1654. MQTTPacket_name(command->command.type), m->c->clientID);
  1655. (*(command->command.onFailure))(command->command.context, &data);
  1656. }
  1657. else if (command->command.onFailure5)
  1658. {
  1659. MQTTAsync_failureData5 data = MQTTAsync_failureData5_initializer;
  1660. data.token = command->command.token;
  1661. data.code = MQTTASYNC_OPERATION_INCOMPLETE; /* interrupted return code */
  1662. data.message = NULL;
  1663. Log(TRACE_MIN, -1, "Calling %s failure for client %s",
  1664. MQTTPacket_name(command->command.type), m->c->clientID);
  1665. (*(command->command.onFailure5))(command->command.context, &data);
  1666. }
  1667. MQTTAsync_freeCommand1(command);
  1668. count++;
  1669. }
  1670. ListEmpty(m->responses);
  1671. }
  1672. Log(TRACE_MINIMUM, -1, "%d responses removed for client %s", count, m->c->clientID);
  1673. FUNC_EXIT;
  1674. }
  1675. void MQTTAsync_freeCommands(MQTTAsyncs* m)
  1676. {
  1677. int count = 0;
  1678. ListElement* current = NULL;
  1679. ListElement *next = NULL;
  1680. FUNC_ENTRY;
  1681. /* remove commands in the command queue relating to this client */
  1682. current = ListNextElement(MQTTAsync_commands, &next);
  1683. ListNextElement(MQTTAsync_commands, &next);
  1684. while (current)
  1685. {
  1686. MQTTAsync_queuedCommand* command = (MQTTAsync_queuedCommand*)(current->content);
  1687. if (command->client == m)
  1688. {
  1689. ListDetach(MQTTAsync_commands, command);
  1690. if (command->command.onFailure)
  1691. {
  1692. MQTTAsync_failureData data;
  1693. data.token = command->command.token;
  1694. data.code = MQTTASYNC_OPERATION_INCOMPLETE; /* interrupted return code */
  1695. data.message = NULL;
  1696. Log(TRACE_MIN, -1, "Calling %s failure for client %s",
  1697. MQTTPacket_name(command->command.type), m->c->clientID);
  1698. (*(command->command.onFailure))(command->command.context, &data);
  1699. }
  1700. else if (command->command.onFailure5)
  1701. {
  1702. MQTTAsync_failureData5 data = MQTTAsync_failureData5_initializer;
  1703. data.token = command->command.token;
  1704. data.code = MQTTASYNC_OPERATION_INCOMPLETE; /* interrupted return code */
  1705. data.message = NULL;
  1706. Log(TRACE_MIN, -1, "Calling %s failure for client %s",
  1707. MQTTPacket_name(command->command.type), m->c->clientID);
  1708. (*(command->command.onFailure5))(command->command.context, &data);
  1709. }
  1710. MQTTAsync_freeCommand(command);
  1711. count++;
  1712. }
  1713. current = next;
  1714. ListNextElement(MQTTAsync_commands, &next);
  1715. }
  1716. Log(TRACE_MINIMUM, -1, "%d commands removed for client %s", count, m->c->clientID);
  1717. FUNC_EXIT;
  1718. }
  1719. static int MQTTAsync_completeConnection(MQTTAsyncs* m, Connack* connack)
  1720. {
  1721. int rc = MQTTASYNC_FAILURE;
  1722. FUNC_ENTRY;
  1723. if (m->c->connect_state == WAIT_FOR_CONNACK) /* MQTT connect sent - wait for CONNACK */
  1724. {
  1725. Log(LOG_PROTOCOL, 1, NULL, m->c->net.socket, m->c->clientID, connack->rc);
  1726. if ((rc = connack->rc) == MQTTASYNC_SUCCESS)
  1727. {
  1728. m->retrying = 0;
  1729. m->c->connected = 1;
  1730. m->c->good = 1;
  1731. m->c->connect_state = NOT_IN_PROGRESS;
  1732. if (m->c->cleansession || m->c->cleanstart)
  1733. rc = MQTTAsync_cleanSession(m->c);
  1734. else if (m->c->MQTTVersion >= MQTTVERSION_3_1_1 && connack->flags.bits.sessionPresent == 0)
  1735. {
  1736. Log(LOG_PROTOCOL, -1, "Cleaning session state on connect because sessionPresent is 0");
  1737. rc = MQTTAsync_cleanSession(m->c);
  1738. }
  1739. if (m->c->outboundMsgs->count > 0)
  1740. {
  1741. ListElement* outcurrent = NULL;
  1742. START_TIME_TYPE zero = START_TIME_ZERO;
  1743. while (ListNextElement(m->c->outboundMsgs, &outcurrent))
  1744. {
  1745. Messages* messages = (Messages*)(outcurrent->content);
  1746. memset(&messages->lastTouch, '\0', sizeof(messages->lastTouch));
  1747. }
  1748. MQTTProtocol_retry(zero, 1, 1);
  1749. if (m->c->connected != 1)
  1750. rc = MQTTASYNC_DISCONNECTED;
  1751. }
  1752. }
  1753. m->pack = NULL;
  1754. #if !defined(_WIN32) && !defined(_WIN64)
  1755. Thread_signal_cond(send_cond);
  1756. #else
  1757. Thread_post_sem(send_sem);
  1758. #endif
  1759. }
  1760. FUNC_EXIT_RC(rc);
  1761. return rc;
  1762. }
  1763. /* This is the thread function that handles the calling of callback functions if set */
  1764. thread_return_type WINAPI MQTTAsync_receiveThread(void* n)
  1765. {
  1766. long timeout = 10L; /* first time in we have a small timeout. Gets things started more quickly */
  1767. FUNC_ENTRY;
  1768. Thread_set_name("MQTTAsync_rcv");
  1769. MQTTAsync_lock_mutex(mqttasync_mutex);
  1770. receiveThread_state = RUNNING;
  1771. receiveThread_id = Thread_getid();
  1772. while (!MQTTAsync_tostop)
  1773. {
  1774. int rc = SOCKET_ERROR;
  1775. SOCKET sock = -1;
  1776. MQTTAsyncs* m = NULL;
  1777. MQTTPacket* pack = NULL;
  1778. MQTTAsync_unlock_mutex(mqttasync_mutex);
  1779. pack = MQTTAsync_cycle(&sock, timeout, &rc);
  1780. MQTTAsync_lock_mutex(mqttasync_mutex);
  1781. if (MQTTAsync_tostop)
  1782. break;
  1783. if (sock == 0)
  1784. continue;
  1785. timeout = 1000L;
  1786. /* find client corresponding to socket */
  1787. if (ListFindItem(MQTTAsync_handles, &sock, clientSockCompare) == NULL)
  1788. {
  1789. Log(TRACE_MINIMUM, -1, "Could not find client corresponding to socket %d", sock);
  1790. /* Socket_close(sock); - removing socket in this case is not necessary (Bug 442400) */
  1791. continue;
  1792. }
  1793. m = (MQTTAsyncs*)(MQTTAsync_handles->current->content);
  1794. if (m == NULL)
  1795. {
  1796. Log(LOG_ERROR, -1, "Client structure was NULL for socket %d - removing socket", sock);
  1797. Socket_close(sock);
  1798. continue;
  1799. }
  1800. if (rc == SOCKET_ERROR)
  1801. {
  1802. Log(TRACE_MINIMUM, -1, "Error from MQTTAsync_cycle() - removing socket %d", sock);
  1803. nextOrClose(m, rc, "socket error");
  1804. }
  1805. else
  1806. {
  1807. if (m->c->messageQueue->count > 0 && m->ma)
  1808. {
  1809. qEntry* qe = (qEntry*)(m->c->messageQueue->first->content);
  1810. int topicLen = qe->topicLen;
  1811. if (strlen(qe->topicName) == topicLen)
  1812. topicLen = 0;
  1813. if (MQTTAsync_deliverMessage(m, qe->topicName, topicLen, qe->msg))
  1814. {
  1815. #if !defined(NO_PERSISTENCE)
  1816. if (m->c->persistence)
  1817. MQTTPersistence_unpersistQueueEntry(m->c, (MQTTPersistence_qEntry*)qe);
  1818. #endif
  1819. ListRemove(m->c->messageQueue, qe); /* qe is freed here */
  1820. }
  1821. else
  1822. Log(TRACE_MIN, -1, "False returned from messageArrived for client %s, message remains on queue",
  1823. m->c->clientID);
  1824. }
  1825. if (pack)
  1826. {
  1827. if (pack->header.bits.type == CONNACK)
  1828. {
  1829. Connack* connack = (Connack*)pack;
  1830. int sessionPresent = connack->flags.bits.sessionPresent;
  1831. rc = MQTTAsync_completeConnection(m, connack);
  1832. if (rc == MQTTASYNC_SUCCESS)
  1833. {
  1834. int onSuccess = 0;
  1835. if ((m->serverURIcount > 0)
  1836. && (m->connect.details.conn.currentURI < m->serverURIcount))
  1837. {
  1838. Log(TRACE_MIN, -1, "Connect succeeded to %s",
  1839. m->serverURIs[m->connect.details.conn.currentURI]);
  1840. }
  1841. onSuccess = (m->connect.onSuccess != NULL ||
  1842. m->connect.onSuccess5 != NULL); /* save setting of onSuccess callback */
  1843. if (m->connect.onSuccess)
  1844. {
  1845. MQTTAsync_successData data;
  1846. memset(&data, '\0', sizeof(data));
  1847. Log(TRACE_MIN, -1, "Calling connect success for client %s", m->c->clientID);
  1848. if ((m->serverURIcount > 0)
  1849. && (m->connect.details.conn.currentURI < m->serverURIcount))
  1850. data.alt.connect.serverURI = m->serverURIs[m->connect.details.conn.currentURI];
  1851. else
  1852. data.alt.connect.serverURI = m->serverURI;
  1853. data.alt.connect.MQTTVersion = m->connect.details.conn.MQTTVersion;
  1854. data.alt.connect.sessionPresent = sessionPresent;
  1855. (*(m->connect.onSuccess))(m->connect.context, &data);
  1856. /* Null out callback pointers so they aren't accidentally called again */
  1857. m->connect.onSuccess = NULL;
  1858. m->connect.onFailure = NULL;
  1859. }
  1860. else if (m->connect.onSuccess5)
  1861. {
  1862. MQTTAsync_successData5 data = MQTTAsync_successData5_initializer;
  1863. Log(TRACE_MIN, -1, "Calling connect success for client %s", m->c->clientID);
  1864. if (m->serverURIcount > 0)
  1865. data.alt.connect.serverURI = m->serverURIs[m->connect.details.conn.currentURI];
  1866. else
  1867. data.alt.connect.serverURI = m->serverURI;
  1868. data.alt.connect.MQTTVersion = m->connect.details.conn.MQTTVersion;
  1869. data.alt.connect.sessionPresent = sessionPresent;
  1870. data.properties = connack->properties;
  1871. data.reasonCode = connack->rc;
  1872. (*(m->connect.onSuccess5))(m->connect.context, &data);
  1873. /* Null out callback pointers so they aren't accidentally called again */
  1874. m->connect.onSuccess5 = NULL;
  1875. m->connect.onFailure5 = NULL;
  1876. }
  1877. if (m->connected)
  1878. {
  1879. char* reason = (onSuccess) ? "connect onSuccess called" : "automatic reconnect";
  1880. Log(TRACE_MIN, -1, "Calling connected for client %s", m->c->clientID);
  1881. (*(m->connected))(m->connected_context, reason);
  1882. }
  1883. if (m->c->MQTTVersion >= MQTTVERSION_5)
  1884. {
  1885. if (MQTTProperties_hasProperty(&connack->properties, MQTTPROPERTY_CODE_RECEIVE_MAXIMUM))
  1886. {
  1887. int recv_max = MQTTProperties_getNumericValue(&connack->properties, MQTTPROPERTY_CODE_RECEIVE_MAXIMUM);
  1888. if (m->c->maxInflightMessages > recv_max)
  1889. m->c->maxInflightMessages = recv_max;
  1890. }
  1891. }
  1892. }
  1893. else
  1894. {
  1895. nextOrClose(m, rc, "CONNACK return code");
  1896. }
  1897. MQTTPacket_freeConnack(connack);
  1898. }
  1899. else if (pack->header.bits.type == SUBACK)
  1900. {
  1901. ListElement* current = NULL;
  1902. /* use the msgid to find the callback to be called */
  1903. while (ListNextElement(m->responses, &current))
  1904. {
  1905. MQTTAsync_queuedCommand* command = (MQTTAsync_queuedCommand*)(current->content);
  1906. if (command->command.token == ((Suback*)pack)->msgId)
  1907. {
  1908. Suback* sub = (Suback*)pack;
  1909. if (!ListDetach(m->responses, command)) /* remove the response from the list */
  1910. Log(LOG_ERROR, -1, "Subscribe command not removed from command list");
  1911. /* Call the failure callback if there is one subscribe in the MQTT packet and
  1912. * the return code is 0x80 (failure). If the MQTT packet contains >1 subscription
  1913. * request, then we call onSuccess with the list of returned QoSs, which inelegantly,
  1914. * could include some failures, or worse, the whole list could have failed.
  1915. */
  1916. if (m->c->MQTTVersion >= MQTTVERSION_5)
  1917. {
  1918. if (sub->qoss->count == 1 && *(int*)(sub->qoss->first->content) >= MQTTREASONCODE_UNSPECIFIED_ERROR)
  1919. {
  1920. if (command->command.onFailure5)
  1921. {
  1922. MQTTAsync_failureData5 data = MQTTAsync_failureData5_initializer;
  1923. data.token = command->command.token;
  1924. data.reasonCode = *(int*)(sub->qoss->first->content);
  1925. data.message = NULL;
  1926. data.properties = sub->properties;
  1927. Log(TRACE_MIN, -1, "Calling subscribe failure for client %s", m->c->clientID);
  1928. (*(command->command.onFailure5))(command->command.context, &data);
  1929. }
  1930. }
  1931. else if (command->command.onSuccess5)
  1932. {
  1933. MQTTAsync_successData5 data;
  1934. enum MQTTReasonCodes* array = NULL;
  1935. data.reasonCode = *(int*)(sub->qoss->first->content);
  1936. data.alt.sub.reasonCodeCount = sub->qoss->count;
  1937. if (sub->qoss->count > 1)
  1938. {
  1939. ListElement* cur_qos = NULL;
  1940. enum MQTTReasonCodes* element = array = data.alt.sub.reasonCodes = malloc(sub->qoss->count * sizeof(enum MQTTReasonCodes));
  1941. if (array)
  1942. while (ListNextElement(sub->qoss, &cur_qos))
  1943. *element++ = *(int*)(cur_qos->content);
  1944. }
  1945. data.token = command->command.token;
  1946. data.properties = sub->properties;
  1947. Log(TRACE_MIN, -1, "Calling subscribe success for client %s", m->c->clientID);
  1948. (*(command->command.onSuccess5))(command->command.context, &data);
  1949. if (array)
  1950. free(array);
  1951. }
  1952. }
  1953. else if (sub->qoss->count == 1 && *(int*)(sub->qoss->first->content) == MQTT_BAD_SUBSCRIBE)
  1954. {
  1955. if (command->command.onFailure)
  1956. {
  1957. MQTTAsync_failureData data;
  1958. data.token = command->command.token;
  1959. data.code = *(int*)(sub->qoss->first->content);
  1960. data.message = NULL;
  1961. Log(TRACE_MIN, -1, "Calling subscribe failure for client %s", m->c->clientID);
  1962. (*(command->command.onFailure))(command->command.context, &data);
  1963. }
  1964. }
  1965. else if (command->command.onSuccess)
  1966. {
  1967. MQTTAsync_successData data;
  1968. int* array = NULL;
  1969. if (sub->qoss->count == 1)
  1970. data.alt.qos = *(int*)(sub->qoss->first->content);
  1971. else if (sub->qoss->count > 1)
  1972. {
  1973. ListElement* cur_qos = NULL;
  1974. int* element = array = data.alt.qosList = malloc(sub->qoss->count * sizeof(int));
  1975. if (array)
  1976. while (ListNextElement(sub->qoss, &cur_qos))
  1977. *element++ = *(int*)(cur_qos->content);
  1978. }
  1979. data.token = command->command.token;
  1980. Log(TRACE_MIN, -1, "Calling subscribe success for client %s", m->c->clientID);
  1981. (*(command->command.onSuccess))(command->command.context, &data);
  1982. if (array)
  1983. free(array);
  1984. }
  1985. MQTTAsync_freeCommand(command);
  1986. break;
  1987. }
  1988. }
  1989. rc = MQTTProtocol_handleSubacks(pack, m->c->net.socket);
  1990. }
  1991. else if (pack->header.bits.type == UNSUBACK)
  1992. {
  1993. ListElement* current = NULL;
  1994. Unsuback* unsub = (Unsuback*)pack;
  1995. /* use the msgid to find the callback to be called */
  1996. while (ListNextElement(m->responses, &current))
  1997. {
  1998. MQTTAsync_queuedCommand* command = (MQTTAsync_queuedCommand*)(current->content);
  1999. if (command->command.token == ((Unsuback*)pack)->msgId)
  2000. {
  2001. if (!ListDetach(m->responses, command)) /* remove the response from the list */
  2002. Log(LOG_ERROR, -1, "Unsubscribe command not removed from command list");
  2003. if (command->command.onSuccess || command->command.onSuccess5)
  2004. {
  2005. Log(TRACE_MIN, -1, "Calling unsubscribe success for client %s", m->c->clientID);
  2006. if (command->command.onSuccess)
  2007. {
  2008. MQTTAsync_successData data;
  2009. memset(&data, '\0', sizeof(data));
  2010. data.token = command->command.token;
  2011. (*(command->command.onSuccess))(command->command.context, &data);
  2012. }
  2013. else
  2014. {
  2015. MQTTAsync_successData5 data = MQTTAsync_successData5_initializer;
  2016. enum MQTTReasonCodes* array = NULL;
  2017. data.reasonCode = *(enum MQTTReasonCodes*)(unsub->reasonCodes->first->content);
  2018. data.alt.unsub.reasonCodeCount = unsub->reasonCodes->count;
  2019. if (unsub->reasonCodes->count > 1)
  2020. {
  2021. ListElement* cur_rc = NULL;
  2022. enum MQTTReasonCodes* element = array = data.alt.unsub.reasonCodes = malloc(unsub->reasonCodes->count * sizeof(enum MQTTReasonCodes));
  2023. if (array)
  2024. while (ListNextElement(unsub->reasonCodes, &cur_rc))
  2025. *element++ = *(enum MQTTReasonCodes*)(cur_rc->content);
  2026. }
  2027. data.token = command->command.token;
  2028. data.properties = unsub->properties;
  2029. Log(TRACE_MIN, -1, "Calling unsubscribe success for client %s", m->c->clientID);
  2030. (*(command->command.onSuccess5))(command->command.context, &data);
  2031. if (array)
  2032. free(array);
  2033. }
  2034. }
  2035. MQTTAsync_freeCommand(command);
  2036. break;
  2037. }
  2038. }
  2039. rc = MQTTProtocol_handleUnsubacks(pack, m->c->net.socket);
  2040. }
  2041. else if (pack->header.bits.type == DISCONNECT)
  2042. {
  2043. Ack* disc = (Ack*)pack;
  2044. int discrc = 0;
  2045. discrc = disc->rc;
  2046. if (m->disconnected)
  2047. {
  2048. Log(TRACE_MIN, -1, "Calling disconnected for client %s", m->c->clientID);
  2049. (*(m->disconnected))(m->disconnected_context, &disc->properties, disc->rc);
  2050. }
  2051. rc = MQTTProtocol_handleDisconnects(pack, m->c->net.socket);
  2052. m->c->connected = 0; /* don't send disconnect packet back */
  2053. nextOrClose(m, discrc, "Received disconnect");
  2054. }
  2055. }
  2056. }
  2057. }
  2058. receiveThread_state = STOPPED;
  2059. receiveThread_id = 0;
  2060. MQTTAsync_unlock_mutex(mqttasync_mutex);
  2061. #if !defined(_WIN32) && !defined(_WIN64)
  2062. if (sendThread_state != STOPPED)
  2063. Thread_signal_cond(send_cond);
  2064. #else
  2065. if (sendThread_state != STOPPED)
  2066. Thread_post_sem(send_sem);
  2067. #endif
  2068. FUNC_EXIT;
  2069. #if defined(_WIN32) || defined(_WIN64)
  2070. ExitThread(0);
  2071. #endif
  2072. return 0;
  2073. }
  2074. static void MQTTAsync_stop(void)
  2075. {
  2076. #if !defined(NOSTACKTRACE)
  2077. int rc = 0;
  2078. #endif
  2079. FUNC_ENTRY;
  2080. if (sendThread_state != STOPPED || receiveThread_state != STOPPED)
  2081. {
  2082. int conn_count = 0;
  2083. ListElement* current = NULL;
  2084. if (MQTTAsync_handles != NULL)
  2085. {
  2086. /* find out how many handles are still connected */
  2087. while (ListNextElement(MQTTAsync_handles, &current))
  2088. {
  2089. if (((MQTTAsyncs*)(current->content))->c->connect_state > NOT_IN_PROGRESS ||
  2090. ((MQTTAsyncs*)(current->content))->c->connected)
  2091. ++conn_count;
  2092. }
  2093. }
  2094. Log(TRACE_MIN, -1, "Conn_count is %d", conn_count);
  2095. /* stop the background thread, if we are the last one to be using it */
  2096. if (conn_count == 0)
  2097. {
  2098. int count = 0;
  2099. MQTTAsync_tostop = 1;
  2100. while ((sendThread_state != STOPPED || receiveThread_state != STOPPED) && MQTTAsync_tostop != 0 && ++count < 100)
  2101. {
  2102. MQTTAsync_unlock_mutex(mqttasync_mutex);
  2103. Log(TRACE_MIN, -1, "sleeping");
  2104. MQTTAsync_sleep(100L);
  2105. MQTTAsync_lock_mutex(mqttasync_mutex);
  2106. }
  2107. #if !defined(NOSTACKTRACE)
  2108. rc = 1;
  2109. #endif
  2110. MQTTAsync_tostop = 0;
  2111. }
  2112. }
  2113. FUNC_EXIT_RC(rc);
  2114. }
  2115. static void MQTTAsync_closeOnly(Clients* client, enum MQTTReasonCodes reasonCode, MQTTProperties* props)
  2116. {
  2117. FUNC_ENTRY;
  2118. client->good = 0;
  2119. client->ping_outstanding = 0;
  2120. client->ping_due = 0;
  2121. if (client->net.socket > 0)
  2122. {
  2123. MQTTProtocol_checkPendingWrites();
  2124. if (client->connected && Socket_noPendingWrites(client->net.socket))
  2125. MQTTPacket_send_disconnect(client, reasonCode, props);
  2126. MQTTAsync_lock_mutex(socket_mutex);
  2127. WebSocket_close(&client->net, WebSocket_CLOSE_NORMAL, NULL);
  2128. #if defined(OPENSSL)
  2129. SSL_SESSION_free(client->session); /* is a no-op if session is NULL */
  2130. client->session = NULL; /* show the session has been freed */
  2131. SSLSocket_close(&client->net);
  2132. #endif
  2133. Socket_close(client->net.socket);
  2134. client->net.socket = 0;
  2135. #if defined(OPENSSL)
  2136. client->net.ssl = NULL;
  2137. #endif
  2138. MQTTAsync_unlock_mutex(socket_mutex);
  2139. }
  2140. client->connected = 0;
  2141. client->connect_state = NOT_IN_PROGRESS;
  2142. FUNC_EXIT;
  2143. }
  2144. void MQTTAsync_closeSession(Clients* client, enum MQTTReasonCodes reasonCode, MQTTProperties* props)
  2145. {
  2146. FUNC_ENTRY;
  2147. MQTTAsync_closeOnly(client, reasonCode, props);
  2148. if (client->cleansession ||
  2149. (client->MQTTVersion >= MQTTVERSION_5 && client->sessionExpiry == 0))
  2150. MQTTAsync_cleanSession(client);
  2151. FUNC_EXIT;
  2152. }
  2153. /**
  2154. * List callback function for comparing clients by client structure
  2155. * @param a Async structure
  2156. * @param b Client structure
  2157. * @return boolean indicating whether a and b are equal
  2158. */
  2159. static int clientStructCompare(void* a, void* b)
  2160. {
  2161. MQTTAsyncs* m = (MQTTAsyncs*)a;
  2162. return m->c == (Clients*)b;
  2163. }
  2164. /*
  2165. * Set destinationName and payload to NULL in all responses
  2166. * for a client, so that these memory locations aren't freed twice as they
  2167. * are also stored by MQTTProtocol_storePublication.
  2168. * @param m the client to process
  2169. */
  2170. void MQTTAsync_NULLPublishResponses(MQTTAsyncs* m)
  2171. {
  2172. FUNC_ENTRY;
  2173. if (m->responses)
  2174. {
  2175. ListElement* cur_response = NULL;
  2176. while (ListNextElement(m->responses, &cur_response))
  2177. {
  2178. MQTTAsync_queuedCommand* command = (MQTTAsync_queuedCommand*)(cur_response->content);
  2179. if (command->command.type == PUBLISH)
  2180. {
  2181. /* these values are going to be freed in RemovePublication */
  2182. command->command.details.pub.destinationName = NULL;
  2183. command->command.details.pub.payload = NULL;
  2184. }
  2185. }
  2186. }
  2187. FUNC_EXIT;
  2188. }
  2189. /*
  2190. * Set destinationName and payload to NULL in all commands
  2191. * for a client, so that these memory locations aren't freed twice as they
  2192. * are also stored by MQTTProtocol_storePublication.
  2193. * @param m the client to process
  2194. */
  2195. void MQTTAsync_NULLPublishCommands(MQTTAsyncs* m)
  2196. {
  2197. ListElement* current = NULL;
  2198. ListElement *next = NULL;
  2199. FUNC_ENTRY;
  2200. current = ListNextElement(MQTTAsync_commands, &next);
  2201. ListNextElement(MQTTAsync_commands, &next);
  2202. while (current)
  2203. {
  2204. MQTTAsync_queuedCommand* command = (MQTTAsync_queuedCommand*)(current->content);
  2205. if (command->client == m && command->command.type == PUBLISH)
  2206. {
  2207. /* these values are going to be freed in RemovePublication */
  2208. command->command.details.pub.destinationName = NULL;
  2209. command->command.details.pub.payload = NULL;
  2210. }
  2211. current = next;
  2212. ListNextElement(MQTTAsync_commands, &next);
  2213. }
  2214. FUNC_EXIT;
  2215. }
  2216. /**
  2217. * Clean the MQTT session data. This includes the MQTT inflight messages, because
  2218. * that is part of the MQTT state that will be cleared by the MQTT broker too.
  2219. * However, queued up messages, outgoing or incoming, need (should?) not be cleared
  2220. * as they are outside the scope of the MQTT session.
  2221. */
  2222. static int MQTTAsync_cleanSession(Clients* client)
  2223. {
  2224. int rc = 0;
  2225. ListElement* found = NULL;
  2226. FUNC_ENTRY;
  2227. #if !defined(NO_PERSISTENCE)
  2228. rc = MQTTAsync_unpersistInflightMessages(client);
  2229. #endif
  2230. MQTTProtocol_emptyMessageList(client->inboundMsgs);
  2231. MQTTProtocol_emptyMessageList(client->outboundMsgs);
  2232. client->msgID = 0;
  2233. if ((found = ListFindItem(MQTTAsync_handles, client, clientStructCompare)) != NULL)
  2234. {
  2235. MQTTAsyncs* m = (MQTTAsyncs*)(found->content);
  2236. MQTTAsync_NULLPublishResponses(m);
  2237. MQTTAsync_freeResponses(m);
  2238. }
  2239. else
  2240. Log(LOG_ERROR, -1, "cleanSession: did not find client structure in handles list");
  2241. FUNC_EXIT_RC(rc);
  2242. return rc;
  2243. }
  2244. /*
  2245. * Deliver a message to the messageArrived callback
  2246. * @param m a client structure
  2247. * @param topicName the name of the topic on which the message is being delivered
  2248. * @param topicLen the length of the topic name string
  2249. * @param mm the message to be delivered
  2250. * @return boolean 1 means message has been delivered, 0 that it has not
  2251. */
  2252. static int MQTTAsync_deliverMessage(MQTTAsyncs* m, char* topicName, size_t topicLen, MQTTAsync_message* mm)
  2253. {
  2254. int rc;
  2255. Log(TRACE_MIN, -1, "Calling messageArrived for client %s, queue depth %d",
  2256. m->c->clientID, m->c->messageQueue->count);
  2257. rc = (*(m->ma))(m->maContext, topicName, (int)topicLen, mm);
  2258. /* if 0 (false) is returned by the callback then it failed, so we don't remove the message from
  2259. * the queue, and it will be retried later. If 1 is returned then the message data may have been freed,
  2260. * so we must be careful how we use it.
  2261. */
  2262. return rc;
  2263. }
  2264. void Protocol_processPublication(Publish* publish, Clients* client, int allocatePayload)
  2265. {
  2266. MQTTAsync_message* mm = NULL;
  2267. MQTTAsync_message initialized = MQTTAsync_message_initializer;
  2268. int rc = 0;
  2269. FUNC_ENTRY;
  2270. if ((mm = malloc(sizeof(MQTTAsync_message))) == NULL)
  2271. goto exit;
  2272. memcpy(mm, &initialized, sizeof(MQTTAsync_message));
  2273. if (allocatePayload)
  2274. {
  2275. if ((mm->payload = malloc(publish->payloadlen)) == NULL)
  2276. {
  2277. free(mm);
  2278. goto exit;
  2279. }
  2280. memcpy(mm->payload, publish->payload, publish->payloadlen);
  2281. } else
  2282. mm->payload = publish->payload;
  2283. mm->payloadlen = publish->payloadlen;
  2284. mm->qos = publish->header.bits.qos;
  2285. mm->retained = publish->header.bits.retain;
  2286. if (publish->header.bits.qos == 2)
  2287. mm->dup = 0; /* ensure that a QoS2 message is not passed to the application with dup = 1 */
  2288. else
  2289. mm->dup = publish->header.bits.dup;
  2290. mm->msgid = publish->msgId;
  2291. if (publish->MQTTVersion >= MQTTVERSION_5)
  2292. mm->properties = MQTTProperties_copy(&publish->properties);
  2293. if (client->messageQueue->count == 0 && client->connected)
  2294. {
  2295. ListElement* found = NULL;
  2296. if ((found = ListFindItem(MQTTAsync_handles, client, clientStructCompare)) == NULL)
  2297. Log(LOG_ERROR, -1, "processPublication: did not find client structure in handles list");
  2298. else
  2299. {
  2300. MQTTAsyncs* m = (MQTTAsyncs*)(found->content);
  2301. if (m->ma)
  2302. rc = MQTTAsync_deliverMessage(m, publish->topic, publish->topiclen, mm);
  2303. else
  2304. Log(LOG_ERROR, -1, "Message arrived for client %s but can't deliver it. No messageArrived callback",
  2305. m->c->clientID);
  2306. }
  2307. }
  2308. if (rc == 0) /* if message was not delivered, queue it up */
  2309. {
  2310. qEntry* qe = malloc(sizeof(qEntry));
  2311. if (!qe)
  2312. goto exit;
  2313. qe->msg = mm;
  2314. qe->topicName = publish->topic;
  2315. qe->topicLen = publish->topiclen;
  2316. ListAppend(client->messageQueue, qe, sizeof(qe) + sizeof(mm) + mm->payloadlen + strlen(qe->topicName)+1);
  2317. #if !defined(NO_PERSISTENCE)
  2318. if (client->persistence)
  2319. MQTTPersistence_persistQueueEntry(client, (MQTTPersistence_qEntry*)qe);
  2320. #endif
  2321. }
  2322. exit:
  2323. publish->topic = NULL;
  2324. FUNC_EXIT;
  2325. }
  2326. static int retryLoopIntervalms = 5000;
  2327. void setRetryLoopInterval(int keepalive)
  2328. {
  2329. retryLoopIntervalms = (keepalive*1000) / 10;
  2330. if (retryLoopIntervalms < 100)
  2331. retryLoopIntervalms = 100;
  2332. else if (retryLoopIntervalms > 5000)
  2333. retryLoopIntervalms = 5000;
  2334. }
  2335. int MQTTAsync_disconnect1(MQTTAsync handle, const MQTTAsync_disconnectOptions* options, int internal)
  2336. {
  2337. MQTTAsyncs* m = handle;
  2338. int rc = MQTTASYNC_SUCCESS;
  2339. MQTTAsync_queuedCommand* dis;
  2340. FUNC_ENTRY;
  2341. if (m == NULL || m->c == NULL)
  2342. {
  2343. rc = MQTTASYNC_FAILURE;
  2344. goto exit;
  2345. }
  2346. if (!internal)
  2347. m->shouldBeConnected = 0;
  2348. if (m->c->connected == 0)
  2349. {
  2350. rc = MQTTASYNC_DISCONNECTED;
  2351. goto exit;
  2352. }
  2353. /* Add disconnect request to operation queue */
  2354. if ((dis = malloc(sizeof(MQTTAsync_queuedCommand))) == NULL)
  2355. {
  2356. rc = PAHO_MEMORY_ERROR;
  2357. goto exit;
  2358. }
  2359. memset(dis, '\0', sizeof(MQTTAsync_queuedCommand));
  2360. dis->client = m;
  2361. if (options)
  2362. {
  2363. dis->command.onSuccess = options->onSuccess;
  2364. dis->command.onFailure = options->onFailure;
  2365. dis->command.onSuccess5 = options->onSuccess5;
  2366. dis->command.onFailure5 = options->onFailure5;
  2367. dis->command.context = options->context;
  2368. dis->command.details.dis.timeout = options->timeout;
  2369. if (m->c->MQTTVersion >= MQTTVERSION_5 && options->struct_version >= 1)
  2370. {
  2371. dis->command.properties = MQTTProperties_copy(&options->properties);
  2372. dis->command.details.dis.reasonCode = options->reasonCode;
  2373. }
  2374. }
  2375. dis->command.type = DISCONNECT;
  2376. dis->command.details.dis.internal = internal;
  2377. rc = MQTTAsync_addCommand(dis, sizeof(dis));
  2378. exit:
  2379. FUNC_EXIT_RC(rc);
  2380. return rc;
  2381. }
  2382. static int MQTTAsync_disconnect_internal(MQTTAsync handle, int timeout)
  2383. {
  2384. MQTTAsync_disconnectOptions options = MQTTAsync_disconnectOptions_initializer;
  2385. options.timeout = timeout;
  2386. return MQTTAsync_disconnect1(handle, &options, 1);
  2387. }
  2388. void MQTTProtocol_closeSession(Clients* c, int sendwill)
  2389. {
  2390. nextOrClose((MQTTAsync)c->context, MQTTASYNC_DISCONNECTED, "MQTTProtocol_closeSession");
  2391. }
  2392. static int cmdMessageIDCompare(void* a, void* b)
  2393. {
  2394. MQTTAsync_queuedCommand* cmd = (MQTTAsync_queuedCommand*)a;
  2395. return cmd->command.token == *(int*)b;
  2396. }
  2397. /**
  2398. * Assign a new message id for a client. Make sure it isn't already being used and does
  2399. * not exceed the maximum.
  2400. * @param m a client structure
  2401. * @return the next message id to use, or 0 if none available
  2402. */
  2403. int MQTTAsync_assignMsgId(MQTTAsyncs* m)
  2404. {
  2405. int start_msgid;
  2406. int msgid;
  2407. thread_id_type thread_id = 0;
  2408. int locked = 0;
  2409. /* need to check: commands list and response list for a client */
  2410. FUNC_ENTRY;
  2411. /* We might be called in a callback. In which case, this mutex will be already locked. */
  2412. thread_id = Thread_getid();
  2413. if (thread_id != sendThread_id && thread_id != receiveThread_id)
  2414. {
  2415. MQTTAsync_lock_mutex(mqttasync_mutex);
  2416. locked = 1;
  2417. }
  2418. /* Fetch last message ID in locked state */
  2419. start_msgid = m->c->msgID;
  2420. msgid = start_msgid;
  2421. MQTTAsync_lock_mutex(mqttcommand_mutex);
  2422. msgid = (msgid == MAX_MSG_ID) ? 1 : msgid + 1;
  2423. while (ListFindItem(MQTTAsync_commands, &msgid, cmdMessageIDCompare) ||
  2424. ListFindItem(m->c->outboundMsgs, &msgid, messageIDCompare) ||
  2425. ListFindItem(m->responses, &msgid, cmdMessageIDCompare))
  2426. {
  2427. msgid = (msgid == MAX_MSG_ID) ? 1 : msgid + 1;
  2428. if (msgid == start_msgid)
  2429. { /* we've tried them all - none free */
  2430. msgid = 0;
  2431. break;
  2432. }
  2433. }
  2434. MQTTAsync_unlock_mutex(mqttcommand_mutex);
  2435. if (msgid != 0)
  2436. m->c->msgID = msgid;
  2437. if (locked)
  2438. MQTTAsync_unlock_mutex(mqttasync_mutex);
  2439. FUNC_EXIT_RC(msgid);
  2440. return msgid;
  2441. }
  2442. static void MQTTAsync_retry(void)
  2443. {
  2444. static START_TIME_TYPE last = START_TIME_ZERO;
  2445. START_TIME_TYPE now;
  2446. FUNC_ENTRY;
  2447. now = MQTTTime_now();
  2448. if (MQTTTime_difftime(now, last) >= (DIFF_TIME_TYPE)(retryLoopIntervalms))
  2449. {
  2450. last = MQTTTime_now();
  2451. MQTTProtocol_keepalive(now);
  2452. MQTTProtocol_retry(now, 1, 0);
  2453. }
  2454. else
  2455. MQTTProtocol_retry(now, 0, 0);
  2456. FUNC_EXIT;
  2457. }
  2458. static int MQTTAsync_connecting(MQTTAsyncs* m)
  2459. {
  2460. int rc = -1;
  2461. char* serverURI = m->serverURI;
  2462. #if defined(OPENSSL)
  2463. int default_port = MQTT_DEFAULT_PORT;
  2464. #endif
  2465. FUNC_ENTRY;
  2466. /* This was reported in #1007, but I've not been able to reproduce it. It feels like this is
  2467. * covering up the issue, if it exists. If the error message is ever seen, please consider
  2468. * reporting the circumstances so that more debugging can occur. Thanks - IGC.
  2469. */
  2470. if (m->connect.details.conn.MQTTVersion == MQTTVERSION_DEFAULT) /* should not happen - #1007 */
  2471. {
  2472. Log(LOG_ERROR, -1, "MQTT version is 0 in MQTTAsync_connecting");
  2473. m->connect.details.conn.MQTTVersion = (m->c->MQTTVersion == MQTTVERSION_DEFAULT) ? MQTTVERSION_3_1_1 : m->c->MQTTVersion;
  2474. }
  2475. /* End of #1007 avoiding code */
  2476. if (m->serverURIcount > 0)
  2477. {
  2478. serverURI = m->serverURIs[m->connect.details.conn.currentURI];
  2479. /* skip URI scheme */
  2480. if (strncmp(URI_TCP, serverURI, strlen(URI_TCP)) == 0)
  2481. serverURI += strlen(URI_TCP);
  2482. else if (strncmp(URI_MQTT, serverURI, strlen(URI_MQTT)) == 0)
  2483. serverURI += strlen(URI_MQTT);
  2484. else if (strncmp(URI_WS, serverURI, strlen(URI_WS)) == 0)
  2485. {
  2486. serverURI += strlen(URI_WS);
  2487. #if defined(OPENSSL)
  2488. default_port = WS_DEFAULT_PORT;
  2489. #endif
  2490. }
  2491. #if defined(OPENSSL)
  2492. else if (strncmp(URI_SSL, serverURI, strlen(URI_SSL)) == 0)
  2493. {
  2494. serverURI += strlen(URI_SSL);
  2495. default_port = SECURE_MQTT_DEFAULT_PORT;
  2496. }
  2497. else if (strncmp(URI_MQTTS, serverURI, strlen(URI_MQTTS)) == 0)
  2498. {
  2499. serverURI += strlen(URI_MQTTS);
  2500. default_port = SECURE_MQTT_DEFAULT_PORT;
  2501. }
  2502. else if (strncmp(URI_WSS, serverURI, strlen(URI_WSS)) == 0)
  2503. {
  2504. serverURI += strlen(URI_WSS);
  2505. default_port = WSS_DEFAULT_PORT;
  2506. }
  2507. #endif
  2508. }
  2509. if (m->c->connect_state == TCP_IN_PROGRESS) /* TCP connect started - check for completion */
  2510. {
  2511. int error;
  2512. socklen_t len = sizeof(error);
  2513. if ((rc = getsockopt(m->c->net.socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len)) == 0)
  2514. rc = error;
  2515. if (rc != 0)
  2516. goto exit;
  2517. Socket_clearPendingWrite(m->c->net.socket);
  2518. #if defined(OPENSSL)
  2519. if (m->ssl)
  2520. {
  2521. int port;
  2522. size_t hostname_len;
  2523. int setSocketForSSLrc = 0;
  2524. if (m->c->net.https_proxy) {
  2525. m->c->connect_state = PROXY_CONNECT_IN_PROGRESS;
  2526. if ((rc = Proxy_connect( &m->c->net, 1, serverURI)) == SOCKET_ERROR )
  2527. goto exit;
  2528. }
  2529. hostname_len = MQTTProtocol_addressPort(serverURI, &port, NULL, default_port);
  2530. setSocketForSSLrc = SSLSocket_setSocketForSSL(&m->c->net, m->c->sslopts,
  2531. serverURI, hostname_len);
  2532. if (setSocketForSSLrc != MQTTASYNC_SUCCESS)
  2533. {
  2534. if (m->c->session != NULL)
  2535. if ((rc = SSL_set_session(m->c->net.ssl, m->c->session)) != 1)
  2536. Log(TRACE_MIN, -1, "Failed to set SSL session with stored data, non critical");
  2537. rc = m->c->sslopts->struct_version >= 3 ?
  2538. SSLSocket_connect(m->c->net.ssl, m->c->net.socket, serverURI,
  2539. m->c->sslopts->verify, m->c->sslopts->ssl_error_cb, m->c->sslopts->ssl_error_context) :
  2540. SSLSocket_connect(m->c->net.ssl, m->c->net.socket, serverURI,
  2541. m->c->sslopts->verify, NULL, NULL);
  2542. if (rc == TCPSOCKET_INTERRUPTED)
  2543. {
  2544. rc = MQTTCLIENT_SUCCESS; /* the connect is still in progress */
  2545. m->c->connect_state = SSL_IN_PROGRESS;
  2546. }
  2547. else if (rc == SSL_FATAL)
  2548. {
  2549. rc = SOCKET_ERROR;
  2550. goto exit;
  2551. }
  2552. else if (rc == 1)
  2553. {
  2554. if ( m->websocket )
  2555. {
  2556. m->c->connect_state = WEBSOCKET_IN_PROGRESS;
  2557. if ((rc = WebSocket_connect(&m->c->net, m->ssl, serverURI)) == SOCKET_ERROR )
  2558. goto exit;
  2559. }
  2560. else
  2561. {
  2562. rc = MQTTCLIENT_SUCCESS;
  2563. m->c->connect_state = WAIT_FOR_CONNACK;
  2564. if (MQTTPacket_send_connect(m->c, m->connect.details.conn.MQTTVersion,
  2565. m->connectProps, m->willProps) == SOCKET_ERROR)
  2566. {
  2567. rc = SOCKET_ERROR;
  2568. goto exit;
  2569. }
  2570. }
  2571. if (!m->c->cleansession && m->c->session == NULL)
  2572. m->c->session = SSL_get1_session(m->c->net.ssl);
  2573. }
  2574. }
  2575. else
  2576. {
  2577. rc = SOCKET_ERROR;
  2578. goto exit;
  2579. }
  2580. }
  2581. else
  2582. {
  2583. #endif
  2584. if (m->c->net.http_proxy) {
  2585. m->c->connect_state = PROXY_CONNECT_IN_PROGRESS;
  2586. if ((rc = Proxy_connect( &m->c->net, 0, serverURI)) == SOCKET_ERROR )
  2587. goto exit;
  2588. }
  2589. if ( m->websocket )
  2590. {
  2591. m->c->connect_state = WEBSOCKET_IN_PROGRESS;
  2592. if ((rc = WebSocket_connect(&m->c->net, 0, serverURI)) == SOCKET_ERROR )
  2593. goto exit;
  2594. }
  2595. else
  2596. {
  2597. m->c->connect_state = WAIT_FOR_CONNACK; /* TCP/SSL connect completed, in which case send the MQTT connect packet */
  2598. if ((rc = MQTTPacket_send_connect(m->c, m->connect.details.conn.MQTTVersion,
  2599. m->connectProps, m->willProps)) == SOCKET_ERROR)
  2600. goto exit;
  2601. }
  2602. #if defined(OPENSSL)
  2603. }
  2604. #endif
  2605. }
  2606. #if defined(OPENSSL)
  2607. else if (m->c->connect_state == SSL_IN_PROGRESS) /* SSL connect sent - wait for completion */
  2608. {
  2609. rc = m->c->sslopts->struct_version >= 3 ?
  2610. SSLSocket_connect(m->c->net.ssl, m->c->net.socket, serverURI,
  2611. m->c->sslopts->verify, m->c->sslopts->ssl_error_cb, m->c->sslopts->ssl_error_context) :
  2612. SSLSocket_connect(m->c->net.ssl, m->c->net.socket, serverURI,
  2613. m->c->sslopts->verify, NULL, NULL);
  2614. if (rc != 1)
  2615. goto exit;
  2616. if(!m->c->cleansession && m->c->session == NULL)
  2617. m->c->session = SSL_get1_session(m->c->net.ssl);
  2618. if ( m->websocket )
  2619. {
  2620. m->c->connect_state = WEBSOCKET_IN_PROGRESS;
  2621. if ((rc = WebSocket_connect(&m->c->net, 1, serverURI)) == SOCKET_ERROR )
  2622. goto exit;
  2623. }
  2624. else
  2625. {
  2626. m->c->connect_state = WAIT_FOR_CONNACK; /* SSL connect completed, in which case send the MQTT connect packet */
  2627. if ((rc = MQTTPacket_send_connect(m->c, m->connect.details.conn.MQTTVersion,
  2628. m->connectProps, m->willProps)) == SOCKET_ERROR)
  2629. goto exit;
  2630. }
  2631. }
  2632. #endif
  2633. else if (m->c->connect_state == WEBSOCKET_IN_PROGRESS) /* Websocket connect sent - wait for completion */
  2634. {
  2635. if ((rc = WebSocket_upgrade( &m->c->net ) ) == SOCKET_ERROR )
  2636. goto exit;
  2637. else if (rc != TCPSOCKET_INTERRUPTED)
  2638. {
  2639. m->c->connect_state = WAIT_FOR_CONNACK; /* Websocket upgrade completed, in which case send the MQTT connect packet */
  2640. if ((rc = MQTTPacket_send_connect(m->c, m->connect.details.conn.MQTTVersion, m->connectProps, m->willProps)) == SOCKET_ERROR)
  2641. goto exit;
  2642. }
  2643. }
  2644. exit:
  2645. if ((rc != 0 && rc != TCPSOCKET_INTERRUPTED && (m->c->connect_state != SSL_IN_PROGRESS && m->c->connect_state != WEBSOCKET_IN_PROGRESS)) || (rc == SSL_FATAL))
  2646. nextOrClose(m, MQTTASYNC_FAILURE, "TCP/TLS connect failure");
  2647. FUNC_EXIT_RC(rc);
  2648. return rc;
  2649. }
  2650. static MQTTPacket* MQTTAsync_cycle(SOCKET* sock, unsigned long timeout, int* rc)
  2651. {
  2652. MQTTPacket* pack = NULL;
  2653. int rc1 = 0;
  2654. FUNC_ENTRY;
  2655. #if defined(OPENSSL)
  2656. if ((*sock = SSLSocket_getPendingRead()) == -1)
  2657. {
  2658. #endif
  2659. int should_stop = 0;
  2660. /* 0 from getReadySocket indicates no work to do, rc -1 == error */
  2661. *sock = Socket_getReadySocket(0, (int)timeout, socket_mutex, &rc1);
  2662. *rc = rc1;
  2663. MQTTAsync_lock_mutex(mqttasync_mutex);
  2664. should_stop = MQTTAsync_tostop;
  2665. MQTTAsync_unlock_mutex(mqttasync_mutex);
  2666. if (!should_stop && *sock == 0 && (timeout > 0L))
  2667. MQTTAsync_sleep(100L);
  2668. #if defined(OPENSSL)
  2669. }
  2670. #endif
  2671. MQTTAsync_lock_mutex(mqttasync_mutex);
  2672. if (*sock > 0 && rc1 == 0)
  2673. {
  2674. MQTTAsyncs* m = NULL;
  2675. if (ListFindItem(MQTTAsync_handles, sock, clientSockCompare) != NULL)
  2676. m = (MQTTAsync)(MQTTAsync_handles->current->content);
  2677. if (m != NULL)
  2678. {
  2679. Log(TRACE_MINIMUM, -1, "m->c->connect_state = %d", m->c->connect_state);
  2680. if (m->c->connect_state == TCP_IN_PROGRESS || m->c->connect_state == SSL_IN_PROGRESS || m->c->connect_state == WEBSOCKET_IN_PROGRESS)
  2681. *rc = MQTTAsync_connecting(m);
  2682. else
  2683. pack = MQTTPacket_Factory(m->c->MQTTVersion, &m->c->net, rc);
  2684. if (m->c->connect_state == WAIT_FOR_CONNACK && *rc == SOCKET_ERROR)
  2685. {
  2686. Log(TRACE_MINIMUM, -1, "CONNECT sent but MQTTPacket_Factory has returned SOCKET_ERROR");
  2687. nextOrClose(m, MQTTASYNC_FAILURE, "TCP connect completion failure");
  2688. }
  2689. }
  2690. if (pack)
  2691. {
  2692. int freed = 1;
  2693. /* Note that these handle... functions free the packet structure that they are dealing with */
  2694. if (pack->header.bits.type == PUBLISH)
  2695. *rc = MQTTProtocol_handlePublishes(pack, *sock);
  2696. else if (pack->header.bits.type == PUBACK || pack->header.bits.type == PUBCOMP ||
  2697. pack->header.bits.type == PUBREC)
  2698. {
  2699. int msgid = 0,
  2700. msgtype = 0,
  2701. ackrc = 0,
  2702. mqttversion = 0;
  2703. MQTTProperties msgprops = MQTTProperties_initializer;
  2704. Publications* pubToRemove = NULL;
  2705. /* This block is so that the ack variable is local and isn't accidentally reused */
  2706. {
  2707. static Ack ack;
  2708. ack = *(Ack*)pack;
  2709. /* these values are stored because the packet structure is freed in the handle functions */
  2710. msgid = ack.msgId;
  2711. msgtype = pack->header.bits.type;
  2712. if (ack.MQTTVersion >= MQTTVERSION_5)
  2713. {
  2714. ackrc = ack.rc;
  2715. msgprops = MQTTProperties_copy(&ack.properties);
  2716. mqttversion = ack.MQTTVersion;
  2717. }
  2718. }
  2719. if (pack->header.bits.type == PUBCOMP)
  2720. *rc = MQTTProtocol_handlePubcomps(pack, *sock, &pubToRemove);
  2721. else if (pack->header.bits.type == PUBREC)
  2722. *rc = MQTTProtocol_handlePubrecs(pack, *sock, &pubToRemove);
  2723. else if (pack->header.bits.type == PUBACK)
  2724. *rc = MQTTProtocol_handlePubacks(pack, *sock, &pubToRemove);
  2725. if (!m)
  2726. Log(LOG_ERROR, -1, "PUBCOMP, PUBACK or PUBREC received for no client, msgid %d", msgid);
  2727. if (m && (msgtype != PUBREC || ackrc >= MQTTREASONCODE_UNSPECIFIED_ERROR))
  2728. {
  2729. ListElement* current = NULL;
  2730. if (m->dc)
  2731. {
  2732. Log(TRACE_MIN, -1, "Calling deliveryComplete for client %s, msgid %d", m->c->clientID, msgid);
  2733. (*(m->dc))(m->dcContext, msgid);
  2734. }
  2735. /* use the msgid to find the callback to be called */
  2736. while (ListNextElement(m->responses, &current))
  2737. {
  2738. MQTTAsync_queuedCommand* command = (MQTTAsync_queuedCommand*)(current->content);
  2739. if (command->command.token == msgid)
  2740. {
  2741. if (!ListDetach(m->responses, command)) /* then remove the response from the list */
  2742. Log(LOG_ERROR, -1, "Publish command not removed from command list");
  2743. if (command->command.onSuccess)
  2744. {
  2745. MQTTAsync_successData data;
  2746. data.token = command->command.token;
  2747. data.alt.pub.destinationName = command->command.details.pub.destinationName;
  2748. data.alt.pub.message.payload = command->command.details.pub.payload;
  2749. data.alt.pub.message.payloadlen = command->command.details.pub.payloadlen;
  2750. data.alt.pub.message.qos = command->command.details.pub.qos;
  2751. data.alt.pub.message.retained = command->command.details.pub.retained;
  2752. Log(TRACE_MIN, -1, "Calling publish success for client %s", m->c->clientID);
  2753. (*(command->command.onSuccess))(command->command.context, &data);
  2754. }
  2755. else if (command->command.onSuccess5 && ackrc < MQTTREASONCODE_UNSPECIFIED_ERROR)
  2756. {
  2757. MQTTAsync_successData5 data = MQTTAsync_successData5_initializer;
  2758. data.token = command->command.token;
  2759. data.alt.pub.destinationName = command->command.details.pub.destinationName;
  2760. data.alt.pub.message.payload = command->command.details.pub.payload;
  2761. data.alt.pub.message.payloadlen = command->command.details.pub.payloadlen;
  2762. data.alt.pub.message.qos = command->command.details.pub.qos;
  2763. data.alt.pub.message.retained = command->command.details.pub.retained;
  2764. data.properties = command->command.properties;
  2765. Log(TRACE_MIN, -1, "Calling publish success for client %s", m->c->clientID);
  2766. (*(command->command.onSuccess5))(command->command.context, &data);
  2767. }
  2768. else if (command->command.onFailure5 && ackrc >= MQTTREASONCODE_UNSPECIFIED_ERROR)
  2769. {
  2770. MQTTAsync_failureData5 data = MQTTAsync_failureData5_initializer;
  2771. data.token = command->command.token;
  2772. data.reasonCode = ackrc;
  2773. data.properties = msgprops;
  2774. data.packet_type = pack->header.bits.type;
  2775. Log(TRACE_MIN, -1, "Calling publish failure for client %s", m->c->clientID);
  2776. (*(command->command.onFailure5))(command->command.context, &data);
  2777. }
  2778. if (pubToRemove != NULL)
  2779. {
  2780. MQTTProtocol_removePublication(pubToRemove);
  2781. pubToRemove = NULL;
  2782. /* removePublication has freed the topic and payload memory, so here we indicate that
  2783. * so freeCommand doesn't try to free them again.
  2784. */
  2785. command->command.details.pub.destinationName = NULL;
  2786. command->command.details.pub.payload = NULL;
  2787. }
  2788. MQTTAsync_freeCommand(command);
  2789. break;
  2790. }
  2791. }
  2792. if (mqttversion >= MQTTVERSION_5)
  2793. MQTTProperties_free(&msgprops);
  2794. }
  2795. if (pubToRemove != NULL)
  2796. MQTTProtocol_removePublication(pubToRemove);
  2797. }
  2798. else if (pack->header.bits.type == PUBREL)
  2799. *rc = MQTTProtocol_handlePubrels(pack, *sock);
  2800. else if (pack->header.bits.type == PINGRESP)
  2801. *rc = MQTTProtocol_handlePingresps(pack, *sock);
  2802. else
  2803. freed = 0;
  2804. if (freed)
  2805. pack = NULL;
  2806. }
  2807. }
  2808. MQTTAsync_retry();
  2809. MQTTAsync_unlock_mutex(mqttasync_mutex);
  2810. FUNC_EXIT_RC(*rc);
  2811. return pack;
  2812. }
  2813. int MQTTAsync_getNoBufferedMessages(MQTTAsyncs* m)
  2814. {
  2815. int count = 0;
  2816. MQTTAsync_lock_mutex(mqttcommand_mutex);
  2817. count = m->noBufferedMessages;
  2818. MQTTAsync_unlock_mutex(mqttcommand_mutex);
  2819. return count;
  2820. }