Skip to content

Commit 67a9be6

Browse files
authored
Hold the server's id and name inline (#233)
## Summary Removes the server-identity heap allocations between accept and admission. The connection kept the server's id and name as a `ServerInformationObject` (two `std::string`s), and the published slot copied it. A 43-character id is too long for either standard library's inline string storage, and under libstdc++ so is a name over 15 characters. Admission made 3 such allocations on libc++ and 5 on libstdc++ (ESP-IDF); it now makes 1 on both. Depends on Sendspin/spec#339, which caps `server/hello`'s `name` and `group/update`'s `group_name` at 64 bytes in UTF-8. ## Change - `InlineText<N>` (`src/inline_text.h`) holds bounded text inside the object; `IdText` is now `InlineText<PEER_ID_SIZE>`. `utf8_truncate()` cuts text at a character boundary. - The connection holds the server id as an `IdText` and the name as a 64-byte `ServerName`. `get_server_id()` returns `const IdText&`, and the helpers that took the id as a `std::string` take a `std::string_view`. - The published slot holds the same inline copies. `get_server_information()` builds the public `ServerInformationObject` on the caller's thread, so the public API is unchanged. - `read_friendly_name()` truncates `server/hello`'s `name` and `group/update`'s `group_name` to 64 bytes with one warning log. `group_name` stays a `std::string` in the public `GroupUpdateObject`. - `tools/stack_usage/README.md` is re-derived from fresh ESP32 builds: - protocol task bound at -Og: 6,656 → 6,704 (`ServerHelloMessage` now holds the name inline); - reachable figure at -Og: 6,400 → 6,368; - the 7,168 default does not change. ## Tests - `test_inline_text.cpp`: a table of truncation cases (at the cap, before a lead byte, inside 2-, 3- and 4-byte characters, malformed continuation runs, only continuation bytes before the cut), plus `InlineText::assign()` refusing text over its capacity. - `Protocol.FriendlyNamesAreTruncatedToTheirCap`: a name at the cap is kept whole, and one with a character straddling the cap is truncated before it, for both fields. - `JunkProbeDoesNotBlockRealServer` now also checks the published name through `get_server_information()`. No test checked it before, so a mutant that dropped it passed. - `ADMISSION_ALLOCATIONS` is lowered to 1, checked under clang / libc++ and GCC 16 / libstdc++. The one left is the trust-change note `on_handshake_complete()` queues. - Mutants killed: no truncation in `read_friendly_name()`, unbounded back-off, the `len > 0` guard removed (ASan out-of-bounds read), and the published name dropped.
1 parent f23d2f5 commit 67a9be6

23 files changed

Lines changed: 342 additions & 138 deletions

‎include/sendspin/client.h‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -967,13 +967,13 @@ class SendspinClient {
967967
// listener callback for delivery from the main loop's drain_inbox().
968968

969969
/// @brief Queue an on_pairing_started notification
970-
void note_pairing_started(const std::string& server_id);
970+
void note_pairing_started(std::string_view server_id);
971971

972972
/// @brief Queue an on_pairing_succeeded notification
973-
void note_pairing_succeeded(const std::string& server_id);
973+
void note_pairing_succeeded(std::string_view server_id);
974974

975975
/// @brief Queue an on_pairing_failed notification
976-
void note_pairing_failed(const std::string& server_id, SendspinPairAbortReason reason);
976+
void note_pairing_failed(std::string_view server_id, SendspinPairAbortReason reason);
977977

978978
/// @brief Queue an on_display_pairing_code notification
979979
void note_display_pairing_code(const std::string& code, SendspinPairingCodeFormat format);

‎include/sendspin/types.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ enum class SendspinGoodbyeReason : uint8_t {
4242
/// @brief Server identity fields received in server/hello messages
4343
struct ServerInformationObject {
4444
std::string server_id{};
45+
/// At most 64 bytes in UTF-8, cut at a character boundary
4546
std::string name{};
4647
};
4748

@@ -55,6 +56,7 @@ enum class SendspinPlaybackState : uint8_t {
5556
struct GroupUpdateObject {
5657
std::optional<SendspinPlaybackState> playback_state{};
5758
std::optional<std::string> group_id{};
59+
/// At most 64 bytes in UTF-8, cut at a character boundary
5860
std::optional<std::string> group_name{};
5961
};
6062

‎src/admission.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,9 @@ inline int activity_rank(ActivitySet activities) {
178178
/// shielding a pairing that has finished.
179179
/// @return true if the incoming connection should become the admitted one.
180180
inline bool should_admit_connection(ActivitySet incoming_activities,
181-
const std::string& incoming_server_id,
181+
std::string_view incoming_server_id,
182182
ActivitySet admitted_activities,
183-
const std::string& admitted_server_id, bool has_admitted,
183+
std::string_view admitted_server_id, bool has_admitted,
184184
std::string_view last_playback_server_id,
185185
bool admitted_pairing_in_flight) {
186186
if (!has_admitted) {

‎src/client.cpp‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1740,20 +1740,21 @@ void SendspinClient::on_activation_applied([[maybe_unused]] SendspinConnection*
17401740
#endif
17411741
}
17421742

1743-
void SendspinClient::note_pairing_started(const std::string& server_id) {
1743+
void SendspinClient::note_pairing_started(std::string_view server_id) {
17441744
this->event_state_->push_pairing_note(
1745-
{.type = PairingNoteType::PAIRING_STARTED, .text = server_id});
1745+
{.type = PairingNoteType::PAIRING_STARTED, .text = std::string(server_id)});
17461746
}
17471747

1748-
void SendspinClient::note_pairing_succeeded(const std::string& server_id) {
1748+
void SendspinClient::note_pairing_succeeded(std::string_view server_id) {
17491749
this->event_state_->push_pairing_note(
1750-
{.type = PairingNoteType::PAIRING_SUCCEEDED, .text = server_id});
1750+
{.type = PairingNoteType::PAIRING_SUCCEEDED, .text = std::string(server_id)});
17511751
}
17521752

1753-
void SendspinClient::note_pairing_failed(const std::string& server_id,
1753+
void SendspinClient::note_pairing_failed(std::string_view server_id,
17541754
SendspinPairAbortReason reason) {
1755-
this->event_state_->push_pairing_note(
1756-
{.type = PairingNoteType::PAIRING_FAILED, .text = server_id, .reason = reason});
1755+
this->event_state_->push_pairing_note({.type = PairingNoteType::PAIRING_FAILED,
1756+
.text = std::string(server_id),
1757+
.reason = reason});
17571758
}
17581759

17591760
void SendspinClient::note_display_pairing_code(const std::string& code,

‎src/client_dispatch.cpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -510,15 +510,15 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
510510
ServerHelloMessage hello_msg;
511511
if (parsed.extract<process_server_hello_message>(&hello_msg)) {
512512
// server_id comes from the Noise handshake result (already set on the
513-
// connection); server/hello supplies the display name.
514-
conn->set_server_name(std::move(hello_msg.name));
513+
// connection); server/hello supplies the friendly name.
514+
conn->set_server_name(hello_msg.name);
515515
conn->set_server_source_codecs(hello_msg.source_codecs);
516516
// The nursery scan later in this tick sends client/hello in reply; nothing
517517
// needs to be scheduled here.
518518
conn->set_server_hello_received(true);
519519

520520
SS_LOGD(TAG, "Connected to server '%s' (server_id=%s)",
521-
conn->get_server_information().name.c_str(), conn->get_server_id().c_str());
521+
conn->get_server_name().c_str(), conn->get_server_id().c_str());
522522
}
523523
break;
524524
}

‎src/connection.cpp‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -289,8 +289,7 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) {
289289
this->noise_handshake_.reset();
290290
this->noise_handshake_complete_ = true;
291291
SS_LOGI(TAG, "Noise transport active (server_id=%s, psk_category=%d)",
292-
this->server_information_.server_id.c_str(),
293-
static_cast<int>(this->get_psk_category()));
292+
this->server_id_.c_str(), static_cast<int>(this->get_psk_category()));
294293
}
295294

296295
// 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<uint8_t> msg1_bytes)
334333
SS_LOGE(TAG, "handle_noise_rehandshake: no handshake hash available");
335334
return false;
336335
}
337-
auto result = run_rehandshake_msg1(
338-
msg1_bytes, this->server_information_.server_id, *this->noise_identity_,
339-
*this->noise_record_store_, this->noise_suite_name_, prior_h.value(), *this->json_arena_);
336+
auto result = run_rehandshake_msg1(msg1_bytes, this->server_id_.view(), *this->noise_identity_,
337+
*this->noise_record_store_, this->noise_suite_name_,
338+
prior_h.value(), *this->json_arena_);
340339
if (!result.has_value()) {
341340
SS_LOGW(TAG, "handle_noise_rehandshake: re-handshake failed; closing connection");
342341
return false;
@@ -370,9 +369,9 @@ bool SendspinConnection::handle_noise_rehandshake(std::span<uint8_t> msg1_bytes)
370369
// connection.md "Re-handshake": neither hello is re-sent, so the hello state carries over
371370
// untouched; the server's first message under the new keys is server/activate, which
372371
// first_activate_received_ (cleared above) now waits on.
373-
SS_LOGI(
374-
TAG, "Noise re-handshake complete: server_id=%s psk_category=%d; awaiting server/activate",
375-
this->server_information_.server_id.c_str(), static_cast<int>(this->get_psk_category()));
372+
SS_LOGI(TAG,
373+
"Noise re-handshake complete: server_id=%s psk_category=%d; awaiting server/activate",
374+
this->server_id_.c_str(), static_cast<int>(this->get_psk_category()));
376375
return true;
377376
}
378377

‎src/connection.h‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -345,13 +345,14 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
345345

346346
/// @brief Gets the server ID from the Noise handshake result (set at COMPLETE; empty until
347347
/// then when a Noise handshake is installed on this connection).
348-
const std::string& get_server_id() const {
349-
return this->server_information_.server_id;
348+
const IdText& get_server_id() const {
349+
return this->server_id_;
350350
}
351351

352-
/// @brief Gets the server information from the server/hello message (empty until received).
353-
const ServerInformationObject& get_server_information() const {
354-
return this->server_information_;
352+
/// @brief Gets the server's friendly name from the server/hello message (empty until
353+
/// received).
354+
const ServerName& get_server_name() const {
355+
return this->server_name_;
355356
}
356357

357358
/// @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_this<SendspinConnectio
683684
/// Called at COMPLETE in connection.cpp.
684685
void set_noise_handshake_result(std::string_view server_id, PskCategory psk_category,
685686
std::string_view psk_id) {
686-
this->server_information_.server_id = server_id;
687+
this->server_id_.assign(server_id);
687688
this->psk_category_ = psk_category;
688689
this->psk_id_.assign(psk_id);
689690
}
@@ -707,10 +708,10 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
707708
this->server_source_codecs_ = codecs.value_or(0);
708709
}
709710

710-
/// @brief Sets the server's display name from server/hello; the server_id the handshake
711+
/// @brief Sets the server's friendly name from server/hello; the server_id the handshake
711712
/// recorded stays.
712-
void set_server_name(std::string name) {
713-
this->server_information_.name = std::move(name);
713+
void set_server_name(const ServerName& name) {
714+
this->server_name_ = name;
714715
}
715716

716717
// ========================================
@@ -1009,10 +1010,11 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
10091010
MessageTracer message_tracer_;
10101011
#endif
10111012

1012-
/// Server identity: name from server/hello, server_id from the Noise handshake result
1013-
/// (or re-handshake; unchanged across a re-handshake since it is the same server). Protocol
1014-
/// task only; ConnectionManager publishes a copy to other threads at admission.
1015-
ServerInformationObject server_information_{};
1013+
/// Server identity: server_id from the Noise handshake result (or re-handshake; unchanged
1014+
/// across a re-handshake since it is the same server), name from server/hello. Protocol task
1015+
/// only; ConnectionManager publishes a copy to other threads at admission.
1016+
IdText server_id_{};
1017+
ServerName server_name_{};
10161018

10171019
/// The pairing record staged by the attempt in flight, committed by the
10181020
/// server/pair-finalize handler (nullopt = nothing to store). Protocol task only.

‎src/connection_manager.cpp‎

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -326,8 +326,16 @@ std::optional<TimeTransform> ConnectionManager::clock() const {
326326
}
327327

328328
std::optional<ServerInformationObject> ConnectionManager::server_information() const {
329-
std::lock_guard<std::mutex> lock(this->published_mutex_);
330-
return this->published_.server_information;
329+
std::optional<PublishedServer> server;
330+
{
331+
std::lock_guard<std::mutex> lock(this->published_mutex_);
332+
server = this->published_.server;
333+
}
334+
if (!server.has_value()) {
335+
return std::nullopt;
336+
}
337+
return ServerInformationObject{.server_id = std::string(server->server_id.view()),
338+
.name = std::string(server->name.view())};
331339
}
332340

333341
// ============================================================================
@@ -892,7 +900,7 @@ void ConnectionManager::on_pairing_succeeded(SendspinConnection* conn) {
892900
if (this->pairing_window_conn_ != nullptr && this->pairing_window_conn_ == conn) {
893901
this->close_pairing_window();
894902
}
895-
this->client_->note_pairing_succeeded(conn->get_server_id());
903+
this->client_->note_pairing_succeeded(conn->get_server_id().view());
896904
}
897905

898906
void ConnectionManager::on_connection_lost(SendspinConnection* conn) {
@@ -1041,13 +1049,7 @@ void ConnectionManager::refresh_published_state() {
10411049
// The server information changes only with the primary connection: it is complete before
10421050
// admission (server/hello precedes it).
10431051
const bool primary_changed = primary_id != this->published_primary_id_;
1044-
std::optional<ServerInformationObject> info;
1045-
if (primary_changed) {
1046-
this->published_primary_id_ = primary_id;
1047-
if (primary_conn != nullptr) {
1048-
info = primary_conn->get_server_information();
1049-
}
1050-
}
1052+
this->published_primary_id_ = primary_id;
10511053
// Each admitted slot's clock, which a measurement, the slot's connection or the primary moves.
10521054
// The protocol task is published_'s only writer, so it compares without the lock, and a tick
10531055
// that changed nothing takes none.
@@ -1061,10 +1063,14 @@ void ConnectionManager::refresh_published_state() {
10611063
primary != nullptr ? static_cast<size_t>(primary - this->admitted_.data()) : MAX_ADMITTED;
10621064
if (primary_changed || clocks != this->published_.clocks ||
10631065
primary_slot != this->published_.primary_slot) {
1064-
// Swapped under the leaf lock; the server information it replaces is destroyed outside it.
10651066
std::lock_guard<std::mutex> lock(this->published_mutex_);
1066-
if (primary_changed) {
1067-
this->published_.server_information.swap(info);
1067+
if (primary_changed && primary_conn == nullptr) {
1068+
this->published_.server.reset();
1069+
} else if (primary_changed) {
1070+
// Written in place: the slot is the only copy.
1071+
PublishedServer& server = this->published_.server.emplace();
1072+
server.server_id = primary_conn->get_server_id();
1073+
server.name = primary_conn->get_server_name();
10681074
}
10691075
this->published_.clocks = clocks;
10701076
this->published_.primary_slot = primary_slot;
@@ -1668,10 +1674,10 @@ bool ConnectionManager::should_switch_to_new_server(const SendspinConnection* ad
16681674
const bool pairing_in_flight = !has_admitted || !admitted->is_pairing_finalized();
16691675
return should_admit_connection(
16701676
/*incoming_activities=*/new_conn->get_activities(),
1671-
/*incoming_server_id=*/new_conn->get_server_id(),
1677+
/*incoming_server_id=*/new_conn->get_server_id().view(),
16721678
/*admitted_activities=*/
16731679
has_admitted ? admitted->get_activities() : ActivitySet{},
1674-
/*admitted_server_id=*/has_admitted ? admitted->get_server_id() : std::string{},
1680+
/*admitted_server_id=*/has_admitted ? admitted->get_server_id().view() : std::string_view{},
16751681
/*has_admitted=*/has_admitted,
16761682
/*last_playback_server_id=*/this->last_played_server_id_.view(),
16771683
/*admitted_pairing_in_flight=*/pairing_in_flight);
@@ -1686,14 +1692,14 @@ void ConnectionManager::note_playback_activity(const SendspinConnection* conn) {
16861692
if (!conn->has_activity(SendspinActivity::PLAYBACK)) {
16871693
return;
16881694
}
1689-
const std::string& server_id = conn->get_server_id();
1695+
const IdText& server_id = conn->get_server_id();
16901696
if (server_id.empty()) {
16911697
return;
16921698
}
16931699
// The RAM half updates here, because a later arbitration reads last_played_server_id_; the
16941700
// provider writes for this and for the recency move below wait for
16951701
// SendspinClient::flush_pending_persistence() on the main loop.
1696-
this->client_->note_last_played_server(server_id);
1702+
this->client_->note_last_played_server(server_id.view());
16971703
// A pair-finalize at capacity evicts against the recency order and spares only the records
16981704
// of open connections, so a connection that closes later must not leave its record looking
16991705
// least recent until a deferred move lands. RecordStore::mutex_ is a leaf (docs/conventions.md,

‎src/connection_manager.h‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -382,9 +382,10 @@ class ConnectionManager {
382382
/// connection or its filter.
383383
std::optional<TimeTransform> clock() const;
384384

385-
/// @brief Returns a copy of the primary admitted connection's server information, or nullopt
386-
/// when none is admitted. Any thread: reads a slot written at admission and cleared on the
387-
/// drop, behind the leaf published_mutex_.
385+
/// @brief Returns the primary admitted connection's server information, or nullopt when none
386+
/// is admitted. Any thread: copies the inline id and name out of a slot written at admission
387+
/// and cleared on the drop, behind the leaf published_mutex_, and builds the strings on the
388+
/// caller's thread.
388389
std::optional<ServerInformationObject> server_information() const;
389390

390391
// ========================================
@@ -789,8 +790,7 @@ class ConnectionManager {
789790
/// @param server_id conn->get_server_id(), captured by handle_enter_pairing().
790791
/// @param selected_method The selected method; DYNAMIC_PAIRING_CODE or STATIC_PAIRING_CODE.
791792
void handle_enter_pairing_code(SendspinConnection* conn, uint32_t pairing_index,
792-
const std::string& server_id,
793-
SendspinPairMethod selected_method);
793+
const IdText& server_id, SendspinPairMethod selected_method);
794794

795795
/// @brief Runs the Pairing-PSK branch of handle_enter_pairing(): resolves the pairing
796796
/// outcome and sends client/pair-init followed by client/pair-finalize with the long-term
@@ -799,7 +799,7 @@ class ConnectionManager {
799799
/// @param pairing_index Current pairing_index counter, captured by handle_enter_pairing().
800800
/// @param server_id conn->get_server_id(), captured by handle_enter_pairing().
801801
void handle_enter_pairing_psk(SendspinConnection* conn, uint32_t pairing_index,
802-
const std::string& server_id);
802+
const IdText& server_id);
803803

804804
/// @brief Handles a pair/abort on an admitted connection.
805805
/// Cleans up pairing state. Per pairing.md "pair/abort", only closes the connection for reason
@@ -995,15 +995,22 @@ class ConnectionManager {
995995
/// @brief Each admitted slot's clock (admitted_[slot]), nullopt for a free slot
996996
using ClockSlots = std::array<std::optional<TimeTransform>, MAX_ADMITTED>;
997997

998+
/// @brief The primary connection's server identity, held inline so the publish copies it
999+
/// without a heap allocation
1000+
struct PublishedServer {
1001+
IdText server_id{};
1002+
ServerName name{};
1003+
};
1004+
9981005
/// @brief What other threads read of the admitted connections
9991006
struct PublishedState {
10001007
ClockSlots clocks{};
10011008
/// The slot in clocks of the primary connection (primary()), MAX_ADMITTED for none.
10021009
size_t primary_slot{MAX_ADMITTED};
1003-
/// The primary connection's server information.
1004-
std::optional<ServerInformationObject> server_information;
1010+
/// The primary connection's server identity.
1011+
std::optional<PublishedServer> server;
10051012
};
1006-
/// Guards published_. A leaf (docs/conventions.md): held only to copy or swap a member, so it
1013+
/// Guards published_. A leaf (docs/conventions.md): held only to copy a member, so it
10071014
/// also serialises the role threads' clock() reads behind server_information() copies.
10081015
mutable std::mutex published_mutex_;
10091016
/// Written by the protocol task (refresh_published_state()), which, as its only writer, also

0 commit comments

Comments
 (0)