Harden firmware recovery and retries
Improve companion BLE delivery and idempotent remote CLI retries, make FPF7 persistence atomic with FPF6 migration, verify staged OTA data on resume, and clarify filter policy wildcard and BlackHole semantics.
This commit is contained in:
1 parent
7f56da7a34
commit
11b692abfa
37 files changed
+1666
-307
No files matched your search
@@ -1,4 +1,5 @@
|
||||
#include <helpers/BaseChatMesh.h>
|
||||
#include <helpers/RemoteCliRequest.h>
|
||||
#include <Utils.h>
|
||||
|
||||
#ifndef SERVER_RESPONSE_DELAY
|
||||
@@ -486,16 +487,28 @@ int BaseChatMesh::sendMessage(const ContactInfo& recipient, uint32_t timestamp,
|
||||
return rc;
|
||||
}
|
||||
|
||||
int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout) {
|
||||
int BaseChatMesh::sendCommandData(const ContactInfo& recipient,
|
||||
uint32_t timestamp, uint8_t attempt,
|
||||
const char* text, uint32_t& est_timeout,
|
||||
uint32_t logical_request_id) {
|
||||
int text_len = strlen(text);
|
||||
if (text_len > MAX_TEXT_LEN) return MSG_SEND_FAILED;
|
||||
|
||||
uint8_t temp[5+MAX_TEXT_LEN+1];
|
||||
uint8_t temp[5 + MAX_TEXT_LEN + mesh::RemoteCliRequest::EXTENSION_SIZE];
|
||||
memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique
|
||||
temp[4] = (attempt & 3) | (TXT_TYPE_CLI_DATA << 2);
|
||||
memcpy(&temp[5], text, text_len + 1);
|
||||
memcpy(&temp[5], text, text_len);
|
||||
|
||||
auto pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, recipient.id, recipient.getSharedSecret(self_id), temp, 5 + text_len);
|
||||
size_t payload_len = 5 + text_len;
|
||||
if (logical_request_id != 0) {
|
||||
payload_len = mesh::RemoteCliRequest::append(
|
||||
temp, sizeof(temp), 5, text_len, logical_request_id);
|
||||
if (payload_len == 0) return MSG_SEND_FAILED;
|
||||
}
|
||||
|
||||
auto pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, recipient.id,
|
||||
recipient.getSharedSecret(self_id), temp,
|
||||
payload_len);
|
||||
if (pkt == NULL) return MSG_SEND_FAILED;
|
||||
|
||||
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
|
||||
|
||||
@@ -163,7 +163,10 @@ public:
|
||||
int sendMessage(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text,
|
||||
uint32_t& expected_ack, uint32_t& est_timeout, uint8_t* packet_hash = NULL,
|
||||
const uint8_t* replace_retry_key = NULL);
|
||||
int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout);
|
||||
int sendCommandData(const ContactInfo& recipient, uint32_t timestamp,
|
||||
uint8_t attempt, const char* text,
|
||||
uint32_t& est_timeout,
|
||||
uint32_t logical_request_id = 0);
|
||||
bool sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len);
|
||||
bool sendGroupData(mesh::GroupChannel& channel, uint8_t* path, uint8_t path_len, uint16_t data_type, const uint8_t* data, int data_len);
|
||||
int sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout);
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// A command reply should normally clear the BLE stack within a few connection
|
||||
// intervals. Allow generous transient backpressure, but do not leave the app
|
||||
// waiting forever on a link whose notification path has stopped making
|
||||
// progress.
|
||||
static const uint32_t BLE_TX_STALL_TIMEOUT_MS = 10000UL;
|
||||
static const uint32_t BLE_DISCONNECT_RETRY_INTERVAL_MS = 1000UL;
|
||||
|
||||
inline bool bleElapsedAtLeast(uint32_t now, uint32_t since,
|
||||
uint32_t interval_ms) {
|
||||
// Unsigned subtraction remains correct across one millis() rollover.
|
||||
return static_cast<uint32_t>(now - since) >= interval_ms;
|
||||
}
|
||||
|
||||
// Submit at most one ATT notification per writer call. This preserves the
|
||||
// exact number of bytes accepted before a failure; some BLE UART wrappers
|
||||
// collapse an internally partial multi-notification write to a zero return.
|
||||
template <typename WriteChunk>
|
||||
size_t writeBleFrameInChunks(const uint8_t* frame, size_t len,
|
||||
size_t max_payload, WriteChunk write_chunk) {
|
||||
if (frame == nullptr || len == 0 || max_payload == 0) return 0;
|
||||
|
||||
size_t total_written = 0;
|
||||
while (total_written < len) {
|
||||
const size_t remaining = len - total_written;
|
||||
const size_t chunk_len = remaining < max_payload ? remaining : max_payload;
|
||||
size_t chunk_written = write_chunk(frame + total_written, chunk_len);
|
||||
if (chunk_written > chunk_len) chunk_written = chunk_len;
|
||||
total_written += chunk_written;
|
||||
if (chunk_written != chunk_len) break;
|
||||
}
|
||||
return total_written;
|
||||
}
|
||||
|
||||
class BleTxStallWatchdog {
|
||||
bool _active;
|
||||
uint32_t _blocked_since;
|
||||
|
||||
public:
|
||||
BleTxStallWatchdog() : _active(false), _blocked_since(0) {}
|
||||
|
||||
void reset() {
|
||||
_active = false;
|
||||
_blocked_since = 0;
|
||||
}
|
||||
|
||||
bool noteBlocked(uint32_t now,
|
||||
uint32_t timeout_ms = BLE_TX_STALL_TIMEOUT_MS) {
|
||||
if (!_active) {
|
||||
_active = true;
|
||||
_blocked_since = now;
|
||||
return timeout_ms == 0;
|
||||
}
|
||||
|
||||
return bleElapsedAtLeast(now, _blocked_since, timeout_ms);
|
||||
}
|
||||
|
||||
bool active() const { return _active; }
|
||||
};
|
||||
|
||||
// Disconnect requests are asynchronous and can transiently fail. Keep the
|
||||
// transport in a recovery state until its disconnect callback arrives, and
|
||||
// periodically retry the request instead of abandoning a live controller link
|
||||
// after one failed call.
|
||||
class BleDisconnectRecovery {
|
||||
bool _pending;
|
||||
bool _attempted;
|
||||
uint32_t _last_attempt;
|
||||
|
||||
public:
|
||||
BleDisconnectRecovery()
|
||||
: _pending(false), _attempted(false), _last_attempt(0) {}
|
||||
|
||||
void begin() {
|
||||
_pending = true;
|
||||
_attempted = false;
|
||||
_last_attempt = 0;
|
||||
}
|
||||
|
||||
void complete() {
|
||||
_pending = false;
|
||||
_attempted = false;
|
||||
_last_attempt = 0;
|
||||
}
|
||||
|
||||
bool pending() const { return _pending; }
|
||||
|
||||
bool shouldAttempt(
|
||||
uint32_t now,
|
||||
uint32_t retry_interval_ms = BLE_DISCONNECT_RETRY_INTERVAL_MS) {
|
||||
if (!_pending) return false;
|
||||
|
||||
if (!_attempted ||
|
||||
bleElapsedAtLeast(now, _last_attempt, retry_interval_ms)) {
|
||||
_attempted = true;
|
||||
_last_attempt = now;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mesh
|
||||
@@ -10,15 +10,47 @@ inline bool isCompanionPushFrame(const uint8_t* frame, size_t len) {
|
||||
return frame != NULL && len > 0 && (frame[0] & 0x80) != 0;
|
||||
}
|
||||
|
||||
enum CompanionFrameClass : uint8_t {
|
||||
COMPANION_RESPONSE = 0,
|
||||
COMPANION_REQUIRED_PUSH = 1,
|
||||
COMPANION_BEST_EFFORT_PUSH = 2,
|
||||
};
|
||||
|
||||
/**
|
||||
* Companion push codes share one numeric range, but they do not share one
|
||||
* delivery contract. Command completions, login results, MSG_WAITING, and
|
||||
* status/telemetry replies are required for the app to make progress. Only
|
||||
* unsolicited discovery/path updates and packet logs are safe to shed.
|
||||
*
|
||||
* Unknown future push codes default to required so an older transport does
|
||||
* not silently discard a new protocol result it does not yet recognize.
|
||||
*/
|
||||
inline CompanionFrameClass companionFrameClass(const uint8_t* frame,
|
||||
size_t len) {
|
||||
if (!isCompanionPushFrame(frame, len)) return COMPANION_RESPONSE;
|
||||
switch (frame[0]) {
|
||||
case 0x80: // ADVERT
|
||||
case 0x81: // PATH_UPDATED
|
||||
case 0x84: // RAW_DATA
|
||||
case 0x88: // LOG_RX_DATA
|
||||
case 0x8A: // NEW_ADVERT
|
||||
return COMPANION_BEST_EFFORT_PUSH;
|
||||
default:
|
||||
return COMPANION_REQUIRED_PUSH;
|
||||
}
|
||||
}
|
||||
|
||||
inline bool companionFrameRequiresDelivery(const uint8_t* frame, size_t len) {
|
||||
return companionFrameClass(frame, len) != COMPANION_BEST_EFFORT_PUSH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a frame to a companion transport's contiguous outbound queue.
|
||||
*
|
||||
* Protocol responses use codes below 0x80 and complete an app command that is
|
||||
* waiting for them. Push frames use codes at or above 0x80 and are
|
||||
* asynchronous. Keep one slot available for a response, and if an older queue
|
||||
* is already full of mixed traffic, let a response replace the newest push.
|
||||
* Responses are inserted before pushes so packet-log traffic cannot delay a
|
||||
* command indefinitely.
|
||||
* Protocol responses use codes below 0x80. Push frames use codes at or above
|
||||
* 0x80, but some pushes also complete an app operation. Keep one slot away
|
||||
* from best-effort traffic, let required frames displace best-effort traffic,
|
||||
* and order responses before required pushes before best-effort pushes.
|
||||
*/
|
||||
template <typename Frame, typename QueueLength>
|
||||
bool enqueueCompanionFrame(Frame queue[], QueueLength& queue_len, size_t capacity,
|
||||
@@ -28,20 +60,38 @@ bool enqueueCompanionFrame(Frame queue[], QueueLength& queue_len, size_t capacit
|
||||
size_t count = static_cast<size_t>(queue_len);
|
||||
if (count > capacity) return false;
|
||||
|
||||
const bool push = isCompanionPushFrame(src, len);
|
||||
if (push && count >= capacity - 1) {
|
||||
return false; // preserve one slot for the reply to an app command
|
||||
const CompanionFrameClass incoming_class = companionFrameClass(src, len);
|
||||
|
||||
// MSG_WAITING is a level-triggered tickle: one queued copy is enough to tell
|
||||
// the app to fetch all pending messages. Coalescing it preserves space for
|
||||
// command completions without losing information.
|
||||
if (src[0] == 0x83) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (queue[i].len > 0 && queue[i].buf[0] == 0x83) return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (incoming_class == COMPANION_BEST_EFFORT_PUSH
|
||||
&& count >= capacity - 1) {
|
||||
return false; // preserve one slot for delivery-required traffic
|
||||
}
|
||||
|
||||
if (count == capacity) {
|
||||
// A response may displace best-effort asynchronous traffic, but never an
|
||||
// earlier response that another command is already waiting for.
|
||||
// A delivery-required frame may displace best-effort asynchronous traffic,
|
||||
// but never another delivery-required frame.
|
||||
if (incoming_class == COMPANION_BEST_EFFORT_PUSH) return false;
|
||||
size_t evict = count;
|
||||
while (evict > 0) {
|
||||
--evict;
|
||||
if (isCompanionPushFrame(queue[evict].buf, queue[evict].len)) break;
|
||||
if (companionFrameClass(queue[evict].buf, queue[evict].len)
|
||||
== COMPANION_BEST_EFFORT_PUSH) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (companionFrameClass(queue[evict].buf, queue[evict].len)
|
||||
!= COMPANION_BEST_EFFORT_PUSH) {
|
||||
return false;
|
||||
}
|
||||
if (!isCompanionPushFrame(queue[evict].buf, queue[evict].len)) return false;
|
||||
|
||||
for (size_t i = evict; i + 1 < count; ++i) {
|
||||
queue[i] = queue[i + 1];
|
||||
@@ -49,34 +99,32 @@ bool enqueueCompanionFrame(Frame queue[], QueueLength& queue_len, size_t capacit
|
||||
--count;
|
||||
}
|
||||
|
||||
size_t insert_at = count;
|
||||
if (!push) {
|
||||
// Keep responses FIFO with respect to one another, ahead of asynchronous
|
||||
// pushes such as raw-packet logs and message-waiting notifications.
|
||||
// The stable partition also repairs a queue populated by older admission
|
||||
// behavior before this policy gets a chance to add the next response.
|
||||
for (size_t i = 1; i < count; ++i) {
|
||||
if (isCompanionPushFrame(queue[i].buf, queue[i].len)) continue;
|
||||
// Stable insertion sort also repairs a queue populated by older admission
|
||||
// behavior before the next frame is added.
|
||||
for (size_t i = 1; i < count; ++i) {
|
||||
Frame current = queue[i];
|
||||
CompanionFrameClass current_class =
|
||||
companionFrameClass(current.buf, current.len);
|
||||
size_t j = i;
|
||||
while (j > 0
|
||||
&& companionFrameClass(queue[j - 1].buf, queue[j - 1].len)
|
||||
> current_class) {
|
||||
queue[j] = queue[j - 1];
|
||||
--j;
|
||||
}
|
||||
queue[j] = current;
|
||||
}
|
||||
|
||||
Frame response = queue[i];
|
||||
size_t j = i;
|
||||
while (j > 0
|
||||
&& isCompanionPushFrame(queue[j - 1].buf, queue[j - 1].len)) {
|
||||
queue[j] = queue[j - 1];
|
||||
--j;
|
||||
}
|
||||
queue[j] = response;
|
||||
}
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (isCompanionPushFrame(queue[i].buf, queue[i].len)) {
|
||||
insert_at = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (size_t i = count; i > insert_at; --i) {
|
||||
queue[i] = queue[i - 1];
|
||||
size_t insert_at = count;
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (companionFrameClass(queue[i].buf, queue[i].len) > incoming_class) {
|
||||
insert_at = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (size_t i = count; i > insert_at; --i) {
|
||||
queue[i] = queue[i - 1];
|
||||
}
|
||||
|
||||
queue[insert_at].len = len;
|
||||
memcpy(queue[insert_at].buf, src, len);
|
||||
|
||||
@@ -16,19 +16,22 @@ struct DeferredCliCommand {
|
||||
bool pending;
|
||||
int client_index;
|
||||
uint32_t sender_timestamp;
|
||||
uint32_t request_id;
|
||||
uint8_t path_hash_size;
|
||||
uint8_t secret[PUB_KEY_SIZE];
|
||||
char command[MAX_PACKET_PAYLOAD + 1];
|
||||
|
||||
DeferredCliCommand()
|
||||
: pending(false), client_index(-1), sender_timestamp(0), path_hash_size(1) {
|
||||
: pending(false), client_index(-1), sender_timestamp(0), request_id(0),
|
||||
path_hash_size(1) {
|
||||
memset(secret, 0, sizeof(secret));
|
||||
command[0] = 0;
|
||||
}
|
||||
|
||||
bool enqueue(int new_client_index, uint32_t new_sender_timestamp,
|
||||
uint8_t new_path_hash_size, const uint8_t* new_secret,
|
||||
const char* new_command, size_t command_len) {
|
||||
const char* new_command, size_t command_len,
|
||||
uint32_t new_request_id = 0) {
|
||||
if (pending || new_secret == NULL || new_command == NULL
|
||||
|| command_len >= sizeof(command)) {
|
||||
return false;
|
||||
@@ -36,6 +39,8 @@ struct DeferredCliCommand {
|
||||
|
||||
client_index = new_client_index;
|
||||
sender_timestamp = new_sender_timestamp;
|
||||
request_id = new_request_id != 0
|
||||
? new_request_id : new_sender_timestamp;
|
||||
path_hash_size = new_path_hash_size;
|
||||
memcpy(secret, new_secret, sizeof(secret));
|
||||
memcpy(command, new_command, command_len);
|
||||
@@ -44,10 +49,21 @@ struct DeferredCliCommand {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool matches(int other_client_index, uint32_t other_request_id,
|
||||
const char* other_command, size_t other_command_len) const {
|
||||
return pending && other_command != NULL
|
||||
&& client_index == other_client_index
|
||||
&& request_id == other_request_id
|
||||
&& other_command_len < sizeof(command)
|
||||
&& command[other_command_len] == 0
|
||||
&& memcmp(command, other_command, other_command_len) == 0;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
pending = false;
|
||||
client_index = -1;
|
||||
sender_timestamp = 0;
|
||||
request_id = 0;
|
||||
path_hash_size = 1;
|
||||
memset(secret, 0, sizeof(secret));
|
||||
memset(command, 0, sizeof(command));
|
||||
|
||||
@@ -315,6 +315,15 @@ inline uint32_t truncateRulesAtStop(uint32_t match_mask,
|
||||
return effective;
|
||||
}
|
||||
|
||||
inline bool stopActionApplies(bool stop_on_match, bool has_region_target,
|
||||
bool region_target_usable) {
|
||||
// A direct scope= target is derived from its public name and is always
|
||||
// usable. A region= target is configuration-backed; if it disappeared or
|
||||
// can no longer carry floods, its rewrite and its terminal stop are inert.
|
||||
return stop_on_match
|
||||
&& (!has_region_target || region_target_usable);
|
||||
}
|
||||
|
||||
inline bool scopeRuleAllowed(bool requires_region_match,
|
||||
bool incoming_region_allowed) {
|
||||
return !requires_region_match || incoming_region_allowed;
|
||||
|
||||
@@ -7,11 +7,8 @@
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// Keeps the most recently completed remote CLI reply so an exact request
|
||||
// retry can recover a lost response without executing the command twice.
|
||||
// This is deliberately a single bounded entry: remote CLI commands are
|
||||
// serialized, and repeater builds on small MCUs cannot afford one reply-sized
|
||||
// buffer for every ACL client.
|
||||
// Keeps a small bounded history of completed remote CLI replies so a delayed
|
||||
// exact retry can recover a lost response without executing the command twice.
|
||||
class RemoteCliReplyCache {
|
||||
public:
|
||||
static constexpr size_t MAX_REPLY_TEXT =
|
||||
@@ -19,6 +16,12 @@ public:
|
||||
|
||||
RemoteCliReplyCache() { clear(); }
|
||||
|
||||
#if defined(STM32_PLATFORM)
|
||||
static constexpr size_t ENTRY_COUNT = 2;
|
||||
#else
|
||||
static constexpr size_t ENTRY_COUNT = 4;
|
||||
#endif
|
||||
|
||||
static uint32_t fingerprint(const char* command, size_t command_len) {
|
||||
if (command == NULL) return 0;
|
||||
|
||||
@@ -36,46 +39,93 @@ public:
|
||||
uint32_t command_fingerprint, const char* response) {
|
||||
if (sender_pub_key == NULL || response == NULL) return false;
|
||||
|
||||
memcpy(sender_pub_key_, sender_pub_key, sizeof(sender_pub_key_));
|
||||
request_timestamp_ = request_timestamp;
|
||||
command_fingerprint_ = command_fingerprint;
|
||||
Entry* target = NULL;
|
||||
for (size_t i = 0; i < ENTRY_COUNT; ++i) {
|
||||
if (entryMatches(entries_[i], sender_pub_key, request_timestamp,
|
||||
command_fingerprint)) {
|
||||
target = &entries_[i];
|
||||
latest_entry_ = (uint8_t)i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (target == NULL) {
|
||||
target = &entries_[next_entry_];
|
||||
latest_entry_ = next_entry_;
|
||||
next_entry_ = (uint8_t)((next_entry_ + 1) % ENTRY_COUNT);
|
||||
}
|
||||
|
||||
memcpy(target->sender_pub_key, sender_pub_key,
|
||||
sizeof(target->sender_pub_key));
|
||||
target->request_timestamp = request_timestamp;
|
||||
target->command_fingerprint = command_fingerprint;
|
||||
|
||||
size_t response_len = 0;
|
||||
while (response_len < MAX_REPLY_TEXT && response[response_len] != 0) {
|
||||
response_len++;
|
||||
}
|
||||
memcpy(response_, response, response_len);
|
||||
response_[response_len] = 0;
|
||||
valid_ = true;
|
||||
memcpy(target->response, response, response_len);
|
||||
target->response[response_len] = 0;
|
||||
target->valid = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool lookup(const uint8_t* sender_pub_key, uint32_t request_timestamp,
|
||||
uint32_t command_fingerprint,
|
||||
const char** response = NULL) const {
|
||||
for (size_t i = 0; i < ENTRY_COUNT; ++i) {
|
||||
if (!entryMatches(entries_[i], sender_pub_key, request_timestamp,
|
||||
command_fingerprint)) {
|
||||
continue;
|
||||
}
|
||||
if (response != NULL) *response = entries_[i].response;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool matches(const uint8_t* sender_pub_key, uint32_t request_timestamp,
|
||||
uint32_t command_fingerprint) const {
|
||||
return valid_ && sender_pub_key != NULL
|
||||
&& request_timestamp_ == request_timestamp
|
||||
&& command_fingerprint_ == command_fingerprint
|
||||
&& memcmp(sender_pub_key_, sender_pub_key, sizeof(sender_pub_key_)) == 0;
|
||||
return lookup(sender_pub_key, request_timestamp, command_fingerprint);
|
||||
}
|
||||
|
||||
const char* response() const { return response_; }
|
||||
bool hasResponse() const { return valid_ && response_[0] != 0; }
|
||||
bool isValid() const { return valid_; }
|
||||
const char* response() const {
|
||||
return latest_entry_ < ENTRY_COUNT && entries_[latest_entry_].valid
|
||||
? entries_[latest_entry_].response : "";
|
||||
}
|
||||
bool hasResponse() const { return isValid() && response()[0] != 0; }
|
||||
bool isValid() const {
|
||||
return latest_entry_ < ENTRY_COUNT && entries_[latest_entry_].valid;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
valid_ = false;
|
||||
memset(sender_pub_key_, 0, sizeof(sender_pub_key_));
|
||||
request_timestamp_ = 0;
|
||||
command_fingerprint_ = 0;
|
||||
memset(response_, 0, sizeof(response_));
|
||||
memset(entries_, 0, sizeof(entries_));
|
||||
next_entry_ = 0;
|
||||
latest_entry_ = (uint8_t)ENTRY_COUNT;
|
||||
}
|
||||
|
||||
private:
|
||||
bool valid_;
|
||||
uint8_t sender_pub_key_[PUB_KEY_SIZE];
|
||||
uint32_t request_timestamp_;
|
||||
uint32_t command_fingerprint_;
|
||||
char response_[MAX_REPLY_TEXT + 1];
|
||||
struct Entry {
|
||||
bool valid;
|
||||
uint8_t sender_pub_key[PUB_KEY_SIZE];
|
||||
uint32_t request_timestamp;
|
||||
uint32_t command_fingerprint;
|
||||
char response[MAX_REPLY_TEXT + 1];
|
||||
};
|
||||
|
||||
static bool entryMatches(const Entry& entry,
|
||||
const uint8_t* sender_pub_key,
|
||||
uint32_t request_timestamp,
|
||||
uint32_t command_fingerprint) {
|
||||
return entry.valid && sender_pub_key != NULL
|
||||
&& entry.request_timestamp == request_timestamp
|
||||
&& entry.command_fingerprint == command_fingerprint
|
||||
&& memcmp(entry.sender_pub_key, sender_pub_key,
|
||||
sizeof(entry.sender_pub_key)) == 0;
|
||||
}
|
||||
|
||||
Entry entries_[ENTRY_COUNT];
|
||||
uint8_t next_entry_;
|
||||
uint8_t latest_entry_;
|
||||
};
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// Backward-compatible logical request identity for remote CLI retries. The
|
||||
// on-air timestamp remains fresh for legacy replay guards. New servers find
|
||||
// this authenticated extension after the command's NUL; old servers stop at
|
||||
// that NUL and continue to see the original command text.
|
||||
class RemoteCliRequest {
|
||||
public:
|
||||
static constexpr size_t EXTENSION_SIZE = 9; // NUL + "MCR1" + uint32 id
|
||||
|
||||
static size_t append(uint8_t* payload, size_t capacity,
|
||||
size_t command_offset, size_t command_len,
|
||||
uint32_t logical_id) {
|
||||
if (payload == NULL || logical_id == 0
|
||||
|| command_offset + command_len + EXTENSION_SIZE > capacity) {
|
||||
return 0;
|
||||
}
|
||||
size_t pos = command_offset + command_len;
|
||||
payload[pos++] = 0;
|
||||
payload[pos++] = 'M';
|
||||
payload[pos++] = 'C';
|
||||
payload[pos++] = 'R';
|
||||
payload[pos++] = '1';
|
||||
memcpy(payload + pos, &logical_id, sizeof(logical_id));
|
||||
return pos + sizeof(logical_id);
|
||||
}
|
||||
|
||||
static bool parse(const uint8_t* payload, size_t payload_len,
|
||||
size_t command_offset, uint32_t& logical_id) {
|
||||
if (payload == NULL || command_offset >= payload_len) return false;
|
||||
const uint8_t* terminator = (const uint8_t*)memchr(
|
||||
payload + command_offset, 0, payload_len - command_offset);
|
||||
if (terminator == NULL) return false;
|
||||
size_t pos = (size_t)(terminator - payload) + 1;
|
||||
if (pos + 8 > payload_len
|
||||
|| payload[pos] != 'M' || payload[pos + 1] != 'C'
|
||||
|| payload[pos + 2] != 'R' || payload[pos + 3] != '1') {
|
||||
return false;
|
||||
}
|
||||
memcpy(&logical_id, payload + pos + 4, sizeof(logical_id));
|
||||
return logical_id != 0;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mesh
|
||||
@@ -109,7 +109,7 @@ void SerialBLEInterface::onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
|
||||
|
||||
deviceConnected = false;
|
||||
pServer->disconnect(pServer->getConnId());
|
||||
adv_restart_time = millis() + ADVERT_RESTART_DELAY;
|
||||
scheduleAdvertisingRestart((uint32_t)millis());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,7 +122,14 @@ void SerialBLEInterface::onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t
|
||||
BLE_DEBUG_PRINTLN("onConnect(), conn_id=%d, mtu=%d", param->connect.conn_id, pServer->getPeerMTU(param->connect.conn_id));
|
||||
last_conn_id = param->connect.conn_id;
|
||||
deviceConnected = false; // becomes usable only after authentication completes
|
||||
oldDeviceConnected = false;
|
||||
notifySucceeded = false;
|
||||
// BLE callbacks run outside the Arduino loop. FreeRTOS owns the RX queue,
|
||||
// so it is safe to reset here; defer the plain-array TX queue reset to the
|
||||
// loop to avoid racing a notification completion.
|
||||
xQueueReset(recv_queue);
|
||||
_tx_reset_pending.store(true, std::memory_order_release);
|
||||
_adv_restart_pending = false;
|
||||
if (pTxDescriptor != NULL) pTxDescriptor->setNotifications(false);
|
||||
}
|
||||
|
||||
@@ -134,15 +141,22 @@ void SerialBLEInterface::onDisconnect(BLEServer* pServer) {
|
||||
BLE_DEBUG_PRINTLN("onDisconnect()");
|
||||
deviceConnected = false;
|
||||
notifySucceeded = false;
|
||||
xQueueReset(recv_queue);
|
||||
_tx_reset_pending.store(true, std::memory_order_release);
|
||||
if (pTxDescriptor != NULL) pTxDescriptor->setNotifications(false);
|
||||
if (_isEnabled) {
|
||||
adv_restart_time = millis() + ADVERT_RESTART_DELAY;
|
||||
scheduleAdvertisingRestart((uint32_t)millis());
|
||||
}
|
||||
}
|
||||
|
||||
// -------- BLECharacteristicCallbacks methods
|
||||
|
||||
void SerialBLEInterface::onWrite(BLECharacteristic* pCharacteristic, esp_ble_gatts_cb_param_t* param) {
|
||||
if (_tx_disconnect_recovery.pending()) {
|
||||
BLE_DEBUG_PRINTLN("onWrite(): dropping frame while BLE reconnect is pending");
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t* rxValue = pCharacteristic->getData();
|
||||
int len = pCharacteristic->getLength();
|
||||
|
||||
@@ -173,6 +187,58 @@ void SerialBLEInterface::onStatus(BLECharacteristic* pCharacteristic, Status sta
|
||||
void SerialBLEInterface::clearBuffers() {
|
||||
xQueueReset(recv_queue);
|
||||
send_queue_len = 0;
|
||||
notifySucceeded = false;
|
||||
_tx_stall_watchdog.reset();
|
||||
_tx_disconnect_recovery.complete();
|
||||
_tx_reset_pending.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
void SerialBLEInterface::servicePendingTxReset() {
|
||||
if (!_tx_reset_pending.exchange(false, std::memory_order_acq_rel)) return;
|
||||
send_queue_len = 0;
|
||||
notifySucceeded = false;
|
||||
_tx_stall_watchdog.reset();
|
||||
_tx_disconnect_recovery.complete();
|
||||
}
|
||||
|
||||
void SerialBLEInterface::scheduleAdvertisingRestart(uint32_t now) {
|
||||
_adv_restart_started = now;
|
||||
_adv_restart_pending = true;
|
||||
}
|
||||
|
||||
void SerialBLEInterface::serviceTxRecovery(uint32_t now) {
|
||||
if (!_tx_disconnect_recovery.pending()) return;
|
||||
|
||||
if (pServer == NULL || pServer->getConnectedCount() == 0) {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface: stalled TX link is already closed");
|
||||
deviceConnected = false;
|
||||
clearBuffers();
|
||||
if (_isEnabled) scheduleAdvertisingRestart(now);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_tx_disconnect_recovery.shouldAttempt(now)) return;
|
||||
|
||||
// BLEServer::disconnect() does not expose the controller return code. Keep
|
||||
// recovery pending and issue another bounded request until onDisconnect() or
|
||||
// getConnectedCount() confirms that the link actually closed.
|
||||
pServer->disconnect(last_conn_id);
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface: stalled TX disconnect requested");
|
||||
}
|
||||
|
||||
void SerialBLEInterface::recoverStalledTx(const char* cause) {
|
||||
if (_tx_disconnect_recovery.pending()) return;
|
||||
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface: %s; forcing reconnect", cause);
|
||||
|
||||
// Preserve the controller's physical state until the disconnect callback,
|
||||
// while the recovery state makes isConnected() false to callers.
|
||||
xQueueReset(recv_queue);
|
||||
notifySucceeded = false;
|
||||
send_queue_len = 0;
|
||||
_tx_stall_watchdog.reset();
|
||||
_tx_disconnect_recovery.begin();
|
||||
serviceTxRecovery((uint32_t)millis());
|
||||
}
|
||||
|
||||
void SerialBLEInterface::enable() {
|
||||
@@ -190,7 +256,7 @@ void SerialBLEInterface::enable() {
|
||||
//pServer->getAdvertising()->setMaxInterval(1000);
|
||||
|
||||
pServer->getAdvertising()->start();
|
||||
adv_restart_time = 0;
|
||||
_adv_restart_pending = false;
|
||||
}
|
||||
|
||||
void SerialBLEInterface::disable() {
|
||||
@@ -202,16 +268,18 @@ void SerialBLEInterface::disable() {
|
||||
pServer->disconnect(last_conn_id);
|
||||
pService->stop();
|
||||
oldDeviceConnected = deviceConnected = false;
|
||||
adv_restart_time = 0;
|
||||
clearBuffers();
|
||||
_adv_restart_pending = false;
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
|
||||
servicePendingTxReset();
|
||||
if (len > MAX_FRAME_SIZE) {
|
||||
BLE_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d", len);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (deviceConnected && len > 0) {
|
||||
if (isConnected() && len > 0) {
|
||||
if (!mesh::enqueueCompanionFrame(send_queue, send_queue_len, FRAME_QUEUE_SIZE,
|
||||
src, len)) {
|
||||
BLE_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
|
||||
@@ -229,22 +297,33 @@ bool SerialBLEInterface::isReadBusy() const {
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::isWriteBusy() const {
|
||||
return millis() < _last_write + BLE_WRITE_MIN_INTERVAL; // still too soon to start another write?
|
||||
return !mesh::bleElapsedAtLeast((uint32_t)millis(), _last_write,
|
||||
BLE_WRITE_MIN_INTERVAL);
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
const uint32_t now = (uint32_t)millis();
|
||||
servicePendingTxReset();
|
||||
if (_tx_disconnect_recovery.pending()) {
|
||||
serviceTxRecovery(now);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (send_queue_len > 0 // first, check send queue
|
||||
&& millis() >= _last_write + BLE_WRITE_MIN_INTERVAL // space the writes apart
|
||||
&& mesh::bleElapsedAtLeast(now, _last_write,
|
||||
BLE_WRITE_MIN_INTERVAL) // space the writes apart
|
||||
) {
|
||||
const uint16_t peer_mtu = pServer->getPeerMTU(last_conn_id);
|
||||
const bool notifications_ready = pTxDescriptor != NULL && pTxDescriptor->getNotifications();
|
||||
const bool frame_fits = peer_mtu > 3 && send_queue[0].len <= peer_mtu - 3;
|
||||
const bool delivery_required = mesh::companionFrameRequiresDelivery(
|
||||
send_queue[0].buf, send_queue[0].len);
|
||||
|
||||
// A fresh pairing can deliver the app's first command before its CCCD
|
||||
// subscription or MTU exchange completes. Keep the response queued until
|
||||
// both are ready instead of silently dropping/truncating device info.
|
||||
if (notifications_ready && frame_fits) {
|
||||
_last_write = millis();
|
||||
_last_write = now;
|
||||
notifySucceeded = false;
|
||||
pTxCharacteristic->setValue(send_queue[0].buf, send_queue[0].len);
|
||||
pTxCharacteristic->notify();
|
||||
@@ -256,8 +335,21 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
for (int i = 0; i < send_queue_len; i++) { // delete top item from queue
|
||||
send_queue[i] = send_queue[i + 1];
|
||||
}
|
||||
_tx_stall_watchdog.reset();
|
||||
} else if (delivery_required
|
||||
&& _tx_stall_watchdog.noteBlocked(now)) {
|
||||
recoverStalledTx("command reply notification blocked for 10 seconds");
|
||||
return 0;
|
||||
}
|
||||
} else if (delivery_required
|
||||
&& _tx_stall_watchdog.noteBlocked(now)) {
|
||||
recoverStalledTx("command reply waiting for notifications or MTU for 10 seconds");
|
||||
return 0;
|
||||
} else if (!delivery_required) {
|
||||
_tx_stall_watchdog.reset();
|
||||
}
|
||||
} else if (send_queue_len == 0) {
|
||||
_tx_stall_watchdog.reset();
|
||||
}
|
||||
|
||||
Frame frame;
|
||||
@@ -276,28 +368,35 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
//pServer->getAdvertising()->setMinInterval(500);
|
||||
//pServer->getAdvertising()->setMaxInterval(1000);
|
||||
|
||||
adv_restart_time = millis() + ADVERT_RESTART_DELAY;
|
||||
scheduleAdvertisingRestart(now);
|
||||
} else {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> stopping advertising");
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> connecting...");
|
||||
// connecting
|
||||
// do stuff here on connecting
|
||||
pServer->getAdvertising()->stop();
|
||||
adv_restart_time = 0;
|
||||
_adv_restart_pending = false;
|
||||
}
|
||||
oldDeviceConnected = deviceConnected;
|
||||
}
|
||||
|
||||
if (adv_restart_time && millis() >= adv_restart_time) {
|
||||
if (_adv_restart_pending &&
|
||||
mesh::bleElapsedAtLeast(now, _adv_restart_started,
|
||||
ADVERT_RESTART_DELAY)) {
|
||||
if (pServer->getConnectedCount() == 0) {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> re-starting advertising");
|
||||
pServer->getAdvertising()->start(); // re-Start advertising
|
||||
_adv_restart_pending = false;
|
||||
} else {
|
||||
// A disconnect can take longer than the normal restart delay. Keep the
|
||||
// restart armed instead of losing it while the controller still reports
|
||||
// the old connection.
|
||||
_adv_restart_started = now;
|
||||
}
|
||||
adv_restart_time = 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::isConnected() const {
|
||||
return deviceConnected; //pServer != NULL && pServer->getConnectedCount() > 0;
|
||||
return !_tx_disconnect_recovery.pending() && deviceConnected;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "../BaseSerialInterface.h"
|
||||
#include "../BleTxStallWatchdog.h"
|
||||
#include <BLEDevice.h>
|
||||
#include <BLEServer.h>
|
||||
#include <BLEUtils.h>
|
||||
@@ -20,8 +21,12 @@ class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLE
|
||||
bool _isEnabled;
|
||||
uint16_t last_conn_id;
|
||||
uint32_t _pin_code;
|
||||
unsigned long _last_write;
|
||||
unsigned long adv_restart_time;
|
||||
uint32_t _last_write;
|
||||
uint32_t _adv_restart_started;
|
||||
bool _adv_restart_pending;
|
||||
mesh::BleTxStallWatchdog _tx_stall_watchdog;
|
||||
mesh::BleDisconnectRecovery _tx_disconnect_recovery;
|
||||
std::atomic<bool> _tx_reset_pending{false};
|
||||
std::atomic<bool> _pairingRequestPending{false};
|
||||
|
||||
struct Frame {
|
||||
@@ -37,6 +42,10 @@ class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLE
|
||||
Frame send_queue[FRAME_QUEUE_SIZE];
|
||||
|
||||
void clearBuffers();
|
||||
void servicePendingTxReset();
|
||||
void scheduleAdvertisingRestart(uint32_t now);
|
||||
void recoverStalledTx(const char* cause);
|
||||
void serviceTxRecovery(uint32_t now);
|
||||
|
||||
protected:
|
||||
// BLESecurityCallbacks methods
|
||||
@@ -65,7 +74,8 @@ public:
|
||||
deviceConnected = false;
|
||||
oldDeviceConnected = false;
|
||||
notifySucceeded = false;
|
||||
adv_restart_time = 0;
|
||||
_adv_restart_started = 0;
|
||||
_adv_restart_pending = false;
|
||||
_isEnabled = false;
|
||||
_last_write = 0;
|
||||
last_conn_id = 0;
|
||||
|
||||
@@ -277,6 +277,8 @@ void SerialBLEInterface::clearBuffers() {
|
||||
send_queue_len = 0;
|
||||
recv_queue_len = 0;
|
||||
_last_retry_attempt = 0;
|
||||
_tx_stall_watchdog.reset();
|
||||
_tx_disconnect_recovery.complete();
|
||||
bleuart.flush();
|
||||
}
|
||||
|
||||
@@ -298,6 +300,80 @@ void SerialBLEInterface::shiftRecvQueueLeft() {
|
||||
}
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::writeBleUartFrame(const Frame& frame) {
|
||||
BLEConnection* conn = Bluefruit.Connection(_conn_handle);
|
||||
if (conn == nullptr || !conn->connected() ||
|
||||
!bleuart.notifyEnabled(_conn_handle)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const uint16_t mtu = conn->getMtu();
|
||||
if (mtu <= 3) return 0;
|
||||
|
||||
// BLEUart::write() reports either the full requested length or zero, even
|
||||
// when its internal multi-notification loop queued an earlier fragment
|
||||
// before a later fragment failed. Submit one ATT payload at a time so a
|
||||
// non-zero return accurately tells us that part of the protocol frame is
|
||||
// already on the stream and must never be followed by a whole-frame retry.
|
||||
return mesh::writeBleFrameInChunks(
|
||||
frame.buf, frame.len, mtu - 3,
|
||||
[this](const uint8_t* data, size_t len) {
|
||||
return bleuart.write(_conn_handle, data, len);
|
||||
});
|
||||
}
|
||||
|
||||
void SerialBLEInterface::serviceTxRecovery(uint32_t now) {
|
||||
if (!_tx_disconnect_recovery.pending()) return;
|
||||
|
||||
BLEConnection* conn = _conn_handle == BLE_CONN_HANDLE_INVALID
|
||||
? nullptr
|
||||
: Bluefruit.Connection(_conn_handle);
|
||||
if (_conn_handle == BLE_CONN_HANDLE_INVALID || conn == nullptr ||
|
||||
!conn->connected()) {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface: stalled TX link is already closed");
|
||||
_conn_handle = BLE_CONN_HANDLE_INVALID;
|
||||
_isDeviceConnected = false;
|
||||
_peer_address_valid = false;
|
||||
_security_timer.cancel();
|
||||
clearBuffers();
|
||||
if (_isEnabled && !isAdvertising()) {
|
||||
Bluefruit.Advertising.start(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_tx_disconnect_recovery.shouldAttempt(now)) return;
|
||||
|
||||
const uint32_t result = sd_ble_gap_disconnect(
|
||||
_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
|
||||
if (result == NRF_SUCCESS) {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface: stalled TX disconnect requested");
|
||||
} else if (result == NRF_ERROR_INVALID_STATE) {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface: stalled TX disconnect already in progress");
|
||||
} else {
|
||||
BLE_DEBUG_PRINTLN(
|
||||
"SerialBLEInterface: stalled TX disconnect failed, err=0x%08lX; will retry",
|
||||
(unsigned long)result);
|
||||
}
|
||||
}
|
||||
|
||||
void SerialBLEInterface::recoverStalledTx(const char* cause) {
|
||||
if (_tx_disconnect_recovery.pending()) return;
|
||||
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface: %s; forcing reconnect", cause);
|
||||
|
||||
// Keep the physical connection state intact until the SoftDevice confirms
|
||||
// disconnection, but make isConnected() false through the recovery state so
|
||||
// no more companion frames enter this damaged stream.
|
||||
send_queue_len = 0;
|
||||
recv_queue_len = 0;
|
||||
_last_retry_attempt = 0;
|
||||
_tx_stall_watchdog.reset();
|
||||
bleuart.flush();
|
||||
_tx_disconnect_recovery.begin();
|
||||
serviceTxRecovery((uint32_t)millis());
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::isValidConnection(uint16_t handle, bool requireWaitingForSecurity) const {
|
||||
if (_conn_handle != handle) {
|
||||
return false;
|
||||
@@ -365,38 +441,68 @@ size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
const uint32_t check_now = (uint32_t)millis();
|
||||
if (_tx_disconnect_recovery.pending()) {
|
||||
serviceTxRecovery(check_now);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (send_queue_len > 0) {
|
||||
if (!isConnected()) {
|
||||
BLE_DEBUG_PRINTLN("writeBytes: connection invalid, clearing send queue");
|
||||
send_queue_len = 0;
|
||||
_last_retry_attempt = 0;
|
||||
_tx_stall_watchdog.reset();
|
||||
} else {
|
||||
unsigned long now = millis();
|
||||
uint32_t now = check_now;
|
||||
bool throttle_active = (_last_retry_attempt > 0 && (now - _last_retry_attempt) < BLE_RETRY_THROTTLE_MS);
|
||||
|
||||
if (!throttle_active) {
|
||||
Frame frame_to_send = send_queue[0];
|
||||
const bool delivery_required = mesh::companionFrameRequiresDelivery(
|
||||
frame_to_send.buf, frame_to_send.len);
|
||||
|
||||
size_t written = bleuart.write(frame_to_send.buf, frame_to_send.len);
|
||||
size_t written = writeBleUartFrame(frame_to_send);
|
||||
if (written == frame_to_send.len) {
|
||||
BLE_DEBUG_PRINTLN("writeBytes: sz=%u, hdr=%u", (unsigned)frame_to_send.len, (unsigned)frame_to_send.buf[0]);
|
||||
_last_retry_attempt = 0;
|
||||
_tx_stall_watchdog.reset();
|
||||
shiftSendQueueLeft();
|
||||
} else if (written > 0) {
|
||||
BLE_DEBUG_PRINTLN("writeBytes: partial write, sent=%u of %u, dropping corrupted frame", (unsigned)written, (unsigned)frame_to_send.len);
|
||||
_last_retry_attempt = 0;
|
||||
shiftSendQueueLeft();
|
||||
BLE_DEBUG_PRINTLN("writeBytes: partial write, sent=%u of %u",
|
||||
(unsigned)written,
|
||||
(unsigned)frame_to_send.len);
|
||||
// The app cannot recover framing after receiving only part of one
|
||||
// protocol frame. Reconnect instead of following it with another
|
||||
// frame on the same BLE UART stream.
|
||||
recoverStalledTx("partial BLE UART frame");
|
||||
return 0;
|
||||
} else {
|
||||
if (!isConnected()) {
|
||||
BLE_DEBUG_PRINTLN("writeBytes failed: connection lost, dropping frame");
|
||||
_last_retry_attempt = 0;
|
||||
_tx_stall_watchdog.reset();
|
||||
shiftSendQueueLeft();
|
||||
} else {
|
||||
BLE_DEBUG_PRINTLN("writeBytes failed (buffer full), keeping frame for retry");
|
||||
_last_retry_attempt = now;
|
||||
if (delivery_required) {
|
||||
if (_tx_stall_watchdog.noteBlocked((uint32_t)now)) {
|
||||
recoverStalledTx("command reply blocked for 10 seconds");
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
// Best-effort pushes do not make an otherwise healthy but idle
|
||||
// app reconnect. A later response is inserted ahead of them and
|
||||
// starts its own bounded watchdog window.
|
||||
_tx_stall_watchdog.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_tx_stall_watchdog.reset();
|
||||
}
|
||||
|
||||
if (recv_queue_len > 0) {
|
||||
@@ -478,7 +584,8 @@ void SerialBLEInterface::onBleUartRX(uint16_t conn_handle) {
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::isConnected() const {
|
||||
return _isDeviceConnected && Bluefruit.connected() > 0;
|
||||
return !_tx_disconnect_recovery.pending() && _isDeviceConnected &&
|
||||
Bluefruit.connected() > 0;
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::isReadBusy() const {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "../BaseSerialInterface.h"
|
||||
#include "../BleTxStallWatchdog.h"
|
||||
#include "SecuritySessionTimer.h"
|
||||
#include <bluefruit.h>
|
||||
|
||||
@@ -20,6 +21,8 @@ class SerialBLEInterface : public BaseSerialInterface {
|
||||
bool _peer_address_valid;
|
||||
bool _bond_removed_for_connection;
|
||||
SecuritySessionTimer _security_timer;
|
||||
mesh::BleTxStallWatchdog _tx_stall_watchdog;
|
||||
mesh::BleDisconnectRecovery _tx_disconnect_recovery;
|
||||
|
||||
struct Frame {
|
||||
uint8_t len;
|
||||
@@ -37,6 +40,9 @@ class SerialBLEInterface : public BaseSerialInterface {
|
||||
void clearBuffers();
|
||||
void shiftSendQueueLeft();
|
||||
void shiftRecvQueueLeft();
|
||||
size_t writeBleUartFrame(const Frame& frame);
|
||||
void recoverStalledTx(const char* cause);
|
||||
void serviceTxRecovery(uint32_t now);
|
||||
bool removeStoredBondForPeer(const char* cause);
|
||||
bool isValidConnection(uint16_t handle, bool requireWaitingForSecurity = false) const;
|
||||
bool isAdvertising() const;
|
||||
|
||||
@@ -13,38 +13,61 @@ void merkle_combine(uint8_t out[4], const uint8_t* left, const uint8_t* right) {
|
||||
sha256_trunc2(out, 4, left, 4, right, 4);
|
||||
}
|
||||
|
||||
void MerkleAccumulator::reset() {
|
||||
memset(_peaks, 0, sizeof(_peaks));
|
||||
_valid_mask = 0;
|
||||
_count = 0;
|
||||
}
|
||||
|
||||
bool MerkleAccumulator::add(const uint8_t leaf[4]) {
|
||||
if (leaf == nullptr || _count == UINT32_MAX) return false;
|
||||
uint8_t current[4];
|
||||
memcpy(current, leaf, 4);
|
||||
uint8_t level = 0;
|
||||
while (level < 32 && (_valid_mask & ((uint32_t)1U << level)) != 0) {
|
||||
merkle_combine(current, _peaks[level], current);
|
||||
_valid_mask &= ~((uint32_t)1U << level);
|
||||
level++;
|
||||
}
|
||||
if (level >= 32) return false;
|
||||
memcpy(_peaks[level], current, 4);
|
||||
_valid_mask |= (uint32_t)1U << level;
|
||||
_count++;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MerkleAccumulator::finish(uint8_t out[4]) const {
|
||||
if (out == nullptr || _count == 0 || _valid_mask == 0) return false;
|
||||
uint8_t level = 0;
|
||||
while (level < 32
|
||||
&& (_valid_mask & ((uint32_t)1U << level)) == 0) {
|
||||
level++;
|
||||
}
|
||||
if (level >= 32) return false;
|
||||
uint8_t accumulated[4];
|
||||
memcpy(accumulated, _peaks[level], 4);
|
||||
for (uint8_t next = level + 1; next < 32; ++next) {
|
||||
if ((_valid_mask & ((uint32_t)1U << next)) != 0) {
|
||||
merkle_combine(accumulated, _peaks[next], accumulated);
|
||||
}
|
||||
}
|
||||
memcpy(out, accumulated, 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Root via binary-counter / Merkle-Mountain-Range with right-to-left bagging.
|
||||
// Equivalent to the level-by-level "pair adjacent, promote lone last (left||right)" reduction
|
||||
// (verified against the reference implementation across many counts in the native tests).
|
||||
void merkle_root(uint8_t out[4], const uint8_t* leaves, uint32_t count) {
|
||||
if (count == 0) { memset(out, 0, 4); return; }
|
||||
if (count == 1) { memcpy(out, leaves, 4); return; }
|
||||
|
||||
uint8_t peaks[32][4];
|
||||
bool valid[32] = { false };
|
||||
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
uint8_t cur[4];
|
||||
memcpy(cur, leaves + (size_t)i * 4, 4);
|
||||
uint32_t level = 0;
|
||||
while (valid[level]) { // carry: combine with the pending peak at this level
|
||||
merkle_combine(cur, peaks[level], cur); // peak is earlier (left), cur is right
|
||||
valid[level] = false;
|
||||
level++;
|
||||
if (count == 0 || leaves == nullptr) { memset(out, 0, 4); return; }
|
||||
MerkleAccumulator accumulator;
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
if (!accumulator.add(leaves + (size_t)i * 4)) {
|
||||
memset(out, 0, 4);
|
||||
return;
|
||||
}
|
||||
memcpy(peaks[level], cur, 4);
|
||||
valid[level] = true;
|
||||
}
|
||||
|
||||
// bag peaks right-to-left: acc starts at the lowest set level (rightmost peak)
|
||||
int level = 0;
|
||||
while (level < 32 && !valid[level]) level++;
|
||||
uint8_t acc[4];
|
||||
memcpy(acc, peaks[level], 4);
|
||||
for (int l = level + 1; l < 32; l++) {
|
||||
if (valid[l]) merkle_combine(acc, peaks[l], acc); // higher peak is left, acc is right
|
||||
}
|
||||
memcpy(out, acc, 4);
|
||||
if (!accumulator.finish(out)) memset(out, 0, 4);
|
||||
}
|
||||
|
||||
bool merkle_verify(const uint8_t* block, uint32_t block_len, uint32_t index,
|
||||
|
||||
@@ -15,6 +15,24 @@
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// O(log n) streaming root builder. It accepts leaves in index order and keeps
|
||||
// only one four-byte peak per tree level, so flash-backed verification never
|
||||
// needs a block_count*4 scratch buffer.
|
||||
class MerkleAccumulator {
|
||||
public:
|
||||
MerkleAccumulator() { reset(); }
|
||||
|
||||
void reset();
|
||||
bool add(const uint8_t leaf[4]);
|
||||
bool finish(uint8_t out[4]) const;
|
||||
uint32_t count() const { return _count; }
|
||||
|
||||
private:
|
||||
uint8_t _peaks[32][4];
|
||||
uint32_t _valid_mask;
|
||||
uint32_t _count;
|
||||
};
|
||||
|
||||
// leaf digest of one payload block
|
||||
void merkle_leaf(uint8_t out[4], const uint8_t* block, uint32_t block_len);
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ static char fstate_char(OtaManager::FetchState s) {
|
||||
case OtaManager::IDLE: return 'I';
|
||||
case OtaManager::WANT_MANIFEST: return 'W';
|
||||
case OtaManager::WANT_LEAVES: return 'L';
|
||||
case OtaManager::VERIFYING_STAGED: return 'V';
|
||||
case OtaManager::FETCHING: return 'F';
|
||||
case OtaManager::COMPLETE: return 'C';
|
||||
case OtaManager::PAUSED: return 'P';
|
||||
@@ -59,6 +60,7 @@ static const char* state_word(OtaManager::FetchState s) {
|
||||
case OtaManager::IDLE: return "idle";
|
||||
case OtaManager::WANT_MANIFEST: return "starting";
|
||||
case OtaManager::WANT_LEAVES: return "validating seed";
|
||||
case OtaManager::VERIFYING_STAGED: return "verifying staged blocks";
|
||||
case OtaManager::FETCHING: return "downloading";
|
||||
case OtaManager::COMPLETE: return "ready to install";
|
||||
case OtaManager::FAILED: return "failed";
|
||||
@@ -72,6 +74,7 @@ static const char* state_short(OtaManager::FetchState s) {
|
||||
switch (s) {
|
||||
case OtaManager::WANT_MANIFEST: return "manifest";
|
||||
case OtaManager::WANT_LEAVES: return "leaves";
|
||||
case OtaManager::VERIFYING_STAGED: return "verify";
|
||||
case OtaManager::FETCHING: return "dl";
|
||||
case OtaManager::COMPLETE: return "done";
|
||||
case OtaManager::FAILED: return "failed";
|
||||
|
||||
+111
-29
@@ -44,6 +44,8 @@ uint8_t* OtaManager::ensureScratch() {
|
||||
void OtaManager::begin(uint32_t my_target_id, OtaSend send, void* ctx) {
|
||||
_target = my_target_id; _send = send; _ctx = ctx;
|
||||
_fstate = IDLE; _have = 0; _fbc = 0;
|
||||
_resume_verify_idx = 0; _resume_invalidated = false;
|
||||
_resume_merkle.reset();
|
||||
_n_serve = 0; _n_src_obj = 0; _view0.valid = false; _srcv.valid = false;
|
||||
_n_src = 0; _n_cat = 0;
|
||||
}
|
||||
@@ -591,7 +593,9 @@ void OtaManager::deferCatalog(const uint8_t mid[4], uint32_t until_ms) {
|
||||
}
|
||||
|
||||
bool OtaManager::wantRow(const uint8_t* mid, uint32_t target, uint8_t codec, uint8_t flags) const {
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST || _fstate == PAUSED) return false; // busy
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST
|
||||
|| _fstate == WANT_LEAVES || _fstate == VERIFYING_STAGED
|
||||
|| _fstate == PAUSED) return false; // busy
|
||||
if (_fstate == COMPLETE && memcmp(mid, _fid, 4) == 0) return false; // already have it
|
||||
if (!_archive_fetch && !codecOk(codec)) return false; // can't apply this codec
|
||||
if (_have_desired_mid) // manual pull of a specific mid
|
||||
@@ -612,7 +616,9 @@ void OtaManager::clearReassembly() {
|
||||
// Begin (or resume) fetching a chosen mid: try a staged-partial resume first, else request the manifest.
|
||||
void OtaManager::startFetch(const uint8_t* mid, uint32_t target, bool validate) {
|
||||
(void)target;
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST || _fstate == WANT_LEAVES || _fstate == PAUSED) return;
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST
|
||||
|| _fstate == WANT_LEAVES || _fstate == VERIFYING_STAGED
|
||||
|| _fstate == PAUSED) return;
|
||||
_validate = validate; // motatool folder-capture warm-start (seed leaf-diff)
|
||||
// A validate pull is a FRESH seed capture, not a resume: the store already holds the seed's payload (not a
|
||||
// real partial), so never adopt it via resumeStaged - always re-begin and run the manifest->leaves->diff.
|
||||
@@ -777,14 +783,18 @@ void OtaManager::diffStep() {
|
||||
OTA_DBG("OTA: leaf-diff %u/%u already valid; fetching the rest\n", (unsigned)_have, (unsigned)_fbc);
|
||||
freeLeaves(); // clears _diffing + frees the buffer
|
||||
if (_have >= _fbc) { // seed covered the whole image
|
||||
_fstate = _fetch->finalize() ? COMPLETE : FAILED;
|
||||
_fstate = storedLeavesRootMatches() && _fetch->finalize()
|
||||
? COMPLETE : FAILED;
|
||||
return;
|
||||
}
|
||||
_fstate = FETCHING; requestMissing();
|
||||
}
|
||||
|
||||
bool OtaManager::resumeStaged(const uint8_t* want_mid) {
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST) return false;
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST
|
||||
|| _fstate == WANT_LEAVES || _fstate == VERIFYING_STAGED) {
|
||||
return false;
|
||||
}
|
||||
if (!_fetch->reopen()) return false; // nothing persisted in the store
|
||||
uint32_t total = _fetch->staged_size();
|
||||
uint8_t hdr[8];
|
||||
@@ -801,6 +811,7 @@ bool OtaManager::resumeStaged(const uint8_t* want_mid) {
|
||||
uint32_t bs = m.block_size();
|
||||
if (bs == 0 || bs > OTA_MAX_BLOCK) return false;
|
||||
uint32_t bc = m.block_count;
|
||||
if (bc == 0 || bc > 0xFFFFu) return false;
|
||||
if (_archive_fetch && (uint64_t)bc * 4 > OTA_PROOFGEN_SCRATCH) return false;
|
||||
uint32_t leaves_off = 8 + mfl;
|
||||
uint32_t payload_off = leaves_off + bc * 4;
|
||||
@@ -811,25 +822,11 @@ bool OtaManager::resumeStaged(const uint8_t* want_mid) {
|
||||
_fflags = m.flags;
|
||||
_fpoff = payload_off; _floff = leaves_off; _fpsize = m.payload_size; _fbc = bc; _fbs = bs;
|
||||
_ftotal = total;
|
||||
_have = 0;
|
||||
for (uint32_t i = 0; i < bc; i++) if (blockPresent(i)) _have++; // count blocks whose leaf survived
|
||||
clearReassembly();
|
||||
_loop_last_have = 0; _loop_last_mask = 0;
|
||||
OTA_DBG("OTA: RESUME have=%u/%u total=%u\n", (unsigned)_have, (unsigned)bc, (unsigned)total);
|
||||
|
||||
if (_have >= bc) { // already complete -> verify root + finalize
|
||||
uint8_t* scratch = bc * 4 <= OTA_PROOFGEN_SCRATCH ? ensureScratch() : nullptr;
|
||||
if (scratch && _fetch->read(_floff, scratch, bc * 4)) {
|
||||
uint8_t root[4]; merkle_root(root, scratch, bc);
|
||||
_fstate = (memcmp(root, _froot, 4) == 0) ? COMPLETE : FAILED;
|
||||
} else {
|
||||
_fstate = COMPLETE;
|
||||
}
|
||||
if (_fstate == COMPLETE && !_fetch->finalize()) _fstate = FAILED;
|
||||
return true;
|
||||
}
|
||||
_fstate = FETCHING; // resume fetching the holes
|
||||
_loop_last_have = _have; _loop_last_mask = _reasm_mask;
|
||||
beginStagedVerification();
|
||||
OTA_DBG("OTA: RESUME verifying %u blocks total=%u\n",
|
||||
(unsigned)bc, (unsigned)total);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -844,6 +841,92 @@ bool OtaManager::blockPresent(uint32_t i) const {
|
||||
return !(leaf[0]==0xFF && leaf[1]==0xFF && leaf[2]==0xFF && leaf[3]==0xFF);
|
||||
}
|
||||
|
||||
bool OtaManager::storedLeavesRootMatches() const {
|
||||
if (!_fetch || _fbc == 0) return false;
|
||||
MerkleAccumulator accumulator;
|
||||
for (uint32_t i = 0; i < _fbc; ++i) {
|
||||
uint8_t leaf[4];
|
||||
if (!_fetch->read(_floff + i * 4, leaf, sizeof(leaf))
|
||||
|| (leaf[0] == 0xFF && leaf[1] == 0xFF
|
||||
&& leaf[2] == 0xFF && leaf[3] == 0xFF)
|
||||
|| !accumulator.add(leaf)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
uint8_t root[4];
|
||||
return accumulator.finish(root) && memcmp(root, _froot, 4) == 0;
|
||||
}
|
||||
|
||||
void OtaManager::beginStagedVerification() {
|
||||
_have = 0;
|
||||
_resume_verify_idx = 0;
|
||||
_resume_invalidated = false;
|
||||
_resume_merkle.reset();
|
||||
_fstate = VERIFYING_STAGED;
|
||||
}
|
||||
|
||||
void OtaManager::verifyStagedStep() {
|
||||
if (_fstate != VERIFYING_STAGED || !_fetch) return;
|
||||
static const uint8_t missing_leaf[4] = {0xFF, 0xFF, 0xFF, 0xFF};
|
||||
|
||||
for (uint32_t checked = 0;
|
||||
checked < OTA_DIFF_BATCH && _resume_verify_idx < _fbc;
|
||||
++checked, ++_resume_verify_idx) {
|
||||
uint8_t stored_leaf[4];
|
||||
const uint32_t index = _resume_verify_idx;
|
||||
if (!_fetch->read(_floff + index * 4,
|
||||
stored_leaf, sizeof(stored_leaf))) {
|
||||
_fstate = FAILED;
|
||||
return;
|
||||
}
|
||||
if (memcmp(stored_leaf, missing_leaf, sizeof(stored_leaf)) == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const uint32_t length = blockLen(index);
|
||||
if (!_fetch->read(_fpoff + index * _fbs, _reasm_buf, length)) {
|
||||
_fstate = FAILED;
|
||||
return;
|
||||
}
|
||||
uint8_t computed_leaf[4];
|
||||
merkle_leaf(computed_leaf, _reasm_buf, length);
|
||||
if (memcmp(computed_leaf, stored_leaf, sizeof(stored_leaf)) != 0) {
|
||||
// Payload and marker disagree. Clear the marker so the normal fetch path
|
||||
// requests this block again; a stale marker must never bless bad bytes.
|
||||
if (!_fetch->write(_floff + index * 4,
|
||||
missing_leaf, sizeof(missing_leaf))) {
|
||||
_fstate = FAILED;
|
||||
return;
|
||||
}
|
||||
_resume_invalidated = true;
|
||||
continue;
|
||||
}
|
||||
if (!_resume_merkle.add(computed_leaf)) {
|
||||
_fstate = FAILED;
|
||||
return;
|
||||
}
|
||||
_have++;
|
||||
}
|
||||
|
||||
if (_resume_verify_idx < _fbc) return;
|
||||
clearReassembly();
|
||||
if (_resume_invalidated) _fetch->checkpoint();
|
||||
|
||||
if (_have == _fbc) {
|
||||
uint8_t root[4];
|
||||
_fstate = _resume_merkle.finish(root)
|
||||
&& memcmp(root, _froot, sizeof(root)) == 0
|
||||
&& _fetch->finalize()
|
||||
? COMPLETE : FAILED;
|
||||
} else {
|
||||
_fstate = FETCHING;
|
||||
_loop_last_have = _have;
|
||||
_loop_last_mask = 0;
|
||||
requestMissing();
|
||||
}
|
||||
_resume_merkle.reset();
|
||||
}
|
||||
|
||||
void OtaManager::handleData(const uint8_t* m, uint16_t n) {
|
||||
DataMsg dm;
|
||||
if (!decode_data(m, n, dm) || !_fetch) return;
|
||||
@@ -895,14 +978,9 @@ void OtaManager::handleProof(const uint8_t* m, uint16_t n) {
|
||||
// cadence is runtime-tunable via `ota config checkpoint <N>` (0 = never)
|
||||
if (_checkpoint_blocks && _have % _checkpoint_blocks == 0) _fetch->checkpoint();
|
||||
if (_have < _fbc) { requestMissing(); return; } // next block
|
||||
// all blocks present -> final root cross-check + finalize
|
||||
uint8_t* scratch = _fbc * 4 <= OTA_PROOFGEN_SCRATCH ? ensureScratch() : nullptr;
|
||||
if (scratch && _fetch->read(_floff, scratch, _fbc * 4)) {
|
||||
uint8_t root[4]; merkle_root(root, scratch, _fbc);
|
||||
_fstate = (memcmp(root, _froot, 4) == 0) ? COMPLETE : FAILED;
|
||||
} else {
|
||||
_fstate = COMPLETE; // per-block proofs already guaranteed integrity vs the root
|
||||
}
|
||||
// Every leaf must be readable and collectively match the manifest root.
|
||||
// A scratch allocation/read failure is an integrity failure, never success.
|
||||
_fstate = storedLeavesRootMatches() ? COMPLETE : FAILED;
|
||||
if (_fstate == COMPLETE && !_fetch->finalize()) _fstate = FAILED;
|
||||
OTA_DBG("OTA: transfer %s\n", _fstate == COMPLETE ? "COMPLETE" : "FAILED(integrity/storage)");
|
||||
}
|
||||
@@ -975,6 +1053,10 @@ void OtaManager::loop() {
|
||||
s.query_retry_at = _now_ms + OTA_CATALOG_RETRY_MS;
|
||||
}
|
||||
}
|
||||
if (_fstate == VERIFYING_STAGED) {
|
||||
verifyStagedStep();
|
||||
return;
|
||||
}
|
||||
if (_fstate == WANT_MANIFEST) {
|
||||
// Retry GET_MANIFEST ONLY when a tick passed with no new fragment - re-bursting every tick would congest
|
||||
// the link and burn the retry cap while fragments are still arriving (mirrors FETCHING + WANT_LEAVES).
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "OtaStore.h"
|
||||
#include "MotaContainer.h"
|
||||
#include "OtaSource.h"
|
||||
#include "MerkleTree.h"
|
||||
|
||||
// Transport-agnostic OTA session engine (docs/ota_protocol.md Section 5/Section 8). It SERVES a complete `.mota`
|
||||
// (answering GET_MANIFEST / REQ) and/or FETCHES one into an OtaStore (verifying every block against
|
||||
@@ -146,7 +147,10 @@ public:
|
||||
// PAUSED: a folder-destination write failed mid-transfer (the seeder link dropped). Progress is held on
|
||||
// the host; the manager stops requesting and does NOT fall back to RAM/flash. resumeStaged() (called on
|
||||
// reconnect) re-STATs the host file, recomputes which blocks are missing, and resumes.
|
||||
enum FetchState : uint8_t { IDLE, WANT_MANIFEST, WANT_LEAVES, FETCHING, COMPLETE, FAILED, PAUSED };
|
||||
enum FetchState : uint8_t {
|
||||
IDLE, WANT_MANIFEST, WANT_LEAVES, VERIFYING_STAGED, FETCHING,
|
||||
COMPLETE, FAILED, PAUSED
|
||||
};
|
||||
|
||||
// Sentinel for "no block" in the reassembly / peer-REQ / recently-served slots (a real block index is
|
||||
// a small uint16, so 0xFFFFFFFF is never valid).
|
||||
@@ -219,8 +223,9 @@ public:
|
||||
|
||||
// Resume a fetch from a container already persisted in the store (after a reboot). want_mid=nullptr
|
||||
// accepts whatever is staged; otherwise only resumes if the staged manifest_id matches. Re-parses the
|
||||
// stored manifest, recomputes geometry, counts present blocks, and continues FETCHING the holes (or goes
|
||||
// straight to COMPLETE if all blocks are present). Returns true if it adopted a staged container.
|
||||
// stored manifest, recomputes geometry, then incrementally rehashes every staged payload block before
|
||||
// continuing FETCHING the holes. A fully staged image also has to reproduce the manifest Merkle root
|
||||
// before it can become COMPLETE. Returns true if it adopted a staged container.
|
||||
bool resumeStaged(const uint8_t* want_mid);
|
||||
|
||||
// Manual cross-target override (decision: deliberate role switch, e.g. companion -> repeater on the
|
||||
@@ -314,6 +319,8 @@ public:
|
||||
_mf_total = 0; _mf_mask = 0; _mf_len = 0; _loop_last_mfmask = 0;
|
||||
freeLeaves(); _validate = false; _archive_fetch = false;
|
||||
_lv_retries = 0; _loop_last_lvmask = 0;
|
||||
_resume_verify_idx = 0; _resume_invalidated = false;
|
||||
_resume_merkle.reset();
|
||||
}
|
||||
|
||||
FetchState fetchState() const { return _fstate; }
|
||||
@@ -389,6 +396,9 @@ private:
|
||||
}
|
||||
void setDigest(uint8_t out[4]) const; // sha2-256:4 over our served mids
|
||||
bool blockPresent(uint32_t i) const;
|
||||
bool storedLeavesRootMatches() const;
|
||||
void beginStagedVerification();
|
||||
void verifyStagedStep();
|
||||
void requestMissing();
|
||||
uint32_t blockLen(uint32_t i) const;
|
||||
|
||||
@@ -423,6 +433,9 @@ private:
|
||||
uint8_t _froot[4] = {0};
|
||||
uint32_t _ftotal = 0, _fpoff = 0, _floff = 0, _fpsize = 0, _fbc = 0, _fbs = 0;
|
||||
uint32_t _have = 0;
|
||||
uint32_t _resume_verify_idx = 0;
|
||||
bool _resume_invalidated = false;
|
||||
MerkleAccumulator _resume_merkle;
|
||||
uint32_t _req_start = 0, _req_count = 0; // last block requested (per-block serial flow; telemetry)
|
||||
uint32_t _loop_last_have = 0; // for stall detection in loop()
|
||||
uint32_t _desired_target = 0; // manual cross-target override (0 = auto / own target)
|
||||
|
||||
Reference in new issue
Block a user