diff --git a/src/common/BitManipulation.h b/src/common/BitManipulation.h index 859dcef4..6a40613e 100644 --- a/src/common/BitManipulation.h +++ b/src/common/BitManipulation.h @@ -4,7 +4,7 @@ * GPLv2 Open Source. Use is subject to license terms. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * - * Copyright (C) 2025 Bryan Biedenkapp, N2PLL + * Copyright (C) 2025,2026 Bryan Biedenkapp, N2PLL * */ /** @@ -51,6 +51,37 @@ const uint8_t BIT_MASK_TABLE[] = { 0x80U, 0x40U, 0x20U, 0x10U, 0x08U, 0x04U, 0 */ #define READ_BIT(p, i) (p[(i) >> 3] & BIT_MASK_TABLE[(i) & 7]) +/** + * @brief Sets a uint64_t into 8 bytes of a buffer/array. (64-bit value). + * @ingroup common + * @param val uint64_t value to set + * @param buffer uint8_t buffer to set value on + * @param offset Offset within uint8_t buffer + */ +#define SET_UINT64(val, buffer, offset) \ + buffer[0U + offset] = (val >> 56) & 0xFFU; \ + buffer[1U + offset] = (val >> 48) & 0xFFU; \ + buffer[2U + offset] = (val >> 40) & 0xFFU; \ + buffer[3U + offset] = (val >> 32) & 0xFFU; \ + buffer[4U + offset] = (val >> 24) & 0xFFU; \ + buffer[5U + offset] = (val >> 16) & 0xFFU; \ + buffer[6U + offset] = (val >> 8) & 0xFFU; \ + buffer[7U + offset] = (val >> 0) & 0xFFU; +/** + * @brief Gets a uint64_t consisting of 8 bytes from a buffer/array. (64-bit value). + * @ingroup common + * @param buffer uint8_t buffer to get value from + * @param offset Offset within uint8_t buffer + */ +#define GET_UINT64(buffer, offset) \ + ((uint64_t)buffer[offset + 0U] << 56) | \ + ((uint64_t)buffer[offset + 1U] << 48) | \ + ((uint64_t)buffer[offset + 2U] << 40) | \ + ((uint64_t)buffer[offset + 3U] << 32) | \ + ((uint64_t)buffer[offset + 4U] << 24) | \ + ((uint64_t)buffer[offset + 5U] << 16) | \ + ((uint64_t)buffer[offset + 6U] << 8) | \ + ((uint64_t)buffer[offset + 7U] << 0); /** * @brief Sets a uint32_t into 4 bytes of a buffer/array. (32-bit value). * @ingroup common diff --git a/src/common/network/RTPFNEHeader.h b/src/common/network/RTPFNEHeader.h index 0076b220..a747b8a6 100644 --- a/src/common/network/RTPFNEHeader.h +++ b/src/common/network/RTPFNEHeader.h @@ -118,6 +118,8 @@ namespace network SUBSCRIBER_OP_OPERATION = 0x00U, //!< Subscriber Operation Result Query SUBSCRIBER_OP_P25_STATUS = 0x01U, //!< P25 Subscriber Status Query SUBSCRIBER_OP_START = 0x02U, //!< Start Subscriber Operation + SUBSCRIBER_OP_PROXY_REQUEST = 0x03U, //!< Proxied Subscriber Operation Result Query + SUBSCRIBER_OP_PROXY_RESPONSE = 0x04U, //!< Proxied Subscriber Operation Result Response ANNC_SUBFUNC_GRP_AFFIL = 0x00U, //!< Announce Group Affiliation ANNC_SUBFUNC_UNIT_REG = 0x01U, //!< Announce Unit Registration diff --git a/src/fne/HostFNE.cpp b/src/fne/HostFNE.cpp index fd7d48d4..1ab1a0ef 100644 --- a/src/fne/HostFNE.cpp +++ b/src/fne/HostFNE.cpp @@ -931,6 +931,7 @@ bool HostFNE::createPeerNetworks() network->setNetTreeDiscCallback(std::bind(&HostFNE::processNetworkTreeDisconnect, this, std::placeholders::_1, std::placeholders::_2)); network->setNotifyPeerReplicaCallback(std::bind(&HostFNE::processPeerReplicaNotify, this, std::placeholders::_1)); network->setPatchStatusCallback(std::bind(&HostFNE::processPeerPatchStatus, this, std::placeholders::_1, std::placeholders::_2)); + network->setSubscriberOperationProxyCallback(std::bind(&HostFNE::processSubscriberOperationProxyResponse, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); network->enable(enabled); if (enabled) { @@ -1322,3 +1323,12 @@ void HostFNE::processPeerPatchStatus(network::PeerNetwork* peerNetwork, json::ob m_network->processReplicatedPatchStatus(peerNetwork->getPeerId(), obj); } } + +/* Processes a subscriber operation proxy response from an upstream FNE. */ + +void HostFNE::processSubscriberOperationProxyResponse(network::PeerNetwork* peerNetwork, const uint8_t* data, uint32_t length, uint32_t peerId) +{ + if (m_network != nullptr && peerNetwork != nullptr) { + m_network->processSubscriberOperationProxyResponse(peerNetwork, data, length, peerId); + } +} diff --git a/src/fne/HostFNE.h b/src/fne/HostFNE.h index 2b4a04ab..754765da 100644 --- a/src/fne/HostFNE.h +++ b/src/fne/HostFNE.h @@ -306,6 +306,14 @@ private: * @param obj Patch status JSON payload. */ void processPeerPatchStatus(network::PeerNetwork* peerNetwork, json::object obj); + /** + * @brief Processes a subscriber operation proxy response from an upstream FNE. + * @param peerNetwork Upstream peer network instance. + * @param data Packed response buffer. + * @param length Length of the packed response buffer. + * @param peerId Destination peer ID carried in the response. + */ + void processSubscriberOperationProxyResponse(network::PeerNetwork* peerNetwork, const uint8_t* data, uint32_t length, uint32_t peerId); }; #endif // __HOST_FNE_H__ diff --git a/src/fne/network/PeerNetwork.cpp b/src/fne/network/PeerNetwork.cpp index b4777e57..e74fa59e 100644 --- a/src/fne/network/PeerNetwork.cpp +++ b/src/fne/network/PeerNetwork.cpp @@ -50,6 +50,7 @@ PeerNetwork::PeerNetwork(const std::string& address, uint16_t port, uint16_t loc m_netTreeDiscCallback(nullptr), m_peerReplicaCallback(nullptr), m_patchStatusCallback(nullptr), + m_subscriberOperationProxyCallback(nullptr), m_masterPeerId(0U), m_ridAliasLookup(nullptr), m_pidLookup(nullptr), @@ -340,6 +341,14 @@ void PeerNetwork::userPacketHandler(uint32_t peerId, FrameQueue::OpcodePair opco } break; + case NET_FUNC::SUBSCRIBER_OP: // Subscriber Operation + { + if (opcode.second == NET_SUBFUNC::SUBSCRIBER_OP_PROXY_RESPONSE && m_subscriberOperationProxyCallback != nullptr) { + m_subscriberOperationProxyCallback(this, data, length, peerId); + } + } + break; + case NET_FUNC::REPL: // Peer Replication { switch (opcode.second) { diff --git a/src/fne/network/PeerNetwork.h b/src/fne/network/PeerNetwork.h index 7ed453a5..a94a208a 100644 --- a/src/fne/network/PeerNetwork.h +++ b/src/fne/network/PeerNetwork.h @@ -30,6 +30,10 @@ #include #include +#if defined(CATCH2_TEST_COMPILATION) +class FNETestHooks; +#endif + namespace network { // --------------------------------------------------------------------------- @@ -63,6 +67,9 @@ namespace network * @ingroup fne_network */ class HOST_SW_API PeerNetwork : public Network { +#if defined(CATCH2_TEST_COMPILATION) + friend class ::FNETestHooks; +#endif public: /** * @brief Callback for protocol packet processing. @@ -169,6 +176,11 @@ namespace network * @param callback */ void setPatchStatusCallback(std::function&& callback) { m_patchStatusCallback = callback; } + /** + * @brief Sets the subscriber operation proxy response callback. + * @param callback Callback receiving the packed proxy response. + */ + void setSubscriberOperationProxyCallback(std::function&& callback) { m_subscriberOperationProxyCallback = callback; } /** * @brief Writes a complete update of this CFNE's active peer list to the network. @@ -321,27 +333,27 @@ namespace network * @brief DMR Protocol Callback. * (This is called when the master sends a DMR packet.) */ - std::function m_dmrCallback; + ProtocolCallback m_dmrCallback; /** * @brief P25 Protocol Callback. * (This is called when the master sends a P25 packet.) */ - std::function m_p25Callback; + ProtocolCallback m_p25Callback; /** * @brief P25 Phase 2 Protocol Callback. * (This is called when the master sends a P25 Phase 2 packet.) */ - std::function m_p25P2Callback; + ProtocolCallback m_p25P2Callback; /** * @brief NXDN Protocol Callback. * (This is called when the master sends a NXDN packet.) */ - std::function m_nxdnCallback; + ProtocolCallback m_nxdnCallback; /** * @brief Analog Protocol Callback. * (This is called when the master sends a analog packet.) */ - std::function m_analogCallback; + ProtocolCallback m_analogCallback; /** * @brief Network Tree Disconnect Callback. @@ -355,6 +367,10 @@ namespace network * @brief Peer patch status callback. */ std::function m_patchStatusCallback; + /** + * @brief Subscriber operation proxy response callback. + */ + std::function m_subscriberOperationProxyCallback; /** * @brief User overrideable handler that allows user code to process network packets not handled by this class. diff --git a/src/fne/network/TrafficNetwork.cpp b/src/fne/network/TrafficNetwork.cpp index e1296180..72aa994e 100644 --- a/src/fne/network/TrafficNetwork.cpp +++ b/src/fne/network/TrafficNetwork.cpp @@ -112,6 +112,9 @@ TrafficNetwork::TrafficNetwork(HostFNE* host, const std::string& address, uint16 m_affiliationUpdateMutex(), m_unitRouteRegistry(), m_subscriberOperations(5, 10), + m_subscriberOperationProxyPending(), + m_subscriberOperationProxyMutex(), + m_subscriberOperationProxyNextId(1U), m_ccPeerMap(), m_peerReplicaKeyQueue(), m_peerReplicaKEKKeyQueue(), @@ -883,6 +886,19 @@ void TrafficNetwork::clock(uint32_t ms) // expire any pending subscriber operations and remove retained results m_subscriberOperations.expire(); + { + std::lock_guard lock(m_subscriberOperationProxyMutex); + for (auto it = m_subscriberOperationProxyPending.begin(); + it != m_subscriberOperationProxyPending.end();) { + if (it->second.expiresAt <= now) { + LogWarning(LOG_MASTER, "Subscriber operation proxy request timed out, transactionId = %u", + it->first); + it = m_subscriberOperationProxyPending.erase(it); + } else { + ++it; + } + } + } // check jitter buffer timeouts for all peers for (const auto& peer : peersSnapshot()) { @@ -3455,6 +3471,10 @@ bool TrafficNetwork::writePeerQueue(udp::BufferQueue* buffers, uint32_t peerId, PeerConnectionPtr connection = findPeer(peerId); if (connection != nullptr) { #if defined(CATCH2_TEST_COMPILATION) + if (m_testPeerPayloadWriteHandler) { + m_testPeerPayloadWriteHandler(peerId, opcode, data, length); + return true; + } if (m_testPeerWriteHandler) { m_testPeerWriteHandler(peerId, opcode); return true; diff --git a/src/fne/network/TrafficNetwork.h b/src/fne/network/TrafficNetwork.h index fb001d9a..f8baaa5d 100644 --- a/src/fne/network/TrafficNetwork.h +++ b/src/fne/network/TrafficNetwork.h @@ -81,6 +81,8 @@ namespace network { namespace callhandler { class HOST_SW_API TagP25Data; } } namespace network { namespace callhandler { namespace packetdata { class HOST_SW_API P25PacketData; } } } namespace network { namespace callhandler { class HOST_SW_API TagP25P2Data; } } namespace network { class HOST_SW_API P25OTARService; } +namespace network { class HOST_SW_API MetadataNetwork; } +namespace network { class HOST_SW_API PeerNetwork; } namespace network { namespace callhandler { class HOST_SW_API TagNXDNData; } } namespace network { namespace callhandler { class HOST_SW_API TagAnalogData; } } @@ -146,6 +148,23 @@ namespace network // Structure Declaration // --------------------------------------------------------------------------- + /** + * @brief Correlation state for one subscriber operation query forwarded upstream. + * @ingroup fne_network + */ + struct SubscriberOperationProxyPending { + MetadataNetwork* metadata; //!< Metadata network for a local console response. + uint32_t downstreamPeerId; //!< Console or downstream FNE peer ID. + uint32_t downstreamStreamId; //!< Original downstream stream ID. + uint32_t downstreamTransactionId; //!< Downstream proxy transaction ID, or zero for a console. + uint64_t operationId; //!< Requested subscriber operation ID. + uint64_t expiresAt; //!< Expiration time in Unix milliseconds. + }; + + // --------------------------------------------------------------------------- + // Structure Declaration + // --------------------------------------------------------------------------- + /** * @brief Represents the data required for a network packet handler thread. * @ingroup fne_network @@ -260,6 +279,27 @@ namespace network */ SubscriberOperationStore& subscriberOperations() { return m_subscriberOperations; } + /** + * @brief Proxies a subscriber operation result query to the upstream replica parent. + * @param metadata Metadata network used to return a locally originated console response. + * @param downstreamPeerId Console or downstream FNE peer ID awaiting the response. + * @param downstreamStreamId Stream ID supplied by the downstream requestor. + * @param downstreamTransactionId Proxy transaction ID supplied by a downstream FNE, or zero for a console. + * @param operationId Subscriber operation ID to query. + * @param hopLimit Number of additional upstream hops permitted. + * @returns True if the request was forwarded, otherwise false. + */ + bool proxySubscriberOperation(MetadataNetwork* metadata, uint32_t downstreamPeerId, uint32_t downstreamStreamId, uint32_t downstreamTransactionId, + uint64_t operationId, uint8_t hopLimit); + /** + * @brief Processes a packed subscriber operation proxy response received from an upstream parent. + * @param peer Upstream peer network that supplied the response. + * @param data Packed response buffer. + * @param length Length of the packed response buffer. + * @param peerId Destination peer ID carried in the response. + */ + void processSubscriberOperationProxyResponse(PeerNetwork* peer, const uint8_t* data, uint32_t length, uint32_t peerId); + /** * @brief Sets the instances of the Radio ID, Radio Alias, Talkgroup ID, Peer List, and Crypto lookup tables. * @param ridLookup Radio ID Lookup Table Instance @@ -349,6 +389,8 @@ namespace network #if defined(CATCH2_TEST_COMPILATION) friend class ::FNETestHooks; std::function m_testPeerWriteHandler; + std::function m_testSubscriberOperationProxyWriteHandler; + std::function m_testPeerPayloadWriteHandler; #endif friend class MetadataNetwork; friend class callhandler::TagDMRData; @@ -423,6 +465,9 @@ namespace network mutable std::mutex m_affiliationUpdateMutex; UnitRouteRegistry m_unitRouteRegistry; SubscriberOperationStore m_subscriberOperations; + std::unordered_map m_subscriberOperationProxyPending; + std::mutex m_subscriberOperationProxyMutex; + std::atomic m_subscriberOperationProxyNextId; concurrent::shared_unordered_map> m_ccPeerMap; static std::timed_mutex s_keyQueueMutex; std::unordered_map m_peerReplicaKeyQueue; diff --git a/src/fne/network/packet/SubscriberOperation.cpp b/src/fne/network/packet/SubscriberOperation.cpp index fedb6225..ac26a362 100644 --- a/src/fne/network/packet/SubscriberOperation.cpp +++ b/src/fne/network/packet/SubscriberOperation.cpp @@ -10,10 +10,13 @@ */ #include "fne/Defines.h" #include "common/dmr/DMRDefines.h" +#include "common/BitManipulation.h" #include "common/Log.h" #include "common/p25/P25Defines.h" #include "common/json/json.h" #include "network/MetadataNetwork.h" +#include "network/PeerNetwork.h" +#include "fne/HostFNE.h" #include "network/callhandler/TagDMRData.h" #include "network/callhandler/TagP25Data.h" @@ -28,6 +31,240 @@ using namespace network; #define SOP_NXDN "nxdn" const uint32_t SUBSCRIBER_OPERATION_HEADER_LENGTH = 11U; +const uint32_t SUBSCRIBER_OPERATION_PROXY_REQUEST_LENGTH = 16U; +const uint32_t SUBSCRIBER_OPERATION_PROXY_RESPONSE_LENGTH = 52U; +const uint32_t SUBSCRIBER_OPERATION_PROXY_TIMEOUT_MS = 5000U; +const uint8_t SUBSCRIBER_OPERATION_PROXY_HOP_LIMIT = 16U; + +/** + * @brief Result codes for subscriber operation proxy responses. + * @ingroup fne_network + */ +enum SubscriberOperationProxyResult : uint8_t { + SUBSCRIBER_OPERATION_PROXY_FOUND = 0U, + SUBSCRIBER_OPERATION_PROXY_NOT_FOUND = 1U, + SUBSCRIBER_OPERATION_PROXY_NO_ROUTE = 2U +}; + +// --------------------------------------------------------------------------- +// Global Functions +// --------------------------------------------------------------------------- + +/* Encodes a subscriber operation proxy response. */ + +static void encodeProxyResponse(uint8_t* buffer, uint8_t result, uint32_t transactionId, uint64_t operationId, const SubscriberOperationStore::Operation* operation) +{ + ::memset(buffer, 0x00U, SUBSCRIBER_OPERATION_HEADER_LENGTH + SUBSCRIBER_OPERATION_PROXY_RESPONSE_LENGTH); + + const uint32_t offset = SUBSCRIBER_OPERATION_HEADER_LENGTH; + buffer[offset] = result; + SET_UINT32(transactionId, buffer, offset + 4U); // Transaction ID + SET_UINT64(operationId, buffer, offset + 8U); // Operaiton ID + + if (operation == nullptr) + return; + + buffer[offset + 16U] = 1U; // + buffer[offset + 17U] = static_cast(operation->protocol); // Operation Protocol + buffer[offset + 18U] = static_cast(operation->kind); // Opertaion Kind + buffer[offset + 19U] = static_cast(operation->state); // Operation STate + SET_UINT32(operation->targetId, buffer, offset + 20U); // Target ID + SET_UINT32(operation->peerId, buffer, offset + 24U); // Peer ID + SET_UINT32(operation->requestValue, buffer, offset + 28U); // Request Value + SET_UINT32(operation->resultValue, buffer, offset + 32U); // Result Value + SET_UINT64(operation->createdAt, buffer, offset + 36U); // Created At + SET_UINT64(operation->completedAt, buffer, offset + 44U); // Completed At +} + +/* Proxies a subscriber operation result query to the upstream replica parent. */ + +bool TrafficNetwork::proxySubscriberOperation(MetadataNetwork* metadata, uint32_t downstreamPeerId, + uint32_t downstreamStreamId, uint32_t downstreamTransactionId, uint64_t operationId, uint8_t hopLimit) +{ + if (operationId == 0U || hopLimit == 0U || m_host == nullptr) + return false; + + // find an enabled replica peer to proxy the operation query upstream + PeerNetwork* upstream = nullptr; +#if defined(CATCH2_TEST_COMPILATION) + const bool testUpstream = static_cast(m_testSubscriberOperationProxyWriteHandler); +#else + const bool testUpstream = false; +#endif + for (const auto& peer : m_host->m_peerNetworks) { + if (peer.second != nullptr && peer.second->isEnabled() && peer.second->isReplica()) { + upstream = peer.second; + break; + } + } + + if (upstream == nullptr && !testUpstream) + return false; + + uint32_t transactionId = 0U; + const uint64_t now = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + + // scope is intentional + { + std::lock_guard lock(m_subscriberOperationProxyMutex); + if (m_subscriberOperationProxyPending.size() >= 1024U) { + LogWarning(LOG_MASTER, "Subscriber operation proxy queue is full"); + return false; + } + + do { + transactionId = m_subscriberOperationProxyNextId.fetch_add(1U); + } while (transactionId == 0U || m_subscriberOperationProxyPending.find(transactionId) != m_subscriberOperationProxyPending.end()); + + m_subscriberOperationProxyPending[transactionId] = { + metadata, downstreamPeerId, downstreamStreamId, downstreamTransactionId, + operationId, now + SUBSCRIBER_OPERATION_PROXY_TIMEOUT_MS + }; + } + + // build the proxy request packet + uint8_t buffer[SUBSCRIBER_OPERATION_HEADER_LENGTH + SUBSCRIBER_OPERATION_PROXY_REQUEST_LENGTH]; + ::memset(buffer, 0x00U, sizeof(buffer)); + + const uint32_t offset = SUBSCRIBER_OPERATION_HEADER_LENGTH; + buffer[offset] = hopLimit; + SET_UINT32(transactionId, buffer, offset + 4U); + SET_UINT64(operationId, buffer, offset + 8U); + + bool written = false; +#if defined(CATCH2_TEST_COMPILATION) + if (m_testSubscriberOperationProxyWriteHandler) { + written = m_testSubscriberOperationProxyWriteHandler( + { NET_FUNC::SUBSCRIBER_OP, NET_SUBFUNC::SUBSCRIBER_OP_PROXY_REQUEST }, + buffer, sizeof(buffer)); + } else +#endif + { + written = upstream->writeMaster({ NET_FUNC::SUBSCRIBER_OP, NET_SUBFUNC::SUBSCRIBER_OP_PROXY_REQUEST }, buffer, sizeof(buffer), RTP_END_OF_CALL_SEQ, createStreamId(), true); + } + + if (!written) { + std::lock_guard lock(m_subscriberOperationProxyMutex); + m_subscriberOperationProxyPending.erase(transactionId); + } + + return written; +} + +/* Processes a packed subscriber operation proxy response received from an upstream parent. */ + +void TrafficNetwork::processSubscriberOperationProxyResponse(PeerNetwork* peer, const uint8_t* data, uint32_t length, uint32_t peerId) +{ + // validate the upstream peer, packet length, peer ID, and subfunction before parsing the response + const uint32_t packetLength = SUBSCRIBER_OPERATION_HEADER_LENGTH + SUBSCRIBER_OPERATION_PROXY_RESPONSE_LENGTH; + if (peer == nullptr || !peer->isEnabled() || !peer->isReplica() || data == nullptr || length != packetLength || peerId != peer->getPeerId()) { + LogWarning(LOG_MASTER, "Ignoring invalid subscriber operation proxy response"); + return; + } + + // validate the reserved bytes before parsing the response + const uint32_t offset = SUBSCRIBER_OPERATION_HEADER_LENGTH; + if (data[offset + 1U] != 0U || data[offset + 2U] != 0U || data[offset + 3U] != 0U) { + LogWarning(LOG_MASTER, "Ignoring subscriber operation proxy response with nonzero reserved bytes"); + return; + } + + // validate the result and response-found flag before looking up the pending transaction + const uint8_t result = data[offset]; + const uint8_t responseFound = data[offset + 16U]; + if (result > SUBSCRIBER_OPERATION_PROXY_NO_ROUTE || responseFound > 1U || (result == SUBSCRIBER_OPERATION_PROXY_FOUND) != (responseFound == 1U)) { + LogWarning(LOG_MASTER, "Ignoring malformed subscriber operation proxy response result"); + return; + } + + // match the response to a pending transaction by transaction ID and operation ID + const uint32_t transactionId = GET_UINT32(data, offset + 4U); + const uint64_t operationId = GET_UINT64(data, offset + 8U); + SubscriberOperationProxyPending pending{}; + + // scope is intentional + { + std::lock_guard lock(m_subscriberOperationProxyMutex); + auto it = m_subscriberOperationProxyPending.find(transactionId); + if (transactionId == 0U || it == m_subscriberOperationProxyPending.end() || it->second.operationId != operationId) { + LogWarning(LOG_MASTER, "Ignoring unknown subscriber operation proxy response, transactionId = %u", transactionId); + return; + } + + pending = it->second; + m_subscriberOperationProxyPending.erase(it); + } + + // forward the response to the downstream peer when a downstream transaction is pending + if (pending.downstreamTransactionId != 0U) { + uint8_t response[SUBSCRIBER_OPERATION_HEADER_LENGTH + SUBSCRIBER_OPERATION_PROXY_RESPONSE_LENGTH]; + ::memcpy(response, data, sizeof(response)); + + SET_UINT32(pending.downstreamTransactionId, response, offset + 4U); + + writePeer(pending.downstreamPeerId, m_peerId, { NET_FUNC::SUBSCRIBER_OP, NET_SUBFUNC::SUBSCRIBER_OP_PROXY_RESPONSE }, + response, sizeof(response), RTP_END_OF_CALL_SEQ, pending.downstreamStreamId); + return; + } + + // send the response to the downstream console when no downstream transaction is pending + PeerConnectionPtr connection = findPeer(pending.downstreamPeerId); + if (pending.metadata == nullptr || connection == nullptr || !connection->connected() || + connection->peerClass() != PEER_CONN_CLASS_CONSOLE) { + return; + } + + json::object response = json::object(); + response["type"].set("operation"); + response["operationId"].set(operationId); + + const bool found = result == SUBSCRIBER_OPERATION_PROXY_FOUND; + response["found"].set(found); + + json::array operations = json::array(); + if (found) { + const SubscriberOperationStore::Protocol protocol = static_cast(data[offset + 17U]); + const SubscriberOperationStore::Kind kind = static_cast(data[offset + 18U]); + const SubscriberOperationStore::State state = static_cast(data[offset + 19U]); + response["protocol"].set(SubscriberOperationStore::protocolName(protocol)); + response["operation"].set(SubscriberOperationStore::kindName(kind)); + response["state"].set(SubscriberOperationStore::stateName(state)); + + const uint32_t targetId = GET_UINT32(data, offset + 20U) + const uint32_t operationPeerId = GET_UINT32(data, offset + 24U) + const uint32_t requestValue = GET_UINT32(data, offset + 28U) + const uint32_t resultValue = GET_UINT32(data, offset + 32U) + response["targetId"].set(targetId); + response["peerId"].set(operationPeerId); + response["requestValue"].set(requestValue); + response["resultValue"].set(resultValue); + + const uint64_t createdAt = GET_UINT64(data, offset + 36U); + const uint64_t completedAt = GET_UINT64(data, offset + 44U); + response["createdAt"].set(createdAt); + response["completedAt"].set(completedAt); + + json::object operation = response; + operation.erase("type"); + operation.erase("found"); + operations.push_back(json::value(operation)); + } else if (result == SUBSCRIBER_OPERATION_PROXY_NO_ROUTE) { + response["error"].set("no upstream route"); + } + + response["operations"].set(operations); + + const std::string payload = json::value(response).serialize(); + if (payload.length() + SUBSCRIBER_OPERATION_HEADER_LENGTH > DATA_PACKET_LENGTH) + return; + + // build the response packet and write it to the peer metadata + uint8_t buffer[DATA_PACKET_LENGTH]; + ::memset(buffer, 0x00U, sizeof(buffer)); + ::memcpy(buffer + SUBSCRIBER_OPERATION_HEADER_LENGTH, payload.data(), payload.length()); + pending.metadata->writePeerMetadata(connection.get(), m_peerId, { NET_FUNC::SUBSCRIBER_OP, NET_SUBFUNC::SUBSCRIBER_OP_OPERATION }, buffer, + static_cast(payload.length()) + SUBSCRIBER_OPERATION_HEADER_LENGTH, RTP_END_OF_CALL_SEQ, pending.downstreamStreamId); +} // --------------------------------------------------------------------------- // Public Class Members @@ -43,9 +280,14 @@ void MetadataNetwork::PacketHandler::subscriberOperation(TrafficNetwork* network TrafficNetwork::PeerConnectionPtr connection = network->findPeer(peerId); const std::string sourceAddress = udp::Socket::address(req->address); + const NET_SUBFUNC::ENUM subFunction = req->fneHeader.getSubFunction(); + const bool proxyRequest = subFunction == NET_SUBFUNC::SUBSCRIBER_OP_PROXY_REQUEST; // validate the peer connection and source address before processing the subscriber operation request - if (connection == nullptr || !connection->connected() || connection->peerClass() != PEER_CONN_CLASS_CONSOLE || + const bool validConsole = connection != nullptr && connection->peerClass() == PEER_CONN_CLASS_CONSOLE; + const bool validProxyNeighbor = connection != nullptr && connection->peerClass() == PEER_CONN_CLASS_NEIGHBOR && connection->isReplica(); + if (connection == nullptr || !connection->connected() || + (proxyRequest ? !validProxyNeighbor : !validConsole) || (!connection->address().empty() && connection->address() != sourceAddress)) { network->writePeerNAK(peerId, network->createStreamId(), "SUBSCRIBER_OP", NET_CONN_NAK_FNE_UNAUTHORIZED); return; @@ -55,7 +297,6 @@ void MetadataNetwork::PacketHandler::subscriberOperation(TrafficNetwork* network json::object response = json::object(); const bool notFound = false; const bool found = true; - const NET_SUBFUNC::ENUM subFunction = req->fneHeader.getSubFunction(); // helper function to write the response back to the peer const auto writeResponse = [network, mdNetwork, connection, subFunction, streamId](json::object responseObj) { @@ -78,6 +319,60 @@ void MetadataNetwork::PacketHandler::subscriberOperation(TrafficNetwork* network responseLength + SUBSCRIBER_OPERATION_HEADER_LENGTH, RTP_END_OF_CALL_SEQ, streamId); }; + // handle proxy requests by checking the local store before forwarding to another peer + if (proxyRequest) { + const uint32_t packetLength = SUBSCRIBER_OPERATION_HEADER_LENGTH + SUBSCRIBER_OPERATION_PROXY_REQUEST_LENGTH; + if (req->length != static_cast(packetLength)) { + LogWarning(LOG_MASTER, "PEER %u sent malformed subscriber operation proxy request, length = %d", peerId, req->length); + return; + } + + // validate that all reserved bytes in the proxy request are zero + const uint32_t offset = SUBSCRIBER_OPERATION_HEADER_LENGTH; + if (req->buffer[offset + 1U] != 0U || req->buffer[offset + 2U] != 0U || req->buffer[offset + 3U] != 0U) { + LogWarning(LOG_MASTER, "PEER %u sent subscriber operation proxy request with nonzero reserved bytes", + peerId); + return; + } + + const uint8_t hopLimit = req->buffer[offset]; + const uint32_t transactionId = GET_UINT32(req->buffer, offset + 4U); + const uint64_t operationId = GET_UINT64(req->buffer, offset + 8U); + if (hopLimit == 0U || transactionId == 0U || operationId == 0U) { + LogWarning(LOG_MASTER, "PEER %u sent invalid subscriber operation proxy request", peerId); + return; + } + + // check the local store before forwarding the request to another peer + SubscriberOperationStore::Operation operation; + const bool found = network->subscriberOperations().get(operationId, operation); + if (found) { + uint8_t response[SUBSCRIBER_OPERATION_HEADER_LENGTH + SUBSCRIBER_OPERATION_PROXY_RESPONSE_LENGTH]; + + encodeProxyResponse(response, SUBSCRIBER_OPERATION_PROXY_FOUND, transactionId, operationId, &operation); + + network->writePeer(peerId, network->m_peerId, { NET_FUNC::SUBSCRIBER_OP, NET_SUBFUNC::SUBSCRIBER_OP_PROXY_RESPONSE }, + response, sizeof(response), RTP_END_OF_CALL_SEQ, streamId); + + return; + } + + if (hopLimit > 1U && network->proxySubscriberOperation(nullptr, peerId, streamId, transactionId, operationId, hopLimit - 1U)) { + return; + } + + // no peer could satisfy the request; report whether forwarding was possible + uint8_t response[SUBSCRIBER_OPERATION_HEADER_LENGTH + SUBSCRIBER_OPERATION_PROXY_RESPONSE_LENGTH]; + const uint8_t result = hopLimit == 1U ? SUBSCRIBER_OPERATION_PROXY_NOT_FOUND : SUBSCRIBER_OPERATION_PROXY_NO_ROUTE; + + encodeProxyResponse(response, result, transactionId, operationId, nullptr); + + network->writePeer(peerId, network->m_peerId, { NET_FUNC::SUBSCRIBER_OP, NET_SUBFUNC::SUBSCRIBER_OP_PROXY_RESPONSE }, + response, sizeof(response), RTP_END_OF_CALL_SEQ, streamId); + + return; + } + // validate the request length against the expected header and data packet limits if (req->length <= static_cast(SUBSCRIBER_OPERATION_HEADER_LENGTH) || req->length > static_cast(DATA_PACKET_LENGTH)) { response["found"].set(notFound); @@ -261,6 +556,10 @@ void MetadataNetwork::PacketHandler::subscriberOperation(TrafficNetwork* network SubscriberOperationStore::Operation operation; const bool found = operationId != 0U && network->subscriberOperations().get(operationId, operation); + if (!found && operationId != 0U && network->proxySubscriberOperation(mdNetwork, + peerId, streamId, 0U, operationId, SUBSCRIBER_OPERATION_PROXY_HOP_LIMIT)) { + return; + } response["found"].set(found); response["operationId"].set(operationId); if (found) { diff --git a/tests/BitManipulation_Tests.cpp b/tests/BitManipulation_Tests.cpp index a3c8b5d1..49004882 100644 --- a/tests/BitManipulation_Tests.cpp +++ b/tests/BitManipulation_Tests.cpp @@ -41,6 +41,18 @@ TEST_CASE("BitManipulation integer macros round-trip values", "[common][bitmanip { std::array buffer = {}; + SET_UINT64(0x0123456789ABCDEFULL, buffer.data(), 0U); + uint64_t value64 = GET_UINT64(buffer.data(), 0U); + REQUIRE(value64 == 0x0123456789ABCDEFULL); + REQUIRE(buffer[0U] == 0x01U); + REQUIRE(buffer[1U] == 0x23U); + REQUIRE(buffer[2U] == 0x45U); + REQUIRE(buffer[3U] == 0x67U); + REQUIRE(buffer[4U] == 0x89U); + REQUIRE(buffer[5U] == 0xABU); + REQUIRE(buffer[6U] == 0xCDU); + REQUIRE(buffer[7U] == 0xEFU); + SET_UINT32(0x12345678U, buffer.data(), 0U); uint32_t value32 = GET_UINT32(buffer.data(), 0U); REQUIRE(value32 == 0x12345678U); @@ -61,4 +73,4 @@ TEST_CASE("BitManipulation integer macros round-trip values", "[common][bitmanip REQUIRE(value16 == 0xBEEFU); REQUIRE(buffer[8U] == 0xBEU); REQUIRE(buffer[9U] == 0xEFU); -} \ No newline at end of file +} diff --git a/tests/fne/FNENetwork_Tests.cpp b/tests/fne/FNENetwork_Tests.cpp index a891cd4b..ac32eca9 100644 --- a/tests/fne/FNENetwork_Tests.cpp +++ b/tests/fne/FNENetwork_Tests.cpp @@ -64,7 +64,9 @@ public: ~FNEHarness() { FNETestHooks::clearPeerWriteCapture(traffic); + FNETestHooks::clearPeerPayloadWrite(traffic); FNETestHooks::clearMetadataWriteCapture(metadata); + FNETestHooks::clearSubscriberOperationProxyWrite(traffic); FNETestHooks::clearPeers(traffic); } @@ -179,6 +181,144 @@ TEST_CASE("FNE metadata returns subscriber operation and P25 status results", CHECK(statusResponse["solicited"].get()); } +TEST_CASE("FNE metadata proxies subscriber operation queries and correlates responses", + "[fne][metadata][subscriber-operations][proxy]") +{ + constexpr uint32_t CONSOLE_PEER_ID = 1001U; + constexpr uint64_t OPERATION_ID = 0x0012030405060708ULL; + constexpr uint32_t TARGET_ID = 123456U; + constexpr uint32_t RADIO_PEER_ID = 2001U; + + FNEHarness harness; + network::FNEPeerConnection& console = FNETestHooks::addPeer( + harness.traffic, CONSOLE_PEER_ID, network::NET_STAT_RUNNING, true); + console.peerClass(network::PEER_CONN_CLASS_CONSOLE); + + std::vector proxyRequest; + std::vector consoleResponse; + uint8_t responseFunction = network::NET_FUNC::ILLEGAL; + uint8_t responseSubFunction = network::NET_SUBFUNC::NOP; + FNETestHooks::captureSubscriberOperationProxyWrite(harness.traffic, proxyRequest); + FNETestHooks::captureMetadataWrite(harness.metadata, consoleResponse, + responseFunction, responseSubFunction); + + json::object request = json::object(); + request["operationId"].set(OPERATION_ID); + const std::string requestJson = json::value(request).serialize(); + std::vector requestPayload(11U + requestJson.length(), 0U); + ::memcpy(requestPayload.data() + 11U, requestJson.data(), requestJson.length()); + FNETestHooks::dispatchMetadata(harness.traffic, harness.metadata, + network::NET_FUNC::SUBSCRIBER_OP, network::NET_SUBFUNC::SUBSCRIBER_OP_OPERATION, + CONSOLE_PEER_ID, requestPayload); + + REQUIRE(proxyRequest.size() == 27U); + CHECK(proxyRequest[11U] == 16U); + CHECK(proxyRequest[12U] == 0U); + CHECK(proxyRequest[13U] == 0U); + CHECK(proxyRequest[14U] == 0U); + const uint32_t transactionId = GET_UINT32(proxyRequest.data(), 15U) + CHECK(transactionId != 0U); + const uint32_t operationHigh = GET_UINT32(proxyRequest.data(), 19U) + const uint32_t operationLow = GET_UINT32(proxyRequest.data(), 23U) + CHECK(operationHigh == 0x00120304U); + CHECK(operationLow == 0x05060708U); + CHECK(consoleResponse.empty()); + + std::vector proxyResponse(63U, 0U); + proxyResponse[11U] = 0U; + SET_UINT32(transactionId, proxyResponse.data(), 15U); + SET_UINT32(operationHigh, proxyResponse.data(), 19U); + SET_UINT32(operationLow, proxyResponse.data(), 23U); + proxyResponse[27U] = 1U; + proxyResponse[28U] = static_cast(network::SubscriberOperationStore::Protocol::P25); + proxyResponse[29U] = static_cast(network::SubscriberOperationStore::Kind::STATUS_QUERY); + proxyResponse[30U] = static_cast(network::SubscriberOperationStore::State::SUCCEEDED); + SET_UINT32(TARGET_ID, proxyResponse.data(), 31U); + SET_UINT32(RADIO_PEER_ID, proxyResponse.data(), 35U); + SET_UINT32(0U, proxyResponse.data(), 39U); + SET_UINT32(0x1234U, proxyResponse.data(), 43U); + SET_UINT32(0U, proxyResponse.data(), 47U); + SET_UINT32(1000U, proxyResponse.data(), 51U); + SET_UINT32(0U, proxyResponse.data(), 55U); + SET_UINT32(2000U, proxyResponse.data(), 59U); + + network::PeerNetwork upstream("127.0.0.1", 62041U, 0U, 888888U, + "test-password", true, false, true, true, true, true, true, true, + true, true, false, false); + FNETestHooks::enableReplicaPeer(upstream); + FNETestHooks::deliverSubscriberOperationProxyResponse(harness.traffic, upstream, proxyResponse); + + REQUIRE(consoleResponse.size() > 11U); + CHECK(responseFunction == network::NET_FUNC::SUBSCRIBER_OP); + CHECK(responseSubFunction == network::NET_SUBFUNC::SUBSCRIBER_OP_OPERATION); + json::value responseValue; + REQUIRE(json::parse(responseValue, + std::string(reinterpret_cast(consoleResponse.data() + 11U), + consoleResponse.size() - 11U)).empty()); + REQUIRE(responseValue.is()); + json::object& response = responseValue.get(); + CHECK(response["found"].get()); + CHECK(response["operationId"].get() == OPERATION_ID); + CHECK(response["targetId"].get() == TARGET_ID); + CHECK(response["peerId"].get() == RADIO_PEER_ID); + CHECK(response["resultValue"].get() == 0x1234U); + REQUIRE(response["operations"].is()); + CHECK(response["operations"].get().size() == 1U); +} + +TEST_CASE("FNE metadata answers packed subscriber operation proxy requests", + "[fne][metadata][subscriber-operations][proxy]") +{ + constexpr uint32_t NEIGHBOR_PEER_ID = 3001U; + constexpr uint32_t TRANSACTION_ID = 0x11223344U; + constexpr uint32_t TARGET_ID = 123456U; + + FNEHarness harness; + network::FNEPeerConnection& neighbor = FNETestHooks::addPeer( + harness.traffic, NEIGHBOR_PEER_ID, network::NET_STAT_RUNNING, true); + neighbor.peerClass(network::PEER_CONN_CLASS_NEIGHBOR); + neighbor.isReplica(true); + + const uint64_t operationId = harness.traffic.subscriberOperations().oneShot( + network::SubscriberOperationStore::Protocol::P25, + network::SubscriberOperationStore::Kind::RADIO_CHECK, TARGET_ID, 2001U); + REQUIRE(operationId != 0U); + + std::vector responsePayload; + uint8_t responseFunction = network::NET_FUNC::ILLEGAL; + uint8_t responseSubFunction = network::NET_SUBFUNC::NOP; + FNETestHooks::capturePeerPayloadWrite(harness.traffic, responsePayload, + responseFunction, responseSubFunction); + + std::vector requestPayload(27U, 0U); + requestPayload[11U] = 4U; + SET_UINT32(TRANSACTION_ID, requestPayload.data(), 15U); + SET_UINT32(static_cast(operationId >> 32U), requestPayload.data(), 19U); + SET_UINT32(static_cast(operationId & 0xFFFFFFFFU), requestPayload.data(), 23U); + FNETestHooks::dispatchMetadata(harness.traffic, harness.metadata, + network::NET_FUNC::SUBSCRIBER_OP, + network::NET_SUBFUNC::SUBSCRIBER_OP_PROXY_REQUEST, + NEIGHBOR_PEER_ID, requestPayload); + + REQUIRE(responsePayload.size() == 63U); + CHECK(responseFunction == network::NET_FUNC::SUBSCRIBER_OP); + CHECK(responseSubFunction == network::NET_SUBFUNC::SUBSCRIBER_OP_PROXY_RESPONSE); + CHECK(responsePayload[11U] == 0U); + CHECK(responsePayload[27U] == 1U); + const uint32_t responseTransactionId = GET_UINT32(responsePayload.data(), 15U) + const uint32_t responseTargetId = GET_UINT32(responsePayload.data(), 31U) + CHECK(responseTransactionId == TRANSACTION_ID); + CHECK(responseTargetId == TARGET_ID); + + responsePayload.clear(); + requestPayload.pop_back(); + FNETestHooks::dispatchMetadata(harness.traffic, harness.metadata, + network::NET_FUNC::SUBSCRIBER_OP, + network::NET_SUBFUNC::SUBSCRIBER_OP_PROXY_REQUEST, + NEIGHBOR_PEER_ID, requestPayload); + CHECK(responsePayload.empty()); +} + TEST_CASE("FNE metadata starts subscriber operations before transmission", "[fne][metadata][subscriber-operations]") { diff --git a/tests/fne/FNETestHooks.cpp b/tests/fne/FNETestHooks.cpp index d2458f39..b302e8a5 100644 --- a/tests/fne/FNETestHooks.cpp +++ b/tests/fne/FNETestHooks.cpp @@ -107,6 +107,27 @@ void FNETestHooks::clearPeerWriteCapture(TrafficNetwork& network) network.m_testPeerWriteHandler = nullptr; } +/* Captures complete payloads selected by subsequent peer writes. */ + +void FNETestHooks::capturePeerPayloadWrite(TrafficNetwork& network, + std::vector& payload, uint8_t& function, uint8_t& subFunction) +{ + network.m_testPeerPayloadWriteHandler = [&payload, &function, &subFunction](uint32_t, + FrameQueue::OpcodePair opcode, + const uint8_t* data, uint32_t length) { + function = opcode.first; + subFunction = opcode.second; + payload.assign(data, data + length); + }; +} + +/* Clears the peer payload write capture callback. */ + +void FNETestHooks::clearPeerPayloadWrite(TrafficNetwork& network) +{ + network.m_testPeerPayloadWriteHandler = nullptr; +} + /* Captures the next metadata response payload and opcodes. */ void FNETestHooks::captureMetadataWrite(MetadataNetwork& metadata, std::vector& payload, @@ -127,6 +148,46 @@ void FNETestHooks::clearMetadataWriteCapture(MetadataNetwork& metadata) metadata.m_testPeerMetadataWriteHandler = nullptr; } +/* Captures subscriber operation proxy requests written upstream. */ + +void FNETestHooks::captureSubscriberOperationProxyWrite(TrafficNetwork& network, + std::vector& payload) +{ + network.m_testSubscriberOperationProxyWriteHandler = [&payload](FrameQueue::OpcodePair opcode, + const uint8_t* data, uint32_t length) { + if (opcode.first != NET_FUNC::SUBSCRIBER_OP || + opcode.second != NET_SUBFUNC::SUBSCRIBER_OP_PROXY_REQUEST) { + return false; + } + payload.assign(data, data + length); + return true; + }; +} + +/* Clears the subscriber operation proxy write capture callback. */ + +void FNETestHooks::clearSubscriberOperationProxyWrite(TrafficNetwork& network) +{ + network.m_testSubscriberOperationProxyWriteHandler = nullptr; +} + +/* Marks a peer network as an enabled replica for proxy response tests. */ + +void FNETestHooks::enableReplicaPeer(PeerNetwork& peer) +{ + peer.enable(true); + peer.m_peerReplica = true; +} + +/* Delivers a packed subscriber operation proxy response. */ + +void FNETestHooks::deliverSubscriberOperationProxyResponse(TrafficNetwork& network, + PeerNetwork& peer, const std::vector& payload) +{ + network.processSubscriberOperationProxyResponse(&peer, payload.data(), + static_cast(payload.size()), peer.getPeerId()); +} + /* Queues and plays one synthetic parrot frame through a protocol handler. */ void FNETestHooks::playbackParrotFrame(TrafficNetwork& network, ParrotProtocol protocol, diff --git a/tests/fne/FNETestHooks.h b/tests/fne/FNETestHooks.h index ad2ee650..18eac30a 100644 --- a/tests/fne/FNETestHooks.h +++ b/tests/fne/FNETestHooks.h @@ -136,6 +136,20 @@ public: * @param network The TrafficNetwork instance. */ static void clearPeerWriteCapture(network::TrafficNetwork& network); + /** + * @brief Captures complete payloads selected by subsequent peer writes. + * @param network Traffic network instance. + * @param[out] payload Complete peer payload. + * @param[out] function Function opcode. + * @param[out] subFunction Sub-function opcode. + */ + static void capturePeerPayloadWrite(network::TrafficNetwork& network, + std::vector& payload, uint8_t& function, uint8_t& subFunction); + /** + * @brief Clears the peer payload write capture callback. + * @param network Traffic network instance. + */ + static void clearPeerPayloadWrite(network::TrafficNetwork& network); /** * @brief Captures the next metadata response payload and opcodes. * @param metadata Metadata network instance. @@ -150,6 +164,31 @@ public: * @param metadata Metadata network instance. */ static void clearMetadataWriteCapture(network::MetadataNetwork& metadata); + /** + * @brief Captures subscriber operation proxy requests written upstream. + * @param network Traffic network instance. + * @param[out] payload Complete packed request payload. + */ + static void captureSubscriberOperationProxyWrite(network::TrafficNetwork& network, + std::vector& payload); + /** + * @brief Clears the subscriber operation proxy write capture callback. + * @param network Traffic network instance. + */ + static void clearSubscriberOperationProxyWrite(network::TrafficNetwork& network); + /** + * @brief Marks a peer network as an enabled replica for proxy response tests. + * @param peer Peer network instance. + */ + static void enableReplicaPeer(network::PeerNetwork& peer); + /** + * @brief Delivers a packed subscriber operation proxy response. + * @param network Traffic network instance. + * @param peer Upstream replica peer. + * @param payload Complete packed response payload. + */ + static void deliverSubscriberOperationProxyResponse(network::TrafficNetwork& network, + network::PeerNetwork& peer, const std::vector& payload); /** * @brief Queues and plays one synthetic parrot frame through a protocol handler. * @param network The TrafficNetwork instance.