Share the Companion terminal with the WiFi console
This commit is contained in:
1 parent
cb79dcd4e3
commit
d178cf1474
20 files changed
+3047
-2062
No files matched your search
@@ -0,0 +1,100 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// The USB and TCP input buffers hold MAX_TRANS_UNIT * 2 + 32 bytes. Contact
|
||||
// cards need almost twice a radio packet's size after hexadecimal encoding.
|
||||
static const size_t kTerminalCommandCapacity = 255 * 2 + 32;
|
||||
static const size_t kTerminalInitialOutputCapacity = 4096;
|
||||
static const size_t kTerminalOutputCapacity = 32768;
|
||||
|
||||
// A bounded scrollback with absolute cursors. Reads do not consume data, so a
|
||||
// lost HTTP response can be fetched again without skipping or repeating text.
|
||||
// The caller serializes access and supplies storage only for a live session.
|
||||
class TerminalOutputBuffer {
|
||||
char* _data;
|
||||
size_t _capacity;
|
||||
uint64_t _end = 0;
|
||||
uint64_t _first = 0;
|
||||
|
||||
public:
|
||||
TerminalOutputBuffer(char* data, size_t capacity)
|
||||
: _data(data), _capacity(capacity) {}
|
||||
uint64_t end() const { return _end; }
|
||||
void clear() { _end = _first = 0; }
|
||||
void rebind(char* data, size_t capacity) {
|
||||
const uint64_t first = _end > capacity && _end - capacity > _first
|
||||
? _end - capacity : _first;
|
||||
for (uint64_t i = first; i < _end; ++i) data[i % capacity] = _data[i % _capacity];
|
||||
_data = data;
|
||||
_capacity = capacity;
|
||||
_first = first;
|
||||
}
|
||||
void append(const uint8_t* data, size_t len) {
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
if (_capacity) _data[_end % _capacity] = data[i];
|
||||
++_end;
|
||||
}
|
||||
if (_end > _capacity && _end - _capacity > _first) _first = _end - _capacity;
|
||||
}
|
||||
size_t read(uint64_t& cursor, char* out, size_t size, bool& lost) const {
|
||||
const uint64_t first = _first;
|
||||
lost = cursor < first;
|
||||
if (cursor < first) cursor = first;
|
||||
if (cursor > _end) cursor = _end;
|
||||
size_t n = 0;
|
||||
while (n + 1 < size && cursor < _end) {
|
||||
out[n++] = _data[cursor++ % _capacity];
|
||||
}
|
||||
// JSON strings must contain complete UTF-8 characters even when a page
|
||||
// boundary lands inside a multibyte message or contact name.
|
||||
if (n) {
|
||||
size_t lead = n - 1;
|
||||
while (lead > 0 && (static_cast<uint8_t>(out[lead]) & 0xC0) == 0x80) --lead;
|
||||
const uint8_t byte = static_cast<uint8_t>(out[lead]);
|
||||
const size_t width = byte >= 0xF0 ? 4 : byte >= 0xE0 ? 3 : byte >= 0xC0 ? 2 : 1;
|
||||
if (n - lead < width) { cursor -= n - lead; n = lead; }
|
||||
}
|
||||
if (size) out[n] = 0;
|
||||
return n;
|
||||
}
|
||||
};
|
||||
|
||||
// Exactly one command can be pending. A monotonically increasing sequence
|
||||
// makes retries idempotent even after later commands have completed.
|
||||
class TerminalCommandQueue {
|
||||
public:
|
||||
enum Result { Accepted, Replay, Busy, OutOfOrder, Invalid };
|
||||
char command[kTerminalCommandCapacity] = {0};
|
||||
uint32_t sequence = 0;
|
||||
bool pending = false;
|
||||
|
||||
static bool valid(const char* text, size_t length) {
|
||||
return text && length && length < kTerminalCommandCapacity
|
||||
&& strlen(text) == length && !memchr(text, '\r', length)
|
||||
&& !memchr(text, '\n', length);
|
||||
}
|
||||
|
||||
Result submit(uint32_t seq, const char* text, size_t length) {
|
||||
if (!valid(text, length)) return Invalid;
|
||||
if (seq == 0) return OutOfOrder;
|
||||
if (seq <= sequence) return Replay;
|
||||
if (pending) return Busy;
|
||||
if (seq != sequence + 1 || sequence == UINT32_MAX) return OutOfOrder;
|
||||
memcpy(command, text, length);
|
||||
command[length] = 0;
|
||||
sequence = seq;
|
||||
pending = true;
|
||||
return Accepted;
|
||||
}
|
||||
void finish() {
|
||||
memset(command, 0, sizeof(command));
|
||||
pending = false;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mesh
|
||||
+2110
-2019
File diff suppressed because it is too large.
Load diff
@@ -28,6 +28,9 @@ static_assert(sizeof(WEBCONFIG_AP_PREFIX) <= 28,
|
||||
#endif
|
||||
|
||||
#include "WebConfigHtml.h"
|
||||
#include "WebTerminalStream.h"
|
||||
#include <helpers/CLICommandUtils.h>
|
||||
#include <new>
|
||||
#include "helpers/CLICommandUtils.h"
|
||||
#include "helpers/UsbLogging.h"
|
||||
#include "helpers/WebConfigKeys.h"
|
||||
@@ -392,6 +395,7 @@ WebConfigServer::WebConfigServer(Callbacks* callbacks, void* mqtt_prefs, bool ow
|
||||
|
||||
WebConfigServer::~WebConfigServer() {
|
||||
detachRoutes();
|
||||
closeTerminal();
|
||||
if (_mux) vSemaphoreDelete(_mux);
|
||||
}
|
||||
|
||||
@@ -964,6 +968,7 @@ void WebConfigServer::requestStop() {
|
||||
}
|
||||
|
||||
void WebConfigServer::finalizeTeardown() {
|
||||
closeTerminal();
|
||||
// Async requests keep a pointer to their server until disconnect. Retain the
|
||||
// listener and route table for the firmware lifetime; only detach and reclaim
|
||||
// the per-session state.
|
||||
@@ -1028,6 +1033,8 @@ void WebConfigServer::tick(uint32_t now) {
|
||||
}
|
||||
if (_mode == MODE_OFF) return;
|
||||
|
||||
serviceTerminal(now);
|
||||
|
||||
// A primary ESP-NOW radio and its WiFi station cannot remain on different
|
||||
// channels. Reject a router-driven channel move (for example a CSA) and put
|
||||
// the mesh radio back on its boot channel before any reconnect work runs.
|
||||
@@ -1540,6 +1547,12 @@ void WebConfigServer::registerRoutes() {
|
||||
dispatchRequest(r, &WebConfigServer::handleCliPost);
|
||||
},
|
||||
NULL, collectBody);
|
||||
_server->on("/api/terminal", HTTP_GET, [](AsyncWebServerRequest* r) {
|
||||
dispatchRequest(r, &WebConfigServer::handleTerminalOutput);
|
||||
});
|
||||
_server->on("/api/terminal", HTTP_POST, [](AsyncWebServerRequest* r) {
|
||||
dispatchRequest(r, &WebConfigServer::handleTerminalPost);
|
||||
}, NULL, collectBody);
|
||||
_server->on("/api/stats", HTTP_GET, [](AsyncWebServerRequest* r) {
|
||||
dispatchRequest(r, &WebConfigServer::handleStats);
|
||||
});
|
||||
@@ -1692,6 +1705,8 @@ void WebConfigServer::handleStatus(AsyncWebServerRequest* req) {
|
||||
doc["wifi_psk64"] = (_mqtt_prefs == NULL || !_owns_wifi);
|
||||
doc["cli"] = _cli_enabled && _mode == MODE_LAN
|
||||
&& WiFi.status() == WL_CONNECTED && _cb->supportsCliTerminal();
|
||||
doc["terminal_stream"] = _cb->supportsStreamTerminal();
|
||||
doc["terminal_max_command"] = mesh::kTerminalCommandCapacity - 1;
|
||||
doc["capabilities"] = node.capabilities;
|
||||
// Commands the terminal may submit at once. The CLI shares the config
|
||||
// batch's fixed slot, so the cap is MAX_BATCH -- reported rather than
|
||||
@@ -2160,6 +2175,168 @@ void WebConfigServer::handleConfigResult(AsyncWebServerRequest* req) {
|
||||
// path once the operator has read the results. The rest (clkreboot, poweroff,
|
||||
// ota update) do real work on the way down and cannot be faked, so they run
|
||||
// normally and the connection drops -- the UI warns before sending them.
|
||||
void WebConfigServer::closeTerminal() {
|
||||
if (!_terminal) return;
|
||||
if (_terminal->attached) _cb->endStreamTerminal(*_terminal);
|
||||
delete _terminal;
|
||||
_terminal = NULL;
|
||||
}
|
||||
|
||||
void WebConfigServer::serviceTerminal(uint32_t now) {
|
||||
WCLock lock(_mux);
|
||||
if (!_terminal) return;
|
||||
if (now - _terminal->last_seen > (_terminal->closed ? 5000UL : 60000UL)) {
|
||||
closeTerminal();
|
||||
return;
|
||||
}
|
||||
if (_terminal->closed) return;
|
||||
if (_mode != MODE_LAN || !_cli_enabled || WiFi.status() != WL_CONNECTED
|
||||
|| (_terminal->attached && !_cb->ownsStreamTerminal(*_terminal))) {
|
||||
_terminal->println("\r\nERROR: terminal disconnected");
|
||||
if (_terminal->attached) _cb->endStreamTerminal(*_terminal);
|
||||
_terminal->attached = false;
|
||||
_terminal->closed = true;
|
||||
_terminal->queue.finish();
|
||||
return;
|
||||
}
|
||||
if (!_terminal->queue.pending || _batch_state == BATCH_PENDING) return;
|
||||
if (!_terminal->attached) {
|
||||
if (!_cb->beginStreamTerminal(*_terminal)) {
|
||||
_terminal->println("ERROR: another USB or TCP client owns the terminal; close it and retry");
|
||||
_terminal->closed = true;
|
||||
_terminal->queue.finish();
|
||||
return;
|
||||
}
|
||||
_terminal->attached = true;
|
||||
}
|
||||
char* command = _terminal->queue.command;
|
||||
while (*command == ' ' || *command == '\t') ++command;
|
||||
mesh::cli::normalizeCommandVerb(command);
|
||||
if (strcmp(command, "disconnect") == 0) {
|
||||
_terminal->println(" OK - disconnecting");
|
||||
_cb->endStreamTerminal(*_terminal);
|
||||
_terminal->attached = false;
|
||||
_terminal->closed = true;
|
||||
} else {
|
||||
_cb->runStreamTerminal(command);
|
||||
_terminal->print("> ");
|
||||
}
|
||||
_terminal->queue.finish();
|
||||
}
|
||||
|
||||
bool WebConfigServer::checkTerminalAccess(AsyncWebServerRequest* req) {
|
||||
if (_mode != MODE_LAN || !_cli_enabled) {
|
||||
req->send(403, "application/json", "{\"error\":\"terminal requires LAN mode and wifi.cli on\"}");
|
||||
return false;
|
||||
}
|
||||
if (!_cb->supportsStreamTerminal()) {
|
||||
req->send(404, "application/json", "{\"error\":\"stream terminal unavailable\"}");
|
||||
return false;
|
||||
}
|
||||
if (!checkAuth(req)) {
|
||||
req->send(401, "application/json", "{\"error\":\"auth\"}");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void WebConfigServer::handleTerminalPost(AsyncWebServerRequest* req) {
|
||||
if (!checkTerminalAccess(req)) return;
|
||||
if (!req->_tempObject || req->contentLength() > MAX_BODY) {
|
||||
req->send(413, "application/json", "{\"error\":\"body too large\"}");
|
||||
return;
|
||||
}
|
||||
DynamicJsonDocument doc(2048);
|
||||
if (deserializeJson(doc, static_cast<const char*>(req->_tempObject))) {
|
||||
req->send(400, "application/json", "{\"error\":\"bad json\"}");
|
||||
return;
|
||||
}
|
||||
const char* session = doc["session"] | "";
|
||||
JsonString command = doc["command"].as<JsonString>();
|
||||
if (!wcIsValidReqId(session) || !doc["seq"].is<uint32_t>() || command.isNull()) {
|
||||
req->send(400, "application/json", "{\"error\":\"invalid session or command\"}");
|
||||
return;
|
||||
}
|
||||
const uint32_t sequence = doc["seq"].as<uint32_t>();
|
||||
if (!sequence || !mesh::TerminalCommandQueue::valid(command.c_str(), command.size())) {
|
||||
req->send(400, "application/json", "{\"error\":\"command must be one line, at most 541 bytes\"}");
|
||||
return;
|
||||
}
|
||||
WCLock lock(_mux);
|
||||
if (_terminal && strcmp(session, _terminal->session) != 0) {
|
||||
if (!_terminal->closed || _terminal->attached) {
|
||||
req->send(409, "application/json", "{\"error\":\"another browser owns the terminal\"}");
|
||||
return;
|
||||
}
|
||||
delete _terminal;
|
||||
_terminal = NULL;
|
||||
}
|
||||
if (!_terminal) {
|
||||
// A vanished session must never silently start over and resend a message.
|
||||
if (sequence != 1) {
|
||||
req->send(409, "application/json", "{\"error\":\"terminal session expired\"}");
|
||||
return;
|
||||
}
|
||||
_terminal = new (std::nothrow) WebTerminalStream;
|
||||
if (!_terminal || !_terminal->ready()) {
|
||||
delete _terminal;
|
||||
_terminal = NULL;
|
||||
req->send(503, "application/json", "{\"error\":\"not enough free memory for terminal\"}");
|
||||
return;
|
||||
}
|
||||
strlcpy(_terminal->session, session, sizeof(_terminal->session));
|
||||
}
|
||||
if (_terminal->closed) {
|
||||
req->send(409, "application/json", "{\"error\":\"terminal session closed\"}");
|
||||
return;
|
||||
}
|
||||
const auto result = _terminal->queue.submit(sequence, command.c_str(), command.size());
|
||||
if (result != mesh::TerminalCommandQueue::Accepted
|
||||
&& result != mesh::TerminalCommandQueue::Replay) {
|
||||
const bool invalid = result == mesh::TerminalCommandQueue::Invalid;
|
||||
req->send(invalid ? 400 : 409, "application/json", invalid
|
||||
? "{\"error\":\"command must be one line, at most 541 bytes\"}"
|
||||
: "{\"error\":\"terminal busy or command out of order\"}");
|
||||
return;
|
||||
}
|
||||
_terminal->last_seen = millis();
|
||||
req->send(202, "application/json", "{\"accepted\":true}");
|
||||
}
|
||||
|
||||
void WebConfigServer::handleTerminalOutput(AsyncWebServerRequest* req) {
|
||||
if (!checkTerminalAccess(req)) return;
|
||||
const String session = req->hasParam("session") ? req->getParam("session")->value() : "";
|
||||
const String after = req->hasParam("after") ? req->getParam("after")->value() : "0";
|
||||
if (!wcIsValidReqId(session.c_str()) || !after.length() || after.length() > 16
|
||||
|| strspn(after.c_str(), "0123456789") != after.length()) {
|
||||
req->send(400, "application/json", "{\"error\":\"invalid session or cursor\"}");
|
||||
return;
|
||||
}
|
||||
WCLock lock(_mux);
|
||||
if (!_terminal || session != _terminal->session) {
|
||||
req->send(404, "application/json", "{\"error\":\"terminal session expired\"}");
|
||||
return;
|
||||
}
|
||||
uint64_t cursor = strtoull(after.c_str(), NULL, 10);
|
||||
char output[1025];
|
||||
bool lost = false;
|
||||
const size_t n = _terminal->readOutput(cursor, output, sizeof(output), lost);
|
||||
_terminal->last_seen = millis();
|
||||
DynamicJsonDocument doc(1536);
|
||||
doc["output"] = output;
|
||||
doc["cursor"] = cursor;
|
||||
doc["lost"] = lost;
|
||||
// A page may end a few bytes early to keep UTF-8 intact.
|
||||
doc["more"] = n >= sizeof(output) - 4;
|
||||
doc["seq"] = _terminal->queue.sequence;
|
||||
doc["done"] = !_terminal->queue.pending;
|
||||
doc["closed"] = _terminal->closed;
|
||||
AsyncResponseStream* response = req->beginResponseStream("application/json");
|
||||
response->addHeader("Cache-Control", "no-store");
|
||||
serializeJson(doc, *response);
|
||||
req->send(response);
|
||||
}
|
||||
|
||||
void WebConfigServer::handleCliPost(AsyncWebServerRequest* req) {
|
||||
if (_mode != MODE_LAN) {
|
||||
req->send(403, "application/json",
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
#include <freertos/semphr.h>
|
||||
#include <helpers/CompanionWiFiStatus.h>
|
||||
#include <helpers/WebConfigBatch.h>
|
||||
#include <helpers/TerminalSession.h>
|
||||
#include <helpers/WiFiPowerSave.h>
|
||||
#include <helpers/WiFiReconnectPolicy.h>
|
||||
#include <helpers/ui/DisplayBuildFlags.h>
|
||||
@@ -36,6 +37,7 @@
|
||||
class AsyncWebServer;
|
||||
class AsyncWebServerRequest;
|
||||
class DNSServer;
|
||||
class WebTerminalStream;
|
||||
|
||||
#ifndef WEBCONFIG_AP_IDLE_TIMEOUT_MS
|
||||
#if defined(MESHCORE_EXPANDED_PARTITION_PROFILE)
|
||||
@@ -139,6 +141,13 @@ public:
|
||||
virtual void execAdminCommand(char* cmd, char* reply) {
|
||||
execCommand(cmd, reply);
|
||||
}
|
||||
// Companion's browser uses the same stateful Stream terminal as USB/TCP.
|
||||
// All session callbacks run on the mesh loop, never the HTTP task.
|
||||
virtual bool supportsStreamTerminal() const { return false; }
|
||||
virtual bool beginStreamTerminal(Stream& output) { return false; }
|
||||
virtual bool ownsStreamTerminal(const Stream& output) const { return false; }
|
||||
virtual void runStreamTerminal(char* command) {}
|
||||
virtual void endStreamTerminal(Stream& output) {}
|
||||
virtual void rebootNow() = 0;
|
||||
// Bracket a config batch so bridge restarts triggered by individual
|
||||
// `set` handlers can be coalesced into one.
|
||||
@@ -296,6 +305,7 @@ private:
|
||||
uint32_t _setup_wifi_handoff_deadline = 0;
|
||||
char _setup_wifi_handoff_ip[16] = {0};
|
||||
BatchEntry _batch[MAX_BATCH];
|
||||
WebTerminalStream* _terminal = NULL;
|
||||
|
||||
// LAN-mode session (single slot; new login evicts the old session)
|
||||
char _session_token[33] = {0};
|
||||
@@ -330,6 +340,8 @@ private:
|
||||
void detachRoutes();
|
||||
uint32_t handlerRefCount() const;
|
||||
void drainBatch(uint32_t now);
|
||||
void serviceTerminal(uint32_t now);
|
||||
void closeTerminal();
|
||||
void serviceSetupWiFiHandoff(uint32_t now);
|
||||
void finishBatch(uint32_t now);
|
||||
void finalizeTeardown();
|
||||
@@ -347,6 +359,9 @@ private:
|
||||
void handleConfigResult(AsyncWebServerRequest* req);
|
||||
void handleCliPost(AsyncWebServerRequest* req);
|
||||
void handleCliResult(AsyncWebServerRequest* req);
|
||||
void handleTerminalPost(AsyncWebServerRequest* req);
|
||||
void handleTerminalOutput(AsyncWebServerRequest* req);
|
||||
bool checkTerminalAccess(AsyncWebServerRequest* req);
|
||||
void handleStats(AsyncWebServerRequest* req);
|
||||
void handleScan(AsyncWebServerRequest* req);
|
||||
void handlePresets(AsyncWebServerRequest* req);
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <helpers/TerminalSession.h>
|
||||
|
||||
// Allocated only while a browser terminal is open. PSRAM is preferred; boards
|
||||
// without it keep at least 32 KiB of internal heap after allocating scrollback.
|
||||
// Large unread replies can grow the buffer; draining them returns it to 4 KiB.
|
||||
class WebTerminalStream : public Stream {
|
||||
char* _storage;
|
||||
size_t _capacity = mesh::kTerminalInitialOutputCapacity;
|
||||
uint64_t _acknowledged = 0;
|
||||
SemaphoreHandle_t _lock;
|
||||
mesh::TerminalOutputBuffer _output;
|
||||
|
||||
static char* allocate(size_t capacity) {
|
||||
void* data = heap_caps_malloc(capacity,
|
||||
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
if (!data && heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)
|
||||
>= capacity + 32768) {
|
||||
data = heap_caps_malloc(capacity,
|
||||
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
|
||||
}
|
||||
return static_cast<char*>(data);
|
||||
}
|
||||
|
||||
void resize(size_t capacity) {
|
||||
char* storage = allocate(capacity);
|
||||
if (!storage) return;
|
||||
_output.rebind(storage, capacity);
|
||||
free(_storage);
|
||||
_storage = storage;
|
||||
_capacity = capacity;
|
||||
}
|
||||
|
||||
public:
|
||||
char session[24] = {0};
|
||||
mesh::TerminalCommandQueue queue;
|
||||
bool attached = false;
|
||||
bool closed = false;
|
||||
uint32_t last_seen = 0;
|
||||
|
||||
WebTerminalStream() : _storage(allocate(mesh::kTerminalInitialOutputCapacity)),
|
||||
_lock(xSemaphoreCreateMutex()),
|
||||
_output(_storage, _storage ? mesh::kTerminalInitialOutputCapacity : 0) {}
|
||||
~WebTerminalStream() override {
|
||||
free(_storage);
|
||||
if (_lock) vSemaphoreDelete(_lock);
|
||||
}
|
||||
bool ready() const { return _storage && _lock; }
|
||||
using Print::write;
|
||||
size_t write(uint8_t byte) override { return write(&byte, 1); }
|
||||
size_t write(const uint8_t* data, size_t len) override {
|
||||
if (!ready()) return 0;
|
||||
xSemaphoreTake(_lock, portMAX_DELAY);
|
||||
size_t wanted = _capacity;
|
||||
const uint64_t unread = _output.end() - _acknowledged + len;
|
||||
while (wanted < unread && wanted < mesh::kTerminalOutputCapacity) wanted *= 2;
|
||||
if (wanted > _capacity) resize(wanted);
|
||||
_output.append(data, len);
|
||||
xSemaphoreGive(_lock);
|
||||
return len;
|
||||
}
|
||||
size_t readOutput(uint64_t& cursor, char* out, size_t size, bool& lost) {
|
||||
xSemaphoreTake(_lock, portMAX_DELAY);
|
||||
if (cursor <= _output.end() && cursor > _acknowledged) _acknowledged = cursor;
|
||||
if (_capacity > mesh::kTerminalInitialOutputCapacity
|
||||
&& _output.end() - _acknowledged <= mesh::kTerminalInitialOutputCapacity) {
|
||||
resize(mesh::kTerminalInitialOutputCapacity);
|
||||
}
|
||||
const size_t n = _output.read(cursor, out, size, lost);
|
||||
xSemaphoreGive(_lock);
|
||||
return n;
|
||||
}
|
||||
int available() override { return 0; }
|
||||
int read() override { return -1; }
|
||||
int peek() override { return -1; }
|
||||
void flush() override {}
|
||||
};
|
||||
Reference in new issue
Block a user