1 /* 2 * Copyright 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <packet_runtime.h> 20 21 #include <algorithm> 22 #include <array> 23 #include <chrono> 24 #include <cstddef> 25 #include <cstdint> 26 #include <functional> 27 #include <memory> 28 #include <optional> 29 #include <set> 30 #include <unordered_map> 31 #include <utility> 32 #include <vector> 33 34 #include "hci/address.h" 35 #include "hci/address_with_type.h" 36 #include "model/controller/acl_connection_handler.h" 37 #include "model/controller/controller_properties.h" 38 #include "model/controller/le_advertiser.h" 39 #include "model/controller/sco_connection.h" 40 #include "model/controller/vendor_commands/le_apcf.h" 41 #include "packets/hci_packets.h" 42 #include "packets/link_layer_packets.h" 43 #include "phy.h" 44 #include "rust/include/rootcanal_rs.h" 45 46 namespace rootcanal { 47 48 using ::bluetooth::hci::Address; 49 using ::bluetooth::hci::AddressType; 50 using ::bluetooth::hci::AuthenticationEnable; 51 using ::bluetooth::hci::ErrorCode; 52 using ::bluetooth::hci::FilterAcceptListAddressType; 53 using ::bluetooth::hci::OpCode; 54 using ::bluetooth::hci::PageScanRepetitionMode; 55 using rootcanal::apcf::ApcfScanner; 56 57 // Create an address with type Public Device Address or Random Device Address. 58 AddressWithType PeerDeviceAddress(Address address, 59 PeerAddressType peer_address_type); 60 // Create an address with type Public Identity Address or Random Identity 61 // address. 62 AddressWithType PeerIdentityAddress(Address address, 63 PeerAddressType peer_address_type); 64 65 class LinkLayerController { 66 public: 67 static constexpr size_t kIrkSize = 16; 68 static constexpr size_t kLtkSize = 16; 69 static constexpr size_t kLocalNameSize = 248; 70 static constexpr size_t kExtendedInquiryResponseSize = 240; 71 72 // Unique instance identifier. 73 const uint32_t id_; 74 75 // Generate a resolvable private address using the specified IRK. 76 static Address generate_rpa( 77 std::array<uint8_t, LinkLayerController::kIrkSize> irk); 78 79 // Return true if the input IRK is all 0s. 80 static bool irk_is_zero(std::array<uint8_t, LinkLayerController::kIrkSize> irk); 81 82 LinkLayerController(const Address& address, 83 const ControllerProperties& properties, uint32_t id = 0); 84 ~LinkLayerController(); 85 86 ErrorCode SendCommandToRemoteByAddress(OpCode opcode, pdl::packet::slice args, 87 const Address& own_address, 88 const Address& peer_address); 89 ErrorCode SendLeCommandToRemoteByAddress(OpCode opcode, 90 const Address& own_address, 91 const Address& peer_address); 92 ErrorCode SendCommandToRemoteByHandle(OpCode opcode, pdl::packet::slice args, 93 uint16_t handle); 94 ErrorCode SendScoToRemote(bluetooth::hci::ScoView sco_packet); 95 ErrorCode SendAclToRemote(bluetooth::hci::AclView acl_packet); 96 97 void ForwardToLm(bluetooth::hci::CommandView command); 98 void ForwardToLl(bluetooth::hci::CommandView command); 99 100 std::vector<bluetooth::hci::Lap> const& ReadCurrentIacLap() const; 101 void WriteCurrentIacLap(std::vector<bluetooth::hci::Lap> iac_lap); 102 103 ErrorCode AcceptConnectionRequest(const Address& addr, bool try_role_switch); 104 void MakePeripheralConnection(const Address& addr, bool try_role_switch); 105 ErrorCode RejectConnectionRequest(const Address& addr, uint8_t reason); 106 void RejectPeripheralConnection(const Address& addr, uint8_t reason); 107 108 // HCI command Create Connection (Vol 4, Part E § 7.1.5). 109 ErrorCode CreateConnection(const Address& bd_addr, uint16_t packet_type, 110 uint8_t page_scan_mode, uint16_t clock_offset, 111 uint8_t allow_role_switch); 112 113 // HCI command Disconnect (Vol 4, Part E § 7.1.6). 114 // \p host_reason is taken from the Disconnect command, and sent over 115 // to the remote as disconnect error. \p controller_reason is the code 116 // used in the DisconnectionComplete event. 117 ErrorCode Disconnect(uint16_t handle, ErrorCode host_reason, 118 ErrorCode controller_reason = 119 ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST); 120 121 // HCI command Create Connection Cancel (Vol 4, Part E § 7.1.7). 122 ErrorCode CreateConnectionCancel(const Address& bd_addr); 123 124 // Internal task scheduler. 125 // This scheduler is driven by the tick function only, 126 // hence the precision of the scheduler is within a tick period. 127 class Task; 128 using TaskId = uint32_t; 129 using TaskCallback = std::function<void(void)>; 130 static constexpr TaskId kInvalidTaskId = 0; 131 132 /// Schedule a task to be executed \p delay ms in the future. 133 TaskId ScheduleTask(std::chrono::milliseconds delay, 134 TaskCallback task_callback); 135 136 /// Schedule a task to be executed every \p period ms starting 137 /// \p delay ms in the future. Note that the task will be executed 138 /// at most once per \ref Tick() invocation, hence the period 139 /// cannot be lower than the \ref Tick() period. 140 TaskId SchedulePeriodicTask(std::chrono::milliseconds delay, 141 std::chrono::milliseconds period, 142 TaskCallback task_callback); 143 144 /// Cancel the selected task. 145 void CancelScheduledTask(TaskId task_id); 146 147 // Execute tasks that are pending at the current time. 148 void RunPendingTasks(); 149 150 private: 151 void SendDisconnectionCompleteEvent(uint16_t handle, ErrorCode reason); 152 153 public: 154 const Address& GetAddress() const; 155 156 void IncomingPacket(model::packets::LinkLayerPacketView incoming, 157 int8_t rssi); 158 159 void Tick(); 160 161 void Close(); 162 163 // Set the callbacks for sending packets to the HCI. 164 void RegisterEventChannel( 165 const std::function<void(std::shared_ptr<bluetooth::hci::EventBuilder>)>& 166 send_event); 167 168 void RegisterAclChannel( 169 const std::function<void(std::shared_ptr<bluetooth::hci::AclBuilder>)>& 170 send_acl); 171 172 void RegisterScoChannel( 173 const std::function<void(std::shared_ptr<bluetooth::hci::ScoBuilder>)>& 174 send_sco); 175 176 void RegisterIsoChannel( 177 const std::function<void(std::shared_ptr<bluetooth::hci::IsoBuilder>)>& 178 send_iso); 179 180 void RegisterRemoteChannel( 181 const std::function< 182 void(std::shared_ptr<model::packets::LinkLayerPacketBuilder>, 183 Phy::Type, int8_t)>& send_to_remote); 184 185 void Reset(); 186 187 void Paging(); 188 void LeAdvertising(); 189 void LeScanning(); 190 void LeSynchronization(); 191 192 void LeConnectionUpdateComplete(uint16_t handle, uint16_t interval_min, 193 uint16_t interval_max, uint16_t latency, 194 uint16_t supervision_timeout); 195 ErrorCode LeConnectionUpdate(uint16_t handle, uint16_t interval_min, 196 uint16_t interval_max, uint16_t latency, 197 uint16_t supervision_timeout); 198 ErrorCode LeRemoteConnectionParameterRequestReply( 199 uint16_t connection_handle, uint16_t interval_min, uint16_t interval_max, 200 uint16_t timeout, uint16_t latency, uint16_t minimum_ce_length, 201 uint16_t maximum_ce_length); 202 ErrorCode LeRemoteConnectionParameterRequestNegativeReply( 203 uint16_t connection_handle, bluetooth::hci::ErrorCode reason); 204 uint16_t HandleLeConnection(AddressWithType addr, AddressWithType own_addr, 205 bluetooth::hci::Role role, 206 uint16_t connection_interval, 207 uint16_t connection_latency, 208 uint16_t supervision_timeout, 209 bool send_le_channel_selection_algorithm_event); 210 211 bool ResolvingListBusy(); 212 bool FilterAcceptListBusy(); 213 214 bool LeFilterAcceptListContainsDevice( 215 FilterAcceptListAddressType address_type, Address address); 216 bool LeFilterAcceptListContainsDevice(AddressWithType address); 217 218 bool LePeriodicAdvertiserListContainsDevice( 219 bluetooth::hci::AdvertiserAddressType advertiser_address_type, 220 Address advertiser_address, uint8_t advertising_sid); 221 222 enum IrkSelection { 223 Peer, // Use Peer IRK for RPA resolution or generation. 224 Local // Use Local IRK for RPA resolution or generation. 225 }; 226 227 // If the selected address is a Resolvable Private Address, then 228 // resolve the address using the resolving list. If the address cannot 229 // be resolved none is returned. If the address is not a Resolvable 230 // Private Address, the original address is returned. 231 std::optional<AddressWithType> ResolvePrivateAddress(AddressWithType address); 232 233 // Returns true if the input address resolves with the local IRK 234 // associated with the given peer identity address. 235 bool ResolveTargetA(AddressWithType target_a, AddressWithType adv_a); 236 237 // Returns true if either: 238 // • TargetA is identical to the device address, or 239 // • TargetA is a resolvable private address, address 240 // resolution is enabled, and the address is resolved successfully 241 bool ValidateTargetA(AddressWithType target_a, AddressWithType adv_a); 242 243 // Generate a Resolvable Private for the selected peer. 244 // If the address is not found in the resolving list none is returned. 245 // `local` indicates whether to use the local (true) or peer (false) IRK when 246 // generating the Resolvable Private Address. 247 std::optional<AddressWithType> GenerateResolvablePrivateAddress( 248 AddressWithType address, IrkSelection irk); 249 250 // Check if the selected address matches one of the controller's device 251 // addresses (public or random static). IsLocalPublicOrRandomAddress(AddressWithType address)252 bool IsLocalPublicOrRandomAddress(AddressWithType address) { 253 switch (address.GetAddressType()) { 254 case AddressType::PUBLIC_DEVICE_ADDRESS: 255 return address.GetAddress() == address_; 256 case AddressType::RANDOM_DEVICE_ADDRESS: 257 return address.GetAddress() == random_address_; 258 default: 259 return false; 260 } 261 } 262 263 void HandleLeEnableEncryption(uint16_t handle, std::array<uint8_t, 8> rand, 264 uint16_t ediv, 265 std::array<uint8_t, kLtkSize> ltk); 266 267 ErrorCode LeEnableEncryption(uint16_t handle, std::array<uint8_t, 8> rand, 268 uint16_t ediv, 269 std::array<uint8_t, kLtkSize> ltk); 270 271 ErrorCode LeLongTermKeyRequestReply(uint16_t handle, 272 std::array<uint8_t, kLtkSize> ltk); 273 274 ErrorCode LeLongTermKeyRequestNegativeReply(uint16_t handle); 275 276 uint8_t LeReadNumberOfSupportedAdvertisingSets(); 277 278 // Classic 279 void StartInquiry(std::chrono::milliseconds timeout); 280 void InquiryCancel(); 281 void InquiryTimeout(); 282 void SetInquiryMode(uint8_t mode); 283 void SetInquiryLAP(uint64_t lap); 284 void SetInquiryMaxResponses(uint8_t max); 285 void Inquiry(); 286 GetInquiryScanEnable()287 bool GetInquiryScanEnable() const { return inquiry_scan_enable_; } 288 void SetInquiryScanEnable(bool enable); 289 GetPageScanEnable()290 bool GetPageScanEnable() const { return page_scan_enable_; } 291 void SetPageScanEnable(bool enable); 292 GetPageTimeout()293 uint16_t GetPageTimeout() const { return page_timeout_; } 294 void SetPageTimeout(uint16_t page_timeout); 295 296 ErrorCode ChangeConnectionPacketType(uint16_t handle, uint16_t types); 297 ErrorCode ChangeConnectionLinkKey(uint16_t handle); 298 ErrorCode CentralLinkKey(uint8_t key_flag); 299 ErrorCode HoldMode(uint16_t handle, uint16_t hold_mode_max_interval, 300 uint16_t hold_mode_min_interval); 301 ErrorCode SniffMode(uint16_t handle, uint16_t sniff_max_interval, 302 uint16_t sniff_min_interval, uint16_t sniff_attempt, 303 uint16_t sniff_timeout); 304 ErrorCode ExitSniffMode(uint16_t handle); 305 ErrorCode QosSetup(uint16_t handle, uint8_t service_type, uint32_t token_rate, 306 uint32_t peak_bandwidth, uint32_t latency, 307 uint32_t delay_variation); 308 ErrorCode RoleDiscovery(uint16_t handle, bluetooth::hci::Role* role); 309 ErrorCode SwitchRole(Address bd_addr, bluetooth::hci::Role role); 310 ErrorCode ReadLinkPolicySettings(uint16_t handle, uint16_t* settings); 311 ErrorCode WriteLinkPolicySettings(uint16_t handle, uint16_t settings); 312 ErrorCode FlowSpecification(uint16_t handle, uint8_t flow_direction, 313 uint8_t service_type, uint32_t token_rate, 314 uint32_t token_bucket_size, 315 uint32_t peak_bandwidth, uint32_t access_latency); 316 ErrorCode WriteLinkSupervisionTimeout(uint16_t handle, uint16_t timeout); 317 ErrorCode WriteDefaultLinkPolicySettings(uint16_t settings); 318 void CheckExpiringConnection(uint16_t handle); 319 uint16_t ReadDefaultLinkPolicySettings() const; 320 321 void ReadLocalOobData(); 322 void ReadLocalOobExtendedData(); 323 324 ErrorCode AddScoConnection(uint16_t connection_handle, uint16_t packet_type, 325 ScoDatapath datapath); 326 ErrorCode SetupSynchronousConnection( 327 uint16_t connection_handle, uint32_t transmit_bandwidth, 328 uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice_setting, 329 uint8_t retransmission_effort, uint16_t packet_types, 330 ScoDatapath datapath); 331 ErrorCode AcceptSynchronousConnection( 332 Address bd_addr, uint32_t transmit_bandwidth, uint32_t receive_bandwidth, 333 uint16_t max_latency, uint16_t voice_setting, 334 uint8_t retransmission_effort, uint16_t packet_types); 335 ErrorCode RejectSynchronousConnection(Address bd_addr, uint16_t reason); 336 337 // Returns true if any ACL connection exists. 338 bool HasAclConnection(); 339 // Returns true if the specified ACL connection handle is valid. 340 bool HasAclConnection(uint16_t connection_handle); 341 342 void HandleIso(bluetooth::hci::IsoView iso); 343 344 // BR/EDR Commands 345 346 // HCI Read Rssi command (Vol 4, Part E § 7.5.4). 347 ErrorCode ReadRssi(uint16_t connection_handle, int8_t* rssi); 348 349 // LE Commands 350 351 // HCI LE Set Random Address command (Vol 4, Part E § 7.8.4). 352 ErrorCode LeSetRandomAddress(Address random_address); 353 354 // HCI LE Set Resolvable Private Address Timeout command 355 // (Vol 4, Part E § 7.8.45). 356 ErrorCode LeSetResolvablePrivateAddressTimeout(uint16_t rpa_timeout); 357 358 // HCI LE Read Phy command (Vol 4, Part E § 7.8.47). 359 ErrorCode LeReadPhy(uint16_t connection_handle, 360 bluetooth::hci::PhyType* tx_phy, 361 bluetooth::hci::PhyType* rx_phy); 362 363 // HCI LE Set Default Phy command (Vol 4, Part E § 7.8.48). 364 ErrorCode LeSetDefaultPhy(bool all_phys_no_transmit_preference, 365 bool all_phys_no_receive_preference, 366 uint8_t tx_phys, uint8_t rx_phys); 367 368 // HCI LE Set Phy command (Vol 4, Part E § 7.8.49). 369 ErrorCode LeSetPhy(uint16_t connection_handle, 370 bool all_phys_no_transmit_preference, 371 bool all_phys_no_receive_preference, uint8_t tx_phys, 372 uint8_t rx_phys, bluetooth::hci::PhyOptions phy_options); 373 374 // HCI LE Set Host Feature command (Vol 4, Part E § 7.8.115). 375 ErrorCode LeSetHostFeature(uint8_t bit_number, uint8_t bit_value); 376 377 // LE Filter Accept List 378 379 // HCI command LE_Clear_Filter_Accept_List (Vol 4, Part E § 7.8.15). 380 ErrorCode LeClearFilterAcceptList(); 381 382 // HCI command LE_Add_Device_To_Filter_Accept_List (Vol 4, Part E § 7.8.16). 383 ErrorCode LeAddDeviceToFilterAcceptList( 384 FilterAcceptListAddressType address_type, Address address); 385 386 // HCI command LE_Remove_Device_From_Filter_Accept_List (Vol 4, Part E 387 // § 7.8.17). 388 ErrorCode LeRemoveDeviceFromFilterAcceptList( 389 FilterAcceptListAddressType address_type, Address address); 390 391 // LE Address Resolving 392 393 // HCI command LE_Add_Device_To_Resolving_List (Vol 4, Part E § 7.8.38). 394 ErrorCode LeAddDeviceToResolvingList( 395 PeerAddressType peer_identity_address_type, Address peer_identity_address, 396 std::array<uint8_t, kIrkSize> peer_irk, 397 std::array<uint8_t, kIrkSize> local_irk); 398 399 // HCI command LE_Remove_Device_From_Resolving_List (Vol 4, Part E § 7.8.39). 400 ErrorCode LeRemoveDeviceFromResolvingList( 401 PeerAddressType peer_identity_address_type, 402 Address peer_identity_address); 403 404 // HCI command LE_Clear_Resolving_List (Vol 4, Part E § 7.8.40). 405 ErrorCode LeClearResolvingList(); 406 407 // HCI command LE_Read_Peer_Resolvable_Address (Vol 4, Part E § 7.8.42). 408 ErrorCode LeReadPeerResolvableAddress( 409 PeerAddressType peer_identity_address_type, Address peer_identity_address, 410 Address* peer_resolvable_address); 411 412 // HCI command LE_Read_Local_Resolvable_Address (Vol 4, Part E § 7.8.43). 413 ErrorCode LeReadLocalResolvableAddress( 414 PeerAddressType peer_identity_address_type, Address peer_identity_address, 415 Address* local_resolvable_address); 416 417 // HCI command LE_Set_Address_Resolution_Enable (Vol 4, Part E § 7.8.44). 418 ErrorCode LeSetAddressResolutionEnable(bool enable); 419 420 // HCI command LE_Set_Privacy_Mode (Vol 4, Part E § 7.8.77). 421 ErrorCode LeSetPrivacyMode(PeerAddressType peer_identity_address_type, 422 Address peer_identity_address, 423 bluetooth::hci::PrivacyMode privacy_mode); 424 425 // Legacy Advertising 426 427 // HCI command LE_Set_Advertising_Parameters (Vol 4, Part E § 7.8.5). 428 ErrorCode LeSetAdvertisingParameters( 429 uint16_t advertising_interval_min, uint16_t advertising_interval_max, 430 bluetooth::hci::AdvertisingType advertising_type, 431 bluetooth::hci::OwnAddressType own_address_type, 432 bluetooth::hci::PeerAddressType peer_address_type, Address peer_address, 433 uint8_t advertising_channel_map, 434 bluetooth::hci::AdvertisingFilterPolicy advertising_filter_policy); 435 436 // HCI command LE_Set_Advertising_Data (Vol 4, Part E § 7.8.7). 437 ErrorCode LeSetAdvertisingData(const std::vector<uint8_t>& advertising_data); 438 439 // HCI command LE_Set_Scan_Response_Data (Vol 4, Part E § 7.8.8). 440 ErrorCode LeSetScanResponseData( 441 const std::vector<uint8_t>& scan_response_data); 442 443 // HCI command LE_Advertising_Enable (Vol 4, Part E § 7.8.9). 444 ErrorCode LeSetAdvertisingEnable(bool advertising_enable); 445 446 // Extended Advertising 447 448 // HCI command LE_Set_Advertising_Set_Random_Address (Vol 4, Part E § 7.8.52). 449 ErrorCode LeSetAdvertisingSetRandomAddress(uint8_t advertising_handle, 450 Address random_address); 451 452 // HCI command LE_Set_Advertising_Parameters (Vol 4, Part E § 7.8.53). 453 ErrorCode LeSetExtendedAdvertisingParameters( 454 uint8_t advertising_handle, 455 AdvertisingEventProperties advertising_event_properties, 456 uint16_t primary_advertising_interval_min, 457 uint16_t primary_advertising_interval_max, 458 uint8_t primary_advertising_channel_map, 459 bluetooth::hci::OwnAddressType own_address_type, 460 bluetooth::hci::PeerAddressType peer_address_type, Address peer_address, 461 bluetooth::hci::AdvertisingFilterPolicy advertising_filter_policy, 462 uint8_t advertising_tx_power, 463 bluetooth::hci::PrimaryPhyType primary_advertising_phy, 464 uint8_t secondary_max_skip, 465 bluetooth::hci::SecondaryPhyType secondary_advertising_phy, 466 uint8_t advertising_sid, bool scan_request_notification_enable); 467 468 // HCI command LE_Set_Extended_Advertising_Data (Vol 4, Part E § 7.8.54). 469 ErrorCode LeSetExtendedAdvertisingData( 470 uint8_t advertising_handle, bluetooth::hci::Operation operation, 471 bluetooth::hci::FragmentPreference fragment_preference, 472 const std::vector<uint8_t>& advertising_data); 473 474 // HCI command LE_Set_Extended_Scan_Response_Data (Vol 4, Part E § 7.8.55). 475 ErrorCode LeSetExtendedScanResponseData( 476 uint8_t advertising_handle, bluetooth::hci::Operation operation, 477 bluetooth::hci::FragmentPreference fragment_preference, 478 const std::vector<uint8_t>& scan_response_data); 479 480 // HCI command LE_Set_Extended_Advertising_Enable (Vol 4, Part E § 7.8.56). 481 ErrorCode LeSetExtendedAdvertisingEnable( 482 bool enable, const std::vector<bluetooth::hci::EnabledSet>& sets); 483 484 // HCI command LE_Remove_Advertising_Set (Vol 4, Part E § 7.8.59). 485 ErrorCode LeRemoveAdvertisingSet(uint8_t advertising_handle); 486 487 // HCI command LE_Clear_Advertising_Sets (Vol 4, Part E § 7.8.60). 488 ErrorCode LeClearAdvertisingSets(); 489 490 // Legacy Scanning 491 492 // HCI command LE_Set_Scan_Parameters (Vol 4, Part E § 7.8.10). 493 ErrorCode LeSetScanParameters( 494 bluetooth::hci::LeScanType scan_type, uint16_t scan_interval, 495 uint16_t scan_window, bluetooth::hci::OwnAddressType own_address_type, 496 bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy); 497 498 // HCI command LE_Set_Scan_Enable (Vol 4, Part E § 7.8.11). 499 ErrorCode LeSetScanEnable(bool enable, bool filter_duplicates); 500 501 // Extended Scanning 502 503 // HCI command LE_Set_Extended_Scan_Parameters (Vol 4, Part E § 7.8.64). 504 ErrorCode LeSetExtendedScanParameters( 505 bluetooth::hci::OwnAddressType own_address_type, 506 bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy, 507 uint8_t scanning_phys, 508 std::vector<bluetooth::hci::ScanningPhyParameters> 509 scanning_phy_parameters); 510 511 // HCI command LE_Set_Extended_Scan_Enable (Vol 4, Part E § 7.8.65). 512 ErrorCode LeSetExtendedScanEnable( 513 bool enable, bluetooth::hci::FilterDuplicates filter_duplicates, 514 uint16_t duration, uint16_t period); 515 516 // Legacy Connection 517 518 // HCI LE Create Connection command (Vol 4, Part E § 7.8.12). 519 ErrorCode LeCreateConnection( 520 uint16_t scan_interval, uint16_t scan_window, 521 bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, 522 AddressWithType peer_address, 523 bluetooth::hci::OwnAddressType own_address_type, 524 uint16_t connection_interval_min, uint16_t connection_interval_max, 525 uint16_t max_latency, uint16_t supervision_timeout, 526 uint16_t min_ce_length, uint16_t max_ce_length); 527 528 // HCI LE Create Connection Cancel command (Vol 4, Part E § 7.8.12). 529 ErrorCode LeCreateConnectionCancel(); 530 531 // Extended Connection 532 533 // HCI LE Extended Create Connection command (Vol 4, Part E § 7.8.66). 534 ErrorCode LeExtendedCreateConnection( 535 bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, 536 bluetooth::hci::OwnAddressType own_address_type, 537 AddressWithType peer_address, uint8_t initiating_phys, 538 std::vector<bluetooth::hci::InitiatingPhyParameters> 539 initiating_phy_parameters); 540 541 // Periodic Advertising 542 543 // HCI LE Set Periodic Advertising Parameters command (Vol 4, Part E 544 // § 7.8.61). 545 ErrorCode LeSetPeriodicAdvertisingParameters( 546 uint8_t advertising_handle, uint16_t periodic_advertising_interval_min, 547 uint16_t periodic_advertising_interval_max, bool include_tx_power); 548 549 // HCI LE Set Periodic Advertising Data command (Vol 4, Part E § 7.8.62). 550 ErrorCode LeSetPeriodicAdvertisingData( 551 uint8_t advertising_handle, bluetooth::hci::Operation operation, 552 const std::vector<uint8_t>& advertising_data); 553 554 // HCI LE Set Periodic Advertising Enable command (Vol 4, Part E § 7.8.63). 555 ErrorCode LeSetPeriodicAdvertisingEnable(bool enable, bool include_adi, 556 uint8_t advertising_handle); 557 558 // Periodic Sync 559 560 // HCI LE Periodic Advertising Create Sync command (Vol 4, Part E § 7.8.67). 561 ErrorCode LePeriodicAdvertisingCreateSync( 562 bluetooth::hci::PeriodicAdvertisingOptions options, 563 uint8_t advertising_sid, 564 bluetooth::hci::AdvertiserAddressType advertiser_address_type, 565 Address advertiser_address, uint16_t skip, uint16_t sync_timeout, 566 uint8_t sync_cte_type); 567 568 // HCI LE Periodic Advertising Create Sync Cancel command (Vol 4, Part E 569 // § 7.8.68). 570 ErrorCode LePeriodicAdvertisingCreateSyncCancel(); 571 572 // HCI LE Periodic Advertising Terminate Sync command (Vol 4, Part E 573 // § 7.8.69). 574 ErrorCode LePeriodicAdvertisingTerminateSync(uint16_t sync_handle); 575 576 // Periodic Advertiser List 577 578 // HCI LE Add Device To Periodic Advertiser List command (Vol 4, Part E 579 // § 7.8.70). 580 ErrorCode LeAddDeviceToPeriodicAdvertiserList( 581 bluetooth::hci::AdvertiserAddressType advertiser_address_type, 582 Address advertiser_address, uint8_t advertising_sid); 583 584 // HCI LE Remove Device From Periodic Advertiser List command 585 // (Vol 4, Part E § 7.8.71). 586 ErrorCode LeRemoveDeviceFromPeriodicAdvertiserList( 587 bluetooth::hci::AdvertiserAddressType advertiser_address_type, 588 Address advertiser_address, uint8_t advertising_sid); 589 590 // HCI LE Clear Periodic Advertiser List command (Vol 4, Part E § 7.8.72). 591 ErrorCode LeClearPeriodicAdvertiserList(); 592 593 // LE APCF 594 595 ErrorCode LeApcfEnable(bool apcf_enable); 596 597 ErrorCode LeApcfAddFilteringParameters( 598 uint8_t apcf_filter_index, uint16_t apcf_feature_selection, 599 uint16_t apcf_list_logic_type, uint8_t apcf_filter_logic_type, 600 uint8_t rssi_high_thresh, bluetooth::hci::DeliveryMode delivery_mode, 601 uint16_t onfound_timeout, uint8_t onfound_timeout_cnt, 602 uint8_t rssi_low_thresh, uint16_t onlost_timeout, 603 uint16_t num_of_tracking_entries, uint8_t* apcf_available_spaces); 604 605 ErrorCode LeApcfDeleteFilteringParameters(uint8_t apcf_filter_index, 606 uint8_t* apcf_available_spaces); 607 608 ErrorCode LeApcfClearFilteringParameters(uint8_t* apcf_available_spaces); 609 610 ErrorCode LeApcfBroadcasterAddress( 611 bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, 612 bluetooth::hci::Address apcf_broadcaster_address, 613 bluetooth::hci::ApcfApplicationAddressType apcf_application_address_type, 614 uint8_t* apcf_available_spaces); 615 616 ErrorCode LeApcfServiceUuid(bluetooth::hci::ApcfAction apcf_action, 617 uint8_t apcf_filter_index, 618 std::vector<uint8_t> acpf_uuid_data, 619 uint8_t* apcf_available_spaces); 620 621 ErrorCode LeApcfServiceSolicitationUuid( 622 bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, 623 std::vector<uint8_t> acpf_uuid_data, uint8_t* apcf_available_spaces); 624 625 ErrorCode LeApcfLocalName(bluetooth::hci::ApcfAction apcf_action, 626 uint8_t apcf_filter_index, 627 std::vector<uint8_t> apcf_local_name, 628 uint8_t* apcf_available_spaces); 629 630 ErrorCode LeApcfManufacturerData(bluetooth::hci::ApcfAction apcf_action, 631 uint8_t apcf_filter_index, 632 std::vector<uint8_t> apcf_manufacturer_data, 633 uint8_t* apcf_available_spaces); 634 635 ErrorCode LeApcfServiceData(bluetooth::hci::ApcfAction apcf_action, 636 uint8_t apcf_filter_index, 637 std::vector<uint8_t> apcf_service_data, 638 uint8_t* apcf_available_spaces); 639 640 ErrorCode LeApcfAdTypeFilter(bluetooth::hci::ApcfAction apcf_action, 641 uint8_t apcf_filter_index, uint8_t ad_type, 642 std::vector<uint8_t> apcf_ad_data, 643 std::vector<uint8_t> apcf_ad_data_mask, 644 uint8_t* apcf_available_spaces); 645 646 protected: 647 void SendLinkLayerPacket( 648 std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet, 649 int8_t tx_power = 0); 650 void SendLeLinkLayerPacket( 651 std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet, 652 int8_t tx_power = 0); 653 654 void IncomingAclPacket(model::packets::LinkLayerPacketView incoming, 655 int8_t rssi); 656 void IncomingScoPacket(model::packets::LinkLayerPacketView incoming); 657 void IncomingDisconnectPacket(model::packets::LinkLayerPacketView incoming); 658 void IncomingEncryptConnection(model::packets::LinkLayerPacketView incoming); 659 void IncomingEncryptConnectionResponse( 660 model::packets::LinkLayerPacketView incoming); 661 void IncomingInquiryPacket(model::packets::LinkLayerPacketView incoming, 662 uint8_t rssi); 663 void IncomingInquiryResponsePacket( 664 model::packets::LinkLayerPacketView incoming); 665 void IncomingLmpPacket(model::packets::LinkLayerPacketView incoming); 666 void IncomingLlcpPacket(model::packets::LinkLayerPacketView incoming); 667 void IncomingLeConnectedIsochronousPdu( 668 model::packets::LinkLayerPacketView incoming); 669 670 void ScanIncomingLeLegacyAdvertisingPdu( 671 model::packets::LeLegacyAdvertisingPduView& pdu, uint8_t rssi); 672 void ScanIncomingLeExtendedAdvertisingPdu( 673 model::packets::LeExtendedAdvertisingPduView& pdu, uint8_t rssi); 674 void ConnectIncomingLeLegacyAdvertisingPdu( 675 model::packets::LeLegacyAdvertisingPduView& pdu); 676 void ConnectIncomingLeExtendedAdvertisingPdu( 677 model::packets::LeExtendedAdvertisingPduView& pdu); 678 679 void IncomingLeLegacyAdvertisingPdu( 680 model::packets::LinkLayerPacketView incoming, uint8_t rssi); 681 void IncomingLeExtendedAdvertisingPdu( 682 model::packets::LinkLayerPacketView incoming, uint8_t rssi); 683 void IncomingLePeriodicAdvertisingPdu( 684 model::packets::LinkLayerPacketView incoming, uint8_t rssi); 685 686 void IncomingLeConnectPacket(model::packets::LinkLayerPacketView incoming); 687 void IncomingLeConnectCompletePacket( 688 model::packets::LinkLayerPacketView incoming); 689 void IncomingLeConnectionParameterRequest( 690 model::packets::LinkLayerPacketView incoming); 691 void IncomingLeConnectionParameterUpdate( 692 model::packets::LinkLayerPacketView incoming); 693 void IncomingLeEncryptConnection( 694 model::packets::LinkLayerPacketView incoming); 695 void IncomingLeEncryptConnectionResponse( 696 model::packets::LinkLayerPacketView incoming); 697 void IncomingLeReadRemoteFeatures( 698 model::packets::LinkLayerPacketView incoming); 699 void IncomingLeReadRemoteFeaturesResponse( 700 model::packets::LinkLayerPacketView incoming); 701 702 void ProcessIncomingLegacyScanRequest( 703 AddressWithType scanning_address, 704 AddressWithType resolved_scanning_address, 705 AddressWithType advertising_address); 706 void ProcessIncomingExtendedScanRequest( 707 ExtendedAdvertiser const& advertiser, AddressWithType scanning_address, 708 AddressWithType resolved_scanning_address, 709 AddressWithType advertising_address); 710 711 bool ProcessIncomingLegacyConnectRequest( 712 model::packets::LeConnectView const& connect_ind); 713 bool ProcessIncomingExtendedConnectRequest( 714 ExtendedAdvertiser& advertiser, 715 model::packets::LeConnectView const& connect_ind); 716 717 void IncomingLeScanPacket(model::packets::LinkLayerPacketView incoming); 718 719 void IncomingLeScanResponsePacket( 720 model::packets::LinkLayerPacketView incoming, uint8_t rssi); 721 void IncomingPagePacket(model::packets::LinkLayerPacketView incoming); 722 void IncomingPageRejectPacket(model::packets::LinkLayerPacketView incoming); 723 void IncomingPageResponsePacket(model::packets::LinkLayerPacketView incoming); 724 void IncomingReadRemoteLmpFeatures( 725 model::packets::LinkLayerPacketView incoming); 726 void IncomingReadRemoteLmpFeaturesResponse( 727 model::packets::LinkLayerPacketView incoming); 728 void IncomingReadRemoteSupportedFeatures( 729 model::packets::LinkLayerPacketView incoming); 730 void IncomingReadRemoteSupportedFeaturesResponse( 731 model::packets::LinkLayerPacketView incoming); 732 void IncomingReadRemoteExtendedFeatures( 733 model::packets::LinkLayerPacketView incoming); 734 void IncomingReadRemoteExtendedFeaturesResponse( 735 model::packets::LinkLayerPacketView incoming); 736 void IncomingReadRemoteVersion(model::packets::LinkLayerPacketView incoming); 737 void IncomingReadRemoteVersionResponse( 738 model::packets::LinkLayerPacketView incoming); 739 void IncomingReadClockOffset(model::packets::LinkLayerPacketView incoming); 740 void IncomingReadClockOffsetResponse( 741 model::packets::LinkLayerPacketView incoming); 742 void IncomingRemoteNameRequest(model::packets::LinkLayerPacketView incoming); 743 void IncomingRemoteNameRequestResponse( 744 model::packets::LinkLayerPacketView incoming); 745 746 void IncomingScoConnectionRequest( 747 model::packets::LinkLayerPacketView incoming); 748 void IncomingScoConnectionResponse( 749 model::packets::LinkLayerPacketView incoming); 750 void IncomingScoDisconnect(model::packets::LinkLayerPacketView incoming); 751 752 void IncomingPingRequest(model::packets::LinkLayerPacketView incoming); 753 void IncomingRoleSwitchRequest(model::packets::LinkLayerPacketView incoming); 754 void IncomingRoleSwitchResponse(model::packets::LinkLayerPacketView incoming); 755 756 void IncomingLlPhyReq(model::packets::LinkLayerPacketView incoming); 757 void IncomingLlPhyRsp(model::packets::LinkLayerPacketView incoming); 758 void IncomingLlPhyUpdateInd(model::packets::LinkLayerPacketView incoming); 759 760 public: 761 bool IsEventUnmasked(bluetooth::hci::EventCode event) const; 762 bool IsLeEventUnmasked(bluetooth::hci::SubeventCode subevent) const; 763 764 // TODO 765 // The Clock Offset should be specific to an ACL connection. 766 // Returning a proper value is not that important. 767 // NOLINTNEXTLINE(readability-convert-member-functions-to-static) GetClockOffset()768 uint32_t GetClockOffset() const { return 0; } 769 770 // TODO 771 // The Page Scan Repetition Mode should be specific to an ACL connection or 772 // a paging session. GetPageScanRepetitionMode()773 PageScanRepetitionMode GetPageScanRepetitionMode() const { 774 return page_scan_repetition_mode_; 775 } 776 777 // TODO 778 // The Encryption Key Size should be specific to an ACL connection. GetEncryptionKeySize()779 uint8_t GetEncryptionKeySize() const { return min_encryption_key_size_; } 780 GetScoFlowControlEnable()781 bool GetScoFlowControlEnable() const { return sco_flow_control_enable_; } 782 GetAuthenticationEnable()783 AuthenticationEnable GetAuthenticationEnable() { 784 return authentication_enable_; 785 } 786 GetLocalName()787 std::array<uint8_t, kLocalNameSize> const& GetLocalName() { 788 return local_name_; 789 } 790 GetLeSupportedFeatures()791 uint64_t GetLeSupportedFeatures() const { 792 return properties_.le_features | le_host_supported_features_; 793 } 794 GetConnectionAcceptTimeout()795 uint16_t GetConnectionAcceptTimeout() const { 796 return connection_accept_timeout_; 797 } 798 GetVoiceSetting()799 uint16_t GetVoiceSetting() const { return voice_setting_; } GetClassOfDevice()800 uint32_t GetClassOfDevice() const { return class_of_device_; } 801 GetMaxLmpFeaturesPageNumber()802 uint8_t GetMaxLmpFeaturesPageNumber() { 803 return properties_.lmp_features.size() - 1; 804 } 805 806 uint64_t GetLmpFeatures(uint8_t page_number = 0) { 807 return page_number == 1 ? host_supported_features_ 808 : properties_.lmp_features[page_number]; 809 } 810 811 void SetLocalName(std::vector<uint8_t> const& local_name); 812 void SetLocalName(std::array<uint8_t, kLocalNameSize> const& local_name); 813 814 void SetExtendedInquiryResponse( 815 std::array<uint8_t, 240> const& extended_inquiry_response); 816 void SetExtendedInquiryResponse( 817 std::vector<uint8_t> const& extended_inquiry_response); 818 SetClassOfDevice(uint32_t class_of_device)819 void SetClassOfDevice(uint32_t class_of_device) { 820 class_of_device_ = class_of_device; 821 } 822 SetAuthenticationEnable(AuthenticationEnable enable)823 void SetAuthenticationEnable(AuthenticationEnable enable) { 824 authentication_enable_ = enable; 825 } 826 SetScoFlowControlEnable(bool enable)827 void SetScoFlowControlEnable(bool enable) { 828 sco_flow_control_enable_ = enable; 829 } SetVoiceSetting(uint16_t voice_setting)830 void SetVoiceSetting(uint16_t voice_setting) { 831 voice_setting_ = voice_setting; 832 } SetEventMask(uint64_t event_mask)833 void SetEventMask(uint64_t event_mask) { event_mask_ = event_mask; } 834 SetEventMaskPage2(uint64_t event_mask)835 void SetEventMaskPage2(uint64_t event_mask) { 836 event_mask_page_2_ = event_mask; 837 } SetLeEventMask(uint64_t le_event_mask)838 void SetLeEventMask(uint64_t le_event_mask) { 839 le_event_mask_ = le_event_mask; 840 } 841 842 void SetLeHostSupport(bool enable); 843 void SetSecureSimplePairingSupport(bool enable); 844 void SetSecureConnectionsSupport(bool enable); 845 SetConnectionAcceptTimeout(uint16_t timeout)846 void SetConnectionAcceptTimeout(uint16_t timeout) { 847 connection_accept_timeout_ = timeout; 848 } 849 LegacyAdvertising()850 bool LegacyAdvertising() const { return legacy_advertising_in_use_; } ExtendedAdvertising()851 bool ExtendedAdvertising() const { return extended_advertising_in_use_; } 852 SelectLegacyAdvertising()853 bool SelectLegacyAdvertising() { 854 if (extended_advertising_in_use_) { 855 return false; 856 } 857 legacy_advertising_in_use_ = true; 858 return true; 859 } 860 SelectExtendedAdvertising()861 bool SelectExtendedAdvertising() { 862 if (legacy_advertising_in_use_) { 863 return false; 864 } 865 extended_advertising_in_use_ = true; 866 return true; 867 } 868 GetLeSuggestedMaxTxOctets()869 uint16_t GetLeSuggestedMaxTxOctets() const { 870 return le_suggested_max_tx_octets_; 871 } GetLeSuggestedMaxTxTime()872 uint16_t GetLeSuggestedMaxTxTime() const { return le_suggested_max_tx_time_; } 873 SetLeSuggestedMaxTxOctets(uint16_t max_tx_octets)874 void SetLeSuggestedMaxTxOctets(uint16_t max_tx_octets) { 875 le_suggested_max_tx_octets_ = max_tx_octets; 876 } SetLeSuggestedMaxTxTime(uint16_t max_tx_time)877 void SetLeSuggestedMaxTxTime(uint16_t max_tx_time) { 878 le_suggested_max_tx_time_ = max_tx_time; 879 } 880 881 TaskId StartScoStream(Address address); 882 883 private: 884 const Address& address_; 885 const ControllerProperties& properties_; 886 887 // Host Supported Features (Vol 2, Part C § 3.3 Feature Mask Definition). 888 // Page 1 of the LMP feature mask. 889 uint64_t host_supported_features_{0}; 890 bool le_host_support_{false}; 891 bool secure_simple_pairing_host_support_{false}; 892 bool secure_connections_host_support_{false}; 893 894 // Le Host Supported Features (Vol 4, Part E § 7.8.3). 895 // Specifies the bits indicating Host support. 896 uint64_t le_host_supported_features_{0}; 897 bool connected_isochronous_stream_host_support_{false}; 898 bool connection_subrating_host_support_{false}; 899 900 // LE Random Address (Vol 4, Part E § 7.8.4). 901 Address random_address_{Address::kEmpty}; 902 903 // HCI configuration parameters. 904 // 905 // Provide the current HCI Configuration Parameters as defined in section 906 // Vol 4, Part E § 6 of the core specification. 907 908 // Scan Enable (Vol 4, Part E § 6.1). 909 bool page_scan_enable_{false}; 910 bool inquiry_scan_enable_{false}; 911 912 // Inquiry Scan Interval and Window 913 // (Vol 4, Part E § 6.2, 6.3). 914 uint16_t inquiry_scan_interval_{0x1000}; 915 uint16_t inquiry_scan_window_{0x0012}; 916 917 // Page Timeout (Vol 4, Part E § 6.6). 918 uint16_t page_timeout_{0x2000}; 919 920 // Connection Accept Timeout (Vol 4, Part E § 6.7). 921 uint16_t connection_accept_timeout_{0x1FA0}; 922 923 // Page Scan Interval and Window 924 // (Vol 4, Part E § 6.8, 6.9). 925 uint16_t page_scan_interval_{0x0800}; 926 uint16_t page_scan_window_{0x0012}; 927 928 // Voice Setting (Vol 4, Part E § 6.12). 929 uint16_t voice_setting_{0x0060}; 930 931 // Authentication Enable (Vol 4, Part E § 6.16). 932 AuthenticationEnable authentication_enable_{ 933 AuthenticationEnable::NOT_REQUIRED}; 934 935 // Default Link Policy Settings (Vol 4, Part E § 6.18). 936 uint8_t default_link_policy_settings_{0x0000}; 937 938 // Synchronous Flow Control Enable (Vol 4, Part E § 6.22). 939 bool sco_flow_control_enable_{false}; 940 941 // Local Name (Vol 4, Part E § 6.23). 942 std::array<uint8_t, kLocalNameSize> local_name_{}; 943 944 // Extended Inquiry Response (Vol 4, Part E § 6.24). 945 std::array<uint8_t, kExtendedInquiryResponseSize> 946 extended_inquiry_response_{}; 947 948 // Class of Device (Vol 4, Part E § 6.26). 949 uint32_t class_of_device_{0}; 950 951 // Other configuration parameters. 952 953 // Current IAC LAP (Vol 4, Part E § 7.3.44). 954 std::vector<bluetooth::hci::Lap> current_iac_lap_list_{}; 955 956 // Min Encryption Key Size (Vol 4, Part E § 7.3.102). 957 uint8_t min_encryption_key_size_{16}; 958 959 // Event Mask (Vol 4, Part E § 7.3.1) and 960 // Event Mask Page 2 (Vol 4, Part E § 7.3.69) and 961 // LE Event Mask (Vol 4, Part E § 7.8.1). 962 uint64_t event_mask_{0x00001fffffffffff}; 963 uint64_t event_mask_page_2_{0x0}; 964 uint64_t le_event_mask_{0x01f}; 965 966 // Suggested Default Data Length (Vol 4, Part E § 7.8.34). 967 uint16_t le_suggested_max_tx_octets_{0x001b}; 968 uint16_t le_suggested_max_tx_time_{0x0148}; 969 970 // Resolvable Private Address Timeout (Vol 4, Part E § 7.8.45). 971 std::chrono::seconds resolvable_private_address_timeout_{0x0384}; 972 973 // Page Scan Repetition Mode (Vol 2 Part B § 8.3.1 Page Scan substate). 974 // The Page Scan Repetition Mode depends on the selected Page Scan Interval. 975 PageScanRepetitionMode page_scan_repetition_mode_{PageScanRepetitionMode::R0}; 976 977 AclConnectionHandler connections_; 978 979 // Callbacks to send packets back to the HCI. 980 std::function<void(std::shared_ptr<bluetooth::hci::AclBuilder>)> send_acl_; 981 std::function<void(std::shared_ptr<bluetooth::hci::EventBuilder>)> 982 send_event_; 983 std::function<void(std::shared_ptr<bluetooth::hci::ScoBuilder>)> send_sco_; 984 std::function<void(std::shared_ptr<bluetooth::hci::IsoBuilder>)> send_iso_; 985 986 // Callback to send packets to remote devices. 987 std::function<void(std::shared_ptr<model::packets::LinkLayerPacketBuilder>, 988 Phy::Type phy_type, int8_t tx_power)> 989 send_to_remote_; 990 991 uint32_t oob_id_{1}; 992 uint32_t key_id_{1}; 993 994 struct FilterAcceptListEntry { 995 FilterAcceptListAddressType address_type; 996 Address address; 997 }; 998 999 std::vector<FilterAcceptListEntry> le_filter_accept_list_; 1000 1001 struct ResolvingListEntry { 1002 PeerAddressType peer_identity_address_type; 1003 Address peer_identity_address; 1004 std::array<uint8_t, kIrkSize> peer_irk; 1005 std::array<uint8_t, kIrkSize> local_irk; 1006 bluetooth::hci::PrivacyMode privacy_mode; 1007 1008 // Resolvable Private Address being used by the local device. 1009 // It is the last resolvable private address generated for 1010 // this identity address. 1011 std::optional<Address> local_resolvable_address; 1012 // Resolvable Private Address being used by the peer device. 1013 // It is the last resolvable private address received that resolved 1014 // to this identity address. 1015 std::optional<Address> peer_resolvable_address; 1016 }; 1017 1018 std::vector<ResolvingListEntry> le_resolving_list_; 1019 bool le_resolving_list_enabled_{false}; 1020 1021 // Flag set when any legacy advertising command has been received 1022 // since the last power-on-reset. 1023 // From Vol 4, Part E § 3.1.1 Legacy and extended advertising, 1024 // extended advertising are rejected when this bit is set. 1025 bool legacy_advertising_in_use_{false}; 1026 1027 // Flag set when any extended advertising command has been received 1028 // since the last power-on-reset. 1029 // From Vol 4, Part E § 3.1.1 Legacy and extended advertising, 1030 // legacy advertising are rejected when this bit is set. 1031 bool extended_advertising_in_use_{false}; 1032 1033 // Legacy advertising state. 1034 LegacyAdvertiser legacy_advertiser_{}; 1035 1036 // Extended advertising sets. 1037 std::unordered_map<uint8_t, ExtendedAdvertiser> extended_advertisers_{}; 1038 1039 // Local phy preferences, defaults to LE 1M Phy. 1040 uint8_t default_tx_phys_{0x1}; 1041 uint8_t default_rx_phys_{0x1}; 1042 uint8_t requested_tx_phys_{0x1}; 1043 uint8_t requested_rx_phys_{0x1}; 1044 1045 struct PeriodicAdvertiserListEntry { 1046 bluetooth::hci::AdvertiserAddressType advertiser_address_type; 1047 Address advertiser_address; 1048 uint8_t advertising_sid; 1049 }; 1050 1051 std::vector<PeriodicAdvertiserListEntry> le_periodic_advertiser_list_; 1052 1053 struct Scanner { 1054 bool scan_enable; 1055 std::chrono::steady_clock::duration period; 1056 std::chrono::steady_clock::duration duration; 1057 bluetooth::hci::FilterDuplicates filter_duplicates; 1058 bluetooth::hci::OwnAddressType own_address_type; 1059 bluetooth::hci::LeScanningFilterPolicy scan_filter_policy; 1060 1061 struct PhyParameters { 1062 bool enabled; 1063 bluetooth::hci::LeScanType scan_type; 1064 uint16_t scan_interval; 1065 uint16_t scan_window; 1066 }; 1067 1068 PhyParameters le_1m_phy; 1069 PhyParameters le_coded_phy; 1070 1071 // Save information about the advertising PDU being scanned. 1072 bool connectable_scan_response; 1073 bool extended_scan_response; 1074 model::packets::PhyType primary_scan_response_phy; 1075 model::packets::PhyType secondary_scan_response_phy; 1076 std::optional<AddressWithType> pending_scan_request{}; 1077 std::optional<std::chrono::steady_clock::time_point> 1078 pending_scan_request_timeout{}; 1079 1080 // Time keeping 1081 std::optional<std::chrono::steady_clock::time_point> timeout; 1082 std::optional<std::chrono::steady_clock::time_point> periodical_timeout; 1083 1084 // Packet History 1085 std::vector<pdl::packet::slice> history; 1086 IsEnabledScanner1087 bool IsEnabled() const { return scan_enable; } 1088 IsPacketInHistoryScanner1089 bool IsPacketInHistory(pdl::packet::slice const& packet) const { 1090 return std::any_of( 1091 history.begin(), history.end(), 1092 [packet](pdl::packet::slice const& a) { return a == packet; }); 1093 } 1094 AddPacketToHistoryScanner1095 void AddPacketToHistory(pdl::packet::slice packet) { 1096 history.push_back(packet); 1097 } 1098 }; 1099 1100 // Legacy and extended scanning properties. 1101 // Legacy and extended scanning are disambiguated by the use 1102 // of legacy_advertising_in_use_ and extended_advertising_in_use_ flags. 1103 // Only one type of advertising may be used during a controller session. 1104 Scanner scanner_{}; 1105 1106 // APCF scanning state for Android vendor support. 1107 ApcfScanner apcf_scanner_{}; 1108 1109 struct Initiator { 1110 bool connect_enable; 1111 bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy; 1112 bluetooth::hci::AddressWithType peer_address{}; 1113 bluetooth::hci::OwnAddressType own_address_type; 1114 1115 struct PhyParameters { 1116 bool enabled; 1117 uint16_t scan_interval; 1118 uint16_t scan_window; 1119 uint16_t connection_interval_min; 1120 uint16_t connection_interval_max; 1121 uint16_t max_latency; 1122 uint16_t supervision_timeout; 1123 uint16_t min_ce_length; 1124 uint16_t max_ce_length; 1125 }; 1126 1127 PhyParameters le_1m_phy; 1128 PhyParameters le_2m_phy; 1129 PhyParameters le_coded_phy; 1130 1131 // Save information about the ongoing connection. 1132 Address initiating_address{}; // TODO: AddressWithType 1133 std::optional<AddressWithType> pending_connect_request{}; 1134 IsEnabledInitiator1135 bool IsEnabled() const { return connect_enable; } DisableInitiator1136 void Disable() { connect_enable = false; } 1137 }; 1138 1139 // Legacy and extended initiating properties. 1140 // Legacy and extended initiating are disambiguated by the use 1141 // of legacy_advertising_in_use_ and extended_advertising_in_use_ flags. 1142 // Only one type of advertising may be used during a controller session. 1143 Initiator initiator_{}; 1144 1145 struct Synchronizing { 1146 bluetooth::hci::PeriodicAdvertisingOptions options{}; 1147 bluetooth::hci::AdvertiserAddressType advertiser_address_type{}; 1148 Address advertiser_address{}; 1149 uint8_t advertising_sid{}; 1150 std::chrono::steady_clock::duration sync_timeout{}; 1151 }; 1152 1153 struct Synchronized { 1154 bluetooth::hci::AdvertiserAddressType advertiser_address_type; 1155 Address advertiser_address; 1156 uint8_t advertising_sid; 1157 uint16_t sync_handle; 1158 std::chrono::steady_clock::duration sync_timeout; 1159 std::chrono::steady_clock::time_point timeout; 1160 }; 1161 1162 // Periodic advertising synchronizing and synchronized states. 1163 // Contains information for the currently established syncs, and the 1164 // pending sync. 1165 std::optional<Synchronizing> synchronizing_{}; 1166 std::unordered_map<uint16_t, Synchronized> synchronized_{}; 1167 1168 // Buffer to contain the ISO SDU sent from the host stack over HCI. 1169 // The SDU is forwarded to the peer only when complete. 1170 std::vector<uint8_t> iso_sdu_{}; 1171 1172 // Rust state. 1173 std::unique_ptr<const LinkManager, void (*)(const LinkManager*)> lm_; 1174 std::unique_ptr<const LinkLayer, void (*)(const LinkLayer*)> ll_; 1175 struct ControllerOps controller_ops_; 1176 1177 // Classic state. 1178 struct Page { 1179 Address bd_addr; 1180 uint8_t allow_role_switch; 1181 std::chrono::steady_clock::time_point next_page_event{}; 1182 std::chrono::steady_clock::time_point page_timeout{}; 1183 }; 1184 1185 // Page substate. 1186 // RootCanal will allow only one page request running at the same time. 1187 std::optional<Page> page_; 1188 1189 std::chrono::steady_clock::time_point last_inquiry_; 1190 model::packets::InquiryType inquiry_mode_{ 1191 model::packets::InquiryType::STANDARD}; 1192 TaskId inquiry_timer_task_id_ = kInvalidTaskId; 1193 uint64_t inquiry_lap_{}; 1194 uint8_t inquiry_max_responses_{}; 1195 1196 public: 1197 // Type of scheduled tasks. 1198 class Task { 1199 public: Task(std::chrono::steady_clock::time_point time,std::chrono::milliseconds period,TaskCallback callback,TaskId task_id)1200 Task(std::chrono::steady_clock::time_point time, 1201 std::chrono::milliseconds period, TaskCallback callback, 1202 TaskId task_id) 1203 : time(time), 1204 periodic(true), 1205 period(period), 1206 callback(std::move(callback)), 1207 task_id(task_id) {} 1208 Task(std::chrono::steady_clock::time_point time,TaskCallback callback,TaskId task_id)1209 Task(std::chrono::steady_clock::time_point time, TaskCallback callback, 1210 TaskId task_id) 1211 : time(time), 1212 periodic(false), 1213 callback(std::move(callback)), 1214 task_id(task_id) {} 1215 1216 // Operators needed to be in a collection 1217 bool operator<(const Task& another) const { 1218 return std::make_pair(time, task_id) < 1219 std::make_pair(another.time, another.task_id); 1220 } 1221 1222 // These fields should no longer be public if the class ever becomes 1223 // public or gets more complex 1224 std::chrono::steady_clock::time_point time; 1225 const bool periodic; 1226 std::chrono::milliseconds period{}; 1227 TaskCallback callback; 1228 TaskId task_id; 1229 }; 1230 1231 private: 1232 // List currently pending tasks. 1233 std::set<Task> task_queue_{}; 1234 TaskId task_counter_{0}; 1235 1236 // Return the next valid unused task identifier. 1237 TaskId NextTaskId(); 1238 }; 1239 1240 } // namespace rootcanal 1241