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 <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unordered_set>
29 #include "device/include/controller.h"
30 
31 #include "btif_common.h"
32 #include "btif_util.h"
33 #include "main/shim/le_scanning_manager.h"
34 #include "main/shim/shim.h"
35 
36 #include <hardware/bt_gatt.h>
37 
38 #include "advertise_data_parser.h"
39 #include "bta_api.h"
40 #include "bta_gatt_api.h"
41 #include "btif_config.h"
42 #include "btif_dm.h"
43 #include "btif_gatt.h"
44 #include "btif_gatt_util.h"
45 #include "btif_storage.h"
46 #include "osi/include/log.h"
47 #include "stack/include/btu.h"
48 #include "vendor_api.h"
49 
50 using base::Bind;
51 using base::Owned;
52 using std::vector;
53 using RegisterCallback = BleScannerInterface::RegisterCallback;
54 
55 extern const btgatt_callbacks_t* bt_gatt_callbacks;
56 
57 #define SCAN_CBACK_IN_JNI(P_CBACK, ...)                              \
58   do {                                                               \
59     if (bt_gatt_callbacks && bt_gatt_callbacks->scanner->P_CBACK) {  \
60       BTIF_TRACE_API("HAL bt_gatt_callbacks->client->%s", #P_CBACK); \
61       do_in_jni_thread(                                              \
62           Bind(bt_gatt_callbacks->scanner->P_CBACK, __VA_ARGS__));   \
63     } else {                                                         \
64       ASSERTC(0, "Callback is NULL", 0);                             \
65     }                                                                \
66   } while (0)
67 
68 namespace {
69 
70 // all access to this variable should be done on the jni thread
71 std::set<RawAddress> remote_bdaddr_cache;
72 std::queue<RawAddress> remote_bdaddr_cache_ordered;
73 const size_t remote_bdaddr_cache_max_size = 1024;
74 
btif_address_cache_add(const RawAddress & p_bda,uint8_t addr_type)75 void btif_address_cache_add(const RawAddress& p_bda, uint8_t addr_type) {
76   // Remove the oldest entries
77   while (remote_bdaddr_cache.size() >= remote_bdaddr_cache_max_size) {
78     const RawAddress& raw_address = remote_bdaddr_cache_ordered.front();
79     remote_bdaddr_cache.erase(raw_address);
80     remote_bdaddr_cache_ordered.pop();
81   }
82   remote_bdaddr_cache.insert(p_bda);
83   remote_bdaddr_cache_ordered.push(p_bda);
84 }
85 
btif_address_cache_find(const RawAddress & p_bda)86 bool btif_address_cache_find(const RawAddress& p_bda) {
87   return (remote_bdaddr_cache.find(p_bda) != remote_bdaddr_cache.end());
88 }
89 
btif_address_cache_init(void)90 void btif_address_cache_init(void) {
91   remote_bdaddr_cache.clear();
92   remote_bdaddr_cache_ordered = {};
93 }
94 
bta_batch_scan_threshold_cb(tBTM_BLE_REF_VALUE ref_value)95 void bta_batch_scan_threshold_cb(tBTM_BLE_REF_VALUE ref_value) {
96   SCAN_CBACK_IN_JNI(batchscan_threshold_cb, ref_value);
97 }
98 
bta_batch_scan_reports_cb(int client_id,tBTM_STATUS status,uint8_t report_format,uint8_t num_records,std::vector<uint8_t> data)99 void bta_batch_scan_reports_cb(int client_id, tBTM_STATUS status,
100                                uint8_t report_format, uint8_t num_records,
101                                std::vector<uint8_t> data) {
102   SCAN_CBACK_IN_JNI(batchscan_reports_cb, client_id, status, report_format,
103                     num_records, std::move(data));
104 }
105 
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)106 void bta_scan_results_cb_impl(RawAddress bd_addr, tBT_DEVICE_TYPE device_type,
107                               int8_t rssi, tBLE_ADDR_TYPE addr_type,
108                               uint16_t ble_evt_type, uint8_t ble_primary_phy,
109                               uint8_t ble_secondary_phy,
110                               uint8_t ble_advertising_sid, int8_t ble_tx_power,
111                               uint16_t ble_periodic_adv_int,
112                               vector<uint8_t> value) {
113   uint8_t remote_name_len;
114   bt_device_type_t dev_type;
115   bt_property_t properties;
116 
117   const uint8_t* p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
118       value, BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len);
119 
120   if (p_eir_remote_name == NULL) {
121     p_eir_remote_name = AdvertiseDataParser::GetFieldByType(
122         value, BT_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len);
123   }
124 
125   if ((addr_type != BLE_ADDR_RANDOM) || (p_eir_remote_name)) {
126     if (!btif_address_cache_find(bd_addr)) {
127       btif_address_cache_add(bd_addr, addr_type);
128 
129       if (p_eir_remote_name) {
130         if (remote_name_len > BD_NAME_LEN + 1 ||
131             (remote_name_len == BD_NAME_LEN + 1 &&
132              p_eir_remote_name[BD_NAME_LEN] != '\0')) {
133           LOG_INFO("%s dropping invalid packet - device name too long: %d",
134                    __func__, remote_name_len);
135           return;
136         }
137 
138         bt_bdname_t bdname;
139         memcpy(bdname.name, p_eir_remote_name, remote_name_len);
140         if (remote_name_len < BD_NAME_LEN + 1)
141           bdname.name[remote_name_len] = '\0';
142 
143         LOG_VERBOSE("%s BLE device name=%s len=%d dev_type=%d", __func__,
144                     bdname.name, remote_name_len, device_type);
145         btif_dm_update_ble_remote_properties(bd_addr, bdname.name, device_type);
146       }
147     }
148   }
149 
150   dev_type = (bt_device_type_t)device_type;
151   BTIF_STORAGE_FILL_PROPERTY(&properties, BT_PROPERTY_TYPE_OF_DEVICE,
152                              sizeof(dev_type), &dev_type);
153   btif_storage_set_remote_device_property(&(bd_addr), &properties);
154 
155   btif_storage_set_remote_addr_type(&bd_addr, addr_type);
156   HAL_CBACK(bt_gatt_callbacks, scanner->scan_result_cb, ble_evt_type, addr_type,
157             &bd_addr, ble_primary_phy, ble_secondary_phy, ble_advertising_sid,
158             ble_tx_power, rssi, ble_periodic_adv_int, std::move(value));
159 }
160 
bta_scan_results_cb(tBTA_DM_SEARCH_EVT event,tBTA_DM_SEARCH * p_data)161 void bta_scan_results_cb(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) {
162   uint8_t len;
163 
164   if (event == BTA_DM_INQ_CMPL_EVT) {
165     BTIF_TRACE_DEBUG("%s  BLE observe complete. Num Resp %d", __func__,
166                      p_data->inq_cmpl.num_resps);
167     return;
168   }
169 
170   if (event != BTA_DM_INQ_RES_EVT) {
171     BTIF_TRACE_WARNING("%s : Unknown event 0x%x", __func__, event);
172     return;
173   }
174 
175   vector<uint8_t> value;
176   if (p_data->inq_res.p_eir) {
177     value.insert(value.begin(), p_data->inq_res.p_eir,
178                  p_data->inq_res.p_eir + p_data->inq_res.eir_len);
179 
180     if (AdvertiseDataParser::GetFieldByType(
181             value, BTM_EIR_COMPLETE_LOCAL_NAME_TYPE, &len)) {
182       p_data->inq_res.remt_name_not_required = true;
183     }
184   }
185 
186   tBTA_DM_INQ_RES* r = &p_data->inq_res;
187   do_in_jni_thread(Bind(bta_scan_results_cb_impl, r->bd_addr, r->device_type,
188                         r->rssi, r->ble_addr_type, r->ble_evt_type,
189                         r->ble_primary_phy, r->ble_secondary_phy,
190                         r->ble_advertising_sid, r->ble_tx_power,
191                         r->ble_periodic_adv_int, std::move(value)));
192 }
193 
bta_track_adv_event_cb(tBTM_BLE_TRACK_ADV_DATA * p_track_adv_data)194 void bta_track_adv_event_cb(tBTM_BLE_TRACK_ADV_DATA* p_track_adv_data) {
195   btgatt_track_adv_info_t* btif_scan_track_cb = new btgatt_track_adv_info_t;
196 
197   BTIF_TRACE_DEBUG("%s", __func__);
198   btif_gatt_move_track_adv_data(btif_scan_track_cb,
199                                 (btgatt_track_adv_info_t*)p_track_adv_data);
200 
201   SCAN_CBACK_IN_JNI(track_adv_event_cb, Owned(btif_scan_track_cb));
202 }
203 
bta_cback(tBTA_GATTC_EVT,tBTA_GATTC *)204 void bta_cback(tBTA_GATTC_EVT, tBTA_GATTC*) {}
205 
206 class BleScannerInterfaceImpl : public BleScannerInterface {
~BleScannerInterfaceImpl()207   ~BleScannerInterfaceImpl() override{};
208 
RegisterScanner(const bluetooth::Uuid & app_uuid,RegisterCallback cb)209   void RegisterScanner(const bluetooth::Uuid& app_uuid,
210                        RegisterCallback cb) override {
211     do_in_main_thread(FROM_HERE,
212                       Bind(
213                           [](RegisterCallback cb) {
214                             BTA_GATTC_AppRegister(
215                                 bta_cback,
216                                 jni_thread_wrapper(FROM_HERE, std::move(cb)),
217                                 false);
218                           },
219                           std::move(cb)));
220   }
221 
Unregister(int scanner_id)222   void Unregister(int scanner_id) override {
223     do_in_main_thread(FROM_HERE, Bind(&BTA_GATTC_AppDeregister, scanner_id));
224   }
225 
Scan(bool start)226   void Scan(bool start) override {
227     do_in_jni_thread(Bind(
228         [](bool start) {
229           if (!start) {
230             do_in_main_thread(FROM_HERE,
231                               Bind(&BTA_DmBleObserve, false, 0, nullptr));
232             return;
233           }
234 
235           btif_address_cache_init();
236           do_in_main_thread(
237               FROM_HERE, Bind(&BTA_DmBleObserve, true, 0, bta_scan_results_cb));
238         },
239         start));
240   }
241 
ScanFilterParamSetup(uint8_t client_if,uint8_t action,uint8_t filt_index,std::unique_ptr<btgatt_filt_param_setup_t> filt_param,FilterParamSetupCallback cb)242   void ScanFilterParamSetup(
243       uint8_t client_if, uint8_t action, uint8_t filt_index,
244       std::unique_ptr<btgatt_filt_param_setup_t> filt_param,
245       FilterParamSetupCallback cb) override {
246     BTIF_TRACE_DEBUG("%s", __func__);
247 
248     if (filt_param && filt_param->dely_mode == 1) {
249       do_in_main_thread(
250           FROM_HERE, base::Bind(BTM_BleTrackAdvertiser, bta_track_adv_event_cb,
251                                 client_if));
252     }
253 
254     do_in_main_thread(
255         FROM_HERE, base::Bind(&BTM_BleAdvFilterParamSetup, action, filt_index,
256                               base::Passed(&filt_param),
257                               jni_thread_wrapper(FROM_HERE, std::move(cb))));
258   }
259 
ScanFilterAdd(int filter_index,std::vector<ApcfCommand> filters,FilterConfigCallback cb)260   void ScanFilterAdd(int filter_index, std::vector<ApcfCommand> filters,
261                      FilterConfigCallback cb) override {
262     BTIF_TRACE_DEBUG("%s: %d", __func__, filter_index);
263 
264     do_in_main_thread(
265         FROM_HERE,
266         base::Bind(
267             &BTM_LE_PF_set, filter_index, std::move(filters),
268             jni_thread_wrapper(
269                 FROM_HERE,
270                 Bind(std::move(cb),
271                      0 /*TODO: this used to be filter type, unused ?*/))));
272   }
273 
ScanFilterClear(int filter_index,FilterConfigCallback cb)274   void ScanFilterClear(int filter_index, FilterConfigCallback cb) override {
275     BTIF_TRACE_DEBUG("%s: filter_index: %d", __func__, filter_index);
276     do_in_main_thread(
277         FROM_HERE, base::Bind(&BTM_LE_PF_clear, filter_index,
278                               jni_thread_wrapper(
279                                   FROM_HERE, Bind(cb, BTM_BLE_PF_TYPE_ALL))));
280   }
281 
ScanFilterEnable(bool enable,EnableCallback cb)282   void ScanFilterEnable(bool enable, EnableCallback cb) override {
283     BTIF_TRACE_DEBUG("%s: enable: %d", __func__, enable);
284 
285     uint8_t action = enable ? 1 : 0;
286     do_in_main_thread(FROM_HERE,
287                       base::Bind(&BTM_BleEnableDisableFilterFeature, action,
288                                  jni_thread_wrapper(FROM_HERE, std::move(cb))));
289   }
290 
SetScanParameters(int scan_interval,int scan_window,Callback cb)291   void SetScanParameters(int scan_interval, int scan_window,
292                          Callback cb) override {
293     do_in_main_thread(
294         FROM_HERE, base::Bind(&BTM_BleSetScanParams, scan_interval, scan_window,
295                               BTM_BLE_SCAN_MODE_ACTI,
296                               jni_thread_wrapper(FROM_HERE, std::move(cb))));
297   }
298 
BatchscanConfigStorage(int client_if,int batch_scan_full_max,int batch_scan_trunc_max,int batch_scan_notify_threshold,Callback cb)299   void BatchscanConfigStorage(int client_if, int batch_scan_full_max,
300                               int batch_scan_trunc_max,
301                               int batch_scan_notify_threshold,
302                               Callback cb) override {
303     do_in_main_thread(
304         FROM_HERE,
305         base::Bind(&BTM_BleSetStorageConfig, (uint8_t)batch_scan_full_max,
306                    (uint8_t)batch_scan_trunc_max,
307                    (uint8_t)batch_scan_notify_threshold,
308                    jni_thread_wrapper(FROM_HERE, cb),
309                    bta_batch_scan_threshold_cb, (tBTM_BLE_REF_VALUE)client_if));
310   }
311 
BatchscanEnable(int scan_mode,int scan_interval,int scan_window,int addr_type,int discard_rule,Callback cb)312   void BatchscanEnable(int scan_mode, int scan_interval, int scan_window,
313                        int addr_type, int discard_rule, Callback cb) override {
314     do_in_main_thread(
315         FROM_HERE, base::Bind(&BTM_BleEnableBatchScan, scan_mode, scan_interval,
316                               scan_window, discard_rule,
317                               static_cast<tBLE_ADDR_TYPE>(addr_type),
318                               jni_thread_wrapper(FROM_HERE, cb)));
319   }
320 
BatchscanDisable(Callback cb)321   void BatchscanDisable(Callback cb) override {
322     do_in_main_thread(FROM_HERE, base::Bind(&BTM_BleDisableBatchScan,
323                                             jni_thread_wrapper(FROM_HERE, cb)));
324   }
325 
BatchscanReadReports(int client_if,int scan_mode)326   void BatchscanReadReports(int client_if, int scan_mode) override {
327     do_in_main_thread(
328         FROM_HERE,
329         base::Bind(&BTM_BleReadScanReports, (tBLE_SCAN_MODE)scan_mode,
330                    Bind(bta_batch_scan_reports_cb, client_if)));
331   }
332 
StartSync(uint8_t sid,RawAddress address,uint16_t skip,uint16_t timeout,StartSyncCb start_cb,SyncReportCb report_cb,SyncLostCb lost_cb)333   void StartSync(uint8_t sid, RawAddress address, uint16_t skip,
334                  uint16_t timeout, StartSyncCb start_cb, SyncReportCb report_cb,
335                  SyncLostCb lost_cb) override {}
336 
StopSync(uint16_t handle)337   void StopSync(uint16_t handle) override {}
338 
RegisterCallbacks(ScanningCallbacks * callbacks)339   void RegisterCallbacks(ScanningCallbacks* callbacks) {
340     // For GD only
341   }
342 };
343 
344 BleScannerInterface* btLeScannerInstance = nullptr;
345 
346 }  // namespace
347 
get_ble_scanner_instance()348 BleScannerInterface* get_ble_scanner_instance() {
349   if (bluetooth::shim::is_gd_scanning_enabled()) {
350     LOG_INFO("Use gd le scanner");
351     return bluetooth::shim::get_ble_scanner_instance();
352   } else if (btLeScannerInstance == nullptr) {
353     btLeScannerInstance = new BleScannerInterfaceImpl();
354   }
355   return btLeScannerInstance;
356 }
357