1 /******************************************************************************
2 *
3 * Copyright 2016 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 #define LOG_TAG "bt_btif_scanner"
20
21 #include <base/bind.h>
22 #include <base/threading/thread.h>
23 #include <errno.h>
24 #include <hardware/bluetooth.h>
25 #include <hardware/bt_gatt.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include <unordered_set>
31
32 #include "advertise_data_parser.h"
33 #include "bta_api.h"
34 #include "bta_gatt_api.h"
35 #include "btif_common.h"
36 #include "btif_config.h"
37 #include "btif_dm.h"
38 #include "btif_gatt.h"
39 #include "btif_gatt_util.h"
40 #include "btif_storage.h"
41 #include "btif_util.h"
42 #include "device/include/controller.h"
43 #include "main/shim/le_scanning_manager.h"
44 #include "main/shim/shim.h"
45 #include "osi/include/log.h"
46 #include "stack/include/btm_ble_api.h"
47 #include "stack/include/btu.h"
48 #include "types/bluetooth/uuid.h"
49 #include "types/raw_address.h"
50 #include "vendor_api.h"
51
52 using base::Bind;
53 using base::Owned;
54 using std::vector;
55 using RegisterCallback = BleScannerInterface::RegisterCallback;
56
57 extern const btgatt_callbacks_t* bt_gatt_callbacks;
58
59 #define SCAN_CBACK_IN_JNI(P_CBACK, ...) \
60 do { \
61 if (bt_gatt_callbacks && bt_gatt_callbacks->scanner->P_CBACK) { \
62 BTIF_TRACE_API("HAL bt_gatt_callbacks->client->%s", #P_CBACK); \
63 do_in_jni_thread( \
64 Bind(bt_gatt_callbacks->scanner->P_CBACK, __VA_ARGS__)); \
65 } else { \
66 ASSERTC(0, "Callback is NULL", 0); \
67 } \
68 } while (0)
69
70 namespace {
71
72 // all access to this variable should be done on the jni thread
73 std::set<RawAddress> remote_bdaddr_cache;
74 std::queue<RawAddress> remote_bdaddr_cache_ordered;
75 const size_t remote_bdaddr_cache_max_size = 1024;
76
btif_address_cache_add(const RawAddress & p_bda,uint8_t addr_type)77 void btif_address_cache_add(const RawAddress& p_bda, uint8_t addr_type) {
78 // Remove the oldest entries
79 while (remote_bdaddr_cache.size() >= remote_bdaddr_cache_max_size) {
80 const RawAddress& raw_address = remote_bdaddr_cache_ordered.front();
81 remote_bdaddr_cache.erase(raw_address);
82 remote_bdaddr_cache_ordered.pop();
83 }
84 remote_bdaddr_cache.insert(p_bda);
85 remote_bdaddr_cache_ordered.push(p_bda);
86 }
87
btif_address_cache_find(const RawAddress & p_bda)88 bool btif_address_cache_find(const RawAddress& p_bda) {
89 return (remote_bdaddr_cache.find(p_bda) != remote_bdaddr_cache.end());
90 }
91
btif_address_cache_init(void)92 void btif_address_cache_init(void) {
93 remote_bdaddr_cache.clear();
94 remote_bdaddr_cache_ordered = {};
95 }
96
bta_batch_scan_threshold_cb(tBTM_BLE_REF_VALUE ref_value)97 void bta_batch_scan_threshold_cb(tBTM_BLE_REF_VALUE ref_value) {
98 SCAN_CBACK_IN_JNI(batchscan_threshold_cb, ref_value);
99 }
100
bta_batch_scan_reports_cb(int client_id,tBTM_STATUS status,uint8_t report_format,uint8_t num_records,std::vector<uint8_t> data)101 void bta_batch_scan_reports_cb(int client_id, tBTM_STATUS status,
102 uint8_t report_format, uint8_t num_records,
103 std::vector<uint8_t> data) {
104 SCAN_CBACK_IN_JNI(batchscan_reports_cb, client_id, status, report_format,
105 num_records, std::move(data));
106 }
107
bta_scan_results_cb_impl(RawAddress bd_addr,tBT_DEVICE_TYPE device_type,int8_t rssi,tBLE_ADDR_TYPE addr_type,uint16_t ble_evt_type,uint8_t ble_primary_phy,uint8_t ble_secondary_phy,uint8_t ble_advertising_sid,int8_t ble_tx_power,uint16_t ble_periodic_adv_int,vector<uint8_t> value,RawAddress original_bda)108 void bta_scan_results_cb_impl(RawAddress bd_addr, tBT_DEVICE_TYPE device_type,
109 int8_t rssi, tBLE_ADDR_TYPE addr_type,
110 uint16_t ble_evt_type, uint8_t ble_primary_phy,
111 uint8_t ble_secondary_phy,
112 uint8_t ble_advertising_sid, int8_t ble_tx_power,
113 uint16_t ble_periodic_adv_int,
114 vector<uint8_t> value, RawAddress original_bda) {
115 uint8_t remote_name_len;
116 bt_device_type_t dev_type;
117 bt_property_t properties;
118
119 const uint8_t* p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
120 value, HCI_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
121
122 if (p_eir_remote_name == NULL) {
123 p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
124 value, HCI_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
125 }
126
127 if ((addr_type != BLE_ADDR_RANDOM) || (p_eir_remote_name)) {
128 if (!btif_address_cache_find(bd_addr)) {
129 btif_address_cache_add(bd_addr, addr_type);
130
131 if (p_eir_remote_name) {
132 if (remote_name_len > BD_NAME_LEN + 1 ||
133 (remote_name_len == BD_NAME_LEN + 1 &&
134 p_eir_remote_name[BD_NAME_LEN] != '\0')) {
135 LOG_INFO("%s dropping invalid packet - device name too long: %d",
136 __func__, remote_name_len);
137 return;
138 }
139
140 bt_bdname_t bdname;
141 memcpy(bdname.name, p_eir_remote_name, remote_name_len);
142 if (remote_name_len < BD_NAME_LEN + 1)
143 bdname.name[remote_name_len] = '\0';
144
145 LOG_VERBOSE("%s BLE device name=%s len=%d dev_type=%d", __func__,
146 bdname.name, remote_name_len, device_type);
147 btif_dm_update_ble_remote_properties(bd_addr, bdname.name, device_type);
148 }
149 }
150 }
151
152 dev_type = (bt_device_type_t)device_type;
153 BTIF_STORAGE_FILL_PROPERTY(&properties, BT_PROPERTY_TYPE_OF_DEVICE,
154 sizeof(dev_type), &dev_type);
155 btif_storage_set_remote_device_property(&(bd_addr), &properties);
156
157 btif_storage_set_remote_addr_type(&bd_addr, addr_type);
158 HAL_CBACK(bt_gatt_callbacks, scanner->scan_result_cb, ble_evt_type, addr_type,
159 &bd_addr, ble_primary_phy, ble_secondary_phy, ble_advertising_sid,
160 ble_tx_power, rssi, ble_periodic_adv_int, std::move(value),
161 &original_bda);
162 }
163
bta_scan_results_cb(tBTA_DM_SEARCH_EVT event,tBTA_DM_SEARCH * p_data)164 void bta_scan_results_cb(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) {
165 uint8_t len;
166
167 if (event == BTA_DM_INQ_CMPL_EVT) {
168 BTIF_TRACE_DEBUG("%s BLE observe complete. Num Resp %d", __func__,
169 p_data->inq_cmpl.num_resps);
170 return;
171 }
172
173 if (event != BTA_DM_INQ_RES_EVT) {
174 BTIF_TRACE_WARNING("%s : Unknown event 0x%x", __func__, event);
175 return;
176 }
177
178 vector<uint8_t> value;
179 if (p_data->inq_res.p_eir) {
180 value.insert(value.begin(), p_data->inq_res.p_eir,
181 p_data->inq_res.p_eir + p_data->inq_res.eir_len);
182
183 if (AdvertiseDataParser::GetFieldByType(
184 value, HCI_EIR_COMPLETE_LOCAL_NAME_TYPE, &len)) {
185 p_data->inq_res.remt_name_not_required = true;
186 }
187 }
188
189 tBTA_DM_INQ_RES* r = &p_data->inq_res;
190 do_in_jni_thread(
191 Bind(bta_scan_results_cb_impl, r->bd_addr, r->device_type, r->rssi,
192 r->ble_addr_type, r->ble_evt_type, r->ble_primary_phy,
193 r->ble_secondary_phy, r->ble_advertising_sid, r->ble_tx_power,
194 r->ble_periodic_adv_int, std::move(value), r->original_bda));
195 }
196
bta_track_adv_event_cb(tBTM_BLE_TRACK_ADV_DATA * p_track_adv_data)197 void bta_track_adv_event_cb(tBTM_BLE_TRACK_ADV_DATA* p_track_adv_data) {
198 btgatt_track_adv_info_t* btif_scan_track_cb = new btgatt_track_adv_info_t;
199
200 BTIF_TRACE_DEBUG("%s", __func__);
201 btif_gatt_move_track_adv_data(btif_scan_track_cb,
202 (btgatt_track_adv_info_t*)p_track_adv_data);
203
204 SCAN_CBACK_IN_JNI(track_adv_event_cb, Owned(btif_scan_track_cb));
205 }
206
bta_cback(tBTA_GATTC_EVT,tBTA_GATTC *)207 void bta_cback(tBTA_GATTC_EVT, tBTA_GATTC*) {}
208
209 class BleScannerInterfaceImpl : public BleScannerInterface {
~BleScannerInterfaceImpl()210 ~BleScannerInterfaceImpl() override{};
211
RegisterScanner(const bluetooth::Uuid & app_uuid,RegisterCallback cb)212 void RegisterScanner(const bluetooth::Uuid& app_uuid,
213 RegisterCallback cb) override {
214 do_in_main_thread(FROM_HERE,
215 Bind(
216 [](RegisterCallback cb) {
217 BTA_GATTC_AppRegister(
218 bta_cback,
219 jni_thread_wrapper(FROM_HERE, std::move(cb)),
220 false);
221 },
222 std::move(cb)));
223 }
224
Unregister(int scanner_id)225 void Unregister(int scanner_id) override {
226 do_in_main_thread(FROM_HERE, Bind(&BTA_GATTC_AppDeregister, scanner_id));
227 }
228
Scan(bool start)229 void Scan(bool start) override {
230 do_in_jni_thread(Bind(
231 [](bool start) {
232 if (!start) {
233 do_in_main_thread(FROM_HERE,
234 Bind(&BTA_DmBleObserve, false, 0, nullptr));
235 return;
236 }
237
238 btif_address_cache_init();
239 do_in_main_thread(
240 FROM_HERE, Bind(&BTA_DmBleObserve, true, 0, bta_scan_results_cb));
241 },
242 start));
243 }
244
ScanFilterParamSetup(uint8_t client_if,uint8_t action,uint8_t filt_index,std::unique_ptr<btgatt_filt_param_setup_t> filt_param,FilterParamSetupCallback cb)245 void ScanFilterParamSetup(
246 uint8_t client_if, uint8_t action, uint8_t filt_index,
247 std::unique_ptr<btgatt_filt_param_setup_t> filt_param,
248 FilterParamSetupCallback cb) override {
249 BTIF_TRACE_DEBUG("%s", __func__);
250
251 if (filt_param && filt_param->dely_mode == 1) {
252 do_in_main_thread(
253 FROM_HERE, base::Bind(BTM_BleTrackAdvertiser, bta_track_adv_event_cb,
254 client_if));
255 }
256
257 do_in_main_thread(FROM_HERE,
258 base::Bind(&BTM_BleAdvFilterParamSetup,
259 static_cast<tBTM_BLE_SCAN_COND_OP>(action),
260 filt_index, base::Passed(&filt_param),
261 jni_thread_wrapper(FROM_HERE, std::move(cb))));
262 }
263
ScanFilterAdd(int filter_index,std::vector<ApcfCommand> filters,FilterConfigCallback cb)264 void ScanFilterAdd(int filter_index, std::vector<ApcfCommand> filters,
265 FilterConfigCallback cb) override {
266 BTIF_TRACE_DEBUG("%s: %d", __func__, filter_index);
267
268 do_in_main_thread(
269 FROM_HERE,
270 base::Bind(
271 &BTM_LE_PF_set, filter_index, std::move(filters),
272 jni_thread_wrapper(
273 FROM_HERE,
274 Bind(std::move(cb),
275 0 /*TODO: this used to be filter type, unused ?*/))));
276 }
277
ScanFilterClear(int filter_index,FilterConfigCallback cb)278 void ScanFilterClear(int filter_index, FilterConfigCallback cb) override {
279 BTIF_TRACE_DEBUG("%s: filter_index: %d", __func__, filter_index);
280 do_in_main_thread(
281 FROM_HERE, base::Bind(&BTM_LE_PF_clear, filter_index,
282 jni_thread_wrapper(
283 FROM_HERE, Bind(cb, BTM_BLE_PF_TYPE_ALL))));
284 }
285
ScanFilterEnable(bool enable,EnableCallback cb)286 void ScanFilterEnable(bool enable, EnableCallback cb) override {
287 BTIF_TRACE_DEBUG("%s: enable: %d", __func__, enable);
288
289 uint8_t action = enable ? 1 : 0;
290 do_in_main_thread(FROM_HERE,
291 base::Bind(&BTM_BleEnableDisableFilterFeature, action,
292 jni_thread_wrapper(FROM_HERE, std::move(cb))));
293 }
294
SetScanParameters(int scanner_id,int scan_interval,int scan_window,Callback cb)295 void SetScanParameters(int scanner_id, int scan_interval, int scan_window,
296 Callback cb) override {
297 do_in_main_thread(
298 FROM_HERE, base::Bind(&BTM_BleSetScanParams, scan_interval, scan_window,
299 BTM_BLE_SCAN_MODE_ACTI,
300 jni_thread_wrapper(FROM_HERE, std::move(cb))));
301 }
302
BatchscanConfigStorage(int client_if,int batch_scan_full_max,int batch_scan_trunc_max,int batch_scan_notify_threshold,Callback cb)303 void BatchscanConfigStorage(int client_if, int batch_scan_full_max,
304 int batch_scan_trunc_max,
305 int batch_scan_notify_threshold,
306 Callback cb) override {
307 do_in_main_thread(
308 FROM_HERE,
309 base::Bind(&BTM_BleSetStorageConfig, (uint8_t)batch_scan_full_max,
310 (uint8_t)batch_scan_trunc_max,
311 (uint8_t)batch_scan_notify_threshold,
312 jni_thread_wrapper(FROM_HERE, cb),
313 bta_batch_scan_threshold_cb, (tBTM_BLE_REF_VALUE)client_if));
314 }
315
BatchscanEnable(int scan_mode,int scan_interval,int scan_window,int addr_type,int discard_rule,Callback cb)316 void BatchscanEnable(int scan_mode, int scan_interval, int scan_window,
317 int addr_type, int discard_rule, Callback cb) override {
318 do_in_main_thread(
319 FROM_HERE, base::Bind(&BTM_BleEnableBatchScan, scan_mode, scan_interval,
320 scan_window, discard_rule,
321 static_cast<tBLE_ADDR_TYPE>(addr_type),
322 jni_thread_wrapper(FROM_HERE, cb)));
323 }
324
BatchscanDisable(Callback cb)325 void BatchscanDisable(Callback cb) override {
326 do_in_main_thread(FROM_HERE, base::Bind(&BTM_BleDisableBatchScan,
327 jni_thread_wrapper(FROM_HERE, cb)));
328 }
329
BatchscanReadReports(int client_if,int scan_mode)330 void BatchscanReadReports(int client_if, int scan_mode) override {
331 do_in_main_thread(
332 FROM_HERE,
333 base::Bind(&BTM_BleReadScanReports, (tBLE_SCAN_MODE)scan_mode,
334 Bind(bta_batch_scan_reports_cb, client_if)));
335 }
336
StartSync(uint8_t sid,RawAddress address,uint16_t skip,uint16_t timeout,int reg_id)337 void StartSync(uint8_t sid, RawAddress address, uint16_t skip,
338 uint16_t timeout, int reg_id) override {
339 const controller_t* controller = controller_get_interface();
340 if (!controller->supports_ble_periodic_advertising_sync_transfer_sender()) {
341 uint8_t status_no_resource = 2;
342 callbacks_->OnPeriodicSyncStarted(reg_id, status_no_resource, -1, sid, 1,
343 address, 0, 0);
344 return;
345 }
346 StartSyncCb start_sync_cb =
347 base::Bind(&ScanningCallbacks::OnPeriodicSyncStarted,
348 base::Unretained(callbacks_), reg_id);
349 SyncReportCb sync_report_cb = base::Bind(
350 &ScanningCallbacks::OnPeriodicSyncReport, base::Unretained(callbacks_));
351 SyncLostCb sync_lost_cb = base::Bind(&ScanningCallbacks::OnPeriodicSyncLost,
352 base::Unretained(callbacks_));
353 do_in_main_thread(
354 FROM_HERE,
355 base::Bind(&BTM_BleStartPeriodicSync, sid, address, skip, timeout,
356 jni_thread_wrapper(FROM_HERE, std::move(start_sync_cb)),
357 jni_thread_wrapper(FROM_HERE, std::move(sync_report_cb)),
358 jni_thread_wrapper(FROM_HERE, std::move(sync_lost_cb))));
359 }
360
StopSync(uint16_t handle)361 void StopSync(uint16_t handle) override {
362 LOG_DEBUG("handle: %d", handle);
363 const controller_t* controller = controller_get_interface();
364 if (!controller->supports_ble_periodic_advertising_sync_transfer_sender()) {
365 LOG_ERROR("PAST not supported by controller");
366 return;
367 }
368 do_in_main_thread(FROM_HERE, base::Bind(&BTM_BleStopPeriodicSync, handle));
369 }
370
RegisterCallbacks(ScanningCallbacks * callbacks)371 void RegisterCallbacks(ScanningCallbacks* callbacks) override {
372 callbacks_ = callbacks;
373 }
374
CancelCreateSync(uint8_t sid,RawAddress address)375 void CancelCreateSync(uint8_t sid, RawAddress address) override {
376 const controller_t* controller = controller_get_interface();
377 if (!controller->supports_ble_periodic_advertising_sync_transfer_sender()) {
378 LOG_ERROR("PAST not supported by controller");
379 return;
380 }
381 do_in_main_thread(FROM_HERE,
382 base::Bind(&BTM_BleCancelPeriodicSync, sid, address));
383 }
384
TransferSync(RawAddress address,uint16_t service_data,uint16_t sync_handle,int pa_source)385 void TransferSync(RawAddress address, uint16_t service_data,
386 uint16_t sync_handle, int pa_source) override {
387 LOG_DEBUG("address:%s", address.ToString().c_str());
388 const controller_t* controller = controller_get_interface();
389 if (!controller->supports_ble_periodic_advertising_sync_transfer_sender()) {
390 uint8_t status_no_resource = 2;
391 LOG_ERROR("PAST not supported by controller");
392 callbacks_->OnPeriodicSyncTransferred(pa_source, status_no_resource,
393 address);
394 return;
395 }
396 SyncTransferCb sync_transfer_cb =
397 base::Bind(&ScanningCallbacks::OnPeriodicSyncTransferred,
398 base::Unretained(callbacks_), pa_source);
399 do_in_main_thread(
400 FROM_HERE,
401 base::Bind(&BTM_BlePeriodicSyncTransfer, address, service_data,
402 sync_handle,
403 jni_thread_wrapper(FROM_HERE, std::move(sync_transfer_cb))));
404 }
405
TransferSetInfo(RawAddress address,uint16_t service_data,uint8_t adv_handle,int pa_source)406 void TransferSetInfo(RawAddress address, uint16_t service_data,
407 uint8_t adv_handle, int pa_source) override {
408 LOG_DEBUG("address: %s", address.ToString().c_str());
409 const controller_t* controller = controller_get_interface();
410 if (!controller->supports_ble_periodic_advertising_sync_transfer_sender()) {
411 uint8_t status_no_resource = 2;
412 LOG_ERROR(" PAST not supported by controller");
413 callbacks_->OnPeriodicSyncTransferred(pa_source, status_no_resource,
414 address);
415 return;
416 }
417 SyncTransferCb sync_transfer_cb =
418 base::Bind(&ScanningCallbacks::OnPeriodicSyncTransferred,
419 base::Unretained(callbacks_), pa_source);
420 do_in_main_thread(
421 FROM_HERE,
422 base::Bind(&BTM_BlePeriodicSyncSetInfo, address, service_data,
423 adv_handle,
424 jni_thread_wrapper(FROM_HERE, std::move(sync_transfer_cb))));
425 }
426
SyncTxParameters(RawAddress addr,uint8_t mode,uint16_t skip,uint16_t timeout,int reg_id)427 void SyncTxParameters(RawAddress addr, uint8_t mode, uint16_t skip,
428 uint16_t timeout, int reg_id) override {
429 LOG_DEBUG("address: %s", addr.ToString().c_str());
430 const controller_t* controller = controller_get_interface();
431 if (!controller->supports_ble_periodic_advertising_sync_transfer_sender()) {
432 uint8_t status_no_resource = 2;
433 LOG_ERROR(" PAST not supported by controller");
434 callbacks_->OnPeriodicSyncStarted(reg_id, status_no_resource, -1, -1, 1,
435 addr, 0, 0);
436 return;
437 }
438 StartSyncCb start_sync_cb =
439 base::Bind(&ScanningCallbacks::OnPeriodicSyncStarted,
440 base::Unretained(callbacks_), reg_id);
441 do_in_main_thread(
442 FROM_HERE,
443 base::Bind(&BTM_BlePeriodicSyncTxParameters, addr, mode, skip, timeout,
444 jni_thread_wrapper(FROM_HERE, std::move(start_sync_cb))));
445 }
446
447 ScanningCallbacks* callbacks_ = nullptr;
448 };
449
450 } // namespace
451
get_ble_scanner_instance()452 BleScannerInterface* get_ble_scanner_instance() {
453 LOG_INFO("Use gd le scanner");
454 return bluetooth::shim::get_ble_scanner_instance();
455 }
456