forked from eclipse-paho/paho.mqtt.c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMQTTClient.c
3025 lines (2664 loc) · 79.3 KB
/
MQTTClient.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2009, 2021 IBM Corp., Ian Craggs and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial API and implementation and/or initial documentation
* Ian Craggs - bug 384016 - segv setting will message
* Ian Craggs - bug 384053 - v1.0.0.7 - stop MQTTClient_receive on socket error
* Ian Craggs, Allan Stockdill-Mander - add ability to connect with SSL
* Ian Craggs - multiple server connection support
* Ian Craggs - fix for bug 413429 - connectionLost not called
* Ian Craggs - fix for bug 421103 - trying to write to same socket, in publish/retries
* Ian Craggs - fix for bug 419233 - mutexes not reporting errors
* Ian Craggs - fix for bug 420851
* Ian Craggs - fix for bug 432903 - queue persistence
* Ian Craggs - MQTT 3.1.1 support
* Ian Craggs - fix for bug 438176 - MQTT version selection
* Rong Xiang, Ian Craggs - C++ compatibility
* Ian Craggs - fix for bug 443724 - stack corruption
* Ian Craggs - fix for bug 447672 - simultaneous access to socket structure
* Ian Craggs - fix for bug 459791 - deadlock in WaitForCompletion for bad client
* Ian Craggs - fix for bug 474905 - insufficient synchronization for subscribe, unsubscribe, connect
* Ian Craggs - make it clear that yield and receive are not intended for multi-threaded mode (bug 474748)
* Ian Craggs - SNI support, message queue unpersist bug
* Ian Craggs - binary will message support
* Ian Craggs - waitforCompletion fix #240
* Ian Craggs - check for NULL SSL options #334
* Ian Craggs - allocate username/password buffers #431
* Ian Craggs - MQTT 5.0 support
*******************************************************************************/
/**
* @file
* \brief Synchronous API implementation
*
*/
#include <stdlib.h>
#include <string.h>
#if !defined(_WIN32) && !defined(_WIN64)
#include <sys/time.h>
#else
#if defined(_MSC_VER) && _MSC_VER < 1900
#define snprintf _snprintf
#endif
#endif
#include "MQTTClient.h"
#if !defined(NO_PERSISTENCE)
#include "MQTTPersistence.h"
#endif
#include "utf-8.h"
#include "MQTTProtocol.h"
#include "MQTTProtocolOut.h"
#include "Thread.h"
#include "SocketBuffer.h"
#include "StackTrace.h"
#include "Heap.h"
#if defined(OPENSSL)
#include <openssl/ssl.h>
#else
#define URI_SSL "ssl://"
#endif
#include "OsWrapper.h"
#define URI_TCP "tcp://"
#define URI_WS "ws://"
#define URI_WSS "wss://"
#include "VersionInfo.h"
#include "WebSocket.h"
const char *client_timestamp_eye = "MQTTClientV3_Timestamp " BUILD_TIMESTAMP;
const char *client_version_eye = "MQTTClientV3_Version " CLIENT_VERSION;
int MQTTClient_init(void);
void MQTTClient_global_init(MQTTClient_init_options* inits)
{
MQTTClient_init();
#if defined(OPENSSL)
SSLSocket_handleOpensslInit(inits->do_openssl_init);
#endif
}
static ClientStates ClientState =
{
CLIENT_VERSION, /* version */
NULL /* client list */
};
ClientStates* bstate = &ClientState;
MQTTProtocol state;
#if defined(_WIN32) || defined(_WIN64)
static mutex_type mqttclient_mutex = NULL;
static mutex_type socket_mutex = NULL;
static mutex_type subscribe_mutex = NULL;
static mutex_type unsubscribe_mutex = NULL;
static mutex_type connect_mutex = NULL;
#if !defined(NO_HEAP_TRACKING)
extern mutex_type stack_mutex;
extern mutex_type heap_mutex;
#endif
extern mutex_type log_mutex;
int MQTTClient_init(void)
{
DWORD rc = 0;
if (mqttclient_mutex == NULL)
{
if ((mqttclient_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
{
rc = GetLastError();
printf("mqttclient_mutex error %d\n", rc);
goto exit;
}
if ((subscribe_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
{
rc = GetLastError();
printf("subscribe_mutex error %d\n", rc);
goto exit;
}
if ((unsubscribe_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
{
rc = GetLastError();
printf("unsubscribe_mutex error %d\n", rc);
goto exit;
}
if ((connect_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
{
rc = GetLastError();
printf("connect_mutex error %d\n", rc);
goto exit;
}
#if !defined(NO_HEAP_TRACKING)
if ((stack_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
{
rc = GetLastError();
printf("stack_mutex error %d\n", rc);
goto exit;
}
if ((heap_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
{
rc = GetLastError();
printf("heap_mutex error %d\n", rc);
goto exit;
}
#endif
if ((log_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
{
rc = GetLastError();
printf("log_mutex error %d\n", rc);
goto exit;
}
if ((socket_mutex = CreateMutex(NULL, 0, NULL)) == NULL)
{
rc = GetLastError();
printf("socket_mutex error %d\n", rc);
goto exit;
}
}
exit:
return rc;
}
void MQTTClient_cleanup(void)
{
if (connect_mutex)
CloseHandle(connect_mutex);
if (subscribe_mutex)
CloseHandle(subscribe_mutex);
if (unsubscribe_mutex)
CloseHandle(unsubscribe_mutex);
#if !defined(NO_HEAP_TRACKING)
if (stack_mutex)
CloseHandle(stack_mutex);
if (heap_mutex)
CloseHandle(heap_mutex);
#endif
if (log_mutex)
CloseHandle(log_mutex);
if (socket_mutex)
CloseHandle(socket_mutex);
if (mqttclient_mutex)
CloseHandle(mqttclient_mutex);
}
#if defined(PAHO_MQTT_STATIC)
/* Global variable for one-time initialization structure */
static INIT_ONCE g_InitOnce = INIT_ONCE_STATIC_INIT; /* Static initialization */
/* One time initialization function */
BOOL CALLBACK InitOnceFunction (
PINIT_ONCE InitOnce, /* Pointer to one-time initialization structure */
PVOID Parameter, /* Optional parameter passed by InitOnceExecuteOnce */
PVOID *lpContext) /* Receives pointer to event object */
{
int rc = MQTTClient_init();
return rc == 0;
}
#else
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MQTTClient_init();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
if (lpReserved)
MQTTClient_cleanup();
break;
}
return TRUE;
}
#endif
#else
static pthread_mutex_t mqttclient_mutex_store = PTHREAD_MUTEX_INITIALIZER;
static mutex_type mqttclient_mutex = &mqttclient_mutex_store;
static pthread_mutex_t socket_mutex_store = PTHREAD_MUTEX_INITIALIZER;
static mutex_type socket_mutex = &socket_mutex_store;
static pthread_mutex_t subscribe_mutex_store = PTHREAD_MUTEX_INITIALIZER;
static mutex_type subscribe_mutex = &subscribe_mutex_store;
static pthread_mutex_t unsubscribe_mutex_store = PTHREAD_MUTEX_INITIALIZER;
static mutex_type unsubscribe_mutex = &unsubscribe_mutex_store;
static pthread_mutex_t connect_mutex_store = PTHREAD_MUTEX_INITIALIZER;
static mutex_type connect_mutex = &connect_mutex_store;
int MQTTClient_init(void)
{
pthread_mutexattr_t attr;
int rc;
pthread_mutexattr_init(&attr);
#if !defined(_WRS_KERNEL)
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
#else
/* #warning "no pthread_mutexattr_settype" */
#endif /* !defined(_WRS_KERNEL) */
if ((rc = pthread_mutex_init(mqttclient_mutex, &attr)) != 0)
printf("MQTTClient: error %d initializing client_mutex\n", rc);
else if ((rc = pthread_mutex_init(socket_mutex, &attr)) != 0)
printf("MQTTClient: error %d initializing socket_mutex\n", rc);
else if ((rc = pthread_mutex_init(subscribe_mutex, &attr)) != 0)
printf("MQTTClient: error %d initializing subscribe_mutex\n", rc);
else if ((rc = pthread_mutex_init(unsubscribe_mutex, &attr)) != 0)
printf("MQTTClient: error %d initializing unsubscribe_mutex\n", rc);
else if ((rc = pthread_mutex_init(connect_mutex, &attr)) != 0)
printf("MQTTClient: error %d initializing connect_mutex\n", rc);
return rc;
}
#define WINAPI
#endif
static volatile int library_initialized = 0;
static List* handles = NULL;
static int running = 0;
static int tostop = 0;
static thread_id_type run_id = 0;
typedef struct
{
MQTTClient_message* msg;
char* topicName;
int topicLen;
unsigned int seqno; /* only used on restore */
} qEntry;
typedef struct
{
char* serverURI;
const char* currentServerURI; /* when using HA options, set the currently used serverURI */
#if defined(OPENSSL)
int ssl;
#endif
int websocket;
Clients* c;
MQTTClient_connectionLost* cl;
MQTTClient_messageArrived* ma;
MQTTClient_deliveryComplete* dc;
void* context;
MQTTClient_disconnected* disconnected;
void* disconnected_context; /* the context to be associated with the disconnected callback*/
MQTTClient_published* published;
void* published_context; /* the context to be associated with the disconnected callback*/
#if 0
MQTTClient_authHandle* auth_handle;
void* auth_handle_context; /* the context to be associated with the authHandle callback*/
#endif
sem_type connect_sem;
int rc; /* getsockopt return code in connect */
sem_type connack_sem;
sem_type suback_sem;
sem_type unsuback_sem;
MQTTPacket* pack;
unsigned long commandTimeout;
} MQTTClients;
struct props_rc_parms
{
MQTTClients* m;
MQTTProperties* properties;
enum MQTTReasonCodes reasonCode;
};
static void MQTTClient_terminate(void);
static void MQTTClient_emptyMessageQueue(Clients* client);
static int MQTTClient_deliverMessage(
int rc, MQTTClients* m,
char** topicName, int* topicLen,
MQTTClient_message** message);
static int clientSockCompare(void* a, void* b);
static thread_return_type WINAPI connectionLost_call(void* context);
static thread_return_type WINAPI MQTTClient_run(void* n);
static int MQTTClient_stop(void);
static void MQTTClient_closeSession(Clients* client, enum MQTTReasonCodes reason, MQTTProperties* props);
static int MQTTClient_cleanSession(Clients* client);
static MQTTResponse MQTTClient_connectURIVersion(
MQTTClient handle, MQTTClient_connectOptions* options,
const char* serverURI, int MQTTVersion,
START_TIME_TYPE start, ELAPSED_TIME_TYPE millisecsTimeout,
MQTTProperties* connectProperties, MQTTProperties* willProperties);
static MQTTResponse MQTTClient_connectURI(MQTTClient handle, MQTTClient_connectOptions* options, const char* serverURI,
MQTTProperties* connectProperties, MQTTProperties* willProperties);
static int MQTTClient_disconnect1(MQTTClient handle, int timeout, int internal, int stop, enum MQTTReasonCodes, MQTTProperties*);
static int MQTTClient_disconnect_internal(MQTTClient handle, int timeout);
static void MQTTClient_retry(void);
static MQTTPacket* MQTTClient_cycle(int* sock, ELAPSED_TIME_TYPE timeout, int* rc);
static MQTTPacket* MQTTClient_waitfor(MQTTClient handle, int packet_type, int* rc, ELAPSED_TIME_TYPE timeout);
/*static int pubCompare(void* a, void* b); */
static void MQTTProtocol_checkPendingWrites(void);
static void MQTTClient_writeComplete(int socket, int rc);
int MQTTClient_createWithOptions(MQTTClient* handle, const char* serverURI, const char* clientId,
int persistence_type, void* persistence_context, MQTTClient_createOptions* options)
{
int rc = 0;
MQTTClients *m = NULL;
#if (defined(_WIN32) || defined(_WIN64)) && defined(PAHO_MQTT_STATIC)
/* intializes mutexes once. Must come before FUNC_ENTRY */
BOOL bStatus = InitOnceExecuteOnce(&g_InitOnce, InitOnceFunction, NULL, NULL);
#endif
FUNC_ENTRY;
if ((rc = Thread_lock_mutex(mqttclient_mutex)) != 0)
goto exit;
if (serverURI == NULL || clientId == NULL)
{
rc = MQTTCLIENT_NULL_PARAMETER;
goto exit;
}
if (!UTF8_validateString(clientId))
{
rc = MQTTCLIENT_BAD_UTF8_STRING;
goto exit;
}
if (strlen(clientId) == 0 && persistence_type == MQTTCLIENT_PERSISTENCE_DEFAULT)
{
rc = MQTTCLIENT_PERSISTENCE_ERROR;
goto exit;
}
if (strstr(serverURI, "://") != NULL)
{
if (strncmp(URI_TCP, serverURI, strlen(URI_TCP)) != 0
&& strncmp(URI_WS, serverURI, strlen(URI_WS)) != 0
#if defined(OPENSSL)
&& strncmp(URI_SSL, serverURI, strlen(URI_SSL)) != 0
&& strncmp(URI_WSS, serverURI, strlen(URI_WSS)) != 0
#endif
)
{
rc = MQTTCLIENT_BAD_PROTOCOL;
goto exit;
}
}
if (options && (strncmp(options->struct_id, "MQCO", 4) != 0 || options->struct_version != 0))
{
rc = MQTTCLIENT_BAD_STRUCTURE;
goto exit;
}
if (!library_initialized)
{
#if !defined(NO_HEAP_TRACKING)
Heap_initialize();
#endif
Log_initialize((Log_nameValue*)MQTTClient_getVersionInfo());
bstate->clients = ListInitialize();
Socket_outInitialize();
Socket_setWriteCompleteCallback(MQTTClient_writeComplete);
handles = ListInitialize();
#if defined(OPENSSL)
SSLSocket_initialize();
#endif
library_initialized = 1;
}
if ((m = malloc(sizeof(MQTTClients))) == NULL)
{
rc = PAHO_MEMORY_ERROR;
goto exit;
}
*handle = m;
memset(m, '\0', sizeof(MQTTClients));
m->commandTimeout = 10000L;
if (strncmp(URI_TCP, serverURI, strlen(URI_TCP)) == 0)
serverURI += strlen(URI_TCP);
else if (strncmp(URI_WS, serverURI, strlen(URI_WS)) == 0)
{
serverURI += strlen(URI_WS);
m->websocket = 1;
}
else if (strncmp(URI_SSL, serverURI, strlen(URI_SSL)) == 0)
{
#if defined(OPENSSL)
serverURI += strlen(URI_SSL);
m->ssl = 1;
#else
rc = MQTTCLIENT_SSL_NOT_SUPPORTED;
goto exit;
#endif
}
else if (strncmp(URI_WSS, serverURI, strlen(URI_WSS)) == 0)
{
#if defined(OPENSSL)
serverURI += strlen(URI_WSS);
m->ssl = 1;
m->websocket = 1;
#else
rc = MQTTCLIENT_SSL_NOT_SUPPORTED;
goto exit;
#endif
}
m->serverURI = MQTTStrdup(serverURI);
ListAppend(handles, m, sizeof(MQTTClients));
if ((m->c = malloc(sizeof(Clients))) == NULL)
{
ListRemove(handles, m);
rc = PAHO_MEMORY_ERROR;
goto exit;
}
memset(m->c, '\0', sizeof(Clients));
m->c->context = m;
m->c->MQTTVersion = (options) ? options->MQTTVersion : MQTTVERSION_DEFAULT;
m->c->outboundMsgs = ListInitialize();
m->c->inboundMsgs = ListInitialize();
m->c->messageQueue = ListInitialize();
m->c->clientID = MQTTStrdup(clientId);
m->connect_sem = Thread_create_sem(&rc);
m->connack_sem = Thread_create_sem(&rc);
m->suback_sem = Thread_create_sem(&rc);
m->unsuback_sem = Thread_create_sem(&rc);
#if !defined(NO_PERSISTENCE)
rc = MQTTPersistence_create(&(m->c->persistence), persistence_type, persistence_context);
if (rc == 0)
{
rc = MQTTPersistence_initialize(m->c, m->serverURI);
if (rc == 0)
MQTTPersistence_restoreMessageQueue(m->c);
}
#endif
ListAppend(bstate->clients, m->c, sizeof(Clients) + 3*sizeof(List));
exit:
Thread_unlock_mutex(mqttclient_mutex);
FUNC_EXIT_RC(rc);
return rc;
}
int MQTTClient_create(MQTTClient* handle, const char* serverURI, const char* clientId,
int persistence_type, void* persistence_context)
{
return MQTTClient_createWithOptions(handle, serverURI, clientId, persistence_type,
persistence_context, NULL);
}
static void MQTTClient_terminate(void)
{
FUNC_ENTRY;
MQTTClient_stop();
if (library_initialized)
{
ListFree(bstate->clients);
ListFree(handles);
handles = NULL;
WebSocket_terminate();
#if !defined(NO_HEAP_TRACKING)
Heap_terminate();
#endif
Log_terminate();
library_initialized = 0;
}
FUNC_EXIT;
}
static void MQTTClient_emptyMessageQueue(Clients* client)
{
FUNC_ENTRY;
/* empty message queue */
if (client->messageQueue->count > 0)
{
ListElement* current = NULL;
while (ListNextElement(client->messageQueue, ¤t))
{
qEntry* qe = (qEntry*)(current->content);
free(qe->topicName);
MQTTProperties_free(&qe->msg->properties);
free(qe->msg->payload);
free(qe->msg);
}
ListEmpty(client->messageQueue);
}
FUNC_EXIT;
}
void MQTTClient_destroy(MQTTClient* handle)
{
MQTTClients* m = *handle;
FUNC_ENTRY;
Thread_lock_mutex(connect_mutex);
Thread_lock_mutex(mqttclient_mutex);
if (m == NULL)
goto exit;
if (m->c)
{
int saved_socket = m->c->net.socket;
char* saved_clientid = MQTTStrdup(m->c->clientID);
#if !defined(NO_PERSISTENCE)
MQTTPersistence_close(m->c);
#endif
MQTTClient_emptyMessageQueue(m->c);
MQTTProtocol_freeClient(m->c);
if (!ListRemove(bstate->clients, m->c))
Log(LOG_ERROR, 0, NULL);
else
Log(TRACE_MIN, 1, NULL, saved_clientid, saved_socket);
free(saved_clientid);
}
if (m->serverURI)
free(m->serverURI);
Thread_destroy_sem(m->connect_sem);
Thread_destroy_sem(m->connack_sem);
Thread_destroy_sem(m->suback_sem);
Thread_destroy_sem(m->unsuback_sem);
if (!ListRemove(handles, m))
Log(LOG_ERROR, -1, "free error");
*handle = NULL;
if (bstate->clients->count == 0)
MQTTClient_terminate();
exit:
Thread_unlock_mutex(mqttclient_mutex);
Thread_unlock_mutex(connect_mutex);
FUNC_EXIT;
}
void MQTTClient_freeMessage(MQTTClient_message** message)
{
FUNC_ENTRY;
MQTTProperties_free(&(*message)->properties);
free((*message)->payload);
free(*message);
*message = NULL;
FUNC_EXIT;
}
void MQTTClient_free(void* memory)
{
FUNC_ENTRY;
free(memory);
FUNC_EXIT;
}
void MQTTResponse_free(MQTTResponse response)
{
FUNC_ENTRY;
if (response.reasonCodeCount > 0 && response.reasonCodes)
free(response.reasonCodes);
if (response.properties)
{
MQTTProperties_free(response.properties);
free(response.properties);
}
FUNC_EXIT;
}
static int MQTTClient_deliverMessage(int rc, MQTTClients* m, char** topicName, int* topicLen, MQTTClient_message** message)
{
qEntry* qe = (qEntry*)(m->c->messageQueue->first->content);
FUNC_ENTRY;
*message = qe->msg;
*topicName = qe->topicName;
*topicLen = qe->topicLen;
if (strlen(*topicName) != *topicLen)
rc = MQTTCLIENT_TOPICNAME_TRUNCATED;
#if !defined(NO_PERSISTENCE)
if (m->c->persistence)
MQTTPersistence_unpersistQueueEntry(m->c, (MQTTPersistence_qEntry*)qe);
#endif
ListRemove(m->c->messageQueue, m->c->messageQueue->first->content);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* List callback function for comparing clients by socket
* @param a first integer value
* @param b second integer value
* @return boolean indicating whether a and b are equal
*/
static int clientSockCompare(void* a, void* b)
{
MQTTClients* m = (MQTTClients*)a;
return m->c->net.socket == *(int*)b;
}
/**
* Wrapper function to call connection lost on a separate thread. A separate thread is needed to allow the
* connectionLost function to make API calls (e.g. connect)
* @param context a pointer to the relevant client
* @return thread_return_type standard thread return value - not used here
*/
static thread_return_type WINAPI connectionLost_call(void* context)
{
MQTTClients* m = (MQTTClients*)context;
(*(m->cl))(m->context, NULL);
return 0;
}
int MQTTClient_setDisconnected(MQTTClient handle, void* context, MQTTClient_disconnected* disconnected)
{
int rc = MQTTCLIENT_SUCCESS;
MQTTClients* m = handle;
FUNC_ENTRY;
Thread_lock_mutex(mqttclient_mutex);
if (m == NULL || m->c->connect_state != NOT_IN_PROGRESS)
rc = MQTTCLIENT_FAILURE;
else
{
m->disconnected_context = context;
m->disconnected = disconnected;
}
Thread_unlock_mutex(mqttclient_mutex);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* Wrapper function to call disconnected on a separate thread. A separate thread is needed to allow the
* disconnected function to make API calls (e.g. connect)
* @param context a pointer to the relevant client
* @return thread_return_type standard thread return value - not used here
*/
static thread_return_type WINAPI call_disconnected(void* context)
{
struct props_rc_parms* pr = (struct props_rc_parms*)context;
(*(pr->m->disconnected))(pr->m->disconnected_context, pr->properties, pr->reasonCode);
MQTTProperties_free(pr->properties);
free(pr->properties);
free(pr);
return 0;
}
int MQTTClient_setPublished(MQTTClient handle, void* context, MQTTClient_published* published)
{
int rc = MQTTCLIENT_SUCCESS;
MQTTClients* m = handle;
FUNC_ENTRY;
Thread_lock_mutex(mqttclient_mutex);
if (m == NULL || m->c->connect_state != NOT_IN_PROGRESS)
rc = MQTTCLIENT_FAILURE;
else
{
m->published_context = context;
m->published = published;
}
Thread_unlock_mutex(mqttclient_mutex);
FUNC_EXIT_RC(rc);
return rc;
}
#if 0
int MQTTClient_setHandleAuth(MQTTClient handle, void* context, MQTTClient_handleAuth* auth_handle)
{
int rc = MQTTCLIENT_SUCCESS;
MQTTClients* m = handle;
FUNC_ENTRY;
Thread_lock_mutex(mqttclient_mutex);
if (m == NULL || m->c->connect_state != NOT_IN_PROGRESS)
rc = MQTTCLIENT_FAILURE;
else
{
m->auth_handle_context = context;
m->auth_handle = auth_handle;
}
Thread_unlock_mutex(mqttclient_mutex);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* Wrapper function to call authHandle on a separate thread. A separate thread is needed to allow the
* disconnected function to make API calls (e.g. MQTTClient_auth)
* @param context a pointer to the relevant client
* @return thread_return_type standard thread return value - not used here
*/
static thread_return_type WINAPI call_auth_handle(void* context)
{
struct props_rc_parms* pr = (struct props_rc_parms*)context;
(*(pr->m->auth_handle))(pr->m->auth_handle_context, pr->properties, pr->reasonCode);
MQTTProperties_free(pr->properties);
free(pr->properties);
free(pr);
return 0;
}
#endif
/* This is the thread function that handles the calling of callback functions if set */
static thread_return_type WINAPI MQTTClient_run(void* n)
{
long timeout = 10L; /* first time in we have a small timeout. Gets things started more quickly */
FUNC_ENTRY;
running = 1;
run_id = Thread_getid();
Thread_lock_mutex(mqttclient_mutex);
while (!tostop)
{
int rc = SOCKET_ERROR;
int sock = -1;
MQTTClients* m = NULL;
MQTTPacket* pack = NULL;
Thread_unlock_mutex(mqttclient_mutex);
pack = MQTTClient_cycle(&sock, timeout, &rc);
Thread_lock_mutex(mqttclient_mutex);
if (tostop)
break;
timeout = 100L;
/* find client corresponding to socket */
if (ListFindItem(handles, &sock, clientSockCompare) == NULL)
{
/* assert: should not happen */
continue;
}
m = (MQTTClient)(handles->current->content);
if (m == NULL)
{
/* assert: should not happen */
continue;
}
if (rc == SOCKET_ERROR)
{
if (m->c->connected)
MQTTClient_disconnect_internal(m, 0);
else
{
if (m->c->connect_state == SSL_IN_PROGRESS)
{
Log(TRACE_MIN, -1, "Posting connect semaphore for client %s", m->c->clientID);
m->c->connect_state = NOT_IN_PROGRESS;
Thread_post_sem(m->connect_sem);
}
if (m->c->connect_state == WAIT_FOR_CONNACK)
{
Log(TRACE_MIN, -1, "Posting connack semaphore for client %s", m->c->clientID);
m->c->connect_state = NOT_IN_PROGRESS;
Thread_post_sem(m->connack_sem);
}
}
}
else
{
if (m->c->messageQueue->count > 0 && m->ma)
{
qEntry* qe = (qEntry*)(m->c->messageQueue->first->content);
int topicLen = qe->topicLen;
if (strlen(qe->topicName) == topicLen)
topicLen = 0;
Log(TRACE_MIN, -1, "Calling messageArrived for client %s, queue depth %d",
m->c->clientID, m->c->messageQueue->count);
Thread_unlock_mutex(mqttclient_mutex);
rc = (*(m->ma))(m->context, qe->topicName, topicLen, qe->msg);
Thread_lock_mutex(mqttclient_mutex);
/* if 0 (false) is returned by the callback then it failed, so we don't remove the message from
* the queue, and it will be retried later. If 1 is returned then the message data may have been freed,
* so we must be careful how we use it.
*/
if (rc)
{
#if !defined(NO_PERSISTENCE)
if (m->c->persistence)
MQTTPersistence_unpersistQueueEntry(m->c, (MQTTPersistence_qEntry*)qe);
#endif
ListRemove(m->c->messageQueue, qe);
}
else
Log(TRACE_MIN, -1, "False returned from messageArrived for client %s, message remains on queue",
m->c->clientID);
}
if (pack)
{
if (pack->header.bits.type == CONNACK)
{
Log(TRACE_MIN, -1, "Posting connack semaphore for client %s", m->c->clientID);
m->pack = pack;
Thread_post_sem(m->connack_sem);
}
else if (pack->header.bits.type == SUBACK)
{
Log(TRACE_MIN, -1, "Posting suback semaphore for client %s", m->c->clientID);
m->pack = pack;
Thread_post_sem(m->suback_sem);
}
else if (pack->header.bits.type == UNSUBACK)
{
Log(TRACE_MIN, -1, "Posting unsuback semaphore for client %s", m->c->clientID);
m->pack = pack;
Thread_post_sem(m->unsuback_sem);
}
else if (m->c->MQTTVersion >= MQTTVERSION_5)
{
if (pack->header.bits.type == DISCONNECT && m->disconnected)
{
struct props_rc_parms* dp;
Ack* disc = (Ack*)pack;
dp = malloc(sizeof(struct props_rc_parms));
if (dp)
{
dp->m = m;
dp->reasonCode = disc->rc;
dp->properties = malloc(sizeof(MQTTProperties));
if (dp->properties)
{
*(dp->properties) = disc->properties;
MQTTClient_disconnect1(m, 10, 0, 1, MQTTREASONCODE_SUCCESS, NULL);
Log(TRACE_MIN, -1, "Calling disconnected for client %s", m->c->clientID);
Thread_start(call_disconnected, dp);
}
else
free(dp);
}
free(disc);
}
#if 0
if (pack->header.bits.type == AUTH && m->auth_handle)
{
struct props_rc_parms dp;
Ack* disc = (Ack*)pack;
dp.m = m;
dp.properties = &disc->properties;
dp.reasonCode = disc->rc;
free(pack);
Log(TRACE_MIN, -1, "Calling auth_handle for client %s", m->c->clientID);
Thread_start(call_auth_handle, &dp);
}
#endif
}
}
else if (m->c->connect_state == TCP_IN_PROGRESS)
{
int error;
socklen_t len = sizeof(error);
if ((m->rc = getsockopt(m->c->net.socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len)) == 0)
m->rc = error;
Log(TRACE_MIN, -1, "Posting connect semaphore for client %s rc %d", m->c->clientID, m->rc);
m->c->connect_state = NOT_IN_PROGRESS;
Thread_post_sem(m->connect_sem);
}
#if defined(OPENSSL)
else if (m->c->connect_state == SSL_IN_PROGRESS)
{
rc = m->c->sslopts->struct_version >= 3 ?
SSLSocket_connect(m->c->net.ssl, m->c->net.socket, m->serverURI,
m->c->sslopts->verify, m->c->sslopts->ssl_error_cb, m->c->sslopts->ssl_error_context) :
SSLSocket_connect(m->c->net.ssl, m->c->net.socket, m->serverURI,
m->c->sslopts->verify, NULL, NULL);
if (rc == 1 || rc == SSL_FATAL)
{
if (rc == 1 && (m->c->cleansession == 0 && m->c->cleanstart == 0) && m->c->session == NULL)
m->c->session = SSL_get1_session(m->c->net.ssl);
m->rc = rc;
Log(TRACE_MIN, -1, "Posting connect semaphore for SSL client %s rc %d", m->c->clientID, m->rc);
m->c->connect_state = NOT_IN_PROGRESS;
Thread_post_sem(m->connect_sem);
}
}
#endif
else if (m->c->connect_state == WEBSOCKET_IN_PROGRESS)
{
if (rc != TCPSOCKET_INTERRUPTED)
{
Log(TRACE_MIN, -1, "Posting websocket handshake for client %s rc %d", m->c->clientID, m->rc);
m->c->connect_state = WAIT_FOR_CONNACK;
Thread_post_sem(m->connect_sem);
}
}
}
}
run_id = 0;
running = tostop = 0;
Thread_unlock_mutex(mqttclient_mutex);
FUNC_EXIT;
#if defined(_WIN32) || defined(_WIN64)
ExitThread(0);
#endif
return 0;
}
static int MQTTClient_stop(void)
{
int rc = 0;
FUNC_ENTRY;
if (running == 1 && tostop == 0)
{
int conn_count = 0;