// 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/p25/lc/tsbk/TSBKFactory.h"
#include "common/p25/lc/tdulc/TDULCFactory.h"
#include "common/p25/Sync.h"
#include "common/Clock.h"
#include "common/Log.h"
#include "common/Thread.h"
#include "common/Utils.h"
#include "lookups/AffiliationLookup.h"
#include "network/TrafficNetwork.h"
#include "network/callhandler/TagP25Data.h"
#include "HostFNE.h"
#include "FNEMain.h"

using namespace system_clock;
using namespace network;
using namespace network::callhandler;
using namespace network::callhandler::packetdata;
using namespace p25;
using namespace p25::defines;

#include <cassert>
#include <chrono>

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

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

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

    m_packetData = new P25PacketData(network, this, debug);
}

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

TagP25Data::~TagP25Data()
{
    delete m_packetData;
}

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

bool TagP25Data::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();

    // P25 network frame should never be less then 24 bytes
    if (len < 24U) {
        LogError(LOG_NET, "malformed P25 packet, len < 24, shouldn't happen");
        return false;
    }

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

    uint8_t lco = data[4U];

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

    uint8_t controlByte = data[14U];

    uint8_t MFId = data[15U];

    uint32_t sysId = (data[11U] << 8) | (data[12U] << 0);
    uint32_t netId = GET_UINT24(data, 16U);

    uint8_t lsd1 = data[20U];
    uint8_t lsd2 = data[21U];

    DUID::E duid = (DUID::E)data[22U];
    FrameType::E frameType = FrameType::DATA_UNIT;

    if (duid == DUID::PDU) {
        if (m_network->m_disablePacketData)
            return false;
        return m_packetData->processFrame(data, len, peerId, pktSeq, streamId, fromUpstream);
    }

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

    lc::LC control;
    data::LowSpeedData lsd;

    // is this a LDU1, is this the first of a call?
    if (duid == DUID::LDU1) {
        frameType = (FrameType::E)data[180U];

        if (m_debug) {
            LogDebug(LOG_NET, "P25, frameType = $%02X", frameType);
        }

        if (frameType == FrameType::HDU_VALID) {
            uint8_t algId = data[181U];
            uint32_t kid = (data[182U] << 8) | (data[183U] << 0);

            // copy MI data
            uint8_t mi[MI_LENGTH_BYTES];
            ::memset(mi, 0x00U, MI_LENGTH_BYTES);

            for (uint8_t i = 0; i < MI_LENGTH_BYTES; i++) {
                mi[i] = data[184U + i];
            }

            if (m_debug) {
                LogDebug((fromUpstream) ? LOG_PEER : LOG_MASTER, P25_HDU_STR ", HDU_BSDWNACT, dstId = %u, algo = $%02X, kid = $%04X", dstId, algId, kid);

                if (algId != ALGO_UNENCRYPT) {
                    LogDebug(LOG_NET, P25_HDU_STR ", Enc Sync, MI = %02X %02X %02X %02X %02X %02X %02X %02X %02X", 
                        mi[0U], mi[1U], mi[2U], mi[3U], mi[4U], mi[5U], mi[6U], mi[7U], mi[8U]);
                }
            }

            control.setAlgId(algId);
            control.setKId(kid);
            control.setMI(mi);
        }
    }

    control.setLCO(lco);
    control.setSrcId(srcId);
    control.setDstId(dstId);
    control.setMFId(MFId);

    // set the LC group flag based on the control byte
    control.setGroup((controlByte & NET_CTRL_U2U) != NET_CTRL_U2U);

    lsd.setLSD1(lsd1);
    lsd.setLSD2(lsd2);

    uint8_t frameLength = buffer[23U];

    if (!m_network->validateP25FrameLength(frameLength, len, duid))
        return false;

    // process a TSBK out into a class literal if possible
    std::unique_ptr<lc::TSBK> tsbk;
    if (duid == DUID::TSDU) {
        DECLARE_UINT8_ARRAY(data, frameLength);
        ::memcpy(data, buffer + 24U, frameLength);

        tsbk = lc::tsbk::TSBKFactory::createTSBK(data);
    }

    // decode true LDU LC from the network frame into a DFSI LC class literal
    dfsi::LC dfsiLC = dfsi::LC(control, lsd);
    if (duid == DUID::LDU1 || duid == DUID::LDU2) {
        uint8_t netLDU[9U * 25U];
        ::memset(netLDU, 0x00U, 9U * 25U);

        uint8_t missing = BaseNetwork::reconstructLDUVectors(buffer + 24U, frameLength, &dfsiLC, duid, netLDU);
        if (missing > 0U) {
            LogWarning(LOG_NET, (duid == DUID::LDU1) ? P25_LDU1_STR : P25_LDU2_STR ", missing %u LDU voice frames, srcId = %u, dstId = %u", missing, srcId, dstId);
        }

        // if its a LDU2 get the crypto state
        if (duid == DUID::LDU2) {
            control.setAlgId(dfsiLC.control()->getAlgId());
            control.setKId(dfsiLC.control()->getKId());

            // copy MI data
            uint8_t mi[MI_LENGTH_BYTES];
            ::memset(mi, 0x00U, MI_LENGTH_BYTES);
            dfsiLC.control()->getMI(mi);
            control.setMI(mi);
        }
    }

    // is the stream valid?
    if (validate(peerId, control, duid, tsbk.get(), frameType, streamId)) {
        // is this peer ignored?
        if (!isPeerPermitted(peerId, control, duid, streamId, fromUpstream)) {
            return false;
        }

        // special case: if we've received a TSDU and its an LC_CALL_TERM; lets validate the source peer ID,
        //  LC_CALL_TERMs should only be sourced from the peer that initiated the call; other peers should not be
        //  transmitting LC_CALL_TERMs for the call
        if (duid == DUID::TSDU && tsbk != nullptr) {
            if (tsbk->getLCO() == LCO::CALL_TERM) {
                if (dstId == 0U) {
                    LogWarning(LOG_NET, "P25, invalid TSDU, 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];

                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()) {
                    if (status.peerId != peerId) {
                        LogWarning((fromUpstream) ? LOG_PEER : LOG_MASTER, "P25, Illegal Call Termination, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                            peerId, ssrc, sysId, netId, srcId, dstId, streamId, status.peerId, status.srcId, status.dstId, status.streamId, fromUpstream);
                        return false;
                    } else {
                        #define REQ_CALL_END_LOG "P25, Requested Call End, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, sysId, netId, srcId, dstId, streamId, fromUpstream
                        if (m_network->m_logUpstreamCallStartEnd && fromUpstream)
                            LogInfoEx(LOG_PEER, REQ_CALL_END_LOG);
                        else if (!fromUpstream)
                            LogInfoEx(LOG_MASTER, REQ_CALL_END_LOG);
                    }
                }
            }
        }

        // specifically only check the following logic for end of call or voice frames
        if (duid != DUID::TSDU && duid != DUID::PDU) {
            // is this the end of the call stream?
            if ((duid == DUID::TDU) || (duid == DUID::TDULC)) {
                // reject TDU with no source or destination
                if (srcId == 0U && dstId == 0U) {
                    LogWarning(LOG_NET, "P25, invalid TDU, peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, srcId, dstId, streamId, fromUpstream);
                    return false;
                }

                // reject TDU's with no destination
                if (dstId == 0U) {
                    return false;
                }

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

                // perform a test for grant demands, and if the TG isn't valid ignore the demand
                bool grantDemand = (data[14U] & network::NET_CTRL_GRANT_DEMAND) == network::NET_CTRL_GRANT_DEMAND;
                if (grantDemand) {
                    lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(control.getDstId());
                    if (!tg.config().active()) {
                        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()) {
                    if (grantDemand && !switchOver) {
                        LogWarning((fromUpstream) ? LOG_PEER : LOG_MASTER, "P25, Call Grant Collision, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                            peerId, ssrc, sysId, netId, srcId, dstId, streamId, status.peerId, status.srcId, status.dstId, status.streamId, fromUpstream);
                        return false;
                    }
                    else {
                        m_status[dstId].reset();

                        // is this a parrot talkgroup? if so, reset parrot states
                        lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(dstId);
                        if (tg.config().parrot() && !m_parrotPlayback) {
                            if (m_parrotFrames.size() > 0) {
                                m_parrotFramesReady = true;
                                m_parrotFirstFrame = true;
                                LogInfoEx(LOG_NET, "P25, 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 "P25, Private Call End, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, duration = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, sysId, netId, 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 "P25, Call End, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, duration = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, sysId, netId, 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", "P25")
                                    .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);
                    }
                } else {
                    #define NONCALL_TDU_LOG "P25, Non-Call TDU, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, sysId, netId, srcId, dstId, streamId, fromUpstream
                    if (m_network->m_logUpstreamCallStartEnd && fromUpstream)
                        LogInfoEx(LOG_PEER, NONCALL_TDU_LOG);
                    else if (!fromUpstream)
                        LogInfoEx(LOG_MASTER, NONCALL_TDU_LOG);

                    m_status.lock(false);
                    m_status[dstId].callStartTime = pktTime; // because Non-Call TDUs can just happen lets reset the callStartTime to pktTime to prevent insane durations
                    m_status.unlock();
                }
            }

            // is this a new call stream?
            if ((duid != DUID::TDU) && (duid != DUID::TDULC)) {
                if (srcId == 0U && dstId == 0U) {
                    LogWarning(LOG_NET, "P25, invalid call, peer = %u, ssrc = %u, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, 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, "P25, Call Source Switched (Takeover), peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSsrc = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                            peerId, ssrc, sysId, netId, srcId, dstId, streamId, status.peerId, status.ssrc, 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 && ((duid != DUID::TDU) && (duid != DUID::TDULC))) {
                        // 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, "P25, Call Source Switched, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                                    peerId, ssrc, sysId, netId, 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, "P25, 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, "P25, Call Collision, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                                            peerId, ssrc, sysId, netId, 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, "P25, Call Source Switched (Priority), peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, rxPeer = %u, rxSsrc = %u, rxSrcId = %u, rxDstId = %u, rxStreamId = %u, fromUpstream = %u",
                                            peerId, ssrc, sysId, netId, srcId, dstId, streamId, status.peerId, status.ssrc, 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_P25, 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_P25, 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 (lco == LCO::PRIVATE) {
                        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(dstId);
                        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 "P25, Private Call Start, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, sysId, netId, 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 "P25, Call Start, peer = %u, ssrc = %u, sysId = $%03X, netId = $%05X, srcId = %u, dstId = %u, streamId = %u, fromUpstream = %u", peerId, ssrc, sysId, netId, 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
            }
        }

        // process TSDU from peer
        if (!processTSDUFrom(buffer, peerId, duid)) {
            return false;
        }

        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 ((control.getLCO() != LCO::PRIVATE) && !control.getGroup()) {
                // 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 == control.getDstId()) {
                        if (x.second.activeCall)
                            return true;
                    }
                    return false;
                });
                if (it != m_statusPVCall.end()) {
                    privateCallInProgress = true;
                }
            } else {
                if (lco == LCO::PRIVATE) {
                    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 connected to us as peers
        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 ((lco == LCO::PRIVATE) && !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, control, duid, streamId)) {
                        continue;
                    }

                    // process TSDU to peer
                    if (!processTSDUTo(buffer, peer.first, duid)) {
                        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, duid, dstId);

                    m_network->writePeerQueue(&queue, peer.first, ssrc, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, outboundPeerBuffer, len, pktSeq, streamId);
                    if (m_network->m_debug) {
                        LogDebugEx(LOG_P25, "TagP25Data::processFrame()", "Master, ssrc = %u, srcPeer = %u, dstPeer = %u, duid = $%02X, lco = $%02X, MFId = $%02X, srcId = %u, dstId = %u, len = %u, pktSeq = %u, streamId = %u, fromUpstream = %u", 
                            ssrc, peerId, peer.first, duid, lco, MFId, 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, control, duid, streamId, true)) {
                        continue;
                    }

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

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

                    // process TSDUs going to neighbor FNE peers
                    if (processTSDUToNeighbor(outboundPeerBuffer, peerId, dstPeerId, duid)) {
                        // are we a replica peer?
                        if (peer.second->isReplica())
                            peer.second->writeMaster({ NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, outboundPeerBuffer, len, pktSeq, streamId, false, 0U, ssrc);
                        else
                            peer.second->writeMaster({ NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, outboundPeerBuffer, len, pktSeq, streamId);
                        if (m_network->m_debug) {
                            LogDebugEx(LOG_P25, "TagP25Data::processFrame()", "Peers, ssrc = %u, srcPeer = %u, dstPeer = %u, duid = $%02X, lco = $%02X, MFId = $%02X, srcId = %u, dstId = %u, len = %u, pktSeq = %u, streamId = %u, fromUpstream = %u", 
                                ssrc, peerId, dstPeerId, duid, lco, MFId, srcId, dstId, len, pktSeq, streamId, fromUpstream);
                        }
                    }
                }
            }
        }

        return true;
    }

    return false;
}

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

bool TagP25Data::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
    m_network->m_peers.shared_lock();
    if (m_network->m_peers.size() > 0U) {
        for (auto peer : m_network->m_peers) {
            if (peerId != peer.first) {
                write_TSDU_Grant(peer.first, srcId, dstId, 4U, !unitToUnit);
            }
        }
    }
    m_network->m_peers.shared_unlock();

    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 TagP25Data::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 TagP25Data::playbackParrot()
{
    if (m_parrotFrames.size() == 0) {
        m_parrotFramesReady = false;
        m_parrotFirstFrame = true;
        m_parrotPlayback = 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);
        }

        // is this the first parrot frame?
        if (m_parrotFirstFrame) {
            if (m_network->m_parrotGrantDemand) {
                uint32_t srcId = pkt.srcId;
                uint32_t dstId = pkt.dstId;

                // create control data
                lc::LC control = lc::LC();
                control.setSrcId(srcId);
                control.setDstId(dstId);

                // create empty LSD
                data::LowSpeedData lsd = data::LowSpeedData();

                uint8_t controlByte = network::NET_CTRL_GRANT_DEMAND;

                // send grant demand
                uint32_t messageLength = 0U;
                UInt8Array message = m_network->createP25_TDUMessage(messageLength, control, lsd, controlByte);
                if (message != nullptr) {
                    if (m_network->m_parrotOnlyOriginating) {
                        uint32_t targetPeerId = pkt.peerId;

                        // check if this peer is a VC peer (ccPeerId non-zero), and if so
                        // redirect the grant demand to its CC peer
                        m_network->m_peers.shared_lock();
                        auto it = m_network->m_peers.find(pkt.peerId);
                        if (it != m_network->m_peers.end() && it->second->ccPeerId() > 0) {
                            targetPeerId = it->second->ccPeerId();
                        }
                        m_network->m_peers.shared_unlock();

                        LogInfoEx(LOG_P25, "Parrot Grant Demand, peer = %u, srcId = %u, dstId = %u", pkt.peerId, srcId, dstId);
                        m_network->writePeer(targetPeerId, pkt.peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, message.get(), messageLength,
                            RTP_END_OF_CALL_SEQ, m_network->createStreamId());
                    } else {
                        // repeat traffic to the connected peers
                        for (auto peer : m_network->m_peers) {
                            LogInfoEx(LOG_P25, "Parrot Grant Demand, peer = %u, srcId = %u, dstId = %u", peer.first, srcId, dstId);
                            m_network->writePeer(peer.first, pkt.peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, message.get(), messageLength, 
                                RTP_END_OF_CALL_SEQ, m_network->createStreamId());
                        }
                    }
                }
            }

            m_parrotFirstFrame = false;
        }

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

        if (m_network->m_parrotOnlyOriginating) {
            uint32_t ccPeerId = 0U;

            // check if this peer is a VC peer (ccPeerId non-zero), and if so
            // determine its CC peer ID
            m_network->m_peers.shared_lock();
            auto it = m_network->m_peers.find(pkt.peerId);
            if (it != m_network->m_peers.end() && it->second->ccPeerId() > 0) {
                ccPeerId = it->second->ccPeerId();
            }
            m_network->m_peers.shared_unlock();

            // if we have a CC peer ID repeat the parrot traffic to all its connected VC peers
            if (ccPeerId > 0U && m_network->m_ccPeerMap.find(ccPeerId) != m_network->m_ccPeerMap.end()) {
                m_network->m_ccPeerMap.shared_lock();

                // repeat traffic to the connected VC peers
                uint32_t i = 0U;
                udp::BufferQueue queue = udp::BufferQueue();

                for (auto peer : m_network->m_ccPeerMap[ccPeerId]) {
                    // 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, pkt.peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, pkt.buffer, pkt.bufferLen, pkt.pktSeq, pkt.streamId);
                    if (m_network->m_debug) {
                        LogDebug(LOG_P25, "TagP25Data::playbackParrot()", "Parrot, dstPeer = %u, len = %u, pktSeq = %u, streamId = %u", 
                            peer, pkt.bufferLen, pkt.pktSeq, pkt.streamId);
                    }

                    i++;
                }
                m_network->m_frameQueue->flushQueue(&queue);
                m_network->m_ccPeerMap.shared_unlock();
            } else {
                m_network->writePeer(pkt.peerId, pkt.peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, pkt.buffer, pkt.bufferLen, pkt.pktSeq, pkt.streamId);
                if (m_network->m_debug) {
                    LogDebugEx(LOG_P25, "TagP25Data::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_P25 }, pkt.buffer, pkt.bufferLen, pkt.pktSeq, pkt.streamId);
                if (m_network->m_debug) {
                    LogDebug(LOG_P25, "TagP25Data::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(180);
    m_parrotFrames.unlock();
    m_parrotFrames.pop_front();
}

/* Helper to write a call alert packet. */

void TagP25Data::write_TSDU_Call_Alrt(uint32_t peerId, uint32_t srcId, uint32_t dstId)
{
    std::unique_ptr<lc::tsbk::IOSP_CALL_ALRT> iosp = std::make_unique<lc::tsbk::IOSP_CALL_ALRT>();
    iosp->setSrcId(srcId);
    iosp->setDstId(dstId);

    LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, srcId = %u, dstId = %u, txMult = %u", iosp->toString().c_str(), srcId, dstId);

    write_TSDU(peerId, iosp.get());
}

/* Helper to write a radio monitor packet. */

void TagP25Data::write_TSDU_Radio_Mon(uint32_t peerId, uint32_t srcId, uint32_t dstId, uint8_t txMult)
{
    std::unique_ptr<lc::tsbk::IOSP_RAD_MON> iosp = std::make_unique<lc::tsbk::IOSP_RAD_MON>();
    iosp->setSrcId(srcId);
    iosp->setDstId(dstId);
    iosp->setTxMult(txMult);

    LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, srcId = %u, dstId = %u, txMult = %u", iosp->toString().c_str(), srcId, dstId, txMult);

    write_TSDU(peerId, iosp.get());
}

/* Helper to write a extended function packet. */

void TagP25Data::write_TSDU_Ext_Func(uint32_t peerId, uint32_t func, uint32_t arg, uint32_t dstId)
{
    std::unique_ptr<lc::tsbk::IOSP_EXT_FNCT> iosp = std::make_unique<lc::tsbk::IOSP_EXT_FNCT>();
    iosp->setExtendedFunction(func);
    iosp->setSrcId(arg);
    iosp->setDstId(dstId);

    // class $02 is Motorola -- set the MFID properly
    if ((func >> 8) == 0x02U) {
        iosp->setMFId(MFG_MOT);
    }

    LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, mfId = $%02X, op = $%02X, arg = %u, tgt = %u",
        iosp->toString().c_str(), iosp->getMFId(), iosp->getExtendedFunction(), iosp->getSrcId(), iosp->getDstId());

    write_TSDU(peerId, iosp.get());
}

/* Helper to write a group affiliation query packet. */

void TagP25Data::write_TSDU_Grp_Aff_Q(uint32_t peerId, uint32_t dstId)
{
    std::unique_ptr<lc::tsbk::OSP_GRP_AFF_Q> osp = std::make_unique<lc::tsbk::OSP_GRP_AFF_Q>();
    osp->setSrcId(WUID_FNE);
    osp->setDstId(dstId);

    LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, dstId = %u", osp->toString().c_str(), dstId);

    write_TSDU(peerId, osp.get());
}

/* Helper to write a unit registration command packet. */

void TagP25Data::write_TSDU_U_Reg_Cmd(uint32_t peerId, uint32_t dstId)
{
    std::unique_ptr<lc::tsbk::OSP_U_REG_CMD> osp = std::make_unique<lc::tsbk::OSP_U_REG_CMD>();
    osp->setSrcId(WUID_FNE);
    osp->setDstId(dstId);

    LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, dstId = %u", osp->toString().c_str(), dstId);

    write_TSDU(peerId, osp.get());
}

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

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

void TagP25Data::routeRewrite(uint8_t* buffer, uint32_t peerId, uint8_t duid, uint32_t dstId, bool outbound)
{
    uint32_t srcId = GET_UINT24(buffer, 5U);
    uint32_t frameLength = buffer[23U];

    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);

        // are we receiving a TSDU?
        if (duid == DUID::TSDU) {
            DECLARE_UINT8_ARRAY(data, frameLength);
            ::memcpy(data, buffer + 24U, frameLength);

            std::unique_ptr<lc::TSBK> tsbk = lc::tsbk::TSBKFactory::createTSBK(data);
            if (tsbk != nullptr) {
                // handle standard P25 reference opcodes
                switch (tsbk->getLCO()) {
                    case TSBKO::IOSP_GRP_VCH:
                    {
                        LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, emerg = %u, encrypt = %u, prio = %u, chNo = %u-%u, srcId = %u, dstId = %u",
                            tsbk->toString(true).c_str(), tsbk->getEmergency(), tsbk->getEncrypted(), tsbk->getPriority(), tsbk->getGrpVchId(), tsbk->getGrpVchNo(), srcId, rewriteDstId);

                        tsbk->setDstId(rewriteDstId);
                    }
                    break;
                }

                // regenerate TSDU
                uint8_t data[P25_TSDU_FRAME_LENGTH_BYTES + 2U];
                ::memset(data + 2U, 0x00U, P25_TSDU_FRAME_LENGTH_BYTES);

                // Generate Sync
                Sync::addP25Sync(data + 2U);

                // Generate TSBK block
                tsbk->setLastBlock(true); // always set last block -- this a Single Block TSDU
                tsbk->encode(data + 2U);

                if (m_debug) {
                    LogDebug(LOG_RF, P25_TSDU_STR ", lco = $%02X, mfId = $%02X, lastBlock = %u, AIV = %u, EX = %u, srcId = %u, dstId = %u, sysId = $%03X, netId = $%05X",
                        tsbk->getLCO(), tsbk->getMFId(), tsbk->getLastBlock(), tsbk->getAIV(), tsbk->getEX(), tsbk->getSrcId(), tsbk->getDstId(),
                        tsbk->getSysId(), tsbk->getNetId());

                    Utils::dump(1U, "!!! *TSDU (SBF) TSBK Block Data", data + P25_PREAMBLE_LENGTH_BYTES + 2U, P25_TSBK_FEC_LENGTH_BYTES);
                }

                ::memcpy(buffer + 24U, data + 2U, P25_TSDU_FRAME_LENGTH_BYTES);
            }
        }
    }
}

/* Helper to route rewrite destination ID. */

bool TagP25Data::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);
    }

    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();
                }
                return true;
            }
        }
    }

    return false;
}

/* Helper to process TSDUs being passed from a peer. */

bool TagP25Data::processTSDUFrom(uint8_t* buffer, uint32_t peerId, uint8_t duid)
{
    // are we receiving a TSDU?
    if (duid == DUID::TSDU) {
        uint32_t frameLength = P25_TSDU_FRAME_LENGTH_BYTES;//buffer[23U];

        DECLARE_UINT8_ARRAY(data, frameLength);
        ::memcpy(data, buffer + 24U, frameLength);

        std::unique_ptr<lc::TSBK> tsbk = lc::tsbk::TSBKFactory::createTSBK(data);
        if (tsbk != nullptr) {
            // report tsbk event to InfluxDB
            if (m_network->m_enableInfluxDB && m_network->m_influxLogRawData) {
                const uint8_t* raw = tsbk->getDecodedRaw();
                if (raw != nullptr) {
                    std::stringstream ss;
                    ss << std::hex <<
                        (int)raw[0] << (int)raw[1]  << (int)raw[2] << (int)raw[4] <<
                        (int)raw[5] << (int)raw[6]  << (int)raw[7] << (int)raw[8] <<
                        (int)raw[9] << (int)raw[10] << (int)raw[11];

                    influxdb::QueryBuilder()
                        .meas("tsbk_event")
                            .tag("peerId", std::to_string(peerId))
                            .tag("lco", __INT_HEX_STR(tsbk->getLCO()))
                            .tag("tsbk", tsbk->toString())
                                .field("raw", ss.str())
                            .timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count())
                        .requestAsync(m_network->m_influxServer);
                }
            }

            // handle standard P25 reference opcodes
            switch (tsbk->getLCO()) {
            case TSBKO::IOSP_UU_VCH:
            case TSBKO::IOSP_UU_ANS:
                {
                    if (m_network->checkU2UDroppedPeer(peerId))
                        return false;
                }
                break;
            case TSBKO::OSP_ADJ_STS_BCAST:
                {
                    if (m_network->m_disallowAdjStsBcast) {
                        // LogWarning(LOG_P25, "PEER %u, passing ADJ_STS_BCAST to internal peers is prohibited, dropping", peerId);
                        return false;
                    } else {
                        lc::tsbk::OSP_ADJ_STS_BCAST* osp = static_cast<lc::tsbk::OSP_ADJ_STS_BCAST*>(tsbk.get());

                        if (m_network->m_verbose) {
                            LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, sysId = $%03X, rfss = $%02X, site = $%02X, chNo = %u-%u, svcClass = $%02X, peerId = %u", tsbk->toString().c_str(),
                                osp->getAdjSiteSysId(), osp->getAdjSiteRFSSId(), osp->getAdjSiteId(), osp->getAdjSiteChnId(), osp->getAdjSiteChnNo(), osp->getAdjSiteSvcClass(), peerId);
                        }

                        // check if the sending peer is mapped
                        lookups::AdjPeerMapEntry adjPeerMap = m_network->m_adjSiteMapLookup->find(peerId);
                        if (!adjPeerMap.isEmpty()) {
                            if (!adjPeerMap.active()) {
                                // LogWarning(LOG_P25, "PEER %u, passing ADJ_STS_BCAST to other peers is disabled, dropping", peerId);
                                return false;
                            } else {
                                // if the peer is mapped, we can repeat the ADJ_STS_BCAST to other peers
                                if (m_network->m_peers.size() > 0U) {
                                    for (auto peer : m_network->m_peers) {
                                        if (peerId != peer.first) {
                                            write_TSDU(peer.first, osp);
                                        }
                                    }

                                    // this seems strange -- but we want to prevent the main processing loop from repeating the ADJ_STS_BCAST
                                    return false;
                                }
                            }
                        }
                    }
                }
                break;
            case TSBKO::IOSP_RAD_MON:
            case TSBKO::IOSP_RAD_MON_ENH:
                if (m_network->m_disallowRadioMonitor)
                    return false;
                break;
            default:
                break;
            }
        } else {
            std::string peerIdentity = m_network->resolvePeerIdentity(peerId);
            LogWarning(LOG_P25, "PEER %u (%s), passing TSBK that failed to decode? tsbk == nullptr", peerId, peerIdentity.c_str());
        }
    }

    // are we receiving a TDULC?
    if (duid == DUID::TDULC) {
        uint32_t frameLength = buffer[23U];

        DECLARE_UINT8_ARRAY(data, frameLength);
        ::memcpy(data, buffer + 24U, frameLength);

        std::unique_ptr<lc::TDULC> tdulc = lc::tdulc::TDULCFactory::createTDULC(data);
        if (tdulc != nullptr) {
            // handle standard P25 reference opcodes
            switch (tdulc->getLCO()) {
            case LCO::CALL_TERM:
                if (m_network->m_disallowCallTerm)
                    return false;
            default:
                break;
            }
        } else {
            // bryanb: should these be logged?
            //std::string peerIdentity = m_network->resolvePeerIdentity(peerId);
            //LogWarning(LOG_P25, "PEER %u (%s), passing TDULC that failed to decode? tdulc == nullptr", peerId, peerIdentity.c_str());
        }
    }

    return true;
}

/* Helper to process TSDUs being passed to a peer. */

bool TagP25Data::processTSDUTo(uint8_t* buffer, uint32_t peerId, uint8_t duid)
{
    // are we receiving a TSDU?
    if (duid == DUID::TSDU) {
        uint32_t frameLength = P25_TSDU_FRAME_LENGTH_BYTES;//buffer[23U];

        DECLARE_UINT8_ARRAY(data, frameLength);
        ::memcpy(data, buffer + 24U, frameLength);

        std::unique_ptr<lc::TSBK> tsbk = lc::tsbk::TSBKFactory::createTSBK(data);
        if (tsbk != nullptr) {
            //uint32_t srcId = tsbk->getSrcId();
            uint32_t dstId = tsbk->getDstId();

            FNEPeerConnection* connection = nullptr;
            if (peerId > 0 && (m_network->m_peers.find(peerId) != m_network->m_peers.end())) {
                connection = m_network->m_peers[peerId];
            }

            // handle standard P25 reference opcodes
            switch (tsbk->getLCO()) {
            case TSBKO::IOSP_GRP_VCH:
                {
                    if (m_network->m_restrictGrantToAffOnly) {
                        lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(dstId);
                        if (tg.config().affiliated()) {
                            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 the TSDU
                            std::shared_ptr<fne_lookups::AffiliationLookup> aff = m_network->getPeerAffiliations(lookupPeerId);
                            if (aff == nullptr) {
                                std::string peerIdentity = m_network->resolvePeerIdentity(lookupPeerId);
                                //LogError(LOG_P25, "PEER %u (%s) has an invalid affiliations lookup? This shouldn't happen BUGBUG.", lookupPeerId, peerIdentity.c_str());
                                return false; // this will cause no TSDU to pass for this peer now...I'm not sure this is good behavior
                            }
                            else {
                                if (!aff->hasGroupAff(dstId)) {
                                    if (m_debug) {
                                        std::string peerIdentity = m_network->resolvePeerIdentity(lookupPeerId);
                                        LogDebug(LOG_P25, "PEER %u (%s) can fuck off there's no affiliations.", lookupPeerId, peerIdentity.c_str()); // just so Faulty can see more "salty" log messages
                                    }
                                    return false;
                                }
                            }
                        }
                    }
                }
                break;
            case TSBKO::IOSP_RAD_MON:
            case TSBKO::IOSP_RAD_MON_ENH:
                if (m_network->m_disallowRadioMonitor)
                    return false;
                break;
            default:
                break;
            }
        } else {
            std::string peerIdentity = m_network->resolvePeerIdentity(peerId);
            LogWarning(LOG_P25, "PEER %u (%s), passing TSBK that failed to decode? tsbk == nullptr", peerId, peerIdentity.c_str());
        }
    }

    return true;
}

/* Helper to process TSDUs being passed to a neighbor FNE peer. */

bool TagP25Data::processTSDUToNeighbor(uint8_t* buffer, uint32_t srcPeerId, uint32_t dstPeerId, uint8_t duid)
{
    // are we receiving a TSDU?
    if (duid == DUID::TSDU) {
        uint32_t frameLength = buffer[23U];

        DECLARE_UINT8_ARRAY(data, frameLength);
        ::memcpy(data, buffer + 24U, frameLength);

        std::unique_ptr<lc::TSBK> tsbk = lc::tsbk::TSBKFactory::createTSBK(data);
        if (tsbk != nullptr) {
            // handle standard P25 reference opcodes
            switch (tsbk->getLCO()) {
            case TSBKO::OSP_ADJ_STS_BCAST:
                {
                    if (m_network->m_disallowExtAdjStsBcast) {
                        // LogWarning(LOG_NET, "PEER %u, passing ADJ_STS_BCAST to neighbor peers is prohibited, dropping", dstPeerId);
                        return false;
                    } else {
                        lc::tsbk::OSP_ADJ_STS_BCAST* osp = static_cast<lc::tsbk::OSP_ADJ_STS_BCAST*>(tsbk.get());

                        if (m_network->m_verbose) {
                            LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, sysId = $%03X, rfss = $%02X, site = $%02X, chNo = %u-%u, svcClass = $%02X, peerId = %u", tsbk->toString().c_str(),
                                osp->getAdjSiteSysId(), osp->getAdjSiteRFSSId(), osp->getAdjSiteId(), osp->getAdjSiteChnId(), osp->getAdjSiteChnNo(), osp->getAdjSiteSvcClass(), srcPeerId);
                        }
                    }
                }
                break;
            default:
                break;
            }
        } else {
            std::string peerIdentity = m_network->resolvePeerIdentity(srcPeerId);
            LogWarning(LOG_P25, "PEER %u (%s), passing TSBK that failed to decode? tsbk == nullptr", srcPeerId, peerIdentity.c_str());
        }
    }

    return true;
}

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

bool TagP25Data::isPeerPermitted(uint32_t peerId, lc::LC& control, DUID::E duid, uint32_t streamId, bool fromUpstream)
{
    // promiscuous hub mode performs no ACL checking and will pass all traffic
    if (g_promiscuousHub)
        return true;

    if (control.getLCO() == LCO::PRIVATE) {
        if (m_network->m_disallowU2U)
            return false;
        if (!m_network->checkU2UDroppedPeer(peerId))
            return true;

        // is this a U2U call?
        lookups::RadioId rid = m_network->m_ridLookup->find(control.getDstId());
        if (!rid.radioDefault() && rid.radioEnabled()) {
            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
        }
    }

    // always permit a TSDU or PDU
    if (duid == DUID::TSDU || duid == DUID::PDU)
        return true;

    if (duid == DUID::TDULC) {
        // always permit a terminator
        return true;
    }

    if (duid == DUID::TDU) {
        if (m_network->m_filterTerminators) {
            if (/*control.getSrcId() != 0U &&*/control.getDstId() != 0U) {
                // is this a group call?
                lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(control.getDstId());
                if (!tg.isInvalid()) {
                    return true;
                }

                // is this peer excluded from the group?
                std::vector<uint32_t> exclusion = tg.config().exclusion();
                if (exclusion.size() > 0) {
                    auto it = std::find(exclusion.begin(), exclusion.end(), peerId);
                    if (it != exclusion.end()) {
                        return false;
                    }
                }

                tg = m_network->m_tidLookup->findByRewrite(peerId, control.getDstId());
                if (!tg.isInvalid()) {
                    return true;
                }

                // is this a U2U call?
                lookups::RadioId rid = m_network->m_ridLookup->find(control.getDstId());
                if (!rid.radioDefault() && rid.radioEnabled()) {
                    return true;
                }

                return false;
            }
        }

        // always permit a terminator
        return true;
    }

    // is this a group call?
    lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(control.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 other 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(control.getDstId())) {
                return false;
            }
        }
    }

    return true;
}

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

bool TagP25Data::validate(uint32_t peerId, lc::LC& control, DUID::E duid, const p25::lc::TSBK* tsbk, uint8_t frameType, uint32_t streamId)
{
    // promiscuous hub mode performs no ACL checking and will pass all traffic
    if (g_promiscuousHub)
        return true;

    bool skipRidCheck = false;
    if ((control.getMFId() == MFG_MOT && control.getSrcId() == 0U) || control.getSrcId() > WUID_FNE) {
        skipRidCheck = true;
    }

    //LogDebugEx(LOG_P25, "TagP25Data::validate()", "duid = $%02X, mfId = $%02X, lco = $%02X, srcId = %u, dstId = %u", duid, control.getMFId(), control.getLCO(), control.getSrcId(), control.getDstId());

    // is the source ID a blacklisted ID?
    bool rejectUnknownBadCall = false;
    if (!skipRidCheck) {
        lookups::RadioId rid = m_network->m_ridLookup->find(control.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(control.getSrcId()))
                            .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_DISABLED_SRC_RID ", peer = %u, srcId = %u, dstId = %u", peerId, control.getSrcId(), control.getDstId());

                // report In-Call Control to the peer sending traffic
                m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25, NET_ICC::REJECT_TRAFFIC, control.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 PDU if the source is valid
    if (duid == DUID::PDU)
        return true;

    // always validate a terminator if the source is valid
    if (m_network->m_filterTerminators) {
        if ((duid == DUID::TDU || duid == DUID::TDULC) && control.getDstId() != 0U) {
            // is this a private call?
            auto it = std::find_if(m_statusPVCall.begin(), m_statusPVCall.end(), [&](StatusMapPair& x) {
                if (x.second.dstId == control.getDstId()) {
                    if (x.second.activeCall)
                        return true;
                }
                return false;
            });
            if (it != m_statusPVCall.end()) {
                return true;
            }

            // is this a group call?
            lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(control.getDstId());
            if (!tg.isInvalid()) {
                return true;
            }

            tg = m_network->m_tidLookup->findByRewrite(peerId, control.getDstId());
            if (!tg.isInvalid()) {
                return true;
            }

            //LogDebugEx(LOG_P25, "TagP25Data::validate()", "TDU for invalid destination, dropped, dstId = %u", control.getDstId());
            return false;
        }

        if (duid == DUID::TDU || duid == DUID::TDULC)
            return true;
    } else {
        if (duid == DUID::TDU || duid == DUID::TDULC)
            return true;
    }

    // is the call stream rejected?
    m_rejectedCallStreams.lock(false);
    std::vector<uint32_t> rejectedStreams = m_rejectedCallStreams[control.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(control.getSrcId()))
                    .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_CALL_NOT_PERMITTED ", peer = %u, srcId = %u, dstId = %u", peerId, control.getSrcId(), control.getDstId());

        m_rejectedCallStreams.unlock();

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

    // validate private call in-progress
    bool privateCallInProgress = false;
    if ((control.getLCO() != LCO::PRIVATE) && !control.getGroup()) {
        // 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 == control.getDstId()) {
                if (x.second.activeCall)
                    return true;
            }
            return false;
        });
        if (it != m_statusPVCall.end()) {
            privateCallInProgress = true;
        }
    }

    // is this a private call?
    if ((control.getLCO() == LCO::PRIVATE) || privateCallInProgress) {
        // is the destination ID a blacklisted ID?
        lookups::RadioId rid = m_network->m_ridLookup->find(control.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(control.getSrcId()))
                            .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_DISABLED_DST_RID ", peer = %u, srcId = %u, dstId = %u", peerId, control.getSrcId(), control.getDstId());

                // report In-Call Control to the peer sending traffic
                m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25, NET_ICC::REJECT_TRAFFIC, control.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(control.getSrcId()))
                            .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_ILLEGAL_RID_ACCESS ", srcId = %u, dstId = %u", control.getSrcId(), control.getDstId());

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

        return true;
    }

    // always validate a TSDU or PDU if the source is valid
    if (duid == DUID::TSDU) {
        if (rejectUnknownBadCall)
            return false;

        if (tsbk != nullptr) {
            // handle standard P25 reference opcodes
            switch (tsbk->getLCO()) {
                case TSBKO::IOSP_GRP_VCH:
                {
                    lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(tsbk->getDstId());

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

                    if (!tg.config().active()) {
                        return false;
                    }
                }
                break;
                case TSBKO::IOSP_EXT_FNCT:
                {
                    const lc::tsbk::IOSP_EXT_FNCT* iosp = static_cast<const lc::tsbk::IOSP_EXT_FNCT*>(tsbk);
                    if (iosp != nullptr) {
                        lookups::PeerId pid = m_network->m_peerListLookup->find(peerId);
                        uint32_t func = iosp->getExtendedFunction();
                        switch (func) {
                            case ExtendedFunctions::INHIBIT:
                            case ExtendedFunctions::UNINHIBIT:
                                {
                                    if (!pid.peerDefault() && !pid.canIssueInhibit()) {
                                        LogWarning(LOG_P25, "PEER %u attempted inhibit/unhibit, not authorized", peerId);
                                        return false;
                                    }
                                }
                                break;
                        }
                    }
                }
                break;
            }

            // handle validating DVM call termination packets
            if (tsbk->getMFId() == MFG_DVM_OCS) {
                switch (tsbk->getLCO()) {
                    case LCO::CALL_TERM:
                    {
                        lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(tsbk->getDstId());

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

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

        return true;
    }

    // check TGID validity
    lookups::TalkgroupRuleGroupVoice tg = m_network->m_tidLookup->find(control.getDstId());
    if (tg.isInvalid()) {
        //LogDebugEx(LOG_NET, "TagP25Data::validate()", "dstId = %u, invalid dropped", control.getDstId());
        // 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(control.getSrcId()))
                    .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_INV_TALKGROUP ", peer = %u, srcId = %u, dstId = %u", peerId, control.getSrcId(), control.getDstId());

        // report In-Call Control to the peer sending traffic
        m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25, NET_ICC::REJECT_TRAFFIC, control.getDstId());
        return false;
    }
    else {
        // "selectable" strapping doesn't care about encryption state -- anything else does
        if ((tg.config().strapping() != lookups::TG_STRAPPING_SELECTABLE) && (frameType == FrameType::HDU_VALID || duid == DUID::LDU2)) {
            // is the TG strapped but the LC is reporting unencrypted?
            if (tg.config().strapping() == lookups::TG_STRAPPING_STRAPPED) {
                //LogDebugEx(LOG_P25, "TagP25Data::validate()", "tgId = %u, duid = $%02X, strapping = %u, algId = $%02X", control.getDstId(), (uint8_t)duid, tg.config().strapping(), control.getAlgId());
                if (control.getAlgId() == P25DEF::ALGO_UNENCRYPT) {
                    // 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(control.getSrcId()))
                                .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_ENC_TALKGROUP_CLR ", peer = %u, srcId = %u, dstId = %u", peerId, control.getSrcId(), control.getDstId());

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

            // is the TG unstrapped but the LC is reporting encrypted?
            if (tg.config().strapping() == lookups::TG_STRAPPING_CLEAR) {
                if (control.getAlgId() != P25DEF::ALGO_UNENCRYPT) {
                    // 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(control.getSrcId()))
                                .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_CLR_TALKGROUP_ENC ", peer = %u, srcId = %u, dstId = %u", peerId, control.getSrcId(), control.getDstId());

                    // report In-Call Control to the peer sending traffic
                    m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25, NET_ICC::REJECT_TRAFFIC, control.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(control.getSrcId()))
                    .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_ILLEGAL_RID_ACCESS ", srcId = %u, dstId = %u", control.getSrcId(), control.getDstId());

        // report In-Call Control to the peer sending traffic
        m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25, NET_ICC::REJECT_TRAFFIC, control.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(control.getSrcId()))
                    .tag("dstId", std::to_string(control.getDstId()))
                        .field("message", std::string(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_P25, INFLUXDB_ERRSTR_DISABLED_TALKGROUP ", peer = %u, srcId = %u, dstId = %u", peerId, control.getSrcId(), control.getDstId());

        // report In-Call Control to the peer sending traffic
        m_network->writePeerICC(peerId, streamId, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25, NET_ICC::REJECT_TRAFFIC, control.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(), control.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(control.getSrcId()))
                            .tag("dstId", std::to_string(control.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_P25, INFLUXDB_ERRSTR_RID_NOT_PERMITTED ", peer = %u, srcId = %u, dstId = %u", peerId, control.getSrcId(), control.getDstId());

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

    return true;
}

/* Helper to write a grant packet. */

bool TagP25Data::write_TSDU_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

    if (dstId == TGID_ALL) {
        return true; // do not generate grant packets for $FFFF (All Call) TGID
    }

    // 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;
        }
    }

    if (grp) {
        std::unique_ptr<lc::tsbk::IOSP_GRP_VCH> iosp = std::make_unique<lc::tsbk::IOSP_GRP_VCH>();
        iosp->setSrcId(srcId);
        iosp->setDstId(dstId);
        iosp->setGrpVchId(0U);
        iosp->setGrpVchNo(0U);
        iosp->setEmergency(emergency);
        iosp->setEncrypted(encryption);
        iosp->setPriority(priority);

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

        write_TSDU(peerId, iosp.get());
    }
    else {
        std::unique_ptr<lc::tsbk::IOSP_UU_VCH> iosp = std::make_unique<lc::tsbk::IOSP_UU_VCH>();
        iosp->setSrcId(srcId);
        iosp->setDstId(dstId);
        iosp->setGrpVchId(0U);
        iosp->setGrpVchNo(0U);
        iosp->setEmergency(emergency);
        iosp->setEncrypted(encryption);
        iosp->setPriority(priority);

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

        write_TSDU(peerId, iosp.get());
    }

    return true;
}

/* Helper to write a deny packet. */

void TagP25Data::write_TSDU_Deny(uint32_t peerId, uint32_t srcId, uint32_t dstId, uint8_t reason, uint8_t service, bool grp, bool aiv)
{
    std::unique_ptr<lc::tsbk::OSP_DENY_RSP> osp = std::make_unique<lc::tsbk::OSP_DENY_RSP>();
    osp->setAIV(aiv);
    osp->setSrcId(srcId);
    osp->setDstId(dstId);
    osp->setService(service);
    osp->setResponse(reason);
    osp->setGroup(grp);

    if (m_network->m_verbose) {
        LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, AIV = %u, reason = $%02X (%s), srcId = %u, dstId = %u",
            osp->toString().c_str(), osp->getAIV(), reason, P25Utils::denyRsnToString(reason).c_str(),
            osp->getSrcId(), osp->getDstId());
    }

    write_TSDU(peerId, osp.get());
}

/* Helper to write a queue packet. */

void TagP25Data::write_TSDU_Queue(uint32_t peerId, uint32_t srcId, uint32_t dstId, uint8_t reason, uint8_t service, bool grp, bool aiv)
{
    std::unique_ptr<lc::tsbk::OSP_QUE_RSP> osp = std::make_unique<lc::tsbk::OSP_QUE_RSP>();
    osp->setAIV(aiv);
    osp->setSrcId(srcId);
    osp->setDstId(dstId);
    osp->setService(service);
    osp->setResponse(reason);
    osp->setGroup(grp);

    if (m_network->m_verbose) {
        LogInfoEx(LOG_P25, P25_TSDU_STR ", %s, AIV = %u, reason = $%02X (%s), srcId = %u, dstId = %u",
            osp->toString().c_str(), osp->getAIV(), reason, P25Utils::queueRsnToString(reason).c_str(),
            osp->getSrcId(), osp->getDstId());
    }

    write_TSDU(peerId, osp.get());
}

/* Helper to write a network TSDU. */

void TagP25Data::write_TSDU(uint32_t peerId, lc::TSBK* tsbk)
{
    uint8_t data[P25_TSDU_FRAME_LENGTH_BYTES];
    ::memset(data, 0x00U, P25_TSDU_FRAME_LENGTH_BYTES);

    // generate Sync
    Sync::addP25Sync(data);

    // network bursts have no NID

    // generate TSBK block
    tsbk->setLastBlock(true); // always set last block -- this a Single Block TSDU
    tsbk->encode(data);

    // add status bits
    P25Utils::addStatusBits(data, P25_TSDU_FRAME_LENGTH_BYTES, false, true);
    P25Utils::setStatusBitsStartIdle(data);

    if (m_debug) {
        LogDebug(LOG_P25, P25_TSDU_STR ", lco = $%02X, mfId = $%02X, lastBlock = %u, AIV = %u, EX = %u, srcId = %u, dstId = %u, sysId = $%03X, netId = $%05X",
            tsbk->getLCO(), tsbk->getMFId(), tsbk->getLastBlock(), tsbk->getAIV(), tsbk->getEX(), tsbk->getSrcId(), tsbk->getDstId(),
            tsbk->getSysId(), tsbk->getNetId());

        Utils::dump(1U, "!!! *TSDU (SBF) TSBK Block Data", data + P25_PREAMBLE_LENGTH_BYTES, P25_TSBK_FEC_LENGTH_BYTES);
    }

    lc::LC lc = lc::LC();
    lc.setLCO(tsbk->getLCO());
    lc.setMFId(tsbk->getMFId());
    lc.setSrcId(tsbk->getSrcId());
    lc.setDstId(tsbk->getDstId());

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

    uint32_t streamId = m_network->createStreamId();
    if (peerId > 0U) {
        m_network->writePeer(peerId, m_network->m_peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, message.get(), messageLength,
            RTP_END_OF_CALL_SEQ, streamId);
    } else {
        // repeat traffic to the connected peers
        if (m_network->m_peers.size() > 0U) {
            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, m_network->m_peerId, { NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, message.get(), messageLength, 
                    RTP_END_OF_CALL_SEQ, streamId);
                if (m_network->m_debug) {
                    LogDebugEx(LOG_P25, "TagP25Data::write_TSDU()", "P25, peer = %u, len = %u, streamId = %u", 
                        peer.first, messageLength, streamId);
                }

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

        // repeat traffic to neighbor FNE peers
        if (m_network->m_host->m_peerNetworks.size() > 0U) {
            for (auto peer : m_network->m_host->m_peerNetworks) {
                uint32_t dstPeerId = peer.second->getPeerId();
                peer.second->writeMaster({ NET_FUNC::PROTOCOL, NET_SUBFUNC::PROTOCOL_SUBFUNC_P25 }, message.get(), messageLength, RTP_END_OF_CALL_SEQ, streamId);
                if (m_network->m_debug) {
                    LogDebugEx(LOG_P25, "TagP25Data::write_TSDU()", "peer = %u, len = %u, streamId = %u", 
                        dstPeerId, messageLength, streamId);
                }
            }
        }
    }
}
