diff --git a/src/app/Command.cpp b/src/app/Command.cpp index 743484af1c69fe..62fb6c85952533 100644 --- a/src/app/Command.cpp +++ b/src/app/Command.cpp @@ -126,7 +126,7 @@ CHIP_ERROR Command::ProcessCommandMessage(System::PacketBufferHandle && payload, void Command::Shutdown() { - VerifyOrExit(mState != CommandState::Uninitialized, ); + VerifyOrReturn(mState != CommandState::Uninitialized); mCommandMessageWriter.Reset(); AbortExistingExchangeContext(); @@ -136,8 +136,6 @@ void Command::Shutdown() ClearState(); mCommandIndex = 0; -exit: - return; } CHIP_ERROR Command::PrepareCommand(const CommandPathParams & aCommandPathParams, bool aIsStatus) diff --git a/src/app/EventManagement.cpp b/src/app/EventManagement.cpp index c97fa3ceb6198e..0f5c8adcf73c20 100644 --- a/src/app/EventManagement.cpp +++ b/src/app/EventManagement.cpp @@ -668,15 +668,13 @@ CHIP_ERROR EventManagement::EventIterator(const TLVReader & aReader, size_t aDep CHIP_ERROR EventManagement::CopyEventsSince(const TLVReader & aReader, size_t aDepth, void * apContext) { - CHIP_ERROR err = CHIP_NO_ERROR; - TLV::TLVWriter checkpoint; - EventLoadOutContext * loadOutContext = static_cast(apContext); - err = EventIterator(aReader, aDepth, loadOutContext); + EventLoadOutContext * const loadOutContext = static_cast(apContext); + CHIP_ERROR err = EventIterator(aReader, aDepth, loadOutContext); loadOutContext->mCurrentEventNumber++; if (err == CHIP_EVENT_ID_FOUND) { // checkpoint the writer - checkpoint = loadOutContext->mWriter; + TLV::TLVWriter checkpoint = loadOutContext->mWriter; err = CopyEvent(aReader, loadOutContext->mWriter, loadOutContext); @@ -684,13 +682,16 @@ CHIP_ERROR EventManagement::CopyEventsSince(const TLVReader & aReader, size_t aD // successful copy. In all other cases, roll back the // writer state back to the checkpoint, i.e., the state // before we began the copy operation. - VerifyOrExit((err == CHIP_NO_ERROR) || (err == CHIP_END_OF_TLV), loadOutContext->mWriter = checkpoint); + if ((err != CHIP_NO_ERROR) && (err != CHIP_END_OF_TLV)) + { + loadOutContext->mWriter = checkpoint; + return err; + } loadOutContext->mPreviousSystemTime.mValue = loadOutContext->mCurrentSystemTime.mValue; loadOutContext->mFirst = false; } -exit: return err; } @@ -734,86 +735,75 @@ CHIP_ERROR EventManagement::FetchEventsSince(TLVWriter & aWriter, ClusterInfo * CHIP_ERROR EventManagement::GetEventReader(TLVReader & aReader, PriorityLevel aPriority, CircularEventBufferWrapper * apBufWrapper) { - CHIP_ERROR err = CHIP_NO_ERROR; - CircularEventReader reader; CircularEventBuffer * buffer = GetPriorityBuffer(aPriority); - VerifyOrExit(buffer != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); apBufWrapper->mpCurrent = buffer; + + CircularEventReader reader; reader.Init(apBufWrapper); aReader.Init(reader); -exit: - return err; + + return CHIP_NO_ERROR; } CHIP_ERROR EventManagement::FetchEventParameters(const TLVReader & aReader, size_t aDepth, void * apContext) { - CHIP_ERROR err = CHIP_NO_ERROR; - EventEnvelopeContext * envelope = static_cast(apContext); + EventEnvelopeContext * const envelope = static_cast(apContext); TLVReader reader; - uint16_t extPriority; // Note: the type here matches the type case in EventManagement::LogEvent, priority section reader.Init(aReader); if (reader.GetTag() == TLV::ContextTag(EventDataElement::kCsTag_EventPath)) { EventPath::Parser path; - SuccessOrExit(err = path.Init(aReader)); - SuccessOrExit(err = path.GetNodeId(&(envelope->mNodeId))); - SuccessOrExit(err = path.GetEndpointId(&(envelope->mEndpointId))); - SuccessOrExit(err = path.GetClusterId(&(envelope->mClusterId))); - SuccessOrExit(err = path.GetEventId(&(envelope->mEventId))); + ReturnErrorOnFailure(path.Init(aReader)); + ReturnErrorOnFailure(path.GetNodeId(&(envelope->mNodeId))); + ReturnErrorOnFailure(path.GetEndpointId(&(envelope->mEndpointId))); + ReturnErrorOnFailure(path.GetClusterId(&(envelope->mClusterId))); + ReturnErrorOnFailure(path.GetEventId(&(envelope->mEventId))); envelope->mFieldsToRead |= 1 << EventDataElement::kCsTag_EventPath; } if (reader.GetTag() == TLV::ContextTag(EventDataElement::kCsTag_PriorityLevel)) { - err = reader.Get(extPriority); - SuccessOrExit(err); + uint16_t extPriority; // Note: the type here matches the type case in EventManagement::LogEvent, priority section + ReturnErrorOnFailure(reader.Get(extPriority)); envelope->mPriority = static_cast(extPriority); envelope->mFieldsToRead |= 1 << EventDataElement::kCsTag_PriorityLevel; } if (reader.GetTag() == TLV::ContextTag(EventDataElement::kCsTag_DeltaSystemTimestamp)) { - err = reader.Get(envelope->mDeltaSystemTime.mValue); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.Get(envelope->mDeltaSystemTime.mValue)); envelope->mFieldsToRead |= 1 << EventDataElement::kCsTag_DeltaSystemTimestamp; } -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR EventManagement::EvictEvent(CHIPCircularTLVBuffer & apBuffer, void * apAppData, TLVReader & aReader) { - ReclaimEventCtx * ctx = static_cast(apAppData); - CircularEventBuffer * eventBuffer = ctx->mpEventBuffer; - TLVType containerType; - EventEnvelopeContext context; - const bool recurse = false; - CHIP_ERROR err; - PriorityLevel imp = PriorityLevel::Invalid; - // pull out the delta time, pull out the priority - err = aReader.Next(); - SuccessOrExit(err); + ReturnErrorOnFailure(aReader.Next()); - err = aReader.EnterContainer(containerType); - SuccessOrExit(err); + TLVType containerType; + ReturnErrorOnFailure(aReader.EnterContainer(containerType)); - err = TLV::Utilities::Iterate(aReader, FetchEventParameters, &context, recurse); + EventEnvelopeContext context; + constexpr bool recurse = false; + CHIP_ERROR err = TLV::Utilities::Iterate(aReader, FetchEventParameters, &context, recurse); if (err == CHIP_END_OF_TLV) { err = CHIP_NO_ERROR; } - SuccessOrExit(err); - - err = aReader.ExitContainer(containerType); + ReturnErrorOnFailure(err); - SuccessOrExit(err); + ReturnErrorOnFailure(aReader.ExitContainer(containerType)); - imp = static_cast(context.mPriority); + const PriorityLevel imp = static_cast(context.mPriority); + ReclaimEventCtx * const ctx = static_cast(apAppData); + CircularEventBuffer * const eventBuffer = ctx->mpEventBuffer; if (eventBuffer->IsFinalDestinationForPriority(imp)) { // event is getting dropped. Increase the event number and first timestamp. @@ -826,16 +816,12 @@ CHIP_ERROR EventManagement::EvictEvent(CHIPCircularTLVBuffer & apBuffer, void * " };", static_cast(eventBuffer->GetPriorityLevel()), static_cast(imp), ChipLogValueX64(numEventsToDrop)); ctx->mSpaceNeededForMovedEvent = 0; - } - else - { - // event is not getting dropped. Note how much space it requires, and return. - ctx->mSpaceNeededForMovedEvent = aReader.GetLengthRead(); - err = CHIP_END_OF_TLV; + return CHIP_NO_ERROR; } -exit: - return err; + // event is not getting dropped. Note how much space it requires, and return. + ctx->mSpaceNeededForMovedEvent = aReader.GetLengthRead(); + return CHIP_END_OF_TLV; } CHIP_ERROR EventManagement::ScheduleFlushIfNeeded(EventOptions::Type aUrgent) diff --git a/src/app/InteractionModelEngine.cpp b/src/app/InteractionModelEngine.cpp index 599acdd0080787..32def91f2397c8 100644 --- a/src/app/InteractionModelEngine.cpp +++ b/src/app/InteractionModelEngine.cpp @@ -42,16 +42,12 @@ InteractionModelEngine * InteractionModelEngine::GetInstance() CHIP_ERROR InteractionModelEngine::Init(Messaging::ExchangeManager * apExchangeMgr, InteractionModelDelegate * apDelegate) { - CHIP_ERROR err = CHIP_NO_ERROR; - mpExchangeMgr = apExchangeMgr; mpDelegate = apDelegate; - err = mpExchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::InteractionModel::Id, this); - SuccessOrExit(err); + ReturnErrorOnFailure(mpExchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::InteractionModel::Id, this)); mReportingEngine.Init(); - SuccessOrExit(err); for (uint32_t index = 0; index < IM_SERVER_MAX_NUM_PATH_GROUPS - 1; index++) { @@ -60,8 +56,7 @@ CHIP_ERROR InteractionModelEngine::Init(Messaging::ExchangeManager * apExchangeM mClusterInfoPool[IM_SERVER_MAX_NUM_PATH_GROUPS - 1].mpNext = nullptr; mpNextAvailableClusterInfo = mClusterInfoPool; -exit: - return err; + return CHIP_NO_ERROR; } void InteractionModelEngine::Shutdown() @@ -125,26 +120,22 @@ void InteractionModelEngine::Shutdown() CHIP_ERROR InteractionModelEngine::NewCommandSender(CommandSender ** const apCommandSender) { - CHIP_ERROR err = CHIP_ERROR_NO_MEMORY; *apCommandSender = nullptr; for (auto & commandSender : mCommandSenderObjs) { if (commandSender.IsFree()) { - *apCommandSender = &commandSender; - err = commandSender.Init(mpExchangeMgr, mpDelegate); - if (CHIP_NO_ERROR != err) + const CHIP_ERROR err = commandSender.Init(mpExchangeMgr, mpDelegate); + if (err == CHIP_NO_ERROR) { - *apCommandSender = nullptr; - ExitNow(); + *apCommandSender = &commandSender; } - break; + return err; } } -exit: - return err; + return CHIP_ERROR_NO_MEMORY; } CHIP_ERROR InteractionModelEngine::NewReadClient(ReadClient ** const apReadClient) diff --git a/src/app/MessageDef/AttributeDataElement.cpp b/src/app/MessageDef/AttributeDataElement.cpp index eeb65d10a301f9..a8b679475ff9c8 100644 --- a/src/app/MessageDef/AttributeDataElement.cpp +++ b/src/app/MessageDef/AttributeDataElement.cpp @@ -393,27 +393,22 @@ AttributePath::Builder & AttributeDataElement::Builder::CreateAttributePathBuild AttributeDataElement::Builder & AttributeDataElement::Builder::DataVersion(const chip::DataVersion aDataVersion) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_DataVersion), aDataVersion); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_DataVersion), aDataVersion); + ChipLogFunctError(mError); + } return *this; } AttributeDataElement::Builder & AttributeDataElement::Builder::MoreClusterData(const bool aMoreClusterData) { // skip if error has already been set - SuccessOrExit(mError); - - if (aMoreClusterData) + if ((mError == CHIP_NO_ERROR) && aMoreClusterData) { mError = mpWriter->PutBoolean(chip::TLV::ContextTag(kCsTag_MoreClusterDataFlag), true); ChipLogFunctError(mError); } - -exit: return *this; } diff --git a/src/app/MessageDef/AttributeDataVersionList.cpp b/src/app/MessageDef/AttributeDataVersionList.cpp index a7c13cd1f12beb..712a0533f3e74f 100644 --- a/src/app/MessageDef/AttributeDataVersionList.cpp +++ b/src/app/MessageDef/AttributeDataVersionList.cpp @@ -137,24 +137,22 @@ CHIP_ERROR AttributeDataVersionList::Parser::GetVersion(chip::DataVersion * cons AttributeDataVersionList::Builder & AttributeDataVersionList::Builder::AddVersion(const uint64_t aVersion) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::AnonymousTag, aVersion); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::AnonymousTag, aVersion); + ChipLogFunctError(mError); + } return *this; } AttributeDataVersionList::Builder & AttributeDataVersionList::Builder::AddNull(void) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->PutNull(chip::TLV::AnonymousTag); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->PutNull(chip::TLV::AnonymousTag); + ChipLogFunctError(mError); + } return *this; } diff --git a/src/app/MessageDef/AttributePath.cpp b/src/app/MessageDef/AttributePath.cpp index a12d59e9f42c56..77e35dd8364014 100644 --- a/src/app/MessageDef/AttributePath.cpp +++ b/src/app/MessageDef/AttributePath.cpp @@ -217,61 +217,55 @@ CHIP_ERROR AttributePath::Builder::Init(chip::TLV::TLVWriter * const apWriter, c AttributePath::Builder & AttributePath::Builder::NodeId(const uint64_t aNodeId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_NodeId), aNodeId); - ChipLogFunctError(mError); - -exit: - + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_NodeId), aNodeId); + ChipLogFunctError(mError); + } return *this; } AttributePath::Builder & AttributePath::Builder::EndpointId(const chip::EndpointId aEndpointId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EndpointId), aEndpointId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EndpointId), aEndpointId); + ChipLogFunctError(mError); + } return *this; } AttributePath::Builder & AttributePath::Builder::ClusterId(const chip::ClusterId aClusterId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_ClusterId), aClusterId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_ClusterId), aClusterId); + ChipLogFunctError(mError); + } return *this; } AttributePath::Builder & AttributePath::Builder::FieldId(const chip::FieldId aFieldId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_FieldId), aFieldId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_FieldId), aFieldId); + ChipLogFunctError(mError); + } return *this; } AttributePath::Builder & AttributePath::Builder::ListIndex(const chip::ListIndex aListIndex) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_ListIndex), aListIndex); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_ListIndex), aListIndex); + ChipLogFunctError(mError); + } return *this; } diff --git a/src/app/MessageDef/CommandPath.cpp b/src/app/MessageDef/CommandPath.cpp index 4ae3614cb56275..10a915ceae6c5b 100644 --- a/src/app/MessageDef/CommandPath.cpp +++ b/src/app/MessageDef/CommandPath.cpp @@ -196,48 +196,44 @@ CHIP_ERROR CommandPath::Builder::Init(chip::TLV::TLVWriter * const apWriter, con CommandPath::Builder & CommandPath::Builder::EndpointId(const chip::EndpointId aEndpointId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EndpointId), aEndpointId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EndpointId), aEndpointId); + ChipLogFunctError(mError); + } return *this; } CommandPath::Builder & CommandPath::Builder::GroupId(const chip::GroupId aGroupId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_GroupId), aGroupId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_GroupId), aGroupId); + ChipLogFunctError(mError); + } return *this; } CommandPath::Builder & CommandPath::Builder::ClusterId(const chip::ClusterId aClusterId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_ClusterId), aClusterId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_ClusterId), aClusterId); + ChipLogFunctError(mError); + } return *this; } CommandPath::Builder & CommandPath::Builder::CommandId(const chip::CommandId aCommandId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_CommandId), aCommandId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_CommandId), aCommandId); + ChipLogFunctError(mError); + } return *this; } diff --git a/src/app/MessageDef/EventDataElement.cpp b/src/app/MessageDef/EventDataElement.cpp index 2f294cc4b123ee..bc5b661a28e834 100644 --- a/src/app/MessageDef/EventDataElement.cpp +++ b/src/app/MessageDef/EventDataElement.cpp @@ -463,84 +463,81 @@ CHIP_ERROR EventDataElement::Builder::Init(chip::TLV::TLVWriter * const apWriter EventPath::Builder & EventDataElement::Builder::CreateEventPathBuilder() { // skip if error has already been set - VerifyOrExit(CHIP_NO_ERROR == mError, mEventPathBuilder.ResetError(mError)); - - mError = mEventPathBuilder.Init(mpWriter, kCsTag_EventPath); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mEventPathBuilder.Init(mpWriter, kCsTag_EventPath); + ChipLogFunctError(mError); + } + else + { + mEventPathBuilder.ResetError(mError); + } return mEventPathBuilder; } EventDataElement::Builder EventDataElement::Builder::PriorityLevel(const uint8_t aPriorityLevel) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_PriorityLevel), aPriorityLevel); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_PriorityLevel), aPriorityLevel); + ChipLogFunctError(mError); + } return *this; } EventDataElement::Builder EventDataElement::Builder::Number(const uint64_t aNumber) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_Number), aNumber); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_Number), aNumber); + ChipLogFunctError(mError); + } return *this; } EventDataElement::Builder EventDataElement::Builder::UTCTimestamp(const uint64_t aUTCTimestamp) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_UTCTimestamp), aUTCTimestamp); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_UTCTimestamp), aUTCTimestamp); + ChipLogFunctError(mError); + } return *this; } EventDataElement::Builder EventDataElement::Builder::SystemTimestamp(const uint64_t aSystemTimestamp) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_SystemTimestamp), aSystemTimestamp); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_SystemTimestamp), aSystemTimestamp); + ChipLogFunctError(mError); + } return *this; } EventDataElement::Builder EventDataElement::Builder::DeltaUTCTimestamp(const uint64_t aDeltaUTCTimestamp) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_DeltaUTCTimestamp), aDeltaUTCTimestamp); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_DeltaUTCTimestamp), aDeltaUTCTimestamp); + ChipLogFunctError(mError); + } return *this; } EventDataElement::Builder EventDataElement::Builder::DeltaSystemTimestamp(const uint64_t aDeltaSystemTimestamp) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_DeltaSystemTimestamp), aDeltaSystemTimestamp); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_DeltaSystemTimestamp), aDeltaSystemTimestamp); + ChipLogFunctError(mError); + } return *this; } diff --git a/src/app/MessageDef/EventPath.cpp b/src/app/MessageDef/EventPath.cpp index 703b5a099b5e51..85bd28906f25ea 100644 --- a/src/app/MessageDef/EventPath.cpp +++ b/src/app/MessageDef/EventPath.cpp @@ -200,48 +200,44 @@ CHIP_ERROR EventPath::Builder::Init(chip::TLV::TLVWriter * const apWriter, const EventPath::Builder & EventPath::Builder::NodeId(const uint64_t aNodeId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_NodeId), aNodeId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_NodeId), aNodeId); + ChipLogFunctError(mError); + } return *this; } EventPath::Builder & EventPath::Builder::EndpointId(const chip::EndpointId aEndpointId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EndpointId), aEndpointId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EndpointId), aEndpointId); + ChipLogFunctError(mError); + } return *this; } EventPath::Builder & EventPath::Builder::ClusterId(const chip::ClusterId aClusterId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_ClusterId), aClusterId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_ClusterId), aClusterId); + ChipLogFunctError(mError); + } return *this; } EventPath::Builder & EventPath::Builder::EventId(const chip::EventId aEventId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EventId), aEventId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EventId), aEventId); + ChipLogFunctError(mError); + } return *this; } diff --git a/src/app/MessageDef/ReadRequest.cpp b/src/app/MessageDef/ReadRequest.cpp index b360399a89fac2..49888960a0d5fa 100644 --- a/src/app/MessageDef/ReadRequest.cpp +++ b/src/app/MessageDef/ReadRequest.cpp @@ -271,12 +271,11 @@ AttributeDataVersionList::Builder & ReadRequest::Builder::CreateAttributeDataVer ReadRequest::Builder & ReadRequest::Builder::EventNumber(const uint64_t aEventNumber) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EventNumber), aEventNumber); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_EventNumber), aEventNumber); + ChipLogFunctError(mError); + } return *this; } diff --git a/src/app/MessageDef/ReportData.cpp b/src/app/MessageDef/ReportData.cpp index eeab1ca965c477..cb8a29d04ea324 100644 --- a/src/app/MessageDef/ReportData.cpp +++ b/src/app/MessageDef/ReportData.cpp @@ -237,48 +237,52 @@ ReportData::Builder & ReportData::Builder::SuppressResponse(const bool aSuppress ReportData::Builder & ReportData::Builder::SubscriptionId(const uint64_t aSubscriptionId) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_SubscriptionId), aSubscriptionId); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->Put(chip::TLV::ContextTag(kCsTag_SubscriptionId), aSubscriptionId); + ChipLogFunctError(mError); + } return *this; } AttributeDataList::Builder & ReportData::Builder::CreateAttributeDataListBuilder() { // skip if error has already been set - VerifyOrExit(CHIP_NO_ERROR == mError, mAttributeDataListBuilder.ResetError(mError)); - - mError = mAttributeDataListBuilder.Init(mpWriter, kCsTag_AttributeDataList); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mAttributeDataListBuilder.Init(mpWriter, kCsTag_AttributeDataList); + ChipLogFunctError(mError); + } + else + { + mAttributeDataListBuilder.ResetError(mError); + } return mAttributeDataListBuilder; } EventList::Builder & ReportData::Builder::CreateEventDataListBuilder() { // skip if error has already been set - VerifyOrExit(CHIP_NO_ERROR == mError, mAttributeDataListBuilder.ResetError(mError)); - - mError = mEventDataListBuilder.Init(mpWriter, kCsTag_EventDataList); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mEventDataListBuilder.Init(mpWriter, kCsTag_EventDataList); + ChipLogFunctError(mError); + } + else + { + mAttributeDataListBuilder.ResetError(mError); + } return mEventDataListBuilder; } ReportData::Builder & ReportData::Builder::MoreChunkedMessages(const bool aMoreChunkedMessages) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->PutBoolean(chip::TLV::ContextTag(kCsTag_MoreChunkedMessages), aMoreChunkedMessages); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->PutBoolean(chip::TLV::ContextTag(kCsTag_MoreChunkedMessages), aMoreChunkedMessages); + ChipLogFunctError(mError); + } return *this; } diff --git a/src/app/MessageDef/WriteRequest.cpp b/src/app/MessageDef/WriteRequest.cpp index accdd7e3a4a536..a0463c020fd793 100644 --- a/src/app/MessageDef/WriteRequest.cpp +++ b/src/app/MessageDef/WriteRequest.cpp @@ -198,48 +198,53 @@ CHIP_ERROR WriteRequest::Builder::Init(chip::TLV::TLVWriter * const apWriter) WriteRequest::Builder & WriteRequest::Builder::SuppressResponse(const bool aSuppressResponse) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->PutBoolean(chip::TLV::ContextTag(kCsTag_SuppressResponse), aSuppressResponse); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->PutBoolean(chip::TLV::ContextTag(kCsTag_SuppressResponse), aSuppressResponse); + ChipLogFunctError(mError); + } return *this; } AttributeDataList::Builder & WriteRequest::Builder::CreateAttributeDataListBuilder() { // skip if error has already been set - VerifyOrExit(CHIP_NO_ERROR == mError, mAttributeDataListBuilder.ResetError(mError)); - - mError = mAttributeDataListBuilder.Init(mpWriter, kCsTag_AttributeDataList); - ChipLogFunctError(mError); + if (mError == CHIP_NO_ERROR) + { + mError = mAttributeDataListBuilder.Init(mpWriter, kCsTag_AttributeDataList); + ChipLogFunctError(mError); + } + else + { + mAttributeDataListBuilder.ResetError(mError); + } -exit: return mAttributeDataListBuilder; } AttributeDataVersionList::Builder & WriteRequest::Builder::CreateAttributeDataVersionListBuilder() { // skip if error has already been set - VerifyOrExit(CHIP_NO_ERROR == mError, mAttributeDataVersionListBuilder.ResetError(mError)); - - mError = mAttributeDataVersionListBuilder.Init(mpWriter, kCsTag_AttributeDataVersionList); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mAttributeDataVersionListBuilder.Init(mpWriter, kCsTag_AttributeDataVersionList); + ChipLogFunctError(mError); + } + else + { + mAttributeDataVersionListBuilder.ResetError(mError); + } return mAttributeDataVersionListBuilder; } WriteRequest::Builder & WriteRequest::Builder::MoreChunkedMessages(const bool aMoreChunkedMessages) { // skip if error has already been set - SuccessOrExit(mError); - - mError = mpWriter->PutBoolean(chip::TLV::ContextTag(kCsTag_MoreChunkedMessages), aMoreChunkedMessages); - ChipLogFunctError(mError); - -exit: + if (mError == CHIP_NO_ERROR) + { + mError = mpWriter->PutBoolean(chip::TLV::ContextTag(kCsTag_MoreChunkedMessages), aMoreChunkedMessages); + ChipLogFunctError(mError); + } return *this; } diff --git a/src/app/MessageDef/WriteResponse.cpp b/src/app/MessageDef/WriteResponse.cpp index b98426be80c87f..941f51ffc113d5 100644 --- a/src/app/MessageDef/WriteResponse.cpp +++ b/src/app/MessageDef/WriteResponse.cpp @@ -130,12 +130,16 @@ CHIP_ERROR WriteResponse::Builder::Init(chip::TLV::TLVWriter * const apWriter) AttributeStatusList::Builder & WriteResponse::Builder::CreateAttributeStatusListBuilder() { // skip if error has already been set - VerifyOrExit(CHIP_NO_ERROR == mError, mAttributeStatusListBuilder.ResetError(mError)); - - mError = mAttributeStatusListBuilder.Init(mpWriter, kCsTag_AttributeStatusList); - ChipLogFunctError(mError); + if (mError == CHIP_NO_ERROR) + { + mError = mAttributeStatusListBuilder.Init(mpWriter, kCsTag_AttributeStatusList); + ChipLogFunctError(mError); + } + else + { + mAttributeStatusListBuilder.ResetError(mError); + } -exit: return mAttributeStatusListBuilder; } diff --git a/src/app/decoder.cpp b/src/app/decoder.cpp index 4f7724680328bf..5306f49dcab9eb 100644 --- a/src/app/decoder.cpp +++ b/src/app/decoder.cpp @@ -41,22 +41,18 @@ uint16_t extractApsFrame(uint8_t * buffer, uint16_t buf_length, EmberApsFrame * chip::DataModelReader reader(buffer, buf_length); - CHIP_ERROR err = CHIP_NO_ERROR; - // Skip first byte, because that's the always-0 frame control. uint8_t ignored; - err = reader.ReadOctet(&ignored) - .ReadClusterId(&outApsFrame->clusterId) - .ReadEndpointId(&outApsFrame->sourceEndpoint) - .ReadEndpointId(&outApsFrame->destinationEndpoint) - .Read16(&outApsFrame->options) - .ReadGroupId(&outApsFrame->groupId) - .ReadOctet(&outApsFrame->sequence) - .ReadOctet(&outApsFrame->radius) - .StatusCode(); - SuccessOrExit(err); + const CHIP_ERROR err = reader.ReadOctet(&ignored) + .ReadClusterId(&outApsFrame->clusterId) + .ReadEndpointId(&outApsFrame->sourceEndpoint) + .ReadEndpointId(&outApsFrame->destinationEndpoint) + .Read16(&outApsFrame->options) + .ReadGroupId(&outApsFrame->groupId) + .ReadOctet(&outApsFrame->sequence) + .ReadOctet(&outApsFrame->radius) + .StatusCode(); -exit: return err == CHIP_NO_ERROR ? reader.OctetsRead() : 0; } diff --git a/src/app/server/Mdns.cpp b/src/app/server/Mdns.cpp index 3bab44a92f2661..329eacb34c3b63 100644 --- a/src/app/server/Mdns.cpp +++ b/src/app/server/Mdns.cpp @@ -275,20 +275,17 @@ void StartServer() #if CHIP_ENABLE_ROTATING_DEVICE_ID CHIP_ERROR GenerateRotatingDeviceId(char rotatingDeviceIdHexBuffer[], size_t rotatingDeviceIdHexBufferSize) { - CHIP_ERROR error = CHIP_NO_ERROR; char serialNumber[chip::DeviceLayer::ConfigurationManager::kMaxSerialNumberLength + 1]; size_t serialNumberSize = 0; uint16_t lifetimeCounter = 0; size_t rotatingDeviceIdValueOutputSize = 0; - SuccessOrExit(error = - chip::DeviceLayer::ConfigurationMgr().GetSerialNumber(serialNumber, sizeof(serialNumber), serialNumberSize)); - SuccessOrExit(error = chip::DeviceLayer::ConfigurationMgr().GetLifetimeCounter(lifetimeCounter)); - SuccessOrExit(error = AdditionalDataPayloadGenerator().generateRotatingDeviceId( - lifetimeCounter, serialNumber, serialNumberSize, rotatingDeviceIdHexBuffer, rotatingDeviceIdHexBufferSize, - rotatingDeviceIdValueOutputSize)); -exit: - return error; + ReturnErrorOnFailure( + chip::DeviceLayer::ConfigurationMgr().GetSerialNumber(serialNumber, sizeof(serialNumber), serialNumberSize)); + ReturnErrorOnFailure(chip::DeviceLayer::ConfigurationMgr().GetLifetimeCounter(lifetimeCounter)); + return AdditionalDataPayloadGenerator().generateRotatingDeviceId(lifetimeCounter, serialNumber, serialNumberSize, + rotatingDeviceIdHexBuffer, rotatingDeviceIdHexBufferSize, + rotatingDeviceIdValueOutputSize); } #endif diff --git a/src/app/server/OnboardingCodesUtil.cpp b/src/app/server/OnboardingCodesUtil.cpp index 0c7852793b7adf..dd82b30c32bc26 100644 --- a/src/app/server/OnboardingCodesUtil.cpp +++ b/src/app/server/OnboardingCodesUtil.cpp @@ -85,76 +85,91 @@ CHIP_ERROR GetSetupPayload(chip::SetupPayload & aSetupPayload, chip::RendezvousI aSetupPayload.rendezvousInformation = aRendezvousFlags; err = ConfigurationMgr().GetSetupPinCode(aSetupPayload.setUpPINCode); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogProgress(AppServer, "ConfigurationMgr().GetSetupPinCode() failed: %s", chip::ErrorStr(err))); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(AppServer, "ConfigurationMgr().GetSetupPinCode() failed: %s", chip::ErrorStr(err)); + return err; + } err = ConfigurationMgr().GetSetupDiscriminator(aSetupPayload.discriminator); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogProgress(AppServer, "ConfigurationMgr().GetSetupDiscriminator() failed: %s", chip::ErrorStr(err))); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(AppServer, "ConfigurationMgr().GetSetupDiscriminator() failed: %s", chip::ErrorStr(err)); + return err; + } err = ConfigurationMgr().GetVendorId(aSetupPayload.vendorID); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogProgress(AppServer, "ConfigurationMgr().GetVendorId() failed: %s", chip::ErrorStr(err))); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(AppServer, "ConfigurationMgr().GetVendorId() failed: %s", chip::ErrorStr(err)); + return err; + } err = ConfigurationMgr().GetProductId(aSetupPayload.productID); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogProgress(AppServer, "ConfigurationMgr().GetProductId() failed: %s", chip::ErrorStr(err))); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(AppServer, "ConfigurationMgr().GetProductId() failed: %s", chip::ErrorStr(err)); + return err; + } -exit: return err; } CHIP_ERROR GetQRCode(std::string & aQRCode, chip::RendezvousInformationFlags aRendezvousFlags) { - CHIP_ERROR err = CHIP_NO_ERROR; chip::SetupPayload payload; - err = GetSetupPayload(payload, aRendezvousFlags); - VerifyOrExit(err == CHIP_NO_ERROR, ChipLogProgress(AppServer, "GetSetupPayload() failed: %s", chip::ErrorStr(err))); + CHIP_ERROR err = GetSetupPayload(payload, aRendezvousFlags); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(AppServer, "GetSetupPayload() failed: %s", chip::ErrorStr(err)); + return err; + } // TODO: Usage of STL will significantly increase the image size, this should be changed to more efficient method for // generating payload err = chip::QRCodeSetupPayloadGenerator(payload).payloadBase38Representation(aQRCode); - VerifyOrExit(err == CHIP_NO_ERROR, ChipLogProgress(AppServer, "Generating QR Code failed: %s", chip::ErrorStr(err))); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(AppServer, "Generating QR Code failed: %s", chip::ErrorStr(err)); + return err; + } -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR GetQRCodeUrl(char * aQRCodeUrl, size_t aUrlMaxSize, const std::string & aQRCode) { - CHIP_ERROR err = CHIP_NO_ERROR; - int writtenDataSize; - - VerifyOrExit(aQRCodeUrl, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(aUrlMaxSize >= (strlen(kQrCodeBaseUrl) + strlen(kUrlDataAssignmentPhrase) + aQRCode.size() + 1), - err = CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(aQRCodeUrl, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(aUrlMaxSize >= (strlen(kQrCodeBaseUrl) + strlen(kUrlDataAssignmentPhrase) + aQRCode.size() + 1), + CHIP_ERROR_BUFFER_TOO_SMALL); - writtenDataSize = snprintf(aQRCodeUrl, aUrlMaxSize, "%s%s", kQrCodeBaseUrl, kUrlDataAssignmentPhrase); - VerifyOrExit((writtenDataSize > 0) && (writtenDataSize < static_cast(aUrlMaxSize)), - err = CHIP_ERROR_INVALID_STRING_LENGTH); + const int writtenDataSize = snprintf(aQRCodeUrl, aUrlMaxSize, "%s%s", kQrCodeBaseUrl, kUrlDataAssignmentPhrase); + VerifyOrReturnError((writtenDataSize > 0) && (writtenDataSize < static_cast(aUrlMaxSize)), + CHIP_ERROR_INVALID_STRING_LENGTH); - err = EncodeQRCodeToUrl(aQRCode.c_str(), aQRCode.size(), aQRCodeUrl + writtenDataSize, aUrlMaxSize - writtenDataSize); - VerifyOrExit(err == CHIP_NO_ERROR, ); - -exit: - return err; + return EncodeQRCodeToUrl(aQRCode.c_str(), aQRCode.size(), aQRCodeUrl + writtenDataSize, aUrlMaxSize - writtenDataSize); } CHIP_ERROR GetManualPairingCode(std::string & aManualPairingCode, chip::RendezvousInformationFlags aRendezvousFlags) { - CHIP_ERROR err = CHIP_NO_ERROR; chip::SetupPayload payload; - err = GetSetupPayload(payload, aRendezvousFlags); - VerifyOrExit(err == CHIP_NO_ERROR, ChipLogProgress(AppServer, "GetSetupPayload() failed: %s", chip::ErrorStr(err))); + CHIP_ERROR err = GetSetupPayload(payload, aRendezvousFlags); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(AppServer, "GetSetupPayload() failed: %s", chip::ErrorStr(err)); + return err; + } err = chip::ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(aManualPairingCode); - VerifyOrExit(err == CHIP_NO_ERROR, - ChipLogProgress(AppServer, "Generating Manual Pairing Code failed: %s", chip::ErrorStr(err))); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(AppServer, "Generating Manual Pairing Code failed: %s", chip::ErrorStr(err)); + return err; + } -exit: - return err; + return CHIP_NO_ERROR; } static inline bool isCharUnreservedInRfc3986(const char c) @@ -165,10 +180,9 @@ static inline bool isCharUnreservedInRfc3986(const char c) CHIP_ERROR EncodeQRCodeToUrl(const char * aQRCode, size_t aLen, char * aUrl, size_t aMaxSize) { const char upperHexDigits[] = "0123456789ABCDEF"; - CHIP_ERROR err = CHIP_NO_ERROR; size_t i = 0, j = 0; - VerifyOrExit((aQRCode != nullptr) && (aUrl != nullptr), err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((aQRCode != nullptr) && (aUrl != nullptr), CHIP_ERROR_INVALID_ARGUMENT); for (i = 0; i < aLen; ++i) { @@ -176,14 +190,14 @@ CHIP_ERROR EncodeQRCodeToUrl(const char * aQRCode, size_t aLen, char * aUrl, siz if (isCharUnreservedInRfc3986(c)) { - VerifyOrExit((j + 1) < aMaxSize, err = CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError((j + 1) < aMaxSize, CHIP_ERROR_BUFFER_TOO_SMALL); aUrl[j++] = c; } else { - VerifyOrExit((j + 3) < aMaxSize, err = CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError((j + 3) < aMaxSize, CHIP_ERROR_BUFFER_TOO_SMALL); aUrl[j++] = '%'; aUrl[j++] = upperHexDigits[(c & 0xf0) >> 4]; @@ -193,6 +207,5 @@ CHIP_ERROR EncodeQRCodeToUrl(const char * aQRCode, size_t aLen, char * aUrl, siz aUrl[j] = '\0'; -exit: - return err; + return CHIP_NO_ERROR; } diff --git a/src/app/tests/integration/chip_im_initiator.cpp b/src/app/tests/integration/chip_im_initiator.cpp index 68e430ffedca2e..101e260958e95a 100644 --- a/src/app/tests/integration/chip_im_initiator.cpp +++ b/src/app/tests/integration/chip_im_initiator.cpp @@ -128,6 +128,7 @@ CHIP_ERROR SendCommandRequest(chip::app::CommandSender * commandSender) err = commandSender->SendCommandRequest(chip::kTestDeviceNodeId, gAdminId); SuccessOrExit(err); +exit: if (err == CHIP_NO_ERROR) { gCommandCount++; @@ -136,7 +137,6 @@ CHIP_ERROR SendCommandRequest(chip::app::CommandSender * commandSender) { printf("Send invoke command request failed, err: %s\n", chip::ErrorStr(err)); } -exit: return err; } @@ -165,6 +165,7 @@ CHIP_ERROR SendBadCommandRequest(chip::app::CommandSender * commandSender) err = commandSender->SendCommandRequest(chip::kTestDeviceNodeId, gAdminId); SuccessOrExit(err); +exit: if (err == CHIP_NO_ERROR) { gCommandCount++; @@ -173,7 +174,6 @@ CHIP_ERROR SendBadCommandRequest(chip::app::CommandSender * commandSender) { printf("Send invoke command request failed, err: %s\n", chip::ErrorStr(err)); } -exit: return err; } @@ -192,6 +192,7 @@ CHIP_ERROR SendReadRequest() err = gpReadClient->SendReadRequest(chip::kTestDeviceNodeId, gAdminId, &eventPathParams, 1, &attributePathParams, 1, number); SuccessOrExit(err); +exit: if (err == CHIP_NO_ERROR) { gReadCount++; @@ -200,7 +201,6 @@ CHIP_ERROR SendReadRequest() { printf("Send read request failed, err: %s\n", chip::ErrorStr(err)); } -exit: return err; } diff --git a/src/app/tests/integration/chip_im_responder.cpp b/src/app/tests/integration/chip_im_responder.cpp index 1c49d712c28ada..b4d5aa8b89da6e 100644 --- a/src/app/tests/integration/chip_im_responder.cpp +++ b/src/app/tests/integration/chip_im_responder.cpp @@ -53,7 +53,6 @@ bool ServerClusterCommandExists(chip::ClusterId aClusterId, chip::CommandId aCom void DispatchSingleClusterCommand(chip::ClusterId aClusterId, chip::CommandId aCommandId, chip::EndpointId aEndPointId, chip::TLV::TLVReader & aReader, Command * apCommandObj) { - CHIP_ERROR err = CHIP_NO_ERROR; static bool statusCodeFlipper = false; if (aClusterId != kTestClusterId || aCommandId != kTestCommandId || aEndPointId != kTestEndpointId) @@ -85,23 +84,16 @@ void DispatchSingleClusterCommand(chip::ClusterId aClusterId, chip::CommandId aC chip::TLV::TLVWriter * writer; - err = apCommandObj->PrepareCommand(commandPathParams); - SuccessOrExit(err); + ReturnOnFailure(apCommandObj->PrepareCommand(commandPathParams)); writer = apCommandObj->GetCommandDataElementTLVWriter(); - err = writer->Put(chip::TLV::ContextTag(kTestFieldId1), kTestFieldValue1); - SuccessOrExit(err); + ReturnOnFailure(writer->Put(chip::TLV::ContextTag(kTestFieldId1), kTestFieldValue1)); - err = writer->Put(chip::TLV::ContextTag(kTestFieldId2), kTestFieldValue2); - SuccessOrExit(err); + ReturnOnFailure(writer->Put(chip::TLV::ContextTag(kTestFieldId2), kTestFieldValue2)); - err = apCommandObj->FinishCommand(); - SuccessOrExit(err); + ReturnOnFailure(apCommandObj->FinishCommand()); } statusCodeFlipper = !statusCodeFlipper; - -exit: - return; } CHIP_ERROR ReadSingleClusterData(ClusterInfo & aClusterInfo, TLV::TLVWriter & aWriter) diff --git a/src/controller/CHIPCluster.cpp b/src/controller/CHIPCluster.cpp index 62656f2c4c26ae..7156ae94c42ef4 100644 --- a/src/controller/CHIPCluster.cpp +++ b/src/controller/CHIPCluster.cpp @@ -76,13 +76,10 @@ CHIP_ERROR ClusterBase::SendCommand(uint8_t seqNum, chip::System::PacketBufferHa CHIP_ERROR ClusterBase::RequestAttributeReporting(AttributeId attributeId, Callback::Cancelable * onReportCallback) { - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(onReportCallback != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(onReportCallback != nullptr, CHIP_ERROR_INVALID_ARGUMENT); mDevice->AddReportHandler(mEndpoint, mClusterId, attributeId, onReportCallback); -exit: - return err; + return CHIP_NO_ERROR; } } // namespace Controller diff --git a/src/controller/CHIPDevice.cpp b/src/controller/CHIPDevice.cpp index 863e9cdfe228b6..e4f5e28fa4221c 100644 --- a/src/controller/CHIPDevice.cpp +++ b/src/controller/CHIPDevice.cpp @@ -151,10 +151,6 @@ CHIP_ERROR Device::SendCommands(app::CommandSender * commandObj) CHIP_ERROR Device::Serialize(SerializedDevice & output) { - CHIP_ERROR error = CHIP_NO_ERROR; - uint16_t serializedLen = 0; - uint32_t localMessageCounter = 0; - uint32_t peerMessageCounter = 0; SerializableDevice serializable; static_assert(BASE64_ENCODED_LEN(sizeof(serializable)) <= sizeof(output.inner), @@ -169,9 +165,9 @@ CHIP_ERROR Device::Serialize(SerializedDevice & output) serializable.mAdminId = Encoding::LittleEndian::HostSwap16(mAdminId); Transport::PeerConnectionState * connectionState = mSessionManager->GetPeerConnectionState(mSecureSession); - VerifyOrExit(connectionState != nullptr, error = CHIP_ERROR_INCORRECT_STATE); - localMessageCounter = connectionState->GetSessionMessageCounter().GetLocalMessageCounter().Value(); - peerMessageCounter = connectionState->GetSessionMessageCounter().GetPeerMessageCounter().GetCounter(); + VerifyOrReturnError(connectionState != nullptr, CHIP_ERROR_INCORRECT_STATE); + const uint32_t localMessageCounter = connectionState->GetSessionMessageCounter().GetLocalMessageCounter().Value(); + const uint32_t peerMessageCounter = connectionState->GetSessionMessageCounter().GetPeerMessageCounter().GetCounter(); serializable.mLocalMessageCounter = Encoding::LittleEndian::HostSwap32(localMessageCounter); serializable.mPeerMessageCounter = Encoding::LittleEndian::HostSwap32(peerMessageCounter); @@ -183,53 +179,47 @@ CHIP_ERROR Device::Serialize(SerializedDevice & output) "The underlying type of Transport::Type is not uint8_t."); serializable.mDeviceTransport = static_cast(mDeviceAddress.GetTransportType()); - SuccessOrExit(error = Inet::GetInterfaceName(mDeviceAddress.GetInterface(), Uint8::to_char(serializable.mInterfaceName), - sizeof(serializable.mInterfaceName))); + ReturnErrorOnFailure(Inet::GetInterfaceName(mDeviceAddress.GetInterface(), Uint8::to_char(serializable.mInterfaceName), + sizeof(serializable.mInterfaceName))); static_assert(sizeof(serializable.mDeviceAddr) <= INET6_ADDRSTRLEN, "Size of device address must fit within INET6_ADDRSTRLEN"); mDeviceAddress.GetIPAddress().ToString(Uint8::to_char(serializable.mDeviceAddr), sizeof(serializable.mDeviceAddr)); - serializedLen = chip::Base64Encode(Uint8::to_const_uchar(reinterpret_cast(&serializable)), - static_cast(sizeof(serializable)), Uint8::to_char(output.inner)); - VerifyOrExit(serializedLen > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(serializedLen < sizeof(output.inner), error = CHIP_ERROR_INVALID_ARGUMENT); + const uint16_t serializedLen = chip::Base64Encode(Uint8::to_const_uchar(reinterpret_cast(&serializable)), + static_cast(sizeof(serializable)), Uint8::to_char(output.inner)); + VerifyOrReturnError(serializedLen > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(serializedLen < sizeof(output.inner), CHIP_ERROR_INVALID_ARGUMENT); output.inner[serializedLen] = '\0'; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Device::Deserialize(const SerializedDevice & input) { - CHIP_ERROR error = CHIP_NO_ERROR; SerializableDevice serializable; - size_t maxlen = BASE64_ENCODED_LEN(sizeof(serializable)); - size_t len = strnlen(Uint8::to_const_char(&input.inner[0]), maxlen); - uint16_t deserializedLen = 0; - Inet::IPAddress ipAddress = {}; + constexpr size_t maxlen = BASE64_ENCODED_LEN(sizeof(serializable)); + const size_t len = strnlen(Uint8::to_const_char(&input.inner[0]), maxlen); - VerifyOrExit(len < sizeof(SerializedDevice), error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(CanCastTo(len), error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(len < sizeof(SerializedDevice), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(CanCastTo(len), CHIP_ERROR_INVALID_ARGUMENT); CHIP_ZERO_AT(serializable); - deserializedLen = Base64Decode(Uint8::to_const_char(input.inner), static_cast(len), - Uint8::to_uchar(reinterpret_cast(&serializable))); + const uint16_t deserializedLen = Base64Decode(Uint8::to_const_char(input.inner), static_cast(len), + Uint8::to_uchar(reinterpret_cast(&serializable))); - VerifyOrExit(deserializedLen > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(deserializedLen <= sizeof(serializable), error = CHIP_ERROR_INVALID_ARGUMENT); - - uint16_t port; - Inet::InterfaceId interfaceId; + VerifyOrReturnError(deserializedLen > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(deserializedLen <= sizeof(serializable), CHIP_ERROR_INVALID_ARGUMENT); // The second parameter to FromString takes the strlen value. We are subtracting 1 // from the sizeof(serializable.mDeviceAddr) to account for null termination, since // strlen doesn't include null character in the size. - VerifyOrExit( + Inet::IPAddress ipAddress = {}; + VerifyOrReturnError( IPAddress::FromString(Uint8::to_const_char(serializable.mDeviceAddr), sizeof(serializable.mDeviceAddr) - 1, ipAddress), - error = CHIP_ERROR_INVALID_ADDRESS); + CHIP_ERROR_INVALID_ADDRESS); mPairing = serializable.mOpsCreds; mDeviceId = Encoding::LittleEndian::HostSwap64(serializable.mDeviceId); - port = Encoding::LittleEndian::HostSwap16(serializable.mDevicePort); + const uint16_t port = Encoding::LittleEndian::HostSwap16(serializable.mDevicePort); mAdminId = Encoding::LittleEndian::HostSwap16(serializable.mAdminId); mLocalMessageCounter = Encoding::LittleEndian::HostSwap32(serializable.mLocalMessageCounter); mPeerMessageCounter = Encoding::LittleEndian::HostSwap32(serializable.mPeerMessageCounter); @@ -247,7 +237,7 @@ CHIP_ERROR Device::Deserialize(const SerializedDevice & input) // The InterfaceNameToId() API requires initialization of mInterface, and lock/unlock of // LwIP stack. - interfaceId = INET_NULL_INTERFACEID; + Inet::InterfaceId interfaceId = INET_NULL_INTERFACEID; if (serializable.mInterfaceName[0] != '\0') { #if CHIP_SYSTEM_CONFIG_USE_LWIP @@ -257,7 +247,7 @@ CHIP_ERROR Device::Deserialize(const SerializedDevice & input) #if CHIP_SYSTEM_CONFIG_USE_LWIP UNLOCK_TCPIP_CORE(); #endif - VerifyOrExit(CHIP_NO_ERROR == inetErr, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(CHIP_NO_ERROR == inetErr, CHIP_ERROR_INTERNAL); } static_assert(std::is_same::type, uint8_t>::value, @@ -273,11 +263,10 @@ CHIP_ERROR Device::Deserialize(const SerializedDevice & input) case Transport::Type::kTcp: case Transport::Type::kUndefined: default: - ExitNow(error = CHIP_ERROR_INTERNAL); + return CHIP_ERROR_INTERNAL; } -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Device::Persist() @@ -286,7 +275,7 @@ CHIP_ERROR Device::Persist() if (mStorageDelegate != nullptr) { SerializedDevice serialized; - SuccessOrExit(error = Serialize(serialized)); + ReturnErrorOnFailure(Serialize(serialized)); // TODO: no need to base-64 the serialized values AGAIN PERSISTENT_KEY_OP(GetDeviceId(), kPairedDeviceKeyPrefix, key, @@ -296,7 +285,6 @@ CHIP_ERROR Device::Persist() ChipLogError(Controller, "Failed to persist device %" PRId32, error); } } -exit: return error; } diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index a67bf4e2c4e32c..64b4a7fb214663 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -112,11 +112,7 @@ DeviceController::DeviceController() CHIP_ERROR DeviceController::Init(NodeId localDeviceId, ControllerInitParams params) { - CHIP_ERROR err = CHIP_NO_ERROR; - - Transport::AdminPairingInfo * admin = nullptr; - - VerifyOrExit(mState == State::NotInitialized, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mState == State::NotInitialized, CHIP_ERROR_INCORRECT_STATE); if (params.systemLayer != nullptr && params.inetLayer != nullptr) { @@ -126,16 +122,15 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, ControllerInitParams par else { #if CONFIG_DEVICE_LAYER - err = DeviceLayer::PlatformMgr().InitChipStack(); - SuccessOrExit(err); + ReturnErrorOnFailure(DeviceLayer::PlatformMgr().InitChipStack()); mSystemLayer = &DeviceLayer::SystemLayer; mInetLayer = &DeviceLayer::InetLayer; #endif // CONFIG_DEVICE_LAYER } - VerifyOrExit(mSystemLayer != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(mInetLayer != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mSystemLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mInetLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); mStorageDelegate = params.storageDelegate; #if CONFIG_NETWORK_LAYER_BLE @@ -146,7 +141,7 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, ControllerInitParams par } #endif // CONFIG_DEVICE_LAYER mBleLayer = params.bleLayer; - VerifyOrExit(mBleLayer != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mBleLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #endif mTransportMgr = chip::Platform::New(); @@ -154,7 +149,7 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, ControllerInitParams par mExchangeMgr = chip::Platform::New(); mMessageCounterManager = chip::Platform::New(); - err = mTransportMgr->Init( + ReturnErrorOnFailure(mTransportMgr->Init( Transport::UdpListenParameters(mInetLayer).SetAddressType(Inet::kIPAddressType_IPv6).SetListenPort(mListenPort) #if INET_CONFIG_ENABLE_IPV4 , @@ -164,46 +159,37 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, ControllerInitParams par , Transport::BleListenParameters(mBleLayer) #endif - ); - SuccessOrExit(err); + )); - err = mAdmins.Init(mStorageDelegate); - SuccessOrExit(err); + ReturnErrorOnFailure(mAdmins.Init(mStorageDelegate)); - admin = mAdmins.AssignAdminId(mAdminId, localDeviceId); - VerifyOrExit(admin != nullptr, err = CHIP_ERROR_NO_MEMORY); + Transport::AdminPairingInfo * const admin = mAdmins.AssignAdminId(mAdminId, localDeviceId); + VerifyOrReturnError(admin != nullptr, CHIP_ERROR_NO_MEMORY); - err = mAdmins.LoadFromStorage(mAdminId); - SuccessOrExit(err); + ReturnErrorOnFailure(mAdmins.LoadFromStorage(mAdminId)); - err = mSessionMgr->Init(localDeviceId, mSystemLayer, mTransportMgr, &mAdmins, mMessageCounterManager); - SuccessOrExit(err); + ReturnErrorOnFailure(mSessionMgr->Init(localDeviceId, mSystemLayer, mTransportMgr, &mAdmins, mMessageCounterManager)); - err = mExchangeMgr->Init(mSessionMgr); - SuccessOrExit(err); + ReturnErrorOnFailure(mExchangeMgr->Init(mSessionMgr)); - err = mMessageCounterManager->Init(mExchangeMgr); - SuccessOrExit(err); + ReturnErrorOnFailure(mMessageCounterManager->Init(mExchangeMgr)); - err = mExchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::TempZCL::Id, this); - SuccessOrExit(err); + ReturnErrorOnFailure(mExchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::TempZCL::Id, this)); if (params.imDelegate != nullptr) { - err = chip::app::InteractionModelEngine::GetInstance()->Init(mExchangeMgr, params.imDelegate); + ReturnErrorOnFailure(chip::app::InteractionModelEngine::GetInstance()->Init(mExchangeMgr, params.imDelegate)); } else { mDefaultIMDelegate = chip::Platform::New(); - err = chip::app::InteractionModelEngine::GetInstance()->Init(mExchangeMgr, mDefaultIMDelegate); + ReturnErrorOnFailure(chip::app::InteractionModelEngine::GetInstance()->Init(mExchangeMgr, mDefaultIMDelegate)); } - SuccessOrExit(err); mExchangeMgr->SetDelegate(this); #if CHIP_DEVICE_CONFIG_ENABLE_MDNS - err = Mdns::Resolver::Instance().SetResolverDelegate(this); - SuccessOrExit(err); + ReturnErrorOnFailure(Mdns::Resolver::Instance().SetResolverDelegate(this)); RegisterDeviceAddressUpdateDelegate(params.mDeviceAddressUpdateDelegate); @@ -215,16 +201,14 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, ControllerInitParams par mState = State::Initialized; mLocalDeviceId = localDeviceId; - VerifyOrExit(params.operationalCredentialsDelegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(params.operationalCredentialsDelegate != nullptr, CHIP_ERROR_INVALID_ARGUMENT); mOperationalCredentialsDelegate = params.operationalCredentialsDelegate; - err = LoadLocalCredentials(admin); - SuccessOrExit(err); + ReturnErrorOnFailure(LoadLocalCredentials(admin)); ReleaseAllDevices(); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR DeviceController::LoadLocalCredentials(Transport::AdminPairingInfo * admin) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 9e18fb7bbf8cc8..957361720891e4 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -674,14 +674,12 @@ JNI_ANDROID_CHIP_STACK_METHOD(void, handleWriteConfirmation) chip::Ble::ChipBleUUID svcUUID; chip::Ble::ChipBleUUID charUUID; - VerifyOrExit(JavaBytesToUUID(env, svcId, svcUUID), - ChipLogError(Controller, "handleWriteConfirmation() called with invalid service ID")); - VerifyOrExit(JavaBytesToUUID(env, charId, charUUID), - ChipLogError(Controller, "handleWriteConfirmation() called with invalid characteristic ID")); + VerifyOrReturn(JavaBytesToUUID(env, svcId, svcUUID), + ChipLogError(Controller, "handleWriteConfirmation() called with invalid service ID")); + VerifyOrReturn(JavaBytesToUUID(env, charId, charUUID), + ChipLogError(Controller, "handleWriteConfirmation() called with invalid characteristic ID")); sBleLayer.HandleWriteConfirmation(connObj, &svcUUID, &charUUID); -exit: - return; } JNI_ANDROID_CHIP_STACK_METHOD(void, handleSubscribeComplete) @@ -692,14 +690,12 @@ JNI_ANDROID_CHIP_STACK_METHOD(void, handleSubscribeComplete) chip::Ble::ChipBleUUID svcUUID; chip::Ble::ChipBleUUID charUUID; - VerifyOrExit(JavaBytesToUUID(env, svcId, svcUUID), - ChipLogError(Controller, "handleSubscribeComplete() called with invalid service ID")); - VerifyOrExit(JavaBytesToUUID(env, charId, charUUID), - ChipLogError(Controller, "handleSubscribeComplete() called with invalid characteristic ID")); + VerifyOrReturn(JavaBytesToUUID(env, svcId, svcUUID), + ChipLogError(Controller, "handleSubscribeComplete() called with invalid service ID")); + VerifyOrReturn(JavaBytesToUUID(env, charId, charUUID), + ChipLogError(Controller, "handleSubscribeComplete() called with invalid characteristic ID")); sBleLayer.HandleSubscribeComplete(connObj, &svcUUID, &charUUID); -exit: - return; } JNI_ANDROID_CHIP_STACK_METHOD(void, handleUnsubscribeComplete) @@ -710,14 +706,12 @@ JNI_ANDROID_CHIP_STACK_METHOD(void, handleUnsubscribeComplete) chip::Ble::ChipBleUUID svcUUID; chip::Ble::ChipBleUUID charUUID; - VerifyOrExit(JavaBytesToUUID(env, svcId, svcUUID), - ChipLogError(Controller, "handleUnsubscribeComplete() called with invalid service ID")); - VerifyOrExit(JavaBytesToUUID(env, charId, charUUID), - ChipLogError(Controller, "handleUnsubscribeComplete() called with invalid characteristic ID")); + VerifyOrReturn(JavaBytesToUUID(env, svcId, svcUUID), + ChipLogError(Controller, "handleUnsubscribeComplete() called with invalid service ID")); + VerifyOrReturn(JavaBytesToUUID(env, charId, charUUID), + ChipLogError(Controller, "handleUnsubscribeComplete() called with invalid characteristic ID")); sBleLayer.HandleUnsubscribeComplete(connObj, &svcUUID, &charUUID); -exit: - return; } JNI_ANDROID_CHIP_STACK_METHOD(void, handleConnectionError)(JNIEnv * env, jobject self, jint conn) @@ -1109,17 +1103,14 @@ void ThrowError(JNIEnv * env, CHIP_ERROR errToThrow) CHIP_ERROR N2J_ByteArray(JNIEnv * env, const uint8_t * inArray, uint32_t inArrayLen, jbyteArray & outArray) { - CHIP_ERROR err = CHIP_NO_ERROR; - outArray = env->NewByteArray((int) inArrayLen); - VerifyOrExit(outArray != NULL, err = CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(outArray != NULL, CHIP_ERROR_NO_MEMORY); env->ExceptionClear(); env->SetByteArrayRegion(outArray, 0, inArrayLen, (jbyte *) inArray); - VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); + VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR N2J_Error(JNIEnv * env, CHIP_ERROR inErr, jthrowable & outEx) diff --git a/src/controller/python/ChipDeviceController-ScriptBinding.cpp b/src/controller/python/ChipDeviceController-ScriptBinding.cpp index 3e6d0cdb1b8425..99b5dbd2d6c4b0 100644 --- a/src/controller/python/ChipDeviceController-ScriptBinding.cpp +++ b/src/controller/python/ChipDeviceController-ScriptBinding.cpp @@ -134,11 +134,8 @@ CHIP_ERROR pychip_BLEMgrImpl_ConfigureBle(uint32_t bluetoothAdapterId); CHIP_ERROR pychip_DeviceController_NewDeviceController(chip::Controller::DeviceCommissioner ** outDevCtrl, chip::NodeId localDeviceId) { - CHIP_ERROR err = CHIP_NO_ERROR; - CommissionerInitParams initParams; - *outDevCtrl = new chip::Controller::DeviceCommissioner(); - VerifyOrExit(*outDevCtrl != NULL, err = CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(*outDevCtrl != NULL, CHIP_ERROR_NO_MEMORY); if (localDeviceId == chip::kUndefinedNodeId) { @@ -147,17 +144,17 @@ CHIP_ERROR pychip_DeviceController_NewDeviceController(chip::Controller::DeviceC ReturnErrorOnFailure(sOperationalCredentialsIssuer.Initialize(sStorageDelegate)); + CommissionerInitParams initParams; initParams.storageDelegate = &sStorageDelegate; initParams.mDeviceAddressUpdateDelegate = &sDeviceAddressUpdateDelegate; initParams.pairingDelegate = &sPairingDelegate; initParams.operationalCredentialsDelegate = &sOperationalCredentialsIssuer; initParams.imDelegate = &PythonInteractionModelDelegate::Instance(); - SuccessOrExit(err = (*outDevCtrl)->Init(localDeviceId, initParams)); - SuccessOrExit(err = (*outDevCtrl)->ServiceEvents()); + ReturnErrorOnFailure((*outDevCtrl)->Init(localDeviceId, initParams)); + ReturnErrorOnFailure((*outDevCtrl)->ServiceEvents()); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR pychip_DeviceController_DeleteDeviceController(chip::Controller::DeviceCommissioner * devCtrl) diff --git a/src/crypto/CHIPCryptoPAL.cpp b/src/crypto/CHIPCryptoPAL.cpp index dcc0ca34e12af6..32e63c30b07954 100644 --- a/src/crypto/CHIPCryptoPAL.cpp +++ b/src/crypto/CHIPCryptoPAL.cpp @@ -35,8 +35,7 @@ using HKDF_sha_crypto = HKDF_sha; CHIP_ERROR Spake2p::InternalHash(const uint8_t * in, size_t in_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - uint64_t u64_len = in_len; + const uint64_t u64_len = in_len; uint8_t lb[8]; lb[0] = static_cast((u64_len >> 0) & 0xff); @@ -48,17 +47,15 @@ CHIP_ERROR Spake2p::InternalHash(const uint8_t * in, size_t in_len) lb[6] = static_cast((u64_len >> 48) & 0xff); lb[7] = static_cast((u64_len >> 56) & 0xff); - error = Hash(lb, sizeof(lb)); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = Hash(lb, sizeof(lb)); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); if (in != nullptr) { error = Hash(in, in_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); } - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } Spake2p::Spake2p(size_t _fe_size, size_t _point_size, size_t _hash_size) @@ -90,39 +87,32 @@ Spake2p::Spake2p(size_t _fe_size, size_t _point_size, size_t _hash_size) CHIP_ERROR Spake2p::Init(const uint8_t * context, size_t context_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - state = CHIP_SPAKE2P_STATE::PREINIT; + state = CHIP_SPAKE2P_STATE::PREINIT; - error = InitImpl(); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = InitImpl(); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = PointLoad(spake2p_M_p256, sizeof(spake2p_M_p256), M); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = PointLoad(spake2p_N_p256, sizeof(spake2p_N_p256), N); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = InternalHash(context, context_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); state = CHIP_SPAKE2P_STATE::INIT; - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p::WriteMN() { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - - error = InternalHash(spake2p_M_p256, sizeof(spake2p_M_p256)); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = InternalHash(spake2p_M_p256, sizeof(spake2p_M_p256)); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = InternalHash(spake2p_N_p256, sizeof(spake2p_N_p256)); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p::BeginVerifier(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, @@ -130,27 +120,25 @@ CHIP_ERROR Spake2p::BeginVerifier(const uint8_t * my_identity, size_t my_identit size_t Lin_len) { CHIP_ERROR error = CHIP_ERROR_INTERNAL; - VerifyOrExit(state == CHIP_SPAKE2P_STATE::INIT, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::INIT, CHIP_ERROR_INTERNAL); error = InternalHash(peer_identity, peer_identity_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = InternalHash(my_identity, my_identity_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = WriteMN(); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = FELoad(w0in, w0in_len, w0); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = PointLoad(Lin, Lin_len, L); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); state = CHIP_SPAKE2P_STATE::STARTED; role = CHIP_SPAKE2P_ROLE::VERIFIER; - error = CHIP_NO_ERROR; -exit: return error; } @@ -158,31 +146,26 @@ CHIP_ERROR Spake2p::BeginProver(const uint8_t * my_identity, size_t my_identity_ size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, size_t w1in_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - VerifyOrExit(state == CHIP_SPAKE2P_STATE::INIT, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::INIT, CHIP_ERROR_INTERNAL); - error = InternalHash(my_identity, my_identity_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = InternalHash(my_identity, my_identity_len); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = InternalHash(peer_identity, peer_identity_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = WriteMN(); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = FELoad(w0in, w0in_len, w0); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = FELoad(w1in, w1in_len, w1); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); - - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); state = CHIP_SPAKE2P_STATE::STARTED; role = CHIP_SPAKE2P_ROLE::PROVER; - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p::ComputeRoundOne(const uint8_t * pab, size_t pab_len, uint8_t * out, size_t * out_len) @@ -331,28 +314,24 @@ CHIP_ERROR Spake2p::ComputeRoundTwo(const uint8_t * in, size_t in_len, uint8_t * CHIP_ERROR Spake2p::GenerateKeys() { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; static const uint8_t info_keyconfirm[16] = { 'C', 'o', 'n', 'f', 'i', 'r', 'm', 'a', 't', 'i', 'o', 'n', 'K', 'e', 'y', 's' }; - error = HashFinalize(Kae); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = HashFinalize(Kae); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = KDF(Ka, hash_size / 2, nullptr, 0, info_keyconfirm, sizeof(info_keyconfirm), Kcab, hash_size); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p::KeyConfirm(const uint8_t * in, size_t in_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; uint8_t point_buffer[kP256_Point_Length]; void * XY = nullptr; // Choose X if a prover, Y if a verifier uint8_t * Kcaorb = nullptr; // Choose Kcb if a prover, Kca if a verifier - VerifyOrExit(state == CHIP_SPAKE2P_STATE::R2, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::R2, CHIP_ERROR_INTERNAL); if (role == CHIP_SPAKE2P_ROLE::PROVER) { @@ -364,19 +343,17 @@ CHIP_ERROR Spake2p::KeyConfirm(const uint8_t * in, size_t in_len) XY = Y; Kcaorb = Kca; } - VerifyOrExit(XY != nullptr, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(Kcaorb != nullptr, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(XY != nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(Kcaorb != nullptr, CHIP_ERROR_INTERNAL); - error = PointWrite(XY, point_buffer, point_size); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = PointWrite(XY, point_buffer, point_size); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = MacVerify(Kcaorb, hash_size / 2, in, in_len, point_buffer, point_size); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); state = CHIP_SPAKE2P_STATE::KC; - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p::GetKeys(uint8_t * out, size_t * out_len) @@ -395,56 +372,41 @@ CHIP_ERROR Spake2p::GetKeys(uint8_t * out, size_t * out_len) CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::InitImpl() { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - - error = sha256_hash_ctx.Begin(); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = sha256_hash_ctx.Begin(); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = InitInternal(); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::Hash(const uint8_t * in, size_t in_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - - error = sha256_hash_ctx.AddData(in, in_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = sha256_hash_ctx.AddData(in, in_len); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::HashFinalize(uint8_t * out) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; + CHIP_ERROR error = sha256_hash_ctx.Finish(out); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - error = sha256_hash_ctx.Finish(out); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); - - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::KDF(const uint8_t * ikm, const size_t ikm_len, const uint8_t * salt, const size_t salt_len, const uint8_t * info, const size_t info_len, uint8_t * out, size_t out_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; HKDF_sha_crypto mHKDF; - error = mHKDF.HKDF_SHA256(ikm, ikm_len, salt, salt_len, info, info_len, out, out_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + CHIP_ERROR error = mHKDF.HKDF_SHA256(ikm, ikm_len, salt, salt_len, info, info_len, out, out_len); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } } // namespace Crypto diff --git a/src/crypto/CHIPCryptoPAL.h b/src/crypto/CHIPCryptoPAL.h index 6a16249bde97be..9ae103abf832c3 100644 --- a/src/crypto/CHIPCryptoPAL.h +++ b/src/crypto/CHIPCryptoPAL.h @@ -37,36 +37,36 @@ namespace chip { namespace Crypto { -const size_t kMax_x509_Certificate_Length = 600; +constexpr size_t kMax_x509_Certificate_Length = 600; // TODO: Consider renaming these values to be closer to definisions in the spec: // CHIP_CRYPTO_GROUP_SIZE_BYTES // CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES -const size_t kP256_FE_Length = 32; -const size_t kP256_ECDSA_Signature_Length_Raw = (2 * kP256_FE_Length); -const size_t kP256_Point_Length = (2 * kP256_FE_Length + 1); -const size_t kSHA256_Hash_Length = 32; +constexpr size_t kP256_FE_Length = 32; +constexpr size_t kP256_ECDSA_Signature_Length_Raw = (2 * kP256_FE_Length); +constexpr size_t kP256_Point_Length = (2 * kP256_FE_Length + 1); +constexpr size_t kSHA256_Hash_Length = 32; -const size_t kMax_ECDH_Secret_Length = kP256_FE_Length; -const size_t kMax_ECDSA_Signature_Length = 72; -const size_t kMAX_FE_Length = kP256_FE_Length; -const size_t kMAX_Point_Length = kP256_Point_Length; -const size_t kMAX_Hash_Length = kSHA256_Hash_Length; -const size_t kMAX_CSR_Length = 512; +constexpr size_t kMax_ECDH_Secret_Length = kP256_FE_Length; +constexpr size_t kMax_ECDSA_Signature_Length = 72; +constexpr size_t kMAX_FE_Length = kP256_FE_Length; +constexpr size_t kMAX_Point_Length = kP256_Point_Length; +constexpr size_t kMAX_Hash_Length = kSHA256_Hash_Length; +constexpr size_t kMAX_CSR_Length = 512; -const size_t kMin_Salt_Length = 8; -const size_t kMax_Salt_Length = 16; +constexpr size_t kMin_Salt_Length = 8; +constexpr size_t kMax_Salt_Length = 16; -const size_t kP256_PrivateKey_Length = 32; -const size_t kP256_PublicKey_Length = 65; +constexpr size_t kP256_PrivateKey_Length = 32; +constexpr size_t kP256_PublicKey_Length = 65; /* These sizes are hardcoded here to remove header dependency on underlying crypto library * in a public interface file. The validity of these sizes is verified by static_assert in * the implementation files. */ -const size_t kMAX_Spake2p_Context_Size = 1024; -const size_t kMAX_Hash_SHA256_Context_Size = 296; -const size_t kMAX_P256Keypair_Context_Size = 512; +constexpr size_t kMAX_Spake2p_Context_Size = 1024; +constexpr size_t kMAX_Hash_SHA256_Context_Size = 296; +constexpr size_t kMAX_P256Keypair_Context_Size = 512; /** * Spake2+ parameters for P256 @@ -141,11 +141,9 @@ class CapacityBoundBuffer **/ CHIP_ERROR SetLength(size_t len) { - CHIP_ERROR error = CHIP_NO_ERROR; - VerifyOrExit(len <= sizeof(bytes), error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(len <= sizeof(bytes), CHIP_ERROR_INVALID_ARGUMENT); length = len; - exit: - return error; + return CHIP_NO_ERROR; } /** @brief Returns current length of the buffer that's being used diff --git a/src/crypto/CHIPCryptoPALOpenSSL.cpp b/src/crypto/CHIPCryptoPALOpenSSL.cpp index dd7a2e9ddd844a..cbd14363e492bc 100644 --- a/src/crypto/CHIPCryptoPALOpenSSL.cpp +++ b/src/crypto/CHIPCryptoPALOpenSSL.cpp @@ -285,16 +285,13 @@ CHIP_ERROR AES_CCM_decrypt(const uint8_t * ciphertext, size_t ciphertext_length, CHIP_ERROR Hash_SHA256(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) { - CHIP_ERROR error = CHIP_NO_ERROR; - // zero data length hash is supported. - VerifyOrExit(out_buffer != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); SHA256(data, data_length, Uint8::to_uchar(out_buffer)); -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA1(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) @@ -318,44 +315,32 @@ static inline SHA256_CTX * to_inner_hash_sha256_context(HashSHA256OpaqueContext CHIP_ERROR Hash_SHA256_stream::Begin() { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 1; + SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); - SHA256_CTX * context = to_inner_hash_sha256_context(&mContext); - - result = SHA256_Init(context); - VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL); + const int result = SHA256_Init(context); + VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::AddData(const uint8_t * data, const size_t data_length) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 1; + SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); - SHA256_CTX * context = to_inner_hash_sha256_context(&mContext); - - result = SHA256_Update(context, Uint8::to_const_uchar(data), data_length); - VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL); + const int result = SHA256_Update(context, Uint8::to_const_uchar(data), data_length); + VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::Finish(uint8_t * out_buffer) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 1; - - SHA256_CTX * context = to_inner_hash_sha256_context(&mContext); + SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); - result = SHA256_Final(Uint8::to_uchar(out_buffer), context); - VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL); + const int result = SHA256_Final(Uint8::to_uchar(out_buffer), context); + VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } void Hash_SHA256_stream::Clear() @@ -366,11 +351,10 @@ void Hash_SHA256_stream::Clear() CHIP_ERROR HKDF_sha::HKDF_SHA256(const uint8_t * secret, const size_t secret_length, const uint8_t * salt, const size_t salt_length, const uint8_t * info, const size_t info_length, uint8_t * out_buffer, size_t out_length) { - EVP_PKEY_CTX * context; CHIP_ERROR error = CHIP_NO_ERROR; int result = 1; - context = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr); + EVP_PKEY_CTX * const context = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr); VerifyOrExit(context != nullptr, error = CHIP_ERROR_INTERNAL); VerifyOrExit(secret != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); @@ -467,18 +451,14 @@ CHIP_ERROR add_entropy_source(entropy_source fn_source, void * p_source, size_t CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, const size_t out_length) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - VerifyOrExit(out_buffer != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(CanCastTo(out_length), error = CHIP_ERROR_INVALID_ARGUMENT); - result = RAND_priv_bytes(Uint8::to_uchar(out_buffer), static_cast(out_length)); - VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(CanCastTo(out_length), CHIP_ERROR_INVALID_ARGUMENT); + const int result = RAND_priv_bytes(Uint8::to_uchar(out_buffer), static_cast(out_length)); + VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } ECName MapECName(SupportedECPKeyTypes keyType) @@ -1198,14 +1178,14 @@ CHIP_ERROR VerifyCertificateSigningRequest(const uint8_t * csr, size_t csr_lengt do \ { \ _point_ = EC_POINT_new(context->curve); \ - VerifyOrExit(_point_ != nullptr, error = CHIP_ERROR_INTERNAL); \ + VerifyOrReturnError(_point_ != nullptr, CHIP_ERROR_INTERNAL); \ } while (0) #define init_bn(_bn_) \ do \ { \ _bn_ = BN_new(); \ - VerifyOrExit(_bn_ != nullptr, error = CHIP_ERROR_INTERNAL); \ + VerifyOrReturnError(_bn_ != nullptr, CHIP_ERROR_INTERNAL); \ } while (0) #define free_point(_point_) \ @@ -1240,26 +1220,23 @@ static inline Spake2p_Context * to_inner_spake2p_context(Spake2pOpaqueContext * CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::InitInternal() { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int error_openssl = 0; - - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); + Spake2p_Context * const context = to_inner_spake2p_context(&mSpake2pContext); context->curve = nullptr; context->bn_ctx = nullptr; context->md_info = nullptr; context->curve = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1); - VerifyOrExit(context->curve != nullptr, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(context->curve != nullptr, CHIP_ERROR_INTERNAL); G = EC_GROUP_get0_generator(context->curve); - VerifyOrExit(G != nullptr, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(G != nullptr, CHIP_ERROR_INTERNAL); context->bn_ctx = BN_CTX_secure_new(); - VerifyOrExit(context->bn_ctx != nullptr, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(context->bn_ctx != nullptr, CHIP_ERROR_INTERNAL); context->md_info = EVP_sha256(); - VerifyOrExit(context->md_info != nullptr, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(context->md_info != nullptr, CHIP_ERROR_INTERNAL); init_point(M); init_point(N); @@ -1274,17 +1251,15 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::InitInternal() init_bn(tempbn); init_bn(order); - error_openssl = EC_GROUP_get_order(context->curve, static_cast(order), context->bn_ctx); - VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); + const int error_openssl = EC_GROUP_get_order(context->curve, static_cast(order), context->bn_ctx); + VerifyOrReturnError(error_openssl == 1, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } void Spake2p_P256_SHA256_HKDF_HMAC::FreeImpl() { - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); + Spake2p_Context * const context = to_inner_spake2p_context(&mSpake2pContext); if (context->curve != nullptr) { @@ -1342,125 +1317,90 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::Mac(const uint8_t * key, size_t key_le CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::MacVerify(const uint8_t * key, size_t key_len, const uint8_t * mac, size_t mac_len, const uint8_t * in, size_t in_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - VerifyOrExit(mac_len == kSHA256_Hash_Length, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mac_len == kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); uint8_t computed_mac[kSHA256_Hash_Length]; - error = Mac(key, key_len, in, in_len, computed_mac); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + const CHIP_ERROR error = Mac(key, key_len, in, in_len, computed_mac); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - VerifyOrExit(CRYPTO_memcmp(mac, computed_mac, mac_len) == 0, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(CRYPTO_memcmp(mac, computed_mac, mac_len) == 0, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FELoad(const uint8_t * in, size_t in_len, void * fe) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int error_openssl = 0; - BIGNUM * bn_fe = static_cast(fe); + BIGNUM * const bn_fe = static_cast(fe); Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - VerifyOrExit(CanCastTo(in_len), error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(CanCastTo(in_len), CHIP_ERROR_INTERNAL); BN_bin2bn(Uint8::to_const_uchar(in), static_cast(in_len), bn_fe); - error_openssl = BN_mod(bn_fe, bn_fe, (BIGNUM *) order, context->bn_ctx); - VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); + const int error_openssl = BN_mod(bn_fe, bn_fe, (BIGNUM *) order, context->bn_ctx); + VerifyOrReturnError(error_openssl == 1, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEWrite(const void * fe, uint8_t * out, size_t out_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int bn_out_len; - VerifyOrExit(CanCastTo(out_len), error = CHIP_ERROR_INTERNAL); - bn_out_len = BN_bn2binpad(static_cast(fe), Uint8::to_uchar(out), static_cast(out_len)); + VerifyOrReturnError(CanCastTo(out_len), CHIP_ERROR_INTERNAL); + const int bn_out_len = BN_bn2binpad(static_cast(fe), Uint8::to_uchar(out), static_cast(out_len)); + VerifyOrReturnError(bn_out_len == static_cast(out_len), CHIP_ERROR_INTERNAL); - VerifyOrExit(bn_out_len == static_cast(out_len), error = CHIP_ERROR_INTERNAL); - - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEGenerate(void * fe) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int error_openssl = 0; + const int error_openssl = BN_rand_range(static_cast(fe), static_cast(order)); + VerifyOrReturnError(error_openssl == 1, CHIP_ERROR_INTERNAL); - error_openssl = BN_rand_range(static_cast(fe), static_cast(order)); - VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); - - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEMul(void * fer, const void * fe1, const void * fe2) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int error_openssl = 0; + const Spake2p_Context * const context = to_inner_spake2p_context(&mSpake2pContext); - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); + const int error_openssl = BN_mod_mul(static_cast(fer), static_cast(fe1), + static_cast(fe2), static_cast(order), context->bn_ctx); + VerifyOrReturnError(error_openssl == 1, CHIP_ERROR_INTERNAL); - error_openssl = BN_mod_mul(static_cast(fer), static_cast(fe1), static_cast(fe2), - static_cast(order), context->bn_ctx); - VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); - - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointLoad(const uint8_t * in, size_t in_len, void * R) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int error_openssl = 0; + const Spake2p_Context * const context = to_inner_spake2p_context(&mSpake2pContext); - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); - - error_openssl = + const int error_openssl = EC_POINT_oct2point(context->curve, static_cast(R), Uint8::to_const_uchar(in), in_len, context->bn_ctx); - VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error_openssl == 1, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointWrite(const void * R, uint8_t * out, size_t out_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); + const Spake2p_Context * const context = to_inner_spake2p_context(&mSpake2pContext); - size_t ec_out_len = EC_POINT_point2oct(context->curve, static_cast(R), POINT_CONVERSION_UNCOMPRESSED, - Uint8::to_uchar(out), out_len, context->bn_ctx); - VerifyOrExit(ec_out_len == out_len, error = CHIP_ERROR_INTERNAL); + const size_t ec_out_len = EC_POINT_point2oct(context->curve, static_cast(R), POINT_CONVERSION_UNCOMPRESSED, + Uint8::to_uchar(out), out_len, context->bn_ctx); + VerifyOrReturnError(ec_out_len == out_len, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointMul(void * R, const void * P1, const void * fe1) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int error_openssl = 0; + const Spake2p_Context * const context = to_inner_spake2p_context(&mSpake2pContext); - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); + const int error_openssl = EC_POINT_mul(context->curve, static_cast(R), nullptr, static_cast(P1), + static_cast(fe1), context->bn_ctx); + VerifyOrReturnError(error_openssl == 1, CHIP_ERROR_INTERNAL); - error_openssl = EC_POINT_mul(context->curve, static_cast(R), nullptr, static_cast(P1), - static_cast(fe1), context->bn_ctx); - VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); - - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointAddMul(void * R, const void * P1, const void * fe1, const void * P2, @@ -1493,17 +1433,12 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointAddMul(void * R, const void * P1, CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointInvert(void * R) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int error_openssl = 0; - - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); + const Spake2p_Context * const context = to_inner_spake2p_context(&mSpake2pContext); - error_openssl = EC_POINT_invert(context->curve, static_cast(R), context->bn_ctx); - VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); + const int error_openssl = EC_POINT_invert(context->curve, static_cast(R), context->bn_ctx); + VerifyOrReturnError(error_openssl == 1, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) @@ -1549,17 +1484,12 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointIsValid(void * R) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - int error_openssl = 0; + const Spake2p_Context * const context = to_inner_spake2p_context(&mSpake2pContext); - Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); + const int error_openssl = EC_POINT_is_on_curve(context->curve, static_cast(R), context->bn_ctx); + VerifyOrReturnError(error_openssl == 1, CHIP_ERROR_INTERNAL); - error_openssl = EC_POINT_is_on_curve(context->curve, static_cast(R), context->bn_ctx); - VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); - - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } static void security_free_cert_list(X509_LIST * certs) diff --git a/src/crypto/CHIPCryptoPALmbedTLS.cpp b/src/crypto/CHIPCryptoPALmbedTLS.cpp index 954dae3d7c6eb1..d4fdb23ad14848 100644 --- a/src/crypto/CHIPCryptoPALmbedTLS.cpp +++ b/src/crypto/CHIPCryptoPALmbedTLS.cpp @@ -181,28 +181,22 @@ CHIP_ERROR AES_CCM_decrypt(const uint8_t * ciphertext, size_t ciphertext_len, co CHIP_ERROR Hash_SHA256(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - // zero data length hash is supported. - VerifyOrExit(out_buffer != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - result = mbedtls_sha256_ret(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer), 0); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + const int result = mbedtls_sha256_ret(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer), 0); + VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA1(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) { - int result = 0; - // zero data length hash is supported. VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - result = mbedtls_sha1_ret(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer)); + const int result = mbedtls_sha1_ret(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer)); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; @@ -219,44 +213,32 @@ static inline mbedtls_sha256_context * to_inner_hash_sha256_context(HashSHA256Op CHIP_ERROR Hash_SHA256_stream::Begin(void) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); + mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); - result = mbedtls_sha256_starts_ret(context, 0); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + const int result = mbedtls_sha256_starts_ret(context, 0); + VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::AddData(const uint8_t * data, const size_t data_length) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); + mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); - result = mbedtls_sha256_update_ret(context, Uint8::to_const_uchar(data), data_length); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + const int result = mbedtls_sha256_update_ret(context, Uint8::to_const_uchar(data), data_length); + VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::Finish(uint8_t * out_buffer) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); + mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); - result = mbedtls_sha256_finish_ret(context, Uint8::to_uchar(out_buffer)); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + const int result = mbedtls_sha256_finish_ret(context, Uint8::to_uchar(out_buffer)); + VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } void Hash_SHA256_stream::Clear(void) @@ -267,34 +249,29 @@ void Hash_SHA256_stream::Clear(void) CHIP_ERROR HKDF_sha::HKDF_SHA256(const uint8_t * secret, const size_t secret_length, const uint8_t * salt, const size_t salt_length, const uint8_t * info, const size_t info_length, uint8_t * out_buffer, size_t out_length) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 1; - const mbedtls_md_info_t * md; - - VerifyOrExit(secret != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(secret_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(secret != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(secret_length > 0, CHIP_ERROR_INVALID_ARGUMENT); // Salt is optional if (salt_length > 0) { - VerifyOrExit(salt != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(salt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } - VerifyOrExit(info_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(info != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_buffer != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(info_length > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(info != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - md = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); - VerifyOrExit(md != nullptr, error = CHIP_ERROR_INTERNAL); + const mbedtls_md_info_t * const md = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); + VerifyOrReturnError(md != nullptr, CHIP_ERROR_INTERNAL); - result = mbedtls_hkdf(md, Uint8::to_const_uchar(salt), salt_length, Uint8::to_const_uchar(secret), secret_length, - Uint8::to_const_uchar(info), info_length, Uint8::to_uchar(out_buffer), out_length); + const int result = mbedtls_hkdf(md, Uint8::to_const_uchar(salt), salt_length, Uint8::to_const_uchar(secret), secret_length, + Uint8::to_const_uchar(info), info_length, Uint8::to_uchar(out_buffer), out_length); _log_mbedTLS_error(result); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR PBKDF2_sha256::pbkdf2_sha256(const uint8_t * password, size_t plen, const uint8_t * salt, size_t slen, @@ -356,59 +333,50 @@ static EntropyContext * get_entropy_context() static mbedtls_ctr_drbg_context * get_drbg_context() { - EntropyContext * context = get_entropy_context(); + EntropyContext * const context = get_entropy_context(); - mbedtls_ctr_drbg_context * drbgCtxt = &context->mDRBGCtxt; + mbedtls_ctr_drbg_context * const drbgCtxt = &context->mDRBGCtxt; if (!context->mDRBGSeeded) { - int status = mbedtls_ctr_drbg_seed(drbgCtxt, mbedtls_entropy_func, &context->mEntropy, nullptr, 0); - VerifyOrExit(status == 0, _log_mbedTLS_error(status)); + const int status = mbedtls_ctr_drbg_seed(drbgCtxt, mbedtls_entropy_func, &context->mEntropy, nullptr, 0); + if (status != 0) + { + _log_mbedTLS_error(status); + return nullptr; + } context->mDRBGSeeded = true; } return drbgCtxt; - -exit: - return nullptr; } CHIP_ERROR add_entropy_source(entropy_source fn_source, void * p_source, size_t threshold) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - EntropyContext * entropy_ctxt = nullptr; - - VerifyOrExit(fn_source != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(fn_source != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - entropy_ctxt = get_entropy_context(); - VerifyOrExit(entropy_ctxt != nullptr, error = CHIP_ERROR_INTERNAL); + EntropyContext * const entropy_ctxt = get_entropy_context(); + VerifyOrReturnError(entropy_ctxt != nullptr, CHIP_ERROR_INTERNAL); - result = mbedtls_entropy_add_source(&entropy_ctxt->mEntropy, fn_source, p_source, threshold, MBEDTLS_ENTROPY_SOURCE_STRONG); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); -exit: - return error; + const int result = + mbedtls_entropy_add_source(&entropy_ctxt->mEntropy, fn_source, p_source, threshold, MBEDTLS_ENTROPY_SOURCE_STRONG); + VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); + return CHIP_NO_ERROR; } CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, const size_t out_length) { - CHIP_ERROR error = CHIP_NO_ERROR; - int result = 0; - - mbedtls_ctr_drbg_context * drbg_ctxt = nullptr; - - VerifyOrExit(out_buffer != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); - drbg_ctxt = get_drbg_context(); - VerifyOrExit(drbg_ctxt != nullptr, error = CHIP_ERROR_INTERNAL); + mbedtls_ctr_drbg_context * const drbg_ctxt = get_drbg_context(); + VerifyOrReturnError(drbg_ctxt != nullptr, CHIP_ERROR_INTERNAL); - result = mbedtls_ctr_drbg_random(drbg_ctxt, Uint8::to_uchar(out_buffer), out_length); - VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + const int result = mbedtls_ctr_drbg_random(drbg_ctxt, Uint8::to_uchar(out_buffer), out_length); + VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } static int CryptoRNG(void * ctxt, uint8_t * out_buffer, size_t out_length) diff --git a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_HKDF.cpp b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_HKDF.cpp index baac68e4f29634..b49a7a2833d0f5 100644 --- a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_HKDF.cpp +++ b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_HKDF.cpp @@ -40,11 +40,6 @@ CHIP_ERROR HKDF_shaHSM::HKDF_SHA256(const uint8_t * secret, const size_t secret_ const size_t salt_length, const uint8_t * info, const size_t info_length, uint8_t * out_buffer, size_t out_length) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - sss_status_t status = kStatus_SSS_Success; - smStatus_t smstatus = SM_NOT_OK; - sss_object_t keyObject = { 0 }; - if (salt_length > 64 || info_length > 80 || secret_length > 256 || out_length > 768) { /* Length not supported by se05x. Rollback to SW */ @@ -54,41 +49,40 @@ CHIP_ERROR HKDF_shaHSM::HKDF_SHA256(const uint8_t * secret, const size_t secret_ // Salt is optional if (salt_length > 0) { - VerifyOrExit(salt != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(salt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } - VerifyOrExit(info_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(info != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_buffer != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(secret != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(info_length > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(info != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(secret != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(keyid != kKeyId_NotInitialized, error = CHIP_ERROR_HSM); + VerifyOrReturnError(keyid != kKeyId_NotInitialized, CHIP_ERROR_HSM); se05x_sessionOpen(); - status = sss_key_object_init(&keyObject, &gex_sss_chip_ctx.ks); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + sss_object_t keyObject = { 0 }; + sss_status_t status = sss_key_object_init(&keyObject, &gex_sss_chip_ctx.ks); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); status = sss_key_object_allocate_handle(&keyObject, keyid, kSSS_KeyPart_Default, kSSS_CipherType_HMAC, secret_length, kKeyObject_Mode_Transient); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); status = sss_key_store_set_key(&gex_sss_chip_ctx.ks, &keyObject, secret, secret_length, secret_length * 8, NULL, 0); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); - VerifyOrExit(gex_sss_chip_ctx.ks.session != NULL, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(gex_sss_chip_ctx.ks.session != NULL, CHIP_ERROR_INTERNAL); - smstatus = Se05x_API_HKDF_Extended(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, keyObject.keyId, - kSE05x_DigestMode_SHA256, kSE05x_HkdfMode_ExtractExpand, salt, salt_length, 0, info, - info_length, 0, (uint16_t) out_length, out_buffer, &out_length); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + const smStatus_t smstatus = Se05x_API_HKDF_Extended( + &((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, keyObject.keyId, kSE05x_DigestMode_SHA256, + kSE05x_HkdfMode_ExtractExpand, salt, salt_length, 0, info, info_length, 0, (uint16_t) out_length, out_buffer, &out_length); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); status = sss_key_store_erase_key(&gex_sss_chip_ctx.ks, &keyObject); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } } // namespace Crypto diff --git a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp index 71960d9bd4de7b..1d9209fb7951ad 100644 --- a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp +++ b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_P256.cpp @@ -51,37 +51,35 @@ P256KeypairHSM::~P256KeypairHSM() CHIP_ERROR P256KeypairHSM::Initialize() { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - sss_status_t status = kStatus_SSS_Success; sss_object_t keyObject = { 0 }; uint8_t pubkey[128] = { 0, }; - size_t pubKeyLen = sizeof(pubkey); - size_t pbKeyBitLen = sizeof(pubkey) * 8; + constexpr size_t pubKeyLen = sizeof(pubkey); + constexpr size_t pbKeyBitLen = sizeof(pubkey) * 8; if (keyid == 0) { ChipLogDetail(Crypto, "Keyid not set !. Set key id using 'SetKeyId' member class !"); - ExitNow(); + return CHIP_ERROR_INTERNAL; } se05x_sessionOpen(); - status = sss_key_object_init(&keyObject, &gex_sss_chip_ctx.ks); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + sss_status_t status = sss_key_object_init(&keyObject, &gex_sss_chip_ctx.ks); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); if (provisioned_key == false) { status = sss_key_object_allocate_handle(&keyObject, keyid, kSSS_KeyPart_Pair, kSSS_CipherType_EC_NIST_P, 256, kKeyObject_Mode_Transient); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); ChipLogDetail(Crypto, "Creating Nist256 key on SE05X !"); status = sss_key_store_generate_key(&gex_sss_chip_ctx.ks, &keyObject, 256, 0); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); } else { @@ -91,24 +89,22 @@ CHIP_ERROR P256KeypairHSM::Initialize() ChipLogDetail(Crypto, "Provisioned key ! Not creating key in HSM"); status = sss_key_object_get_handle(&keyObject, keyid); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); } status = sss_key_store_get_key(&gex_sss_chip_ctx.ks, &keyObject, pubkey, &pubKeyLen, &pbKeyBitLen); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); { /* Set the public key */ P256PublicKeyHSM & public_key = const_cast(Pubkey()); - VerifyOrExit(pubKeyLen > NIST256_HEADER_OFFSET, error = CHIP_ERROR_INTERNAL); - VerifyOrExit((pubKeyLen - NIST256_HEADER_OFFSET) <= kP256_PublicKey_Length, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(pubKeyLen > NIST256_HEADER_OFFSET, CHIP_ERROR_INTERNAL); + VerifyOrReturnError((pubKeyLen - NIST256_HEADER_OFFSET) <= kP256_PublicKey_Length, CHIP_ERROR_INTERNAL); memcpy((void *) Uint8::to_const_uchar(public_key), pubkey + NIST256_HEADER_OFFSET, pubKeyLen - NIST256_HEADER_OFFSET); public_key.SetPublicKeyId(keyid); } - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR P256KeypairHSM::ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, P256ECDSASignature & out_signature) @@ -233,8 +229,7 @@ CHIP_ERROR P256KeypairHSM::ECDSA_sign_hash(const uint8_t * hash, size_t hash_len CHIP_ERROR P256KeypairHSM::Serialize(P256SerializedKeypair & output) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - size_t len = output.Length() == 0 ? output.Capacity() : output.Length(); + const size_t len = output.Length() == 0 ? output.Capacity() : output.Length(); Encoding::BufferWriter bbuf(output, len); uint8_t privkey[kP256_PrivateKey_Length] = { 0, @@ -246,8 +241,8 @@ CHIP_ERROR P256KeypairHSM::Serialize(P256SerializedKeypair & output) bbuf.Put(Uint8::to_uchar(public_key), public_key.Length()); } - VerifyOrExit(bbuf.Available() == sizeof(privkey), error = CHIP_ERROR_INTERNAL); - VerifyOrExit(sizeof(privkey) >= 4, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(bbuf.Available() == sizeof(privkey), CHIP_ERROR_INTERNAL); + VerifyOrReturnError(sizeof(privkey) >= 4, CHIP_ERROR_INTERNAL); { /* When HSM is used for ECC key generation, store key info in private key buffer */ @@ -256,28 +251,24 @@ CHIP_ERROR P256KeypairHSM::Serialize(P256SerializedKeypair & output) } bbuf.Put(privkey, sizeof(privkey)); - VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bbuf.Fit(), CHIP_ERROR_BUFFER_TOO_SMALL); output.SetLength(bbuf.Needed()); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR P256KeypairHSM::Deserialize(P256SerializedKeypair & input) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - /* Set the public key */ P256PublicKeyHSM & public_key = const_cast(Pubkey()); Encoding::BufferWriter bbuf((uint8_t *) Uint8::to_const_uchar(public_key), public_key.Length()); - VerifyOrExit(input.Length() == public_key.Length() + kP256_PrivateKey_Length, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(input.Length() == public_key.Length() + kP256_PrivateKey_Length, CHIP_ERROR_INVALID_ARGUMENT); bbuf.Put(static_cast(input), public_key.Length()); /* Set private key info */ - VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(bbuf.Fit(), CHIP_ERROR_NO_MEMORY); { /* When HSM is used for ECC key generation, key info in stored in private key buffer */ const uint8_t * privkey = Uint8::to_const_uchar(input) + public_key.Length(); @@ -285,77 +276,62 @@ CHIP_ERROR P256KeypairHSM::Deserialize(P256SerializedKeypair & input) public_key.SetPublicKeyId(keyid); } - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR P256KeypairHSM::ECDH_derive_secret(const P256PublicKey & remote_public_key, P256ECDHDerivedSecret & out_secret) const { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - const uint8_t * rem_pubKey = nullptr; - size_t rem_pubKeyLen = 0; - size_t secret_length = (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(); - smStatus_t smstatus = SM_NOT_OK; + size_t secret_length = (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(); - VerifyOrExit(keyid != kKeyId_NotInitialized, error = CHIP_ERROR_HSM); + VerifyOrReturnError(keyid != kKeyId_NotInitialized, CHIP_ERROR_HSM); ChipLogDetail(Crypto, "ECDH_derive_secret: Using SE05X for ECDH !"); se05x_sessionOpen(); - rem_pubKey = Uint8::to_const_uchar(remote_public_key); - rem_pubKeyLen = remote_public_key.Length(); + const uint8_t * const rem_pubKey = Uint8::to_const_uchar(remote_public_key); + const size_t rem_pubKeyLen = remote_public_key.Length(); - VerifyOrExit(gex_sss_chip_ctx.ks.session != nullptr, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(gex_sss_chip_ctx.ks.session != nullptr, CHIP_ERROR_INTERNAL); - smstatus = Se05x_API_ECGenSharedSecret(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, keyid, rem_pubKey, - rem_pubKeyLen, Uint8::to_uchar(out_secret), &secret_length); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + const smStatus_t smstatus = Se05x_API_ECGenSharedSecret(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, keyid, + rem_pubKey, rem_pubKeyLen, Uint8::to_uchar(out_secret), &secret_length); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); - SuccessOrExit(out_secret.SetLength(secret_length)); - - error = CHIP_NO_ERROR; -exit: - return error; + return out_secret.SetLength(secret_length); } /* EC Public key HSM implementation */ CHIP_ERROR SE05X_Set_ECDSA_Public_Key(sss_object_t * keyObject, const uint8_t * key, size_t keylen) { - sss_status_t status = kStatus_SSS_Fail; uint8_t public_key[128] = { 0, }; - size_t public_key_len = 0; - CHIP_ERROR error = CHIP_ERROR_INTERNAL; /* ECC NIST-256 Public Key header */ const uint8_t nist256_header[] = { 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00 }; /* Set public key */ - status = sss_key_object_init(keyObject, &gex_sss_chip_ctx.ks); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + sss_status_t status = sss_key_object_init(keyObject, &gex_sss_chip_ctx.ks); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); status = sss_key_object_allocate_handle(keyObject, kKeyId_sha256_ecc_pub_keyid, kSSS_KeyPart_Public, kSSS_CipherType_EC_NIST_P, 256, kKeyObject_Mode_Transient); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); - VerifyOrExit((sizeof(nist256_header) + keylen) <= sizeof(public_key), error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError((sizeof(nist256_header) + keylen) <= sizeof(public_key), CHIP_ERROR_INTERNAL); memcpy(public_key, nist256_header, sizeof(nist256_header)); - public_key_len = public_key_len + sizeof(nist256_header); + size_t public_key_len = public_key_len + sizeof(nist256_header); memcpy(public_key + public_key_len, key, keylen); public_key_len = public_key_len + keylen; status = sss_key_store_set_key(&gex_sss_chip_ctx.ks, keyObject, public_key, public_key_len, 256, NULL, 0); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR P256PublicKeyHSM::ECDSA_validate_msg_signature(const uint8_t * msg, size_t msg_length, diff --git a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_PBKDF.cpp b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_PBKDF.cpp index ba416282bb10af..2f601a60b58311 100644 --- a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_PBKDF.cpp +++ b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_PBKDF.cpp @@ -39,48 +39,42 @@ PBKDF2_sha256HSM::~PBKDF2_sha256HSM() {} CHIP_ERROR PBKDF2_sha256HSM::pbkdf2_sha256(const uint8_t * password, size_t plen, const uint8_t * salt, size_t slen, unsigned int iteration_count, uint32_t key_length, uint8_t * output) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - smStatus_t smStatus = SM_NOT_OK; - sss_status_t status = kStatus_SSS_Fail; - sss_object_t hmacKeyObj = { - 0, - }; - - VerifyOrExit(password != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(plen > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(key_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(output != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(slen >= chip::Crypto::kMin_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(slen <= chip::Crypto::kMax_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(salt != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(password != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(plen > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(key_length > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(output != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(slen >= chip::Crypto::kMin_Salt_Length, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(slen <= chip::Crypto::kMax_Salt_Length, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(salt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(keyid != kKeyId_NotInitialized, error = CHIP_ERROR_HSM); + VerifyOrReturnError(keyid != kKeyId_NotInitialized, CHIP_ERROR_HSM); se05x_sessionOpen(); - status = sss_key_object_init(&hmacKeyObj, &gex_sss_chip_ctx.ks); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + sss_object_t hmacKeyObj = { + 0, + }; + sss_status_t status = sss_key_object_init(&hmacKeyObj, &gex_sss_chip_ctx.ks); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); status = sss_key_object_allocate_handle(&hmacKeyObj, keyid, kSSS_KeyPart_Default, kSSS_CipherType_HMAC, sizeof(password), kKeyObject_Mode_Transient); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); status = sss_key_store_set_key(&gex_sss_chip_ctx.ks, &hmacKeyObj, password, plen, plen * 8, NULL, 0); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); - - VerifyOrExit(gex_sss_chip_ctx.ks.session != NULL, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); - smStatus = Se05x_API_PBKDF2(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, keyid, kSE05x_Pbkdf2_HMAC_SHA256, salt, - slen, (uint16_t) iteration_count, (uint16_t) key_length, output, (size_t *) &key_length); + VerifyOrReturnError(gex_sss_chip_ctx.ks.session != NULL, CHIP_ERROR_INTERNAL); - VerifyOrExit(smStatus == SM_OK, error = CHIP_ERROR_INTERNAL); + const smStatus_t smStatus = + Se05x_API_PBKDF2(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, keyid, kSE05x_Pbkdf2_HMAC_SHA256, salt, slen, + (uint16_t) iteration_count, (uint16_t) key_length, output, (size_t *) &key_length); + VerifyOrReturnError(smStatus == SM_OK, CHIP_ERROR_INTERNAL); status = sss_key_store_erase_key(&gex_sss_chip_ctx.ks, &hmacKeyObj); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } } // namespace Crypto diff --git a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_Spake2p.cpp b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_Spake2p.cpp index 55f640fde826fb..fd09be13d387c3 100644 --- a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_Spake2p.cpp +++ b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_Spake2p.cpp @@ -91,23 +91,23 @@ CHIP_ERROR create_init_crypto_obj(chip::Crypto::CHIP_SPAKE2P_ROLE role, hsm_pake se05x_delete_key(m_id); error = se05x_set_key(m_id, chip::Crypto::spake2p_M_p256, sizeof(chip::Crypto::spake2p_M_p256), kSSS_KeyPart_Public, kSSS_CipherType_EC_NIST_P); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); se05x_delete_key(n_id); error = se05x_set_key(n_id, chip::Crypto::spake2p_N_p256, sizeof(chip::Crypto::spake2p_N_p256), kSSS_KeyPart_Public, kSSS_CipherType_EC_NIST_P); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); - VerifyOrExit(gex_sss_chip_ctx.ks.session != NULL, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(gex_sss_chip_ctx.ks.session != NULL, CHIP_ERROR_INTERNAL); subtype.spakeAlgo = kSE05x_SpakeAlgo_P256_SHA256_HKDF_HMAC; #if ENABLE_REENTRANCY - VerifyOrExit(spake_objects_created < LIMIT_CRYPTO_OBJECTS, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(spake_objects_created < LIMIT_CRYPTO_OBJECTS, CHIP_ERROR_INTERNAL); smstatus = Se05x_API_CreateCryptoObject(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, kSE05x_CryptoContext_SPAKE, subtype); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); /* Increment number of crypto objects created */ spake_objects_created++; @@ -127,24 +127,19 @@ CHIP_ERROR create_init_crypto_obj(chip::Crypto::CHIP_SPAKE2P_ROLE role, hsm_pake { smstatus = Se05x_API_CreateCryptoObject(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, kSE05x_CryptoContext_SPAKE, subtype); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); } #endif smstatus = Se05x_API_PAKEInitProtocol(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, m_id, n_id); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_ComputeRoundOne_HSM(hsm_pake_context_t * phsm_pake_context, chip::Crypto::CHIP_SPAKE2P_ROLE role, const uint8_t * pab, size_t pab_len, uint8_t * out, size_t * out_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - smStatus_t smstatus = SM_NOT_OK; - #if SSS_HAVE_SE05X_VER_GTE_16_03 #else uint8_t * prand = NULL; @@ -155,11 +150,11 @@ CHIP_ERROR Spake2p_ComputeRoundOne_HSM(hsm_pake_context_t * phsm_pake_context, c #endif SE05x_CryptoObjectID_t spakeObjectId = phsm_pake_context->spake_objId; - VerifyOrExit(out != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_len != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_len != nullptr, CHIP_ERROR_INVALID_ARGUMENT); if (pab_len > 0) { - VerifyOrExit(pab != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(pab != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } if (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER) @@ -178,10 +173,10 @@ CHIP_ERROR Spake2p_ComputeRoundOne_HSM(hsm_pake_context_t * phsm_pake_context, c sss_rng_context_t rng_ctx; status = sss_rng_context_init(&rng_ctx, &gex_sss_chip_ctx.session); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); status = sss_rng_get_random(&rng_ctx, tempBuf, sizeof(tempBuf)); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); sss_rng_context_free(&rng_ctx); @@ -190,71 +185,58 @@ CHIP_ERROR Spake2p_ComputeRoundOne_HSM(hsm_pake_context_t * phsm_pake_context, c #endif - VerifyOrExit(gex_sss_chip_ctx.ks.session != NULL, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(gex_sss_chip_ctx.ks.session != NULL, CHIP_ERROR_INTERNAL); #if SSS_HAVE_SE05X_VER_GTE_16_03 - smstatus = Se05x_API_PAKEComputeKeyShare(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, - (uint8_t *) pab, pab_len, out, out_len); + const smStatus_t smstatus = Se05x_API_PAKEComputeKeyShare(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, + spakeObjectId, (uint8_t *) pab, pab_len, out, out_len); #else - smstatus = Se05x_API_PAKEComputeKeyShare(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, - (uint8_t *) pab, pab_len, out, out_len, prand, prand_len); + const smStatus_t smstatus = + Se05x_API_PAKEComputeKeyShare(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, (uint8_t *) pab, + pab_len, out, out_len, prand, prand_len); #endif - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_ComputeRoundTwo_HSM(hsm_pake_context_t * phsm_pake_context, chip::Crypto::CHIP_SPAKE2P_ROLE role, const uint8_t * in, size_t in_len, uint8_t * out, size_t * out_len, uint8_t * pKeyKe, size_t * pkeyKeLen) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - smStatus_t smstatus = SM_NOT_OK; - const uint8_t * pab = NULL; - size_t pab_len = 0; - SE05x_CryptoObjectID_t spakeObjectId = phsm_pake_context->spake_objId; + VerifyOrReturnError(in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_len != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(pKeyKe != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(pkeyKeLen != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(in != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(out_len != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(pKeyKe != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(pkeyKeLen != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + const uint8_t * const pab = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER) ? NULL : in; + const size_t pab_len = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER) ? 0 : in_len; - pab = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER) ? NULL : in; - pab_len = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER) ? 0 : in_len; + VerifyOrReturnError(gex_sss_chip_ctx.ks.session != NULL, CHIP_ERROR_INTERNAL); - VerifyOrExit(gex_sss_chip_ctx.ks.session != NULL, error = CHIP_ERROR_INTERNAL); + const SE05x_CryptoObjectID_t spakeObjectId = phsm_pake_context->spake_objId; + const smStatus_t smstatus = + Se05x_API_PAKEComputeSessionKeys(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, + (uint8_t *) pab, pab_len, pKeyKe, pkeyKeLen, out, out_len); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); - smstatus = Se05x_API_PAKEComputeSessionKeys(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, - (uint8_t *) pab, pab_len, pKeyKe, pkeyKeLen, out, out_len); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); - - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_KeyConfirm_HSM(hsm_pake_context_t * phsm_pake_context, chip::Crypto::CHIP_SPAKE2P_ROLE role, const uint8_t * in, size_t in_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - smStatus_t smstatus = SM_NOT_OK; - uint8_t presult = 0; - SE05x_CryptoObjectID_t spakeObjectId = phsm_pake_context->spake_objId; - - VerifyOrExit(in != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(gex_sss_chip_ctx.ks.session != NULL, CHIP_ERROR_INTERNAL); - VerifyOrExit(gex_sss_chip_ctx.ks.session != NULL, error = CHIP_ERROR_INTERNAL); + uint8_t presult = 0; + const SE05x_CryptoObjectID_t spakeObjectId = phsm_pake_context->spake_objId; + const smStatus_t smstatus = Se05x_API_PAKEVerifySessionKeys(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, + spakeObjectId, (uint8_t *) in, in_len, &presult); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); - smstatus = Se05x_API_PAKEVerifySessionKeys(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, spakeObjectId, - (uint8_t *) in, in_len, &presult); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); - - error = (presult == 1) ? CHIP_NO_ERROR : CHIP_ERROR_INTERNAL; -exit: - return error; + return (presult == 1) ? CHIP_NO_ERROR : CHIP_ERROR_INTERNAL; } namespace chip { @@ -262,8 +244,7 @@ namespace Crypto { CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::Init(const uint8_t * context, size_t context_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - state = CHIP_SPAKE2P_STATE::PREINIT; + state = CHIP_SPAKE2P_STATE::PREINIT; #if ENABLE_REENTRANCY static uint8_t alreadyInitialised = 0; @@ -277,20 +258,19 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::Init(const uint8_t * context, size_ if (context_len > 0) { - VerifyOrExit(context != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(context != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } - VerifyOrExit(context_len <= sizeof(hsm_pake_context.spake_context), error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(context_len <= sizeof(hsm_pake_context.spake_context), CHIP_ERROR_INTERNAL); memset(hsm_pake_context.spake_context, 0, sizeof(hsm_pake_context.spake_context)); memcpy(hsm_pake_context.spake_context, context, context_len); hsm_pake_context.spake_context_len = context_len; - error = Spake2p::Init(context, context_len); + const CHIP_ERROR error = Spake2p::Init(context, context_len); if (error == CHIP_NO_ERROR) { state = CHIP_SPAKE2P_STATE::INIT; } -exit: return error; } @@ -307,49 +287,49 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginVerifier(const uint8_t * my_id size_t w0in_mod_len = 32; smStatus_t smstatus = SM_NOT_OK; - VerifyOrExit(w0in != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(Lin != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(state == CHIP_SPAKE2P_STATE::INIT, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(w0in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(Lin != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::INIT, CHIP_ERROR_INTERNAL); if (my_identity_len > 0) { - VerifyOrExit(my_identity != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(my_identity != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } if (peer_identity_len > 0) { - VerifyOrExit(peer_identity != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(peer_identity != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } error = FELoad(w0in, w0in_len, w0); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = FEWrite(w0, w0in_mod, w0in_mod_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = create_init_crypto_obj(chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER, &hsm_pake_context); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); #if SSS_HAVE_SE05X_VER_GTE_16_02 smstatus = Se05x_API_PAKEConfigDevice(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, SE05x_SPAKEDevice_B, hsm_pake_context.spake_objId); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); smstatus = Se05x_API_PAKEInitDevice(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, hsm_pake_context.spake_objId, (uint8_t *) hsm_pake_context.spake_context, hsm_pake_context.spake_context_len, (uint8_t *) peer_identity, peer_identity_len, (uint8_t *) my_identity, my_identity_len); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); #else smstatus = Se05x_API_PAKEConfigDevice(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, SE05x_SPAKEDevice_B, hsm_pake_context.spake_objId, (uint8_t *) hsm_pake_context.spake_context, hsm_pake_context.spake_context_len, (uint8_t *) peer_identity, peer_identity_len, (uint8_t *) my_identity, my_identity_len); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); #endif error = se05x_set_key(w0in_id_v, w0in_mod, w0in_mod_len, kSSS_KeyPart_Default, kSSS_CipherType_AES); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = se05x_set_key(Lin_id_v, Lin, Lin_len, kSSS_KeyPart_Public, kSSS_CipherType_EC_NIST_P); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); #if SSS_HAVE_SE05X_VER_GTE_16_02 smstatus = Se05x_API_PAKEInitCredentials(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, @@ -358,14 +338,12 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginVerifier(const uint8_t * my_id smstatus = Se05x_API_PAKEInitDevice(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, hsm_pake_context.spake_objId, w0in_id_v, 0, Lin_id_v); #endif - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); state = CHIP_SPAKE2P_STATE::STARTED; role = CHIP_SPAKE2P_ROLE::VERIFIER; - error = CHIP_NO_ERROR; -exit: - return error; + return CHIP_NO_ERROR; } #endif @@ -386,56 +364,56 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_iden }; size_t w1in_mod_len = 32; - VerifyOrExit(w0in != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(w1in != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w0in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w1in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); if (my_identity_len > 0) { - VerifyOrExit(my_identity != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(my_identity != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } if (peer_identity_len > 0) { - VerifyOrExit(peer_identity != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(peer_identity != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } - VerifyOrExit(state == CHIP_SPAKE2P_STATE::INIT, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::INIT, CHIP_ERROR_INTERNAL); error = FELoad(w0in, w0in_len, w0); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = FEWrite(w0, w0in_mod, w0in_mod_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = FELoad(w1in, w1in_len, w1); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = FEWrite(w1, w1in_mod, w1in_mod_len); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = create_init_crypto_obj(chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER, &hsm_pake_context); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); #if SSS_HAVE_SE05X_VER_GTE_16_02 smstatus = Se05x_API_PAKEConfigDevice(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, SE05x_SPAKEDevice_A, hsm_pake_context.spake_objId); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); smstatus = Se05x_API_PAKEInitDevice(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, hsm_pake_context.spake_objId, (uint8_t *) hsm_pake_context.spake_context, hsm_pake_context.spake_context_len, (uint8_t *) my_identity, my_identity_len, (uint8_t *) peer_identity, peer_identity_len); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); #else smstatus = Se05x_API_PAKEConfigDevice(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, SE05x_SPAKEDevice_A, hsm_pake_context.spake_objId, (uint8_t *) hsm_pake_context.spake_context, hsm_pake_context.spake_context_len, (uint8_t *) peer_identity, peer_identity_len, (uint8_t *) my_identity, my_identity_len); - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); #endif error = se05x_set_key(w0in_id_p, w0in_mod, w0in_mod_len, kSSS_KeyPart_Default, kSSS_CipherType_AES); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); error = se05x_set_key(w1in_id_p, w1in_mod, w1in_mod_len, kSSS_KeyPart_Default, kSSS_CipherType_AES); - VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == CHIP_NO_ERROR, CHIP_ERROR_INTERNAL); #if SSS_HAVE_SE05X_VER_GTE_16_02 smstatus = Se05x_API_PAKEInitCredentials(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, @@ -444,120 +422,104 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_iden smstatus = Se05x_API_PAKEInitDevice(&((sss_se05x_session_t *) &gex_sss_chip_ctx.session)->s_ctx, hsm_pake_context.spake_objId, w0in_id_p, w1in_id_p, 0); #endif - VerifyOrExit(smstatus == SM_OK, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(smstatus == SM_OK, CHIP_ERROR_INTERNAL); - error = CHIP_NO_ERROR; state = CHIP_SPAKE2P_STATE::STARTED; role = CHIP_SPAKE2P_ROLE::PROVER; -exit: - return error; + return CHIP_NO_ERROR; } #endif CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::ComputeRoundOne(const uint8_t * pab, size_t pab_len, uint8_t * out, size_t * out_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - - VerifyOrExit(state == CHIP_SPAKE2P_STATE::STARTED, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(*out_len >= point_size, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::STARTED, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(*out_len >= point_size, CHIP_ERROR_INTERNAL); #if !ENABLE_HSM_SPAKE_VERIFIER - if (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER) - { - goto sw_rollback; - } + const bool sw_rollback_verifier = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER); +#else + constexpr bool sw_rollback_verifier = false; #endif #if ((CHIP_CRYPTO_HSM) && (!ENABLE_HSM_SPAKE_PROVER)) - if (role == chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER) + const bool sw_roolback_prover = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER); +#else + constexpr bool sw_rollback_prover = false; +#endif + + if (sw_rollback_verifier || sw_rollback_prover) { - goto sw_rollback; + return Spake2p::ComputeRoundOne(pab, pab_len, out, out_len); } -#endif - error = Spake2p_ComputeRoundOne_HSM(&hsm_pake_context, role, pab, pab_len, out, out_len); + CHIP_ERROR error = Spake2p_ComputeRoundOne_HSM(&hsm_pake_context, role, pab, pab_len, out, out_len); if (CHIP_NO_ERROR == error) { state = CHIP_SPAKE2P_STATE::R1; } - goto exit; - -#if (!ENABLE_HSM_SPAKE_VERIFIER) || (!ENABLE_HSM_SPAKE_PROVER) -sw_rollback: -#endif - - error = Spake2p::ComputeRoundOne(pab, pab_len, out, out_len); - -exit: return error; } CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::ComputeRoundTwo(const uint8_t * in, size_t in_len, uint8_t * out, size_t * out_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; - uint8_t pKeyKe[16] = { - 0, - }; - size_t pkeyKeLen = sizeof(pKeyKe); - - VerifyOrExit(*out_len >= hash_size, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(state == CHIP_SPAKE2P_STATE::R1, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(in_len == point_size, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(*out_len >= hash_size, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::R1, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(in_len == point_size, CHIP_ERROR_INTERNAL); #if !ENABLE_HSM_SPAKE_VERIFIER - if (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER) - { - goto sw_rollback; - } + const bool sw_rollback_verifier = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER); +#else + constexpr bool sw_rollback_verifier = false; #endif #if !ENABLE_HSM_SPAKE_PROVER - if (role == chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER) + const bool sw_roolback_prover = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER); +#else + constexpr bool sw_rollback_prover = false; +#endif + + if (sw_rollback_verifier || sw_rollback_prover) { - goto sw_rollback; + return Spake2p::ComputeRoundTwo(in, in_len, out, out_len); } -#endif - error = Spake2p_ComputeRoundTwo_HSM(&hsm_pake_context, role, in, in_len, out, out_len, pKeyKe, &pkeyKeLen); + uint8_t pKeyKe[16] = { + 0, + }; + constexpr size_t pkeyKeLen = sizeof(pKeyKe); + + const CHIP_ERROR error = Spake2p_ComputeRoundTwo_HSM(&hsm_pake_context, role, in, in_len, out, out_len, pKeyKe, &pkeyKeLen); if (CHIP_NO_ERROR == error) { memcpy((Kae + 16), pKeyKe, pkeyKeLen); state = CHIP_SPAKE2P_STATE::R2; } - - goto exit; - -#if ((!ENABLE_HSM_SPAKE_VERIFIER) || (!ENABLE_HSM_SPAKE_PROVER)) -sw_rollback: -#endif - - error = Spake2p::ComputeRoundTwo(in, in_len, out, out_len); - -exit: return error; } CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::KeyConfirm(const uint8_t * in, size_t in_len) { - CHIP_ERROR error = CHIP_ERROR_INTERNAL; VerifyOrExit(state == CHIP_SPAKE2P_STATE::R2, error = CHIP_ERROR_INTERNAL); #if !ENABLE_HSM_SPAKE_VERIFIER - if (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER) - { - goto sw_rollback; - } + const bool sw_rollback_verifier = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::VERIFIER); +#else + constexpr bool sw_rollback_verifier = false; #endif #if !ENABLE_HSM_SPAKE_PROVER - if (role == chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER) + const bool sw_roolback_prover = (role == chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER); +#else + constexpr bool sw_rollback_prover = false; +#endif + + if (sw_rollback_verifier || sw_rollback_prover) { - goto sw_rollback; + return Spake2p::KeyConfirm(in, in_len); } -#endif - error = Spake2p_KeyConfirm_HSM(&hsm_pake_context, role, in, in_len); + const CHIP_ERROR error = Spake2p_KeyConfirm_HSM(&hsm_pake_context, role, in, in_len); if (CHIP_NO_ERROR == error) { state = CHIP_SPAKE2P_STATE::KC; @@ -565,15 +527,6 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::KeyConfirm(const uint8_t * in, size Spake2p_Finish_HSM(&hsm_pake_context); - goto exit; - -#if (!ENABLE_HSM_SPAKE_VERIFIER || !ENABLE_HSM_SPAKE_PROVER) -sw_rollback: -#endif - - error = Spake2p::KeyConfirm(in, in_len); - -exit: return error; } diff --git a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_utils.cpp b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_utils.cpp index d4baedbf7dd4d1..391156b251c37e 100644 --- a/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_utils.cpp +++ b/src/crypto/hsm/nxp/CHIPCryptoPALHsm_SE05X_utils.cpp @@ -78,9 +78,6 @@ static Mutex sSEObjMutex; void se05x_sessionOpen(void) { static int is_session_open = 0; - sss_status_t status = kStatus_SSS_Fail; - const char * portName; - if (is_session_open) { return; @@ -88,31 +85,29 @@ void se05x_sessionOpen(void) memset(&gex_sss_chip_ctx, 0, sizeof(gex_sss_chip_ctx)); - status = ex_sss_boot_connectstring(0, NULL, &portName); + const char * portName = nullptr; + sss_status_t status = ex_sss_boot_connectstring(0, NULL, &portName); if (kStatus_SSS_Success != status) { ChipLogError(Crypto, "se05x error: %s\n", "ex_sss_boot_connectstring failed"); - goto exit; + return; } status = ex_sss_boot_open(&gex_sss_chip_ctx, portName); if (kStatus_SSS_Success != status) { ChipLogError(Crypto, "se05x error: %s\n", "ex_sss_boot_open failed"); - goto exit; + return; } status = ex_sss_key_store_and_object_init(&gex_sss_chip_ctx); if (kStatus_SSS_Success != status) { ChipLogError(Crypto, "se05x error: %s\n", "ex_sss_key_store_and_object_init failed"); - goto exit; + return; } is_session_open = 1; - -exit: - return; } /* Delete key in se05x */ @@ -152,7 +147,6 @@ void se05x_delete_key(uint32_t keyid) /* Set key in se05x */ CHIP_ERROR se05x_set_key(uint32_t keyid, const uint8_t * key, size_t keylen, sss_key_part_t keyPart, sss_cipher_type_t cipherType) { - CHIP_ERROR error = CHIP_NO_ERROR; sss_status_t status = kStatus_SSS_Success; sss_object_t keyObject = { 0 }; const uint8_t keyBuf[128] = { @@ -165,7 +159,7 @@ CHIP_ERROR se05x_set_key(uint32_t keyid, const uint8_t * key, size_t keylen, sss if (cipherType == kSSS_CipherType_EC_NIST_P) { - VerifyOrExit(keylen < (sizeof(keyBuf) - sizeof(header1)), error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(keylen < (sizeof(keyBuf) - sizeof(header1)), CHIP_ERROR_INTERNAL); memcpy((void *) keyBuf, (const uint8_t *) header1, sizeof(header1)); keyBufLen = keyBufLen + sizeof(header1); @@ -177,7 +171,7 @@ CHIP_ERROR se05x_set_key(uint32_t keyid, const uint8_t * key, size_t keylen, sss } else { - VerifyOrExit(keylen < sizeof(keyBuf), error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(keylen < sizeof(keyBuf), CHIP_ERROR_INTERNAL); memcpy((void *) keyBuf, (const uint8_t *) key, keylen); keyBufLen = keylen; @@ -185,16 +179,15 @@ CHIP_ERROR se05x_set_key(uint32_t keyid, const uint8_t * key, size_t keylen, sss } status = sss_key_object_init(&keyObject, &gex_sss_chip_ctx.ks); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); status = sss_key_object_allocate_handle(&keyObject, keyid, keyPart, cipherType, keyBufLen, kKeyObject_Mode_Persistent); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); status = sss_key_store_set_key(&gex_sss_chip_ctx.ks, &keyObject, keyBuf, keyBufLen, bitlen, NULL, 0); - VerifyOrExit(status == kStatus_SSS_Success, error = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(status == kStatus_SSS_Success, CHIP_ERROR_INTERNAL); -exit: - return error; + return CHIP_NO_ERROR; } #if ENABLE_REENTRANCY diff --git a/src/inet/IPEndPointBasis.cpp b/src/inet/IPEndPointBasis.cpp index 4c34c06349e305..1efefb5fa6d4cb 100644 --- a/src/inet/IPEndPointBasis.cpp +++ b/src/inet/IPEndPointBasis.cpp @@ -133,17 +133,11 @@ IPEndPointBasis::LeaveMulticastGroupHandler IPEndPointBasis::sLeaveMulticastGrou #if CHIP_SYSTEM_CONFIG_USE_LWIP || CHIP_SYSTEM_CONFIG_USE_SOCKETS static INET_ERROR CheckMulticastGroupArgs(InterfaceId aInterfaceId, const IPAddress & aAddress) { - INET_ERROR lRetval = INET_NO_ERROR; - bool lIsPresent, lIsMulticast; - - lIsPresent = IsInterfaceIdPresent(aInterfaceId); - VerifyOrExit(lIsPresent, lRetval = INET_ERROR_UNKNOWN_INTERFACE); + VerifyOrReturnError(IsInterfaceIdPresent(aInterfaceId), INET_ERROR_UNKNOWN_INTERFACE); - lIsMulticast = aAddress.IsMulticast(); - VerifyOrExit(lIsMulticast, lRetval = INET_ERROR_WRONG_ADDRESS_TYPE); + VerifyOrReturnError(aAddress.IsMulticast(), INET_ERROR_WRONG_ADDRESS_TYPE); -exit: - return (lRetval); + return INET_NO_ERROR; } #endif // CHIP_SYSTEM_CONFIG_USE_LWIP || CHIP_SYSTEM_CONFIG_USE_SOCKETS @@ -153,32 +147,17 @@ static INET_ERROR CheckMulticastGroupArgs(InterfaceId aInterfaceId, const IPAddr static INET_ERROR LwIPIPv4JoinLeaveMulticastGroup(InterfaceId aInterfaceId, const IPAddress & aAddress, err_t (*aMethod)(struct netif *, const LWIP_IPV4_ADDR_T *)) { - INET_ERROR lRetval = INET_NO_ERROR; - err_t lStatus; - struct netif * lNetif; - LWIP_IPV4_ADDR_T lIPv4Address; - - lNetif = IPEndPointBasis::FindNetifFromInterfaceId(aInterfaceId); - VerifyOrExit(lNetif != NULL, lRetval = INET_ERROR_UNKNOWN_INTERFACE); + struct netif * const lNetif = IPEndPointBasis::FindNetifFromInterfaceId(aInterfaceId); + VerifyOrReturnError(lNetif != nullptr, INET_ERROR_UNKNOWN_INTERFACE); - lIPv4Address = IPV4_TO_LWIPADDR(aAddress); + const LWIP_IPV4_ADDR_T lIPv4Address = IPV4_TO_LWIPADDR(aAddress); + const err_t lStatus = aMethod(lNetif, &lIPv4Address); - lStatus = aMethod(lNetif, &lIPv4Address); - - switch (lStatus) + if (lStatus == ERR_MEM) { - - case ERR_MEM: - lRetval = INET_ERROR_NO_MEMORY; - break; - - default: - lRetval = chip::System::MapErrorLwIP(lStatus); - break; + return INET_ERROR_NO_MEMORY; } - -exit: - return (lRetval); + return chip::System::MapErrorLwIP(lStatus); } #endif // LWIP_IPV4 && LWIP_IGMP #endif // INET_CONFIG_ENABLE_IPV4 @@ -197,32 +176,17 @@ static INET_ERROR LwIPIPv4JoinLeaveMulticastGroup(InterfaceId aInterfaceId, cons static INET_ERROR LwIPIPv6JoinLeaveMulticastGroup(InterfaceId aInterfaceId, const IPAddress & aAddress, err_t (*aMethod)(struct netif *, const LWIP_IPV6_ADDR_T *)) { - INET_ERROR lRetval = INET_NO_ERROR; - err_t lStatus; - struct netif * lNetif; - LWIP_IPV6_ADDR_T lIPv6Address; + struct netif * const lNetif = IPEndPointBasis::FindNetifFromInterfaceId(aInterfaceId); + VerifyOrReturnError(lNetif != nullptr, INET_ERROR_UNKNOWN_INTERFACE); - lNetif = IPEndPointBasis::FindNetifFromInterfaceId(aInterfaceId); - VerifyOrExit(lNetif != NULL, lRetval = INET_ERROR_UNKNOWN_INTERFACE); + const LWIP_IPV6_ADDR_T lIPv6Address = IPV6_TO_LWIPADDR(aAddress); + const err_t lStatus = aMethod(lNetif, &lIPv6Address); - lIPv6Address = IPV6_TO_LWIPADDR(aAddress); - - lStatus = aMethod(lNetif, &lIPv6Address); - - switch (lStatus) + if (lStatus == ERR_MEM) { - - case ERR_MEM: - lRetval = INET_ERROR_NO_MEMORY; - break; - - default: - lRetval = chip::System::MapErrorLwIP(lStatus); - break; + return INET_ERROR_NO_MEMORY; } - -exit: - return (lRetval); + return chip::System::MapErrorLwIP(lStatus); } #endif // LWIP_IPV6_MLD && LWIP_IPV6_ND && LWIP_IPV6 #endif // CHIP_SYSTEM_CONFIG_USE_LWIP @@ -231,15 +195,13 @@ static INET_ERROR LwIPIPv6JoinLeaveMulticastGroup(InterfaceId aInterfaceId, cons #if IP_MULTICAST_LOOP || IPV6_MULTICAST_LOOP static INET_ERROR SocketsSetMulticastLoopback(int aSocket, bool aLoopback, int aProtocol, int aOption) { - INET_ERROR lRetval = INET_NO_ERROR; - int lStatus; - unsigned int lValue = aLoopback; - - lStatus = setsockopt(aSocket, aProtocol, aOption, &lValue, sizeof(lValue)); - VerifyOrExit(lStatus == 0, lRetval = chip::System::MapErrorPOSIX(errno)); + const unsigned int lValue = aLoopback; + if (setsockopt(aSocket, aProtocol, aOption, &lValue, sizeof(lValue)) != 0) + { + return chip::System::MapErrorPOSIX(errno); + } -exit: - return (lRetval); + return INET_NO_ERROR; } #endif // IP_MULTICAST_LOOP || IPV6_MULTICAST_LOOP @@ -276,10 +238,8 @@ static INET_ERROR SocketsSetMulticastLoopback(int aSocket, IPVersion aIPVersion, static INET_ERROR SocketsIPv4JoinLeaveMulticastGroup(int aSocket, InterfaceId aInterfaceId, const IPAddress & aAddress, int aCommand) { - INET_ERROR lRetval = INET_NO_ERROR; IPAddress lInterfaceAddress; bool lInterfaceAddressFound = false; - struct ip_mreq lMulticastRequest; for (InterfaceAddressIterator lAddressIterator; lAddressIterator.HasCurrent(); lAddressIterator.Next()) { @@ -296,17 +256,18 @@ static INET_ERROR SocketsIPv4JoinLeaveMulticastGroup(int aSocket, InterfaceId aI } } - VerifyOrExit(lInterfaceAddressFound, lRetval = INET_ERROR_ADDRESS_NOT_FOUND); + VerifyOrReturnError(lInterfaceAddressFound, INET_ERROR_ADDRESS_NOT_FOUND); + struct ip_mreq lMulticastRequest; memset(&lMulticastRequest, 0, sizeof(lMulticastRequest)); lMulticastRequest.imr_interface = lInterfaceAddress.ToIPv4(); lMulticastRequest.imr_multiaddr = aAddress.ToIPv4(); - lRetval = setsockopt(aSocket, IPPROTO_IP, aCommand, &lMulticastRequest, sizeof(lMulticastRequest)); - VerifyOrExit(lRetval == 0, lRetval = chip::System::MapErrorPOSIX(errno)); - -exit: - return (lRetval); + if (setsockopt(aSocket, IPPROTO_IP, aCommand, &lMulticastRequest, sizeof(lMulticastRequest)) != 0) + { + return chip::System::MapErrorPOSIX(errno); + } + return INET_NO_ERROR; } #endif // INET_CONFIG_ENABLE_IPV4 @@ -314,26 +275,21 @@ static INET_ERROR SocketsIPv4JoinLeaveMulticastGroup(int aSocket, InterfaceId aI static INET_ERROR SocketsIPv6JoinLeaveMulticastGroup(int aSocket, InterfaceId aInterfaceId, const IPAddress & aAddress, int aCommand) { - INET_ERROR lRetval = INET_NO_ERROR; + VerifyOrReturnError(CanCastTo(aInterfaceId), INET_ERROR_UNEXPECTED_EVENT); const unsigned int lIfIndex = static_cast(aInterfaceId); - struct ipv6_mreq lMulticastRequest; - - // Check whether that cast we did was actually safe. We can't VerifyOrExit - // before declaring variables, and can't reassign lIfIndex without making it - // non-const, so have to do things in this order. - VerifyOrExit(CanCastTo(aInterfaceId), lRetval = INET_ERROR_UNEXPECTED_EVENT); + struct ipv6_mreq lMulticastRequest; memset(&lMulticastRequest, 0, sizeof(lMulticastRequest)); - VerifyOrExit(CanCastTo(lIfIndex), lRetval = INET_ERROR_UNEXPECTED_EVENT); + VerifyOrReturnError(CanCastTo(lIfIndex), INET_ERROR_UNEXPECTED_EVENT); lMulticastRequest.ipv6mr_interface = static_cast(lIfIndex); lMulticastRequest.ipv6mr_multiaddr = aAddress.ToIPv6(); - lRetval = setsockopt(aSocket, IPPROTO_IPV6, aCommand, &lMulticastRequest, sizeof(lMulticastRequest)); - VerifyOrExit(lRetval == 0, lRetval = chip::System::MapErrorPOSIX(errno)); - -exit: - return (lRetval); + if (setsockopt(aSocket, IPPROTO_IPV6, aCommand, &lMulticastRequest, sizeof(lMulticastRequest)) != 0) + { + return chip::System::MapErrorPOSIX(errno); + } + return INET_NO_ERROR; } #endif // INET_IPV6_ADD_MEMBERSHIP || INET_IPV6_DROP_MEMBERSHIP @@ -836,27 +792,23 @@ INET_ERROR IPEndPointBasis::BindInterface(IPAddressType aAddressType, InterfaceI INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System::PacketBufferHandle && aBuffer, uint16_t aSendFlags) { - INET_ERROR res = INET_NO_ERROR; - PeerSockAddr peerSockAddr; - struct iovec msgIOV; - uint8_t controlData[256]; - struct msghdr msgHeader; - InterfaceId intfId = aPktInfo->Interface; - // Ensure the destination address type is compatible with the endpoint address type. - VerifyOrExit(mAddrType == aPktInfo->DestAddress.Type(), res = INET_ERROR_BAD_ARGS); + VerifyOrReturnError(mAddrType == aPktInfo->DestAddress.Type(), INET_ERROR_BAD_ARGS); // For now the entire message must fit within a single buffer. - VerifyOrExit(!aBuffer->HasChainedBuffer(), res = INET_ERROR_MESSAGE_TOO_LONG); + VerifyOrReturnError(!aBuffer->HasChainedBuffer(), INET_ERROR_MESSAGE_TOO_LONG); - memset(&msgHeader, 0, sizeof(msgHeader)); + struct iovec msgIOV; + msgIOV.iov_base = aBuffer->Start(); + msgIOV.iov_len = aBuffer->DataLength(); - msgIOV.iov_base = aBuffer->Start(); - msgIOV.iov_len = aBuffer->DataLength(); + struct msghdr msgHeader; + memset(&msgHeader, 0, sizeof(msgHeader)); msgHeader.msg_iov = &msgIOV; msgHeader.msg_iovlen = 1; // Construct a sockaddr_in/sockaddr_in6 structure containing the destination information. + PeerSockAddr peerSockAddr; memset(&peerSockAddr, 0, sizeof(peerSockAddr)); msgHeader.msg_name = &peerSockAddr; if (mAddrType == kIPAddressType_IPv6) @@ -864,7 +816,7 @@ INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System: peerSockAddr.in6.sin6_family = AF_INET6; peerSockAddr.in6.sin6_port = htons(aPktInfo->DestPort); peerSockAddr.in6.sin6_addr = aPktInfo->DestAddress.ToIPv6(); - VerifyOrExit(CanCastTo(aPktInfo->Interface), res = INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(CanCastTo(aPktInfo->Interface), INET_ERROR_INCORRECT_STATE); peerSockAddr.in6.sin6_scope_id = static_cast(aPktInfo->Interface); msgHeader.msg_namelen = sizeof(sockaddr_in6); } @@ -884,6 +836,7 @@ INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System: // for messages to multicast addresses, which under Linux // don't seem to get sent out the correct interface, despite // the socket being bound. + InterfaceId intfId = aPktInfo->Interface; if (intfId == INET_NULL_INTERFACEID) intfId = mBoundIntfId; @@ -894,6 +847,7 @@ INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System: if (intfId != INET_NULL_INTERFACEID || aPktInfo->SrcAddress.Type() != kIPAddressType_Any) { #if defined(IP_PKTINFO) || defined(IPV6_PKTINFO) + uint8_t controlData[256]; memset(controlData, 0, sizeof(controlData)); msgHeader.msg_control = controlData; msgHeader.msg_controllen = sizeof(controlData); @@ -912,7 +866,7 @@ INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System: struct in_pktinfo * pktInfo = reinterpret_cast CMSG_DATA(controlHdr); if (!CanCastToipi_ifindex)>(intfId)) { - ExitNow(res = INET_ERROR_NOT_SUPPORTED); + return INET_ERROR_NOT_SUPPORTED; } pktInfo->ipi_ifindex = static_castipi_ifindex)>(intfId); @@ -920,7 +874,7 @@ INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System: msgHeader.msg_controllen = CMSG_SPACE(sizeof(in_pktinfo)); #else // !defined(IP_PKTINFO) - ExitNow(res = INET_ERROR_NOT_SUPPORTED); + return INET_ERROR_NOT_SUPPORTED; #endif // !defined(IP_PKTINFO) } @@ -936,34 +890,29 @@ INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System: struct in6_pktinfo * pktInfo = reinterpret_cast CMSG_DATA(controlHdr); if (!CanCastToipi6_ifindex)>(intfId)) { - ExitNow(res = INET_ERROR_UNEXPECTED_EVENT); + return INET_ERROR_UNEXPECTED_EVENT; } pktInfo->ipi6_ifindex = static_castipi6_ifindex)>(intfId); pktInfo->ipi6_addr = aPktInfo->SrcAddress.ToIPv6(); msgHeader.msg_controllen = CMSG_SPACE(sizeof(in6_pktinfo)); #else // !defined(IPV6_PKTINFO) - ExitNow(res = INET_ERROR_NOT_SUPPORTED); + return INET_ERROR_NOT_SUPPORTED; #endif // !defined(IPV6_PKTINFO) } #else // !(defined(IP_PKTINFO) && defined(IPV6_PKTINFO)) - IgnoreUnusedVariable(controlData); - ExitNow(res = INET_ERROR_NOT_SUPPORTED); + return INET_ERROR_NOT_SUPPORTED; #endif // !(defined(IP_PKTINFO) && defined(IPV6_PKTINFO)) } // Send IP packet. - { - const ssize_t lenSent = sendmsg(mSocket.GetFD(), &msgHeader, 0); - if (lenSent == -1) - res = chip::System::MapErrorPOSIX(errno); - else if (lenSent != aBuffer->DataLength()) - res = INET_ERROR_OUTBOUND_MESSAGE_TRUNCATED; - } - -exit: - return (res); + const ssize_t lenSent = sendmsg(mSocket.GetFD(), &msgHeader, 0); + if (lenSent == -1) + return chip::System::MapErrorPOSIX(errno); + if (lenSent != aBuffer->DataLength()) + return INET_ERROR_OUTBOUND_MESSAGE_TRUNCATED; + return INET_NO_ERROR; } INET_ERROR IPEndPointBasis::GetSocket(IPAddressType aAddressType, int aType, int aProtocol) @@ -1236,51 +1185,46 @@ INET_ERROR IPEndPointBasis::ConfigureProtocol(IPAddressType aAddressType, const INET_ERROR IPEndPointBasis::Bind(IPAddressType aAddressType, const IPAddress & aAddress, uint16_t aPort, const nw_parameters_t & aParameters) { - INET_ERROR res = INET_NO_ERROR; nw_endpoint_t endpoint = nullptr; - VerifyOrExit(aParameters != NULL, res = INET_ERROR_BAD_ARGS); + VerifyOrReturnError(aParameters != NULL, INET_ERROR_BAD_ARGS); - res = ConfigureProtocol(aAddressType, aParameters); - SuccessOrExit(res); + ReturnErrorOnFailure(ConfigureProtocol(aAddressType, aParameters)); - res = GetEndPoint(endpoint, aAddressType, aAddress, aPort); + INET_ERROR res = GetEndPoint(endpoint, aAddressType, aAddress, aPort); nw_parameters_set_local_endpoint(aParameters, endpoint); nw_release(endpoint); - SuccessOrExit(res); + ReturnErrorOnFailure(res); mDispatchQueue = dispatch_queue_create("inet_dispatch_global", DISPATCH_QUEUE_CONCURRENT); - VerifyOrExit(mDispatchQueue != NULL, res = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(mDispatchQueue != NULL, INET_ERROR_NO_MEMORY); dispatch_retain(mDispatchQueue); mConnectionSemaphore = dispatch_semaphore_create(0); - VerifyOrExit(mConnectionSemaphore != NULL, res = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(mConnectionSemaphore != NULL, INET_ERROR_NO_MEMORY); dispatch_retain(mConnectionSemaphore); mSendSemaphore = dispatch_semaphore_create(0); - VerifyOrExit(mSendSemaphore != NULL, res = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(mSendSemaphore != NULL, INET_ERROR_NO_MEMORY); dispatch_retain(mSendSemaphore); mAddrType = aAddressType; mConnection = NULL; -exit: - return res; + return INET_NO_ERROR; } INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System::PacketBufferHandle && aBuffer, uint16_t aSendFlags) { - __block INET_ERROR res = INET_NO_ERROR; dispatch_data_t content; // Ensure the destination address type is compatible with the endpoint address type. - VerifyOrExit(mAddrType == aPktInfo->DestAddress.Type(), res = INET_ERROR_BAD_ARGS); + VerifyOrReturnError(mAddrType == aPktInfo->DestAddress.Type(), INET_ERROR_BAD_ARGS); // For now the entire message must fit within a single buffer. - VerifyOrExit(aBuffer->Next() == NULL, res = INET_ERROR_MESSAGE_TOO_LONG); + VerifyOrReturnError(aBuffer->Next() == NULL, INET_ERROR_MESSAGE_TOO_LONG); - res = GetConnection(aPktInfo); - SuccessOrExit(res); + ReturnErrorOnFailure(GetConnection(aPktInfo)); // Send a message, and wait for it to be dispatched. content = dispatch_data_create(aBuffer->Start(), aBuffer->DataLength(), mDispatchQueue, DISPATCH_DATA_DESTRUCTOR_DEFAULT); @@ -1291,7 +1235,7 @@ INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System: // the semaphore. In this case the INET_ERROR will not update with the result of the completion handler. // To make sure caller knows that sending a message has failed the following code consider there is an error // _unless_ the completion handler says otherwise. - res = INET_ERROR_UNEXPECTED_EVENT; + __block INET_ERROR res = INET_ERROR_UNEXPECTED_EVENT; nw_connection_send(mConnection, content, NW_CONNECTION_DEFAULT_MESSAGE_CONTEXT, true, ^(nw_error_t error) { if (error) { @@ -1307,7 +1251,6 @@ INET_ERROR IPEndPointBasis::SendMsg(const IPPacketInfo * aPktInfo, chip::System: dispatch_semaphore_wait(mSendSemaphore, DISPATCH_TIME_FOREVER); -exit: return res; } @@ -1376,7 +1319,6 @@ void IPEndPointBasis::GetPacketInfo(const nw_connection_t & aConnection, IPPacke INET_ERROR IPEndPointBasis::GetEndPoint(nw_endpoint_t & aEndPoint, const IPAddressType aAddressType, const IPAddress & aAddress, uint16_t aPort) { - INET_ERROR res = INET_NO_ERROR; char addrStr[INET6_ADDRSTRLEN]; char portStr[INET_PORTSTRLEN]; @@ -1395,20 +1337,18 @@ INET_ERROR IPEndPointBasis::GetEndPoint(nw_endpoint_t & aEndPoint, const IPAddre snprintf(portStr, sizeof(portStr), "%u", aPort); aEndPoint = nw_endpoint_create_host(addrStr, portStr); - VerifyOrExit(aEndPoint != NULL, res = INET_ERROR_BAD_ARGS); + VerifyOrReturnError(aEndPoint != NULL, INET_ERROR_BAD_ARGS); -exit: - return res; + return INET_NO_ERROR; } INET_ERROR IPEndPointBasis::GetConnection(const IPPacketInfo * aPktInfo) { - INET_ERROR res = INET_NO_ERROR; + VerifyOrReturnError(mParameters != NULL, INET_ERROR_INCORRECT_STATE); + nw_endpoint_t endpoint = NULL; nw_connection_t connection = NULL; - VerifyOrExit(mParameters != NULL, res = INET_ERROR_INCORRECT_STATE); - if (mConnection) { nw_path_t path = nw_connection_copy_current_path(mConnection); @@ -1416,24 +1356,19 @@ INET_ERROR IPEndPointBasis::GetConnection(const IPPacketInfo * aPktInfo) const IPAddress remote_address = IPAddress::FromSockAddr(*nw_endpoint_get_address(remote_endpoint)); const uint16_t remote_port = nw_endpoint_get_port(remote_endpoint); const bool isDifferentEndPoint = aPktInfo->DestPort != remote_port || aPktInfo->DestAddress != remote_address; - VerifyOrExit(isDifferentEndPoint, res = INET_NO_ERROR); + VerifyOrReturnError(isDifferentEndPoint, INET_NO_ERROR); - res = ReleaseConnection(); + ReturnErrorOnFailure(ReleaseConnection()); } - SuccessOrExit(res); - res = GetEndPoint(endpoint, mAddrType, aPktInfo->DestAddress, aPktInfo->DestPort); - SuccessOrExit(res); + ReturnErrorOnFailure(GetEndPoint(endpoint, mAddrType, aPktInfo->DestAddress, aPktInfo->DestPort)); connection = nw_connection_create(endpoint, mParameters); nw_release(endpoint); - VerifyOrExit(connection != NULL, res = INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(connection != NULL, INET_ERROR_INCORRECT_STATE); - res = StartConnection(connection); - -exit: - return res; + return StartConnection(connection); } INET_ERROR IPEndPointBasis::StartListener() @@ -1441,19 +1376,19 @@ INET_ERROR IPEndPointBasis::StartListener() __block INET_ERROR res = INET_NO_ERROR; nw_listener_t listener; - VerifyOrExit(mListener == NULL, res = INET_ERROR_INCORRECT_STATE); - VerifyOrExit(mListenerSemaphore == NULL, res = INET_ERROR_INCORRECT_STATE); - VerifyOrExit(mListenerQueue == NULL, res = INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mListener == NULL, INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mListenerSemaphore == NULL, INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mListenerQueue == NULL, INET_ERROR_INCORRECT_STATE); listener = nw_listener_create(mParameters); - VerifyOrExit(listener != NULL, res = INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(listener != NULL, INET_ERROR_INCORRECT_STATE); mListenerSemaphore = dispatch_semaphore_create(0); - VerifyOrExit(mListenerSemaphore != NULL, res = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(mListenerSemaphore != NULL, INET_ERROR_NO_MEMORY); dispatch_retain(mListenerSemaphore); mListenerQueue = dispatch_queue_create("inet_dispatch_listener", DISPATCH_QUEUE_CONCURRENT); - VerifyOrExit(mListenerQueue != NULL, res = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(mListenerQueue != NULL, INET_ERROR_NO_MEMORY); dispatch_retain(mListenerQueue); nw_listener_set_queue(listener, mListenerQueue); @@ -1500,11 +1435,10 @@ INET_ERROR IPEndPointBasis::StartListener() nw_listener_start(listener); dispatch_semaphore_wait(mListenerSemaphore, DISPATCH_TIME_FOREVER); - SuccessOrExit(res); + ReturnErrorOnFailure(res); mListener = listener; nw_retain(mListener); -exit: return res; } @@ -1563,7 +1497,6 @@ INET_ERROR IPEndPointBasis::StartConnection(nw_connection_t & aConnection) nw_retain(mConnection); HandleDataReceived(mConnection); -exit: return res; } @@ -1617,35 +1550,30 @@ void IPEndPointBasis::ReleaseAll() INET_ERROR IPEndPointBasis::ReleaseListener() { - INET_ERROR res = INET_NO_ERROR; - - VerifyOrExit(mListener, res = INET_ERROR_INCORRECT_STATE); - VerifyOrExit(mDispatchQueue, res = INET_ERROR_INCORRECT_STATE); - VerifyOrExit(mConnectionSemaphore, res = INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mListener, INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mDispatchQueue, INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mConnectionSemaphore, INET_ERROR_INCORRECT_STATE); nw_listener_cancel(mListener); dispatch_semaphore_wait(mListenerSemaphore, DISPATCH_TIME_FOREVER); nw_release(mListener); mListener = NULL; -exit: - return res; + return INET_NO_ERROR; } INET_ERROR IPEndPointBasis::ReleaseConnection() { - INET_ERROR res = INET_NO_ERROR; - VerifyOrExit(mConnection, res = INET_ERROR_INCORRECT_STATE); - VerifyOrExit(mDispatchQueue, res = INET_ERROR_INCORRECT_STATE); - VerifyOrExit(mConnectionSemaphore, res = INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mConnection, INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mDispatchQueue, INET_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mConnectionSemaphore, INET_ERROR_INCORRECT_STATE); nw_connection_cancel(mConnection); dispatch_semaphore_wait(mConnectionSemaphore, DISPATCH_TIME_FOREVER); nw_release(mConnection); mConnection = NULL; -exit: - return res; + return INET_NO_ERROR; } #endif // CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK diff --git a/src/inet/tests/TestInetLayer.cpp b/src/inet/tests/TestInetLayer.cpp index 786df8e368889c..1317ec535d9b35 100644 --- a/src/inet/tests/TestInetLayer.cpp +++ b/src/inet/tests/TestInetLayer.cpp @@ -447,19 +447,19 @@ static bool HandleOption(const char * aProgram, OptionSet * aOptions, int aIdent bool HandleNonOptionArgs(const char * aProgram, int argc, char * argv[]) { - bool retval = true; - if (Common::IsSender()) { if (argc == 0) { PrintArgError("%s: Please specify a destination address.\n", aProgram); - retval = false; - goto exit; + return false; } - retval = IPAddress::FromString(argv[0], sDestinationAddress); - VerifyOrExit(retval == true, PrintArgError("%s: Please specify a valid destination address: %s\n", aProgram, argv[0])); + if (!IPAddress::FromString(argv[0], sDestinationAddress)) + { + PrintArgError("%s: Please specify a valid destination address: %s\n", aProgram, argv[0]); + return false; + } sDestinationString = argv[0]; @@ -470,8 +470,7 @@ bool HandleNonOptionArgs(const char * aProgram, int argc, char * argv[]) if (argc > 0) { PrintArgError("%s: unexpected argument: %s\n", aProgram, argv[0]); - retval = false; - goto exit; + return false; } // If no IP version or transport flags were specified, use the defaults. @@ -493,8 +492,7 @@ bool HandleNonOptionArgs(const char * aProgram, int argc, char * argv[]) sTestState.mStats.mTransmit.mExpected = kExpectedTxSizeDefault; } -exit: - return (retval); + return true; } static void PrintReceivedStats(const TransferStats & aStats) @@ -504,28 +502,22 @@ static void PrintReceivedStats(const TransferStats & aStats) static bool HandleDataReceived(const PacketBufferHandle & aBuffer, bool aCheckBuffer, uint8_t aFirstValue) { - const bool lStatsByPacket = true; - bool lStatus = true; + constexpr bool lStatsByPacket = true; - lStatus = Common::HandleDataReceived(aBuffer, sTestState.mStats, !lStatsByPacket, aCheckBuffer, aFirstValue); - VerifyOrExit(lStatus == true, ); + if (!Common::HandleDataReceived(aBuffer, sTestState.mStats, !lStatsByPacket, aCheckBuffer, aFirstValue)) + { + return false; + } PrintReceivedStats(sTestState.mStats); -exit: - return (lStatus); + return true; } static bool HandleDataReceived(const PacketBufferHandle & aBuffer, bool aCheckBuffer) { - const uint8_t lFirstValue = 0; - bool lStatus = true; - - lStatus = HandleDataReceived(aBuffer, aCheckBuffer, lFirstValue); - VerifyOrExit(lStatus == true, ); - -exit: - return (lStatus); + constexpr uint8_t lFirstValue = 0; + return HandleDataReceived(aBuffer, aCheckBuffer, lFirstValue); } // TCP Endpoint Callbacks @@ -809,7 +801,6 @@ static INET_ERROR PrepareTransportForSend() static INET_ERROR DriveSendForDestination(const IPAddress & aAddress, uint16_t aSize) { PacketBufferHandle lBuffer; - INET_ERROR lStatus = INET_NO_ERROR; if ((gOptFlags & (kOptFlagUseRawIP)) == (kOptFlagUseRawIP)) { @@ -821,18 +812,17 @@ static INET_ERROR DriveSendForDestination(const IPAddress & aAddress, uint16_t a if ((gOptFlags & kOptFlagUseIPv6) == (kOptFlagUseIPv6)) { lBuffer = Common::MakeICMPv6DataBuffer(aSize); - VerifyOrExit(!lBuffer.IsNull(), lStatus = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(!lBuffer.IsNull(), INET_ERROR_NO_MEMORY); } #if INET_CONFIG_ENABLE_IPV4 else if ((gOptFlags & kOptFlagUseIPv4) == (kOptFlagUseIPv4)) { lBuffer = Common::MakeICMPv4DataBuffer(aSize); - VerifyOrExit(!lBuffer.IsNull(), lStatus = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(!lBuffer.IsNull(), INET_ERROR_NO_MEMORY); } #endif // INET_CONFIG_ENABLE_IPV4 - lStatus = sRawIPEndPoint->SendTo(aAddress, std::move(lBuffer)); - SuccessOrExit(lStatus); + ReturnErrorOnFailure(sRawIPEndPoint->SendTo(aAddress, std::move(lBuffer))); } else { @@ -844,15 +834,14 @@ static INET_ERROR DriveSendForDestination(const IPAddress & aAddress, uint16_t a // patterned from zero to aSize - 1. lBuffer = Common::MakeDataBuffer(aSize, lFirstValue); - VerifyOrExit(!lBuffer.IsNull(), lStatus = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(!lBuffer.IsNull(), INET_ERROR_NO_MEMORY); - lStatus = sUDPIPEndPoint->SendTo(aAddress, kUDPPort, std::move(lBuffer)); - SuccessOrExit(lStatus); + ReturnErrorOnFailure(sUDPIPEndPoint->SendTo(aAddress, kUDPPort, std::move(lBuffer))); } else if ((gOptFlags & kOptFlagUseTCPIP) == kOptFlagUseTCPIP) { const uint32_t lFirstValue = sTestState.mStats.mTransmit.mActual; - VerifyOrExit(lFirstValue < 256u, lStatus = INET_ERROR_UNEXPECTED_EVENT); + VerifyOrReturnError(lFirstValue < 256u, INET_ERROR_UNEXPECTED_EVENT); // For TCP, we'll send one byte stream of // sTestState.mStats.mTransmit.mExpected in n aSize or @@ -860,15 +849,13 @@ static INET_ERROR DriveSendForDestination(const IPAddress & aAddress, uint16_t a // sTestState.mStats.mTransmit.mExpected - 1. lBuffer = Common::MakeDataBuffer(aSize, uint8_t(lFirstValue)); - VerifyOrExit(!lBuffer.IsNull(), lStatus = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(!lBuffer.IsNull(), INET_ERROR_NO_MEMORY); - lStatus = sTCPIPEndPoint->Send(std::move(lBuffer)); - SuccessOrExit(lStatus); + ReturnErrorOnFailure(sTCPIPEndPoint->Send(std::move(lBuffer))); } } -exit: - return (lStatus); + return INET_NO_ERROR; } void DriveSend() diff --git a/src/inet/tests/TestInetLayerCommon.cpp b/src/inet/tests/TestInetLayerCommon.cpp index 624a507e2f4817..13300aee8708ac 100644 --- a/src/inet/tests/TestInetLayerCommon.cpp +++ b/src/inet/tests/TestInetLayerCommon.cpp @@ -138,39 +138,31 @@ static void FillDataBufferPattern(uint8_t * aBuffer, uint16_t aLength, uint16_t static bool CheckDataBufferPattern(const uint8_t * aBuffer, uint16_t aLength, uint16_t aPatternStartOffset, uint8_t aFirstValue) { - bool lStatus = true; - for (uint16_t i = aPatternStartOffset; i < aLength; i++) { const uint8_t lValue = aBuffer[i]; - // clang-format off - VerifyOrExit(lValue == static_cast(aFirstValue), - printf("Bad data value at offset %u (0x%04x): " - "expected 0x%02x, found 0x%02x\n", - i, i, aFirstValue, lValue); - lStatus = false; - DumpMemory(aBuffer + aPatternStartOffset, - aLength - aPatternStartOffset, - "0x", - 16)); - // clang-format on + if (lValue != static_cast(aFirstValue)) + { + printf("Bad data value at offset %u (0x%04x): " + "expected 0x%02x, found 0x%02x\n", + i, i, aFirstValue, lValue); + DumpMemory(aBuffer + aPatternStartOffset, aLength - aPatternStartOffset, "0x", 16); + return false; + } aFirstValue++; } -exit: - return (lStatus); + return true; } static PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength, uint16_t aPatternStartOffset, uint8_t aFirstValue) { - PacketBufferHandle lBuffer; + VerifyOrReturnError(aPatternStartOffset <= aDesiredLength, PacketBufferHandle()); - VerifyOrExit(aPatternStartOffset <= aDesiredLength, ); - - lBuffer = PacketBufferHandle::New(aDesiredLength); - VerifyOrExit(!lBuffer.IsNull(), ); + PacketBufferHandle lBuffer = PacketBufferHandle::New(aDesiredLength); + VerifyOrReturnError(!lBuffer.IsNull(), lBuffer); aDesiredLength = min(lBuffer->MaxDataLength(), aDesiredLength); @@ -178,18 +170,13 @@ static PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength, uint16_t aPatt lBuffer->SetDataLength(aDesiredLength); -exit: return lBuffer; } static PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength, uint16_t aPatternStartOffset) { constexpr uint8_t lFirstValue = 0; - PacketBufferHandle lBuffer = MakeDataBuffer(aDesiredLength, aPatternStartOffset, lFirstValue); - VerifyOrExit(!lBuffer.IsNull(), ); - -exit: - return (lBuffer); + return MakeDataBuffer(aDesiredLength, aPatternStartOffset, lFirstValue); } template @@ -251,7 +238,6 @@ PacketBufferHandle MakeDataBuffer(uint16_t aDesiredLength) static bool HandleDataReceived(const PacketBufferHandle & aBuffer, TransferStats & aStats, bool aStatsByPacket, bool aCheckBuffer, uint16_t aPatternStartOffset, uint8_t aFirstValue) { - bool lStatus = true; uint16_t lTotalDataLength = 0; // Walk through each buffer in the packet chain, checking the @@ -260,17 +246,15 @@ static bool HandleDataReceived(const PacketBufferHandle & aBuffer, TransferStats for (PacketBufferHandle lBuffer = aBuffer.Retain(); !lBuffer.IsNull(); lBuffer.Advance()) { const uint16_t lDataLength = lBuffer->DataLength(); + const uint8_t * const p = lBuffer->Start(); - if (aCheckBuffer) + if (aCheckBuffer && !CheckDataBufferPattern(p, lDataLength, aPatternStartOffset, aFirstValue)) { - const uint8_t * p = lBuffer->Start(); - - lStatus = CheckDataBufferPattern(p, lDataLength, aPatternStartOffset, aFirstValue); - VerifyOrExit(lStatus == true, ); + return false; } - lTotalDataLength = static_cast(lTotalDataLength + lBuffer->DataLength()); - aFirstValue = static_cast(aFirstValue + lBuffer->DataLength()); + lTotalDataLength = static_cast(lTotalDataLength + lDataLength); + aFirstValue = static_cast(aFirstValue + lDataLength); } // If we are accumulating stats by packet rather than by size, @@ -278,8 +262,7 @@ static bool HandleDataReceived(const PacketBufferHandle & aBuffer, TransferStats aStats.mReceive.mActual += ((aStatsByPacket) ? 1 : lTotalDataLength); -exit: - return (lStatus); + return true; } static bool HandleICMPDataReceived(PacketBufferHandle aBuffer, uint16_t aHeaderLength, TransferStats & aStats, bool aStatsByPacket, diff --git a/src/inet/tests/TestInetLayerMulticast.cpp b/src/inet/tests/TestInetLayerMulticast.cpp index 4f3f9a038cc898..fa40b95bc2ab6e 100644 --- a/src/inet/tests/TestInetLayerMulticast.cpp +++ b/src/inet/tests/TestInetLayerMulticast.cpp @@ -470,14 +470,11 @@ static bool HandleOption(const char * aProgram, OptionSet * aOptions, int aIdent bool HandleNonOptionArgs(const char * aProgram, int argc, char * argv[]) { - bool retval = true; - if ((gOptFlags & (kOptFlagListen | kOptFlagNoLoopback)) == (kOptFlagListen | kOptFlagNoLoopback)) { PrintArgError("%s: the listen option is exclusive with the loopback suppression option. Please select one or the other.\n", aProgram); - retval = false; - goto exit; + return false; } // If there were any additional, non-parsed arguments, it's an error. @@ -485,8 +482,7 @@ bool HandleNonOptionArgs(const char * aProgram, int argc, char * argv[]) if (argc > 0) { PrintArgError("%s: unexpected argument: %s\n", aProgram, argv[0]); - retval = false; - goto exit; + return false; } // If no IP version or transport flags were specified, use the defaults. @@ -496,8 +492,7 @@ bool HandleNonOptionArgs(const char * aProgram, int argc, char * argv[]) gOptFlags |= kOptFlagsDefault; } -exit: - return (retval); + return true; } // Create an IPv4 administratively-scoped multicast address @@ -535,47 +530,40 @@ static void SetGroup(GroupAddress & aGroupAddress, uint32_t aGroupIdentifier, ui static bool ParseGroupOpt(const char * aProgram, const char * aValue, bool aIPv6, uint32_t & aOutLastGroupIndex) { uint32_t lGroupIdentifier; - bool lRetval = true; if (sGroupAddresses.mSize == sGroupAddresses.mCapacity) { PrintArgError("%s: the maximum number of allowed groups (%zu) have been specified\n", aProgram, sGroupAddresses.mCapacity); - lRetval = false; - goto exit; + return false; } if (!ParseInt(aValue, lGroupIdentifier)) { PrintArgError("%s: unrecognized group %s\n", aProgram, aValue); - lRetval = false; - goto exit; + return false; } aOutLastGroupIndex = sGroupAddresses.mSize++; SetGroup(sGroupAddresses.mAddresses[aOutLastGroupIndex], lGroupIdentifier, lGroupIdentifier, lGroupIdentifier); -exit: - return (lRetval); + return true; } static bool ParseAndUpdateExpectedGroupPackets(const char * aProgram, const char * aValue, uint32_t aGroup, const char * aDescription, uint32_t & aOutExpected) { uint32_t lExpectedGroupPackets; - bool lRetval = true; if (!ParseInt(aValue, lExpectedGroupPackets)) { PrintArgError("%s: invalid value specified for expected group %u %s packets: %s\n", aProgram, aGroup, aDescription, aValue); - lRetval = false; - goto exit; + return false; } aOutExpected = lExpectedGroupPackets; -exit: - return (lRetval); + return true; } static GroupAddress * FindGroupAddress(const IPAddress & aSourceAddress) @@ -604,33 +592,25 @@ static void PrintReceivedStats(const GroupAddress & aGroupAddress) static bool HandleDataReceived(const PacketBufferHandle & aBuffer, GroupAddress & aGroupAddress, bool aCheckBuffer) { - const bool lStatsByPacket = true; - bool lStatus = true; - - lStatus = Common::HandleDataReceived(aBuffer, aGroupAddress.mStats, lStatsByPacket, aCheckBuffer); - VerifyOrExit(lStatus == true, ); + constexpr bool lStatsByPacket = true; + if (!Common::HandleDataReceived(aBuffer, aGroupAddress.mStats, lStatsByPacket, aCheckBuffer)) + { + return false; + } PrintReceivedStats(aGroupAddress); -exit: - return (lStatus); + return true; } static bool HandleDataReceived(const PacketBufferHandle & aBuffer, const IPPacketInfo & aPacketInfo, bool aCheckBuffer) { - bool lStatus = true; - GroupAddress * lGroupAddress; - - lGroupAddress = FindGroupAddress(aPacketInfo.DestAddress); - + GroupAddress * const lGroupAddress = FindGroupAddress(aPacketInfo.DestAddress); if (lGroupAddress != nullptr) { - lStatus = HandleDataReceived(aBuffer, *lGroupAddress, aCheckBuffer); - VerifyOrExit(lStatus == true, ); + return HandleDataReceived(aBuffer, *lGroupAddress, aCheckBuffer); } - -exit: - return (lStatus); + return true; } // Raw Endpoint Callbacks @@ -747,7 +727,6 @@ static INET_ERROR PrepareTransportForSend() static INET_ERROR DriveSendForDestination(const IPAddress & aAddress, uint16_t aSize) { PacketBufferHandle lBuffer; - INET_ERROR lStatus = INET_NO_ERROR; if ((gOptFlags & (kOptFlagUseRawIP)) == (kOptFlagUseRawIP)) { @@ -759,48 +738,40 @@ static INET_ERROR DriveSendForDestination(const IPAddress & aAddress, uint16_t a if ((gOptFlags & kOptFlagUseIPv6) == (kOptFlagUseIPv6)) { lBuffer = Common::MakeICMPv6DataBuffer(aSize); - VerifyOrExit(!lBuffer.IsNull(), lStatus = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(!lBuffer.IsNull(), INET_ERROR_NO_MEMORY); } #if INET_CONFIG_ENABLE_IPV4 else if ((gOptFlags & kOptFlagUseIPv4) == (kOptFlagUseIPv4)) { lBuffer = Common::MakeICMPv4DataBuffer(aSize); - VerifyOrExit(!lBuffer.IsNull(), lStatus = INET_ERROR_NO_MEMORY); + VerifyOrReturnError(!lBuffer.IsNull(), INET_ERROR_NO_MEMORY); } #endif // INET_CONFIG_ENABLE_IPV4 - lStatus = sRawIPEndPoint->SendTo(aAddress, std::move(lBuffer)); - SuccessOrExit(lStatus); + return sRawIPEndPoint->SendTo(aAddress, std::move(lBuffer)); } - else + + if ((gOptFlags & kOptFlagUseUDPIP) == kOptFlagUseUDPIP) { - if ((gOptFlags & kOptFlagUseUDPIP) == kOptFlagUseUDPIP) - { - const uint8_t lFirstValue = 0; + const uint8_t lFirstValue = 0; - // For UDP, we'll send n aSize or smaller datagrams, each - // patterned from zero to aSize - 1. + // For UDP, we'll send n aSize or smaller datagrams, each + // patterned from zero to aSize - 1. - lBuffer = Common::MakeDataBuffer(aSize, lFirstValue); - VerifyOrExit(!lBuffer.IsNull(), lStatus = INET_ERROR_NO_MEMORY); + lBuffer = Common::MakeDataBuffer(aSize, lFirstValue); + VerifyOrReturnError(!lBuffer.IsNull(), INET_ERROR_NO_MEMORY); - lStatus = sUDPIPEndPoint->SendTo(aAddress, kUDPPort, std::move(lBuffer)); - SuccessOrExit(lStatus); - } + return sUDPIPEndPoint->SendTo(aAddress, kUDPPort, std::move(lBuffer)); } -exit: - return (lStatus); + return INET_NO_ERROR; } static INET_ERROR DriveSendForGroup(GroupAddress & aGroupAddress) { - INET_ERROR lStatus = INET_NO_ERROR; - if (aGroupAddress.mStats.mTransmit.mActual < aGroupAddress.mStats.mTransmit.mExpected) { - lStatus = DriveSendForDestination(aGroupAddress.mMulticastAddress, gSendSize); - SuccessOrExit(lStatus); + ReturnErrorOnFailure(DriveSendForDestination(aGroupAddress.mMulticastAddress, gSendSize)); aGroupAddress.mStats.mTransmit.mActual++; @@ -808,28 +779,20 @@ static INET_ERROR DriveSendForGroup(GroupAddress & aGroupAddress) aGroupAddress.mStats.mTransmit.mExpected, aGroupAddress.mGroup); } -exit: - return (lStatus); + return INET_NO_ERROR; } template static INET_ERROR DriveSendForGroups(GroupAddresses & aGroupAddresses) { - INET_ERROR lStatus = INET_NO_ERROR; - // Iterate over each multicast group for which this node is a // member and send a packet. - for (size_t i = 0; i < aGroupAddresses.mSize; i++) { - GroupAddress & lGroupAddress = aGroupAddresses.mAddresses[i]; - - lStatus = DriveSendForGroup(lGroupAddress); - SuccessOrExit(lStatus); + ReturnErrorOnFailure(DriveSendForGroup(aGroupAddresses.mAddresses[i])); } -exit: - return (lStatus); + return INET_NO_ERROR; } void DriveSend() diff --git a/src/inet/tests/TestSetupFaultInjectionPosix.cpp b/src/inet/tests/TestSetupFaultInjectionPosix.cpp index 6a525bd4b38ced..e3aac9690140ed 100644 --- a/src/inet/tests/TestSetupFaultInjectionPosix.cpp +++ b/src/inet/tests/TestSetupFaultInjectionPosix.cpp @@ -68,13 +68,13 @@ static void RebootCallbackFn() if (!lArgv.Alloc(static_cast(sRestartCallbackCtx.mArgc + 2))) { printf("** failed to allocate memory **\n"); - ExitNow(); + return; } if (gSigusr1Received) { printf("** skipping restart case after SIGUSR1 **\n"); - ExitNow(); + return; } for (i = 0; sRestartCallbackCtx.mArgv[i] != nullptr; i++) @@ -108,9 +108,6 @@ static void RebootCallbackFn() printf("********** Restarting *********\n"); fflush(stdout); execvp(lArgv[0], lArgv.Get()); - -exit: - return; } static void PostInjectionCallbackFn(nl::FaultInjection::Manager * aManager, nl::FaultInjection::Identifier aId, diff --git a/src/lib/asn1/ASN1Writer.cpp b/src/lib/asn1/ASN1Writer.cpp index 09cb6af05078ef..09e3d08a5580d8 100644 --- a/src/lib/asn1/ASN1Writer.cpp +++ b/src/lib/asn1/ASN1Writer.cpp @@ -335,16 +335,13 @@ ASN1_ERROR ASN1Writer::PutNull() ASN1_ERROR ASN1Writer::PutConstructedType(const uint8_t * val, uint16_t valLen) { - ASN1_ERROR err = ASN1_NO_ERROR; - // Do nothing for a null writer. - VerifyOrExit(mBuf != nullptr, err = ASN1_NO_ERROR); + VerifyOrReturnError(mBuf != nullptr, ASN1_NO_ERROR); memcpy(mWritePoint, val, valLen); mWritePoint += valLen; -exit: - return err; + return ASN1_NO_ERROR; } ASN1_ERROR ASN1Writer::StartConstructedType(uint8_t cls, uint32_t tag) diff --git a/src/lib/core/CHIPTLVUtilities.cpp b/src/lib/core/CHIPTLVUtilities.cpp index 0b7d6797e2c7ed..32d428f9ca02c6 100644 --- a/src/lib/core/CHIPTLVUtilities.cpp +++ b/src/lib/core/CHIPTLVUtilities.cpp @@ -65,34 +65,31 @@ static CHIP_ERROR Iterate(TLVReader & aReader, size_t aDepth, IterateHandler aHa if (aReader.GetType() == kTLVType_NotSpecified) { - retval = aReader.Next(); - SuccessOrExit(retval); + ReturnErrorOnFailure(aReader.Next()); } do { const TLVType theType = aReader.GetType(); - retval = (aHandler)(aReader, aDepth, aContext); - SuccessOrExit(retval); + ReturnErrorOnFailure((aHandler)(aReader, aDepth, aContext)); if (aRecurse && TLVTypeIsContainer(theType)) { TLVType containerType; - retval = aReader.EnterContainer(containerType); - SuccessOrExit(retval); + ReturnErrorOnFailure(aReader.EnterContainer(containerType)); retval = Iterate(aReader, aDepth + 1, aHandler, aContext, aRecurse); - if (retval != CHIP_END_OF_TLV) - SuccessOrExit(retval); + if ((retval != CHIP_END_OF_TLV) && (retval != CHIP_NO_ERROR)) + { + return retval; + } - retval = aReader.ExitContainer(containerType); - SuccessOrExit(retval); + ReturnErrorOnFailure(aReader.ExitContainer(containerType)); } } while ((retval = aReader.Next()) == CHIP_NO_ERROR); -exit: return retval; } @@ -149,18 +146,13 @@ CHIP_ERROR Iterate(const TLVReader & aReader, IterateHandler aHandler, void * aC */ CHIP_ERROR Iterate(const TLVReader & aReader, IterateHandler aHandler, void * aContext, const bool aRecurse) { - const size_t depth = 0; - TLVReader temp; - CHIP_ERROR retval = CHIP_ERROR_NOT_IMPLEMENTED; - - VerifyOrExit(aHandler != nullptr, retval = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(aHandler != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + TLVReader temp; temp.Init(aReader); - retval = Iterate(temp, depth, aHandler, aContext, aRecurse); - -exit: - return retval; + constexpr size_t depth = 0; + return Iterate(temp, depth, aHandler, aContext, aRecurse); } /** @@ -179,14 +171,11 @@ CHIP_ERROR Iterate(const TLVReader & aReader, IterateHandler aHandler, void * aC */ static CHIP_ERROR CountHandler(const TLVReader & aReader, size_t aDepth, void * aContext) { - CHIP_ERROR retval = CHIP_NO_ERROR; - - VerifyOrExit(aContext != nullptr, retval = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(aContext != nullptr, CHIP_ERROR_INVALID_ARGUMENT); *static_cast(aContext) += 1; -exit: - return retval; + return CHIP_NO_ERROR; } /** @@ -205,12 +194,8 @@ static CHIP_ERROR CountHandler(const TLVReader & aReader, size_t aDepth, void * */ CHIP_ERROR Count(const TLVReader & aReader, size_t & aCount) { - const bool recurse = true; - CHIP_ERROR retval; - - retval = Count(aReader, aCount, recurse); - - return retval; + constexpr bool recurse = true; + return Count(aReader, aCount, recurse); } /** @@ -232,11 +217,9 @@ CHIP_ERROR Count(const TLVReader & aReader, size_t & aCount) */ CHIP_ERROR Count(const TLVReader & aReader, size_t & aCount, const bool aRecurse) { - CHIP_ERROR retval; - aCount = 0; - retval = Iterate(aReader, CountHandler, &aCount, aRecurse); + CHIP_ERROR retval = Iterate(aReader, CountHandler, &aCount, aRecurse); if (retval == CHIP_END_OF_TLV) retval = CHIP_NO_ERROR; @@ -261,20 +244,17 @@ CHIP_ERROR Count(const TLVReader & aReader, size_t & aCount, const bool aRecurse */ static CHIP_ERROR FindHandler(const TLVReader & aReader, size_t aDepth, void * aContext) { - const FindContext * theContext = static_cast(aContext); - CHIP_ERROR retval = CHIP_NO_ERROR; - - VerifyOrExit(aContext != nullptr, retval = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(aContext != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + const FindContext * const theContext = static_cast(aContext); if (theContext->mTag == aReader.GetTag()) { theContext->mReader.Init(aReader); // terminate the iteration when the specified tag is found - retval = CHIP_ERROR_MAX; + return CHIP_ERROR_MAX; } -exit: - return retval; + return CHIP_NO_ERROR; } /** @@ -294,12 +274,8 @@ static CHIP_ERROR FindHandler(const TLVReader & aReader, size_t aDepth, void * a */ CHIP_ERROR Find(const TLVReader & aReader, const uint64_t & aTag, TLVReader & aResult) { - const bool recurse = true; - CHIP_ERROR retval; - - retval = Find(aReader, aTag, aResult, recurse); - - return retval; + constexpr bool recurse = true; + return Find(aReader, aTag, aResult, recurse); } /** @@ -324,9 +300,7 @@ CHIP_ERROR Find(const TLVReader & aReader, const uint64_t & aTag, TLVReader & aR CHIP_ERROR Find(const TLVReader & aReader, const uint64_t & aTag, TLVReader & aResult, const bool aRecurse) { FindContext theContext = { aTag, aResult }; - CHIP_ERROR retval; - - retval = Iterate(aReader, FindHandler, &theContext, aRecurse); + CHIP_ERROR retval = Iterate(aReader, FindHandler, &theContext, aRecurse); if (retval == CHIP_ERROR_MAX) retval = CHIP_NO_ERROR; diff --git a/src/lib/core/tests/TestCHIPTLV.cpp b/src/lib/core/tests/TestCHIPTLV.cpp index d1a0f47c1899a9..3c43c268065029 100644 --- a/src/lib/core/tests/TestCHIPTLV.cpp +++ b/src/lib/core/tests/TestCHIPTLV.cpp @@ -3725,12 +3725,12 @@ static void TLVReaderFuzzTest(nlTestSuite * inSuite, void * inContext) { printf("Unexpected success of fuzz test: offset %u, original value 0x%02X, mutated value 0x%02X\n", static_cast(i), static_cast(origVal), static_cast(fuzzedData[i])); - ExitNow(); + return; } time(&now); if (now >= endTime) - ExitNow(); + return; fuzzedData[i] = origVal; } @@ -3738,9 +3738,6 @@ static void TLVReaderFuzzTest(nlTestSuite * inSuite, void * inContext) if (m < sizeof(sFixedFuzzVals)) m++; } - -exit: - return; } // Test Suite diff --git a/src/lib/support/LifetimePersistedCounter.cpp b/src/lib/support/LifetimePersistedCounter.cpp index 3ac866ddb2f408..0f141e5f4e471d 100644 --- a/src/lib/support/LifetimePersistedCounter.cpp +++ b/src/lib/support/LifetimePersistedCounter.cpp @@ -33,54 +33,38 @@ LifetimePersistedCounter::~LifetimePersistedCounter() {} CHIP_ERROR LifetimePersistedCounter::Init(const chip::Platform::PersistedStorage::Key aId) { - CHIP_ERROR err = CHIP_NO_ERROR; - mId = aId; uint32_t startValue; // Read our previously-stored starting value. - SuccessOrExit(err = ReadStartValue(startValue)); + ReturnErrorOnFailure(ReadStartValue(startValue)); // This will set the starting value, after which we're ready. - SuccessOrExit(err = MonotonicallyIncreasingCounter::Init(startValue)); - -exit: - return err; + return MonotonicallyIncreasingCounter::Init(startValue); } CHIP_ERROR LifetimePersistedCounter::Advance() { - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(mId != chip::Platform::PersistedStorage::kEmptyKey, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mId != chip::Platform::PersistedStorage::kEmptyKey, CHIP_ERROR_INCORRECT_STATE); - SuccessOrExit(err = MonotonicallyIncreasingCounter::Advance()); + ReturnErrorOnFailure(MonotonicallyIncreasingCounter::Advance()); - SuccessOrExit(err = chip::Platform::PersistedStorage::Write(mId, GetValue())); -exit: - return err; + return chip::Platform::PersistedStorage::Write(mId, GetValue()); } CHIP_ERROR LifetimePersistedCounter::ReadStartValue(uint32_t & aStartValue) { - CHIP_ERROR err = CHIP_NO_ERROR; - aStartValue = 0; - err = chip::Platform::PersistedStorage::Read(mId, aStartValue); + CHIP_ERROR err = chip::Platform::PersistedStorage::Read(mId, aStartValue); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { // No previously-stored value, no worries, the counter is initialized to zero. // Suppress the error. err = CHIP_NO_ERROR; } - else - { - SuccessOrExit(err); - } -exit: return err; } diff --git a/src/lib/support/PersistedCounter.cpp b/src/lib/support/PersistedCounter.cpp index 1f8ba575d99b1d..17569a29d1891f 100644 --- a/src/lib/support/PersistedCounter.cpp +++ b/src/lib/support/PersistedCounter.cpp @@ -34,8 +34,7 @@ PersistedCounter::~PersistedCounter() {} CHIP_ERROR PersistedCounter::Init(const chip::Platform::PersistedStorage::Key aId, uint32_t aEpoch) { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(aEpoch > 0, err = CHIP_ERROR_INVALID_INTEGER_VALUE); + VerifyOrReturnError(aEpoch > 0, CHIP_ERROR_INVALID_INTEGER_VALUE); // Store the ID. mId = aId; @@ -44,47 +43,36 @@ PersistedCounter::Init(const chip::Platform::PersistedStorage::Key aId, uint32_t uint32_t startValue; // Read our previously-stored starting value. - err = ReadStartValue(startValue); - SuccessOrExit(err); + ReturnErrorOnFailure(ReadStartValue(startValue)); #if CHIP_CONFIG_PERSISTED_COUNTER_DEBUG_LOGGING ChipLogDetail(EventLogging, "PersistedCounter::Init() aEpoch 0x%x startValue 0x%x", aEpoch, startValue); #endif - err = PersistNextEpochStart(startValue + aEpoch); - SuccessOrExit(err); + ReturnErrorOnFailure(PersistNextEpochStart(startValue + aEpoch)); // This will set the starting value, after which we're ready. - err = MonotonicallyIncreasingCounter::Init(startValue); - SuccessOrExit(err); - -exit: - return err; + return MonotonicallyIncreasingCounter::Init(startValue); } CHIP_ERROR PersistedCounter::Advance() { - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(mId != chip::Platform::PersistedStorage::kEmptyKey, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mId != chip::Platform::PersistedStorage::kEmptyKey, CHIP_ERROR_INCORRECT_STATE); - err = MonotonicallyIncreasingCounter::Advance(); - SuccessOrExit(err); + ReturnErrorOnFailure(MonotonicallyIncreasingCounter::Advance()); if (GetValue() >= mNextEpoch) { // Value advanced past the previously persisted "start point". // Ensure that a new starting point is persisted. - err = PersistNextEpochStart(mNextEpoch + mEpoch); - SuccessOrExit(err); + ReturnErrorOnFailure(PersistNextEpochStart(mNextEpoch + mEpoch)); // Advancing the epoch should have ensured that the current value // is valid - VerifyOrExit(GetValue() < mNextEpoch, err = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(GetValue() < mNextEpoch, CHIP_ERROR_INTERNAL); } -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR @@ -101,11 +89,9 @@ PersistedCounter::PersistNextEpochStart(uint32_t aStartValue) CHIP_ERROR PersistedCounter::ReadStartValue(uint32_t & aStartValue) { - CHIP_ERROR err = CHIP_NO_ERROR; - aStartValue = 0; - err = chip::Platform::PersistedStorage::Read(mId, aStartValue); + CHIP_ERROR err = chip::Platform::PersistedStorage::Read(mId, aStartValue); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { // No previously-stored value, no worries, the counter is initialized to zero. @@ -114,15 +100,14 @@ PersistedCounter::ReadStartValue(uint32_t & aStartValue) } else { - SuccessOrExit(err); + ReturnErrorOnFailure(err); } #if CHIP_CONFIG_PERSISTED_COUNTER_DEBUG_LOGGING ChipLogDetail(EventLogging, "PersistedCounter::ReadStartValue() aStartValue 0x%x", aStartValue); #endif -exit: - return err; + return CHIP_NO_ERROR; } } // namespace chip diff --git a/src/lib/support/SerializableIntegerSet.cpp b/src/lib/support/SerializableIntegerSet.cpp index b5a0e38f59c3e9..3948c5bad92a76 100644 --- a/src/lib/support/SerializableIntegerSet.cpp +++ b/src/lib/support/SerializableIntegerSet.cpp @@ -65,11 +65,9 @@ uint16_t SerializableU64SetBase::FindIndex(uint64_t value) CHIP_ERROR SerializableU64SetBase::Insert(uint64_t value) { - CHIP_ERROR err = CHIP_ERROR_NO_MEMORY; - uint16_t index = 0; - VerifyOrExit(value != mEmptyValue, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(value != mEmptyValue, CHIP_ERROR_INVALID_ARGUMENT); - index = FirstAvailableForUniqueId(value); + const uint16_t index = FirstAvailableForUniqueId(value); if (index < mCapacity) { mData[index] = value; @@ -77,18 +75,17 @@ CHIP_ERROR SerializableU64SetBase::Insert(uint64_t value) { mNextAvailable = static_cast(index + 1); } - err = CHIP_NO_ERROR; + return CHIP_NO_ERROR; } -exit: - return err; + return CHIP_ERROR_NO_MEMORY; } void SerializableU64SetBase::Remove(uint64_t value) { if (value != mEmptyValue) { - uint16_t index = FindIndex(value); + const uint16_t index = FindIndex(value); if (index < mCapacity) { mData[index] = mEmptyValue; diff --git a/src/lib/support/TimeUtils.cpp b/src/lib/support/TimeUtils.cpp index c28ce6df17a64a..3e4e885601f6ce 100644 --- a/src/lib/support/TimeUtils.cpp +++ b/src/lib/support/TimeUtils.cpp @@ -545,18 +545,15 @@ void SecondsSinceEpochToCalendarTime(uint32_t secondsSinceEpoch, uint16_t & year bool CalendarToChipEpochTime(uint16_t year, uint8_t month, uint8_t dayOfMonth, uint8_t hour, uint8_t minute, uint8_t second, uint32_t & chipEpochTime) { - bool res = true; - uint32_t daysSinceUnixEpoch; - - VerifyOrExit(year >= kChipEpochBaseYear && year <= kChipEpochMaxYear, res = false); + VerifyOrReturnError(year >= kChipEpochBaseYear && year <= kChipEpochMaxYear, false); + uint32_t daysSinceUnixEpoch; CalendarDateToDaysSinceEpoch(year, month, dayOfMonth, daysSinceUnixEpoch); chipEpochTime = ((daysSinceUnixEpoch - kChipEpochDaysSinceUnixEpoch) * kSecondsPerDay) + (hour * kSecondsPerHour) + (minute * kSecondsPerMinute) + second; -exit: - return res; + return true; } void ChipEpochToCalendarTime(uint32_t chipEpochTime, uint16_t & year, uint8_t & month, uint8_t & dayOfMonth, uint8_t & hour, @@ -568,14 +565,11 @@ void ChipEpochToCalendarTime(uint32_t chipEpochTime, uint16_t & year, uint8_t & bool UnixEpochToChipEpochTime(uint32_t unixEpochTime, uint32_t & chipEpochTime) { - bool res = true; - - VerifyOrExit(unixEpochTime >= kChipEpochSecondsSinceUnixEpoch, res = false); + VerifyOrReturnError(unixEpochTime >= kChipEpochSecondsSinceUnixEpoch, false); chipEpochTime = unixEpochTime - kChipEpochSecondsSinceUnixEpoch; -exit: - return res; + return true; } } // namespace chip diff --git a/src/lib/support/tests/TestPersistedStorageImplementation.cpp b/src/lib/support/tests/TestPersistedStorageImplementation.cpp index bedae432ec4cd1..d8310aa42452cf 100644 --- a/src/lib/support/tests/TestPersistedStorageImplementation.cpp +++ b/src/lib/support/tests/TestPersistedStorageImplementation.cpp @@ -61,7 +61,6 @@ static void RemoveEndOfLineSymbol(char * str) static CHIP_ERROR GetCounterValueFromFile(const char * aKey, uint32_t & aValue) { - CHIP_ERROR err = CHIP_NO_ERROR; char key[CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH]; char value[CHIP_CONFIG_PERSISTED_STORAGE_MAX_VALUE_LENGTH]; @@ -75,24 +74,18 @@ static CHIP_ERROR GetCounterValueFromFile(const char * aKey, uint32_t & aValue) { if (fgets(value, sizeof(value), sPersistentStoreFile) == nullptr) { - err = CHIP_ERROR_PERSISTED_STORAGE_FAILED; + return CHIP_ERROR_PERSISTED_STORAGE_FAILED; } - else - { - RemoveEndOfLineSymbol(value); + RemoveEndOfLineSymbol(value); - if (!ParseInt(value, aValue, 0)) - err = CHIP_ERROR_PERSISTED_STORAGE_FAILED; - } + if (!ParseInt(value, aValue, 0)) + return CHIP_ERROR_PERSISTED_STORAGE_FAILED; - ExitNow(); + return CHIP_NO_ERROR; } } - err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; - -exit: - return err; + return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; } static CHIP_ERROR SaveCounterValueToFile(const char * aKey, uint32_t aValue) @@ -142,8 +135,8 @@ CHIP_ERROR Read(const char * aKey, uint32_t & aValue) CHIP_ERROR err = CHIP_NO_ERROR; std::map::iterator it; - VerifyOrExit(aKey != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(strlen(aKey) <= CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH, err = CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(aKey != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(strlen(aKey) <= CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH, CHIP_ERROR_INVALID_STRING_LENGTH); if (sPersistentStoreFile) { @@ -152,14 +145,13 @@ CHIP_ERROR Read(const char * aKey, uint32_t & aValue) else { it = sPersistentStore.find(aKey); - VerifyOrExit(it != sPersistentStore.end(), err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(it != sPersistentStore.end(), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); size_t aValueLength = Base64Decode(it->second.c_str(), static_cast(it->second.length()), reinterpret_cast(&aValue)); - VerifyOrExit(aValueLength == sizeof(uint32_t), err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrReturnError(aValueLength == sizeof(uint32_t), CHIP_ERROR_PERSISTED_STORAGE_FAILED); } -exit: return err; } @@ -167,8 +159,8 @@ CHIP_ERROR Write(const char * aKey, uint32_t aValue) { CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(aKey != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(strlen(aKey) <= CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH, err = CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(aKey != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(strlen(aKey) <= CHIP_CONFIG_PERSISTED_STORAGE_MAX_KEY_LENGTH, CHIP_ERROR_INVALID_STRING_LENGTH); if (sPersistentStoreFile) { @@ -184,7 +176,6 @@ CHIP_ERROR Write(const char * aKey, uint32_t aValue) sPersistentStore[aKey] = encodedValue; } -exit: return err; } diff --git a/src/protocols/bdx/BdxTransferSession.cpp b/src/protocols/bdx/BdxTransferSession.cpp index 0cb18883e8c442..4cfcde276a4292 100644 --- a/src/protocols/bdx/BdxTransferSession.cpp +++ b/src/protocols/bdx/BdxTransferSession.cpp @@ -49,11 +49,7 @@ CHIP_ERROR AttachHeader(chip::Protocols::Id protocolId, uint8_t msgType, ::chip: payloadHeader.SetMessageType(protocolId, msgType); - CHIP_ERROR err = payloadHeader.EncodeBeforeData(msgBuf); - SuccessOrExit(err); - -exit: - return err; + return payloadHeader.EncodeBeforeData(msgBuf); } template @@ -141,11 +137,7 @@ void TransferSession::PollOutput(OutputEvent & event, uint64_t curTimeMs) CHIP_ERROR TransferSession::StartTransfer(TransferRole role, const TransferInitData & initData, uint32_t timeoutMs) { - CHIP_ERROR err = CHIP_NO_ERROR; - MessageType msgType; - TransferInit initMsg; - - VerifyOrExit(mState == TransferState::kUnitialized, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mState == TransferState::kUnitialized, CHIP_ERROR_INCORRECT_STATE); mRole = role; mTimeoutMs = timeoutMs; @@ -157,6 +149,7 @@ CHIP_ERROR TransferSession::StartTransfer(TransferRole role, const TransferInitD mTransferLength = initData.Length; // Prepare TransferInit message + TransferInit initMsg; initMsg.TransferCtlOptions = initData.TransferCtlFlags; initMsg.Version = kBdxVersion; initMsg.MaxBlockSize = mMaxSupportedBlockSize; @@ -167,28 +160,23 @@ CHIP_ERROR TransferSession::StartTransfer(TransferRole role, const TransferInitD initMsg.Metadata = initData.Metadata; initMsg.MetadataLength = initData.MetadataLength; - err = WriteToPacketBuffer(initMsg, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(WriteToPacketBuffer(initMsg, mPendingMsgHandle)); - msgType = (mRole == TransferRole::kSender) ? MessageType::SendInit : MessageType::ReceiveInit; - err = AttachHeader(msgType, mPendingMsgHandle); - SuccessOrExit(err); + const MessageType msgType = (mRole == TransferRole::kSender) ? MessageType::SendInit : MessageType::ReceiveInit; + ReturnErrorOnFailure(AttachHeader(msgType, mPendingMsgHandle)); mState = TransferState::kAwaitingAccept; mAwaitingResponse = true; mPendingOutput = OutputEventType::kMsgToSend; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR TransferSession::WaitForTransfer(TransferRole role, BitFlags xferControlOpts, uint16_t maxBlockSize, uint32_t timeoutMs) { - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(mState == TransferState::kUnitialized, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mState == TransferState::kUnitialized, CHIP_ERROR_INCORRECT_STATE); // Used to determine compatibility with any future TransferInit parameters mRole = role; @@ -198,23 +186,20 @@ CHIP_ERROR TransferSession::WaitForTransfer(TransferRole role, BitFlags proposedControlOpts(mTransferRequestData.TransferCtlFlags); - VerifyOrExit(mState == TransferState::kNegotiateTransferParams, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mState == TransferState::kNegotiateTransferParams, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mPendingOutput == OutputEventType::kNone, CHIP_ERROR_INCORRECT_STATE); // Don't allow a Control method that wasn't supported by the initiator // MaxBlockSize can't be larger than the proposed value - VerifyOrExit(proposedControlOpts.Has(acceptData.ControlMode), err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(acceptData.MaxBlockSize <= mTransferRequestData.MaxBlockSize, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(proposedControlOpts.Has(acceptData.ControlMode), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(acceptData.MaxBlockSize <= mTransferRequestData.MaxBlockSize, CHIP_ERROR_INVALID_ARGUMENT); mTransferMaxBlockSize = acceptData.MaxBlockSize; @@ -232,11 +217,9 @@ CHIP_ERROR TransferSession::AcceptTransfer(const TransferAcceptData & acceptData acceptMsg.Metadata = acceptData.Metadata; acceptMsg.MetadataLength = acceptData.MetadataLength; - err = WriteToPacketBuffer(acceptMsg, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(WriteToPacketBuffer(acceptMsg, mPendingMsgHandle)); - err = AttachHeader(MessageType::ReceiveAccept, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(AttachHeader(MessageType::ReceiveAccept, mPendingMsgHandle)); } else { @@ -247,11 +230,9 @@ CHIP_ERROR TransferSession::AcceptTransfer(const TransferAcceptData & acceptData acceptMsg.Metadata = acceptData.Metadata; acceptMsg.MetadataLength = acceptData.MetadataLength; - err = WriteToPacketBuffer(acceptMsg, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(WriteToPacketBuffer(acceptMsg, mPendingMsgHandle)); - err = AttachHeader(MessageType::SendAccept, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(AttachHeader(MessageType::SendAccept, mPendingMsgHandle)); } mPendingOutput = OutputEventType::kMsgToSend; @@ -264,61 +245,50 @@ CHIP_ERROR TransferSession::AcceptTransfer(const TransferAcceptData & acceptData mAwaitingResponse = true; } -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR TransferSession::PrepareBlockQuery() { - CHIP_ERROR err = CHIP_NO_ERROR; - BlockQuery queryMsg; - - VerifyOrExit(mState == TransferState::kTransferInProgress, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mRole == TransferRole::kReceiver, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(!mAwaitingResponse, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mState == TransferState::kTransferInProgress, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mRole == TransferRole::kReceiver, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mPendingOutput == OutputEventType::kNone, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mAwaitingResponse, CHIP_ERROR_INCORRECT_STATE); + BlockQuery queryMsg; queryMsg.BlockCounter = mNextQueryNum; - err = WriteToPacketBuffer(queryMsg, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(WriteToPacketBuffer(queryMsg, mPendingMsgHandle)); - err = AttachHeader(MessageType::BlockQuery, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(AttachHeader(MessageType::BlockQuery, mPendingMsgHandle)); mPendingOutput = OutputEventType::kMsgToSend; mAwaitingResponse = true; mLastQueryNum = mNextQueryNum++; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR TransferSession::PrepareBlock(const BlockData & inData) { - CHIP_ERROR err = CHIP_NO_ERROR; - DataBlock blockMsg; - MessageType msgType; - - VerifyOrExit(mState == TransferState::kTransferInProgress, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mRole == TransferRole::kSender, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(!mAwaitingResponse, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mState == TransferState::kTransferInProgress, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mRole == TransferRole::kSender, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mPendingOutput == OutputEventType::kNone, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mAwaitingResponse, CHIP_ERROR_INCORRECT_STATE); // Verify non-zero data is provided and is no longer than MaxBlockSize (BlockEOF may contain 0 length data) - VerifyOrExit((inData.Data != nullptr) && (inData.Length <= mTransferMaxBlockSize), err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((inData.Data != nullptr) && (inData.Length <= mTransferMaxBlockSize), CHIP_ERROR_INVALID_ARGUMENT); + DataBlock blockMsg; blockMsg.BlockCounter = mNextBlockNum; blockMsg.Data = inData.Data; blockMsg.DataLength = inData.Length; - err = WriteToPacketBuffer(blockMsg, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(WriteToPacketBuffer(blockMsg, mPendingMsgHandle)); - msgType = inData.IsEof ? MessageType::BlockEOF : MessageType::Block; - err = AttachHeader(msgType, mPendingMsgHandle); - SuccessOrExit(err); + const MessageType msgType = inData.IsEof ? MessageType::BlockEOF : MessageType::Block; + ReturnErrorOnFailure(AttachHeader(msgType, mPendingMsgHandle)); mPendingOutput = OutputEventType::kMsgToSend; @@ -330,29 +300,23 @@ CHIP_ERROR TransferSession::PrepareBlock(const BlockData & inData) mAwaitingResponse = true; mLastBlockNum = mNextBlockNum++; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR TransferSession::PrepareBlockAck() { - CHIP_ERROR err = CHIP_NO_ERROR; - CounterMessage ackMsg; - MessageType msgType; + VerifyOrReturnError(mRole == TransferRole::kReceiver, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError((mState == TransferState::kTransferInProgress) || (mState == TransferState::kReceivedEOF), + CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mPendingOutput == OutputEventType::kNone, CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mRole == TransferRole::kReceiver, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit((mState == TransferState::kTransferInProgress) || (mState == TransferState::kReceivedEOF), - err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); - - ackMsg.BlockCounter = mLastBlockNum; - msgType = (mState == TransferState::kReceivedEOF) ? MessageType::BlockAckEOF : MessageType::BlockAck; + CounterMessage ackMsg; + ackMsg.BlockCounter = mLastBlockNum; + const MessageType msgType = (mState == TransferState::kReceivedEOF) ? MessageType::BlockAckEOF : MessageType::BlockAck; - err = WriteToPacketBuffer(ackMsg, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(WriteToPacketBuffer(ackMsg, mPendingMsgHandle)); - err = AttachHeader(msgType, mPendingMsgHandle); - SuccessOrExit(err); + ReturnErrorOnFailure(AttachHeader(msgType, mPendingMsgHandle)); if (mState == TransferState::kTransferInProgress) { @@ -372,22 +336,18 @@ CHIP_ERROR TransferSession::PrepareBlockAck() mPendingOutput = OutputEventType::kMsgToSend; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR TransferSession::AbortTransfer(StatusCode reason) { - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit((mState != TransferState::kUnitialized) && (mState != TransferState::kTransferDone) && - (mState != TransferState::kErrorState), - err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError((mState != TransferState::kUnitialized) && (mState != TransferState::kTransferDone) && + (mState != TransferState::kErrorState), + CHIP_ERROR_INCORRECT_STATE); PrepareStatusReport(reason); -exit: - return err; + return CHIP_NO_ERROR; } void TransferSession::Reset() @@ -417,43 +377,36 @@ void TransferSession::Reset() CHIP_ERROR TransferSession::HandleMessageReceived(System::PacketBufferHandle msg, uint64_t curTimeMs) { - CHIP_ERROR err = CHIP_NO_ERROR; - PayloadHeader payloadHeader; - - VerifyOrExit(!msg.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!msg.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); - err = payloadHeader.DecodeAndConsume(msg); - SuccessOrExit(err); + PayloadHeader payloadHeader; + ReturnErrorOnFailure(payloadHeader.DecodeAndConsume(msg)); if (payloadHeader.HasProtocol(Protocols::BDX::Id)) { - err = HandleBdxMessage(payloadHeader, std::move(msg)); - SuccessOrExit(err); + ReturnErrorOnFailure(HandleBdxMessage(payloadHeader, std::move(msg))); mTimeoutStartTimeMs = curTimeMs; } else if (payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::StatusReport)) { - err = HandleStatusReportMessage(payloadHeader, std::move(msg)); - SuccessOrExit(err); + ReturnErrorOnFailure(HandleStatusReportMessage(payloadHeader, std::move(msg))); } else { - err = CHIP_ERROR_INVALID_MESSAGE_TYPE; + return CHIP_ERROR_INVALID_MESSAGE_TYPE; } -exit: - return err; + return CHIP_NO_ERROR; } // Return CHIP_ERROR only if there was a problem decoding the message. Otherwise, call PrepareStatusReport(). CHIP_ERROR TransferSession::HandleBdxMessage(PayloadHeader & header, System::PacketBufferHandle msg) { - CHIP_ERROR err = CHIP_NO_ERROR; - MessageType msgType = static_cast(header.GetMessageType()); + VerifyOrReturnError(!msg.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mPendingOutput == OutputEventType::kNone, CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(!msg.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(mPendingOutput == OutputEventType::kNone, err = CHIP_ERROR_INCORRECT_STATE); + const MessageType msgType = static_cast(header.GetMessageType()); switch (msgType) { @@ -483,12 +436,10 @@ CHIP_ERROR TransferSession::HandleBdxMessage(PayloadHeader & header, System::Pac HandleBlockAckEOF(std::move(msg)); break; default: - err = CHIP_ERROR_INVALID_MESSAGE_TYPE; - break; + return CHIP_ERROR_INVALID_MESSAGE_TYPE; } -exit: - return err; + return CHIP_NO_ERROR; } /** @@ -518,22 +469,20 @@ CHIP_ERROR TransferSession::HandleStatusReportMessage(PayloadHeader & header, Sy void TransferSession::HandleTransferInit(MessageType msgType, System::PacketBufferHandle msgData) { - CHIP_ERROR err = CHIP_NO_ERROR; - TransferInit transferInit; - - VerifyOrExit(mState == TransferState::kAwaitingInitMsg, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mState == TransferState::kAwaitingInitMsg, PrepareStatusReport(StatusCode::kUnexpectedMessage)); if (mRole == TransferRole::kSender) { - VerifyOrExit(msgType == MessageType::ReceiveInit, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(msgType == MessageType::ReceiveInit, PrepareStatusReport(StatusCode::kUnexpectedMessage)); } else { - VerifyOrExit(msgType == MessageType::SendInit, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(msgType == MessageType::SendInit, PrepareStatusReport(StatusCode::kUnexpectedMessage)); } - err = transferInit.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + TransferInit transferInit; + const CHIP_ERROR err = transferInit.Parse(msgData.Retain()); + VerifyOrReturn(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); ResolveTransferControlOptions(transferInit.TransferCtlOptions); mTransferVersion = ::chip::min(kBdxVersion, transferInit.Version); @@ -557,25 +506,19 @@ void TransferSession::HandleTransferInit(MessageType msgType, System::PacketBuff mPendingOutput = OutputEventType::kInitReceived; mState = TransferState::kNegotiateTransferParams; - -exit: - return; } void TransferSession::HandleReceiveAccept(System::PacketBufferHandle msgData) { - CHIP_ERROR err = CHIP_NO_ERROR; - ReceiveAccept rcvAcceptMsg; - - VerifyOrExit(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mState == TransferState::kAwaitingAccept, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mState == TransferState::kAwaitingAccept, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - err = rcvAcceptMsg.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + ReceiveAccept rcvAcceptMsg; + const CHIP_ERROR err = rcvAcceptMsg.Parse(msgData.Retain()); + VerifyOrReturn(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); // Verify that Accept parameters are compatible with the original proposed parameters - err = VerifyProposedMode(rcvAcceptMsg.TransferCtlFlags); - SuccessOrExit(err); + ReturnOnFailure(VerifyProposedMode(rcvAcceptMsg.TransferCtlFlags)); mTransferMaxBlockSize = rcvAcceptMsg.MaxBlockSize; mStartOffset = rcvAcceptMsg.StartOffset; @@ -595,25 +538,19 @@ void TransferSession::HandleReceiveAccept(System::PacketBufferHandle msgData) mAwaitingResponse = (mControlMode == TransferControlFlags::kSenderDrive); mState = TransferState::kTransferInProgress; - -exit: - return; } void TransferSession::HandleSendAccept(System::PacketBufferHandle msgData) { - CHIP_ERROR err = CHIP_NO_ERROR; - SendAccept sendAcceptMsg; - - VerifyOrExit(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mState == TransferState::kAwaitingAccept, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mState == TransferState::kAwaitingAccept, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - err = sendAcceptMsg.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + SendAccept sendAcceptMsg; + const CHIP_ERROR err = sendAcceptMsg.Parse(msgData.Retain()); + VerifyOrReturn(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); // Verify that Accept parameters are compatible with the original proposed parameters - err = VerifyProposedMode(sendAcceptMsg.TransferCtlFlags); - SuccessOrExit(err); + ReturnOnFailure(VerifyProposedMode(sendAcceptMsg.TransferCtlFlags)); // Note: if VerifyProposedMode() returned with no error, then mControlMode must match the proposed mode in the SendAccept // message @@ -631,53 +568,44 @@ void TransferSession::HandleSendAccept(System::PacketBufferHandle msgData) mAwaitingResponse = (mControlMode == TransferControlFlags::kReceiverDrive); mState = TransferState::kTransferInProgress; - -exit: - return; } void TransferSession::HandleBlockQuery(System::PacketBufferHandle msgData) { - CHIP_ERROR err = CHIP_NO_ERROR; - BlockQuery query; - - VerifyOrExit(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - err = query.Parse(std::move(msgData)); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + BlockQuery query; + const CHIP_ERROR err = query.Parse(std::move(msgData)); + VerifyOrReturn(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); - VerifyOrExit(query.BlockCounter == mNextBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); + VerifyOrReturn(query.BlockCounter == mNextBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); mPendingOutput = OutputEventType::kQueryReceived; mAwaitingResponse = false; mLastQueryNum = query.BlockCounter; - -exit: - return; } void TransferSession::HandleBlock(System::PacketBufferHandle msgData) { - CHIP_ERROR err = CHIP_NO_ERROR; - Block blockMsg; - - VerifyOrExit(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - err = blockMsg.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + Block blockMsg; + const CHIP_ERROR err = blockMsg.Parse(msgData.Retain()); + VerifyOrReturn(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); - VerifyOrExit(blockMsg.BlockCounter == mLastQueryNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); - VerifyOrExit((blockMsg.DataLength > 0) && (blockMsg.DataLength <= mTransferMaxBlockSize), - PrepareStatusReport(StatusCode::kBadMessageContents)); + VerifyOrReturn(blockMsg.BlockCounter == mLastQueryNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); + VerifyOrReturn((blockMsg.DataLength > 0) && (blockMsg.DataLength <= mTransferMaxBlockSize), + PrepareStatusReport(StatusCode::kBadMessageContents)); if (IsTransferLengthDefinite()) { - VerifyOrExit(mNumBytesProcessed + blockMsg.DataLength <= mTransferLength, PrepareStatusReport(StatusCode::kLengthMismatch)); + VerifyOrReturn(mNumBytesProcessed + blockMsg.DataLength <= mTransferLength, + PrepareStatusReport(StatusCode::kLengthMismatch)); } mBlockEventData.Data = blockMsg.Data; @@ -691,25 +619,20 @@ void TransferSession::HandleBlock(System::PacketBufferHandle msgData) mLastBlockNum = blockMsg.BlockCounter; mAwaitingResponse = false; - -exit: - return; } void TransferSession::HandleBlockEOF(System::PacketBufferHandle msgData) { - CHIP_ERROR err = CHIP_NO_ERROR; - BlockEOF blockEOFMsg; - - VerifyOrExit(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mRole == TransferRole::kReceiver, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - err = blockEOFMsg.Parse(msgData.Retain()); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + BlockEOF blockEOFMsg; + const CHIP_ERROR err = blockEOFMsg.Parse(msgData.Retain()); + VerifyOrReturn(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); - VerifyOrExit(blockEOFMsg.BlockCounter == mLastQueryNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); - VerifyOrExit(blockEOFMsg.DataLength <= mTransferMaxBlockSize, PrepareStatusReport(StatusCode::kBadMessageContents)); + VerifyOrReturn(blockEOFMsg.BlockCounter == mLastQueryNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); + VerifyOrReturn(blockEOFMsg.DataLength <= mTransferMaxBlockSize, PrepareStatusReport(StatusCode::kBadMessageContents)); mBlockEventData.Data = blockEOFMsg.Data; mBlockEventData.Length = blockEOFMsg.DataLength; @@ -723,55 +646,42 @@ void TransferSession::HandleBlockEOF(System::PacketBufferHandle msgData) mAwaitingResponse = false; mState = TransferState::kReceivedEOF; - -exit: - return; } void TransferSession::HandleBlockAck(System::PacketBufferHandle msgData) { - CHIP_ERROR err = CHIP_NO_ERROR; - BlockAck ackMsg; - - VerifyOrExit(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mState == TransferState::kTransferInProgress, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - err = ackMsg.Parse(std::move(msgData)); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); - VerifyOrExit(ackMsg.BlockCounter == mLastBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); + BlockAck ackMsg; + const CHIP_ERROR err = ackMsg.Parse(std::move(msgData)); + VerifyOrReturn(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + VerifyOrReturn(ackMsg.BlockCounter == mLastBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); mPendingOutput = OutputEventType::kAckReceived; // In Receiver Drive, the Receiver can send a BlockAck to indicate receipt of the message and reset the timeout. // In this case, the Sender should wait to receive a BlockQuery next. mAwaitingResponse = (mControlMode == TransferControlFlags::kReceiverDrive); - -exit: - return; } void TransferSession::HandleBlockAckEOF(System::PacketBufferHandle msgData) { - CHIP_ERROR err = CHIP_NO_ERROR; - BlockAckEOF ackMsg; - - VerifyOrExit(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mState == TransferState::kAwaitingEOFAck, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - VerifyOrExit(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mRole == TransferRole::kSender, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mState == TransferState::kAwaitingEOFAck, PrepareStatusReport(StatusCode::kUnexpectedMessage)); + VerifyOrReturn(mAwaitingResponse, PrepareStatusReport(StatusCode::kUnexpectedMessage)); - err = ackMsg.Parse(std::move(msgData)); - VerifyOrExit(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); - VerifyOrExit(ackMsg.BlockCounter == mLastBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); + BlockAckEOF ackMsg; + const CHIP_ERROR err = ackMsg.Parse(std::move(msgData)); + VerifyOrReturn(err == CHIP_NO_ERROR, PrepareStatusReport(StatusCode::kBadMessageContents)); + VerifyOrReturn(ackMsg.BlockCounter == mLastBlockNum, PrepareStatusReport(StatusCode::kBadBlockCounter)); mPendingOutput = OutputEventType::kAckEOFReceived; mAwaitingResponse = false; mState = TransferState::kTransferDone; - -exit: - return; } void TransferSession::ResolveTransferControlOptions(const BitFlags & proposed) diff --git a/src/protocols/bdx/tests/TestBdxTransferSession.cpp b/src/protocols/bdx/tests/TestBdxTransferSession.cpp index 1dbf8348060ef8..b7ac4fd009e49a 100644 --- a/src/protocols/bdx/tests/TestBdxTransferSession.cpp +++ b/src/protocols/bdx/tests/TestBdxTransferSession.cpp @@ -30,65 +30,53 @@ const uint64_t tlvListTag = TLV::ProfileTag(7777, 8888); // Helper method for generating a complete TLV structure with a list containing a single tag and string CHIP_ERROR WriteChipTLVString(uint8_t * buf, uint32_t bufLen, const char * data, uint32_t & written) { - CHIP_ERROR err = CHIP_NO_ERROR; - written = 0; + written = 0; TLV::TLVWriter writer; writer.Init(buf, bufLen); { TLV::TLVWriter listWriter; - err = writer.OpenContainer(tlvListTag, TLV::kTLVType_List, listWriter); - SuccessOrExit(err); - err = listWriter.PutString(tlvStrTag, data); - SuccessOrExit(err); - err = writer.CloseContainer(listWriter); - SuccessOrExit(err); + ReturnErrorOnFailure(writer.OpenContainer(tlvListTag, TLV::kTLVType_List, listWriter)); + ReturnErrorOnFailure(listWriter.PutString(tlvStrTag, data)); + ReturnErrorOnFailure(writer.CloseContainer(listWriter)); } - err = writer.Finalize(); - SuccessOrExit(err); + ReturnErrorOnFailure(writer.Finalize()); written = writer.GetLengthWritten(); -exit: - return err; + return CHIP_NO_ERROR; } // Helper method: read a TLV structure with a single tag and string and verify it matches expected string. CHIP_ERROR ReadAndVerifyTLVString(nlTestSuite * inSuite, void * inContext, const uint8_t * dataStart, uint32_t len, const char * expected, uint16_t expectedLen) { - CHIP_ERROR err = CHIP_NO_ERROR; TLV::TLVReader reader; char tmp[64] = { 0 }; uint32_t readLength = 0; - VerifyOrExit(sizeof(tmp) > len, err = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(sizeof(tmp) > len, CHIP_ERROR_INTERNAL); reader.Init(dataStart, len); - err = reader.Next(); + CHIP_ERROR err = reader.Next(); - VerifyOrExit(reader.GetTag() == tlvListTag, err = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(reader.GetTag() == tlvListTag, CHIP_ERROR_INTERNAL); // Metadata must have a top-level list { TLV::TLVReader listReader; - err = reader.OpenContainer(listReader); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.OpenContainer(listReader)); - err = listReader.Next(); - SuccessOrExit(err); + ReturnErrorOnFailure(listReader.Next()); - VerifyOrExit(listReader.GetTag() == tlvStrTag, err = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(listReader.GetTag() == tlvStrTag, CHIP_ERROR_INTERNAL); readLength = listReader.GetLength(); - VerifyOrExit(readLength == expectedLen, err = CHIP_ERROR_INTERNAL); - err = listReader.GetString(tmp, sizeof(tmp)); - SuccessOrExit(err); - VerifyOrExit(!memcmp(expected, tmp, readLength), err = CHIP_ERROR_INTERNAL); + VerifyOrReturnError(readLength == expectedLen, CHIP_ERROR_INTERNAL); + ReturnErrorOnFailure(listReader.GetString(tmp, sizeof(tmp))); + VerifyOrReturnError(!memcmp(expected, tmp, readLength), CHIP_ERROR_INTERNAL); - err = reader.CloseContainer(listReader); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.CloseContainer(listReader)); } -exit: return err; } diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 57d5b6f41a4b48..93d5469fc7a35d 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -286,16 +286,13 @@ int CASE_TestSecurePairing_Setup(void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - CHIP_ERROR error; CertificateKeyId trustedRootId = { .mId = sTestCert_Root01_SubjectKeyId, .mLen = sTestCert_Root01_SubjectKeyId_Len }; - error = chip::Platform::MemoryInit(); - SuccessOrExit(error); + ReturnErrorOnFailure(chip::Platform::MemoryInit()); gTransportMgr.Init(&gLoopback); - error = ctx.Init(&sSuite, &gTransportMgr); - SuccessOrExit(error); + ReturnErrorOnFailure(ctx.Init(&sSuite, &gTransportMgr)); ctx.SetSourceNodeId(kAnyNodeId); ctx.SetDestinationNodeId(kAnyNodeId); @@ -305,71 +302,56 @@ int CASE_TestSecurePairing_Setup(void * inContext) gTransportMgr.SetSecureSessionMgr(&ctx.GetSecureSessionManager()); - error = commissionerOpKeysSerialized.SetLength(sTestCert_Node01_01_PublicKey_Len + sTestCert_Node01_01_PrivateKey_Len); - SuccessOrExit(error); + ReturnErrorOnFailure( + commissionerOpKeysSerialized.SetLength(sTestCert_Node01_01_PublicKey_Len + sTestCert_Node01_01_PrivateKey_Len)); memcpy((uint8_t *) (commissionerOpKeysSerialized), sTestCert_Node01_01_PublicKey, sTestCert_Node01_01_PublicKey_Len); memcpy((uint8_t *) (commissionerOpKeysSerialized) + sTestCert_Node01_01_PublicKey_Len, sTestCert_Node01_01_PrivateKey, sTestCert_Node01_01_PrivateKey_Len); - error = commissionerOpKeys.Deserialize(commissionerOpKeysSerialized); - SuccessOrExit(error); + ReturnErrorOnFailure(commissionerOpKeys.Deserialize(commissionerOpKeysSerialized)); - error = accessoryOpKeysSerialized.SetLength(sTestCert_Node01_01_PublicKey_Len + sTestCert_Node01_01_PrivateKey_Len); - SuccessOrExit(error); + ReturnErrorOnFailure( + accessoryOpKeysSerialized.SetLength(sTestCert_Node01_01_PublicKey_Len + sTestCert_Node01_01_PrivateKey_Len)); memcpy((uint8_t *) (accessoryOpKeysSerialized), sTestCert_Node01_01_PublicKey, sTestCert_Node01_01_PublicKey_Len); memcpy((uint8_t *) (accessoryOpKeysSerialized) + sTestCert_Node01_01_PublicKey_Len, sTestCert_Node01_01_PrivateKey, sTestCert_Node01_01_PrivateKey_Len); - error = accessoryOpKeys.Deserialize(accessoryOpKeysSerialized); - SuccessOrExit(error); + ReturnErrorOnFailure(accessoryOpKeys.Deserialize(accessoryOpKeysSerialized)); - error = commissionerCertificateSet.Init(kStandardCertsCount, kTestCertBufSize); - SuccessOrExit(error); + ReturnErrorOnFailure(commissionerCertificateSet.Init(kStandardCertsCount, kTestCertBufSize)); - error = accessoryCertificateSet.Init(kStandardCertsCount, kTestCertBufSize); - SuccessOrExit(error); + ReturnErrorOnFailure(accessoryCertificateSet.Init(kStandardCertsCount, kTestCertBufSize)); // Add the trusted root certificate to the certificate set. - error = commissionerCertificateSet.LoadCert(sTestCert_Root01_Chip, sTestCert_Root01_Chip_Len, - BitFlags(CertDecodeFlags::kIsTrustAnchor)); - SuccessOrExit(error); + ReturnErrorOnFailure(commissionerCertificateSet.LoadCert(sTestCert_Root01_Chip, sTestCert_Root01_Chip_Len, + BitFlags(CertDecodeFlags::kIsTrustAnchor))); - error = accessoryCertificateSet.LoadCert(sTestCert_Root01_Chip, sTestCert_Root01_Chip_Len, - BitFlags(CertDecodeFlags::kIsTrustAnchor)); - SuccessOrExit(error); + ReturnErrorOnFailure(accessoryCertificateSet.LoadCert(sTestCert_Root01_Chip, sTestCert_Root01_Chip_Len, + BitFlags(CertDecodeFlags::kIsTrustAnchor))); - error = commissionerCertificateSet.LoadCert(sTestCert_ICA01_Chip, sTestCert_ICA01_Chip_Len, - BitFlags(CertDecodeFlags::kIsTrustAnchor)); - SuccessOrExit(error); + ReturnErrorOnFailure(commissionerCertificateSet.LoadCert(sTestCert_ICA01_Chip, sTestCert_ICA01_Chip_Len, + BitFlags(CertDecodeFlags::kIsTrustAnchor))); - error = accessoryCertificateSet.LoadCert(sTestCert_ICA01_Chip, sTestCert_ICA01_Chip_Len, - BitFlags(CertDecodeFlags::kIsTrustAnchor)); - SuccessOrExit(error); + ReturnErrorOnFailure(accessoryCertificateSet.LoadCert(sTestCert_ICA01_Chip, sTestCert_ICA01_Chip_Len, + BitFlags(CertDecodeFlags::kIsTrustAnchor))); - error = commissionerDevOpCred.Init(&commissionerCertificateSet, 1); - SuccessOrExit(error); + ReturnErrorOnFailure(commissionerDevOpCred.Init(&commissionerCertificateSet, 1)); - error = commissionerDevOpCred.SetDevOpCred(trustedRootId, sTestCert_Node01_01_Chip, - static_cast(sTestCert_Node01_01_Chip_Len)); - SuccessOrExit(error); + ReturnErrorOnFailure(commissionerDevOpCred.SetDevOpCred(trustedRootId, sTestCert_Node01_01_Chip, + static_cast(sTestCert_Node01_01_Chip_Len))); - error = commissionerDevOpCred.SetDevOpCredKeypair(trustedRootId, &commissionerOpKeys); - SuccessOrExit(error); + ReturnErrorOnFailure(commissionerDevOpCred.SetDevOpCredKeypair(trustedRootId, &commissionerOpKeys)); - error = accessoryDevOpCred.Init(&accessoryCertificateSet, 1); - SuccessOrExit(error); + ReturnErrorOnFailure(accessoryDevOpCred.Init(&accessoryCertificateSet, 1)); - error = accessoryDevOpCred.SetDevOpCred(trustedRootId, sTestCert_Node01_01_Chip, - static_cast(sTestCert_Node01_01_Chip_Len)); - SuccessOrExit(error); + ReturnErrorOnFailure(accessoryDevOpCred.SetDevOpCred(trustedRootId, sTestCert_Node01_01_Chip, + static_cast(sTestCert_Node01_01_Chip_Len))); - error = accessoryDevOpCred.SetDevOpCredKeypair(trustedRootId, &accessoryOpKeys); - SuccessOrExit(error); + ReturnErrorOnFailure(accessoryDevOpCred.SetDevOpCredKeypair(trustedRootId, &accessoryOpKeys)); -exit: - return error; + return CHIP_NO_ERROR; } /** diff --git a/src/setup_payload/AdditionalDataPayloadGenerator.cpp b/src/setup_payload/AdditionalDataPayloadGenerator.cpp index 341c0e6c26de9d..7441fc9aec257f 100644 --- a/src/setup_payload/AdditionalDataPayloadGenerator.cpp +++ b/src/setup_payload/AdditionalDataPayloadGenerator.cpp @@ -46,7 +46,6 @@ AdditionalDataPayloadGenerator::generateAdditionalDataPayload(uint16_t lifetimeC size_t serialNumberBufferSize, PacketBufferHandle & bufferHandle, BitFlags additionalDataFields) { - CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferTLVWriter writer; TLVWriter innerWriter; char rotatingDeviceIdBuffer[RotatingDeviceId::kHexMaxLength]; @@ -55,26 +54,23 @@ AdditionalDataPayloadGenerator::generateAdditionalDataPayload(uint16_t lifetimeC // Initialize TLVWriter writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - SuccessOrExit(err = writer.OpenContainer(AnonymousTag, kTLVType_Structure, innerWriter)); + ReturnErrorOnFailure(writer.OpenContainer(AnonymousTag, kTLVType_Structure, innerWriter)); if (additionalDataFields.Has(AdditionalDataFields::RotatingDeviceId)) { // Generating Device Rotating Id - SuccessOrExit(err = generateRotatingDeviceId(lifetimeCounter, serialNumberBuffer, serialNumberBufferSize, - rotatingDeviceIdBuffer, ArraySize(rotatingDeviceIdBuffer), - rotatingDeviceIdBufferSize)); + ReturnErrorOnFailure(generateRotatingDeviceId(lifetimeCounter, serialNumberBuffer, serialNumberBufferSize, + rotatingDeviceIdBuffer, ArraySize(rotatingDeviceIdBuffer), + rotatingDeviceIdBufferSize)); // Adding the rotating device id to the TLV data - SuccessOrExit(err = innerWriter.PutString(ContextTag(kRotatingDeviceIdTag), rotatingDeviceIdBuffer, - static_cast(rotatingDeviceIdBufferSize))); + ReturnErrorOnFailure(innerWriter.PutString(ContextTag(kRotatingDeviceIdTag), rotatingDeviceIdBuffer, + static_cast(rotatingDeviceIdBufferSize))); } - SuccessOrExit(err = writer.CloseContainer(innerWriter)); + ReturnErrorOnFailure(writer.CloseContainer(innerWriter)); - SuccessOrExit(err = writer.Finalize(&bufferHandle)); - -exit: - return err; + return writer.Finalize(&bufferHandle); } CHIP_ERROR AdditionalDataPayloadGenerator::generateRotatingDeviceId(uint16_t lifetimeCounter, const char * serialNumberBuffer, @@ -82,8 +78,6 @@ CHIP_ERROR AdditionalDataPayloadGenerator::generateRotatingDeviceId(uint16_t lif size_t rotatingDeviceIdBufferSize, size_t & rotatingDeviceIdValueOutputSize) { - CHIP_ERROR err = CHIP_NO_ERROR; - Hash_SHA256_stream hash; uint8_t outputBuffer[RotatingDeviceId::kMaxLength]; uint8_t hashOutputBuffer[kSHA256_Hash_Length]; BufferWriter outputBufferWriter(outputBuffer, ArraySize(outputBuffer)); @@ -92,15 +86,16 @@ CHIP_ERROR AdditionalDataPayloadGenerator::generateRotatingDeviceId(uint16_t lif Put16(lifetimeCounterBuffer, lifetimeCounter); - VerifyOrExit(rotatingDeviceIdBufferSize >= RotatingDeviceId::kHexMaxLength, err = CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(rotatingDeviceIdBufferSize >= RotatingDeviceId::kHexMaxLength, CHIP_ERROR_BUFFER_TOO_SMALL); // Computing the Rotating Device Id // RDI = Lifetime_Counter + SuffixBytes(SHA256(Serial_Number + Lifetime_Counter), 16) - SuccessOrExit(err = hash.Begin()); - SuccessOrExit(err = hash.AddData(Uint8::from_const_char(serialNumberBuffer), serialNumberBufferSize)); - SuccessOrExit(err = hash.AddData(lifetimeCounterBuffer, sizeof(lifetimeCounter))); - SuccessOrExit(err = hash.Finish(hashOutputBuffer)); + Hash_SHA256_stream hash; + ReturnErrorOnFailure(hash.Begin()); + ReturnErrorOnFailure(hash.AddData(Uint8::from_const_char(serialNumberBuffer), serialNumberBufferSize)); + ReturnErrorOnFailure(hash.AddData(lifetimeCounterBuffer, sizeof(lifetimeCounter))); + ReturnErrorOnFailure(hash.Finish(hashOutputBuffer)); outputBufferWriter.Put16(lifetimeCounter); outputBufferWriter.Put(&hashOutputBuffer[kSHA256_Hash_Length - RotatingDeviceId::kHashSuffixLength], @@ -117,6 +112,5 @@ CHIP_ERROR AdditionalDataPayloadGenerator::generateRotatingDeviceId(uint16_t lif rotatingDeviceIdValueOutputSize = rotatingDeviceIdBufferIndex * 2; ChipLogDetail(DeviceLayer, "rotatingDeviceId: %s", rotatingDeviceIdBuffer); -exit: - return err; + return CHIP_NO_ERROR; } diff --git a/src/setup_payload/AdditionalDataPayloadParser.cpp b/src/setup_payload/AdditionalDataPayloadParser.cpp index 053cd4d19a4f94..f183359a82f35b 100644 --- a/src/setup_payload/AdditionalDataPayloadParser.cpp +++ b/src/setup_payload/AdditionalDataPayloadParser.cpp @@ -37,33 +37,26 @@ namespace chip { CHIP_ERROR AdditionalDataPayloadParser::populatePayload(SetupPayloadData::AdditionalDataPayload & outPayload) { - CHIP_ERROR err = CHIP_NO_ERROR; TLV::TLVReader reader; TLV::TLVReader innerReader; reader.Init(mPayloadBufferData, mPayloadBufferLength); - err = reader.Next(TLV::kTLVType_Structure, TLV::AnonymousTag); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.Next(TLV::kTLVType_Structure, TLV::AnonymousTag)); // Open the container - err = reader.OpenContainer(innerReader); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.OpenContainer(innerReader)); - err = innerReader.Next(TLV::kTLVType_UTF8String, TLV::ContextTag(SetupPayloadData::kRotatingDeviceIdTag)); - SuccessOrExit(err); + ReturnErrorOnFailure(innerReader.Next(TLV::kTLVType_UTF8String, TLV::ContextTag(SetupPayloadData::kRotatingDeviceIdTag))); // Get the value of the rotating device id char rotatingDeviceId[SetupPayloadData::kRotatingDeviceIdLength]; - err = innerReader.GetString(rotatingDeviceId, sizeof(rotatingDeviceId)); - SuccessOrExit(err); + ReturnErrorOnFailure(innerReader.GetString(rotatingDeviceId, sizeof(rotatingDeviceId))); outPayload.rotatingDeviceId = std::string(rotatingDeviceId); // Verify the end of the container - err = reader.VerifyEndOfContainer(); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.VerifyEndOfContainer()); -exit: - return err; + return CHIP_NO_ERROR; } } // namespace chip diff --git a/src/setup_payload/QRCodeSetupPayloadGenerator.cpp b/src/setup_payload/QRCodeSetupPayloadGenerator.cpp index 88c20f6ca1c424..7dc875fa5fa724 100644 --- a/src/setup_payload/QRCodeSetupPayloadGenerator.cpp +++ b/src/setup_payload/QRCodeSetupPayloadGenerator.cpp @@ -43,13 +43,10 @@ namespace chip { static CHIP_ERROR populateBits(uint8_t * bits, size_t & offset, uint64_t input, size_t numberOfBits, size_t totalPayloadDataSizeInBits) { - CHIP_ERROR err = CHIP_NO_ERROR; - size_t index; - - VerifyOrExit(offset + numberOfBits <= totalPayloadDataSizeInBits, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(input < 1u << numberOfBits, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(offset + numberOfBits <= totalPayloadDataSizeInBits, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(input < 1u << numberOfBits, CHIP_ERROR_INVALID_ARGUMENT); - index = offset; + size_t index = offset; offset += numberOfBits; while (input != 0) { @@ -60,24 +57,18 @@ static CHIP_ERROR populateBits(uint8_t * bits, size_t & offset, uint64_t input, index++; input >>= 1; } -exit: - return err; + return CHIP_NO_ERROR; } static CHIP_ERROR populateTLVBits(uint8_t * bits, size_t & offset, const uint8_t * tlvBuf, size_t tlvBufSizeInBytes, size_t totalPayloadDataSizeInBits) { - CHIP_ERROR err = CHIP_NO_ERROR; for (size_t i = 0; i < tlvBufSizeInBytes; i++) { - uint8_t value = tlvBuf[i]; - err = populateBits(bits, offset, value, 8, totalPayloadDataSizeInBits); - if (err != CHIP_NO_ERROR) - { - return err; - } + const uint8_t value = tlvBuf[i]; + ReturnErrorOnFailure(populateBits(bits, offset, value, 8, totalPayloadDataSizeInBits)); } - return err; + return CHIP_NO_ERROR; } CHIP_ERROR writeTag(TLV::TLVWriter & writer, uint64_t tag, OptionalQRCodeInfo & info) @@ -131,41 +122,34 @@ CHIP_ERROR writeTag(TLV::TLVWriter & writer, uint64_t tag, OptionalQRCodeInfoExt CHIP_ERROR QRCodeSetupPayloadGenerator::generateTLVFromOptionalData(SetupPayload & outPayload, uint8_t * tlvDataStart, uint32_t maxLen, size_t & tlvDataLengthInBytes) { - CHIP_ERROR err = CHIP_NO_ERROR; std::vector optionalData = outPayload.getAllOptionalVendorData(); std::vector optionalExtensionData = outPayload.getAllOptionalExtensionData(); - VerifyOrExit(!optionalData.empty() || !optionalExtensionData.empty(), err = CHIP_NO_ERROR); + VerifyOrReturnError(!optionalData.empty() || !optionalExtensionData.empty(), CHIP_NO_ERROR); TLV::TLVWriter rootWriter; rootWriter.Init(tlvDataStart, maxLen); TLV::TLVWriter innerStructureWriter; - err = rootWriter.OpenContainer(TLV::AnonymousTag, TLV::kTLVType_Structure, innerStructureWriter); - SuccessOrExit(err); + ReturnErrorOnFailure(rootWriter.OpenContainer(TLV::AnonymousTag, TLV::kTLVType_Structure, innerStructureWriter)); for (OptionalQRCodeInfo info : optionalData) { - err = writeTag(innerStructureWriter, TLV::ContextTag(info.tag), info); - SuccessOrExit(err); + ReturnErrorOnFailure(writeTag(innerStructureWriter, TLV::ContextTag(info.tag), info)); } for (OptionalQRCodeInfoExtension info : optionalExtensionData) { - err = writeTag(innerStructureWriter, TLV::ContextTag(info.tag), info); - SuccessOrExit(err); + ReturnErrorOnFailure(writeTag(innerStructureWriter, TLV::ContextTag(info.tag), info)); } - err = rootWriter.CloseContainer(innerStructureWriter); - SuccessOrExit(err); + ReturnErrorOnFailure(rootWriter.CloseContainer(innerStructureWriter)); - err = rootWriter.Finalize(); - SuccessOrExit(err); + ReturnErrorOnFailure(rootWriter.Finalize()); tlvDataLengthInBytes = rootWriter.GetLengthWritten(); -exit: - return err; + return CHIP_NO_ERROR; } static CHIP_ERROR generateBitSet(SetupPayload & payload, uint8_t * bits, uint8_t * tlvDataStart, size_t tlvDataLengthInBytes) @@ -199,14 +183,12 @@ static CHIP_ERROR payloadBase38RepresentationWithTLV(SetupPayload & setupPayload uint8_t bits[bitsetSize]; memset(bits, 0, bitsetSize); std::string encodedPayload; - CHIP_ERROR err = generateBitSet(setupPayload, bits, tlvDataStart, tlvDataLengthInBytes); - SuccessOrExit(err); + ReturnErrorOnFailure(generateBitSet(setupPayload, bits, tlvDataStart, tlvDataLengthInBytes)); encodedPayload = base38Encode(bits, ArraySize(bits)); encodedPayload.insert(0, kQRCodePrefix); base38Representation = encodedPayload; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR QRCodeSetupPayloadGenerator::payloadBase38Representation(std::string & base38Representation) @@ -219,19 +201,13 @@ CHIP_ERROR QRCodeSetupPayloadGenerator::payloadBase38Representation(std::string CHIP_ERROR QRCodeSetupPayloadGenerator::payloadBase38Representation(std::string & base38Representation, uint8_t * tlvDataStart, uint32_t tlvDataStartSize) { - CHIP_ERROR err = CHIP_NO_ERROR; size_t tlvDataLengthInBytes = 0; - VerifyOrExit(mPayload.isValidQRCodePayload(), err = CHIP_ERROR_INVALID_ARGUMENT); - err = generateTLVFromOptionalData(mPayload, tlvDataStart, tlvDataStartSize, tlvDataLengthInBytes); - SuccessOrExit(err); + VerifyOrReturnError(mPayload.isValidQRCodePayload(), CHIP_ERROR_INVALID_ARGUMENT); + ReturnErrorOnFailure(generateTLVFromOptionalData(mPayload, tlvDataStart, tlvDataStartSize, tlvDataLengthInBytes)); - err = payloadBase38RepresentationWithTLV(mPayload, base38Representation, kTotalPayloadDataSizeInBytes + tlvDataLengthInBytes, - tlvDataStart, tlvDataLengthInBytes); - SuccessOrExit(err); - -exit: - return err; + return payloadBase38RepresentationWithTLV(mPayload, base38Representation, kTotalPayloadDataSizeInBytes + tlvDataLengthInBytes, + tlvDataStart, tlvDataLengthInBytes); } #if !defined(__clang__) diff --git a/src/setup_payload/QRCodeSetupPayloadParser.cpp b/src/setup_payload/QRCodeSetupPayloadParser.cpp index afdc0dcdff1189..870d607e24f37b 100644 --- a/src/setup_payload/QRCodeSetupPayloadParser.cpp +++ b/src/setup_payload/QRCodeSetupPayloadParser.cpp @@ -67,87 +67,73 @@ static CHIP_ERROR readBits(std::vector buf, size_t & index, uint64_t & static CHIP_ERROR openTLVContainer(TLV::TLVReader & reader, TLV::TLVType type, uint64_t tag, TLV::TLVReader & containerReader) { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(reader.GetType() == type, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(reader.GetTag() == tag, err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(reader.GetLength() == 0, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(reader.GetType() == type, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(reader.GetTag() == tag, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(reader.GetLength() == 0, CHIP_ERROR_INVALID_ARGUMENT); - err = reader.OpenContainer(containerReader); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.OpenContainer(containerReader)); - VerifyOrExit(containerReader.GetContainerType() == type, err = CHIP_ERROR_INVALID_ARGUMENT); -exit: - return err; + VerifyOrReturnError(containerReader.GetContainerType() == type, CHIP_ERROR_INVALID_ARGUMENT); + return CHIP_NO_ERROR; } static CHIP_ERROR retrieveOptionalInfoString(TLV::TLVReader & reader, OptionalQRCodeInfo & info) { - CHIP_ERROR err; - uint32_t valLength = reader.GetLength(); + const uint32_t valLength = reader.GetLength(); chip::Platform::ScopedMemoryBuffer value; value.Alloc(valLength + 1); - VerifyOrExit(value, err = CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(value, CHIP_ERROR_NO_MEMORY); - err = reader.GetString(value.Get(), valLength + 1); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.GetString(value.Get(), valLength + 1)); info.type = optionalQRCodeInfoTypeString; info.data = std::string(value.Get()); -exit: - return err; + return CHIP_NO_ERROR; } static CHIP_ERROR retrieveOptionalInfoInt32(TLV::TLVReader & reader, OptionalQRCodeInfo & info) { int32_t value; - CHIP_ERROR err = reader.Get(value); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.Get(value)); info.type = optionalQRCodeInfoTypeInt32; info.int32 = value; -exit: - return err; + return CHIP_NO_ERROR; } static CHIP_ERROR retrieveOptionalInfoInt64(TLV::TLVReader & reader, OptionalQRCodeInfoExtension & info) { int64_t value; - CHIP_ERROR err = reader.Get(value); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.Get(value)); info.type = optionalQRCodeInfoTypeInt64; info.int64 = value; -exit: - return err; + return CHIP_NO_ERROR; } static CHIP_ERROR retrieveOptionalInfoUInt32(TLV::TLVReader & reader, OptionalQRCodeInfoExtension & info) { uint32_t value; - CHIP_ERROR err = reader.Get(value); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.Get(value)); info.type = optionalQRCodeInfoTypeUInt32; info.uint32 = value; -exit: - return err; + return CHIP_NO_ERROR; } static CHIP_ERROR retrieveOptionalInfoUInt64(TLV::TLVReader & reader, OptionalQRCodeInfoExtension & info) { uint64_t value; - CHIP_ERROR err = reader.Get(value); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.Get(value)); info.type = optionalQRCodeInfoTypeUInt64; info.uint64 = value; -exit: - return err; + return CHIP_NO_ERROR; } static CHIP_ERROR retrieveOptionalInfo(TLV::TLVReader & reader, OptionalQRCodeInfo & info, optionalQRCodeInfoType type) @@ -201,19 +187,17 @@ static CHIP_ERROR retrieveOptionalInfo(TLV::TLVReader & reader, OptionalQRCodeIn CHIP_ERROR QRCodeSetupPayloadParser::retrieveOptionalInfos(SetupPayload & outPayload, TLV::TLVReader & reader) { CHIP_ERROR err = CHIP_NO_ERROR; - TLV::TLVType type; - uint8_t tag; while (err == CHIP_NO_ERROR) { - type = reader.GetType(); + const TLV::TLVType type = reader.GetType(); if (type != TLV::kTLVType_UTF8String && type != TLV::kTLVType_SignedInteger && type != TLV::kTLVType_UnsignedInteger) { err = reader.Next(); continue; } - tag = static_cast(TLV::TagNumFromTag(reader.GetTag())); - VerifyOrExit(TLV::IsContextTag(tag) == true || TLV::IsProfileTag(tag) == true, err = CHIP_ERROR_INVALID_TLV_TAG); + const uint8_t tag = static_cast(TLV::TagNumFromTag(reader.GetTag())); + VerifyOrReturnError(TLV::IsContextTag(tag) == true || TLV::IsProfileTag(tag) == true, CHIP_ERROR_INVALID_TLV_TAG); optionalQRCodeInfoType elemType = optionalQRCodeInfoTypeUnknown; if (type == TLV::kTLVType_UTF8String) @@ -229,21 +213,17 @@ CHIP_ERROR QRCodeSetupPayloadParser::retrieveOptionalInfos(SetupPayload & outPay { OptionalQRCodeInfoExtension info; info.tag = tag; - err = retrieveOptionalInfo(reader, info, elemType); - SuccessOrExit(err); + ReturnErrorOnFailure(retrieveOptionalInfo(reader, info, elemType)); - err = outPayload.addOptionalExtensionData(info); - SuccessOrExit(err); + ReturnErrorOnFailure(outPayload.addOptionalExtensionData(info)); } else { OptionalQRCodeInfo info; info.tag = tag; - err = retrieveOptionalInfo(reader, info, elemType); - SuccessOrExit(err); + ReturnErrorOnFailure(retrieveOptionalInfo(reader, info, elemType)); - err = outPayload.addOptionalVendorData(info); - SuccessOrExit(err); + ReturnErrorOnFailure(outPayload.addOptionalVendorData(info)); } err = reader.Next(); } @@ -252,7 +232,6 @@ CHIP_ERROR QRCodeSetupPayloadParser::retrieveOptionalInfos(SetupPayload & outPay err = CHIP_NO_ERROR; } -exit: return err; } @@ -265,8 +244,7 @@ CHIP_ERROR QRCodeSetupPayloadParser::parseTLVFields(SetupPayload & outPayload, u } TLV::TLVReader rootReader; rootReader.Init(tlvDataStart, static_cast(tlvDataLengthInBytes)); - err = rootReader.Next(); - SuccessOrExit(err); + ReturnErrorOnFailure(rootReader.Next()); if (rootReader.GetType() != TLV::kTLVType_Structure) { @@ -274,17 +252,14 @@ CHIP_ERROR QRCodeSetupPayloadParser::parseTLVFields(SetupPayload & outPayload, u } TLV::TLVReader innerStructureReader; - err = openTLVContainer(rootReader, TLV::kTLVType_Structure, TLV::AnonymousTag, innerStructureReader); - SuccessOrExit(err); - err = innerStructureReader.Next(); - SuccessOrExit(err); + ReturnErrorOnFailure(openTLVContainer(rootReader, TLV::kTLVType_Structure, TLV::AnonymousTag, innerStructureReader)); + ReturnErrorOnFailure(innerStructureReader.Next()); err = retrieveOptionalInfos(outPayload, innerStructureReader); if (err == CHIP_END_OF_TLV) { err = CHIP_NO_ERROR; } -exit: return err; } @@ -351,61 +326,47 @@ static std::string extractPayload(std::string inString) CHIP_ERROR QRCodeSetupPayloadParser::populatePayload(SetupPayload & outPayload) { std::vector buf; - CHIP_ERROR err = CHIP_NO_ERROR; size_t indexToReadFrom = 0; uint64_t dest; std::string payload = extractPayload(mBase38Representation); - VerifyOrExit(payload.length() != 0, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(payload.length() != 0, CHIP_ERROR_INVALID_ARGUMENT); - err = base38Decode(payload, buf); - SuccessOrExit(err); + ReturnErrorOnFailure(base38Decode(payload, buf)); - err = readBits(buf, indexToReadFrom, dest, kVersionFieldLengthInBits); - SuccessOrExit(err); + ReturnErrorOnFailure(readBits(buf, indexToReadFrom, dest, kVersionFieldLengthInBits)); static_assert(kVersionFieldLengthInBits <= 8, "Won't fit in uint8_t"); outPayload.version = static_cast(dest); - err = readBits(buf, indexToReadFrom, dest, kVendorIDFieldLengthInBits); - SuccessOrExit(err); + ReturnErrorOnFailure(readBits(buf, indexToReadFrom, dest, kVendorIDFieldLengthInBits)); static_assert(kVendorIDFieldLengthInBits <= 16, "Won't fit in uint16_t"); outPayload.vendorID = static_cast(dest); - err = readBits(buf, indexToReadFrom, dest, kProductIDFieldLengthInBits); - SuccessOrExit(err); + ReturnErrorOnFailure(readBits(buf, indexToReadFrom, dest, kProductIDFieldLengthInBits)); static_assert(kProductIDFieldLengthInBits <= 16, "Won't fit in uint16_t"); outPayload.productID = static_cast(dest); - err = readBits(buf, indexToReadFrom, dest, kCommissioningFlowFieldLengthInBits); - SuccessOrExit(err); + ReturnErrorOnFailure(readBits(buf, indexToReadFrom, dest, kCommissioningFlowFieldLengthInBits)); static_assert(kCommissioningFlowFieldLengthInBits <= std::numeric_limits>::digits, "Won't fit in CommissioningFlow"); outPayload.commissioningFlow = static_cast(dest); - err = readBits(buf, indexToReadFrom, dest, kRendezvousInfoFieldLengthInBits); - SuccessOrExit(err); + ReturnErrorOnFailure(readBits(buf, indexToReadFrom, dest, kRendezvousInfoFieldLengthInBits)); static_assert(kRendezvousInfoFieldLengthInBits <= 8 * sizeof(RendezvousInformationFlag), "Won't fit in RendezvousInformationFlags"); outPayload.rendezvousInformation = RendezvousInformationFlags(static_cast(dest)); - err = readBits(buf, indexToReadFrom, dest, kPayloadDiscriminatorFieldLengthInBits); - SuccessOrExit(err); + ReturnErrorOnFailure(readBits(buf, indexToReadFrom, dest, kPayloadDiscriminatorFieldLengthInBits)); static_assert(kPayloadDiscriminatorFieldLengthInBits <= 16, "Won't fit in uint16_t"); outPayload.discriminator = static_cast(dest); - err = readBits(buf, indexToReadFrom, dest, kSetupPINCodeFieldLengthInBits); - SuccessOrExit(err); + ReturnErrorOnFailure(readBits(buf, indexToReadFrom, dest, kSetupPINCodeFieldLengthInBits)); static_assert(kSetupPINCodeFieldLengthInBits <= 32, "Won't fit in uint32_t"); outPayload.setUpPINCode = static_cast(dest); - err = readBits(buf, indexToReadFrom, dest, kPaddingFieldLengthInBits); - SuccessOrExit(err); - - err = populateTLV(outPayload, buf, indexToReadFrom); - SuccessOrExit(err); + ReturnErrorOnFailure(readBits(buf, indexToReadFrom, dest, kPaddingFieldLengthInBits)); -exit: - return err; + return populateTLV(outPayload, buf, indexToReadFrom); } } // namespace chip diff --git a/src/setup_payload/SetupPayload.cpp b/src/setup_payload/SetupPayload.cpp index abf7962a3d9796..7919c3b4837872 100644 --- a/src/setup_payload/SetupPayload.cpp +++ b/src/setup_payload/SetupPayload.cpp @@ -109,32 +109,22 @@ bool SetupPayload::isValidManualCode() CHIP_ERROR SetupPayload::addOptionalVendorData(uint8_t tag, std::string data) { - CHIP_ERROR err = CHIP_NO_ERROR; OptionalQRCodeInfo info; info.tag = tag; info.type = optionalQRCodeInfoTypeString; info.data = std::move(data); - err = addOptionalVendorData(info); - SuccessOrExit(err); - -exit: - return err; + return addOptionalVendorData(info); } CHIP_ERROR SetupPayload::addOptionalVendorData(uint8_t tag, int32_t data) { - CHIP_ERROR err = CHIP_NO_ERROR; OptionalQRCodeInfo info; info.tag = tag; info.type = optionalQRCodeInfoTypeInt32; info.int32 = data; - err = addOptionalVendorData(info); - SuccessOrExit(err); - -exit: - return err; + return addOptionalVendorData(info); } std::vector SetupPayload::getAllOptionalVendorData() const @@ -149,51 +139,37 @@ std::vector SetupPayload::getAllOptionalVendorData() const CHIP_ERROR SetupPayload::removeOptionalVendorData(uint8_t tag) { - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(optionalVendorData.find(tag) != optionalVendorData.end(), err = CHIP_ERROR_KEY_NOT_FOUND); + VerifyOrReturnError(optionalVendorData.find(tag) != optionalVendorData.end(), CHIP_ERROR_KEY_NOT_FOUND); optionalVendorData.erase(tag); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR SetupPayload::addSerialNumber(std::string serialNumber) { - CHIP_ERROR err = CHIP_NO_ERROR; OptionalQRCodeInfoExtension info; info.tag = kSerialNumberTag; info.type = optionalQRCodeInfoTypeString; info.data = std::move(serialNumber); - err = addOptionalExtensionData(info); - SuccessOrExit(err); - -exit: - return err; + return addOptionalExtensionData(info); } CHIP_ERROR SetupPayload::addSerialNumber(uint32_t serialNumber) { - CHIP_ERROR err = CHIP_NO_ERROR; OptionalQRCodeInfoExtension info; info.tag = kSerialNumberTag; info.type = optionalQRCodeInfoTypeUInt32; info.uint32 = serialNumber; - err = addOptionalExtensionData(info); - SuccessOrExit(err); - -exit: - return err; + return addOptionalExtensionData(info); } CHIP_ERROR SetupPayload::getSerialNumber(std::string & outSerialNumber) const { CHIP_ERROR err = CHIP_NO_ERROR; OptionalQRCodeInfoExtension info; - err = getOptionalExtensionData(kSerialNumberTag, info); - SuccessOrExit(err); + ReturnErrorOnFailure(getOptionalExtensionData(kSerialNumberTag, info)); switch (info.type) { @@ -205,50 +181,42 @@ CHIP_ERROR SetupPayload::getSerialNumber(std::string & outSerialNumber) const break; default: err = CHIP_ERROR_INVALID_ARGUMENT; + break; } -exit: return err; } CHIP_ERROR SetupPayload::removeSerialNumber() { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(optionalExtensionData.find(kSerialNumberTag) != optionalExtensionData.end(), err = CHIP_ERROR_KEY_NOT_FOUND); + VerifyOrReturnError(optionalExtensionData.find(kSerialNumberTag) != optionalExtensionData.end(), CHIP_ERROR_KEY_NOT_FOUND); optionalExtensionData.erase(kSerialNumberTag); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR SetupPayload::addOptionalVendorData(const OptionalQRCodeInfo & info) { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(IsVendorTag(info.tag), err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsVendorTag(info.tag), CHIP_ERROR_INVALID_ARGUMENT); optionalVendorData[info.tag] = info; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR SetupPayload::addOptionalExtensionData(const OptionalQRCodeInfoExtension & info) { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(IsCHIPTag(info.tag), err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsCHIPTag(info.tag), CHIP_ERROR_INVALID_ARGUMENT); optionalExtensionData[info.tag] = info; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR SetupPayload::getOptionalVendorData(uint8_t tag, OptionalQRCodeInfo & info) { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrExit(optionalVendorData.find(tag) != optionalVendorData.end(), err = CHIP_ERROR_KEY_NOT_FOUND); + VerifyOrReturnError(optionalVendorData.find(tag) != optionalVendorData.end(), CHIP_ERROR_KEY_NOT_FOUND); info = optionalVendorData[tag]; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR SetupPayload::getOptionalExtensionData(uint8_t tag, OptionalQRCodeInfoExtension & info) const @@ -287,47 +255,45 @@ std::vector SetupPayload::getAllOptionalExtensionDa bool SetupPayload::operator==(SetupPayload & input) { - bool isIdentical = true; std::vector inputOptionalVendorData; std::vector inputOptionalExtensionData; - VerifyOrExit(this->version == input.version && this->vendorID == input.vendorID && this->productID == input.productID && - this->commissioningFlow == input.commissioningFlow && - this->rendezvousInformation == input.rendezvousInformation && this->discriminator == input.discriminator && - this->setUpPINCode == input.setUpPINCode, - isIdentical = false); + VerifyOrReturnError(this->version == input.version && this->vendorID == input.vendorID && this->productID == input.productID && + this->commissioningFlow == input.commissioningFlow && + this->rendezvousInformation == input.rendezvousInformation && + this->discriminator == input.discriminator && this->setUpPINCode == input.setUpPINCode, + false); inputOptionalVendorData = input.getAllOptionalVendorData(); - VerifyOrExit(optionalVendorData.size() == inputOptionalVendorData.size(), isIdentical = false); + VerifyOrReturnError(optionalVendorData.size() == inputOptionalVendorData.size(), false); for (const OptionalQRCodeInfo & inputInfo : inputOptionalVendorData) { OptionalQRCodeInfo info; CHIP_ERROR err = getOptionalVendorData(inputInfo.tag, info); - VerifyOrExit(err == CHIP_NO_ERROR, isIdentical = false); - VerifyOrExit(inputInfo.type == info.type, isIdentical = false); - VerifyOrExit(inputInfo.data == info.data, isIdentical = false); - VerifyOrExit(inputInfo.int32 == info.int32, isIdentical = false); + VerifyOrReturnError(err == CHIP_NO_ERROR, false); + VerifyOrReturnError(inputInfo.type == info.type, false); + VerifyOrReturnError(inputInfo.data == info.data, false); + VerifyOrReturnError(inputInfo.int32 == info.int32, false); } inputOptionalExtensionData = input.getAllOptionalExtensionData(); - VerifyOrExit(optionalExtensionData.size() == inputOptionalExtensionData.size(), isIdentical = false); + VerifyOrReturnError(optionalExtensionData.size() == inputOptionalExtensionData.size(), false); for (const OptionalQRCodeInfoExtension & inputInfo : inputOptionalExtensionData) { OptionalQRCodeInfoExtension info; CHIP_ERROR err = getOptionalExtensionData(inputInfo.tag, info); - VerifyOrExit(err == CHIP_NO_ERROR, isIdentical = false); - VerifyOrExit(inputInfo.type == info.type, isIdentical = false); - VerifyOrExit(inputInfo.data == info.data, isIdentical = false); - VerifyOrExit(inputInfo.int32 == info.int32, isIdentical = false); - VerifyOrExit(inputInfo.int64 == info.int64, isIdentical = false); - VerifyOrExit(inputInfo.uint32 == info.uint32, isIdentical = false); - VerifyOrExit(inputInfo.uint64 == info.uint64, isIdentical = false); + VerifyOrReturnError(err == CHIP_NO_ERROR, false); + VerifyOrReturnError(inputInfo.type == info.type, false); + VerifyOrReturnError(inputInfo.data == info.data, false); + VerifyOrReturnError(inputInfo.int32 == info.int32, false); + VerifyOrReturnError(inputInfo.int64 == info.int64, false); + VerifyOrReturnError(inputInfo.uint32 == info.uint32, false); + VerifyOrReturnError(inputInfo.uint64 == info.uint64, false); } -exit: - return isIdentical; + return true; } } // namespace chip diff --git a/src/setup_payload/SetupPayloadHelper.cpp b/src/setup_payload/SetupPayloadHelper.cpp index 9f2a32f3957294..1018bee6201b2f 100644 --- a/src/setup_payload/SetupPayloadHelper.cpp +++ b/src/setup_payload/SetupPayloadHelper.cpp @@ -143,9 +143,8 @@ static CHIP_ERROR addParameter(SetupPayload & setupPayload, const SetupPayloadPa CHIP_ERROR loadPayloadFromFile(SetupPayload & setupPayload, const std::string & filePath) { - CHIP_ERROR err = CHIP_NO_ERROR; std::ifstream fileStream(filePath); - VerifyOrExit(!fileStream.fail(), err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!fileStream.fail(), CHIP_ERROR_INVALID_ARGUMENT); while (fileStream) { @@ -161,14 +160,11 @@ CHIP_ERROR loadPayloadFromFile(SetupPayload & setupPayload, const std::string & { continue; } - err = resolveSetupPayloadParameter(parameter, key, value); - SuccessOrExit(err); + ReturnErrorOnFailure(resolveSetupPayloadParameter(parameter, key, value)); - err = addParameter(setupPayload, parameter); - SuccessOrExit(err); + ReturnErrorOnFailure(addParameter(setupPayload, parameter)); } -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR generateQRCodeFromFilePath(std::string filePath, std::string & outCode) diff --git a/src/setup_payload/java/SetupPayloadParser-JNI.cpp b/src/setup_payload/java/SetupPayloadParser-JNI.cpp index c91360f2c6169b..0b069671dd2b4e 100644 --- a/src/setup_payload/java/SetupPayloadParser-JNI.cpp +++ b/src/setup_payload/java/SetupPayloadParser-JNI.cpp @@ -165,7 +165,6 @@ jobject TransformSetupPayload(JNIEnv * env, SetupPayload & payload) CHIP_ERROR ThrowUnrecognizedQRCodeException(JNIEnv * env, jstring qrCodeObj) { - CHIP_ERROR err = CHIP_NO_ERROR; jclass exceptionCls = nullptr; jmethodID exceptionConstructor = nullptr; jthrowable exception = nullptr; @@ -173,20 +172,18 @@ CHIP_ERROR ThrowUnrecognizedQRCodeException(JNIEnv * env, jstring qrCodeObj) env->ExceptionClear(); exceptionCls = env->FindClass("chip/setuppayload/SetupPayloadParser$UnrecognizedQrCodeException"); - VerifyOrExit(exceptionCls != NULL, err = SETUP_PAYLOAD_PARSER_JNI_ERROR_TYPE_NOT_FOUND); + VerifyOrReturnError(exceptionCls != NULL, SETUP_PAYLOAD_PARSER_JNI_ERROR_TYPE_NOT_FOUND); exceptionConstructor = env->GetMethodID(exceptionCls, "", "(Ljava/lang/String;)V"); - VerifyOrExit(exceptionConstructor != NULL, err = SETUP_PAYLOAD_PARSER_JNI_ERROR_METHOD_NOT_FOUND); + VerifyOrReturnError(exceptionConstructor != NULL, SETUP_PAYLOAD_PARSER_JNI_ERROR_METHOD_NOT_FOUND); exception = (jthrowable) env->NewObject(exceptionCls, exceptionConstructor, qrCodeObj); - VerifyOrExit(exception != NULL, err = SETUP_PAYLOAD_PARSER_JNI_ERROR_EXCEPTION_THROWN); + VerifyOrReturnError(exception != NULL, SETUP_PAYLOAD_PARSER_JNI_ERROR_EXCEPTION_THROWN); env->Throw(exception); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR ThrowInvalidEntryCodeFormatException(JNIEnv * env, jstring entryCodeObj) { - CHIP_ERROR err = CHIP_NO_ERROR; jclass exceptionCls = nullptr; jmethodID exceptionConstructor = nullptr; jthrowable exception = nullptr; @@ -194,13 +191,12 @@ CHIP_ERROR ThrowInvalidEntryCodeFormatException(JNIEnv * env, jstring entryCodeO env->ExceptionClear(); exceptionCls = env->FindClass("chip/setuppayload/SetupPayloadParser$InvalidEntryCodeFormatException"); - VerifyOrExit(exceptionCls != NULL, err = SETUP_PAYLOAD_PARSER_JNI_ERROR_TYPE_NOT_FOUND); + VerifyOrReturnError(exceptionCls != NULL, SETUP_PAYLOAD_PARSER_JNI_ERROR_TYPE_NOT_FOUND); exceptionConstructor = env->GetMethodID(exceptionCls, "", "(Ljava/lang/String;)V"); - VerifyOrExit(exceptionConstructor != NULL, err = SETUP_PAYLOAD_PARSER_JNI_ERROR_METHOD_NOT_FOUND); + VerifyOrReturnError(exceptionConstructor != NULL, SETUP_PAYLOAD_PARSER_JNI_ERROR_METHOD_NOT_FOUND); exception = (jthrowable) env->NewObject(exceptionCls, exceptionConstructor, entryCodeObj); - VerifyOrExit(exception != NULL, err = SETUP_PAYLOAD_PARSER_JNI_ERROR_EXCEPTION_THROWN); + VerifyOrReturnError(exception != NULL, SETUP_PAYLOAD_PARSER_JNI_ERROR_EXCEPTION_THROWN); env->Throw(exception); -exit: - return err; + return CHIP_NO_ERROR; } diff --git a/src/transport/raw/BLE.cpp b/src/transport/raw/BLE.cpp index 9a00b275450a70..0f2432a81897ae 100644 --- a/src/transport/raw/BLE.cpp +++ b/src/transport/raw/BLE.cpp @@ -61,11 +61,10 @@ void BLEBase::ClearState() CHIP_ERROR BLEBase::Init(const BleListenParameters & param) { - CHIP_ERROR err = CHIP_NO_ERROR; BleLayer * bleLayer = param.GetBleLayer(); - VerifyOrExit(mState == State::kNotReady, err = CHIP_ERROR_INCORRECT_STATE); - VerifyOrExit(bleLayer != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mState == State::kNotReady, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(bleLayer != nullptr, CHIP_ERROR_INCORRECT_STATE); mBleLayer = bleLayer; mBleLayer->mBleTransport = this; @@ -73,25 +72,19 @@ CHIP_ERROR BLEBase::Init(const BleListenParameters & param) mState = State::kInitialized; - SuccessOrExit(err); - -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR BLEBase::SetEndPoint(Ble::BLEEndPoint * endPoint) { - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(endPoint->mState == BLEEndPoint::kState_Connected, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(endPoint->mState == BLEEndPoint::kState_Connected, CHIP_ERROR_INVALID_ARGUMENT); mBleEndPoint = endPoint; // Manually trigger the OnConnectComplete callback. - OnEndPointConnectComplete(endPoint, err); + OnEndPointConnectComplete(endPoint, CHIP_NO_ERROR); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR BLEBase::SendMessage(const Transport::PeerAddress & address, System::PacketBufferHandle && msgBuf)