From 10c452f8acd688af89b78dd819871b7bb328e33e Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 11:45:09 -0500 Subject: [PATCH 1/2] Hold the server's id and name inline The connection kept the server's identity as a ServerInformationObject, two std::strings, and the published slot copied it: a 43-character id outgrows both standard libraries' inline strings, and libstdc++'s also the name, so admission made 3 (libc++) or 5 (libstdc++) heap allocations for it. InlineText holds bounded text in the object (IdText is now one), and the connection and the published slot keep the id and a 64-byte name in it. get_server_information() builds the public strings on the caller's thread. server/hello's name and group/update's group_name are truncated to 64 UTF-8 bytes at a character boundary, the cap the spec is adding. Admission now allocates once on both libraries: the trust note. --- include/sendspin/client.h | 6 +- include/sendspin/types.h | 2 + src/admission.h | 4 +- src/client.cpp | 15 ++-- src/client_dispatch.cpp | 6 +- src/connection.cpp | 15 ++-- src/connection.h | 28 ++++---- src/connection_manager.cpp | 40 ++++++----- src/connection_manager.h | 25 ++++--- src/connection_manager_pairing.cpp | 26 +++---- src/crypto/keys.h | 48 +------------ src/inline_text.h | 103 ++++++++++++++++++++++++++++ src/protocol.cpp | 17 ++++- src/protocol_messages.h | 11 ++- src/record_store.cpp | 4 +- src/record_store.h | 4 +- tests/CMakeLists.txt | 1 + tests/test_allocations.cpp | 9 +-- tests/test_connection_lifecycle.cpp | 1 + tests/test_inline_text.cpp | 68 ++++++++++++++++++ tests/test_protocol.cpp | 37 +++++++++- tools/stack_usage/README.md | 4 +- 22 files changed, 337 insertions(+), 137 deletions(-) create mode 100644 src/inline_text.h create mode 100644 tests/test_inline_text.cpp diff --git a/include/sendspin/client.h b/include/sendspin/client.h index ca669c37..1a298e87 100644 --- a/include/sendspin/client.h +++ b/include/sendspin/client.h @@ -967,13 +967,13 @@ class SendspinClient { // listener callback for delivery from the main loop's drain_inbox(). /// @brief Queue an on_pairing_started notification - void note_pairing_started(const std::string& server_id); + void note_pairing_started(std::string_view server_id); /// @brief Queue an on_pairing_succeeded notification - void note_pairing_succeeded(const std::string& server_id); + void note_pairing_succeeded(std::string_view server_id); /// @brief Queue an on_pairing_failed notification - void note_pairing_failed(const std::string& server_id, SendspinPairAbortReason reason); + void note_pairing_failed(std::string_view server_id, SendspinPairAbortReason reason); /// @brief Queue an on_display_pairing_code notification void note_display_pairing_code(const std::string& code, SendspinPairingCodeFormat format); diff --git a/include/sendspin/types.h b/include/sendspin/types.h index f023bb09..bd2800ab 100644 --- a/include/sendspin/types.h +++ b/include/sendspin/types.h @@ -42,6 +42,7 @@ enum class SendspinGoodbyeReason : uint8_t { /// @brief Server identity fields received in server/hello messages struct ServerInformationObject { std::string server_id{}; + /// At most 64 bytes in UTF-8, cut at a character boundary std::string name{}; }; @@ -55,6 +56,7 @@ enum class SendspinPlaybackState : uint8_t { struct GroupUpdateObject { std::optional playback_state{}; std::optional group_id{}; + /// At most 64 bytes in UTF-8, cut at a character boundary std::optional group_name{}; }; diff --git a/src/admission.h b/src/admission.h index a7e1fcea..46e69d07 100644 --- a/src/admission.h +++ b/src/admission.h @@ -178,9 +178,9 @@ inline int activity_rank(ActivitySet activities) { /// shielding a pairing that has finished. /// @return true if the incoming connection should become the admitted one. inline bool should_admit_connection(ActivitySet incoming_activities, - const std::string& incoming_server_id, + std::string_view incoming_server_id, ActivitySet admitted_activities, - const std::string& admitted_server_id, bool has_admitted, + std::string_view admitted_server_id, bool has_admitted, std::string_view last_playback_server_id, bool admitted_pairing_in_flight) { if (!has_admitted) { diff --git a/src/client.cpp b/src/client.cpp index b9a7f3db..c35dfa10 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1740,20 +1740,21 @@ void SendspinClient::on_activation_applied([[maybe_unused]] SendspinConnection* #endif } -void SendspinClient::note_pairing_started(const std::string& server_id) { +void SendspinClient::note_pairing_started(std::string_view server_id) { this->event_state_->push_pairing_note( - {.type = PairingNoteType::PAIRING_STARTED, .text = server_id}); + {.type = PairingNoteType::PAIRING_STARTED, .text = std::string(server_id)}); } -void SendspinClient::note_pairing_succeeded(const std::string& server_id) { +void SendspinClient::note_pairing_succeeded(std::string_view server_id) { this->event_state_->push_pairing_note( - {.type = PairingNoteType::PAIRING_SUCCEEDED, .text = server_id}); + {.type = PairingNoteType::PAIRING_SUCCEEDED, .text = std::string(server_id)}); } -void SendspinClient::note_pairing_failed(const std::string& server_id, +void SendspinClient::note_pairing_failed(std::string_view server_id, SendspinPairAbortReason reason) { - this->event_state_->push_pairing_note( - {.type = PairingNoteType::PAIRING_FAILED, .text = server_id, .reason = reason}); + this->event_state_->push_pairing_note({.type = PairingNoteType::PAIRING_FAILED, + .text = std::string(server_id), + .reason = reason}); } void SendspinClient::note_display_pairing_code(const std::string& code, diff --git a/src/client_dispatch.cpp b/src/client_dispatch.cpp index 5f9f609c..2179d18e 100644 --- a/src/client_dispatch.cpp +++ b/src/client_dispatch.cpp @@ -510,15 +510,15 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const ServerHelloMessage hello_msg; if (parsed.extract(&hello_msg)) { // server_id comes from the Noise handshake result (already set on the - // connection); server/hello supplies the display name. - conn->set_server_name(std::move(hello_msg.name)); + // connection); server/hello supplies the friendly name. + conn->set_server_name(hello_msg.name); conn->set_server_source_codecs(hello_msg.source_codecs); // The nursery scan later in this tick sends client/hello in reply; nothing // needs to be scheduled here. conn->set_server_hello_received(true); SS_LOGD(TAG, "Connected to server '%s' (server_id=%s)", - conn->get_server_information().name.c_str(), conn->get_server_id().c_str()); + conn->get_server_name().c_str(), conn->get_server_id().c_str()); } break; } diff --git a/src/connection.cpp b/src/connection.cpp index b73629ee..80ef97f5 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -289,8 +289,7 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { this->noise_handshake_.reset(); this->noise_handshake_complete_ = true; SS_LOGI(TAG, "Noise transport active (server_id=%s, psk_category=%d)", - this->server_information_.server_id.c_str(), - static_cast(this->get_psk_category())); + this->server_id_.c_str(), static_cast(this->get_psk_category())); } // NEED_MORE, or COMPLETE handled above: nothing else to do until the next frame. @@ -334,9 +333,9 @@ bool SendspinConnection::handle_noise_rehandshake(std::span msg1_bytes) SS_LOGE(TAG, "handle_noise_rehandshake: no handshake hash available"); return false; } - auto result = run_rehandshake_msg1( - msg1_bytes, this->server_information_.server_id, *this->noise_identity_, - *this->noise_record_store_, this->noise_suite_name_, prior_h.value(), *this->json_arena_); + auto result = run_rehandshake_msg1(msg1_bytes, this->server_id_.view(), *this->noise_identity_, + *this->noise_record_store_, this->noise_suite_name_, + prior_h.value(), *this->json_arena_); if (!result.has_value()) { SS_LOGW(TAG, "handle_noise_rehandshake: re-handshake failed; closing connection"); return false; @@ -370,9 +369,9 @@ bool SendspinConnection::handle_noise_rehandshake(std::span msg1_bytes) // connection.md "Re-handshake": neither hello is re-sent, so the hello state carries over // untouched; the server's first message under the new keys is server/activate, which // first_activate_received_ (cleared above) now waits on. - SS_LOGI( - TAG, "Noise re-handshake complete: server_id=%s psk_category=%d; awaiting server/activate", - this->server_information_.server_id.c_str(), static_cast(this->get_psk_category())); + SS_LOGI(TAG, + "Noise re-handshake complete: server_id=%s psk_category=%d; awaiting server/activate", + this->server_id_.c_str(), static_cast(this->get_psk_category())); return true; } diff --git a/src/connection.h b/src/connection.h index 12e09dbf..3a602c63 100644 --- a/src/connection.h +++ b/src/connection.h @@ -345,13 +345,14 @@ class SendspinConnection : public std::enable_shared_from_thisserver_information_.server_id; + const IdText& get_server_id() const { + return this->server_id_; } - /// @brief Gets the server information from the server/hello message (empty until received). - const ServerInformationObject& get_server_information() const { - return this->server_information_; + /// @brief Gets the server's friendly name from the server/hello message (empty until + /// received). + const ServerName& get_server_name() const { + return this->server_name_; } /// @brief Whether server/hello's source@v1 support object lists `codec` among the codecs the @@ -683,7 +684,7 @@ class SendspinConnection : public std::enable_shared_from_thisserver_information_.server_id = server_id; + this->server_id_.assign(server_id); this->psk_category_ = psk_category; this->psk_id_.assign(psk_id); } @@ -707,10 +708,10 @@ class SendspinConnection : public std::enable_shared_from_thisserver_source_codecs_ = codecs.value_or(0); } - /// @brief Sets the server's display name from server/hello; the server_id the handshake + /// @brief Sets the server's friendly name from server/hello; the server_id the handshake /// recorded stays. - void set_server_name(std::string name) { - this->server_information_.name = std::move(name); + void set_server_name(const ServerName& name) { + this->server_name_ = name; } // ======================================== @@ -1009,10 +1010,11 @@ class SendspinConnection : public std::enable_shared_from_this ConnectionManager::clock() const { } std::optional ConnectionManager::server_information() const { - std::lock_guard lock(this->published_mutex_); - return this->published_.server_information; + std::optional server; + { + std::lock_guard lock(this->published_mutex_); + server = this->published_.server; + } + if (!server.has_value()) { + return std::nullopt; + } + return ServerInformationObject{.server_id = std::string(server->server_id.view()), + .name = std::string(server->name.view())}; } // ============================================================================ @@ -892,7 +900,7 @@ void ConnectionManager::on_pairing_succeeded(SendspinConnection* conn) { if (this->pairing_window_conn_ != nullptr && this->pairing_window_conn_ == conn) { this->close_pairing_window(); } - this->client_->note_pairing_succeeded(conn->get_server_id()); + this->client_->note_pairing_succeeded(conn->get_server_id().view()); } void ConnectionManager::on_connection_lost(SendspinConnection* conn) { @@ -1041,13 +1049,7 @@ void ConnectionManager::refresh_published_state() { // The server information changes only with the primary connection: it is complete before // admission (server/hello precedes it). const bool primary_changed = primary_id != this->published_primary_id_; - std::optional info; - if (primary_changed) { - this->published_primary_id_ = primary_id; - if (primary_conn != nullptr) { - info = primary_conn->get_server_information(); - } - } + this->published_primary_id_ = primary_id; // Each admitted slot's clock, which a measurement, the slot's connection or the primary moves. // The protocol task is published_'s only writer, so it compares without the lock, and a tick // that changed nothing takes none. @@ -1061,10 +1063,14 @@ void ConnectionManager::refresh_published_state() { primary != nullptr ? static_cast(primary - this->admitted_.data()) : MAX_ADMITTED; if (primary_changed || clocks != this->published_.clocks || primary_slot != this->published_.primary_slot) { - // Swapped under the leaf lock; the server information it replaces is destroyed outside it. std::lock_guard lock(this->published_mutex_); - if (primary_changed) { - this->published_.server_information.swap(info); + if (primary_changed && primary_conn == nullptr) { + this->published_.server.reset(); + } else if (primary_changed) { + // Written in place: the slot is the only copy. + PublishedServer& server = this->published_.server.emplace(); + server.server_id = primary_conn->get_server_id(); + server.name = primary_conn->get_server_name(); } this->published_.clocks = clocks; this->published_.primary_slot = primary_slot; @@ -1668,10 +1674,10 @@ bool ConnectionManager::should_switch_to_new_server(const SendspinConnection* ad const bool pairing_in_flight = !has_admitted || !admitted->is_pairing_finalized(); return should_admit_connection( /*incoming_activities=*/new_conn->get_activities(), - /*incoming_server_id=*/new_conn->get_server_id(), + /*incoming_server_id=*/new_conn->get_server_id().view(), /*admitted_activities=*/ has_admitted ? admitted->get_activities() : ActivitySet{}, - /*admitted_server_id=*/has_admitted ? admitted->get_server_id() : std::string{}, + /*admitted_server_id=*/has_admitted ? admitted->get_server_id().view() : std::string_view{}, /*has_admitted=*/has_admitted, /*last_playback_server_id=*/this->last_played_server_id_.view(), /*admitted_pairing_in_flight=*/pairing_in_flight); @@ -1686,14 +1692,14 @@ void ConnectionManager::note_playback_activity(const SendspinConnection* conn) { if (!conn->has_activity(SendspinActivity::PLAYBACK)) { return; } - const std::string& server_id = conn->get_server_id(); + const IdText& server_id = conn->get_server_id(); if (server_id.empty()) { return; } // The RAM half updates here, because a later arbitration reads last_played_server_id_; the // provider writes for this and for the recency move below wait for // SendspinClient::flush_pending_persistence() on the main loop. - this->client_->note_last_played_server(server_id); + this->client_->note_last_played_server(server_id.view()); // A pair-finalize at capacity evicts against the recency order and spares only the records // of open connections, so a connection that closes later must not leave its record looking // least recent until a deferred move lands. RecordStore::mutex_ is a leaf (docs/conventions.md, diff --git a/src/connection_manager.h b/src/connection_manager.h index e5b47677..d57ae546 100644 --- a/src/connection_manager.h +++ b/src/connection_manager.h @@ -382,9 +382,10 @@ class ConnectionManager { /// connection or its filter. std::optional clock() const; - /// @brief Returns a copy of the primary admitted connection's server information, or nullopt - /// when none is admitted. Any thread: reads a slot written at admission and cleared on the - /// drop, behind the leaf published_mutex_. + /// @brief Returns the primary admitted connection's server information, or nullopt when none + /// is admitted. Any thread: copies the inline id and name out of a slot written at admission + /// and cleared on the drop, behind the leaf published_mutex_, and builds the strings on the + /// caller's thread. std::optional server_information() const; // ======================================== @@ -789,8 +790,7 @@ class ConnectionManager { /// @param server_id conn->get_server_id(), captured by handle_enter_pairing(). /// @param selected_method The selected method; DYNAMIC_PAIRING_CODE or STATIC_PAIRING_CODE. void handle_enter_pairing_code(SendspinConnection* conn, uint32_t pairing_index, - const std::string& server_id, - SendspinPairMethod selected_method); + const IdText& server_id, SendspinPairMethod selected_method); /// @brief Runs the Pairing-PSK branch of handle_enter_pairing(): resolves the pairing /// outcome and sends client/pair-init followed by client/pair-finalize with the long-term @@ -799,7 +799,7 @@ class ConnectionManager { /// @param pairing_index Current pairing_index counter, captured by handle_enter_pairing(). /// @param server_id conn->get_server_id(), captured by handle_enter_pairing(). void handle_enter_pairing_psk(SendspinConnection* conn, uint32_t pairing_index, - const std::string& server_id); + const IdText& server_id); /// @brief Handles a pair/abort on an admitted connection. /// Cleans up pairing state. Per pairing.md "pair/abort", only closes the connection for reason @@ -995,15 +995,22 @@ class ConnectionManager { /// @brief Each admitted slot's clock (admitted_[slot]), nullopt for a free slot using ClockSlots = std::array, MAX_ADMITTED>; + /// @brief The primary connection's server identity, held inline so the publish copies it + /// without a heap allocation + struct PublishedServer { + IdText server_id{}; + ServerName name{}; + }; + /// @brief What other threads read of the admitted connections struct PublishedState { ClockSlots clocks{}; /// The slot in clocks of the primary connection (primary()), MAX_ADMITTED for none. size_t primary_slot{MAX_ADMITTED}; - /// The primary connection's server information. - std::optional server_information; + /// The primary connection's server identity. + std::optional server; }; - /// Guards published_. A leaf (docs/conventions.md): held only to copy or swap a member, so it + /// Guards published_. A leaf (docs/conventions.md): held only to copy a member, so it /// also serialises the role threads' clock() reads behind server_information() copies. mutable std::mutex published_mutex_; /// Written by the protocol task (refresh_published_state()), which, as its only writer, also diff --git a/src/connection_manager_pairing.cpp b/src/connection_manager_pairing.cpp index ba26ba42..311ede4e 100644 --- a/src/connection_manager_pairing.cpp +++ b/src/connection_manager_pairing.cpp @@ -192,7 +192,7 @@ void ConnectionManager::handle_enter_pairing(SendspinConnection* conn) { conn->set_pairing_in_progress(true); // Queued before any other note of the attempt, so the queue-order drain delivers it ahead of // the attempt's prompt or failure. - this->client_->note_pairing_started(conn->get_server_id()); + this->client_->note_pairing_started(conn->get_server_id().view()); // The pairing server/activate counter (pairing.md "Pairing index") was already bumped at the // point this activate was received (on_server_activate()). Do not bump again here: this @@ -203,7 +203,7 @@ void ConnectionManager::handle_enter_pairing(SendspinConnection* conn) { // (sent as pairing_index and reused for the CPace sid). const uint32_t pairing_index = conn->get_pairing_index(); - const std::string& server_id = conn->get_server_id(); + const IdText& server_id = conn->get_server_id(); const auto& selected_method = conn->get_pairing_method(); if (selected_method.has_value() && @@ -217,7 +217,7 @@ void ConnectionManager::handle_enter_pairing(SendspinConnection* conn) { } void ConnectionManager::handle_enter_pairing_code(SendspinConnection* conn, uint32_t pairing_index, - const std::string& server_id, + const IdText& server_id, SendspinPairMethod selected_method) { const bool is_dynamic = selected_method == SendspinPairMethod::DYNAMIC_PAIRING_CODE; const auto& static_code = this->client_->config_.static_pairing_code; @@ -296,11 +296,11 @@ void ConnectionManager::handle_enter_pairing_code(SendspinConnection* conn, uint } void ConnectionManager::handle_enter_pairing_psk(SendspinConnection* conn, uint32_t pairing_index, - const std::string& server_id) { + const IdText& server_id) { // resolve_pairing_outcome mints the long-term PSK and the record that holds it. It cannot // fail: a pairing never fails for lack of record storage (pairing.md "Pairing Records"), // and room for the record is made where it is stored. - auto outcome = this->client_->record_store_->resolve_pairing_outcome(server_id); + auto outcome = this->client_->record_store_->resolve_pairing_outcome(server_id.view()); // pairing.md "Pairing PSK Flow": after the pairing server/activate the client sends // client/pair-init followed immediately by client/pair-finalize, without waiting for a @@ -363,7 +363,7 @@ void ConnectionManager::abort_pairing_attempt(SendspinConnection* conn, SendspinPairAbortReason public_reason, SendspinGoodbyeReason goodbye_reason) { // server_id is copied so it survives any tear-down below. - const std::string server_id = conn->get_server_id(); + const IdText server_id = conn->get_server_id(); // Snapshot before clear_pairing_state()/drop_connection() clear it (see PairingUiSnapshot). const PairingUiSnapshot ui = snapshot_pairing_ui(conn); @@ -385,7 +385,7 @@ void ConnectionManager::abort_pairing_attempt(SendspinConnection* conn, } // Queued after any drop_connection() so they survive to be dispatched on the main loop. - this->client_->note_pairing_failed(server_id, public_reason); + this->client_->note_pairing_failed(server_id.view(), public_reason); this->client_->note_pairing_ui_dismissals(ui); } @@ -426,7 +426,7 @@ void ConnectionManager::handle_pairing_message(SendspinConnection* conn, case PairingMessageKind::MALFORMED: { auto& ps = conn->pairing_session(); - const std::string& server_id = conn->get_server_id(); + const IdText& server_id = conn->get_server_id(); // A server pairing message (server/pair-init, server/pair-auth, or // server/pair-confirm) failed to parse. If no pairing-code session is active on this @@ -468,7 +468,7 @@ void ConnectionManager::handle_pairing_message(SendspinConnection* conn, void ConnectionManager::handle_pair_init(SendspinConnection* conn, const ServerPairingMessage& message) { auto& ps = conn->pairing_session(); - const std::string& server_id = conn->get_server_id(); + const IdText& server_id = conn->get_server_id(); // Step 1: server/pair-init received. This step belongs to the dynamic pairing code alone; // the static flow goes straight from client/pair-init to server/pair-auth (pairing.md @@ -550,7 +550,7 @@ void ConnectionManager::handle_pair_init(SendspinConnection* conn, void ConnectionManager::handle_pair_auth(SendspinConnection* conn, const ServerPairingMessage& message) { auto& ps = conn->pairing_session(); - const std::string& server_id = conn->get_server_id(); + const IdText& server_id = conn->get_server_id(); // Step 2: server/pair-auth received. Expect step AWAIT_SERVER_PAIR_AUTH. if (ps.step != SendspinConnection::PairingStep::AWAIT_SERVER_PAIR_AUTH) { @@ -594,7 +594,7 @@ void ConnectionManager::handle_pair_confirm(SendspinConnection* conn, const ServerPairingMessage& message) { auto& ps = conn->pairing_session(); RecordStore& store = *this->client_->record_store_; - const std::string& server_id = conn->get_server_id(); + const IdText& server_id = conn->get_server_id(); // Step 3: server/pair-confirm received. Expect step AWAIT_SERVER_PAIR_CONFIRM. if (ps.step != SendspinConnection::PairingStep::AWAIT_SERVER_PAIR_CONFIRM) { @@ -690,7 +690,7 @@ void ConnectionManager::handle_pair_confirm(SendspinConnection* conn, // Now run the same resolve_pairing_outcome path as pairing_psk, then send // client/pair-finalize. The server will respond with server/pair-finalize. - auto outcome = store.resolve_pairing_outcome(server_id); + auto outcome = store.resolve_pairing_outcome(server_id.view()); // The code-based flows carry the new PSK wrapped under the CPace output, not in the clear // (pairing.md "Wrapping"). K_wrap = SHA-256(PSK_WRAP_LABEL || sid || ISK); the PSK is @@ -768,7 +768,7 @@ void ConnectionManager::start_pairing_attempt(SendspinConnection* conn) { } auto& ps = conn->pairing_session(); - const std::string& server_id = conn->get_server_id(); + const IdText& server_id = conn->get_server_id(); if (ps.method == SendspinPairMethod::DYNAMIC_PAIRING_CODE) { // Generate nonce_B and its commitment, then send client/pair-init with commit_B and diff --git a/src/crypto/keys.h b/src/crypto/keys.h index 424eaaf5..befe9e1e 100644 --- a/src/crypto/keys.h +++ b/src/crypto/keys.h @@ -23,6 +23,7 @@ #pragma once #include "constants.h" +#include "inline_text.h" #include #include @@ -66,51 +67,8 @@ using PeerIdText = std::array; /// @brief A peer_id or psk_id held inline, NUL-terminated /// /// Both are PEER_ID_SIZE base64url characters (psk_id_for(), Identity::peer_id()), so either fits -/// without a heap allocation; longer text names no id this client holds and is refused. -static_assert(PEER_ID_SIZE <= UINT8_MAX, "IdText holds its size in a uint8_t"); - -class IdText { -public: - IdText() = default; - - /// @brief Holds `text`. - /// @return false, leaving the text empty, when `text` is longer than PEER_ID_SIZE. - bool assign(std::string_view text) { - if (text.size() > PEER_ID_SIZE) { - this->size_ = 0; - this->chars_[0] = '\0'; - return false; - } - text.copy(this->chars_.data(), text.size()); - this->chars_[text.size()] = '\0'; - this->size_ = static_cast(text.size()); - return true; - } - - std::string_view view() const { - return {this->chars_.data(), this->size_}; - } - - const char* c_str() const { - return this->chars_.data(); - } - - bool empty() const { - return this->size_ == 0; - } - - bool operator==(std::string_view other) const { - return this->view() == other; - } - - bool operator==(const IdText& other) const { - return this->view() == other.view(); - } - -private: - std::array chars_{}; - uint8_t size_{0}; -}; +/// without a heap allocation; longer text names no id this client holds and is refused (assign()). +using IdText = InlineText; /// @brief Decode a peer_id to the X25519 public key it names. /// diff --git a/src/inline_text.h b/src/inline_text.h new file mode 100644 index 00000000..a2f97835 --- /dev/null +++ b/src/inline_text.h @@ -0,0 +1,103 @@ +// Copyright 2026 Sendspin Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/// @file inline_text.h +/// @brief Bounded text held inside the object, and UTF-8-safe truncation + +#pragma once + +#include +#include +#include +#include + +namespace sendspin { + +/// @brief High two bits of a UTF-8 byte, which 0b10 marks as a continuation byte +constexpr uint8_t UTF8_CONTINUATION_MASK = 0xC0; +/// @brief Masked value of a UTF-8 continuation byte +constexpr uint8_t UTF8_CONTINUATION_BITS = 0x80; +/// @brief Continuation bytes one UTF-8 character carries past its lead byte, at most +constexpr int UTF8_MAX_CONTINUATION_BYTES = 3; + +/// @brief Returns the longest prefix of `text`, at most `max_bytes` long, that ends on a UTF-8 +/// character boundary +/// +/// Backs off over at most three continuation bytes, the most one UTF-8 character carries past its +/// lead byte, so text that is not UTF-8 is still cut within three bytes of `max_bytes`. +inline std::string_view utf8_truncate(std::string_view text, size_t max_bytes) { + if (text.size() <= max_bytes) { + return text; + } + size_t len = max_bytes; + for (int backed_off = 0; backed_off < UTF8_MAX_CONTINUATION_BYTES && len > 0; ++backed_off) { + if ((static_cast(text[len]) & UTF8_CONTINUATION_MASK) != UTF8_CONTINUATION_BITS) { + break; + } + --len; + } + return text.substr(0, len); +} + +/// @brief Text of at most N bytes held inline, NUL-terminated +template +class InlineText { + static_assert(N <= UINT8_MAX, "InlineText holds its size in a uint8_t"); + +public: + InlineText() = default; + + /// @brief Holds `text`. + /// @return false, leaving the text empty, when `text` is longer than N. + bool assign(std::string_view text) { + if (text.size() > N) { + this->set(std::string_view{}); + return false; + } + this->set(text); + return true; + } + + std::string_view view() const { + return {this->chars_.data(), this->size_}; + } + + const char* c_str() const { + return this->chars_.data(); + } + + bool empty() const { + return this->size_ == 0; + } + + bool operator==(std::string_view other) const { + return this->view() == other; + } + + bool operator==(const InlineText& other) const { + return this->view() == other.view(); + } + +private: + void set(std::string_view text) { + text.copy(this->chars_.data(), text.size()); + this->chars_[text.size()] = '\0'; + this->size_ = static_cast(text.size()); + } + + std::array chars_{}; + uint8_t size_{0}; +}; + +} // namespace sendspin diff --git a/src/protocol.cpp b/src/protocol.cpp index 7cd2ae69..1fc90441 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -86,6 +86,18 @@ static std::optional read_bool_field(JsonVariantConst var, const char* nam return var.as(); } +/// @brief Reads a friendly name: messaging.md "server/hello" and "group/update" cap one at +/// MAX_FRIENDLY_NAME_BYTES, and a longer one is truncated at a UTF-8 character boundary (logged), +/// never rejected. `var` must hold a string. +static std::string_view read_friendly_name(JsonVariantConst var, const char* field) { + const auto text = var.as(); + const std::string_view kept = utf8_truncate(text, MAX_FRIENDLY_NAME_BYTES); + if (kept.size() != text.size()) { + SS_LOGW(TAG, "Truncating %s: longer than %zu bytes", field, MAX_FRIENDLY_NAME_BYTES); + } + return kept; +} + /// @brief Reads an enum field parsed from a wire string via `from_string`. Absent or null returns /// nullopt silently; a present non-string, or a string that `from_string` does not recognize, is /// logged and returns nullopt. The caller picks the policy: an optional field leaves its current @@ -337,7 +349,7 @@ bool process_server_hello_message(JsonObject root, ServerHelloMessage* hello_msg if (hello_msg == nullptr) { return true; } - hello_msg->name = root["payload"]["name"].as(); + hello_msg->name.assign(read_friendly_name(root["payload"]["name"], "server/hello name")); // roles/source/v1.md "server/hello source@v1 support object": supported_codecs is a required // list of strings that must include flac and pcm, and a source ignores the codec identifiers @@ -491,7 +503,8 @@ bool process_group_update_message(JsonObject root, GroupUpdateMessage* group_msg // Parse optional group_name; use empty string to signal clearing JsonVariantConst group_name_var = root["payload"]["group_name"]; if (group_name_var.is()) { - group_msg->group.group_name = group_name_var.as(); + group_msg->group.group_name = + std::string(read_friendly_name(group_name_var, "group/update group_name")); } else if (!group_name_var.isUnbound() && group_name_var.isNull()) { // Field set to null: use empty string to clear group_msg->group.group_name = ""; diff --git a/src/protocol_messages.h b/src/protocol_messages.h index b41ed043..b818cc59 100644 --- a/src/protocol_messages.h +++ b/src/protocol_messages.h @@ -19,6 +19,7 @@ #pragma once #include "crypto/psk_wrap.h" +#include "inline_text.h" #include "inline_vector.h" #include "platform/network_info.h" #include "sendspin/color_role.h" @@ -998,11 +999,19 @@ constexpr uint8_t source_codec_bit(SendspinCodecFormat codec) { static_assert(static_cast(SendspinCodecFormat::UNSUPPORTED) < 8, "codec mask is a uint8_t"); +/// @brief Longest friendly name the server sends, in UTF-8 bytes: messaging.md "server/hello" +/// caps `name` and "group/update" caps `group_name` at 64 bytes, and a client truncates a longer +/// one at a UTF-8 character boundary. +constexpr size_t MAX_FRIENDLY_NAME_BYTES = 64; + +/// @brief The server's friendly name from server/hello, cut to MAX_FRIENDLY_NAME_BYTES +using ServerName = InlineText; + /// @brief Parsed server/hello handshake message received at connection startup. /// server_id comes from the Noise handshake result (set on the connection at COMPLETE), and /// activities/active_roles come from the server/activate message that follows. struct ServerHelloMessage { - std::string name{}; + ServerName name{}; /// Codecs the server accepts in client-stream/start, as source_codec_bit() bits; a set value /// always carries the PCM and FLAC bits, nullopt when server/hello carried no valid /// source@v1_support object (roles/source/v1.md "server/hello source@v1 support object"). diff --git a/src/record_store.cpp b/src/record_store.cpp index 9a1c04ea..c6ad7c53 100644 --- a/src/record_store.cpp +++ b/src/record_store.cpp @@ -310,7 +310,7 @@ const SendspinPairingRecord* RecordStore::record_by_psk_id(std::string_view psk_ return &this->records_[idx].record; } -const SendspinPairingRecord* RecordStore::record_by_server_id(const std::string& server_id) const { +const SendspinPairingRecord* RecordStore::record_by_server_id(std::string_view server_id) const { for (const auto& stored : this->records_) { if (stored.record.server_id == server_id) { return &stored.record; @@ -495,7 +495,7 @@ bool RecordStore::note_record_played(std::string_view psk_id) { // Pairing outcome // ============================================================================ -RecordStore::PairingOutcome RecordStore::resolve_pairing_outcome(const std::string& server_id) { +RecordStore::PairingOutcome RecordStore::resolve_pairing_outcome(std::string_view server_id) { std::array psk{}; platform_random_bytes(psk.data(), psk.size()); diff --git a/src/record_store.h b/src/record_store.h index 00dcf1f6..6aead7fc 100644 --- a/src/record_store.h +++ b/src/record_store.h @@ -270,7 +270,7 @@ class RecordStore { /// /// Minting cannot fail on a full store: store_record_superseding() supersedes a re-pair's /// existing record and evicts for a net-new one (pairing.md "Pairing Records"). - [[nodiscard]] PairingOutcome resolve_pairing_outcome(const std::string& server_id); + [[nodiscard]] PairingOutcome resolve_pairing_outcome(std::string_view server_id); private: // ======================================== @@ -345,7 +345,7 @@ class RecordStore { /// @brief The record bound to server_id, or nullptr. Same rules. [[nodiscard]] const SendspinPairingRecord* record_by_server_id( - const std::string& server_id) const; + std::string_view server_id) const; /// @brief Sentinel find_index() returns for a psk_id the store does not hold. static constexpr size_t NPOS = static_cast(-1); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 52ef1fa9..cd325971 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -37,6 +37,7 @@ add_executable(sendspin_tests test_protocol_task.cpp test_inbox.cpp test_player_role.cpp + test_inline_text.cpp test_inline_vector.cpp test_fixed_block_pool.cpp test_visualizer_role.cpp diff --git a/tests/test_allocations.cpp b/tests/test_allocations.cpp index 8a6a666b..15cc2375 100644 --- a/tests/test_allocations.cpp +++ b/tests/test_allocations.cpp @@ -427,13 +427,8 @@ void expect_library_allocations(const Window& window, const char* title, size_t constexpr uint16_t ALLOCATION_TEST_PORT = 19300; constexpr int TIME_BURST_SIZE = 8; -// libstdc++ (ESP-IDF's) keeps strings of up to 15 characters inline, libc++ up to 22: the fake -// server's name, parsed and then published, allocates only under libstdc++. -#ifdef _LIBCPP_VERSION -constexpr size_t ADMISSION_ALLOCATIONS = 3; -#else -constexpr size_t ADMISSION_ALLOCATIONS = 5; -#endif +// The pairing slot's vector growing for the trust note on_handshake_complete() queues. +constexpr size_t ADMISSION_ALLOCATIONS = 1; constexpr size_t CLIENT_STATE_ALLOCATIONS = 0; constexpr size_t TIME_BURST_ALLOCATIONS = 0; diff --git a/tests/test_connection_lifecycle.cpp b/tests/test_connection_lifecycle.cpp index ab5428b8..e2be3d9b 100644 --- a/tests/test_connection_lifecycle.cpp +++ b/tests/test_connection_lifecycle.cpp @@ -297,6 +297,7 @@ TEST(ConnectionLifecycle, JunkProbeDoesNotBlockRealServer) { auto info = client.get_server_information(); ASSERT_TRUE(info.has_value()); EXPECT_EQ(info->server_id, server_identity.peer_id()); + EXPECT_EQ(info->name, "Fake Encrypted Server"); // The probes never complete a WebSocket handshake, so the transport layer closes them without // them ever reaching the manager (host: IXWebSocket's 3 s server-side handshake timeout; on diff --git a/tests/test_inline_text.cpp b/tests/test_inline_text.cpp new file mode 100644 index 00000000..44326deb --- /dev/null +++ b/tests/test_inline_text.cpp @@ -0,0 +1,68 @@ +// Copyright 2026 Sendspin Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/// @file test_inline_text.cpp +/// @brief Tests for utf8_truncate() and InlineText: cuts on a character boundary, and refusal of +/// text that does not fit + +#include "inline_text.h" + +#include + +#include + +namespace sendspin { +namespace { + +// A cut never splits a character: it lands at max_bytes when that is a boundary, and otherwise +// backs off to the start of the character max_bytes falls inside. +TEST(InlineText, Utf8TruncateCutsOnACharacterBoundary) { + struct Case { + const char* what; + std::string_view text; + size_t max_bytes; + std::string_view kept; + }; + // "\xC3\xA9" is U+00E9 (2 bytes), "\xE2\x82\xAC" U+20AC (3), "\xF0\x9F\x8E\xB5" U+1F3B5 (4). + const Case cases[] = { + {"Control: fits", "abc", 3, "abc"}, + {"Control: ASCII cut at max", "abcdef", 4, "abcd"}, + {"cut before a lead byte", "abc\xC3\xA9", 3, "abc"}, + {"inside a 2-byte character", "ab\xC3\xA9", 3, "ab"}, + {"Control: after a 2-byte character", "ab\xC3\xA9x", 4, "ab\xC3\xA9"}, + {"inside a 3-byte character", "a\xE2\x82\xAC", 3, "a"}, + {"1 byte into a 4-byte character", "a\xF0\x9F\x8E\xB5", 2, "a"}, + {"3 bytes into a 4-byte character", "a\xF0\x9F\x8E\xB5", 4, "a"}, + {"a run of continuation bytes backs off at most 3", "abc\x80\x80\x80\x80\x80", 7, + "abc\x80"}, + {"zero bytes", "abc", 0, ""}, + {"only continuation bytes before the cut", "\x80\x80", 1, ""}, + }; + for (const Case& c : cases) { + EXPECT_EQ(utf8_truncate(c.text, c.max_bytes), c.kept) << c.what; + } +} + +// assign() refuses text over N and leaves the holder empty, NUL-terminated. +TEST(InlineText, AssignRefusesTextOverItsCapacity) { + InlineText<4> text; + ASSERT_TRUE(text.assign("abcd")); // Control: text at the capacity is held + EXPECT_EQ(text.view(), "abcd"); + EXPECT_FALSE(text.assign("abcde")); + EXPECT_TRUE(text.empty()); + EXPECT_STREQ(text.c_str(), ""); +} + +} // namespace +} // namespace sendspin diff --git a/tests/test_protocol.cpp b/tests/test_protocol.cpp index 258068e3..940c1fec 100644 --- a/tests/test_protocol.cpp +++ b/tests/test_protocol.cpp @@ -615,7 +615,42 @@ TEST(Protocol, ServerHelloRequiresName) { ASSERT_TRUE(parse(R"({"type":"server/hello","payload":{"name":"srv"}})", doc_ok, root_ok)); ServerHelloMessage ok; ASSERT_TRUE(process_server_hello_message(root_ok, &ok)); - EXPECT_EQ(ok.name, "srv"); + EXPECT_EQ(ok.name.view(), "srv"); +} + +// messaging.md "server/hello" and "group/update": a friendly name over MAX_FRIENDLY_NAME_BYTES is +// truncated at a character boundary rather than rejected, and one at the cap is kept whole. +TEST(Protocol, FriendlyNamesAreTruncatedToTheirCap) { + struct Case { + const char* what; + std::string name; + std::string kept; + }; + const std::string below_cap(MAX_FRIENDLY_NAME_BYTES - 1, 'a'); + const Case cases[] = { + {"Control: at the cap", below_cap + "a", below_cap + "a"}, + // U+00E9 straddles the cap, so the cut lands before it. + {"a character straddling the cap", below_cap + "\xC3\xA9", below_cap}, + }; + for (const Case& c : cases) { + SCOPED_TRACE(c.what); + + JsonDocument hello_doc; + JsonObject hello_root; + ASSERT_TRUE(parse(R"({"type":"server/hello","payload":{"name":")" + c.name + R"("}})", + hello_doc, hello_root)); + ServerHelloMessage hello; + ASSERT_TRUE(process_server_hello_message(hello_root, &hello)); + EXPECT_EQ(hello.name.view(), c.kept); + + JsonDocument group_doc; + JsonObject group_root; + ASSERT_TRUE(parse(R"({"type":"group/update","payload":{"group_name":")" + c.name + R"("}})", + group_doc, group_root)); + GroupUpdateMessage group; + ASSERT_TRUE(process_group_update_message(group_root, &group)); + EXPECT_EQ(group.group.group_name, c.kept); + } } // roles/source/v1.md "server/hello source@v1 support object": the codecs the server accepts in diff --git a/tools/stack_usage/README.md b/tools/stack_usage/README.md index 7e149a80..8f8a9395 100644 --- a/tools/stack_usage/README.md +++ b/tools/stack_usage/README.md @@ -137,7 +137,7 @@ Measured on xtensa-esp32 with ESP-IDF 5.5 and GCC 14.2, at `-Os` (ESPHome's defa | --- | --- | --- | --- | --- | --- | --- | | httpd | `httpd_thread` | esp_http_server's own WebSocket upgrade response (544 to 576 bytes) | 4,032 | 3,968 | 4,608 (`DEFAULT_HTTPD_STACK_SIZE`) | shared ESP-IDF tail | | websocket client | `esp_websocket_client_task` | library event handler (3,520 / 3,600) closing on a stalled protocol task via `fail_inbound()` through the inbound transport's close | 3,904 | 3,968 | 4,608 (`DEFAULT_WEBSOCKET_STACK_SIZE`) | shared ESP-IDF tail | -| protocol task | task entry | as bounded: an esp_websocket_client send error into the event handler, `handle_data()`, `fail_inbound()` and `httpd_sess_trigger_close` (unreachable); reachable: a pairing confirm dropping an outbound connection whose goodbye send fails (5,920 at -Os), and at -Og a `stream/start` parse's string conversion (6,400) | 6,544 | 6,656 | 7,168 (`DEFAULT_PROTOCOL_TASK_STACK_SIZE`) | shared ESP-IDF tail | +| protocol task | task entry | as bounded: an esp_websocket_client send error into the event handler, `handle_data()`, `fail_inbound()` and `httpd_sess_trigger_close` (unreachable); reachable: a pairing confirm dropping an outbound connection whose goodbye send fails (5,920 at -Os), and at -Og a `stream/start` parse's string conversion (6,368) | 6,544 | 6,704 | 7,168 (`DEFAULT_PROTOCOL_TASK_STACK_SIZE`) | shared ESP-IDF tail | | source, PCM | `thread_entry()` | `begin_chunk()`'s outbound acquire | 1,104 | 1,168 | 2,048 (`DEFAULT_SOURCE_TASK_STACK_SIZE`) | FreeRTOS critical-section assert | | source, Opus | `thread_entry()` | the Opus encode, `quant_partition()` charged one pass | 5,152 | 5,168 | 6,656 (`DEFAULT_OPUS_SOURCE_TASK_STACK_SIZE`) | shared ESP-IDF tail | | source, FLAC | `thread_entry()` | the FLAC encode through micro-flac's LPC design | 4,464 | 4,432 | 5,120 (`DEFAULT_FLAC_SOURCE_TASK_STACK_SIZE`) | libgcc `__divdi3` | @@ -151,7 +151,7 @@ Notes per task: connection takes. 3,968 + 384 = 4,352, rounded up. - protocol task: noise-c and libsodium included. The bounded chain's tail cannot execute (an outbound connection never reaches the server connection's close override), so the default is - sized from the reachable chain: 6,400 + 384 = 6,784, rounded up to 7,168. + sized from the reachable chain: 6,368 + 384 = 6,752, rounded up to 7,168. - source, PCM: the task sends nothing itself and logs nothing. The `std::thread` entry frames above `thread_entry()` are not counted and come out of the rounding slack. 1,168 + 384 = 1,552, rounded up. From 72f8e54d89c1e55b5edcfdda2c0ebe3d906f05d7 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Tue, 3 Nov 2026 12:00:51 -0500 Subject: [PATCH 2/2] Pin the 64-byte name cap and lengthen the fake server's name The friendly-name test built its inputs from MAX_FRIENDLY_NAME_BYTES, so a cap drifting off the spec's 64 still passed; it now uses a literal 63-byte prefix. The fake server's hello name was 21 bytes, inside libc++'s inline string, so the allocation test could not see a heap copy of it on macOS; it is now 32 bytes, named FAKE_SERVER_HELLO_NAME. --- tests/lifecycle_test_fixtures.h | 6 +++++- tests/test_connection_lifecycle.cpp | 2 +- tests/test_protocol.cpp | 6 +++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/lifecycle_test_fixtures.h b/tests/lifecycle_test_fixtures.h index a0bd4692..aab669b4 100644 --- a/tests/lifecycle_test_fixtures.h +++ b/tests/lifecycle_test_fixtures.h @@ -504,13 +504,17 @@ struct FakeEncryptedServerOptions { int64_t server_clock_offset_us{0}; }; +/// The name every FakeEncryptedServer sends in server/hello. Longer than the 22 characters libc++ +/// keeps inline, so a heap copy of it shows in the allocation test under either standard library. +inline constexpr const char* FAKE_SERVER_HELLO_NAME = "Fake Encrypted Server Under Test"; + class FakeEncryptedServer : public NoiseInitiatorFixtureBase { public: FakeEncryptedServer(const std::string& url, std::string suite_name, Identity server_identity, std::string psk_id, std::array psk, FakeEncryptedServerOptions options = {}) : NoiseInitiatorFixtureBase(std::move(suite_name), server_identity, std::move(psk_id), psk, - "Fake Encrypted Server", + FAKE_SERVER_HELLO_NAME, options.psk_category.value_or("")), options_(std::move(options)) { this->ws_.setUrl(url); diff --git a/tests/test_connection_lifecycle.cpp b/tests/test_connection_lifecycle.cpp index e2be3d9b..75135040 100644 --- a/tests/test_connection_lifecycle.cpp +++ b/tests/test_connection_lifecycle.cpp @@ -297,7 +297,7 @@ TEST(ConnectionLifecycle, JunkProbeDoesNotBlockRealServer) { auto info = client.get_server_information(); ASSERT_TRUE(info.has_value()); EXPECT_EQ(info->server_id, server_identity.peer_id()); - EXPECT_EQ(info->name, "Fake Encrypted Server"); + EXPECT_EQ(info->name, FAKE_SERVER_HELLO_NAME); // The probes never complete a WebSocket handshake, so the transport layer closes them without // them ever reaching the manager (host: IXWebSocket's 3 s server-side handshake timeout; on diff --git a/tests/test_protocol.cpp b/tests/test_protocol.cpp index 940c1fec..52d33d84 100644 --- a/tests/test_protocol.cpp +++ b/tests/test_protocol.cpp @@ -618,15 +618,15 @@ TEST(Protocol, ServerHelloRequiresName) { EXPECT_EQ(ok.name.view(), "srv"); } -// messaging.md "server/hello" and "group/update": a friendly name over MAX_FRIENDLY_NAME_BYTES is -// truncated at a character boundary rather than rejected, and one at the cap is kept whole. +// messaging.md "server/hello" and "group/update": a friendly name over 64 bytes is truncated at a +// character boundary rather than rejected, and one of exactly 64 bytes is kept whole. TEST(Protocol, FriendlyNamesAreTruncatedToTheirCap) { struct Case { const char* what; std::string name; std::string kept; }; - const std::string below_cap(MAX_FRIENDLY_NAME_BYTES - 1, 'a'); + const std::string below_cap(63, 'a'); const Case cases[] = { {"Control: at the cap", below_cap + "a", below_cap + "a"}, // U+00E9 straddles the cap, so the cut lands before it.