Skip to content

Commit

Permalink
Add a NodeId header and some NodeId utilities (#8465)
Browse files Browse the repository at this point in the history
Fixes #8461

The encoder.cpp changes are needed because it used to bootleg the
PacketBuffer header via basic-types.h including MessageHeader.h,
instead of doing include-what-you-use correctly.
  • Loading branch information
bzbarsky-apple authored and pull[bot] committed Sep 2, 2021
1 parent 31184df commit 7358513
Show file tree
Hide file tree
Showing 21 changed files with 125 additions and 60 deletions.
14 changes: 10 additions & 4 deletions examples/chip-tool/commands/pairing/PairingCommand.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

#include "PairingCommand.h"
#include "platform/PlatformManager.h"
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <crypto/CHIPCryptoPAL.h>
#include <lib/core/CHIPSafeCasts.h>
#include <support/logging/CHIPLogging.h>
Expand All @@ -40,12 +41,17 @@ CHIP_ERROR PairingCommand::Run()
#if CONFIG_PAIR_WITH_RANDOM_ID
// Generate a random remote id so we don't end up reusing the same node id
// for different nodes.
//
// TODO: Ideally we'd just ask for an operational cert for the commissionnee
// and get the node from that, but the APIs are not set up that way yet.
NodeId randomId;
DRBG_get_bytes(reinterpret_cast<uint8_t *>(&randomId), sizeof(randomId));
ChipLogProgress(Controller, "Generated random node id: 0x" ChipLogFormatX64, ChipLogValueX64(randomId));
if (GetExecContext()->storage->SetRemoteNodeId(randomId) == CHIP_NO_ERROR)
if (Controller::ExampleOperationalCredentialsIssuer::GetRandomOperationalNodeId(&randomId) == CHIP_NO_ERROR)
{
GetExecContext()->remoteId = randomId;
ChipLogProgress(Controller, "Generated random node id: 0x" ChipLogFormatX64, ChipLogValueX64(randomId));
if (GetExecContext()->storage->SetRemoteNodeId(randomId) == CHIP_NO_ERROR)
{
GetExecContext()->remoteId = randomId;
}
}
#endif // CONFIG_PAIR_WITH_RANDOM_ID

Expand Down
1 change: 1 addition & 0 deletions examples/pump-app/pump-common/gen/encoder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include <support/BufferWriter.h>
#include <support/SafeInt.h>
#include <support/logging/CHIPLogging.h>
#include <system/SystemPacketBuffer.h>

#include <app/common/gen/ids/Attributes.h>
#include <app/common/gen/ids/Clusters.h>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include <support/BufferWriter.h>
#include <support/SafeInt.h>
#include <support/logging/CHIPLogging.h>
#include <system/SystemPacketBuffer.h>

#include <app/common/gen/ids/Attributes.h>
#include <app/common/gen/ids/Clusters.h>
Expand Down
4 changes: 2 additions & 2 deletions src/app/util/CHIPDeviceCallbacksMgr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ CHIP_ERROR CHIPDeviceCallbacksMgr::CancelResponseCallback(NodeId nodeId, uint8_t

CHIP_ERROR CHIPDeviceCallbacksMgr::AddResponseFilter(const ResponseCallbackInfo & info, TLVDataFilter filter)
{
constexpr ResponseCallbackInfo kEmptyInfo{ kAnyNodeId, 0 };
constexpr ResponseCallbackInfo kEmptyInfo{ kPlaceholderNodeId, 0 };

for (size_t i = 0; i < kTLVFilterPoolSize; i++)
{
Expand All @@ -112,7 +112,7 @@ CHIP_ERROR CHIPDeviceCallbacksMgr::PopResponseFilter(const ResponseCallbackInfo
{
*outFilter = mTLVFilterPool[i].filter;
}
mTLVFilterPool[i].info = ResponseCallbackInfo{ kAnyNodeId, 0 };
mTLVFilterPool[i].info = ResponseCallbackInfo{ kPlaceholderNodeId, 0 };
mTLVFilterPool[i].filter = nullptr;
return CHIP_NO_ERROR;
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/util/CHIPDeviceCallbacksMgr.h
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ class DLL_EXPORT CHIPDeviceCallbacksMgr

struct TLVFilterItem
{
ResponseCallbackInfo info = { kAnyNodeId, 0 };
ResponseCallbackInfo info = { kPlaceholderNodeId, 0 };
TLVDataFilter filter = nullptr;
};

Expand Down
2 changes: 1 addition & 1 deletion src/app/util/basic-types.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
#include <stdint.h>

// Pull in NodeId
#include <transport/raw/MessageHeader.h>
#include <lib/core/NodeId.h>

// Pull in VendorId
#include <core/CHIPVendorIdentifiers.hpp>
Expand Down
1 change: 1 addition & 0 deletions src/app/zap-templates/templates/app/encoder-src.zapt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <support/BufferWriter.h>
#include <support/SafeInt.h>
#include <support/logging/CHIPLogging.h>
#include <system/SystemPacketBuffer.h>

#include <app/common/gen/ids/Attributes.h>
#include <app/common/gen/ids/Clusters.h>
Expand Down
6 changes: 4 additions & 2 deletions src/controller/CHIPDeviceController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
#include <core/CHIPEncoding.h>
#include <core/CHIPSafeCasts.h>
#include <credentials/CHIPCert.h>
#include <crypto/CHIPCryptoPAL.h>
#include <lib/core/NodeId.h>
#include <messaging/ExchangeContext.h>
#include <protocols/secure_channel/MessageCounterManager.h>
#include <setup_payload/QRCodeSetupPayloadParser.h>
Expand Down Expand Up @@ -859,7 +861,7 @@ CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParam

Transport::AdminPairingInfo * admin = mAdmins.FindAdminWithId(mAdminId);

VerifyOrExit(remoteDeviceId != kAnyNodeId && remoteDeviceId != kUndefinedNodeId, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(IsOperationalNodeId(remoteDeviceId), err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(mDeviceBeingPaired == kNumMaxActiveDevices, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(admin != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
Expand Down Expand Up @@ -974,7 +976,7 @@ CHIP_ERROR DeviceCommissioner::PairTestDeviceWithoutSecurity(NodeId remoteDevice

// Check that the caller has provided an IP address (instead of a BLE peer address)
VerifyOrExit(peerAddress.GetTransportType() == Transport::Type::kUdp, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(remoteDeviceId != kUndefinedNodeId && remoteDeviceId != kAnyNodeId, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(IsOperationalNodeId(remoteDeviceId), err = CHIP_ERROR_INVALID_ARGUMENT);

VerifyOrExit(mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(mDeviceBeingPaired == kNumMaxActiveDevices, err = CHIP_ERROR_INCORRECT_STATE);
Expand Down
21 changes: 21 additions & 0 deletions src/controller/ExampleOperationalCredentialsIssuer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,5 +142,26 @@ CHIP_ERROR ExampleOperationalCredentialsIssuer::GetRootCACertificate(FabricId fa
return CHIP_NO_ERROR;
}

CHIP_ERROR ExampleOperationalCredentialsIssuer::GetRandomOperationalNodeId(NodeId * aNodeId)
{
for (int i = 0; i < 10; ++i)
{
CHIP_ERROR err = DRBG_get_bytes(reinterpret_cast<uint8_t *>(aNodeId), sizeof(*aNodeId));
if (err != CHIP_NO_ERROR)
{
return err;
}

if (IsOperationalNodeId(*aNodeId))
{
return CHIP_NO_ERROR;
}
}

// Terrible, universe-ending luck (chances are 1 in 2^280 or so here, if our
// DRBG is good).
return CHIP_ERROR_INTERNAL;
}

} // namespace Controller
} // namespace chip
9 changes: 9 additions & 0 deletions src/controller/ExampleOperationalCredentialsIssuer.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ class DLL_EXPORT ExampleOperationalCredentialsIssuer : public OperationalCredent

void SetCertificateValidityPeriod(uint32_t validity) { mValidity = validity; }

/**
* Generate a random operational node id.
*
* @param[out] aNodeId where to place the generated id.
*
* On error no guarantees are made about the state of aNodeId.
*/
static CHIP_ERROR GetRandomOperationalNodeId(NodeId * aNodeId);

private:
Crypto::P256Keypair mIssuer;
Crypto::P256Keypair mIntermediateIssuer;
Expand Down
1 change: 1 addition & 0 deletions src/controller/data_model/gen/encoder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include <support/BufferWriter.h>
#include <support/SafeInt.h>
#include <support/logging/CHIPLogging.h>
#include <system/SystemPacketBuffer.h>

#include <app/common/gen/ids/Attributes.h>
#include <app/common/gen/ids/Clusters.h>
Expand Down
1 change: 1 addition & 0 deletions src/lib/core/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ static_library("core") {
"CHIPTLVUpdater.cpp",
"CHIPTLVUtilities.cpp",
"CHIPTLVWriter.cpp",
"NodeId.h",
"PeerId.h",
]

Expand Down
62 changes: 62 additions & 0 deletions src/lib/core/NodeId.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#pragma once

#include <cstdint>

namespace chip {

// TODO: Consider making this a class and the various utility methods static
// methods.
using NodeId = uint64_t;

constexpr NodeId kUndefinedNodeId = 0ULL;

// The range of possible NodeId values has some pieces carved out for special
// uses.
constexpr NodeId kMinGroupNodeId = 0xFFFF'FFFF'FFFF'0000ULL;
// The max group id is complicated, depending on how we want to count the
// various special group ids. Let's not define it for now, until we have use
// cases.

constexpr NodeId kMinTemporaryLocalId = 0xFFFF'FFFE'0000'0000ULL;
// We use the largest available temporary local id to represent
// kPlaceholderNodeId, so the range is narrowed compared to the spec.
constexpr NodeId kMaxTemporaryLocalId = 0xFFFF'FFFE'FFFF'FFFEULL;
constexpr NodeId kPlaceholderNodeId = 0xFFFF'FFFE'FFFF'FFFFULL;

constexpr NodeId kMinCASEAuthTag1 = 0xFFFF'FFFD'0000'0000ULL;
constexpr NodeId kMaxCASEAuthTag1 = 0xFFFF'FFFD'FFFF'FFFFULL;

constexpr NodeId kMinCASEAuthTag2 = 0xFFFF'FFFC'0000'0000ULL;
constexpr NodeId kMaxCASEAuthTag2 = 0xFFFF'FFFC'FFFF'FFFFULL;

constexpr NodeId kMinPAKEKeyId = 0xFFFF'FFFB'0000'0000ULL;
constexpr NodeId kMaxPAKEKeyId = 0xFFFF'FFFB'FFFF'FFFFULL;

// There are more reserved ranges here, not assigned to anything yet, going down
// all the way to 0xFFFF'FFF0'0000'0000ULL

constexpr NodeId kMaxOperationalNodeId = 0xFFFF'FFEF'FFFF'FFFFULL;

constexpr bool IsOperationalNodeId(NodeId aNodeId)
{
return (aNodeId != kUndefinedNodeId) && (aNodeId <= kMaxOperationalNodeId);
}

} // namespace chip
7 changes: 2 additions & 5 deletions src/lib/core/PeerId.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,12 @@

#pragma once

#include <lib/core/NodeId.h>

namespace chip {

/// Convenience types to make it clear what different number types mean
using NodeId = uint64_t;
using FabricId = uint64_t;

constexpr NodeId kUndefinedNodeId = 0ULL;
constexpr NodeId kAnyNodeId = 0xFFFFFFFFFFFFFFFFULL;

constexpr FabricId kUndefinedFabricId = 0ULL;
constexpr uint16_t kUndefinedVendorId = 0U;

Expand Down
36 changes: 0 additions & 36 deletions src/lib/support/CHIPArgParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,6 @@
#define CHIP_ARG_PARSER_PARSE_FABRIC_ID 0
#endif // CHIP_ARG_PARSER_PARSE_FABRIC_ID

#ifndef CHIP_ARG_PARSER_PARSE_NODE_ID
#define CHIP_ARG_PARSER_PARSE_NODE_ID 0
#endif // CHIP_ARG_PARSER_PARSE_NODE_ID

namespace chip {
namespace ArgParser {

Expand Down Expand Up @@ -892,38 +888,6 @@ bool ParseInt(const char * str, uint8_t & output)
return false;
}

#if CHIP_ARG_PARSER_PARSE_NODE_ID
/**
* Parse a CHIP node id in text form.
*
* @param[in] str A pointer to a NULL-terminated C string containing
* the node id to parse.
* @param[out] output A reference to an uint64_t lvalue in which the parsed
* value will be stored on success.
*
* @return true if the value was successfully parsed; false if not.
*
* @details
* The ParseNodeId() function accepts either a 64-bit node id given in hex
* format (with or without a leading '0x'), or the words 'any' or 'all' which
* are interpreted as meaning the Any node id (0xFFFFFFFFFFFFFFFF).
*/
bool ParseNodeId(const char * str, uint64_t & nodeId)
{
char * parseEnd;

if (strcasecmp(str, "any") == 0 || strcasecmp(str, "all") == 0)
{
nodeId = kAnyNodeId;
return true;
}

errno = 0;
nodeId = strtoull(str, &parseEnd, 16);
return parseEnd > str && *parseEnd == 0 && (nodeId != ULLONG_MAX || errno == 0);
}
#endif // CHIP_ARG_PARSER_PARSE_NODE_ID

#if CHIP_ARG_PARSER_PARSE_FABRIC_ID
/**
* Parse a CHIP fabric id in text form.
Expand Down
1 change: 0 additions & 1 deletion src/lib/support/CHIPArgParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ bool ParseInt(const char * str, uint64_t & output);
bool ParseInt(const char * str, int32_t & output, int base);
bool ParseInt(const char * str, uint32_t & output, int base);
bool ParseInt(const char * str, uint64_t & output, int base);
bool ParseNodeId(const char * str, uint64_t & nodeId);
bool ParseFabricId(const char * str, uint64_t & fabricId, bool allowReserved = false);
bool ParseSubnetId(const char * str, uint16_t & subnetId);
bool ParseHexString(const char * hexStr, uint32_t strLen, uint8_t * outBuf, uint32_t outBufSize, uint32_t & outDataLen);
Expand Down
2 changes: 1 addition & 1 deletion src/messaging/ExchangeContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ bool ExchangeContext::MatchExchange(SecureSessionHandle session, const PacketHea

// AND The message's source Node ID matches the peer Node ID associated with the exchange, or the peer Node ID of the
// exchange is 'any'.
&& ((mSecureSession.GetPeerNodeId() == kAnyNodeId) ||
&& ((mSecureSession.GetPeerNodeId() == kPlaceholderNodeId) ||
(packetHeader.GetSourceNodeId().HasValue() && mSecureSession.GetPeerNodeId() == packetHeader.GetSourceNodeId().Value()))

// AND The message was sent by an initiator and the exchange context is a responder (IsInitiator==false)
Expand Down
4 changes: 2 additions & 2 deletions src/messaging/tests/TestReliableMessageProtocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -568,8 +568,8 @@ void CheckResendSessionEstablishmentMessageWithPeerExchange(nlTestSuite * inSuit
CHIP_ERROR err = ctx.Init(inSuite, &gTransportMgr);
NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);

ctx.SetSourceNodeId(kAnyNodeId);
ctx.SetDestinationNodeId(kAnyNodeId);
ctx.SetSourceNodeId(kPlaceholderNodeId);
ctx.SetDestinationNodeId(kPlaceholderNodeId);
ctx.SetLocalKeyId(0);
ctx.SetPeerKeyId(0);
ctx.SetAdminId(kUndefinedAdminId);
Expand Down
4 changes: 2 additions & 2 deletions src/protocols/secure_channel/tests/TestCASESession.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -482,8 +482,8 @@ CHIP_ERROR CASETestSecurePairingSetup(void * inContext)

ReturnErrorOnFailure(ctx.Init(&sSuite, &gTransportMgr));

ctx.SetSourceNodeId(kAnyNodeId);
ctx.SetDestinationNodeId(kAnyNodeId);
ctx.SetSourceNodeId(kPlaceholderNodeId);
ctx.SetDestinationNodeId(kPlaceholderNodeId);
ctx.SetLocalKeyId(0);
ctx.SetPeerKeyId(0);
ctx.SetAdminId(kUndefinedAdminId);
Expand Down
4 changes: 2 additions & 2 deletions src/protocols/secure_channel/tests/TestPASESession.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -388,8 +388,8 @@ int TestSecurePairing_Setup(void * inContext)
if (err != CHIP_NO_ERROR)
return FAILURE;

ctx.SetSourceNodeId(kAnyNodeId);
ctx.SetDestinationNodeId(kAnyNodeId);
ctx.SetSourceNodeId(kPlaceholderNodeId);
ctx.SetDestinationNodeId(kPlaceholderNodeId);
ctx.SetLocalKeyId(0);
ctx.SetPeerKeyId(0);
ctx.SetAdminId(kUndefinedAdminId);
Expand Down
2 changes: 1 addition & 1 deletion src/transport/SecureSessionHandle.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class SecureSessionMgr;
class SecureSessionHandle
{
public:
SecureSessionHandle() : mPeerNodeId(kAnyNodeId), mPeerKeyId(0), mAdmin(Transport::kUndefinedAdminId) {}
SecureSessionHandle() : mPeerNodeId(kPlaceholderNodeId), mPeerKeyId(0), mAdmin(Transport::kUndefinedAdminId) {}
SecureSessionHandle(NodeId peerNodeId, uint16_t peerKeyId, Transport::AdminId admin) :
mPeerNodeId(peerNodeId), mPeerKeyId(peerKeyId), mAdmin(admin)
{}
Expand Down

0 comments on commit 7358513

Please sign in to comment.