This repository was archived by the owner on Dec 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathExchangeContext.cpp
More file actions
1684 lines (1477 loc) · 60.6 KB
/
Copy pathExchangeContext.cpp
File metadata and controls
1684 lines (1477 loc) · 60.6 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) 2013-2017 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements the ExchangeContext class.
*
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <stdint.h>
#include <stdlib.h>
#include <Weave/Core/WeaveCore.h>
#include <Weave/Core/WeaveEncoding.h>
#include <Weave/Profiles/WeaveProfiles.h>
#include <Weave/Profiles/common/CommonProfile.h>
#include <Weave/Support/CodeUtils.h>
#include <Weave/Support/FlagUtils.hpp>
#include <Weave/Support/RandUtils.h>
#include <Weave/Support/logging/WeaveLogging.h>
#include <SystemLayer/SystemTimer.h>
#include <Weave/Support/WeaveFaultInjection.h>
#include <SystemLayer/SystemStats.h>
//#include <nestlabs/log/nllog.hpp>
#undef nlLogError
#define nlLogError(MSG, ...)
namespace nl {
namespace Weave {
using namespace nl::Weave::Encoding;
enum {
kFlagInitiator = 0x0001, /// This context is the initiator of the exchange.
kFlagConnectionClosed = 0x0002, /// This context was associated with a WeaveConnection.
kFlagAutoRequestAck = 0x0004, /// When set, automatically request an acknowledgment whenever a message is sent via UDP.
kFlagDropAck = 0x0008, /// Internal and debug only: when set, the exchange layer does not send an acknowledgment.
kFlagResponseExpected = 0x0010, /// If a response is expected for a message that is being sent.
kFlagAckPending = 0x0020, /// When set, signifies that there is an acknowledgment pending to be sent back.
kFlagPeerRequestedAck = 0x0040, /// When set, signifies that at least one message received on this exchange requested an acknowledgment.
/// This flag is read by the application to decide if it needs to request an acknowledgment for the
/// response message it is about to send. This flag can also indicate whether peer is using WRMP.
kFlagMsgRcvdFromPeer = 0x0080, /// When set, signifies that at least one message has been received from peer on this exchange context.
kFlagAutoReleaseKey = 0x0100, /// Automatically release the message encryption key when the exchange context is freed.
kFlagAutoReleaseConnection = 0x0200, /// Automatically release the associated WeaveConnection when the exchange context is freed.
kFlagUseEphemeralUDPPort = 0x0400, /// When set, use the local ephemeral UDP port as the source port for outbound messages.
};
/**
* Determine whether the context is the initiator of the exchange.
*
* @return Returns 'true' if it is the initiator, else 'false'.
*
*/
bool ExchangeContext::IsInitiator(void) const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagInitiator));
}
/**
* Determine whether the ExchangeContext has an associated active WeaveConnection.
*
* @return Returns 'true' if connection is closed, else 'false'.
*/
bool ExchangeContext::IsConnectionClosed(void) const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagConnectionClosed));
}
/**
* Determine whether a response is expected for messages sent over
* this exchange.
*
* @return Returns 'true' if response expected, else 'false'.
*/
bool ExchangeContext::IsResponseExpected(void) const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagResponseExpected));
}
/**
* Set the kFlagInitiator flag bit. This flag is set by the node that
* initiates an exchange.
*
* @param[in] inInitiator A Boolean indicating whether (true) or not
* (false) the context is the initiator of
* the exchange.
*
*/
void ExchangeContext::SetInitiator(bool inInitiator)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagInitiator), inInitiator);
}
/**
* Set the kFlagConnectionClosed flag bit. This flag is set
* when a WeaveConnection associated with an ExchangeContext
* is closed.
*
* @param[in] inConnectionClosed A Boolean indicating whether
* (true) or not (false) the context
* was associated with a connection.
*
*/
void ExchangeContext::SetConnectionClosed(bool inConnectionClosed)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagConnectionClosed), inConnectionClosed);
}
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
/**
* Determine whether there is already an acknowledgment pending to be sent
* to the peer on this exchange.
*
*/
bool ExchangeContext::IsAckPending(void) const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagAckPending));
}
/**
* Determine whether peer requested acknowledgment for at least one message
* on this exchange.
*
* @return Returns 'true' if acknowledgment requested, else 'false'.
*/
bool ExchangeContext::HasPeerRequestedAck(void) const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagPeerRequestedAck));
}
/**
* Determine whether at least one message has been received
* on this exchange from peer.
*
* @return Returns 'true' if message received, else 'false'.
*/
bool ExchangeContext::HasRcvdMsgFromPeer(void) const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagMsgRcvdFromPeer));
}
/**
* Set if a message has been received from the peer
* on this exchange.
*
* @param[in] inMsgRcvdFromPeer A Boolean indicating whether (true) or not
* (false) a message has been received
* from the peer on this exchange context.
*
*/
void ExchangeContext::SetMsgRcvdFromPeer(bool inMsgRcvdFromPeer)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagMsgRcvdFromPeer), inMsgRcvdFromPeer);
}
/**
* Set if an acknowledgment needs to be sent back to the peer on this exchange.
*
* @param[in] inAckPending A Boolean indicating whether (true) or not
* (false) an acknowledgment should be sent back
* in response to a received message.
*
*/
void ExchangeContext::SetAckPending(bool inAckPending)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagAckPending), inAckPending);
}
/**
* Set if an acknowledgment was requested in the last message received
* on this exchange.
*
* @param[in] inPeerRequestedAck A Boolean indicating whether (true) or not
* (false) an acknowledgment was requested
* in the last received message.
*
*/
void ExchangeContext::SetPeerRequestedAck(bool inPeerRequestedAck)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagPeerRequestedAck), inPeerRequestedAck);
}
/**
* Set whether the WeaveExchangeManager should not send acknowledgements
* for this context.
*
* For internal, debug use only.
*
* @param[in] inDropAck A Boolean indicating whether (true) or not
* (false) the acknowledgements should be not
* sent for the exchange.
*
*/
void ExchangeContext::SetDropAck(bool inDropAck)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagDropAck), inDropAck);
}
/**
* Determine whether the WeaveExchangeManager should not send an
* acknowledgement.
*
* For internal, debug use only.
*
*/
bool ExchangeContext::ShouldDropAck(void) const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagDropAck));
}
static inline bool IsWRMPControlMessage(uint32_t profileId, uint8_t msgType)
{
return (profileId == nl::Weave::Profiles::kWeaveProfile_Common &&
(msgType == nl::Weave::Profiles::Common::kMsgType_WRMP_Throttle_Flow ||
msgType == nl::Weave::Profiles::Common::kMsgType_WRMP_Delayed_Delivery));
}
#endif // WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
/**
* Set whether a response is expected on this exchange.
*
* @param[in] inResponseExpected A Boolean indicating whether (true) or not
* (false) a response is expected on this
* exchange.
*
*/
void ExchangeContext::SetResponseExpected(bool inResponseExpected)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagResponseExpected), inResponseExpected);
}
/**
* Returns whether an acknowledgment will be requested whenever a message is sent.
*/
bool ExchangeContext::AutoRequestAck() const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagAutoRequestAck));
}
/**
* Set whether an acknowledgment should be requested whenever a message is sent.
*
* @param[in] autoReqAck A Boolean indicating whether or not an
* acknowledgment should be requested whenever a
* message is sent.
*/
void ExchangeContext::SetAutoRequestAck(bool autoReqAck)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagAutoRequestAck), autoReqAck);
}
/**
* Return whether the encryption key associated with the exchange should be
* released when the exchange is freed.
*/
bool ExchangeContext::GetAutoReleaseKey() const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagAutoReleaseKey));
}
/**
* Set whether the encryption key associated with the exchange should be
* released when the exchange is freed.
*
* @param[in] autoReleaseKey True if the message encryption key should be
* automatically released.
*/
void ExchangeContext::SetAutoReleaseKey(bool autoReleaseKey)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagAutoReleaseKey), autoReleaseKey);
}
/**
* Return whether the Weave connection associated with the exchange should be
* released when the exchange is freed.
*/
bool ExchangeContext::ShouldAutoReleaseConnection() const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagAutoReleaseConnection));
}
/**
* Set whether the Weave connection associated with the exchange should be
* released when the exchange is freed.
*
* @param[in] autoReleaseCon True if the Weave connection should be
* automatically released.
*/
void ExchangeContext::SetShouldAutoReleaseConnection(bool autoReleaseCon)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagAutoReleaseConnection), autoReleaseCon);
}
/**
* @fn bool ExchangeContext::UseEphemeralUDPPort(void) const
*
* Return whether outbound messages sent via the exchange should be sent from
* the local ephemeral UDP port.
*/
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
bool ExchangeContext::UseEphemeralUDPPort(void) const
{
return GetFlag(mFlags, static_cast<uint16_t>(kFlagUseEphemeralUDPPort));
}
#endif // WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
/**
* Set whether outbound messages sent via the exchange should be sent from
* the local ephemeral UDP port.
*/
void ExchangeContext::SetUseEphemeralUDPPort(bool val)
{
SetFlag(mFlags, static_cast<uint16_t>(kFlagUseEphemeralUDPPort), val);
}
#endif // WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
/**
* Send a Weave message on this exchange.
*
* @param[in] profileId The profile identifier of the Weave message to be sent.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @param[in] msgBuf A pointer to the PacketBuffer object holding the Weave message.
*
* @param[in] sendFlags Flags set by the application for the Weave message being sent.
*
* @param[in] msgCtxt A pointer to an application-specific context object to be associated
* with the message being sent.
* @retval #WEAVE_ERROR_INVALID_ARGUMENT if an invalid argument was passed to this SendMessage API.
* @retval #WEAVE_ERROR_SEND_THROTTLED if this exchange context has been throttled when using the
* Weave reliable messaging protocol.
* @retval #WEAVE_ERROR_WRONG_MSG_VERSION_FOR_EXCHANGE if there is a mismatch in the specific send operation and the
* Weave message protocol version that is supported. For example,
* this error would be generated if Weave Reliable Messaging
* semantics are being attempted when the Weave message protocol
* version is V1.
* @retval #WEAVE_ERROR_NOT_CONNECTED if the context was associated with a connection that is now
* closed.
* @retval #WEAVE_ERROR_INCORRECT_STATE if the state of the exchange context is incorrect.
* @retval #WEAVE_NO_ERROR if the Weave layer successfully sent the message down to the
* network layer.
*/
WEAVE_ERROR ExchangeContext::SendMessage(uint32_t profileId, uint8_t msgType, PacketBuffer *msgBuf, uint16_t sendFlags,
void *msgCtxt)
{
// Setup the message info structure.
WeaveMessageInfo msgInfo;
msgInfo.Clear();
msgInfo.SourceNodeId = ExchangeMgr->FabricState->LocalNodeId;
msgInfo.DestNodeId = PeerNodeId;
msgInfo.EncryptionType = EncryptionType;
msgInfo.KeyId = KeyId;
return SendMessage(profileId, msgType, msgBuf, sendFlags, &msgInfo, msgCtxt);
}
/**
* Send a Weave message on this exchange.
*
* @param[in] profileId The profile identifier of the Weave message to be sent.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @param[in] msgBuf A pointer to the PacketBuffer object holding the Weave message.
*
* @param[in] sendFlags Flags set by the application for the Weave message being sent.
*
* @param[in] msgInfo A pointer to the WeaveMessageInfo object.
*
* @param[in] msgCtxt A pointer to an application-specific context object to be
* associated with the message being sent.
*
* @retval #WEAVE_ERROR_INVALID_ARGUMENT if an invalid argument was passed to this SendMessage API.
* @retval #WEAVE_ERROR_SEND_THROTTLED if this exchange context has been throttled when using the
* Weave reliable messaging protocol.
* @retval #WEAVE_ERROR_WRONG_MSG_VERSION_FOR_EXCHANGE if there is a mismatch in the specific send operation and the
* Weave message protocol version that is supported. For example,
* this error would be generated if Weave Reliable Messaging
* semantics are being attempted when the Weave message protocol
* version is V1.
* @retval #WEAVE_ERROR_NOT_CONNECTED if the context was associated with a connection that is now
* closed.
* @retval #WEAVE_ERROR_INCORRECT_STATE if the state of the exchange context is incorrect.
* @retval #WEAVE_NO_ERROR if the Weave layer successfully sent the message down to the
* network layer.
*/
WEAVE_ERROR ExchangeContext::SendMessage(uint32_t profileId, uint8_t msgType, PacketBuffer *msgBuf, uint16_t sendFlags,
WeaveMessageInfo * msgInfo, void *msgCtxt)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
bool sendCalled = false;
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
WeaveExchangeManager::RetransTableEntry *entry = NULL;
#endif
#if WEAVE_RETAIN_LOGGING
uint16_t payloadLen = msgBuf->DataLength();
#endif
// Don't let method get called on a freed object.
VerifyOrDie(ExchangeMgr != NULL && mRefCount != 0);
// we hold the exchange context here in case the entity that
// originally generated it tries to close it as a result of
// an error arising below. at the end, we have to close it.
AddRef();
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// If sending via UDP and the auto-request ACK feature is enabled, automatically
// request an acknowledgment, UNLESS the NoAutoRequestAck send flag has been specified.
if (Con == NULL && (mFlags & kFlagAutoRequestAck) != 0 && (sendFlags & kSendFlag_NoAutoRequestAck) == 0)
{
sendFlags |= kSendFlag_RequestAck;
}
// Do not allow WRM to be used over a TCP connection
if ((sendFlags & kSendFlag_RequestAck) && Con != NULL)
{
ExitNow(err = WEAVE_ERROR_INVALID_ARGUMENT);
}
// Abort early if Throttle is already set;
VerifyOrExit(mWRMPThrottleTimeout == 0, err = WEAVE_ERROR_SEND_THROTTLED);
#else // WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// If WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING == 0, then
// kSendFlag_RequestAck should not be set.
if (sendFlags & kSendFlag_RequestAck)
{
ExitNow(err = WEAVE_ERROR_INVALID_ARGUMENT);
}
#endif // WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// Set the Message Protocol Version
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
if (sendFlags & kSendFlag_RequestAck || IsWRMPControlMessage(profileId, msgType) ||
(profileId == nl::Weave::Profiles::kWeaveProfile_Common &&
msgType == nl::Weave::Profiles::Common::kMsgType_Null))
{
if (kWeaveMessageVersion_Unspecified == mMsgProtocolVersion)
{
mMsgProtocolVersion = msgInfo->MessageVersion = kWeaveMessageVersion_V2;
}
else
{
VerifyOrExit(mMsgProtocolVersion == kWeaveMessageVersion_V2, err = WEAVE_ERROR_WRONG_MSG_VERSION_FOR_EXCHANGE);
}
}
#endif
if (kWeaveMessageVersion_Unspecified == mMsgProtocolVersion)
{
mMsgProtocolVersion = msgInfo->MessageVersion = kWeaveMessageVersion_V1;
}
else
{
msgInfo->MessageVersion = mMsgProtocolVersion;
}
// Prevent sending if the context was associated with a connection that is now closed.
VerifyOrExit(!IsConnectionClosed(), err = WEAVE_ERROR_NOT_CONNECTED);
// TODO: implement support for retransmissions.
// flag validation
if (sendFlags & kSendFlag_RetransmissionTrickle)
{
//We do not allow WRM to be used when Trickle retransmission is requested
if (sendFlags & kSendFlag_RequestAck)
{
ExitNow(err = WEAVE_ERROR_INVALID_ARGUMENT);
}
// We do not support trickle retrasnmissions over
// connection-oriented exchanges
VerifyOrExit(Con == NULL, err=WEAVE_ERROR_INVALID_ARGUMENT);
if (0 == RetransInterval)
{ // we're not retransmitting, do not hold onto the buffer
sendFlags &= ~kSendFlag_RetainBuffer;
}
else
{
sendFlags |= kSendFlag_RetainBuffer;
msg = msgBuf;
}
}
// Add the exchange header to the message buffer.
WeaveExchangeHeader exchangeHeader;
memset(&exchangeHeader, 0, sizeof(exchangeHeader));
err = EncodeExchHeader(&exchangeHeader, profileId, msgType, msgBuf, sendFlags);
SuccessOrExit(err);
// If a response message is expected...
if ((sendFlags & kSendFlag_ExpectResponse) != 0)
{
// Only one 'response expected' message can be outstanding at a time.
VerifyOrExit(!IsResponseExpected(), err = WEAVE_ERROR_INCORRECT_STATE);
SetResponseExpected(true);
// Arm the response timer if a timeout has been specified.
if (ResponseTimeout > 0)
{
err = StartResponseTimer();
SuccessOrExit(err);
}
}
//Fill in appropriate message header flags
if (sendFlags & kSendFlag_DelaySend)
msgInfo->Flags |= kWeaveMessageFlag_DelaySend;
//FIXME: RS: possibly unnecessary, should addref instead
if (sendFlags & kSendFlag_RetainBuffer)
msgInfo->Flags |= kWeaveMessageFlag_RetainBuffer;
if (sendFlags & kSendFlag_AlreadyEncoded)
msgInfo->Flags |= kWeaveMessageFlag_MessageEncoded;
if (sendFlags & kSendFlag_ReuseMessageId)
msgInfo->Flags |= kWeaveMessageFlag_ReuseMessageId;
if (sendFlags & kSendFlag_ReuseSourceId)
msgInfo->Flags |= kWeaveMessageFlag_ReuseSourceId;
if (sendFlags & kSendFlag_DefaultMulticastSourceAddress)
msgInfo->Flags |= kWeaveMessageFlag_DefaultMulticastSourceAddress;
SetFlag(msgInfo->Flags, kWeaveMessageFlag_FromInitiator, IsInitiator());
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
SetFlag(msgInfo->Flags, kWeaveMessageFlag_ViaEphemeralUDPPort, UseEphemeralUDPPort());
#endif // WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
// Send the message via UDP or TCP/BLE based on the presence of a connection.
if (Con != NULL)
{
// Hook the message received callback on the connection so that the WeaveExchangeManager gets
// called when messages arrive.
Con->OnMessageReceived = WeaveExchangeManager::HandleMessageReceived;
err = Con->SendMessage(msgInfo, msgBuf);
msgBuf = NULL;
sendCalled = true;
}
else
{
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
if (sendFlags & kSendFlag_RequestAck)
{
err = ExchangeMgr->MessageLayer->SelectDestNodeIdAndAddress(msgInfo->DestNodeId, PeerAddr);
SuccessOrExit(err);
err = ExchangeMgr->MessageLayer->EncodeMessage(PeerAddr, PeerPort, PeerIntf,
msgInfo, msgBuf);
SuccessOrExit(err);
// Copy msg to a right-sized buffer if applicable
msgBuf = PacketBuffer::RightSize(msgBuf);
//Add to Table for subsequent sending
err = ExchangeMgr->AddToRetransTable(this, msgBuf, msgInfo->MessageId, msgCtxt, &entry);
SuccessOrExit(err);
msgBuf = NULL;
err = ExchangeMgr->SendFromRetransTable(entry);
sendCalled = true;
SuccessOrExit(err);
WEAVE_FAULT_INJECT(FaultInjection::kFault_WRMDoubleTx,
entry->nextRetransTime = 0;
ExchangeMgr->WRMPStartTimer()
);
}
else
#endif // WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
{
err = ExchangeMgr->MessageLayer->SendMessage(PeerAddr, PeerPort, PeerIntf,
msgInfo, msgBuf);
msgBuf = NULL;
sendCalled = true;
SuccessOrExit(err);
}
if (sendFlags & kSendFlag_RetransmissionTrickle)
{
currentBcastMsgID = msgInfo->MessageId;
if (RetransInterval != 0)
{
if (StartTimerT() != WEAVE_NO_ERROR)
{
nlLogError("EC: cant start T\n");
}
}
}
}
exit:
if (sendCalled)
{
if(!nl::Weave::Platform::IsProfileSilenced(static_cast<nl::Weave::Profiles::WeaveProfileId>(profileId)))
{
WeaveLogRetain(ExchangeManager, "Msg %s %08" PRIX32 ":%d %d %016" PRIX64 " %04" PRIX16 " %04" PRIX16 " %ld MsgId:%08" PRIX32,
"sent", profileId, msgType, (int)payloadLen, msgInfo->DestNodeId,
(Con ? Con->LogId() : 0), ExchangeId, (long)err, msgInfo->MessageId);
}
}
if (err != WEAVE_NO_ERROR && IsResponseExpected())
{
CancelResponseTimer();
SetResponseExpected(false);
}
if (msgBuf != NULL && (sendFlags & kSendFlag_RetainBuffer) == 0)
{
PacketBuffer::Free(msgBuf);
if (msg == msgBuf)
msg = NULL;
}
//Release the reference to the exchange context acquired above. Under normal circumstances
//this will merely decrement the reference count, without actually freeing the exchange context.
//However if one of the function calls in this method resulted in a callback to the application,
//the application may have released its reference, resulting in the exchange context actually
//being freed here.
Release();
return err;
}
/**
* Send a Common::Null message.
*
* @note When sent via UDP, the null message is sent *without* requesting an acknowledgment,
* even in the case where the auto-request acknowledgment feature has been enabled on the
* exchange.
*
* @retval #WEAVE_ERROR_NO_MEMORY If no available PacketBuffers.
* @retval #WEAVE_NO_ERROR If the method succeeded or the error wasn't critical.
* @retval other Another critical error returned by SendMessage().
*
*/
WEAVE_ERROR ExchangeContext::SendCommonNullMessage(void)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
PacketBuffer *msgBuf = NULL;
// Allocate a buffer for the null message
msgBuf = PacketBuffer::NewWithAvailableSize(0);
VerifyOrExit(msgBuf != NULL, err = WEAVE_ERROR_NO_MEMORY);
// Send the null message
err = SendMessage(nl::Weave::Profiles::kWeaveProfile_Common,
nl::Weave::Profiles::Common::kMsgType_Null, msgBuf,
kSendFlag_NoAutoRequestAck);
msgBuf = NULL;
exit:
if (WeaveMessageLayer::IsSendErrorNonCritical(err))
{
WeaveLogError(ExchangeManager, "Non-crit err %ld sending solitary ack",
long(err));
err = WEAVE_NO_ERROR;
}
if (err != WEAVE_NO_ERROR)
{
WeaveLogError(ExchangeManager, "Failed to send Solitary ack for MsgId:%08" PRIX32 " to Peer %016" PRIX64 ":%ld",
mPendingPeerAckId, PeerNodeId, (long)err);
}
return err;
}
/**
* Encode the exchange header into a message buffer.
*
* @param[in] exchangeHeader A pointer to the Weave Exchange header object.
*
* @param[in] profileId The profile identifier of the Weave message to be sent.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @param[in] msgBuf A pointer to the PacketBuffer needed for the Weave message.
*
* @param[in] sendFlags Flags set by the application for the Weave message being sent.
*
*
* @retval #WEAVE_ERROR_BUFFER_TOO_SMALL If the message buffer does not have sufficient space
* for encoding the exchange header.
* @retval #WEAVE_NO_ERROR If encoding of the message was successful.
*/
WEAVE_ERROR ExchangeContext::EncodeExchHeader(WeaveExchangeHeader *exchangeHeader, uint32_t profileId, uint8_t msgType,
PacketBuffer *msgBuf, uint16_t sendFlags)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
// Fill the exchange header to the message buffer.
exchangeHeader->Version = kWeaveExchangeVersion_V1;
exchangeHeader->ExchangeId = ExchangeId;
exchangeHeader->ProfileId = profileId;
exchangeHeader->MessageType = msgType;
// sendFlags under special circumstances (such as a retransmission
// of the remote alarm) can override the initiator flag in the
// exchange header. The semantics here really is: use the
// ExchangeId in the namespace of the SourceNodeId
exchangeHeader->Flags = (IsInitiator() || (sendFlags & kSendFlag_FromInitiator)) ? kWeaveExchangeFlag_Initiator : 0;
// WRMP PreProcess Checks and Flag setting
if (mMsgProtocolVersion == kWeaveMessageVersion_V2)
{
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
//If there is a pending acknowledgment piggyback it on this message.
//If there is no pending acknowledgment piggyback the last Ack that was sent.
// - HasPeerRequestedAck() is used to verify that AckId field is valid
// to avoid piggybacking uninitialized AckId.
if (HasPeerRequestedAck())
{
// Expire any virtual ticks that have expired so all wakeup sources reflect the current time
ExchangeMgr->WRMPExpireTicks();
exchangeHeader->Flags |= kWeaveExchangeFlag_AckId;
exchangeHeader->AckMsgId = mPendingPeerAckId;
//Set AckPending flag to false after setting the Ack flag;
SetAckPending(false);
// Schedule next physical wakeup
ExchangeMgr->WRMPStartTimer();
#if defined(DEBUG)
WeaveLogProgress(ExchangeManager, "Piggybacking Ack for MsgId:%08" PRIX32 " with msg",
mPendingPeerAckId);
#endif
}
//Assert the flag if message requires an Ack back;
if ((sendFlags & kSendFlag_RequestAck) && !IsWRMPControlMessage(profileId, msgType))
{
exchangeHeader->Flags |= kWeaveExchangeFlag_NeedsAck;
}
#endif // WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
}
err = WeaveExchangeManager::PrependHeader(exchangeHeader, msgBuf);
return err;
}
/**
* Cancel the Trickle retransmission mechanism.
*
*/
void ExchangeContext::CancelRetrans()
{
// NOTE: modify for other retransmission schemes
TeardownTrickleRetransmit();
}
/**
* Increment the reference counter for the exchange context by one.
*
*/
void ExchangeContext::AddRef()
{
mRefCount++;
#if defined(WEAVE_EXCHANGE_CONTEXT_DETAIL_LOGGING)
WeaveLogProgress(ExchangeManager, "ec id: %d [%04" PRIX16 "], refCount++: %d", EXCHANGE_CONTEXT_ID(this - ExchangeMgr->ContextPool), ExchangeId, mRefCount);
#endif
}
void ExchangeContext::DoClose(bool clearRetransTable)
{
// Clear app callbacks
OnMessageReceived = NULL;
OnResponseTimeout = NULL;
OnRetransmissionTimeout = NULL;
OnConnectionClosed = NULL;
OnKeyError = NULL;
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// Expire any virtual ticks that have expired so all wakeup sources reflect the current time
ExchangeMgr->WRMPExpireTicks();
OnThrottleRcvd = NULL;
OnDDRcvd = NULL;
OnSendError = NULL;
OnAckRcvd = NULL;
// Flush any pending WRM acks
WRMPFlushAcks();
// Clear the WRM retransmission table
if (clearRetransTable)
{
ExchangeMgr->ClearRetransmitTable(this);
}
// Schedule next physical wakeup
ExchangeMgr->WRMPStartTimer();
#endif
// Cancel the trickle retransmission timer.
CancelRetrans();
// Cancel the response timer.
CancelResponseTimer();
}
/**
* Gracefully close an exchange context. This call decrements the
* reference count and releases the exchange when the reference
* count goes to zero.
*
*/
void ExchangeContext::Close()
{
VerifyOrDie(ExchangeMgr != NULL && mRefCount != 0);
#if defined(WEAVE_EXCHANGE_CONTEXT_DETAIL_LOGGING)
WeaveLogProgress(ExchangeManager, "ec id: %d [%04" PRIX16 "], %s", EXCHANGE_CONTEXT_ID(this - ExchangeMgr->ContextPool), ExchangeId, __func__);
#endif
DoClose(false);
Release();
}
/**
* Abort the Exchange context immediately and release all
* references to it.
*
*/
void ExchangeContext::Abort()
{
VerifyOrDie(ExchangeMgr != NULL && mRefCount != 0);
#if defined(WEAVE_EXCHANGE_CONTEXT_DETAIL_LOGGING)
WeaveLogProgress(ExchangeManager, "ec id: %d [%04" PRIX16 "], %s", EXCHANGE_CONTEXT_ID(this - ExchangeMgr->ContextPool), ExchangeId, __func__);
#endif
DoClose(true);
Release();
}
/**
* Release reference to this exchange context. If count is down
* to one then close the context, reset all application callbacks,
* and stop all timers.
*
*/
void ExchangeContext::Release(void)
{
VerifyOrDie(ExchangeMgr != NULL && mRefCount != 0);
if (mRefCount == 1)
{
//Ideally, in this scenario, the retransmit table should
//be clear of any outstanding messages for this context and
//the boolean parameter passed to DoClose() should not matter.
WeaveExchangeManager *em = ExchangeMgr;
#if defined(WEAVE_EXCHANGE_CONTEXT_DETAIL_LOGGING)
uint16_t tmpid = ExchangeId;
#endif
// If so configured, automatically release any reservation held on
// the message encryption key.
if (GetAutoReleaseKey())
{
em->MessageLayer->SecurityMgr->ReleaseKey(PeerNodeId, KeyId);
}
// If configured, automatically release a reference to the WeaveConnection object.
if (ShouldAutoReleaseConnection() && Con != NULL)
{
SetShouldAutoReleaseConnection(false);
Con->Release();
}
DoClose(false);
mRefCount = 0;
ExchangeMgr = NULL;
em->mContextsInUse--;
em->MessageLayer->SignalMessageLayerActivityChanged();
#if defined(WEAVE_EXCHANGE_CONTEXT_DETAIL_LOGGING)
WeaveLogProgress(ExchangeManager, "ec-- id: %d [%04" PRIX16 "], inUse: %d, addr: 0x%x", EXCHANGE_CONTEXT_ID(this - em->ContextPool), tmpid, em->mContextsInUse, this);
#endif
SYSTEM_STATS_DECREMENT(nl::Weave::System::Stats::kExchangeMgr_NumContexts);
}
else
{
mRefCount--;
#if defined(WEAVE_EXCHANGE_CONTEXT_DETAIL_LOGGING)
WeaveLogProgress(ExchangeManager, "ec id: %d [%04" PRIX16 "], refCount--: %d", EXCHANGE_CONTEXT_ID(this - ExchangeMgr->ContextPool), ExchangeId, mRefCount);
#endif
}
}
WEAVE_ERROR ExchangeContext::ResendMessage()
{
WeaveMessageInfo msgInfo;
WEAVE_ERROR res;
uint8_t * payload;
if (msg == NULL)
{
return WEAVE_ERROR_INCORRECT_STATE;
}
msgInfo.Clear();
msgInfo.MessageVersion = mMsgProtocolVersion;
msgInfo.SourceNodeId = ExchangeMgr->FabricState->LocalNodeId;
msgInfo.EncryptionType = EncryptionType;
msgInfo.KeyId = KeyId;
msgInfo.DestNodeId = PeerNodeId;
res = ExchangeMgr->MessageLayer->DecodeHeader(msg, &msgInfo, &payload);
if (res != WEAVE_NO_ERROR)
return WEAVE_ERROR_INCORRECT_STATE;
msgInfo.Flags |=
kWeaveMessageFlag_RetainBuffer |
kWeaveMessageFlag_MessageEncoded |
kWeaveMessageFlag_ReuseMessageId |
kWeaveMessageFlag_ReuseSourceId;
return ExchangeMgr->MessageLayer->ResendMessage(PeerAddr, PeerPort, PeerIntf, &msgInfo, msg);
}
/**
* Start the Trickle rebroadcast algorithm's periodic retransmission timer mechanism.
*
* @return #WEAVE_NO_ERROR if successful, else an INET_ERROR mapped into a WEAVE_ERROR.
*
*/
WEAVE_ERROR ExchangeContext::StartTimerT()
{
if (RetransInterval == 0)
{
return WEAVE_NO_ERROR;
}
// range from 1 to RetransInterval
backoff = 1 + (GetRandU32() % (RetransInterval-1));
msgsReceived = 0;
WeaveLogDetail(ExchangeManager, "Trickle new interval");
return ExchangeMgr->MessageLayer->SystemLayer->StartTimer(backoff, TimerTau, this);
}
void ExchangeContext::TimerT(System::Layer* aSystemLayer, void* aAppState, System::Error aError)
{
ExchangeContext* client = reinterpret_cast<ExchangeContext*>(aAppState);
if ( (aSystemLayer == NULL) || (aAppState == NULL) || (aError != WEAVE_SYSTEM_NO_ERROR))
{
return;
}
if (client->StartTimerT() != WEAVE_NO_ERROR)
{
nlLogError("EC: cant start T\n");
}
}
void ExchangeContext::TimerTau(System::Layer* aSystemLayer, void* aAppState, System::Error aError)
{
ExchangeContext* ec = reinterpret_cast<ExchangeContext*>(aAppState);
if ( (aSystemLayer == NULL) || (aAppState == NULL) || (aError != WEAVE_SYSTEM_NO_ERROR))
{
return;
}
if (ec->msgsReceived < ec->rebroadcastThreshold)