diff --git a/src/core/Makefile.am b/src/core/Makefile.am index 3f70f19b8..9db5c4404 100644 --- a/src/core/Makefile.am +++ b/src/core/Makefile.am @@ -222,6 +222,7 @@ HEADERS_COMMON = \ common/message.hpp \ common/notifier.hpp \ common/owner-locator.hpp \ + common/random.hpp \ common/settings.hpp \ common/new.hpp \ common/tasklet.hpp \ diff --git a/src/core/api/link_raw_api.cpp b/src/core/api/link_raw_api.cpp index a7d0bd17f..41df8d1d6 100644 --- a/src/core/api/link_raw_api.cpp +++ b/src/core/api/link_raw_api.cpp @@ -33,12 +33,11 @@ #include "openthread-core-config.h" -#include - #include "common/debug.hpp" #include "common/instance.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" using namespace ot; @@ -585,7 +584,7 @@ void LinkRaw::StartCsmaBackoff(void) backoffExponent = Mac::kMaxBE; } - backoff = (otPlatRandomGet() % (1UL << backoffExponent)); + backoff = Random::GetUint32InRange(0, 1U << backoffExponent); backoff *= (static_cast(Mac::kUnitBackoffPeriod) * OT_RADIO_SYMBOL_TIME); otLogDebgPlat(&mInstance, "LinkRaw Starting RetransmitTimeout Timer (%d ms)", backoff); diff --git a/src/core/coap/coap.cpp b/src/core/coap/coap.cpp index c8778b950..38b4d9f76 100644 --- a/src/core/coap/coap.cpp +++ b/src/core/coap/coap.cpp @@ -30,13 +30,12 @@ #include "coap.hpp" -#include - #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #include "net/ip6.hpp" #include "net/udp6.hpp" #include "thread/thread_netif.hpp" @@ -62,7 +61,7 @@ CoapBase::CoapBase(Instance & aInstance, , mDefaultHandler(NULL) , mDefaultHandlerContext(NULL) { - mMessageId = static_cast(otPlatRandomGet()); + mMessageId = Random::GetUint16(); } otError CoapBase::Start(uint16_t aPort) @@ -739,9 +738,9 @@ CoapMetadata::CoapMetadata(bool aConfirmable, mResponseContext = aContext; mRetransmissionCount = 0; mRetransmissionTimeout = TimerMilli::SecToMsec(kAckTimeout); - mRetransmissionTimeout += otPlatRandomGet() % (TimerMilli::SecToMsec(kAckTimeout) * kAckRandomFactorNumerator / - kAckRandomFactorDenominator - - TimerMilli::SecToMsec(kAckTimeout) + 1); + mRetransmissionTimeout += Random::GetUint32InRange( + 0, TimerMilli::SecToMsec(kAckTimeout) * kAckRandomFactorNumerator / kAckRandomFactorDenominator - + TimerMilli::SecToMsec(kAckTimeout) + 1); if (aConfirmable) { diff --git a/src/core/coap/coap_header.cpp b/src/core/coap/coap_header.cpp index 28bf2c7ae..62110845c 100644 --- a/src/core/coap/coap_header.cpp +++ b/src/core/coap/coap_header.cpp @@ -33,13 +33,12 @@ #include "coap_header.hpp" -#include - #include "coap/coap.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/random.hpp" namespace ot { namespace Coap { @@ -417,14 +416,11 @@ exit: void Header::SetToken(uint8_t aTokenLength) { - assert(aTokenLength <= kMaxTokenLength); - uint8_t token[kMaxTokenLength] = {0}; - for (uint8_t i = 0; i < aTokenLength; i++) - { - token[i] = static_cast(otPlatRandomGet()); - } + assert(aTokenLength <= kMaxTokenLength); + + Random::FillBuffer(token, aTokenLength); SetToken(token, aTokenLength); } diff --git a/src/core/common/random.hpp b/src/core/common/random.hpp new file mode 100644 index 000000000..01d597cbc --- /dev/null +++ b/src/core/common/random.hpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2018, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes definitions for OpenThread random number generation. + */ + +#ifndef RANDOM_HPP_ +#define RANDOM_HPP_ + +#include "openthread-core-config.h" + +#include "utils/wrap_stdint.h" + +#include + +namespace ot { +namespace Random { + +/** + * @addtogroup core-random + * + * @brief + * This module includes definitions for OpenThread random number generation. + * + * The functions in this header file uses the platform random number generator `otPlatRandomGet()`. + * + * @{ + * + */ + +/** + * This function generates and returns a random byte. + * + * @returns A random `uint8_t` value. + * + */ +inline uint8_t GetUint8(void) +{ + return static_cast(otPlatRandomGet() & 0xff); +} + +/** + * This function generates and returns a random `uint16_t` value. + * + * @returns A random `uint16_t` value. + * + */ +inline uint16_t GetUint16(void) +{ + return static_cast(otPlatRandomGet() & 0xffff); +} + +/** + * This function generates and returns a random `uint32_t` value. + * + * @returns A random `uint32_t` value. + * + */ +inline uint32_t GetUint32(void) +{ + return otPlatRandomGet(); +} + +/** + * This function generates and returns a random `uint8_t` value within a given range `[aMin, aMax)`. + * + * @param[in] aMin A minimum value (this value can be included in returned random result). + * @param[in] aMax A maximum value (this value is excluded from returned random result). + * + * @return A random `uint8_t` value in the given range (i.e., aMin <= random value < aMax). + */ +inline uint8_t GetUint8InRange(uint8_t aMin, uint8_t aMax) +{ + return (aMin + (GetUint8() % (aMax - aMin))); +} + +/** + * This function generates and returns a random `uint16_t` value within a given range `[aMin, aMax)`. + * + * @note The returned random value can include the @p aMin value but excludes the @p aMax. + * + * @param[in] aMin A minimum value (this value can be included in returned random result). + * @param[in] aMax A maximum value (this value is excluded from returned random result). + * + * @return A random `uint16_t` value in the given range (i.e., aMin <= random value < aMax). + */ +inline uint16_t GetUint16InRange(uint16_t aMin, uint16_t aMax) +{ + return (aMin + (GetUint16() % (aMax - aMin))); +} + +/** + * This function generates and returns a random `uint32_t` value within a given range `[aMin, aMax)`. + * + * @note The returned random value can include the @p aMin value but excludes the @p aMax. + * + * @param[in] aMin A minimum value (this value can be included in returned random result). + * @param[in] aMax A maximum value (this value is excluded from returned random result). + * + * @return A random `uint32_t` value in the given range (i.e., aMin <= random value < aMax). + */ +inline uint32_t GetUint32InRange(uint32_t aMin, uint32_t aMax) +{ + return (aMin + (GetUint32() % (aMax - aMin))); +} + +/** + * This function fills a given buffer with random bytes. + * + * @param[out] aBuffer A pointer to a buffer to fill with the random bytes. + * @param[in] aSize Size of buffer (number of bytes to fill). + * + */ +inline void FillBuffer(uint8_t *aBuffer, uint16_t aSize) +{ + while (aSize-- != 0) + { + *aBuffer++ = GetUint8(); + } +} + +/** + * @} + * + */ + +} // namespace Random +} // namespace ot + +#endif // RANDOM_HPP_ diff --git a/src/core/common/trickle_timer.cpp b/src/core/common/trickle_timer.cpp index db14fe657..d17fabf1d 100644 --- a/src/core/common/trickle_timer.cpp +++ b/src/core/common/trickle_timer.cpp @@ -33,10 +33,9 @@ #include "trickle_timer.hpp" -#include - #include "common/code_utils.hpp" #include "common/debug.hpp" +#include "common/random.hpp" namespace ot { @@ -84,7 +83,7 @@ void TrickleTimer::Start(uint32_t aIntervalMin, uint32_t aIntervalMax, Mode aMod } else { - I = Imin + otPlatRandomGet() % (Imax - Imin); + I = Random::GetUint32InRange(Imin, Imax); } // Start a new interval @@ -139,7 +138,7 @@ void TrickleTimer::StartNewInterval(void) else if (mMode == kModeMPL) { // Initialize t to random value between (0, I] - t = otPlatRandomGet() % I; + t = Random::GetUint32InRange(0, I); } else if (mMode == kModePlainTimer) { @@ -149,7 +148,7 @@ void TrickleTimer::StartNewInterval(void) else { // Initialize t to random value between (I/2, I] - t = (I / 2) + otPlatRandomGet() % (I / 2); + t = Random::GetUint32InRange(I / 2, I); } // Start the timer for 't' milliseconds from now @@ -190,7 +189,7 @@ void TrickleTimer::HandleTimerFired(void) if (mMode == kModePlainTimer) { // Initialize I to [Imin, Imax] - I = Imin + otPlatRandomGet() % (Imax - Imin); + I = Random::GetUint32InRange(Imin, Imax); // Start a new interval StartNewInterval(); diff --git a/src/core/mac/mac.cpp b/src/core/mac/mac.cpp index 87415a305..6f76af093 100644 --- a/src/core/mac/mac.cpp +++ b/src/core/mac/mac.cpp @@ -37,14 +37,13 @@ #include "utils/wrap_string.h" -#include - #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #include "crypto/aes_ccm.hpp" #include "crypto/sha256.hpp" #include "mac/mac_frame.hpp" @@ -119,8 +118,8 @@ Mac::Mac(Instance &aInstance) , mSendTail(NULL) , mReceiveHead(NULL) , mReceiveTail(NULL) - , mBeaconSequence(static_cast(otPlatRandomGet())) - , mDataSequence(static_cast(otPlatRandomGet())) + , mBeaconSequence(Random::GetUint8()) + , mDataSequence(Random::GetUint8()) , mCsmaAttempts(0) , mTransmitAttempts(0) , mScanChannelMask() @@ -419,10 +418,7 @@ exit: void Mac::GenerateExtAddress(ExtAddress *aExtAddress) { - for (size_t i = 0; i < sizeof(ExtAddress); i++) - { - aExtAddress->m8[i] = static_cast(otPlatRandomGet()); - } + Random::FillBuffer(aExtAddress->m8, sizeof(ExtAddress)); aExtAddress->SetGroup(false); aExtAddress->SetLocal(true); @@ -861,7 +857,7 @@ void Mac::StartCsmaBackoff(void) backoffExponent = kMaxBE; } - backoff = (otPlatRandomGet() % (1UL << backoffExponent)); + backoff = Random::GetUint32InRange(0, 1U << backoffExponent); backoff *= (static_cast(kUnitBackoffPeriod) * OT_RADIO_SYMBOL_TIME); // Put the radio in either sleep or receive mode depending on diff --git a/src/core/net/dhcp6_client.cpp b/src/core/net/dhcp6_client.cpp index 6b9b1ca79..f00b67344 100644 --- a/src/core/net/dhcp6_client.cpp +++ b/src/core/net/dhcp6_client.cpp @@ -36,13 +36,13 @@ #include "dhcp6_client.hpp" #include -#include #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #include "mac/mac.hpp" #include "net/dhcp6.hpp" #include "thread/thread_netif.hpp" @@ -307,10 +307,7 @@ bool Dhcp6Client::ProcessNextIdentityAssociation() } // new transaction id - for (uint8_t i = 0; i < kTransactionIdSize; i++) - { - mTransactionId[i] = static_cast(otPlatRandomGet()); - } + Random::FillBuffer(mTransactionId, kTransactionIdSize); // ensure mIdentityAssociationHead is the prefix agent to solicit. if (prevIdentityAssociation) diff --git a/src/core/net/ip6_mpl.cpp b/src/core/net/ip6_mpl.cpp index 092ed1910..48e365c74 100644 --- a/src/core/net/ip6_mpl.cpp +++ b/src/core/net/ip6_mpl.cpp @@ -33,12 +33,11 @@ #include "ip6_mpl.hpp" -#include - #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/message.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #include "net/ip6.hpp" namespace ot { @@ -47,7 +46,7 @@ namespace Ip6 { void MplBufferedMessageMetadata::GenerateNextTransmissionTime(uint32_t aCurrentTime, uint8_t aInterval) { // Emulate Trickle timer behavior and set up the next retransmission within [0,I) range. - uint8_t t = aInterval == 0 ? aInterval : otPlatRandomGet() % aInterval; + uint8_t t = aInterval == 0 ? aInterval : Random::GetUint8InRange(0, aInterval); // Set transmission time at the beginning of the next interval. SetTransmissionTime(aCurrentTime + GetIntervalOffset() + t); diff --git a/src/core/thread/mesh_forwarder.cpp b/src/core/thread/mesh_forwarder.cpp index 0b655be5a..ce6a07287 100644 --- a/src/core/thread/mesh_forwarder.cpp +++ b/src/core/thread/mesh_forwarder.cpp @@ -35,8 +35,6 @@ #include "mesh_forwarder.hpp" -#include - #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" @@ -44,6 +42,7 @@ #include "common/logging.hpp" #include "common/message.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #include "net/ip6.hpp" #include "net/ip6_filter.hpp" #include "net/netif.hpp" @@ -87,7 +86,7 @@ MeshForwarder::MeshForwarder(Instance &aInstance) #endif , mDataPollManager(aInstance) { - mFragTag = static_cast(otPlatRandomGet()); + mFragTag = Random::GetUint16(); GetNetif().GetMac().RegisterReceiver(mMacReceiver); mIpCounters.mTxSuccess = 0; @@ -498,7 +497,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) do { - panid = static_cast(otPlatRandomGet()); + panid = Random::GetUint16(); } while (panid == Mac::kPanIdBroadcast); netif.GetMac().SetPanId(panid); diff --git a/src/core/thread/mle.cpp b/src/core/thread/mle.cpp index de036d0a1..3c6c5a54c 100644 --- a/src/core/thread/mle.cpp +++ b/src/core/thread/mle.cpp @@ -36,7 +36,6 @@ #include "mle.hpp" #include -#include #include #include "common/code_utils.hpp" @@ -45,6 +44,7 @@ #include "common/instance.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #include "common/settings.hpp" #include "crypto/aes_ccm.hpp" #include "mac/mac_frame.hpp" @@ -108,7 +108,6 @@ Mle::Mle(Instance &aInstance) , mNotifierCallback(&Mle::HandleStateChanged, this) { uint8_t meshLocalPrefix[8]; - size_t i = 0; memset(&mLeaderData, 0, sizeof(mLeaderData)); memset(&mParentLeaderData, 0, sizeof(mParentLeaderData)); @@ -140,7 +139,7 @@ Mle::Mle(Instance &aInstance) #if OPENTHREAD_ENABLE_SERVICE // Service Alocs - for (i = 0; i < sizeof(mServiceAlocs) / sizeof(mServiceAlocs[0]); i++) + for (size_t i = 0; i < sizeof(mServiceAlocs) / sizeof(mServiceAlocs[0]); i++) { memset(&mServiceAlocs[i], 0, sizeof(mServiceAlocs[i])); @@ -161,10 +160,8 @@ Mle::Mle(Instance &aInstance) meshLocalPrefix[7] = 0x00; // mesh-local 64 - for (i = OT_IP6_PREFIX_SIZE; i < OT_IP6_ADDRESS_SIZE; i++) - { - mMeshLocal64.GetAddress().mFields.m8[i] = static_cast(otPlatRandomGet()); - } + Random::FillBuffer(mMeshLocal64.GetAddress().mFields.m8 + OT_IP6_PREFIX_SIZE, + OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE); mMeshLocal64.mPrefixLength = 64; mMeshLocal64.mPreferred = true; @@ -569,7 +566,7 @@ otError Mle::BecomeChild(AttachMode aMode) netif.GetMeshForwarder().SetRxOnWhenIdle(true); - mParentRequestTimer.Start((otPlatRandomGet() % kParentRequestRouterTimeout) + 1); + mParentRequestTimer.Start(1 + Random::GetUint32InRange(0, kParentRequestRouterTimeout)); exit: return error; @@ -1336,10 +1333,8 @@ void Mle::HandleStateChanged(uint32_t aFlags) if (!netif.IsUnicastAddress(mMeshLocal64.GetAddress())) { // Mesh Local EID was removed, choose a new one and add it back - for (int i = 8; i < 16; i++) - { - mMeshLocal64.GetAddress().mFields.m8[i] = static_cast(otPlatRandomGet()); - } + Random::FillBuffer(mMeshLocal64.GetAddress().mFields.m8 + OT_IP6_PREFIX_SIZE, + OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE); netif.AddUnicastAddress(mMeshLocal64); GetNotifier().SetFlags(OT_CHANGED_THREAD_ML_ADDR); @@ -1656,10 +1651,7 @@ otError Mle::SendParentRequest(void) uint8_t scanMask = 0; Ip6::Address destination; - for (uint8_t i = 0; i < sizeof(mParentRequest.mChallenge); i++) - { - mParentRequest.mChallenge[i] = static_cast(otPlatRandomGet()); - } + Random::FillBuffer(mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge)); switch (mParentRequestState) { @@ -1900,11 +1892,7 @@ otError Mle::SendChildUpdateRequest(void) switch (mRole) { case OT_DEVICE_ROLE_DETACHED: - for (uint8_t i = 0; i < sizeof(mParentRequest.mChallenge); i++) - { - mParentRequest.mChallenge[i] = static_cast(otPlatRandomGet()); - } - + Random::FillBuffer(mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge)); SuccessOrExit(error = AppendChallenge(*message, mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge))); break; @@ -2540,7 +2528,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo if (mRetrieveNewNetworkData || (static_cast(leaderData.GetDataVersion() - netif.GetNetworkDataLeader().GetVersion()) > 0)) { - delay = otPlatRandomGet() % kMleMaxResponseDelay; + delay = Random::GetUint16InRange(0, kMleMaxResponseDelay); SendDataRequest(aMessageInfo.GetPeerAddr(), tlvs, sizeof(tlvs), delay); } } @@ -2699,7 +2687,7 @@ exit: if (aMessageInfo.GetSockAddr().IsMulticast()) { - delay = otPlatRandomGet() % kMleMaxResponseDelay; + delay = Random::GetUint16InRange(0, kMleMaxResponseDelay); } else { @@ -3594,7 +3582,7 @@ void Mle::StartParentSearchTimer(void) { uint32_t interval; - interval = (otPlatRandomGet() % kParentSearchJitterInterval); + interval = Random::GetUint32InRange(0, kParentSearchJitterInterval); if (mParentSearchIsInBackoff) { diff --git a/src/core/thread/mle_router.cpp b/src/core/thread/mle_router.cpp index 22595f873..2d372e51d 100644 --- a/src/core/thread/mle_router.cpp +++ b/src/core/thread/mle_router.cpp @@ -36,7 +36,6 @@ #include "mle_router.hpp" -#include #include #include "common/code_utils.hpp" @@ -45,6 +44,7 @@ #include "common/instance.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #include "common/settings.hpp" #include "mac/mac_frame.hpp" #include "meshcop/meshcop.hpp" @@ -152,7 +152,7 @@ uint8_t MleRouter::AllocateRouterId(void) // choose available router id at random uint8_t freeBit; - freeBit = otPlatRandomGet() % numAvailable; + freeBit = Random::GetUint8InRange(0, numAvailable); // allocate router id for (uint8_t i = 0; i <= kMaxRouterId; i++) @@ -307,10 +307,10 @@ otError MleRouter::BecomeLeader(void) } else { - SetLeaderData(otPlatRandomGet(), mLeaderWeight, mRouterId); + SetLeaderData(Random::GetUint32(), mLeaderWeight, mRouterId); } - mRouterIdSequence = static_cast(otPlatRandomGet()); + mRouterIdSequence = Random::GetUint8(); netif.GetNetworkDataLeader().Reset(); netif.GetLeader().SetEmptyCommissionerData(); @@ -355,7 +355,7 @@ otError MleRouter::HandleChildStart(AttachMode aMode) ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); - mRouterSelectionJitterTimeout = (otPlatRandomGet() % mRouterSelectionJitter) + 1; + mRouterSelectionJitterTimeout = 1 + Random::GetUint8InRange(0, mRouterSelectionJitter); StopLeader(); mStateUpdateTimer.Start(kStateUpdatePeriod); @@ -652,10 +652,7 @@ otError MleRouter::SendLinkRequest(Neighbor *aNeighbor) if (aNeighbor == NULL) { - for (uint8_t i = 0; i < sizeof(mChallenge); i++) - { - mChallenge[i] = static_cast(otPlatRandomGet()); - } + Random::FillBuffer(mChallenge, sizeof(mChallenge)); mChallengeTimeout = (((2 * kMaxResponseDelay) + kStateUpdatePeriod - 1) / kStateUpdatePeriod); @@ -675,11 +672,7 @@ otError MleRouter::SendLinkRequest(Neighbor *aNeighbor) { uint8_t challenge[ChallengeTlv::kMaxSize]; - for (uint8_t i = 0; i < sizeof(challenge); i++) - { - challenge[i] = static_cast(otPlatRandomGet()); - } - + Random::FillBuffer(challenge, sizeof(challenge)); SuccessOrExit(error = AppendChallenge(*message, challenge, sizeof(challenge))); } @@ -871,7 +864,7 @@ otError MleRouter::SendLinkAccept(const Ip6::MessageInfo &aMessageInfo, if (aMessageInfo.GetSockAddr().IsMulticast()) { SuccessOrExit(error = AddDelayedResponse(*message, aMessageInfo.GetPeerAddr(), - (otPlatRandomGet() % kMaxResponseDelay) + 1)); + 1 + Random::GetUint16InRange(0, kMaxResponseDelay))); LogMleMessage("Delay Link Accept", aMessageInfo.GetPeerAddr()); } @@ -1469,7 +1462,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa (mDeviceMode & ModeTlv::kModeFFD) && (mRouterSelectionJitterTimeout == 0) && (GetActiveRouterCount() < mRouterUpgradeThreshold)) { - mRouterSelectionJitterTimeout = (otPlatRandomGet() % mRouterSelectionJitter) + 1; + mRouterSelectionJitterTimeout = 1 + Random::GetUint8InRange(0, mRouterSelectionJitter); ExitNow(); } @@ -1546,7 +1539,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa HasMinDowngradeNeighborRouters() && HasSmallNumberOfChildren() && HasOneNeighborwithComparableConnectivity(route, routerId)) { - mRouterSelectionJitterTimeout = (otPlatRandomGet() % mRouterSelectionJitter) + 1; + mRouterSelectionJitterTimeout = 1 + Random::GetUint8InRange(0, mRouterSelectionJitter); } // fall through @@ -2045,11 +2038,11 @@ otError MleRouter::SendParentResponse(Child *aChild, const ChallengeTlv &aChalle if (aRoutersOnlyRequest) { - delay = (otPlatRandomGet() % kParentResponseMaxDelayRouters) + 1; + delay = 1 + Random::GetUint16InRange(0, kParentResponseMaxDelayRouters); } else { - delay = (otPlatRandomGet() % kParentResponseMaxDelayAll) + 1; + delay = 1 + Random::GetUint16InRange(0, kParentResponseMaxDelayAll); } SuccessOrExit(error = AddDelayedResponse(*message, destination, delay)); @@ -2634,7 +2627,7 @@ otError MleRouter::HandleNetworkDataUpdateRouter(void) destination.mFields.m16[0] = HostSwap16(0xff02); destination.mFields.m16[7] = HostSwap16(0x0001); - delay = (mRole == OT_DEVICE_ROLE_LEADER) ? 0 : (otPlatRandomGet() % kUnsolicitedDataResponseJitter); + delay = (mRole == OT_DEVICE_ROLE_LEADER) ? 0 : Random::GetUint16InRange(0, kUnsolicitedDataResponseJitter); SendDataResponse(destination, tlvs, sizeof(tlvs), delay); SynchronizeChildNetworkData(); @@ -2871,7 +2864,7 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 tlv.SetLength(static_cast(message->GetLength() - startOffset)); message->Write(startOffset - sizeof(tlv), sizeof(tlv), &tlv); - delay = otPlatRandomGet() % (kDiscoveryMaxJitter + 1); + delay = Random::GetUint16InRange(0, kDiscoveryMaxJitter + 1); SuccessOrExit(error = AddDelayedResponse(*message, aDestination, delay)); diff --git a/src/core/thread/topology.cpp b/src/core/thread/topology.cpp index dad951dfe..a43eddb56 100644 --- a/src/core/thread/topology.cpp +++ b/src/core/thread/topology.cpp @@ -44,10 +44,7 @@ namespace ot { void Neighbor::GenerateChallenge(void) { - for (uint8_t i = 0; i < sizeof(mValidPending.mPending.mChallenge); i++) - { - mValidPending.mPending.mChallenge[i] = static_cast(otPlatRandomGet()); - } + Random::FillBuffer(mValidPending.mPending.mChallenge, sizeof(mValidPending.mPending.mChallenge)); } void Child::ClearIp6Addresses(void) @@ -218,10 +215,7 @@ exit: void Child::GenerateChallenge(void) { - for (uint8_t i = 0; i < sizeof(mAttachChallenge); i++) - { - mAttachChallenge[i] = static_cast(otPlatRandomGet()); - } + Random::FillBuffer(mAttachChallenge, sizeof(mAttachChallenge)); } const Mac::Address &Child::GetMacAddress(Mac::Address &aMacAddress) const diff --git a/src/core/thread/topology.hpp b/src/core/thread/topology.hpp index 0705bfb03..46d98a779 100644 --- a/src/core/thread/topology.hpp +++ b/src/core/thread/topology.hpp @@ -36,9 +36,8 @@ #include "openthread-core-config.h" -#include - #include "common/message.hpp" +#include "common/random.hpp" #include "mac/mac_frame.hpp" #include "net/ip6.hpp" #include "thread/link_quality.hpp" diff --git a/src/core/utils/channel_manager.cpp b/src/core/utils/channel_manager.cpp index e9440f75d..00d4fb855 100644 --- a/src/core/utils/channel_manager.cpp +++ b/src/core/utils/channel_manager.cpp @@ -40,6 +40,7 @@ #include "common/instance.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #if OPENTHREAD_ENABLE_CHANNEL_MANAGER && OPENTHREAD_FTD @@ -78,7 +79,7 @@ otError ChannelManager::RequestChannelChange(uint8_t aChannel) mChannel = aChannel; mActiveTimestamp = 0; - mTimer.Start((otPlatRandomGet() % kRequestStartJitterInterval) + 1); + mTimer.Start(1 + Random::GetUint32InRange(0, kRequestStartJitterInterval)); exit: return error; @@ -138,7 +139,7 @@ void ChannelManager::PreparePendingDataset(void) } } - pendingTimestamp += (otPlatRandomGet() % kMaxTimestampIncrease) + 1; + pendingTimestamp += 1 + Random::GetUint32InRange(0, kMaxTimestampIncrease); error = netif.GetActiveDataset().Get(dataset); @@ -201,7 +202,7 @@ void ChannelManager::PreparePendingDataset(void) } else { - mActiveTimestamp = dataset.mActiveTimestamp + 1 + (otPlatRandomGet() % kMaxTimestampIncrease); + mActiveTimestamp = dataset.mActiveTimestamp + 1 + Random::GetUint32InRange(0, kMaxTimestampIncrease); } dataset.mActiveTimestamp = mActiveTimestamp; diff --git a/src/core/utils/channel_monitor.cpp b/src/core/utils/channel_monitor.cpp index e5b7fa127..e303d957b 100644 --- a/src/core/utils/channel_monitor.cpp +++ b/src/core/utils/channel_monitor.cpp @@ -36,6 +36,7 @@ #include "common/code_utils.hpp" #include "common/logging.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #if OPENTHREAD_ENABLE_CHANNEL_MONITOR @@ -96,7 +97,7 @@ void ChannelMonitor::RestartTimer(void) uint16_t interval = kTimerInterval; int16_t jitter; - jitter = (otPlatRandomGet() % (2 * kMaxJitterInterval)) - kMaxJitterInterval; + jitter = static_cast(Random::GetUint16InRange(0, 2 * kMaxJitterInterval)) - kMaxJitterInterval; if (jitter >= kTimerInterval) { diff --git a/src/core/utils/jam_detector.cpp b/src/core/utils/jam_detector.cpp index 0aa7b064d..7a88dcc5b 100644 --- a/src/core/utils/jam_detector.cpp +++ b/src/core/utils/jam_detector.cpp @@ -34,11 +34,11 @@ #include "jam_detector.hpp" #include -#include #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/owner-locator.hpp" +#include "common/random.hpp" #include "thread/thread_netif.hpp" #if OPENTHREAD_ENABLE_JAM_DETECTION @@ -175,7 +175,7 @@ void JamDetector::HandleTimer(void) } } - mTimer.Start(mSampleInterval + (otPlatRandomGet() % kMaxRandomDelay)); + mTimer.Start(mSampleInterval + Random::GetUint32InRange(0, kMaxRandomDelay)); exit: return; diff --git a/src/core/utils/slaac_address.cpp b/src/core/utils/slaac_address.cpp index fae760333..d95eb7c7b 100644 --- a/src/core/utils/slaac_address.cpp +++ b/src/core/utils/slaac_address.cpp @@ -39,6 +39,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" +#include "common/random.hpp" #include "crypto/sha256.hpp" #include "mac/mac.hpp" #include "net/ip6_address.hpp" @@ -151,11 +152,7 @@ void Slaac::UpdateAddresses(otInstance * aInstance, otError Slaac::CreateRandomIid(otInstance *, otNetifAddress *aAddress, void *) { - for (size_t i = sizeof(aAddress[i].mAddress) - OT_IP6_IID_SIZE; i < sizeof(aAddress[i].mAddress); i++) - { - aAddress->mAddress.mFields.m8[i] = static_cast(otPlatRandomGet()); - } - + Random::FillBuffer(aAddress->mAddress.mFields.m8 + OT_IP6_ADDRESS_SIZE - OT_IP6_IID_SIZE, OT_IP6_IID_SIZE); return OT_ERROR_NONE; } diff --git a/src/core/utils/slaac_address.hpp b/src/core/utils/slaac_address.hpp index 124caaf81..7715aa590 100644 --- a/src/core/utils/slaac_address.hpp +++ b/src/core/utils/slaac_address.hpp @@ -37,7 +37,6 @@ #include "openthread-core-config.h" #include -#include namespace ot { namespace Utils {