MQTTClient.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2024 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 API and implementation and/or initial documentation
  15. * Ian Craggs - bug 384016 - segv setting will message
  16. * Ian Craggs - bug 384053 - v1.0.0.7 - stop MQTTClient_receive on socket error
  17. * Ian Craggs, Allan Stockdill-Mander - add ability to connect with SSL
  18. * Ian Craggs - multiple server connection support
  19. * Ian Craggs - fix for bug 413429 - connectionLost not called
  20. * Ian Craggs - fix for bug 421103 - trying to write to same socket, in publish/retries
  21. * Ian Craggs - fix for bug 419233 - mutexes not reporting errors
  22. * Ian Craggs - fix for bug 420851
  23. * Ian Craggs - fix for bug 432903 - queue persistence
  24. * Ian Craggs - MQTT 3.1.1 support
  25. * Ian Craggs - fix for bug 438176 - MQTT version selection
  26. * Rong Xiang, Ian Craggs - C++ compatibility
  27. * Ian Craggs - fix for bug 443724 - stack corruption
  28. * Ian Craggs - fix for bug 447672 - simultaneous access to socket structure
  29. * Ian Craggs - fix for bug 459791 - deadlock in WaitForCompletion for bad client
  30. * Ian Craggs - fix for bug 474905 - insufficient synchronization for subscribe, unsubscribe, connect
  31. * Ian Craggs - make it clear that yield and receive are not intended for multi-threaded mode (bug 474748)
  32. * Ian Craggs - SNI support, message queue unpersist bug
  33. * Ian Craggs - binary will message support
  34. * Ian Craggs - waitforCompletion fix #240
  35. * Ian Craggs - check for NULL SSL options #334
  36. * Ian Craggs - allocate username/password buffers #431
  37. * Ian Craggs - MQTT 5.0 support
  38. * Sven Gambel - add generic proxy support
  39. *******************************************************************************/
  40. /**
  41. * @file
  42. * \brief Synchronous API implementation
  43. *
  44. */
  45. #include <stdlib.h>
  46. #include <string.h>
  47. #if !defined(_WIN32) && !defined(_WIN64)
  48. #include <sys/time.h>
  49. #else
  50. #if defined(_MSC_VER) && _MSC_VER < 1900
  51. #define snprintf _snprintf
  52. #endif
  53. #endif
  54. #include "MQTTClient.h"
  55. #if !defined(NO_PERSISTENCE)
  56. #include "MQTTPersistence.h"
  57. #endif
  58. #include "utf-8.h"
  59. #include "MQTTProtocol.h"
  60. #include "MQTTProtocolOut.h"
  61. #include "Thread.h"
  62. #include "SocketBuffer.h"
  63. #include "StackTrace.h"
  64. #include "Heap.h"
  65. #if defined(OPENSSL)
  66. #include <openssl/ssl.h>
  67. #else
  68. #define URI_SSL "ssl://"
  69. #define URI_MQTTS "mqtts://"
  70. #endif
  71. #include "OsWrapper.h"
  72. #define URI_TCP "tcp://"
  73. #define URI_MQTT "mqtt://"
  74. #define URI_WS "ws://"
  75. #define URI_WSS "wss://"
  76. #define URI_UNIX "unix://"
  77. #include "VersionInfo.h"
  78. #include "WebSocket.h"
  79. #include "Proxy.h"
  80. const char *client_timestamp_eye = "MQTTClientV3_Timestamp " BUILD_TIMESTAMP;
  81. const char *client_version_eye = "MQTTClientV3_Version " CLIENT_VERSION;
  82. struct conlost_sync_data {
  83. sem_type sem;
  84. void *m;
  85. };
  86. int MQTTClient_init(void);
  87. void MQTTClient_global_init(MQTTClient_init_options* inits)
  88. {
  89. MQTTClient_init();
  90. #if defined(OPENSSL)
  91. SSLSocket_handleOpensslInit(inits->do_openssl_init);
  92. #endif
  93. }
  94. static ClientStates ClientState =
  95. {
  96. CLIENT_VERSION, /* version */
  97. NULL /* client list */
  98. };
  99. ClientStates* bstate = &ClientState;
  100. MQTTProtocol state;
  101. #if defined(_WIN32) || defined(_WIN64)
  102. static mutex_type mqttclient_mutex = NULL;
  103. mutex_type socket_mutex = NULL;
  104. static mutex_type subscribe_mutex = NULL;
  105. static mutex_type connect_mutex = NULL;
  106. #if !defined(NO_HEAP_TRACKING)
  107. extern mutex_type stack_mutex;
  108. extern mutex_type heap_mutex;
  109. #endif
  110. extern mutex_type log_mutex;
  111. int MQTTClient_init(void)
  112. {
  113. DWORD rc = 0;
  114. if (mqttclient_mutex == NULL)
  115. {
  116. if ((mqttclient_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
  117. {
  118. rc = GetLastError();
  119. printf("mqttclient_mutex error %d\n", rc);
  120. goto exit;
  121. }
  122. if ((subscribe_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
  123. {
  124. rc = GetLastError();
  125. printf("subscribe_mutex error %d\n", rc);
  126. goto exit;
  127. }
  128. if ((connect_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
  129. {
  130. rc = GetLastError();
  131. printf("connect_mutex error %d\n", rc);
  132. goto exit;
  133. }
  134. #if !defined(NO_HEAP_TRACKING)
  135. if ((stack_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
  136. {
  137. rc = GetLastError();
  138. printf("stack_mutex error %d\n", rc);
  139. goto exit;
  140. }
  141. if ((heap_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
  142. {
  143. rc = GetLastError();
  144. printf("heap_mutex error %d\n", rc);
  145. goto exit;
  146. }
  147. #endif
  148. if ((log_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
  149. {
  150. rc = GetLastError();
  151. printf("log_mutex error %d\n", rc);
  152. goto exit;
  153. }
  154. if ((socket_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
  155. {
  156. rc = GetLastError();
  157. printf("socket_mutex error %d\n", rc);
  158. goto exit;
  159. }
  160. }
  161. exit:
  162. return rc;
  163. }
  164. void MQTTClient_cleanup(void)
  165. {
  166. if (connect_mutex)
  167. CloseHandle(connect_mutex);
  168. if (subscribe_mutex)
  169. CloseHandle(subscribe_mutex);
  170. #if !defined(NO_HEAP_TRACKING)
  171. if (stack_mutex)
  172. CloseHandle(stack_mutex);
  173. if (heap_mutex)
  174. CloseHandle(heap_mutex);
  175. #endif
  176. if (log_mutex)
  177. CloseHandle(log_mutex);
  178. if (socket_mutex)
  179. CloseHandle(socket_mutex);
  180. if (mqttclient_mutex)
  181. CloseHandle(mqttclient_mutex);
  182. }
  183. #if defined(PAHO_MQTT_STATIC)
  184. /* Global variable for one-time initialization structure */
  185. static INIT_ONCE g_InitOnce = INIT_ONCE_STATIC_INIT; /* Static initialization */
  186. /* One time initialization function */
  187. BOOL CALLBACK InitOnceFunction (
  188. PINIT_ONCE InitOnce, /* Pointer to one-time initialization structure */
  189. PVOID Parameter, /* Optional parameter passed by InitOnceExecuteOnce */
  190. PVOID *lpContext) /* Receives pointer to event object */
  191. {
  192. int rc = MQTTClient_init();
  193. return rc == 0;
  194. }
  195. #else
  196. BOOL APIENTRY DllMain(HANDLE hModule,
  197. DWORD ul_reason_for_call,
  198. LPVOID lpReserved)
  199. {
  200. switch (ul_reason_for_call)
  201. {
  202. case DLL_PROCESS_ATTACH:
  203. MQTTClient_init();
  204. break;
  205. case DLL_THREAD_ATTACH:
  206. break;
  207. case DLL_THREAD_DETACH:
  208. break;
  209. case DLL_PROCESS_DETACH:
  210. if (lpReserved)
  211. MQTTClient_cleanup();
  212. break;
  213. }
  214. return TRUE;
  215. }
  216. #endif
  217. #else
  218. static pthread_mutex_t mqttclient_mutex_store = PTHREAD_MUTEX_INITIALIZER;
  219. static mutex_type mqttclient_mutex = &mqttclient_mutex_store;
  220. static pthread_mutex_t socket_mutex_store = PTHREAD_MUTEX_INITIALIZER;
  221. mutex_type socket_mutex = &socket_mutex_store;
  222. static pthread_mutex_t subscribe_mutex_store = PTHREAD_MUTEX_INITIALIZER;
  223. static mutex_type subscribe_mutex = &subscribe_mutex_store;
  224. static pthread_mutex_t connect_mutex_store = PTHREAD_MUTEX_INITIALIZER;
  225. static mutex_type connect_mutex = &connect_mutex_store;
  226. int MQTTClient_init(void)
  227. {
  228. pthread_mutexattr_t attr;
  229. int rc;
  230. pthread_mutexattr_init(&attr);
  231. #if !defined(_WRS_KERNEL)
  232. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
  233. #else
  234. /* #warning "no pthread_mutexattr_settype" */
  235. #endif /* !defined(_WRS_KERNEL) */
  236. if ((rc = pthread_mutex_init(mqttclient_mutex, &attr)) != 0)
  237. printf("MQTTClient: error %d initializing client_mutex\n", rc);
  238. else if ((rc = pthread_mutex_init(socket_mutex, &attr)) != 0)
  239. printf("MQTTClient: error %d initializing socket_mutex\n", rc);
  240. else if ((rc = pthread_mutex_init(subscribe_mutex, &attr)) != 0)
  241. printf("MQTTClient: error %d initializing subscribe_mutex\n", rc);
  242. else if ((rc = pthread_mutex_init(connect_mutex, &attr)) != 0)
  243. printf("MQTTClient: error %d initializing connect_mutex\n", rc);
  244. return rc;
  245. }
  246. #define WINAPI
  247. #endif
  248. static volatile int library_initialized = 0;
  249. static List* handles = NULL;
  250. static int running = 0;
  251. static int tostop = 0;
  252. static thread_id_type run_id = 0;
  253. typedef struct
  254. {
  255. MQTTClient_message* msg;
  256. char* topicName;
  257. int topicLen;
  258. unsigned int seqno; /* only used on restore */
  259. } qEntry;
  260. typedef struct
  261. {
  262. char* serverURI;
  263. const char* currentServerURI; /* when using HA options, set the currently used serverURI */
  264. int unixsock;
  265. #if defined(OPENSSL)
  266. int ssl;
  267. #endif
  268. int websocket;
  269. Clients* c;
  270. MQTTClient_connectionLost* cl;
  271. MQTTClient_messageArrived* ma;
  272. MQTTClient_deliveryComplete* dc;
  273. void* context;
  274. MQTTClient_disconnected* disconnected;
  275. void* disconnected_context; /* the context to be associated with the disconnected callback*/
  276. MQTTClient_published* published;
  277. void* published_context; /* the context to be associated with the disconnected callback*/
  278. #if 0
  279. MQTTClient_authHandle* auth_handle;
  280. void* auth_handle_context; /* the context to be associated with the authHandle callback*/
  281. #endif
  282. sem_type connect_sem;
  283. int rc; /* getsockopt return code in connect */
  284. sem_type connack_sem;
  285. sem_type suback_sem;
  286. sem_type unsuback_sem;
  287. MQTTPacket* pack;
  288. unsigned long commandTimeout;
  289. } MQTTClients;
  290. struct props_rc_parms
  291. {
  292. MQTTClients* m;
  293. MQTTProperties* properties;
  294. enum MQTTReasonCodes reasonCode;
  295. };
  296. static void MQTTClient_terminate(void);
  297. static void MQTTClient_emptyMessageQueue(Clients* client);
  298. static int MQTTClient_deliverMessage(
  299. int rc, MQTTClients* m,
  300. char** topicName, int* topicLen,
  301. MQTTClient_message** message);
  302. static int clientSockCompare(void* a, void* b);
  303. static thread_return_type WINAPI connectionLost_call(void* context);
  304. static thread_return_type WINAPI MQTTClient_run(void* n);
  305. static int MQTTClient_stop(void);
  306. static void MQTTClient_closeSession(Clients* client, enum MQTTReasonCodes reason, MQTTProperties* props);
  307. static int MQTTClient_cleanSession(Clients* client);
  308. static MQTTResponse MQTTClient_connectURIVersion(
  309. MQTTClient handle, MQTTClient_connectOptions* options,
  310. const char* serverURI, int MQTTVersion,
  311. START_TIME_TYPE start, ELAPSED_TIME_TYPE millisecsTimeout,
  312. MQTTProperties* connectProperties, MQTTProperties* willProperties);
  313. static MQTTResponse MQTTClient_connectURI(MQTTClient handle, MQTTClient_connectOptions* options, const char* serverURI,
  314. MQTTProperties* connectProperties, MQTTProperties* willProperties);
  315. static int MQTTClient_disconnect1(MQTTClient handle, int timeout, int internal, int stop, enum MQTTReasonCodes, MQTTProperties*);
  316. static int MQTTClient_disconnect_internal(MQTTClient handle, int timeout);
  317. static void MQTTClient_retry(void);
  318. static MQTTPacket* MQTTClient_cycle(SOCKET* sock, ELAPSED_TIME_TYPE timeout, int* rc);
  319. static MQTTPacket* MQTTClient_waitfor(MQTTClient handle, int packet_type, int* rc, int64_t timeout);
  320. /*static int pubCompare(void* a, void* b); */
  321. static void MQTTProtocol_checkPendingWrites(void);
  322. static void MQTTClient_writeComplete(SOCKET socket, int rc);
  323. static void MQTTClient_writeContinue(SOCKET socket);
  324. int MQTTClient_createWithOptions(MQTTClient* handle, const char* serverURI, const char* clientId,
  325. int persistence_type, void* persistence_context, MQTTClient_createOptions* options)
  326. {
  327. int rc = 0;
  328. MQTTClients *m = NULL;
  329. #if (defined(_WIN32) || defined(_WIN64)) && defined(PAHO_MQTT_STATIC)
  330. /* intializes mutexes once. Must come before FUNC_ENTRY */
  331. BOOL bStatus = InitOnceExecuteOnce(&g_InitOnce, InitOnceFunction, NULL, NULL);
  332. #endif
  333. FUNC_ENTRY;
  334. if ((rc = Paho_thread_lock_mutex(mqttclient_mutex)) != 0)
  335. goto nounlock_exit;
  336. if (serverURI == NULL || clientId == NULL)
  337. {
  338. rc = MQTTCLIENT_NULL_PARAMETER;
  339. goto exit;
  340. }
  341. if (!UTF8_validateString(clientId))
  342. {
  343. rc = MQTTCLIENT_BAD_UTF8_STRING;
  344. goto exit;
  345. }
  346. if (strlen(clientId) == 0 && persistence_type == MQTTCLIENT_PERSISTENCE_DEFAULT)
  347. {
  348. rc = MQTTCLIENT_PERSISTENCE_ERROR;
  349. goto exit;
  350. }
  351. if (strstr(serverURI, "://") != NULL)
  352. {
  353. if (strncmp(URI_TCP, serverURI, strlen(URI_TCP)) != 0
  354. && strncmp(URI_MQTT, serverURI, strlen(URI_MQTT)) != 0
  355. && strncmp(URI_WS, serverURI, strlen(URI_WS)) != 0
  356. #if defined(OPENSSL)
  357. && strncmp(URI_SSL, serverURI, strlen(URI_SSL)) != 0
  358. && strncmp(URI_MQTTS, serverURI, strlen(URI_MQTTS)) != 0
  359. && strncmp(URI_WSS, serverURI, strlen(URI_WSS)) != 0
  360. #endif
  361. #if defined(UNIXSOCK)
  362. && strncmp(URI_UNIX, serverURI, strlen(URI_UNIX)) != 0
  363. #endif
  364. )
  365. {
  366. rc = MQTTCLIENT_BAD_PROTOCOL;
  367. goto exit;
  368. }
  369. }
  370. if (options && (strncmp(options->struct_id, "MQCO", 4) != 0 || options->struct_version != 0))
  371. {
  372. rc = MQTTCLIENT_BAD_STRUCTURE;
  373. goto exit;
  374. }
  375. if (!library_initialized)
  376. {
  377. #if !defined(NO_HEAP_TRACKING)
  378. Heap_initialize();
  379. #endif
  380. Log_initialize((Log_nameValue*)MQTTClient_getVersionInfo());
  381. bstate->clients = ListInitialize();
  382. Socket_outInitialize();
  383. Socket_setWriteCompleteCallback(MQTTClient_writeComplete);
  384. Socket_setWriteContinueCallback(MQTTClient_writeContinue);
  385. Socket_setWriteAvailableCallback(MQTTProtocol_writeAvailable);
  386. handles = ListInitialize();
  387. #if defined(OPENSSL)
  388. SSLSocket_initialize();
  389. #endif
  390. library_initialized = 1;
  391. }
  392. if ((m = malloc(sizeof(MQTTClients))) == NULL)
  393. {
  394. rc = PAHO_MEMORY_ERROR;
  395. goto exit;
  396. }
  397. *handle = m;
  398. memset(m, '\0', sizeof(MQTTClients));
  399. m->commandTimeout = 10000L;
  400. if (strncmp(URI_TCP, serverURI, strlen(URI_TCP)) == 0)
  401. serverURI += strlen(URI_TCP);
  402. else if (strncmp(URI_MQTT, serverURI, strlen(URI_MQTT)) == 0)
  403. serverURI += strlen(URI_MQTT);
  404. else if (strncmp(URI_WS, serverURI, strlen(URI_WS)) == 0)
  405. {
  406. serverURI += strlen(URI_WS);
  407. m->websocket = 1;
  408. }
  409. else if (strncmp(URI_SSL, serverURI, strlen(URI_SSL)) == 0)
  410. {
  411. #if defined(OPENSSL)
  412. serverURI += strlen(URI_SSL);
  413. m->ssl = 1;
  414. #else
  415. rc = MQTTCLIENT_SSL_NOT_SUPPORTED;
  416. goto exit;
  417. #endif
  418. }
  419. else if (strncmp(URI_MQTTS, serverURI, strlen(URI_MQTTS)) == 0)
  420. {
  421. #if defined(OPENSSL)
  422. serverURI += strlen(URI_MQTTS);
  423. m->ssl = 1;
  424. #else
  425. rc = MQTTCLIENT_SSL_NOT_SUPPORTED;
  426. goto exit;
  427. #endif
  428. }
  429. else if (strncmp(URI_WSS, serverURI, strlen(URI_WSS)) == 0)
  430. {
  431. #if defined(OPENSSL)
  432. serverURI += strlen(URI_WSS);
  433. m->ssl = 1;
  434. m->websocket = 1;
  435. #else
  436. rc = MQTTCLIENT_SSL_NOT_SUPPORTED;
  437. goto exit;
  438. #endif
  439. }
  440. #if defined(UNIXSOCK)
  441. else if (strncmp(URI_UNIX, serverURI, strlen(URI_UNIX)) == 0)
  442. {
  443. serverURI += strlen(URI_UNIX);
  444. m->unixsock = 1;
  445. }
  446. #endif
  447. m->serverURI = MQTTStrdup(serverURI);
  448. ListAppend(handles, m, sizeof(MQTTClients));
  449. if ((m->c = malloc(sizeof(Clients))) == NULL)
  450. {
  451. ListRemove(handles, m);
  452. rc = PAHO_MEMORY_ERROR;
  453. goto exit;
  454. }
  455. memset(m->c, '\0', sizeof(Clients));
  456. m->c->context = m;
  457. m->c->MQTTVersion = (options) ? options->MQTTVersion : MQTTVERSION_DEFAULT;
  458. m->c->outboundMsgs = ListInitialize();
  459. m->c->inboundMsgs = ListInitialize();
  460. m->c->messageQueue = ListInitialize();
  461. m->c->outboundQueue = ListInitialize();
  462. m->c->clientID = MQTTStrdup(clientId);
  463. m->connect_sem = Thread_create_sem(&rc);
  464. m->connack_sem = Thread_create_sem(&rc);
  465. m->suback_sem = Thread_create_sem(&rc);
  466. m->unsuback_sem = Thread_create_sem(&rc);
  467. #if !defined(NO_PERSISTENCE)
  468. rc = MQTTPersistence_create(&(m->c->persistence), persistence_type, persistence_context);
  469. if (rc == 0)
  470. {
  471. rc = MQTTPersistence_initialize(m->c, m->serverURI);
  472. if (rc == 0)
  473. MQTTPersistence_restoreMessageQueue(m->c);
  474. }
  475. #endif
  476. ListAppend(bstate->clients, m->c, sizeof(Clients) + 3*sizeof(List));
  477. exit:
  478. Paho_thread_unlock_mutex(mqttclient_mutex);
  479. nounlock_exit:
  480. FUNC_EXIT_RC(rc);
  481. return rc;
  482. }
  483. int MQTTClient_create(MQTTClient* handle, const char* serverURI, const char* clientId,
  484. int persistence_type, void* persistence_context)
  485. {
  486. return MQTTClient_createWithOptions(handle, serverURI, clientId, persistence_type,
  487. persistence_context, NULL);
  488. }
  489. static void MQTTClient_terminate(void)
  490. {
  491. FUNC_ENTRY;
  492. MQTTClient_stop();
  493. if (library_initialized)
  494. {
  495. ListFree(bstate->clients);
  496. ListFree(handles);
  497. handles = NULL;
  498. WebSocket_terminate();
  499. #if !defined(NO_HEAP_TRACKING)
  500. Heap_terminate();
  501. #endif
  502. Log_terminate();
  503. library_initialized = 0;
  504. }
  505. FUNC_EXIT;
  506. }
  507. static void MQTTClient_emptyMessageQueue(Clients* client)
  508. {
  509. FUNC_ENTRY;
  510. /* empty message queue */
  511. if (client->messageQueue->count > 0)
  512. {
  513. ListElement* current = NULL;
  514. while (ListNextElement(client->messageQueue, &current))
  515. {
  516. qEntry* qe = (qEntry*)(current->content);
  517. free(qe->topicName);
  518. MQTTProperties_free(&qe->msg->properties);
  519. free(qe->msg->payload);
  520. free(qe->msg);
  521. }
  522. ListEmpty(client->messageQueue);
  523. }
  524. FUNC_EXIT;
  525. }
  526. void MQTTClient_destroy(MQTTClient* handle)
  527. {
  528. MQTTClients* m = *handle;
  529. FUNC_ENTRY;
  530. Paho_thread_lock_mutex(connect_mutex);
  531. Paho_thread_lock_mutex(mqttclient_mutex);
  532. if (m == NULL)
  533. goto exit;
  534. if (m->c)
  535. {
  536. SOCKET saved_socket = m->c->net.socket;
  537. char* saved_clientid = MQTTStrdup(m->c->clientID);
  538. #if !defined(NO_PERSISTENCE)
  539. MQTTPersistence_close(m->c);
  540. #endif
  541. MQTTClient_emptyMessageQueue(m->c);
  542. MQTTProtocol_freeClient(m->c);
  543. if (!ListRemove(bstate->clients, m->c))
  544. Log(LOG_ERROR, 0, NULL);
  545. else
  546. Log(TRACE_MIN, 1, NULL, saved_clientid, saved_socket);
  547. free(saved_clientid);
  548. }
  549. if (m->serverURI)
  550. free(m->serverURI);
  551. Thread_destroy_sem(m->connect_sem);
  552. Thread_destroy_sem(m->connack_sem);
  553. Thread_destroy_sem(m->suback_sem);
  554. Thread_destroy_sem(m->unsuback_sem);
  555. if (!ListRemove(handles, m))
  556. Log(LOG_ERROR, -1, "free error");
  557. *handle = NULL;
  558. if (bstate->clients->count == 0)
  559. MQTTClient_terminate();
  560. exit:
  561. Paho_thread_unlock_mutex(mqttclient_mutex);
  562. Paho_thread_unlock_mutex(connect_mutex);
  563. FUNC_EXIT;
  564. }
  565. void MQTTClient_freeMessage(MQTTClient_message** message)
  566. {
  567. FUNC_ENTRY;
  568. MQTTProperties_free(&(*message)->properties);
  569. free((*message)->payload);
  570. free(*message);
  571. *message = NULL;
  572. FUNC_EXIT;
  573. }
  574. void MQTTClient_free(void* memory)
  575. {
  576. FUNC_ENTRY;
  577. free(memory);
  578. FUNC_EXIT;
  579. }
  580. void* MQTTClient_malloc(size_t size)
  581. {
  582. void* val;
  583. int rc = 0;
  584. FUNC_ENTRY;
  585. val = malloc(size);
  586. rc = (val != NULL);
  587. FUNC_EXIT_RC(rc);
  588. return val;
  589. }
  590. void MQTTResponse_free(MQTTResponse response)
  591. {
  592. FUNC_ENTRY;
  593. if (response.reasonCodeCount > 0 && response.reasonCodes)
  594. free(response.reasonCodes);
  595. if (response.properties)
  596. {
  597. MQTTProperties_free(response.properties);
  598. free(response.properties);
  599. }
  600. FUNC_EXIT;
  601. }
  602. static int MQTTClient_deliverMessage(int rc, MQTTClients* m, char** topicName, int* topicLen, MQTTClient_message** message)
  603. {
  604. qEntry* qe = (qEntry*)(m->c->messageQueue->first->content);
  605. FUNC_ENTRY;
  606. *message = qe->msg;
  607. *topicName = qe->topicName;
  608. *topicLen = qe->topicLen;
  609. if (strlen(*topicName) != *topicLen)
  610. rc = MQTTCLIENT_TOPICNAME_TRUNCATED;
  611. #if !defined(NO_PERSISTENCE)
  612. if (m->c->persistence)
  613. MQTTPersistence_unpersistQueueEntry(m->c, (MQTTPersistence_qEntry*)qe);
  614. #endif
  615. ListRemove(m->c->messageQueue, m->c->messageQueue->first->content);
  616. FUNC_EXIT_RC(rc);
  617. return rc;
  618. }
  619. /**
  620. * List callback function for comparing clients by socket
  621. * @param a first integer value
  622. * @param b second integer value
  623. * @return boolean indicating whether a and b are equal
  624. */
  625. static int clientSockCompare(void* a, void* b)
  626. {
  627. MQTTClients* m = (MQTTClients*)a;
  628. return m->c->net.socket == *(int*)b;
  629. }
  630. /**
  631. * Wrapper function to call connection lost on a separate thread. A separate thread is needed to allow the
  632. * connectionLost function to make API calls (e.g. connect)
  633. * @param context a pointer to the relevant client
  634. * @return thread_return_type standard thread return value - not used here
  635. */
  636. static thread_return_type WINAPI connectionLost_call(void* context)
  637. {
  638. struct conlost_sync_data *data = (struct conlost_sync_data *)context;
  639. MQTTClients* m = (MQTTClients *)data->m;
  640. (*(m->cl))(m->context, NULL);
  641. Thread_post_sem(data->sem);
  642. return 0;
  643. }
  644. int MQTTClient_setDisconnected(MQTTClient handle, void* context, MQTTClient_disconnected* disconnected)
  645. {
  646. int rc = MQTTCLIENT_SUCCESS;
  647. MQTTClients* m = handle;
  648. FUNC_ENTRY;
  649. Paho_thread_lock_mutex(mqttclient_mutex);
  650. if (m == NULL || m->c->connect_state != NOT_IN_PROGRESS)
  651. rc = MQTTCLIENT_FAILURE;
  652. else
  653. {
  654. m->disconnected_context = context;
  655. m->disconnected = disconnected;
  656. }
  657. Paho_thread_unlock_mutex(mqttclient_mutex);
  658. FUNC_EXIT_RC(rc);
  659. return rc;
  660. }
  661. /**
  662. * Wrapper function to call disconnected on a separate thread. A separate thread is needed to allow the
  663. * disconnected function to make API calls (e.g. connect)
  664. * @param context a pointer to the relevant client
  665. * @return thread_return_type standard thread return value - not used here
  666. */
  667. static thread_return_type WINAPI call_disconnected(void* context)
  668. {
  669. struct props_rc_parms* pr = (struct props_rc_parms*)context;
  670. (*(pr->m->disconnected))(pr->m->disconnected_context, pr->properties, pr->reasonCode);
  671. MQTTProperties_free(pr->properties);
  672. free(pr->properties);
  673. free(pr);
  674. return 0;
  675. }
  676. int MQTTClient_setPublished(MQTTClient handle, void* context, MQTTClient_published* published)
  677. {
  678. int rc = MQTTCLIENT_SUCCESS;
  679. MQTTClients* m = handle;
  680. FUNC_ENTRY;
  681. Paho_thread_lock_mutex(mqttclient_mutex);
  682. if (m == NULL || m->c->connect_state != NOT_IN_PROGRESS)
  683. rc = MQTTCLIENT_FAILURE;
  684. else
  685. {
  686. m->published_context = context;
  687. m->published = published;
  688. }
  689. Paho_thread_unlock_mutex(mqttclient_mutex);
  690. FUNC_EXIT_RC(rc);
  691. return rc;
  692. }
  693. #if 0
  694. int MQTTClient_setHandleAuth(MQTTClient handle, void* context, MQTTClient_handleAuth* auth_handle)
  695. {
  696. int rc = MQTTCLIENT_SUCCESS;
  697. MQTTClients* m = handle;
  698. FUNC_ENTRY;
  699. Paho_thread_lock_mutex(mqttclient_mutex);
  700. if (m == NULL || m->c->connect_state != NOT_IN_PROGRESS)
  701. rc = MQTTCLIENT_FAILURE;
  702. else
  703. {
  704. m->auth_handle_context = context;
  705. m->auth_handle = auth_handle;
  706. }
  707. Paho_thread_unlock_mutex(mqttclient_mutex);
  708. FUNC_EXIT_RC(rc);
  709. return rc;
  710. }
  711. /**
  712. * Wrapper function to call authHandle on a separate thread. A separate thread is needed to allow the
  713. * disconnected function to make API calls (e.g. MQTTClient_auth)
  714. * @param context a pointer to the relevant client
  715. * @return thread_return_type standard thread return value - not used here
  716. */
  717. static thread_return_type WINAPI call_auth_handle(void* context)
  718. {
  719. struct props_rc_parms* pr = (struct props_rc_parms*)context;
  720. (*(pr->m->auth_handle))(pr->m->auth_handle_context, pr->properties, pr->reasonCode);
  721. MQTTProperties_free(pr->properties);
  722. free(pr->properties);
  723. free(pr);
  724. return 0;
  725. }
  726. #endif
  727. /* This is the thread function that handles the calling of callback functions if set */
  728. static thread_return_type WINAPI MQTTClient_run(void* n)
  729. {
  730. long timeout = 10L; /* first time in we have a small timeout. Gets things started more quickly */
  731. FUNC_ENTRY;
  732. Thread_set_name("MQTTClient_run");
  733. Paho_thread_lock_mutex(mqttclient_mutex);
  734. run_id = Paho_thread_getid();
  735. running = 1;
  736. while (!tostop)
  737. {
  738. int rc = SOCKET_ERROR;
  739. SOCKET sock = -1;
  740. MQTTClients* m = NULL;
  741. MQTTPacket* pack = NULL;
  742. Paho_thread_unlock_mutex(mqttclient_mutex);
  743. pack = MQTTClient_cycle(&sock, timeout, &rc);
  744. Paho_thread_lock_mutex(mqttclient_mutex);
  745. if (tostop)
  746. break;
  747. timeout = 100L;
  748. /* find client corresponding to socket */
  749. if (ListFindItem(handles, &sock, clientSockCompare) == NULL)
  750. {
  751. /* assert: should not happen */
  752. continue;
  753. }
  754. m = (MQTTClient)(handles->current->content);
  755. if (m == NULL)
  756. {
  757. /* assert: should not happen */
  758. continue;
  759. }
  760. if (rc == SOCKET_ERROR)
  761. {
  762. if (m->c->connected)
  763. MQTTClient_disconnect_internal(m, 0);
  764. else
  765. {
  766. if (m->c->connect_state == SSL_IN_PROGRESS)
  767. {
  768. Log(TRACE_MIN, -1, "Posting connect semaphore for client %s", m->c->clientID);
  769. m->c->connect_state = NOT_IN_PROGRESS;
  770. Thread_post_sem(m->connect_sem);
  771. }
  772. if (m->c->connect_state == WAIT_FOR_CONNACK)
  773. {
  774. Log(TRACE_MIN, -1, "Posting connack semaphore for client %s", m->c->clientID);
  775. m->c->connect_state = NOT_IN_PROGRESS;
  776. Thread_post_sem(m->connack_sem);
  777. }
  778. }
  779. }
  780. else
  781. {
  782. if (m->c->messageQueue->count > 0 && m->ma)
  783. {
  784. qEntry* qe = (qEntry*)(m->c->messageQueue->first->content);
  785. int topicLen = qe->topicLen;
  786. if (strlen(qe->topicName) == topicLen)
  787. topicLen = 0;
  788. Log(TRACE_MIN, -1, "Calling messageArrived for client %s, queue depth %d",
  789. m->c->clientID, m->c->messageQueue->count);
  790. Paho_thread_unlock_mutex(mqttclient_mutex);
  791. rc = (*(m->ma))(m->context, qe->topicName, topicLen, qe->msg);
  792. Paho_thread_lock_mutex(mqttclient_mutex);
  793. /* if 0 (false) is returned by the callback then it failed, so we don't remove the message from
  794. * the queue, and it will be retried later. If 1 is returned then the message data may have been freed,
  795. * so we must be careful how we use it.
  796. */
  797. if (rc)
  798. {
  799. #if !defined(NO_PERSISTENCE)
  800. if (m->c->persistence)
  801. MQTTPersistence_unpersistQueueEntry(m->c, (MQTTPersistence_qEntry*)qe);
  802. #endif
  803. ListRemove(m->c->messageQueue, qe);
  804. }
  805. else
  806. Log(TRACE_MIN, -1, "False returned from messageArrived for client %s, message remains on queue",
  807. m->c->clientID);
  808. }
  809. if (pack)
  810. {
  811. if (pack->header.bits.type == CONNACK)
  812. {
  813. Log(TRACE_MIN, -1, "Posting connack semaphore for client %s", m->c->clientID);
  814. m->pack = pack;
  815. Thread_post_sem(m->connack_sem);
  816. }
  817. else if (pack->header.bits.type == SUBACK)
  818. {
  819. Log(TRACE_MIN, -1, "Posting suback semaphore for client %s", m->c->clientID);
  820. m->pack = pack;
  821. Thread_post_sem(m->suback_sem);
  822. }
  823. else if (pack->header.bits.type == UNSUBACK)
  824. {
  825. Log(TRACE_MIN, -1, "Posting unsuback semaphore for client %s", m->c->clientID);
  826. m->pack = pack;
  827. Thread_post_sem(m->unsuback_sem);
  828. }
  829. else if (m->c->MQTTVersion >= MQTTVERSION_5)
  830. {
  831. if (pack->header.bits.type == DISCONNECT && m->disconnected)
  832. {
  833. struct props_rc_parms* dp;
  834. Ack* disc = (Ack*)pack;
  835. dp = malloc(sizeof(struct props_rc_parms));
  836. if (dp)
  837. {
  838. dp->m = m;
  839. dp->reasonCode = disc->rc;
  840. dp->properties = malloc(sizeof(MQTTProperties));
  841. if (dp->properties)
  842. {
  843. *(dp->properties) = disc->properties;
  844. MQTTClient_disconnect1(m, 10, 0, 1, MQTTREASONCODE_SUCCESS, NULL);
  845. Log(TRACE_MIN, -1, "Calling disconnected for client %s", m->c->clientID);
  846. Paho_thread_start(call_disconnected, dp);
  847. }
  848. else
  849. free(dp);
  850. }
  851. free(disc);
  852. }
  853. #if 0
  854. if (pack->header.bits.type == AUTH && m->auth_handle)
  855. {
  856. struct props_rc_parms dp;
  857. Ack* disc = (Ack*)pack;
  858. dp.m = m;
  859. dp.properties = &disc->properties;
  860. dp.reasonCode = disc->rc;
  861. free(pack);
  862. Log(TRACE_MIN, -1, "Calling auth_handle for client %s", m->c->clientID);
  863. Paho_thread_start(call_auth_handle, &dp);
  864. }
  865. #endif
  866. }
  867. }
  868. else if (m->c->connect_state == TCP_IN_PROGRESS)
  869. {
  870. int error;
  871. socklen_t len = sizeof(error);
  872. if ((m->rc = getsockopt(m->c->net.socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len)) == 0)
  873. m->rc = error;
  874. Log(TRACE_MIN, -1, "Posting connect semaphore for client %s rc %d", m->c->clientID, m->rc);
  875. m->c->connect_state = NOT_IN_PROGRESS;
  876. Thread_post_sem(m->connect_sem);
  877. }
  878. #if defined(OPENSSL)
  879. else if (m->c->connect_state == SSL_IN_PROGRESS)
  880. {
  881. rc = m->c->sslopts->struct_version >= 3 ?
  882. SSLSocket_connect(m->c->net.ssl, m->c->net.socket, m->serverURI,
  883. m->c->sslopts->verify, m->c->sslopts->ssl_error_cb, m->c->sslopts->ssl_error_context) :
  884. SSLSocket_connect(m->c->net.ssl, m->c->net.socket, m->serverURI,
  885. m->c->sslopts->verify, NULL, NULL);
  886. if (rc == 1 || rc == SSL_FATAL)
  887. {
  888. if (rc == 1 && (m->c->cleansession == 0 && m->c->cleanstart == 0) && m->c->session == NULL)
  889. m->c->session = SSL_get1_session(m->c->net.ssl);
  890. m->rc = rc;
  891. Log(TRACE_MIN, -1, "Posting connect semaphore for SSL client %s rc %d", m->c->clientID, m->rc);
  892. m->c->connect_state = NOT_IN_PROGRESS;
  893. Thread_post_sem(m->connect_sem);
  894. }
  895. }
  896. #endif
  897. else if (m->c->connect_state == WEBSOCKET_IN_PROGRESS)
  898. {
  899. if (rc != TCPSOCKET_INTERRUPTED)
  900. {
  901. Log(TRACE_MIN, -1, "Posting websocket handshake for client %s rc %d", m->c->clientID, m->rc);
  902. m->c->connect_state = WAIT_FOR_CONNACK;
  903. Thread_post_sem(m->connect_sem);
  904. }
  905. }
  906. }
  907. }
  908. run_id = 0;
  909. running = tostop = 0;
  910. Paho_thread_unlock_mutex(mqttclient_mutex);
  911. FUNC_EXIT;
  912. #if defined(_WIN32) || defined(_WIN64)
  913. ExitThread(0);
  914. #endif
  915. return 0;
  916. }
  917. static int MQTTClient_stop(void)
  918. {
  919. int rc = 0;
  920. FUNC_ENTRY;
  921. if (running == 1 && tostop == 0)
  922. {
  923. int conn_count = 0;
  924. ListElement* current = NULL;
  925. if (handles != NULL)
  926. {
  927. /* find out how many handles are still connected */
  928. while (ListNextElement(handles, &current))
  929. {
  930. if (((MQTTClients*)(current->content))->c->connect_state > NOT_IN_PROGRESS ||
  931. ((MQTTClients*)(current->content))->c->connected)
  932. ++conn_count;
  933. }
  934. }
  935. Log(TRACE_MIN, -1, "Conn_count is %d", conn_count);
  936. /* stop the background thread, if we are the last one to be using it */
  937. if (conn_count == 0)
  938. {
  939. int count = 0;
  940. tostop = 1;
  941. if (Paho_thread_getid() != run_id)
  942. {
  943. while (running && ++count < 100)
  944. {
  945. Paho_thread_unlock_mutex(mqttclient_mutex);
  946. Log(TRACE_MIN, -1, "sleeping");
  947. MQTTTime_sleep(100L);
  948. Paho_thread_lock_mutex(mqttclient_mutex);
  949. }
  950. }
  951. rc = 1;
  952. }
  953. }
  954. FUNC_EXIT_RC(rc);
  955. return rc;
  956. }
  957. int MQTTClient_setCallbacks(MQTTClient handle, void* context, MQTTClient_connectionLost* cl,
  958. MQTTClient_messageArrived* ma, MQTTClient_deliveryComplete* dc)
  959. {
  960. int rc = MQTTCLIENT_SUCCESS;
  961. MQTTClients* m = handle;
  962. FUNC_ENTRY;
  963. Paho_thread_lock_mutex(mqttclient_mutex);
  964. if (m == NULL || ma == NULL || m->c->connect_state != NOT_IN_PROGRESS)
  965. rc = MQTTCLIENT_FAILURE;
  966. else
  967. {
  968. m->context = context;
  969. m->cl = cl;
  970. m->ma = ma;
  971. m->dc = dc;
  972. }
  973. Paho_thread_unlock_mutex(mqttclient_mutex);
  974. FUNC_EXIT_RC(rc);
  975. return rc;
  976. }
  977. static void MQTTClient_closeSession(Clients* client, enum MQTTReasonCodes reason, MQTTProperties* props)
  978. {
  979. FUNC_ENTRY;
  980. client->good = 0;
  981. client->ping_outstanding = 0;
  982. client->ping_due = 0;
  983. if (client->net.socket > 0)
  984. {
  985. if (client->connected)
  986. MQTTPacket_send_disconnect(client, reason, props);
  987. Paho_thread_lock_mutex(socket_mutex);
  988. WebSocket_close(&client->net, WebSocket_CLOSE_NORMAL, NULL);
  989. #if defined(OPENSSL)
  990. SSL_SESSION_free(client->session); /* is a no-op if session is NULL */
  991. client->session = NULL; /* show the session has been freed */
  992. SSLSocket_close(&client->net);
  993. #endif
  994. Paho_thread_unlock_mutex(socket_mutex);
  995. Socket_close(client->net.socket);
  996. client->net.socket = 0;
  997. #if defined(OPENSSL)
  998. client->net.ssl = NULL;
  999. #endif
  1000. }
  1001. client->connected = 0;
  1002. client->connect_state = NOT_IN_PROGRESS;
  1003. if (client->MQTTVersion < MQTTVERSION_5 && client->cleansession)
  1004. MQTTClient_cleanSession(client);
  1005. FUNC_EXIT;
  1006. }
  1007. static int MQTTClient_cleanSession(Clients* client)
  1008. {
  1009. int rc = 0;
  1010. FUNC_ENTRY;
  1011. #if !defined(NO_PERSISTENCE)
  1012. rc = MQTTPersistence_clear(client);
  1013. #endif
  1014. MQTTProtocol_emptyMessageList(client->inboundMsgs);
  1015. MQTTProtocol_emptyMessageList(client->outboundMsgs);
  1016. MQTTClient_emptyMessageQueue(client);
  1017. client->msgID = 0;
  1018. FUNC_EXIT_RC(rc);
  1019. return rc;
  1020. }
  1021. void Protocol_processPublication(Publish* publish, Clients* client, int allocatePayload)
  1022. {
  1023. qEntry* qe = NULL;
  1024. MQTTClient_message* mm = NULL;
  1025. MQTTClient_message initialized = MQTTClient_message_initializer;
  1026. FUNC_ENTRY;
  1027. qe = malloc(sizeof(qEntry));
  1028. if (!qe)
  1029. goto exit;
  1030. mm = malloc(sizeof(MQTTClient_message));
  1031. if (!mm)
  1032. {
  1033. free(qe);
  1034. goto exit;
  1035. }
  1036. memcpy(mm, &initialized, sizeof(MQTTClient_message));
  1037. qe->msg = mm;
  1038. qe->topicName = publish->topic;
  1039. qe->topicLen = publish->topiclen;
  1040. publish->topic = NULL;
  1041. if (allocatePayload)
  1042. {
  1043. mm->payload = malloc(publish->payloadlen);
  1044. if (mm->payload == NULL)
  1045. {
  1046. free(mm);
  1047. free(qe);
  1048. goto exit;
  1049. }
  1050. memcpy(mm->payload, publish->payload, publish->payloadlen);
  1051. }
  1052. else
  1053. mm->payload = publish->payload;
  1054. mm->payloadlen = publish->payloadlen;
  1055. mm->qos = publish->header.bits.qos;
  1056. mm->retained = publish->header.bits.retain;
  1057. if (publish->header.bits.qos == 2)
  1058. mm->dup = 0; /* ensure that a QoS2 message is not passed to the application with dup = 1 */
  1059. else
  1060. mm->dup = publish->header.bits.dup;
  1061. mm->msgid = publish->msgId;
  1062. if (publish->MQTTVersion >= 5)
  1063. mm->properties = MQTTProperties_copy(&publish->properties);
  1064. ListAppend(client->messageQueue, qe, sizeof(qe) + sizeof(mm) + mm->payloadlen + strlen(qe->topicName)+1);
  1065. #if !defined(NO_PERSISTENCE)
  1066. if (client->persistence)
  1067. MQTTPersistence_persistQueueEntry(client, (MQTTPersistence_qEntry*)qe);
  1068. #endif
  1069. exit:
  1070. FUNC_EXIT;
  1071. }
  1072. static MQTTResponse MQTTClient_connectURIVersion(MQTTClient handle, MQTTClient_connectOptions* options, const char* serverURI, int MQTTVersion,
  1073. START_TIME_TYPE start, ELAPSED_TIME_TYPE millisecsTimeout, MQTTProperties* connectProperties, MQTTProperties* willProperties)
  1074. {
  1075. MQTTClients* m = handle;
  1076. int rc = SOCKET_ERROR;
  1077. int sessionPresent = 0;
  1078. MQTTResponse resp = MQTTResponse_initializer;
  1079. FUNC_ENTRY;
  1080. resp.reasonCode = SOCKET_ERROR;
  1081. if (m->ma && !running)
  1082. {
  1083. int count = 0;
  1084. Paho_thread_start(MQTTClient_run, handle);
  1085. if (MQTTTime_elapsed(start) >= millisecsTimeout)
  1086. {
  1087. rc = SOCKET_ERROR;
  1088. goto exit;
  1089. }
  1090. while (!running && ++count < 5)
  1091. {
  1092. Paho_thread_unlock_mutex(mqttclient_mutex);
  1093. MQTTTime_sleep(100L);
  1094. Paho_thread_lock_mutex(mqttclient_mutex);
  1095. }
  1096. if (!running)
  1097. {
  1098. rc = SOCKET_ERROR;
  1099. goto exit;
  1100. }
  1101. }
  1102. Log(TRACE_MIN, -1, "Connecting to serverURI %s with MQTT version %d", serverURI, MQTTVersion);
  1103. #if defined(OPENSSL)
  1104. #if defined(__GNUC__) && defined(__linux__)
  1105. rc = MQTTProtocol_connect(serverURI, m->c, m->unixsock, m->ssl, m->websocket, MQTTVersion, connectProperties, willProperties,
  1106. millisecsTimeout - MQTTTime_elapsed(start));
  1107. #else
  1108. rc = MQTTProtocol_connect(serverURI, m->c, m->unixsock, m->ssl, m->websocket, MQTTVersion, connectProperties, willProperties);
  1109. #endif
  1110. #else
  1111. #if defined(__GNUC__) && defined(__linux__)
  1112. rc = MQTTProtocol_connect(serverURI, m->c, m->unixsock, m->websocket, MQTTVersion, connectProperties, willProperties,
  1113. millisecsTimeout - MQTTTime_elapsed(start));
  1114. #else
  1115. rc = MQTTProtocol_connect(serverURI, m->c, m->unixsock, m->websocket, MQTTVersion, connectProperties, willProperties);
  1116. #endif
  1117. #endif
  1118. if (rc == SOCKET_ERROR)
  1119. goto exit;
  1120. if (m->c->connect_state == NOT_IN_PROGRESS)
  1121. {
  1122. rc = SOCKET_ERROR;
  1123. goto exit;
  1124. }
  1125. if (m->c->connect_state == TCP_IN_PROGRESS) /* TCP connect started - wait for completion */
  1126. {
  1127. Paho_thread_unlock_mutex(mqttclient_mutex);
  1128. MQTTClient_waitfor(handle, CONNECT, &rc, millisecsTimeout - MQTTTime_elapsed(start));
  1129. Paho_thread_lock_mutex(mqttclient_mutex);
  1130. if (rc != 0)
  1131. {
  1132. rc = SOCKET_ERROR;
  1133. goto exit;
  1134. }
  1135. #if defined(OPENSSL)
  1136. if (m->ssl)
  1137. {
  1138. int port1;
  1139. size_t hostname_len;
  1140. const char *topic;
  1141. int setSocketForSSLrc = 0;
  1142. if (m->c->net.https_proxy) {
  1143. m->c->connect_state = PROXY_CONNECT_IN_PROGRESS;
  1144. if ((rc = Proxy_connect( &m->c->net, 1, serverURI)) == SOCKET_ERROR )
  1145. goto exit;
  1146. }
  1147. hostname_len = MQTTProtocol_addressPort(serverURI, &port1, &topic, MQTT_DEFAULT_PORT);
  1148. setSocketForSSLrc = SSLSocket_setSocketForSSL(&m->c->net, m->c->sslopts,
  1149. serverURI, hostname_len);
  1150. if (setSocketForSSLrc != MQTTCLIENT_SUCCESS)
  1151. {
  1152. if (m->c->session != NULL)
  1153. if ((rc = SSL_set_session(m->c->net.ssl, m->c->session)) != 1)
  1154. Log(TRACE_MIN, -1, "Failed to set SSL session with stored data, non critical");
  1155. rc = m->c->sslopts->struct_version >= 3 ?
  1156. SSLSocket_connect(m->c->net.ssl, m->c->net.socket, serverURI,
  1157. m->c->sslopts->verify, m->c->sslopts->ssl_error_cb, m->c->sslopts->ssl_error_context) :
  1158. SSLSocket_connect(m->c->net.ssl, m->c->net.socket, serverURI,
  1159. m->c->sslopts->verify, NULL, NULL);
  1160. if (rc == TCPSOCKET_INTERRUPTED)
  1161. m->c->connect_state = SSL_IN_PROGRESS; /* the connect is still in progress */
  1162. else if (rc == SSL_FATAL)
  1163. {
  1164. rc = SOCKET_ERROR;
  1165. goto exit;
  1166. }
  1167. else if (rc == 1)
  1168. {
  1169. if (m->websocket)
  1170. {
  1171. m->c->connect_state = WEBSOCKET_IN_PROGRESS;
  1172. rc = WebSocket_connect(&m->c->net, 1, serverURI);
  1173. if ( rc == SOCKET_ERROR )
  1174. goto exit;
  1175. }
  1176. else
  1177. {
  1178. rc = MQTTCLIENT_SUCCESS;
  1179. m->c->connect_state = WAIT_FOR_CONNACK;
  1180. if (MQTTPacket_send_connect(m->c, MQTTVersion, connectProperties, willProperties) == SOCKET_ERROR)
  1181. {
  1182. rc = SOCKET_ERROR;
  1183. goto exit;
  1184. }
  1185. if ((m->c->cleansession == 0 && m->c->cleanstart == 0) && m->c->session == NULL)
  1186. m->c->session = SSL_get1_session(m->c->net.ssl);
  1187. }
  1188. }
  1189. }
  1190. else
  1191. {
  1192. rc = SOCKET_ERROR;
  1193. goto exit;
  1194. }
  1195. }
  1196. #endif
  1197. else
  1198. {
  1199. if (m->c->net.http_proxy) {
  1200. m->c->connect_state = PROXY_CONNECT_IN_PROGRESS;
  1201. if ((rc = Proxy_connect( &m->c->net, 0, serverURI)) == SOCKET_ERROR )
  1202. goto exit;
  1203. }
  1204. if (m->websocket)
  1205. {
  1206. m->c->connect_state = WEBSOCKET_IN_PROGRESS;
  1207. if ( WebSocket_connect(&m->c->net, 0, serverURI) == SOCKET_ERROR )
  1208. {
  1209. rc = SOCKET_ERROR;
  1210. goto exit;
  1211. }
  1212. }
  1213. else
  1214. {
  1215. m->c->connect_state = WAIT_FOR_CONNACK; /* TCP connect completed, in which case send the MQTT connect packet */
  1216. if (MQTTPacket_send_connect(m->c, MQTTVersion, connectProperties, willProperties) == SOCKET_ERROR)
  1217. {
  1218. rc = SOCKET_ERROR;
  1219. goto exit;
  1220. }
  1221. }
  1222. }
  1223. }
  1224. #if defined(OPENSSL)
  1225. if (m->c->connect_state == SSL_IN_PROGRESS) /* SSL connect sent - wait for completion */
  1226. {
  1227. Paho_thread_unlock_mutex(mqttclient_mutex);
  1228. MQTTClient_waitfor(handle, CONNECT, &rc, millisecsTimeout - MQTTTime_elapsed(start));
  1229. Paho_thread_lock_mutex(mqttclient_mutex);
  1230. if (rc != 1)
  1231. {
  1232. rc = SOCKET_ERROR;
  1233. goto exit;
  1234. }
  1235. if((m->c->cleansession == 0 && m->c->cleanstart == 0) && m->c->session == NULL)
  1236. m->c->session = SSL_get1_session(m->c->net.ssl);
  1237. if ( m->websocket )
  1238. {
  1239. /* wait for websocket connect */
  1240. m->c->connect_state = WEBSOCKET_IN_PROGRESS;
  1241. rc = WebSocket_connect( &m->c->net, 1, serverURI);
  1242. if ( rc != 1 )
  1243. {
  1244. rc = SOCKET_ERROR;
  1245. goto exit;
  1246. }
  1247. }
  1248. else
  1249. {
  1250. m->c->connect_state = WAIT_FOR_CONNACK; /* TCP connect completed, in which case send the MQTT connect packet */
  1251. if (MQTTPacket_send_connect(m->c, MQTTVersion, connectProperties, willProperties) == SOCKET_ERROR)
  1252. {
  1253. rc = SOCKET_ERROR;
  1254. goto exit;
  1255. }
  1256. }
  1257. }
  1258. #endif
  1259. if (m->c->connect_state == WEBSOCKET_IN_PROGRESS) /* websocket request sent - wait for upgrade */
  1260. {
  1261. Paho_thread_unlock_mutex(mqttclient_mutex);
  1262. MQTTClient_waitfor(handle, CONNECT, &rc, millisecsTimeout - MQTTTime_elapsed(start));
  1263. Paho_thread_lock_mutex(mqttclient_mutex);
  1264. m->c->connect_state = WAIT_FOR_CONNACK; /* websocket upgrade complete */
  1265. if (MQTTPacket_send_connect(m->c, MQTTVersion, connectProperties, willProperties) == SOCKET_ERROR)
  1266. {
  1267. rc = SOCKET_ERROR;
  1268. goto exit;
  1269. }
  1270. }
  1271. if (m->c->connect_state == WAIT_FOR_CONNACK) /* MQTT connect sent - wait for CONNACK */
  1272. {
  1273. MQTTPacket* pack = NULL;
  1274. Paho_thread_unlock_mutex(mqttclient_mutex);
  1275. pack = MQTTClient_waitfor(handle, CONNACK, &rc, millisecsTimeout - MQTTTime_elapsed(start));
  1276. Paho_thread_lock_mutex(mqttclient_mutex);
  1277. if (pack == NULL)
  1278. rc = SOCKET_ERROR;
  1279. else
  1280. {
  1281. Connack* connack = (Connack*)pack;
  1282. Log(TRACE_PROTOCOL, 1, NULL, m->c->net.socket, m->c->clientID, connack->rc);
  1283. if ((rc = connack->rc) == MQTTCLIENT_SUCCESS)
  1284. {
  1285. m->c->connected = 1;
  1286. m->c->good = 1;
  1287. m->c->connect_state = NOT_IN_PROGRESS;
  1288. if (MQTTVersion >= MQTTVERSION_3_1_1)
  1289. sessionPresent = connack->flags.bits.sessionPresent;
  1290. if (m->c->cleansession || m->c->cleanstart)
  1291. rc = MQTTClient_cleanSession(m->c);
  1292. if (m->c->outboundMsgs->count > 0)
  1293. {
  1294. ListElement* outcurrent = NULL;
  1295. START_TIME_TYPE zero = START_TIME_ZERO;
  1296. while (ListNextElement(m->c->outboundMsgs, &outcurrent))
  1297. {
  1298. Messages* m2 = (Messages*)(outcurrent->content);
  1299. memset(&m2->lastTouch, '\0', sizeof(m2->lastTouch));
  1300. }
  1301. MQTTProtocol_retry(zero, 1, 1);
  1302. if (m->c->connected != 1)
  1303. rc = MQTTCLIENT_DISCONNECTED;
  1304. }
  1305. if (m->c->MQTTVersion == MQTTVERSION_5)
  1306. {
  1307. if ((resp.properties = malloc(sizeof(MQTTProperties))) == NULL)
  1308. {
  1309. rc = PAHO_MEMORY_ERROR;
  1310. goto exit;
  1311. }
  1312. *resp.properties = MQTTProperties_copy(&connack->properties);
  1313. if (MQTTProperties_hasProperty(&connack->properties, MQTTPROPERTY_CODE_SERVER_KEEP_ALIVE))
  1314. {
  1315. /* update the keep alive from the server keep alive */
  1316. int server_keep_alive = (int)MQTTProperties_getNumericValue(&connack->properties, MQTTPROPERTY_CODE_SERVER_KEEP_ALIVE);
  1317. if (server_keep_alive != -999999)
  1318. {
  1319. Log(LOG_PROTOCOL, -1, "Setting keep alive interval to server keep alive %d", server_keep_alive);
  1320. m->c->keepAliveInterval = server_keep_alive;
  1321. }
  1322. }
  1323. else if (m->c->keepAliveInterval != m->c->savedKeepAliveInterval)
  1324. {
  1325. /* if the keep alive has been previously updated with a server keep alive, but there is no server keep alive
  1326. on this connect, reset it to the value requested in the original connect API */
  1327. Log(LOG_PROTOCOL, -1, "Resetting keep alive interval to %d", m->c->savedKeepAliveInterval);
  1328. m->c->keepAliveInterval = m->c->savedKeepAliveInterval;
  1329. }
  1330. }
  1331. }
  1332. MQTTPacket_freeConnack(connack);
  1333. m->pack = NULL;
  1334. }
  1335. }
  1336. exit:
  1337. if (rc == MQTTCLIENT_SUCCESS)
  1338. {
  1339. if (options->struct_version >= 4) /* means we have to fill out return values */
  1340. {
  1341. options->returned.serverURI = serverURI;
  1342. options->returned.MQTTVersion = MQTTVersion;
  1343. options->returned.sessionPresent = sessionPresent;
  1344. }
  1345. }
  1346. else
  1347. MQTTClient_disconnect1(handle, 0, 0, (MQTTVersion == 3), MQTTREASONCODE_SUCCESS, NULL); /* don't want to call connection lost */
  1348. resp.reasonCode = rc;
  1349. FUNC_EXIT_RC(resp.reasonCode);
  1350. return resp;
  1351. }
  1352. static int retryLoopIntervalms = 5000;
  1353. void setRetryLoopInterval(int keepalive)
  1354. {
  1355. retryLoopIntervalms = (keepalive*1000) / 10;
  1356. if (retryLoopIntervalms < 100)
  1357. retryLoopIntervalms = 100;
  1358. else if (retryLoopIntervalms > 5000)
  1359. retryLoopIntervalms = 5000;
  1360. }
  1361. static MQTTResponse MQTTClient_connectURI(MQTTClient handle, MQTTClient_connectOptions* options, const char* serverURI,
  1362. MQTTProperties* connectProperties, MQTTProperties* willProperties)
  1363. {
  1364. MQTTClients* m = handle;
  1365. START_TIME_TYPE start;
  1366. ELAPSED_TIME_TYPE millisecsTimeout = 30000L;
  1367. MQTTResponse rc = MQTTResponse_initializer;
  1368. int MQTTVersion = 0;
  1369. FUNC_ENTRY;
  1370. rc.reasonCode = SOCKET_ERROR;
  1371. millisecsTimeout = options->connectTimeout * 1000;
  1372. start = MQTTTime_start_clock();
  1373. m->currentServerURI = serverURI;
  1374. m->c->keepAliveInterval = m->c->savedKeepAliveInterval = options->keepAliveInterval;
  1375. m->c->retryInterval = options->retryInterval;
  1376. setRetryLoopInterval(options->keepAliveInterval);
  1377. m->c->MQTTVersion = options->MQTTVersion;
  1378. m->c->cleanstart = m->c->cleansession = 0;
  1379. if (m->c->MQTTVersion >= MQTTVERSION_5)
  1380. m->c->cleanstart = options->cleanstart;
  1381. else
  1382. m->c->cleansession = options->cleansession;
  1383. m->c->maxInflightMessages = (options->reliable) ? 1 : 10;
  1384. if (options->struct_version >= 6)
  1385. {
  1386. if (options->maxInflightMessages > 0)
  1387. m->c->maxInflightMessages = options->maxInflightMessages;
  1388. }
  1389. if (options->struct_version >= 7)
  1390. {
  1391. m->c->net.httpHeaders = options->httpHeaders;
  1392. }
  1393. if (options->struct_version >= 8)
  1394. {
  1395. if (options->httpProxy)
  1396. m->c->httpProxy = MQTTStrdup(options->httpProxy);
  1397. if (options->httpsProxy)
  1398. m->c->httpsProxy = MQTTStrdup(options->httpsProxy);
  1399. }
  1400. if (m->c->will)
  1401. {
  1402. free(m->c->will->payload);
  1403. free(m->c->will->topic);
  1404. free(m->c->will);
  1405. m->c->will = NULL;
  1406. }
  1407. if (options->will && (options->will->struct_version == 0 || options->will->struct_version == 1))
  1408. {
  1409. const void* source = NULL;
  1410. if ((m->c->will = malloc(sizeof(willMessages))) == NULL)
  1411. {
  1412. rc.reasonCode = PAHO_MEMORY_ERROR;
  1413. goto exit;
  1414. }
  1415. if (options->will->message || (options->will->struct_version == 1 && options->will->payload.data))
  1416. {
  1417. if (options->will->struct_version == 1 && options->will->payload.data)
  1418. {
  1419. m->c->will->payloadlen = options->will->payload.len;
  1420. source = options->will->payload.data;
  1421. }
  1422. else
  1423. {
  1424. m->c->will->payloadlen = (int)strlen(options->will->message);
  1425. source = (void*)options->will->message;
  1426. }
  1427. if ((m->c->will->payload = malloc(m->c->will->payloadlen)) == NULL)
  1428. {
  1429. free(m->c->will);
  1430. rc.reasonCode = PAHO_MEMORY_ERROR;
  1431. goto exit;
  1432. }
  1433. memcpy(m->c->will->payload, source, m->c->will->payloadlen);
  1434. }
  1435. else
  1436. {
  1437. m->c->will->payload = NULL;
  1438. m->c->will->payloadlen = 0;
  1439. }
  1440. m->c->will->qos = options->will->qos;
  1441. m->c->will->retained = options->will->retained;
  1442. m->c->will->topic = MQTTStrdup(options->will->topicName);
  1443. }
  1444. #if defined(OPENSSL)
  1445. if (m->c->sslopts)
  1446. {
  1447. if (m->c->sslopts->trustStore)
  1448. free((void*)m->c->sslopts->trustStore);
  1449. if (m->c->sslopts->keyStore)
  1450. free((void*)m->c->sslopts->keyStore);
  1451. if (m->c->sslopts->privateKey)
  1452. free((void*)m->c->sslopts->privateKey);
  1453. if (m->c->sslopts->privateKeyPassword)
  1454. free((void*)m->c->sslopts->privateKeyPassword);
  1455. if (m->c->sslopts->enabledCipherSuites)
  1456. free((void*)m->c->sslopts->enabledCipherSuites);
  1457. if (m->c->sslopts->struct_version >= 2)
  1458. {
  1459. if (m->c->sslopts->CApath)
  1460. free((void*)m->c->sslopts->CApath);
  1461. }
  1462. free(m->c->sslopts);
  1463. m->c->sslopts = NULL;
  1464. }
  1465. if (options->struct_version != 0 && options->ssl)
  1466. {
  1467. if ((m->c->sslopts = malloc(sizeof(MQTTClient_SSLOptions))) == NULL)
  1468. {
  1469. rc.reasonCode = PAHO_MEMORY_ERROR;
  1470. goto exit;
  1471. }
  1472. memset(m->c->sslopts, '\0', sizeof(MQTTClient_SSLOptions));
  1473. m->c->sslopts->struct_version = options->ssl->struct_version;
  1474. if (options->ssl->trustStore)
  1475. m->c->sslopts->trustStore = MQTTStrdup(options->ssl->trustStore);
  1476. if (options->ssl->keyStore)
  1477. m->c->sslopts->keyStore = MQTTStrdup(options->ssl->keyStore);
  1478. if (options->ssl->privateKey)
  1479. m->c->sslopts->privateKey = MQTTStrdup(options->ssl->privateKey);
  1480. if (options->ssl->privateKeyPassword)
  1481. m->c->sslopts->privateKeyPassword = MQTTStrdup(options->ssl->privateKeyPassword);
  1482. if (options->ssl->enabledCipherSuites)
  1483. m->c->sslopts->enabledCipherSuites = MQTTStrdup(options->ssl->enabledCipherSuites);
  1484. m->c->sslopts->enableServerCertAuth = options->ssl->enableServerCertAuth;
  1485. if (m->c->sslopts->struct_version >= 1)
  1486. m->c->sslopts->sslVersion = options->ssl->sslVersion;
  1487. if (m->c->sslopts->struct_version >= 2)
  1488. {
  1489. m->c->sslopts->verify = options->ssl->verify;
  1490. if (options->ssl->CApath)
  1491. m->c->sslopts->CApath = MQTTStrdup(options->ssl->CApath);
  1492. }
  1493. if (m->c->sslopts->struct_version >= 3)
  1494. {
  1495. m->c->sslopts->ssl_error_cb = options->ssl->ssl_error_cb;
  1496. m->c->sslopts->ssl_error_context = options->ssl->ssl_error_context;
  1497. }
  1498. if (m->c->sslopts->struct_version >= 4)
  1499. {
  1500. m->c->sslopts->ssl_psk_cb = options->ssl->ssl_psk_cb;
  1501. m->c->sslopts->ssl_psk_context = options->ssl->ssl_psk_context;
  1502. m->c->sslopts->disableDefaultTrustStore = options->ssl->disableDefaultTrustStore;
  1503. }
  1504. if (m->c->sslopts->struct_version >= 5)
  1505. {
  1506. m->c->sslopts->protos = options->ssl->protos;
  1507. m->c->sslopts->protos_len = options->ssl->protos_len;
  1508. }
  1509. }
  1510. #endif
  1511. if (m->c->username)
  1512. {
  1513. free((void*)m->c->username);
  1514. m->c->username = NULL;
  1515. }
  1516. if (options->username)
  1517. m->c->username = MQTTStrdup(options->username);
  1518. if (m->c->password)
  1519. {
  1520. free((void*)m->c->password);
  1521. m->c->password = NULL;
  1522. }
  1523. if (options->password)
  1524. {
  1525. m->c->password = MQTTStrdup(options->password);
  1526. m->c->passwordlen = (int)strlen(options->password);
  1527. }
  1528. else if (options->struct_version >= 5 && options->binarypwd.data)
  1529. {
  1530. m->c->passwordlen = options->binarypwd.len;
  1531. if ((m->c->password = malloc(m->c->passwordlen)) == NULL)
  1532. {
  1533. rc.reasonCode = PAHO_MEMORY_ERROR;
  1534. goto exit;
  1535. }
  1536. memcpy((void*)m->c->password, options->binarypwd.data, m->c->passwordlen);
  1537. }
  1538. if (options->struct_version >= 3)
  1539. MQTTVersion = options->MQTTVersion;
  1540. else
  1541. MQTTVersion = MQTTVERSION_DEFAULT;
  1542. if (MQTTVersion == MQTTVERSION_DEFAULT)
  1543. {
  1544. rc = MQTTClient_connectURIVersion(handle, options, serverURI, 4, start, millisecsTimeout,
  1545. connectProperties, willProperties);
  1546. if (rc.reasonCode != MQTTCLIENT_SUCCESS)
  1547. {
  1548. rc = MQTTClient_connectURIVersion(handle, options, serverURI, 3, start, millisecsTimeout,
  1549. connectProperties, willProperties);
  1550. }
  1551. }
  1552. else
  1553. rc = MQTTClient_connectURIVersion(handle, options, serverURI, MQTTVersion, start, millisecsTimeout,
  1554. connectProperties, willProperties);
  1555. exit:
  1556. FUNC_EXIT_RC(rc.reasonCode);
  1557. return rc;
  1558. }
  1559. MQTTResponse MQTTClient_connectAll(MQTTClient handle, MQTTClient_connectOptions* options,
  1560. MQTTProperties* connectProperties, MQTTProperties* willProperties);
  1561. int MQTTClient_connect(MQTTClient handle, MQTTClient_connectOptions* options)
  1562. {
  1563. MQTTClients* m = handle;
  1564. MQTTResponse response;
  1565. if (m != NULL && m->c != NULL && m->c->MQTTVersion >= MQTTVERSION_5)
  1566. return MQTTCLIENT_WRONG_MQTT_VERSION;
  1567. response = MQTTClient_connectAll(handle, options, NULL, NULL);
  1568. return response.reasonCode;
  1569. }
  1570. MQTTResponse MQTTClient_connect5(MQTTClient handle, MQTTClient_connectOptions* options,
  1571. MQTTProperties* connectProperties, MQTTProperties* willProperties)
  1572. {
  1573. MQTTClients* m = handle;
  1574. MQTTResponse response = MQTTResponse_initializer;
  1575. if (m != NULL && m->c != NULL && m->c->MQTTVersion < MQTTVERSION_5)
  1576. {
  1577. response.reasonCode = MQTTCLIENT_WRONG_MQTT_VERSION;
  1578. return response;
  1579. }
  1580. return MQTTClient_connectAll(handle, options, connectProperties, willProperties);
  1581. }
  1582. MQTTResponse MQTTClient_connectAll(MQTTClient handle, MQTTClient_connectOptions* options,
  1583. MQTTProperties* connectProperties, MQTTProperties* willProperties)
  1584. {
  1585. MQTTClients* m = handle;
  1586. MQTTResponse rc = MQTTResponse_initializer;
  1587. FUNC_ENTRY;
  1588. Paho_thread_lock_mutex(connect_mutex);
  1589. Paho_thread_lock_mutex(mqttclient_mutex);
  1590. rc.reasonCode = SOCKET_ERROR;
  1591. if (!library_initialized)
  1592. {
  1593. rc.reasonCode = MQTTCLIENT_FAILURE;
  1594. goto exit;
  1595. }
  1596. if (options == NULL || m == NULL || m->c == NULL)
  1597. {
  1598. rc.reasonCode = MQTTCLIENT_NULL_PARAMETER;
  1599. goto exit;
  1600. }
  1601. if (strncmp(options->struct_id, "MQTC", 4) != 0 || options->struct_version < 0 || options->struct_version > 8)
  1602. {
  1603. rc.reasonCode = MQTTCLIENT_BAD_STRUCTURE;
  1604. goto exit;
  1605. }
  1606. #if defined(OPENSSL)
  1607. if (m->ssl && options->ssl == NULL)
  1608. {
  1609. rc.reasonCode = MQTTCLIENT_NULL_PARAMETER;
  1610. goto exit;
  1611. }
  1612. #endif
  1613. if (options->will) /* check validity of will options structure */
  1614. {
  1615. if (strncmp(options->will->struct_id, "MQTW", 4) != 0 || (options->will->struct_version != 0 && options->will->struct_version != 1))
  1616. {
  1617. rc.reasonCode = MQTTCLIENT_BAD_STRUCTURE;
  1618. goto exit;
  1619. }
  1620. if (options->will->qos < 0 || options->will->qos > 2)
  1621. {
  1622. rc.reasonCode = MQTTCLIENT_BAD_QOS;
  1623. goto exit;
  1624. }
  1625. if (options->will->topicName == NULL)
  1626. {
  1627. rc.reasonCode = MQTTCLIENT_NULL_PARAMETER;
  1628. goto exit;
  1629. } else if (strlen(options->will->topicName) == 0)
  1630. {
  1631. rc.reasonCode = MQTTCLIENT_0_LEN_WILL_TOPIC;
  1632. goto exit;
  1633. }
  1634. }
  1635. #if defined(OPENSSL)
  1636. if (options->struct_version != 0 && options->ssl) /* check validity of SSL options structure */
  1637. {
  1638. if (strncmp(options->ssl->struct_id, "MQTS", 4) != 0 || options->ssl->struct_version < 0 || options->ssl->struct_version > 5)
  1639. {
  1640. rc.reasonCode = MQTTCLIENT_BAD_STRUCTURE;
  1641. goto exit;
  1642. }
  1643. }
  1644. #endif
  1645. if ((options->username && !UTF8_validateString(options->username)) ||
  1646. (options->password && !UTF8_validateString(options->password)))
  1647. {
  1648. rc.reasonCode = MQTTCLIENT_BAD_UTF8_STRING;
  1649. goto exit;
  1650. }
  1651. if (options->MQTTVersion != MQTTVERSION_DEFAULT &&
  1652. (options->MQTTVersion < MQTTVERSION_3_1 || options->MQTTVersion > MQTTVERSION_5))
  1653. {
  1654. rc.reasonCode = MQTTCLIENT_BAD_MQTT_VERSION;
  1655. goto exit;
  1656. }
  1657. if (options->MQTTVersion >= MQTTVERSION_5)
  1658. {
  1659. if (options->cleansession != 0)
  1660. {
  1661. rc.reasonCode = MQTTCLIENT_BAD_MQTT_OPTION;
  1662. goto exit;
  1663. }
  1664. }
  1665. else if (options->cleanstart != 0)
  1666. {
  1667. rc.reasonCode = MQTTCLIENT_BAD_MQTT_OPTION;
  1668. goto exit;
  1669. }
  1670. if (options->struct_version < 2 || options->serverURIcount == 0)
  1671. {
  1672. if ( !m )
  1673. {
  1674. rc.reasonCode = MQTTCLIENT_NULL_PARAMETER;
  1675. goto exit;
  1676. }
  1677. rc = MQTTClient_connectURI(handle, options, m->serverURI, connectProperties, willProperties);
  1678. }
  1679. else
  1680. {
  1681. int i;
  1682. for (i = 0; i < options->serverURIcount; ++i)
  1683. {
  1684. char* serverURI = options->serverURIs[i];
  1685. if (strncmp(URI_TCP, serverURI, strlen(URI_TCP)) == 0)
  1686. serverURI += strlen(URI_TCP);
  1687. else if (strncmp(URI_MQTT, serverURI, strlen(URI_MQTT)) == 0)
  1688. serverURI += strlen(URI_TCP);
  1689. else if (strncmp(URI_WS, serverURI, strlen(URI_WS)) == 0)
  1690. {
  1691. serverURI += strlen(URI_WS);
  1692. m->websocket = 1;
  1693. }
  1694. #if defined(OPENSSL)
  1695. else if (strncmp(URI_SSL, serverURI, strlen(URI_SSL)) == 0)
  1696. {
  1697. serverURI += strlen(URI_SSL);
  1698. m->ssl = 1;
  1699. }
  1700. else if (strncmp(URI_MQTTS, serverURI, strlen(URI_MQTTS)) == 0)
  1701. {
  1702. serverURI += strlen(URI_MQTTS);
  1703. m->ssl = 1;
  1704. }
  1705. else if (strncmp(URI_WSS, serverURI, strlen(URI_WSS)) == 0)
  1706. {
  1707. serverURI += strlen(URI_WSS);
  1708. m->ssl = 1;
  1709. m->websocket = 1;
  1710. }
  1711. #endif
  1712. #if defined(UNIXSOCK)
  1713. else if (strncmp(URI_UNIX, serverURI, strlen(URI_UNIX)) == 0)
  1714. {
  1715. serverURI += strlen(URI_UNIX);
  1716. m->unixsock = 1;
  1717. }
  1718. #endif
  1719. rc = MQTTClient_connectURI(handle, options, serverURI, connectProperties, willProperties);
  1720. if (rc.reasonCode == MQTTREASONCODE_SUCCESS)
  1721. break;
  1722. }
  1723. }
  1724. if (rc.reasonCode == MQTTREASONCODE_SUCCESS)
  1725. {
  1726. if (rc.properties && MQTTProperties_hasProperty(rc.properties, MQTTPROPERTY_CODE_RECEIVE_MAXIMUM))
  1727. {
  1728. int recv_max = (int)MQTTProperties_getNumericValue(rc.properties, MQTTPROPERTY_CODE_RECEIVE_MAXIMUM);
  1729. if (m->c->maxInflightMessages > recv_max)
  1730. m->c->maxInflightMessages = recv_max;
  1731. }
  1732. }
  1733. exit:
  1734. if (m && m->c && m->c->will)
  1735. {
  1736. if (m->c->will->payload)
  1737. free(m->c->will->payload);
  1738. if (m->c->will->topic)
  1739. free(m->c->will->topic);
  1740. free(m->c->will);
  1741. m->c->will = NULL;
  1742. }
  1743. Paho_thread_unlock_mutex(mqttclient_mutex);
  1744. Paho_thread_unlock_mutex(connect_mutex);
  1745. FUNC_EXIT_RC(rc.reasonCode);
  1746. return rc;
  1747. }
  1748. /**
  1749. * mqttclient_mutex must be locked when you call this function, if multi threaded
  1750. */
  1751. static int MQTTClient_disconnect1(MQTTClient handle, int timeout, int call_connection_lost, int stop,
  1752. enum MQTTReasonCodes reason, MQTTProperties* props)
  1753. {
  1754. MQTTClients* m = handle;
  1755. START_TIME_TYPE start;
  1756. int rc = MQTTCLIENT_SUCCESS;
  1757. int was_connected = 0;
  1758. struct conlost_sync_data sync = {
  1759. NULL, m
  1760. };
  1761. FUNC_ENTRY;
  1762. if (m == NULL || m->c == NULL)
  1763. {
  1764. rc = MQTTCLIENT_FAILURE;
  1765. goto exit;
  1766. }
  1767. was_connected = m->c->connected; /* should be 1 */
  1768. if (m->c->connected != 0)
  1769. {
  1770. start = MQTTTime_start_clock();
  1771. m->c->connect_state = DISCONNECTING; /* indicate disconnecting */
  1772. while (m->c->inboundMsgs->count > 0 || m->c->outboundMsgs->count > 0)
  1773. { /* wait for all inflight message flows to finish, up to timeout */
  1774. if (MQTTTime_elapsed(start) >= (ELAPSED_TIME_TYPE)timeout)
  1775. break;
  1776. Paho_thread_unlock_mutex(mqttclient_mutex);
  1777. MQTTClient_yield();
  1778. Paho_thread_lock_mutex(mqttclient_mutex);
  1779. }
  1780. }
  1781. MQTTClient_closeSession(m->c, reason, props);
  1782. exit:
  1783. if (stop)
  1784. MQTTClient_stop();
  1785. if (call_connection_lost && m->cl && was_connected)
  1786. {
  1787. sync.sem = Thread_create_sem(&rc);
  1788. Log(TRACE_MIN, -1, "Calling connectionLost for client %s", m->c->clientID);
  1789. Paho_thread_start(connectionLost_call, &sync);
  1790. Thread_wait_sem(sync.sem, 5000);
  1791. Thread_destroy_sem(sync.sem);
  1792. }
  1793. FUNC_EXIT_RC(rc);
  1794. return rc;
  1795. }
  1796. /**
  1797. * mqttclient_mutex must be locked when you call this function, if multi threaded
  1798. */
  1799. static int MQTTClient_disconnect_internal(MQTTClient handle, int timeout)
  1800. {
  1801. return MQTTClient_disconnect1(handle, timeout, 1, 1, MQTTREASONCODE_SUCCESS, NULL);
  1802. }
  1803. /**
  1804. * mqttclient_mutex must be locked when you call this function, if multi threaded
  1805. */
  1806. void MQTTProtocol_closeSession(Clients* c, int sendwill)
  1807. {
  1808. MQTTClient_disconnect_internal((MQTTClient)c->context, 0);
  1809. }
  1810. int MQTTClient_disconnect(MQTTClient handle, int timeout)
  1811. {
  1812. int rc = 0;
  1813. Paho_thread_lock_mutex(mqttclient_mutex);
  1814. rc = MQTTClient_disconnect1(handle, timeout, 0, 1, MQTTREASONCODE_SUCCESS, NULL);
  1815. Paho_thread_unlock_mutex(mqttclient_mutex);
  1816. return rc;
  1817. }
  1818. int MQTTClient_disconnect5(MQTTClient handle, int timeout, enum MQTTReasonCodes reason, MQTTProperties* props)
  1819. {
  1820. int rc = 0;
  1821. Paho_thread_lock_mutex(mqttclient_mutex);
  1822. rc = MQTTClient_disconnect1(handle, timeout, 0, 1, reason, props);
  1823. Paho_thread_unlock_mutex(mqttclient_mutex);
  1824. return rc;
  1825. }
  1826. int MQTTClient_isConnected(MQTTClient handle)
  1827. {
  1828. MQTTClients* m = handle;
  1829. int rc = 0;
  1830. FUNC_ENTRY;
  1831. Paho_thread_lock_mutex(mqttclient_mutex);
  1832. if (m && m->c)
  1833. rc = m->c->connected;
  1834. Paho_thread_unlock_mutex(mqttclient_mutex);
  1835. FUNC_EXIT_RC(rc);
  1836. return rc;
  1837. }
  1838. MQTTResponse MQTTClient_subscribeMany5(MQTTClient handle, int count, char* const* topic,
  1839. int* qos, MQTTSubscribe_options* opts, MQTTProperties* props)
  1840. {
  1841. MQTTClients* m = handle;
  1842. List* topics = NULL;
  1843. List* qoss = NULL;
  1844. int i = 0;
  1845. int rc = MQTTCLIENT_FAILURE;
  1846. MQTTResponse resp = MQTTResponse_initializer;
  1847. int msgid = 0;
  1848. FUNC_ENTRY;
  1849. Paho_thread_lock_mutex(subscribe_mutex);
  1850. Paho_thread_lock_mutex(mqttclient_mutex);
  1851. resp.reasonCode = MQTTCLIENT_FAILURE;
  1852. if (m == NULL || m->c == NULL)
  1853. {
  1854. rc = MQTTCLIENT_FAILURE;
  1855. goto exit;
  1856. }
  1857. if (m->c->connected == 0)
  1858. {
  1859. rc = MQTTCLIENT_DISCONNECTED;
  1860. goto exit;
  1861. }
  1862. for (i = 0; i < count; i++)
  1863. {
  1864. if (!UTF8_validateString(topic[i]))
  1865. {
  1866. rc = MQTTCLIENT_BAD_UTF8_STRING;
  1867. goto exit;
  1868. }
  1869. if (qos[i] < 0 || qos[i] > 2)
  1870. {
  1871. rc = MQTTCLIENT_BAD_QOS;
  1872. goto exit;
  1873. }
  1874. }
  1875. if ((msgid = MQTTProtocol_assignMsgId(m->c)) == 0)
  1876. {
  1877. rc = MQTTCLIENT_MAX_MESSAGES_INFLIGHT;
  1878. goto exit;
  1879. }
  1880. topics = ListInitialize();
  1881. qoss = ListInitialize();
  1882. for (i = 0; i < count; i++)
  1883. {
  1884. ListAppend(topics, topic[i], strlen(topic[i]));
  1885. ListAppend(qoss, &qos[i], sizeof(int));
  1886. }
  1887. rc = MQTTProtocol_subscribe(m->c, topics, qoss, msgid, opts, props);
  1888. ListFreeNoContent(topics);
  1889. ListFreeNoContent(qoss);
  1890. if (rc == TCPSOCKET_COMPLETE)
  1891. {
  1892. MQTTPacket* pack = NULL;
  1893. Paho_thread_unlock_mutex(mqttclient_mutex);
  1894. pack = MQTTClient_waitfor(handle, SUBACK, &rc, m->commandTimeout);
  1895. Paho_thread_lock_mutex(mqttclient_mutex);
  1896. if (pack != NULL)
  1897. {
  1898. Suback* sub = (Suback*)pack;
  1899. if (m->c->MQTTVersion == MQTTVERSION_5)
  1900. {
  1901. if (sub->properties.count > 0)
  1902. {
  1903. if ((resp.properties = malloc(sizeof(MQTTProperties))) == NULL)
  1904. {
  1905. rc = PAHO_MEMORY_ERROR;
  1906. goto exit;
  1907. }
  1908. *resp.properties = MQTTProperties_copy(&sub->properties);
  1909. }
  1910. resp.reasonCodeCount = sub->qoss->count;
  1911. resp.reasonCode = *(int*)sub->qoss->first->content;
  1912. if (sub->qoss->count > 1)
  1913. {
  1914. ListElement* current = NULL;
  1915. int rc_count = 0;
  1916. if ((resp.reasonCodes = malloc(sizeof(enum MQTTReasonCodes) * (sub->qoss->count))) == NULL)
  1917. {
  1918. rc = PAHO_MEMORY_ERROR;
  1919. goto exit;
  1920. }
  1921. while (ListNextElement(sub->qoss, &current))
  1922. (resp.reasonCodes)[rc_count++] = *(enum MQTTReasonCodes*)(current->content);
  1923. }
  1924. }
  1925. else
  1926. {
  1927. ListElement *current = NULL;
  1928. /* if the returned count is greater than requested, it's an error*/
  1929. if (sub->qoss->count > count)
  1930. rc = MQTTCLIENT_FAILURE;
  1931. else
  1932. {
  1933. i = 0;
  1934. while (ListNextElement(sub->qoss, &current))
  1935. {
  1936. int *reqqos = (int*) (current->content);
  1937. qos[i++] = *reqqos;
  1938. }
  1939. }
  1940. resp.reasonCode = rc;
  1941. }
  1942. rc = MQTTProtocol_handleSubacks(pack, m->c->net.socket);
  1943. m->pack = NULL;
  1944. }
  1945. else
  1946. rc = SOCKET_ERROR;
  1947. }
  1948. if (rc == SOCKET_ERROR)
  1949. MQTTClient_disconnect_internal(handle, 0);
  1950. else if (rc == TCPSOCKET_COMPLETE)
  1951. rc = MQTTCLIENT_SUCCESS;
  1952. exit:
  1953. if (rc < 0)
  1954. resp.reasonCode = rc;
  1955. Paho_thread_unlock_mutex(mqttclient_mutex);
  1956. Paho_thread_unlock_mutex(subscribe_mutex);
  1957. FUNC_EXIT_RC(resp.reasonCode);
  1958. return resp;
  1959. }
  1960. int MQTTClient_subscribeMany(MQTTClient handle, int count, char* const* topic, int* qos)
  1961. {
  1962. MQTTClients* m = handle;
  1963. MQTTResponse response = MQTTResponse_initializer;
  1964. if (m != NULL && m->c != NULL && m->c->MQTTVersion >= MQTTVERSION_5)
  1965. response.reasonCode = MQTTCLIENT_WRONG_MQTT_VERSION;
  1966. else
  1967. response = MQTTClient_subscribeMany5(handle, count, topic, qos, NULL, NULL);
  1968. return response.reasonCode;
  1969. }
  1970. MQTTResponse MQTTClient_subscribe5(MQTTClient handle, const char* topic, int qos,
  1971. MQTTSubscribe_options* opts, MQTTProperties* props)
  1972. {
  1973. MQTTResponse rc;
  1974. FUNC_ENTRY;
  1975. rc = MQTTClient_subscribeMany5(handle, 1, (char * const *)(&topic), &qos, opts, props);
  1976. if (qos == MQTT_BAD_SUBSCRIBE) /* addition for MQTT 3.1.1 - error code from subscribe */
  1977. rc.reasonCode = MQTT_BAD_SUBSCRIBE;
  1978. FUNC_EXIT_RC(rc.reasonCode);
  1979. return rc;
  1980. }
  1981. int MQTTClient_subscribe(MQTTClient handle, const char* topic, int qos)
  1982. {
  1983. MQTTClients* m = handle;
  1984. MQTTResponse response = MQTTResponse_initializer;
  1985. if (m->c->MQTTVersion >= MQTTVERSION_5)
  1986. response.reasonCode = MQTTCLIENT_WRONG_MQTT_VERSION;
  1987. else
  1988. response = MQTTClient_subscribe5(handle, topic, qos, NULL, NULL);
  1989. return response.reasonCode;
  1990. }
  1991. MQTTResponse MQTTClient_unsubscribeMany5(MQTTClient handle, int count, char* const* topic, MQTTProperties* props)
  1992. {
  1993. MQTTClients* m = handle;
  1994. List* topics = NULL;
  1995. int i = 0;
  1996. int rc = SOCKET_ERROR;
  1997. MQTTResponse resp = MQTTResponse_initializer;
  1998. int msgid = 0;
  1999. FUNC_ENTRY;
  2000. Paho_thread_lock_mutex(subscribe_mutex);
  2001. Paho_thread_lock_mutex(mqttclient_mutex);
  2002. resp.reasonCode = MQTTCLIENT_FAILURE;
  2003. if (m == NULL || m->c == NULL)
  2004. {
  2005. rc = MQTTCLIENT_FAILURE;
  2006. goto exit;
  2007. }
  2008. if (m->c->connected == 0)
  2009. {
  2010. rc = MQTTCLIENT_DISCONNECTED;
  2011. goto exit;
  2012. }
  2013. for (i = 0; i < count; i++)
  2014. {
  2015. if (!UTF8_validateString(topic[i]))
  2016. {
  2017. rc = MQTTCLIENT_BAD_UTF8_STRING;
  2018. goto exit;
  2019. }
  2020. }
  2021. if ((msgid = MQTTProtocol_assignMsgId(m->c)) == 0)
  2022. {
  2023. rc = MQTTCLIENT_MAX_MESSAGES_INFLIGHT;
  2024. goto exit;
  2025. }
  2026. topics = ListInitialize();
  2027. for (i = 0; i < count; i++)
  2028. ListAppend(topics, topic[i], strlen(topic[i]));
  2029. rc = MQTTProtocol_unsubscribe(m->c, topics, msgid, props);
  2030. ListFreeNoContent(topics);
  2031. if (rc == TCPSOCKET_COMPLETE)
  2032. {
  2033. MQTTPacket* pack = NULL;
  2034. Paho_thread_unlock_mutex(mqttclient_mutex);
  2035. pack = MQTTClient_waitfor(handle, UNSUBACK, &rc, m->commandTimeout);
  2036. Paho_thread_lock_mutex(mqttclient_mutex);
  2037. if (pack != NULL)
  2038. {
  2039. Unsuback* unsub = (Unsuback*)pack;
  2040. if (m->c->MQTTVersion == MQTTVERSION_5)
  2041. {
  2042. if (unsub->properties.count > 0)
  2043. {
  2044. if ((resp.properties = malloc(sizeof(MQTTProperties))) == NULL)
  2045. {
  2046. rc = PAHO_MEMORY_ERROR;
  2047. goto exit;
  2048. }
  2049. *resp.properties = MQTTProperties_copy(&unsub->properties);
  2050. }
  2051. resp.reasonCodeCount = unsub->reasonCodes->count;
  2052. resp.reasonCode = *(int*)unsub->reasonCodes->first->content;
  2053. if (unsub->reasonCodes->count > 1)
  2054. {
  2055. ListElement* current = NULL;
  2056. int rc_count = 0;
  2057. if ((resp.reasonCodes = malloc(sizeof(enum MQTTReasonCodes) * (unsub->reasonCodes->count))) == NULL)
  2058. {
  2059. rc = PAHO_MEMORY_ERROR;
  2060. goto exit;
  2061. }
  2062. while (ListNextElement(unsub->reasonCodes, &current))
  2063. (resp.reasonCodes)[rc_count++] = *(enum MQTTReasonCodes*)(current->content);
  2064. }
  2065. }
  2066. else
  2067. resp.reasonCode = rc;
  2068. rc = MQTTProtocol_handleUnsubacks(pack, m->c->net.socket);
  2069. m->pack = NULL;
  2070. }
  2071. else
  2072. rc = SOCKET_ERROR;
  2073. }
  2074. if (rc == SOCKET_ERROR)
  2075. MQTTClient_disconnect_internal(handle, 0);
  2076. exit:
  2077. if (rc < 0)
  2078. resp.reasonCode = rc;
  2079. Paho_thread_unlock_mutex(mqttclient_mutex);
  2080. Paho_thread_unlock_mutex(subscribe_mutex);
  2081. FUNC_EXIT_RC(resp.reasonCode);
  2082. return resp;
  2083. }
  2084. int MQTTClient_unsubscribeMany(MQTTClient handle, int count, char* const* topic)
  2085. {
  2086. MQTTClients* m = handle;
  2087. MQTTResponse response = MQTTResponse_initializer;
  2088. if (m != NULL && m->c != NULL && m->c->MQTTVersion >= MQTTVERSION_5)
  2089. response.reasonCode = MQTTCLIENT_WRONG_MQTT_VERSION;
  2090. else
  2091. response = MQTTClient_unsubscribeMany5(handle, count, topic, NULL);
  2092. return response.reasonCode;
  2093. }
  2094. MQTTResponse MQTTClient_unsubscribe5(MQTTClient handle, const char* topic, MQTTProperties* props)
  2095. {
  2096. MQTTResponse rc;
  2097. rc = MQTTClient_unsubscribeMany5(handle, 1, (char * const *)(&topic), props);
  2098. return rc;
  2099. }
  2100. int MQTTClient_unsubscribe(MQTTClient handle, const char* topic)
  2101. {
  2102. MQTTResponse response = MQTTClient_unsubscribe5(handle, topic, NULL);
  2103. return response.reasonCode;
  2104. }
  2105. MQTTResponse MQTTClient_publish5(MQTTClient handle, const char* topicName, int payloadlen, const void* payload,
  2106. int qos, int retained, MQTTProperties* properties, MQTTClient_deliveryToken* deliveryToken)
  2107. {
  2108. int rc = MQTTCLIENT_SUCCESS;
  2109. MQTTClients* m = handle;
  2110. Messages* msg = NULL;
  2111. Publish* p = NULL;
  2112. int blocked = 0;
  2113. int msgid = 0;
  2114. MQTTResponse resp = MQTTResponse_initializer;
  2115. FUNC_ENTRY;
  2116. Paho_thread_lock_mutex(mqttclient_mutex);
  2117. if (m == NULL || m->c == NULL)
  2118. rc = MQTTCLIENT_FAILURE;
  2119. else if (m->c->connected == 0)
  2120. rc = MQTTCLIENT_DISCONNECTED;
  2121. else if (!UTF8_validateString(topicName))
  2122. rc = MQTTCLIENT_BAD_UTF8_STRING;
  2123. if (rc != MQTTCLIENT_SUCCESS)
  2124. goto exit;
  2125. /* If outbound queue is full, block until it is not */
  2126. while (m->c->outboundMsgs->count >= m->c->maxInflightMessages ||
  2127. Socket_noPendingWrites(m->c->net.socket) == 0) /* wait until the socket is free of large packets being written */
  2128. {
  2129. if (blocked == 0)
  2130. {
  2131. blocked = 1;
  2132. Log(TRACE_MIN, -1, "Blocking publish on queue full for client %s", m->c->clientID);
  2133. }
  2134. Paho_thread_unlock_mutex(mqttclient_mutex);
  2135. MQTTClient_yield();
  2136. Paho_thread_lock_mutex(mqttclient_mutex);
  2137. if (m->c->connected == 0)
  2138. {
  2139. rc = MQTTCLIENT_FAILURE;
  2140. goto exit;
  2141. }
  2142. }
  2143. if (blocked == 1)
  2144. Log(TRACE_MIN, -1, "Resuming publish now queue not full for client %s", m->c->clientID);
  2145. if (qos > 0 && (msgid = MQTTProtocol_assignMsgId(m->c)) == 0)
  2146. { /* this should never happen as we've waited for spaces in the queue */
  2147. rc = MQTTCLIENT_MAX_MESSAGES_INFLIGHT;
  2148. goto exit;
  2149. }
  2150. if ((p = malloc(sizeof(Publish))) == NULL)
  2151. {
  2152. rc = PAHO_MEMORY_ERROR;
  2153. goto exit_and_free;
  2154. }
  2155. memset(p->mask, '\0', sizeof(p->mask));
  2156. p->payload = NULL;
  2157. p->payloadlen = payloadlen;
  2158. if (payloadlen > 0)
  2159. {
  2160. if ((p->payload = malloc(payloadlen)) == NULL)
  2161. {
  2162. rc = PAHO_MEMORY_ERROR;
  2163. goto exit_and_free;
  2164. }
  2165. memcpy(p->payload, payload, payloadlen);
  2166. }
  2167. if ((p->topic = MQTTStrdup(topicName)) == NULL)
  2168. {
  2169. rc = PAHO_MEMORY_ERROR;
  2170. goto exit_and_free;
  2171. }
  2172. p->msgId = msgid;
  2173. p->MQTTVersion = m->c->MQTTVersion;
  2174. if (m->c->MQTTVersion >= MQTTVERSION_5)
  2175. {
  2176. if (properties)
  2177. p->properties = *properties;
  2178. else
  2179. {
  2180. MQTTProperties props = MQTTProperties_initializer;
  2181. p->properties = props;
  2182. }
  2183. }
  2184. rc = MQTTProtocol_startPublish(m->c, p, qos, retained, &msg);
  2185. /* If the packet was partially written to the socket, wait for it to complete.
  2186. * However, if the client is disconnected during this time and qos is not 0, still return success, as
  2187. * the packet has already been written to persistence and assigned a message id so will
  2188. * be sent when the client next connects.
  2189. */
  2190. if (rc == TCPSOCKET_INTERRUPTED)
  2191. {
  2192. while (m->c->connected == 1)
  2193. {
  2194. pending_writes* writing = NULL;
  2195. Paho_thread_lock_mutex(socket_mutex);
  2196. writing = SocketBuffer_getWrite(m->c->net.socket);
  2197. Paho_thread_unlock_mutex(socket_mutex);
  2198. if (writing == NULL)
  2199. break;
  2200. Paho_thread_unlock_mutex(mqttclient_mutex);
  2201. MQTTClient_yield();
  2202. Paho_thread_lock_mutex(mqttclient_mutex);
  2203. }
  2204. rc = (qos > 0 || m->c->connected == 1) ? MQTTCLIENT_SUCCESS : MQTTCLIENT_FAILURE;
  2205. }
  2206. if (deliveryToken && qos > 0)
  2207. *deliveryToken = msg->msgid;
  2208. exit_and_free:
  2209. if (p)
  2210. {
  2211. if (p->topic)
  2212. free(p->topic);
  2213. if (p->payload)
  2214. free(p->payload);
  2215. free(p);
  2216. }
  2217. if (rc == SOCKET_ERROR)
  2218. {
  2219. MQTTClient_disconnect_internal(handle, 0);
  2220. /* Return success for qos > 0 as the send will be retried automatically */
  2221. rc = (qos > 0) ? MQTTCLIENT_SUCCESS : MQTTCLIENT_FAILURE;
  2222. }
  2223. exit:
  2224. Paho_thread_unlock_mutex(mqttclient_mutex);
  2225. resp.reasonCode = rc;
  2226. FUNC_EXIT_RC(resp.reasonCode);
  2227. return resp;
  2228. }
  2229. int MQTTClient_publish(MQTTClient handle, const char* topicName, int payloadlen, const void* payload,
  2230. int qos, int retained, MQTTClient_deliveryToken* deliveryToken)
  2231. {
  2232. MQTTClients* m = handle;
  2233. MQTTResponse rc = MQTTResponse_initializer;
  2234. if (m->c->MQTTVersion >= MQTTVERSION_5)
  2235. rc.reasonCode = MQTTCLIENT_WRONG_MQTT_VERSION;
  2236. else
  2237. rc = MQTTClient_publish5(handle, topicName, payloadlen, payload, qos, retained, NULL, deliveryToken);
  2238. return rc.reasonCode;
  2239. }
  2240. MQTTResponse MQTTClient_publishMessage5(MQTTClient handle, const char* topicName, MQTTClient_message* message,
  2241. MQTTClient_deliveryToken* deliveryToken)
  2242. {
  2243. MQTTResponse rc = MQTTResponse_initializer;
  2244. MQTTProperties* props = NULL;
  2245. FUNC_ENTRY;
  2246. if (message == NULL)
  2247. {
  2248. rc.reasonCode = MQTTCLIENT_NULL_PARAMETER;
  2249. goto exit;
  2250. }
  2251. if (strncmp(message->struct_id, "MQTM", 4) != 0 ||
  2252. (message->struct_version != 0 && message->struct_version != 1))
  2253. {
  2254. rc.reasonCode = MQTTCLIENT_BAD_STRUCTURE;
  2255. goto exit;
  2256. }
  2257. if (message->struct_version >= 1)
  2258. props = &message->properties;
  2259. rc = MQTTClient_publish5(handle, topicName, message->payloadlen, message->payload,
  2260. message->qos, message->retained, props, deliveryToken);
  2261. exit:
  2262. FUNC_EXIT_RC(rc.reasonCode);
  2263. return rc;
  2264. }
  2265. int MQTTClient_publishMessage(MQTTClient handle, const char* topicName, MQTTClient_message* message,
  2266. MQTTClient_deliveryToken* deliveryToken)
  2267. {
  2268. MQTTClients* m = handle;
  2269. MQTTResponse rc = MQTTResponse_initializer;
  2270. if (strncmp(message->struct_id, "MQTM", 4) != 0 ||
  2271. (message->struct_version != 0 && message->struct_version != 1))
  2272. rc.reasonCode = MQTTCLIENT_BAD_STRUCTURE;
  2273. else if (m != NULL && m->c != NULL && m->c->MQTTVersion >= MQTTVERSION_5)
  2274. rc.reasonCode = MQTTCLIENT_WRONG_MQTT_VERSION;
  2275. else
  2276. rc = MQTTClient_publishMessage5(handle, topicName, message, deliveryToken);
  2277. return rc.reasonCode;
  2278. }
  2279. static void MQTTClient_retry(void)
  2280. {
  2281. static START_TIME_TYPE last = START_TIME_ZERO;
  2282. START_TIME_TYPE now;
  2283. FUNC_ENTRY;
  2284. now = MQTTTime_now();
  2285. if (MQTTTime_difftime(now, last) >= (DIFF_TIME_TYPE)(retryLoopIntervalms))
  2286. {
  2287. last = MQTTTime_now();
  2288. MQTTProtocol_keepalive(now);
  2289. MQTTProtocol_retry(now, 1, 0);
  2290. }
  2291. else
  2292. MQTTProtocol_retry(now, 0, 0);
  2293. FUNC_EXIT;
  2294. }
  2295. static MQTTPacket* MQTTClient_cycle(SOCKET* sock, ELAPSED_TIME_TYPE timeout, int* rc)
  2296. {
  2297. static Ack ack;
  2298. MQTTPacket* pack = NULL;
  2299. int rc1 = 0;
  2300. START_TIME_TYPE start;
  2301. FUNC_ENTRY;
  2302. #if defined(OPENSSL)
  2303. if ((*sock = SSLSocket_getPendingRead()) == -1)
  2304. {
  2305. /* 0 from getReadySocket indicates no work to do, rc -1 == error */
  2306. #endif
  2307. start = MQTTTime_start_clock();
  2308. *sock = Socket_getReadySocket(0, (int)timeout, socket_mutex, rc);
  2309. *rc = rc1;
  2310. if (*sock == 0 && timeout >= 100L && MQTTTime_elapsed(start) < (int64_t)10)
  2311. MQTTTime_sleep(100L);
  2312. #if defined(OPENSSL)
  2313. }
  2314. #endif
  2315. Paho_thread_lock_mutex(mqttclient_mutex);
  2316. if (*sock > 0 && rc1 == 0)
  2317. {
  2318. MQTTClients* m = NULL;
  2319. if (ListFindItem(handles, sock, clientSockCompare) != NULL)
  2320. m = (MQTTClient)(handles->current->content);
  2321. if (m != NULL)
  2322. {
  2323. if (m->c->connect_state == TCP_IN_PROGRESS || m->c->connect_state == SSL_IN_PROGRESS)
  2324. *rc = 0; /* waiting for connect state to clear */
  2325. else if (m->c->connect_state == WEBSOCKET_IN_PROGRESS)
  2326. *rc = WebSocket_upgrade(&m->c->net);
  2327. else
  2328. {
  2329. pack = MQTTPacket_Factory(m->c->MQTTVersion, &m->c->net, rc);
  2330. if (*rc == TCPSOCKET_INTERRUPTED)
  2331. *rc = 0;
  2332. }
  2333. }
  2334. if (pack)
  2335. {
  2336. int freed = 1;
  2337. /* Note that these handle... functions free the packet structure that they are dealing with */
  2338. if (pack->header.bits.type == PUBLISH)
  2339. *rc = MQTTProtocol_handlePublishes(pack, *sock);
  2340. else if (pack->header.bits.type == PUBACK || pack->header.bits.type == PUBCOMP)
  2341. {
  2342. int msgid;
  2343. ack = (pack->header.bits.type == PUBCOMP) ? *(Pubcomp*)pack : *(Puback*)pack;
  2344. msgid = ack.msgId;
  2345. if (m && m->c->MQTTVersion >= MQTTVERSION_5 && m->published)
  2346. {
  2347. Log(TRACE_MIN, -1, "Calling published for client %s, msgid %d", m->c->clientID, msgid);
  2348. (*(m->published))(m->published_context, msgid, pack->header.bits.type, &ack.properties, ack.rc);
  2349. }
  2350. *rc = (pack->header.bits.type == PUBCOMP) ?
  2351. MQTTProtocol_handlePubcomps(pack, *sock, NULL) : MQTTProtocol_handlePubacks(pack, *sock, NULL);
  2352. if (m && m->dc)
  2353. {
  2354. Log(TRACE_MIN, -1, "Calling deliveryComplete for client %s, msgid %d", m->c->clientID, msgid);
  2355. (*(m->dc))(m->context, msgid);
  2356. }
  2357. }
  2358. else if (pack->header.bits.type == PUBREC)
  2359. {
  2360. Pubrec* pubrec = (Pubrec*)pack;
  2361. if (m && m->c->MQTTVersion >= MQTTVERSION_5 && m->published && pubrec->rc >= MQTTREASONCODE_UNSPECIFIED_ERROR)
  2362. {
  2363. Log(TRACE_MIN, -1, "Calling published for client %s, msgid %d", m->c->clientID, ack.msgId);
  2364. (*(m->published))(m->published_context, pubrec->msgId, pack->header.bits.type,
  2365. &pubrec->properties, pubrec->rc);
  2366. }
  2367. *rc = MQTTProtocol_handlePubrecs(pack, *sock, NULL);
  2368. }
  2369. else if (pack->header.bits.type == PUBREL)
  2370. *rc = MQTTProtocol_handlePubrels(pack, *sock);
  2371. else if (pack->header.bits.type == PINGRESP)
  2372. *rc = MQTTProtocol_handlePingresps(pack, *sock);
  2373. else
  2374. freed = 0;
  2375. if (freed)
  2376. pack = NULL;
  2377. }
  2378. }
  2379. MQTTClient_retry();
  2380. Paho_thread_unlock_mutex(mqttclient_mutex);
  2381. FUNC_EXIT_RC(*rc);
  2382. return pack;
  2383. }
  2384. static MQTTPacket* MQTTClient_waitfor(MQTTClient handle, int packet_type, int* rc, int64_t timeout)
  2385. {
  2386. MQTTPacket* pack = NULL;
  2387. MQTTClients* m = handle;
  2388. START_TIME_TYPE start = MQTTTime_start_clock();
  2389. int is_running = 0; /* local copy of running */
  2390. FUNC_ENTRY;
  2391. if (((MQTTClients*)handle) == NULL || timeout <= 0L)
  2392. {
  2393. *rc = MQTTCLIENT_FAILURE;
  2394. goto exit;
  2395. }
  2396. Paho_thread_lock_mutex(mqttclient_mutex);
  2397. is_running = running;
  2398. Paho_thread_unlock_mutex(mqttclient_mutex);
  2399. if (is_running)
  2400. {
  2401. if (packet_type == CONNECT)
  2402. {
  2403. if ((*rc = Thread_wait_sem(m->connect_sem, (int)timeout)) == 0)
  2404. *rc = m->rc;
  2405. }
  2406. else if (packet_type == CONNACK)
  2407. *rc = Thread_wait_sem(m->connack_sem, (int)timeout);
  2408. else if (packet_type == SUBACK)
  2409. *rc = Thread_wait_sem(m->suback_sem, (int)timeout);
  2410. else if (packet_type == UNSUBACK)
  2411. *rc = Thread_wait_sem(m->unsuback_sem, (int)timeout);
  2412. if (*rc == 0 && packet_type != CONNECT && m->pack == NULL)
  2413. Log(LOG_ERROR, -1, "waitfor unexpectedly is NULL for client %s, packet_type %d, timeout %ld", m->c->clientID, packet_type, timeout);
  2414. pack = m->pack;
  2415. }
  2416. else
  2417. {
  2418. *rc = TCPSOCKET_COMPLETE;
  2419. while (1)
  2420. {
  2421. SOCKET sock = -1;
  2422. pack = MQTTClient_cycle(&sock, 100L, rc);
  2423. if (sock == m->c->net.socket)
  2424. {
  2425. if (*rc == SOCKET_ERROR)
  2426. break;
  2427. if (pack && (pack->header.bits.type == packet_type))
  2428. break;
  2429. if (m->c->connect_state == TCP_IN_PROGRESS)
  2430. {
  2431. int error;
  2432. socklen_t len = sizeof(error);
  2433. if ((*rc = getsockopt(m->c->net.socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len)) == 0)
  2434. *rc = error;
  2435. break;
  2436. }
  2437. #if defined(OPENSSL)
  2438. else if (m->c->connect_state == SSL_IN_PROGRESS)
  2439. {
  2440. *rc = m->c->sslopts->struct_version >= 3 ?
  2441. SSLSocket_connect(m->c->net.ssl, sock, m->currentServerURI,
  2442. m->c->sslopts->verify, m->c->sslopts->ssl_error_cb, m->c->sslopts->ssl_error_context) :
  2443. SSLSocket_connect(m->c->net.ssl, sock, m->currentServerURI,
  2444. m->c->sslopts->verify, NULL, NULL);
  2445. if (*rc == SSL_FATAL)
  2446. break;
  2447. else if (*rc == 1) /* rc == 1 means SSL connect has finished and succeeded */
  2448. {
  2449. if ((m->c->cleansession == 0 && m->c->cleanstart == 0) && m->c->session == NULL)
  2450. m->c->session = SSL_get1_session(m->c->net.ssl);
  2451. break;
  2452. }
  2453. }
  2454. #endif
  2455. else if (m->c->connect_state == WEBSOCKET_IN_PROGRESS && *rc != TCPSOCKET_INTERRUPTED)
  2456. {
  2457. *rc = 1;
  2458. break;
  2459. }
  2460. else if (m->c->connect_state == PROXY_CONNECT_IN_PROGRESS )
  2461. {
  2462. *rc = 1;
  2463. break;
  2464. }
  2465. else if (m->c->connect_state == WAIT_FOR_CONNACK)
  2466. {
  2467. int error;
  2468. socklen_t len = sizeof(error);
  2469. if (getsockopt(m->c->net.socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len) == 0)
  2470. {
  2471. if (error)
  2472. {
  2473. *rc = error;
  2474. break;
  2475. }
  2476. }
  2477. }
  2478. }
  2479. if (MQTTTime_elapsed(start) > (uint64_t)timeout)
  2480. {
  2481. pack = NULL;
  2482. break;
  2483. }
  2484. }
  2485. }
  2486. exit:
  2487. FUNC_EXIT_RC(*rc);
  2488. return pack;
  2489. }
  2490. int MQTTClient_receive(MQTTClient handle, char** topicName, int* topicLen, MQTTClient_message** message,
  2491. unsigned long timeout)
  2492. {
  2493. int rc = TCPSOCKET_COMPLETE;
  2494. START_TIME_TYPE start = MQTTTime_start_clock();
  2495. ELAPSED_TIME_TYPE elapsed = 0L;
  2496. MQTTClients* m = handle;
  2497. FUNC_ENTRY;
  2498. if (m == NULL || m->c == NULL
  2499. || running) /* receive is not meant to be called in a multi-thread environment */
  2500. {
  2501. rc = MQTTCLIENT_FAILURE;
  2502. goto exit;
  2503. }
  2504. if (m->c->connected == 0)
  2505. {
  2506. rc = MQTTCLIENT_DISCONNECTED;
  2507. goto exit;
  2508. }
  2509. *topicName = NULL;
  2510. *message = NULL;
  2511. /* if there is already a message waiting, don't hang around but still do some packet handling */
  2512. if (m->c->messageQueue->count > 0)
  2513. timeout = 0L;
  2514. elapsed = MQTTTime_elapsed(start);
  2515. do
  2516. {
  2517. SOCKET sock = 0;
  2518. MQTTClient_cycle(&sock, (timeout > elapsed) ? timeout - elapsed : 0L, &rc);
  2519. if (rc == SOCKET_ERROR)
  2520. {
  2521. if (ListFindItem(handles, &sock, clientSockCompare) && /* find client corresponding to socket */
  2522. (MQTTClient)(handles->current->content) == handle)
  2523. break; /* there was an error on the socket we are interested in */
  2524. }
  2525. elapsed = MQTTTime_elapsed(start);
  2526. }
  2527. while (elapsed < timeout && m->c->messageQueue->count == 0);
  2528. if (m->c->messageQueue->count > 0)
  2529. rc = MQTTClient_deliverMessage(rc, m, topicName, topicLen, message);
  2530. if (rc == SOCKET_ERROR)
  2531. MQTTClient_disconnect_internal(handle, 0);
  2532. exit:
  2533. FUNC_EXIT_RC(rc);
  2534. return rc;
  2535. }
  2536. void MQTTClient_yield(void)
  2537. {
  2538. START_TIME_TYPE start = MQTTTime_start_clock();
  2539. ELAPSED_TIME_TYPE elapsed = 0L;
  2540. ELAPSED_TIME_TYPE timeout = 100L;
  2541. int rc = 0;
  2542. FUNC_ENTRY;
  2543. if (running) /* yield is not meant to be called in a multi-thread environment */
  2544. {
  2545. MQTTTime_sleep(timeout);
  2546. goto exit;
  2547. }
  2548. elapsed = MQTTTime_elapsed(start);
  2549. do
  2550. {
  2551. SOCKET sock = -1;
  2552. MQTTClient_cycle(&sock, (timeout > elapsed) ? timeout - elapsed : 0L, &rc);
  2553. Paho_thread_lock_mutex(mqttclient_mutex);
  2554. if (rc == SOCKET_ERROR && ListFindItem(handles, &sock, clientSockCompare))
  2555. {
  2556. MQTTClients* m = (MQTTClient)(handles->current->content);
  2557. if (m->c->connect_state != DISCONNECTING)
  2558. MQTTClient_disconnect_internal(m, 0);
  2559. }
  2560. Paho_thread_unlock_mutex(mqttclient_mutex);
  2561. elapsed = MQTTTime_elapsed(start);
  2562. }
  2563. while (elapsed < timeout);
  2564. exit:
  2565. FUNC_EXIT;
  2566. }
  2567. /*
  2568. static int pubCompare(void* a, void* b)
  2569. {
  2570. Messages* msg = (Messages*)a;
  2571. return msg->publish == (Publications*)b;
  2572. }*/
  2573. int MQTTClient_waitForCompletion(MQTTClient handle, MQTTClient_deliveryToken mdt, unsigned long timeout)
  2574. {
  2575. int rc = MQTTCLIENT_FAILURE;
  2576. START_TIME_TYPE start = MQTTTime_start_clock();
  2577. ELAPSED_TIME_TYPE elapsed = 0L;
  2578. MQTTClients* m = handle;
  2579. FUNC_ENTRY;
  2580. Paho_thread_lock_mutex(mqttclient_mutex);
  2581. elapsed = MQTTTime_elapsed(start);
  2582. while (elapsed < timeout)
  2583. {
  2584. if (m == NULL || m->c == NULL)
  2585. {
  2586. rc = MQTTCLIENT_FAILURE;
  2587. goto exit;
  2588. }
  2589. if (m->c->connected == 0)
  2590. {
  2591. rc = MQTTCLIENT_DISCONNECTED;
  2592. goto exit;
  2593. }
  2594. if (ListFindItem(m->c->outboundMsgs, &mdt, messageIDCompare) == NULL)
  2595. {
  2596. rc = MQTTCLIENT_SUCCESS; /* well we couldn't find it */
  2597. goto exit;
  2598. }
  2599. Paho_thread_unlock_mutex(mqttclient_mutex);
  2600. MQTTClient_yield();
  2601. Paho_thread_lock_mutex(mqttclient_mutex);
  2602. elapsed = MQTTTime_elapsed(start);
  2603. }
  2604. exit:
  2605. Paho_thread_unlock_mutex(mqttclient_mutex);
  2606. FUNC_EXIT_RC(rc);
  2607. return rc;
  2608. }
  2609. int MQTTClient_getPendingDeliveryTokens(MQTTClient handle, MQTTClient_deliveryToken **tokens)
  2610. {
  2611. int rc = MQTTCLIENT_SUCCESS;
  2612. MQTTClients* m = handle;
  2613. *tokens = NULL;
  2614. FUNC_ENTRY;
  2615. Paho_thread_lock_mutex(mqttclient_mutex);
  2616. if (m == NULL)
  2617. {
  2618. rc = MQTTCLIENT_FAILURE;
  2619. goto exit;
  2620. }
  2621. if (m->c && m->c->outboundMsgs->count > 0)
  2622. {
  2623. ListElement* current = NULL;
  2624. int count = 0;
  2625. *tokens = malloc(sizeof(MQTTClient_deliveryToken) * (m->c->outboundMsgs->count + 1));
  2626. if (!*tokens)
  2627. {
  2628. rc = PAHO_MEMORY_ERROR;
  2629. goto exit;
  2630. }
  2631. while (ListNextElement(m->c->outboundMsgs, &current))
  2632. {
  2633. Messages* m2 = (Messages*)(current->content);
  2634. (*tokens)[count++] = m2->msgid;
  2635. }
  2636. (*tokens)[count] = -1;
  2637. }
  2638. exit:
  2639. Paho_thread_unlock_mutex(mqttclient_mutex);
  2640. FUNC_EXIT_RC(rc);
  2641. return rc;
  2642. }
  2643. void MQTTClient_setTraceLevel(enum MQTTCLIENT_TRACE_LEVELS level)
  2644. {
  2645. Log_setTraceLevel((enum LOG_LEVELS)level);
  2646. }
  2647. void MQTTClient_setTraceCallback(MQTTClient_traceCallback* callback)
  2648. {
  2649. Log_setTraceCallback((Log_traceCallback*)callback);
  2650. }
  2651. int MQTTClient_setCommandTimeout(MQTTClient handle, unsigned long milliSeconds)
  2652. {
  2653. int rc = MQTTCLIENT_SUCCESS;
  2654. MQTTClients* m = handle;
  2655. FUNC_ENTRY;
  2656. if (milliSeconds < 5000L)
  2657. rc = MQTTCLIENT_FAILURE;
  2658. else
  2659. m->commandTimeout = milliSeconds;
  2660. FUNC_EXIT_RC(rc);
  2661. return rc;
  2662. }
  2663. MQTTClient_nameValue* MQTTClient_getVersionInfo(void)
  2664. {
  2665. #define MAX_INFO_STRINGS 8
  2666. static MQTTClient_nameValue libinfo[MAX_INFO_STRINGS + 1];
  2667. int i = 0;
  2668. libinfo[i].name = "Product name";
  2669. libinfo[i++].value = "Eclipse Paho Synchronous MQTT C Client Library";
  2670. libinfo[i].name = "Version";
  2671. libinfo[i++].value = CLIENT_VERSION;
  2672. libinfo[i].name = "Build level";
  2673. libinfo[i++].value = BUILD_TIMESTAMP;
  2674. #if defined(OPENSSL)
  2675. libinfo[i].name = "OpenSSL version";
  2676. libinfo[i++].value = SSLeay_version(SSLEAY_VERSION);
  2677. libinfo[i].name = "OpenSSL flags";
  2678. libinfo[i++].value = SSLeay_version(SSLEAY_CFLAGS);
  2679. libinfo[i].name = "OpenSSL build timestamp";
  2680. libinfo[i++].value = SSLeay_version(SSLEAY_BUILT_ON);
  2681. libinfo[i].name = "OpenSSL platform";
  2682. libinfo[i++].value = SSLeay_version(SSLEAY_PLATFORM);
  2683. libinfo[i].name = "OpenSSL directory";
  2684. libinfo[i++].value = SSLeay_version(SSLEAY_DIR);
  2685. #endif
  2686. libinfo[i].name = NULL;
  2687. libinfo[i].value = NULL;
  2688. return libinfo;
  2689. }
  2690. const char* MQTTClient_strerror(int code)
  2691. {
  2692. static char buf[30];
  2693. int chars = 0;
  2694. switch (code) {
  2695. case MQTTCLIENT_SUCCESS:
  2696. return "Success";
  2697. case MQTTCLIENT_FAILURE:
  2698. return "Failure";
  2699. case MQTTCLIENT_DISCONNECTED:
  2700. return "Disconnected";
  2701. case MQTTCLIENT_MAX_MESSAGES_INFLIGHT:
  2702. return "Maximum in-flight messages amount reached";
  2703. case MQTTCLIENT_BAD_UTF8_STRING:
  2704. return "Invalid UTF8 string";
  2705. case MQTTCLIENT_NULL_PARAMETER:
  2706. return "Invalid (NULL) parameter";
  2707. case MQTTCLIENT_TOPICNAME_TRUNCATED:
  2708. return "Topic containing NULL characters has been truncated";
  2709. case MQTTCLIENT_BAD_STRUCTURE:
  2710. return "Bad structure";
  2711. case MQTTCLIENT_BAD_QOS:
  2712. return "Invalid QoS value";
  2713. case MQTTCLIENT_SSL_NOT_SUPPORTED:
  2714. return "SSL is not supported";
  2715. case MQTTCLIENT_BAD_MQTT_VERSION:
  2716. return "Unrecognized MQTT version";
  2717. case MQTTCLIENT_BAD_PROTOCOL:
  2718. return "Invalid protocol scheme";
  2719. case MQTTCLIENT_BAD_MQTT_OPTION:
  2720. return "Options for wrong MQTT version";
  2721. case MQTTCLIENT_WRONG_MQTT_VERSION:
  2722. return "Client created for another version of MQTT";
  2723. case MQTTCLIENT_0_LEN_WILL_TOPIC:
  2724. return "Zero length will topic on connect";
  2725. }
  2726. chars = snprintf(buf, sizeof(buf), "Unknown error code %d", code);
  2727. if (chars >= sizeof(buf))
  2728. {
  2729. buf[sizeof(buf)-1] = '\0';
  2730. Log(LOG_ERROR, 0, "Error writing %d chars with snprintf", chars);
  2731. }
  2732. return buf;
  2733. }
  2734. /**
  2735. * See if any pending writes have been completed, and cleanup if so.
  2736. * Cleaning up means removing any publication data that was stored because the write did
  2737. * not originally complete.
  2738. */
  2739. static void MQTTProtocol_checkPendingWrites(void)
  2740. {
  2741. FUNC_ENTRY;
  2742. if (state.pending_writes.count > 0)
  2743. {
  2744. ListElement* le = state.pending_writes.first;
  2745. while (le)
  2746. {
  2747. if (Socket_noPendingWrites(((pending_write*)(le->content))->socket))
  2748. {
  2749. MQTTProtocol_removePublication(((pending_write*)(le->content))->p);
  2750. state.pending_writes.current = le;
  2751. ListRemove(&(state.pending_writes), le->content); /* does NextElement itself */
  2752. le = state.pending_writes.current;
  2753. }
  2754. else
  2755. ListNextElement(&(state.pending_writes), &le);
  2756. }
  2757. }
  2758. FUNC_EXIT;
  2759. }
  2760. static void MQTTClient_writeComplete(SOCKET socket, int rc)
  2761. {
  2762. ListElement* found = NULL;
  2763. FUNC_ENTRY;
  2764. /* a partial write is now complete for a socket - this will be on a publish*/
  2765. MQTTProtocol_checkPendingWrites();
  2766. /* find the client using this socket */
  2767. if ((found = ListFindItem(handles, &socket, clientSockCompare)) != NULL)
  2768. {
  2769. MQTTClients* m = (MQTTClients*)(found->content);
  2770. m->c->net.lastSent = MQTTTime_now();
  2771. }
  2772. FUNC_EXIT;
  2773. }
  2774. static void MQTTClient_writeContinue(SOCKET socket)
  2775. {
  2776. ListElement* found = NULL;
  2777. if ((found = ListFindItem(handles, &socket, clientSockCompare)) != NULL)
  2778. {
  2779. MQTTClients* m = (MQTTClients*)(found->content);
  2780. m->c->net.lastSent = MQTTTime_now();
  2781. }
  2782. }