Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020-2021 Project CHIP Authors
4 : * All rights reserved.
5 : *
6 : * Licensed under the Apache License, Version 2.0 (the "License");
7 : * you may not use this file except in compliance with the License.
8 : * You may obtain a copy of the License at
9 : *
10 : * http://www.apache.org/licenses/LICENSE-2.0
11 : *
12 : * Unless required by applicable law or agreed to in writing, software
13 : * distributed under the License is distributed on an "AS IS" BASIS,
14 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 : * See the License for the specific language governing permissions and
16 : * limitations under the License.
17 : */
18 :
19 : /**
20 : * @file
21 : * This file defines objects for a CHIP Interaction Data model Engine which handle unsolicited IM message, and
22 : * manage different kinds of IM client and handlers.
23 : *
24 : */
25 :
26 : #include "InteractionModelEngine.h"
27 :
28 : #include <cinttypes>
29 :
30 : #include <access/AccessRestrictionProvider.h>
31 : #include <access/Privilege.h>
32 : #include <access/RequestPath.h>
33 : #include <access/SubjectDescriptor.h>
34 : #include <app/AppConfig.h>
35 : #include <app/CommandHandlerInterfaceRegistry.h>
36 : #include <app/ConcreteClusterPath.h>
37 : #include <app/EventPathParams.h>
38 : #include <app/RequiredPrivilege.h>
39 : #include <app/data-model-provider/ActionReturnStatus.h>
40 : #include <app/data-model-provider/MetadataList.h>
41 : #include <app/data-model-provider/MetadataLookup.h>
42 : #include <app/data-model-provider/MetadataTypes.h>
43 : #include <app/data-model-provider/OperationTypes.h>
44 : #include <app/data-model/List.h>
45 : #include <app/util/IMClusterCommandHandler.h>
46 : #include <app/util/af-types.h>
47 : #include <app/util/endpoint-config-api.h>
48 : #include <lib/core/CHIPError.h>
49 : #include <lib/core/DataModelTypes.h>
50 : #include <lib/core/Global.h>
51 : #include <lib/core/TLVUtilities.h>
52 : #include <lib/support/CHIPFaultInjection.h>
53 : #include <lib/support/CodeUtils.h>
54 : #include <lib/support/FibonacciUtils.h>
55 : #include <protocols/interaction_model/StatusCode.h>
56 :
57 : namespace chip {
58 : namespace app {
59 : namespace {
60 :
61 : /**
62 : * Helper to handle wildcard events in the event path.
63 : *
64 : * Validates that ACL access is permitted to:
65 : * - Cluster::View in case the path is a wildcard for the event id
66 : * - Event read if the path is a concrete event path
67 : */
68 18 : bool MayHaveAccessibleEventPathForEndpointAndCluster(const ConcreteClusterPath & path, const EventPathParams & aEventPath,
69 : const Access::SubjectDescriptor & aSubjectDescriptor)
70 : {
71 18 : Access::RequestPath requestPath{ .cluster = path.mClusterId,
72 18 : .endpoint = path.mEndpointId,
73 18 : .requestType = Access::RequestType::kEventReadRequest };
74 :
75 18 : Access::Privilege requiredPrivilege = Access::Privilege::kView;
76 :
77 18 : if (!aEventPath.HasWildcardEventId())
78 : {
79 12 : requestPath.entityId = aEventPath.mEventId;
80 : requiredPrivilege =
81 12 : RequiredPrivilege::ForReadEvent(ConcreteEventPath(path.mEndpointId, path.mClusterId, aEventPath.mEventId));
82 : }
83 :
84 18 : return (Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, requiredPrivilege) == CHIP_NO_ERROR);
85 : }
86 :
87 18 : bool MayHaveAccessibleEventPathForEndpoint(DataModel::Provider * aProvider, EndpointId aEndpoint,
88 : const EventPathParams & aEventPath, const Access::SubjectDescriptor & aSubjectDescriptor)
89 : {
90 18 : if (!aEventPath.HasWildcardClusterId())
91 : {
92 36 : return MayHaveAccessibleEventPathForEndpointAndCluster(ConcreteClusterPath(aEndpoint, aEventPath.mClusterId), aEventPath,
93 18 : aSubjectDescriptor);
94 : }
95 :
96 0 : for (auto & cluster : aProvider->ServerClustersIgnoreError(aEventPath.mEndpointId))
97 : {
98 0 : if (MayHaveAccessibleEventPathForEndpointAndCluster(ConcreteClusterPath(aEventPath.mEndpointId, cluster.clusterId),
99 : aEventPath, aSubjectDescriptor))
100 : {
101 0 : return true;
102 : }
103 0 : }
104 :
105 0 : return false;
106 : }
107 :
108 18 : bool MayHaveAccessibleEventPath(DataModel::Provider * aProvider, const EventPathParams & aEventPath,
109 : const Access::SubjectDescriptor & subjectDescriptor)
110 : {
111 18 : VerifyOrReturnValue(aProvider != nullptr, false);
112 :
113 18 : if (!aEventPath.HasWildcardEndpointId())
114 : {
115 18 : return MayHaveAccessibleEventPathForEndpoint(aProvider, aEventPath.mEndpointId, aEventPath, subjectDescriptor);
116 : }
117 :
118 0 : for (const DataModel::EndpointEntry & ep : aProvider->EndpointsIgnoreError())
119 : {
120 0 : if (MayHaveAccessibleEventPathForEndpoint(aProvider, ep.id, aEventPath, subjectDescriptor))
121 : {
122 0 : return true;
123 : }
124 0 : }
125 0 : return false;
126 : }
127 :
128 : } // namespace
129 :
130 : class AutoReleaseSubscriptionInfoIterator
131 : {
132 : public:
133 0 : AutoReleaseSubscriptionInfoIterator(SubscriptionResumptionStorage::SubscriptionInfoIterator * iterator) : mIterator(iterator){};
134 0 : ~AutoReleaseSubscriptionInfoIterator() { mIterator->Release(); }
135 :
136 0 : SubscriptionResumptionStorage::SubscriptionInfoIterator * operator->() const { return mIterator; }
137 :
138 : private:
139 : SubscriptionResumptionStorage::SubscriptionInfoIterator * mIterator;
140 : };
141 :
142 : using Protocols::InteractionModel::Status;
143 :
144 : Global<InteractionModelEngine> sInteractionModelEngine;
145 :
146 315 : InteractionModelEngine::InteractionModelEngine() : mReportingEngine(this) {}
147 :
148 6840 : InteractionModelEngine * InteractionModelEngine::GetInstance()
149 : {
150 6840 : return &sInteractionModelEngine.get();
151 : }
152 :
153 408 : CHIP_ERROR InteractionModelEngine::Init(Messaging::ExchangeManager * apExchangeMgr, FabricTable * apFabricTable,
154 : reporting::ReportScheduler * reportScheduler, CASESessionManager * apCASESessionMgr,
155 : SubscriptionResumptionStorage * subscriptionResumptionStorage,
156 : EventManagement * eventManagement)
157 : {
158 408 : VerifyOrReturnError(apFabricTable != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
159 408 : VerifyOrReturnError(apExchangeMgr != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
160 408 : VerifyOrReturnError(reportScheduler != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
161 :
162 408 : mState = State::kInitializing;
163 408 : mpExchangeMgr = apExchangeMgr;
164 408 : mpFabricTable = apFabricTable;
165 408 : mpCASESessionMgr = apCASESessionMgr;
166 408 : mpSubscriptionResumptionStorage = subscriptionResumptionStorage;
167 408 : mReportScheduler = reportScheduler;
168 :
169 408 : ReturnErrorOnFailure(mpFabricTable->AddFabricDelegate(this));
170 408 : ReturnErrorOnFailure(mpExchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::InteractionModel::Id, this));
171 :
172 408 : mReportingEngine.Init((eventManagement != nullptr) ? eventManagement : &EventManagement::GetInstance());
173 :
174 408 : StatusIB::RegisterErrorFormatter();
175 :
176 408 : mState = State::kInitialized;
177 408 : return CHIP_NO_ERROR;
178 : }
179 :
180 394 : void InteractionModelEngine::Shutdown()
181 : {
182 394 : VerifyOrReturn(State::kUninitialized != mState);
183 :
184 285 : mpExchangeMgr->GetSessionManager()->SystemLayer()->CancelTimer(ResumeSubscriptionsTimerCallback, this);
185 :
186 : // TODO: individual object clears the entire command handler interface registry.
187 : // This may not be expected as IME does NOT own the command handler interface registry.
188 : //
189 : // This is to be cleaned up once InteractionModelEngine maintains a data model fully and
190 : // the code-generation model can do its clear in its shutdown method.
191 285 : CommandHandlerInterfaceRegistry::Instance().UnregisterAllHandlers();
192 285 : mCommandResponderObjs.ReleaseAll();
193 :
194 285 : mTimedHandlers.ForEachActiveObject([this](TimedHandler * obj) -> Loop {
195 1 : mpExchangeMgr->CloseAllContextsForDelegate(obj);
196 1 : return Loop::Continue;
197 : });
198 :
199 285 : mTimedHandlers.ReleaseAll();
200 :
201 285 : mReadHandlers.ReleaseAll();
202 :
203 : #if CHIP_CONFIG_ENABLE_READ_CLIENT
204 : // Shut down any subscription clients that are still around. They won't be
205 : // able to work after this point anyway, since we're about to drop our refs
206 : // to them.
207 285 : ShutdownAllSubscriptions();
208 :
209 : //
210 : // We hold weak references to ReadClient objects. The application ultimately
211 : // actually owns them, so it's on them to eventually shut them down and free them
212 : // up.
213 : //
214 : // However, we should null out their pointers back to us at the very least so that
215 : // at destruction time, they won't attempt to reach back here to remove themselves
216 : // from this list.
217 : //
218 289 : for (auto * readClient = mpActiveReadClientList; readClient != nullptr;)
219 : {
220 4 : readClient->mpImEngine = nullptr;
221 4 : auto * tmpClient = readClient->GetNextClient();
222 4 : readClient->SetNextClient(nullptr);
223 4 : readClient = tmpClient;
224 : }
225 :
226 : //
227 : // After that, we just null out our tracker.
228 : //
229 285 : mpActiveReadClientList = nullptr;
230 : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
231 :
232 1425 : for (auto & writeHandler : mWriteHandlers)
233 : {
234 1140 : if (!writeHandler.IsFree())
235 : {
236 0 : writeHandler.Close();
237 : }
238 : }
239 :
240 285 : mReportingEngine.Shutdown();
241 285 : mAttributePathPool.ReleaseAll();
242 285 : mEventPathPool.ReleaseAll();
243 285 : mDataVersionFilterPool.ReleaseAll();
244 285 : mpExchangeMgr->UnregisterUnsolicitedMessageHandlerForProtocol(Protocols::InteractionModel::Id);
245 :
246 285 : mpCASESessionMgr = nullptr;
247 :
248 : //
249 : // We _should_ be clearing these out, but doing so invites a world
250 : // of trouble. #21233 tracks fixing the underlying assumptions to make
251 : // this possible.
252 : //
253 : // mpFabricTable = nullptr;
254 : // mpExchangeMgr = nullptr;
255 :
256 285 : mState = State::kUninitialized;
257 : }
258 :
259 69 : uint32_t InteractionModelEngine::GetNumActiveReadHandlers() const
260 : {
261 69 : return static_cast<uint32_t>(mReadHandlers.Allocated());
262 : }
263 :
264 51 : uint32_t InteractionModelEngine::GetNumActiveReadHandlers(ReadHandler::InteractionType aType) const
265 : {
266 51 : uint32_t count = 0;
267 :
268 51 : mReadHandlers.ForEachActiveObject([aType, &count](const ReadHandler * handler) {
269 73 : if (handler->IsType(aType))
270 : {
271 61 : count++;
272 : }
273 :
274 73 : return Loop::Continue;
275 : });
276 :
277 51 : return count;
278 : }
279 :
280 19 : uint32_t InteractionModelEngine::GetNumActiveReadHandlers(ReadHandler::InteractionType aType, FabricIndex aFabricIndex) const
281 : {
282 19 : uint32_t count = 0;
283 :
284 19 : mReadHandlers.ForEachActiveObject([aType, aFabricIndex, &count](const ReadHandler * handler) {
285 66 : if (handler->IsType(aType) && handler->GetAccessingFabricIndex() == aFabricIndex)
286 : {
287 31 : count++;
288 : }
289 :
290 66 : return Loop::Continue;
291 : });
292 :
293 19 : return count;
294 : }
295 :
296 2306 : ReadHandler * InteractionModelEngine::ActiveHandlerAt(unsigned int aIndex)
297 : {
298 2306 : if (aIndex >= mReadHandlers.Allocated())
299 : {
300 0 : return nullptr;
301 : }
302 :
303 2306 : unsigned int i = 0;
304 2306 : ReadHandler * ret = nullptr;
305 :
306 2306 : mReadHandlers.ForEachActiveObject([aIndex, &i, &ret](ReadHandler * handler) {
307 14992 : if (i == aIndex)
308 : {
309 2306 : ret = handler;
310 2306 : return Loop::Break;
311 : }
312 :
313 12686 : i++;
314 12686 : return Loop::Continue;
315 : });
316 :
317 2306 : return ret;
318 : }
319 :
320 1 : WriteHandler * InteractionModelEngine::ActiveWriteHandlerAt(unsigned int aIndex)
321 : {
322 1 : unsigned int i = 0;
323 :
324 1 : for (auto & writeHandler : mWriteHandlers)
325 : {
326 1 : if (!writeHandler.IsFree())
327 : {
328 1 : if (i == aIndex)
329 : {
330 1 : return &writeHandler;
331 : }
332 0 : i++;
333 : }
334 : }
335 0 : return nullptr;
336 : }
337 :
338 14 : uint32_t InteractionModelEngine::GetNumActiveWriteHandlers() const
339 : {
340 14 : uint32_t numActive = 0;
341 :
342 70 : for (auto & writeHandler : mWriteHandlers)
343 : {
344 56 : if (!writeHandler.IsFree())
345 : {
346 2 : numActive++;
347 : }
348 : }
349 :
350 14 : return numActive;
351 : }
352 :
353 : #if CHIP_CONFIG_ENABLE_READ_CLIENT
354 2 : CHIP_ERROR InteractionModelEngine::ShutdownSubscription(const ScopedNodeId & aPeerNodeId, SubscriptionId aSubscriptionId)
355 : {
356 2 : assertChipStackLockedByCurrentThread();
357 2 : for (auto * readClient = mpActiveReadClientList; readClient != nullptr;)
358 : {
359 : // Grab the next client now, because we might be about to delete readClient.
360 2 : auto * nextClient = readClient->GetNextClient();
361 6 : if (readClient->IsSubscriptionType() && readClient->IsMatchingSubscriptionId(aSubscriptionId) &&
362 6 : readClient->GetFabricIndex() == aPeerNodeId.GetFabricIndex() && readClient->GetPeerNodeId() == aPeerNodeId.GetNodeId())
363 : {
364 2 : readClient->Close(CHIP_NO_ERROR);
365 2 : return CHIP_NO_ERROR;
366 : }
367 0 : readClient = nextClient;
368 : }
369 :
370 0 : return CHIP_ERROR_KEY_NOT_FOUND;
371 : }
372 :
373 0 : void InteractionModelEngine::ShutdownSubscriptions(FabricIndex aFabricIndex, NodeId aPeerNodeId)
374 : {
375 0 : assertChipStackLockedByCurrentThread();
376 0 : ShutdownMatchingSubscriptions(MakeOptional(aFabricIndex), MakeOptional(aPeerNodeId));
377 0 : }
378 0 : void InteractionModelEngine::ShutdownSubscriptions(FabricIndex aFabricIndex)
379 : {
380 0 : assertChipStackLockedByCurrentThread();
381 0 : ShutdownMatchingSubscriptions(MakeOptional(aFabricIndex));
382 0 : }
383 :
384 285 : void InteractionModelEngine::ShutdownAllSubscriptions()
385 : {
386 285 : assertChipStackLockedByCurrentThread();
387 285 : ShutdownMatchingSubscriptions();
388 285 : }
389 :
390 1 : void InteractionModelEngine::ShutdownAllSubscriptionHandlers()
391 : {
392 1 : mReadHandlers.ForEachActiveObject([&](auto * handler) {
393 1 : if (!handler->IsType(ReadHandler::InteractionType::Subscribe))
394 : {
395 0 : return Loop::Continue;
396 : }
397 1 : handler->Close();
398 1 : return Loop::Continue;
399 : });
400 1 : }
401 :
402 285 : void InteractionModelEngine::ShutdownMatchingSubscriptions(const Optional<FabricIndex> & aFabricIndex,
403 : const Optional<NodeId> & aPeerNodeId)
404 : {
405 : // This is assuming that ReadClient::Close will not affect any other
406 : // ReadClients in the list.
407 289 : for (auto * readClient = mpActiveReadClientList; readClient != nullptr;)
408 : {
409 : // Grab the next client now, because we might be about to delete readClient.
410 4 : auto * nextClient = readClient->GetNextClient();
411 4 : if (readClient->IsSubscriptionType())
412 : {
413 4 : bool fabricMatches = !aFabricIndex.HasValue() || (aFabricIndex.Value() == readClient->GetFabricIndex());
414 4 : bool nodeIdMatches = !aPeerNodeId.HasValue() || (aPeerNodeId.Value() == readClient->GetPeerNodeId());
415 4 : if (fabricMatches && nodeIdMatches)
416 : {
417 4 : readClient->Close(CHIP_NO_ERROR);
418 : }
419 : }
420 4 : readClient = nextClient;
421 : }
422 285 : }
423 : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
424 :
425 38 : bool InteractionModelEngine::SubjectHasActiveSubscription(FabricIndex aFabricIndex, NodeId subjectID)
426 : {
427 38 : bool isActive = false;
428 38 : mReadHandlers.ForEachActiveObject([aFabricIndex, subjectID, &isActive](ReadHandler * handler) {
429 52 : VerifyOrReturnValue(handler->IsType(ReadHandler::InteractionType::Subscribe), Loop::Continue);
430 :
431 52 : Access::SubjectDescriptor subject = handler->GetSubjectDescriptor();
432 52 : VerifyOrReturnValue(subject.fabricIndex == aFabricIndex, Loop::Continue);
433 :
434 35 : if (subject.authMode == Access::AuthMode::kCase)
435 : {
436 35 : if (subject.cats.CheckSubjectAgainstCATs(subjectID) || subjectID == subject.subject)
437 : {
438 33 : isActive = handler->IsActiveSubscription();
439 :
440 : // Exit loop only if isActive is set to true.
441 : // Otherwise keep looking for another subscription that could match the subject.
442 33 : VerifyOrReturnValue(!isActive, Loop::Break);
443 : }
444 : }
445 :
446 24 : return Loop::Continue;
447 : });
448 :
449 38 : return isActive;
450 : }
451 :
452 6 : bool InteractionModelEngine::SubjectHasPersistedSubscription(FabricIndex aFabricIndex, NodeId subjectID)
453 : {
454 6 : bool persistedSubMatches = false;
455 :
456 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
457 6 : auto * iterator = mpSubscriptionResumptionStorage->IterateSubscriptions();
458 : // Verify that we were able to allocate an iterator. If not, we are probably currently trying to resubscribe to our persisted
459 : // subscriptions. As such, we assume we have a persisted subscription and return true.
460 : // If we don't have a persisted subscription for the given fabric index and subjectID, we will send a Check-In message next time
461 : // we transition to ActiveMode.
462 6 : VerifyOrReturnValue(iterator, true);
463 :
464 6 : SubscriptionResumptionStorage::SubscriptionInfo subscriptionInfo;
465 9 : while (iterator->Next(subscriptionInfo))
466 : {
467 : // TODO(#31873): Persistent subscription only stores the NodeID for now. We cannot check if the CAT matches
468 6 : if (subscriptionInfo.mFabricIndex == aFabricIndex && subscriptionInfo.mNodeId == subjectID)
469 : {
470 3 : persistedSubMatches = true;
471 3 : break;
472 : }
473 : }
474 6 : iterator->Release();
475 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
476 :
477 6 : return persistedSubMatches;
478 6 : }
479 :
480 15 : bool InteractionModelEngine::FabricHasAtLeastOneActiveSubscription(FabricIndex aFabricIndex)
481 : {
482 15 : bool hasActiveSubscription = false;
483 15 : mReadHandlers.ForEachActiveObject([aFabricIndex, &hasActiveSubscription](ReadHandler * handler) {
484 11 : VerifyOrReturnValue(handler->IsType(ReadHandler::InteractionType::Subscribe), Loop::Continue);
485 :
486 11 : Access::SubjectDescriptor subject = handler->GetSubjectDescriptor();
487 11 : VerifyOrReturnValue(subject.fabricIndex == aFabricIndex, Loop::Continue);
488 :
489 9 : if ((subject.authMode == Access::AuthMode::kCase) && handler->IsActiveSubscription())
490 : {
491 : // On first subscription found for fabric, we can immediately stop checking.
492 5 : hasActiveSubscription = true;
493 5 : return Loop::Break;
494 : }
495 :
496 4 : return Loop::Continue;
497 : });
498 :
499 15 : return hasActiveSubscription;
500 : }
501 :
502 33 : void InteractionModelEngine::OnDone(CommandResponseSender & apResponderObj)
503 : {
504 33 : mCommandResponderObjs.ReleaseObject(&apResponderObj);
505 33 : }
506 :
507 : // TODO(#30453): Follow up refactor. Remove need for InteractionModelEngine::OnDone(CommandHandlerImpl).
508 0 : void InteractionModelEngine::OnDone(CommandHandlerImpl & apCommandObj)
509 : {
510 : // We are no longer expecting to receive this callback. With the introduction of CommandResponseSender, it is now
511 : // responsible for receiving this callback.
512 0 : VerifyOrDie(false);
513 : }
514 :
515 863 : void InteractionModelEngine::OnDone(ReadHandler & apReadObj)
516 : {
517 : //
518 : // Deleting an item can shift down the contents of the underlying pool storage,
519 : // rendering any tracker using positional indexes invalid. Let's reset it,
520 : // based on which readHandler we are getting rid of.
521 : //
522 863 : mReportingEngine.ResetReadHandlerTracker(&apReadObj);
523 :
524 863 : mReadHandlers.ReleaseObject(&apReadObj);
525 863 : TryToResumeSubscriptions();
526 863 : }
527 :
528 863 : void InteractionModelEngine::TryToResumeSubscriptions()
529 : {
530 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
531 863 : if (!mSubscriptionResumptionScheduled && HasSubscriptionsToResume())
532 : {
533 0 : mSubscriptionResumptionScheduled = true;
534 0 : auto timeTillNextSubscriptionResumptionSecs = ComputeTimeSecondsTillNextSubscriptionResumption();
535 0 : mpExchangeMgr->GetSessionManager()->SystemLayer()->StartTimer(
536 0 : System::Clock::Seconds32(timeTillNextSubscriptionResumptionSecs), ResumeSubscriptionsTimerCallback, this);
537 0 : mNumSubscriptionResumptionRetries++;
538 0 : ChipLogProgress(InteractionModel, "Schedule subscription resumption when failing to establish session, Retries: %" PRIu32,
539 : mNumSubscriptionResumptionRetries);
540 : }
541 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
542 863 : }
543 :
544 33 : Status InteractionModelEngine::OnInvokeCommandRequest(Messaging::ExchangeContext * apExchangeContext,
545 : const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload,
546 : bool aIsTimedInvoke)
547 : {
548 : // TODO(#30453): Refactor CommandResponseSender's constructor to accept an exchange context parameter.
549 33 : CommandResponseSender * commandResponder = mCommandResponderObjs.CreateObject(this, this);
550 33 : if (commandResponder == nullptr)
551 : {
552 0 : ChipLogProgress(InteractionModel, "no resource for Invoke interaction");
553 0 : return Status::Busy;
554 : }
555 33 : CHIP_FAULT_INJECT(FaultInjection::kFault_IMInvoke_SeparateResponses,
556 : commandResponder->TestOnlyInvokeCommandRequestWithFaultsInjected(
557 : apExchangeContext, std::move(aPayload), aIsTimedInvoke,
558 : CommandHandlerImpl::NlFaultInjectionType::SeparateResponseMessages);
559 : return Status::Success;);
560 33 : CHIP_FAULT_INJECT(FaultInjection::kFault_IMInvoke_SeparateResponsesInvertResponseOrder,
561 : commandResponder->TestOnlyInvokeCommandRequestWithFaultsInjected(
562 : apExchangeContext, std::move(aPayload), aIsTimedInvoke,
563 : CommandHandlerImpl::NlFaultInjectionType::SeparateResponseMessagesAndInvertedResponseOrder);
564 : return Status::Success;);
565 33 : CHIP_FAULT_INJECT(
566 : FaultInjection::kFault_IMInvoke_SkipSecondResponse,
567 : commandResponder->TestOnlyInvokeCommandRequestWithFaultsInjected(
568 : apExchangeContext, std::move(aPayload), aIsTimedInvoke, CommandHandlerImpl::NlFaultInjectionType::SkipSecondResponse);
569 : return Status::Success;);
570 33 : commandResponder->OnInvokeCommandRequest(apExchangeContext, std::move(aPayload), aIsTimedInvoke);
571 33 : return Status::Success;
572 : }
573 :
574 297 : CHIP_ERROR InteractionModelEngine::ParseAttributePaths(const Access::SubjectDescriptor & aSubjectDescriptor,
575 : AttributePathIBs::Parser & aAttributePathListParser,
576 : bool & aHasValidAttributePath, size_t & aRequestedAttributePathCount)
577 : {
578 297 : TLV::TLVReader pathReader;
579 297 : aAttributePathListParser.GetReader(&pathReader);
580 297 : CHIP_ERROR err = CHIP_NO_ERROR;
581 :
582 297 : aHasValidAttributePath = false;
583 297 : aRequestedAttributePathCount = 0;
584 :
585 662 : while (CHIP_NO_ERROR == (err = pathReader.Next(TLV::AnonymousTag())))
586 : {
587 365 : AttributePathIB::Parser path;
588 : //
589 : // We create an iterator to point to a single item object list that tracks the path we just parsed.
590 : // This avoids the 'parse all paths' approach that is employed in ReadHandler since we want to
591 : // avoid allocating out of the path store during this minimal initial processing stage.
592 : //
593 365 : SingleLinkedListNode<AttributePathParams> paramsList;
594 :
595 365 : ReturnErrorOnFailure(path.Init(pathReader));
596 365 : ReturnErrorOnFailure(path.ParsePath(paramsList.mValue));
597 :
598 365 : if (paramsList.mValue.IsWildcardPath())
599 : {
600 :
601 10 : auto state = AttributePathExpandIterator::Position::StartIterating(¶msList);
602 10 : AttributePathExpandIterator pathIterator(GetDataModelProvider(), state);
603 10 : ConcreteAttributePath readPath;
604 :
605 : // The definition of "valid path" is "path exists and ACL allows access". The "path exists" part is handled by
606 : // AttributePathExpandIterator. So we just need to check the ACL bits.
607 10 : while (pathIterator.Next(readPath))
608 : {
609 : // leave requestPath.entityId optional value unset to indicate wildcard
610 8 : Access::RequestPath requestPath{ .cluster = readPath.mClusterId,
611 8 : .endpoint = readPath.mEndpointId,
612 8 : .requestType = Access::RequestType::kAttributeReadRequest };
613 8 : err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath,
614 : RequiredPrivilege::ForReadAttribute(readPath));
615 8 : if (err == CHIP_NO_ERROR)
616 : {
617 8 : aHasValidAttributePath = true;
618 8 : break;
619 : }
620 : }
621 10 : }
622 : else
623 : {
624 355 : ConcreteAttributePath concretePath(paramsList.mValue.mEndpointId, paramsList.mValue.mClusterId,
625 355 : paramsList.mValue.mAttributeId);
626 :
627 355 : if (IsExistentAttributePath(concretePath))
628 : {
629 351 : Access::RequestPath requestPath{ .cluster = concretePath.mClusterId,
630 351 : .endpoint = concretePath.mEndpointId,
631 : .requestType = Access::RequestType::kAttributeReadRequest,
632 351 : .entityId = paramsList.mValue.mAttributeId };
633 :
634 351 : err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath,
635 : RequiredPrivilege::ForReadAttribute(concretePath));
636 351 : if (err == CHIP_NO_ERROR)
637 : {
638 351 : aHasValidAttributePath = true;
639 : }
640 : }
641 : }
642 :
643 365 : aRequestedAttributePathCount++;
644 : }
645 :
646 297 : if (err == CHIP_ERROR_END_OF_TLV)
647 : {
648 297 : err = CHIP_NO_ERROR;
649 : }
650 :
651 297 : return err;
652 : }
653 :
654 18 : CHIP_ERROR InteractionModelEngine::ParseEventPaths(const Access::SubjectDescriptor & aSubjectDescriptor,
655 : EventPathIBs::Parser & aEventPathListParser, bool & aHasValidEventPath,
656 : size_t & aRequestedEventPathCount)
657 : {
658 18 : TLV::TLVReader pathReader;
659 18 : aEventPathListParser.GetReader(&pathReader);
660 18 : CHIP_ERROR err = CHIP_NO_ERROR;
661 :
662 18 : aHasValidEventPath = false;
663 18 : aRequestedEventPathCount = 0;
664 :
665 52 : while (CHIP_NO_ERROR == (err = pathReader.Next(TLV::AnonymousTag())))
666 : {
667 34 : EventPathIB::Parser path;
668 34 : ReturnErrorOnFailure(path.Init(pathReader));
669 :
670 34 : EventPathParams eventPath;
671 34 : ReturnErrorOnFailure(path.ParsePath(eventPath));
672 :
673 34 : ++aRequestedEventPathCount;
674 :
675 34 : if (aHasValidEventPath)
676 : {
677 : // Can skip all the rest of the checking.
678 16 : continue;
679 : }
680 :
681 : // The definition of "valid path" is "path exists and ACL allows
682 : // access". We need to do some expansion of wildcards to handle that.
683 18 : aHasValidEventPath = MayHaveAccessibleEventPath(mDataModelProvider, eventPath, aSubjectDescriptor);
684 : }
685 :
686 18 : if (err == CHIP_ERROR_END_OF_TLV)
687 : {
688 18 : err = CHIP_NO_ERROR;
689 : }
690 :
691 18 : return err;
692 : }
693 :
694 1101 : Protocols::InteractionModel::Status InteractionModelEngine::OnReadInitialRequest(Messaging::ExchangeContext * apExchangeContext,
695 : const PayloadHeader & aPayloadHeader,
696 : System::PacketBufferHandle && aPayload,
697 : ReadHandler::InteractionType aInteractionType)
698 : {
699 1101 : ChipLogDetail(InteractionModel, "Received %s request",
700 : aInteractionType == ReadHandler::InteractionType::Subscribe ? "Subscribe" : "Read");
701 :
702 : //
703 : // Let's first figure out if the client has sent us a subscribe request and requested we keep any existing
704 : // subscriptions from that source.
705 : //
706 1101 : if (aInteractionType == ReadHandler::InteractionType::Subscribe)
707 : {
708 306 : System::PacketBufferTLVReader reader;
709 306 : bool keepExistingSubscriptions = true;
710 :
711 306 : if (apExchangeContext->GetSessionHandle()->GetFabricIndex() == kUndefinedFabricIndex)
712 : {
713 : // Subscriptions must be associated to a fabric.
714 0 : return Status::UnsupportedAccess;
715 : }
716 :
717 306 : reader.Init(aPayload.Retain());
718 :
719 306 : SubscribeRequestMessage::Parser subscribeRequestParser;
720 306 : VerifyOrReturnError(subscribeRequestParser.Init(reader) == CHIP_NO_ERROR, Status::InvalidAction);
721 :
722 : #if CHIP_CONFIG_IM_PRETTY_PRINT
723 304 : subscribeRequestParser.PrettyPrint();
724 : #endif
725 :
726 304 : VerifyOrReturnError(subscribeRequestParser.GetKeepSubscriptions(&keepExistingSubscriptions) == CHIP_NO_ERROR,
727 : Status::InvalidAction);
728 304 : if (!keepExistingSubscriptions)
729 : {
730 : //
731 : // Walk through all existing subscriptions and shut down those whose subscriber matches
732 : // that which just came in.
733 : //
734 78 : mReadHandlers.ForEachActiveObject([apExchangeContext](ReadHandler * handler) {
735 4 : if (handler->IsFromSubscriber(*apExchangeContext))
736 : {
737 4 : ChipLogProgress(InteractionModel,
738 : "Deleting previous active subscription from NodeId: " ChipLogFormatX64 ", FabricIndex: %u",
739 : ChipLogValueX64(apExchangeContext->GetSessionHandle()->AsSecureSession()->GetPeerNodeId()),
740 : apExchangeContext->GetSessionHandle()->GetFabricIndex());
741 4 : handler->Close();
742 : }
743 :
744 4 : return Loop::Continue;
745 : });
746 :
747 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
748 78 : if (mpSubscriptionResumptionStorage != nullptr)
749 : {
750 0 : SubscriptionResumptionStorage::SubscriptionInfo subscriptionInfo;
751 0 : auto * iterator = mpSubscriptionResumptionStorage->IterateSubscriptions();
752 :
753 0 : while (iterator->Next(subscriptionInfo))
754 : {
755 0 : if (subscriptionInfo.mNodeId == apExchangeContext->GetSessionHandle()->AsSecureSession()->GetPeerNodeId() &&
756 0 : subscriptionInfo.mFabricIndex == apExchangeContext->GetSessionHandle()->GetFabricIndex())
757 : {
758 0 : ChipLogProgress(InteractionModel,
759 : "Deleting previous non-active subscription from NodeId: " ChipLogFormatX64
760 : ", FabricIndex: %u, SubscriptionId: 0x%" PRIx32,
761 : ChipLogValueX64(subscriptionInfo.mNodeId), subscriptionInfo.mFabricIndex,
762 : subscriptionInfo.mSubscriptionId);
763 0 : mpSubscriptionResumptionStorage->Delete(subscriptionInfo.mNodeId, subscriptionInfo.mFabricIndex,
764 : subscriptionInfo.mSubscriptionId);
765 : }
766 : }
767 0 : iterator->Release();
768 :
769 : // If we have no subscriptions to resume, we can cancel the timer, which might be armed
770 : // if one of the subscriptions we deleted was about to be resumed.
771 0 : if (!HasSubscriptionsToResume())
772 : {
773 0 : mpExchangeMgr->GetSessionManager()->SystemLayer()->CancelTimer(ResumeSubscriptionsTimerCallback, this);
774 0 : mSubscriptionResumptionScheduled = false;
775 0 : mNumSubscriptionResumptionRetries = 0;
776 : }
777 0 : }
778 : #endif // CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
779 : }
780 :
781 : {
782 304 : size_t requestedAttributePathCount = 0;
783 304 : size_t requestedEventPathCount = 0;
784 304 : AttributePathIBs::Parser attributePathListParser;
785 304 : bool hasValidAttributePath = false;
786 304 : bool mayHaveValidEventPath = false;
787 :
788 304 : CHIP_ERROR err = subscribeRequestParser.GetAttributeRequests(&attributePathListParser);
789 304 : if (err == CHIP_NO_ERROR)
790 : {
791 297 : auto subjectDescriptor = apExchangeContext->GetSessionHandle()->AsSecureSession()->GetSubjectDescriptor();
792 297 : err = ParseAttributePaths(subjectDescriptor, attributePathListParser, hasValidAttributePath,
793 : requestedAttributePathCount);
794 297 : if (err != CHIP_NO_ERROR)
795 : {
796 0 : return Status::InvalidAction;
797 : }
798 : }
799 7 : else if (err != CHIP_ERROR_END_OF_TLV)
800 : {
801 0 : return Status::InvalidAction;
802 : }
803 :
804 304 : EventPathIBs::Parser eventPathListParser;
805 304 : err = subscribeRequestParser.GetEventRequests(&eventPathListParser);
806 304 : if (err == CHIP_NO_ERROR)
807 : {
808 18 : auto subjectDescriptor = apExchangeContext->GetSessionHandle()->AsSecureSession()->GetSubjectDescriptor();
809 18 : err = ParseEventPaths(subjectDescriptor, eventPathListParser, mayHaveValidEventPath, requestedEventPathCount);
810 18 : if (err != CHIP_NO_ERROR)
811 : {
812 0 : return Status::InvalidAction;
813 : }
814 : }
815 286 : else if (err != CHIP_ERROR_END_OF_TLV)
816 : {
817 0 : return Status::InvalidAction;
818 : }
819 :
820 304 : if (requestedAttributePathCount == 0 && requestedEventPathCount == 0)
821 : {
822 1 : ChipLogError(InteractionModel,
823 : "Subscription from [%u:" ChipLogFormatX64 "] has no attribute or event paths. Rejecting request.",
824 : apExchangeContext->GetSessionHandle()->GetFabricIndex(),
825 : ChipLogValueX64(apExchangeContext->GetSessionHandle()->AsSecureSession()->GetPeerNodeId()));
826 1 : return Status::InvalidAction;
827 : }
828 :
829 303 : if (!hasValidAttributePath && !mayHaveValidEventPath)
830 : {
831 3 : ChipLogError(InteractionModel,
832 : "Subscription from [%u:" ChipLogFormatX64 "] has no access at all. Rejecting request.",
833 : apExchangeContext->GetSessionHandle()->GetFabricIndex(),
834 : ChipLogValueX64(apExchangeContext->GetSessionHandle()->AsSecureSession()->GetPeerNodeId()));
835 3 : return Status::InvalidAction;
836 : }
837 :
838 : // The following cast is safe, since we can only hold a few tens of paths in one request.
839 300 : if (!EnsureResourceForSubscription(apExchangeContext->GetSessionHandle()->GetFabricIndex(), requestedAttributePathCount,
840 : requestedEventPathCount))
841 : {
842 2 : return Status::PathsExhausted;
843 : }
844 : }
845 306 : }
846 : else
847 : {
848 795 : System::PacketBufferTLVReader reader;
849 795 : reader.Init(aPayload.Retain());
850 :
851 795 : ReadRequestMessage::Parser readRequestParser;
852 795 : VerifyOrReturnError(readRequestParser.Init(reader) == CHIP_NO_ERROR, Status::InvalidAction);
853 :
854 : #if CHIP_CONFIG_IM_PRETTY_PRINT
855 791 : readRequestParser.PrettyPrint();
856 : #endif
857 : {
858 791 : size_t requestedAttributePathCount = 0;
859 791 : size_t requestedEventPathCount = 0;
860 791 : AttributePathIBs::Parser attributePathListParser;
861 791 : CHIP_ERROR err = readRequestParser.GetAttributeRequests(&attributePathListParser);
862 791 : if (err == CHIP_NO_ERROR)
863 : {
864 670 : TLV::TLVReader pathReader;
865 670 : attributePathListParser.GetReader(&pathReader);
866 670 : VerifyOrReturnError(TLV::Utilities::Count(pathReader, requestedAttributePathCount, false) == CHIP_NO_ERROR,
867 : Status::InvalidAction);
868 : }
869 121 : else if (err != CHIP_ERROR_END_OF_TLV)
870 : {
871 0 : return Status::InvalidAction;
872 : }
873 791 : EventPathIBs::Parser eventpathListParser;
874 791 : err = readRequestParser.GetEventRequests(&eventpathListParser);
875 791 : if (err == CHIP_NO_ERROR)
876 : {
877 317 : TLV::TLVReader pathReader;
878 317 : eventpathListParser.GetReader(&pathReader);
879 317 : VerifyOrReturnError(TLV::Utilities::Count(pathReader, requestedEventPathCount, false) == CHIP_NO_ERROR,
880 : Status::InvalidAction);
881 : }
882 474 : else if (err != CHIP_ERROR_END_OF_TLV)
883 : {
884 0 : return Status::InvalidAction;
885 : }
886 :
887 : // The following cast is safe, since we can only hold a few tens of paths in one request.
888 791 : Status checkResult = EnsureResourceForRead(apExchangeContext->GetSessionHandle()->GetFabricIndex(),
889 : requestedAttributePathCount, requestedEventPathCount);
890 791 : if (checkResult != Status::Success)
891 : {
892 7 : return checkResult;
893 : }
894 : }
895 795 : }
896 :
897 : // We have already reserved enough resources for read requests, and have granted enough resources for current subscriptions, so
898 : // we should be able to allocate resources requested by this request.
899 1082 : ReadHandler * handler = mReadHandlers.CreateObject(*this, apExchangeContext, aInteractionType, mReportScheduler);
900 1082 : if (handler == nullptr)
901 : {
902 0 : ChipLogProgress(InteractionModel, "no resource for %s interaction",
903 : aInteractionType == ReadHandler::InteractionType::Subscribe ? "Subscribe" : "Read");
904 0 : return Status::ResourceExhausted;
905 : }
906 :
907 1082 : handler->OnInitialRequest(std::move(aPayload));
908 :
909 1082 : return Status::Success;
910 : }
911 :
912 427 : Protocols::InteractionModel::Status InteractionModelEngine::OnWriteRequest(Messaging::ExchangeContext * apExchangeContext,
913 : const PayloadHeader & aPayloadHeader,
914 : System::PacketBufferHandle && aPayload,
915 : bool aIsTimedWrite)
916 : {
917 427 : ChipLogDetail(InteractionModel, "Received Write request");
918 :
919 429 : for (auto & writeHandler : mWriteHandlers)
920 : {
921 429 : if (writeHandler.IsFree())
922 : {
923 427 : VerifyOrReturnError(writeHandler.Init(GetDataModelProvider(), this) == CHIP_NO_ERROR, Status::Busy);
924 426 : return writeHandler.OnWriteRequest(apExchangeContext, std::move(aPayload), aIsTimedWrite);
925 : }
926 : }
927 0 : ChipLogProgress(InteractionModel, "no resource for write interaction");
928 0 : return Status::Busy;
929 : }
930 :
931 5 : CHIP_ERROR InteractionModelEngine::OnTimedRequest(Messaging::ExchangeContext * apExchangeContext,
932 : const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload,
933 : Protocols::InteractionModel::Status & aStatus)
934 : {
935 5 : TimedHandler * handler = mTimedHandlers.CreateObject(this);
936 5 : if (handler == nullptr)
937 : {
938 0 : ChipLogProgress(InteractionModel, "no resource for Timed interaction");
939 0 : aStatus = Status::Busy;
940 0 : return CHIP_ERROR_NO_MEMORY;
941 : }
942 :
943 : // The timed handler takes over handling of this exchange and will do its
944 : // own status reporting as needed.
945 5 : aStatus = Status::Success;
946 5 : apExchangeContext->SetDelegate(handler);
947 5 : return handler->OnMessageReceived(apExchangeContext, aPayloadHeader, std::move(aPayload));
948 : }
949 :
950 : #if CHIP_CONFIG_ENABLE_READ_CLIENT
951 87 : Status InteractionModelEngine::OnUnsolicitedReportData(Messaging::ExchangeContext * apExchangeContext,
952 : const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload)
953 : {
954 87 : System::PacketBufferTLVReader reader;
955 87 : reader.Init(aPayload.Retain());
956 :
957 87 : ReportDataMessage::Parser report;
958 87 : VerifyOrReturnError(report.Init(reader) == CHIP_NO_ERROR, Status::InvalidAction);
959 :
960 : #if CHIP_CONFIG_IM_PRETTY_PRINT
961 85 : report.PrettyPrint();
962 : #endif
963 :
964 85 : SubscriptionId subscriptionId = 0;
965 85 : VerifyOrReturnError(report.GetSubscriptionId(&subscriptionId) == CHIP_NO_ERROR, Status::InvalidAction);
966 84 : VerifyOrReturnError(report.ExitContainer() == CHIP_NO_ERROR, Status::InvalidAction);
967 :
968 84 : ReadClient * foundSubscription = nullptr;
969 312 : for (auto * readClient = mpActiveReadClientList; readClient != nullptr; readClient = readClient->GetNextClient())
970 : {
971 228 : auto peer = apExchangeContext->GetSessionHandle()->GetPeer();
972 228 : if (readClient->GetFabricIndex() != peer.GetFabricIndex() || readClient->GetPeerNodeId() != peer.GetNodeId())
973 : {
974 146 : continue;
975 : }
976 :
977 : // Notify Subscriptions about incoming communication from node
978 195 : readClient->OnUnsolicitedMessageFromPublisher();
979 :
980 195 : if (!readClient->IsSubscriptionActive())
981 : {
982 0 : continue;
983 : }
984 :
985 195 : if (!readClient->IsMatchingSubscriptionId(subscriptionId))
986 : {
987 113 : continue;
988 : }
989 :
990 82 : if (!foundSubscription)
991 : {
992 82 : foundSubscription = readClient;
993 : }
994 : }
995 :
996 84 : if (foundSubscription)
997 : {
998 82 : foundSubscription->OnUnsolicitedReportData(apExchangeContext, std::move(aPayload));
999 82 : return Status::Success;
1000 : }
1001 :
1002 2 : ChipLogDetail(InteractionModel, "Received report with invalid subscriptionId %" PRIu32, subscriptionId);
1003 :
1004 2 : return Status::InvalidSubscription;
1005 87 : }
1006 : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
1007 :
1008 1658 : CHIP_ERROR InteractionModelEngine::OnUnsolicitedMessageReceived(const PayloadHeader & payloadHeader,
1009 : ExchangeDelegate *& newDelegate)
1010 : {
1011 : // TODO: Implement OnUnsolicitedMessageReceived, let messaging layer dispatch message to ReadHandler/ReadClient/TimedHandler
1012 : // directly.
1013 1658 : newDelegate = this;
1014 1658 : return CHIP_NO_ERROR;
1015 : }
1016 :
1017 1658 : CHIP_ERROR InteractionModelEngine::OnMessageReceived(Messaging::ExchangeContext * apExchangeContext,
1018 : const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload)
1019 : {
1020 : using namespace Protocols::InteractionModel;
1021 :
1022 1658 : Protocols::InteractionModel::Status status = Status::Failure;
1023 :
1024 : // Ensure that DataModel::Provider has access to the exchange the message was received on.
1025 1658 : CurrentExchangeValueScope scopedExchangeContext(*this, apExchangeContext);
1026 :
1027 : // Group Message can only be an InvokeCommandRequest or WriteRequest
1028 1658 : if (apExchangeContext->IsGroupExchangeContext() &&
1029 1658 : !aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::InvokeCommandRequest) &&
1030 0 : !aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::WriteRequest))
1031 : {
1032 0 : ChipLogProgress(InteractionModel, "Msg type %d not supported for group message", aPayloadHeader.GetMessageType());
1033 0 : return CHIP_NO_ERROR;
1034 : }
1035 :
1036 1658 : if (aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::InvokeCommandRequest))
1037 : {
1038 32 : status = OnInvokeCommandRequest(apExchangeContext, aPayloadHeader, std::move(aPayload), /* aIsTimedInvoke = */ false);
1039 : }
1040 1626 : else if (aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::ReadRequest))
1041 : {
1042 795 : status = OnReadInitialRequest(apExchangeContext, aPayloadHeader, std::move(aPayload), ReadHandler::InteractionType::Read);
1043 : }
1044 831 : else if (aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::WriteRequest))
1045 : {
1046 426 : status = OnWriteRequest(apExchangeContext, aPayloadHeader, std::move(aPayload), /* aIsTimedWrite = */ false);
1047 : }
1048 405 : else if (aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::SubscribeRequest))
1049 : {
1050 306 : status =
1051 306 : OnReadInitialRequest(apExchangeContext, aPayloadHeader, std::move(aPayload), ReadHandler::InteractionType::Subscribe);
1052 : }
1053 : #if CHIP_CONFIG_ENABLE_READ_CLIENT
1054 99 : else if (aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::ReportData))
1055 : {
1056 87 : status = OnUnsolicitedReportData(apExchangeContext, aPayloadHeader, std::move(aPayload));
1057 : }
1058 : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
1059 12 : else if (aPayloadHeader.HasMessageType(MsgType::TimedRequest))
1060 : {
1061 5 : OnTimedRequest(apExchangeContext, aPayloadHeader, std::move(aPayload), status);
1062 : }
1063 : else
1064 : {
1065 7 : ChipLogProgress(InteractionModel, "Msg type %d not supported", aPayloadHeader.GetMessageType());
1066 7 : status = Status::InvalidAction;
1067 : }
1068 :
1069 1658 : if (status != Status::Success && !apExchangeContext->IsGroupExchangeContext())
1070 : {
1071 32 : return StatusResponse::Send(status, apExchangeContext, false /*aExpectResponse*/);
1072 : }
1073 :
1074 1626 : return CHIP_NO_ERROR;
1075 1658 : }
1076 :
1077 0 : void InteractionModelEngine::OnResponseTimeout(Messaging::ExchangeContext * ec)
1078 : {
1079 0 : ChipLogError(InteractionModel, "Time out! Failed to receive IM response from Exchange: " ChipLogFormatExchange,
1080 : ChipLogValueExchange(ec));
1081 0 : }
1082 :
1083 : #if CHIP_CONFIG_ENABLE_READ_CLIENT
1084 7 : void InteractionModelEngine::OnActiveModeNotification(ScopedNodeId aPeer)
1085 : {
1086 9 : for (ReadClient * pListItem = mpActiveReadClientList; pListItem != nullptr;)
1087 : {
1088 2 : auto pNextItem = pListItem->GetNextClient();
1089 : // It is possible that pListItem is destroyed by the app in OnActiveModeNotification.
1090 : // Get the next item before invoking `OnActiveModeNotification`.
1091 2 : if (ScopedNodeId(pListItem->GetPeerNodeId(), pListItem->GetFabricIndex()) == aPeer)
1092 : {
1093 2 : pListItem->OnActiveModeNotification();
1094 : }
1095 2 : pListItem = pNextItem;
1096 : }
1097 7 : }
1098 :
1099 5 : void InteractionModelEngine::OnPeerTypeChange(ScopedNodeId aPeer, ReadClient::PeerType aType)
1100 : {
1101 : // TODO: Follow up to use a iterator function to avoid copy/paste here.
1102 8 : for (ReadClient * pListItem = mpActiveReadClientList; pListItem != nullptr;)
1103 : {
1104 : // It is possible that pListItem is destroyed by the app in OnPeerTypeChange.
1105 : // Get the next item before invoking `OnPeerTypeChange`.
1106 3 : auto pNextItem = pListItem->GetNextClient();
1107 3 : if (ScopedNodeId(pListItem->GetPeerNodeId(), pListItem->GetFabricIndex()) == aPeer)
1108 : {
1109 3 : pListItem->OnPeerTypeChange(aType);
1110 : }
1111 3 : pListItem = pNextItem;
1112 : }
1113 5 : }
1114 :
1115 314 : void InteractionModelEngine::AddReadClient(ReadClient * apReadClient)
1116 : {
1117 314 : apReadClient->SetNextClient(mpActiveReadClientList);
1118 314 : mpActiveReadClientList = apReadClient;
1119 314 : }
1120 : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
1121 :
1122 6 : bool InteractionModelEngine::TrimFabricForSubscriptions(FabricIndex aFabricIndex, bool aForceEvict)
1123 : {
1124 6 : const size_t pathPoolCapacity = GetPathPoolCapacityForSubscriptions();
1125 6 : const size_t readHandlerPoolCapacity = GetReadHandlerPoolCapacityForSubscriptions();
1126 :
1127 6 : uint8_t fabricCount = mpFabricTable->FabricCount();
1128 6 : size_t attributePathsSubscribedByCurrentFabric = 0;
1129 6 : size_t eventPathsSubscribedByCurrentFabric = 0;
1130 6 : size_t subscriptionsEstablishedByCurrentFabric = 0;
1131 :
1132 6 : if (fabricCount == 0)
1133 : {
1134 0 : return false;
1135 : }
1136 :
1137 : // Note: This is OK only when we have assumed the fabricCount is not zero. Should be revised when adding support to
1138 : // subscriptions on PASE sessions.
1139 6 : size_t perFabricPathCapacity = pathPoolCapacity / static_cast<size_t>(fabricCount);
1140 6 : size_t perFabricSubscriptionCapacity = readHandlerPoolCapacity / static_cast<size_t>(fabricCount);
1141 :
1142 6 : ReadHandler * candidate = nullptr;
1143 6 : size_t candidateAttributePathsUsed = 0;
1144 6 : size_t candidateEventPathsUsed = 0;
1145 :
1146 : // It is safe to use & here since this function will be called on current stack.
1147 6 : mReadHandlers.ForEachActiveObject([&](ReadHandler * handler) {
1148 47 : if (handler->GetAccessingFabricIndex() != aFabricIndex || !handler->IsType(ReadHandler::InteractionType::Subscribe))
1149 : {
1150 13 : return Loop::Continue;
1151 : }
1152 :
1153 34 : size_t attributePathsUsed = handler->GetAttributePathCount();
1154 34 : size_t eventPathsUsed = handler->GetEventPathCount();
1155 :
1156 34 : attributePathsSubscribedByCurrentFabric += attributePathsUsed;
1157 34 : eventPathsSubscribedByCurrentFabric += eventPathsUsed;
1158 34 : subscriptionsEstablishedByCurrentFabric++;
1159 :
1160 34 : if (candidate == nullptr)
1161 : {
1162 6 : candidate = handler;
1163 : }
1164 : // This handler uses more resources than the one we picked before.
1165 28 : else if ((attributePathsUsed > perFabricPathCapacity || eventPathsUsed > perFabricPathCapacity) &&
1166 0 : (candidateAttributePathsUsed <= perFabricPathCapacity && candidateEventPathsUsed <= perFabricPathCapacity))
1167 : {
1168 0 : candidate = handler;
1169 0 : candidateAttributePathsUsed = attributePathsUsed;
1170 0 : candidateEventPathsUsed = eventPathsUsed;
1171 : }
1172 : // This handler is older than the one we picked before.
1173 28 : else if (handler->GetTransactionStartGeneration() < candidate->GetTransactionStartGeneration() &&
1174 : // And the level of resource usage is the same (both exceed or neither exceed)
1175 0 : ((attributePathsUsed > perFabricPathCapacity || eventPathsUsed > perFabricPathCapacity) ==
1176 0 : (candidateAttributePathsUsed > perFabricPathCapacity || candidateEventPathsUsed > perFabricPathCapacity)))
1177 : {
1178 0 : candidate = handler;
1179 : }
1180 34 : return Loop::Continue;
1181 : });
1182 :
1183 6 : if (candidate != nullptr &&
1184 6 : (aForceEvict || attributePathsSubscribedByCurrentFabric > perFabricPathCapacity ||
1185 0 : eventPathsSubscribedByCurrentFabric > perFabricPathCapacity ||
1186 0 : subscriptionsEstablishedByCurrentFabric > perFabricSubscriptionCapacity))
1187 : {
1188 : SubscriptionId subId;
1189 6 : candidate->GetSubscriptionId(subId);
1190 6 : ChipLogProgress(DataManagement, "Evicting Subscription ID %u:0x%" PRIx32, candidate->GetSubjectDescriptor().fabricIndex,
1191 : subId);
1192 6 : candidate->Close();
1193 6 : return true;
1194 : }
1195 0 : return false;
1196 : }
1197 :
1198 300 : bool InteractionModelEngine::EnsureResourceForSubscription(FabricIndex aFabricIndex, size_t aRequestedAttributePathCount,
1199 : size_t aRequestedEventPathCount)
1200 : {
1201 : #if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP && !CHIP_CONFIG_IM_FORCE_FABRIC_QUOTA_CHECK
1202 : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
1203 300 : const bool allowUnlimited = !mForceHandlerQuota;
1204 : #else // CONFIG_BUILD_FOR_HOST_UNIT_TEST
1205 : // If the resources are allocated on the heap, we should be able to handle as many Read / Subscribe requests as possible.
1206 : const bool allowUnlimited = true;
1207 : #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST
1208 : #else // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP && !CHIP_CONFIG_IM_FORCE_FABRIC_QUOTA_CHECK
1209 : const bool allowUnlimited = false;
1210 : #endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP && !CHIP_CONFIG_IM_FORCE_FABRIC_QUOTA_CHECK
1211 :
1212 : // Don't couple with read requests, always reserve enough resource for read requests.
1213 :
1214 300 : const size_t pathPoolCapacity = GetPathPoolCapacityForSubscriptions();
1215 300 : const size_t readHandlerPoolCapacity = GetReadHandlerPoolCapacityForSubscriptions();
1216 :
1217 : // If we return early here, the compiler will complain about the unreachable code, so we add a always-true check.
1218 300 : const size_t attributePathCap = allowUnlimited ? SIZE_MAX : pathPoolCapacity;
1219 300 : const size_t eventPathCap = allowUnlimited ? SIZE_MAX : pathPoolCapacity;
1220 300 : const size_t readHandlerCap = allowUnlimited ? SIZE_MAX : readHandlerPoolCapacity;
1221 :
1222 300 : size_t usedAttributePaths = 0;
1223 300 : size_t usedEventPaths = 0;
1224 300 : size_t usedReadHandlers = 0;
1225 :
1226 306 : auto countResourceUsage = [&]() {
1227 306 : usedAttributePaths = 0;
1228 306 : usedEventPaths = 0;
1229 306 : usedReadHandlers = 0;
1230 306 : mReadHandlers.ForEachActiveObject([&](auto * handler) {
1231 6388 : if (!handler->IsType(ReadHandler::InteractionType::Subscribe))
1232 : {
1233 34 : return Loop::Continue;
1234 : }
1235 6354 : usedAttributePaths += handler->GetAttributePathCount();
1236 6354 : usedEventPaths += handler->GetEventPathCount();
1237 6354 : usedReadHandlers++;
1238 6354 : return Loop::Continue;
1239 : });
1240 606 : };
1241 :
1242 300 : countResourceUsage();
1243 :
1244 300 : if (usedAttributePaths + aRequestedAttributePathCount <= attributePathCap &&
1245 293 : usedEventPaths + aRequestedEventPathCount <= eventPathCap && usedReadHandlers < readHandlerCap)
1246 : {
1247 : // We have enough resources, then we serve the requests in a best-effort manner.
1248 293 : return true;
1249 : }
1250 :
1251 7 : if ((aRequestedAttributePathCount > kMinSupportedPathsPerSubscription &&
1252 7 : usedAttributePaths + aRequestedAttributePathCount > attributePathCap) ||
1253 0 : (aRequestedEventPathCount > kMinSupportedPathsPerSubscription && usedEventPaths + aRequestedEventPathCount > eventPathCap))
1254 : {
1255 : // We cannot offer enough resources, and the subscription is requesting more than the spec limit.
1256 2 : return false;
1257 : }
1258 :
1259 6 : const auto evictAndUpdateResourceUsage = [&](FabricIndex fabricIndex, bool forceEvict) {
1260 6 : bool ret = TrimFabricForSubscriptions(fabricIndex, forceEvict);
1261 6 : countResourceUsage();
1262 6 : return ret;
1263 5 : };
1264 :
1265 : //
1266 : // At this point, we have an inbound request that respects minimas but we still don't have enough resources to handle it. Which
1267 : // means that we definitely have handlers on existing fabrics that are over limits and need to evict at least one of them to
1268 : // make space.
1269 : //
1270 : // There might be cases that one fabric has lots of subscriptions with one interested path, while the other fabrics are not
1271 : // using excess resources. So we need to do this multiple times until we have enough room or no fabrics are using excess
1272 : // resources.
1273 : //
1274 5 : bool didEvictHandler = true;
1275 16 : while (didEvictHandler)
1276 : {
1277 11 : didEvictHandler = false;
1278 18 : for (const auto & fabric : *mpFabricTable)
1279 : {
1280 : // The resources are enough to serve this request, do not evict anything.
1281 17 : if (usedAttributePaths + aRequestedAttributePathCount <= attributePathCap &&
1282 10 : usedEventPaths + aRequestedEventPathCount <= eventPathCap && usedReadHandlers < readHandlerCap)
1283 : {
1284 10 : break;
1285 : }
1286 7 : didEvictHandler = didEvictHandler || evictAndUpdateResourceUsage(fabric.GetFabricIndex(), false);
1287 : }
1288 : }
1289 :
1290 : // The above loop cannot guarantee the resources for the new subscriptions when the resource usage from all fabrics are exactly
1291 : // within the quota (which means we have exactly used all resources). Evict (from the large subscriptions first then from
1292 : // oldest) subscriptions from the current fabric until we have enough resource for the new subscription.
1293 5 : didEvictHandler = true;
1294 5 : while ((usedAttributePaths + aRequestedAttributePathCount > attributePathCap ||
1295 5 : usedEventPaths + aRequestedEventPathCount > eventPathCap || usedReadHandlers >= readHandlerCap) &&
1296 : // Avoid infinity loop
1297 : didEvictHandler)
1298 : {
1299 0 : didEvictHandler = evictAndUpdateResourceUsage(aFabricIndex, true);
1300 : }
1301 :
1302 : // If didEvictHandler is false, means the loop above evicted all subscriptions from the current fabric but we still don't have
1303 : // enough resources for the new subscription, this should never happen.
1304 : // This is safe as long as we have rejected subscriptions without a fabric associated (with a PASE session) before.
1305 : // Note: Spec#5141: should reject subscription requests on PASE sessions.
1306 5 : VerifyOrDieWithMsg(didEvictHandler, DataManagement, "Failed to get required resources by evicting existing subscriptions.");
1307 :
1308 : // We have ensured enough resources by the logic above.
1309 5 : return true;
1310 : }
1311 :
1312 31 : bool InteractionModelEngine::TrimFabricForRead(FabricIndex aFabricIndex)
1313 : {
1314 31 : const size_t guaranteedReadRequestsPerFabric = GetGuaranteedReadRequestsPerFabric();
1315 31 : const size_t minSupportedPathsPerFabricForRead = guaranteedReadRequestsPerFabric * kMinSupportedPathsPerReadRequest;
1316 :
1317 31 : size_t attributePathsUsedByCurrentFabric = 0;
1318 31 : size_t eventPathsUsedByCurrentFabric = 0;
1319 31 : size_t readTransactionsOnCurrentFabric = 0;
1320 :
1321 31 : ReadHandler * candidate = nullptr;
1322 31 : size_t candidateAttributePathsUsed = 0;
1323 31 : size_t candidateEventPathsUsed = 0;
1324 :
1325 : // It is safe to use & here since this function will be called on current stack.
1326 31 : mReadHandlers.ForEachActiveObject([&](ReadHandler * handler) {
1327 81 : if (handler->GetAccessingFabricIndex() != aFabricIndex || !handler->IsType(ReadHandler::InteractionType::Read))
1328 : {
1329 49 : return Loop::Continue;
1330 : }
1331 :
1332 32 : size_t attributePathsUsed = handler->GetAttributePathCount();
1333 32 : size_t eventPathsUsed = handler->GetEventPathCount();
1334 :
1335 32 : attributePathsUsedByCurrentFabric += attributePathsUsed;
1336 32 : eventPathsUsedByCurrentFabric += eventPathsUsed;
1337 32 : readTransactionsOnCurrentFabric++;
1338 :
1339 32 : if (candidate == nullptr)
1340 : {
1341 18 : candidate = handler;
1342 : }
1343 : // Oversized read handlers will be evicted first.
1344 14 : else if ((attributePathsUsed > kMinSupportedPathsPerReadRequest || eventPathsUsed > kMinSupportedPathsPerReadRequest) &&
1345 3 : (candidateAttributePathsUsed <= kMinSupportedPathsPerReadRequest &&
1346 1 : candidateEventPathsUsed <= kMinSupportedPathsPerReadRequest))
1347 : {
1348 1 : candidate = handler;
1349 : }
1350 : // Read Handlers are "first come first served", so we give eariler read transactions a higher priority.
1351 16 : else if (handler->GetTransactionStartGeneration() > candidate->GetTransactionStartGeneration() &&
1352 : // And the level of resource usage is the same (both exceed or neither exceed)
1353 3 : ((attributePathsUsed > kMinSupportedPathsPerReadRequest || eventPathsUsed > kMinSupportedPathsPerReadRequest) ==
1354 4 : (candidateAttributePathsUsed > kMinSupportedPathsPerReadRequest ||
1355 1 : candidateEventPathsUsed > kMinSupportedPathsPerReadRequest)))
1356 : {
1357 1 : candidate = handler;
1358 : }
1359 :
1360 32 : if (candidate == handler)
1361 : {
1362 20 : candidateAttributePathsUsed = attributePathsUsed;
1363 20 : candidateEventPathsUsed = eventPathsUsed;
1364 : }
1365 32 : return Loop::Continue;
1366 : });
1367 :
1368 49 : if (candidate != nullptr &&
1369 18 : ((attributePathsUsedByCurrentFabric > minSupportedPathsPerFabricForRead ||
1370 13 : eventPathsUsedByCurrentFabric > minSupportedPathsPerFabricForRead ||
1371 13 : readTransactionsOnCurrentFabric > guaranteedReadRequestsPerFabric) ||
1372 : // Always evict the transactions on PASE sessions if the fabric table is full.
1373 9 : (aFabricIndex == kUndefinedFabricIndex && mpFabricTable->FabricCount() == GetConfigMaxFabrics())))
1374 : {
1375 13 : candidate->Close();
1376 13 : return true;
1377 : }
1378 18 : return false;
1379 : }
1380 :
1381 791 : Protocols::InteractionModel::Status InteractionModelEngine::EnsureResourceForRead(FabricIndex aFabricIndex,
1382 : size_t aRequestedAttributePathCount,
1383 : size_t aRequestedEventPathCount)
1384 : {
1385 : #if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP && !CHIP_CONFIG_IM_FORCE_FABRIC_QUOTA_CHECK
1386 : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
1387 791 : const bool allowUnlimited = !mForceHandlerQuota;
1388 : #else // CONFIG_BUILD_FOR_HOST_UNIT_TEST
1389 : // If the resources are allocated on the heap, we should be able to handle as many Read / Subscribe requests as possible.
1390 : const bool allowUnlimited = true;
1391 : #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST
1392 : #else // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP && !CHIP_CONFIG_IM_FORCE_FABRIC_QUOTA_CHECK
1393 : const bool allowUnlimited = false;
1394 : #endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP && !CHIP_CONFIG_IM_FORCE_FABRIC_QUOTA_CHECK
1395 :
1396 : // If we return early here, the compiler will complain about the unreachable code, so we add a always-true check.
1397 791 : const size_t attributePathCap = allowUnlimited ? SIZE_MAX : GetPathPoolCapacityForReads();
1398 791 : const size_t eventPathCap = allowUnlimited ? SIZE_MAX : GetPathPoolCapacityForReads();
1399 791 : const size_t readHandlerCap = allowUnlimited ? SIZE_MAX : GetReadHandlerPoolCapacityForReads();
1400 :
1401 791 : const size_t guaranteedReadRequestsPerFabric = GetGuaranteedReadRequestsPerFabric();
1402 791 : const size_t guaranteedPathsPerFabric = kMinSupportedPathsPerReadRequest * guaranteedReadRequestsPerFabric;
1403 :
1404 791 : size_t usedAttributePaths = 0;
1405 791 : size_t usedEventPaths = 0;
1406 791 : size_t usedReadHandlers = 0;
1407 :
1408 822 : auto countResourceUsage = [&]() {
1409 822 : usedAttributePaths = 0;
1410 822 : usedEventPaths = 0;
1411 822 : usedReadHandlers = 0;
1412 822 : mReadHandlers.ForEachActiveObject([&](auto * handler) {
1413 178 : if (!handler->IsType(ReadHandler::InteractionType::Read))
1414 : {
1415 7 : return Loop::Continue;
1416 : }
1417 171 : usedAttributePaths += handler->GetAttributePathCount();
1418 171 : usedEventPaths += handler->GetEventPathCount();
1419 171 : usedReadHandlers++;
1420 171 : return Loop::Continue;
1421 : });
1422 1613 : };
1423 :
1424 835 : auto haveEnoughResourcesForTheRequest = [&]() {
1425 1652 : return usedAttributePaths + aRequestedAttributePathCount <= attributePathCap &&
1426 835 : usedEventPaths + aRequestedEventPathCount <= eventPathCap && usedReadHandlers < readHandlerCap;
1427 791 : };
1428 :
1429 791 : countResourceUsage();
1430 :
1431 791 : if (haveEnoughResourcesForTheRequest())
1432 : {
1433 : // We have enough resources, then we serve the requests in a best-effort manner.
1434 773 : return Status::Success;
1435 : }
1436 :
1437 18 : if ((aRequestedAttributePathCount > kMinSupportedPathsPerReadRequest &&
1438 4 : usedAttributePaths + aRequestedAttributePathCount > attributePathCap) ||
1439 15 : (aRequestedEventPathCount > kMinSupportedPathsPerReadRequest && usedEventPaths + aRequestedEventPathCount > eventPathCap))
1440 : {
1441 : // We cannot offer enough resources, and the read transaction is requesting more than the spec limit.
1442 3 : return Status::PathsExhausted;
1443 : }
1444 :
1445 : // If we have commissioned CHIP_CONFIG_MAX_FABRICS already, and this transaction doesn't have an associated fabric index, reject
1446 : // the request if we don't have sufficient resources for this request.
1447 15 : if (mpFabricTable->FabricCount() == GetConfigMaxFabrics() && aFabricIndex == kUndefinedFabricIndex)
1448 : {
1449 1 : return Status::Busy;
1450 : }
1451 :
1452 14 : size_t usedAttributePathsInFabric = 0;
1453 14 : size_t usedEventPathsInFabric = 0;
1454 14 : size_t usedReadHandlersInFabric = 0;
1455 14 : mReadHandlers.ForEachActiveObject([&](auto * handler) {
1456 35 : if (!handler->IsType(ReadHandler::InteractionType::Read) || handler->GetAccessingFabricIndex() != aFabricIndex)
1457 : {
1458 33 : return Loop::Continue;
1459 : }
1460 2 : usedAttributePathsInFabric += handler->GetAttributePathCount();
1461 2 : usedEventPathsInFabric += handler->GetEventPathCount();
1462 2 : usedReadHandlersInFabric++;
1463 2 : return Loop::Continue;
1464 : });
1465 :
1466 : // Busy, since there are already some read requests ongoing on this fabric, please retry later.
1467 14 : if (usedAttributePathsInFabric + aRequestedAttributePathCount > guaranteedPathsPerFabric ||
1468 11 : usedEventPathsInFabric + aRequestedEventPathCount > guaranteedPathsPerFabric ||
1469 11 : usedReadHandlersInFabric >= guaranteedReadRequestsPerFabric)
1470 : {
1471 3 : return Status::Busy;
1472 : }
1473 :
1474 31 : const auto evictAndUpdateResourceUsage = [&](FabricIndex fabricIndex) {
1475 31 : bool ret = TrimFabricForRead(fabricIndex);
1476 31 : countResourceUsage();
1477 31 : return ret;
1478 11 : };
1479 :
1480 : //
1481 : // At this point, we have an inbound request that respects minimas but we still don't have enough resources to handle it. Which
1482 : // means that we definitely have handlers on existing fabrics that are over limits and need to evict at least one of them to
1483 : // make space.
1484 : //
1485 11 : bool didEvictHandler = true;
1486 21 : while (didEvictHandler)
1487 : {
1488 21 : didEvictHandler = false;
1489 21 : didEvictHandler = didEvictHandler || evictAndUpdateResourceUsage(kUndefinedFabricIndex);
1490 21 : if (haveEnoughResourcesForTheRequest())
1491 : {
1492 11 : break;
1493 : }
1494 : // If the fabric table is full, we won't evict read requests from normal fabrics before we have evicted all read requests
1495 : // from PASE sessions.
1496 10 : if (mpFabricTable->FabricCount() == GetConfigMaxFabrics() && didEvictHandler)
1497 : {
1498 1 : continue;
1499 : }
1500 13 : for (const auto & fabric : *mpFabricTable)
1501 : {
1502 12 : didEvictHandler = didEvictHandler || evictAndUpdateResourceUsage(fabric.GetFabricIndex());
1503 : // If we now have enough resources to serve this request, stop evicting things.
1504 12 : if (haveEnoughResourcesForTheRequest())
1505 : {
1506 8 : break;
1507 : }
1508 : }
1509 : }
1510 :
1511 : // Now all fabrics are not oversized (since we have trimmed the oversized fabrics in the loop above), and the read handler is
1512 : // also not oversized, we should be able to handle this read transaction.
1513 11 : VerifyOrDie(haveEnoughResourcesForTheRequest());
1514 :
1515 11 : return Status::Success;
1516 : }
1517 :
1518 : #if CHIP_CONFIG_ENABLE_READ_CLIENT
1519 149 : void InteractionModelEngine::RemoveReadClient(ReadClient * apReadClient)
1520 : {
1521 149 : ReadClient * pPrevListItem = nullptr;
1522 149 : ReadClient * pCurListItem = mpActiveReadClientList;
1523 :
1524 154 : while (pCurListItem != apReadClient)
1525 : {
1526 : //
1527 : // Item must exist in this tracker list. If not, there's a bug somewhere.
1528 : //
1529 5 : VerifyOrDie(pCurListItem != nullptr);
1530 :
1531 5 : pPrevListItem = pCurListItem;
1532 5 : pCurListItem = pCurListItem->GetNextClient();
1533 : }
1534 :
1535 149 : if (pPrevListItem)
1536 : {
1537 3 : pPrevListItem->SetNextClient(apReadClient->GetNextClient());
1538 : }
1539 : else
1540 : {
1541 146 : mpActiveReadClientList = apReadClient->GetNextClient();
1542 : }
1543 :
1544 149 : apReadClient->SetNextClient(nullptr);
1545 149 : }
1546 :
1547 95 : size_t InteractionModelEngine::GetNumActiveReadClients()
1548 : {
1549 95 : ReadClient * pListItem = mpActiveReadClientList;
1550 95 : size_t count = 0;
1551 :
1552 95 : while (pListItem)
1553 : {
1554 0 : pListItem = pListItem->GetNextClient();
1555 0 : count++;
1556 : }
1557 :
1558 95 : return count;
1559 : }
1560 :
1561 14 : bool InteractionModelEngine::InActiveReadClientList(ReadClient * apReadClient)
1562 : {
1563 14 : ReadClient * pListItem = mpActiveReadClientList;
1564 :
1565 14 : while (pListItem)
1566 : {
1567 14 : if (pListItem == apReadClient)
1568 : {
1569 14 : return true;
1570 : }
1571 :
1572 0 : pListItem = pListItem->GetNextClient();
1573 : }
1574 :
1575 0 : return false;
1576 : }
1577 : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
1578 :
1579 2490 : bool InteractionModelEngine::HasConflictWriteRequests(const WriteHandler * apWriteHandler, const ConcreteAttributePath & aPath)
1580 : {
1581 12434 : for (auto & writeHandler : mWriteHandlers)
1582 : {
1583 9948 : if (writeHandler.IsFree() || &writeHandler == apWriteHandler)
1584 : {
1585 9936 : continue;
1586 : }
1587 12 : if (writeHandler.IsCurrentlyProcessingWritePath(aPath))
1588 : {
1589 4 : return true;
1590 : }
1591 : }
1592 2486 : return false;
1593 : }
1594 :
1595 1137 : void InteractionModelEngine::ReleaseAttributePathList(SingleLinkedListNode<AttributePathParams> *& aAttributePathList)
1596 : {
1597 1137 : ReleasePool(aAttributePathList, mAttributePathPool);
1598 1137 : }
1599 :
1600 1558 : CHIP_ERROR InteractionModelEngine::PushFrontAttributePathList(SingleLinkedListNode<AttributePathParams> *& aAttributePathList,
1601 : AttributePathParams & aAttributePath)
1602 : {
1603 1558 : CHIP_ERROR err = PushFront(aAttributePathList, aAttributePath, mAttributePathPool);
1604 1558 : if (err == CHIP_ERROR_NO_MEMORY)
1605 : {
1606 0 : ChipLogError(InteractionModel, "AttributePath pool full");
1607 0 : return CHIP_IM_GLOBAL_STATUS(PathsExhausted);
1608 : }
1609 1558 : return err;
1610 : }
1611 :
1612 1604 : bool InteractionModelEngine::IsExistentAttributePath(const ConcreteAttributePath & path)
1613 : {
1614 1604 : DataModel::AttributeFinder finder(mDataModelProvider);
1615 1604 : return finder.Find(path).has_value();
1616 1604 : }
1617 :
1618 971 : void InteractionModelEngine::RemoveDuplicateConcreteAttributePath(SingleLinkedListNode<AttributePathParams> *& aAttributePaths)
1619 : {
1620 971 : SingleLinkedListNode<AttributePathParams> * prev = nullptr;
1621 971 : auto * path1 = aAttributePaths;
1622 :
1623 2526 : while (path1 != nullptr)
1624 : {
1625 1555 : bool duplicate = false;
1626 :
1627 : // skip all wildcard paths and invalid concrete attribute
1628 2804 : if (path1->mValue.IsWildcardPath() ||
1629 1249 : !IsExistentAttributePath(
1630 2804 : ConcreteAttributePath(path1->mValue.mEndpointId, path1->mValue.mClusterId, path1->mValue.mAttributeId)))
1631 : {
1632 576 : prev = path1;
1633 576 : path1 = path1->mpNext;
1634 576 : continue;
1635 : }
1636 :
1637 : // Check whether a wildcard path expands to something that includes this concrete path.
1638 3334 : for (auto * path2 = aAttributePaths; path2 != nullptr; path2 = path2->mpNext)
1639 : {
1640 2364 : if (path2 == path1)
1641 : {
1642 975 : continue;
1643 : }
1644 :
1645 1389 : if (path2->mValue.IsWildcardPath() && path2->mValue.IsAttributePathSupersetOf(path1->mValue))
1646 : {
1647 9 : duplicate = true;
1648 9 : break;
1649 : }
1650 : }
1651 :
1652 : // if path1 duplicates something from wildcard expansion, discard path1
1653 979 : if (!duplicate)
1654 : {
1655 970 : prev = path1;
1656 970 : path1 = path1->mpNext;
1657 970 : continue;
1658 : }
1659 :
1660 9 : if (path1 == aAttributePaths)
1661 : {
1662 5 : aAttributePaths = path1->mpNext;
1663 5 : mAttributePathPool.ReleaseObject(path1);
1664 5 : path1 = aAttributePaths;
1665 : }
1666 : else
1667 : {
1668 4 : prev->mpNext = path1->mpNext;
1669 4 : mAttributePathPool.ReleaseObject(path1);
1670 4 : path1 = prev->mpNext;
1671 : }
1672 : }
1673 971 : }
1674 :
1675 1129 : void InteractionModelEngine::ReleaseEventPathList(SingleLinkedListNode<EventPathParams> *& aEventPathList)
1676 : {
1677 1129 : ReleasePool(aEventPathList, mEventPathPool);
1678 1129 : }
1679 :
1680 497 : CHIP_ERROR InteractionModelEngine::PushFrontEventPathParamsList(SingleLinkedListNode<EventPathParams> *& aEventPathList,
1681 : EventPathParams & aEventPath)
1682 : {
1683 497 : CHIP_ERROR err = PushFront(aEventPathList, aEventPath, mEventPathPool);
1684 497 : if (err == CHIP_ERROR_NO_MEMORY)
1685 : {
1686 0 : ChipLogError(InteractionModel, "EventPath pool full");
1687 0 : return CHIP_IM_GLOBAL_STATUS(PathsExhausted);
1688 : }
1689 497 : return err;
1690 : }
1691 :
1692 2208 : void InteractionModelEngine::ReleaseDataVersionFilterList(SingleLinkedListNode<DataVersionFilter> *& aDataVersionFilterList)
1693 : {
1694 2208 : ReleasePool(aDataVersionFilterList, mDataVersionFilterPool);
1695 2208 : }
1696 :
1697 2492 : CHIP_ERROR InteractionModelEngine::PushFrontDataVersionFilterList(SingleLinkedListNode<DataVersionFilter> *& aDataVersionFilterList,
1698 : DataVersionFilter & aDataVersionFilter)
1699 : {
1700 2492 : CHIP_ERROR err = PushFront(aDataVersionFilterList, aDataVersionFilter, mDataVersionFilterPool);
1701 2492 : if (err == CHIP_ERROR_NO_MEMORY)
1702 : {
1703 0 : ChipLogError(InteractionModel, "DataVersionFilter pool full, ignore this filter");
1704 0 : err = CHIP_NO_ERROR;
1705 : }
1706 2492 : return err;
1707 : }
1708 :
1709 : template <typename T, size_t N>
1710 4474 : void InteractionModelEngine::ReleasePool(SingleLinkedListNode<T> *& aObjectList,
1711 : ObjectPool<SingleLinkedListNode<T>, N> & aObjectPool)
1712 : {
1713 4474 : SingleLinkedListNode<T> * current = aObjectList;
1714 9012 : while (current != nullptr)
1715 : {
1716 4538 : SingleLinkedListNode<T> * nextObject = current->mpNext;
1717 4538 : aObjectPool.ReleaseObject(current);
1718 4538 : current = nextObject;
1719 : }
1720 :
1721 4474 : aObjectList = nullptr;
1722 4474 : }
1723 :
1724 : template <typename T, size_t N>
1725 4547 : CHIP_ERROR InteractionModelEngine::PushFront(SingleLinkedListNode<T> *& aObjectList, T & aData,
1726 : ObjectPool<SingleLinkedListNode<T>, N> & aObjectPool)
1727 : {
1728 4547 : SingleLinkedListNode<T> * object = aObjectPool.CreateObject();
1729 4547 : if (object == nullptr)
1730 : {
1731 0 : return CHIP_ERROR_NO_MEMORY;
1732 : }
1733 4547 : object->mValue = aData;
1734 4547 : object->mpNext = aObjectList;
1735 4547 : aObjectList = object;
1736 4547 : return CHIP_NO_ERROR;
1737 : }
1738 :
1739 23 : void InteractionModelEngine::DispatchCommand(CommandHandlerImpl & apCommandObj, const ConcreteCommandPath & aCommandPath,
1740 : TLV::TLVReader & apPayload)
1741 : {
1742 23 : Access::SubjectDescriptor subjectDescriptor = apCommandObj.GetSubjectDescriptor();
1743 :
1744 23 : DataModel::InvokeRequest request;
1745 23 : request.path = aCommandPath;
1746 23 : request.invokeFlags.Set(DataModel::InvokeFlags::kTimed, apCommandObj.IsTimedInvoke());
1747 23 : request.subjectDescriptor = &subjectDescriptor;
1748 :
1749 23 : std::optional<DataModel::ActionReturnStatus> status = GetDataModelProvider()->InvokeCommand(request, apPayload, &apCommandObj);
1750 :
1751 : // Provider indicates that handler status or data was already set (or will be set asynchronously) by
1752 : // returning std::nullopt. If any other value is returned, it is requesting that a status is set. This
1753 : // includes CHIP_NO_ERROR: in this case CHIP_NO_ERROR would mean set a `status success on the command`
1754 23 : if (status.has_value())
1755 : {
1756 0 : apCommandObj.AddStatus(aCommandPath, status->GetStatusCode());
1757 : }
1758 23 : }
1759 :
1760 30 : Protocols::InteractionModel::Status InteractionModelEngine::ValidateCommandCanBeDispatched(const DataModel::InvokeRequest & request)
1761 : {
1762 :
1763 30 : DataModel::AcceptedCommandEntry acceptedCommandEntry;
1764 :
1765 30 : Status status = CheckCommandExistence(request.path, acceptedCommandEntry);
1766 :
1767 30 : if (status != Status::Success)
1768 : {
1769 7 : ChipLogDetail(DataManagement, "No command " ChipLogFormatMEI " in Cluster " ChipLogFormatMEI " on Endpoint %u",
1770 : ChipLogValueMEI(request.path.mCommandId), ChipLogValueMEI(request.path.mClusterId), request.path.mEndpointId);
1771 7 : return status;
1772 : }
1773 :
1774 23 : status = CheckCommandAccess(request, acceptedCommandEntry);
1775 23 : VerifyOrReturnValue(status == Status::Success, status);
1776 :
1777 23 : return CheckCommandFlags(request, acceptedCommandEntry);
1778 : }
1779 :
1780 23 : Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandAccess(const DataModel::InvokeRequest & aRequest,
1781 : const DataModel::AcceptedCommandEntry & entry)
1782 : {
1783 23 : if (aRequest.subjectDescriptor == nullptr)
1784 : {
1785 0 : return Status::UnsupportedAccess; // we require a subject for invoke
1786 : }
1787 :
1788 23 : Access::RequestPath requestPath{ .cluster = aRequest.path.mClusterId,
1789 23 : .endpoint = aRequest.path.mEndpointId,
1790 : .requestType = Access::RequestType::kCommandInvokeRequest,
1791 23 : .entityId = aRequest.path.mCommandId };
1792 :
1793 23 : CHIP_ERROR err = Access::GetAccessControl().Check(*aRequest.subjectDescriptor, requestPath, entry.invokePrivilege);
1794 23 : if (err != CHIP_NO_ERROR)
1795 : {
1796 0 : if ((err != CHIP_ERROR_ACCESS_DENIED) && (err != CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL))
1797 : {
1798 0 : return Status::Failure;
1799 : }
1800 0 : return err == CHIP_ERROR_ACCESS_DENIED ? Status::UnsupportedAccess : Status::AccessRestricted;
1801 : }
1802 :
1803 23 : return Status::Success;
1804 : }
1805 :
1806 23 : Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandFlags(const DataModel::InvokeRequest & aRequest,
1807 : const DataModel::AcceptedCommandEntry & entry)
1808 : {
1809 23 : const bool commandNeedsTimedInvoke = entry.flags.Has(DataModel::CommandQualityFlags::kTimed);
1810 23 : const bool commandIsFabricScoped = entry.flags.Has(DataModel::CommandQualityFlags::kFabricScoped);
1811 :
1812 23 : if (commandNeedsTimedInvoke && !aRequest.invokeFlags.Has(DataModel::InvokeFlags::kTimed))
1813 : {
1814 0 : return Status::NeedsTimedInteraction;
1815 : }
1816 :
1817 23 : if (commandIsFabricScoped)
1818 : {
1819 : // SPEC: Else if the command in the path is fabric-scoped and there is no accessing fabric,
1820 : // a CommandStatusIB SHALL be generated with the UNSUPPORTED_ACCESS Status Code.
1821 :
1822 : // Fabric-scoped commands are not allowed before a specific accessing fabric is available.
1823 : // This is mostly just during a PASE session before AddNOC.
1824 0 : if (aRequest.GetAccessingFabricIndex() == kUndefinedFabricIndex)
1825 : {
1826 0 : return Status::UnsupportedAccess;
1827 : }
1828 : }
1829 :
1830 23 : return Status::Success;
1831 : }
1832 :
1833 30 : Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandExistence(const ConcreteCommandPath & aCommandPath,
1834 : DataModel::AcceptedCommandEntry & entry)
1835 : {
1836 30 : auto provider = GetDataModelProvider();
1837 :
1838 30 : DataModel::ListBuilder<DataModel::AcceptedCommandEntry> acceptedCommands;
1839 30 : (void) provider->AcceptedCommands(aCommandPath, acceptedCommands);
1840 46 : for (auto & existing : acceptedCommands.TakeBuffer())
1841 : {
1842 39 : if (existing.commandId == aCommandPath.mCommandId)
1843 : {
1844 23 : entry = existing;
1845 23 : return Protocols::InteractionModel::Status::Success;
1846 : }
1847 30 : }
1848 :
1849 : // invalid command, return the right failure status
1850 7 : return DataModel::ValidateClusterPath(provider, aCommandPath, Protocols::InteractionModel::Status::UnsupportedCommand);
1851 30 : }
1852 :
1853 502 : DataModel::Provider * InteractionModelEngine::SetDataModelProvider(DataModel::Provider * model)
1854 : {
1855 : // Altering data model should not be done while IM is actively handling requests.
1856 502 : VerifyOrDie(mReadHandlers.begin() == mReadHandlers.end());
1857 :
1858 502 : if (model == mDataModelProvider)
1859 : {
1860 : // no-op, just return
1861 18 : return model;
1862 : }
1863 :
1864 484 : DataModel::Provider * oldModel = mDataModelProvider;
1865 484 : if (oldModel != nullptr)
1866 : {
1867 238 : CHIP_ERROR err = oldModel->Shutdown();
1868 238 : if (err != CHIP_NO_ERROR)
1869 : {
1870 0 : ChipLogError(InteractionModel, "Failure on interaction model shutdown: %" CHIP_ERROR_FORMAT, err.Format());
1871 : }
1872 : }
1873 :
1874 484 : mDataModelProvider = model;
1875 484 : if (mDataModelProvider != nullptr)
1876 : {
1877 246 : DataModel::InteractionModelContext context;
1878 :
1879 246 : context.eventsGenerator = &EventManagement::GetInstance();
1880 246 : context.dataModelChangeListener = &mReportingEngine;
1881 246 : context.actionContext = this;
1882 :
1883 246 : CHIP_ERROR err = mDataModelProvider->Startup(context);
1884 246 : if (err != CHIP_NO_ERROR)
1885 : {
1886 0 : ChipLogError(InteractionModel, "Failure on interaction model startup: %" CHIP_ERROR_FORMAT, err.Format());
1887 : }
1888 : }
1889 :
1890 484 : return oldModel;
1891 : }
1892 :
1893 9737 : DataModel::Provider * InteractionModelEngine::GetDataModelProvider() const
1894 : {
1895 : // These should be called within the CHIP processing loop.
1896 9737 : assertChipStackLockedByCurrentThread();
1897 :
1898 9737 : return mDataModelProvider;
1899 : }
1900 :
1901 2 : void InteractionModelEngine::OnTimedInteractionFailed(TimedHandler * apTimedHandler)
1902 : {
1903 2 : mTimedHandlers.ReleaseObject(apTimedHandler);
1904 2 : }
1905 :
1906 1 : void InteractionModelEngine::OnTimedInvoke(TimedHandler * apTimedHandler, Messaging::ExchangeContext * apExchangeContext,
1907 : const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload)
1908 : {
1909 : using namespace Protocols::InteractionModel;
1910 :
1911 : // Reset the ourselves as the exchange delegate for now, to match what we'd
1912 : // do with an initial unsolicited invoke.
1913 1 : apExchangeContext->SetDelegate(this);
1914 1 : mTimedHandlers.ReleaseObject(apTimedHandler);
1915 :
1916 1 : VerifyOrDie(aPayloadHeader.HasMessageType(MsgType::InvokeCommandRequest));
1917 1 : VerifyOrDie(!apExchangeContext->IsGroupExchangeContext());
1918 :
1919 1 : Status status = OnInvokeCommandRequest(apExchangeContext, aPayloadHeader, std::move(aPayload), /* aIsTimedInvoke = */ true);
1920 1 : if (status != Status::Success)
1921 : {
1922 0 : StatusResponse::Send(status, apExchangeContext, /* aExpectResponse = */ false);
1923 : }
1924 1 : }
1925 :
1926 1 : void InteractionModelEngine::OnTimedWrite(TimedHandler * apTimedHandler, Messaging::ExchangeContext * apExchangeContext,
1927 : const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload)
1928 : {
1929 : using namespace Protocols::InteractionModel;
1930 :
1931 : // Reset the ourselves as the exchange delegate for now, to match what we'd
1932 : // do with an initial unsolicited write.
1933 1 : apExchangeContext->SetDelegate(this);
1934 1 : mTimedHandlers.ReleaseObject(apTimedHandler);
1935 :
1936 1 : VerifyOrDie(aPayloadHeader.HasMessageType(MsgType::WriteRequest));
1937 1 : VerifyOrDie(!apExchangeContext->IsGroupExchangeContext());
1938 :
1939 1 : Status status = OnWriteRequest(apExchangeContext, aPayloadHeader, std::move(aPayload), /* aIsTimedWrite = */ true);
1940 1 : if (status != Status::Success)
1941 : {
1942 1 : StatusResponse::Send(status, apExchangeContext, /* aExpectResponse = */ false);
1943 : }
1944 1 : }
1945 :
1946 0 : bool InteractionModelEngine::HasActiveRead()
1947 : {
1948 0 : return ((mReadHandlers.ForEachActiveObject([](ReadHandler * handler) {
1949 0 : if (handler->IsType(ReadHandler::InteractionType::Read))
1950 : {
1951 0 : return Loop::Break;
1952 : }
1953 :
1954 0 : return Loop::Continue;
1955 0 : }) == Loop::Break));
1956 : }
1957 :
1958 0 : uint16_t InteractionModelEngine::GetMinGuaranteedSubscriptionsPerFabric() const
1959 : {
1960 : #if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
1961 0 : return UINT16_MAX;
1962 : #else
1963 : return static_cast<uint16_t>(
1964 : std::min(GetReadHandlerPoolCapacityForSubscriptions() / GetConfigMaxFabrics(), static_cast<size_t>(UINT16_MAX)));
1965 : #endif
1966 : }
1967 :
1968 5 : size_t InteractionModelEngine::GetNumDirtySubscriptions() const
1969 : {
1970 5 : size_t numDirtySubscriptions = 0;
1971 5 : mReadHandlers.ForEachActiveObject([&](const auto readHandler) {
1972 33 : if (readHandler->IsType(ReadHandler::InteractionType::Subscribe) && readHandler->IsDirty())
1973 : {
1974 8 : numDirtySubscriptions++;
1975 : }
1976 33 : return Loop::Continue;
1977 : });
1978 5 : return numDirtySubscriptions;
1979 : }
1980 :
1981 7 : void InteractionModelEngine::OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex)
1982 : {
1983 7 : mReadHandlers.ForEachActiveObject([fabricIndex](ReadHandler * handler) {
1984 67 : if (handler->GetAccessingFabricIndex() == fabricIndex)
1985 : {
1986 67 : ChipLogProgress(InteractionModel, "Deleting expired ReadHandler for NodeId: " ChipLogFormatX64 ", FabricIndex: %u",
1987 : ChipLogValueX64(handler->GetInitiatorNodeId()), fabricIndex);
1988 67 : handler->Close();
1989 : }
1990 :
1991 67 : return Loop::Continue;
1992 : });
1993 :
1994 : #if CHIP_CONFIG_ENABLE_READ_CLIENT
1995 141 : for (auto * readClient = mpActiveReadClientList; readClient != nullptr;)
1996 : {
1997 : // ReadClient::Close may delete the read client so that readClient->GetNextClient() will be use-after-free.
1998 : // We need save readClient as nextReadClient before closing.
1999 134 : if (readClient->GetFabricIndex() == fabricIndex)
2000 : {
2001 67 : ChipLogProgress(InteractionModel, "Fabric removed, deleting obsolete read client with FabricIndex: %u", fabricIndex);
2002 67 : auto * nextReadClient = readClient->GetNextClient();
2003 67 : readClient->Close(CHIP_ERROR_IM_FABRIC_DELETED, false);
2004 67 : readClient = nextReadClient;
2005 : }
2006 : else
2007 : {
2008 67 : readClient = readClient->GetNextClient();
2009 : }
2010 : }
2011 : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
2012 :
2013 35 : for (auto & handler : mWriteHandlers)
2014 : {
2015 28 : if (!(handler.IsFree()) && handler.GetAccessingFabricIndex() == fabricIndex)
2016 : {
2017 1 : ChipLogProgress(InteractionModel, "Fabric removed, deleting obsolete write handler with FabricIndex: %u", fabricIndex);
2018 1 : handler.Close();
2019 : }
2020 : }
2021 :
2022 : // Applications may hold references to CommandHandlerImpl instances for async command processing.
2023 : // Therefore we can't forcible destroy CommandHandlers here. Their exchanges will get closed by
2024 : // the fabric removal, though, so they will fail when they try to actually send their command response
2025 : // and will close at that point.
2026 7 : }
2027 :
2028 1 : CHIP_ERROR InteractionModelEngine::ResumeSubscriptions()
2029 : {
2030 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
2031 1 : VerifyOrReturnError(mpSubscriptionResumptionStorage, CHIP_NO_ERROR);
2032 : #if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2033 1 : VerifyOrReturnError(!mSubscriptionResumptionScheduled, CHIP_NO_ERROR);
2034 : #endif
2035 :
2036 : // To avoid the case of a reboot loop causing rapid traffic generation / power consumption, subscription resumption should make
2037 : // use of the persisted min-interval values, and wait before resumption. Ideally, each persisted subscription should wait their
2038 : // own min-interval value before resumption, but that both A) potentially runs into a timer resource issue, and B) having a
2039 : // low-powered device wake many times also has energy use implications. The logic below waits the largest of the persisted
2040 : // min-interval values before resuming subscriptions.
2041 :
2042 : // Even though this causes subscription-to-subscription interaction by linking the min-interval values, this is the right thing
2043 : // to do for now because it's both simple and avoids the timer resource and multiple-wake problems. This issue is to track
2044 : // future improvements: https://github.com/project-chip/connectedhomeip/issues/25439
2045 :
2046 1 : SubscriptionResumptionStorage::SubscriptionInfo subscriptionInfo;
2047 1 : auto * iterator = mpSubscriptionResumptionStorage->IterateSubscriptions();
2048 1 : mNumOfSubscriptionsToResume = 0;
2049 1 : uint16_t minInterval = 0;
2050 1 : while (iterator->Next(subscriptionInfo))
2051 : {
2052 0 : mNumOfSubscriptionsToResume++;
2053 0 : minInterval = std::max(minInterval, subscriptionInfo.mMinInterval);
2054 : }
2055 1 : iterator->Release();
2056 :
2057 1 : if (mNumOfSubscriptionsToResume)
2058 : {
2059 : #if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2060 0 : mSubscriptionResumptionScheduled = true;
2061 : #endif
2062 0 : ChipLogProgress(InteractionModel, "Resuming %d subscriptions in %u seconds", mNumOfSubscriptionsToResume, minInterval);
2063 0 : ReturnErrorOnFailure(mpExchangeMgr->GetSessionManager()->SystemLayer()->StartTimer(System::Clock::Seconds16(minInterval),
2064 : ResumeSubscriptionsTimerCallback, this));
2065 : }
2066 : else
2067 : {
2068 1 : ChipLogProgress(InteractionModel, "No subscriptions to resume");
2069 : }
2070 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
2071 :
2072 1 : return CHIP_NO_ERROR;
2073 1 : }
2074 :
2075 0 : void InteractionModelEngine::ResumeSubscriptionsTimerCallback(System::Layer * apSystemLayer, void * apAppState)
2076 : {
2077 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
2078 0 : VerifyOrReturn(apAppState != nullptr);
2079 0 : InteractionModelEngine * imEngine = static_cast<InteractionModelEngine *>(apAppState);
2080 : #if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2081 0 : imEngine->mSubscriptionResumptionScheduled = false;
2082 0 : bool resumedSubscriptions = false;
2083 : #endif // CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2084 0 : SubscriptionResumptionStorage::SubscriptionInfo subscriptionInfo;
2085 0 : AutoReleaseSubscriptionInfoIterator iterator(imEngine->mpSubscriptionResumptionStorage->IterateSubscriptions());
2086 0 : while (iterator->Next(subscriptionInfo))
2087 : {
2088 : // If subscription happens between reboot and this timer callback, it's already live and should skip resumption
2089 0 : if (Loop::Break == imEngine->mReadHandlers.ForEachActiveObject([&](ReadHandler * handler) {
2090 : SubscriptionId subscriptionId;
2091 0 : handler->GetSubscriptionId(subscriptionId);
2092 0 : if (subscriptionId == subscriptionInfo.mSubscriptionId)
2093 : {
2094 0 : return Loop::Break;
2095 : }
2096 0 : return Loop::Continue;
2097 : }))
2098 : {
2099 0 : ChipLogProgress(InteractionModel, "Skip resuming live subscriptionId %" PRIu32, subscriptionInfo.mSubscriptionId);
2100 0 : continue;
2101 : }
2102 :
2103 0 : auto subscriptionResumptionSessionEstablisher = Platform::MakeUnique<SubscriptionResumptionSessionEstablisher>();
2104 0 : if (subscriptionResumptionSessionEstablisher == nullptr)
2105 : {
2106 0 : ChipLogProgress(InteractionModel, "Failed to create SubscriptionResumptionSessionEstablisher");
2107 0 : return;
2108 : }
2109 :
2110 0 : if (subscriptionResumptionSessionEstablisher->ResumeSubscription(*imEngine->mpCASESessionMgr, subscriptionInfo) !=
2111 0 : CHIP_NO_ERROR)
2112 : {
2113 0 : ChipLogProgress(InteractionModel, "Failed to ResumeSubscription 0x%" PRIx32, subscriptionInfo.mSubscriptionId);
2114 0 : return;
2115 : }
2116 0 : subscriptionResumptionSessionEstablisher.release();
2117 : #if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2118 0 : resumedSubscriptions = true;
2119 : #endif // CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2120 0 : }
2121 :
2122 : #if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2123 : // If no persisted subscriptions needed resumption then all resumption retries are done
2124 0 : if (!resumedSubscriptions)
2125 : {
2126 0 : imEngine->mNumSubscriptionResumptionRetries = 0;
2127 : }
2128 : #endif // CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2129 :
2130 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
2131 0 : }
2132 :
2133 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2134 12 : uint32_t InteractionModelEngine::ComputeTimeSecondsTillNextSubscriptionResumption()
2135 : {
2136 : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
2137 12 : if (mSubscriptionResumptionRetrySecondsOverride > 0)
2138 : {
2139 0 : return static_cast<uint32_t>(mSubscriptionResumptionRetrySecondsOverride);
2140 : }
2141 : #endif
2142 12 : if (mNumSubscriptionResumptionRetries > CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MAX_FIBONACCI_STEP_INDEX)
2143 : {
2144 1 : return CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MAX_RETRY_INTERVAL_SECS;
2145 : }
2146 :
2147 : return CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MIN_RETRY_INTERVAL_SECS +
2148 11 : GetFibonacciForIndex(mNumSubscriptionResumptionRetries) *
2149 11 : CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_WAIT_TIME_MULTIPLIER_SECS;
2150 : }
2151 :
2152 863 : bool InteractionModelEngine::HasSubscriptionsToResume()
2153 : {
2154 863 : VerifyOrReturnValue(mpSubscriptionResumptionStorage != nullptr, false);
2155 :
2156 : // Look through persisted subscriptions and see if any aren't already in mReadHandlers pool
2157 0 : SubscriptionResumptionStorage::SubscriptionInfo subscriptionInfo;
2158 0 : auto * iterator = mpSubscriptionResumptionStorage->IterateSubscriptions();
2159 0 : bool foundSubscriptionToResume = false;
2160 0 : while (iterator->Next(subscriptionInfo))
2161 : {
2162 0 : if (Loop::Break == mReadHandlers.ForEachActiveObject([&](ReadHandler * handler) {
2163 : SubscriptionId subscriptionId;
2164 0 : handler->GetSubscriptionId(subscriptionId);
2165 0 : if (subscriptionId == subscriptionInfo.mSubscriptionId)
2166 : {
2167 0 : return Loop::Break;
2168 : }
2169 0 : return Loop::Continue;
2170 : }))
2171 : {
2172 0 : continue;
2173 : }
2174 :
2175 0 : foundSubscriptionToResume = true;
2176 0 : break;
2177 : }
2178 0 : iterator->Release();
2179 :
2180 0 : return foundSubscriptionToResume;
2181 0 : }
2182 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2183 :
2184 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
2185 6 : void InteractionModelEngine::DecrementNumSubscriptionsToResume()
2186 : {
2187 6 : VerifyOrReturn(mNumOfSubscriptionsToResume > 0);
2188 5 : mNumOfSubscriptionsToResume--;
2189 :
2190 : #if CHIP_CONFIG_ENABLE_ICD_CIP && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2191 : if (mICDManager && !mNumOfSubscriptionsToResume)
2192 : {
2193 : mICDManager->SetBootUpResumeSubscriptionExecuted();
2194 : }
2195 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2196 : }
2197 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
2198 :
2199 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2200 0 : void InteractionModelEngine::ResetNumSubscriptionsRetries()
2201 : {
2202 : // Check if there are any subscriptions to resume, if not the retry counter can be reset.
2203 0 : if (!HasSubscriptionsToResume())
2204 : {
2205 0 : mNumSubscriptionResumptionRetries = 0;
2206 : }
2207 0 : }
2208 : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
2209 : } // namespace app
2210 : } // namespace chip
|