Add secure host CLI bridge and harden OTA workflows

Expose the Full Companion terminal over TCP and add an authenticated, replay-resistant host command service with documented CPU temperature, reboot, and allowlisted program examples.\n\nImprove LoRa OTA diagnostics and persistent CLI handling, reduce clock correction drift to ten minutes, and make mOTA stream flush behavior an explicit transport policy with regression coverage.
This commit is contained in:
mikecarper committed 2026-08-23 15:29:30 -07:00
1 parent 83c1dd95fe
commit b699e552ec
46 files changed
+4364 -359

No files matched your search

+4
View File
@@ -17,6 +17,10 @@ enum class CompanionWiFiPowerSaveResult : uint8_t {
bool toggleCompanionWiFi();
bool isCompanionWiFiEnabled();
// Reload saved credentials after a text-terminal update. The reconnect is
// deferred so the command reply can leave USB/TCP before WiFi is restarted.
void scheduleCompanionWiFiCredentialReload();
// Companion WiFi power save is stored in the shared mesh-wifi NVS namespace.
// The returned mode is always the effective mode: WiFi+BLE builds map a stale
// or default "none" value to "min" because modem sleep is required for radio
File diff suppressed because it is too large. Load diff
+10
View File
@@ -164,6 +164,11 @@ public:
void exitTerminalMode();
bool isTerminalMode() const { return _terminal_mode; }
void handleTerminalCommand(char* command);
#if defined(COMPANION_RADIO_FULL)
bool enterNetworkTerminalMode(Stream& output);
void exitNetworkTerminalMode(Stream& output);
bool isNetworkTerminalMode(const Stream& output) const;
#endif
#endif
#if defined(COMPANION_RADIO_FULL)
@@ -302,6 +307,10 @@ private:
void syncWiFiPowerSaving();
#endif
#ifdef ENABLE_USB_INTERFACE
Stream& terminalOutput();
bool hasTerminalOutput() const { return _terminal_output != NULL; }
void resetTerminalSession();
void printTerminalBanner(bool show_binary_stop);
ContactInfo* getTerminalRecipient();
void printTerminalPath(const ContactInfo& recipient);
void handleTerminalPath(ContactInfo& recipient, const char* path_spec);
@@ -374,6 +383,7 @@ private:
bool _cli_rescue;
#ifdef ENABLE_USB_INTERFACE
bool _terminal_mode;
Stream* _terminal_output;
mesh::TerminalDisplayFilter _terminal_display;
bool _terminal_recipient_set;
uint8_t _terminal_recipient_key[PUB_KEY_SIZE];
+114 -25
View File
@@ -284,11 +284,10 @@ static void clearUsbTerminalLine() {
}
static void printUsbTerminalInputEcho() {
const char* password = nullptr;
const char* password =
mesh::cli::terminalPasswordInput(usb_terminal_line);
size_t visible_len = usb_terminal_line_len;
if (mesh::cli::parseTerminalArgumentCommand(
usb_terminal_line, "login", password)
== mesh::cli::TerminalArgumentCommandMatch::Valid) {
if (password != nullptr) {
visible_len = static_cast<size_t>(password - usb_terminal_line);
}
@@ -515,6 +514,8 @@ void halt() {
static bool companion_wifi_active = false;
static bool companion_wifi_disable_in_progress = false;
static bool companion_wifi_services_stopped = false;
static bool companion_wifi_credential_reload_pending = false;
static unsigned long companion_wifi_credential_reload_at = 0;
static bool companion_wifi_power_save_loaded = false;
static uint8_t companion_wifi_power_save = mesh::wifi::kDefaultPowerSave;
@@ -612,6 +613,15 @@ void halt() {
}
}
void scheduleCompanionWiFiCredentialReload() {
loadCompanionWiFiCredentials();
companion_wifi_credential_reload_pending = true;
companion_wifi_credential_reload_at = millis() + 1500UL;
if (companion_wifi_credential_reload_at == 0) {
companion_wifi_credential_reload_at = 1;
}
}
bool isCompanionWiFiEnabled() {
return companion_wifi_requested;
}
@@ -693,11 +703,10 @@ void halt() {
}
#endif
/* WIFI OTA CONSOLE - a tiny text CLI for OTA over WiFi. Connect with e.g. `nc <ip> 5002` and type
`ota status` / `ota ls` / `ota announce` / ... - one client at a time, on a DEDICATED port separate from
the companion (5000) and the seeder (5001). Full companions also accept `tempradio ...`,
`normalradio`, and WiFi power-save commands here so a host can manage the source without
occupying the binary port. */
/* WIFI TEXT CONSOLE - one client at a time on a dedicated port, separate from
Binary Companion (5000) and the mOTA seeder (5001). A Full Companion exposes
the same role CLI here as its USB terminal. Other OTA-enabled Companion
builds retain the bounded `ota ...` management console. */
#if defined(ESP32) && defined(WIFI_SSID) && defined(ENABLE_OTA)
#include <helpers/ota/OtaCli.h> // mesh::ota::handle_ota_command(line, reply, board)
#include <helpers/esp32/WiFiOtaSeeder.h>
@@ -706,50 +715,103 @@ void halt() {
#endif
static WiFiServer ota_console_server(OTA_CONSOLE_TCP_PORT);
static WiFiClient ota_console_client;
static char ota_console_line[128];
static uint8_t ota_console_len = 0;
static char ota_console_line[MAX_TRANS_UNIT * 2 + 32];
static size_t ota_console_len = 0;
static bool ota_console_discard_line = false;
static void ota_console_clear_line() {
memset(ota_console_line, 0, sizeof(ota_console_line));
ota_console_len = 0;
}
static void ota_console_start() {
ota_console_server.begin();
#if defined(COMPANION_RADIO_FULL) && defined(ENABLE_USB_INTERFACE)
WIFI_DEBUG_PRINTLN("Full Companion terminal listening on :%d (nc <ip> %d)",
OTA_CONSOLE_TCP_PORT, OTA_CONSOLE_TCP_PORT);
#else
WIFI_DEBUG_PRINTLN("OTA console listening on :%d (nc <ip> %d, type `ota ...`)",
OTA_CONSOLE_TCP_PORT, OTA_CONSOLE_TCP_PORT);
#endif
}
static void ota_console_stop() {
#if defined(COMPANION_RADIO_FULL) && defined(ENABLE_USB_INTERFACE)
the_mesh.exitNetworkTerminalMode(ota_console_client);
#endif
if (ota_console_client) ota_console_client.stop();
ota_console_server.end();
ota_console_len = 0;
ota_console_clear_line();
ota_console_discard_line = false;
}
static void ota_console_loop() {
if (!ota_console_client || !ota_console_client.connected()) {
WiFiClient c = ota_console_server.available();
if (c) { ota_console_client = c; ota_console_len = 0;
ota_console_client.print("OTA console - type `ota ...`");
#if defined(COMPANION_RADIO_FULL)
ota_console_client.print(" or `tempradio freq,bw,sf,cr,minutes`");
ota_console_client.print("; `get/set wifi.powersave`");
#if defined(COMPANION_RADIO_FULL) && defined(ENABLE_USB_INTERFACE)
the_mesh.exitNetworkTerminalMode(ota_console_client);
#endif
ota_console_client.print("\r\n> "); }
WiFiClient c = ota_console_server.available();
if (c) {
ota_console_client = c;
ota_console_clear_line();
ota_console_discard_line = false;
#if defined(COMPANION_RADIO_FULL) && defined(ENABLE_USB_INTERFACE)
if (!the_mesh.enterNetworkTerminalMode(ota_console_client)) {
ota_console_client.print(
"ERROR: USB currently owns the Full Companion terminal\r\n");
ota_console_client.stop();
}
#else
ota_console_client.print("OTA console - type `ota ...`\r\n> ");
#endif
}
return;
}
#if defined(COMPANION_RADIO_FULL) && defined(ENABLE_USB_INTERFACE)
if (!the_mesh.isNetworkTerminalMode(ota_console_client)) {
ota_console_client.print(
"\r\nERROR: terminal ownership moved to USB; closing\r\n");
ota_console_client.stop();
ota_console_clear_line();
ota_console_discard_line = false;
return;
}
#endif
while (ota_console_client.available()) {
char ch = (char)ota_console_client.read();
if (ota_console_discard_line) {
if (ch == '\r' || ch == '\n') {
ota_console_discard_line = false;
ota_console_client.print(" ERROR: command too long\r\n> ");
}
continue;
}
if (ch == '\r' || ch == '\n') {
if (ota_console_len == 0) continue; // ignore blanks / the CRLF pair
ota_console_line[ota_console_len] = 0;
char reply[160]; reply[0] = 0;
#if defined(COMPANION_RADIO_FULL)
if (!the_mesh.handleFullOtaCommand(ota_console_line, reply, sizeof(reply)))
strcpy(reply, "supported: ota ... | tempradio ... | normalradio | get/set wifi.powersave");
#if defined(COMPANION_RADIO_FULL) && defined(ENABLE_USB_INTERFACE)
if (strcmp(ota_console_line, "disconnect") == 0) {
ota_console_client.print(" OK - disconnecting\r\n");
the_mesh.exitNetworkTerminalMode(ota_console_client);
ota_console_client.stop();
ota_console_clear_line();
ota_console_discard_line = false;
return;
}
the_mesh.handleTerminalCommand(ota_console_line);
ota_console_client.print("> ");
#else
char reply[160]; reply[0] = 0;
if (!mesh::ota::handle_ota_command(ota_console_line, reply, board))
strcpy(reply, "only `ota ...` commands are supported on this console");
#endif
ota_console_client.print(" -> "); ota_console_client.print(reply); ota_console_client.print("\r\n> ");
ota_console_len = 0;
#endif
ota_console_clear_line();
} else if (ota_console_len < sizeof(ota_console_line) - 1) {
ota_console_line[ota_console_len++] = ch;
} else {
ota_console_clear_line();
ota_console_discard_line = true;
}
}
}
@@ -763,6 +825,32 @@ void halt() {
wifi_setup_recovery_mode = false;
}
static void serviceCompanionWiFiCredentialReload() {
if (!companion_wifi_credential_reload_pending
|| static_cast<int32_t>(millis() - companion_wifi_credential_reload_at) < 0) {
return;
}
#ifdef WITH_WEBCONFIG
if (the_mesh.isWebConfigActiveOrStopping()) return;
#endif
companion_wifi_credential_reload_pending = false;
companion_wifi_credential_reload_at = 0;
loadCompanionWiFiCredentials();
resetCompanionWiFiRecoveryState();
if (!companion_wifi_requested || !companion_wifi_active
|| !companion_wifi_has_credentials) {
return;
}
WiFi.mode(WIFI_STA);
WiFi.setAutoReconnect(true);
WiFi.disconnect(false, false);
WiFi.begin(configured_wifi_ssid, configured_wifi_password);
wifi_reconnect_tracker.noteAttempt(millis());
WIFI_DEBUG_PRINTLN("WiFi credentials reloaded; reconnecting to saved SSID");
}
static void startCompanionWiFi() {
if (companion_wifi_active) return;
@@ -1226,6 +1314,7 @@ void loop() {
#ifdef WITH_WEBCONFIG
the_mesh.serviceWebConfig();
#endif
serviceCompanionWiFiCredentialReload();
serviceCompanionWiFiState();
if (companion_wifi_requested && companion_wifi_active) {
#ifdef ENABLE_OTA
+230
View File
@@ -0,0 +1,230 @@
# LoRa CLI host service example
This example lets an authenticated remote administrator ask a computer attached
to a repeater to perform a small, explicitly allowed operation. The included
service implements this fixed allowlist:
```text
host help
host cpu-temp
host hostname
host uptime
host load
host memory
host disk-free
host reboot
host run <alias> [arguments]
```
The status commands read bounded operating-system APIs or virtual files. The
service never invokes a shell and does not accept arbitrary commands,
file paths, or executable names. Locally configured program aliases can accept
strictly validated arguments. Host reboot is disabled by default.
Normal repeater firmware includes the host bridge. The specialized Wio-E5
RS232 bridge image omits it to stay within that board's fixed 240 KiB
application partition; use the normal Wio-E5 repeater image for this service.
## Using it with meshcoretomqtt
`meshcoretomqtt` remains the only process that opens the repeater's USB serial
port. The data path is:
```text
LoRa admin -> repeater -> USB -> meshcoretomqtt -> MQTT broker
MQTT broker -> host endpoint -> signed remote-serial MQTT -> meshcoretomqtt
meshcoretomqtt -> USB -> repeater -> LoRa reply
```
Two processes must not read the same serial TTY. The MQTT endpoint avoids that
race and can run on the same Pi as the broker and `meshcoretomqtt`, or on a
different host.
The current `meshcoretomqtt` release publishes repeater `DEBUG` records only
when it is launched with `--debug`. Add `--debug` to its existing systemd
`ExecStart` command and restart it. Keep any existing `--config` arguments.
This publishes other firmware debug records too, so use broker ACLs and do not
expose the debug topic publicly.
The host-command authorization does not compare the repeater clock with the Pi
clock. Several minutes of drift, an unset repeater wall clock, or a later clock
correction cannot make an old request executable. Freshness comes from the
live one-time challenge described below. The normal `meshcoretomqtt`
`sync_time` setting can remain enabled for its other uses, but this feature does
not depend on it.
Generate a dedicated service signing key with the Python environment already
installed by `meshcoretomqtt`:
```sh
sudo /opt/mctomqtt/venv/bin/python3 host_cli_service.py \
--generate-key /etc/mctomqtt/host-cli-key.json
sudo chown mctomqtt:mctomqtt /etc/mctomqtt/host-cli-key.json
sudo chmod 600 /etc/mctomqtt/host-cli-key.json
```
The command prints the public key. Add only that public key to the existing
`meshcoretomqtt` configuration:
```toml
[remote_serial]
enabled = true
allowed_companions = [
"SERVICE_PUBLIC_KEY_PRINTED_ABOVE"
]
nonce_ttl = 120
command_timeout = 10
```
The name `allowed_companions` comes from `meshcoretomqtt`; a dedicated service
identity works because it uses the same Ed25519 token format. Restart
`mctomqtt` after changing the file.
Run the endpoint against the same broker and topic namespace. Replace `USA`
with the exact three-character IATA value used by that broker and replace the
repeater key with the repeater's complete 64-hex-character public key:
```sh
sudo -u mctomqtt /opt/mctomqtt/venv/bin/python3 host_cli_service.py \
--broker 127.0.0.1 \
--iata USA \
--repeater-key REPEATER_PUBLIC_KEY \
--service-key /etc/mctomqtt/host-cli-key.json
```
For a password-protected broker, add `--username NAME --password-file FILE`.
For TLS, add `--tls`, and optionally `--ca-cert FILE`. If the debug or serial
command topic is customized in `meshcoretomqtt`, pass the matching
`--request-topic` or `--command-topic` value.
To enable the exact `host reboot` request, give only `systemctl reboot` to the
service account in `/etc/sudoers.d/meshcore-host-cli`:
```text
mctomqtt ALL=(root) NOPASSWD: /usr/bin/systemctl reboot
```
Set that file to mode `440`, then add `--allow-reboot` to the endpoint command.
The endpoint publishes `OK - host reboot scheduled in 5s`, waits for the MQTT
publish, and then runs the fixed argv
`/usr/bin/sudo -n /usr/bin/systemctl reboot` after five seconds. Change the
delay from 3 through 60 seconds with `--reboot-delay`; no LoRa text is ever
inserted into the process invocation. Do not add a broad sudo wildcard.
## Allowlisted programs with arguments
Pass `--programs-file FILE` to expose selected local programs as
`host run <alias> [arguments]`. Start with `programs.example.json`, replace its
example executable paths with installed programs, and keep the file owned by a
trusted local account. The service rejects a group- or world-writable allowlist
or executable.
Each entry fixes the executable and any leading arguments in `argv`. Its remote
arguments have an exact count and one of three validators:
- `choice` accepts only one explicitly listed value;
- `integer` accepts a canonical nonnegative decimal value inside `min` and
`max`;
- `token` accepts a bounded ASCII token that starts with a letter or digit and
contains only letters, digits, `_`, `.`, `:`, `@`, `+`, `,`, or `-`.
For the example `fan` entry, the remote command is:
```text
cmd host run fan on 15
```
It always executes this argument vector, without a shell:
```text
/usr/local/bin/mesh-fan-control --source lora on 15
```
An alias cannot select another executable. Extra arguments, option-shaped
tokens such as `--help`, invalid choices, out-of-range integers, shell syntax,
control characters, and malformed quoting are rejected before a process is
started. Program timeouts are limited to 1-5 seconds so the reply fits inside
the repeater's 10-second host-service deadline. The selected local program is
still trusted code; give its service account only the operating-system
permissions that program needs.
From a companion's authenticated remote CLI, select and log into the repeater,
then run:
```text
cmd host help
cmd host cpu-temp
```
Use `cmd get host` to view the bridge limits and whether a request is waiting.
## Injection and replay protection
The broker is transport, not the trust boundary. The endpoint accepts a request
only when all of these checks pass:
- the LoRa caller was authenticated by the repeater and has administrator
permission;
- the MQTT `origin_id` is the configured repeater identity;
- the complete protocol record has a valid Ed25519 signature from that
repeater;
- the request contains the pending 32-bit ID and a fresh random 64-bit nonce;
- Base64URL framing, UTF-8, and byte limits are valid;
- a new random 64-bit service challenge is returned through the signed serial
channel and the repeater signs proof that the exact request is still pending;
- only after that live proof does the decoded request reach the fixed built-in
or locally configured program allowlist.
For `run`, the request must additionally match a locally configured alias and
every argument validator. Execution uses a fixed absolute executable,
`shell=False`, a fixed minimal environment, no stdin, and `/` as its working
directory.
The initial signed request never executes an action. The endpoint first stores
it in memory and sends `@claim=<random>` with the same ID and nonce. The
firmware accepts that claim only through physical USB while that exact LoRa
request is pending, then emits a signed `CLAIMED` proof containing the random
value. The endpoint removes the proof before running the action, making action
execution at most once even if MQTT redelivers a record.
A captured request can at most make the endpoint issue a new challenge; a
repeater with no matching live request will not sign it. A captured `CLAIMED`
record cannot match the endpoint's new random challenge, and a service restart
forgets all outstanding challenges. These replay properties do not use wall
clock time. The final response still travels in a short-lived JWT whose
signature, signer allowlist, target, expiration, and independent nonce are
checked by `meshcoretomqtt`. When both processes run on the same Pi, that JWT
check naturally uses the same host clock; if they run on different computers,
those two computers need compatible clocks. Repeater-to-Pi clock drift remains
irrelevant.
Request text is Base64URL encoded before it enters the line-oriented USB stream.
Reply controls such as carriage return and newline are converted to spaces, and
the firmware independently rejects control characters and malformed UTF-8.
This prevents text from becoming a second serial command.
Protect `host-cli-key.json`: any private key placed in
`allowed_companions` is trusted by `meshcoretomqtt` to sign serial requests.
Use a dedicated broker account whose ACL can only subscribe to this repeater's
debug topic and publish to this repeater's `serial/commands` topic.
## Limits
- LoRa `host` command: 155 UTF-8 bytes after `host `, or 152 bytes when the
companion uses its legacy three-byte correlation prefix.
- LoRa reply: 162 UTF-8 bytes total, including that correlation prefix.
- One request can be pending per repeater.
- Live-claim deadline: 4 seconds, followed by up to 6 seconds for execution and
the reply.
- `host.reply` is accepted only from the physical USB serial command path, not
from LoRa or the Ethernet CLI.
Run the dependency-free logic tests with:
```sh
cd examples/host_cli_service
python3 -m unittest -v
```
The live service needs Python 3.11 or later, `paho-mqtt`, and
`ed25519-orlp`; the standard `/opt/mctomqtt/venv` already contains them.
File diff suppressed because it is too large. Load diff
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env python3
"""Compatibility entry point for the expanded MeshCore host CLI service."""
from host_cli_service import main
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,41 @@
{
"programs": {
"fan": {
"argv": [
"/usr/local/bin/mesh-fan-control",
"--source",
"lora"
],
"timeout_seconds": 3,
"arguments": [
{
"name": "state",
"type": "choice",
"choices": [
"on",
"off"
]
},
{
"name": "minutes",
"type": "integer",
"min": 1,
"max": 60
}
]
},
"label-status": {
"argv": [
"/usr/local/bin/mesh-label-status"
],
"timeout_seconds": 3,
"arguments": [
{
"name": "label",
"type": "token",
"max_bytes": 24
}
]
}
}
}
@@ -0,0 +1,585 @@
from __future__ import annotations
import base64
import json
from pathlib import Path
import tempfile
import unittest
from unittest import mock
import host_cli_service as service
PUBLIC_KEY = "11" * 32
PRIVATE_KEY = "22" * 64
SIGNATURE = bytes([0xA5]) * 64
def request_payload(
text: str = "cpu-temp",
request_id: str = "89ABCDEF",
) -> tuple[str, bytes]:
encoded = base64.urlsafe_b64encode(text.encode()).rstrip(b"=").decode()
signed = f"HOSTCLI/1 REQUEST {request_id} 0123456789ABCDEF {encoded}"
message = "DEBUG " + signed + " " + SIGNATURE.hex().upper()
payload = json.dumps(
{"type": "DEBUG", "origin_id": PUBLIC_KEY, "message": message}
).encode()
return signed, payload
def claim_payload(
challenge: str = "FEDCBA9876543210",
request_id: str = "89ABCDEF",
) -> tuple[str, bytes]:
signed = (
f"HOSTCLI/1 CLAIMED {request_id} 0123456789ABCDEF {challenge}"
)
message = "DEBUG " + signed + " " + SIGNATURE.hex().upper()
payload = json.dumps(
{"type": "DEBUG", "origin_id": PUBLIC_KEY, "message": message}
).encode()
return signed, payload
class HostRequestTests(unittest.TestCase):
def test_accepts_only_a_valid_repeater_signature(self) -> None:
expected, payload = request_payload()
def verifier(signature: bytes, message: bytes, public: bytes) -> bool:
return (
signature == SIGNATURE
and message == expected.encode()
and public == bytes.fromhex(PUBLIC_KEY)
)
request = service.parse_and_verify_request(
payload, PUBLIC_KEY, verifier=verifier,
)
self.assertEqual(
service.HostRequest(
"89ABCDEF", "0123456789ABCDEF", "cpu-temp"
),
request,
)
def test_rejects_forged_content_and_wrong_origin(self) -> None:
_expected, payload = request_payload("cpu-temp")
forged = payload.replace(b"Y3B1LXRlbXA", b"ZXJhc2U")
with self.assertRaisesRegex(ValueError, "signature"):
service.parse_and_verify_request(
forged, PUBLIC_KEY, verifier=lambda *_args: False,
)
document = json.loads(payload)
document["origin_id"] = "33" * 32
with self.assertRaisesRegex(ValueError, "origin"):
service.parse_and_verify_request(
json.dumps(document), PUBLIC_KEY,
verifier=lambda *_args: True,
)
def test_ignores_unrelated_debug_records(self) -> None:
payload = json.dumps(
{"type": "DEBUG", "origin_id": PUBLIC_KEY,
"message": "DEBUG ordinary log"}
)
self.assertIsNone(
service.parse_and_verify_request(
payload, PUBLIC_KEY, verifier=lambda *_args: True,
)
)
def test_accepts_only_a_valid_signed_claim(self) -> None:
expected, payload = claim_payload()
def verifier(signature: bytes, message: bytes, public: bytes) -> bool:
return (
signature == SIGNATURE
and message == expected.encode()
and public == bytes.fromhex(PUBLIC_KEY)
)
self.assertEqual(
service.HostClaim(
"89ABCDEF", "0123456789ABCDEF", "FEDCBA9876543210"
),
service.parse_and_verify_claim(
payload, PUBLIC_KEY, verifier=verifier
),
)
with self.assertRaisesRegex(ValueError, "signature"):
service.parse_and_verify_claim(
payload, PUBLIC_KEY, verifier=lambda *_args: False
)
def test_rejects_a_zero_claim_challenge(self) -> None:
_signed, payload = claim_payload("0000000000000000")
with self.assertRaisesRegex(ValueError, "must not be zero"):
service.parse_and_verify_claim(
payload, PUBLIC_KEY, verifier=lambda *_args: True
)
class RequestHandlerTests(unittest.TestCase):
def test_reads_pi_cpu_temperature(self) -> None:
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "temp"
path.write_text("47250\n", encoding="ascii")
self.assertEqual(
service.HostResult("CPU 47.2 C"),
service.handle_request("cpu-temp", path),
)
def test_never_executes_or_accepts_injected_commands(self) -> None:
response = service.handle_request(
"cpu-temp\r\nerase", Path("/does/not/matter")
)
self.assertEqual(
service.HostResult("Err - unsupported host request"), response
)
request = service.HostRequest(
"12345678", "FEDCBA9876543210", "cpu-temp"
)
command = service.make_serial_reply(request, "OK\r\nerase")
self.assertEqual(
"host.reply 12345678 FEDCBA9876543210 OK erase", command
)
self.assertNotIn("\r", command)
self.assertNotIn("\n", command)
self.assertEqual(
"OK 31mnot-a-terminal-control",
service.bounded_line_text("OK\N{CONTROL SEQUENCE INTRODUCER}31m"
"not-a-terminal-control"),
)
def test_exact_fixed_commands_and_opt_in_reboot(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
uptime = root / "uptime"
load = root / "loadavg"
memory = root / "meminfo"
uptime.write_text("183845.2 0.0\n", encoding="ascii")
load.write_text("0.12 0.34 0.56 1/1 1\n", encoding="ascii")
memory.write_text(
"MemTotal: 1024000 kB\nMemAvailable: 512000 kB\n",
encoding="ascii",
)
kwargs = {
"uptime_path": uptime,
"load_path": load,
"memory_path": memory,
"disk_path": root,
}
self.assertEqual(
"Uptime 2d 3h 4m",
service.handle_request("uptime", root, **kwargs).text,
)
self.assertEqual(
"Load 0.12 0.34 0.56",
service.handle_request("load", root, **kwargs).text,
)
self.assertEqual(
"Memory 500/1000 MiB available",
service.handle_request("memory", root, **kwargs).text,
)
self.assertTrue(
service.handle_request("disk-free", root, **kwargs).text.startswith(
"Disk "
)
)
disabled = service.handle_request("reboot", Path("/unused"))
self.assertEqual("Err - host reboot is disabled", disabled.text)
self.assertFalse(disabled.reboot_requested)
enabled = service.handle_request(
"reboot", Path("/unused"), allow_reboot=True, reboot_delay=7
)
self.assertEqual("OK - host reboot scheduled in 7s", enabled.text)
self.assertTrue(enabled.reboot_requested)
self.assertEqual(
service.HostResult("Err - unsupported host request"),
service.handle_request("reboot now", Path("/unused"),
allow_reboot=True),
)
def test_reply_is_utf8_bounded(self) -> None:
text = "x" * 161 + "\N{EURO SIGN}"
bounded = service.bounded_line_text(text)
self.assertLessEqual(len(bounded.encode()), service.MAX_REPLY_BYTES)
self.assertEqual("x" * 161, bounded)
def test_runs_only_a_fixed_program_with_validated_arguments(self) -> None:
programs = {
"fan": service.ProgramDefinition(
alias="fan",
argv=("/usr/local/bin/mesh-fan-control", "--source", "lora"),
arguments=(
service.ProgramArgumentRule(
"state", "choice", choices=("on", "off")
),
service.ProgramArgumentRule(
"minutes", "integer", minimum=1, maximum=60
),
),
timeout_seconds=3,
)
}
completed = subprocess_result = mock.Mock(
returncode=0, stdout="fan scheduled\n"
)
with mock.patch.object(
service.subprocess, "run", return_value=completed
) as run:
result = service.handle_request(
"run fan on 15", Path("/unused"), programs=programs
)
self.assertEqual("fan scheduled", result.text)
self.assertIs(completed, subprocess_result)
argv = run.call_args.args[0]
self.assertEqual(
[
"/usr/local/bin/mesh-fan-control",
"--source",
"lora",
"on",
"15",
],
argv,
)
self.assertFalse(run.call_args.kwargs["shell"])
self.assertEqual("/", run.call_args.kwargs["cwd"])
def test_rejects_program_alias_and_argument_injection(self) -> None:
programs = {
"fan": service.ProgramDefinition(
alias="fan",
argv=("/usr/local/bin/mesh-fan-control",),
arguments=(
service.ProgramArgumentRule(
"state", "choice", choices=("on", "off")
),
),
)
}
rejected = (
"run other on",
"run fan --help",
"run fan on;reboot",
"run fan on\nreboot",
"run fan on extra",
"run fan -1",
)
with mock.patch.object(service.subprocess, "run") as run:
for request in rejected:
with self.subTest(request=request):
self.assertTrue(
service.handle_request(
request, Path("/unused"), programs=programs
).text.startswith("Err -")
)
run.assert_not_called()
def test_loads_a_bounded_program_allowlist(self) -> None:
executable = Path("/bin/echo").resolve()
with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / "programs.json"
config.write_text(
json.dumps(
{
"programs": {
"sample": {
"argv": [str(executable), "fixed"],
"timeout_seconds": 2,
"arguments": [
{
"name": "mode",
"type": "choice",
"choices": ["short", "full"],
},
{
"name": "count",
"type": "integer",
"min": 1,
"max": 5,
},
{
"name": "label",
"type": "token",
"max_bytes": 12,
},
],
}
}
}
),
encoding="utf-8",
)
config.chmod(0o644)
programs = service.load_programs_file(config)
self.assertEqual((str(executable), "fixed"), programs["sample"].argv)
self.assertEqual(3, len(programs["sample"].arguments))
def test_rejects_writable_program_allowlist(self) -> None:
with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / "programs.json"
config.write_text('{"programs": {}}', encoding="ascii")
config.chmod(0o666)
with self.assertRaisesRegex(ValueError, "group/world writable"):
service.load_programs_file(config)
class TokenTests(unittest.TestCase):
def test_signed_remote_serial_token_has_required_claims(self) -> None:
key = service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY)
def signer(message: bytes, public: bytes, private: bytes) -> bytes:
self.assertEqual(bytes.fromhex(PUBLIC_KEY), public)
self.assertEqual(bytes.fromhex(PRIVATE_KEY), private)
self.assertEqual(1, message.count(b"."))
return SIGNATURE
token = service.create_auth_token(
key,
{
"command": (
"host.reply 12345678 FEDCBA9876543210 CPU 47.2 C"
),
"target": "44" * 32,
"nonce": "nonce-value",
},
now=1000,
signer=signer,
)
header_part, payload_part, signature_part = token.split(".")
del header_part
padding = "=" * ((4 - len(payload_part) % 4) % 4)
claims = json.loads(base64.urlsafe_b64decode(payload_part + padding))
self.assertEqual(PUBLIC_KEY, claims["publicKey"])
self.assertEqual(1000, claims["iat"])
self.assertEqual(1030, claims["exp"])
self.assertEqual("44" * 32, claims["target"])
self.assertEqual(SIGNATURE.hex().upper(), signature_part)
class EndpointTests(unittest.TestCase):
def test_request_needs_matching_live_claim_before_reboot(self) -> None:
events: list[object] = []
class PublishResult:
rc = 0
def wait_for_publish(self, timeout: float) -> None:
events.append(("wait", timeout))
class Client:
def publish(self, topic: str, token: str, qos: int) -> PublishResult:
events.append(("publish", topic, token, qos))
return PublishResult()
endpoint = service.HostCliEndpoint(
client=Client(),
repeater_public_key="44" * 32,
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
command_topic="serial/commands",
temperature_path=Path("/unused"),
allow_reboot=True,
reboot_delay=7,
reboot_scheduler=lambda delay: events.append(("reboot", delay)),
challenge_generator=lambda: "A1B2C3D4E5F60718",
monotonic=lambda: 100.0,
)
request = service.HostRequest(
"12345678", "FEDCBA9876543210", "reboot"
)
claim = service.HostClaim(
request.request_id,
request.request_nonce,
"A1B2C3D4E5F60718",
)
def make_token(
_key: service.ServiceKey, claims: dict[str, object]
) -> str:
events.append(("token", claims["command"]))
return "signed"
reboot_result = service.HostResult(
"OK - host reboot scheduled in 7s", reboot_requested=True
)
with mock.patch.object(
service, "parse_and_verify_request", return_value=request
), mock.patch.object(
service, "create_auth_token", side_effect=make_token
), mock.patch.object(
service, "handle_request", return_value=reboot_result
) as handler:
self.assertTrue(endpoint.handle_mqtt_message(b"request"))
handler.assert_not_called()
with mock.patch.object(
service, "parse_and_verify_request", return_value=None
), mock.patch.object(
service, "parse_and_verify_claim", return_value=claim
):
self.assertTrue(endpoint.handle_mqtt_message(b"claim"))
self.assertEqual(
(
"token",
"host.reply 12345678 FEDCBA9876543210 "
"@claim=A1B2C3D4E5F60718",
),
events[0],
)
self.assertEqual("publish", events[1][0])
self.assertEqual(
(
"token",
"host.reply 12345678 FEDCBA9876543210 "
"OK - host reboot scheduled in 7s",
),
events[2],
)
self.assertEqual("publish", events[3][0])
self.assertEqual(("wait", 2.0), events[4])
self.assertEqual(("reboot", 7), events[5])
def test_mismatched_expired_and_replayed_claims_do_not_execute(self) -> None:
now = [10.0]
class Client:
def publish(self, _topic: str, _token: str, qos: int) -> mock.Mock:
self.qos = qos
return mock.Mock(rc=0)
endpoint = service.HostCliEndpoint(
client=Client(),
repeater_public_key="44" * 32,
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
command_topic="serial/commands",
temperature_path=Path("/unused"),
challenge_generator=lambda: "1111222233334444",
monotonic=lambda: now[0],
)
request = service.HostRequest(
"12345678", "FEDCBA9876543210", "cpu-temp"
)
matching = service.HostClaim(
request.request_id, request.request_nonce, "1111222233334444"
)
wrong = service.HostClaim(
request.request_id, request.request_nonce, "9999888877776666"
)
with mock.patch.object(
service, "create_auth_token", return_value="signed"
), mock.patch.object(
service, "handle_request", return_value=service.HostResult("OK")
) as handler:
endpoint._handle_request(request)
endpoint._handle_claim(wrong)
handler.assert_not_called()
endpoint._handle_claim(matching)
handler.assert_called_once()
endpoint._handle_claim(matching)
handler.assert_called_once()
restarted = service.HostCliEndpoint(
client=Client(),
repeater_public_key="44" * 32,
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
command_topic="serial/commands",
temperature_path=Path("/unused"),
)
restarted._handle_claim(matching)
handler.assert_called_once()
later = service.HostCliEndpoint(
client=Client(),
repeater_public_key="44" * 32,
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
command_topic="serial/commands",
temperature_path=Path("/unused"),
challenge_generator=lambda: "5555666677778888",
challenge_timeout_seconds=8.0,
monotonic=lambda: now[0],
)
later._handle_request(request)
now[0] = 19.0
later._handle_claim(
service.HostClaim(
request.request_id,
request.request_nonce,
"5555666677778888",
)
)
handler.assert_called_once()
def test_run_program_is_not_started_by_request_record_alone(self) -> None:
client = mock.Mock()
client.publish.return_value = mock.Mock(rc=0)
programs = {
"sample": service.ProgramDefinition(
alias="sample",
argv=("/usr/bin/printf", "%s"),
arguments=(
service.ProgramArgumentRule(
"value", "choice", choices=("safe",)
),
),
)
}
endpoint = service.HostCliEndpoint(
client=client,
repeater_public_key="44" * 32,
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
command_topic="serial/commands",
temperature_path=Path("/unused"),
programs=programs,
challenge_generator=lambda: "ABCDEF0123456789",
)
request = service.HostRequest(
"12345678", "FEDCBA9876543210", "run sample safe"
)
with mock.patch.object(
service, "create_auth_token", return_value="signed"
), mock.patch.object(service.subprocess, "run") as run:
endpoint._handle_request(request)
run.assert_not_called()
run.return_value = mock.Mock(returncode=0, stdout="done\n")
endpoint._handle_claim(
service.HostClaim(
request.request_id,
request.request_nonce,
"ABCDEF0123456789",
)
)
run.assert_called_once()
def test_failed_challenge_publish_clears_pending_state(self) -> None:
client = mock.Mock()
client.publish.return_value = mock.Mock(rc=7)
endpoint = service.HostCliEndpoint(
client=client,
repeater_public_key="44" * 32,
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
command_topic="serial/commands",
temperature_path=Path("/unused"),
challenge_generator=lambda: "ABCDEF0123456789",
)
request = service.HostRequest(
"12345678", "FEDCBA9876543210", "cpu-temp"
)
with mock.patch.object(
service, "create_auth_token", return_value="signed"
), self.assertRaisesRegex(RuntimeError, "publish failed"):
endpoint._handle_request(request)
self.assertIsNone(endpoint.pending)
self.assertEqual({}, endpoint.seen)
if __name__ == "__main__":
unittest.main()
+241 -16
View File
@@ -101,6 +101,12 @@ extern "C" caddr_t _sbrk(int increment);
#define CLI_REPLY_DELAY_MILLIS 600
#if MESH_ENABLE_HOST_CLI
static_assert(mesh::HostCliBridge::REMOTE_REPLY_MAX
== mesh::RemoteCliReplyCache::MAX_REPLY_TEXT,
"host CLI and remote CLI reply limits must stay aligned");
#endif
// Max time to flush the outbound queue (START alert + CLI reply) before the OTA
// teardown blocks the loop until reboot. Best-effort: exits early once the queue
// drains (immediate on a healthy node), caps the wait on a jammed/duty-limited
@@ -2796,28 +2802,46 @@ void MyMesh::onUserGpioTimerCompleted(uint8_t pin, uint8_t state,
}
#endif
void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
if (!deferred_cli_command.pending) return;
void MyMesh::clearDeferredCliCommand() {
deferred_cli_command.clear();
deferred_cli_reply_scoped = false;
memset(deferred_cli_reply_scope.key, 0, sizeof(deferred_cli_reply_scope.key));
#if MESH_ENABLE_HOST_CLI
host_cli_waiting = false;
host_cli_claimed = false;
host_cli_claim_emit = false;
host_cli_deadline = 0;
host_cli_claim_emit_at = 0;
host_cli_nonce = 0;
host_cli_claim_challenge = 0;
#endif
}
#if MESH_ENABLE_HOST_CLI
bool MyMesh::completeHostCliRequest(const char* service_reply) {
if (!deferred_cli_command.pending || !host_cli_waiting
|| service_reply == NULL) {
return false;
}
const int client_index = deferred_cli_command.client_index;
if (client_index < 0 || client_index >= acl.getNumClients()) {
MESH_DEBUG_PRINTLN("processDeferredCliCommand: invalid client idx: %d", client_index);
deferred_cli_command.clear();
deferred_cli_reply_scoped = false;
memset(deferred_cli_reply_scope.key, 0, sizeof(deferred_cli_reply_scope.key));
return;
MESH_DEBUG_PRINTLN("completeHostCliRequest: invalid client idx: %d",
client_index);
clearDeferredCliCommand();
return false;
}
ClientInfo* client = acl.getClientByIdx(client_index);
char* reply = (char*)&reply_data[5];
reply[0] = 0;
mesh::HostCliBridge::formatRemoteReply(
reply, mesh::HostCliBridge::REMOTE_REPLY_MAX + 1U,
deferred_cli_command.command, service_reply);
const uint32_t command_fingerprint =
mesh::RemoteCliReplyCache::fingerprint(
deferred_cli_command.command,
strlen(deferred_cli_command.command));
handleCommand(deferred_cli_command.sender_timestamp, client,
deferred_cli_command.command, reply, client_index,
deferred_cli_command.path_hash_size);
remote_cli_reply_cache.remember(client->id.pub_key,
deferred_cli_command.request_id,
command_fingerprint, reply);
@@ -2825,9 +2849,173 @@ void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
deferred_cli_command.path_hash_size,
deferred_cli_command.sender_timestamp, reply,
deferred_cli_reply_scoped ? &deferred_cli_reply_scope : NULL);
deferred_cli_command.clear();
deferred_cli_reply_scoped = false;
memset(deferred_cli_reply_scope.key, 0, sizeof(deferred_cli_reply_scope.key));
clearDeferredCliCommand();
return true;
}
bool MyMesh::handleHostCliSerialReply(const char* command, char* reply) {
mesh::HostCliBridge::ReplyView parsed;
const mesh::HostCliBridge::ParseResult result =
mesh::HostCliBridge::parseReply(command, parsed);
if (result == mesh::HostCliBridge::NOT_HOST_COMMAND) return false;
if (reply == NULL) return true;
if (result != mesh::HostCliBridge::VALID_HOST_COMMAND) {
strcpy(reply, "Err - invalid host.reply format");
} else if (!deferred_cli_command.pending || !host_cli_waiting) {
strcpy(reply, "Err - no host request is pending");
} else if (parsed.request_id != deferred_cli_command.request_id
|| parsed.request_nonce != host_cli_nonce) {
strcpy(reply, "Err - host request token mismatch");
} else if (millisHasNowPassed(host_cli_deadline)) {
completeHostCliRequest("Err - host service timeout");
strcpy(reply, "Err - host request expired");
} else {
uint64_t claim_challenge = 0;
const bool is_claim = mesh::HostCliBridge::parseServiceClaim(
parsed.text, parsed.text_len, claim_challenge);
if (is_claim && (host_cli_claimed || host_cli_claim_emit)) {
strcpy(reply, "Err - host request already claimed");
} else if (is_claim) {
host_cli_claim_challenge = claim_challenge;
host_cli_claim_emit = true;
host_cli_claim_emit_at = futureMillis(
mesh::HostCliBridge::SERVICE_CLAIM_EMIT_DELAY_MILLIS);
host_cli_deadline = futureMillis(
mesh::HostCliBridge::SERVICE_REPLY_TIMEOUT_MILLIS);
strcpy(reply, "OK - host claim accepted");
} else if (!host_cli_claimed) {
strcpy(reply, "Err - host request not claimed");
} else if (!completeHostCliRequest(parsed.text)) {
strcpy(reply, "Err - host requester is unavailable");
} else {
strcpy(reply, "OK - host reply accepted");
}
}
return true;
}
#endif
void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
if (!deferred_cli_command.pending) return;
const int client_index = deferred_cli_command.client_index;
if (client_index < 0 || client_index >= acl.getNumClients()) {
MESH_DEBUG_PRINTLN("processDeferredCliCommand: invalid client idx: %d", client_index);
clearDeferredCliCommand();
return;
}
#if MESH_ENABLE_HOST_CLI
if (host_cli_waiting) {
if (millisHasNowPassed(host_cli_deadline)) {
completeHostCliRequest("Err - host service timeout");
return;
}
if (host_cli_claim_emit
&& millisHasNowPassed(host_cli_claim_emit_at)) {
char record[mesh::HostCliBridge::CLAIMED_USB_RECORD_MAX + 1U];
memcpy(record, "DEBUG ", 6);
char* signed_content = record + 6;
if (!mesh::HostCliBridge::formatUsbClaim(
signed_content,
mesh::HostCliBridge::CLAIMED_SIGNED_CONTENT_MAX + 1U,
deferred_cli_command.request_id, host_cli_nonce,
host_cli_claim_challenge)) {
completeHostCliRequest("Err - could not confirm host service");
return;
}
const size_t signed_content_len = strlen(signed_content);
uint8_t signature[SIGNATURE_SIZE];
self_id.sign(signature, (const uint8_t*)signed_content,
signed_content_len);
record[6U + signed_content_len] = ' ';
mesh::Utils::toHex(record + 6U + signed_content_len + 1U,
signature, sizeof(signature));
Serial.println(record);
host_cli_claim_emit = false;
host_cli_claim_emit_at = 0;
host_cli_claimed = true;
}
return;
}
#endif
ClientInfo* client = acl.getClientByIdx(client_index);
char* reply = (char*)&reply_data[5];
reply[0] = 0;
#if MESH_ENABLE_HOST_CLI
mesh::HostCliBridge::RequestView host_request;
const mesh::HostCliBridge::ParseResult host_result =
mesh::HostCliBridge::parseRequest(deferred_cli_command.command,
host_request);
if (host_result != mesh::HostCliBridge::NOT_HOST_COMMAND) {
if (!client->isAdmin()) {
mesh::HostCliBridge::formatRemoteReply(
reply, mesh::HostCliBridge::REMOTE_REPLY_MAX + 1U,
deferred_cli_command.command, "Err - not permitted");
} else if (host_result != mesh::HostCliBridge::VALID_HOST_COMMAND) {
mesh::HostCliBridge::formatRemoteReply(
reply, mesh::HostCliBridge::REMOTE_REPLY_MAX + 1U,
deferred_cli_command.command,
"Err - use: host <text up to 155 bytes>");
} else {
uint64_t request_nonce = 0;
getRNG()->random((uint8_t*)&request_nonce, sizeof(request_nonce));
if (request_nonce == 0) request_nonce = 1;
char record[mesh::HostCliBridge::USB_RECORD_MAX + 1U];
memcpy(record, "DEBUG ", 6);
char* signed_content = record + 6;
if (mesh::HostCliBridge::formatUsbRequest(
signed_content,
mesh::HostCliBridge::USB_SIGNED_CONTENT_MAX + 1U,
deferred_cli_command.request_id, request_nonce,
host_request.text, host_request.text_len)) {
const size_t signed_content_len = strlen(signed_content);
uint8_t signature[SIGNATURE_SIZE];
self_id.sign(signature, (const uint8_t*)signed_content,
signed_content_len);
record[6U + signed_content_len] = ' ';
mesh::Utils::toHex(record + 6U + signed_content_len + 1U,
signature, sizeof(signature));
Serial.println(record);
host_cli_waiting = true;
host_cli_claimed = false;
host_cli_claim_emit = false;
host_cli_claim_emit_at = 0;
host_cli_nonce = request_nonce;
host_cli_claim_challenge = 0;
host_cli_deadline = futureMillis(
mesh::HostCliBridge::SERVICE_CLAIM_TIMEOUT_MILLIS);
return;
}
mesh::HostCliBridge::formatRemoteReply(
reply, mesh::HostCliBridge::REMOTE_REPLY_MAX + 1U,
deferred_cli_command.command,
"Err - could not encode host request");
}
} else {
#endif
handleCommand(deferred_cli_command.sender_timestamp, client,
deferred_cli_command.command, reply, client_index,
deferred_cli_command.path_hash_size);
#if MESH_ENABLE_HOST_CLI
}
#endif
const uint32_t command_fingerprint =
mesh::RemoteCliReplyCache::fingerprint(
deferred_cli_command.command,
strlen(deferred_cli_command.command));
remote_cli_reply_cache.remember(client->id.pub_key,
deferred_cli_command.request_id,
command_fingerprint, reply);
sendRemoteCliReply(client, deferred_cli_command.secret,
deferred_cli_command.path_hash_size,
deferred_cli_command.sender_timestamp, reply,
deferred_cli_reply_scoped ? &deferred_cli_reply_scope : NULL);
clearDeferredCliCommand();
}
bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
@@ -2948,6 +3136,15 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
next_local_advert = next_flood_advert = 0;
deferred_cli_reply_scoped = false;
memset(deferred_cli_reply_scope.key, 0, sizeof(deferred_cli_reply_scope.key));
#if MESH_ENABLE_HOST_CLI
host_cli_waiting = false;
host_cli_claimed = false;
host_cli_claim_emit = false;
host_cli_deadline = 0;
host_cli_claim_emit_at = 0;
host_cli_nonce = 0;
host_cli_claim_challenge = 0;
#endif
pending_self_advert_delay = 0;
pending_self_advert = false;
pending_self_advert_flood = false;
@@ -3012,7 +3209,7 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
clock_sync_last_fresh_count = 0;
clock_sync_last_required_count = CLOCK_SYNC_REQUIRED_SAMPLES_DEFAULT;
clock_sync_required_samples = CLOCK_SYNC_REQUIRED_SAMPLES_DEFAULT;
clock_sync_drift_seconds = CLOCK_SYNC_DRIFT_DEFAULT_SECONDS;
clock_sync_drift_seconds = mesh::CLOCK_SYNC_DRIFT_DEFAULT_SECONDS;
clock_sync_last_estimate = 0;
clock_sync_last_abs_drift = 0;
clock_sync_internet_requested_millis = 0;
@@ -8893,7 +9090,7 @@ void MyMesh::loadClockSyncPrefs() {
clock_sync_mesh_enabled = CLOCK_SYNC_MESH_DEFAULT_ENABLED != 0;
clock_sync_mesh_edge_enabled = CLOCK_SYNC_MESH_EDGE_DEFAULT_ENABLED != 0;
clock_sync_internet_enabled = false;
clock_sync_drift_seconds = CLOCK_SYNC_DRIFT_DEFAULT_SECONDS;
clock_sync_drift_seconds = mesh::CLOCK_SYNC_DRIFT_DEFAULT_SECONDS;
clock_sync_required_samples = CLOCK_SYNC_REQUIRED_SAMPLES_DEFAULT;
if (_fs != NULL && _fs->exists(CLOCK_SYNC_PREFS_FILE)) {
@@ -10183,6 +10380,34 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, ClientInfo* sender, char *
const mesh::cli::NoArgCommandMatch discover_neighbors_match =
mesh::cli::matchNoArgCommand(command, "discover.neighbors");
#if MESH_ENABLE_HOST_CLI
if (strcmp(command, "get host") == 0) {
if (host_cli_waiting && deferred_cli_command.pending) {
snprintf(reply, 160,
"> waiting,%s,id=%08lX,request_max=%u,reply_max=%u,"
"claim=%lus,reply=%lus",
(host_cli_claimed || host_cli_claim_emit) ? "reply" : "claim",
(unsigned long)deferred_cli_command.request_id,
(unsigned)mesh::HostCliBridge::REQUEST_TEXT_MAX,
(unsigned)mesh::HostCliBridge::REMOTE_REPLY_MAX,
(unsigned long)(
mesh::HostCliBridge::SERVICE_CLAIM_TIMEOUT_MILLIS / 1000UL),
(unsigned long)(
mesh::HostCliBridge::SERVICE_REPLY_TIMEOUT_MILLIS / 1000UL));
} else {
snprintf(reply, 160,
"> ready,idle,request_max=%u,reply_max=%u,claim=%lus,reply=%lus",
(unsigned)mesh::HostCliBridge::REQUEST_TEXT_MAX,
(unsigned)mesh::HostCliBridge::REMOTE_REPLY_MAX,
(unsigned long)(
mesh::HostCliBridge::SERVICE_CLAIM_TIMEOUT_MILLIS / 1000UL),
(unsigned long)(
mesh::HostCliBridge::SERVICE_REPLY_TIMEOUT_MILLIS / 1000UL));
}
return;
}
#endif
#if MESH_ENABLE_TELEMETRY_HISTORY
const char* telemetry_args = NULL;
mesh::TelemetryHistory::Series telemetry_series =
+22 -1
View File
@@ -83,6 +83,12 @@
#include <helpers/ClientACL.h>
#include <helpers/CommonCLI.h>
#include <helpers/DeferredCliCommand.h>
#ifndef MESH_ENABLE_HOST_CLI
#define MESH_ENABLE_HOST_CLI 1
#endif
#if MESH_ENABLE_HOST_CLI
#include <helpers/HostCliBridge.h>
#endif
#include <helpers/RemoteCliReplyCache.h>
#include <helpers/RemoteCliRequest.h>
#if defined(ESP32_PLATFORM) || defined(USER_GPIO_CONTROL)
@@ -246,7 +252,6 @@ struct NeighbourInfo {
#define CLOCK_SYNC_CONSENSUS_WINDOW_SECONDS 600UL
#define CLOCK_SYNC_DRIFT_MIN_SECONDS 30UL
#define CLOCK_SYNC_DRIFT_MAX_SECONDS 86400UL
#define CLOCK_SYNC_DRIFT_DEFAULT_SECONDS 3600UL
#define CLOCK_SYNC_MESH_SUPPRESS_NONE 0
#define CLOCK_SYNC_MESH_SUPPRESS_CLI 1
#define CLOCK_SYNC_MESH_SUPPRESS_GPS 2
@@ -282,6 +287,15 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
mesh::RemoteCliReplyCache remote_cli_reply_cache;
TransportKey deferred_cli_reply_scope;
bool deferred_cli_reply_scoped;
#if MESH_ENABLE_HOST_CLI
bool host_cli_waiting;
bool host_cli_claimed;
bool host_cli_claim_emit;
unsigned long host_cli_deadline;
unsigned long host_cli_claim_emit_at;
uint64_t host_cli_nonce;
uint64_t host_cli_claim_challenge;
#endif
uint32_t pending_self_advert_delay;
bool pending_self_advert;
bool pending_self_advert_flood;
@@ -597,6 +611,10 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
int handleRequest(ClientInfo* sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len);
mesh::Packet* createSelfAdvert();
void processDeferredCliCommand();
void clearDeferredCliCommand();
#if MESH_ENABLE_HOST_CLI
bool completeHostCliRequest(const char* service_reply);
#endif
void sendRemoteCliReply(ClientInfo* client, const uint8_t* secret,
uint8_t path_hash_size, uint32_t sender_timestamp,
const char* reply, const TransportKey* fallback_scope);
@@ -936,6 +954,9 @@ public:
void handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
handleCommand(sender_timestamp, NULL, command, reply);
}
#if MESH_ENABLE_HOST_CLI
bool handleHostCliSerialReply(const char* command, char* reply);
#endif
void loop();
uint32_t getPowerSaveSleepSeconds(uint32_t max_secs) const;
+53 -10
View File
@@ -47,7 +47,14 @@ void halt() {
while (1) ;
}
static char command[160];
#if MESH_ENABLE_HOST_CLI
static constexpr size_t LOCAL_SERIAL_COMMAND_MAX =
mesh::HostCliBridge::SERIAL_REPLY_COMMAND_MAX;
#else
static constexpr size_t LOCAL_SERIAL_COMMAND_MAX = 159U;
#endif
static char command[LOCAL_SERIAL_COMMAND_MAX + 2U];
static bool command_overflow = false;
#ifdef ETHERNET_ENABLED
static char ethernet_command[160];
#endif
@@ -179,30 +186,66 @@ void setup() {
static void __attribute__((noinline)) serviceCommandInterfaces() {
// Handle Serial CLI
int len = strlen(command);
while (Serial.available() && len < sizeof(command)-1) {
bool line_complete = false;
bool overlong_line_complete = false;
while (Serial.available()) {
char c = Serial.read();
if (c != '\n') {
if (c == '\n') continue;
Serial.print(c);
if (command_overflow) {
if (c == '\r') {
command_overflow = false;
overlong_line_complete = true;
break;
}
continue;
}
if (c == '\r') {
line_complete = true;
break;
}
if ((size_t)len < LOCAL_SERIAL_COMMAND_MAX) {
command[len++] = c;
command[len] = 0;
Serial.print(c);
} else {
// Discard the entire record through its delimiter. Never parse a
// truncated prefix as one command and its tail as a second command.
command[0] = 0;
len = 0;
command_overflow = true;
}
if (c == '\r') break;
}
if (len == sizeof(command)-1) { // command buffer full
command[sizeof(command)-1] = '\r';
}
if (len > 0 && command[len - 1] == '\r') { // received complete line
if (overlong_line_complete) {
Serial.print('\n');
Serial.println(" -> Err - command too long");
command[0] = 0;
return;
}
if (line_complete) {
Serial.print('\n');
command[len - 1] = 0; // replace newline with C string null terminator
char reply[160];
reply[0] = 0;
#ifdef ETHERNET_ENABLED
if (!ethernet_handle_command(command, reply)) {
#if MESH_ENABLE_HOST_CLI
if (!the_mesh.handleHostCliSerialReply(command, reply)) {
the_mesh.handleCommand(0, command, reply);
}
#else
the_mesh.handleCommand(0, command, reply);
#endif
}
#else
#if MESH_ENABLE_HOST_CLI
if (!the_mesh.handleHostCliSerialReply(command, reply)) {
the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
}
#else
the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
#endif
#endif
if (reply[0]) {
Serial.print(" -> "); Serial.println(reply);