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