Allow local CLI maintenance across direct connections

This commit is contained in:
mikecarper committed 2026-09-08 21:44:57 -07:00
1 parent 001b4985f7
commit 06c51fdef5
39 files changed
+3338 -2312

No files matched your search

+19 -1
View File
@@ -4301,6 +4301,24 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* reply) {
const char* config = &command[4];
if (strcmp(config, "password") == 0) {
if (sender_timestamp == 0) {
snprintf(reply, 160, "> %s", _prefs->password);
} else {
strcpy(reply, "Error: get password requires a local connection");
}
return;
}
#if defined(ESP_PLATFORM) && defined(ADMIN_PASSWORD) && !defined(WEBCONFIG_DISABLED) && !defined(WITH_MQTT_BRIDGE)
if (strcmp(config, "wifi.pwd") == 0) {
if (sender_timestamp != 0) {
strcpy(reply, "> ******** (local connection only)");
} else if (!_callbacks->getWiFiPassword(reply)) {
strcpy(reply, "Error: WiFi password unavailable on this build");
}
return;
}
#endif
if (strcmp(config, "powersaving") == 0) {
snprintf(reply, 160, "> %s", _prefs->powersaving_enabled ? "on" : "off");
return;
@@ -4444,7 +4462,7 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
sprintf(reply, "> %d", ((uint32_t) _prefs->advert_interval) * 2);
} else if (configKeyEquals(config, "guest.password")) {
sprintf(reply, "> %s", _prefs->guest_password);
} else if (sender_timestamp == 0 && configKeyEquals(config, "prv.key")) { // from serial command line only
} else if (sender_timestamp == 0 && configKeyEquals(config, "prv.key")) { // local connections only
uint8_t prv_key[PRV_KEY_SIZE];
int len = _callbacks->getSelfId().writeTo(prv_key, PRV_KEY_SIZE);
mesh::Utils::toHex(tmp, prv_key, len);
+4
View File
@@ -598,6 +598,10 @@ public:
(void)reply;
return false;
};
virtual bool getWiFiPassword(char* reply) const {
(void)reply;
return false;
};
virtual bool getWiFiStatus(char* reply) const {
(void)reply;
return false;
+7 -7
View File
@@ -988,20 +988,20 @@ bool CommonCLI::handleObserverGetCmd(uint32_t sender_timestamp, const char* conf
} else if (memcmp(subcmd, "username", 8) == 0) {
sprintf(reply, "> %s", _mqtt_prefs.mqtt_slot_username[slot]);
} else if (memcmp(subcmd, "password", 8) == 0) {
// Serial only; remote sees set/unset.
// Local connections only; remote sees set/unset.
if (sender_timestamp == 0) {
sprintf(reply, "> %s", _mqtt_prefs.mqtt_slot_password[slot]);
} else {
strcpy(reply, _mqtt_prefs.mqtt_slot_password[slot][0] ? "> ******** (serial only)" : "> (not set)");
strcpy(reply, _mqtt_prefs.mqtt_slot_password[slot][0] ? "> ******** (local connection only)" : "> (not set)");
}
} else if (memcmp(subcmd, "token", 5) == 0) {
// Serial only; remote sees set/unset.
// Local connections only; remote sees set/unset.
if (_mqtt_prefs.mqtt_slot_token[slot][0] == '\0') {
strcpy(reply, "> (not set)");
} else if (sender_timestamp == 0) {
sprintf(reply, "> %s", _mqtt_prefs.mqtt_slot_token[slot]);
} else {
strcpy(reply, "> ******** (serial only)");
strcpy(reply, "> ******** (local connection only)");
}
} else if (memcmp(subcmd, "topic", 5) == 0) {
if (_mqtt_prefs.mqtt_slot_topic[slot][0] != '\0') {
@@ -1031,11 +1031,11 @@ bool CommonCLI::handleObserverGetCmd(uint32_t sender_timestamp, const char* conf
} else if (memcmp(config, "wifi.ssid", 9) == 0) {
sprintf(reply, "> %s", _mqtt_prefs.wifi_ssid);
} else if (memcmp(config, "wifi.pwd", 8) == 0) {
// Serial only (WiFi creds grant LAN access); remote sees set/unset.
// Local connections only (WiFi creds grant LAN access); remote sees set/unset.
if (sender_timestamp == 0) {
sprintf(reply, "> %s", _mqtt_prefs.wifi_password);
} else {
strcpy(reply, _mqtt_prefs.wifi_password[0] ? "> ******** (serial only)" : "> (not set)");
strcpy(reply, _mqtt_prefs.wifi_password[0] ? "> ******** (local connection only)" : "> (not set)");
}
} else if (memcmp(config, "wifi.status", 11) == 0) {
wl_status_t status = WiFi.status();
@@ -1135,7 +1135,7 @@ bool CommonCLI::handleObserverGetCmd(uint32_t sender_timestamp, const char* conf
#endif
} else if (memcmp(config, "alert.hashtag", 13) == 0) {
sprintf(reply, "> %s", _mqtt_prefs.alert_hashtag[0] ? _mqtt_prefs.alert_hashtag : "(unset)");
} else if (sender_timestamp == 0 && memcmp(config, "alert.psk", 9) == 0) { // from serial command line only
} else if (sender_timestamp == 0 && memcmp(config, "alert.psk", 9) == 0) { // local connections only
sprintf(reply, "> %s", _mqtt_prefs.alert_psk_hex[0] ? _mqtt_prefs.alert_psk_hex : "(unset)");
} else if (memcmp(config, "alert.region", 12) == 0) {
sprintf(reply, "> %s", _mqtt_prefs.alert_region[0] ? _mqtt_prefs.alert_region : "(unset, using default scope)");
+89
View File
@@ -0,0 +1,89 @@
#pragma once
#include <Arduino.h>
#include <string.h>
namespace mesh {
// A local listing belongs to its requesting connection. Advance one bounded
// chunk per mesh loop and retain unwritten bytes when the client is slow.
template<class FileHandle> class LocalCliOutput {
public:
using RowReader = size_t (*)(void*, size_t&, char*, size_t);
private:
Stream* _output = nullptr;
FileHandle _file;
size_t _remaining = 0;
RowReader _rows = nullptr;
void* _context = nullptr;
size_t _row = 0;
char _pending[160] = {};
size_t _size = 0, _offset = 0;
bool _ending = false;
public:
LocalCliOutput() = default;
explicit LocalCliOutput(FileHandle file) : _file(file) {}
bool busy() const { return _output != nullptr; }
bool owns(const Stream& output) const { return _output == &output; }
void cancel() {
if (_file) _file.close();
_output = nullptr;
_rows = nullptr;
_context = nullptr;
_remaining = _size = _offset = _row = 0;
_ending = false;
memset(_pending, 0, sizeof(_pending));
}
bool startFile(Stream& output, FileHandle file) {
if (busy()) { if (file) file.close(); return false; }
_output = &output;
_file = file;
// Snapshot the length: live logging cannot extend this dump indefinitely.
_remaining = _file ? _file.size() : 0;
return true;
}
bool startRows(Stream& output, RowReader rows, void* context,
const char* header) {
if (busy()) return false;
_output = &output;
_rows = rows;
_context = context;
_size = snprintf(_pending, sizeof(_pending), "%s", header);
if (_size >= sizeof(_pending)) _size = sizeof(_pending) - 1;
return true;
}
void service() {
if (!busy()) return;
if (_offset == _size) {
_size = _offset = 0;
if (_ending) { cancel(); return; }
if (_rows) {
_size = _rows(_context, _row, _pending, sizeof(_pending));
if (_size == 0) { cancel(); return; }
if (_size >= sizeof(_pending)) { cancel(); return; }
} else if (_remaining) {
const size_t count = _remaining < sizeof(_pending)
? _remaining : sizeof(_pending);
const int got = _file.read(reinterpret_cast<uint8_t*>(_pending), count);
if (got <= 0) {
_size = snprintf(_pending, sizeof(_pending), "\r\nError: log read failed\r\n");
_ending = true;
} else {
_size = static_cast<size_t>(got);
_remaining -= _size;
}
} else {
_size = snprintf(_pending, sizeof(_pending), "\r\n EOF\r\n");
_ending = true;
}
}
const int room = _output->availableForWrite();
if (room <= 0) return;
const size_t count = _size - _offset < static_cast<size_t>(room)
? _size - _offset : static_cast<size_t>(room);
_offset += _output->write(
reinterpret_cast<const uint8_t*>(_pending + _offset), count);
}
};
} // namespace mesh
+3 -11
View File
@@ -98,22 +98,14 @@ static inline bool wcIsSecretKey(const char* key) {
return false;
}
// CommonCLI answers a secret getter in plaintext only for the serial console
// (sender_timestamp 0) and masks it for remote callers. The web CLI executes
// with sender_timestamp 0 -- that is what makes `erase`, `stats-*` and `set freq`
// reachable -- so it would otherwise inherit the serial console's plaintext
// answers for an HTTP request. This says which `get` commands must be masked
// back down, restoring the distinction for a caller not at the serial port.
//
// Writing these has always been possible from the portal; reading them never
// was, because handleConfigGet masks them (wcIsSecretKey). The two are different
// capabilities: replacing a WiFi password does not reveal the current one, and
// replacing an identity does not reveal the existing private key.
// Identify explicit secret getters separately from config-form fields. Local
// CLI connections may read these values; configuration snapshots remain masked.
static inline bool wcIsSecretReadCommand(const char* cmd) {
if (strncmp(cmd, "get ", 4) != 0) return false;
const char* key = cmd + 4;
while (*key == ' ') key++;
if (strcmp(key, "prv.key") == 0) return true; // this node's identity
if (strcmp(key, "password") == 0) return true;
if (strcmp(key, "guest.password") == 0) return true;
if (strcmp(key, "alert.psk") == 0) return true;
if (strcmp(key, "bridge.secret") == 0) return true;
File diff suppressed because it is too large. Load diff
+43 -40
View File
@@ -239,7 +239,7 @@ static inline bool wcIsDeferredReboot(const char* cmd) {
// Commands the CLI reaches but the portal cannot honestly serve. Rejected at
// POST so nothing in the sequence runs, rather than failing halfway with a
// reply that does not explain itself. Returns the reason, or NULL if fine.
static const char* wcCliUnavailable(const char* cmd) {
static const char* wcCliUnavailable(const char* cmd, bool streamed = false) {
// ESP32Board::startOTAUpdate() does `new AsyncWebServer(80)` with no bind
// check and answers "Started" regardless. The portal already holds port 80,
// so from here it can only leak the allocation, inhibit sleep, and lie.
@@ -254,15 +254,10 @@ static const char* wcCliUnavailable(const char* cmd) {
return "clock sync takes its time from the caller, which a web request has "
"no way to supply. Use `time <epoch-seconds>` instead.";
}
// Both write their real output to Serial and hand back a stub the terminal
// would render as success. Bare `log` also streams a whole file from the loop
// task, stalling the mesh and the radio while it does.
if (strcmp(cmd, "log") == 0) {
return "log writes the packet log to the serial console, not here, and "
"blocks the radio while it does. Use `log start` / `log stop`.";
}
if (strcmp(cmd, "get acl") == 0) {
return "get acl writes to the serial console, not here.";
// The bounded batch reply cannot hold these listings. The browser terminal
// uses /api/terminal, which streams them back to the requesting connection.
if (!streamed && (strcmp(cmd, "log") == 0 || strcmp(cmd, "get acl") == 0)) {
return "Use /api/terminal for streamed listings.";
}
return NULL;
}
@@ -273,33 +268,9 @@ static inline bool wcCliEchoesSecret(const char* cmd) {
return strncmp(cmd, "password ", 9) == 0;
}
// CommonCLI splits its surface by CALLER, not by command: a serial caller
// (sender_timestamp 0, physical access) reads secrets in plaintext, while a
// remote one gets "******** (serial only)". Its own comments say so -- "Serial
// only (WiFi creds grant LAN access); remote sees set/unset".
//
// execCommand passes 0, which is what makes `erase`, `stats-*` and `set freq`
// reachable from the terminal at all. Left alone, that also claims
// physical-access trust for an HTTP request: `get prv.key` would hand this
// node's identity to anyone associated with the open setup AP, and `get
// wifi.pwd` would hand over the operator's network. Reading a secret and
// writing one are not the same capability -- the wizard has always been able to
// REPLACE these; nothing in the portal could ever READ them, because
// /api/config masks them (wcIsSecretKey).
//
// So the command surface stays whole and only the READ is masked, restoring the
// distinction CommonCLI intended for a caller who is not at the serial port.
// Which commands those are lives in WebConfigKeys.h (wcIsSecretReadCommand),
// beside the rest of the secret classification and host-tested with it.
// Keep the set/unset signal, which is the useful part and what CommonCLI itself
// reports remotely; only the value goes. A getter answers "> value".
static void wcMaskSecretReply(char* reply) {
const char* val = reply;
if (val[0] == '>' && val[1] == ' ') val += 2;
const bool unset = (val[0] == 0 || strcmp(val, "(not set)") == 0);
strcpy(reply, unset ? "> (not set)" : "> ******** (serial only)");
}
// CLI requests require LAN mode and authentication. Explicit getters have
// local-connection privileges, including secret reads. The configuration API
// still masks secrets, and the open setup AP has no CLI endpoint.
// Reply classification lives in WebConfigBatch.h with the rest of the decisions
// (WebConfigBatch::cliReplyIsFailure / cliReplyGatesReboot / cliWriteSucceeded),
// so the shapes CommonCLI actually emits are enumerated in one host-tested place.
@@ -620,6 +591,22 @@ bool WebConfigServer::formatWiFiSSID(char* reply, size_t reply_len) {
return true;
}
bool WebConfigServer::formatWiFiPassword(char* reply, size_t reply_len) {
if (!reply || !reply_len) return false;
char ssid[33] = {}, password[65] = {};
if (!loadStandaloneWiFi(ssid, sizeof(ssid), password, sizeof(password))) {
if (_active) {
strlcpy(password, _active->_wifi_password, sizeof(password));
}
#ifdef WIFI_PWD
else strlcpy(password, WIFI_PWD, sizeof(password));
#endif
}
snprintf(reply, reply_len, "> %s", password);
memset(password, 0, sizeof(password));
return true;
}
bool WebConfigServer::formatWiFiPowerSave(char* reply, size_t reply_len) {
if (!reply || reply_len == 0) return false;
@@ -1314,7 +1301,6 @@ void WebConfigServer::drainBatch(uint32_t now) {
strcpy(e.reply, "OK");
_admin_pwd_set = true;
}
if (wcIsSecretReadCommand(e.cmd)) wcMaskSecretReply(e.reply);
if (WebConfigBatch::cliReplyGatesReboot(e.cmd)) {
_batch_all_ok = WebConfigBatch::nextAllOk(
_batch_all_ok, WebConfigBatch::cliWriteSucceeded(e.reply));
@@ -2166,7 +2152,7 @@ void WebConfigServer::handleConfigResult(AsyncWebServerRequest* req) {
// commands go into the shared deferred slot and tick() drains them.
//
// Unlike a save this is not allowlisted. It is restricted to authenticated LAN
// mode and uses the remote-admin callback, so serial-only secrets stay hidden.
// mode. Commands use local-connection privileges, just like the USB terminal.
// ---------------------------------------------------------------------------
// Commands whose CLI handler never returns would take the node down mid-drain,
@@ -2199,6 +2185,13 @@ void WebConfigServer::serviceTerminal(uint32_t now) {
_terminal->queue.finish();
return;
}
if (_terminal->running) {
if (_cb->streamTerminalBusy()) return;
if (_terminal->availableForWrite() < 2) return;
_terminal->print("> ");
_terminal->queue.finish();
_terminal->running = false;
}
if (!_terminal->queue.pending || _batch_state == BATCH_PENDING) return;
if (!_terminal->attached) {
if (!_cb->beginStreamTerminal(*_terminal)) {
@@ -2218,7 +2211,17 @@ void WebConfigServer::serviceTerminal(uint32_t now) {
_terminal->attached = false;
_terminal->closed = true;
} else {
_cb->runStreamTerminal(command);
const char* unavailable = wcCliUnavailable(command, true);
if (unavailable) {
_terminal->print("Error: ");
_terminal->println(unavailable);
} else {
_cb->runStreamTerminal(command);
}
if (_cb->streamTerminalBusy()) {
_terminal->running = true;
return;
}
_terminal->print("> ");
}
_terminal->queue.finish();
+4 -2
View File
@@ -135,8 +135,8 @@ public:
virtual void getNodeSnapshot(NodeSnapshot& snapshot) = 0;
// Run one CLI command. Called from tick() only (loop task); reply is 160 bytes.
virtual void execCommand(char* cmd, char* reply) = 0;
// Browser terminal commands use remote-admin semantics so serial-only
// secrets and destructive maintenance commands remain unavailable.
// Authenticated LAN commands have local-console access, like a direct
// USB/Ethernet connection. LoRa access is handled separately by each role.
virtual bool supportsCliTerminal() const { return false; }
virtual void execAdminCommand(char* cmd, char* reply) {
execCommand(cmd, reply);
@@ -147,6 +147,7 @@ public:
virtual bool beginStreamTerminal(Stream& output) { return false; }
virtual bool ownsStreamTerminal(const Stream& output) const { return false; }
virtual void runStreamTerminal(char* command) {}
virtual bool streamTerminalBusy() const { return false; }
virtual void endStreamTerminal(Stream& output) {}
virtual void rebootNow() = 0;
// Bracket a config batch so bridge restarts triggered by individual
@@ -198,6 +199,7 @@ public:
static bool setWiFiCliEnabled(const char* value, char* reply,
size_t reply_len);
static bool formatWiFiSSID(char* reply, size_t reply_len);
static bool formatWiFiPassword(char* reply, size_t reply_len);
static bool formatWiFiStatus(
char* reply, size_t reply_len,
const mesh::wifi::CompanionWiFiRuntimeState* companion_runtime = NULL);
+9
View File
@@ -40,6 +40,7 @@ public:
char session[24] = {0};
mesh::TerminalCommandQueue queue;
bool attached = false;
bool running = false;
bool closed = false;
uint32_t last_seen = 0;
@@ -75,6 +76,14 @@ public:
xSemaphoreGive(_lock);
return n;
}
int availableForWrite() override {
if (!ready()) return 0;
xSemaphoreTake(_lock, portMAX_DELAY);
const uint64_t unread = _output.end() - _acknowledged;
const int room = unread < _capacity ? static_cast<int>(_capacity - unread) : 0;
xSemaphoreGive(_lock);
return room;
}
int available() override { return 0; }
int read() override { return -1; }
int peek() override { return -1; }
+7
View File
@@ -30,6 +30,12 @@ static SPIClass ETHERNET_SPI_PORT(NRF_SPIM1, PIN_SPI1_MISO, PIN_SPI1_SCK, PIN_SP
static EthernetServer ethernet_server(ETHERNET_TCP_PORT);
static EthernetClient ethernet_client;
static volatile bool ethernet_running = false;
static bool ethernet_session_reset = false;
static bool ethernet_take_session_reset() {
const bool changed = ethernet_session_reset;
ethernet_session_reset = false;
return changed;
}
// FreeRTOS task: handles hw init, DHCP, and retries in the background
static void ethernet_task(void* param) {
@@ -107,6 +113,7 @@ static void ethernet_check_client() {
if (newClient) {
if (ethernet_client) ethernet_client.stop();
ethernet_client = newClient;
ethernet_session_reset = true;
IPAddress ip = ethernet_client.remoteIP();
Serial.printf("ETH: Client connected from %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
ethernet_client.println(ETHERNET_CLI_BANNER);