From 397f5b429179f45a753817a2db6446e082e18978 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Thu, 29 Jan 2026 07:55:26 -0800 Subject: [PATCH] [coap] simplify response handler and use `Msg` class (#12338) This commit updates `Coap::ResponseHandler` to use a single `Coap::Msg` pointer instead of separate `Message` and `MessageInfo` pointers. The `Msg` class encapsulates both the CoAP message and its associated IP message info, simplifying the handler signature and usage. It retains support for the legacy `otCoapResponseHandler` signature (which uses separate parameters) for the public API by introducing `SendMessageWithResponseHandlerSeparateParams`. This ensures that public APIs like `otCoapSendRequest` continue to work without breaking changes while allowing internal modules to benefit from the simplified interface. It introduces `CoapBase::SendCallbacks` to consolidate the storage and invocation logic for different callback types, including the new `ResponseHandler`, the legacy `ResponseHandlerSeparateParams`, and block-wise transfer hooks. All internal modules (MLE, MeshCoP, Network Data, etc.) are updated to define their response handlers using the new `ResponseHandler` signature with `Msg` input. --- src/core/api/coap_api.cpp | 28 +-- src/core/api/coap_secure_api.cpp | 16 +- src/core/coap/coap.cpp | 197 ++++++++++++++-------- src/core/coap/coap.hpp | 119 ++++++++----- src/core/coap/coap_secure.cpp | 37 ++-- src/core/coap/coap_secure.hpp | 59 ++++--- src/core/meshcop/border_agent.cpp | 23 +-- src/core/meshcop/border_agent.hpp | 7 +- src/core/meshcop/commissioner.cpp | 30 ++-- src/core/meshcop/dataset_manager.cpp | 15 +- src/core/meshcop/dataset_manager.hpp | 6 +- src/core/meshcop/joiner.cpp | 17 +- src/core/meshcop/joiner_router.cpp | 11 +- src/core/thread/anycast_locator.cpp | 19 +-- src/core/thread/anycast_locator.hpp | 6 +- src/core/thread/dua_manager.cpp | 16 +- src/core/thread/mle.hpp | 2 +- src/core/thread/mle_ftd.cpp | 18 +- src/core/thread/mlr_manager.cpp | 46 ++--- src/core/thread/mlr_manager.hpp | 14 +- src/core/thread/network_data_notifier.cpp | 4 +- src/core/thread/network_diagnostic.cpp | 37 ++-- src/core/thread/network_diagnostic.hpp | 22 +-- src/core/thread/tmf.hpp | 38 +---- src/core/utils/history_tracker_server.cpp | 19 +-- src/core/utils/history_tracker_server.hpp | 10 +- src/core/utils/mesh_diag.cpp | 10 +- 27 files changed, 425 insertions(+), 401 deletions(-) diff --git a/src/core/api/coap_api.cpp b/src/core/api/coap_api.cpp index 72eedb9ad..90930de17 100644 --- a/src/core/api/coap_api.cpp +++ b/src/core/api/coap_api.cpp @@ -255,8 +255,12 @@ otError otCoapSendRequestWithParameters(otInstance *aInstance, VerifyOrExit(!AsCoreType(aMessage).IsOriginThreadNetif(), error = kErrorInvalidArgs); - error = AsCoreType(aInstance).Get().SendMessage( - AsCoapMessage(aMessage), AsCoreType(aMessageInfo), AsCoreTypePtr(aTxParameters), aHandler, aContext); + error = AsCoreType(aInstance).Get().SendMessageWithResponseHandlerSeparateParams( + AsCoapMessage(aMessage), AsCoreType(aMessageInfo), AsCoreTypePtr(aTxParameters), aHandler, +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + /* aTransmitHook */ nullptr, /* aReceiveHook */ nullptr, +#endif + aContext); exit: return error; @@ -346,9 +350,9 @@ otError otCoapSendRequestBlockWiseWithParameters(otInstance *aIn VerifyOrExit(!AsCoreType(aMessage).IsOriginThreadNetif(), error = kErrorInvalidArgs); - error = AsCoreType(aInstance).Get().SendMessage( - AsCoapMessage(aMessage), AsCoreType(aMessageInfo), AsCoreTypePtr(aTxParameters), aHandler, aContext, - aTransmitHook, aReceiveHook); + error = AsCoreType(aInstance).Get().SendMessageWithResponseHandlerSeparateParams( + AsCoapMessage(aMessage), AsCoreType(aMessageInfo), AsCoreTypePtr(aTxParameters), aHandler, aTransmitHook, + aReceiveHook, aContext); exit: return error; @@ -362,8 +366,8 @@ otError otCoapSendRequestBlockWise(otInstance *aInstance, otCoapBlockwiseTransmitHook aTransmitHook, otCoapBlockwiseReceiveHook aReceiveHook) { - return otCoapSendRequestBlockWiseWithParameters(aInstance, aMessage, aMessageInfo, aHandler, aContext, nullptr, - aTransmitHook, aReceiveHook); + return otCoapSendRequestBlockWiseWithParameters(aInstance, aMessage, aMessageInfo, aHandler, aContext, + /* aTxParameters */ nullptr, aTransmitHook, aReceiveHook); } otError otCoapSendResponseBlockWiseWithParameters(otInstance *aInstance, @@ -377,9 +381,9 @@ otError otCoapSendResponseBlockWiseWithParameters(otInstance *aI VerifyOrExit(!AsCoreType(aMessage).IsOriginThreadNetif(), error = kErrorInvalidArgs); - error = AsCoreType(aInstance).Get().SendMessage( - AsCoapMessage(aMessage), AsCoreType(aMessageInfo), AsCoreTypePtr(aTxParameters), nullptr, aContext, - aTransmitHook, nullptr); + error = AsCoreType(aInstance).Get().SendMessageWithResponseHandlerSeparateParams( + AsCoapMessage(aMessage), AsCoreType(aMessageInfo), AsCoreTypePtr(aTxParameters), /* aResponseHandler */ nullptr, + aTransmitHook, /* aReceiveHook */ nullptr, aContext); exit: return error; } @@ -390,8 +394,8 @@ otError otCoapSendResponseBlockWise(otInstance *aInstance, void *aContext, otCoapBlockwiseTransmitHook aTransmitHook) { - return otCoapSendResponseBlockWiseWithParameters(aInstance, aMessage, aMessageInfo, nullptr, aContext, - aTransmitHook); + return otCoapSendResponseBlockWiseWithParameters(aInstance, aMessage, aMessageInfo, /* aTxParamters */ nullptr, + aContext, aTransmitHook); } #endif // OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE diff --git a/src/core/api/coap_secure_api.cpp b/src/core/api/coap_secure_api.cpp index 3f322543a..0f0fc6bc3 100644 --- a/src/core/api/coap_secure_api.cpp +++ b/src/core/api/coap_secure_api.cpp @@ -159,8 +159,8 @@ otError otCoapSecureSendRequestBlockWise(otInstance *aInstance, otCoapBlockwiseTransmitHook aTransmitHook, otCoapBlockwiseReceiveHook aReceiveHook) { - return AsCoreType(aInstance).Get().SendMessage(AsCoapMessage(aMessage), aHandler, - aContext, aTransmitHook, aReceiveHook); + return AsCoreType(aInstance).Get().SendMessageWithResponseHandlerSeparateParams( + AsCoapMessage(aMessage), aHandler, aTransmitHook, aReceiveHook, aContext); } #endif @@ -169,8 +169,12 @@ otError otCoapSecureSendRequest(otInstance *aInstance, otCoapResponseHandler aHandler, void *aContext) { - return AsCoreType(aInstance).Get().SendMessage(AsCoapMessage(aMessage), aHandler, - aContext); + return AsCoreType(aInstance).Get().SendMessageWithResponseHandlerSeparateParams( + AsCoapMessage(aMessage), aHandler, +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + /* aTransmitHook */ nullptr, /* aReceiveHook */ nullptr, +#endif + aContext); } #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE @@ -216,8 +220,8 @@ otError otCoapSecureSendResponseBlockWise(otInstance *aInstance, { OT_UNUSED_VARIABLE(aMessageInfo); - return AsCoreType(aInstance).Get().SendMessage(AsCoapMessage(aMessage), nullptr, - aContext, aTransmitHook); + return AsCoreType(aInstance).Get().SendMessageWithResponseHandlerSeparateParams( + AsCoapMessage(aMessage), /* aResponseHandler */ nullptr, aTransmitHook, /* aReceiveHook */ nullptr, aContext); } #endif diff --git a/src/core/coap/coap.cpp b/src/core/coap/coap.cpp index f864b87a2..f25cf8a30 100644 --- a/src/core/coap/coap.cpp +++ b/src/core/coap/coap.cpp @@ -252,21 +252,10 @@ Error CoapBase::Send(ot::Message &aMessage, const Ip6::MessageInfo &aMessageInfo return error; } -#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE Error CoapBase::SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, const TxParameters *aTxParameters, - ResponseHandler aHandler, - void *aContext, - BlockwiseTransmitHook aTransmitHook, - BlockwiseReceiveHook aReceiveHook) -#else -Error CoapBase::SendMessage(Message &aMessage, - const Ip6::MessageInfo &aMessageInfo, - const TxParameters *aTxParameters, - ResponseHandler aHandler, - void *aContext) -#endif + const SendCallbacks &aCallbacks) { Error error; Message *storedCopy = nullptr; @@ -286,10 +275,7 @@ Error CoapBase::SendMessage(Message &aMessage, } #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - metadata.mBlockwiseReceiveHook = aReceiveHook; - metadata.mBlockwiseTransmitHook = aTransmitHook; - - SuccessOrExit(error = ProcessBlockwiseSend(txMsg, aTransmitHook, aContext)); + SuccessOrExit(error = ProcessBlockwiseSend(txMsg, aCallbacks)); #endif switch (txMsg.GetType()) @@ -309,7 +295,7 @@ Error CoapBase::SendMessage(Message &aMessage, { copyLength = txMsg.mMessage.GetLength(); } - else if (txMsg.IsNonConfirmable() && (aHandler != nullptr)) + else if (txMsg.IsNonConfirmable() && aCallbacks.HasResponseHandler()) { // As we do not retransmit non confirmable messages, create a // copy of header only, for token information. @@ -332,8 +318,7 @@ Error CoapBase::SendMessage(Message &aMessage, metadata.mDestinationPort = txMsg.mMessageInfo.GetPeerPort(); metadata.mDestinationAddress = txMsg.mMessageInfo.GetPeerAddr(); metadata.mMulticastLoop = txMsg.mMessageInfo.GetMulticastLoop(); - metadata.mResponseHandler = aHandler; - metadata.mResponseContext = aContext; + metadata.mCallbacks = aCallbacks; metadata.mRetransmissionsRemaining = aTxParameters->mMaxRetransmit; metadata.mRetransmissionTimeout = aTxParameters->CalculateInitialRetransmissionTimeout(); metadata.mAcknowledged = false; @@ -362,22 +347,47 @@ exit: return error; } +Error CoapBase::SendMessage(Message &aMessage, + const Ip6::MessageInfo &aMessageInfo, + const TxParameters *aTxParameters, + ResponseHandler aHandler, + void *aContext) +{ + SendCallbacks callbacks; + + callbacks.Clear(); + callbacks.mResponseHandler = aHandler; + callbacks.mContext = aContext; + + return SendMessage(aMessage, aMessageInfo, aTxParameters, callbacks); +} + Error CoapBase::SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, const TxParameters &aTxParameters) { - return SendMessage(aMessage, aMessageInfo, &aTxParameters, nullptr, nullptr); + SendCallbacks callbacks; + + callbacks.Clear(); + + return SendMessage(aMessage, aMessageInfo, &aTxParameters, callbacks); } Error CoapBase::SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, - ResponseHandler aHandler, + const ResponseHandler aHandler, void *aContext) { - return SendMessage(aMessage, aMessageInfo, nullptr, aHandler, aContext); + SendCallbacks callbacks; + + callbacks.Clear(); + callbacks.mContext = aContext; + callbacks.mResponseHandler = aHandler; + + return SendMessage(aMessage, aMessageInfo, /* aTxParameters */ nullptr, callbacks); } Error CoapBase::SendMessage(OwnedPtr aMessage, const Ip6::MessageInfo &aMessageInfo, - ResponseHandler aHandler, + const ResponseHandler aHandler, void *aContext) { Error error; @@ -409,6 +419,29 @@ exit: return error; } +Error CoapBase::SendMessageWithResponseHandlerSeparateParams(Message &aMessage, + const Ip6::MessageInfo &aMessageInfo, + const TxParameters *aTxParameters, + ResponseHandlerSeparateParams aHandler, +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + BlockwiseTransmitHook aTransmitHook, + BlockwiseReceiveHook aReceiveHook, +#endif + void *aContext) +{ + SendCallbacks callbacks; + + callbacks.Clear(); + callbacks.mResponseHandlerSeparateParams = aHandler; + callbacks.mContext = aContext; +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + callbacks.mBlockwiseTransmitHook = aTransmitHook; + callbacks.mBlockwiseReceiveHook = aReceiveHook; +#endif + + return SendMessage(aMessage, aMessageInfo, aTxParameters, callbacks); +} + Error CoapBase::SendReset(const Msg &aRxMsg) { return SendEmptyMessage(kTypeReset, aRxMsg); } Error CoapBase::SendAck(const Msg &aRxMsg) { return SendEmptyMessage(kTypeAck, aRxMsg); } @@ -556,7 +589,7 @@ void CoapBase::FinalizeCoapTransaction(Message &aRequest, const Metadata &aMetad { DequeueMessage(aRequest); - aMetadata.InvokeResponseHandler(aResponse, aResult); + aMetadata.mCallbacks.InvokeResponseHandler(aResponse, aResult); } Error CoapBase::AbortTransaction(ResponseHandler aHandler, void *aContext) @@ -568,7 +601,7 @@ Error CoapBase::AbortTransaction(ResponseHandler aHandler, void *aContext) { metadata.ReadFrom(message); - if (metadata.mResponseHandler == aHandler && metadata.mResponseContext == aContext) + if (metadata.mCallbacks.Matches(aHandler, aContext)) { FinalizeCoapTransaction(message, metadata, nullptr, kErrorAbort); error = kErrorNone; @@ -717,7 +750,7 @@ void CoapBase::ProcessReceivedResponse(Msg &aRxMsg) // response, and we have a response handler; then we're dealing // with RFC7641 rules here. If there is no response handler, then // we're wasting our time! - if (metadata.mObserve && metadata.mIsRequest && (metadata.mResponseHandler != nullptr)) + if (metadata.mObserve && metadata.mIsRequest && metadata.mCallbacks.HasResponseHandler()) { Option::Iterator iterator; @@ -765,7 +798,7 @@ void CoapBase::ProcessReceivedResponse(Msg &aRxMsg) // Remove the message if response is not expected, otherwise await // response. - if (metadata.mResponseHandler == nullptr) + if (!metadata.mCallbacks.HasResponseHandler()) { DequeueMessage(*request); } @@ -779,7 +812,7 @@ void CoapBase::ProcessReceivedResponse(Msg &aRxMsg) if (shouldObserve) { // This is a RFC7641 notification. The request is *not* done! - metadata.InvokeResponseHandler(&aRxMsg, kErrorNone); + metadata.mCallbacks.InvokeResponseHandler(&aRxMsg, kErrorNone); // Consider the message acknowledged at this point. metadata.mAcknowledged = true; @@ -813,7 +846,7 @@ void CoapBase::ProcessReceivedResponse(Msg &aRxMsg) #if OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE if (shouldObserve) { - metadata.InvokeResponseHandler(&aRxMsg, kErrorNone); + metadata.mCallbacks.InvokeResponseHandler(&aRxMsg, kErrorNone); // When any Observe response is seen, consider a NON observe // request "acknowledged" at this point. This will keep the @@ -833,9 +866,9 @@ void CoapBase::ProcessReceivedResponse(Msg &aRxMsg) // If the request was to a multicast address, then this is NOT // the final message, we may see more. - if ((metadata.mResponseHandler != nullptr) && metadata.mDestinationAddress.IsMulticast()) + if (metadata.mCallbacks.HasResponseHandler() && metadata.mDestinationAddress.IsMulticast()) { - metadata.InvokeResponseHandler(&aRxMsg, kErrorNone); + metadata.mCallbacks.InvokeResponseHandler(&aRxMsg, kErrorNone); } else { @@ -958,16 +991,7 @@ void CoapBase::RemoveBlockWiseResource(ResourceBlockWise &aResource) aResource.SetNext(nullptr); } -Error CoapBase::SendMessage(Message &aMessage, - const Ip6::MessageInfo &aMessageInfo, - const TxParameters *aTxParameters, - ResponseHandler aHandler, - void *aContext) -{ - return SendMessage(aMessage, aMessageInfo, aTxParameters, aHandler, aContext, nullptr, nullptr); -} - -Error CoapBase::ProcessBlockwiseSend(Msg &aMsg, BlockwiseTransmitHook aTransmitHook, void *aContext) +Error CoapBase::ProcessBlockwiseSend(Msg &aMsg, const SendCallbacks &aCallbacks) { Error error = kErrorNone; uint8_t type = aMsg.GetType(); @@ -978,7 +1002,7 @@ Error CoapBase::ProcessBlockwiseSend(Msg &aMsg, BlockwiseTransmitHook aTransmitH VerifyOrExit(type != kTypeReset); - VerifyOrExit(aTransmitHook != nullptr); + VerifyOrExit(aCallbacks.HasBlockwiseTransmitHook()); SuccessOrExit(aMsg.mMessage.ReadBlockOptionValues(type == kTypeAck ? kOptionBlock2 : kOptionBlock1, blockInfo)); @@ -987,7 +1011,7 @@ Error CoapBase::ProcessBlockwiseSend(Msg &aMsg, BlockwiseTransmitHook aTransmitH blockSize = blockInfo.GetBlockSize(); VerifyOrExit(blockSize <= kMaxBlockSize, error = kErrorNoBufs); - SuccessOrExit(error = aTransmitHook(aContext, buf, 0, &blockSize, &moreBlocks)); + SuccessOrExit(error = aCallbacks.mBlockwiseTransmitHook(aCallbacks.mContext, buf, 0, &blockSize, &moreBlocks)); SuccessOrExit(error = aMsg.mMessage.AppendBytes(buf, blockSize)); switch (type) @@ -1015,7 +1039,7 @@ Error CoapBase::ProcessBlockwiseResponse(Msg &aRxMsg, Message &aRequest, const M uint8_t blockOptionType = 0; uint32_t totalTransferSize = 0; - if (aMetadata.mBlockwiseTransmitHook != nullptr || aMetadata.mBlockwiseReceiveHook != nullptr) + if (aMetadata.mCallbacks.HasBlockwiseTransmitHook() || aMetadata.mCallbacks.HasBlockwiseReceiveHook()) { // Search for CoAP Block-Wise Option [RFC7959] Option::Iterator iterator; @@ -1054,29 +1078,31 @@ Error CoapBase::ProcessBlockwiseResponse(Msg &aRxMsg, Message &aRequest, const M FinalizeCoapTransaction(aRequest, aMetadata, &aRxMsg, kErrorNone); break; case 1: // Block1 option - if (aRxMsg.GetCode() == kCodeContinue && aMetadata.mBlockwiseTransmitHook != nullptr) + if (aRxMsg.GetCode() == kCodeContinue && aMetadata.mCallbacks.HasBlockwiseTransmitHook()) { error = SendNextBlock1Request(aRequest, aRxMsg, aMetadata); } - if (aRxMsg.GetCode() != kCodeContinue || aMetadata.mBlockwiseTransmitHook == nullptr || error != kErrorNone) + if (aRxMsg.GetCode() != kCodeContinue || !aMetadata.mCallbacks.HasBlockwiseTransmitHook() || + error != kErrorNone) { FinalizeCoapTransaction(aRequest, aMetadata, &aRxMsg, error); } break; case 2: // Block2 option - if (aRxMsg.GetCode() < kCodeBadRequest && aMetadata.mBlockwiseReceiveHook != nullptr) + if (aRxMsg.GetCode() < kCodeBadRequest && aMetadata.mCallbacks.HasBlockwiseReceiveHook()) { error = SendNextBlock2Request(aRequest, aRxMsg, aMetadata, totalTransferSize, false); } - if (aRxMsg.GetCode() >= kCodeBadRequest || aMetadata.mBlockwiseReceiveHook == nullptr || error != kErrorNone) + if (aRxMsg.GetCode() >= kCodeBadRequest || !aMetadata.mCallbacks.HasBlockwiseReceiveHook() || + error != kErrorNone) { FinalizeCoapTransaction(aRequest, aMetadata, &aRxMsg, error); } break; case 3: // Block1 & Block2 option - if (aRxMsg.GetCode() < kCodeBadRequest && aMetadata.mBlockwiseReceiveHook != nullptr) + if (aRxMsg.GetCode() < kCodeBadRequest && aMetadata.mCallbacks.HasBlockwiseReceiveHook()) { error = SendNextBlock2Request(aRequest, aRxMsg, aMetadata, totalTransferSize, true); } @@ -1315,9 +1341,9 @@ Error CoapBase::SendNextBlock1Request(Message &aRequest, Msg &aRxMsg, const Meta requestBlockInfo.mBlockSzx = msgBlockInfo.mBlockSzx; requestBlockInfo.mMoreBlocks = false; - SuccessOrExit(error = aMetadata.mBlockwiseTransmitHook(aMetadata.mResponseContext, buf, - requestBlockInfo.GetBlockOffsetPosition(), &blockSize, - &requestBlockInfo.mMoreBlocks)); + SuccessOrExit(error = aMetadata.mCallbacks.mBlockwiseTransmitHook(aMetadata.mCallbacks.mContext, buf, + requestBlockInfo.GetBlockOffsetPosition(), + &blockSize, &requestBlockInfo.mMoreBlocks)); VerifyOrExit(blockSize <= msgBlockInfo.GetBlockSize(), error = kErrorInvalidArgs); @@ -1334,9 +1360,7 @@ Error CoapBase::SendNextBlock1Request(Message &aRequest, Msg &aRxMsg, const Meta LogInfo("Send Block1 Nr. %d, Size: %d bytes, More Blocks Flag: %d", requestBlockInfo.mBlockNumber, requestBlockInfo.GetBlockSize(), requestBlockInfo.mMoreBlocks); - SuccessOrExit(error = SendMessage(*request, aRxMsg.mMessageInfo, /* aTxParamters */ nullptr, - aMetadata.mResponseHandler, aMetadata.mResponseContext, - aMetadata.mBlockwiseTransmitHook, aMetadata.mBlockwiseReceiveHook)); + SuccessOrExit(error = SendMessage(*request, aRxMsg.mMessageInfo, /* aTxParamters */ nullptr, aMetadata.mCallbacks)); exit: FreeMessageOnError(request, error); @@ -1350,12 +1374,13 @@ Error CoapBase::SendNextBlock2Request(Message &aRequest, uint32_t aTotalLength, bool aBeginBlock1Transfer) { - Error error = kErrorNone; - Message *request = nullptr; - uint8_t buf[kMaxBlockSize]; - OffsetRange offsetRange; - BlockInfo msgBlockInfo; - BlockInfo requestBlockInfo; + Error error = kErrorNone; + Message *request = nullptr; + uint8_t buf[kMaxBlockSize]; + OffsetRange offsetRange; + BlockInfo msgBlockInfo; + BlockInfo requestBlockInfo; + SendCallbacks callbacks; SuccessOrExit(error = aRxMsg.mMessage.ReadBlockOptionValues(kOptionBlock2, msgBlockInfo)); @@ -1365,9 +1390,9 @@ Error CoapBase::SendNextBlock2Request(Message &aRequest, VerifyOrExit(offsetRange.GetLength() <= msgBlockInfo.GetBlockSize(), error = kErrorNoBufs); aRxMsg.mMessage.ReadBytes(offsetRange, buf); - SuccessOrExit( - error = aMetadata.mBlockwiseReceiveHook(aMetadata.mResponseContext, buf, msgBlockInfo.GetBlockOffsetPosition(), - offsetRange.GetLength(), msgBlockInfo.mMoreBlocks, aTotalLength)); + SuccessOrExit(error = aMetadata.mCallbacks.mBlockwiseReceiveHook( + aMetadata.mCallbacks.mContext, buf, msgBlockInfo.GetBlockOffsetPosition(), + offsetRange.GetLength(), msgBlockInfo.mMoreBlocks, aTotalLength)); LogInfo("Received Block2 Nr. %d , Size: %d bytes, More Blocks Flag: %d", msgBlockInfo.mBlockNumber, msgBlockInfo.GetBlockSize(), msgBlockInfo.mMoreBlocks); @@ -1392,9 +1417,10 @@ Error CoapBase::SendNextBlock2Request(Message &aRequest, LogInfo("Request Block2 Nr. %d, Size: %d bytes", requestBlockInfo.mBlockNumber, requestBlockInfo.GetBlockSize()); - SuccessOrExit(error = SendMessage(*request, aRxMsg.mMessageInfo, /* aTxParameters */ nullptr, - aMetadata.mResponseHandler, aMetadata.mResponseContext, nullptr, - aMetadata.mBlockwiseReceiveHook)); + callbacks = aMetadata.mCallbacks; + callbacks.mBlockwiseTransmitHook = nullptr; + + SuccessOrExit(error = SendMessage(*request, aRxMsg.mMessageInfo, /* aTxParameters */ nullptr, callbacks)); exit: FreeMessageOnError(request, error); @@ -1621,16 +1647,47 @@ bool CoapBase::IsObserveSubscription(const Metadata &aMetadata) #endif // OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE //--------------------------------------------------------------------------------------------------------------------- -// CoapBase::Metadata +// CoapBase::SendCallbacks -void CoapBase::Metadata::InvokeResponseHandler(Msg *aMsg, Error aResult) const +void CoapBase::SendCallbacks::Clear(void) +{ + // We avoid using `ClearAllBytes()` or `Clearable` because they + // zero out all object memory. Unlike standard data pointers, the + // C++ standard does not strictly guarantee that a `nullptr` + // function pointer is represented by an "all-bits-zero" memory + // pattern. + + mContext = nullptr; + mResponseHandler = nullptr; + mResponseHandlerSeparateParams = nullptr; +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + mBlockwiseReceiveHook = nullptr; + mBlockwiseTransmitHook = nullptr; +#endif +} + +bool CoapBase::SendCallbacks::HasResponseHandler(void) const +{ + return (mResponseHandler != nullptr) || (mResponseHandlerSeparateParams != nullptr); +} + +bool CoapBase::SendCallbacks::Matches(ResponseHandler aHandler, void *aContext) const +{ + return (mResponseHandler == aHandler) && (mContext == aContext); +} + +void CoapBase::SendCallbacks::InvokeResponseHandler(Msg *aMsg, Error aResult) const { if (mResponseHandler != nullptr) + { + mResponseHandler(mContext, aMsg, aResult); + } + else if (mResponseHandlerSeparateParams != nullptr) { Message *message = (aMsg != nullptr) ? &aMsg->mMessage : nullptr; const Ip6::MessageInfo *messageInfo = (aMsg != nullptr) ? &aMsg->mMessageInfo : nullptr; - mResponseHandler(mResponseContext, message, messageInfo, aResult); + mResponseHandlerSeparateParams(mContext, message, messageInfo, aResult); } } diff --git a/src/core/coap/coap.hpp b/src/core/coap/coap.hpp index e6799b8a4..ac76fa1a6 100644 --- a/src/core/coap/coap.hpp +++ b/src/core/coap/coap.hpp @@ -71,9 +71,26 @@ class CoapBase; /** * Represents a function pointer which is called when a CoAP response is received or on the request timeout. * + * This is the callback function definition used by the public `otCoap` APIs where the `aMessage` and `aMessageInfo` + * are passed as separate parameters. Core modules should use `ResponseHandler` callback instead which gets a single + * `Msg` input (encapsulating both message and its `Ip6::MessageInfo`). + * * Please see otCoapResponseHandler for details. */ -typedef otCoapResponseHandler ResponseHandler; +typedef otCoapResponseHandler ResponseHandlerSeparateParams; + +/** + * Represents a function pointer which is called when a CoAP response is received or on the request timeout + * + * @param[in] aContext A pointer to application-specific context. + * @param[in] aMessage A pointer to the received `Msg` response. `nullptr` if no response was received. + * @param[in] aResult A result of the CoAP transaction. + * + * @retval kErrorNone A response was received successfully. + * @retval kErrorAbort The CoAP transaction was reset by peer. + * @retval kErrorResponseTimeout No response or acknowledgment received during timeout period. + */ +typedef void (*ResponseHandler)(void *aContext, Msg *aMsg, Error aResult); /** * Represents a function pointer which is called when a CoAP request associated with a given URI path is @@ -636,6 +653,33 @@ public: */ void GetRequestAndCachedResponsesQueueInfo(MessageQueue::Info &aQueueInfo) const; + /** + * Sends a CoAP message with custom transmission parameters using `ResponseHandlerSeparateParams` handle type. + * + * This version of `SendMessage()` is intended for use by the public OT CoAP APIs, `otCoap*` and should not be used + * within the OpenThread core modules. + * + * @param[in] aMessage A reference to the message to send. + * @param[in] aMessageInfo A reference to the message info associated with @p aMessage. + * @param[in] aTxParameters A pointer to `TxParameters`. If `nullptr`, default `TxParameters will be used. + * @param[in] aHandler A function pointer that shall be called on response reception or time-out. + * @param[in] aTransmitHook A pointer to a hook function for outgoing block-wise transfer. + * @param[in] aReceiveHook A pointer to a hook function for incoming block-wise transfer. + * @param[in] aContext A pointer to arbitrary context information. + * + * @retval kErrorNone Successfully sent CoAP message. + * @retval kErrorNoBufs Failed to allocate retransmission data. + */ + Error SendMessageWithResponseHandlerSeparateParams(Message &aMessage, + const Ip6::MessageInfo &aMessageInfo, + const TxParameters *aTxParameters, + ResponseHandlerSeparateParams aHandler, +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + BlockwiseTransmitHook aTransmitHook, + BlockwiseReceiveHook aReceiveHook, +#endif + void *aContext); + #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE /** * Adds a block-wise resource to the CoAP server. @@ -651,32 +695,6 @@ public: */ void RemoveBlockWiseResource(ResourceBlockWise &aResource); - /** - * Sends a CoAP message block-wise with custom transmission parameters. - * - * If a response for a request is expected, respective function and context information should be provided. - * If no response is expected, these arguments should be NULL pointers. - * If Message ID was not set in the header (equal to 0), this method will assign unique Message ID to the message. - * - * @param[in] aMessage A reference to the message to send. - * @param[in] aMessageInfo A reference to the message info associated with @p aMessage. - * @param[in] aTxParameters A pointer to `TxParameters`. If `nullptr`, default `TxParameters will be used. - * @param[in] aHandler A function pointer that shall be called on response reception or time-out. - * @param[in] aContext A pointer to arbitrary context information. - * @param[in] aTransmitHook A pointer to a hook function for outgoing block-wise transfer. - * @param[in] aReceiveHook A pointer to a hook function for incoming block-wise transfer. - * - * @retval kErrorNone Successfully sent CoAP message. - * @retval kErrorNoBufs Failed to allocate retransmission data. - */ - Error SendMessage(Message &aMessage, - const Ip6::MessageInfo &aMessageInfo, - const TxParameters *aTxParameters, - otCoapResponseHandler aHandler, - void *aContext, - BlockwiseTransmitHook aTransmitHook, - BlockwiseReceiveHook aReceiveHook); - /** * Sends a header-only CoAP message to indicate not all blocks have been sent or * were sent out of order. @@ -744,18 +762,35 @@ protected: private: static constexpr uint16_t kMaxBlockSize = OPENTHREAD_CONFIG_COAP_MAX_BLOCK_LENGTH; + struct SendCallbacks + { + void Clear(void); + bool HasResponseHandler(void) const; + bool Matches(ResponseHandler aHandler, void *aContext) const; + void InvokeResponseHandler(Msg *aMsg, Error aResult) const; +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + bool HasBlockwiseReceiveHook(void) const { return mBlockwiseReceiveHook != nullptr; } + bool HasBlockwiseTransmitHook(void) const { return mBlockwiseTransmitHook != nullptr; } +#endif + + void *mContext; + ResponseHandler mResponseHandler; + ResponseHandlerSeparateParams mResponseHandlerSeparateParams; +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + BlockwiseReceiveHook mBlockwiseReceiveHook; + BlockwiseTransmitHook mBlockwiseTransmitHook; +#endif + }; + struct Metadata : public Message::FooterData { - void InvokeResponseHandler(Msg *aMsg, Error aResult) const; - - Ip6::Address mSourceAddress; // IPv6 address of the message source. - Ip6::Address mDestinationAddress; // IPv6 address of the message destination. - uint16_t mDestinationPort; // UDP port of the message destination. - ResponseHandler mResponseHandler; // A function pointer that is called on response reception. - void *mResponseContext; // A pointer to arbitrary context information. - TimeMilli mNextTimerShot; // Time when the timer should shoot for this message. - uint32_t mRetransmissionTimeout; // Delay that is applied to next retransmission. - uint8_t mRetransmissionsRemaining; // Number of retransmissions remaining. + Ip6::Address mSourceAddress; // IPv6 address of the message source. + Ip6::Address mDestinationAddress; // IPv6 address of the message destination. + uint16_t mDestinationPort; // UDP port of the message destination. + SendCallbacks mCallbacks; // All callbacks, response handler and clockwise rx/tx hooks. + TimeMilli mNextTimerShot; // Time when the timer should shoot for this message. + uint32_t mRetransmissionTimeout; // Delay that is applied to next retransmission. + uint8_t mRetransmissionsRemaining; // Number of retransmissions remaining. #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE uint8_t mHopLimit; // The hop limit. #endif @@ -768,10 +803,6 @@ private: #if OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE bool mObserve : 1; // Information that this request involves Observations. bool mIsRequest : 1; -#endif -#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - BlockwiseReceiveHook mBlockwiseReceiveHook; // Function pointer called on Block2 response reception. - BlockwiseTransmitHook mBlockwiseTransmitHook; // Function pointer called on Block1 response reception. #endif }; @@ -818,13 +849,17 @@ private: bool InvokeResponseFallback(Msg &aRxMsg) const; void ProcessReceivedRequest(Msg &aRxMsg); void ProcessReceivedResponse(Msg &aRxMsg); + Error SendMessage(Message &aMessage, + const Ip6::MessageInfo &aMessageInfo, + const TxParameters *aTxParameters, + const SendCallbacks &aCallbacks); void SendCopy(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); Error SendEmptyMessage(Type aType, const Msg &aRxMsg); Error Send(ot::Message &aMessage, const Ip6::MessageInfo &aMessageInfo); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - Error ProcessBlockwiseSend(Msg &aMsg, BlockwiseTransmitHook aTransmitHook, void *aContext); + Error ProcessBlockwiseSend(Msg &aMsg, const SendCallbacks &aCallbacks); Error ProcessBlockwiseResponse(Msg &aRxMsg, Message &aRequest, const Metadata &aMetadata); Error ProcessBlockwiseRequest(Msg &aRxMsg, Message::UriPathStringBuffer &aUriPath, bool &aDidHandle); void FreeLastBlockResponse(void); diff --git a/src/core/coap/coap_secure.cpp b/src/core/coap/coap_secure.cpp index 516a204d1..b08cc19c8 100644 --- a/src/core/coap/coap_secure.cpp +++ b/src/core/coap/coap_secure.cpp @@ -58,27 +58,32 @@ void SecureSession::Cleanup(void) mTransmitTask.Unpost(); } -#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - -Error SecureSession::SendMessage(Message &aMessage, - ResponseHandler aHandler, - void *aContext, - otCoapBlockwiseTransmitHook aTransmitHook, - otCoapBlockwiseReceiveHook aReceiveHook) -{ - return IsConnected() ? CoapBase::SendMessage(aMessage, GetMessageInfo(), /* aTxParameters */ nullptr, aHandler, - aContext, aTransmitHook, aReceiveHook) - : kErrorInvalidState; -} - -#else - Error SecureSession::SendMessage(Message &aMessage, ResponseHandler aHandler, void *aContext) { return IsConnected() ? CoapBase::SendMessage(aMessage, GetMessageInfo(), aHandler, aContext) : kErrorInvalidState; } -#endif // OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE +Error SecureSession::SendMessage(Message &aMessage) +{ + return IsConnected() ? CoapBase::SendMessage(aMessage, GetMessageInfo()) : kErrorInvalidState; +} + +Error SecureSession::SendMessageWithResponseHandlerSeparateParams(Message &aMessage, + ResponseHandlerSeparateParams aHandler, +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + BlockwiseTransmitHook aTransmitHook, + BlockwiseReceiveHook aReceiveHook, +#endif + void *aContext) +{ + return IsConnected() ? CoapBase::SendMessageWithResponseHandlerSeparateParams(aMessage, GetMessageInfo(), + /* aTxParameters */ nullptr, aHandler, +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + aTransmitHook, aReceiveHook, +#endif + aContext) + : kErrorInvalidState; +} Error SecureSession::Transmit(CoapBase &aCoapBase, ot::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { diff --git a/src/core/coap/coap_secure.hpp b/src/core/coap/coap_secure.hpp index 86fa61012..6d700ef26 100644 --- a/src/core/coap/coap_secure.hpp +++ b/src/core/coap/coap_secure.hpp @@ -73,10 +73,38 @@ public: */ void SetConnectCallback(ConnectHandler aHandler, void *aContext) { mConnectCallback.Set(aHandler, aContext); } -#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE /** * Sends a CoAP message over secure DTLS session. * + * If Message Id was not set in the header (equal to 0), this function will assign unique Message Id to the message. + * + * @param[in] aMessage A reference to the message to send. + * @param[in] aHandler A function pointer that shall be called on response reception or time-out. + * @param[in] aContext A pointer to arbitrary context information. + * + * @retval kErrorNone Successfully sent CoAP message. + * @retval kErrorNoBufs Failed to allocate retransmission data. + * @retval kErrorInvalidState DTLS connection was not initialized. + */ + Error SendMessage(Message &aMessage, ResponseHandler aHandler, void *aContext); + + /** + * Sends a CoAP message over secure DTLS session. + * + * @param[in] aMessage A reference to the message to send. + * + * @retval kErrorNone Successfully sent CoAP message. + * @retval kErrorNoBufs Failed to allocate retransmission data. + * @retval kErrorInvalidState DTLS connection was not initialized. + */ + Error SendMessage(Message &aMessage); + + /** + * Sends a CoAP message over secure DTLS session using `ResponseHandlerSeparateParams` handle type. + * + * This version of `SendMessage()` is intended for use by the public OT CoAP APIs, `otCoap*` and should not be used + * within the OpenThread core modules. + * * If a response for a request is expected, respective function and context information should be provided. * If no response is expected, these arguments should be NULL pointers. * If Message Id was not set in the header (equal to 0), this function will assign unique Message Id to the message. @@ -91,30 +119,13 @@ public: * @retval kErrorNoBufs Failed to allocate retransmission data. * @retval kErrorInvalidState DTLS connection was not initialized. */ - Error SendMessage(Message &aMessage, - ResponseHandler aHandler = nullptr, - void *aContext = nullptr, - otCoapBlockwiseTransmitHook aTransmitHook = nullptr, - otCoapBlockwiseReceiveHook aReceiveHook = nullptr); - -#else - /** - * Sends a CoAP message over secure DTLS session. - * - * If a response for a request is expected, respective function and context information should be provided. - * If no response is expected, these arguments should be nullptr pointers. - * If Message Id was not set in the header (equal to 0), this function will assign unique Message Id to the message. - * - * @param[in] aMessage A reference to the message to send. - * @param[in] aHandler A function pointer that shall be called on response reception or time-out. - * @param[in] aContext A pointer to arbitrary context information. - * - * @retval kErrorNone Successfully sent CoAP message. - * @retval kErrorNoBufs Failed to allocate retransmission data. - * @retval kErrorInvalidState DTLS connection was not initialized. - */ - Error SendMessage(Message &aMessage, ResponseHandler aHandler = nullptr, void *aContext = nullptr); + Error SendMessageWithResponseHandlerSeparateParams(Message &aMessage, + ResponseHandlerSeparateParams aHandler, +#if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE + BlockwiseTransmitHook aTransmitHook, + BlockwiseReceiveHook aReceiveHook, #endif + void *aContext); protected: SecureSession(Instance &aInstance, Dtls::Transport &aDtlsTransport); diff --git a/src/core/meshcop/border_agent.cpp b/src/core/meshcop/border_agent.cpp index 181c6c869..47b3e448c 100644 --- a/src/core/meshcop/border_agent.cpp +++ b/src/core/meshcop/border_agent.cpp @@ -718,20 +718,15 @@ exit: return error; } -void Manager::CoapDtlsSession::HandleLeaderResponseToFwdTmf(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aResult) +void Manager::CoapDtlsSession::HandleLeaderResponseToFwdTmf(void *aContext, Coap::Msg *aMsg, otError aResult) { - OT_UNUSED_VARIABLE(aMessageInfo); - OwnedPtr forwardContext(static_cast(aContext)); - forwardContext->mSession.HandleLeaderResponseToFwdTmf(*forwardContext.Get(), AsCoapMessagePtr(aMessage), aResult); + forwardContext->mSession.HandleLeaderResponseToFwdTmf(*forwardContext.Get(), aMsg, aResult); } void Manager::CoapDtlsSession::HandleLeaderResponseToFwdTmf(const ForwardContext &aForwardContext, - const Coap::Message *aResponse, + const Coap::Msg *aResponse, Error aResult) { OwnedPtr forwardMessage; @@ -756,11 +751,11 @@ void Manager::CoapDtlsSession::HandleLeaderResponseToFwdTmf(const ForwardContext forwardMessage.Reset(NewPriorityMessage()); VerifyOrExit(forwardMessage != nullptr, error = kErrorNoBufs); - if (aResponse->ReadCode() == Coap::kCodeChanged) + if (aResponse->GetCode() == Coap::kCodeChanged) { uint8_t state; - SuccessOrExit(error = Tlv::Find(*aResponse, state)); + SuccessOrExit(error = Tlv::Find(aResponse->mMessage, state)); switch (state) { @@ -769,7 +764,7 @@ void Manager::CoapDtlsSession::HandleLeaderResponseToFwdTmf(const ForwardContext { uint16_t sessionId; - SuccessOrExit(error = Tlv::Find(*aResponse, sessionId)); + SuccessOrExit(error = Tlv::Find(aResponse->mMessage, sessionId)); Get().HandleCommissionerPetitionAccepted(*this, sessionId); } @@ -785,15 +780,15 @@ void Manager::CoapDtlsSession::HandleLeaderResponseToFwdTmf(const ForwardContext } SuccessOrExit(error = - forwardMessage->Init(Coap::kTypeNonConfirmable, static_cast(aResponse->ReadCode()))); + forwardMessage->Init(Coap::kTypeNonConfirmable, static_cast(aResponse->GetCode()))); SuccessOrExit(error = forwardMessage->WriteToken(aForwardContext.mToken)); - if (aResponse->GetLength() > aResponse->GetOffset()) + if (aResponse->mMessage.GetLength() > aResponse->mMessage.GetOffset()) { SuccessOrExit(error = forwardMessage->AppendPayloadMarker()); } - SuccessOrExit(error = ForwardToCommissioner(forwardMessage.PassOwnership(), *aResponse)); + SuccessOrExit(error = ForwardToCommissioner(forwardMessage.PassOwnership(), aResponse->mMessage)); exit: if (error != kErrorNone) diff --git a/src/core/meshcop/border_agent.hpp b/src/core/meshcop/border_agent.hpp index bfd8b5456..ed23967e1 100644 --- a/src/core/meshcop/border_agent.hpp +++ b/src/core/meshcop/border_agent.hpp @@ -312,12 +312,9 @@ private: static void HandleConnected(ConnectEvent aEvent, void *aContext); void HandleConnected(ConnectEvent aEvent); - static void HandleLeaderResponseToFwdTmf(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aResult); + static void HandleLeaderResponseToFwdTmf(void *aContext, Coap::Msg *aMsg, otError aResult); void HandleLeaderResponseToFwdTmf(const ForwardContext &aForwardContext, - const Coap::Message *aResponse, + const Coap::Msg *aResponse, Error aResult); static bool HandleResource(CoapBase &aCoapBase, const char *aUriPath, Coap::Msg &aMsg); bool HandleResource(const char *aUriPath, Coap::Msg &aMsg); diff --git a/src/core/meshcop/commissioner.cpp b/src/core/meshcop/commissioner.cpp index ea4ea68c6..545990a6d 100644 --- a/src/core/meshcop/commissioner.cpp +++ b/src/core/meshcop/commissioner.cpp @@ -617,7 +617,7 @@ Error Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, uint8_t messageInfo.SetSockAddrToRlocPeerAddrToLeaderAloc(); SuccessOrExit(error = Get().SendMessage(message.PassOwnership(), messageInfo, - Commissioner::HandleMgmtCommissionerGetResponse, this)); + HandleMgmtCommissionerGetResponse, this)); LogInfo("Sent %s to leader", UriToString()); @@ -625,9 +625,9 @@ exit: return error; } -void Commissioner::HandleMgmtCommissionerGetResponse(Coap::Message *aMessage, Error aResult) +void Commissioner::HandleMgmtCommissionerGetResponse(Coap::Msg *aMsg, Error aResult) { - VerifyOrExit(aResult == kErrorNone && aMessage->ReadCode() == Coap::kCodeChanged); + VerifyOrExit(aResult == kErrorNone && aMsg->GetCode() == Coap::kCodeChanged); LogInfo("Received %s response", UriToString()); exit: @@ -674,7 +674,7 @@ Error Commissioner::SendMgmtCommissionerSetRequest(const CommissioningDataset &a messageInfo.SetSockAddrToRlocPeerAddrToLeaderAloc(); SuccessOrExit(error = Get().SendMessage(message.PassOwnership(), messageInfo, - Commissioner::HandleMgmtCommissionerSetResponse, this)); + HandleMgmtCommissionerSetResponse, this)); LogInfo("Sent %s to leader", UriToString()); @@ -682,13 +682,13 @@ exit: return error; } -void Commissioner::HandleMgmtCommissionerSetResponse(Coap::Message *aMessage, Error aResult) +void Commissioner::HandleMgmtCommissionerSetResponse(Coap::Msg *aMsg, Error aResult) { Error error; uint8_t state; SuccessOrExit(error = aResult); - VerifyOrExit(aMessage->ReadCode() == Coap::kCodeChanged && Tlv::Find(*aMessage, state) == kErrorNone && + VerifyOrExit(aMsg->GetCode() == Coap::kCodeChanged && Tlv::Find(aMsg->mMessage, state) == kErrorNone && state != StateTlv::kPending, error = kErrorParse); @@ -713,7 +713,7 @@ Error Commissioner::SendPetition(void) messageInfo.SetSockAddrToRlocPeerAddrToLeaderAloc(); SuccessOrExit(error = Get().SendMessage(message.PassOwnership(), messageInfo, - Commissioner::HandleLeaderPetitionResponse, this)); + HandleLeaderPetitionResponse, this)); LogInfo("Sent %s", UriToString()); @@ -721,21 +721,21 @@ exit: return error; } -void Commissioner::HandleLeaderPetitionResponse(Coap::Message *aMessage, Error aResult) +void Commissioner::HandleLeaderPetitionResponse(Coap::Msg *aMsg, Error aResult) { uint8_t state; bool retransmit = false; VerifyOrExit(mState != kStateActive); - VerifyOrExit(aResult == kErrorNone && aMessage->ReadCode() == Coap::kCodeChanged, + VerifyOrExit(aResult == kErrorNone && aMsg->GetCode() == Coap::kCodeChanged, retransmit = (mState == kStatePetition)); LogInfo("Received %s response", UriToString()); - SuccessOrExit(Tlv::Find(*aMessage, state)); + SuccessOrExit(Tlv::Find(aMsg->mMessage, state)); VerifyOrExit(state == StateTlv::kAccept, IgnoreError(Stop(kDoNotSendKeepAlive))); - SuccessOrExit(Tlv::Find(*aMessage, mSessionId)); + SuccessOrExit(Tlv::Find(aMsg->mMessage, mSessionId)); // reject this session by sending KeepAlive reject if commissioner is in disabled state // this could happen if commissioner is stopped by API during petitioning @@ -786,7 +786,7 @@ void Commissioner::SendKeepAlive(uint16_t aSessionId) messageInfo.SetSockAddrToRlocPeerAddrToLeaderAloc(); SuccessOrExit(error = Get().SendMessage(message.PassOwnership(), messageInfo, - Commissioner::HandleLeaderKeepAliveResponse, this)); + HandleLeaderKeepAliveResponse, this)); LogInfo("Sent %s", UriToString()); @@ -794,17 +794,17 @@ exit: LogWarnOnError(error, "send keep alive"); } -void Commissioner::HandleLeaderKeepAliveResponse(Coap::Message *aMessage, Error aResult) +void Commissioner::HandleLeaderKeepAliveResponse(Coap::Msg *aMsg, Error aResult) { uint8_t state; VerifyOrExit(mState == kStateActive); - VerifyOrExit(aResult == kErrorNone && aMessage->ReadCode() == Coap::kCodeChanged, + VerifyOrExit(aResult == kErrorNone && aMsg->GetCode() == Coap::kCodeChanged, IgnoreError(Stop(kDoNotSendKeepAlive))); LogInfo("Received %s response", UriToString()); - SuccessOrExit(Tlv::Find(*aMessage, state)); + SuccessOrExit(Tlv::Find(aMsg->mMessage, state)); VerifyOrExit(state == StateTlv::kAccept, IgnoreError(Stop(kDoNotSendKeepAlive))); mTimer.Start(Time::SecToMsec(kKeepAliveTimeout) / 2); diff --git a/src/core/meshcop/dataset_manager.cpp b/src/core/meshcop/dataset_manager.cpp index 86dbe8572..0d72e5fc5 100644 --- a/src/core/meshcop/dataset_manager.cpp +++ b/src/core/meshcop/dataset_manager.cpp @@ -495,24 +495,13 @@ exit: return error; } -void DatasetManager::HandleMgmtSetResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aError) +void DatasetManager::HandleMgmtSetResponse(Coap::Msg *aMsg, Error aError) { - static_cast(aContext)->HandleMgmtSetResponse(AsCoapMessagePtr(aMessage), - AsCoreTypePtr(aMessageInfo), aError); -} - -void DatasetManager::HandleMgmtSetResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aError) -{ - OT_UNUSED_VARIABLE(aMessageInfo); - Error error; uint8_t state = StateTlv::kPending; SuccessOrExit(error = aError); - VerifyOrExit(Tlv::Find(*aMessage, state) == kErrorNone && state != StateTlv::kPending, + VerifyOrExit(Tlv::Find(aMsg->mMessage, state) == kErrorNone && state != StateTlv::kPending, error = kErrorParse); if (state == StateTlv::kReject) diff --git a/src/core/meshcop/dataset_manager.hpp b/src/core/meshcop/dataset_manager.hpp index c408074cd..29b553000 100644 --- a/src/core/meshcop/dataset_manager.hpp +++ b/src/core/meshcop/dataset_manager.hpp @@ -286,12 +286,8 @@ private: void SignalDatasetChange(void) const; void SyncLocalWithLeader(const Dataset &aDataset); Error SendSetRequest(const Dataset &aDataset); - void HandleMgmtSetResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aError); - static void HandleMgmtSetResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aError); + DeclareTmfResponseHandlerIn(DatasetManager, HandleMgmtSetResponse); #if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE void MoveKeysToSecureStorage(Dataset &aDataset) const; diff --git a/src/core/meshcop/joiner.cpp b/src/core/meshcop/joiner.cpp index e98887136..3f21e4eb7 100644 --- a/src/core/meshcop/joiner.cpp +++ b/src/core/meshcop/joiner.cpp @@ -460,7 +460,7 @@ void Joiner::SendJoinerFinalize(void) LogCertMessage("[THCI] direction=send | type=JOIN_FIN.req |", *mFinalizeMessage); #endif - SuccessOrExit(Get().SendMessage(*mFinalizeMessage, Joiner::HandleJoinerFinalizeResponse, this)); + SuccessOrExit(Get().SendMessage(*mFinalizeMessage, HandleJoinerFinalizeResponse, this)); mFinalizeMessage = nullptr; LogInfo("Sent %s", UriToString()); @@ -469,19 +469,16 @@ exit: return; } -void Joiner::HandleJoinerFinalizeResponse(Coap::Message *aMessage, Error aResult) +void Joiner::HandleJoinerFinalizeResponse(Coap::Msg *aMsg, Error aResult) { - uint8_t state; - Coap::HeaderInfo header; + uint8_t state; VerifyOrExit(mState == kStateConnected && aResult == kErrorNone); - OT_ASSERT(aMessage != nullptr); + OT_ASSERT(aMsg != nullptr); - SuccessOrExit(aMessage->ParseHeaderInfo(header)); + VerifyOrExit(aMsg->IsAck() && aMsg->GetCode() == Coap::kCodeChanged); - VerifyOrExit(header.IsAck() && header.GetCode() == Coap::kCodeChanged); - - SuccessOrExit(Tlv::Find(*aMessage, state)); + SuccessOrExit(Tlv::Find(aMsg->mMessage, state)); SetState(kStateEntrust); mTimer.Start(kResponseTimeout); @@ -489,7 +486,7 @@ void Joiner::HandleJoinerFinalizeResponse(Coap::Message *aMessage, Error aResult LogInfo("Received %s %d", UriToString(), state); #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE - LogCertMessage("[THCI] direction=recv | type=JOIN_FIN.rsp |", *aMessage); + LogCertMessage("[THCI] direction=recv | type=JOIN_FIN.rsp |", aMsg->mMessage); #endif exit: diff --git a/src/core/meshcop/joiner_router.cpp b/src/core/meshcop/joiner_router.cpp index a9ca147a8..a494e9183 100644 --- a/src/core/meshcop/joiner_router.cpp +++ b/src/core/meshcop/joiner_router.cpp @@ -258,10 +258,9 @@ Error JoinerRouter::SendJoinerEntrust(const Ip6::MessageInfo &aMessageInfo) message = PrepareJoinerEntrustMessage(); VerifyOrExit(message != nullptr, error = kErrorNoBufs); - IgnoreError(Get().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this)); + IgnoreError(Get().AbortTransaction(HandleJoinerEntrustResponse, this)); - SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo, - &JoinerRouter::HandleJoinerEntrustResponse, this)); + SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo, HandleJoinerEntrustResponse, this)); LogInfo("Sent %s (len= %d)", UriToString(), message->GetLength()); LogCert("[THCI] direction=send | type=JOIN_ENT.ntf"); @@ -304,13 +303,13 @@ exit: return message; } -void JoinerRouter::HandleJoinerEntrustResponse(Coap::Message *aMessage, Error aResult) +void JoinerRouter::HandleJoinerEntrustResponse(Coap::Msg *aMsg, Error aResult) { SendDelayedJoinerEntrust(); - VerifyOrExit(aResult == kErrorNone && aMessage != nullptr); + VerifyOrExit(aResult == kErrorNone && aMsg != nullptr); - VerifyOrExit(aMessage->ReadCode() == Coap::kCodeChanged); + VerifyOrExit(aMsg->GetCode() == Coap::kCodeChanged); LogInfo("Receive %s response", UriToString()); LogCert("[THCI] direction=recv | type=JOIN_ENT.rsp"); diff --git a/src/core/thread/anycast_locator.cpp b/src/core/thread/anycast_locator.cpp index f24dd7e7b..44a1cf014 100644 --- a/src/core/thread/anycast_locator.cpp +++ b/src/core/thread/anycast_locator.cpp @@ -73,29 +73,18 @@ exit: return error; } -void AnycastLocator::HandleResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aError) +void AnycastLocator::HandleResponse(Coap::Msg *aMsg, Error aError) { - static_cast(aContext)->HandleResponse(AsCoapMessagePtr(aMessage), AsCoreTypePtr(aMessageInfo), - aError); -} - -void AnycastLocator::HandleResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aError) -{ - OT_UNUSED_VARIABLE(aMessageInfo); - uint16_t rloc16 = Mle::kInvalidRloc16; const Ip6::Address *address = nullptr; Ip6::Address meshLocalAddress; SuccessOrExit(aError); - OT_ASSERT(aMessage != nullptr); + OT_ASSERT(aMsg != nullptr); meshLocalAddress.SetPrefix(Get().GetMeshLocalPrefix()); - SuccessOrExit(Tlv::Find(*aMessage, meshLocalAddress.GetIid())); - SuccessOrExit(Tlv::Find(*aMessage, rloc16)); + SuccessOrExit(Tlv::Find(aMsg->mMessage, meshLocalAddress.GetIid())); + SuccessOrExit(Tlv::Find(aMsg->mMessage, rloc16)); #if OPENTHREAD_FTD Get().UpdateSnoopedCacheEntry(meshLocalAddress, rloc16, Get().GetShortAddress()); diff --git a/src/core/thread/anycast_locator.hpp b/src/core/thread/anycast_locator.hpp index 666c75c09..e4d869219 100644 --- a/src/core/thread/anycast_locator.hpp +++ b/src/core/thread/anycast_locator.hpp @@ -93,12 +93,10 @@ public: bool IsInProgress(void) const { return mCallback.IsSet(); } private: - static void HandleResponse(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, otError aError); - - void HandleResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aError); - template void HandleTmf(Coap::Msg &aMsg); + DeclareTmfResponseHandlerIn(AnycastLocator, HandleResponse); + Callback mCallback; }; diff --git a/src/core/thread/dua_manager.cpp b/src/core/thread/dua_manager.cpp index 7ad3681e1..6167e8a5f 100644 --- a/src/core/thread/dua_manager.cpp +++ b/src/core/thread/dua_manager.cpp @@ -73,7 +73,7 @@ void DuaManager::HandleDomainPrefixUpdate(BackboneRouter::DomainPrefixEvent aEve { if (mIsDuaPending) { - IgnoreError(Get().AbortTransaction(&DuaManager::HandleDuaResponse, this)); + IgnoreError(Get().AbortTransaction(HandleDuaResponse, this)); } #if OPENTHREAD_CONFIG_DUA_ENABLE @@ -227,7 +227,7 @@ void DuaManager::RemoveDomainUnicastAddress(void) { if (mDuaState == kRegistering && mIsDuaPending) { - IgnoreError(Get().AbortTransaction(&DuaManager::HandleDuaResponse, this)); + IgnoreError(Get().AbortTransaction(HandleDuaResponse, this)); } mDuaState = kNotExist; @@ -513,7 +513,7 @@ void DuaManager::PerformNextRegistration(void) messageInfo.SetSockAddrToRloc(); - SuccessOrExit(error = Get().SendMessage(*message, messageInfo, &DuaManager::HandleDuaResponse, this)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo, HandleDuaResponse, this)); mIsDuaPending = true; mRegisteringDua = dua; @@ -539,7 +539,7 @@ exit: FreeMessageOnError(message, error); } -void DuaManager::HandleDuaResponse(Coap::Message *aMessage, Error aResult) +void DuaManager::HandleDuaResponse(Coap::Msg *aMsg, Error aResult) { Error error; @@ -555,12 +555,12 @@ void DuaManager::HandleDuaResponse(Coap::Message *aMessage, Error aResult) } VerifyOrExit(aResult == kErrorNone, error = kErrorParse); - OT_ASSERT(aMessage != nullptr); + OT_ASSERT(aMsg != nullptr); - VerifyOrExit(aMessage->ReadCode() == Coap::kCodeChanged || aMessage->ReadCode() >= Coap::kCodeBadRequest, + VerifyOrExit(aMsg->GetCode() == Coap::kCodeChanged || aMsg->GetCode() >= Coap::kCodeBadRequest, error = kErrorParse); - error = ProcessDuaResponse(*aMessage); + error = ProcessDuaResponse(aMsg->mMessage); exit: if (error != kErrorResponseTimeout) @@ -738,7 +738,7 @@ void DuaManager::HandleChildDuaAddressEvent(const Child &aChild, ChildDuaAddress // Abort on going proxy DUA.req for this child if (mChildIndexDuaRegistering == childIndex) { - IgnoreError(Get().AbortTransaction(&DuaManager::HandleDuaResponse, this)); + IgnoreError(Get().AbortTransaction(HandleDuaResponse, this)); } mChildDuaMask.Remove(childIndex); diff --git a/src/core/thread/mle.hpp b/src/core/thread/mle.hpp index 73389233d..b12c5ee23 100644 --- a/src/core/thread/mle.hpp +++ b/src/core/thread/mle.hpp @@ -2414,7 +2414,7 @@ private: template void HandleTmf(Coap::Msg &aMsg); - DeclareTmfResponseHandlerFullParamIn(Mle, HandleAddressSolicitResponse); + DeclareTmfResponseHandlerIn(Mle, HandleAddressSolicitResponse); #if OPENTHREAD_CONFIG_TMF_PROXY_DUA_ENABLE void SignalDuaAddressEvent(const Child &aChild, const Ip6::Address &aOldDua) const; diff --git a/src/core/thread/mle_ftd.cpp b/src/core/thread/mle_ftd.cpp index e3d6e549e..bc1d7d382 100644 --- a/src/core/thread/mle_ftd.cpp +++ b/src/core/thread/mle_ftd.cpp @@ -72,7 +72,7 @@ void Mle::HandlePartitionChange(void) mPreviousPartitionIdTimeout = GetNetworkIdTimeout(); Get().Clear(); - IgnoreError(Get().AbortTransaction(&Mle::HandleAddressSolicitResponse, this)); + IgnoreError(Get().AbortTransaction(HandleAddressSolicitResponse, this)); mRouterTable.Clear(); } @@ -3288,7 +3288,7 @@ Error Mle::SendAddressSolicit(RouterUpgradeReason aReason) messageInfo.SetSockAddrToRlocPeerAddrToLeaderRloc(); - SuccessOrExit(error = Get().SendMessage(*message, messageInfo, &HandleAddressSolicitResponse, this)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo, HandleAddressSolicitResponse, this)); mAddressSolicitPending = true; Log(kMessageSend, kTypeAddressSolicit, messageInfo.GetPeerAddr()); @@ -3321,7 +3321,7 @@ exit: LogSendError(kTypeAddressRelease, error); } -void Mle::HandleAddressSolicitResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aResult) +void Mle::HandleAddressSolicitResponse(Coap::Msg *aMsg, Error aResult) { uint8_t status; uint16_t rloc16; @@ -3331,13 +3331,13 @@ void Mle::HandleAddressSolicitResponse(Coap::Message *aMessage, const Ip6::Messa mAddressSolicitPending = false; - VerifyOrExit(aResult == kErrorNone && aMessage != nullptr && aMessageInfo != nullptr); + VerifyOrExit(aResult == kErrorNone && aMsg != nullptr); - VerifyOrExit(aMessage->ReadCode() == Coap::kCodeChanged); + VerifyOrExit(aMsg->GetCode() == Coap::kCodeChanged); - Log(kMessageReceive, kTypeAddressReply, aMessageInfo->GetPeerAddr()); + Log(kMessageReceive, kTypeAddressReply, aMsg->mMessageInfo.GetPeerAddr()); - SuccessOrExit(Tlv::Find(*aMessage, status)); + SuccessOrExit(Tlv::Find(aMsg->mMessage, status)); if (status != kAddrSolicitSuccess) { @@ -3356,10 +3356,10 @@ void Mle::HandleAddressSolicitResponse(Coap::Message *aMessage, const Ip6::Messa ExitNow(); } - SuccessOrExit(Tlv::Find(*aMessage, rloc16)); + SuccessOrExit(Tlv::Find(aMsg->mMessage, rloc16)); routerId = RouterIdFromRloc16(rloc16); - SuccessOrExit(Tlv::FindTlv(*aMessage, routerMaskTlv)); + SuccessOrExit(Tlv::FindTlv(aMsg->mMessage, routerMaskTlv)); VerifyOrExit(routerMaskTlv.IsValid()); SetAlternateRloc16(GetRloc16()); diff --git a/src/core/thread/mlr_manager.cpp b/src/core/thread/mlr_manager.cpp index 200620f54..029d13377 100644 --- a/src/core/thread/mlr_manager.cpp +++ b/src/core/thread/mlr_manager.cpp @@ -335,7 +335,7 @@ exit: return error; } -void MlrManager::HandleRegisterResponse(Coap::Message *aMessage, Error aResult) +void MlrManager::HandleRegisterResponse(Coap::Msg *aMsg, Error aResult) { uint8_t status; Error error; @@ -343,18 +343,18 @@ void MlrManager::HandleRegisterResponse(Coap::Message *aMessage, Error aResult) mRegisterPending = false; - error = ParseMlrResponse(aResult, aMessage, status, failedAddresses); + error = ParseMlrResponse(aResult, aMsg, status, failedAddresses); mRegisterCallback.InvokeAndClearIfSet(error, status, failedAddresses.GetArrayBuffer(), failedAddresses.GetLength()); } #endif // OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE -Error MlrManager::SendMlrMessage(const Ip6::Address *aAddresses, - uint8_t aAddressNum, - const uint32_t *aTimeout, - Coap::ResponseHandler aResponseHandler, - void *aResponseContext) +Error MlrManager::SendMlrMessage(const Ip6::Address *aAddresses, + uint8_t aAddressNum, + const uint32_t *aTimeout, + const Coap::ResponseHandler aResponseHandler, + void *aContext) { OT_UNUSED_VARIABLE(aTimeout); @@ -403,7 +403,7 @@ Error MlrManager::SendMlrMessage(const Ip6::Address *aAddresses, messageInfo.SetSockAddrToRloc(); - error = Get().SendMessage(*message, messageInfo, aResponseHandler, aResponseContext); + error = Get().SendMessage(*message, messageInfo, aResponseHandler, aContext); LogInfo("Sent MLR.req: addressNum=%d", aAddressNum); @@ -413,24 +413,13 @@ exit: return error; } -void MlrManager::HandleMlrResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aResult) +void MlrManager::HandleMlrResponse(Coap::Msg *aMsg, Error aResult) { - static_cast(aContext)->HandleMlrResponse(AsCoapMessagePtr(aMessage), AsCoreTypePtr(aMessageInfo), - aResult); -} - -void MlrManager::HandleMlrResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aResult) -{ - OT_UNUSED_VARIABLE(aMessageInfo); - uint8_t status; Error error; AddressArray failedAddresses; - error = ParseMlrResponse(aResult, aMessage, status, failedAddresses); + error = ParseMlrResponse(aResult, aMsg, status, failedAddresses); FinishMlr(error == kErrorNone && status == kMlrSuccess, failedAddresses); @@ -457,22 +446,19 @@ void MlrManager::HandleMlrResponse(Coap::Message *aMessage, const Ip6::MessageIn } } -Error MlrManager::ParseMlrResponse(Error aResult, - Coap::Message *aMessage, - uint8_t &aStatus, - AddressArray &aFailedAddresses) +Error MlrManager::ParseMlrResponse(Error aResult, Coap::Msg *aMsg, uint8_t &aStatus, AddressArray &aFailedAddresses) { Error error; OffsetRange offsetRange; aStatus = kMlrGeneralFailure; - VerifyOrExit(aResult == kErrorNone && aMessage != nullptr, error = kErrorParse); - VerifyOrExit(aMessage->ReadCode() == Coap::kCodeChanged, error = kErrorParse); + VerifyOrExit(aResult == kErrorNone && aMsg != nullptr, error = kErrorParse); + VerifyOrExit(aMsg->GetCode() == Coap::kCodeChanged, error = kErrorParse); - SuccessOrExit(error = Tlv::Find(*aMessage, aStatus)); + SuccessOrExit(error = Tlv::Find(aMsg->mMessage, aStatus)); - if (ThreadTlv::FindTlvValueOffsetRange(*aMessage, Ip6AddressesTlv::kIp6Addresses, offsetRange) == kErrorNone) + if (ThreadTlv::FindTlvValueOffsetRange(aMsg->mMessage, Ip6AddressesTlv::kIp6Addresses, offsetRange) == kErrorNone) { VerifyOrExit(offsetRange.GetLength() % sizeof(Ip6::Address) == 0, error = kErrorParse); VerifyOrExit(offsetRange.GetLength() / sizeof(Ip6::Address) <= Ip6AddressesTlv::kMaxAddresses, @@ -480,7 +466,7 @@ Error MlrManager::ParseMlrResponse(Error aResult, while (!offsetRange.IsEmpty()) { - IgnoreError(aMessage->Read(offsetRange, *aFailedAddresses.PushBack())); + IgnoreError(aMsg->mMessage.Read(offsetRange, *aFailedAddresses.PushBack())); offsetRange.AdvanceOffset(sizeof(Ip6::Address)); } } diff --git a/src/core/thread/mlr_manager.hpp b/src/core/thread/mlr_manager.hpp index 9e74f4a08..428c62559 100644 --- a/src/core/thread/mlr_manager.hpp +++ b/src/core/thread/mlr_manager.hpp @@ -155,17 +155,11 @@ private: uint8_t aAddressNum, const uint32_t *aTimeout, Coap::ResponseHandler aResponseHandler, - void *aResponseContext); + void *aContext); - static void HandleMlrResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aResult); - void HandleMlrResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aResult); - static Error ParseMlrResponse(Error aResult, - Coap::Message *aMessage, - uint8_t &aStatus, - AddressArray &aFailedAddresses); + DeclareTmfResponseHandlerIn(MlrManager, HandleMlrResponse); + + static Error ParseMlrResponse(Error aResult, Coap::Msg *aMsg, uint8_t &aStatus, AddressArray &aFailedAddresses); #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE DeclareTmfResponseHandlerIn(MlrManager, HandleRegisterResponse); diff --git a/src/core/thread/network_data_notifier.cpp b/src/core/thread/network_data_notifier.cpp index b61cc9232..68c31509b 100644 --- a/src/core/thread/network_data_notifier.cpp +++ b/src/core/thread/network_data_notifier.cpp @@ -242,9 +242,9 @@ void Notifier::HandleNotifierEvents(Events aEvents) void Notifier::HandleTimer(void) { SynchronizeServerData(); } -void Notifier::HandleCoapResponse(Coap::Message *aMessage, Error aResult) +void Notifier::HandleCoapResponse(Coap::Msg *aMsg, Error aResult) { - OT_UNUSED_VARIABLE(aMessage); + OT_UNUSED_VARIABLE(aMsg); mWaitingForResponse = false; diff --git a/src/core/thread/network_diagnostic.cpp b/src/core/thread/network_diagnostic.cpp index 8c289d57d..c3a3c0c42 100644 --- a/src/core/thread/network_diagnostic.cpp +++ b/src/core/thread/network_diagnostic.cpp @@ -805,34 +805,27 @@ void Server::SendNextAnswer(Coap::Message &aAnswer, const Ip6::Address &aDestina } } -void Server::HandleAnswerResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aResult) +void Server::HandleAnswerResponse(void *aContext, Coap::Msg *aMsg, Error aResult) { Coap::Message *nextAnswer = static_cast(aContext); VerifyOrExit(nextAnswer != nullptr); - nextAnswer->Get().HandleAnswerResponse(*nextAnswer, AsCoapMessagePtr(aMessage), AsCoreTypePtr(aMessageInfo), - aResult); + nextAnswer->Get().HandleAnswerResponse(*nextAnswer, aMsg, aResult); exit: return; } -void Server::HandleAnswerResponse(Coap::Message &aNextAnswer, - Coap::Message *aResponse, - const Ip6::MessageInfo *aMessageInfo, - Error aResult) +void Server::HandleAnswerResponse(Coap::Message &aNextAnswer, Coap::Msg *aResponse, Error aResult) { Error error = aResult; SuccessOrExit(error); - VerifyOrExit(aResponse != nullptr && aMessageInfo != nullptr, error = kErrorDrop); - VerifyOrExit(aResponse->ReadCode() == Coap::kCodeChanged, error = kErrorDrop); + VerifyOrExit(aResponse != nullptr, error = kErrorDrop); + VerifyOrExit(aResponse->GetCode() == Coap::kCodeChanged, error = kErrorDrop); - SendNextAnswer(aNextAnswer, aMessageInfo->GetPeerAddr()); + SendNextAnswer(aNextAnswer, aResponse->mMessageInfo.GetPeerAddr()); exit: if (error != kErrorNone) @@ -1031,7 +1024,7 @@ Error Client::SendDiagnosticGet(const Ip6::Address &aDestination, else { error = SendCommand(kUriDiagnosticGetRequest, Message::kPriorityNormal, aDestination, aTlvTypes, aCount, - &HandleGetResponse, this); + HandleGetResponse, this); } SuccessOrExit(error); @@ -1042,6 +1035,15 @@ exit: return error; } +Error Client::SendCommand(Uri aUri, + Message::Priority aPriority, + const Ip6::Address &aDestination, + const uint8_t aTlvTypes[], + uint8_t aCount) +{ + return SendCommand(aUri, aPriority, aDestination, aTlvTypes, aCount, nullptr, nullptr); +} + Error Client::SendCommand(Uri aUri, Message::Priority aPriority, const Ip6::Address &aDestination, @@ -1093,13 +1095,14 @@ exit: return error; } -void Client::HandleGetResponse(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aResult) +void Client::HandleGetResponse(Coap::Msg *aMsg, Error aResult) { SuccessOrExit(aResult); - VerifyOrExit(aMessage->ReadCode() == Coap::kCodeChanged, aResult = kErrorFailed); + VerifyOrExit(aMsg->GetCode() == Coap::kCodeChanged, aResult = kErrorFailed); exit: - mGetCallback.InvokeIfSet(aResult, aMessage, aMessageInfo); + mGetCallback.InvokeIfSet(aResult, (aMsg == nullptr) ? nullptr : &aMsg->mMessage, + (aMsg == nullptr) ? nullptr : &aMsg->mMessageInfo); } template <> void Client::HandleTmf(Coap::Msg &aMsg) diff --git a/src/core/thread/network_diagnostic.hpp b/src/core/thread/network_diagnostic.hpp index 7878cd1ff..b0313024d 100644 --- a/src/core/thread/network_diagnostic.hpp +++ b/src/core/thread/network_diagnostic.hpp @@ -175,14 +175,8 @@ private: Error AppendChildTableIp6AddressList(Message &aMessage); #endif - static void HandleAnswerResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aResult); - void HandleAnswerResponse(Coap::Message &aNextAnswer, - Coap::Message *aResponse, - const Ip6::MessageInfo *aMessageInfo, - Error aResult); + static void HandleAnswerResponse(void *aContext, Coap::Msg *aMsg, Error aResult); + void HandleAnswerResponse(Coap::Message &aNextAnswer, Coap::Msg *aResponse, Error aResult); #endif #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE Error AppendBorderRouterIfAddrs(Message &aMessage); @@ -281,10 +275,16 @@ private: const Ip6::Address &aDestination, const uint8_t aTlvTypes[], uint8_t aCount, - Coap::ResponseHandler aHandler = nullptr, - void *aContext = nullptr); + Coap::ResponseHandler aHandler, + void *aContext); - DeclareTmfResponseHandlerFullParamIn(Client, HandleGetResponse); + Error SendCommand(Uri aUri, + Message::Priority aPriority, + const Ip6::Address &aDestination, + const uint8_t aTlvTypes[], + uint8_t aCount); + + DeclareTmfResponseHandlerIn(Client, HandleGetResponse); template void HandleTmf(Coap::Msg &aMsg); diff --git a/src/core/thread/tmf.hpp b/src/core/thread/tmf.hpp index a73a5678e..71ae38e0e 100644 --- a/src/core/thread/tmf.hpp +++ b/src/core/thread/tmf.hpp @@ -67,40 +67,18 @@ namespace Tmf { * * The `Type` class MUST implement the following member method which will be invoked by the `static` handler: * - * void MethodName(Coap::Message *aMessage, Error aResult); + * void MethodName(Coap::Msg *aMsg, Error aResult); * * @param[in] Type The class `Type` in which the TMF response handler is declared. * @param[in] MethodName The handler method name. */ -#define DeclareTmfResponseHandlerIn(Type, MethodName) \ - static void MethodName(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, otError aResult) \ - { \ - OT_UNUSED_VARIABLE(aMessageInfo); \ - static_cast(aContext)->MethodName(AsCoapMessagePtr(aMessage), aResult); \ - } \ - \ - void MethodName(Coap::Message *aMessage, Error aResult) - -/** - * Declares a TMF/CoAP response handler with access to `MessageInfo` in a given class `Type`. - * - * This macro is a variant of `DeclareTmfResponseHandlerIn` and is intended for cases where the response handler needs - * access to the full parameters including `Ip6::MessageInfo`. - * - * The `Type` class MUST implement the following member method which will be invoked by the `static` handler: - * - * void MethodName(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aResult); - * - * @param[in] Type The class `Type` in which the TMF response handler is declared. - * @param[in] MethodName The handler method name. - */ -#define DeclareTmfResponseHandlerFullParamIn(Type, MethodName) \ - static void MethodName(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, otError aResult) \ - { \ - static_cast(aContext)->MethodName(AsCoapMessagePtr(aMessage), AsCoreTypePtr(aMessageInfo), aResult); \ - } \ - \ - void MethodName(Coap::Message *aMessage, const Ip6::MessageInfo *aMessageInfo, Error aResult) +#define DeclareTmfResponseHandlerIn(Type, MethodName) \ + static void MethodName(void *aContext, Coap::Msg *aMsg, Error aResult) \ + { \ + static_cast(aContext)->MethodName(aMsg, aResult); \ + } \ + \ + void MethodName(Coap::Msg *aMsg, Error aResult) constexpr uint16_t kUdpPort = 61631; ///< TMF UDP Port diff --git a/src/core/utils/history_tracker_server.cpp b/src/core/utils/history_tracker_server.cpp index db899880e..7f64f52e8 100644 --- a/src/core/utils/history_tracker_server.cpp +++ b/src/core/utils/history_tracker_server.cpp @@ -257,34 +257,27 @@ void Server::PrepareMessageInfoForDest(const Ip6::Address &aDestination, Tmf::Me aMessageInfo.SetPeerAddr(aDestination); } -void Server::HandleAnswerResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aResult) +void Server::HandleAnswerResponse(void *aContext, Coap::Msg *aMsg, Error aResult) { Coap::Message *nextAnswer = static_cast(aContext); VerifyOrExit(nextAnswer != nullptr); - nextAnswer->Get().HandleAnswerResponse(*nextAnswer, AsCoapMessagePtr(aMessage), AsCoreTypePtr(aMessageInfo), - aResult); + nextAnswer->Get().HandleAnswerResponse(*nextAnswer, aMsg, aResult); exit: return; } -void Server::HandleAnswerResponse(Coap::Message &aNextAnswer, - Coap::Message *aResponse, - const Ip6::MessageInfo *aMessageInfo, - Error aResult) +void Server::HandleAnswerResponse(Coap::Message &aNextAnswer, Coap::Msg *aResponse, Error aResult) { Error error = aResult; SuccessOrExit(error); - VerifyOrExit(aResponse != nullptr && aMessageInfo != nullptr, error = kErrorDrop); - VerifyOrExit(aResponse->ReadCode() == Coap::kCodeChanged, error = kErrorDrop); + VerifyOrExit(aResponse != nullptr, error = kErrorDrop); + VerifyOrExit(aResponse->GetCode() == Coap::kCodeChanged, error = kErrorDrop); - SendNextAnswer(aNextAnswer, aMessageInfo->GetPeerAddr()); + SendNextAnswer(aNextAnswer, aResponse->mMessageInfo.GetPeerAddr()); exit: if (error != kErrorNone) diff --git a/src/core/utils/history_tracker_server.hpp b/src/core/utils/history_tracker_server.hpp index 209bec95c..c207f9551 100644 --- a/src/core/utils/history_tracker_server.hpp +++ b/src/core/utils/history_tracker_server.hpp @@ -91,14 +91,8 @@ private: void PrepareMessageInfoForDest(const Ip6::Address &aDestination, Tmf::MessageInfo &aMessageInfo) const; Error AppendNetworkInfo(Coap::Message *&aAnswer, AnswerInfo &aInfo, const RequestTlv &aRequestTlv); - static void HandleAnswerResponse(void *aContext, - otMessage *aMessage, - const otMessageInfo *aMessageInfo, - otError aResult); - void HandleAnswerResponse(Coap::Message &aNextAnswer, - Coap::Message *aResponse, - const Ip6::MessageInfo *aMessageInfo, - Error aResult); + static void HandleAnswerResponse(void *aContext, Coap::Msg *aMsg, Error aResult); + void HandleAnswerResponse(Coap::Message &aNextAnswer, Coap::Msg *aResponse, Error aResult); template void HandleTmf(Coap::Msg &aMsg); diff --git a/src/core/utils/mesh_diag.cpp b/src/core/utils/mesh_diag.cpp index 25432710c..0f412b708 100644 --- a/src/core/utils/mesh_diag.cpp +++ b/src/core/utils/mesh_diag.cpp @@ -113,7 +113,7 @@ exit: return error; } -void MeshDiag::HandleDiagGetResponse(Coap::Message *aMessage, Error aResult) +void MeshDiag::HandleDiagGetResponse(Coap::Msg *aMsg, Error aResult) { Error error; RouterInfo routerInfo; @@ -121,17 +121,17 @@ void MeshDiag::HandleDiagGetResponse(Coap::Message *aMessage, Error aResult) ChildIterator childIterator; SuccessOrExit(aResult); - VerifyOrExit(aMessage != nullptr); + VerifyOrExit(aMsg != nullptr); VerifyOrExit(mState == kStateDiscoverTopology); - SuccessOrExit(routerInfo.ParseFrom(*aMessage)); + SuccessOrExit(routerInfo.ParseFrom(aMsg->mMessage)); - if (ip6AddrIterator.InitFrom(*aMessage) == kErrorNone) + if (ip6AddrIterator.InitFrom(aMsg->mMessage) == kErrorNone) { routerInfo.mIp6AddrIterator = &ip6AddrIterator; } - if (childIterator.InitFrom(*aMessage, routerInfo.mRloc16) == kErrorNone) + if (childIterator.InitFrom(aMsg->mMessage, routerInfo.mRloc16) == kErrorNone) { routerInfo.mChildIterator = &childIterator; }