diff --git a/include/sendspin/client.h b/include/sendspin/client.h index 3573beae..2e6ee855 100644 --- a/include/sendspin/client.h +++ b/include/sendspin/client.h @@ -854,8 +854,9 @@ class SendspinClient { /// only. void process_inbound(SendspinConnection& conn, InboundMessage& message); - /// @brief Builds the client/hello fields from config and every role. Protocol task. - ClientHelloMessage build_client_hello(); + /// @brief Fills `msg` with the client/hello fields from config and every role, viewing them. + /// Protocol task. + void build_client_hello(ClientHelloMessage& msg); /// @brief Builds the client/state snapshot publish_state() hands the protocol task: the /// availability and every role's state object. Main loop only, where that state lives. diff --git a/src/admission.h b/src/admission.h index 2cc6b556..e3c92401 100644 --- a/src/admission.h +++ b/src/admission.h @@ -33,7 +33,6 @@ #include #include #include -#include namespace sendspin { @@ -41,18 +40,6 @@ namespace sendspin { // Trust enforcement (PSK category -> allowed activities) // ============================================================================ -/// @brief Whether `activities` contains `target`. Activity lists are always tiny, so a linear -/// scan is used everywhere in this file instead of a set. -inline bool contains_activity(const std::vector& activities, - SendspinActivity target) { - for (const auto& a : activities) { - if (a == target) { - return true; - } - } - return false; -} - /// @brief Whether an activity set is allowed for the matched PSK category. /// /// The table in messaging.md "server/activate": @@ -83,13 +70,10 @@ inline bool activity_set_allowed(PskCategory category, bool has_playback, bool h return !has_playback || unpaired_access; } -/// @brief activity_set_allowed() for a declared activity list. -inline bool activities_allowed(PskCategory category, - const std::vector& activities, - bool unpaired_access) { - return activity_set_allowed(category, contains_activity(activities, SendspinActivity::PLAYBACK), - contains_activity(activities, SendspinActivity::PAIRING), - unpaired_access); +/// @brief activity_set_allowed() for a declared activity set. +inline bool activities_allowed(PskCategory category, ActivitySet activities, bool unpaired_access) { + return activity_set_allowed(category, activities.contains(SendspinActivity::PLAYBACK), + activities.contains(SendspinActivity::PAIRING), unpaired_access); } /// @brief Whether a connection declaring `activities` is "playback-capable": `activities` @@ -100,12 +84,10 @@ inline bool activities_allowed(PskCategory category, /// @param activities Activities declared in the server/activate message. /// @param unpaired_access Whether unpaired (Sentinel) access is enabled. /// @return true if the connection is playback-capable under these activities. -inline bool is_playback_capable(PskCategory category, - const std::vector& activities, +inline bool is_playback_capable(PskCategory category, ActivitySet activities, bool unpaired_access) { return activity_set_allowed(category, /*has_playback=*/true, - contains_activity(activities, SendspinActivity::PAIRING), - unpaired_access); + activities.contains(SendspinActivity::PAIRING), unpaired_access); } /// @brief Whether `activities`/`active_roles` satisfy the matched PSK's structural constraints. @@ -119,8 +101,8 @@ inline bool is_playback_capable(PskCategory category, /// @param has_roles Whether the effective active_roles set is non-empty. /// @param unpaired_access Whether unpaired (Sentinel) access is enabled. /// @return true if the activate is structurally admissible. -inline bool admissible(PskCategory category, const std::vector& activities, - bool has_roles, bool unpaired_access) { +inline bool admissible(PskCategory category, ActivitySet activities, bool has_roles, + bool unpaired_access) { if (!activities_allowed(category, activities, unpaired_access)) { return false; } @@ -133,8 +115,7 @@ inline bool admissible(PskCategory category, const std::vector /// stops admitting unpaired access. /// /// @param category, activities, has_roles Same as admissible(). -inline bool relies_on_unpaired_access(PskCategory category, - const std::vector& activities, +inline bool relies_on_unpaired_access(PskCategory category, ActivitySet activities, bool has_roles) { return admissible(category, activities, has_roles, /*unpaired_access=*/true) && !admissible(category, activities, has_roles, /*unpaired_access=*/false); @@ -152,9 +133,9 @@ inline bool relies_on_unpaired_access(PskCategory category, /// /// @param category, activities, has_roles, unpaired_access Same as admissible(). /// @return PAIRING_REQUIRED if enabling unpaired access would have admitted it, else UNAUTHORIZED. -inline SendspinGoodbyeReason inadmissible_reject_reason( - PskCategory category, const std::vector& activities, bool has_roles, - bool unpaired_access) { +inline SendspinGoodbyeReason inadmissible_reject_reason(PskCategory category, + ActivitySet activities, bool has_roles, + bool unpaired_access) { if (!unpaired_access && relies_on_unpaired_access(category, activities, has_roles)) { return SendspinGoodbyeReason::PAIRING_REQUIRED; } @@ -169,20 +150,11 @@ inline SendspinGoodbyeReason inadmissible_reject_reason( /// /// connection.md "Multiple servers (server-initiated)" ranks playback above pairing and an empty /// set lowest, so playback=2 > pairing=1 > none=0. -inline int activity_rank(const std::vector& activities) { - bool has_playback = false; - bool has_pairing = false; - for (const auto& a : activities) { - if (a == SendspinActivity::PLAYBACK) { - has_playback = true; - } else if (a == SendspinActivity::PAIRING) { - has_pairing = true; - } - } - if (has_playback) { +inline int activity_rank(ActivitySet activities) { + if (activities.contains(SendspinActivity::PLAYBACK)) { return 2; } - if (has_pairing) { + if (activities.contains(SendspinActivity::PAIRING)) { return 1; } return 0; @@ -204,9 +176,9 @@ inline int activity_rank(const std::vector& activities) { /// declares PAIRING but has already been acked with server/pair-finalize, so rule 2 stops /// shielding a pairing that has finished. /// @return true if the incoming connection should become the admitted one. -inline bool should_admit_connection(const std::vector& incoming_activities, +inline bool should_admit_connection(ActivitySet incoming_activities, const std::string& incoming_server_id, - const std::vector& admitted_activities, + ActivitySet admitted_activities, const std::string& admitted_server_id, bool has_admitted, const std::optional& last_playback_server_id, bool admitted_pairing_in_flight) { @@ -221,8 +193,8 @@ inline bool should_admit_connection(const std::vector& incomin // admitted_pairing_in_flight=false once server/pair-finalize is acked. Substituting an empty // activity set instead would drop the admitted side to rank 0 and hand a rank-0 newcomer the // last_playback tiebreak below, which it could never have won before. - if (admitted_pairing_in_flight && - contains_activity(admitted_activities, SendspinActivity::PAIRING) && incoming_rank != 0) { + if (admitted_pairing_in_flight && admitted_activities.contains(SendspinActivity::PAIRING) && + incoming_rank != 0) { return false; } diff --git a/src/client.cpp b/src/client.cpp index bedd381d..03ab6f42 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -168,19 +168,6 @@ struct HighPerformanceRequests { uint32_t releases{0}; }; -/// @brief Resolve the `locations` hint for a pair-method descriptor in client/hello. -/// @return The hint to advertise, or nullopt to omit the field. -/// -/// The hint is informational (pairing.md "client/hello pair-method descriptor"): only the -/// application knows where its secret was published, so an unset value means the client has -/// nothing to say rather than a default worth sending. -std::optional> locations_hint(const std::vector& configured) { - if (configured.empty()) { - return std::nullopt; - } - return configured; -} - /// @brief Whether `role` is in `mask`, logging the teardown once per role rather than once per /// call site. [[maybe_unused]] bool role_removed(uint16_t mask, SendspinRole role) { @@ -1402,32 +1389,38 @@ void SendspinClient::cleanup_connection_state(uint16_t teardown_roles) { #endif } -ClientHelloMessage SendspinClient::build_client_hello() { +void SendspinClient::build_client_hello(ClientHelloMessage& msg) { // Reached only from ConnectionManager::send_hello_message(), so only for a connection, so // only after a successful start(): record_store_ exists and is dereferenced unguarded below. - ClientHelloMessage msg; msg.name = this->config_.name; + const auto view = [](const std::optional& value) { + return value.has_value() ? std::optional(value.value()) : std::nullopt; + }; + DeviceInfoObject& device_info = msg.device_info.emplace(); + device_info.product_name = view(this->config_.product_name); + device_info.manufacturer = view(this->config_.manufacturer); + device_info.software_version = view(this->config_.software_version); // Use the explicitly configured MAC when provided; otherwise fall back to platform detection // (reliable on ESP, best-effort on host). Leaves the field absent if neither is available. - const std::optional interface_mac = - this->config_.mac_address ? this->config_.mac_address : platform_get_interface_mac(); - - DeviceInfoObject device_info{}; - device_info.product_name = this->config_.product_name; - device_info.manufacturer = this->config_.manufacturer; - device_info.software_version = this->config_.software_version; - device_info.mac_address = interface_mac; - msg.device_info = device_info; + device_info.mac_address = view(this->config_.mac_address); + if (!device_info.mac_address.has_value()) { + if (const std::optional detected = platform_get_interface_mac()) { + msg.detected_mac = detected.value(); + device_info.mac_address = msg.detected_mac.data(); + } + } // pairing.md "client/hello pair-method descriptor". offers_*() is the single source both this // and the server/activate admissibility check read, so a method advertised here is one an - // activation can select. pairing_psk is always advertised (see pairing_offers.h). + // activation can select. pairing_psk is always advertised (see pairing_offers.h). The + // `locations` hint is informational: only the application knows where its secret was + // published, so an empty list is omitted rather than replaced by a default. { PairMethodDescriptor psk_desc; psk_desc.method = SendspinPairMethod::PAIRING_PSK; - psk_desc.locations = locations_hint(this->config_.pairing_psk_locations); - msg.supported_pair_methods.push_back(std::move(psk_desc)); + psk_desc.locations = this->config_.pairing_psk_locations; + msg.supported_pair_methods.push_back(psk_desc); } // out_channels and formats are both required and non-empty. No `locations`: a per-session code // has no resting place for the operator to look it up in. @@ -1436,15 +1429,15 @@ ClientHelloMessage SendspinClient::build_client_hello() { dynamic_desc.method = SendspinPairMethod::DYNAMIC_PAIRING_CODE; dynamic_desc.out_channels = this->config_.pairing_code_out_channels; dynamic_desc.formats = this->config_.pairing_code_formats; - msg.supported_pair_methods.push_back(std::move(dynamic_desc)); + msg.supported_pair_methods.push_back(dynamic_desc); } // Offered only when the dynamic code is not: messaging.md "client/hello" permits at most one // pairing-code method. if (offers_static_pairing_code(this->config_)) { PairMethodDescriptor static_desc; static_desc.method = SendspinPairMethod::STATIC_PAIRING_CODE; - static_desc.locations = locations_hint(this->config_.static_pairing_code_locations); - msg.supported_pair_methods.push_back(std::move(static_desc)); + static_desc.locations = this->config_.static_pairing_code_locations; + msg.supported_pair_methods.push_back(static_desc); } msg.unpaired_access_enabled = this->unpaired_access_enabled_.load(std::memory_order_acquire); @@ -1485,8 +1478,6 @@ ClientHelloMessage SendspinClient::build_client_hello() { this->source_->impl_->build_hello_fields(msg); } #endif - - return msg; } // ============================================================================ diff --git a/src/client_dispatch.cpp b/src/client_dispatch.cpp index a49e444b..3285ecf0 100644 --- a/src/client_dispatch.cpp +++ b/src/client_dispatch.cpp @@ -527,13 +527,14 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const case SendspinServerToClientMessageType::SERVER_ACTIVATE: { ServerActivateMessage activate_msg; if (parsed.extract(&activate_msg)) { - SS_LOGD(TAG, "server/activate received (activities_count=%zu)", - activate_msg.activities.size()); + SS_LOGD(TAG, "server/activate received (playback=%d, pairing=%d)", + activate_msg.activities.contains(SendspinActivity::PLAYBACK), + activate_msg.activities.contains(SendspinActivity::PAIRING)); // Applied before the next message is parsed: trust enforcement, role // ownership and, for a nursery connection that is now operational, admission // all land here, so the role traffic the server sends behind this activate // meets the gate this activation set. - this->connection_manager_->on_server_activate(conn, std::move(activate_msg)); + this->connection_manager_->on_server_activate(conn, activate_msg); } break; } diff --git a/src/connection.h b/src/connection.h index 7a37027e..dc308886 100644 --- a/src/connection.h +++ b/src/connection.h @@ -366,12 +366,12 @@ class SendspinConnection : public std::enable_shared_from_this& get_activities() const { + ActivitySet get_activities() const { return this->activities_; } /// @brief Returns the sticky active_roles set declared by server/activate. Protocol task only. - const std::vector& get_active_roles() const { + ActiveRoles get_active_roles() const { return this->active_roles_; } @@ -571,26 +571,20 @@ class SendspinConnection : public std::enable_shared_from_thisactive_role_mask_ & role_mask_bit(role)) != 0; + return (this->active_roles_.mask() & role_mask_bit(role)) != 0; } /// @brief The active roles as a bitmask of role_mask_bit() values. Protocol task only. uint16_t get_active_role_mask() const { - return this->active_role_mask_; + return this->active_roles_.mask(); } /// @brief Returns true if the given activity is in the current activity set. bool has_activity(SendspinActivity activity) const { - for (const auto& a : this->activities_) { - if (a == activity) { - return true; - } - } - return false; + return this->activities_.contains(activity); } /// @brief Applies a server/activate update: stores activities and updates active_roles @@ -604,24 +598,14 @@ class SendspinConnection : public std::enable_shared_from_this& activities, - const std::optional>& active_roles, + void apply_server_activate(ActivitySet activities, std::optional active_roles, const std::optional& pairing_method, const std::optional& pairing_format) { this->activities_ = activities; if (active_roles.has_value()) { this->active_roles_ = active_roles.value(); } - // Rebuilt on every activation, sticky set included, so the mask cannot drift from - // active_roles_. - this->active_role_mask_ = active_role_mask(this->active_roles_); - bool has_pairing = false; - for (const auto& a : activities) { - if (a == SendspinActivity::PAIRING) { - has_pairing = true; - break; - } - } + const bool has_pairing = activities.contains(SendspinActivity::PAIRING); this->pairing_method_ = has_pairing ? pairing_method : std::nullopt; this->pairing_format_ = has_pairing ? pairing_format : std::nullopt; this->first_activate_received_ = true; @@ -1119,15 +1103,15 @@ class SendspinConnection : public std::enable_shared_from_this activities_{}; + // Struct fields /// Active roles declared by server/activate (sticky: preserved across activates that omit /// the field). Empty until the first activate that includes active_roles. Protocol task only. - std::vector active_roles_{}; + ActiveRoles active_roles_{}; + + /// Activities declared by server/activate (empty until the first activate is applied). + /// Protocol task only: see apply_server_activate(). + ActivitySet activities_{}; /// Pairing method from the pairing object of the last pairing server/activate; nullopt /// outside a pairing activation. Read by the pairing flow. Protocol task only. @@ -1162,12 +1146,6 @@ class SendspinConnection : public std::enable_shared_from_this time_frame_sent_us_{0}; - // 16-bit fields - - /// active_roles_ as a bitmask of the roles this library implements (see is_role_active()). - /// Rebuilt by apply_server_activate(). Protocol task only. - uint16_t active_role_mask_{0}; - // 8-bit fields /// Lifecycle-flag axes. diff --git a/src/connection_manager.cpp b/src/connection_manager.cpp index 0940afc4..ad117143 100644 --- a/src/connection_manager.cpp +++ b/src/connection_manager.cpp @@ -49,9 +49,6 @@ static const char* const TAG = "sendspin.conn_mgr"; static constexpr int64_t WS_SERVER_START_RETRY_MS = 5000LL; static constexpr int64_t WS_SERVER_START_RETRY_US = WS_SERVER_START_RETRY_MS * US_PER_MS; -/// @brief Stands in for an active_roles set the server left out or the client refuses to keep. -static const std::vector EMPTY_ROLES{}; - /// @brief Refuses an activation the client cannot act on /// /// pairing.md "Client <-> Server: pair/abort" answers a method or format the client does not offer @@ -140,9 +137,8 @@ static const char* to_cstr(SetupStage stage) { /// the connection then also takes the operational path (SendspinClient::on_handshake_complete()). /// @return The selected method, or nullopt when the activate does not select pairing. static std::optional selected_pairing_method( - const std::vector& activities, - const std::optional& pairing_method) { - if (!contains_activity(activities, SendspinActivity::PAIRING) || !pairing_method.has_value()) { + ActivitySet activities, const std::optional& pairing_method) { + if (!activities.contains(SendspinActivity::PAIRING) || !pairing_method.has_value()) { return std::nullopt; } const SendspinPairMethod method = pairing_method.value(); @@ -623,7 +619,8 @@ void ConnectionManager::apply_unpaired_access_change(bool enabled) { // Protocol task: message handlers // ============================================================================ -void ConnectionManager::on_server_activate(SendspinConnection* conn, ServerActivateMessage&& msg) { +void ConnectionManager::on_server_activate(SendspinConnection* conn, + const ServerActivateMessage& msg) { NurseryEntry* nursery_entry = this->find_in_nursery(conn); AdmittedEntry* admitted_entry = this->find_admitted(conn); if (nursery_entry == this->nursery_.end() && admitted_entry == nullptr) { @@ -642,9 +639,8 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn, ServerActiv // activate can legally narrow activities without re-sending an empty active_roles). const bool playback_capable = is_playback_capable(conn->get_psk_category(), msg.activities, unpaired_access); - const std::vector& effective_roles = - msg.active_roles.has_value() ? msg.active_roles.value() - : (playback_capable ? conn->get_active_roles() : EMPTY_ROLES); + const ActiveRoles effective_roles = + msg.active_roles.value_or(playback_capable ? conn->get_active_roles() : ActiveRoles{}); const bool has_roles = !effective_roles.empty(); // Trust enforcement against the PSK category the Noise handshake resolved for this @@ -670,7 +666,7 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn, ServerActiv // single point every pairing server/activate is received, so a rejected activate does not // leave the client permanently behind the server's count. handle_enter_pairing() reads this // value; it must not bump again. - const bool is_pairing_activate = contains_activity(msg.activities, SendspinActivity::PAIRING); + const bool is_pairing_activate = msg.activities.contains(SendspinActivity::PAIRING); if (is_pairing_activate) { conn->bump_pairing_index(); } @@ -728,13 +724,13 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn, ServerActiv const bool is_first = !conn->first_activate_received(); // Pass the same active_roles the admissibility check above used: when the message - // omitted active_roles but the connection is no longer playback-capable, that is - // effective_roles == EMPTY_ROLES, and it must be applied (not left sticky) so the - // persisted active_roles_ is actually cleared (messaging.md "Playback-capable connections"). - const std::optional> active_roles_to_apply = + // omitted active_roles but the connection is no longer playback-capable, that is an empty + // effective_roles, and it must be applied (not left sticky) so the persisted active_roles_ + // is actually cleared (messaging.md "Playback-capable connections"). + const std::optional active_roles_to_apply = msg.active_roles.has_value() ? msg.active_roles - : (!playback_capable ? std::make_optional(EMPTY_ROLES) : std::nullopt); + : (!playback_capable ? std::make_optional(ActiveRoles{}) : std::nullopt); // Copied before the activate is applied: messaging.md "client/state" ties the next state // update to the active-role set changing, so the comparison needs the set this activation // replaces. @@ -768,7 +764,7 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn, ServerActiv // an is_first activate also require is_handshake_complete(). this->note_playback_activity(conn); - const auto& activities = conn->get_activities(); + const ActivitySet activities = conn->get_activities(); const std::optional pairing_method = selected_pairing_method(activities, conn->get_pairing_method()); const bool selects_pairing = pairing_method.has_value(); @@ -808,7 +804,7 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn, ServerActiv // declares both purposes therefore runs the operational path as well as the // pairing one, and first: going operational clears stale pairing state the // new attempt must not inherit. - if (is_first && contains_activity(activities, SendspinActivity::PLAYBACK)) { + if (is_first && activities.contains(SendspinActivity::PLAYBACK)) { this->client_->on_handshake_complete(conn); } SS_LOGI(TAG, @@ -819,8 +815,7 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn, ServerActiv // connection.md "Re-handshake" makes a post-re-handshake activation a subsequent // one, so messaging.md "client/state" owes an update for a role it activates. const bool adds_role = (conn->get_active_role_mask() & ~roles_before) != 0; - if (is_first && adds_role && - !contains_activity(activities, SendspinActivity::PLAYBACK)) { + if (is_first && adds_role && !activities.contains(SendspinActivity::PLAYBACK)) { this->client_->publish_client_state(conn); } } @@ -1551,7 +1546,8 @@ bool ConnectionManager::send_hello_message(SendspinConnection* conn) { return true; } - const ClientHelloMessage hello = this->client_->build_client_hello(); + ClientHelloMessage hello; + this->client_->build_client_hello(hello); // client/hello is encrypted like every other post-handshake message. The hello is only sent // once server/hello arrives, so send_json always routes to the active Noise transport here. @@ -1670,7 +1666,7 @@ bool ConnectionManager::should_switch_to_new_server(const SendspinConnection* ad /*incoming_activities=*/new_conn->get_activities(), /*incoming_server_id=*/new_conn->get_server_id(), /*admitted_activities=*/ - has_admitted ? admitted->get_activities() : std::vector{}, + has_admitted ? admitted->get_activities() : ActivitySet{}, /*admitted_server_id=*/has_admitted ? admitted->get_server_id() : std::string{}, /*has_admitted=*/has_admitted, /*last_playback_server_id=*/this->last_played_server_id_, @@ -1764,12 +1760,12 @@ NurseryEntry* ConnectionManager::promote_or_arbitrate_nursery_entry(NurseryEntry // state before the new attempt. A playback-capable connection may carry active roles with // pairing alone (messaging.md "server/activate"), and those still owe the initial // client/state (messaging.md "client/state"), published without going operational. - const auto& activities = admitted->get_activities(); + const ActivitySet activities = admitted->get_activities(); const std::optional pairing_method = selected_pairing_method(activities, admitted->get_pairing_method()); const bool selects_pairing = pairing_method.has_value(); - if (!selects_pairing || contains_activity(activities, SendspinActivity::PLAYBACK)) { + if (!selects_pairing || activities.contains(SendspinActivity::PLAYBACK)) { this->client_->on_handshake_complete(admitted); } if (selects_pairing) { @@ -1778,7 +1774,7 @@ NurseryEntry* ConnectionManager::promote_or_arbitrate_nursery_entry(NurseryEntry this->handle_enter_pairing(admitted); // handle_enter_pairing() may have dropped the connection: checked first. if (this->find_admitted(admitted) != nullptr && - !contains_activity(activities, SendspinActivity::PLAYBACK) && + !activities.contains(SendspinActivity::PLAYBACK) && !admitted->get_active_roles().empty()) { this->client_->publish_client_state(admitted); } diff --git a/src/connection_manager.h b/src/connection_manager.h index e8a67290..32dce5cc 100644 --- a/src/connection_manager.h +++ b/src/connection_manager.h @@ -460,7 +460,7 @@ class ConnectionManager { /// @brief Applies a server/activate: trust enforcement, pairing-method admissibility, role /// ownership and removals, and, for a nursery connection that is now operational, admission /// before this returns. - void on_server_activate(SendspinConnection* conn, ServerActivateMessage&& msg); + void on_server_activate(SendspinConnection* conn, const ServerActivateMessage& msg); /// @brief Handles a pair/abort from the server (an unrecognized reason arrives as /// METHOD_NOT_SUPPORTED). Only an admitted connection hosts a pairing attempt. diff --git a/src/esp/network_info.cpp b/src/esp/network_info.cpp index 710749e0..1b40210d 100644 --- a/src/esp/network_info.cpp +++ b/src/esp/network_info.cpp @@ -30,11 +30,8 @@ static const char* const TAG = "sendspin.network_info"; namespace { -/// @brief Size of a formatted MAC string buffer: "aa:bb:cc:dd:ee:ff" plus null terminator. -constexpr size_t MAC_STR_BUF_SIZE = 18; - /// @brief Formats six MAC octets as lowercase colon-separated text, or nullopt if all zero. -std::optional format_mac(const uint8_t* mac) { +std::optional format_mac(const uint8_t* mac) { bool all_zero = true; for (int i = 0; i < 6; i++) { if (mac[i] != 0) { @@ -46,22 +43,22 @@ std::optional format_mac(const uint8_t* mac) { return std::nullopt; // emulators/unprovisioned efuse can report a zeroed MAC } - char buf[MAC_STR_BUF_SIZE]; - std::snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], - mac[4], mac[5]); - return std::string(buf); + MacAddressText text{}; + std::snprintf(text.data(), text.size(), "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], + mac[3], mac[4], mac[5]); + return text; } } // namespace -std::optional platform_get_interface_mac() { +std::optional platform_get_interface_mac() { uint8_t mac[6] = {0}; // Prefer the MAC of the default network interface - the one outbound connections route over. // This resolves to the correct address whether the device is on Wi-Fi or Ethernet. esp_netif_t* netif = esp_netif_get_default_netif(); if (netif != nullptr && esp_netif_get_mac(netif, mac) == ESP_OK) { - if (std::optional detected = format_mac(mac); detected.has_value()) { + if (std::optional detected = format_mac(mac); detected.has_value()) { return detected; } } diff --git a/src/host/network_info.cpp b/src/host/network_info.cpp index 2e2dd171..9c281ee3 100644 --- a/src/host/network_info.cpp +++ b/src/host/network_info.cpp @@ -52,15 +52,13 @@ static const char* const TAG = "sendspin.network_info"; namespace { -/// @brief Size of a formatted MAC string buffer: "aa:bb:cc:dd:ee:ff" plus null terminator. -constexpr size_t MAC_STR_BUF_SIZE = 18; /// @brief First octet of the IPv4 loopback range 127.0.0.0/8. constexpr uint8_t IPV4_LOOPBACK_FIRST_OCTET = 127; /// @brief High 16 bits of the IPv4 link-local range 169.254.0.0/16. constexpr uint16_t IPV4_LINK_LOCAL_PREFIX = 0xA9FE; /// @brief Formats six MAC octets as lowercase colon-separated text, or nullopt if all zero. -std::optional format_mac(const uint8_t* mac) { +std::optional format_mac(const uint8_t* mac) { bool all_zero = true; for (int i = 0; i < 6; i++) { if (mac[i] != 0) { @@ -72,10 +70,10 @@ std::optional format_mac(const uint8_t* mac) { return std::nullopt; } - char buf[MAC_STR_BUF_SIZE]; - std::snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], - mac[4], mac[5]); - return std::string(buf); + MacAddressText text{}; + std::snprintf(text.data(), text.size(), "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], + mac[3], mac[4], mac[5]); + return text; } /// @brief True if `sa` is a routable (non-loopback, non-link-local) IPv4/IPv6 address. @@ -113,7 +111,7 @@ bool is_routable_ip(const struct sockaddr* sa) { #if defined(_WIN32) -std::optional platform_get_interface_mac() { +std::optional platform_get_interface_mac() { // A first call with no buffer reports the size it needs; retry if the adapter list grows // between calls. const ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER; @@ -153,7 +151,7 @@ std::optional platform_get_interface_mac() { auto result = format_mac(adapter->PhysicalAddress); if (result.has_value()) { - SS_LOGD(TAG, "auto-detected MAC %s on adapter %s", result->c_str(), + SS_LOGD(TAG, "auto-detected MAC %s on adapter %s", result->data(), adapter->AdapterName); return result; } @@ -163,7 +161,7 @@ std::optional platform_get_interface_mac() { #else -std::optional platform_get_interface_mac() { +std::optional platform_get_interface_mac() { struct ifaddrs* ifaddr = nullptr; if (getifaddrs(&ifaddr) != 0 || ifaddr == nullptr) { SS_LOGW(TAG, "getifaddrs failed; cannot auto-detect MAC address"); @@ -180,7 +178,7 @@ std::optional platform_get_interface_mac() { } } - std::optional result; + std::optional result; for (struct ifaddrs* ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) { if (ifa->ifa_addr == nullptr || ifa->ifa_name == nullptr) { continue; @@ -217,7 +215,7 @@ std::optional platform_get_interface_mac() { result = format_mac(sll->sll_addr); #endif if (result.has_value()) { - SS_LOGD(TAG, "auto-detected MAC %s on interface %s", result->c_str(), ifa->ifa_name); + SS_LOGD(TAG, "auto-detected MAC %s on interface %s", result->data(), ifa->ifa_name); break; } } diff --git a/src/platform/network_info.h b/src/platform/network_info.h index 92f551d8..a62e3cae 100644 --- a/src/platform/network_info.h +++ b/src/platform/network_info.h @@ -17,11 +17,18 @@ #pragma once +#include +#include #include -#include namespace sendspin { +/// @brief Size of a MAC address as text, "aa:bb:cc:dd:ee:ff", with its NUL. +static constexpr size_t MAC_ADDRESS_TEXT_SIZE = 18; + +/// @brief A MAC address as NUL-terminated text. +using MacAddressText = std::array; + /// @brief Best-effort lookup of the local MAC address used for Sendspin connections. /// /// Returned as lowercase colon-separated form (e.g., "aa:bb:cc:dd:ee:ff"), suitable @@ -36,6 +43,6 @@ namespace sendspin { /// (non-link-local) IP address. This is a heuristic (the "primary" interface), not necessarily /// the interface a given connection is bound to; on multi-homed hosts it may differ. Prefer /// setting SendspinClientConfig::mac_address explicitly when the exact interface matters. -std::optional platform_get_interface_mac(); +std::optional platform_get_interface_mac(); } // namespace sendspin diff --git a/src/player_role.cpp b/src/player_role.cpp index d943b562..78c2555d 100644 --- a/src/player_role.cpp +++ b/src/player_role.cpp @@ -284,7 +284,7 @@ void PlayerRole::Impl::build_hello_fields(ClientHelloMessage& msg) { .supported_formats = this->config.audio_formats, .buffer_capacity = this->advertised_buffer_capacity(), }; - msg.player_v1_support = std::move(player_support); + msg.player_v1_support = player_support; } size_t PlayerRole::Impl::buffer_capacity_share() const { diff --git a/src/protocol.cpp b/src/protocol.cpp index 67ccff7d..9018fc68 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -384,13 +384,13 @@ bool process_server_activate_message(JsonObject root, ServerActivateMessage* act return true; } - activate_msg->activities.clear(); + activate_msg->activities = ActivitySet{}; JsonArrayConst activities_array = root["payload"]["activities"].as(); for (JsonVariantConst act_var : activities_array) { if (act_var.is()) { auto act = activity_from_string(act_var.as()); if (act.has_value()) { - activate_msg->activities.push_back(act.value()); + activate_msg->activities.insert(act.value()); } } } @@ -398,12 +398,13 @@ bool process_server_activate_message(JsonObject root, ServerActivateMessage* act // active_roles is optional and sticky (omitted = keep prior set). JsonVariantConst roles_var = root["payload"]["active_roles"]; if (roles_var.is()) { - activate_msg->active_roles = std::vector{}; + ActiveRoles roles; for (JsonVariantConst role_var : roles_var.as()) { if (role_var.is()) { - activate_msg->active_roles->push_back(role_var.as()); + roles.add(role_var.as()); } } + activate_msg->active_roles = roles; } else { activate_msg->active_roles = std::nullopt; } @@ -871,25 +872,22 @@ void build_client_hello_message(const ClientHelloMessage* msg, JsonDocument& doc JsonObject methods_obj = root["payload"]["supported_pair_methods"].to(); for (const auto& desc : msg->supported_pair_methods) { JsonObject method_obj = methods_obj[to_cstr(desc.method)].to(); - const auto& out_channels = desc.out_channels; - if (out_channels.has_value() && !out_channels->empty()) { + if (!desc.out_channels.empty()) { JsonArray ch_arr = method_obj["out_channels"].to(); - for (const auto& ch : out_channels.value()) { + for (const auto& ch : desc.out_channels) { ch_arr.add(to_cstr(ch)); } } - const auto& formats = desc.formats; - if (formats.has_value() && !formats->empty()) { + if (!desc.formats.empty()) { JsonArray fmt_arr = method_obj["formats"].to(); - for (const auto& fmt : formats.value()) { + for (const auto& fmt : desc.formats) { fmt_arr.add(to_cstr(fmt)); } } - const auto& locations = desc.locations; - if (locations.has_value() && !locations->empty()) { + if (!desc.locations.empty()) { JsonArray loc_arr = method_obj["locations"].to(); - for (const auto& loc : locations.value()) { - loc_arr.add(loc.c_str()); + for (const auto& loc : desc.locations) { + loc_arr.add(loc); } } } diff --git a/src/protocol_messages.h b/src/protocol_messages.h index 4ff143a1..29519f56 100644 --- a/src/protocol_messages.h +++ b/src/protocol_messages.h @@ -19,6 +19,8 @@ #pragma once #include "crypto/psk_wrap.h" +#include "inline_vector.h" +#include "platform/network_info.h" #include "sendspin/color_role.h" #include "sendspin/config.h" #include "sendspin/controller_role.h" @@ -32,7 +34,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -137,7 +141,7 @@ enum class SendspinRole : uint8_t { VISUALIZER, // Audio visualization role COLOR, // Audio-derived color palette role SOURCE, // Audio capture role (streams to the server) - COUNT, // Not a role; bounds the walk in active_role_mask(). Keep last. + COUNT, // Not a role; bounds the walk in role_from_string(). Keep last. }; /// @brief Protocol wire string for a role (e.g. "player@v1") @@ -162,22 +166,6 @@ inline const char* to_cstr(SendspinRole role) { } } -/// @brief Whether a versioned role name is in an active_roles set -/// -/// The comparison is on the exact versioned name this library implements, not the family, because -/// messaging.md "server/activate" counts "replacement of an active role version" as removal of the -/// version that was active: a client offered `player@v1` that is handed `player@v2` implements -/// neither the new version's behavior nor, any longer, the old one's. -inline bool role_in(const std::vector& active_roles, SendspinRole role) { - const char* name = to_cstr(role); - for (const auto& active : active_roles) { - if (active == name) { - return true; - } - } - return false; -} - /// @brief Bit that represents `role` in an active-role mask inline uint16_t role_mask_bit(SendspinRole role) { return static_cast(1U << static_cast(role)); @@ -189,21 +177,63 @@ static_assert(static_cast(SendspinRole::COUNT) <= 16, "role mask is a u static constexpr uint16_t ALL_ROLES_MASK = static_cast((1U << static_cast(SendspinRole::COUNT)) - 1U); -/// @brief Builds the mask of roles this library implements that `active_roles` names. +/// @brief The role this library implements under a versioned role name, or nullopt /// -/// The mask is what the receive path reads, so it is built with the same exact-version test role -/// removal uses and the two can never disagree. -inline uint16_t active_role_mask(const std::vector& active_roles) { - uint16_t mask = 0; +/// The comparison is on the exact versioned name this library implements, not the family, because +/// messaging.md "server/activate" counts "replacement of an active role version" as removal of the +/// version that was active: a client offered `player@v1` that is handed `player@v2` implements +/// neither the new version's behavior nor, any longer, the old one's. +inline std::optional role_from_string(std::string_view name) { for (uint8_t i = 0; i < static_cast(SendspinRole::COUNT); ++i) { const auto role = static_cast(i); - if (role_in(active_roles, role)) { - mask |= role_mask_bit(role); + if (name == to_cstr(role)) { + return role; } } - return mask; + return std::nullopt; } +/// @brief A server/activate active_roles set, as the client acts on it: the roles this library +/// implements that it names, and whether it names any role at all +/// +/// The mask is what the receive and send gates, the client/state role objects and role removal +/// all read, so none of them can disagree. A role this library does not implement still makes +/// the set non-empty: messaging.md "Playback-capable connections" requires an empty set of a +/// connection that is not playback-capable, whatever it names. +class ActiveRoles { +public: + ActiveRoles() = default; + ActiveRoles(std::initializer_list names) { + for (const std::string_view name : names) { + this->add(name); + } + } + + /// @brief Adds one versioned role name to the set. + void add(std::string_view name) { + this->names_any_ = true; + if (const std::optional role = role_from_string(name)) { + this->mask_ |= role_mask_bit(role.value()); + } + } + + /// @brief The named roles this library implements, as role_mask_bit() bits. + uint16_t mask() const { + return this->mask_; + } + + /// @brief Whether no role was named, implemented here or not. + bool empty() const { + return !this->names_any_; + } + + bool operator==(const ActiveRoles&) const = default; + +private: + uint16_t mask_{0}; + bool names_any_{false}; +}; + /// @brief Activity declared in a server/activate message. /// A connection declares a SET of activities rather than a single reason (messaging.md /// "server/activate"). @@ -235,6 +265,34 @@ inline std::optional activity_from_string(std::string_view str return std::nullopt; } +/// @brief The activities a server/activate declares: a set, its members unordered and unique +class ActivitySet { +public: + ActivitySet() = default; + ActivitySet(std::initializer_list activities) { + for (const SendspinActivity activity : activities) { + this->insert(activity); + } + } + + void insert(SendspinActivity activity) { + this->bits_ |= bit(activity); + } + + bool contains(SendspinActivity activity) const { + return (this->bits_ & bit(activity)) != 0; + } + + bool operator==(const ActivitySet&) const = default; + +private: + static uint8_t bit(SendspinActivity activity) { + return static_cast(1U << static_cast(activity)); + } + + uint8_t bits_{0}; +}; + /// @brief Pairing method on the wire (advertised in client/hello, selected in server/activate). enum class SendspinPairMethod : uint8_t { PAIRING_PSK, // Out-of-band distributed Pairing PSK @@ -422,12 +480,13 @@ inline std::optional playback_state_from_string(std::stri return std::nullopt; } -/// @brief Optional hardware and software identity fields sent in client/hello messages +/// @brief Optional hardware and software identity fields sent in client/hello messages, viewing +/// the strings they name struct DeviceInfoObject { - std::optional product_name{}; - std::optional manufacturer{}; - std::optional software_version{}; - std::optional mac_address{}; + std::optional product_name{}; + std::optional manufacturer{}; + std::optional software_version{}; + std::optional mac_address{}; }; // --- player_role.h --- @@ -484,9 +543,10 @@ inline std::optional player_command_from_string(std::stri return std::nullopt; } -/// @brief Player capabilities advertised to the server during the hello handshake +/// @brief Player capabilities advertised to the server during the hello handshake, viewing the +/// player config's formats struct PlayerSupportObject { - std::vector supported_formats{}; + std::span supported_formats{}; size_t buffer_capacity{}; }; @@ -819,37 +879,46 @@ struct ClientSourceStateObject { // Message envelope structs // ============================================================================ -/// @brief A pairing method descriptor for client/hello supported_pair_methods. -/// Optional fields are omitted from the wire when not set (omit_none semantics). The methods are -/// held as a list rather than a map because the wire object has at most two keys and the -/// descriptor names its own: `method` is serialized as the key this descriptor sits under, not as -/// a field of it (pairing.md "client/hello pair-method descriptor"). +/// @brief A pairing method descriptor for client/hello supported_pair_methods, viewing the lists +/// it names. +/// An empty list is omitted from the wire (omit_none semantics). The methods are held as a list +/// rather than a map because the wire object has at most two keys and the descriptor names its +/// own: `method` is serialized as the key this descriptor sits under, not as a field of it +/// (pairing.md "client/hello pair-method descriptor"). struct PairMethodDescriptor { SendspinPairMethod method{SendspinPairMethod::PAIRING_PSK}; /// @brief Channels the dynamic pairing code is conveyed through. Required and non-empty on - /// the dynamic_pairing_code descriptor, absent on the others. - std::optional> out_channels; + /// the dynamic_pairing_code descriptor, empty on the others. + std::span out_channels; /// @brief Emission formats the client offers. Required and non-empty on the - /// dynamic_pairing_code descriptor, absent on the others. - std::optional> formats; + /// dynamic_pairing_code descriptor, empty on the others. + std::span formats; /// @brief Where the operator can find the method's configured secret: /// 'device' | 'leaflet' | 'operator'. Informational hint for static_pairing_code and - /// pairing_psk only; absent for dynamic_pairing_code, whose code has no resting place. - std::optional> locations; + /// pairing_psk only; empty for dynamic_pairing_code, whose code has no resting place. + std::span locations; }; +/// @brief Most pair methods a client/hello lists: pairing_psk and at most one pairing-code method +/// (messaging.md "client/hello"). +static constexpr size_t MAX_HELLO_PAIR_METHODS = 2; + /// @brief Outgoing client/hello handshake message sent at connection startup. /// Under encryption, client_id and version are carried in client/init (the cleartext Noise -/// handshake frame), not repeated here. +/// handshake frame), not repeated here. Its strings and lists view the client's config and roles, +/// so it is built and serialized in one go and never outlives them. struct ClientHelloMessage { - std::string name{}; + std::string_view name{}; std::optional device_info{}; - std::vector supported_roles{}; + /// @brief Storage for a MAC address detected at build time, which device_info views; the view + /// stays valid because the message can be neither copied nor moved (its InlineVectors). + MacAddressText detected_mac{}; + InlineVector(SendspinRole::COUNT)> supported_roles{}; std::optional player_v1_support{}; std::optional visualizer_support{}; std::optional source_v1_support{}; bool unpaired_access_enabled{false}; - std::vector supported_pair_methods{}; + InlineVector supported_pair_methods{}; }; /// @brief Outgoing client/state message reporting client playback state to the server @@ -923,8 +992,8 @@ struct ServerHelloMessage { /// Declares the server's current activity set and active roles for this connection /// (messaging.md "server/activate"). struct ServerActivateMessage { - std::vector activities{}; - std::optional> active_roles; // sticky: nullopt = keep prior set + ActivitySet activities{}; + std::optional active_roles; // sticky: nullopt = keep prior set /// From payload.pairing.method: the pairing method the server picked. nullopt when the /// message carries no pairing object or names an unrecognized method string. std::optional pairing_method; diff --git a/tests/test_admission.cpp b/tests/test_admission.cpp index d9418c89..f1d21467 100644 --- a/tests/test_admission.cpp +++ b/tests/test_admission.cpp @@ -31,7 +31,7 @@ using namespace sendspin; // NOLINT(google-build-using-namespace): test-local convenience -using Acts = std::vector; +using Acts = ActivitySet; static const auto PB = SendspinActivity::PLAYBACK; static const auto PR = SendspinActivity::PAIRING; diff --git a/tests/test_allocations.cpp b/tests/test_allocations.cpp index 9d183229..f4badd26 100644 --- a/tests/test_allocations.cpp +++ b/tests/test_allocations.cpp @@ -427,12 +427,12 @@ 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 MAC -// address and the fake server's name, each copied three times, allocate only under libstdc++. +// libstdc++ (ESP-IDF's) keeps strings of up to 15 characters inline, libc++ up to 22: the fake +// server's name, copied three times, allocates only under libstdc++. #ifdef _LIBCPP_VERSION -constexpr size_t ADMISSION_ALLOCATIONS = 44; +constexpr size_t ADMISSION_ALLOCATIONS = 24; #else -constexpr size_t ADMISSION_ALLOCATIONS = 50; +constexpr size_t ADMISSION_ALLOCATIONS = 27; #endif constexpr size_t CLIENT_STATE_ALLOCATIONS = 3; constexpr size_t TIME_BURST_ALLOCATIONS = 0; diff --git a/tests/test_client_lifecycle.cpp b/tests/test_client_lifecycle.cpp index 929e5582..7ec767c2 100644 --- a/tests/test_client_lifecycle.cpp +++ b/tests/test_client_lifecycle.cpp @@ -1738,7 +1738,7 @@ TEST(ClientLifecycle, TheCommandQueueRefusesSendsButNeverALifecycleRequest) { ConnectionManager& manager = *client.connection_manager_; manager.liveness_timeout_us_ = 0; auto conn = std::make_shared(); - conn->apply_server_activate({}, std::vector{"player@v1", "controller@v1"}, + conn->apply_server_activate({}, ActiveRoles{"player@v1", "controller@v1"}, std::nullopt, std::nullopt); conn->set_client_hello_sent(row.operational); conn->set_server_hello_received(row.operational); @@ -1918,7 +1918,7 @@ TEST(ClientLifecycle, TheConnectedFlagRisesOnlyAtTheEndOfTheTick) { conn->set_noise_handshake_result("server", PskCategory::LONG_TERM, "psk"); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); - conn->apply_server_activate({SendspinActivity::PLAYBACK}, std::vector{}, + conn->apply_server_activate({SendspinActivity::PLAYBACK}, ActiveRoles{}, std::nullopt, std::nullopt); manager.install_admitted(conn, 0); diff --git a/tests/test_dynamic_pairing_code.cpp b/tests/test_dynamic_pairing_code.cpp index 7cce194f..a433caed 100644 --- a/tests/test_dynamic_pairing_code.cpp +++ b/tests/test_dynamic_pairing_code.cpp @@ -440,13 +440,15 @@ TEST(DynamicPairingCodeCPace, MismatchedAssociatedDataFailsVerify) { TEST(DynamicPairingCode, ClientHelloDescriptorCarriesChannelsAndFormats) { ClientHelloMessage msg; msg.name = "TestDevice"; - PairMethodDescriptor dynamic_desc; - dynamic_desc.method = SendspinPairMethod::DYNAMIC_PAIRING_CODE; - dynamic_desc.out_channels = std::vector{ + const std::vector configured_channels = { SendspinPairingCodeChannel::DISPLAY, SendspinPairingCodeChannel::SPEAKER}; - dynamic_desc.formats = std::vector{ + const std::vector configured_formats = { SendspinPairingCodeFormat::DIGITS, SendspinPairingCodeFormat::QR_CODE}; - msg.supported_pair_methods.push_back(std::move(dynamic_desc)); + PairMethodDescriptor dynamic_desc; + dynamic_desc.method = SendspinPairMethod::DYNAMIC_PAIRING_CODE; + dynamic_desc.out_channels = configured_channels; + dynamic_desc.formats = configured_formats; + msg.supported_pair_methods.push_back(dynamic_desc); const std::string out = built_text([&](JsonDocument& message) { build_client_hello_message(&msg, message); }); @@ -484,7 +486,7 @@ TEST(StaticPairingCode, ClientHelloDescriptorShape) { msg.name = "TestDevice"; PairMethodDescriptor static_desc; static_desc.method = SendspinPairMethod::STATIC_PAIRING_CODE; - msg.supported_pair_methods.push_back(std::move(static_desc)); + msg.supported_pair_methods.push_back(static_desc); const std::string out = built_text([&](JsonDocument& message) { build_client_hello_message(&msg, message); }); @@ -506,10 +508,11 @@ TEST(StaticPairingCode, ClientHelloDescriptorShape) { TEST(StaticPairingCode, ClientHelloLocationsHint) { ClientHelloMessage msg; msg.name = "TestDevice"; + const std::vector configured_locations = {"device", "leaflet"}; PairMethodDescriptor static_desc; static_desc.method = SendspinPairMethod::STATIC_PAIRING_CODE; - static_desc.locations = std::vector{"device", "leaflet"}; - msg.supported_pair_methods.push_back(std::move(static_desc)); + static_desc.locations = configured_locations; + msg.supported_pair_methods.push_back(static_desc); const std::string out = built_text([&](JsonDocument& message) { build_client_hello_message(&msg, message); }); diff --git a/tests/test_encrypted_lifecycle.cpp b/tests/test_encrypted_lifecycle.cpp index 124f403c..e47ab345 100644 --- a/tests/test_encrypted_lifecycle.cpp +++ b/tests/test_encrypted_lifecycle.cpp @@ -1883,9 +1883,8 @@ class DispatchTestConnection : public SendspinConnection { /// every role this fixture drives. DispatchTestConnection() { this->apply_server_activate({SendspinActivity::PLAYBACK}, - std::vector{"player@v1", "controller@v1", - "metadata@v1", "color@v1", - "artwork@v1", "visualizer@v1"}, + ActiveRoles{"player@v1", "controller@v1", "metadata@v1", + "color@v1", "artwork@v1", "visualizer@v1"}, std::nullopt, std::nullopt); } @@ -2607,7 +2606,7 @@ class StateRecordingConnection : public DispatchTestConnection { TEST(EncryptedLifecycle, TheFirstClientStateLeavesOnlyOnceTheConnectionIsAdmitted) { struct Row { const char* label; - std::vector activities; + ActivitySet activities; std::optional pairing_method; }; const Row rows[] = { @@ -2635,7 +2634,7 @@ TEST(EncryptedLifecycle, TheFirstClientStateLeavesOnlyOnceTheConnectionIsAdmitte } // No player in the active set: an active player's state also waits for clock sync, which // lands after admission by itself and would hide the gate under test. - conn->apply_server_activate(row.activities, std::vector{"metadata@v1"}, + conn->apply_server_activate(row.activities, ActiveRoles{"metadata@v1"}, row.pairing_method, std::nullopt); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); @@ -3153,7 +3152,7 @@ TEST(EncryptedLifecycle, APlayingGroupDoesNotMakeAnIdleServerTheLastPlaybackOne) TEST(EncryptedLifecycle, OnlyPlaybackOnTheAdmittedConnectionMovesRecency) { struct Row { const char* name; - std::vector activities; + ActivitySet activities; bool admitted; std::vector expected_order; }; diff --git a/tests/test_network_info.cpp b/tests/test_network_info.cpp index 9c2c372a..aef0cf90 100644 --- a/tests/test_network_info.cpp +++ b/tests/test_network_info.cpp @@ -23,10 +23,10 @@ using namespace sendspin; // sandboxed CI runner), so this asserts the contract rather than a specific value: the result is // either absent or a well-formed lowercase colon-separated MAC. TEST(NetworkInfo, InterfaceMacIsWellFormedOrAbsent) { - const std::optional mac = platform_get_interface_mac(); + const std::optional mac = platform_get_interface_mac(); if (!mac.has_value()) { GTEST_SKIP() << "no routable interface detected in this environment"; } const std::regex mac_re("^[0-9a-f]{2}(:[0-9a-f]{2}){5}$"); - EXPECT_TRUE(std::regex_match(*mac, mac_re)) << "malformed MAC: " << *mac; + EXPECT_TRUE(std::regex_match(mac->data(), mac_re)) << "malformed MAC: " << mac->data(); } diff --git a/tests/test_noise_transport.cpp b/tests/test_noise_transport.cpp index ca0dad2f..1a28950b 100644 --- a/tests/test_noise_transport.cpp +++ b/tests/test_noise_transport.cpp @@ -1867,9 +1867,8 @@ TEST(NoiseTransport, ASendFailureAfterTheEncryptDropsTheConnectionInItsTick) { conn->init_time_filter(); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); - conn->apply_server_activate({SendspinActivity::PLAYBACK}, - std::vector{"controller@v1"}, std::nullopt, - std::nullopt); + conn->apply_server_activate({SendspinActivity::PLAYBACK}, ActiveRoles{"controller@v1"}, + std::nullopt, std::nullopt); // Not due until the row opens it, so only the row's own site sends. conn->time_burst().last_burst_complete_time_ = platform_time_us() / 1000; manager.install_admitted(conn, role_mask_bit(SendspinRole::CONTROLLER)); diff --git a/tests/test_pairing_state_machine.cpp b/tests/test_pairing_state_machine.cpp index 5dae6a86..c03476d8 100644 --- a/tests/test_pairing_state_machine.cpp +++ b/tests/test_pairing_state_machine.cpp @@ -610,8 +610,8 @@ class PairingStateMachineTest : public ::testing::Test { /// path, ConnectionManager::on_server_activate() (trust check, apply_server_activate, then /// either the already-admitted branch's leftover-activate handling or /// on_handshake_complete()): the call process_json_message() makes on the protocol task. - void post_activate(std::vector activities, - std::optional> active_roles, + void post_activate(ActivitySet activities, + std::optional active_roles, std::optional pairing_method, std::optional pairing_format = std::nullopt) { ServerActivateMessage message; @@ -619,8 +619,7 @@ class PairingStateMachineTest : public ::testing::Test { message.active_roles = std::move(active_roles); message.pairing_method = pairing_method; message.pairing_format = pairing_format; - this->client_->connection_manager_->on_server_activate(this->injected_conn_.get(), - std::move(message)); + this->client_->connection_manager_->on_server_activate(this->injected_conn_.get(), message); } /// Put the injected connection into, or out of, the state @@ -680,7 +679,8 @@ class PairingStateMachineTest : public ::testing::Test { std::optional> hello_locations(const char* method) { JsonDocument doc; JsonObject root; - const ClientHelloMessage hello = this->client_->build_client_hello(); + ClientHelloMessage hello; + this->client_->build_client_hello(hello); EXPECT_TRUE(parse_json( built_text([&](JsonDocument& message) { build_client_hello_message(&hello, message); }), doc, root)); @@ -1315,7 +1315,7 @@ TEST_F(PairingStateMachineTest, TrafficContinuesWhileActivitiesDeclarePairing) { << "client/state must keep flowing while activities declare pairing"; // The activate that leaves pairing changes nothing about any of this. - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); this->pump(); ASSERT_FALSE(conn->has_activity(SendspinActivity::PAIRING)); conn->time_frame_tag_ = 0; @@ -2062,13 +2062,13 @@ TEST_F(PairingStateMachineTest, SubsequentActivateEntersPairingForEitherCodeMeth const int windows_before = this->listener_.count(PairingEventKind::OPEN_WINDOW); // First activate: empty activities -> connection goes operational, no pairing. - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); this->pump(); EXPECT_EQ(this->listener_.count(PairingEventKind::STARTED), started_before); EXPECT_TRUE(conn->sent_text_.empty()); // Subsequent activate declaring [pairing] -> must enter pairing. - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, row.method, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, row.method, row.format); this->pump(); @@ -2106,12 +2106,12 @@ TEST_F(PairingStateMachineTest, UnofferedFormatOnActivationIsRejected) { } FakeConnection* conn = this->inject_provisional_current_connection("server-badformat"); - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); this->pump(); ASSERT_TRUE(conn->sent_text_.empty()); // A format this device does not advertise. - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::DYNAMIC_PAIRING_CODE, SendspinPairingCodeFormat::QR_CODE); this->pump(); @@ -2123,7 +2123,7 @@ TEST_F(PairingStateMachineTest, UnofferedFormatOnActivationIsRejected) { EXPECT_EQ(conn->disconnect_count_, 0) << "the connection must stay open after the abort"; // Missing entirely on a dynamic_pairing_code activation (a required field): also rejected. - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::DYNAMIC_PAIRING_CODE, std::nullopt); this->pump(); ASSERT_EQ(conn->sent_text_.size(), 2u); @@ -2131,7 +2131,7 @@ TEST_F(PairingStateMachineTest, UnofferedFormatOnActivationIsRejected) { EXPECT_FALSE(this->listener_.fired(PairingEventKind::STARTED)); // Control: the format this device does advertise starts the attempt. - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::DYNAMIC_PAIRING_CODE, SendspinPairingCodeFormat::DIGITS); this->pump(); @@ -2150,11 +2150,11 @@ TEST_F(PairingStateMachineTest, PairingActivateWithoutMethodIsAborted) { this->enable_unpaired_access(); FakeConnection* conn = this->inject_provisional_current_connection("server-no-method"); - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); this->pump(); ASSERT_TRUE(conn->sent_text_.empty()); - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, std::nullopt); + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, std::nullopt); this->pump(); EXPECT_FALSE(this->listener_.fired(PairingEventKind::STARTED)); @@ -2165,7 +2165,7 @@ TEST_F(PairingStateMachineTest, PairingActivateWithoutMethodIsAborted) { EXPECT_EQ(conn->disconnect_count_, 0) << "the connection must stay open after the abort"; // The same refusal with roles declared beside the pairing activity. - const std::vector roles{"metadata@v1"}; + const ActiveRoles roles{"metadata@v1"}; this->post_activate({SendspinActivity::PAIRING}, roles, std::nullopt); this->pump(); ASSERT_EQ(conn->sent_text_.size(), 2u); @@ -2189,11 +2189,11 @@ TEST_F(PairingStateMachineTest, UnofferedPairingMethodOnActivationIsRejected) { this->init_client(/*pairing_code_emission_supported=*/true); FakeConnection* conn = this->inject_provisional_current_connection("server-unoffered-method"); - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); this->pump(); ASSERT_TRUE(conn->sent_text_.empty()); - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::STATIC_PAIRING_CODE); this->pump(); @@ -2205,7 +2205,7 @@ TEST_F(PairingStateMachineTest, UnofferedPairingMethodOnActivationIsRejected) { // Control: the method this device does offer starts the attempt, so the refusal above is the // offer rule and not the gate refusing every pairing activate. - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::DYNAMIC_PAIRING_CODE, SendspinPairingCodeFormat::DIGITS); this->pump(); @@ -2424,7 +2424,7 @@ TEST_F(PairingStateMachineTest, LeftoverActivateDiscardsPendingRecordAndPairingS conn->pairing_session().attempt_deadline_us = platform_time_us() + 120LL * 1000LL * 1000LL; // The server leaves pairing without finalizing: activate instead of pair-finalize. - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); this->pump(); // Going operational must have discarded the pending record and reset the pairing session. @@ -2508,10 +2508,9 @@ TEST_F(PairingStateMachineTest, CancellingActivateDismissesThePromptItLeftShowin conn->set_pairing_in_progress(false); } if (row.reselect_pairing) { - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, - row.method); + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, row.method); } else { - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); } this->pump(); @@ -2571,7 +2570,7 @@ TEST_F(PairingStateMachineTest, AbortThenRestartReachesTheListenerInOrder) { if (row.drain_between) { this->pump(); } - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::STATIC_PAIRING_CODE); this->pump(); @@ -2618,13 +2617,13 @@ TEST_F(PairingStateMachineTest, PairingIndexIncrementsAcrossRepeatedPairingActiv // An empty activate first, so the pairing activates that follow are subsequent ones on an // already-operational connection (the path a repeat actually takes). - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); this->pump(); ASSERT_TRUE(conn->sent_text_.empty()); EXPECT_EQ(conn->get_pairing_index(), 0u) << "a non-pairing activate must not count"; for (uint32_t expected = 1; expected <= 3; ++expected) { - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::DYNAMIC_PAIRING_CODE, SendspinPairingCodeFormat::DIGITS); this->pump(); @@ -2658,7 +2657,7 @@ TEST_F(PairingStateMachineTest, RejectedActivateStillCountsTowardPairingIndex) { // becomes true), no pairing. Needed so the next two activates are genuinely "subsequent" and // take the same real arbitration path SubsequentActivateEntersStaticCodePairing exercises, // rather than the nursery-promotion path (which this lightweight harness does not model). - this->post_activate({}, std::vector{}, std::nullopt); + this->post_activate({}, ActiveRoles{}, std::nullopt); this->pump(); EXPECT_TRUE(conn->sent_text_.empty()); @@ -2666,7 +2665,7 @@ TEST_F(PairingStateMachineTest, RejectedActivateStillCountsTowardPairingIndex) { // (PskCategory::SENTINEL, not PAIRING), so category_ok fails and the admissibility gate rejects // it with pair/abort(method_not_supported) and leaves the connection open, WITHOUT ever // reaching handle_enter_pairing(). The counter must still have advanced to 1. - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::PAIRING_PSK); this->pump(); EXPECT_EQ(last_pair_abort_reason(conn->sent_text_), "method_not_supported"); @@ -2680,7 +2679,7 @@ TEST_F(PairingStateMachineTest, RejectedActivateStillCountsTowardPairingIndex) { // dynamic method does not require a Pairing-category PSK; offered: an out-channel and a // format are configured). Must proceed into pairing and its client/pair-init must carry // pairing_index == 2: BOTH the rejected and the accepted activate counted. - this->post_activate({SendspinActivity::PAIRING}, std::vector{}, + this->post_activate({SendspinActivity::PAIRING}, ActiveRoles{}, SendspinPairMethod::DYNAMIC_PAIRING_CODE, SendspinPairingCodeFormat::DIGITS); this->pump(); @@ -2905,7 +2904,7 @@ TEST_F(PairingStateMachineTest, FinalizedPairingIsNotEvictedByRankZeroLastPlayba // landed, so get_activities() still reports [PAIRING]. current->note_pairing_finalize_ack(); ASSERT_TRUE(current->is_pairing_finalized()); - ASSERT_EQ(current->get_activities().size(), 1u); + ASSERT_EQ(current->get_activities(), ActivitySet{SendspinActivity::PAIRING}); // A rank-0 peer (no activities) whose server_id is the last playback server: exactly the // inputs admission rule 5 keys on. diff --git a/tests/test_player_role.cpp b/tests/test_player_role.cpp index 413dea05..cd3f0c8e 100644 --- a/tests/test_player_role.cpp +++ b/tests/test_player_role.cpp @@ -427,9 +427,8 @@ TEST(PlayerRoleAvailability, AudioIsDiscardedWhileTheClientIsUnavailable) { } auto conn = std::make_shared(); - conn->apply_server_activate({SendspinActivity::PLAYBACK}, - std::vector{"player@v1"}, std::nullopt, - std::nullopt); + conn->apply_server_activate({SendspinActivity::PLAYBACK}, ActiveRoles{"player@v1"}, + std::nullopt, std::nullopt); client.connection_manager_->install_admitted(conn, role_mask_bit(SendspinRole::PLAYER)); InboundMessage message = receive_into_ring(ring, audio_chunk(), 0); diff --git a/tests/test_protocol.cpp b/tests/test_protocol.cpp index 3c036876..62fe404f 100644 --- a/tests/test_protocol.cpp +++ b/tests/test_protocol.cpp @@ -140,10 +140,9 @@ TEST(Protocol, EnumWireStringsRoundTrip) { }, pair_abort_reason_from_string, "not_a_reason"); - // Roles are read back from server/activate's active_roles through active_role_mask(). - { - SCOPED_TRACE("SendspinRole"); - const std::array roles{ + round_trip( + "SendspinRole", + std::array{ std::pair{SendspinRole::PLAYER, "player@v1"}, std::pair{SendspinRole::CONTROLLER, "controller@v1"}, std::pair{SendspinRole::METADATA, "metadata@v1"}, @@ -151,14 +150,8 @@ TEST(Protocol, EnumWireStringsRoundTrip) { std::pair{SendspinRole::VISUALIZER, "visualizer@v1"}, std::pair{SendspinRole::COLOR, "color@v1"}, std::pair{SendspinRole::SOURCE, "source@v1"}, - }; - for (const auto& [role, wire] : roles) { - SCOPED_TRACE(wire); - EXPECT_STREQ(to_cstr(role), wire); - EXPECT_EQ(active_role_mask({wire}), role_mask_bit(role)); - } - EXPECT_EQ(active_role_mask({"source@v2"}), 0U); - } + }, + role_from_string, "source@v2"); emitted_as("SourceSignal", std::array{ std::pair{SourceSignal::PRESENT, "present"}, @@ -1114,8 +1107,10 @@ TEST(Protocol, FormatClientHelloPlayerSupportOmitsSupportedCommands) { ClientHelloMessage msg; msg.name = "Speaker"; msg.supported_roles.push_back(SendspinRole::PLAYER); + const std::vector formats = { + {SendspinCodecFormat::FLAC, 2, 44100, 16}}; PlayerSupportObject support{}; - support.supported_formats = {{SendspinCodecFormat::FLAC, 2, 44100, 16}}; + support.supported_formats = formats; support.buffer_capacity = 4096; msg.player_v1_support = support; @@ -1345,13 +1340,14 @@ TEST(Protocol, ClientHelloUnpairedAccessIsAlwaysEmitted) { TEST(Protocol, ClientHelloPairMethodsAreKeyedByMethod) { ClientHelloMessage msg; msg.name = "TestDevice"; + const std::vector locations = {"device"}; PairMethodDescriptor psk_desc; psk_desc.method = SendspinPairMethod::PAIRING_PSK; - psk_desc.locations = std::vector{"device"}; - msg.supported_pair_methods.push_back(std::move(psk_desc)); + psk_desc.locations = locations; + msg.supported_pair_methods.push_back(psk_desc); PairMethodDescriptor static_desc; static_desc.method = SendspinPairMethod::STATIC_PAIRING_CODE; - msg.supported_pair_methods.push_back(std::move(static_desc)); + msg.supported_pair_methods.push_back(static_desc); JsonDocument doc; ASSERT_FALSE(deserializeJson(doc, built_text([&](JsonDocument& message) { @@ -1394,7 +1390,7 @@ TEST(Protocol, ServerActivateParsesTheActivitiesList) { struct Row { const char* name; const char* activities_json; - std::vector expected; + ActivitySet expected; }; const Row rows[] = { {"Control: one activity", R"(["playback"])", {SendspinActivity::PLAYBACK}}, @@ -1421,19 +1417,39 @@ TEST(Protocol, ServerActivateParsesTheActivitiesList) { } } -TEST(Protocol, ServerActivateWithActiveRoles) { - JsonDocument doc; - JsonObject root; - ASSERT_TRUE(parse( - R"({"type":"server/activate","payload":{"activities":["playback"],"active_roles":["player@v1","metadata@v1"]}})", - doc, root)); - - ServerActivateMessage msg; - ASSERT_TRUE(process_server_activate_message(root, &msg)); - ASSERT_TRUE(msg.active_roles.has_value()); - ASSERT_EQ(msg.active_roles->size(), 2u); - EXPECT_EQ((*msg.active_roles)[0], "player@v1"); - EXPECT_EQ((*msg.active_roles)[1], "metadata@v1"); +// messaging.md "server/activate": a present active_roles is the new set, read as the roles this +// library implements plus whether it names any role at all. A version this library does not +// implement sets no bit but still makes the set non-empty, which admission reads. +TEST(Protocol, ServerActivateReadsActiveRoles) { + struct Row { + const char* name; + const char* roles_json; + uint16_t mask; + bool empty; + }; + const Row rows[] = { + {"Control: implemented roles", R"(["player@v1","metadata@v1"])", + static_cast(role_mask_bit(SendspinRole::PLAYER) | + role_mask_bit(SendspinRole::METADATA)), + false}, + {"a version this library does not implement", R"(["player@v2"])", 0, false}, + {"an explicit empty set", "[]", 0, true}, + {"no string element", "[7]", 0, true}, + }; + for (const Row& row : rows) { + SCOPED_TRACE(row.name); + JsonDocument doc; + JsonObject root; + ASSERT_TRUE(parse(std::string(R"({"type":"server/activate","payload":{"activities":)" + R"(["playback"],"active_roles":)") + + row.roles_json + "}}", + doc, root)); + ServerActivateMessage msg; + ASSERT_TRUE(process_server_activate_message(root, &msg)); + ASSERT_TRUE(msg.active_roles.has_value()); + EXPECT_EQ(msg.active_roles->mask(), row.mask); + EXPECT_EQ(msg.active_roles->empty(), row.empty); + } } // messaging.md "server/activate" nests the pairing parameters: payload.pairing = @@ -1708,7 +1724,7 @@ TEST(Protocol, Be64HelpersAreBigEndianAndRoundTrip) { TEST(Protocol, FormatClientHelloSourceSupport) { ClientHelloMessage msg; msg.name = "Line In"; - msg.supported_roles = {SendspinRole::SOURCE}; + msg.supported_roles.push_back(SendspinRole::SOURCE); msg.source_v1_support = SourceSupportObject{.line_sense = true}; JsonDocument doc; @@ -1728,7 +1744,7 @@ TEST(Protocol, FormatClientHelloSourceSupport) { EXPECT_EQ(doc_no_features["payload"]["source@v1_support"].as().size(), 0U); // Control: a client without the role sends no support object. - msg.supported_roles = {}; + msg.supported_roles.clear(); msg.source_v1_support.reset(); JsonDocument doc_unset; ASSERT_FALSE(deserializeJson(doc_unset, built_text([&](JsonDocument& message) { diff --git a/tests/test_source_role.cpp b/tests/test_source_role.cpp index 519feaef..894bb951 100644 --- a/tests/test_source_role.cpp +++ b/tests/test_source_role.cpp @@ -503,7 +503,8 @@ TEST(SourceRoleObjects, HelloAndStateFields) { ClientHelloMessage hello; source.impl_->build_hello_fields(hello); - ASSERT_EQ(hello.supported_roles, std::vector{SendspinRole::SOURCE}); + ASSERT_EQ(hello.supported_roles.size(), 1U); + EXPECT_EQ(hello.supported_roles[0], SendspinRole::SOURCE); ASSERT_TRUE(hello.source_v1_support.has_value()); EXPECT_TRUE(hello.source_v1_support->line_sense); @@ -893,9 +894,8 @@ class SourceStandIn { conn->init_time_filter(); conn->set_client_hello_sent(true); conn->set_server_hello_received(true); - conn->apply_server_activate({SendspinActivity::PLAYBACK}, - std::vector{"source@v1"}, std::nullopt, - std::nullopt); + conn->apply_server_activate({SendspinActivity::PLAYBACK}, ActiveRoles{"source@v1"}, + std::nullopt, std::nullopt); // No time burst falls due during a test, so no client/time interleaves. conn->time_burst().last_burst_complete_time_ = platform_time_us() / 1000; if (synced) {