-
Notifications
You must be signed in to change notification settings - Fork 3
/
MQTTClient.cpp
1623 lines (1423 loc) · 68.4 KB
/
MQTTClient.cpp
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
// We need our implementation
#include "Network/Clients/MQTT.hpp"
#if MQTTUseAuth == 1
/** Used to track reentrancy in the AUTH recursive scheme */
enum AuthReentrancy
{
FromConnect = 0x80000000,
AuthMask = 0x7FFFFFFF,
};
#endif
#if MQTTOnlyBSDSocket != 1
// We need socket declaration
#include "include/Network/Socket.hpp"
// We need SSL socket declaration too
#include "include/Network/SSLSocket.hpp"
// We need FastLock too
#include "include/Threading/Lock.hpp"
#endif
#if MQTTUseTLS == 1
// We need MBedTLS code
// #include <mbedtls/certs.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/entropy.h>
#include <mbedtls/error.h>
#include <mbedtls/net_sockets.h>
#include <mbedtls/platform.h>
#include <mbedtls/ssl.h>
#endif
// We need StackHeapBuffer to avoid stressing the heap allocator when it's not required
#include "include/Platform/StackHeapBuffer.hpp"
// This is the maximum allocation that'll be performed on the stack before it's being replaced by heap allocation
// This also means that the stack size for the thread using such function must be larger than this value
#define StackSizeAllocationLimit CONFIG_ESP_EMQTT5_STACK_SIZE
namespace Network { namespace Client {
#if MQTTOnlyBSDSocket != 1
/* The socket class we are using for socket operations.
There's a default implementation for Berkeley socket and (Open)SSL socket in the ClassPath, but
you can implement any library you want, like, for example, lwIP, so change this if you do */
typedef Network::Socket::BerkeleySocket Socket;
#if MQTTUseTLS == 1
/* The SSL socket we are using (when using SSL/TLS connection).
There's a default implementation for (Open/Libre)SSL socket in ClassPath, but you can implement
one class with, for example, MBEDTLS here if you want. Change this if you do */
typedef Network::Socket::SSL_TLS SSLSocket;
/** The SSL context to (re)use. If you need to skip negotiating, you'll need to modify this context */
typedef SSLSocket::SSLContext SSLContext;
#endif
/** The scoped lock class we are using */
typedef Threading::ScopedLock ScopedLock;
struct MQTTv5::Impl
{
/** The multithread protection for this object */
Threading::Lock lock;
/** This client socket */
Socket * socket;
/** The DER encoded certificate (if provided) */
const DynamicBinDataView * brokerCert;
#if MQTTUseTLS == 1
/** The SSL context (if any used) */
SSLContext * sslContext;
#endif
/** This client unique identifier */
DynamicString clientID;
/** The message received callback to use */
MessageReceived * cb;
/** The default timeout in milliseconds */
uint32 timeoutMs;
/** The last communication time in second */
uint32 lastCommunication;
/** The publish current default identifier allocator */
uint16 publishCurrentId;
/** The keep alive delay in seconds */
uint16 keepAlive;
/** The reading state. Because data on a TCP stream is
a stream, we have to remember what state we are currently following while parsing data */
enum RecvState
{
Ready = 0,
GotType,
GotLength,
GotCompletePacket,
} recvState;
/** The receiving buffer size */
uint32 recvBufferSize;
/** The maximum packet size the server is willing to accept */
uint32 maxPacketSize;
/** The available data in the buffer */
uint32 available;
/** The receiving data buffer */
uint8 * recvBuffer;
/** The receiving VBInt size for the packet header */
uint8 packetExpectedVBSize;
#if MQTTUseAuth == 1
/** Used to track the origin of the AUTH exchange */
uint32 authSource;
#endif
uint16 allocatePacketID()
{
return ++publishCurrentId;
}
Impl(const char * clientID, MessageReceived * callback, const DynamicBinDataView * brokerCert)
: socket(0), brokerCert(brokerCert),
#if MQTTUseTLS == 1
sslContext(0),
#endif
#if MQTTUseAuth == 1
authSource(0),
#endif
clientID(clientID), cb(callback), timeoutMs(3000), lastCommunication(0), publishCurrentId(0), keepAlive(300),
recvState(Ready), recvBufferSize(max(callback->maxPacketSize(), 8U)), maxPacketSize(65535), available(0), recvBuffer((uint8*)::malloc(recvBufferSize)), packetExpectedVBSize(Protocol::MQTT::Common::VBInt(recvBufferSize).getSize())
{}
~Impl() { delete socket; socket = 0; ::free(recvBuffer); recvBuffer = 0; recvBufferSize = 0; }
inline void setTimeout(uint32 timeout) { timeoutMs = timeout; }
bool shouldPing()
{
return (((uint32)time(NULL) - lastCommunication) >= keepAlive);
}
int send(const char * buffer, const uint32 length)
{
if (!socket) return -1;
#if MQTTDumpCommunication == 1
// Dump the packet to send
String packetDump;
Utils::hexDump(packetDump, (const uint8*)buffer, length, 16, true, true);
Protocol::MQTT::V5::FixedHeader header;
header.raw = buffer[0];
Logger::log(Logger::Dump, "> Sending packet: %s(R:%d,Q:%d,D:%d)%s", Protocol::MQTT::V5::Helper::getControlPacketName((Protocol::MQTT::Common::ControlPacketType)(uint8)header.type), header.retain, header.QoS, header.dup, (const char*)packetDump);
#endif
return socket->sendReliably(buffer, (int)length, timeoutMs);
}
bool hasValidLength() const
{
Protocol::MQTT::Common::VBInt l;
return l.readFrom(recvBuffer + 1, available - 1) != Protocol::MQTT::Common::BadData;
}
/** Receive a control packet from the socket in the given time.
@retval positive The number of bytes received
@retval 0 Protocol error, you should close the socket
@retval -1 Socket error
@retval -2 Timeout */
int receiveControlPacket(const bool lowLatency = false)
{
if (!socket) return -1;
// Depending on the current state, we need to fetch as many bytes as possible within the given timeoutMs
// This is a complex problem here because we want both to optimize for
// - latency (returns as fast as possible when we've received a complete packet)
// - blocking time (don't return immediately if the data is currently in transfer, need to wait for it to arrive)
// - minimal syscalls (don't call recv byte per byte as the overhead will be significant)
// - network queue (don't fetch more byte than necessary for getting a single control packet)
// - streaming usage (this can be called while a control packet was being received and we timed out)
// So the algorithm used here depends on the current receiving state
// If we haven't received packet length yet, we have to fetch the header very carefully
// Else, we can enter a more general receiving loop until we have all bytes from the control packet
int ret = 0;
Protocol::MQTT::Common::VBInt len;
#if MQTTLowLatency == 1
// In low latency mode, return as early as possible
if (lowLatency && !socket->select(true, false, 0)) return -2;
#endif
// We want to keep track of complete timeout time over multiple operations
Time::TimeOut timeout(timeoutMs);
switch (recvState)
{
case Ready:
case GotType:
{ // Here, make sure we only fetch the length first
// The minimal size is 2 bytes for PINGRESP, DISCONNECT and AUTH.
// Because of this, we can't really outsmart the system everytime
ret = socket->receiveReliably((char*)&recvBuffer[available], 2 - available, timeout);
if (ret > 0) available += ret;
// Deal with timeout first
if (timeout == 0) return -2;
// Deal with socket errors here
if (ret < 0 || available < 2) return -1;
// Depending on the packet type, let's wait for more data
if (recvBuffer[0] < 0xD0 || recvBuffer[1]) // Below ping response or packet size larger than 2 bytes
{
int querySize = (packetExpectedVBSize + 1) - available;
ret = socket->receiveReliably((char*)&recvBuffer[available], querySize, timeout);
if (ret > 0) available += ret;
// Deal with timeout first
if (timeout == 0) return -2;
// Deal with socket errors here
if (ret < 0) return ret;
}
recvState = GotLength;
break;
}
default: break;
}
// Here we should either have a valid control packet header
uint32 r = len.readFrom(&recvBuffer[1], available - 1);
if (r == Protocol::MQTT::Common::BadData)
return 0; // Close the socket here, the given data are wrong or not the right protocol
if (r == Protocol::MQTT::Common::NotEnoughData)
{
if (available >= (packetExpectedVBSize+1))
{ // The server sends us a packet that's larger than the expected maximum size,
// In MQTTv5 it's a protocol error, so let's disconnect
return 0;
}
// We haven't received enough data in the given timeout to make progress, let's report a timeout
recvState = GotType;
return -2;
}
uint32 remainingLength = len;
uint32 totalPacketSize = remainingLength + 1 + len.getSize();
ret = totalPacketSize == available ? 0 : socket->receiveReliably((char*)&recvBuffer[available], (totalPacketSize - available), timeout);
if (ret > 0) available += ret;
if (timeout == 0) return -2;
if (ret < 0) return ret;
// Ok, let's check if we have received the complete packet
if (available == totalPacketSize)
{
recvState = GotCompletePacket;
#if MQTTDumpCommunication == 1
// Dump the packet received
String packetDump;
Utils::hexDump(packetDump, recvBuffer, available, 16, true, true);
Protocol::MQTT::V5::FixedHeader header;
header.raw = recvBuffer[0];
Logger::log(Logger::Dump, "< Received packet: %s(R:%d,Q:%d,D:%d)%s", Protocol::MQTT::V5::Helper::getControlPacketName((Protocol::MQTT::Common::ControlPacketType)(uint8)header.type), header.retain, header.QoS, header.dup, (const char*)packetDump);
#endif
lastCommunication = (uint32)time(NULL);
return (int)available;
}
// No yet, but we probably timed-out.
return -2;
}
/** Get the last received packet type */
Protocol::MQTT::V5::ControlPacketType getLastPacketType() const
{
if (recvState != GotCompletePacket) return Protocol::MQTT::V5::RESERVED;
Protocol::MQTT::V5::FixedHeader header;
header.raw = recvBuffer[0];
return (Protocol::MQTT::V5::ControlPacketType)header.type;
}
/** Extract a control packet of the given type */
int extractControlPacket(const Protocol::MQTT::V5::ControlPacketType type, Protocol::MQTT::Common::Serializable & packet)
{
if (recvState != GotCompletePacket)
{
int ret = receiveControlPacket();
if (ret <= 0) return ret;
if (recvState != GotCompletePacket)
return -2;
}
// Check the packet is the last expected type
if (getLastPacketType() != type) return -3;
// Seems to be the expected type, let's unserialize it
uint32 r = packet.readFrom(recvBuffer, recvBufferSize);
if (Protocol::MQTT::Common::isError(r)) return -4; // Parsing error
// Done with receiving the packet let's remember it
resetPacketReceivingState();
#if MQTTDumpCommunication == 1
MQTTString out;
packet.dump(out, 2);
Logger::log(Logger::Dump, "Received\n%.*s", MQTTStringGetLength(out), MQTTStringGetData(out));
#endif
return (int)r;
}
void resetPacketReceivingState() { recvState = Ready; available = 0; }
void close()
{
delete0(socket);
}
bool isOpen()
{
return socket != nullptr;
}
int connectWith(const char * host, const uint16 port, const bool withTLS)
{
if (isOpen()) return -1;
if (withTLS)
{
#if MQTTUseTLS == 1
if (!sslContext)
{ // If one certificate is given let's use it instead of the default CA bundle
sslContext = brokerCert ? new SSLContext(NULL, Crypto::SSLContext::Any) : new SSLContext();
}
if (!sslContext) return -2;
// Insert here any session specific configuration or certificate validator
if (brokerCert)
{
if (const char * error = sslContext->loadCertificateFromDER(brokerCert->data, brokerCert->length))
{
Logger::log(Logger::Error, "Could not load the given certificate: %s", error);
return -2;
}
}
socket = new Network::Socket::SSL_TLS(*sslContext, Network::Socket::BaseSocket::Stream);
#else
return -1;
#endif
} else socket = new Socket(Network::Socket::BaseSocket::Stream);
if (!socket) return -2;
// Let the socket be asynchronous and without Nagle's algorithm
if (!socket->setOption(Network::Socket::BaseSocket::Blocking, 0)) return -3;
if (!socket->setOption(Network::Socket::BaseSocket::NoDelay, 1)) return -4;
if (!socket->setOption(Network::Socket::BaseSocket::NoSigPipe, 1)) return -5;
// Then connect the socket to the server
int ret = socket->connect(Network::Address::URL("", String(host) + ":" + port, ""));
if (ret < 0) return -6;
if (ret == 0) return 0;
// Here, we need to wait until connection happens or times out
if (socket->select(false, true, timeoutMs)) return 0;
return -7;
}
MQTTv5::ErrorType handleAuth()
{
Protocol::MQTT::V5::ROAuthPacket packet;
int ret = extractControlPacket(type, packet);
if (ret > 0)
{
// Parse the Auth packet and call the user method
// Try to find the auth method, and the auth data
DynamicStringView authMethod;
DynamicBinDataView authData;
Protocol::MQTT::V5::VisitorVariant visitor;
while (packet.props.getProperty(visitor) && (authMethod.length == 0 || authData.length == 0))
{
if (visitor.propertyType() == Protocol::MQTT::V5::AuthenticationMethod)
{
auto view = visitor.as< DynamicStringView >();
authMethod = *view;
}
else if (visitor.propertyType() == Protocol::MQTT::V5::AuthenticationData)
{
auto data = visitor.as< DynamicBinDataView >();
authData = *data;
}
}
return cb->authReceived(packet.fixedVariableHeader.reason(), authMethod, authData, packet.props) ? MQTTv5::ErrorType::Success : MQTTv5::ErrorType::NetworkError;
}
return ErrorType::NetworkError;
}
MQTTv5::ErrorType handleConnACK()
{
// Parse the ConnACK packet;
Protocol::MQTT::V5::ROConnACKPacket packet;
int ret = extractControlPacket(type, packet);
if (ret > 0)
{
// We are only interested in the result of the connection
if (packet.fixedVariableHeader.acknowledgeFlag & 1)
{ // Session is present on the server. For now, we don't care, do we ?
}
if (packet.fixedVariableHeader.reasonCode != 0
#if MQTTUseAuth == 1
&& packet.fixedVariableHeader.reasonCode != Protocol::MQTT::V5::NotAuthorized
&& packet.fixedVariableHeader.reasonCode != Protocol::MQTT::V5::BadAuthenticationMethod
#endif
)
{
// We have failed connection with the following reason:
return (MQTTv5::ReasonCodes)packet.fixedVariableHeader.reasonCode;
}
// Now, we are going to parse the other properties
#if MQTTUseAuth == 1
DynamicStringView authMethod;
DynamicBinDataView authData;
#endif
Protocol::MQTT::V5::VisitorVariant visitor;
while (packet.props.getProperty(visitor))
{
switch (visitor.propertyType())
{
case Protocol::MQTT::V5::PacketSizeMax:
{
auto pod = visitor.as< Protocol::MQTT::V5::LittleEndianPODVisitor<uint32> >();
maxPacketSize = pod->getValue();
break;
}
case Protocol::MQTT::V5::AssignedClientID:
{
auto view = visitor.as< Protocol::MQTT::V5::DynamicStringView >();
clientID.from(view->data, view->length); // This allocates memory for holding the copy
break;
}
case Protocol::MQTT::V5::ServerKeepAlive:
{
auto pod = visitor.as< Protocol::MQTT::V5::LittleEndianPODVisitor<uint16> >();
keepAlive = (pod->getValue() + (pod->getValue()>>1)) >> 1; // Use 0.75 of the server's told value
break;
}
#if MQTTUseAuth == 1
case Protocol::MQTT::V5::AuthenticationMethod:
{
auto view = visitor.as<DynamicStringView>();
authMethod = *view;
} break;
case Protocol::MQTT::V5::AuthenticationData:
{
auto data = visitor.as<DynamicBinDataView>();
authData = *data;
} break;
#endif
// Actually, we don't care about other properties. Maybe we should ?
default: break;
}
}
#if MQTTUseAuth == 1
if (packet.fixedVariableHeader.reasonCode == Protocol::MQTT::V5::NotAuthorized
|| packet.fixedVariableHeader.reasonCode == Protocol::MQTT::V5::BadAuthenticationMethod)
{ // Let the user be aware of the required authentication properties so next connect will/can contains them
return cb->authReceived((ReasonCodes)packet.fixedVariableHeader.reasonCode, authMethod, authData, packet.props) ? ErrorType::Success : ErrorType::NetworkError;
}
#endif
return ErrorType::Success;
}
return Protocol::MQTT::V5::ProtocolError;
}
};
#else
#ifndef MQTTLock
/* If you have a true lock object in your system (for example, in FreeRTOS, use a mutex),
you should provide one instead of this one as this one just burns CPU while waiting */
class SpinLock
{
mutable std::atomic<bool> state;
public:
/** Construction */
SpinLock() : state(false) {}
/** Acquire the lock */
inline void acquire() volatile
{
while (state.exchange(true, std::memory_order_acq_rel))
{
// Put a sleep method here (using select here since it's cross platform in BSD socket API)
struct timeval tv;
tv.tv_sec = 0; tv.tv_usec = 500; // Wait 0.5ms per loop
select(0, NULL, NULL, NULL, &tv);
}
}
/** Try to acquire the lock */
inline bool tryAcquire() volatile { return state.exchange(true, std::memory_order_acq_rel) == false; }
/** Check if the lock is taken. For debugging purpose only */
inline bool isLocked() const volatile { return state.load(std::memory_order_consume); }
/** Release the lock */
inline void release() volatile { state.store(false, std::memory_order_release);; }
};
typedef SpinLock Lock;
struct ScopedLock
{
Lock & a;
ScopedLock(Lock & a) : a(a) { a.acquire(); }
~ScopedLock() { a.release(); }
};
#else
#define Lock MQTTLock
#define ScopedLock MQTTScopedLock
#endif
#ifndef closesocket
#define closesocket close
#endif
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
#if MQTTDumpCommunication == 1
static void hexdump(const void * buf, int len)
{
for (int i = 0; i < len; i++)
printf("%02X ", ((unsigned char*)buf)[i]);
printf("\n"); // Flush output
}
static void dumpBufferAsPacket(const char * prompt, const uint8* buffer, uint32 length)
{
// Dump the packet to send
Protocol::MQTT::V5::FixedHeader header;
header.raw = buffer[0];
printf("%s: %s(R:%d,Q:%d,D:%d)\n", prompt, Protocol::MQTT::V5::Helper::getControlPacketName((Protocol::MQTT::Common::ControlPacketType)(uint8)header.type), (uint8)header.retain, (uint8)header.QoS, (uint8)header.dup);
hexdump(buffer, length);
}
#endif
#if MQTTUseTLS == 1
// Small optimization to remove useless virtual table in the final binary if not used
#define MQTTVirtual virtual
#else
#define MQTTVirtual
#endif
struct BaseSocket
{
int socket;
struct timeval & timeoutMs;
MQTTVirtual int connect(const char * host, uint16 port, const MQTTv5::DynamicBinDataView *)
{
socket = ::socket(AF_INET, SOCK_STREAM, 0);
if (socket == -1) return -2;
// Please notice that under linux, it's not required to set the socket
// as non blocking if you define SO_SNDTIMEO, for connect timeout.
// so the code below could be optimized away. Yet, lwIP does show the
// same behavior so when a timeout for connection is actually required
// you must issue a select call here.
// Set non blocking here
int socketFlags = ::fcntl(socket, F_GETFL, 0);
if (socketFlags == -1) return -3;
if (::fcntl(socket, F_SETFL, (socketFlags | O_NONBLOCK)) != 0) return -3;
// Let the socket be without Nagle's algorithm
int flag = 1;
if (::setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag)) < 0) return -4;
// Then connect the socket to the server
struct addrinfo hints = {};
hints.ai_family = AF_INET; // IPv4 only for now
hints.ai_flags = AI_ADDRCONFIG;
hints.ai_socktype = SOCK_STREAM;
// Resolve address
struct addrinfo *result = NULL;
if (getaddrinfo(host, NULL, &hints, &result) < 0 || result == NULL) return -5;
// Then connect to it
struct sockaddr_in address;
address.sin_port = htons(port);
address.sin_family = AF_INET;
address.sin_addr = ((struct sockaddr_in *)(result->ai_addr))->sin_addr;
// free result
freeaddrinfo(result);
int ret = ::connect(socket, (const sockaddr*)&address, sizeof(address));
if (ret < 0 && errno != EINPROGRESS) return -6;
if (ret == 0) return 0;
// Here, we need to wait until connection happens or times out
if (select(false, true))
{
// Restore blocking behavior here
if (::fcntl(socket, F_SETFL, socketFlags) != 0) return -3;
// And set timeouts for both recv and send
if (::setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &timeoutMs, sizeof(timeoutMs)) < 0) return -4;
if (::setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, &timeoutMs, sizeof(timeoutMs)) < 0) return -4;
// Ok, done!
return 0;
}
return -7;
}
MQTTVirtual int recv(char * buffer, const uint32 minLength, const uint32 maxLength = 0)
{
int ret = ::recv(socket, buffer, minLength, MSG_WAITALL);
if (ret <= 0) return ret;
if (maxLength <= minLength) return ret;
int nret = ::recv(socket, &buffer[ret], maxLength - ret, 0);
return nret <= 0 ? nret : nret + ret;
}
MQTTVirtual int send(const char * buffer, const uint32 length)
{
#if MQTTDumpCommunication == 1
dumpBufferAsPacket("> Sending packet", (const uint8*)buffer, length);
#endif
return ::send(socket, buffer, (int)length, 0);
}
// Useful socket helpers functions here
MQTTVirtual int select(bool reading, bool writing, bool instantaneous = false)
{
// Linux modifies the timeout when calling select
struct timeval v = timeoutMs;
if (instantaneous) memset(&v, 0, sizeof(v));
fd_set set;
FD_ZERO(&set);
FD_SET(socket, &set);
// Then select
return ::select(socket + 1, reading ? &set : NULL, writing ? &set : NULL, NULL, &v);
}
BaseSocket(struct timeval & timeoutMs) : socket(-1), timeoutMs(timeoutMs) {}
MQTTVirtual ~BaseSocket() { ::closesocket(socket); socket = -1; }
};
#if MQTTUseTLS == 1
class MBTLSSocket : public BaseSocket
{
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context entropySource;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_x509_crt cacert;
mbedtls_net_context net;
private:
bool buildConf(const MQTTv5::DynamicBinDataView * brokerCert)
{
if (brokerCert)
{ // Use given root certificate (if you have a recent version of mbedtls, you could use mbedtls_x509_crt_parse_der_nocopy instead to skip a useless copy here)
if (::mbedtls_x509_crt_parse_der(&cacert, brokerCert->data, brokerCert->length))
return false;
}
// Now create configuration from default
if (::mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT))
return false;
::mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
::mbedtls_ssl_conf_authmode(&conf, brokerCert ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE);
uint32_t ms = timeoutMs.tv_usec / 1000;
::mbedtls_ssl_conf_read_timeout(&conf, ms < 50 ? 3000 : ms);
// Random number generator
::mbedtls_ssl_conf_rng(&conf, ::mbedtls_ctr_drbg_random, &entropySource);
if (::mbedtls_ctr_drbg_seed(&entropySource, ::mbedtls_entropy_func, &entropy, NULL, 0))
return false;
if (::mbedtls_ssl_setup(&ssl, &conf))
return false;
return true;
}
public:
MBTLSSocket(struct timeval & timeoutMs) : BaseSocket(timeoutMs)
{
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
mbedtls_x509_crt_init(&cacert);
mbedtls_ctr_drbg_init(&entropySource);
mbedtls_entropy_init(&entropy);
}
int connect(const char * host, uint16 port, const MQTTv5::DynamicBinDataView * brokerCert)
{
int ret = BaseSocket::connect(host, port, 0);
if (ret) return ret;
// MBedTLS doesn't deal with natural socket timeout correctly, so let's fix that
struct timeval zeroTO = {};
if (::setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &zeroTO, sizeof(zeroTO)) < 0) return -4;
if (::setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, &zeroTO, sizeof(zeroTO)) < 0) return -4;
net.fd = socket;
if (!buildConf(brokerCert)) return -8;
if (::mbedtls_ssl_set_hostname(&ssl, host)) return -9;
// Set the method the SSL engine is using to fetch/send data to the other side
::mbedtls_ssl_set_bio(&ssl, &net, ::mbedtls_net_send, NULL, ::mbedtls_net_recv_timeout);
ret = ::mbedtls_ssl_handshake(&ssl);
if (ret != 0 && ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
return -10;
// Check certificate if one provided
if (brokerCert)
{
uint32_t flags = mbedtls_ssl_get_verify_result(&ssl);
if (flags != 0)
{
#if MQTTDumpCommunication == 1
char verify_buf[100] = {0};
mbedtls_x509_crt_verify_info(verify_buf, sizeof(verify_buf), " ! ", flags);
printf("mbedtls_ssl_get_verify_result: %s flag: 0x%x\n", verify_buf, (unsigned int)flags);
#endif
return -11;
}
}
return 0;
}
int send(const char * buffer, const uint32 length)
{
#if MQTTDumpCommunication == 1
dumpBufferAsPacket("> Sending packet", (const uint8*)buffer, length);
#endif
return ::mbedtls_ssl_write(&ssl, (const uint8*)buffer, length);
}
int recv(char * buffer, const uint32 minLength, const uint32 maxLength = 0)
{
uint32 ret = 0;
while (ret < minLength)
{
int r = ::mbedtls_ssl_read(&ssl, (uint8*)&buffer[ret], minLength - ret);
if (r <= 0)
{
// Those means that we need to call again the read method
if (r == MBEDTLS_ERR_SSL_WANT_READ || r == MBEDTLS_ERR_SSL_WANT_WRITE)
continue;
if (r == MBEDTLS_ERR_SSL_TIMEOUT) {
errno = EWOULDBLOCK; // Remember it's a timeout
return -1;
}
return ret ? (int)ret : r; // Silent error here
}
ret += (uint32)r;
}
if (maxLength <= minLength) return ret;
// This one is a non blocking call
int nret = ::mbedtls_ssl_read(&ssl, (uint8*)&buffer[ret], maxLength - ret);
if (nret == MBEDTLS_ERR_SSL_TIMEOUT) return ret;
return nret <= 0 ? nret : nret + ret;
}
~MBTLSSocket()
{
mbedtls_ssl_close_notify(&ssl);
mbedtls_x509_crt_free(&cacert);
mbedtls_entropy_free(&entropy);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&entropySource);
mbedtls_ssl_free(&ssl);
}
};
#endif
struct MQTTv5::Impl
{
/** The multithread protection for this object */
Lock lock;
/** This client socket */
BaseSocket * socket;
/** The DER encoded certificate (if provided) */
const DynamicBinDataView * brokerCert;
/** This client unique identifier */
DynamicString clientID;
/** The message received callback to use */
MessageReceived * cb;
/** The default timeout in milliseconds */
struct timeval timeoutMs;
/** The last communication time in second */
uint32 lastCommunication;
/** The publish current default identifier allocator */
uint16 publishCurrentId;
/** The keep alive delay in seconds */
uint16 keepAlive;
#if MQTTUseAuth == 1
/** Mask used to track the origin of the AUTH exchange and reentrancy issues */
uint32 authSource;
#endif
/** The reading state. Because data on a TCP stream is
a stream, we have to remember what state we are currently following while parsing data */
enum RecvState
{
Ready = 0,
GotType,
GotLength,
GotCompletePacket,
} recvState;
/** The receiving buffer size */
uint32 recvBufferSize;
/** The maximum packet size the server is willing to accept */
uint32 maxPacketSize;
/** The available data in the buffer */
uint32 available;
/** The receiving data buffer */
uint8 * recvBuffer;
/** The receiving VBInt size for the packet header */
uint8 packetExpectedVBSize;
uint16 allocatePacketID()
{
return ++publishCurrentId;
}
Impl(const char * clientID, MessageReceived * callback, const DynamicBinDataView * brokerCert)
: socket(0), brokerCert(brokerCert), clientID(clientID), cb(callback), timeoutMs({3, 0}), lastCommunication(0), publishCurrentId(0), keepAlive(300),
#if MQTTUseAuth == 1
authSource(0),
#endif
recvState(Ready), recvBufferSize(max(callback->maxPacketSize(), 8U)), maxPacketSize(65535), available(0), recvBuffer((uint8*)::malloc(recvBufferSize)), packetExpectedVBSize(Protocol::MQTT::Common::VBInt(recvBufferSize).getSize())
{}
~Impl() { delete0(socket); ::free(recvBuffer); recvBuffer = 0; recvBufferSize = 0; }
inline void setTimeout(uint32 timeout)
{
timeoutMs.tv_sec = (uint32)timeout / 1024; // Avoid division here (compiler should shift the value here), the value is approximative anyway
timeoutMs.tv_usec = ((uint32)timeout & 1023) * 977; // Avoid modulo here and make sure it doesn't overflow (since 1023 * 977 < 1000000)
}
bool shouldPing()
{
return (((uint32)time(NULL) - lastCommunication) >= keepAlive);
}
bool hasValidLength() const
{
Protocol::MQTT::Common::VBInt l;
return l.readFrom(recvBuffer + 1, available - 1) != Protocol::MQTT::Common::BadData;
}
/** Receive a control packet from the socket in the given time.
@retval positive The number of bytes received
@retval 0 Protocol error, you should close the socket
@retval -1 Socket error
@retval -2 Timeout */
int receiveControlPacket(const bool lowLatency = false)
{
if (!socket) return -1;
// Depending on the current state, we need to fetch as many bytes as possible within the given timeoutMs
// This is a complex problem here because we want both to optimize for
// - latency (returns as fast as possible when we've received a complete packet)
// - blocking time (don't return immediately if the data is currently in transfer, need to wait for it to arrive)
// - minimal syscalls (don't call recv byte per byte as the overhead will be significant)
// - network queue (don't fetch more byte than necessary for getting a single control packet)
// - streaming usage (this can be called while a control packet was being received and we timed out)
// So the algorithm used here depends on the current receiving state
// If we haven't received packet length yet, we have to fetch the header very carefully
// Else, we can enter a more general receiving loop until we have all bytes from the control packet
int ret = 0;
Protocol::MQTT::Common::VBInt len;
#if MQTTLowLatency == 1
// In low latency mode, return as early as possible
if (lowLatency && !socket->select(true, false, true)) return -2;
#endif
// We want to keep track of complete timeout time over multiple operations
switch (recvState)
{
case Ready:
case GotType:
{ // Here, make sure we only fetch the length first
// The minimal size is 2 bytes for PINGRESP and shortcut DISCONNECT / AUTH.
// Because of this, we can't really outsmart the system everytime
ret = socket->recv((char*)&recvBuffer[available], 2 - available);
if (ret > 0) available += ret;
// Deal with timeout first
if (ret < 0 || available < 2)
return (errno == EWOULDBLOCK) ? -2 : -1;
// Depending on the packet type, let's wait for more data
if (recvBuffer[0] < 0xD0 || recvBuffer[1]) // Below ping response or packet size larger than 2 bytes
{
int querySize = (packetExpectedVBSize + 1) - available;
ret = socket->recv((char*)&recvBuffer[available], querySize);
if (ret > 0) available += ret;
// Deal with timeout first
if (ret < 0) return (errno == EWOULDBLOCK) ? -2 : -1;
}
recvState = GotLength;
break;
}
default: break;
}
// Here we should either have a valid control packet header
uint32 r = len.readFrom(&recvBuffer[1], available - 1);
if (r == Protocol::MQTT::Common::BadData)
return 0; // Close the socket here, the given data are wrong or not the right protocol
if (r == Protocol::MQTT::Common::NotEnoughData)
{
if (available >= (packetExpectedVBSize+1))
{ // The server sends us a packet that's larger than the expected maximum size,
// In MQTTv5 it's a protocol error, so let's disconnect
return 0;
}
// We haven't received enough data in the given timeout to make progress, let's report a timeout
recvState = GotType;
return -2;
}
uint32 remainingLength = len;
uint32 totalPacketSize = remainingLength + 1 + len.getSize();
ret = totalPacketSize == available ? 0 : socket->recv((char*)&recvBuffer[available], totalPacketSize - available);
if (ret > 0) available += ret;
if (ret < 0) return (errno == EWOULDBLOCK) ? -2 : -1;
// Ok, let's check if we have received the complete packet
if (available == totalPacketSize)
{
recvState = GotCompletePacket;
#if MQTTDumpCommunication == 1
dumpBufferAsPacket("< Received packet", recvBuffer, available);
#endif
lastCommunication = (uint32)time(NULL);
return (int)available;
}
// No yet, but we probably timed-out.
return -2;
}
/** Get the last received packet type */
Protocol::MQTT::V5::ControlPacketType getLastPacketType() const
{
if (recvState != GotCompletePacket) return Protocol::MQTT::V5::RESERVED;
Protocol::MQTT::V5::FixedHeader header;
header.raw = recvBuffer[0];
return (Protocol::MQTT::V5::ControlPacketType)(uint8)header.type;
}
/** Extract a control packet of the given type */
int extractControlPacket(const Protocol::MQTT::V5::ControlPacketType type, Protocol::MQTT::Common::Serializable & packet)
{
if (recvState != GotCompletePacket)
{
int ret = receiveControlPacket();
if (ret <= 0) return ret;
if (recvState != GotCompletePacket)
return -2;
}
// Check the packet is the last expected type
if (getLastPacketType() != type) return -3;
// Seems to be the expected type, let's unserialize it
uint32 r = packet.readFrom(recvBuffer, recvBufferSize);
if (Protocol::MQTT::Common::isError(r)) return -4; // Parsing error
// Done with receiving the packet let's remember it
resetPacketReceivingState();
#if MQTTDumpCommunication == 1
// String out;
// packet.dump(out, 2);
// printf("Received\n%s\n", (const char*)out);
#endif
return (int)r;
}
void resetPacketReceivingState() { recvState = Ready; available = 0; }
void close()
{
delete0(socket);
}
bool isOpen()
{
return socket;
}
int send(const char * buffer, const int size) { return socket ? socket->send(buffer, size) : -1; }
int connectWith(const char * host, const uint16 port, const bool withTLS)
{
if (isOpen()) return -1;
socket =
#if MQTTUseTLS == 1
withTLS ? new MBTLSSocket(timeoutMs) :
#endif
new BaseSocket(timeoutMs);
return socket ? socket->connect(host, port, brokerCert) : -1;
}
#if MQTTUseAuth == 1
MQTTv5::ErrorType handleAuth()
{
Protocol::MQTT::V5::ROAuthPacket packet;