mirror of
https://github.com/liquidraver/ZephCore.git
synced 2026-12-06 23:34:08 +00:00
CONFIG_ZEPHCORE_ROLE_FORWARDER, gated on the lora1 alias. One node identity on two radios: a packet heard on one side may go out on the other, never back on its own, if the fwd rules allow it. - RepeaterMesh takes its node state from RepeaterShared: ACL, regions, transport keys, flood filter, twin guard, failed-login limiter, time sync, neighbours. Side b uses side a's failed-datagram budget. - Crossing: the repeater's allowPacketForward() checks, then, through roleAllowsForward() and before anything is recorded, the direct hash-collision guard and the fwd rules (ForwarderRules, default deny). - Per side: name, radio, TX power, timing, LBT and cad.ceiling, RX gain and duty cycle, adverts, send queue, contention. Side b's prefs in prefs_b.json; side a's are authoritative for shared fields at boot. - CLI: per-radio .a/.b/.peer suffixes, `fwd` for the rules. - RAK4631 + RAK13300 conf and overlay; compile-only CI build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
309 lines
9.5 KiB
C++
309 lines
9.5 KiB
C++
/*
|
|
* SPDX-License-Identifier: MIT
|
|
* ForwarderMesh - the forwarder role: one node identity on two radios
|
|
*/
|
|
|
|
#include "ForwarderMesh.h"
|
|
|
|
#include <adapters/datastore/ZephyrFsUtil.h>
|
|
#include <adapters/radio/LoRaRadio.h>
|
|
#include <helpers/TxtDataHelpers.h>
|
|
#include <mesh/ContentionTracker.h>
|
|
#include <mesh/Utils.h>
|
|
#include <zephyr/logging/log.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
LOG_MODULE_REGISTER(zephcore_forwarder, CONFIG_ZEPHCORE_MAIN_LOG_LEVEL);
|
|
|
|
using forwarder::CliRoute;
|
|
using forwarder::SIDE_A;
|
|
using forwarder::SIDE_B;
|
|
|
|
/* ------------------------------ ForwarderSide ------------------------------ */
|
|
|
|
ForwarderSide::ForwarderSide(ForwarderMesh& fwd, uint8_t side, mesh::MainBoard& board,
|
|
mesh::LoRaRadio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng,
|
|
mesh::RTCClock& rtc, mesh::MeshTables& tables, RepeaterShared& shared,
|
|
mesh::PacketManager& mgr)
|
|
: RepeaterMesh(board, radio, ms, rng, rtc, tables, shared, mgr), _fwd(fwd), _lora(radio)
|
|
{
|
|
_side = side;
|
|
_loads_shared = side == SIDE_A;
|
|
_tag_neighbour_side = true;
|
|
}
|
|
|
|
void ForwarderSide::begin(RepeaterDataStore* store)
|
|
{
|
|
RepeaterMesh::begin(store);
|
|
}
|
|
|
|
bool ForwarderSide::isDirectCollision(const mesh::Packet* pkt)
|
|
{
|
|
#if MAX_NEIGHBOURS
|
|
const uint8_t* hash;
|
|
uint8_t len;
|
|
if (!forwarder::nextHopAfterSelf(pkt, &hash, &len)) return false;
|
|
uint8_t sides = 0;
|
|
const NeighbourInfo* n = shared().neighbours;
|
|
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
|
|
if (n[i].heard_timestamp != 0 && n[i].id.isHashMatch(hash, len)) {
|
|
sides |= 1u << (n[i].side & 1);
|
|
}
|
|
}
|
|
return forwarder::isDirectCollision(sides, _side);
|
|
#else
|
|
(void)pkt;
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
/* Asked inside the repeater's checks, before anything is recorded: the
|
|
* direct-crossing guard, then the `fwd` rules. */
|
|
bool ForwarderSide::roleAllowsForward(const mesh::Packet* packet)
|
|
{
|
|
if (_peer == nullptr) return false;
|
|
if (packet->isRouteDirect() && isDirectCollision(packet)) return false;
|
|
return _fwd.allowsCrossing(_side, packet);
|
|
}
|
|
|
|
/* Never onto this radio: the packet goes out on the other one. */
|
|
void ForwarderSide::queueRetransmit(mesh::Packet* pkt, uint8_t priority, uint32_t delay_millis)
|
|
{
|
|
(void)delay_millis;
|
|
if (_peer == nullptr) {
|
|
releasePacket(pkt);
|
|
return;
|
|
}
|
|
_peer->acceptForward(pkt, priority);
|
|
}
|
|
|
|
void ForwarderSide::routeDirectRecvAcks(mesh::Packet* packet, uint32_t delay_millis)
|
|
{
|
|
if (_peer != nullptr) {
|
|
_peer->acceptAcks(packet, delay_millis);
|
|
}
|
|
}
|
|
|
|
/* A slot draw sized to this radio's SF/BW and contention. Not anchored to a
|
|
* reception end: nobody on this side heard the packet arrive. */
|
|
uint32_t ForwarderSide::forwardDelay()
|
|
{
|
|
uint32_t d = getCADFailRetryDelay();
|
|
return d > 0 ? d : 1;
|
|
}
|
|
|
|
void ForwarderSide::acceptForward(mesh::Packet* pkt, uint8_t priority)
|
|
{
|
|
if (pkt->isRouteFlood()) {
|
|
_contention.trackRetransmit(mesh::ContentionTracker::computePacketHash32(pkt), (uint32_t)_ms->getMillis());
|
|
}
|
|
mesh::Dispatcher::queueRetransmit(pkt, priority, forwardDelay());
|
|
_fwd.noteCrossed(_side ^ 1);
|
|
}
|
|
|
|
void ForwarderSide::acceptAcks(mesh::Packet* pkt, uint32_t delay_millis)
|
|
{
|
|
mesh::Mesh::routeDirectRecvAcks(pkt, delay_millis + forwardDelay());
|
|
_fwd.noteCrossed(_side ^ 1);
|
|
}
|
|
|
|
/* Hold while the other radio is receiving a packet, for at most one
|
|
* maximum-length packet's airtime at its settings (no reception is longer). */
|
|
bool ForwarderSide::holdTxForOtherRadio(uint32_t now)
|
|
{
|
|
if (_peer == nullptr) return false;
|
|
bool receiving = _peer->lora().isReceivingPacket();
|
|
return forwarder::holdForOtherRadio(receiving, now,
|
|
receiving ? _peer->lora().getEstAirtimeFor(MAX_TRANS_UNIT) : 0,
|
|
&_peer_hold_start);
|
|
}
|
|
|
|
void ForwarderSide::savePrefs()
|
|
{
|
|
RepeaterDataStore* store = getStore();
|
|
if (store) {
|
|
if (_side == SIDE_A) {
|
|
store->savePrefs(*getNodePrefs());
|
|
} else {
|
|
store->saveSidePrefs(*getNodePrefs());
|
|
}
|
|
}
|
|
if (_peer) _peer->takeSharedPrefs(*getNodePrefs());
|
|
}
|
|
|
|
void ForwarderSide::takeSharedPrefs(const NodePrefs& from)
|
|
{
|
|
NodePrefs before = *getNodePrefs();
|
|
forwarder::copySharedPrefs(*getNodePrefs(), from);
|
|
if (memcmp(&before, getNodePrefs(), sizeof(NodePrefs)) == 0) return;
|
|
RepeaterDataStore* store = getStore();
|
|
if (!store) return;
|
|
if (_side == SIDE_A) {
|
|
store->savePrefs(*getNodePrefs());
|
|
} else {
|
|
store->saveSidePrefs(*getNodePrefs());
|
|
}
|
|
}
|
|
|
|
/* Routes a CLI line to a side (helpers/ForwarderPolicy.h), then runs it as a
|
|
* repeater would. `fwd` is the node's; the "xx|" reply header is kept. */
|
|
void ForwarderSide::handleCommand(uint32_t sender_timestamp, char* command, char* reply)
|
|
{
|
|
if (isRegionLoadActive() || _peer == nullptr) {
|
|
runOwnCommand(sender_timestamp, command, reply);
|
|
return;
|
|
}
|
|
char* body = command;
|
|
while (*body == ' ') body++;
|
|
size_t hdr = (strlen(body) > 4 && body[2] == '|') ? 3 : 0;
|
|
char* line = body + hdr;
|
|
if (StrHelper::isBlank(line)) {
|
|
runOwnCommand(sender_timestamp, command, reply);
|
|
return;
|
|
}
|
|
size_t cap = (sender_timestamp == 0 ? CLI_REPLY_SIZE : CLI_REMOTE_REPLY_SIZE) - hdr;
|
|
|
|
if (_fwd.handleFwdCommand(line, reply + hdr, cap)) {
|
|
memcpy(reply, body, hdr);
|
|
return;
|
|
}
|
|
|
|
char err[96];
|
|
CliRoute r = forwarder::routeCliLine(line, sender_timestamp != 0, _side, err, sizeof(err));
|
|
switch (r.kind) {
|
|
case CliRoute::ERROR:
|
|
memcpy(reply, body, hdr);
|
|
snprintf(reply + hdr, cap, "%s", r.error);
|
|
return;
|
|
case CliRoute::LOCAL:
|
|
runOwnCommand(sender_timestamp, command, reply);
|
|
return;
|
|
case CliRoute::SIDE:
|
|
(r.side == _side ? this : _peer)->runOwnCommand(sender_timestamp, command, reply);
|
|
return;
|
|
case CliRoute::BOTH: {
|
|
char again[CLI_REPLY_SIZE];
|
|
char reply_b[CLI_REPLY_SIZE];
|
|
snprintf(again, sizeof(again), "%s", command);
|
|
reply_b[0] = 0;
|
|
_fwd.side(SIDE_A).runOwnCommand(sender_timestamp, command, reply);
|
|
_fwd.side(SIDE_B).runOwnCommand(sender_timestamp, again, reply_b);
|
|
char reply_a[CLI_REPLY_SIZE];
|
|
snprintf(reply_a, sizeof(reply_a), "%s", reply + hdr);
|
|
memcpy(reply, body, hdr);
|
|
int half = (int)(cap / 2) - 4; /* each side's reply gets half */
|
|
snprintf(reply + hdr, cap, "a: %.*s\nb: %.*s", half, reply_a, half, reply_b + hdr);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* ------------------------------ ForwarderMesh ------------------------------ */
|
|
|
|
ForwarderMesh::ForwarderMesh(mesh::MainBoard& board, mesh::LoRaRadio& radio_a, mesh::LoRaRadio& radio_b,
|
|
mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc,
|
|
mesh::MeshTables& tables, RepeaterShared& shared,
|
|
mesh::PacketManager& mgr_a, mesh::PacketManager& mgr_b)
|
|
: _shared(shared),
|
|
_a(*this, SIDE_A, board, radio_a, ms, rng, rtc, tables, shared, mgr_a),
|
|
_b(*this, SIDE_B, board, radio_b, ms, rng, rtc, tables, shared, mgr_b)
|
|
{
|
|
_a.setPeer(&_b);
|
|
_b.setPeer(&_a);
|
|
}
|
|
|
|
void ForwarderMesh::begin(RepeaterDataStore* store)
|
|
{
|
|
_store = store;
|
|
_a.begin(store); /* loads the shared state */
|
|
_b.begin(store);
|
|
loadRules();
|
|
LOG_INF("Forwarder: %d fwd rules, default %s", _rules.count(),
|
|
_rules.defaultAllow() ? "allow" : "deny");
|
|
}
|
|
|
|
void ForwarderMesh::loop()
|
|
{
|
|
_a.loop();
|
|
_b.loop();
|
|
}
|
|
|
|
bool ForwarderMesh::allowsCrossing(uint8_t from, const mesh::Packet* pkt)
|
|
{
|
|
uint8_t dir = from == SIDE_A ? ForwarderRules::DIR_A_TO_B : ForwarderRules::DIR_B_TO_A;
|
|
return _rules.allows(dir, pkt, *this);
|
|
}
|
|
|
|
bool ForwarderMesh::handleFwdCommand(const char* line, char* reply, size_t cap)
|
|
{
|
|
bool changed = false;
|
|
if (strcmp(line, "fwd stats") == 0) {
|
|
/* The crossing counters lead the rule hit counters. */
|
|
int n = snprintf(reply, cap, "a>b:%u b>a:%u\n", (unsigned)_crossed[0], (unsigned)_crossed[1]);
|
|
if (n > 0 && (size_t)n < cap) {
|
|
_rules.command(line, reply + n, cap - n, &changed, *this);
|
|
}
|
|
return true;
|
|
}
|
|
if (!_rules.command(line, reply, cap, &changed, *this)) return false;
|
|
if (changed) saveRules();
|
|
return true;
|
|
}
|
|
|
|
void ForwarderMesh::loadRules()
|
|
{
|
|
char path[48];
|
|
uint8_t buf[ForwarderRules::BLOB_MAX];
|
|
size_t len = 0;
|
|
snprintf(path, sizeof(path), "%s/fwd", _store->getBasePath());
|
|
if (zephcore_fs_read_file(path, buf, sizeof(buf), &len) && !_rules.load(buf, len)) {
|
|
LOG_WRN("%s does not parse: no fwd rules, default deny", path);
|
|
}
|
|
}
|
|
|
|
void ForwarderMesh::saveRules()
|
|
{
|
|
char path[48];
|
|
uint8_t buf[ForwarderRules::BLOB_MAX];
|
|
size_t len = _rules.save(buf, sizeof(buf));
|
|
snprintf(path, sizeof(path), "%s/fwd", _store->getBasePath());
|
|
if (len > 0) zephcore_fs_atomic_replace(path, buf, len, "fwd");
|
|
}
|
|
|
|
void ForwarderMesh::hashtagKey(const char* name, uint8_t key[ForwarderRules::KEY_SIZE])
|
|
{
|
|
mesh::Utils::sha256(key, ForwarderRules::KEY_SIZE, (const uint8_t*)name, (int)strlen(name));
|
|
}
|
|
|
|
bool ForwarderMesh::inRegion(const mesh::Packet* pkt, const ForwarderRules::Rule& r)
|
|
{
|
|
if (!pkt->hasTransportCodes()) return false;
|
|
if (r.region_keyed) {
|
|
TransportKey k;
|
|
memcpy(k.key, r.region_key, sizeof(k.key));
|
|
return k.calcTransportCode(pkt) == pkt->transport_codes[0];
|
|
}
|
|
RegionEntry* e = _shared.region_map.findByName(r.region);
|
|
if (e == nullptr) return false;
|
|
TransportKey keys[4];
|
|
int n = _shared.region_map.getTransportKeysFor(*e, keys, 4);
|
|
for (int i = 0; i < n; i++) {
|
|
if (keys[i].calcTransportCode(pkt) == pkt->transport_codes[0]) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/* The channel-hash byte first, then the MAC: a 1-byte hash collision alone
|
|
* does not pass. */
|
|
bool ForwarderMesh::fromChannel(const mesh::Packet* pkt, const uint8_t key[ForwarderRules::KEY_SIZE])
|
|
{
|
|
uint8_t hash;
|
|
mesh::Utils::sha256(&hash, 1, key, ForwarderRules::KEY_SIZE);
|
|
if (pkt->payload_len < 3 || pkt->payload[0] != hash) return false;
|
|
uint8_t secret[PUB_KEY_SIZE] = {0};
|
|
memcpy(secret, key, ForwarderRules::KEY_SIZE);
|
|
uint8_t data[MAX_PACKET_PAYLOAD];
|
|
return mesh::Utils::MACThenDecrypt(secret, data, &pkt->payload[1], pkt->payload_len - 1) > 0;
|
|
}
|