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 "hci/address.h"
20 #include "hci/hci_packets.h"
21 #include "include/hci.h"
22 #include "include/inquiry.h"
23 #include "include/phy.h"
24 #include "model/controller/acl_connection_handler.h"
25 #include "model/controller/le_advertiser.h"
26 #include "model/devices/device_properties.h"
27 #include "model/setup/async_manager.h"
28 #include "packets/link_layer_packets.h"
29 #include "security_manager.h"
30 
31 namespace test_vendor_lib {
32 
33 using ::bluetooth::hci::Address;
34 using ::bluetooth::hci::ErrorCode;
35 using ::bluetooth::hci::OpCode;
36 
37 class LinkLayerController {
38  public:
39   static constexpr size_t kIrk_size = 16;
40 
LinkLayerController(const DeviceProperties & properties)41   LinkLayerController(const DeviceProperties& properties) : properties_(properties) {}
42   ErrorCode SendCommandToRemoteByAddress(
43       OpCode opcode, bluetooth::packet::PacketView<true> args,
44       const Address& remote);
45   ErrorCode SendCommandToRemoteByHandle(
46       OpCode opcode, bluetooth::packet::PacketView<true> args, uint16_t handle);
47   ErrorCode SendScoToRemote(bluetooth::hci::ScoPacketView sco_packet);
48   ErrorCode SendAclToRemote(bluetooth::hci::AclPacketView acl_packet);
49 
50   void WriteSimplePairingMode(bool enabled);
51   void StartSimplePairing(const Address& address);
52   void AuthenticateRemoteStage1(const Address& address, PairingType pairing_type);
53   void AuthenticateRemoteStage2(const Address& address);
54   ErrorCode LinkKeyRequestReply(const Address& address,
55                                 const std::array<uint8_t, 16>& key);
56   ErrorCode LinkKeyRequestNegativeReply(const Address& address);
57   ErrorCode IoCapabilityRequestReply(const Address& peer, uint8_t io_capability,
58                                      uint8_t oob_data_present_flag,
59                                      uint8_t authentication_requirements);
60   ErrorCode IoCapabilityRequestNegativeReply(const Address& peer,
61                                              ErrorCode reason);
62   ErrorCode UserConfirmationRequestReply(const Address& peer);
63   ErrorCode UserConfirmationRequestNegativeReply(const Address& peer);
64   ErrorCode UserPasskeyRequestReply(const Address& peer,
65                                     uint32_t numeric_value);
66   ErrorCode UserPasskeyRequestNegativeReply(const Address& peer);
67   ErrorCode RemoteOobDataRequestReply(const Address& peer,
68                                       const std::vector<uint8_t>& c,
69                                       const std::vector<uint8_t>& r);
70   ErrorCode RemoteOobDataRequestNegativeReply(const Address& peer);
71   void HandleSetConnectionEncryption(const Address& address, uint16_t handle, uint8_t encryption_enable);
72   ErrorCode SetConnectionEncryption(uint16_t handle, uint8_t encryption_enable);
73   void HandleAuthenticationRequest(const Address& address, uint16_t handle);
74   ErrorCode AuthenticationRequested(uint16_t handle);
75 
76   ErrorCode AcceptConnectionRequest(const Address& addr, bool try_role_switch);
77   void MakeSlaveConnection(const Address& addr, bool try_role_switch);
78   ErrorCode RejectConnectionRequest(const Address& addr, uint8_t reason);
79   void RejectSlaveConnection(const Address& addr, uint8_t reason);
80   ErrorCode CreateConnection(const Address& addr, uint16_t packet_type,
81                              uint8_t page_scan_mode, uint16_t clock_offset,
82                              uint8_t allow_role_switch);
83   ErrorCode CreateConnectionCancel(const Address& addr);
84   ErrorCode Disconnect(uint16_t handle, uint8_t reason);
85 
86  private:
87   void DisconnectCleanup(uint16_t handle, uint8_t reason);
88 
89  public:
90   void IncomingPacket(model::packets::LinkLayerPacketView incoming);
91 
92   void TimerTick();
93 
94   AsyncTaskId ScheduleTask(std::chrono::milliseconds delay_ms, const TaskCallback& task);
95 
96   void CancelScheduledTask(AsyncTaskId task);
97 
98   // Set the callbacks for sending packets to the HCI.
99   void RegisterEventChannel(
100       const std::function<void(
101           std::shared_ptr<bluetooth::hci::EventPacketBuilder>)>& send_event);
102 
103   void RegisterAclChannel(
104       const std::function<
105           void(std::shared_ptr<bluetooth::hci::AclPacketBuilder>)>& send_acl);
106 
107   void RegisterScoChannel(const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& send_sco);
108 
109   void RegisterIsoChannel(
110       const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>&
111           send_iso);
112 
113   void RegisterRemoteChannel(
114       const std::function<void(
115           std::shared_ptr<model::packets::LinkLayerPacketBuilder>, Phy::Type)>&
116           send_to_remote);
117 
118   // Set the callbacks for scheduling tasks.
119   void RegisterTaskScheduler(
120       std::function<AsyncTaskId(std::chrono::milliseconds, const TaskCallback&)> event_scheduler);
121 
122   void RegisterPeriodicTaskScheduler(
123       std::function<AsyncTaskId(std::chrono::milliseconds, std::chrono::milliseconds, const TaskCallback&)>
124           periodic_event_scheduler);
125 
126   void RegisterTaskCancel(std::function<void(AsyncTaskId)> cancel);
127   void Reset();
128 
129   void LeAdvertising();
130 
131   ErrorCode SetLeExtendedAddress(uint8_t handle, Address address);
132 
133   ErrorCode SetLeExtendedAdvertisingData(uint8_t handle,
134                                          const std::vector<uint8_t>& data);
135 
136   ErrorCode SetLeExtendedAdvertisingParameters(
137       uint8_t set, uint16_t interval_min, uint16_t interval_max,
138       bluetooth::hci::LegacyAdvertisingProperties type,
139       bluetooth::hci::OwnAddressType own_address_type,
140       bluetooth::hci::PeerAddressType peer_address_type, Address peer,
141       bluetooth::hci::AdvertisingFilterPolicy filter_policy);
142   ErrorCode LeRemoveAdvertisingSet(uint8_t set);
143   ErrorCode LeClearAdvertisingSets();
144   void LeConnectionUpdateComplete(
145       bluetooth::hci::LeConnectionUpdateView connection_update_view);
146   ErrorCode LeConnectionUpdate(
147       bluetooth::hci::LeConnectionUpdateView connection_update_view);
148 
149   void HandleLeConnection(AddressWithType addr, AddressWithType own_addr,
150                           uint8_t role, uint16_t connection_interval,
151                           uint16_t connection_latency,
152                           uint16_t supervision_timeout);
153 
154   void LeConnectListClear();
155   void LeConnectListAddDevice(Address addr, uint8_t addr_type);
156   void LeConnectListRemoveDevice(Address addr, uint8_t addr_type);
157   bool LeConnectListContainsDevice(Address addr, uint8_t addr_type);
158   bool LeConnectListFull();
159   void LeResolvingListClear();
160   void LeResolvingListAddDevice(Address addr, uint8_t addr_type,
161                                 std::array<uint8_t, kIrk_size> peerIrk,
162                                 std::array<uint8_t, kIrk_size> localIrk);
163   void LeResolvingListRemoveDevice(Address addr, uint8_t addr_type);
164   bool LeResolvingListContainsDevice(Address addr, uint8_t addr_type);
165   bool LeResolvingListFull();
166   void LeSetPrivacyMode(uint8_t address_type, Address addr, uint8_t mode);
167 
168   void HandleLeEnableEncryption(uint16_t handle, std::array<uint8_t, 8> rand,
169                                 uint16_t ediv, std::array<uint8_t, 16> ltk);
170 
171   ErrorCode LeEnableEncryption(uint16_t handle, std::array<uint8_t, 8> rand,
172                                uint16_t ediv, std::array<uint8_t, 16> ltk);
173 
174   ErrorCode SetLeAdvertisingEnable(uint8_t le_advertising_enable);
175 
176   void LeDisableAdvertisingSets();
177 
178   uint8_t LeReadNumberOfSupportedAdvertisingSets();
179 
180   ErrorCode SetLeExtendedAdvertisingEnable(
181       bluetooth::hci::Enable enable,
182       const std::vector<bluetooth::hci::EnabledSet>& enabled_sets);
183 
SetLeScanEnable(bluetooth::hci::OpCode enabling_opcode)184   void SetLeScanEnable(bluetooth::hci::OpCode enabling_opcode) {
185     le_scan_enable_ = enabling_opcode;
186   }
SetLeScanType(uint8_t le_scan_type)187   void SetLeScanType(uint8_t le_scan_type) {
188     le_scan_type_ = le_scan_type;
189   }
SetLeScanInterval(uint16_t le_scan_interval)190   void SetLeScanInterval(uint16_t le_scan_interval) {
191     le_scan_interval_ = le_scan_interval;
192   }
SetLeScanWindow(uint16_t le_scan_window)193   void SetLeScanWindow(uint16_t le_scan_window) {
194     le_scan_window_ = le_scan_window;
195   }
SetLeScanFilterPolicy(uint8_t le_scan_filter_policy)196   void SetLeScanFilterPolicy(uint8_t le_scan_filter_policy) {
197     le_scan_filter_policy_ = le_scan_filter_policy;
198   }
SetLeFilterDuplicates(uint8_t le_scan_filter_duplicates)199   void SetLeFilterDuplicates(uint8_t le_scan_filter_duplicates) {
200     le_scan_filter_duplicates_ = le_scan_filter_duplicates;
201   }
SetLeAddressType(uint8_t le_address_type)202   void SetLeAddressType(uint8_t le_address_type) {
203     le_address_type_ = le_address_type;
204   }
SetLeConnect(bool le_connect)205   ErrorCode SetLeConnect(bool le_connect) {
206     le_connect_ = le_connect;
207     return ErrorCode::SUCCESS;
208   }
SetLeConnectionIntervalMin(uint16_t min)209   void SetLeConnectionIntervalMin(uint16_t min) {
210     le_connection_interval_min_ = min;
211   }
SetLeConnectionIntervalMax(uint16_t max)212   void SetLeConnectionIntervalMax(uint16_t max) {
213     le_connection_interval_max_ = max;
214   }
SetLeConnectionLatency(uint16_t latency)215   void SetLeConnectionLatency(uint16_t latency) {
216     le_connection_latency_ = latency;
217   }
SetLeSupervisionTimeout(uint16_t timeout)218   void SetLeSupervisionTimeout(uint16_t timeout) {
219     le_connection_supervision_timeout_ = timeout;
220   }
SetLeMinimumCeLength(uint16_t min)221   void SetLeMinimumCeLength(uint16_t min) {
222     le_connection_minimum_ce_length_ = min;
223   }
SetLeMaximumCeLength(uint16_t max)224   void SetLeMaximumCeLength(uint16_t max) {
225     le_connection_maximum_ce_length_ = max;
226   }
SetLeInitiatorFilterPolicy(uint8_t le_initiator_filter_policy)227   void SetLeInitiatorFilterPolicy(uint8_t le_initiator_filter_policy) {
228     le_initiator_filter_policy_ = le_initiator_filter_policy;
229   }
SetLePeerAddressType(uint8_t peer_address_type)230   void SetLePeerAddressType(uint8_t peer_address_type) {
231     le_peer_address_type_ = peer_address_type;
232   }
SetLePeerAddress(const Address & peer_address)233   void SetLePeerAddress(const Address& peer_address) {
234     le_peer_address_ = peer_address;
235   }
236 
237   // Classic
238   void StartInquiry(std::chrono::milliseconds timeout);
239   void InquiryCancel();
240   void InquiryTimeout();
241   void SetInquiryMode(uint8_t mode);
242   void SetInquiryLAP(uint64_t lap);
243   void SetInquiryMaxResponses(uint8_t max);
244   void Inquiry();
245 
246   void SetInquiryScanEnable(bool enable);
247   void SetPageScanEnable(bool enable);
248 
249   ErrorCode ChangeConnectionPacketType(uint16_t handle, uint16_t types);
250   ErrorCode ChangeConnectionLinkKey(uint16_t handle);
251   ErrorCode MasterLinkKey(uint8_t key_flag);
252   ErrorCode HoldMode(uint16_t handle, uint16_t hold_mode_max_interval,
253                      uint16_t hold_mode_min_interval);
254   ErrorCode SniffMode(uint16_t handle, uint16_t sniff_max_interval,
255                       uint16_t sniff_min_interval, uint16_t sniff_attempt,
256                       uint16_t sniff_timeout);
257   ErrorCode ExitSniffMode(uint16_t handle);
258   ErrorCode QosSetup(uint16_t handle, uint8_t service_type, uint32_t token_rate,
259                      uint32_t peak_bandwidth, uint32_t latency,
260                      uint32_t delay_variation);
261   ErrorCode SwitchRole(Address bd_addr, uint8_t role);
262   ErrorCode WriteLinkPolicySettings(uint16_t handle, uint16_t settings);
263   ErrorCode FlowSpecification(uint16_t handle, uint8_t flow_direction,
264                               uint8_t service_type, uint32_t token_rate,
265                               uint32_t token_bucket_size,
266                               uint32_t peak_bandwidth, uint32_t access_latency);
267   ErrorCode WriteLinkSupervisionTimeout(uint16_t handle, uint16_t timeout);
268   ErrorCode WriteDefaultLinkPolicySettings(uint16_t settings);
269   uint16_t ReadDefaultLinkPolicySettings();
270 
271  protected:
272   void SendLeLinkLayerPacket(
273       std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet);
274   void SendLinkLayerPacket(
275       std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet);
276   void IncomingAclPacket(model::packets::LinkLayerPacketView packet);
277   void IncomingDisconnectPacket(model::packets::LinkLayerPacketView packet);
278   void IncomingEncryptConnection(model::packets::LinkLayerPacketView packet);
279   void IncomingEncryptConnectionResponse(
280       model::packets::LinkLayerPacketView packet);
281   void IncomingInquiryPacket(model::packets::LinkLayerPacketView packet);
282   void IncomingInquiryResponsePacket(
283       model::packets::LinkLayerPacketView packet);
284   void IncomingIoCapabilityRequestPacket(
285       model::packets::LinkLayerPacketView packet);
286   void IncomingIoCapabilityResponsePacket(
287       model::packets::LinkLayerPacketView packet);
288   void IncomingIoCapabilityNegativeResponsePacket(
289       model::packets::LinkLayerPacketView packet);
290   void IncomingLeAdvertisementPacket(
291       model::packets::LinkLayerPacketView packet);
292   void IncomingLeConnectPacket(model::packets::LinkLayerPacketView packet);
293   void IncomingLeConnectCompletePacket(
294       model::packets::LinkLayerPacketView packet);
295   void IncomingLeEncryptConnection(model::packets::LinkLayerPacketView packet);
296   void IncomingLeEncryptConnectionResponse(
297       model::packets::LinkLayerPacketView packet);
298   void IncomingLeScanPacket(model::packets::LinkLayerPacketView packet);
299   void IncomingLeScanResponsePacket(model::packets::LinkLayerPacketView packet);
300   void IncomingPagePacket(model::packets::LinkLayerPacketView packet);
301   void IncomingPageRejectPacket(model::packets::LinkLayerPacketView packet);
302   void IncomingPageResponsePacket(model::packets::LinkLayerPacketView packet);
303   void IncomingReadRemoteLmpFeatures(
304       model::packets::LinkLayerPacketView packet);
305   void IncomingReadRemoteLmpFeaturesResponse(
306       model::packets::LinkLayerPacketView packet);
307   void IncomingReadRemoteSupportedFeatures(
308       model::packets::LinkLayerPacketView packet);
309   void IncomingReadRemoteSupportedFeaturesResponse(
310       model::packets::LinkLayerPacketView packet);
311   void IncomingReadRemoteExtendedFeatures(
312       model::packets::LinkLayerPacketView packet);
313   void IncomingReadRemoteExtendedFeaturesResponse(
314       model::packets::LinkLayerPacketView packet);
315   void IncomingReadRemoteVersion(model::packets::LinkLayerPacketView packet);
316   void IncomingReadRemoteVersionResponse(
317       model::packets::LinkLayerPacketView packet);
318   void IncomingReadClockOffset(model::packets::LinkLayerPacketView packet);
319   void IncomingReadClockOffsetResponse(
320       model::packets::LinkLayerPacketView packet);
321   void IncomingRemoteNameRequest(model::packets::LinkLayerPacketView packet);
322   void IncomingRemoteNameRequestResponse(
323       model::packets::LinkLayerPacketView packet);
324 
325  private:
326   const DeviceProperties& properties_;
327   AclConnectionHandler connections_;
328   // Add timestamps?
329   std::vector<std::shared_ptr<model::packets::LinkLayerPacketBuilder>>
330       commands_awaiting_responses_;
331 
332   // Timing related state
333   std::vector<AsyncTaskId> controller_events_;
334   AsyncTaskId timer_tick_task_{};
335   std::chrono::milliseconds timer_period_ = std::chrono::milliseconds(100);
336 
337   // Callbacks to schedule tasks.
338   std::function<AsyncTaskId(std::chrono::milliseconds, const TaskCallback&)> schedule_task_;
339   std::function<AsyncTaskId(std::chrono::milliseconds, std::chrono::milliseconds, const TaskCallback&)>
340       schedule_periodic_task_;
341   std::function<void(AsyncTaskId)> cancel_task_;
342 
343   // Callbacks to send packets back to the HCI.
344   std::function<void(std::shared_ptr<bluetooth::hci::AclPacketBuilder>)>
345       send_acl_;
346   std::function<void(std::shared_ptr<bluetooth::hci::EventPacketBuilder>)>
347       send_event_;
348   std::function<void(std::shared_ptr<std::vector<uint8_t>>)> send_sco_;
349   std::function<void(std::shared_ptr<std::vector<uint8_t>>)> send_iso_;
350 
351   // Callback to send packets to remote devices.
352   std::function<void(std::shared_ptr<model::packets::LinkLayerPacketBuilder>,
353                      Phy::Type phy_type)>
354       send_to_remote_;
355 
356   // LE state
357   std::vector<uint8_t> le_event_mask_;
358 
359   std::vector<std::tuple<Address, uint8_t>> le_connect_list_;
360   std::vector<std::tuple<Address, uint8_t, std::array<uint8_t, kIrk_size>,
361                          std::array<uint8_t, kIrk_size>>>
362       le_resolving_list_;
363 
364   std::array<LeAdvertiser, 3> advertisers_;
365 
366   bluetooth::hci::OpCode le_scan_enable_{bluetooth::hci::OpCode::NONE};
367   uint8_t le_scan_type_{};
368   uint16_t le_scan_interval_{};
369   uint16_t le_scan_window_{};
370   uint8_t le_scan_filter_policy_{};
371   uint8_t le_scan_filter_duplicates_{};
372   uint8_t le_address_type_{};
373 
374   bool le_connect_{false};
375   uint16_t le_connection_interval_min_{};
376   uint16_t le_connection_interval_max_{};
377   uint16_t le_connection_latency_{};
378   uint16_t le_connection_supervision_timeout_{};
379   uint16_t le_connection_minimum_ce_length_{};
380   uint16_t le_connection_maximum_ce_length_{};
381   uint8_t le_initiator_filter_policy_{};
382 
383   Address le_peer_address_{};
384   uint8_t le_peer_address_type_{};
385 
386   // Classic state
387 
388   SecurityManager security_manager_{10};
389   std::chrono::steady_clock::time_point last_inquiry_;
390   model::packets::InquiryType inquiry_mode_{
391       model::packets::InquiryType::STANDARD};
392   AsyncTaskId inquiry_timer_task_id_ = kInvalidTaskId;
393   uint64_t inquiry_lap_{};
394   uint8_t inquiry_max_responses_{};
395   uint16_t default_link_policy_settings_ = 0;
396 
397   bool page_scans_enabled_{false};
398   bool inquiry_scans_enabled_{false};
399 
400   bool simple_pairing_mode_enabled_{false};
401 };
402 
403 }  // namespace test_vendor_lib
404