• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 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 #define LOG_TAG "bt_shim_scanner"
18 
19 #include "le_scanning_manager.h"
20 
21 #include <base/bind.h>
22 #include <base/logging.h>
23 #include <base/threading/thread.h>
24 #include <hardware/bluetooth.h>
25 #include <stdio.h>
26 
27 #include <unordered_set>
28 
29 #include "advertise_data_parser.h"
30 #include "btif/include/btif_common.h"
31 #include "hci/address.h"
32 #include "hci/le_scanning_manager.h"
33 #include "include/hardware/ble_scanner.h"
34 #include "main/shim/ble_scanner_interface_impl.h"
35 #include "main/shim/dumpsys.h"
36 #include "main/shim/entry.h"
37 #include "main/shim/helpers.h"
38 #include "main/shim/le_scanning_manager.h"
39 #include "main/shim/shim.h"
40 #include "stack/btm/btm_int_types.h"
41 #include "stack/include/btm_log_history.h"
42 #include "storage/device.h"
43 #include "storage/le_device.h"
44 #include "storage/storage_module.h"
45 #include "types/ble_address_with_type.h"
46 #include "types/bluetooth/uuid.h"
47 #include "types/raw_address.h"
48 
49 using bluetooth::ToGdAddress;
50 using bluetooth::ToRawAddress;
51 
52 namespace {
53 constexpr char kBtmLogTag[] = "SCAN";
54 constexpr uint16_t kAllowServiceDataFilter = 0x0040;
55 constexpr uint16_t kAllowADTypeFilter = 0x80;
56 constexpr uint8_t kFilterLogicOr = 0x00;
57 constexpr uint8_t kFilterLogicAnd = 0x01;
58 constexpr uint8_t kLowestRssiValue = 129;
59 constexpr uint16_t kAllowAllFilter = 0x00;
60 constexpr uint16_t kListLogicOr = 0x01;
61 
62 class DefaultScanningCallback : public ::ScanningCallbacks {
OnScannerRegistered(const bluetooth::Uuid app_uuid,uint8_t scanner_id,uint8_t status)63   void OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scanner_id,
64                            uint8_t status) override {
65     LogUnused();
66   }
OnSetScannerParameterComplete(uint8_t scanner_id,uint8_t status)67   void OnSetScannerParameterComplete(uint8_t scanner_id,
68                                      uint8_t status) override {
69     LogUnused();
70   }
OnScanResult(uint16_t event_type,uint8_t address_type,RawAddress bda,uint8_t primary_phy,uint8_t secondary_phy,uint8_t advertising_sid,int8_t tx_power,int8_t rssi,uint16_t periodic_advertising_interval,std::vector<uint8_t> advertising_data)71   void OnScanResult(uint16_t event_type, uint8_t address_type, RawAddress bda,
72                     uint8_t primary_phy, uint8_t secondary_phy,
73                     uint8_t advertising_sid, int8_t tx_power, int8_t rssi,
74                     uint16_t periodic_advertising_interval,
75                     std::vector<uint8_t> advertising_data) override {
76     LogUnused();
77   }
OnTrackAdvFoundLost(AdvertisingTrackInfo advertising_track_info)78   void OnTrackAdvFoundLost(
79       AdvertisingTrackInfo advertising_track_info) override {
80     LogUnused();
81   }
OnBatchScanReports(int client_if,int status,int report_format,int num_records,std::vector<uint8_t> data)82   void OnBatchScanReports(int client_if, int status, int report_format,
83                           int num_records, std::vector<uint8_t> data) override {
84     LogUnused();
85   }
OnBatchScanThresholdCrossed(int client_if)86   void OnBatchScanThresholdCrossed(int client_if) override { LogUnused(); }
OnPeriodicSyncStarted(int reg_id,uint8_t status,uint16_t sync_handle,uint8_t advertising_sid,uint8_t address_type,RawAddress address,uint8_t phy,uint16_t interval)87   void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle,
88                              uint8_t advertising_sid, uint8_t address_type,
89                              RawAddress address, uint8_t phy,
90                              uint16_t interval) override {
91     LogUnused();
92   };
OnPeriodicSyncReport(uint16_t sync_handle,int8_t tx_power,int8_t rssi,uint8_t status,std::vector<uint8_t> data)93   void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi,
94                             uint8_t status,
95                             std::vector<uint8_t> data) override {
96     LogUnused();
97   };
OnPeriodicSyncLost(uint16_t sync_handle)98   void OnPeriodicSyncLost(uint16_t sync_handle) override { LogUnused(); };
OnPeriodicSyncTransferred(int pa_source,uint8_t status,RawAddress address)99   void OnPeriodicSyncTransferred(int pa_source, uint8_t status,
100                                  RawAddress address) override {
101     LogUnused();
102   };
103 
104  private:
LogUnused()105   static void LogUnused() {
106     LOG_WARN("BLE Scanning callbacks have not been registered");
107   }
108 } default_scanning_callback_;
109 
110 }  // namespace
111 
112 ::ScanningCallbacks* bluetooth::shim::default_scanning_callback =
113     static_cast<::ScanningCallbacks*>(&default_scanning_callback_);
114 extern ::ScanningCallbacks* bluetooth::shim::default_scanning_callback;
115 
116 extern tBTM_CB btm_cb;
117 
118 extern void btm_ble_process_adv_pkt_cont_for_inquiry(
119     uint16_t event_type, tBLE_ADDR_TYPE address_type,
120     const RawAddress& raw_address, uint8_t primary_phy, uint8_t secondary_phy,
121     uint8_t advertising_sid, int8_t tx_power, int8_t rssi,
122     uint16_t periodic_adv_int, std::vector<uint8_t> advertising_data);
123 
124 extern void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr,
125                                                  BD_NAME bd_name,
126                                                  tBT_DEVICE_TYPE dev_type);
127 
128 extern void btm_ble_process_adv_addr(RawAddress& raw_address,
129                                      tBLE_ADDR_TYPE* address_type);
130 
131 using bluetooth::shim::BleScannerInterfaceImpl;
132 
Init()133 void BleScannerInterfaceImpl::Init() {
134   LOG_INFO("init BleScannerInterfaceImpl");
135   bluetooth::shim::GetScanning()->RegisterScanningCallback(this);
136 }
137 
138 /** Registers a scanner with the stack */
RegisterScanner(const bluetooth::Uuid & uuid,RegisterCallback)139 void BleScannerInterfaceImpl::RegisterScanner(const bluetooth::Uuid& uuid,
140                                               RegisterCallback) {
141   LOG(INFO) << __func__ << " in shim layer";
142   auto app_uuid = bluetooth::hci::Uuid::From128BitBE(uuid.To128BitBE());
143   bluetooth::shim::GetScanning()->RegisterScanner(app_uuid);
144 }
145 
146 /** Unregister a scanner from the stack */
Unregister(int scanner_id)147 void BleScannerInterfaceImpl::Unregister(int scanner_id) {
148   LOG(INFO) << __func__ << " in shim layer, scanner_id:" << scanner_id;
149   bluetooth::shim::GetScanning()->Unregister(scanner_id);
150 }
151 
152   /** Start or stop LE device scanning */
Scan(bool start)153 void BleScannerInterfaceImpl::Scan(bool start) {
154   LOG(INFO) << __func__ << " in shim layer " <<  ((start) ? "started" : "stopped");
155   bluetooth::shim::GetScanning()->Scan(start);
156   BTM_LogHistory(
157       kBtmLogTag, RawAddress::kEmpty,
158       base::StringPrintf("Le scan %s", (start) ? "started" : "stopped"));
159   if (start) {
160     btm_cb.ble_ctr_cb.set_ble_observe_active();
161   } else {
162     btm_cb.ble_ctr_cb.reset_ble_observe();
163   }
164   do_in_jni_thread(FROM_HERE,
165                    base::Bind(&BleScannerInterfaceImpl::AddressCache::init,
166                               base::Unretained(&address_cache_)));
167 }
168 
169   /** Setup scan filter params */
ScanFilterParamSetup(uint8_t client_if,uint8_t action,uint8_t filter_index,std::unique_ptr<btgatt_filt_param_setup_t> filt_param,FilterParamSetupCallback cb)170 void BleScannerInterfaceImpl::ScanFilterParamSetup(
171     uint8_t client_if, uint8_t action, uint8_t filter_index,
172     std::unique_ptr<btgatt_filt_param_setup_t> filt_param,
173     FilterParamSetupCallback cb) {
174   LOG(INFO) << __func__ << " in shim layer";
175 
176   auto apcf_action = static_cast<bluetooth::hci::ApcfAction>(action);
177   bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter;
178 
179   if (filt_param != nullptr) {
180     if (filt_param && filt_param->dely_mode == 1 &&
181         apcf_action == hci::ApcfAction::ADD) {
182       bluetooth::shim::GetScanning()->TrackAdvertiser(filter_index, client_if);
183     }
184     advertising_filter_parameter.feature_selection = filt_param->feat_seln;
185     advertising_filter_parameter.list_logic_type = filt_param->list_logic_type;
186     advertising_filter_parameter.filter_logic_type =
187         filt_param->filt_logic_type;
188     advertising_filter_parameter.rssi_high_thresh = filt_param->rssi_high_thres;
189     advertising_filter_parameter.delivery_mode =
190         static_cast<bluetooth::hci::DeliveryMode>(filt_param->dely_mode);
191     if (filt_param && filt_param->dely_mode == 1) {
192       advertising_filter_parameter.onfound_timeout = filt_param->found_timeout;
193       advertising_filter_parameter.onfound_timeout_cnt =
194           filt_param->found_timeout_cnt;
195       advertising_filter_parameter.rssi_low_thresh = filt_param->rssi_low_thres;
196       advertising_filter_parameter.onlost_timeout = filt_param->lost_timeout;
197       advertising_filter_parameter.num_of_tracking_entries =
198           filt_param->num_of_tracking_entries;
199     }
200   }
201 
202   bluetooth::shim::GetScanning()->ScanFilterParameterSetup(
203       apcf_action, filter_index, advertising_filter_parameter);
204   // TODO refactor callback mechanism
205   do_in_jni_thread(FROM_HERE,
206                    base::Bind(cb, 0, 0, btm_status_value(BTM_SUCCESS)));
207 }
208 
209 /** Configure a scan filter condition  */
ScanFilterAdd(int filter_index,std::vector<ApcfCommand> filters,FilterConfigCallback cb)210 void BleScannerInterfaceImpl::ScanFilterAdd(int filter_index,
211                                             std::vector<ApcfCommand> filters,
212                                             FilterConfigCallback cb) {
213   LOG(INFO) << __func__ << " in shim layer";
214   std::vector<bluetooth::hci::AdvertisingPacketContentFilterCommand>
215       new_filters = {};
216   for (size_t i = 0; i < filters.size(); i++) {
217     bluetooth::hci::AdvertisingPacketContentFilterCommand command{};
218     if (!parse_filter_command(command, filters[i])) {
219       LOG_ERROR("invalid apcf command");
220       return;
221     }
222     new_filters.push_back(command);
223   }
224   bluetooth::shim::GetScanning()->ScanFilterAdd(filter_index, new_filters);
225   do_in_jni_thread(FROM_HERE,
226                    base::Bind(cb, 0, 0, 0, btm_status_value(BTM_SUCCESS)));
227 }
228 
229 /** Clear all scan filter conditions for specific filter index*/
ScanFilterClear(int filter_index,FilterConfigCallback cb)230 void BleScannerInterfaceImpl::ScanFilterClear(int filter_index,
231                                               FilterConfigCallback cb) {
232   LOG(INFO) << __func__ << " in shim layer";
233   // This function doesn't used in java layer
234 }
235 
236 /** Enable / disable scan filter feature*/
ScanFilterEnable(bool enable,EnableCallback cb)237 void BleScannerInterfaceImpl::ScanFilterEnable(bool enable, EnableCallback cb) {
238   LOG(INFO) << __func__ << " in shim layer";
239   bluetooth::shim::GetScanning()->ScanFilterEnable(enable);
240 
241   uint8_t action = enable ? 1 : 0;
242   do_in_jni_thread(FROM_HERE,
243                    base::Bind(cb, action, btm_status_value(BTM_SUCCESS)));
244 }
245 
246   /** Sets the LE scan interval and window in units of N*0.625 msec */
SetScanParameters(int scanner_id,int scan_interval,int scan_window,Callback cb)247 void BleScannerInterfaceImpl::SetScanParameters(int scanner_id,
248                                                 int scan_interval,
249                                                 int scan_window, Callback cb) {
250   LOG(INFO) << __func__ << " in shim layer";
251   tBTM_BLE_INQ_CB* p_cb = &btm_cb.ble_ctr_cb.inq_var;
252   if (BTM_BLE_ISVALID_PARAM(scan_interval, BTM_BLE_SCAN_INT_MIN,
253                             BTM_BLE_EXT_SCAN_INT_MAX) &&
254       BTM_BLE_ISVALID_PARAM(scan_window, BTM_BLE_SCAN_WIN_MIN,
255                             BTM_BLE_EXT_SCAN_WIN_MAX)) {
256     p_cb->scan_type = BTM_BLE_SCAN_MODE_ACTI;
257     p_cb->scan_interval = scan_interval;
258     p_cb->scan_window = scan_window;
259   }
260 
261   // use active scan
262   auto scan_type = static_cast<bluetooth::hci::LeScanType>(0x01);
263   bluetooth::shim::GetScanning()->SetScanParameters(scanner_id, scan_type,
264                                                     scan_interval, scan_window);
265 }
266 
267 /* Configure the batchscan storage */
BatchscanConfigStorage(int client_if,int batch_scan_full_max,int batch_scan_trunc_max,int batch_scan_notify_threshold,Callback cb)268 void BleScannerInterfaceImpl::BatchscanConfigStorage(
269     int client_if, int batch_scan_full_max, int batch_scan_trunc_max,
270     int batch_scan_notify_threshold, Callback cb) {
271   LOG(INFO) << __func__ << " in shim layer";
272   bluetooth::shim::GetScanning()->BatchScanConifgStorage(
273       batch_scan_full_max, batch_scan_trunc_max, batch_scan_notify_threshold,
274       client_if);
275   do_in_jni_thread(FROM_HERE, base::Bind(cb, btm_status_value(BTM_SUCCESS)));
276 }
277 
278 /* Enable batchscan */
BatchscanEnable(int scan_mode,int scan_interval,int scan_window,int addr_type,int discard_rule,Callback cb)279 void BleScannerInterfaceImpl::BatchscanEnable(int scan_mode, int scan_interval,
280                                               int scan_window, int addr_type,
281                                               int discard_rule, Callback cb) {
282   LOG(INFO) << __func__ << " in shim layer";
283   auto batch_scan_mode = static_cast<bluetooth::hci::BatchScanMode>(scan_mode);
284   auto batch_scan_discard_rule =
285       static_cast<bluetooth::hci::BatchScanDiscardRule>(discard_rule);
286   bluetooth::shim::GetScanning()->BatchScanEnable(
287       batch_scan_mode, scan_window, scan_interval, batch_scan_discard_rule);
288   do_in_jni_thread(FROM_HERE, base::Bind(cb, btm_status_value(BTM_SUCCESS)));
289 }
290 
291 /* Disable batchscan */
BatchscanDisable(Callback cb)292 void BleScannerInterfaceImpl::BatchscanDisable(Callback cb) {
293   LOG(INFO) << __func__ << " in shim layer";
294   bluetooth::shim::GetScanning()->BatchScanDisable();
295   do_in_jni_thread(FROM_HERE, base::Bind(cb, btm_status_value(BTM_SUCCESS)));
296 }
297 
298 /* Read out batchscan reports */
BatchscanReadReports(int client_if,int scan_mode)299 void BleScannerInterfaceImpl::BatchscanReadReports(int client_if,
300                                                    int scan_mode) {
301   LOG(INFO) << __func__ << " in shim layer";
302   auto batch_scan_mode = static_cast<bluetooth::hci::BatchScanMode>(scan_mode);
303   auto scanner_id = static_cast<bluetooth::hci::ScannerId>(client_if);
304   bluetooth::shim::GetScanning()->BatchScanReadReport(scanner_id,
305                                                       batch_scan_mode);
306 }
307 
308 extern bool btm_random_pseudo_to_identity_addr(
309     RawAddress* random_pseudo, tBLE_ADDR_TYPE* p_identity_addr_type);
310 
311 extern bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr,
312                                                tBLE_ADDR_TYPE* p_addr_type,
313                                                bool refresh);
314 
315 extern tACL_CONN* btm_acl_for_bda(const RawAddress& bd_addr,
316                                   tBT_TRANSPORT transport);
317 
StartSync(uint8_t sid,RawAddress address,uint16_t skip,uint16_t timeout,int reg_id)318 void BleScannerInterfaceImpl::StartSync(uint8_t sid, RawAddress address,
319                                         uint16_t skip, uint16_t timeout,
320                                         int reg_id) {
321   LOG(INFO) << __func__ << " in shim layer";
322   tBLE_ADDR_TYPE address_type = BLE_ADDR_RANDOM;
323   tINQ_DB_ENT* p_i = btm_inq_db_find(address);
324   if (p_i) {
325     address_type = p_i->inq_info.results.ble_addr_type;  // Random
326   }
327   btm_random_pseudo_to_identity_addr(&address, &address_type);
328   address_type &= ~BLE_ADDR_TYPE_ID_BIT;
329   bluetooth::shim::GetScanning()->StartSync(
330       sid, ToAddressWithType(address, address_type), skip, timeout, reg_id);
331 }
332 
StopSync(uint16_t handle)333 void BleScannerInterfaceImpl::StopSync(uint16_t handle) {
334   LOG(INFO) << __func__ << " in shim layer";
335   bluetooth::shim::GetScanning()->StopSync(handle);
336 }
337 
CancelCreateSync(uint8_t sid,RawAddress address)338 void BleScannerInterfaceImpl::CancelCreateSync(uint8_t sid,
339                                                RawAddress address) {
340   LOG(INFO) << __func__ << " in shim layer";
341   bluetooth::shim::GetScanning()->CancelCreateSync(sid, ToGdAddress(address));
342 }
343 
TransferSync(RawAddress address,uint16_t service_data,uint16_t sync_handle,int pa_source)344 void BleScannerInterfaceImpl::TransferSync(RawAddress address,
345                                            uint16_t service_data,
346                                            uint16_t sync_handle,
347                                            int pa_source) {
348   LOG(INFO) << __func__ << " in shim layer";
349   tACL_CONN* p_acl = btm_acl_for_bda(address, BT_TRANSPORT_LE);
350   if (p_acl == NULL || !HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT(
351                            p_acl->peer_le_features)) {
352     LOG_ERROR("[PAST] Remote doesn't support PAST");
353     scanning_callbacks_->OnPeriodicSyncTransferred(
354         pa_source, BTM_MODE_UNSUPPORTED, address);
355     return;
356   }
357   bluetooth::shim::GetScanning()->TransferSync(
358       ToGdAddress(address), service_data, sync_handle, pa_source);
359 }
360 
TransferSetInfo(RawAddress address,uint16_t service_data,uint8_t adv_handle,int pa_source)361 void BleScannerInterfaceImpl::TransferSetInfo(RawAddress address,
362                                               uint16_t service_data,
363                                               uint8_t adv_handle,
364                                               int pa_source) {
365   LOG(INFO) << __func__ << " in shim layer";
366   tACL_CONN* p_acl = btm_acl_for_bda(address, BT_TRANSPORT_LE);
367   if (p_acl == NULL || !HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT(
368                            p_acl->peer_le_features)) {
369     LOG_ERROR("[PAST] Remote doesn't support PAST");
370     scanning_callbacks_->OnPeriodicSyncTransferred(
371         pa_source, BTM_MODE_UNSUPPORTED, address);
372     return;
373   }
374   bluetooth::shim::GetScanning()->TransferSetInfo(
375       ToGdAddress(address), service_data, adv_handle, pa_source);
376 }
377 
SyncTxParameters(RawAddress addr,uint8_t mode,uint16_t skip,uint16_t timeout,int reg_id)378 void BleScannerInterfaceImpl::SyncTxParameters(RawAddress addr, uint8_t mode,
379                                                uint16_t skip, uint16_t timeout,
380                                                int reg_id) {
381   LOG(INFO) << __func__ << " in shim layer";
382   bluetooth::shim::GetScanning()->SyncTxParameters(ToGdAddress(addr), mode,
383                                                    skip, timeout, reg_id);
384 }
385 
RegisterCallbacks(ScanningCallbacks * callbacks)386 void BleScannerInterfaceImpl::RegisterCallbacks(ScanningCallbacks* callbacks) {
387   LOG(INFO) << __func__ << " in shim layer";
388   scanning_callbacks_ = callbacks;
389 }
390 
OnScannerRegistered(const bluetooth::hci::Uuid app_uuid,bluetooth::hci::ScannerId scanner_id,ScanningStatus status)391 void BleScannerInterfaceImpl::OnScannerRegistered(
392     const bluetooth::hci::Uuid app_uuid, bluetooth::hci::ScannerId scanner_id,
393     ScanningStatus status) {
394   auto uuid = bluetooth::Uuid::From128BitBE(app_uuid.To128BitBE());
395   do_in_jni_thread(FROM_HERE,
396                    base::Bind(&ScanningCallbacks::OnScannerRegistered,
397                               base::Unretained(scanning_callbacks_), uuid,
398                               scanner_id, status));
399 }
400 
OnSetScannerParameterComplete(bluetooth::hci::ScannerId scanner_id,ScanningStatus status)401 void BleScannerInterfaceImpl::OnSetScannerParameterComplete(
402     bluetooth::hci::ScannerId scanner_id, ScanningStatus status) {
403   do_in_jni_thread(
404       FROM_HERE,
405       base::Bind(&ScanningCallbacks::OnSetScannerParameterComplete,
406                  base::Unretained(scanning_callbacks_), scanner_id, status));
407 }
408 
OnScanResult(uint16_t event_type,uint8_t address_type,bluetooth::hci::Address address,uint8_t primary_phy,uint8_t secondary_phy,uint8_t advertising_sid,int8_t tx_power,int8_t rssi,uint16_t periodic_advertising_interval,std::vector<uint8_t> advertising_data)409 void BleScannerInterfaceImpl::OnScanResult(
410     uint16_t event_type, uint8_t address_type, bluetooth::hci::Address address,
411     uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid,
412     int8_t tx_power, int8_t rssi, uint16_t periodic_advertising_interval,
413     std::vector<uint8_t> advertising_data) {
414   RawAddress raw_address = ToRawAddress(address);
415   tBLE_ADDR_TYPE ble_addr_type = to_ble_addr_type(address_type);
416 
417   if (ble_addr_type != BLE_ADDR_ANONYMOUS) {
418     btm_ble_process_adv_addr(raw_address, &ble_addr_type);
419   }
420 
421   do_in_jni_thread(
422       FROM_HERE,
423       base::BindOnce(&BleScannerInterfaceImpl::handle_remote_properties,
424                      base::Unretained(this), raw_address, ble_addr_type,
425                      advertising_data));
426 
427   do_in_jni_thread(
428       FROM_HERE,
429       base::BindOnce(&ScanningCallbacks::OnScanResult,
430                      base::Unretained(scanning_callbacks_), event_type,
431                      static_cast<uint8_t>(address_type), raw_address,
432                      primary_phy, secondary_phy, advertising_sid, tx_power,
433                      rssi, periodic_advertising_interval, advertising_data));
434 
435   // TODO: Remove when StartInquiry in GD part implemented
436   btm_ble_process_adv_pkt_cont_for_inquiry(
437       event_type, ble_addr_type, raw_address, primary_phy, secondary_phy,
438       advertising_sid, tx_power, rssi, periodic_advertising_interval,
439       advertising_data);
440 }
441 
OnTrackAdvFoundLost(bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info)442 void BleScannerInterfaceImpl::OnTrackAdvFoundLost(
443     bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info) {
444   AdvertisingTrackInfo track_info = {};
445   RawAddress raw_address =
446       ToRawAddress(on_found_on_lost_info.advertiser_address);
447 
448   if (on_found_on_lost_info.advertiser_address_type != BLE_ADDR_ANONYMOUS) {
449     btm_ble_process_adv_addr(raw_address,
450                              &on_found_on_lost_info.advertiser_address_type);
451   }
452 
453   track_info.advertiser_address = raw_address;
454   track_info.advertiser_address_type =
455       on_found_on_lost_info.advertiser_address_type;
456   track_info.scanner_id = on_found_on_lost_info.scanner_id;
457   track_info.filter_index = on_found_on_lost_info.filter_index;
458   track_info.advertiser_state = on_found_on_lost_info.advertiser_state;
459   track_info.advertiser_info_present =
460       static_cast<uint8_t>(on_found_on_lost_info.advertiser_info_present);
461   if (on_found_on_lost_info.advertiser_info_present ==
462       bluetooth::hci::AdvtInfoPresent::ADVT_INFO_PRESENT) {
463     track_info.tx_power = on_found_on_lost_info.tx_power;
464     track_info.rssi = on_found_on_lost_info.rssi;
465     track_info.time_stamp = on_found_on_lost_info.time_stamp;
466     auto adv_data = on_found_on_lost_info.adv_packet;
467     track_info.adv_packet_len = (uint8_t)adv_data.size();
468     track_info.adv_packet.reserve(adv_data.size());
469     track_info.adv_packet.insert(track_info.adv_packet.end(), adv_data.begin(),
470                                  adv_data.end());
471     auto scan_rsp_data = on_found_on_lost_info.scan_response;
472     track_info.scan_response_len = (uint8_t)scan_rsp_data.size();
473     track_info.scan_response.reserve(adv_data.size());
474     track_info.scan_response.insert(track_info.scan_response.end(),
475                                     scan_rsp_data.begin(), scan_rsp_data.end());
476   }
477   do_in_jni_thread(
478       FROM_HERE,
479       base::BindOnce(&ScanningCallbacks::OnTrackAdvFoundLost,
480                      base::Unretained(scanning_callbacks_), track_info));
481 }
482 
OnBatchScanReports(int client_if,int status,int report_format,int num_records,std::vector<uint8_t> data)483 void BleScannerInterfaceImpl::OnBatchScanReports(int client_if, int status,
484                                                  int report_format,
485                                                  int num_records,
486                                                  std::vector<uint8_t> data) {
487   do_in_jni_thread(
488       FROM_HERE,
489       base::BindOnce(&ScanningCallbacks::OnBatchScanReports,
490                      base::Unretained(scanning_callbacks_), client_if, status,
491                      report_format, num_records, data));
492 }
493 
OnBatchScanThresholdCrossed(int client_if)494 void BleScannerInterfaceImpl::OnBatchScanThresholdCrossed(int client_if) {
495   do_in_jni_thread(
496       FROM_HERE,
497       base::BindOnce(&ScanningCallbacks::OnBatchScanThresholdCrossed,
498                      base::Unretained(scanning_callbacks_), client_if));
499 }
500 
OnPeriodicSyncStarted(int reg_id,uint8_t status,uint16_t sync_handle,uint8_t advertising_sid,bluetooth::hci::AddressWithType address_with_type,uint8_t phy,uint16_t interval)501 void BleScannerInterfaceImpl::OnPeriodicSyncStarted(
502     int reg_id, uint8_t status, uint16_t sync_handle, uint8_t advertising_sid,
503     bluetooth::hci::AddressWithType address_with_type, uint8_t phy,
504     uint16_t interval) {
505   RawAddress raw_address = ToRawAddress(address_with_type.GetAddress());
506   tBLE_ADDR_TYPE ble_addr_type =
507       to_ble_addr_type((uint8_t)address_with_type.GetAddressType());
508   if (ble_addr_type & BLE_ADDR_TYPE_ID_BIT) {
509     btm_identity_addr_to_random_pseudo(&raw_address, &ble_addr_type, true);
510   }
511 
512   do_in_jni_thread(FROM_HERE,
513                    base::BindOnce(&ScanningCallbacks::OnPeriodicSyncStarted,
514                                   base::Unretained(scanning_callbacks_), reg_id,
515                                   status, sync_handle, advertising_sid,
516                                   static_cast<int>(ble_addr_type), raw_address,
517                                   phy, interval));
518 }
519 
OnPeriodicSyncReport(uint16_t sync_handle,int8_t tx_power,int8_t rssi,uint8_t status,std::vector<uint8_t> data)520 void BleScannerInterfaceImpl::OnPeriodicSyncReport(uint16_t sync_handle,
521                                                    int8_t tx_power, int8_t rssi,
522                                                    uint8_t status,
523                                                    std::vector<uint8_t> data) {
524   do_in_jni_thread(
525       FROM_HERE,
526       base::BindOnce(&ScanningCallbacks::OnPeriodicSyncReport,
527                      base::Unretained(scanning_callbacks_), sync_handle,
528                      tx_power, rssi, status, std::move(data)));
529 }
530 
OnPeriodicSyncLost(uint16_t sync_handle)531 void BleScannerInterfaceImpl::OnPeriodicSyncLost(uint16_t sync_handle) {
532   do_in_jni_thread(
533       FROM_HERE,
534       base::BindOnce(&ScanningCallbacks::OnPeriodicSyncLost,
535                      base::Unretained(scanning_callbacks_), sync_handle));
536 }
537 
OnPeriodicSyncTransferred(int pa_source,uint8_t status,bluetooth::hci::Address address)538 void BleScannerInterfaceImpl::OnPeriodicSyncTransferred(
539     int pa_source, uint8_t status, bluetooth::hci::Address address) {
540   do_in_jni_thread(FROM_HERE,
541                    base::BindOnce(&ScanningCallbacks::OnPeriodicSyncTransferred,
542                                   base::Unretained(scanning_callbacks_),
543                                   pa_source, status, ToRawAddress(address)));
544 }
545 
OnTimeout()546 void BleScannerInterfaceImpl::OnTimeout() {}
OnFilterEnable(bluetooth::hci::Enable enable,uint8_t status)547 void BleScannerInterfaceImpl::OnFilterEnable(bluetooth::hci::Enable enable,
548                                              uint8_t status) {}
OnFilterParamSetup(uint8_t available_spaces,bluetooth::hci::ApcfAction action,uint8_t status)549 void BleScannerInterfaceImpl::OnFilterParamSetup(
550     uint8_t available_spaces, bluetooth::hci::ApcfAction action,
551     uint8_t status) {}
OnFilterConfigCallback(bluetooth::hci::ApcfFilterType filter_type,uint8_t available_spaces,bluetooth::hci::ApcfAction action,uint8_t status)552 void BleScannerInterfaceImpl::OnFilterConfigCallback(
553     bluetooth::hci::ApcfFilterType filter_type, uint8_t available_spaces,
554     bluetooth::hci::ApcfAction action, uint8_t status) {}
555 
parse_filter_command(bluetooth::hci::AdvertisingPacketContentFilterCommand & advertising_packet_content_filter_command,ApcfCommand apcf_command)556 bool BleScannerInterfaceImpl::parse_filter_command(
557     bluetooth::hci::AdvertisingPacketContentFilterCommand&
558         advertising_packet_content_filter_command,
559     ApcfCommand apcf_command) {
560   advertising_packet_content_filter_command.filter_type =
561       static_cast<bluetooth::hci::ApcfFilterType>(apcf_command.type);
562   bluetooth::hci::Address address = ToGdAddress(apcf_command.address);
563   advertising_packet_content_filter_command.address = address;
564   advertising_packet_content_filter_command.application_address_type =
565       static_cast<bluetooth::hci::ApcfApplicationAddressType>(
566           apcf_command.addr_type);
567 
568   if (!apcf_command.uuid.IsEmpty()) {
569     uint8_t uuid_len = apcf_command.uuid.GetShortestRepresentationSize();
570     switch (uuid_len) {
571       case bluetooth::Uuid::kNumBytes16: {
572         advertising_packet_content_filter_command.uuid =
573             bluetooth::hci::Uuid::From16Bit(apcf_command.uuid.As16Bit());
574       } break;
575       case bluetooth::Uuid::kNumBytes32: {
576         advertising_packet_content_filter_command.uuid =
577             bluetooth::hci::Uuid::From32Bit(apcf_command.uuid.As32Bit());
578       } break;
579       case bluetooth::Uuid::kNumBytes128: {
580         advertising_packet_content_filter_command.uuid =
581             bluetooth::hci::Uuid::From128BitBE(apcf_command.uuid.To128BitBE());
582       } break;
583       default:
584         LOG_WARN("illegal UUID length %d", (uint16_t)uuid_len);
585         return false;
586     }
587   }
588 
589   if (!apcf_command.uuid_mask.IsEmpty()) {
590     uint8_t uuid_len = apcf_command.uuid.GetShortestRepresentationSize();
591     switch (uuid_len) {
592       case bluetooth::Uuid::kNumBytes16: {
593         advertising_packet_content_filter_command.uuid_mask =
594             bluetooth::hci::Uuid::From16Bit(apcf_command.uuid_mask.As16Bit());
595       } break;
596       case bluetooth::Uuid::kNumBytes32: {
597         advertising_packet_content_filter_command.uuid_mask =
598             bluetooth::hci::Uuid::From32Bit(apcf_command.uuid_mask.As32Bit());
599       } break;
600       case bluetooth::Uuid::kNumBytes128: {
601         advertising_packet_content_filter_command.uuid_mask =
602             bluetooth::hci::Uuid::From128BitBE(
603                 apcf_command.uuid_mask.To128BitBE());
604       } break;
605       default:
606         LOG_WARN("illegal UUID length %d", (uint16_t)uuid_len);
607         return false;
608     }
609   }
610 
611   advertising_packet_content_filter_command.name.assign(
612       apcf_command.name.begin(), apcf_command.name.end());
613   advertising_packet_content_filter_command.company = apcf_command.company;
614   advertising_packet_content_filter_command.company_mask =
615       apcf_command.company_mask;
616   advertising_packet_content_filter_command.ad_type = apcf_command.ad_type;
617   advertising_packet_content_filter_command.data.assign(
618       apcf_command.data.begin(), apcf_command.data.end());
619   advertising_packet_content_filter_command.data_mask.assign(
620       apcf_command.data_mask.begin(), apcf_command.data_mask.end());
621   advertising_packet_content_filter_command.irk = apcf_command.irk;
622   return true;
623 }
624 
handle_remote_properties(RawAddress bd_addr,tBLE_ADDR_TYPE addr_type,std::vector<uint8_t> advertising_data)625 void BleScannerInterfaceImpl::handle_remote_properties(
626     RawAddress bd_addr, tBLE_ADDR_TYPE addr_type,
627     std::vector<uint8_t> advertising_data) {
628   if (!bluetooth::shim::is_gd_stack_started_up()) {
629     LOG_WARN("Gd stack is stopped, return");
630     return;
631   }
632 
633   // skip anonymous advertisment
634   if (addr_type == BLE_ADDR_ANONYMOUS) {
635     return;
636   }
637 
638   auto device_type = bluetooth::hci::DeviceType::LE;
639   uint8_t flag_len;
640   const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType(
641       advertising_data, BTM_BLE_AD_TYPE_FLAG, &flag_len);
642   if (p_flag != NULL && flag_len != 0) {
643     if ((BTM_BLE_BREDR_NOT_SPT & *p_flag) == 0) {
644       device_type = bluetooth::hci::DeviceType::DUAL;
645     }
646   }
647 
648   uint8_t remote_name_len;
649   const uint8_t* p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
650       advertising_data, HCI_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
651 
652   if (p_eir_remote_name == NULL) {
653     p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
654         advertising_data, HCI_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
655   }
656 
657   // update device name
658   if ((addr_type != BLE_ADDR_RANDOM) || (p_eir_remote_name)) {
659     if (!address_cache_.find(bd_addr)) {
660       address_cache_.add(bd_addr);
661 
662       if (p_eir_remote_name) {
663         if (remote_name_len > BD_NAME_LEN + 1 ||
664             (remote_name_len == BD_NAME_LEN + 1 &&
665              p_eir_remote_name[BD_NAME_LEN] != '\0')) {
666           LOG_INFO("%s dropping invalid packet - device name too long: %d",
667                    __func__, remote_name_len);
668           return;
669         }
670 
671         bt_bdname_t bdname;
672         memcpy(bdname.name, p_eir_remote_name, remote_name_len);
673         if (remote_name_len < BD_NAME_LEN + 1)
674           bdname.name[remote_name_len] = '\0';
675 
676         btif_dm_update_ble_remote_properties(bd_addr, bdname.name, device_type);
677       }
678     }
679   }
680   auto* storage_module = bluetooth::shim::GetStorage();
681   bluetooth::hci::Address address = ToGdAddress(bd_addr);
682 
683   // update device type
684   auto mutation = storage_module->Modify();
685   bluetooth::storage::Device device =
686       storage_module->GetDeviceByLegacyKey(address);
687   mutation.Add(device.SetDeviceType(device_type));
688   mutation.Commit();
689 
690   // update address type
691   auto mutation2 = storage_module->Modify();
692   bluetooth::storage::LeDevice le_device = device.Le();
693   mutation2.Add(
694       le_device.SetAddressType((bluetooth::hci::AddressType)addr_type));
695   mutation2.Commit();
696 }
697 
add(const RawAddress & p_bda)698 void BleScannerInterfaceImpl::AddressCache::add(const RawAddress& p_bda) {
699   // Remove the oldest entries
700   while (remote_bdaddr_cache_.size() >= remote_bdaddr_cache_max_size_) {
701     const RawAddress& raw_address = remote_bdaddr_cache_ordered_.front();
702     remote_bdaddr_cache_.erase(raw_address);
703     remote_bdaddr_cache_ordered_.pop();
704   }
705   remote_bdaddr_cache_.insert(p_bda);
706   remote_bdaddr_cache_ordered_.push(p_bda);
707 }
708 
find(const RawAddress & p_bda)709 bool BleScannerInterfaceImpl::AddressCache::find(const RawAddress& p_bda) {
710   return (remote_bdaddr_cache_.find(p_bda) != remote_bdaddr_cache_.end());
711 }
712 
init(void)713 void BleScannerInterfaceImpl::AddressCache::init(void) {
714   remote_bdaddr_cache_.clear();
715   remote_bdaddr_cache_ordered_ = {};
716 }
717 
718 BleScannerInterfaceImpl* bt_le_scanner_instance = nullptr;
719 
get_ble_scanner_instance()720 BleScannerInterface* bluetooth::shim::get_ble_scanner_instance() {
721   if (bt_le_scanner_instance == nullptr) {
722     bt_le_scanner_instance = new BleScannerInterfaceImpl();
723   }
724   return bt_le_scanner_instance;
725 }
726 
init_scanning_manager()727 void bluetooth::shim::init_scanning_manager() {
728   static_cast<BleScannerInterfaceImpl*>(
729       bluetooth::shim::get_ble_scanner_instance())
730       ->Init();
731 }
732 
is_ad_type_filter_supported()733 bool bluetooth::shim::is_ad_type_filter_supported() {
734   return bluetooth::shim::GetScanning()->IsAdTypeFilterSupported();
735 }
736 
set_ad_type_rsi_filter(bool enable)737 void bluetooth::shim::set_ad_type_rsi_filter(bool enable) {
738   bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter;
739   bluetooth::shim::GetScanning()->ScanFilterParameterSetup(
740       bluetooth::hci::ApcfAction::DELETE, 0x00, advertising_filter_parameter);
741   if (enable) {
742     std::vector<bluetooth::hci::AdvertisingPacketContentFilterCommand> filters =
743         {};
744     bluetooth::hci::AdvertisingPacketContentFilterCommand filter{};
745     filter.filter_type = bluetooth::hci::ApcfFilterType::AD_TYPE;
746     filter.ad_type = BTM_BLE_AD_TYPE_RSI;
747     filters.push_back(filter);
748     bluetooth::shim::GetScanning()->ScanFilterAdd(0x00, filters);
749 
750     advertising_filter_parameter.delivery_mode =
751         bluetooth::hci::DeliveryMode::IMMEDIATE;
752     advertising_filter_parameter.feature_selection = kAllowADTypeFilter;
753     advertising_filter_parameter.list_logic_type = kAllowADTypeFilter;
754     advertising_filter_parameter.filter_logic_type = kFilterLogicOr;
755     advertising_filter_parameter.rssi_high_thresh = kLowestRssiValue;
756     bluetooth::shim::GetScanning()->ScanFilterParameterSetup(
757         bluetooth::hci::ApcfAction::ADD, 0x00, advertising_filter_parameter);
758   }
759 }
760 
set_empty_filter(bool enable)761 void bluetooth::shim::set_empty_filter(bool enable) {
762   bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter;
763   bluetooth::shim::GetScanning()->ScanFilterParameterSetup(
764       bluetooth::hci::ApcfAction::DELETE, 0x00, advertising_filter_parameter);
765   if (enable) {
766     /* Add an allow-all filter on index 0 */
767     advertising_filter_parameter.delivery_mode =
768         bluetooth::hci::DeliveryMode::IMMEDIATE;
769     advertising_filter_parameter.feature_selection = kAllowAllFilter;
770     advertising_filter_parameter.list_logic_type = kListLogicOr;
771     advertising_filter_parameter.filter_logic_type = kFilterLogicOr;
772     advertising_filter_parameter.rssi_high_thresh = kLowestRssiValue;
773     bluetooth::shim::GetScanning()->ScanFilterParameterSetup(
774         bluetooth::hci::ApcfAction::ADD, 0x00, advertising_filter_parameter);
775   }
776 }
777 
set_target_announcements_filter(bool enable)778 void bluetooth::shim::set_target_announcements_filter(bool enable) {
779   uint8_t filter_index = 0x03;
780 
781   LOG_DEBUG(" enable %d", enable);
782 
783   bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter = {};
784   bluetooth::shim::GetScanning()->ScanFilterParameterSetup(
785       bluetooth::hci::ApcfAction::DELETE, filter_index,
786       advertising_filter_parameter);
787 
788   if (!enable) return;
789 
790   advertising_filter_parameter.delivery_mode =
791       bluetooth::hci::DeliveryMode::IMMEDIATE;
792   advertising_filter_parameter.feature_selection = kAllowServiceDataFilter;
793   advertising_filter_parameter.list_logic_type = kListLogicOr;
794   advertising_filter_parameter.filter_logic_type = kFilterLogicAnd;
795   advertising_filter_parameter.rssi_high_thresh = kLowestRssiValue;
796 
797   /* Add targeted announcements filter on index 4 */
798   std::vector<bluetooth::hci::AdvertisingPacketContentFilterCommand>
799       cap_bap_filter = {};
800 
801   bluetooth::hci::AdvertisingPacketContentFilterCommand cap_filter{};
802   cap_filter.filter_type = bluetooth::hci::ApcfFilterType::SERVICE_DATA;
803   cap_filter.data = {0x53, 0x18, 0x01};
804   cap_filter.data_mask = {0x53, 0x18, 0xFF};
805   cap_bap_filter.push_back(cap_filter);
806 
807   bluetooth::hci::AdvertisingPacketContentFilterCommand bap_filter{};
808   bap_filter.filter_type = bluetooth::hci::ApcfFilterType::SERVICE_DATA;
809   bap_filter.data = {0x4e, 0x18, 0x01};
810   bap_filter.data_mask = {0x4e, 0x18, 0xFF};
811 
812   cap_bap_filter.push_back(bap_filter);
813   bluetooth::shim::GetScanning()->ScanFilterAdd(filter_index, cap_bap_filter);
814 
815   bluetooth::shim::GetScanning()->ScanFilterParameterSetup(
816       bluetooth::hci::ApcfAction::ADD, filter_index,
817       advertising_filter_parameter);
818 }
819