-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathMQTTProtocolClient.c
More file actions
1119 lines (1017 loc) · 33.8 KB
/
Copy pathMQTTProtocolClient.c
File metadata and controls
1119 lines (1017 loc) · 33.8 KB
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, 2022 IBM Corp. and Ian Craggs
*
* 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 - fix for bug 413429 - connectionLost not called
* Ian Craggs - fix for bug 421103 - trying to write to same socket, in retry
* Rong Xiang, Ian Craggs - C++ compatibility
* Ian Craggs - turn off DUP flag for PUBREL - MQTT 3.1.1
* Ian Craggs - ensure that acks are not sent if write is outstanding on socket
* Ian Craggs - MQTT 5.0 support
*******************************************************************************/
/**
* @file
* \brief Functions dealing with the MQTT protocol exchanges
*
* Some other related functions are in the MQTTProtocolOut module
* */
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "MQTTProtocolClient.h"
#if !defined(NO_PERSISTENCE)
#include "MQTTPersistence.h"
#endif
#include "Socket.h"
#include "SocketBuffer.h"
#include "StackTrace.h"
#include "Heap.h"
#if !defined(min)
#define min(A,B) ( (A) < (B) ? (A):(B))
#endif
extern MQTTProtocol state;
extern ClientStates* bstate;
static void MQTTProtocol_storeQoS0(Clients* pubclient, Publish* publish);
static int MQTTProtocol_startPublishCommon(
Clients* pubclient,
Publish* publish,
int qos,
int retained);
static void MQTTProtocol_retries(START_TIME_TYPE now, Clients* client, int regardless);
static int MQTTProtocol_queueAck(Clients* client, int ackType, int msgId);
typedef struct {
int messageId;
int ackType;
} AckRequest;
/**
* List callback function for comparing Message structures by message id
* @param a first integer value
* @param b second integer value
* @return boolean indicating whether a and b are equal
*/
int messageIDCompare(void* a, void* b)
{
Messages* msg = (Messages*)a;
return msg->msgid == *(int*)b;
}
/**
* Assign a new message id for a client. Make sure it isn't already being used and does
* not exceed the maximum.
* @param client a client structure
* @return the next message id to use, or 0 if none available
*/
int MQTTProtocol_assignMsgId(Clients* client)
{
int start_msgid = client->msgID;
int msgid = start_msgid;
FUNC_ENTRY;
msgid = (msgid == MAX_MSG_ID) ? 1 : msgid + 1;
while (ListFindItem(client->outboundMsgs, &msgid, messageIDCompare) != NULL)
{
msgid = (msgid == MAX_MSG_ID) ? 1 : msgid + 1;
if (msgid == start_msgid)
{ /* we've tried them all - none free */
msgid = 0;
break;
}
}
if (msgid != 0)
client->msgID = msgid;
FUNC_EXIT_RC(msgid);
return msgid;
}
static void MQTTProtocol_storeQoS0(Clients* pubclient, Publish* publish)
{
int len;
pending_write* pw = NULL;
FUNC_ENTRY;
/* store the publication until the write is finished */
if ((pw = malloc(sizeof(pending_write))) == NULL)
goto exit;
Log(TRACE_MIN, 12, NULL);
if ((pw->p = MQTTProtocol_storePublication(publish, &len)) == NULL)
{
free(pw);
goto exit;
}
pw->socket = pubclient->net.socket;
if (!ListAppend(&(state.pending_writes), pw, sizeof(pending_write)+len))
{
free(pw->p);
free(pw);
goto exit;
}
/* we don't copy QoS 0 messages unless we have to, so now we have to tell the socket buffer where
the saved copy is */
if (SocketBuffer_updateWrite(pw->socket, pw->p->topic, pw->p->payload) == NULL)
Log(LOG_SEVERE, 0, "Error updating write");
publish->payload = publish->topic = NULL;
exit:
FUNC_EXIT;
}
/**
* Utility function to start a new publish exchange.
* @param pubclient the client to send the publication to
* @param publish the publication data
* @param qos the MQTT QoS to use
* @param retained boolean - whether to set the MQTT retained flag
* @return the completion code
*/
static int MQTTProtocol_startPublishCommon(Clients* pubclient, Publish* publish, int qos, int retained)
{
int rc = TCPSOCKET_COMPLETE;
FUNC_ENTRY;
rc = MQTTPacket_send_publish(publish, 0, qos, retained, &pubclient->net, pubclient->clientID);
if (qos == 0 && rc == TCPSOCKET_INTERRUPTED)
MQTTProtocol_storeQoS0(pubclient, publish);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* Start a new publish exchange. Store any state necessary and try to send the packet
* @param pubclient the client to send the publication to
* @param publish the publication data
* @param qos the MQTT QoS to use
* @param retained boolean - whether to set the MQTT retained flag
* @param mm - pointer to the message to send
* @return the completion code
*/
int MQTTProtocol_startPublish(Clients* pubclient, Publish* publish, int qos, int retained, Messages** mm)
{
Publish qos12pub = *publish;
int rc = 0;
FUNC_ENTRY;
if (qos > 0)
{
*mm = MQTTProtocol_createMessage(publish, mm, qos, retained, 0);
ListAppend(pubclient->outboundMsgs, *mm, (*mm)->len);
/* we change these pointers to the saved message location just in case the packet could not be written
entirely; the socket buffer will use these locations to finish writing the packet */
qos12pub.payload = (*mm)->publish->payload;
qos12pub.topic = (*mm)->publish->topic;
qos12pub.properties = (*mm)->properties;
qos12pub.MQTTVersion = (*mm)->MQTTVersion;
publish = &qos12pub;
}
rc = MQTTProtocol_startPublishCommon(pubclient, publish, qos, retained);
if (qos > 0)
memcpy((*mm)->publish->mask, publish->mask, sizeof((*mm)->publish->mask));
FUNC_EXIT_RC(rc);
return rc;
}
/**
* Copy and store message data for retries
* @param publish the publication data
* @param mm - pointer to the message data to store
* @param qos the MQTT QoS to use
* @param retained boolean - whether to set the MQTT retained flag
* @param allocatePayload boolean - whether or not to malloc payload
* @return pointer to the message data stored
*/
Messages* MQTTProtocol_createMessage(Publish* publish, Messages **mm, int qos, int retained, int allocatePayload)
{
Messages* m = malloc(sizeof(Messages));
FUNC_ENTRY;
if (!m)
goto exit;
m->len = sizeof(Messages);
if (*mm == NULL || (*mm)->publish == NULL)
{
int len1;
*mm = m;
if ((m->publish = MQTTProtocol_storePublication(publish, &len1)) == NULL)
{
free(m);
goto exit;
}
m->len += len1;
if (allocatePayload)
{
char *temp = m->publish->payload;
if ((m->publish->payload = malloc(m->publish->payloadlen)) == NULL)
{
free(m);
goto exit;
}
memcpy(m->publish->payload, temp, m->publish->payloadlen);
}
}
else /* this is now never used, I think */
{
++(((*mm)->publish)->refcount);
m->publish = (*mm)->publish;
}
m->msgid = publish->msgId;
m->qos = qos;
m->retain = retained;
m->MQTTVersion = publish->MQTTVersion;
if (m->MQTTVersion >= 5)
m->properties = MQTTProperties_copy(&publish->properties);
m->lastTouch = MQTTTime_now();
if (qos == 2)
m->nextMessageType = PUBREC;
exit:
FUNC_EXIT;
return m;
}
/**
* Store message data for possible retry
* @param publish the publication data
* @param len returned length of the data stored
* @return the publication stored
*/
Publications* MQTTProtocol_storePublication(Publish* publish, int* len)
{
Publications* p = malloc(sizeof(Publications));
FUNC_ENTRY;
if (!p)
goto exit;
p->refcount = 1;
*len = (int)strlen(publish->topic)+1;
p->topic = publish->topic;
publish->topic = NULL;
*len += sizeof(Publications);
p->topiclen = publish->topiclen;
p->payloadlen = publish->payloadlen;
p->payload = publish->payload;
publish->payload = NULL;
*len += publish->payloadlen;
memcpy(p->mask, publish->mask, sizeof(p->mask));
if ((ListAppend(&(state.publications), p, *len)) == NULL)
{
free(p);
p = NULL;
}
exit:
FUNC_EXIT;
return p;
}
/**
* Remove stored message data. Opposite of storePublication
* @param p stored publication to remove
*/
void MQTTProtocol_removePublication(Publications* p)
{
FUNC_ENTRY;
if (p && --(p->refcount) == 0)
{
if (p->payload)
{
free(p->payload);
p->payload = NULL;
}
if (p->topic)
{
free(p->topic);
p->topic = NULL;
}
ListRemove(&(state.publications), p);
}
FUNC_EXIT;
}
/**
* Process an incoming publish packet for a socket
* The payload field of the packet has not been transferred to another buffer at this point.
* If it's needed beyond the scope of this function, it has to be copied.
* @param pack pointer to the publish packet
* @param sock the socket on which the packet was received
* @return completion code
*/
int MQTTProtocol_handlePublishes(void* pack, SOCKET sock)
{
Publish* publish = (Publish*)pack;
Clients* client = NULL;
char* clientid = NULL;
int rc = TCPSOCKET_COMPLETE;
int socketHasPendingWrites = 0;
FUNC_ENTRY;
client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
clientid = client->clientID;
Log(LOG_PROTOCOL, 11, NULL, sock, clientid, publish->msgId, publish->header.bits.qos,
publish->header.bits.retain, publish->payloadlen, min(20, publish->payloadlen), publish->payload);
if (publish->header.bits.qos == 0)
{
Protocol_processPublication(publish, client, 1);
goto exit;
}
socketHasPendingWrites = !Socket_noPendingWrites(sock);
if (publish->header.bits.qos == 1)
{
Protocol_processPublication(publish, client, 1);
if (socketHasPendingWrites)
rc = MQTTProtocol_queueAck(client, PUBACK, publish->msgId);
else
rc = MQTTPacket_send_puback(publish->MQTTVersion, publish->msgId, &client->net, client->clientID);
}
else if (publish->header.bits.qos == 2)
{
/* store publication in inbound list */
int len;
int already_received = 0;
ListElement* listElem = NULL;
Messages* m = malloc(sizeof(Messages));
Publications* p = NULL;
if (!m)
{
rc = PAHO_MEMORY_ERROR;
goto exit;
}
p = MQTTProtocol_storePublication(publish, &len);
m->publish = p;
m->msgid = publish->msgId;
m->qos = publish->header.bits.qos;
m->retain = publish->header.bits.retain;
m->MQTTVersion = publish->MQTTVersion;
if (m->MQTTVersion >= MQTTVERSION_5)
m->properties = MQTTProperties_copy(&publish->properties);
m->nextMessageType = PUBREL;
if ((listElem = ListFindItem(client->inboundMsgs, &(m->msgid), messageIDCompare)) != NULL)
{ /* discard queued publication with same msgID that the current incoming message */
Messages* msg = (Messages*)(listElem->content);
MQTTProtocol_removePublication(msg->publish);
if (msg->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&msg->properties);
ListInsert(client->inboundMsgs, m, sizeof(Messages) + len, listElem);
ListRemove(client->inboundMsgs, msg);
already_received = 1;
} else
ListAppend(client->inboundMsgs, m, sizeof(Messages) + len);
if (m->MQTTVersion >= MQTTVERSION_5 && already_received == 0)
{
Publish publish1;
publish1.header.bits.qos = m->qos;
publish1.header.bits.retain = m->retain;
publish1.msgId = m->msgid;
publish1.topic = m->publish->topic;
publish1.topiclen = m->publish->topiclen;
publish1.payload = m->publish->payload;
publish1.payloadlen = m->publish->payloadlen;
publish1.MQTTVersion = m->MQTTVersion;
publish1.properties = m->properties;
Protocol_processPublication(&publish1, client, 1);
ListRemove(&(state.publications), m->publish);
m->publish = NULL;
} else
{ /* allocate and copy payload data as it's needed for pubrel.
For other cases, it's done in Protocol_processPublication */
char *temp = m->publish->payload;
if ((m->publish->payload = malloc(m->publish->payloadlen)) == NULL)
{
rc = PAHO_MEMORY_ERROR;
goto exit;
}
memcpy(m->publish->payload, temp, m->publish->payloadlen);
}
if (socketHasPendingWrites)
rc = MQTTProtocol_queueAck(client, PUBREC, publish->msgId);
else
rc = MQTTPacket_send_pubrec(publish->MQTTVersion, publish->msgId, &client->net, client->clientID);
publish->topic = NULL;
}
exit:
MQTTPacket_freePublish(publish);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* Process an incoming puback packet for a socket
* @param pack pointer to the publish packet
* @param sock the socket on which the packet was received
* @return completion code
*/
int MQTTProtocol_handlePubacks(void* pack, SOCKET sock, Publications** pubToRemove)
{
Puback* puback = (Puback*)pack;
Clients* client = NULL;
int rc = TCPSOCKET_COMPLETE;
FUNC_ENTRY;
client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
Log(LOG_PROTOCOL, 14, NULL, sock, client->clientID, puback->msgId);
/* look for the message by message id in the records of outbound messages for this client */
if (ListFindItem(client->outboundMsgs, &(puback->msgId), messageIDCompare) == NULL)
Log(TRACE_MIN, 3, NULL, "PUBACK", client->clientID, puback->msgId);
else
{
Messages* m = (Messages*)(client->outboundMsgs->current->content);
if (m->qos != 1)
Log(TRACE_MIN, 4, NULL, "PUBACK", client->clientID, puback->msgId, m->qos);
else
{
Log(TRACE_MIN, 6, NULL, "PUBACK", client->clientID, puback->msgId);
#if !defined(NO_PERSISTENCE)
rc = MQTTPersistence_remove(client,
(m->MQTTVersion >= MQTTVERSION_5) ? PERSISTENCE_V5_PUBLISH_SENT : PERSISTENCE_PUBLISH_SENT,
m->qos, puback->msgId);
#endif
if (pubToRemove != NULL)
*pubToRemove = m->publish;
else
MQTTProtocol_removePublication(m->publish);
if (m->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&m->properties);
ListRemove(client->outboundMsgs, m);
}
}
if (puback->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&puback->properties);
free(pack);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* Process an incoming pubrec packet for a socket
* @param pack pointer to the publish packet
* @param sock the socket on which the packet was received
* @return completion code
*/
int MQTTProtocol_handlePubrecs(void* pack, SOCKET sock, Publications** pubToRemove)
{
Pubrec* pubrec = (Pubrec*)pack;
Clients* client = NULL;
int rc = TCPSOCKET_COMPLETE;
int send_pubrel = 1; /* boolean to send PUBREL or not */
FUNC_ENTRY;
client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
Log(LOG_PROTOCOL, 15, NULL, sock, client->clientID, pubrec->msgId);
/* look for the message by message id in the records of outbound messages for this client */
client->outboundMsgs->current = NULL;
if (ListFindItem(client->outboundMsgs, &(pubrec->msgId), messageIDCompare) == NULL)
{
if (pubrec->header.bits.dup == 0)
Log(TRACE_MIN, 3, NULL, "PUBREC", client->clientID, pubrec->msgId);
}
else
{
Messages* m = (Messages*)(client->outboundMsgs->current->content);
if (m->qos != 2)
{
if (pubrec->header.bits.dup == 0)
Log(TRACE_MIN, 4, NULL, "PUBREC", client->clientID, pubrec->msgId, m->qos);
}
else if (m->nextMessageType != PUBREC)
{
if (pubrec->header.bits.dup == 0)
Log(TRACE_MIN, 5, NULL, "PUBREC", client->clientID, pubrec->msgId);
}
else
{
if (pubrec->MQTTVersion >= MQTTVERSION_5 && pubrec->rc >= MQTTREASONCODE_UNSPECIFIED_ERROR)
{
Log(TRACE_MIN, -1, "Pubrec error %d received for client %s msgid %d, not sending PUBREL",
pubrec->rc, client->clientID, pubrec->msgId);
#if !defined(NO_PERSISTENCE)
rc = MQTTPersistence_remove(client,
(pubrec->MQTTVersion >= MQTTVERSION_5) ? PERSISTENCE_V5_PUBLISH_SENT : PERSISTENCE_PUBLISH_SENT,
m->qos, pubrec->msgId);
#endif
if (pubToRemove != NULL)
*pubToRemove = m->publish;
else
MQTTProtocol_removePublication(m->publish);
if (m->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&m->properties);
ListRemove(client->outboundMsgs, m);
(++state.msgs_sent);
send_pubrel = 0; /* in MQTT v5, stop the exchange if there is an error reported */
}
else
{
m->nextMessageType = PUBCOMP;
m->lastTouch = MQTTTime_now();
}
}
}
if (!send_pubrel)
; /* only don't send ack on MQTT v5 PUBREC error, otherwise send ack under all circumstances because MQTT state can get out of step */
else if (!Socket_noPendingWrites(sock))
rc = MQTTProtocol_queueAck(client, PUBREL, pubrec->msgId);
else
rc = MQTTPacket_send_pubrel(pubrec->MQTTVersion, pubrec->msgId, 0, &client->net, client->clientID);
if (pubrec->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&pubrec->properties);
free(pack);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* Process an incoming pubrel packet for a socket
* @param pack pointer to the publish packet
* @param sock the socket on which the packet was received
* @return completion code
*/
int MQTTProtocol_handlePubrels(void* pack, SOCKET sock)
{
Pubrel* pubrel = (Pubrel*)pack;
Clients* client = NULL;
int rc = TCPSOCKET_COMPLETE;
FUNC_ENTRY;
client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
Log(LOG_PROTOCOL, 17, NULL, sock, client->clientID, pubrel->msgId);
/* look for the message by message id in the records of inbound messages for this client */
if (ListFindItem(client->inboundMsgs, &(pubrel->msgId), messageIDCompare) == NULL)
{
if (pubrel->header.bits.dup == 0)
Log(TRACE_MIN, 3, NULL, "PUBREL", client->clientID, pubrel->msgId);
}
else
{
Messages* m = (Messages*)(client->inboundMsgs->current->content);
if (m->qos != 2)
Log(TRACE_MIN, 4, NULL, "PUBREL", client->clientID, pubrel->msgId, m->qos);
else if (m->nextMessageType != PUBREL)
Log(TRACE_MIN, 5, NULL, "PUBREL", client->clientID, pubrel->msgId);
else
{
Publish publish;
memset(&publish, '\0', sizeof(publish));
publish.header.bits.qos = m->qos;
publish.header.bits.retain = m->retain;
publish.msgId = m->msgid;
if (m->publish)
{
publish.topic = m->publish->topic;
publish.topiclen = m->publish->topiclen;
publish.payload = m->publish->payload;
publish.payloadlen = m->publish->payloadlen;
}
publish.MQTTVersion = m->MQTTVersion;
if (publish.MQTTVersion >= MQTTVERSION_5)
publish.properties = m->properties;
else
Protocol_processPublication(&publish, client, 0); /* only for 3.1.1 and lower */
#if !defined(NO_PERSISTENCE)
rc += MQTTPersistence_remove(client,
(m->MQTTVersion >= MQTTVERSION_5) ? PERSISTENCE_V5_PUBLISH_RECEIVED : PERSISTENCE_PUBLISH_RECEIVED,
m->qos, pubrel->msgId);
#endif
if (m->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&m->properties);
if (m->publish)
ListRemove(&(state.publications), m->publish);
ListRemove(client->inboundMsgs, m);
++(state.msgs_received);
}
}
/* Send ack under all circumstances because MQTT state can get out of step - this standard also says to do this */
if (!Socket_noPendingWrites(sock))
rc = MQTTProtocol_queueAck(client, PUBCOMP, pubrel->msgId);
else
rc = MQTTPacket_send_pubcomp(pubrel->MQTTVersion, pubrel->msgId, &client->net, client->clientID);
if (pubrel->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&pubrel->properties);
free(pack);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* Process an incoming pubcomp packet for a socket
* @param pack pointer to the publish packet
* @param sock the socket on which the packet was received
* @return completion code
*/
int MQTTProtocol_handlePubcomps(void* pack, SOCKET sock, Publications** pubToRemove)
{
Pubcomp* pubcomp = (Pubcomp*)pack;
Clients* client = NULL;
int rc = TCPSOCKET_COMPLETE;
FUNC_ENTRY;
client = (Clients*)(ListFindItem(bstate->clients, &sock, clientSocketCompare)->content);
Log(LOG_PROTOCOL, 19, NULL, sock, client->clientID, pubcomp->msgId);
/* look for the message by message id in the records of outbound messages for this client */
if (ListFindItem(client->outboundMsgs, &(pubcomp->msgId), messageIDCompare) == NULL)
{
if (pubcomp->header.bits.dup == 0)
Log(TRACE_MIN, 3, NULL, "PUBCOMP", client->clientID, pubcomp->msgId);
}
else
{
Messages* m = (Messages*)(client->outboundMsgs->current->content);
if (m->qos != 2)
Log(TRACE_MIN, 4, NULL, "PUBCOMP", client->clientID, pubcomp->msgId, m->qos);
else
{
if (m->nextMessageType != PUBCOMP)
Log(TRACE_MIN, 5, NULL, "PUBCOMP", client->clientID, pubcomp->msgId);
else
{
Log(TRACE_MIN, 6, NULL, "PUBCOMP", client->clientID, pubcomp->msgId);
#if !defined(NO_PERSISTENCE)
rc = MQTTPersistence_remove(client,
(m->MQTTVersion >= MQTTVERSION_5) ? PERSISTENCE_V5_PUBLISH_SENT : PERSISTENCE_PUBLISH_SENT,
m->qos, pubcomp->msgId);
if (rc != 0)
Log(LOG_ERROR, -1, "Error removing PUBCOMP for client id %s msgid %d from persistence", client->clientID, pubcomp->msgId);
#endif
if (pubToRemove != NULL)
*pubToRemove = m->publish;
else
MQTTProtocol_removePublication(m->publish);
if (m->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&m->properties);
ListRemove(client->outboundMsgs, m);
(++state.msgs_sent);
}
}
}
if (pubcomp->MQTTVersion >= MQTTVERSION_5)
MQTTProperties_free(&pubcomp->properties);
free(pack);
FUNC_EXIT_RC(rc);
return rc;
}
/**
* MQTT protocol keepAlive processing. Sends PINGREQ packets as required.
* @param now current time
*/
void MQTTProtocol_keepalive(START_TIME_TYPE now)
{
ListElement* current = NULL;
FUNC_ENTRY;
ListNextElement(bstate->clients, ¤t);
while (current)
{
Clients* client = (Clients*)(current->content);
ListNextElement(bstate->clients, ¤t);
if (client->connected == 0 || client->keepAliveInterval == 0)
continue;
if (client->ping_outstanding == 1)
{
if (MQTTTime_difftime(now, client->net.lastPing) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1500) &&
/* if last received is more recent, we could be receiving a large packet */
MQTTTime_difftime(now, client->net.lastReceived) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1500))
{
Log(TRACE_PROTOCOL, -1, "PINGRESP not received in keepalive interval for client %s on socket %d, disconnecting", client->clientID, client->net.socket);
MQTTProtocol_closeSession(client, 1);
}
}
else if (client->ping_due == 1 &&
(MQTTTime_difftime(now, client->ping_due_time) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1500)))
{
/* if the last received time is more recent than the ping due time, we could be receiving a large packet,
* preventing the PINGRESP being received */
if (MQTTTime_difftime(now, client->ping_due_time) <= MQTTTime_difftime(now, client->net.lastReceived))
{
/* ping still outstanding after keep alive interval, so close session */
Log(TRACE_PROTOCOL, -1, "PINGREQ still outstanding for client %s on socket %d, disconnecting", client->clientID, client->net.socket);
MQTTProtocol_closeSession(client, 1);
}
}
else if (MQTTTime_difftime(now, client->net.lastSent) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1000))
/* the time since we last sent a packet, or part of a packet has exceeded the keep alive, so we need to send a ping */
{
if (Socket_noPendingWrites(client->net.socket))
{
if (MQTTPacket_send_pingreq(&client->net, client->clientID) != TCPSOCKET_COMPLETE)
{
Log(TRACE_PROTOCOL, -1, "Error sending PINGREQ for client %s on socket %d, disconnecting", client->clientID, client->net.socket);
MQTTProtocol_closeSession(client, 1);
}
else
{
client->ping_due = 0;
client->net.lastPing = now;
client->ping_outstanding = 1;
}
}
else if (client->ping_due == 0)
{
Log(TRACE_PROTOCOL, -1, "Couldn't send PINGREQ for client %s on socket %d, noting",
client->clientID, client->net.socket);
client->ping_due = 1;
client->ping_due_time = now;
}
}
else if (MQTTTime_difftime(now, client->net.lastReceived) >= (DIFF_TIME_TYPE)(client->keepAliveInterval * 1000))
/* the time since we last received any data has exceeded the keep alive, so we can send a ping to see if the server is alive */
{
/* Check that no writes are pending for the socket. If there are, forget about it, as this PING use is optional */
if (Socket_noPendingWrites(client->net.socket))
{
if (MQTTPacket_send_pingreq(&client->net, client->clientID) != TCPSOCKET_COMPLETE)
{
Log(TRACE_PROTOCOL, -1, "Error sending PINGREQ for client %s on socket %d, disconnecting", client->clientID, client->net.socket);
MQTTProtocol_closeSession(client, 1);
}
else
{
client->ping_due = 0;
client->net.lastPing = now;
client->ping_outstanding = 1;
}
}
}
}
FUNC_EXIT;
}
/**
* MQTT retry processing per client
* @param now current time
* @param client - the client to which to apply the retry processing
* @param regardless boolean - retry packets regardless of retry interval (used on reconnect)
*/
static void MQTTProtocol_retries(START_TIME_TYPE now, Clients* client, int regardless)
{
ListElement* outcurrent = NULL;
FUNC_ENTRY;
if (!regardless && client->retryInterval <= 0 && /* 0 or -ive retryInterval turns off retry except on reconnect */
client->connect_sent == client->connect_count)
goto exit;
if (regardless)
client->connect_count = client->outboundMsgs->count; /* remember the number of messages to retry on connect */
else if (client->connect_sent < client->connect_count) /* continue a connect retry which didn't complete first time around */
regardless = 1;
while (client && ListNextElement(client->outboundMsgs, &outcurrent) &&
client->connected && client->good && /* client is connected and has no errors */
Socket_noPendingWrites(client->net.socket)) /* there aren't any previous packets still stacked up on the socket */
{
Messages* m = (Messages*)(outcurrent->content);
if (regardless || MQTTTime_difftime(now, m->lastTouch) > (DIFF_TIME_TYPE)(max(client->retryInterval, 10) * 1000))
{
if (regardless)
++client->connect_sent;
if (m->qos == 1 || (m->qos == 2 && m->nextMessageType == PUBREC))
{
Publish publish;
int rc;
Log(TRACE_MIN, 7, NULL, "PUBLISH", client->clientID, client->net.socket, m->msgid);
publish.msgId = m->msgid;
publish.topic = m->publish->topic;
publish.payload = m->publish->payload;
publish.payloadlen = m->publish->payloadlen;
publish.properties = m->properties;
publish.MQTTVersion = m->MQTTVersion;
memcpy(publish.mask, m->publish->mask, sizeof(publish.mask));
rc = MQTTPacket_send_publish(&publish, 1, m->qos, m->retain, &client->net, client->clientID);
memcpy(m->publish->mask, publish.mask, sizeof(m->publish->mask)); /* store websocket mask used in send */
if (rc == SOCKET_ERROR)
{
client->good = 0;
Log(TRACE_PROTOCOL, 29, NULL, client->clientID, client->net.socket,
Socket_getpeer(client->net.socket));
MQTTProtocol_closeSession(client, 1);
client = NULL;
}
else
{
if (m->qos == 0 && rc == TCPSOCKET_INTERRUPTED)
MQTTProtocol_storeQoS0(client, &publish);
m->lastTouch = MQTTTime_now();
}
}
else if (m->qos && m->nextMessageType == PUBCOMP)
{
Log(TRACE_MIN, 7, NULL, "PUBREL", client->clientID, client->net.socket, m->msgid);
if (MQTTPacket_send_pubrel(m->MQTTVersion, m->msgid, 0, &client->net, client->clientID) != TCPSOCKET_COMPLETE)
{
client->good = 0;
Log(TRACE_PROTOCOL, 29, NULL, client->clientID, client->net.socket,
Socket_getpeer(client->net.socket));
MQTTProtocol_closeSession(client, 1);
client = NULL;
}
else
m->lastTouch = MQTTTime_now();
}
}
}
exit:
FUNC_EXIT;
}
/**
* Queue an ack message. This is used when the socket is full (e.g. SSL_ERROR_WANT_WRITE).
* To be completed/cleared when the socket is no longer full
* @param client the client that received the published message
* @param ackType the type of ack to send
* @param msgId the msg id of the message we are acknowledging
* @return the completion code
*/
int MQTTProtocol_queueAck(Clients* client, int ackType, int msgId)
{
int rc = 0;
AckRequest* ackReq = NULL;
FUNC_ENTRY;
ackReq = malloc(sizeof(AckRequest));
if (!ackReq)
rc = PAHO_MEMORY_ERROR;
else
{
ackReq->messageId = msgId;
ackReq->ackType = ackType;
ListAppend(client->outboundQueue, ackReq, sizeof(AckRequest));
}
FUNC_EXIT_RC(rc);
return rc;
}
/**
* MQTT retry protocol and socket pending writes processing.
* @param now current time
* @param doRetry boolean - retries as well as pending writes?
* @param regardless boolean - retry packets regardless of retry interval (used on reconnect)
*/
void MQTTProtocol_retry(START_TIME_TYPE now, int doRetry, int regardless)
{
ListElement* current = NULL;
FUNC_ENTRY;
ListNextElement(bstate->clients, ¤t);
/* look through the outbound message list of each client, checking to see if a retry is necessary */
while (current)
{
Clients* client = (Clients*)(current->content);
ListNextElement(bstate->clients, ¤t);
if (client->connected == 0)
continue;
if (client->good == 0)
{
MQTTProtocol_closeSession(client, 1);
continue;
}
if (Socket_noPendingWrites(client->net.socket) == 0)
continue;
if (doRetry)
MQTTProtocol_retries(now, client, regardless);
}
FUNC_EXIT;
}
/**
* Free a client structure
* @param client the client data to free
*/
void MQTTProtocol_freeClient(Clients* client)
{
FUNC_ENTRY;
/* free up pending message lists here, and any other allocated data */
MQTTProtocol_freeMessageList(client->outboundMsgs);
MQTTProtocol_freeMessageList(client->inboundMsgs);
ListFree(client->messageQueue);
ListFree(client->outboundQueue);
free(client->clientID);
client->clientID = NULL;
if (client->will)
{
free(client->will->payload);
free(client->will->topic);
free(client->will);
client->will = NULL;
}
if (client->username)
free((void*)client->username);
if (client->password)
free((void*)client->password);
if (client->httpProxy)
free(client->httpProxy);
if (client->httpsProxy)
free(client->httpsProxy);
if (client->net.http_proxy_auth)
free(client->net.http_proxy_auth);
#if defined(OPENSSL)
if (client->net.https_proxy_auth)
free(client->net.https_proxy_auth);
if (client->sslopts)
{
if (client->sslopts->trustStore)
free((void*)client->sslopts->trustStore);
if (client->sslopts->keyStore)
free((void*)client->sslopts->keyStore);
if (client->sslopts->privateKey)
free((void*)client->sslopts->privateKey);
if (client->sslopts->privateKeyPassword)
free((void*)client->sslopts->privateKeyPassword);
if (client->sslopts->enabledCipherSuites)
free((void*)client->sslopts->enabledCipherSuites);
if (client->sslopts->struct_version >= 2)
{
if (client->sslopts->CApath)
free((void*)client->sslopts->CApath);
}
if (client->sslopts->struct_version >= 5)
{
if (client->sslopts->protos)
free((void*)client->sslopts->protos);
}
if (client->sslopts->struct_version >= 6)
{
if(client->sslopts->providerName)
free((void*)client->sslopts->providerName);
}
free(client->sslopts);
client->sslopts = NULL;
}
#endif
/* don't free the client structure itself... this is done elsewhere */
FUNC_EXIT;
}
/**
* Empty a message list, leaving it able to accept new messages
* @param msgList the message list to empty