SensESP 3.5.1-alpha
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
signalk_ws_client.h
Go to the documentation of this file.
1#ifndef SENSESP_SRC_SENSESP_SIGNALK_SIGNALK_WS_CLIENT_H_
2#define SENSESP_SRC_SENSESP_SIGNALK_SIGNALK_WS_CLIENT_H_
3
4#include "sensesp.h"
5
6#include <algorithm>
7
8#include <ArduinoJson.h>
9#include <esp_websocket_client.h>
10#include <atomic>
11#include <functional>
12#include <list>
13#include <set>
14
20#include "sensesp_base_app.h"
21
22// Maximum number of received value/put deltas buffered for processing on the
23// main task. Oldest entries are dropped when the buffer is full.
24#ifndef SENSESP_MAX_RECEIVED_VALUE_UPDATES
25#define SENSESP_MAX_RECEIVED_VALUE_UPDATES 20
26#endif
27
28// Maximum number of received meta deltas buffered for processing on the main
29// task, budgeted independently of value deltas so a metadata burst (~one entry
30// per subscribed path at subscribe time when sendMeta=all is enabled) cannot
31// evict pending values, and vice versa. Override per board via build_flags if
32// you subscribe many paths and need the full burst delivered (more paths =>
33// more buffered meta => more RAM).
34#ifndef SENSESP_MAX_RECEIVED_META_UPDATES
35#define SENSESP_MAX_RECEIVED_META_UPDATES 20
36#endif
37
38// Signal K WebSocket buffer size in bytes, allocated by esp_websocket_client for
39// both the tx and rx buffer. send_delta drops any delta longer than this rather
40// than let esp_websocket_client split it across non-blocking writes and abort
41// the connection (see signalk_ws_delta_size.h). Override per board via
42// build_flags to hold the largest delta a device sends (e.g. a GNSS receiver's
43// full-sky satellitesInView); kept small by default for memory-constrained
44// boards.
45#ifndef SENSESP_SK_WS_BUFFER_SIZE
46#define SENSESP_SK_WS_BUFFER_SIZE 1024
47#endif
48
49namespace sensesp {
50
51static const char* NULL_AUTH_TOKEN = "";
52
53// HTTP status returned on a WebSocket upgrade when the Signal K server rejects
54// the auth token.
55static constexpr int kHttpUnauthorized = 401;
56
72bool should_clear_token_on_status(int handshake_status);
73
79 // TLS certificate pinning rejected the server certificate. Distinct from a
80 // plain disconnect so the UI can tell a cert problem from a network drop.
82};
83
89 virtual public ValueProducer<SKWSConnectionState> {
90 public:
92 // main task methods
93
94 SKWSClient(const String& config_path,
95 std::shared_ptr<SKDeltaQueue> sk_delta_queue,
96 const String& server_address, uint16_t server_port,
97 bool use_mdns = true);
98
99 const String get_server_address() const { return server_address_; }
100 uint16_t get_server_port() const { return server_port_; }
101
102 virtual bool to_json(JsonObject& root) override final;
103 virtual bool from_json(const JsonObject& config) override final;
104
112
121
122 String get_connection_status();
123
125 // SK websocket connection methods
126
127 void on_disconnected();
128 // handshake_status is the HTTP status of a failed WebSocket upgrade (0 if not
129 // applicable); a 401 means the auth token was rejected.
130 void on_error(int handshake_status);
131 void on_connected();
132 void on_receive_delta(uint8_t* payload, size_t length);
133 void on_receive_updates(JsonDocument& message);
134 void on_receive_put(JsonDocument& message);
135 void connect();
136 void loop();
137 bool is_connected();
146 void restart();
147 bool is_connect_due() const { return millis() >= next_attempt_ms_; }
148 void send_delta();
149
155 void sendTXT(String& payload);
156
160 bool is_ssl_enabled() const { return ssl_enabled_; }
161
178 String get_auth_token() const { return auth_token_; }
179
186 void set_ssl_enabled(bool enabled) {
187 ssl_enabled_ = enabled;
188 save();
189 }
190
205 void set_send_meta_enabled(bool enabled) {
206 send_meta_enabled_ = enabled;
207 save();
208 }
209
213 bool is_tofu_enabled() const { return tofu_enabled_; }
214
222 void set_tofu_enabled(bool enabled) {
223 tofu_enabled_ = enabled;
224 save();
225 }
226
228 bool has_tofu_anchor() const {
229 return !tofu_ca_pem_.isEmpty() || !tofu_fingerprint_.isEmpty();
230 }
231
233 bool has_tofu_ca() const { return !tofu_ca_pem_.isEmpty(); }
234 const String& get_tofu_ca() const { return tofu_ca_pem_; }
235
237 bool has_tofu_fingerprint() const { return !tofu_fingerprint_.isEmpty(); }
238 const String& get_tofu_fingerprint() const { return tofu_fingerprint_; }
239
241 const String& get_tofu_pin_cn() const { return tofu_pin_cn_; }
242 bool is_tofu_pin_ca() const { return tofu_pin_is_ca_; }
243
248 const String& get_tofu_san() const { return tofu_san_; }
249
257 void reset_tofu() {
258 tofu_ca_pem_ = "";
260 tofu_pin_cn_ = "";
261 tofu_pin_is_ca_ = false;
262 tofu_san_ = "";
263 save();
264 }
265
269 void stash_pending_ca(const String& ca_pem, const String& cn) {
270 pending_ca_pem_ = ca_pem;
272 pending_cn_ = cn;
273 pending_is_ca_ = true;
274 pending_valid_ = true;
275 }
276 void stash_pending_leaf(const String& fingerprint, const String& cn) {
277 pending_ca_pem_ = "";
278 pending_fingerprint_ = fingerprint;
279 pending_cn_ = cn;
280 pending_is_ca_ = false;
281 pending_valid_ = true;
282 }
285 void set_pending_san(const String& san) { pending_san_ = san; }
287 pending_ca_pem_ = "";
289 pending_cn_ = "";
290 pending_san_ = "";
291 pending_is_ca_ = false;
292 pending_valid_ = false;
293 }
295 bool has_pending_ca() const { return pending_valid_ && pending_is_ca_; }
299 if (!pending_valid_) {
300 return;
301 }
304 if (pending_is_ca_) {
307 tofu_san_ = pending_san_; // bind the leaf identity in CA-anchor mode
308 } else {
310 tofu_ca_pem_ = "";
311 tofu_san_ = ""; // leaf mode: the fingerprint binds identity
312 }
314 save();
315 }
316
319 void flag_cert_error() { cert_error_.store(true); }
320
324 uint32_t client_generation() const { return client_generation_.load(); }
325
326 protected:
327 // these are the actually used values
328 String server_address_ = "";
329 uint16_t server_port_ = 80;
330 // these are the hardcoded and/or conf file values
332 uint16_t conf_server_port_ = 0;
333 bool use_mdns_ = true;
334
335 String client_id_ = "";
336 String polling_href_ = "";
337 String auth_token_ = NULL_AUTH_TOKEN;
338
339 unsigned long next_attempt_ms_ = 0;
340 unsigned long connect_interval_ms_ = 2000;
341
342 // SSL/TLS configuration
343 bool ssl_enabled_ = false;
344 bool tofu_enabled_ = true; // TOFU enabled by default
345
346 // Subscribe with ?sendMeta=all so metadata (zones, units, etc) is
347 // pushed in-stream rather than requiring REST /meta polls.
349
350 // TOFU trust anchor. At most one of these is non-empty once captured:
351 // tofu_ca_pem_ — PEM of the pinned issuing CA (CA-anchor mode)
352 // tofu_fingerprint_ — SHA256 hex of the pinned leaf (leaf-fingerprint mode,
353 // and the legacy on-disk format the migration reads)
354 String tofu_fingerprint_ = ""; // SHA256 fingerprint in hex (64 chars)
355 String tofu_ca_pem_ = ""; // PEM of pinned CA (CA-anchor mode)
356 // TOFU'd leaf identity (normalized DNS SAN set) bound in CA-anchor mode, so a
357 // reconnecting leaf must present the same identity AND chain to the pinned CA.
358 // This is what makes CA pinning safe against a public CA (e.g. Let's Encrypt):
359 // a valid leaf for a different name from the same CA fails the identity check.
360 // Empty in leaf-fingerprint mode.
361 String tofu_san_ = "";
362 // Display-only identity of the pinned cert, captured at pin time (X.509
363 // parsing is only available during the handshake). The CN is attacker-
364 // controlled at capture and is bounded + sanitized before storage.
365 String tofu_pin_cn_ = "";
366 bool tofu_pin_is_ca_ = false;
367
368 // Candidate anchor seen during the current connection attempt, persisted only
369 // after the connection succeeds (commit_pending_tofu) so an unauthenticated
370 // MITM handshake cannot plant a trust anchor.
371 String pending_ca_pem_ = "";
373 String pending_cn_ = "";
374 String pending_san_ = "";
375 bool pending_is_ca_ = false;
376 bool pending_valid_ = false;
377
378 // Set by the verify callback (transport task) on certificate rejection; read
379 // by set_connection_state to surface kSKWSCertificateError. Atomic because the
380 // callback and state changes may run on different cores.
381 std::atomic<bool> cert_error_{false};
382
385
390
391 // Atomic for pointer-atomicity: the connect worker builds/stores it; the
392 // SK/event-loop context loads it to send and reaps it via exchange(nullptr)
393 // (single check-and-null, so no double-free). Writers are serialized
394 // single-owner-at-a-time by auth_job_running_ / teardown_in_progress_.
395 // NOTE: the atomic confers pointer-atomicity, not lifetime safety. send_delta
396 // and sendTXT run on the event loop, serialized with detach_teardown (same
397 // context), so they cannot hold a handle across its reap. Transport-task
398 // senders (on_connected -> subscribe_listeners, on_receive_put's response)
399 // are made safe by esp_websocket_client_stop() joining the transport task
400 // before destroy() frees the struct. See #1033.
401 std::atomic<esp_websocket_client_handle_t> client_{nullptr};
402 // Bumped on every teardown so the (singleton) event handler can drop late
403 // callbacks from a client that has been handed off for destruction. The
404 // handler is registered with the generation current at build time; an event
405 // whose generation != client_generation_ comes from a torn-down client.
406 std::atomic<uint32_t> client_generation_{0};
407 // True while a detached task is stopping+destroying a previous client.
408 // Bring-up is deferred until it clears, so at most one client ever exists.
409 std::atomic<bool> teardown_in_progress_{false};
410 // True while a one-shot worker is running a (blocking) connect attempt
411 // (mDNS / SSL-detect / access-request / poll legs). The dispatcher skips
412 // while it is set, so at most one attempt runs at a time.
413 std::atomic<bool> auth_job_running_{false};
414 // Holds a handle whose detached reaper task failed to spawn (OOM); the event
415 // loop retries the spawn each tick rather than reaping it synchronously (which
416 // would block the loop). At most one at a time (teardown_in_progress_ defers
417 // bring-up until it is reaped).
418 std::atomic<esp_websocket_client_handle_t> pending_teardown_{nullptr};
419 std::shared_ptr<SKDeltaQueue> sk_delta_queue_;
424
429
437 bool is_meta = false;
438 JsonDocument doc;
439 };
440
442 SemaphoreHandle_t received_updates_semaphore_ =
443 xSemaphoreCreateRecursiveMutexStatic(&received_updates_semaphore_buffer_);
444 std::list<ReceivedUpdate> received_updates_{};
445
447 // methods for all tasks
448
449 bool take_received_updates_semaphore(unsigned long int timeout_ms = 0) {
450 if (timeout_ms == 0) {
451 return xSemaphoreTakeRecursive(received_updates_semaphore_,
452 portMAX_DELAY) == pdTRUE;
453 } else {
454 return xSemaphoreTakeRecursive(received_updates_semaphore_,
455 timeout_ms) == pdTRUE;
456 }
457 }
459 xSemaphoreGiveRecursive(received_updates_semaphore_);
460 }
461
466 void enqueue_received_update(ReceivedUpdate&& update);
467
469 // main task methods
470
472
474 // SK websocket connection methods
475
476#ifndef SENSESP_SSL_SUPPORT
477 // Validate the auth token over plain HTTP before opening the WebSocket
478 // stream. Only used on non-SSL builds; SSL builds validate it on the upgrade
479 // itself (see connect()) to avoid a second TLS handshake that fragments the
480 // heap.
481 void test_token(const String host, const uint16_t port);
482#endif
483 void send_access_request(const String host, const uint16_t port);
484 void poll_access_request(const String host, const uint16_t port,
485 const String href);
486 void connect_ws(const String& host, const uint16_t port);
493 void detach_teardown();
497 void reap_async(esp_websocket_client_handle_t old);
499 static void teardown_task(void* arg);
503 void run_connect_attempt();
504 static void connect_worker(void* arg);
505 void subscribe_listeners();
506 bool get_mdns_service(String& server_address, uint16_t& server_port);
507 bool detect_ssl();
508
510 // A certificate rejection during this attempt (flagged by the verify
511 // callback) is surfaced distinctly instead of as a generic disconnect.
512 // This is the single chokepoint, so it covers all four TLS paths — the
513 // three esp_http_client requests and the websocket — without touching each
514 // call site. A fresh attempt (authorizing/connecting) or success clears the
515 // flag.
518 } else if (state != SKWSConnectionState::kSKWSDisconnected &&
520 cert_error_.store(false);
521 }
523 connection_state_.set(state);
524 }
526
529 (esp_random() % (connect_interval_ms_ / 4 + 1));
531 std::min(connect_interval_ms_ * 2, (unsigned long)60000);
532 }
533
537};
538
539inline const String ConfigSchema(const SKWSClient& obj) {
540 return "{\"type\":\"object\",\"properties\":{"
541 "\"ssl_enabled\":{\"title\":\"SSL/TLS Enabled\",\"type\":\"boolean\"},"
542 "\"tofu_enabled\":{\"title\":\"TOFU Verification\",\"type\":\"boolean\"},"
543 "\"tofu_pin_cn\":{\"title\":\"Pinned Certificate\",\"type\":\"string\",\"readOnly\":true},"
544 "\"tofu_pin_is_ca\":{\"title\":\"Pinned as CA\",\"type\":\"boolean\",\"readOnly\":true},"
545 "\"send_meta_enabled\":{\"title\":\"Subscribe with sendMeta=all\","
546 "\"description\":\"Request metadata deltas (units, zones, displayName, displayUnits) over the WS stream. Disable only for constrained clients that ignore them.\","
547 "\"type\":\"boolean\"}"
548 "}}";
549}
550
551inline bool ConfigRequiresRestart(const SKWSClient& obj) { return true; }
552
553} // namespace sensesp
554
555#endif
virtual bool save() override
Save the object to a persistent storage.
Definition saveable.cpp:40
Integrator integrates (accumulates) the incoming values.
Definition integrator.h:19
The websocket connection to the Signal K server.
void commit_pending_tofu()
Persist a stashed anchor after a successful (authenticated) connection. Called from on_connected().
void poll_access_request(const String host, const uint16_t port, const String href)
void on_receive_delta(uint8_t *payload, size_t length)
Called when the websocket receives a delta.
SemaphoreHandle_t received_updates_semaphore_
unsigned long connect_interval_ms_
void process_received_updates()
Loop through the received updates and process them.
void set_ssl_enabled(bool enabled)
Enable or disable SSL/TLS manually.
const String & get_tofu_ca() const
std::atomic< esp_websocket_client_handle_t > pending_teardown_
std::atomic< bool > auth_job_running_
void connect_ws(const String &host, const uint16_t port)
void stash_pending_leaf(const String &fingerprint, const String &cn)
unsigned long next_attempt_ms_
Integrator< int, int > delta_tx_count_producer_
TaskQueueProducer< SKWSConnectionState > connection_state_
const String & get_tofu_pin_cn() const
Identity (CN) of whatever is pinned, and whether it is a CA.
SKWSConnectionState get_connection_state()
std::atomic< bool > teardown_in_progress_
void on_receive_put(JsonDocument &message)
Called when a PUT event is received.
uint32_t client_generation() const
Generation tag of the currently-valid client. The event handler compares the generation it was regist...
void release_received_updates_semaphore()
void run_connect_attempt()
The (blocking) connect attempt — mDNS resolve, SSL detect, and the access-request / poll / connect_ws...
SKWSConnectionState task_connection_state_
void send_access_request(const String host, const uint16_t port)
std::atomic< uint32_t > client_generation_
void on_error(int handshake_status)
Called when the websocket connection encounters an error.
Integrator< int, int > delta_rx_count_producer_
std::list< ReceivedUpdate > received_updates_
bool is_send_meta_enabled() const
Whether the WS subscribes with sendMeta=all.
virtual bool to_json(JsonObject &root) override final
uint16_t get_server_port() const
void detach_teardown()
Hand client_ to a detached one-shot task that stops+destroys it, so the blocking teardown never runs ...
void enqueue_received_update(ReceivedUpdate &&update)
Push a received delta entry onto the queue, enforcing a per-kind budget so a metadata burst (one meta...
void sendTXT(String &payload)
Send some processed data to the websocket.
uint32_t last_oversize_log_ms_
millis() timestamp of the last oversize-delta-drop warning, used to rate-limit it when a device keeps...
bool get_mdns_service(String &server_address, uint16_t &server_port)
std::atomic< esp_websocket_client_handle_t > client_
const String & get_tofu_san() const
TOFU'd leaf identity (normalized DNS SAN set) bound in CA-anchor mode. A reconnecting leaf must chain...
void on_disconnected()
Called when the websocket connection is disconnected.
ValueProducer< int > & get_delta_tx_count_producer()
void reap_async(esp_websocket_client_handle_t old)
Spawn the detached reaper for old; on spawn failure (OOM) stash it in pending_teardown_ for a later r...
void subscribe_listeners()
Subscribes the SK delta paths to the websocket.
void on_receive_updates(JsonDocument &message)
Called when a delta update is received.
void test_token(const String host, const uint16_t port)
bool has_tofu_ca() const
True if a pinned CA certificate is stored (CA-anchor mode).
bool has_tofu_fingerprint() const
True if a pinned leaf fingerprint is stored (leaf-fingerprint mode).
void set_connection_state(SKWSConnectionState state)
ValueProducer< int > & get_delta_rx_count_producer()
Get the delta rx count producer object.
void stash_pending_ca(const String &ca_pem, const String &cn)
Stash a candidate anchor seen during a handshake. Persisted only after the connection succeeds (commi...
bool take_received_updates_semaphore(unsigned long int timeout_ms=0)
StaticSemaphore_t received_updates_semaphore_buffer_
virtual bool from_json(const JsonObject &config) override final
void set_tofu_enabled(bool enabled)
Enable or disable TOFU certificate verification.
std::atomic< bool > cert_error_
void set_pending_san(const String &san)
Record the leaf's identity (SAN set) for the pending CA anchor, captured at depth 0 and committed alo...
String get_connection_status()
Get a String representation of the current connection state.
static void connect_worker(void *arg)
void set_send_meta_enabled(bool enabled)
const String get_server_address() const
TaskQueueProducer< int > delta_tx_tick_producer_
Emits the number of deltas sent since last report.
void reset_tofu()
Reset the stored trust anchor (CA or leaf fingerprint).
static void teardown_task(void *arg)
Body of the detached teardown task (stop+destroy+self-delete).
bool has_tofu_anchor() const
True if any trust anchor (pinned CA or leaf fingerprint) is stored.
const String & get_tofu_fingerprint() const
bool is_ssl_enabled() const
Check if SSL/TLS is enabled.
std::shared_ptr< SKDeltaQueue > sk_delta_queue_
void restart()
Drop the current connection (detached, non-blocking teardown) and let the reconnect path rebuild it.
void on_connected()
Called when the websocket connection is established.
bool is_tofu_enabled() const
Check if TOFU certificate verification is enabled.
String get_auth_token() const
Current Signal K access token, or an empty string if none.
bool has_pending_ca() const
True if a candidate CA has already been stashed this handshake.
void flag_cert_error()
Flag a certificate rejection from the verify callback so the next disconnect surfaces as kSKWSCertifi...
Producer class that works across task boundaries.
virtual void set(const T &value) override
A base class for any sensor or piece of code that outputs a value for consumption elsewhere.
const String ConfigSchema(const SmartSwitchController &obj)
std::shared_ptr< reactesp::EventLoop > event_loop()
Definition sensesp.cpp:9
bool should_clear_token_on_status(int handshake_status)
Decide whether a failed WebSocket upgrade should clear the auth token.
bool ConfigRequiresRestart(const HTTPServer &obj)
A single received delta entry awaiting dispatch on the main task.