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