Harden nRF52 contact and settings persistence
This commit is contained in:
1 parent
249c3680b3
commit
2ce59b58ed
23 files changed
+11024
-383
No files matched your search
@@ -226,7 +226,10 @@ size_t ArduinoSerialInterface::writeFrame(const uint8_t src[], size_t len) {
|
||||
if (_passthroughMode) return len;
|
||||
if (_flow_ctl) {
|
||||
if (!isConnected()) {
|
||||
return len; // nobody is listening, drop instead of filling the TX buffer
|
||||
// Best-effort pushes may be discarded while nobody is listening. A
|
||||
// command response or required push must report failure so a multi-frame
|
||||
// producer can retry it without silently skipping an item.
|
||||
return mesh::companionFrameRequiresDelivery(src, len) ? 0 : len;
|
||||
}
|
||||
if (!enqueueFrame(src, len)) return 0;
|
||||
serviceTransmit();
|
||||
|
||||
@@ -129,7 +129,9 @@ ContactInfo* BaseChatMesh::allocateContactSlot(bool transient_only) {
|
||||
#else
|
||||
if (num_contacts < MAX_ANON_CONTACTS+MAX_CONTACTS) {
|
||||
#endif
|
||||
return &contacts[num_contacts++];
|
||||
ContactInfo* allocated = &contacts[num_contacts++];
|
||||
contact_table_revision++;
|
||||
return allocated;
|
||||
} else if (shouldOverwriteWhenFull()) {
|
||||
// Find oldest non-favourite contact by oldest lastmod timestamp
|
||||
for (int i = MAX_ANON_CONTACTS; i < num_contacts; i++) {
|
||||
@@ -140,7 +142,10 @@ ContactInfo* BaseChatMesh::allocateContactSlot(bool transient_only) {
|
||||
}
|
||||
}
|
||||
if (oldest_idx >= 0) {
|
||||
onContactOverwrite(contacts[oldest_idx].id.pub_key);
|
||||
if (!onContactOverwrite(contacts[oldest_idx])) {
|
||||
return NULL;
|
||||
}
|
||||
contact_table_revision++;
|
||||
return &contacts[oldest_idx];
|
||||
}
|
||||
}
|
||||
@@ -171,6 +176,11 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
|
||||
MESH_DEBUG_PRINTLN("onAdvertRecv: invalid app_data, or name is missing: len=%d", app_data_len);
|
||||
return;
|
||||
}
|
||||
if (!canMutateContacts()) {
|
||||
MESH_DEBUG_PRINTLN(
|
||||
"onAdvertRecv: contact store incomplete; ignoring contact mutation");
|
||||
return;
|
||||
}
|
||||
|
||||
ContactInfo* from = NULL;
|
||||
for (int i = 0; i < num_contacts; i++) {
|
||||
@@ -287,7 +297,9 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
|
||||
data[len] = 0; // need to make a C string again, with null terminator
|
||||
|
||||
if (flags == TXT_TYPE_PLAIN) {
|
||||
from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time
|
||||
if (canMutateContacts()) {
|
||||
from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time
|
||||
}
|
||||
onMessageRecv(from, packet, sender_timestamp, (const char *) &data[5]); // let UI know
|
||||
|
||||
int text_len = strlen((char *)&data[5]);
|
||||
@@ -345,10 +357,12 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
|
||||
}
|
||||
}
|
||||
} else if (flags == TXT_TYPE_SIGNED_PLAIN) {
|
||||
if (sender_timestamp > from.sync_since) { // make sure 'sync_since' is up-to-date
|
||||
from.sync_since = sender_timestamp;
|
||||
if (canMutateContacts()) {
|
||||
if (sender_timestamp > from.sync_since) { // make sure 'sync_since' is up-to-date
|
||||
from.sync_since = sender_timestamp;
|
||||
}
|
||||
from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time
|
||||
}
|
||||
from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time
|
||||
onSignedMessageRecv(from, packet, sender_timestamp, &data[5], (const char *) &data[9]); // let UI know
|
||||
|
||||
uint32_t ack_hash; // calc truncated hash of the message timestamp + text + OUR pub_key, to prove to sender that we got it
|
||||
@@ -410,10 +424,12 @@ bool BaseChatMesh::onPeerPathRecv(mesh::Packet* packet, int sender_idx, const ui
|
||||
bool BaseChatMesh::onContactPathRecv(ContactInfo& from, uint8_t* in_path, uint8_t in_path_len, uint8_t* out_path, uint8_t out_path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) {
|
||||
// NOTE: default impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path.
|
||||
// FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?)
|
||||
from.out_path_len = mesh::Packet::copyPath(from.out_path, out_path, out_path_len); // store a copy of path, for sendDirect()
|
||||
from.lastmod = getRTCClock()->getCurrentTime();
|
||||
if (canMutateContacts()) {
|
||||
from.out_path_len = mesh::Packet::copyPath(from.out_path, out_path, out_path_len); // store a copy of path, for sendDirect()
|
||||
from.lastmod = getRTCClock()->getCurrentTime();
|
||||
|
||||
onContactPathUpdated(from);
|
||||
onContactPathUpdated(from);
|
||||
}
|
||||
|
||||
if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
|
||||
// also got an encoded ACK!
|
||||
@@ -992,6 +1008,38 @@ ContactInfo* BaseChatMesh::lookupContactByPubKey(const uint8_t* pub_key, int pre
|
||||
return NULL; // not found
|
||||
}
|
||||
|
||||
ContactInfo* BaseChatMesh::lookupTransientContactByPubKey(const uint8_t* pub_key, int prefix_len) {
|
||||
for (int i = 0; i < MAX_ANON_CONTACTS; i++) {
|
||||
auto c = &contacts[i];
|
||||
if (memcmp(c->id.pub_key, pub_key, prefix_len) == 0) return c;
|
||||
}
|
||||
return NULL; // not found
|
||||
}
|
||||
|
||||
ContactInfo* BaseChatMesh::lookupPersistentContactByPubKey(const uint8_t* pub_key, int prefix_len) {
|
||||
for (int i = MAX_ANON_CONTACTS; i < num_contacts; i++) {
|
||||
auto c = &contacts[i];
|
||||
if (memcmp(c->id.pub_key, pub_key, prefix_len) == 0) return c;
|
||||
}
|
||||
return NULL; // not found
|
||||
}
|
||||
|
||||
bool BaseChatMesh::isTransientContact(const ContactInfo& contact) const {
|
||||
for (int i = 0; i < MAX_ANON_CONTACTS; i++) {
|
||||
if (&contacts[i] == &contact) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool BaseChatMesh::clearTransientContact(ContactInfo& contact) {
|
||||
if (!isTransientContact(contact)) return false;
|
||||
memset(&contact, 0, sizeof(contact));
|
||||
#if defined(NRF52_PLATFORM)
|
||||
contact.storage_slot = mesh::storage::CONTACT_SLOT_NONE;
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BaseChatMesh::addContact(const ContactInfo& contact) {
|
||||
ContactInfo* dest = allocateContactSlot(contact.type == ADV_TYPE_NONE);
|
||||
if (dest) {
|
||||
@@ -1003,8 +1051,10 @@ bool BaseChatMesh::addContact(const ContactInfo& contact) {
|
||||
}
|
||||
|
||||
bool BaseChatMesh::removeContact(ContactInfo& contact) {
|
||||
int idx = 0;
|
||||
while (idx < num_contacts && !contacts[idx].id.matches(contact.id)) {
|
||||
// removeContact() is for stored contacts only. Match the exact live object so
|
||||
// duplicate keys cannot remove a transient prefix slot or a different record.
|
||||
int idx = MAX_ANON_CONTACTS;
|
||||
while (idx < num_contacts && &contacts[idx] != &contact) {
|
||||
idx++;
|
||||
}
|
||||
if (idx >= num_contacts) return false; // not found
|
||||
@@ -1015,6 +1065,7 @@ bool BaseChatMesh::removeContact(ContactInfo& contact) {
|
||||
contacts[idx] = contacts[idx + 1];
|
||||
idx++;
|
||||
}
|
||||
contact_table_revision++;
|
||||
return true; // Success
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ class BaseChatMesh : public mesh::Mesh {
|
||||
int sort_array[MAX_CONTACTS+MAX_ANON_CONTACTS];
|
||||
#endif
|
||||
int num_contacts;
|
||||
uint32_t contact_table_revision;
|
||||
int matching_peer_indexes[MAX_SEARCH_RESULTS];
|
||||
unsigned long txt_send_timeout;
|
||||
#ifdef MAX_GROUP_CHANNELS
|
||||
@@ -107,6 +108,7 @@ protected:
|
||||
sort_array = sort_array_fallback;
|
||||
contact_capacity = CONTACT_PSRAM_FALLBACK_TOTAL_SLOTS;
|
||||
#endif
|
||||
contact_table_revision = 0;
|
||||
resetContacts();
|
||||
|
||||
#ifdef MAX_GROUP_CHANNELS
|
||||
@@ -129,6 +131,7 @@ protected:
|
||||
}
|
||||
#endif
|
||||
num_contacts = MAX_ANON_CONTACTS; // seed the first contacts for anon requests
|
||||
contact_table_revision++;
|
||||
}
|
||||
void populateContactFromAdvert(ContactInfo& ci, const mesh::Identity& id, const AdvertDataParser& parser, uint32_t timestamp);
|
||||
ContactInfo* allocateContactSlot(bool transient_only=false); // helper to find slot for new contact
|
||||
@@ -139,7 +142,11 @@ protected:
|
||||
virtual void onContactsFull() {};
|
||||
virtual bool shouldOverwriteWhenFull() const { return false; }
|
||||
virtual uint8_t getAutoAddMaxHops() const { return 0; } // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops
|
||||
virtual void onContactOverwrite(const uint8_t* pub_key) {};
|
||||
virtual bool canMutateContacts() const { return true; }
|
||||
// Return false to preserve the exact selected contact when a subclass cannot
|
||||
// safely retire its associated persistent state. A refusal must not mutate
|
||||
// the contact or its backing state.
|
||||
virtual bool onContactOverwrite(const ContactInfo&) { return true; };
|
||||
virtual void onDiscoveredContact(ContactInfo& contact, bool is_new, uint8_t path_len, const uint8_t* path) = 0;
|
||||
virtual ContactInfo* processAck(const uint8_t *data) = 0;
|
||||
virtual void onContactPathUpdated(const ContactInfo& contact) = 0;
|
||||
@@ -209,10 +216,15 @@ public:
|
||||
void scanRecentContacts(int last_n, ContactVisitor* visitor);
|
||||
ContactInfo* searchContactsByPrefix(const char* name_prefix);
|
||||
ContactInfo* lookupContactByPubKey(const uint8_t* pub_key, int prefix_len);
|
||||
ContactInfo* lookupTransientContactByPubKey(const uint8_t* pub_key, int prefix_len);
|
||||
ContactInfo* lookupPersistentContactByPubKey(const uint8_t* pub_key, int prefix_len);
|
||||
bool isTransientContact(const ContactInfo& contact) const;
|
||||
bool clearTransientContact(ContactInfo& contact);
|
||||
bool removeContact(ContactInfo& contact);
|
||||
bool addContact(const ContactInfo& contact);
|
||||
int getTotalContactSlots() const { return num_contacts; }
|
||||
int getNumContacts() const { return num_contacts - MAX_ANON_CONTACTS; } // don't include the reserved slots at start
|
||||
uint32_t getContactTableRevision() const { return contact_table_revision; }
|
||||
bool getContactByIdx(uint32_t idx, ContactInfo& contact);
|
||||
ContactInfo* getContactPtrByIdx(uint32_t idx) {
|
||||
return idx < (uint32_t)num_contacts ? &contacts[idx] : NULL;
|
||||
|
||||
@@ -22,6 +22,10 @@ static const uint16_t CONTACT_SLOT_NONE = 0xFFFF;
|
||||
static const uint8_t CONTACT_PAGE_VERSION = 1;
|
||||
static const uint8_t CONTACT_PAGE_MAGIC[4] = {'M', 'C', 'P', '4'};
|
||||
|
||||
inline uint32_t contactPageValidSlotMask() {
|
||||
return (1UL << CONTACTS_PER_PAGE) - 1UL;
|
||||
}
|
||||
|
||||
struct ContactPageHeader {
|
||||
uint8_t page_index;
|
||||
uint32_t occupied;
|
||||
@@ -35,6 +39,22 @@ enum class ContactStoreSource : uint8_t {
|
||||
PAGED,
|
||||
};
|
||||
|
||||
enum class ContactPathState : uint8_t {
|
||||
ABSENT,
|
||||
PRESENT,
|
||||
IO_ERROR,
|
||||
};
|
||||
|
||||
// Adafruit_LittleFS::exists() collapses every lfs_stat() error into false.
|
||||
// Keep the raw result distinguishable so a transient media error can never be
|
||||
// treated as proof that an authoritative stored source or journal is absent.
|
||||
inline ContactPathState classifyContactPathStat(int result,
|
||||
int no_entry_result) {
|
||||
if (result == 0) return ContactPathState::PRESENT;
|
||||
if (result == no_entry_result) return ContactPathState::ABSENT;
|
||||
return ContactPathState::IO_ERROR;
|
||||
}
|
||||
|
||||
// A retained legacy file means migration is still in progress. Its complete
|
||||
// record count is the authoritative prefix boundary; page records at or above
|
||||
// that boundary have already committed.
|
||||
@@ -59,6 +79,12 @@ inline uint16_t legacyContactCountForSize(size_t file_size) {
|
||||
return (uint16_t)(count < capacity ? count : capacity);
|
||||
}
|
||||
|
||||
inline bool isValidLegacyContactFileSize(size_t file_size) {
|
||||
const size_t capacity = CONTACT_PAGE_COUNT * CONTACTS_PER_PAGE;
|
||||
return file_size % CONTACT_RECORD_SIZE == 0
|
||||
&& file_size <= capacity * CONTACT_RECORD_SIZE;
|
||||
}
|
||||
|
||||
inline uint8_t legacyMigrationPage(uint16_t legacy_contact_count) {
|
||||
return legacy_contact_count == 0 ? CONTACT_PAGE_COUNT
|
||||
: (uint8_t)((legacy_contact_count - 1) / CONTACTS_PER_PAGE);
|
||||
@@ -112,6 +138,13 @@ inline uint32_t updateCRC32(uint32_t crc, const uint8_t* data, size_t len) {
|
||||
return crc;
|
||||
}
|
||||
|
||||
inline bool contactRecordHasData(
|
||||
const uint8_t record[CONTACT_RECORD_SIZE]) {
|
||||
uint8_t combined = 0;
|
||||
for (uint16_t i = 0; i < CONTACT_RECORD_SIZE; i++) combined |= record[i];
|
||||
return combined != 0;
|
||||
}
|
||||
|
||||
inline void encodeContactPageHeader(uint8_t dest[CONTACT_PAGE_HEADER_SIZE],
|
||||
const ContactPageHeader& header) {
|
||||
memcpy(dest, CONTACT_PAGE_MAGIC, sizeof(CONTACT_PAGE_MAGIC));
|
||||
@@ -126,7 +159,6 @@ inline void encodeContactPageHeader(uint8_t dest[CONTACT_PAGE_HEADER_SIZE],
|
||||
inline bool decodeContactPageHeader(const uint8_t src[CONTACT_PAGE_HEADER_SIZE],
|
||||
uint8_t expected_page,
|
||||
ContactPageHeader& header) {
|
||||
const uint32_t valid_slots = (1UL << CONTACTS_PER_PAGE) - 1UL;
|
||||
if (memcmp(src, CONTACT_PAGE_MAGIC, sizeof(CONTACT_PAGE_MAGIC)) != 0
|
||||
|| src[4] != CONTACT_PAGE_VERSION || src[5] != expected_page
|
||||
|| readLE16(&src[6]) != CONTACT_RECORD_SIZE) {
|
||||
@@ -137,7 +169,10 @@ inline bool decodeContactPageHeader(const uint8_t src[CONTACT_PAGE_HEADER_SIZE],
|
||||
header.occupied = readLE32(&src[8]);
|
||||
header.generation = readLE32(&src[12]);
|
||||
header.payload_crc = readLE32(&src[16]);
|
||||
return (header.occupied & ~valid_slots) == 0;
|
||||
// Occupancy is repairable from the CRC-protected record payload. Keep the
|
||||
// header parseable even when an unused high bit was upset so load can retain
|
||||
// the page's contacts and rewrite the corrected mask.
|
||||
return true;
|
||||
}
|
||||
|
||||
class DirtyPageSet {
|
||||
|
||||
@@ -20,6 +20,21 @@ inline bool isInternalExtraFsReservedByApplication(uint32_t application_end) {
|
||||
return application_end <= INTERNAL_EXTRAFS_START;
|
||||
}
|
||||
|
||||
// Read flash through an injected word reader so the erased-media decision can
|
||||
// be covered by native tests. Refuse malformed/empty ranges: only a complete,
|
||||
// word-aligned scan can authorize a boot-time format.
|
||||
template <typename ReadWord>
|
||||
bool isErasedFlashRange(uint32_t start, uint32_t size, ReadWord read_word) {
|
||||
if (size == 0 || (start % sizeof(uint32_t)) != 0
|
||||
|| (size % sizeof(uint32_t)) != 0) {
|
||||
return false;
|
||||
}
|
||||
for (uint32_t offset = 0; offset < size; offset += sizeof(uint32_t)) {
|
||||
if (read_word(start + offset) != 0xFFFFFFFFUL) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
enum class InternalSecondaryFsBootResult {
|
||||
Mounted,
|
||||
InitializedBlank,
|
||||
|
||||
Reference in new issue
Block a user