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 pathWeaveExchangeMgr.cpp
More file actions
1895 lines (1663 loc) · 69.2 KB
/
Copy pathWeaveExchangeMgr.cpp
File metadata and controls
1895 lines (1663 loc) · 69.2 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 WeaveExchangeManager class.
*
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <Weave/Core/WeaveCore.h>
#include <Weave/Profiles/WeaveProfiles.h>
#include <Weave/Profiles/common/CommonProfile.h>
#include <Weave/Profiles/security/WeaveSecurity.h>
#include <Weave/Core/WeaveEncoding.h>
#include <Weave/Support/CodeUtils.h>
#include <Weave/Support/RandUtils.h>
#include <Weave/Support/logging/WeaveLogging.h>
#include <Weave/Support/WeaveFaultInjection.h>
#include <SystemLayer/SystemTimer.h>
#include <SystemLayer/SystemStats.h>
namespace nl {
namespace Weave {
using namespace nl::Weave::Profiles;
using namespace nl::Weave::Encoding;
/**
* Constructor for the WeaveExchangeManager class.
* It sets the state to kState_NotInitialized.
*
* @note
* The class must be initialized via WeaveExchangeManager::Init()
* prior to use.
*
*/
WeaveExchangeManager::WeaveExchangeManager()
{
State = kState_NotInitialized;
}
/**
* Initialize the WeaveExchangeManager object. Within the lifetime
* of this instance, this method is invoked once after object
* construction until a call to Shutdown is made to terminate the
* instance.
*
* @param[in] msgLayer A pointer to the WeaveMessageLayer object.
*
* @retval #WEAVE_ERROR_INCORRECT_STATE If the state is not equal to
* kState_NotInitialized.
* @retval #WEAVE_NO_ERROR On success.
*
*/
WEAVE_ERROR WeaveExchangeManager::Init(WeaveMessageLayer *msgLayer)
{
if (State != kState_NotInitialized)
return WEAVE_ERROR_INCORRECT_STATE;
MessageLayer = msgLayer;
FabricState = msgLayer->FabricState;
NextExchangeId = GetRandU16();
memset(ContextPool, 0, sizeof(ContextPool));
mContextsInUse = 0;
InitBindingPool();
memset(UMHandlerPool, 0, sizeof(UMHandlerPool));
OnExchangeContextChanged = NULL;
msgLayer->ExchangeMgr = this;
msgLayer->OnMessageReceived = HandleMessageReceived;
msgLayer->OnAcceptError = HandleAcceptError;
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
mWRMPTimerInterval = WEAVE_CONFIG_WRMP_TIMER_DEFAULT_PERIOD; //WRMP Timer tick period
memset(RetransTable, 0, sizeof(RetransTable));
mWRMPTimeStampBase = System::Timer::GetCurrentEpoch();
mWRMPCurrentTimerExpiry = 0;
#endif
State = kState_Initialized;
return WEAVE_NO_ERROR;
}
/**
* Shutdown the WeaveExchangeManager. This terminates this instance
* of the object and releases all held resources.
*
* @note
* The application should only call this function after ensuring that
* there are no active ExchangeContext objects. Furthermore, it is the
* onus of the application to de-allocate the WeaveExchangeManager
* object after calling WeaveExchangeManager::Shutdown().
*
* @return #WEAVE_NO_ERROR unconditionally.
*
*/
WEAVE_ERROR WeaveExchangeManager::Shutdown()
{
if (MessageLayer != NULL)
{
if (MessageLayer->ExchangeMgr == this)
{
MessageLayer->ExchangeMgr = NULL;
MessageLayer->OnMessageReceived = NULL;
MessageLayer->OnAcceptError = NULL;
}
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
WRMPStopTimer();
//Clear the retransmit table
for (int i = 0; i < WEAVE_CONFIG_WRMP_RETRANS_TABLE_SIZE; i++)
{
ClearRetransmitTable(RetransTable[i]);
}
#endif
MessageLayer = NULL;
}
OnExchangeContextChanged = NULL;
FabricState = NULL;
State = kState_NotInitialized;
return WEAVE_NO_ERROR;
}
/**
* Creates a new ExchangeContext with a given peer Weave node specified by the peer node identifier.
*
* @param[in] peerNodeId The node identifier of the peer with which the ExchangeContext is being set up.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @return A pointer to the created ExchangeContext object On success. Otherwise NULL if no object
* can be allocated or is available.
*
*/
ExchangeContext *WeaveExchangeManager::NewContext(const uint64_t &peerNodeId, void *appState)
{
return NewContext(peerNodeId, FabricState->SelectNodeAddress(peerNodeId), WEAVE_PORT, INET_NULL_INTERFACEID, appState);
}
/**
* Creates a new ExchangeContext with a given peer Weave node specified by the peer node identifier
* and peer IP address.
*
* @param[in] peerNodeId The node identifier of the peer with which the ExchangeContext is being set up.
*
* @param[in] peerAddr The IP address of the peer node.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @return A pointer to the created ExchangeContext object On success. Otherwise, NULL if no object
* can be allocated or is available.
*
*/
ExchangeContext *WeaveExchangeManager::NewContext(const uint64_t &peerNodeId, const IPAddress &peerAddr, void *appState)
{
return NewContext(peerNodeId, peerAddr, WEAVE_PORT, INET_NULL_INTERFACEID, appState);
}
/**
* Creates a new ExchangeContext with a given peer Weave node specified by the peer node identifier, peer IP address,
* and destination port on a specified interface.
*
* @param[in] peerNodeId The node identifier of the peer with which the ExchangeContext is being set up.
*
* @param[in] peerAddr The IP address of the peer node.
*
* @param[in] peerPort The port of the peer node.
*
* @param[in] sendIntfId The interface to use for sending Weave messages on this exchange.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @return A pointer to the created ExchangeContext object On success. Otherwise, NULL if no object
* can be allocated or is available.
*
*/
ExchangeContext *WeaveExchangeManager::NewContext(const uint64_t &peerNodeId, const IPAddress &peerAddr, uint16_t peerPort, InterfaceId sendIntfId, void *appState)
{
ExchangeContext *ec = AllocContext();
if (ec != NULL)
{
ec->ExchangeId = NextExchangeId++;
ec->PeerNodeId = peerNodeId;
ec->PeerAddr = peerAddr;
ec->PeerPort = (peerPort != 0) ? peerPort : WEAVE_PORT;
ec->PeerIntf = sendIntfId;
ec->AppState = appState;
ec->SetInitiator(true);
//Initialize WRMP variables
ec->mMsgProtocolVersion = 0;
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// No need to set WRMP timer, this will be done when we add to retrans table
ec->mWRMPNextAckTime = 0;
ec->SetAckPending(false);
ec->SetMsgRcvdFromPeer(false);
ec->mWRMPConfig = gDefaultWRMPConfig;
ec->mWRMPThrottleTimeout = 0;
//Internal and for Debug Only; When set, Exchange Layer does not send Ack.
ec->SetDropAck(false);
//Initialize the App callbacks to NULL
ec->OnThrottleRcvd = NULL;
ec->OnDDRcvd = NULL;
ec->OnAckRcvd = NULL;
ec->OnSendError = NULL;
#endif
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
ec->SetUseEphemeralUDPPort(MessageLayer->EphemeralUDPPortEnabled());
#endif // WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
WeaveLogProgress(ExchangeManager, "ec id: %d, AppState: 0x%x", EXCHANGE_CONTEXT_ID(ec - ContextPool), ec->AppState);
}
return ec;
}
/**
* Creates a new ExchangeContext with a given peer Weave node over a specified WeaveConnection.
*
* @param[in] con A pointer to the WeaveConnection object representing the TCP connection
* with the peer.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @return A pointer to the created ExchangeContext object On success. Otherwise, NULL if no object
* can be allocated or is available.
*
*/
ExchangeContext *WeaveExchangeManager::NewContext(WeaveConnection *con, void *appState)
{
ExchangeContext *ec = NewContext(con->PeerNodeId, con->PeerAddr, con->PeerPort, INET_NULL_INTERFACEID, appState);
if (ec != NULL)
{
ec->Con = con;
ec->KeyId = con->DefaultKeyId;
ec->EncryptionType = con->DefaultEncryptionType;
}
return ec;
}
/**
* Find the ExchangeContext from a pool matching a given set of parameters.
*
* @param[in] peerNodeId The node identifier of the peer with which the ExchangeContext has been set up.
*
* @param[in] con A pointer to the WeaveConnection object representing the TCP connection
* with the peer.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @param[in] isInitiator Boolean indicator of whether the local node is the initiator of the exchange.
*
* @return A pointer to the ExchangeContext object matching the provided parameters On success, NULL on no match.
*
*/
ExchangeContext *WeaveExchangeManager::FindContext(uint64_t peerNodeId, WeaveConnection *con, void *appState, bool isInitiator)
{
ExchangeContext *ec = (ExchangeContext *) ContextPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_EXCHANGE_CONTEXTS; i++, ec++)
if (ec->ExchangeMgr != NULL && ec->PeerNodeId == peerNodeId &&
ec->Con == con && ec->AppState == appState &&
ec->IsInitiator() == isInitiator)
return ec;
return NULL;
}
/**
* Register an unsolicited message handler for a given profile identifier. This handler would be
* invoked for all messages of the given profile.
*
* @param[in] profileId The profile identifier of the received message.
*
* @param[in] handler The unsolicited message handler.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @retval #WEAVE_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If the unsolicited message handler pool
* is full and a new one cannot be allocated.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::RegisterUnsolicitedMessageHandler(uint32_t profileId,
ExchangeContext::MessageReceiveFunct handler, void *appState)
{
return RegisterUMH(profileId, (int16_t) -1, NULL, false, handler, appState);
}
/**
* Register an unsolicited message handler for a given profile identifier. This handler would be invoked for all messages of the given profile.
*
* @param[in] profileId The profile identifier of the received message.
*
* @param[in] handler The unsolicited message handler.
*
* @param[in] allowDups Boolean indicator of whether duplicate messages are allowed for a given profile.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @retval #WEAVE_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If the unsolicited message handler pool
* is full and a new one cannot be allocated.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::RegisterUnsolicitedMessageHandler(uint32_t profileId,
ExchangeContext::MessageReceiveFunct handler, bool allowDups, void *appState)
{
return RegisterUMH(profileId, (int16_t) -1, NULL, allowDups, handler, appState);
}
/**
* Register an unsolicited message handler for a given profile identifier and message type.
*
* @param[in] profileId The profile identifier of the received message.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @param[in] handler The unsolicited message handler.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @retval #WEAVE_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If the unsolicited message handler pool
* is full and a new one cannot be allocated.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::RegisterUnsolicitedMessageHandler(uint32_t profileId, uint8_t msgType,
ExchangeContext::MessageReceiveFunct handler, void *appState)
{
return RegisterUMH(profileId, (int16_t) msgType, NULL, false, handler, appState);
}
/**
* Register an unsolicited message handler for a given profile identifier and message type.
*
* @param[in] profileId The profile identifier of the received message.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @param[in] handler The unsolicited message handler.
*
* @param[in] allowDups Boolean indicator of whether duplicate messages are allowed for a given
* profile identifier and message type.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @retval #WEAVE_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If the unsolicited message handler pool
* is full and a new one cannot be allocated.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::RegisterUnsolicitedMessageHandler(uint32_t profileId, uint8_t msgType,
ExchangeContext::MessageReceiveFunct handler, bool allowDups, void *appState)
{
return RegisterUMH(profileId, (int16_t) msgType, NULL, allowDups, handler, appState);
}
/**
* Register an unsolicited message handler for a given profile identifier, message type on a specified Weave
* connection.
*
* @param[in] profileId The profile identifier of the received message.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @param[in] con A pointer to the WeaveConnection object representing the TCP connection
* with the peer.
*
* @param[in] handler The unsolicited message handler.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @retval #WEAVE_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If the unsolicited message handler pool
* is full and a new one cannot be allocated.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::RegisterUnsolicitedMessageHandler(uint32_t profileId, uint8_t msgType, WeaveConnection *con,
ExchangeContext::MessageReceiveFunct handler, void *appState)
{
return RegisterUMH(profileId, (int16_t) msgType, con, false, handler, appState);
}
/**
* Register an unsolicited message handler for a given profile identifier, message type on a specified Weave
* connection.
*
* @param[in] profileId The profile identifier of the received message.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @param[in] con A pointer to the WeaveConnection object representing the TCP connection
* with the peer.
*
* @param[in] handler The unsolicited message handler.
*
* @param[in] allowDups Boolean indicator of whether duplicate messages are allowed for a given
* profile identifier, message type on a specified Weave connection.
*
* @param[in] appState A pointer to a higher layer object that holds context state.
*
* @retval #WEAVE_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If the unsolicited message handler pool
* is full and a new one cannot be allocated.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::RegisterUnsolicitedMessageHandler(uint32_t profileId, uint8_t msgType, WeaveConnection *con,
ExchangeContext::MessageReceiveFunct handler, bool allowDups, void *appState)
{
return RegisterUMH(profileId, (int16_t) msgType, con, allowDups, handler, appState);
}
/**
* Unregister an unsolicited message handler for a given profile identifier.
*
* @param[in] profileId The profile identifier of the received message.
*
* @retval #WEAVE_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER If the matching unsolicited message handler
* is not found.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::UnregisterUnsolicitedMessageHandler(uint32_t profileId)
{
return UnregisterUMH(profileId, (int16_t) -1, NULL);
}
/**
* Unregister an unsolicited message handler for a given profile identifier and message type.
*
* @param[in] profileId The profile identifier of the received message.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @retval #WEAVE_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER If the matching unsolicited message handler
* is not found.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::UnregisterUnsolicitedMessageHandler(uint32_t profileId, uint8_t msgType)
{
return UnregisterUMH(profileId, (int16_t) msgType, NULL);
}
/**
* Unregister an unsolicited message handler for a given profile identifier, message type, and Weave connection.
*
* @param[in] profileId The profile identifier of the received message.
*
* @param[in] msgType The message type of the corresponding profile.
*
* @param[in] con A pointer to the WeaveConnection object representing the TCP connection
* with the peer.
*
* @retval #WEAVE_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER If the matching unsolicited message handler
* is not found.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveExchangeManager::UnregisterUnsolicitedMessageHandler(uint32_t profileId, uint8_t msgType, WeaveConnection *con)
{
return UnregisterUMH(profileId, (int16_t) msgType, con);
}
void WeaveExchangeManager::HandleAcceptError(WeaveMessageLayer *msgLayer, WEAVE_ERROR err)
{
WeaveLogError(ExchangeManager, "Accept FAILED, err = %s", ErrorStr(err));
}
void WeaveExchangeManager::HandleConnectionReceived(WeaveConnection *con)
{
// Hook the OnMessageReceived callback for new inbound connections.
con->OnMessageReceived = HandleMessageReceived;
}
void WeaveExchangeManager::HandleConnectionClosed(WeaveConnection *con, WEAVE_ERROR conErr)
{
for (int i = 0; i < WEAVE_CONFIG_MAX_BINDINGS; i++)
{
BindingPool[i].OnConnectionClosed(con, conErr);
}
ExchangeContext *ec = (ExchangeContext *) ContextPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_EXCHANGE_CONTEXTS; i++, ec++)
if (ec->ExchangeMgr != NULL && ec->Con == con)
{
ec->HandleConnectionClosed(conErr);
}
UnsolicitedMessageHandler *umh = (UnsolicitedMessageHandler *) UMHandlerPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
if (umh->Handler != NULL && umh->Con == con)
{
SYSTEM_STATS_DECREMENT(nl::Weave::System::Stats::kExchangeMgr_NumUMHandlers);
umh->Handler = NULL;
}
}
/**
* Expire the timers started by ExchangeContext instances.
* This function is not meant to be used in production code.
*
* @return Number of timers found running.
*/
#if WEAVE_CONFIG_TEST
size_t WeaveExchangeManager::ExpireExchangeTimers(void)
{
size_t retval = 0;
ExchangeContext *ec = (ExchangeContext *) ContextPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_EXCHANGE_CONTEXTS; i++, ec++)
{
if (ec->ExchangeMgr != NULL)
{
if (ec->ResponseTimeout)
{
ec->CancelResponseTimer();
ec->ResponseTimeout = 1;
ec->StartResponseTimer();
retval++;
}
}
}
return retval;
}
#endif
ExchangeContext *WeaveExchangeManager::AllocContext()
{
ExchangeContext *ec = (ExchangeContext *) ContextPool;
WEAVE_FAULT_INJECT(FaultInjection::kFault_AllocExchangeContext,
return NULL);
for (int i = 0; i < WEAVE_CONFIG_MAX_EXCHANGE_CONTEXTS; i++, ec++)
if (ec->ExchangeMgr == NULL)
{
*ec = ExchangeContext();
ec->ExchangeMgr = this;
ec->mRefCount = 1;
mContextsInUse++;
MessageLayer->SignalMessageLayerActivityChanged();
#if defined(WEAVE_EXCHANGE_CONTEXT_DETAIL_LOGGING)
WeaveLogProgress(ExchangeManager, "ec++ id: %d, inUse: %d, addr: 0x%x", EXCHANGE_CONTEXT_ID(ec - ContextPool), mContextsInUse, ec);
#endif
SYSTEM_STATS_INCREMENT(nl::Weave::System::Stats::kExchangeMgr_NumContexts);
return ec;
}
WeaveLogError(ExchangeManager, "Alloc ctxt FAILED");
return NULL;
}
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
void WeaveExchangeManager::WRMPProcessDDMessage(uint32_t PauseTimeMillis, uint64_t DelayedNodeId)
{
// Expire any virtual ticks that have expired so all wakeup sources reflect the current time
WRMPExpireTicks();
//Go through the retrans table entries for that node and adjust the timer.
for (int i = 0; i < WEAVE_CONFIG_WRMP_RETRANS_TABLE_SIZE; i++)
{
//Exchcontext is the sentinel object to ascertain validity of the element
if (RetransTable[i].exchContext)
{
//Adjust the retrans timer value if Delayed Node identifier matches Peer in ExchangeContext
if (DelayedNodeId == RetransTable[i].exchContext->PeerNodeId)
{
//Paustime is specified in milliseconds; Update retrans values
RetransTable[i].nextRetransTime += (PauseTimeMillis / mWRMPTimerInterval);
//Call the application callback
if (RetransTable[i].exchContext->OnDDRcvd)
{
RetransTable[i].exchContext->OnDDRcvd(RetransTable[i].exchContext,
PauseTimeMillis);
}
else
{
WeaveLogError(ExchangeManager,
"No App Handler for Delayed Delivery for ExchangeContext with Id %04" PRIX16,
RetransTable[i].exchContext->ExchangeId);
}
}//DelayedNodeId == PeerNodeId
}//exchContext
}//for loop in table entry
// Schedule next physical wakeup
WRMPStartTimer();
}
#endif // WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
static void DefaultOnMessageReceived(ExchangeContext *ec, const IPPacketInfo *pktInfo, const WeaveMessageInfo *msgInfo, uint32_t profileId,
uint8_t msgType, PacketBuffer *payload)
{
WeaveLogError(ExchangeManager,
"Dropping unexpected message %08" PRIX32 ":%d %04" PRIX16 " MsgId:%08" PRIX32,
profileId, msgType, ec->ExchangeId, msgInfo->MessageId);
PacketBuffer::Free(payload);
}
void WeaveExchangeManager::DispatchMessage(WeaveMessageInfo *msgInfo, PacketBuffer *msgBuf)
{
WeaveExchangeHeader exchangeHeader;
UnsolicitedMessageHandler *umh = NULL;
UnsolicitedMessageHandler *matchingUMH = NULL;
ExchangeContext *ec = NULL;
WeaveConnection *msgCon = NULL;
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
const uint8_t *p = NULL;
uint32_t PauseTimeMillis = 0;
uint64_t DelayedNodeId = 0;
bool dupMsg;
bool msgNeedsAck;
bool sendAckAndCloseExchange;
#endif
#if WEAVE_CONFIG_USE_APP_GROUP_KEYS_FOR_MSG_ENC
bool isMsgCounterSyncResp;
bool peerGroupMsgIdNotSynchronized;
#endif
WEAVE_ERROR err = WEAVE_NO_ERROR;
// Decode the exchange header.
err = DecodeHeader(&exchangeHeader, msgInfo, msgBuf);
SuccessOrExit(err);
//Check if the version is supported
if ((msgInfo->MessageVersion != kWeaveMessageVersion_V1) &&
(msgInfo->MessageVersion != kWeaveMessageVersion_V2))
{
ExitNow(err = WEAVE_ERROR_UNSUPPORTED_MESSAGE_VERSION);
}
// Notify Weave Security Manager that encrypted message has been received.
if (msgInfo->EncryptionType != kWeaveEncryptionType_None)
{
MessageLayer->SecurityMgr->OnEncryptedMsgRcvd(msgInfo->KeyId, msgInfo->SourceNodeId, msgInfo->EncryptionType);
}
msgCon = msgInfo->InCon;
if(!nl::Weave::Platform::IsProfileSilenced(static_cast<nl::Weave::Profiles::WeaveProfileId>(exchangeHeader.ProfileId)))
{
WeaveLogRetain(ExchangeManager, "Msg %s %08" PRIX32 ":%d %d %016" PRIX64 " %04" PRIX16 " %04" PRIX16 " %ld MsgId:%08" PRIX32,
"rcvd", exchangeHeader.ProfileId, exchangeHeader.MessageType,
(int)msgBuf->DataLength(), msgInfo->SourceNodeId, msgCon->LogId(), exchangeHeader.ExchangeId,
(long)err, msgInfo->MessageId);
}
#if WEAVE_CONFIG_USE_APP_GROUP_KEYS_FOR_MSG_ENC
isMsgCounterSyncResp = exchangeHeader.ProfileId == nl::Weave::Profiles::kWeaveProfile_Security &&
exchangeHeader.MessageType == nl::Weave::Profiles::Security::kMsgType_MsgCounterSyncResp;
peerGroupMsgIdNotSynchronized = (msgInfo->Flags & kWeaveMessageFlag_PeerGroupMsgIdNotSynchronized) != 0;
// If received message is a MsgCounterSyncResp process it first.
if (isMsgCounterSyncResp)
{
MessageLayer->SecurityMgr->HandleMsgCounterSyncRespMsg(msgInfo, msgBuf);
msgBuf = NULL;
}
// If message counter synchronization was requested.
if ((msgInfo->Flags & kWeaveMessageFlag_MsgCounterSyncReq) != 0)
{
MessageLayer->SecurityMgr->SendMsgCounterSyncResp(msgInfo, msgInfo->InPacketInfo);
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// Retransmit all pending messages that were encrypted with application group key.
RetransPendingAppGroupMsgs(msgInfo->SourceNodeId);
#endif
}
// Otherwise, if received message is not MsgCounterSyncResp and peer's message counter synchronization is needed.
else if (!isMsgCounterSyncResp && peerGroupMsgIdNotSynchronized)
{
MessageLayer->SecurityMgr->SendSolitaryMsgCounterSyncReq(msgInfo, msgInfo->InPacketInfo);
}
// Exit now without error if received MsgCounterSyncResp message.
if (isMsgCounterSyncResp)
{
ExitNow();
}
#endif // WEAVE_CONFIG_USE_APP_GROUP_KEYS_FOR_MSG_ENC
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
//Received Delayed Delivery Message: Extend time for pending retrans objects
if (exchangeHeader.ProfileId == nl::Weave::Profiles::kWeaveProfile_Common &&
exchangeHeader.MessageType == nl::Weave::Profiles::Common::kMsgType_WRMP_Delayed_Delivery)
{
// Process Delayed Delivery message if it is not a duplicate.
if ((msgInfo->Flags & kWeaveMessageFlag_DuplicateMessage) == 0)
{
p = msgBuf->Start();
PauseTimeMillis = LittleEndian::Read32(p);
DelayedNodeId = LittleEndian::Read64(p);
WRMPProcessDDMessage(PauseTimeMillis, DelayedNodeId);
}
//Return after processing Delayed Delivery message
ExitNow(err = WEAVE_NO_ERROR);
}//If delayed delivery Msg
#endif
// Search for an existing exchange that the message applies to. If a match is found...
ec = (ExchangeContext *) ContextPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_EXCHANGE_CONTEXTS; i++, ec++)
{
if (ec->ExchangeMgr != NULL && ec->MatchExchange(msgCon, msgInfo, &exchangeHeader))
{
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// Found a matching exchange. Set flag for correct subsequent WRM
// retransmission timeout selection.
if (!ec->HasRcvdMsgFromPeer())
{
ec->SetMsgRcvdFromPeer(true);
}
#endif
//Matched ExchangeContext; send to message handler.
ec->HandleMessage(msgInfo, &exchangeHeader, msgBuf);
msgBuf = NULL;
ExitNow(err = WEAVE_NO_ERROR);
}
}
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// Is message a duplicate that needs ack.
msgNeedsAck = exchangeHeader.Flags & kWeaveExchangeFlag_NeedsAck;
dupMsg = (msgInfo->Flags & kWeaveMessageFlag_DuplicateMessage);
#endif
// Search for an unsolicited message handler if it marked as being sent by an initiator. Since we didn't
// find an existing exchange that matches the message, it must be an unsolicited message. However all
// unsolicited messages must be marked as being from an initiator.
if (exchangeHeader.Flags & kWeaveExchangeFlag_Initiator)
{
// Search for an unsolicited message handler that can handle the message. Prefer handlers that can explicitly
// handle the message type over handlers that handle all messages for a profile.
umh = (UnsolicitedMessageHandler *) UMHandlerPool;
matchingUMH = NULL;
for (int i = 0; i < WEAVE_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
if (umh->Handler != NULL && umh->ProfileId == exchangeHeader.ProfileId && (umh->Con == NULL || umh->Con == msgCon)
&& (!(msgInfo->Flags & kWeaveMessageFlag_DuplicateMessage) || umh->AllowDuplicateMsgs))
{
if (umh->MessageType == exchangeHeader.MessageType)
{
matchingUMH = umh;
break;
}
if (umh->MessageType == -1)
matchingUMH = umh;
}
}
// Discard the message if it isn't marked as being sent by an initiator and the message is not a duplicate
// that needs to send ack to the peer.
else
{
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
if (!msgNeedsAck)
#endif
ExitNow(err = WEAVE_ERROR_UNSOLICITED_MSG_NO_ORIGINATOR);
}
// If no existing exchange that the message applies to was found we need to create
// a new exchange context (EC) in the following cases:
//
// (Dup.) Msg | UMH is | Allow | Need Peer | Action
// Needs Ack | Found | Dup. | MsgIdSync |
// ----------------------------------------------------------------------------------------------------------
// Y | Y | Y | - | Create EC, ec->HandleMessage() sends Dup ack and App callback.
// Y | Y | N | N | Create EC; ec->HandleMessage() sends Dup ack; Close EC.
// Y | N | - | N | Create EC, ec->HandleMessage() sends Dup ack; Close EC.
// N | Y | - | - | Create EC, ec->HandleMessage() sends ack (if needed) and App callback.
// N | N | - | - | Do nothing.
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// Create new exchange to send ack for a duplicate message and then close this exchange.
sendAckAndCloseExchange = msgNeedsAck && (matchingUMH == NULL || (dupMsg && !matchingUMH->AllowDuplicateMsgs));
#if WEAVE_CONFIG_USE_APP_GROUP_KEYS_FOR_MSG_ENC
// Don't create new EC only to send an ack if Peer's message counter synchronization is required.
if (peerGroupMsgIdNotSynchronized)
sendAckAndCloseExchange = false;
#endif
#endif
// If we found a handler or we need to open a new exchange to send ack for a duplicate message.
if (matchingUMH != NULL
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
|| sendAckAndCloseExchange
#endif
)
{
ExchangeContext::MessageReceiveFunct umhandler = NULL;
ec = AllocContext();
VerifyOrExit(ec != NULL, err = WEAVE_ERROR_NO_MEMORY);
ec->Con = msgCon;
ec->ExchangeId = exchangeHeader.ExchangeId;
ec->PeerNodeId = msgInfo->SourceNodeId;
if (msgInfo->InPacketInfo != NULL)
{
ec->PeerAddr = msgInfo->InPacketInfo->SrcAddress;
ec->PeerPort = msgInfo->InPacketInfo->SrcPort;
// If the message was received over UDP, and the peer's address is an
// IPv6 link-local, capture the interface to be used when sending packets
// back to the peer.
//
// Specifying an outbound interface when sending UDP packets has a subtle
// effect on routing and source address selection. Thus it is only done when
// required by the type of destination address.
//
if (ec->Con == NULL && ec->PeerAddr.IsIPv6LinkLocal())
{
ec->PeerIntf = msgInfo->InPacketInfo->Interface;
}
}
ec->EncryptionType = msgInfo->EncryptionType;
ec->KeyId = msgInfo->KeyId;
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// No need to set WRMP timer, this will be done when we add to retrans table
ec->mWRMPNextAckTime = 0;
ec->SetAckPending(false);
ec->SetMsgRcvdFromPeer(true);
ec->mWRMPConfig = gDefaultWRMPConfig;
ec->mWRMPThrottleTimeout = 0;
//Internal and for Debug Only; When set, Exchange Layer does not send Ack.
ec->SetDropAck(false);
#endif
//Set the ExchangeContext version from the Message header version
ec->mMsgProtocolVersion = msgInfo->MessageVersion;
// If UMH was found and the exchange is created not just for sending ack.
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
if (!sendAckAndCloseExchange)
#endif
{
umhandler = matchingUMH->Handler;
ec->SetInitiator(false);
ec->AppState = matchingUMH->AppState;
ec->OnMessageReceived = DefaultOnMessageReceived;
ec->AllowDuplicateMsgs = matchingUMH->AllowDuplicateMsgs;
WeaveLogProgress(ExchangeManager, "ec id: %d, AppState: 0x%x", EXCHANGE_CONTEXT_ID(ec - ContextPool), ec->AppState);
}
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// If the exchange is created only to send ack.
else
{
// If rcvd msg is from initiator then this exchange is created as not Initiator (argument to SetInitiator() is false).
// If rcvd msg is not from initiator then this exchange is created as Initiator (argument to SetInitiator() is true).
ec->SetInitiator((exchangeHeader.Flags & kWeaveExchangeFlag_Initiator) == 0);
}
#endif
// If support for ephemeral UDP ports is enabled, arrange to send outbound messages on this exchange from the
// local ephemeral UDP port IF the inbound message that initiated the exchange was sent TO the local ephemeral port.
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
ec->SetUseEphemeralUDPPort(GetFlag(msgInfo->Flags, kWeaveMessageFlag_ViaEphemeralUDPPort));
#endif // WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
// Add a reservation for the message encryption key. This will ensure the key is not removed until the exchange is freed.
MessageLayer->SecurityMgr->ReserveKey(ec->PeerNodeId, ec->KeyId);
// Arrange to automatically release the encryption key when the exchange is freed.
ec->SetAutoReleaseKey(true);
ec->HandleMessage(msgInfo, &exchangeHeader, msgBuf, umhandler);
msgBuf = NULL;
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// Close exchange if it was created only to send ack for a duplicate message.
if (sendAckAndCloseExchange)
ec->Close();
#endif
}
exit:
if (err != WEAVE_NO_ERROR)
{
WeaveLogError(ExchangeManager, "DispatchMessage failed, err = %d", err);
}
if (msgBuf != NULL)
{
PacketBuffer::Free(msgBuf);
}
return;
}
WEAVE_ERROR WeaveExchangeManager::RegisterUMH(uint32_t profileId, int16_t msgType, WeaveConnection *con, bool allowDups,
ExchangeContext::MessageReceiveFunct handler, void *appState)
{
UnsolicitedMessageHandler *umh = (UnsolicitedMessageHandler *) UMHandlerPool;
UnsolicitedMessageHandler *selected = NULL;
for (int i = 0; i < WEAVE_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
{
if (umh->Handler == NULL)
{
if (selected == NULL)
selected = umh;
}
else if (umh->ProfileId == profileId && umh->MessageType == msgType && umh->Con == con)
{
umh->Handler = handler;
umh->AppState = appState;
return WEAVE_NO_ERROR;
}
}
if (selected == NULL)
return WEAVE_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS;
selected->Handler = handler;
selected->AppState = appState;
selected->ProfileId = profileId;
selected->Con = con;
selected->MessageType = msgType;
selected->AllowDuplicateMsgs = allowDups;
SYSTEM_STATS_INCREMENT(nl::Weave::System::Stats::kExchangeMgr_NumUMHandlers);
return WEAVE_NO_ERROR;
}
WEAVE_ERROR WeaveExchangeManager::UnregisterUMH(uint32_t profileId, int16_t msgType, WeaveConnection *con)
{
UnsolicitedMessageHandler *umh = (UnsolicitedMessageHandler *) UMHandlerPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
{
if (umh->Handler != NULL && umh->ProfileId == profileId && umh->MessageType == msgType && umh->Con == con)
{
umh->Handler = NULL;
SYSTEM_STATS_DECREMENT(nl::Weave::System::Stats::kExchangeMgr_NumUMHandlers);
return WEAVE_NO_ERROR;
}
}
return WEAVE_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER;
}
void WeaveExchangeManager::HandleMessageReceived(WeaveMessageLayer *msgLayer, WeaveMessageInfo *msgInfo, PacketBuffer *msgBuf)
{
msgLayer->ExchangeMgr->DispatchMessage(msgInfo, msgBuf);
}
void WeaveExchangeManager::HandleMessageReceived(WeaveConnection *con, WeaveMessageInfo *msgInfo, PacketBuffer *msgBuf)
{
con->MessageLayer->ExchangeMgr->DispatchMessage(msgInfo, msgBuf);
}
WEAVE_ERROR WeaveExchangeManager::PrependHeader(WeaveExchangeHeader *exchangeHeader, PacketBuffer *buf)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
uint16_t headLen = 8; //Constant part: Version/Flags + Msg Type + Exch Id + Profile Id
uint8_t *p = NULL;
// Make sure the buffer has a reserved size big enough to hold the full Weave header.
if (!buf->EnsureReservedSize(WEAVE_HEADER_RESERVE_SIZE))
ExitNow(err = WEAVE_ERROR_BUFFER_TOO_SMALL);
// Verify the right application version is selected.
if (exchangeHeader->Version != kWeaveExchangeVersion_V1)
ExitNow(err = WEAVE_ERROR_UNSUPPORTED_EXCHANGE_VERSION);