// SPDX-License-Identifier: GPL-2.0-only
/*
 * Digital Voice Modem - Converged FNE Software
 * GPLv2 Open Source. Use is subject to license terms.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 *  Copyright (C) 2023-2026 Bryan Biedenkapp, N2PLL
 *
 */
#include "fne/Defines.h"
#include "common/nxdn/NXDNDefines.h"
#include "common/nxdn/channel/LICH.h"
#include "common/nxdn/channel/CAC.h"
#include "common/nxdn/channel/FACCH1.h"
#include "common/nxdn/channel/UDCH.h"
#include "common/nxdn/lc/rcch/RCCHFactory.h"
#include "common/nxdn/lc/RTCH.h"
#include "common/nxdn/NXDNUtils.h"
#include "common/nxdn/Sync.h"
#include "common/Clock.h"
#include "common/Log.h"
#include "common/Utils.h"
#include "lookups/AffiliationLookup.h"
#include "network/TrafficNetwork.h"
#include "network/callhandler/TagNXDNData.h"
#include "HostFNE.h"
#include "FNEMain.h"

using namespace system_clock;
using namespace network;
using namespace network::callhandler;
using namespace nxdn;
using namespace nxdn::defines;

#include <cassert>
#include <chrono>

// ---------------------------------------------------------------------------
//  Public Class Members
// ---------------------------------------------------------------------------

/* Initializes a new instance of the TagNXDNData class. */

TagNXDNData::TagNXDNData(TrafficNetwork* network, bool debug) :
    m_network(network),
    m_parrotFrames(),
    m_parrotFramesReady(false),
    m_parrotPlayback(false),
    m_lastParrotPeerId(0U),
    m_lastParrotSrcId(0U),
    m_lastParrotDstId(0U),
    m_status(),
    m_statusPVCall(),
    m_rejectedCallStreams(),
    m_debug(debug)
{
    assert(network != nullptr);
}

/* Finalizes a instance of the TagNXDNData class. */

TagNXDNData::~TagNXDNData() = default;

/* Process a data frame from the network. */

bool TagNXDNData::processFrame(const uint8_t* data, uint32_t len, uint32_t peerId, uint32_t ssrc, uint16_t pktSeq, uint32_t streamId, bool fromUpstream)
{
    hrc::hrc_t pktTime = hrc::now();

    DECLARE_UINT8_ARRAY(buffer, len);
    ::memcpy(buffer, data, len);

    uint8_t messageType = data[4U];

    uint32_t srcId = GET_UINT24(data, 5U);
    uint32_t dstId = GET_UINT24(data, 8U);

    if (messageType == MessageType::RTCH_DCALL_HDR ||
        messageType == MessageType::RTCH_DCALL_DATA) {
        if (m_network->m_disablePacketData)
            return false;
    }

    // perform TGID route rewrites if configured
    routeRewrite(buffer, peerId, messageType, dstId, false);
    dstId = GET_UINT24(buffer, 8U);

    lc::RTCH lc;

    lc.setMessageType(messageType);
    lc.setSrcId((uint16_t)srcId & 0xFFFFU);
    lc.setDstId((uint16_t)dstId & 0xFFFFU);

    bool group = (data[15U] & 0x40U) == 0x40U ? false : true;
    lc.setGroup(group);

    // process raw NXDN data bytes
    UInt8Array frame;
    uint8_t frameLength = buffer[23U];
    if (frameLength <= 24) {
        frame = std::unique_ptr<uint8_t[]>(new uint8_t[frameLength]);
        ::memset(frame.get(), 0x00U, frameLength);
    }
    else {
        frame = std::unique_ptr<uint8_t[]>(new uint8_t[frameLength]);
        ::memset(frame.get(), 0x00U, frameLength);
        ::memcpy(frame.get(), buffer + 24U, frameLength);
    }

    NXDNUtils::scrambler(frame.get() + 2U);

    channel::LICH lich;
    bool valid = lich.decode(frame.get() + 2U);

    std::unique_ptr<lc::RCCH> rcch;
    if (valid) {
        RFChannelType::E rfct = lich.getRFCT();
        FuncChannelType::E fct = lich.getFCT();
        ChOption::E option = lich.getOption();

        if (rfct == RFChannelType::RCCH) {
            rcch = lc::rcch::RCCHFactory::createRCCH(frame.get(), frameLength);
        }
        else if (rfct == RFChannelType::RTCH || rfct == RFChannelType::RDCH) {
            // forward onto the specific processor for final processing and delivery
            switch (fct) {
                case FuncChannelType::USC_UDCH:
                {
                    channel::UDCH udch;
                    bool validUDCH = udch.decode(frame.get() + 2U);
                    if (validUDCH) {
                        // The layer3 data will only be correct if valid is true
                        uint8_t buffer[NXDN_RTCH_LC_LENGTH_BYTES];
                        udch.getData(buffer);

                        lc.decode(buffer, NXDN_UDCH_LENGTH_BITS);
                    }
                }
                break;
                default:
                {
                    if (fct == FuncChannelType::USC_SACCH_NS) {
                        // the SACCH on a non-superblock frame is usually an idle and not interesting apart from the RAN.
                        channel::FACCH1 facch;
                        bool valid = facch.decode(frame.get() + 2U, NXDN_FSW_LENGTH_BITS + NXDN_LICH_LENGTH_BITS + NXDN_SACCH_FEC_LENGTH_BITS);
                        if (!valid)
                            valid = facch.decode(frame.get() + 2U, NXDN_FSW_LENGTH_BITS + NXDN_LICH_LENGTH_BITS + NXDN_SACCH_FEC_LENGTH_BITS + NXDN_FACCH1_FEC_LENGTH_BITS);
                        if (valid) {
                            uint8_t buffer[10U];
                            facch.getData(buffer);

                            lc.decode(buffer, NXDN_FACCH1_FEC_LENGTH_BITS);
                        }
                    } else {
                        channel::FACCH1 facch;
                        bool valid = false;
                        switch (option) {
                        case ChOption::STEAL_FACCH:
                            valid = facch.decode(frame.get() + 2U, NXDN_FSW_LENGTH_BITS + NXDN_LICH_LENGTH_BITS + NXDN_SACCH_FEC_LENGTH_BITS);
                            if (!valid)
                                valid = facch.decode(frame.get() + 2U, NXDN_FSW_LENGTH_BITS + NXDN_LICH_LENGTH_BITS + NXDN_SACCH_FEC_LENGTH_BITS + NXDN_FACCH1_FEC_LENGTH_BITS);
                            break;
                        case ChOption::STEAL_FACCH1_1:
                            valid = facch.decode(frame.get() + 2U, NXDN_FSW_LENGTH_BITS + NXDN_LICH_LENGTH_BITS + NXDN_SACCH_FEC_LENGTH_BITS);
                            break;
                        case ChOption::STEAL_FACCH1_2:
                            valid = facch.decode(frame.get() + 2U, NXDN_FSW_LENGTH_BITS + NXDN_LICH_LENGTH_BITS + NXDN_SACCH_FEC_LENGTH_BITS + NXDN_FACCH1_FEC_LENGTH_BITS);
                            break;
                        default:
                            break;
                        }

                        if (valid) {
                            uint8_t buffer[10U];
                            facch.getData(buffer);

                            lc.decode(buffer, NXDN_FACCH1_FEC_LENGTH_BITS);
                        }
                    }
                }
                break;
            }
        }
    }

    // is the stream valid?
    if (validate(peerId, lc, messageType, streamId)) {
        // is this peer ignored?
        if (!isPeerPermitted(peerId, lc, messageType, streamId, fromUpstream)) {
            return false;
        }

        // specifically only check the following logic for end of call, voice or data frames
        if ((messageType == MessageType::RTCH_TX_REL || messageType == MessageType::RTCH_TX_REL_EX) ||
            (messageType == MessageType::RTCH_VCALL || messageType == MessageType::RTCH_DCALL_HDR ||
             messageType == MessageType::RTCH_DCALL_DATA)) {
            // is this the end of the call stream?
            if (messageType == MessageType::RTCH_TX_REL || messageType == MessageType::RTCH_TX_REL_EX) {
                if (srcId == 0U && dstId == 0U) {
                    LogWarning(LOG_NET, "NXDN, invalid TX_REL, peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, srcId, dstId, streamId, fromUpstream);
                    return false;
                }

                RxStatus status = m_status[dstId];
                uint64_t duration = hrc::diff(pktTime, status.callStartTime);

                auto it = std::find_if(m_status.begin(), m_status.end(), [&](StatusMapPair& x) {
                    if (x.second.dstId == dstId) {
                        if (x.second.activeCall)
                            return true;
                    }
                    return false;
                });
                if (it != m_status.end()) {
                    m_status[dstId].reset();

                    // is this a parrot talkgroup? if so, clear any remaining frames from the buffer
                    lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(dstId);
                    if (tg.config().parrot() && !m_parrotPlayback) {
                        if (m_parrotFrames.size() > 0) {
                            m_parrotFramesReady = true;
                            LogInfoEx(LOG_NET, "NXDN, Parrot Playback will Start, peer = %u, srcId = %u", peerId, srcId);
                            m_network->m_parrotDelayTimer.start();
                        }
                    }

                    // is this a private call?
                    auto it = std::find_if(m_statusPVCall.begin(), m_statusPVCall.end(), [&](StatusMapPair& x) {
                        if (x.second.dstId == dstId) {
                            if (x.second.activeCall)
                                return true;
                        }
                        return false;
                    });
                    if (it != m_statusPVCall.end()) {
                        m_statusPVCall[dstId].reset();

                        m_network->m_globalAff->releaseGrant(dstId);

                        #define PRV_CALL_END_LOG "NXDN, Private Call End, peer = %u, ssrc = %u, srcId = %u, dstId = %u, duration = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, srcId, dstId, duration / 1000, streamId, fromUpstream
                        if (m_network->m_logUpstreamCallStartEnd && fromUpstream)
                            LogInfoEx(LOG_PEER, PRV_CALL_END_LOG);
                        else if (!fromUpstream)
                            LogInfoEx(LOG_MASTER, PRV_CALL_END_LOG);
                    }
                    else {
                        m_network->m_globalAff->releaseGrant(dstId);

                        #define CALL_END_LOG "NXDN, Call End, peer = %u, ssrc = %u, srcId = %u, dstId = %u, duration = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, srcId, dstId, duration / 1000, streamId, fromUpstream
                        if (m_network->m_logUpstreamCallStartEnd && fromUpstream)
                            LogInfoEx(LOG_PEER, CALL_END_LOG);
                        else if (!fromUpstream)
                            LogInfoEx(LOG_MASTER, CALL_END_LOG);
                    }

                    // clear any rejected call streams for this TG
                    m_rejectedCallStreams.lock(false);
                    m_rejectedCallStreams[dstId].clear();
                    m_rejectedCallStreams.unlock();

                    if (!tg.config().parrot()) {
                        m_network->m_totalActiveCalls--;
                        if (m_network->m_totalActiveCalls < 0)
                            m_network->m_totalActiveCalls = 0;
                    }

                    // report call event to InfluxDB
                    if (m_network->m_enableInfluxDB) {
                        influxdb::QueryBuilder()
                            .meas("call_event")
                                .tag("peerId", std::to_string(peerId))
                                .tag("mode", "NXDN")
                                .tag("streamId", std::to_string(streamId))
                                .tag("srcId", std::to_string(srcId))
                                .tag("dstId", std::to_string(dstId))
                                    .field("duration", duration)
                                .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                            .requestAsync(m_network->m_influxServer);
                    }

                    m_network->eraseStreamPktSeq(peerId, streamId);
                }
            }

            // is this a new call stream?
            if ((messageType != MessageType::RTCH_TX_REL && messageType != MessageType::RTCH_TX_REL_EX)) {
                if (srcId == 0U && dstId == 0U) {
                    LogWarning(LOG_NET, "NXDN, invalid call, peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, srcId, dstId, streamId, fromUpstream);
                    return false;
                }

                bool switchOver = (data[14U] & network::NET_CTRL_SWITCH_OVER) == network::NET_CTRL_SWITCH_OVER;

                auto it = std::find_if(m_status.begin(), m_status.end(), [&](StatusMapPair& x) {
                    if (x.second.dstId == dstId) {
                        if (x.second.activeCall)
                            return true;
                    }
                    return false;
                });
                if (it != m_status.end()) {
                    RxStatus status = m_status[dstId];

                    // is the call being taken over?
                    if (status.callTakeover) {
                        LogInfoEx((fromUpstream) ? LOG_PEER : LOG_MASTER, "NXDN, Call Source Switched (Takeover), peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                            peerId, ssrc, srcId, dstId, streamId, status.peerId, status.srcId, status.dstId, status.streamId, fromUpstream);

                        m_status.lock(false);
                        m_status[dstId].streamId = streamId;
                        m_status[dstId].srcId = srcId;
                        m_status[dstId].ssrc = ssrc;
                        m_status[dstId].callTakeover = false; // reset takeover flag
                        m_status.unlock();

                        status = m_status[dstId];
                    }

                    if (streamId != status.streamId) {
                        // perform TG switch over -- this can happen in special conditions where a TG may rapidly switch
                        // from one source to another (primarily from bridge resources)
                        if (switchOver) {
                            m_status.lock(false);
                            m_status[dstId].streamId = streamId;
                            m_status[dstId].ssrc = ssrc;
                            if (status.srcId == 0U)
                                m_status[dstId].srcId = srcId;
                            if (status.srcId != srcId) {
                                LogInfoEx((fromUpstream) ? LOG_PEER : LOG_MASTER, "NXDN, Call Source Switched, peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                                    peerId, ssrc, srcId, dstId, streamId, status.peerId, status.srcId, status.dstId, status.streamId, fromUpstream);
                                m_status[dstId].srcId = srcId;
                            }
                            m_status.unlock();
                        }
                        else {
                            if (status.srcId != 0U && status.srcId != srcId) {
                                bool hasCallPriority = false;

                                // determine if the peer trying to transmit has call priority
                                if (m_network->m_callCollisionTimeout > 0U) {
                                    m_network->m_peers.shared_lock();
                                    for (auto peer : m_network->m_peers) {
                                        if (peerId == peer.first) {
                                            FNEPeerConnection* conn = peer.second;
                                            if (conn != nullptr) {
                                                hasCallPriority = conn->hasCallPriority();
                                                break;
                                            }
                                        }
                                    }
                                    m_network->m_peers.shared_unlock();
                                }

                                // perform standard call collision if the call collision timeout is set *and*
                                //  the peer doesn't have call priority
                                if (m_network->m_callCollisionTimeout > 0U && !hasCallPriority) {
                                    uint64_t lastPktDuration = hrc::diff(hrc::now(), status.lastPacket);
                                    if ((lastPktDuration / 1000) > m_network->m_callCollisionTimeout) {
                                        LogWarning((fromUpstream) ? LOG_PEER : LOG_MASTER, "NXDN, Call Collision, lasted more then %us with no further updates, resetting call source", m_network->m_callCollisionTimeout);

                                        m_status.lock(false);
                                        m_status[dstId].streamId = streamId;
                                        m_status[dstId].srcId = srcId;
                                        m_status[dstId].ssrc = ssrc;
                                        m_status.unlock();

                                        // because the call stream source has reset, clear any rejected call streams for 
                                        // this TG to allow the new source to transmit
                                        m_rejectedCallStreams.lock(false);
                                        m_rejectedCallStreams[dstId].clear();
                                        m_rejectedCallStreams.unlock();
                                    } else {
                                        LogWarning((fromUpstream) ? LOG_PEER : LOG_MASTER, "NXDN, Call Collision, peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                                            peerId, ssrc, srcId, dstId, streamId, status.peerId, status.srcId, status.dstId, status.streamId, fromUpstream);

                                        m_rejectedCallStreams.lock(false);
                                        m_rejectedCallStreams[dstId].push_back(streamId);
                                        m_rejectedCallStreams.unlock();

                                        m_network->m_totalCallCollisions++;

                                        return false;
                                    }
                                } else {
                                    if (hasCallPriority && !m_network->m_disallowInCallCtrl) {
                                        LogInfoEx((fromUpstream) ? LOG_PEER : LOG_MASTER, "NXDN, Call Source Switched (Priority), peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                                            peerId, ssrc, srcId, dstId, streamId, status.peerId, status.srcId, status.dstId, status.streamId, fromUpstream);

                                        // since we're gonna switch over the stream and interrupt the current call inprogress lets try to ICC the transmitting peer
                                        if (m_network->isPeerLocal(m_status[dstId].ssrc))
                                            m_network->writePeerICC(m_status[dstId].peerId, m_status[dstId].streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, dstId, 0U, true, false,
                                                m_status[dstId].ssrc);
                                        else
                                            m_network->writePeerICC(m_status[dstId].peerId, m_status[dstId].streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, dstId, 0U, true, true,
                                                m_status[dstId].ssrc);
                                    }

                                    m_status.lock(false);
                                    m_status[dstId].streamId = streamId;
                                    m_status[dstId].srcId = srcId;
                                    m_status[dstId].ssrc = ssrc;
                                    m_status.unlock();
                                }
                            }
                        }
                    }
                }
                else {
                    // is this a parrot talkgroup? if so, clear any remaining frames from the buffer
                    lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(dstId);
                    if (tg.config().parrot() && !m_parrotPlayback) {
                        m_parrotFramesReady = false;
                        if (m_parrotFrames.size() > 0) {
                            m_parrotFrames.lock(false);
                            for (auto& pkt : m_parrotFrames) {
                                if (pkt.buffer != nullptr) {
                                    delete[] pkt.buffer;
                                }
                            }
                            m_parrotFrames.unlock();
                            m_parrotFrames.clear();
                        }
                    }

                    // this is a new call stream
                    m_status.lock(false);
                    m_status[dstId].callStartTime = pktTime;
                    m_status[dstId].srcId = srcId;
                    m_status[dstId].dstId = dstId;
                    m_status[dstId].streamId = streamId;
                    m_status[dstId].peerId = peerId;
                    m_status[dstId].ssrc = ssrc;
                    m_status[dstId].activeCall = true;
                    m_status.unlock();

                    // clear any rejected call streams for this TG
                    m_rejectedCallStreams.lock(false);
                    m_rejectedCallStreams[dstId].clear();
                    m_rejectedCallStreams.unlock();

                    if (!tg.config().parrot()) {
                        m_network->m_totalCallsProcessed++;
                        m_network->m_totalActiveCalls++;
                    }

                    // is this a private call?
                    if (!group) {
                        m_statusPVCall.lock(false);
                        m_statusPVCall[dstId].callStartTime = pktTime;
                        m_statusPVCall[dstId].srcId = srcId;
                        m_statusPVCall[dstId].dstId = dstId;
                        m_statusPVCall[dstId].streamId = streamId;
                        m_statusPVCall[dstId].peerId = peerId;
                        m_statusPVCall[dstId].ssrc = ssrc;
                        m_statusPVCall[dstId].activeCall = true;

                        // find the SSRC of the peer that registered this unit
                        uint32_t regSSRC = m_network->findPeerUnitReg(srcId);
                        m_statusPVCall[dstId].dstPeerId = regSSRC;
                        m_statusPVCall.unlock();

                        if (!m_network->m_globalAff->isGranted(dstId))
                            m_network->m_globalAff->grantCh(dstId, srcId, ssrc, fne_lookups::GRANT_TIMER_TIMEOUT, false);

                        #define PRV_CALL_START_LOG "NXDN, Private Call Start, peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, srcId, dstId, streamId, fromUpstream
                        if (m_network->m_logUpstreamCallStartEnd && fromUpstream)
                            LogInfoEx(LOG_PEER, PRV_CALL_START_LOG);
                        else if (!fromUpstream)
                            LogInfoEx(LOG_MASTER, PRV_CALL_START_LOG);
                    }
                    else {
                        if (!m_network->m_globalAff->isGranted(dstId))
                            m_network->m_globalAff->grantCh(dstId, srcId, ssrc, fne_lookups::GRANT_TIMER_TIMEOUT, true);

                        #define CALL_START_LOG "NXDN, Call Start, peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, srcId, dstId, streamId, fromUpstream
                        if (m_network->m_logUpstreamCallStartEnd && fromUpstream)
                            LogInfoEx(LOG_PEER, CALL_START_LOG);
                        else if (!fromUpstream)
                            LogInfoEx(LOG_MASTER, CALL_START_LOG);
                    }
                }
            }
        }

        // is this a parrot talkgroup?
        lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(dstId);
        if (tg.config().parrot()) {
            uint8_t *copy = new uint8_t[len];
            ::memcpy(copy, buffer, len);

            ParrotFrame parrotFrame = ParrotFrame();
            parrotFrame.buffer = copy;
            parrotFrame.bufferLen = len;

            parrotFrame.pktSeq = pktSeq;
            parrotFrame.streamId = streamId;
            parrotFrame.peerId = peerId;

            parrotFrame.srcId = srcId;
            parrotFrame.dstId = dstId;

            m_parrotFrames.push_back(parrotFrame);

            if (m_network->m_parrotOnlyOriginating) {
                return true; // end here because parrot calls should never repeat anywhere
            }
        }

        m_status.lock(false);
        m_status[dstId].lastPacket = hrc::now();
        m_status.unlock();

        bool noConnectedPeerRepeat = false;
        bool privateCallInProgress = false;

        // is this a private call in-progress?
        if (m_network->m_restrictPVCallToRegOnly) {
            if (!group) {
                privateCallInProgress = true;
            }

            if (privateCallInProgress) {
                // if we've not determined the destination peer, we have to repeat it everywhere
                if (m_statusPVCall[dstId].dstPeerId == 0U) {
                    noConnectedPeerRepeat = false;
                    privateCallInProgress = false; // trick the system to repeat everywhere
                } else {
                    // if this is a private call, check if the destination peer is one directly connected to us, if not
                    // flag the call so it only repeats to neighbor FNE peers
                    if (m_network->m_peers.size() > 0U && !noConnectedPeerRepeat) {
                        noConnectedPeerRepeat = true;
                        for (auto peer : m_network->m_peers) {
                            if (peerId != peer.first) {
                                FNEPeerConnection* conn = peer.second;
                                if (conn != nullptr) {
                                    if (conn->peerClass() == PEER_CONN_CLASS_NEIGHBOR) {
                                        continue;
                                    }
                                }

                                if (m_statusPVCall[dstId].dstPeerId == peer.first) {
                                    noConnectedPeerRepeat = false;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        /*
        ** MASTER TRAFFIC
        */

        // repeat traffic to nodes peered to us as master
        if (m_network->m_peers.size() > 0U && !noConnectedPeerRepeat) {
            uint32_t i = 0U;
            udp::BufferQueue queue = udp::BufferQueue();

            m_network->m_peers.shared_lock();
            for (auto peer : m_network->m_peers) {
                if (peer.second == nullptr)
                    continue;
                if (peerId != peer.first) {
                    FNEPeerConnection* conn = peer.second;
                    if (ssrc == peer.first) {
                        // skip the peer if it is the source peer
                        continue;
                    }

                    if (m_network->m_restrictPVCallToRegOnly) {
                        // is this peer an upstream neighbor peer?
                        bool neighbor = false;
                        if (conn != nullptr) {
                            neighbor = conn->peerClass() == PEER_CONN_CLASS_NEIGHBOR;
                        }

                        // is this a private call?
                        if (!group && !neighbor) {
                            // is this a private call? if so only repeat to the peer that registered the unit
                            auto it = std::find_if(m_statusPVCall.begin(), m_statusPVCall.end(), [&](StatusMapPair& x) {
                                if (x.second.dstId == dstId) {
                                    if (x.second.activeCall)
                                        return true;
                                }
                                return false;
                            });
                            if (it != m_statusPVCall.end()) {
                                if (peer.first != m_statusPVCall[dstId].dstPeerId) {
                                    continue;
                                }
                            }
                        }
                    }

                    // is this peer ignored?
                    if (!isPeerPermitted(peer.first, lc, messageType, streamId)) {
                        continue;
                    }

                    // every MAX_QUEUED_PEER_MSGS peers flush the queue
                    if (i % MAX_QUEUED_PEER_MSGS == 0U) {
                        m_network->m_frameQueue->flushQueue(&queue);
                    }

                    DECLARE_UINT8_ARRAY(outboundPeerBuffer, len);
                    ::memcpy(outboundPeerBuffer, buffer, len);

                    // perform TGID route rewrites if configured
                    routeRewrite(outboundPeerBuffer, peer.first, messageType, dstId);

                    m_network->writePeerQueue(&queue, peer.first, ssrc, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN }, outboundPeerBuffer, len, pktSeq, streamId);
                    if (m_network->m_debug) {
                        LogDebugEx(LOG_NXDN, "TagNXDNData::processFrame()", "Master, ssrc = %u, srcPeer = %u,  dstPeer = %u, messageType = $%02X, srcId = %u, dstId = %u, len = %u, pktSeq = %u, streamId = %u, fromUpstream = %u", 
                            ssrc, peerId, peer.first, messageType, srcId, dstId, len, pktSeq, streamId, fromUpstream);
                    }

                    i++;
                }
            }
            m_network->m_frameQueue->flushQueue(&queue);
            m_network->m_peers.shared_unlock();
        }

        // if this is a private call, and we have already repeated to the connected peer that registered
        // the unit, don't repeat to any neighbor FNE peers
        if (privateCallInProgress && !noConnectedPeerRepeat) {
            return true;
        }

        /*
        ** PEER TRAFFIC (e.g. upstream networks this FNE is peered to)
        */

        // repeat traffic to master nodes we have connected to as a peer
        if (m_network->m_host->m_peerNetworks.size() > 0U && !tg.config().parrot()) {
            for (auto peer : m_network->m_host->m_peerNetworks) {
                uint32_t dstPeerId = peer.second->getPeerId();

                // don't try to repeat traffic to the source peer...if this traffic
                // is coming from a neighbor FNE peer
                if (dstPeerId != peerId) {
                    if (ssrc == dstPeerId) {
                        // skip the peer if it is the source peer
                        continue;
                    }

                    // skip peer if it isn't enabled
                    if (!peer.second->isEnabled()) {
                        continue;
                    }

                    // is this peer ignored?
                    if (!isPeerPermitted(dstPeerId, lc, messageType, streamId, true)) {
                        continue;
                    }

                    DECLARE_UINT8_ARRAY(outboundPeerBuffer, len);
                    ::memcpy(outboundPeerBuffer, buffer, len);

                    // perform TGID route rewrites if configured
                    routeRewrite(outboundPeerBuffer, dstPeerId, messageType, dstId);

                    // are we a replica peer?
                    if (peer.second->isReplica())
                        peer.second->writeMaster({ NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN }, outboundPeerBuffer, len, pktSeq, streamId, false, 0U, ssrc);
                    else
                        peer.second->writeMaster({ NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN }, outboundPeerBuffer, len, pktSeq, streamId);
                    if (m_network->m_debug) {
                        LogDebugEx(LOG_NXDN, "TagNXDNData::processFrame()", "Peers, ssrc = %u, srcPeer = %u, dstPeer = %u, messageType = $%02X, srcId = %u, dstId = %u, len = %u, pktSeq = %u, streamId = %u, fromUpstream = %u", 
                            ssrc, peerId, dstPeerId, messageType, srcId, dstId, len, pktSeq, streamId, fromUpstream);
                    }
                }
            }
        }

        return true;
    }

    return false;
}

/* Process a grant request frame from the network. */

bool TagNXDNData::processGrantReq(uint32_t srcId, uint32_t dstId, bool unitToUnit, uint32_t peerId, uint16_t pktSeq, uint32_t streamId)
{
    // if we have an Rx status for the destination deny the grant
    auto it = std::find_if(m_status.begin(), m_status.end(), [&](StatusMapPair& x) {
        if (x.second.dstId == dstId) {
            if (x.second.activeCall)
                return true;
        }
        return false;
    });
    if (it != m_status.end()) {
        return false;
    }

    // is the source ID a blacklisted ID?
    lookups::RadioId rid = m_network->m_ridLookup->find(srcId);
    if (!rid.radioDefault()) {
        if (!rid.radioEnabled()) {
            return false;
        }
    }

    lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(dstId);

    // check TGID validity
    if (tg.isInvalid()) {
        return false;
    }

    if (!tg.config().active()) {
        return false;
    }

    // repeat traffic to the connected peers
    if (m_network->m_peers.size() > 0U) {
        for (auto peer : m_network->m_peers) {
            if (peerId != peer.first) {
                write_Message_Grant(peer.first, srcId, dstId, 4U, !unitToUnit);
            }
        }
    }

    if (!m_network->m_globalAff->isGranted(dstId)) {
        if (m_network->m_globalAff->grantCh(dstId, srcId, peerId, fne_lookups::GRANT_TIMER_TIMEOUT, !unitToUnit)) {
            return true;
        }
    }

    return false;
}

/* Helper to trigger a call takeover from a In-Call control event. */

void TagNXDNData::triggerCallTakeover(uint32_t dstId)
{
    auto it = std::find_if(m_status.begin(), m_status.end(), [&](StatusMapPair& x) {
        if (x.second.dstId == dstId) {
            if (x.second.activeCall)
                return true;
        }
        return false;
    });
    if (it != m_status.end()) {
        m_status.lock(false);
        m_status[dstId].callTakeover = true;
        m_status.unlock();
    }
}

/* Helper to playback a parrot frame to the network. */

void TagNXDNData::playbackParrot()
{
    if (m_parrotFrames.size() == 0) {
        m_parrotFramesReady = false;
        return;
    }

    m_parrotPlayback = true;

    auto& pkt = m_parrotFrames[0];
    m_parrotFrames.lock();
    if (pkt.buffer != nullptr) {
        // has the override source ID been set?
        if (m_network->m_parrotOverrideSrcId > 0U) {
            pkt.srcId = m_network->m_parrotOverrideSrcId;

            // override source ID
            SET_UINT24(m_network->m_parrotOverrideSrcId, pkt.buffer, 5U);
        }

        m_lastParrotPeerId = pkt.peerId;
        m_lastParrotSrcId = pkt.srcId;
        m_lastParrotDstId = pkt.dstId;

        if (m_network->m_parrotOnlyOriginating) {
            m_network->writePeer(pkt.peerId, pkt.peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN }, pkt.buffer, pkt.bufferLen, pkt.pktSeq, pkt.streamId);
            if (m_network->m_debug) {
                LogDebugEx(LOG_NXDN, "TagNXDNData::playbackParrot()", "Parrot, dstPeer = %u, len = %u, pktSeq = %u, streamId = %u", 
                    pkt.peerId, pkt.bufferLen, pkt.pktSeq, pkt.streamId);
            }
        }
        else {
            // repeat traffic to the connected peers
            uint32_t i = 0U;
            udp::BufferQueue queue = udp::BufferQueue();

            m_network->m_peers.shared_lock();
            for (auto peer : m_network->m_peers) {
                // every MAX_QUEUED_PEER_MSGS peers flush the queue
                if (i % MAX_QUEUED_PEER_MSGS == 0U) {
                    m_network->m_frameQueue->flushQueue(&queue);
                }

                m_network->writePeerQueue(&queue, peer.first, pkt.peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN }, pkt.buffer, pkt.bufferLen, pkt.pktSeq, pkt.streamId);
                if (m_network->m_debug) {
                    LogDebugEx(LOG_NXDN, "TagNXDNData::playbackParrot()", "Parrot, dstPeer = %u, len = %u, pktSeq = %u, streamId = %u", 
                        peer.first, pkt.bufferLen, pkt.pktSeq, pkt.streamId);
                }

                i++;
            }
            m_network->m_frameQueue->flushQueue(&queue);
            m_network->m_peers.shared_unlock();
        }

        delete[] pkt.buffer;
    }
    Thread::sleep(60);
    m_parrotFrames.unlock();
    m_parrotFrames.pop_front();
}

// ---------------------------------------------------------------------------
//  Private Class Members
// ---------------------------------------------------------------------------

/* Helper to route rewrite the network data buffer. */

void TagNXDNData::routeRewrite(uint8_t* buffer, uint32_t peerId, uint8_t messageType, uint32_t dstId, bool outbound)
{
    uint32_t rewriteDstId = dstId;

    // does the data require route writing?
    if (peerRewrite(peerId, rewriteDstId, outbound)) {
        // rewrite destination TGID in the frame
        SET_UINT24(rewriteDstId, buffer, 8U);
    }
}

/* Helper to route rewrite destination ID. */

bool TagNXDNData::peerRewrite(uint32_t peerId, uint32_t& dstId, bool outbound)
{
    lookups::TalkgroupRuleGroupVoice tg;
    if (outbound) {
        tg = m_network->m_tidLookup->find(dstId);
    }
    else {
        tg = m_network->m_tidLookup->findByRewrite(peerId, dstId);
    }

    bool rewrote = false;
    if (tg.config().rewriteSize() > 0) {
        std::vector<lookups::TalkgroupRuleRewrite> rewrites = tg.config().rewrite();
        for (auto entry : rewrites) {
            if (entry.peerId() == peerId) {
                if (outbound) {
                    dstId = entry.tgId();
                }
                else {
                    dstId = tg.source().tgId();
                }
                rewrote = true;
                break;
            }
        }
    }

    return rewrote;
}

/* Helper to determine if the peer is permitted for traffic. */

bool TagNXDNData::isPeerPermitted(uint32_t peerId, lc::RTCH& lc, uint8_t messageType, uint32_t streamId, bool fromUpstream)
{
    // promiscuous hub mode performs no ACL checking and will pass all traffic
    if (g_promiscuousHub)
        return true;

    if (!lc.getGroup()) {
        if (m_network->m_disallowU2U)
            return false;
        if (!m_network->checkU2UDroppedPeer(peerId))
            return true;
        return false;
    }

    FNEPeerConnection* connection = nullptr; // bryanb: this is a possible null ref concurrency issue
                                             //     it is possible if the timing is just right to get a valid 
                                             //     connection back initially, and then for it to be deleted
    if (peerId > 0 && (m_network->m_peers.find(peerId) != m_network->m_peers.end())) {
        connection = m_network->m_peers[peerId];
    }

    if (connection != nullptr) {
        // is this peer a replica peer?
        if (connection->isReplica()) {
            return true; // replica peers are *always* allowed to receive traffic and no other rules may filter
                         // these peers
        }

        // is this peer a SysView peer?
        if (connection->peerClass() == PEER_CONN_CLASS_SYSVIEW) {
            return true; // SysView peers are *always* allowed to receive traffic and no other rules may filter
                         // these peers
        }
    }

    // is this a group call?
    if (lc.getGroup()) {
        lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(lc.getDstId());

        std::vector<uint32_t> inclusion = tg.config().inclusion();
        std::vector<uint32_t> exclusion = tg.config().exclusion();

        // peer inclusion lists take priority over exclusion lists
        if (inclusion.size() > 0) {
            auto it = std::find(inclusion.begin(), inclusion.end(), peerId);
            if (it == inclusion.end()) {
                return false;
            }
        }
        else {
            if (exclusion.size() > 0) {
                auto it = std::find(exclusion.begin(), exclusion.end(), peerId);
                if (it != exclusion.end()) {
                    return false;
                }
            }
        }

        // peer always send list takes priority over any following affiliation rules
        std::vector<uint32_t> alwaysSend = tg.config().alwaysSend();
        if (alwaysSend.size() > 0) {
            auto it = std::find(alwaysSend.begin(), alwaysSend.end(), peerId);
            if (it != alwaysSend.end()) {
                return true; // skip any following checks and always send traffic
            }
        }

        // is this peer a conventional peer?
        if (m_network->m_allowConvSiteAffOverride) {
            if (connection != nullptr) {
                if (connection->peerClass() == PEER_CONN_CLASS_STANDARD && connection->isConventional()) {
                    fromUpstream = true; // we'll just set the fromUpstream flag to disable the affiliation check
                                         // for conventional peers
                }
            }
        }

        // is this peer a console peer?
        if (connection != nullptr) {
            if (connection->peerClass() == PEER_CONN_CLASS_CONSOLE) {
                fromUpstream = true; // we'll just set the fromUpstream flag to disable the affiliation check
                                     // for console peers
            }
        }

        // is this a TG that requires affiliations to repeat?
        // NOTE: neighbor FNE peers *always* repeat traffic regardless of affiliation
        if (tg.config().affiliated() && !fromUpstream) {
            uint32_t lookupPeerId = peerId;
            if (connection != nullptr) {
                if (connection->ccPeerId() > 0U)
                    lookupPeerId = connection->ccPeerId();
            }

            // check the affiliations for this peer to see if we can repeat traffic
            std::shared_ptr<fne_lookups::AffiliationLookup> aff = m_network->getPeerAffiliations(lookupPeerId);
            if (aff == nullptr) {
                std::string peerIdentity = m_network->resolvePeerIdentity(lookupPeerId);
                //LogError(LOG_NET, "PEER %u (%s) has an invalid affiliations lookup? This shouldn't happen BUGBUG.", lookupPeerId, peerIdentity.c_str());
                return false; // this will cause no traffic to pass for this peer now...I'm not sure this is good behavior
            }
            else {
                if (!aff->hasGroupAff(lc.getDstId())) {
                    return false;
                }
            }
        }
    }

    return true;
}

/* Helper to validate the DMR call stream. */

bool TagNXDNData::validate(uint32_t peerId, lc::RTCH& lc, uint8_t messageType, uint32_t streamId)
{
    // promiscuous hub mode performs no ACL checking and will pass all traffic
    if (g_promiscuousHub)
        return true;

    // is the source ID a blacklisted ID?
    bool rejectUnknownBadCall = false;
    lookups::RadioId rid = m_network->m_ridLookup->find(lc.getSrcId());
    if (!rid.radioDefault()) {
        if (!rid.radioEnabled()) {
            // report error event to InfluxDB
            if (m_network->m_enableInfluxDB) {
                influxdb::QueryBuilder()
                    .meas("call_error_event")
                        .tag("peerId", std::to_string(peerId))
                        .tag("streamId", std::to_string(streamId))
                        .tag("srcId", std::to_string(lc.getSrcId()))
                        .tag("dstId", std::to_string(lc.getDstId()))
                            .field("message", std::string(INFLUXDB_ERRSTR_DISABLED_SRC_RID))
                        .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                    .requestAsync(m_network->m_influxServer);
            }

            if (m_network->m_logDenials)
                LogError(LOG_NXDN, INFLUXDB_ERRSTR_DISABLED_SRC_RID ", peer = %u, srcId = %u, dstId = %u", peerId, lc.getSrcId(), lc.getDstId());

            // report In-Call Control to the peer sending traffic
            m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId());
            return false;
        }
    }
    else {
        // if this is a default radio -- and we are rejecting undefined radios
        // report call error
        if (m_network->m_rejectUnknownRID) {
            rejectUnknownBadCall = true;
        }
    }

    // always validate a terminator if the source is valid
    if (messageType == MessageType::RTCH_TX_REL || messageType == MessageType::RTCH_TX_REL_EX)
        return true;

    // is the call stream rejected?
    m_rejectedCallStreams.lock(false);
    std::vector<uint32_t> rejectedStreams = m_rejectedCallStreams[lc.getDstId()];
    if (std::find(rejectedStreams.begin(), rejectedStreams.end(), streamId) != rejectedStreams.end()) {
        // report error event to InfluxDB
        if (m_network->m_enableInfluxDB) {
            influxdb::QueryBuilder()
                .meas("call_error_event")
                    .tag("peerId", std::to_string(peerId))
                    .tag("streamId", std::to_string(streamId))
                    .tag("srcId", std::to_string(lc.getSrcId()))
                    .tag("dstId", std::to_string(lc.getDstId()))
                        .field("message", std::string(INFLUXDB_ERRSTR_CALL_NOT_PERMITTED))
                    .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                .requestAsync(m_network->m_influxServer);
        }

        if (m_network->m_logDenials)
            LogError(LOG_NXDN, INFLUXDB_ERRSTR_CALL_NOT_PERMITTED ", peer = %u, srcId = %u, dstId = %u", peerId, lc.getSrcId(), lc.getDstId());

        m_rejectedCallStreams.unlock();

        // report In-Call Control to the peer sending traffic
        m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId());
        return false;
    }
    m_rejectedCallStreams.unlock();

    // is this a private call?
    if (!lc.getGroup()) {
        // is the destination ID a blacklisted ID?
        lookups::RadioId rid = m_network->m_ridLookup->find(lc.getDstId());
        if (!rid.radioDefault()) {
            if (!rid.radioEnabled()) {
                // report error event to InfluxDB
                if (m_network->m_enableInfluxDB) {
                    influxdb::QueryBuilder()
                        .meas("call_error_event")
                            .tag("peerId", std::to_string(peerId))
                            .tag("streamId", std::to_string(streamId))
                            .tag("srcId", std::to_string(lc.getSrcId()))
                            .tag("dstId", std::to_string(lc.getDstId()))
                                .field("message", std::string(INFLUXDB_ERRSTR_DISABLED_DST_RID))
                            .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                        .requestAsync(m_network->m_influxServer);
                }

                if (m_network->m_logDenials)
                    LogError(LOG_NXDN, INFLUXDB_ERRSTR_DISABLED_DST_RID ", peer = %u, srcId = %u, dstId = %u", peerId, lc.getSrcId(), lc.getDstId());

                // report In-Call Control to the peer sending traffic
                m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId());
                return false;
            }
        }
        else {
            // if this is a default radio -- and we are rejecting undefined radios
            // report call error
            if (m_network->m_rejectUnknownRID) {
                // report error event to InfluxDB
                if (m_network->m_enableInfluxDB) {
                    influxdb::QueryBuilder()
                        .meas("call_error_event")
                            .tag("peerId", std::to_string(peerId))
                            .tag("streamId", std::to_string(streamId))
                            .tag("srcId", std::to_string(lc.getSrcId()))
                            .tag("dstId", std::to_string(lc.getDstId()))
                                .field("message", std::string(INFLUXDB_ERRSTR_ILLEGAL_RID_ACCESS))
                            .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                        .requestAsync(m_network->m_influxServer);
                }

                if (m_network->m_logDenials)
                    LogWarning(LOG_NXDN, INFLUXDB_ERRSTR_ILLEGAL_RID_ACCESS ", srcId = %u, dstId = %u", lc.getSrcId(), lc.getDstId());

                // report In-Call Control to the peer sending traffic
                m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId());
                return false;
            }
        }

        return true;
    }

    lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(lc.getDstId());

    // check TGID validity
    if (tg.isInvalid()) {
        // report error event to InfluxDB
        if (m_network->m_enableInfluxDB) {
            influxdb::QueryBuilder()
                .meas("call_error_event")
                    .tag("peerId", std::to_string(peerId))
                    .tag("streamId", std::to_string(streamId))
                    .tag("srcId", std::to_string(lc.getSrcId()))
                    .tag("dstId", std::to_string(lc.getDstId()))
                        .field("message", std::string(INFLUXDB_ERRSTR_INV_TALKGROUP))
                    .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                .requestAsync(m_network->m_influxServer);
        }

        if (m_network->m_logDenials)
            LogError(LOG_NXDN, INFLUXDB_ERRSTR_INV_TALKGROUP ", peer = %u, srcId = %u, dstId = %u", peerId, lc.getSrcId(), lc.getDstId());

        // report In-Call Control to the peer sending traffic
        m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId());
        return false;
    }
    else {
        // "selectable" strapping doesn't care about encryption state -- anything else does
        if (tg.config().strapping() != lookups::TG_STRAPPING_SELECTABLE) {
            // is the TG strapped but the LC is reporting unencrypted?
            if (tg.config().strapping() == lookups::TG_STRAPPING_STRAPPED) {
                if (lc.getAlgId() == NXDDEF::CIPHER_TYPE_NONE) {
                    // report error event to InfluxDB
                    if (m_network->m_enableInfluxDB) {
                        influxdb::QueryBuilder()
                            .meas("call_error_event")
                                .tag("peerId", std::to_string(peerId))
                                .tag("streamId", std::to_string(streamId))
                                .tag("srcId", std::to_string(lc.getSrcId()))
                                .tag("dstId", std::to_string(lc.getDstId()))
                                    .field("message", std::string(INFLUXDB_ERRSTR_ENC_TALKGROUP_CLR))
                                .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                            .requestAsync(m_network->m_influxServer);
                    }

                    if (m_network->m_logDenials)
                        LogError(LOG_NXDN, INFLUXDB_ERRSTR_ENC_TALKGROUP_CLR ", peer = %u, srcId = %u, dstId = %u", peerId, lc.getSrcId(), lc.getDstId());

                    // report In-Call Control to the peer sending traffic
                    m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId(), 0U, true);
                    return false;
                }
            }

            // is the TG unstrapped but the LC is reporting encrypted?
            if (tg.config().strapping() == lookups::TG_STRAPPING_CLEAR) {
                if (lc.getAlgId() != NXDDEF::CIPHER_TYPE_NONE) {
                    // report error event to InfluxDB
                    if (m_network->m_enableInfluxDB) {
                        influxdb::QueryBuilder()
                            .meas("call_error_event")
                                .tag("peerId", std::to_string(peerId))
                                .tag("streamId", std::to_string(streamId))
                                .tag("srcId", std::to_string(lc.getSrcId()))
                                .tag("dstId", std::to_string(lc.getDstId()))
                                    .field("message", std::string(INFLUXDB_ERRSTR_CLR_TALKGROUP_ENC))
                                .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                            .requestAsync(m_network->m_influxServer);
                    }

                    if (m_network->m_logDenials)
                        LogError(LOG_NXDN, INFLUXDB_ERRSTR_CLR_TALKGROUP_ENC ", peer = %u, srcId = %u, dstId = %u", peerId, lc.getSrcId(), lc.getDstId());

                    // report In-Call Control to the peer sending traffic
                    m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId(), 0U, true);
                    return false;
                }
            }
        }
    }

    // peer always send list takes priority over any following affiliation rules
    bool isAlwaysPeer = false;
    std::vector<uint32_t> alwaysSend = tg.config().alwaysSend();
    if (alwaysSend.size() > 0) {
        auto it = std::find(alwaysSend.begin(), alwaysSend.end(), peerId);
        if (it != alwaysSend.end()) {
            isAlwaysPeer = true; // skip any following checks and always send traffic
            rejectUnknownBadCall = false;
        }
    }

    // fail call if the reject flag is set
    if (rejectUnknownBadCall) {
        // report error event to InfluxDB
        if (m_network->m_enableInfluxDB) {
            influxdb::QueryBuilder()
                .meas("call_error_event")
                    .tag("peerId", std::to_string(peerId))
                    .tag("streamId", std::to_string(streamId))
                    .tag("srcId", std::to_string(lc.getSrcId()))
                    .tag("dstId", std::to_string(lc.getDstId()))
                        .field("message", std::string(INFLUXDB_ERRSTR_ILLEGAL_RID_ACCESS))
                    .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                .requestAsync(m_network->m_influxServer);
        }

        if (m_network->m_logDenials)
            LogWarning(LOG_NXDN, INFLUXDB_ERRSTR_ILLEGAL_RID_ACCESS ", srcId = %u, dstId = %u", lc.getSrcId(), lc.getDstId());

        // report In-Call Control to the peer sending traffic
        m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId());
        return false;
    }

    // is the TGID active?
    if (!tg.config().active()) {
        // report error event to InfluxDB
        if (m_network->m_enableInfluxDB) {
            influxdb::QueryBuilder()
                .meas("call_error_event")
                    .tag("peerId", std::to_string(peerId))
                    .tag("streamId", std::to_string(streamId))
                    .tag("srcId", std::to_string(lc.getSrcId()))
                    .tag("dstId", std::to_string(lc.getDstId()))
                        .field("message", INFLUXDB_ERRSTR_DISABLED_TALKGROUP)
                    .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                .requestAsync(m_network->m_influxServer);
        }

        if (m_network->m_logDenials)
            LogError(LOG_NXDN, INFLUXDB_ERRSTR_DISABLED_TALKGROUP ", peer = %u, srcId = %u, dstId = %u", peerId, lc.getSrcId(), lc.getDstId());

        // report In-Call Control to the peer sending traffic
        m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId());
        return false;
    }

    // always peers can violate the rules...hurray
    if (!isAlwaysPeer) {
        // does the TGID have a permitted RID list?
        if (tg.config().permittedRIDs().size() > 0) {
            // does the transmitting RID have permission?
            std::vector<uint32_t> permittedRIDs = tg.config().permittedRIDs();
            if (std::find(permittedRIDs.begin(), permittedRIDs.end(), lc.getSrcId()) == permittedRIDs.end()) {
                // report error event to InfluxDB
                if (m_network->m_enableInfluxDB) {
                    influxdb::QueryBuilder()
                        .meas("call_error_event")
                            .tag("peerId", std::to_string(peerId))
                            .tag("streamId", std::to_string(streamId))
                            .tag("srcId", std::to_string(lc.getSrcId()))
                            .tag("dstId", std::to_string(lc.getDstId()))
                                .field("message", std::string(INFLUXDB_ERRSTR_RID_NOT_PERMITTED))
                            .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                        .requestAsync(m_network->m_influxServer);
                }

                if (m_network->m_logDenials)
                    LogError(LOG_NXDN, INFLUXDB_ERRSTR_RID_NOT_PERMITTED ", peer = %u, srcId = %u, dstId = %u", peerId, lc.getSrcId(), lc.getDstId());

                // report In-Call Control to the peer sending traffic
                m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN, NET_ICC::REJECT_TRAFFIC, lc.getDstId());
                return false;
            }
        }
    }

    return true;
}

/* Helper to write a grant packet. */

bool TagNXDNData::write_Message_Grant(uint32_t peerId, uint32_t srcId, uint32_t dstId, uint8_t serviceOptions, bool grp)
{
    bool emergency = ((serviceOptions & 0xFFU) & 0x80U) == 0x80U;           // Emergency Flag
    bool encryption = ((serviceOptions & 0xFFU) & 0x40U) == 0x40U;          // Encryption Flag
    uint8_t priority = ((serviceOptions & 0xFFU) & 0x07U);                  // Priority

    std::unique_ptr<lc::rcch::MESSAGE_TYPE_VCALL_CONN> rcch = std::make_unique<lc::rcch::MESSAGE_TYPE_VCALL_CONN>();

    // check the affiliations for this peer to see if we can grant traffic
    std::shared_ptr<fne_lookups::AffiliationLookup> aff = m_network->getPeerAffiliations(peerId);
    if (aff == nullptr) {
        std::string peerIdentity = m_network->resolvePeerIdentity(peerId);
        LogError(LOG_MASTER, "PEER %u (%s) has an invalid affiliations lookup? This shouldn't happen BUGBUG.", peerId, peerIdentity.c_str());
        return false; // this will cause no traffic to pass for this peer now...I'm not sure this is good behavior
    }
    else {
        if (!aff->hasGroupAff(dstId)) {
            return false;
        }
    }

    rcch->setMessageType(MessageType::RTCH_VCALL);
    rcch->setGrpVchNo(0U);
    rcch->setGroup(grp);
    rcch->setSrcId(srcId);
    rcch->setDstId(dstId);

    rcch->setEmergency(emergency);
    rcch->setEncrypted(encryption);
    rcch->setPriority(priority);

    if (m_network->m_verbose) {
        LogInfoEx(LOG_NXDN, "%s, emerg = %u, encrypt = %u, prio = %u, chNo = %u, srcId = %u, dstId = %u, peerId = %u",
            rcch->toString().c_str(), rcch->getEmergency(), rcch->getEncrypted(), rcch->getPriority(), rcch->getGrpVchNo(), rcch->getSrcId(), rcch->getDstId(), peerId);
    }

    write_Message(peerId, rcch.get());
    return true;
}

/* Helper to write a deny packet. */

void TagNXDNData::write_Message_Deny(uint32_t peerId, uint32_t srcId, uint32_t dstId, uint8_t reason, uint8_t service)
{
    std::unique_ptr<lc::RCCH> rcch = nullptr;

    switch (service) {
    case MessageType::RTCH_VCALL:
        rcch = std::make_unique<lc::rcch::MESSAGE_TYPE_VCALL_CONN>();
        rcch->setMessageType(MessageType::RTCH_VCALL);
    default:
        return;
    }

    rcch->setCauseResponse(reason);
    rcch->setSrcId(srcId);
    rcch->setDstId(dstId);

    if (m_network->m_verbose) {
        LogInfoEx(LOG_NXDN, "MSG_DENIAL (Message Denial), reason = $%02X (%s), service = $%02X, srcId = %u, dstId = %u",
            reason, NXDNUtils::causeToString(reason).c_str(), service, srcId, dstId);
    }

    write_Message(peerId, rcch.get());
}

/* Helper to write a network RCCH. */

void TagNXDNData::write_Message(uint32_t peerId, lc::RCCH* rcch)
{
    uint8_t data[NXDN_FRAME_LENGTH_BYTES + 2U];
    ::memset(data + 2U, 0x00U, NXDN_FRAME_LENGTH_BYTES);

    Sync::addNXDNSync(data + 2U);

    // generate the LICH
    channel::LICH lich;
    lich.setRFCT(RFChannelType::RCCH);
    lich.setFCT(FuncChannelType::CAC_OUTBOUND);
    lich.setOption(ChOption::DATA_COMMON);
    lich.setOutbound(true);
    lich.encode(data + 2U);

    uint8_t buffer[NXDN_RCCH_LC_LENGTH_BYTES];
    ::memset(buffer, 0x00U, NXDN_RCCH_LC_LENGTH_BYTES);

    rcch->encode(buffer, NXDN_RCCH_LC_LENGTH_BITS);

    // generate the CAC
    channel::CAC cac;
    cac.setRAN(0U);
    cac.setStructure(ChStructure::SR_RCCH_SINGLE);
    cac.setData(buffer);
    cac.encode(data + 2U);

    NXDNUtils::scrambler(data + 2U);
    NXDNUtils::addPostBits(data + 2U);

    lc::RTCH lc = lc::RTCH();
    lc.setMessageType(rcch->getMessageType());
    lc.setSrcId(rcch->getSrcId());
    lc.setDstId(rcch->getDstId());

    uint32_t messageLength = 0U;
    UInt8Array message = m_network->createNXDN_Message(messageLength, lc, data, NXDN_FRAME_LENGTH_BYTES + 2U);
    if (message == nullptr) {
        return;
    }

    uint32_t streamId = m_network->createStreamId();
    m_network->writePeer(peerId, m_network->m_peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_NXDN }, message.get(), messageLength, RTP_END_OF_CALL_SEQ, streamId);
}
