Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 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 : #include <app/AppConfig.h>
20 : #include <app/AttributeAccessInterfaceRegistry.h>
21 : #include <app/AttributeValueDecoder.h>
22 : #include <app/ConcreteAttributePath.h>
23 : #include <app/GlobalAttributes.h>
24 : #include <app/InteractionModelEngine.h>
25 : #include <app/MessageDef/EventPathIB.h>
26 : #include <app/MessageDef/StatusIB.h>
27 : #include <app/StatusResponse.h>
28 : #include <app/WriteHandler.h>
29 : #include <app/data-model-provider/ActionReturnStatus.h>
30 : #include <app/data-model-provider/MetadataLookup.h>
31 : #include <app/data-model-provider/MetadataTypes.h>
32 : #include <app/data-model-provider/OperationTypes.h>
33 : #include <app/reporting/Engine.h>
34 : #include <app/util/MatterCallbacks.h>
35 : #include <credentials/GroupDataProvider.h>
36 : #include <lib/core/CHIPError.h>
37 : #include <lib/core/DataModelTypes.h>
38 : #include <lib/support/CodeUtils.h>
39 : #include <lib/support/TypeTraits.h>
40 : #include <lib/support/logging/TextOnlyLogging.h>
41 : #include <messaging/ExchangeContext.h>
42 : #include <protocols/interaction_model/StatusCode.h>
43 : #include <transport/raw/GroupcastTesting.h>
44 :
45 : #include <optional>
46 :
47 : namespace chip {
48 : namespace app {
49 :
50 : namespace {
51 :
52 : using Protocols::InteractionModel::Status;
53 :
54 : /// Wraps a EndpointIterator and ensures that `::Release()` is called
55 : /// for the iterator (assuming it is non-null)
56 : class AutoReleaseGroupEndpointIterator
57 : {
58 : public:
59 2 : explicit AutoReleaseGroupEndpointIterator(Credentials::GroupDataProvider::EndpointIterator * iterator) : mIterator(iterator) {}
60 2 : ~AutoReleaseGroupEndpointIterator()
61 : {
62 2 : if (mIterator != nullptr)
63 : {
64 2 : mIterator->Release();
65 : }
66 2 : }
67 :
68 2 : bool IsNull() const { return mIterator == nullptr; }
69 8 : bool Next(Credentials::GroupDataProvider::GroupEndpoint & item) { return mIterator->Next(item); }
70 :
71 : private:
72 : Credentials::GroupDataProvider::EndpointIterator * mIterator;
73 : };
74 :
75 : } // namespace
76 :
77 : using namespace Protocols::InteractionModel;
78 : using Status = Protocols::InteractionModel::Status;
79 :
80 979 : CHIP_ERROR WriteHandler::Init(DataModel::Provider * apProvider, WriteHandlerDelegate * apWriteHandlerDelegate)
81 : {
82 979 : VerifyOrReturnError(!mExchangeCtx, CHIP_ERROR_INCORRECT_STATE);
83 979 : VerifyOrReturnError(apWriteHandlerDelegate, CHIP_ERROR_INVALID_ARGUMENT);
84 979 : VerifyOrReturnError(apProvider, CHIP_ERROR_INVALID_ARGUMENT);
85 978 : mDataModelProvider = apProvider;
86 :
87 978 : mDelegate = apWriteHandlerDelegate;
88 978 : MoveToState(State::Initialized);
89 :
90 978 : mProcessingAttributePath.ClearValue();
91 :
92 978 : return CHIP_NO_ERROR;
93 : }
94 :
95 978 : void WriteHandler::Close()
96 : {
97 978 : VerifyOrReturn(mState != State::Uninitialized);
98 :
99 : // DeliverFinalListWriteEnd will be a no-op if we have called
100 : // DeliverFinalListWriteEnd in success conditions, so passing false for
101 : // wasSuccessful here is safe: if it does anything, we were in fact not
102 : // successful.
103 978 : DeliverFinalListWriteEnd(false /* wasSuccessful */);
104 978 : mExchangeCtx.Release();
105 978 : mStateFlags.Clear(StateBits::kSuppressResponse);
106 978 : mDataModelProvider = nullptr;
107 978 : MoveToState(State::Uninitialized);
108 : }
109 :
110 1102 : std::optional<bool> WriteHandler::IsListAttributePath(const ConcreteAttributePath & path)
111 : {
112 1102 : if (mDataModelProvider == nullptr)
113 : {
114 : #if CHIP_CONFIG_DATA_MODEL_EXTRA_LOGGING
115 0 : ChipLogError(DataManagement, "Null data model while checking attribute properties.");
116 : #endif
117 0 : return std::nullopt;
118 : }
119 :
120 1102 : DataModel::AttributeFinder finder(mDataModelProvider);
121 1102 : std::optional<DataModel::AttributeEntry> info = finder.Find(path);
122 :
123 1102 : if (!info.has_value())
124 : {
125 8 : return std::nullopt;
126 : }
127 :
128 1094 : return info->HasFlags(DataModel::AttributeQualityFlags::kListAttribute);
129 1102 : }
130 :
131 3890 : Status WriteHandler::HandleWriteRequestMessage(Messaging::ExchangeContext * apExchangeContext,
132 : System::PacketBufferHandle && aPayload, bool aIsTimedWrite)
133 : {
134 3890 : System::PacketBufferHandle packet = System::PacketBufferHandle::New(chip::app::kMaxSecureSduLengthBytes);
135 3890 : VerifyOrReturnError(!packet.IsNull(), Status::Failure);
136 :
137 3890 : System::PacketBufferTLVWriter messageWriter;
138 3890 : messageWriter.Init(std::move(packet));
139 7780 : VerifyOrReturnError(mWriteResponseBuilder.Init(&messageWriter) == CHIP_NO_ERROR, Status::Failure);
140 :
141 3890 : mWriteResponseBuilder.CreateWriteResponses();
142 7780 : VerifyOrReturnError(mWriteResponseBuilder.GetError() == CHIP_NO_ERROR, Status::Failure);
143 :
144 3890 : Status status = ProcessWriteRequest(std::move(aPayload), aIsTimedWrite);
145 :
146 : // Do not send response on Group Write or Write request with SuppressResponse flag set.
147 3890 : if (status == Status::Success && !apExchangeContext->IsGroupExchangeContext() && !mStateFlags.Has(StateBits::kSuppressResponse))
148 : {
149 3876 : CHIP_ERROR err = SendWriteResponse(std::move(messageWriter));
150 7752 : if (err != CHIP_NO_ERROR)
151 : {
152 0 : status = Status::Failure;
153 : }
154 : }
155 :
156 3890 : return status;
157 3890 : }
158 :
159 978 : Status WriteHandler::OnWriteRequest(Messaging::ExchangeContext * apExchangeContext, System::PacketBufferHandle && aPayload,
160 : bool aIsTimedWrite)
161 : {
162 : //
163 : // Let's take over further message processing on this exchange from the IM.
164 : // This is only relevant during chunked requests.
165 : //
166 978 : mExchangeCtx.Grab(apExchangeContext);
167 :
168 978 : Status status = HandleWriteRequestMessage(apExchangeContext, std::move(aPayload), aIsTimedWrite);
169 :
170 : // The write transaction will be alive only when the message was handled successfully and there are more chunks.
171 978 : if (!(status == Status::Success && mStateFlags.Has(StateBits::kHasMoreChunks)))
172 : {
173 114 : const bool suppressResponse = mStateFlags.Has(StateBits::kSuppressResponse);
174 114 : Close();
175 : // Return Success if SuppressResponse is set to avoid sending StatusResponse when error is caught
176 : // in InteractionModelEngine.
177 114 : if (suppressResponse)
178 : {
179 9 : return Status::Success;
180 : }
181 : }
182 :
183 969 : return status;
184 : }
185 :
186 2914 : CHIP_ERROR WriteHandler::OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
187 : System::PacketBufferHandle && aPayload)
188 : {
189 2914 : CHIP_ERROR err = CHIP_NO_ERROR;
190 :
191 2914 : VerifyOrDieWithMsg(apExchangeContext == mExchangeCtx.Get(), DataManagement,
192 : "Incoming exchange context should be same as the initial request.");
193 2914 : VerifyOrDieWithMsg(!apExchangeContext->IsGroupExchangeContext(), DataManagement,
194 : "OnMessageReceived should not be called on GroupExchangeContext");
195 2914 : if (!aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::WriteRequest))
196 : {
197 2 : if (aPayloadHeader.HasMessageType(Protocols::InteractionModel::MsgType::StatusResponse))
198 : {
199 1 : CHIP_ERROR statusError = CHIP_NO_ERROR;
200 : // Parse the status response so we can log it properly.
201 1 : TEMPORARY_RETURN_IGNORED StatusResponse::ProcessStatusResponse(std::move(aPayload), statusError);
202 : }
203 2 : ChipLogDetail(DataManagement, "Unexpected message type %d", aPayloadHeader.GetMessageType());
204 2 : if (!mStateFlags.Has(StateBits::kSuppressResponse))
205 : {
206 2 : TEMPORARY_RETURN_IGNORED StatusResponse::Send(Status::InvalidAction, apExchangeContext, false /*aExpectResponse*/);
207 : }
208 2 : Close();
209 2 : return CHIP_ERROR_INVALID_MESSAGE_TYPE;
210 : }
211 :
212 : Status status =
213 2912 : HandleWriteRequestMessage(apExchangeContext, std::move(aPayload), false /* chunked write should not be timed write */);
214 2912 : if (status == Status::Success)
215 : {
216 : // We have no more chunks, the write response has been sent in HandleWriteRequestMessage, so close directly.
217 2912 : if (!mStateFlags.Has(StateBits::kHasMoreChunks))
218 : {
219 853 : Close();
220 : }
221 : }
222 : else
223 : {
224 0 : if (!mStateFlags.Has(StateBits::kSuppressResponse))
225 : {
226 0 : err = StatusResponse::Send(status, apExchangeContext, false /*aExpectResponse*/);
227 : }
228 0 : Close();
229 : }
230 2912 : return err;
231 : }
232 :
233 8 : void WriteHandler::OnResponseTimeout(Messaging::ExchangeContext * apExchangeContext)
234 : {
235 8 : ChipLogError(DataManagement, "Time out! failed to receive status response from Exchange: " ChipLogFormatExchange,
236 : ChipLogValueExchange(apExchangeContext));
237 8 : Close();
238 8 : }
239 :
240 3877 : CHIP_ERROR WriteHandler::FinalizeMessage(System::PacketBufferTLVWriter && aMessageWriter, System::PacketBufferHandle & packet)
241 : {
242 3877 : VerifyOrReturnError(mState == State::AddStatus, CHIP_ERROR_INCORRECT_STATE);
243 3877 : ReturnErrorOnFailure(mWriteResponseBuilder.GetWriteResponses().EndOfAttributeStatuses());
244 3877 : ReturnErrorOnFailure(mWriteResponseBuilder.EndOfWriteResponseMessage());
245 3877 : ReturnErrorOnFailure(aMessageWriter.Finalize(&packet));
246 3877 : return CHIP_NO_ERROR;
247 : }
248 :
249 3877 : CHIP_ERROR WriteHandler::SendWriteResponse(System::PacketBufferTLVWriter && aMessageWriter)
250 : {
251 3877 : CHIP_ERROR err = CHIP_NO_ERROR;
252 3877 : System::PacketBufferHandle packet;
253 :
254 3877 : VerifyOrExit(mState == State::AddStatus, err = CHIP_ERROR_INCORRECT_STATE);
255 :
256 3877 : err = FinalizeMessage(std::move(aMessageWriter), packet);
257 3877 : SuccessOrExit(err);
258 :
259 3877 : VerifyOrExit(mExchangeCtx, err = CHIP_ERROR_INCORRECT_STATE);
260 3877 : err = mExchangeCtx->UseSuggestedResponseTimeout(app::kExpectedIMProcessingTime);
261 3877 : SuccessOrExit(err);
262 7752 : err = mExchangeCtx->SendMessage(Protocols::InteractionModel::MsgType::WriteResponse, std::move(packet),
263 3876 : mStateFlags.Has(StateBits::kHasMoreChunks) ? Messaging::SendMessageFlags::kExpectResponse
264 : : Messaging::SendMessageFlags::kNone);
265 3876 : SuccessOrExit(err);
266 :
267 3876 : MoveToState(State::Sending);
268 :
269 3877 : exit:
270 7754 : return err;
271 3877 : }
272 :
273 937 : void WriteHandler::DeliverListWriteBegin(const ConcreteAttributePath & aPath)
274 : {
275 937 : if (mDataModelProvider != nullptr)
276 : {
277 937 : mDataModelProvider->ListAttributeWriteNotification(aPath, DataModel::ListWriteOperation::kListWriteBegin,
278 937 : GetAccessingFabricIndex());
279 : }
280 937 : }
281 :
282 943 : void WriteHandler::DeliverListWriteEnd(const ConcreteAttributePath & aPath, bool writeWasSuccessful)
283 : {
284 943 : if (mDataModelProvider != nullptr)
285 : {
286 943 : mDataModelProvider->ListAttributeWriteNotification(aPath,
287 : writeWasSuccessful ? DataModel::ListWriteOperation::kListWriteSuccess
288 : : DataModel::ListWriteOperation::kListWriteFailure,
289 943 : GetAccessingFabricIndex());
290 : }
291 943 : }
292 :
293 1935 : void WriteHandler::DeliverFinalListWriteEnd(bool writeWasSuccessful)
294 : {
295 1935 : if (mProcessingAttributePath.HasValue() && mStateFlags.Has(StateBits::kProcessingAttributeIsList))
296 : {
297 935 : DeliverListWriteEnd(mProcessingAttributePath.Value(), writeWasSuccessful);
298 : }
299 1935 : mProcessingAttributePath.ClearValue();
300 1935 : }
301 :
302 4 : CHIP_ERROR WriteHandler::DeliverFinalListWriteEndForGroupWrite(bool writeWasSuccessful)
303 : {
304 4 : VerifyOrReturnError(mProcessingAttributePath.HasValue() && mStateFlags.Has(StateBits::kProcessingAttributeIsList),
305 : CHIP_NO_ERROR);
306 :
307 0 : Credentials::GroupDataProvider::GroupEndpoint mapping;
308 0 : Credentials::GroupDataProvider * groupDataProvider = Credentials::GetGroupDataProvider();
309 : Credentials::GroupDataProvider::EndpointIterator * iterator;
310 :
311 0 : GroupId groupId = mExchangeCtx->GetSessionHandle()->AsIncomingGroupSession()->GetGroupId();
312 0 : FabricIndex fabricIndex = GetAccessingFabricIndex();
313 :
314 0 : auto processingConcreteAttributePath = mProcessingAttributePath.Value();
315 0 : mProcessingAttributePath.ClearValue();
316 :
317 0 : iterator = groupDataProvider->IterateEndpoints(fabricIndex);
318 0 : VerifyOrReturnError(iterator != nullptr, CHIP_ERROR_NO_MEMORY);
319 :
320 0 : while (iterator->Next(mapping))
321 : {
322 0 : if (groupId != mapping.group_id)
323 : {
324 0 : continue;
325 : }
326 :
327 0 : processingConcreteAttributePath.mEndpointId = mapping.endpoint_id;
328 :
329 0 : VerifyOrReturnError(mDelegate, CHIP_ERROR_INCORRECT_STATE);
330 0 : if (!mDelegate->HasConflictWriteRequests(this, processingConcreteAttributePath))
331 : {
332 0 : DeliverListWriteEnd(processingConcreteAttributePath, writeWasSuccessful);
333 : }
334 : }
335 0 : iterator->Release();
336 0 : return CHIP_NO_ERROR;
337 : }
338 : namespace {
339 :
340 : // To reduce the various use of previousProcessed.HasValue() && previousProcessed.Value() == nextAttribute to save code size.
341 14513 : bool IsSameAttribute(const Optional<ConcreteAttributePath> & previousProcessed, const ConcreteDataAttributePath & nextAttribute)
342 : {
343 14513 : return previousProcessed.HasValue() && previousProcessed.Value() == nextAttribute;
344 : }
345 :
346 5216 : bool ShouldReportListWriteEnd(const Optional<ConcreteAttributePath> & previousProcessed, bool previousProcessedAttributeIsList,
347 : const ConcreteDataAttributePath & nextAttribute)
348 : {
349 5216 : return previousProcessedAttributeIsList && !IsSameAttribute(previousProcessed, nextAttribute) && previousProcessed.HasValue();
350 : }
351 :
352 5216 : bool ShouldReportListWriteBegin(const Optional<ConcreteAttributePath> & previousProcessed, bool previousProcessedAttributeIsList,
353 : const ConcreteDataAttributePath & nextAttribute)
354 : {
355 5216 : return !IsSameAttribute(previousProcessed, nextAttribute) && nextAttribute.IsListOperation();
356 : }
357 :
358 : } // namespace
359 :
360 3880 : CHIP_ERROR WriteHandler::ProcessAttributeDataIBs(TLV::TLVReader & aAttributeDataIBsReader)
361 : {
362 3880 : CHIP_ERROR err = CHIP_NO_ERROR;
363 :
364 3880 : VerifyOrReturnError(mExchangeCtx, CHIP_ERROR_INTERNAL);
365 3880 : const Access::SubjectDescriptor subjectDescriptor = mExchangeCtx->GetSessionHandle()->GetSubjectDescriptor();
366 :
367 18214 : while (CHIP_NO_ERROR == (err = aAttributeDataIBsReader.Next()))
368 : {
369 5227 : chip::TLV::TLVReader dataReader;
370 5227 : AttributeDataIB::Parser element;
371 5227 : AttributePathIB::Parser attributePath;
372 5227 : ConcreteDataAttributePath dataAttributePath;
373 5227 : TLV::TLVReader reader = aAttributeDataIBsReader;
374 :
375 5227 : err = element.Init(reader);
376 5227 : SuccessOrExit(err);
377 :
378 5227 : err = element.GetPath(&attributePath);
379 5227 : SuccessOrExit(err);
380 :
381 5227 : err = attributePath.GetConcreteAttributePath(dataAttributePath);
382 5227 : SuccessOrExit(err);
383 :
384 5227 : err = element.GetData(&dataReader);
385 5227 : SuccessOrExit(err);
386 :
387 5227 : if (!dataAttributePath.IsListOperation() && IsListAttributePath(dataAttributePath).value_or(false))
388 : {
389 1065 : dataAttributePath.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll;
390 : }
391 :
392 5227 : VerifyOrExit(mDelegate, err = CHIP_ERROR_INCORRECT_STATE);
393 14567 : if (mDelegate->HasConflictWriteRequests(this, dataAttributePath) ||
394 : // Per chunking protocol, we are processing the list entries, but the initial empty list is not processed, so we reject
395 : // it with Busy status code.
396 9340 : (dataAttributePath.IsListItemOperation() && !IsSameAttribute(mProcessingAttributePath, dataAttributePath)))
397 : {
398 13 : err = AddStatusInternal(dataAttributePath, StatusIB(Status::Busy));
399 13 : continue;
400 : }
401 :
402 5214 : if (ShouldReportListWriteEnd(mProcessingAttributePath, mStateFlags.Has(StateBits::kProcessingAttributeIsList),
403 : dataAttributePath))
404 : {
405 8 : DeliverListWriteEnd(mProcessingAttributePath.Value(), mStateFlags.Has(StateBits::kAttributeWriteSuccessful));
406 : }
407 :
408 5214 : if (ShouldReportListWriteBegin(mProcessingAttributePath, mStateFlags.Has(StateBits::kProcessingAttributeIsList),
409 : dataAttributePath))
410 : {
411 937 : DeliverListWriteBegin(dataAttributePath);
412 937 : mStateFlags.Set(StateBits::kAttributeWriteSuccessful);
413 : }
414 :
415 5214 : mStateFlags.Set(StateBits::kProcessingAttributeIsList, dataAttributePath.IsListOperation());
416 5214 : mProcessingAttributePath.SetValue(dataAttributePath);
417 :
418 5214 : DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Write,
419 : DataModelCallbacks::OperationOrder::Pre, dataAttributePath);
420 :
421 5214 : TLV::TLVWriter backup;
422 5214 : DataVersion version = 0;
423 5214 : mWriteResponseBuilder.GetWriteResponses().Checkpoint(backup);
424 5214 : err = element.GetDataVersion(&version);
425 10428 : if (CHIP_NO_ERROR == err)
426 : {
427 12 : dataAttributePath.mDataVersion.SetValue(version);
428 : }
429 10404 : else if (CHIP_END_OF_TLV == err)
430 : {
431 5202 : err = CHIP_NO_ERROR;
432 : }
433 5214 : SuccessOrExit(err);
434 5214 : err = WriteClusterData(subjectDescriptor, dataAttributePath, dataReader);
435 10428 : if (err != CHIP_NO_ERROR)
436 : {
437 0 : mWriteResponseBuilder.GetWriteResponses().Rollback(backup);
438 0 : err = AddStatusInternal(dataAttributePath, StatusIB(err));
439 : }
440 :
441 5214 : DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Write,
442 : DataModelCallbacks::OperationOrder::Post, dataAttributePath);
443 5214 : SuccessOrExit(err);
444 : }
445 :
446 7760 : if (CHIP_END_OF_TLV == err)
447 : {
448 3880 : err = CHIP_NO_ERROR;
449 : }
450 :
451 3880 : SuccessOrExit(err);
452 :
453 3880 : if (!mStateFlags.Has(StateBits::kHasMoreChunks))
454 : {
455 957 : DeliverFinalListWriteEnd(mStateFlags.Has(StateBits::kAttributeWriteSuccessful));
456 : }
457 :
458 2923 : exit:
459 3880 : return err;
460 : }
461 :
462 2 : CHIP_ERROR WriteHandler::ProcessGroupAttributeDataIBs(TLV::TLVReader & aAttributeDataIBsReader)
463 : {
464 2 : CHIP_ERROR err = CHIP_NO_ERROR;
465 :
466 2 : VerifyOrReturnError(mExchangeCtx, CHIP_ERROR_INTERNAL);
467 : const Access::SubjectDescriptor subjectDescriptor =
468 2 : mExchangeCtx->GetSessionHandle()->AsIncomingGroupSession()->GetSubjectDescriptor();
469 :
470 2 : GroupId groupId = mExchangeCtx->GetSessionHandle()->AsIncomingGroupSession()->GetGroupId();
471 2 : FabricIndex fabric = GetAccessingFabricIndex();
472 :
473 8 : while (CHIP_NO_ERROR == (err = aAttributeDataIBsReader.Next()))
474 : {
475 2 : chip::TLV::TLVReader dataReader;
476 2 : AttributeDataIB::Parser element;
477 2 : AttributePathIB::Parser attributePath;
478 2 : ConcreteDataAttributePath dataAttributePath;
479 2 : TLV::TLVReader reader = aAttributeDataIBsReader;
480 :
481 2 : err = element.Init(reader);
482 2 : SuccessOrExit(err);
483 :
484 2 : err = element.GetPath(&attributePath);
485 2 : SuccessOrExit(err);
486 :
487 2 : err = attributePath.GetGroupAttributePath(dataAttributePath);
488 2 : SuccessOrExit(err);
489 :
490 2 : err = element.GetData(&dataReader);
491 2 : SuccessOrExit(err);
492 :
493 2 : if (!dataAttributePath.IsListOperation() && dataReader.GetType() == TLV::TLVType::kTLVType_Array)
494 : {
495 0 : dataAttributePath.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll;
496 : }
497 :
498 2 : ChipLogDetail(DataManagement,
499 : "Received group attribute write for Group=%u Cluster=" ChipLogFormatMEI " attribute=" ChipLogFormatMEI,
500 : groupId, ChipLogValueMEI(dataAttributePath.mClusterId), ChipLogValueMEI(dataAttributePath.mAttributeId));
501 :
502 2 : AutoReleaseGroupEndpointIterator iterator(Credentials::GetGroupDataProvider()->IterateEndpoints(fabric));
503 2 : VerifyOrExit(!iterator.IsNull(), err = CHIP_ERROR_NO_MEMORY);
504 :
505 2 : bool shouldReportListWriteEnd = ShouldReportListWriteEnd(
506 2 : mProcessingAttributePath, mStateFlags.Has(StateBits::kProcessingAttributeIsList), dataAttributePath);
507 2 : bool shouldReportListWriteBegin = false; // This will be set below.
508 :
509 2 : std::optional<bool> isListAttribute = std::nullopt;
510 :
511 2 : Credentials::GroupDataProvider::GroupEndpoint mapping;
512 8 : while (iterator.Next(mapping))
513 : {
514 6 : if (groupId != mapping.group_id)
515 : {
516 4 : continue;
517 : }
518 :
519 2 : dataAttributePath.mEndpointId = mapping.endpoint_id;
520 : // Groupcast Testing
521 2 : auto & testing = Groupcast::GetTesting();
522 2 : if (testing.IsEnabled() && testing.IsFabricUnderTest(fabric))
523 : {
524 0 : testing.SetGroupID(groupId);
525 0 : testing.SetEndpointID(dataAttributePath.mEndpointId);
526 0 : testing.SetClusterID(dataAttributePath.mClusterId);
527 0 : testing.SetElementID(static_cast<uint32_t>(dataAttributePath.mAttributeId));
528 : }
529 :
530 : // Try to get the metadata from for the attribute from one of the expanded endpoints (it doesn't really matter which
531 : // endpoint we pick, as long as it's valid) and update the path info according to it and recheck if we need to report
532 : // list write begin.
533 2 : if (!isListAttribute.has_value())
534 : {
535 2 : isListAttribute = IsListAttributePath(dataAttributePath);
536 2 : bool currentAttributeIsList = isListAttribute.value_or(false);
537 :
538 2 : if (!dataAttributePath.IsListOperation() && currentAttributeIsList)
539 : {
540 0 : dataAttributePath.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll;
541 : }
542 : ConcreteDataAttributePath pathForCheckingListWriteBegin(kInvalidEndpointId, dataAttributePath.mClusterId,
543 2 : dataAttributePath.mEndpointId, dataAttributePath.mListOp,
544 2 : dataAttributePath.mListIndex);
545 : shouldReportListWriteBegin =
546 2 : ShouldReportListWriteBegin(mProcessingAttributePath, mStateFlags.Has(StateBits::kProcessingAttributeIsList),
547 : pathForCheckingListWriteBegin);
548 : }
549 :
550 2 : if (shouldReportListWriteEnd)
551 : {
552 0 : auto processingConcreteAttributePath = mProcessingAttributePath.Value();
553 0 : processingConcreteAttributePath.mEndpointId = mapping.endpoint_id;
554 0 : VerifyOrExit(mDelegate, err = CHIP_ERROR_INCORRECT_STATE);
555 0 : if (mDelegate->HasConflictWriteRequests(this, processingConcreteAttributePath))
556 : {
557 0 : DeliverListWriteEnd(processingConcreteAttributePath, true /* writeWasSuccessful */);
558 : }
559 : }
560 :
561 2 : VerifyOrExit(mDelegate, err = CHIP_ERROR_INCORRECT_STATE);
562 2 : if (mDelegate->HasConflictWriteRequests(this, dataAttributePath))
563 : {
564 0 : ChipLogDetail(DataManagement,
565 : "Writing attribute endpoint=%u Cluster=" ChipLogFormatMEI " attribute=" ChipLogFormatMEI
566 : " is conflict with other write transactions.",
567 : mapping.endpoint_id, ChipLogValueMEI(dataAttributePath.mClusterId),
568 : ChipLogValueMEI(dataAttributePath.mAttributeId));
569 0 : continue;
570 : }
571 :
572 2 : if (shouldReportListWriteBegin)
573 : {
574 0 : DeliverListWriteBegin(dataAttributePath);
575 : }
576 :
577 2 : ChipLogDetail(DataManagement,
578 : "Processing group attribute write for endpoint=%u Cluster=" ChipLogFormatMEI
579 : " attribute=" ChipLogFormatMEI,
580 : mapping.endpoint_id, ChipLogValueMEI(dataAttributePath.mClusterId),
581 : ChipLogValueMEI(dataAttributePath.mAttributeId));
582 :
583 2 : chip::TLV::TLVReader tmpDataReader(dataReader);
584 :
585 2 : DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Write,
586 : DataModelCallbacks::OperationOrder::Pre, dataAttributePath);
587 2 : err = WriteClusterData(subjectDescriptor, dataAttributePath, tmpDataReader);
588 4 : if (err != CHIP_NO_ERROR)
589 : {
590 0 : ChipLogError(DataManagement,
591 : "WriteClusterData Endpoint=%u Cluster=" ChipLogFormatMEI " Attribute =" ChipLogFormatMEI
592 : " failed: %" CHIP_ERROR_FORMAT,
593 : mapping.endpoint_id, ChipLogValueMEI(dataAttributePath.mClusterId),
594 : ChipLogValueMEI(dataAttributePath.mAttributeId), err.Format());
595 : }
596 2 : DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Write,
597 : DataModelCallbacks::OperationOrder::Post, dataAttributePath);
598 : }
599 :
600 2 : dataAttributePath.mEndpointId = kInvalidEndpointId;
601 2 : mStateFlags.Set(StateBits::kProcessingAttributeIsList, dataAttributePath.IsListOperation());
602 2 : mProcessingAttributePath.SetValue(dataAttributePath);
603 2 : }
604 :
605 4 : if (CHIP_END_OF_TLV == err)
606 : {
607 2 : err = CHIP_NO_ERROR;
608 : }
609 :
610 2 : err = DeliverFinalListWriteEndForGroupWrite(true);
611 :
612 2 : exit:
613 : // The DeliverFinalListWriteEndForGroupWrite above will deliver the successful state of the list write and clear the
614 : // mProcessingAttributePath making the following call no-op. So we call it again after the exit label to deliver a failure state
615 : // to the clusters. Ignore the error code since we need to deliver other more important failures.
616 2 : TEMPORARY_RETURN_IGNORED DeliverFinalListWriteEndForGroupWrite(false);
617 2 : return err;
618 : }
619 :
620 3890 : Status WriteHandler::ProcessWriteRequest(System::PacketBufferHandle && aPayload, bool aIsTimedWrite)
621 : {
622 3890 : CHIP_ERROR err = CHIP_NO_ERROR;
623 3890 : System::PacketBufferTLVReader reader;
624 :
625 3890 : WriteRequestMessage::Parser writeRequestParser;
626 3890 : AttributeDataIBs::Parser AttributeDataIBsParser;
627 3890 : TLV::TLVReader AttributeDataIBsReader;
628 : // Default to InvalidAction for our status; that's what we want if any of
629 : // the parsing of our overall structure or paths fails. Once we have a
630 : // successfully parsed path, the only way we will get a failure return is if
631 : // our path handling fails to AddStatus on us.
632 : //
633 : // TODO: That's not technically InvalidAction, and we should probably make
634 : // our callees hand out Status as well.
635 3890 : Status status = Status::InvalidAction;
636 :
637 3890 : mLastSuccessfullyWrittenPath = std::nullopt;
638 :
639 3890 : reader.Init(std::move(aPayload));
640 :
641 3890 : err = writeRequestParser.Init(reader);
642 3890 : SuccessOrExit(err);
643 :
644 : #if CHIP_CONFIG_IM_PRETTY_PRINT
645 3889 : TEMPORARY_RETURN_IGNORED writeRequestParser.PrettyPrint();
646 : #endif // CHIP_CONFIG_IM_PRETTY_PRINT
647 : bool boolValue;
648 :
649 3889 : boolValue = mStateFlags.Has(StateBits::kSuppressResponse);
650 3889 : err = writeRequestParser.GetSuppressResponse(&boolValue);
651 7778 : if (err == CHIP_END_OF_TLV)
652 : {
653 4 : err = CHIP_NO_ERROR;
654 : }
655 3889 : SuccessOrExit(err);
656 3889 : mStateFlags.Set(StateBits::kSuppressResponse, boolValue);
657 :
658 3889 : boolValue = mStateFlags.Has(StateBits::kIsTimedRequest);
659 3889 : err = writeRequestParser.GetTimedRequest(&boolValue);
660 3889 : SuccessOrExit(err);
661 3889 : mStateFlags.Set(StateBits::kIsTimedRequest, boolValue);
662 :
663 3889 : boolValue = mStateFlags.Has(StateBits::kHasMoreChunks);
664 3889 : err = writeRequestParser.GetMoreChunkedMessages(&boolValue);
665 7778 : if (err == CHIP_ERROR_END_OF_TLV)
666 : {
667 4 : err = CHIP_NO_ERROR;
668 : }
669 3889 : SuccessOrExit(err);
670 3889 : mStateFlags.Set(StateBits::kHasMoreChunks, boolValue);
671 :
672 9745 : if (mStateFlags.Has(StateBits::kHasMoreChunks) &&
673 8784 : (mExchangeCtx->IsGroupExchangeContext() || mStateFlags.Has(StateBits::kIsTimedRequest) ||
674 2928 : mStateFlags.Has(StateBits::kSuppressResponse)))
675 : {
676 : // Sanity check: group exchange context should only have one chunk.
677 : // Also, timed requests should not have more than one chunk.
678 : // A chunked write needs intermediate WriteResponses (sent with kExpectResponse) to keep the exchange
679 : // alive and pace the sender, so SuppressResponse is incompatible with more chunks; rejecting the
680 : // combination avoids leaving a handler allocated on an exchange that the messaging layer closes.
681 5 : ExitNow(err = CHIP_ERROR_INVALID_MESSAGE_TYPE);
682 : }
683 :
684 3884 : err = writeRequestParser.GetWriteRequests(&AttributeDataIBsParser);
685 3884 : SuccessOrExit(err);
686 :
687 3884 : if (mStateFlags.Has(StateBits::kIsTimedRequest) != aIsTimedWrite)
688 : {
689 : // The message thinks it should be part of a timed interaction but it's
690 : // not, or vice versa.
691 2 : status = Status::TimedRequestMismatch;
692 2 : goto exit;
693 : }
694 :
695 3882 : AttributeDataIBsParser.GetReader(&AttributeDataIBsReader);
696 :
697 3882 : if (mExchangeCtx->IsGroupExchangeContext())
698 : {
699 2 : err = ProcessGroupAttributeDataIBs(AttributeDataIBsReader);
700 : }
701 : else
702 : {
703 3880 : err = ProcessAttributeDataIBs(AttributeDataIBsReader);
704 : }
705 3882 : SuccessOrExit(err);
706 3882 : SuccessOrExit(err = writeRequestParser.ExitContainer());
707 :
708 7764 : if (err == CHIP_NO_ERROR)
709 : {
710 3882 : status = Status::Success;
711 : }
712 :
713 0 : exit:
714 7780 : if (err != CHIP_NO_ERROR)
715 : {
716 6 : ChipLogError(DataManagement, "Failed to process write request: %" CHIP_ERROR_FORMAT, err.Format());
717 : }
718 7780 : return status;
719 3890 : }
720 :
721 0 : CHIP_ERROR WriteHandler::AddStatus(const ConcreteDataAttributePath & aPath,
722 : const Protocols::InteractionModel::ClusterStatusCode & aStatus)
723 : {
724 0 : return AddStatusInternal(aPath, StatusIB{ aStatus });
725 : }
726 :
727 0 : CHIP_ERROR WriteHandler::AddClusterSpecificSuccess(const ConcreteDataAttributePath & aPath, ClusterStatus aClusterStatus)
728 : {
729 0 : return AddStatus(aPath, Protocols::InteractionModel::ClusterStatusCode::ClusterSpecificSuccess(aClusterStatus));
730 : }
731 :
732 0 : CHIP_ERROR WriteHandler::AddClusterSpecificFailure(const ConcreteDataAttributePath & aPath, ClusterStatus aClusterStatus)
733 : {
734 0 : return AddStatus(aPath, Protocols::InteractionModel::ClusterStatusCode::ClusterSpecificFailure(aClusterStatus));
735 : }
736 :
737 5229 : CHIP_ERROR WriteHandler::AddStatusInternal(const ConcreteDataAttributePath & aPath, const StatusIB & aStatus)
738 : {
739 5229 : AttributeStatusIBs::Builder & writeResponses = mWriteResponseBuilder.GetWriteResponses();
740 5229 : AttributeStatusIB::Builder & attributeStatusIB = writeResponses.CreateAttributeStatus();
741 :
742 5229 : if (!aStatus.IsSuccess())
743 : {
744 51 : mStateFlags.Clear(StateBits::kAttributeWriteSuccessful);
745 : }
746 :
747 5229 : ReturnErrorOnFailure(writeResponses.GetError());
748 :
749 5229 : AttributePathIB::Builder & path = attributeStatusIB.CreatePath();
750 5229 : ReturnErrorOnFailure(attributeStatusIB.GetError());
751 5229 : ReturnErrorOnFailure(path.Encode(aPath));
752 :
753 5229 : StatusIB::Builder & statusIBBuilder = attributeStatusIB.CreateErrorStatus();
754 5229 : ReturnErrorOnFailure(attributeStatusIB.GetError());
755 5229 : statusIBBuilder.EncodeStatusIB(aStatus);
756 5229 : ReturnErrorOnFailure(statusIBBuilder.GetError());
757 5229 : ReturnErrorOnFailure(attributeStatusIB.EndOfAttributeStatusIB());
758 :
759 5229 : MoveToState(State::AddStatus);
760 5229 : return CHIP_NO_ERROR;
761 : }
762 :
763 1883 : FabricIndex WriteHandler::GetAccessingFabricIndex() const
764 : {
765 1883 : return mExchangeCtx->GetSessionHandle()->GetFabricIndex();
766 : }
767 :
768 0 : const char * WriteHandler::GetStateStr() const
769 : {
770 : #if CHIP_DETAIL_LOGGING
771 0 : switch (mState)
772 : {
773 0 : case State::Uninitialized:
774 0 : return "Uninitialized";
775 :
776 0 : case State::Initialized:
777 0 : return "Initialized";
778 :
779 0 : case State::AddStatus:
780 0 : return "AddStatus";
781 0 : case State::Sending:
782 0 : return "Sending";
783 : }
784 : #endif // CHIP_DETAIL_LOGGING
785 0 : return "N/A";
786 : }
787 :
788 11061 : void WriteHandler::MoveToState(const State aTargetState)
789 : {
790 11061 : mState = aTargetState;
791 11061 : ChipLogDetail(DataManagement, "IM WH moving to [%s]", GetStateStr());
792 11061 : }
793 :
794 5216 : DataModel::ActionReturnStatus WriteHandler::CheckWriteAllowed(const Access::SubjectDescriptor & aSubject,
795 : const ConcreteDataAttributePath & aPath)
796 : {
797 :
798 : // Execute the ACL Access Granting Algorithm before existence checks, assuming the required_privilege for the element is
799 : // View, to determine if the subject would have had at least some access against the concrete path. This is done so we don't
800 : // leak information if we do fail existence checks.
801 : // SPEC-DIVERGENCE: For non-concrete paths, the spec mandates only one ACL check (the one after the existence check), unlike the
802 : // concrete path case, when there is one ACL check before existence check and a second one after. However, because this code is
803 : // also used in the group path case, we end up performing an ADDITIONAL ACL check before the existence check. In practice, this
804 : // divergence is not observable.
805 5216 : Status writeAccessStatus = CheckWriteAccess(aSubject, aPath, Access::Privilege::kView);
806 5216 : VerifyOrReturnValue(writeAccessStatus == Status::Success, writeAccessStatus);
807 :
808 5213 : DataModel::AttributeFinder finder(mDataModelProvider);
809 :
810 5213 : std::optional<DataModel::AttributeEntry> attributeEntry = finder.Find(aPath);
811 :
812 : // if path is not valid, return a spec-compliant return code.
813 5213 : if (!attributeEntry.has_value())
814 : {
815 5 : return DataModel::ValidateClusterPath(mDataModelProvider, aPath, Status::UnsupportedAttribute);
816 : }
817 :
818 : // Allow writes on writable attributes only
819 5208 : VerifyOrReturnValue(attributeEntry->GetWritePrivilege().has_value(), Status::UnsupportedWrite);
820 :
821 : // Execute the ACL Access Granting Algorithm against the concrete path a second time, using the actual required_privilege
822 5208 : writeAccessStatus = CheckWriteAccess(aSubject, aPath, *attributeEntry->GetWritePrivilege());
823 5208 : VerifyOrReturnValue(writeAccessStatus == Status::Success, writeAccessStatus);
824 :
825 : // SPEC:
826 : // If the path indicates specific attribute data that requires a Timed Write
827 : // transaction to write and this action is not part of a Timed Write transaction,
828 : // an AttributeStatusIB SHALL be generated with the NEEDS_TIMED_INTERACTION Status Code.
829 5208 : VerifyOrReturnValue(IsTimedWrite() || !attributeEntry->HasFlags(DataModel::AttributeQualityFlags::kTimed),
830 : Status::NeedsTimedInteraction);
831 :
832 : // SPEC:
833 : // Else if the attribute in the path indicates a fabric-scoped list and there is no accessing
834 : // fabric, an AttributeStatusIB SHALL be generated with the UNSUPPORTED_ACCESS Status Code,
835 : // with the Path field indicating only the path to the attribute.
836 10366 : if (attributeEntry->HasFlags(DataModel::AttributeQualityFlags::kListAttribute) &&
837 5158 : attributeEntry->HasFlags(DataModel::AttributeQualityFlags::kFabricScoped))
838 : {
839 0 : VerifyOrReturnError(aSubject.fabricIndex != kUndefinedFabricIndex, Status::UnsupportedAccess);
840 : }
841 :
842 : // SPEC:
843 : // Else if the DataVersion field of the AttributeDataIB is present and does not match the
844 : // data version of the indicated cluster instance, an AttributeStatusIB SHALL be generated
845 : // with the DATA_VERSION_MISMATCH Status Code.
846 5208 : if (aPath.mDataVersion.HasValue())
847 : {
848 12 : DataModel::ServerClusterFinder clusterFinder(mDataModelProvider);
849 12 : std::optional<DataModel::ServerClusterEntry> cluster_entry = clusterFinder.Find(aPath);
850 :
851 : // path is valid based on above checks (we have an attribute entry)
852 12 : VerifyOrDie(cluster_entry.has_value());
853 12 : VerifyOrReturnValue(cluster_entry->dataVersion == aPath.mDataVersion.Value(), Status::DataVersionMismatch);
854 12 : }
855 :
856 5202 : return Status::Success;
857 5213 : }
858 :
859 10424 : Status WriteHandler::CheckWriteAccess(const Access::SubjectDescriptor & aSubject, const ConcreteAttributePath & aPath,
860 : const Access::Privilege aRequiredPrivilege)
861 : {
862 :
863 10424 : bool checkAcl = true;
864 10424 : if (mLastSuccessfullyWrittenPath.has_value())
865 : {
866 : // only validate ACL if path has changed
867 : //
868 : // Note that this is NOT operator==: we could do `checkAcl == (aPath != *mLastSuccessfullyWrittenPath)`
869 : // however that seems to use more flash.
870 2650 : if ((aPath.mEndpointId == mLastSuccessfullyWrittenPath->mEndpointId) &&
871 5300 : (aPath.mClusterId == mLastSuccessfullyWrittenPath->mClusterId) &&
872 2650 : (aPath.mAttributeId == mLastSuccessfullyWrittenPath->mAttributeId))
873 : {
874 2634 : checkAcl = false;
875 : }
876 : }
877 :
878 10424 : if (checkAcl)
879 : {
880 7790 : Access::RequestPath requestPath{ .cluster = aPath.mClusterId,
881 7790 : .endpoint = aPath.mEndpointId,
882 : .requestType = Access::RequestType::kAttributeWriteRequest,
883 7790 : .entityId = aPath.mAttributeId };
884 :
885 7790 : CHIP_ERROR err = Access::GetAccessControl().Check(aSubject, requestPath, aRequiredPrivilege);
886 :
887 15580 : if (err == CHIP_NO_ERROR)
888 : {
889 7787 : return Status::Success;
890 : }
891 :
892 6 : if (err == CHIP_ERROR_ACCESS_DENIED)
893 : {
894 3 : return Status::UnsupportedAccess;
895 : }
896 :
897 0 : if (err == CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL)
898 : {
899 0 : return Status::AccessRestricted;
900 : }
901 :
902 0 : return Status::Failure;
903 : }
904 :
905 2634 : return Status::Success;
906 : }
907 :
908 5216 : CHIP_ERROR WriteHandler::WriteClusterData(const Access::SubjectDescriptor & aSubject, const ConcreteDataAttributePath & aPath,
909 : TLV::TLVReader & aData)
910 : {
911 : // Writes do not have a checked-path. If data model interface is enabled (both checked and only version)
912 : // the write is done via the DataModel interface
913 5216 : VerifyOrReturnError(mDataModelProvider != nullptr, CHIP_ERROR_INCORRECT_STATE);
914 :
915 5216 : ChipLogDetail(DataManagement, "Writing attribute: Cluster=" ChipLogFormatMEI " Endpoint=0x%x AttributeId=" ChipLogFormatMEI,
916 : ChipLogValueMEI(aPath.mClusterId), aPath.mEndpointId, ChipLogValueMEI(aPath.mAttributeId));
917 :
918 5216 : DataModel::ActionReturnStatus status = CheckWriteAllowed(aSubject, aPath);
919 5216 : if (status.IsSuccess())
920 : {
921 5202 : DataModel::WriteAttributeRequest request(aPath, aSubject);
922 :
923 5202 : request.writeFlags.Set(DataModel::WriteFlags::kTimed, IsTimedWrite());
924 :
925 5202 : AttributeValueDecoder decoder(aData, aSubject);
926 5202 : status = mDataModelProvider->WriteAttribute(request, decoder);
927 : }
928 :
929 5216 : mLastSuccessfullyWrittenPath = status.IsSuccess() ? std::make_optional(aPath) : std::nullopt;
930 :
931 5216 : return AddStatusInternal(aPath, StatusIB(status.GetStatusCode()));
932 : }
933 :
934 : } // namespace app
935 : } // namespace chip
|