activity_sdk_device_prepare.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. #include <algorithm>
  2. #include <limits>
  3. #include "../../middleware/bap/activity_message/sensor_auth_update.h"
  4. #include "../../middleware/content/packages/tables/region_reader.h"
  5. #include "../../state/activity/runtime.h"
  6. #include "activity_sdk_device_internal.h"
  7. namespace sunrise::server::activity::activity_sdk_devices::detail {
  8. namespace auth = middleware::bap::activity_message::scriptable_auth;
  9. namespace format = state::activity_sdk::format;
  10. namespace layouts = state::build_data::scenarios;
  11. namespace sdk = state::activity_sdk;
  12. namespace tables = middleware::content::packages::tables;
  13. static_assert(format::kDeviceSlotType == auth::kType23SlotType);
  14. static_assert(format::kDeviceAuthSchema == auth::kType23Schema);
  15. static_assert(format::kObjectSlotType == auth::kType4SlotType);
  16. static_assert(format::kObjectAuthSchema == auth::kType4Schema);
  17. namespace {
  18. /** @return True when both complete groups have the same key and compressed wire layout. */
  19. [[nodiscard]] bool same_roster_layout(const layouts::RosterGroup& left,
  20. const layouts::RosterGroup& right) noexcept {
  21. if (!layouts::valid_roster_group(left) || !layouts::valid_roster_group(right)
  22. || left.registryKey != right.registryKey || left.slotCount != right.slotCount) {
  23. return false;
  24. }
  25. for (std::size_t index = 0; index < left.slotCount; ++index) {
  26. if (left.slotTypes[index] != right.slotTypes[index]
  27. || left.slotFlags[index] != right.slotFlags[index]
  28. || left.slotIndices[index] != right.slotIndices[index]) {
  29. return false;
  30. }
  31. }
  32. return true;
  33. }
  34. /** Finds the selected Auth slot in one materialized group's compressed order. */
  35. [[nodiscard]] bool selected_slot_offset(const layouts::RosterGroup& group,
  36. const format::Slot& slot,
  37. std::uint16_t& output) noexcept {
  38. output = 0;
  39. if (!layouts::valid_roster_group(group)
  40. || slot.slotIndex > (std::numeric_limits<std::uint16_t>::max)()) {
  41. return false;
  42. }
  43. std::size_t matches = 0;
  44. for (std::size_t index = 0; index < group.slotCount; ++index) {
  45. if (group.slotIndices[index] != slot.slotIndex || group.slotTypes[index] != slot.slotType
  46. || (group.slotFlags[index] & layouts::kSlotAuthFlag) == 0) {
  47. continue;
  48. }
  49. output = static_cast<std::uint16_t>(index);
  50. ++matches;
  51. }
  52. return matches == 1;
  53. }
  54. /** Resolves a materialized occurrence group to at most one canonical roster row. */
  55. [[nodiscard]] Status canonical_target(const sdk::BoundView& view,
  56. const format::Scenario& scenario,
  57. const format::Slot& slot,
  58. const layouts::RosterGroup& generatedGroup,
  59. std::int32_t effectiveRegion,
  60. host::ScriptableTarget& output,
  61. bool& found) noexcept {
  62. output = {};
  63. found = false;
  64. if (view.binding.destination.packageNameLength == 0
  65. || view.binding.destination.packageNameLength
  66. > view.binding.destination.packageName.size()) {
  67. return Status::invalidView;
  68. }
  69. const std::string_view destination(
  70. reinterpret_cast<const char*>(view.binding.destination.packageName.data()),
  71. view.binding.destination.packageNameLength);
  72. layouts::Definition layout{};
  73. if (!state::build_data::find_scenario_layout(destination, layout) || layout.tag != scenario.tag
  74. || layout.rosterGroupCount > layout.rosterGroups.size()
  75. || layout.bubbleGroupCount > layout.bubbleGroups.size()) {
  76. return Status::targetUnavailable;
  77. }
  78. const std::uint32_t activeBubble =
  79. static_cast<std::uint32_t>(effectiveRegion) / tables::kSliceSetIndexFactor;
  80. std::size_t activeMatches = 0;
  81. std::uint16_t selectedTable = 0;
  82. layouts::RosterGroup selectedGroup{};
  83. const auto consider = [&](std::uint16_t tableIndex, bool active) noexcept {
  84. layouts::RosterGroup candidate{};
  85. if (!state::build_data::find_roster_group(tableIndex, candidate)) {
  86. return false;
  87. }
  88. if (!same_roster_layout(generatedGroup, candidate)) {
  89. return true;
  90. }
  91. if (active) {
  92. if (activeMatches == 0) {
  93. activeMatches = 1;
  94. selectedTable = tableIndex;
  95. selectedGroup = candidate;
  96. } else if (tableIndex != selectedTable) {
  97. // The same canonical table may be published in both the always-active and bubble
  98. // lanes. That is one target; only a distinct active table is ambiguous.
  99. activeMatches = 2;
  100. }
  101. }
  102. return true;
  103. };
  104. for (std::size_t index = 0; index < layout.rosterGroupCount; ++index) {
  105. if (!consider(layout.rosterGroups[index], true)) {
  106. return Status::targetUnavailable;
  107. }
  108. }
  109. for (std::size_t index = 0; index < layout.bubbleGroupCount; ++index) {
  110. const bool active =
  111. activeBubble < layouts::kBubbleCapacity
  112. && (layout.bubbleGroupMasks[index] & (std::uint64_t{1} << activeBubble)) != 0;
  113. if (!consider(layout.bubbleGroups[index], active)) {
  114. return Status::targetUnavailable;
  115. }
  116. }
  117. if (activeMatches > 1) {
  118. return Status::ambiguousTarget;
  119. }
  120. if (activeMatches == 0) {
  121. return Status::ready;
  122. }
  123. std::uint16_t slotOffset = 0;
  124. if (!selected_slot_offset(selectedGroup, slot, slotOffset)) {
  125. return Status::invalidSlot;
  126. }
  127. output.objectTag = selectedGroup.objectTag;
  128. output.registryKey = selectedGroup.registryKey;
  129. output.authSchema = slot.authSchema;
  130. output.rosterGroupIndex = selectedTable;
  131. output.rosterSlotOffset = slotOffset;
  132. output.slotIndex = static_cast<std::uint16_t>(slot.slotIndex);
  133. output.slotType = static_cast<std::uint8_t>(slot.slotType);
  134. found = true;
  135. return Status::ready;
  136. }
  137. /** Finishes the exact canonical or state-local route resolved from the bound SDK. */
  138. [[nodiscard]] Status finish_prepared(const sdk::BoundView& view,
  139. const server::bap::ActivityLinkView& link,
  140. PreparedDevice& output) noexcept {
  141. output.activityClientGeneration = link.activityClientGeneration;
  142. output.scenarioRow = view.scenarioRow;
  143. output.effectiveRegion = link.effectiveRegion;
  144. return Status::ready;
  145. }
  146. } // namespace
  147. /** Maps the SDK binding validator to this API's stable refusal surface. */
  148. [[nodiscard]] Status binding_status(const sdk::BoundView& view,
  149. server::bap::ActivityLinkView& link) noexcept {
  150. if (view.catalog == nullptr || sdk::bound_activity(view) == nullptr
  151. || sdk::bound_scenario(view) == nullptr) {
  152. return Status::invalidView;
  153. }
  154. if (!state::activity::binding_matches(view.binding)) {
  155. return Status::staleBinding;
  156. }
  157. (void)server::bap::activity_link_view(view.binding, link);
  158. switch (
  159. sdk::revalidate(view, view.binding, link.matchingLinks, link.activityClientGeneration)) {
  160. case sdk::Status::ready:
  161. return link.effectiveRegion >= 0 ? Status::ready : Status::noActivityLink;
  162. case sdk::Status::missingClient:
  163. case sdk::Status::ambiguousClient:
  164. return Status::noActivityLink;
  165. case sdk::Status::staleSession:
  166. return Status::staleBinding;
  167. case sdk::Status::staleActivityClient:
  168. return Status::staleActivityClient;
  169. case sdk::Status::notReady:
  170. case sdk::Status::missing:
  171. case sdk::Status::wrongSdkBuild:
  172. case sdk::Status::catalogInvalid:
  173. case sdk::Status::wrongActivity:
  174. case sdk::Status::activityJoinNotExact:
  175. case sdk::Status::missingScenarioLink:
  176. return Status::invalidView;
  177. }
  178. return Status::invalidView;
  179. }
  180. /** Resolves one SDK slot through a published canonical group or its exact live occurrence. */
  181. [[nodiscard]] Status
  182. prepare_slot(const sdk::BoundView& view, std::uint32_t slotRow, PreparedDevice& output) noexcept {
  183. output = {};
  184. server::bap::ActivityLinkView link{};
  185. const Status live = binding_status(view, link);
  186. if (live != Status::ready) {
  187. return live;
  188. }
  189. const sdk::Catalog& catalog = *view.catalog;
  190. const format::Scenario* const scenario = sdk::bound_scenario(view);
  191. const auto slots = catalog.slots();
  192. const auto objects = catalog.objects();
  193. const auto occurrences = catalog.occurrences();
  194. const auto states = catalog.states();
  195. const auto bubbles = catalog.bubbles();
  196. if (scenario == nullptr || slotRow >= slots.size()) {
  197. return Status::invalidSlot;
  198. }
  199. const format::Slot& slot = slots[slotRow];
  200. if (slot.objectIndex >= objects.size()
  201. || slot.slotIndex > middleware::bap::activity_message::sensor_auth_update::kMaximumSlotIndex
  202. || slot.slotType > middleware::bap::activity_message::sensor_auth_update::kMaximumSlotType
  203. || slot.authSchema == 0 || slot.authSchema == format::kAbsentIndex) {
  204. return Status::invalidSlot;
  205. }
  206. if ((slot.flags & format::kSlotSchemaJoinExact) == 0) {
  207. return Status::schemaJoinNotExact;
  208. }
  209. const format::Object& object = objects[slot.objectIndex];
  210. if (object.objectTag == 0 || object.objectKey == 0
  211. || !sdk::materialize_roster_group(catalog, object, output.generatedRosterGroup)) {
  212. return Status::invalidSlot;
  213. }
  214. std::uint16_t slotOffset = 0;
  215. if (!selected_slot_offset(output.generatedRosterGroup, slot, slotOffset)) {
  216. return Status::invalidSlot;
  217. }
  218. bool canonical = false;
  219. const Status canonicalStatus = canonical_target(view,
  220. *scenario,
  221. slot,
  222. output.generatedRosterGroup,
  223. link.effectiveRegion,
  224. output.target,
  225. canonical);
  226. if (canonicalStatus != Status::ready) {
  227. output = {};
  228. return canonicalStatus;
  229. }
  230. if (canonical) {
  231. return finish_prepared(view, link, output);
  232. }
  233. const format::Occurrence* selected = nullptr;
  234. std::uint32_t selectedState = format::kAbsentIndex;
  235. for (const format::Occurrence& occurrence : sdk::scenario_occurrences(catalog, *scenario)) {
  236. if (occurrence.scenarioIndex != view.scenarioRow || &occurrence < occurrences.data()
  237. || &occurrence >= occurrences.data() + occurrences.size()) {
  238. return Status::invalidView;
  239. }
  240. if (occurrence.objectIndex != slot.objectIndex) {
  241. continue;
  242. }
  243. if (occurrence.stateIndex >= states.size() || occurrence.bubbleIndex >= bubbles.size()) {
  244. return Status::invalidView;
  245. }
  246. const format::State& candidateState = states[occurrence.stateIndex];
  247. const format::Bubble& candidateBubble = bubbles[occurrence.bubbleIndex];
  248. if (candidateState.scenarioIndex != view.scenarioRow
  249. || candidateBubble.scenarioIndex != view.scenarioRow
  250. || candidateState.bubbleIndex != occurrence.bubbleIndex
  251. || candidateState.stateOrdinal >= tables::kSliceSetIndexFactor
  252. || candidateBubble.bubbleOrdinal >= layouts::kBubbleCapacity) {
  253. return Status::invalidView;
  254. }
  255. const std::uint64_t candidateRegion =
  256. static_cast<std::uint64_t>(candidateState.sliceSetIndex) + candidateState.stateOrdinal;
  257. if (candidateRegion != static_cast<std::uint64_t>(link.effectiveRegion)) {
  258. continue;
  259. }
  260. if (selected == nullptr) {
  261. selected = &occurrence;
  262. selectedState = occurrence.stateIndex;
  263. } else if (occurrence.stateIndex != selectedState) {
  264. return Status::ambiguousTarget;
  265. }
  266. }
  267. if (selected == nullptr) {
  268. return Status::targetUnavailable;
  269. }
  270. if (selected->stateIndex >= states.size() || selected->bubbleIndex >= bubbles.size()
  271. || selected->objectIndex >= objects.size()) {
  272. return Status::invalidView;
  273. }
  274. const format::State& state = states[selected->stateIndex];
  275. const format::Bubble& bubble = bubbles[selected->bubbleIndex];
  276. if (state.scenarioIndex != view.scenarioRow || bubble.scenarioIndex != view.scenarioRow
  277. || state.bubbleIndex != selected->bubbleIndex || object.objectTag == 0
  278. || object.objectKey == 0 || state.stateOrdinal >= tables::kSliceSetIndexFactor
  279. || bubble.bubbleOrdinal >= layouts::kBubbleCapacity) {
  280. return Status::invalidView;
  281. }
  282. output.target.objectTag = output.generatedRosterGroup.objectTag;
  283. output.target.registryKey = output.generatedRosterGroup.registryKey;
  284. output.target.authSchema = slot.authSchema;
  285. output.target.rosterGroupIndex = host::kGeneratedRosterGroupIndex;
  286. output.target.rosterSlotOffset = slotOffset;
  287. output.target.slotIndex = static_cast<std::uint16_t>(slot.slotIndex);
  288. output.target.sdkObjectIndex = selected->objectIndex;
  289. output.target.stateLocalRegion = link.effectiveRegion;
  290. output.target.slotType = static_cast<std::uint8_t>(slot.slotType);
  291. output.target.stateLocalRoster = true;
  292. output.stateRow = selected->stateIndex;
  293. return finish_prepared(view, link, output);
  294. }
  295. /** Resolves the legacy type-23 device facade through the shared typed SDK Auth slot route. */
  296. [[nodiscard]] Status prepare(const sdk::BoundView& view,
  297. std::uint32_t slotRow,
  298. auth::Type23Channel channel,
  299. float value,
  300. PreparedDevice& output) noexcept {
  301. (void)value;
  302. const auto channelIndex = static_cast<std::size_t>(channel);
  303. if (channelIndex >= auth::kType23ChannelCount) {
  304. return Status::invalidChannel;
  305. }
  306. if (view.catalog == nullptr || slotRow >= view.catalog->slots().size()) {
  307. return Status::invalidSlot;
  308. }
  309. const format::Slot& slot = view.catalog->slots()[slotRow];
  310. if (slot.slotType != format::kDeviceSlotType
  311. || slot.componentClass != format::kDeviceComponentClass
  312. || slot.senseSchema != format::kDeviceSenseSchema
  313. || slot.authSchema != format::kDeviceAuthSchema) {
  314. return Status::invalidSlot;
  315. }
  316. return prepare_slot(view, slotRow, output);
  317. }
  318. /**
  319. * Resolves one exact type-31 trigger slot. Type 31 carries no caller value, so unlike the device
  320. * path there is no channel or range to check first.
  321. * @param view Pinned SDK view whose binding is revalidated.
  322. * @param slotRow Catalog row the pulse targets.
  323. * @param output Cleared, then receives the resolved target.
  324. * @return ready only for an exact type-31 slot on a live owned binding.
  325. */
  326. [[nodiscard]] Status prepare_trigger(const sdk::BoundView& view,
  327. std::uint32_t slotRow,
  328. PreparedDevice& output) noexcept {
  329. if (view.catalog == nullptr || slotRow >= view.catalog->slots().size()) {
  330. return Status::invalidSlot;
  331. }
  332. const format::Slot& slot = view.catalog->slots()[slotRow];
  333. if (slot.slotType != auth::kType31SlotType || slot.authSchema != auth::kType31Schema) {
  334. return Status::invalidSlot;
  335. }
  336. return prepare_slot(view, slotRow, output);
  337. }
  338. /** Resolves one package-owned object entry without accepting a caller transform. */
  339. [[nodiscard]] Status prepare_object(const sdk::BoundView& view,
  340. std::uint32_t slotRow,
  341. std::int32_t entryIndex,
  342. PreparedDevice& output) noexcept {
  343. if (view.catalog == nullptr || slotRow >= view.catalog->slots().size() || entryIndex < 0) {
  344. return Status::invalidSlot;
  345. }
  346. const format::Slot& slot = view.catalog->slots()[slotRow];
  347. if (slot.slotType != format::kObjectSlotType
  348. || slot.componentClass != format::kObjectComponentClass
  349. || slot.senseSchema != format::kObjectSenseSchema
  350. || slot.authSchema != format::kObjectAuthSchema) {
  351. return Status::invalidSlot;
  352. }
  353. return prepare_slot(view, slotRow, output);
  354. }
  355. /** Resolves one exact actor channel bridge. */
  356. [[nodiscard]] Status prepare_combatant(const sdk::BoundView& view,
  357. std::uint32_t slotRow,
  358. PreparedDevice& output) noexcept {
  359. if (view.catalog == nullptr || slotRow >= view.catalog->slots().size()) {
  360. return Status::invalidSlot;
  361. }
  362. const format::Slot& slot = view.catalog->slots()[slotRow];
  363. if (slot.slotType != auth::kType2SlotType || slot.componentClass != auth::kType2ComponentClass
  364. || slot.senseSchema != auth::kType2SenseSchema || slot.authSchema != auth::kType2Schema) {
  365. return Status::invalidSlot;
  366. }
  367. return prepare_slot(view, slotRow, output);
  368. }
  369. /** Verifies exact SDK identity and schema-decodes one retained Auth body. */
  370. [[nodiscard]] Status validate_auth(const sdk::BoundView& view,
  371. std::uint32_t slotRow,
  372. std::uint32_t objectTag,
  373. std::uint32_t registryKey,
  374. std::uint32_t authSchema,
  375. std::uint16_t slotIndex,
  376. std::uint8_t slotType,
  377. std::span<const std::byte> body,
  378. std::uint16_t bitCount,
  379. std::span<const std::byte> sdkBuildSha256) noexcept {
  380. if (view.catalog == nullptr || sdkBuildSha256.size() != 32U
  381. || view.catalog->sdk_build_sha256().size() != sdkBuildSha256.size()
  382. || !std::equal(sdkBuildSha256.begin(),
  383. sdkBuildSha256.end(),
  384. view.catalog->sdk_build_sha256().begin())) {
  385. return Status::wrongSdkBuild;
  386. }
  387. const auto slots = view.catalog->slots();
  388. const auto objects = view.catalog->objects();
  389. if (slotRow >= slots.size()) {
  390. return Status::invalidSlot;
  391. }
  392. const format::Slot& slot = slots[slotRow];
  393. if (slot.objectIndex >= objects.size() || objectTag == 0 || registryKey == 0 || authSchema == 0
  394. || slotType > middleware::bap::activity_message::sensor_auth_update::kMaximumSlotType
  395. || slotIndex > middleware::bap::activity_message::sensor_auth_update::kMaximumSlotIndex
  396. || objects[slot.objectIndex].objectTag != objectTag
  397. || objects[slot.objectIndex].objectKey != registryKey || slot.authSchema != authSchema
  398. || slot.slotIndex != slotIndex || slot.slotType != slotType) {
  399. return Status::invalidSlot;
  400. }
  401. if ((slot.flags & format::kSlotSchemaJoinExact) == 0) {
  402. return Status::schemaJoinNotExact;
  403. }
  404. if (body.empty()
  405. || body.size()
  406. > middleware::bap::activity_message::sensor_auth_update::kAuthOverrideByteCapacity
  407. || bitCount > body.size() * 8U || bitCount + 7U < body.size() * 8U) {
  408. return Status::invalidBody;
  409. }
  410. const std::size_t trailingBits = bitCount % 8U;
  411. if (trailingBits != 0) {
  412. const std::uint8_t paddingMask =
  413. static_cast<std::uint8_t>((std::uint16_t{1} << (8U - trailingBits)) - 1U);
  414. if ((std::to_integer<std::uint8_t>(body.back()) & paddingMask) != 0) {
  415. return Status::invalidBody;
  416. }
  417. }
  418. // An occupancy Auth body is exactly 87 bits, which the wire pads to 11 bytes.
  419. constexpr std::size_t kOccupancyAuthBits = 87;
  420. constexpr std::size_t kOccupancyAuthBytes = 11;
  421. const bool occupancy = slotType == format::kOccupancySlotType
  422. && authSchema == format::kOccupancyAuthSchema
  423. && bitCount == kOccupancyAuthBits && body.size() == kOccupancyAuthBytes;
  424. const bool directive =
  425. slotType == middleware::bap::activity_message::scriptable_auth::kType68SlotType
  426. && authSchema == middleware::bap::activity_message::scriptable_auth::kType68Schema
  427. && middleware::bap::activity_message::scriptable_auth::validate_type68_body(body, bitCount);
  428. const bool engagement =
  429. slotType == middleware::bap::activity_message::scriptable_auth::kType70SlotType
  430. && authSchema == middleware::bap::activity_message::scriptable_auth::kType70Schema
  431. && middleware::bap::activity_message::scriptable_auth::validate_type70_body(body, bitCount);
  432. const bool publicEvent =
  433. slotType == middleware::bap::activity_message::scriptable_auth::kType71SlotType
  434. && authSchema == middleware::bap::activity_message::scriptable_auth::kType71Schema
  435. && middleware::bap::activity_message::scriptable_auth::validate_type71_body(body, bitCount);
  436. const bool performance =
  437. slotType == middleware::bap::activity_message::scriptable_auth::kType42SlotType
  438. && authSchema == middleware::bap::activity_message::scriptable_auth::kType42Schema
  439. && middleware::bap::activity_message::scriptable_auth::validate_type42_body(body, bitCount);
  440. const bool combatant =
  441. slotType == middleware::bap::activity_message::scriptable_auth::kType2SlotType
  442. && authSchema == middleware::bap::activity_message::scriptable_auth::kType2Schema
  443. && middleware::bap::activity_message::scriptable_auth::validate_type2_body(body, bitCount);
  444. if (!occupancy && !directive && !engagement && !publicEvent && !performance && !combatant) {
  445. return Status::invalidBody;
  446. }
  447. return Status::ready;
  448. }
  449. } // namespace sunrise::server::activity::activity_sdk_devices::detail