MQTTAsyncUtils.c 102 KB

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