Files
firmware/src/meshUtils.cpp
James Rich 269b974e96 feat: populate MyNodeInfo.device_id on all platforms (#10995)
* feat: populate MyNodeInfo.device_id on all platforms

RP2040/RP2350 use the 64-bit pico unique board id, STM32WL the 96-bit
silicon UID, ESP32-S2 joins the existing OPTIONAL_UNIQUE_ID efuse branch,
and everything else (classic ESP32 in particular) falls back to a
deterministic factory-MAC-derived id, resolving the long-standing FIXME.
Portduino keeps the config-supplied id preferred and now uses the MAC
fallback when the config omits one.

No proto or persistence changes; the id is re-read from silicon each
boot and PhoneAPI still zeroes it for unauthenticated clients.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: declare zero_mac const to satisfy cppcheck

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: address review feedback on device_id derivation

Clear any disk-loaded device_id before the silicon derivation so a failed
read leaves it unset rather than stale (Copilot), and size the portduino
config copy with sizeof instead of a literal 16 (CodeRabbit).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: extract device_id generation into per-arch getDeviceId()

Per review feedback on #10995: move the platform-specific
MyNodeInfo.device_id derivation out of the #if/#elif ladder in
NodeDB.cpp into a getDeviceId() interface (target_specific.h)
implemented per-architecture alongside each platform's getMacAddr():

  - esp32:     efuse OPTIONAL_UNIQUE_ID (C3/S2/S3/C6); classic ESP32 -> MAC
  - nrf52:     FICR DEVICEID + DEVICEADDR
  - nrf54l15:  FICR->INFO.DEVICEID + DEVICEADDR (NRF_FICR-guarded, MAC fallback)
  - rp2xx0:    pico_get_unique_board_id()
  - stm32wl:   HAL_GetUIDw0/1/2()
  - portduino: config-supplied id preferred, else MAC

The shared MAC-derived fallback moves to meshUtils as
getMacAddrDeviceId(). NodeDB.cpp now zero-inits the field and makes a
single getDeviceId() call, dropping ~65 lines of platform boilerplate
plus the esp_efuse/pico/stm32 includes that came with it. No behavior
change: device_id is still re-read from silicon each boot and never
persisted.

Builds green: native-macos, tbeam, heltec-v3, rak4631, rak11310, rak3172.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: address review of device_id refactor

- getMacAddrDeviceId(): zero-init the mac[6] buffer. getMacAddr() can return
  without writing (e.g. Portduino with no MAC source), so the old uninitialized
  buffer let stack garbage pass the all-zeros guard and become device_id. The
  pre-refactor code relied on the zero-initialized static ourMacAddr; restore
  that guarantee.
- nrf54l15 getDeviceId(): drop the `#if defined(NRF_FICR)` guard and read FICR
  unconditionally (as the pre-refactor NodeDB code did). The guarded #else fell
  back to getMacAddr()'s hard-coded placeholder MAC, which would give every unit
  an identical device_id; a missing NRF_FICR should be a loud compile error.
- NodeDB.cpp: `#include "target_specific.h"` instead of hand-copied externs for
  getMacAddr/getDeviceId; retire the stale FIXME. Same for meshUtils.cpp (whose
  extern comment wrongly claimed the TU was Arduino-free).
- Delete the orphaned commented-out device_id hex-dump block in NodeDB.cpp.
- Trim/de-duplicate the getDeviceId contract comments (single-sourced in
  target_specific.h).

Builds green: native-macos, tbeam.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs: trim device_id comments to the repo's 1-2 line guideline

Addresses CodeRabbit review nitpick on #10995: shorten the getDeviceId()
(target_specific.h), getMacAddrDeviceId() (meshUtils.h), device-id refresh
(NodeDB.cpp), and nrf54l15 getDeviceId comments to two lines each, per the
"one or two lines maximum" coding guideline. Comment-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 16:28:25 -05:00

231 lines
7.0 KiB
C++

#include "meshUtils.h"
#include "target_specific.h"
#include <string.h>
/*
* Find the first occurrence of find in s, where the search is limited to the
* first slen characters of s.
* -
* Copyright (c) 2001 Mike Barcroft <mike@FreeBSD.org>
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
char *strnstr(const char *s, const char *find, size_t slen)
{
char c;
if ((c = *find++) != '\0') {
char sc;
size_t len;
len = strlen(find);
do {
do {
if (slen-- < 1 || (sc = *s++) == '\0')
return (NULL);
} while (sc != c);
if (len > slen)
return (NULL);
} while (strncmp(s, find, len) != 0);
s--;
}
return ((char *)s);
}
void printBytes(const char *label, const uint8_t *p, size_t numbytes)
{
int labelSize = strlen(label);
char *messageBuffer = new char[labelSize + (numbytes * 3) + 2];
strncpy(messageBuffer, label, labelSize);
for (size_t i = 0; i < numbytes; i++)
snprintf(messageBuffer + labelSize + i * 3, 4, " %02x", p[i]);
strcpy(messageBuffer + labelSize + numbytes * 3, "\n");
LOG_DEBUG(messageBuffer);
delete[] messageBuffer;
}
bool memfll(const uint8_t *mem, uint8_t find, size_t numbytes)
{
for (uint8_t i = 0; i < numbytes; i++) {
if (mem[i] != find)
return false;
}
return true;
}
bool getMacAddrDeviceId(uint8_t *deviceId)
{
// Zero-initialized: getMacAddr() may return without writing (e.g. Portduino with no MAC
// source), and we want that no-write case to hit the all-zeros guard below, not read garbage.
uint8_t mac[6] = {0};
getMacAddr(mac);
if (memfll(mac, 0, sizeof(mac))) {
LOG_WARN("MAC is all zeros, leaving device_id unset");
return false;
}
memcpy(deviceId, mac, sizeof(mac));
return true;
}
bool isOneOf(int item, int count, ...)
{
va_list args;
va_start(args, count);
bool found = false;
for (int i = 0; i < count; ++i) {
if (item == va_arg(args, int)) {
found = true;
break;
}
}
va_end(args);
return found;
}
const std::string vformat(const char *const zcFormat, ...)
{
va_list vaArgs;
va_start(vaArgs, zcFormat);
va_list vaArgsCopy;
va_copy(vaArgsCopy, vaArgs);
const int iLen = std::vsnprintf(NULL, 0, zcFormat, vaArgsCopy);
va_end(vaArgsCopy);
std::vector<char> zc(iLen + 1);
std::vsnprintf(zc.data(), zc.size(), zcFormat, vaArgs);
va_end(vaArgs);
return std::string(zc.data(), iLen);
}
size_t pb_string_length(const char *str, size_t max_len)
{
size_t len = 0;
for (size_t i = 0; i < max_len; i++) {
if (str[i] != '\0') {
len = i + 1;
}
}
return len;
}
bool sanitizeUtf8(char *buf, size_t bufSize)
{
if (!buf || bufSize == 0)
return false;
// Ensure null-terminated within buffer; report if we had to enforce it
bool replaced = (buf[bufSize - 1] != '\0');
buf[bufSize - 1] = '\0';
size_t i = 0;
size_t len = strlen(buf);
while (i < len) {
uint8_t b = (uint8_t)buf[i];
// Determine expected sequence length from lead byte
size_t seqLen;
uint32_t minCodepoint;
if (b <= 0x7F) {
// ASCII - valid single byte
i++;
continue;
} else if ((b & 0xE0) == 0xC0) {
seqLen = 2;
minCodepoint = 0x80; // Reject overlong
} else if ((b & 0xF0) == 0xE0) {
seqLen = 3;
minCodepoint = 0x800;
} else if ((b & 0xF8) == 0xF0) {
seqLen = 4;
minCodepoint = 0x10000;
} else {
// Invalid lead byte (0x80-0xBF or 0xF8+)
buf[i] = '?';
replaced = true;
i++;
continue;
}
// Check that we have enough bytes remaining
if (i + seqLen > len) {
// Truncated sequence at end of string - replace remaining bytes
for (size_t j = i; j < len; j++) {
buf[j] = '?';
}
replaced = true;
break;
}
// Validate continuation bytes (must be 10xxxxxx)
bool valid = true;
for (size_t j = 1; j < seqLen; j++) {
if (((uint8_t)buf[i + j] & 0xC0) != 0x80) {
valid = false;
break;
}
}
if (valid) {
// Decode codepoint to check for overlong encodings and surrogates
uint32_t cp = 0;
if (seqLen == 2)
cp = b & 0x1F;
else if (seqLen == 3)
cp = b & 0x0F;
else
cp = b & 0x07;
for (size_t j = 1; j < seqLen; j++)
cp = (cp << 6) | ((uint8_t)buf[i + j] & 0x3F);
if (cp < minCodepoint || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) {
// Overlong encoding, out of Unicode range, or surrogate half
valid = false;
}
}
if (valid) {
i += seqLen;
} else {
// Replace only the lead byte; continuation bytes will be caught on next iteration
buf[i] = '?';
replaced = true;
i++;
}
}
return replaced;
}
void clampLongName(char *longName)
{
longName[MAX_LONG_NAME_BYTES] = '\0';
sanitizeUtf8(longName, MAX_LONG_NAME_BYTES + 1);
}