1 /******************************************************************************
2  *
3  *  Copyright 2003-2012 Broadcom Corporation
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 /******************************************************************************
20  *
21  *  This file contains the GATT client discovery procedures and cache
22  *  related functions.
23  *
24  ******************************************************************************/
25 
26 #define LOG_TAG "bt_bta_gattc"
27 
28 #include <base/functional/bind.h>
29 #include <base/functional/callback.h>
30 #include <base/strings/string_number_conversions.h>
31 #include <base/strings/stringprintf.h>
32 #include <bluetooth/log.h>
33 
34 #include <cstdint>
35 #include <cstdio>
36 #include <vector>
37 
38 #include "bta/gatt/bta_gattc_int.h"
39 #include "bta/gatt/database.h"
40 #include "device/include/interop.h"
41 #include "internal_include/bt_target.h"
42 #include "osi/include/allocator.h"
43 #include "stack/btm/btm_sec.h"
44 #include "stack/include/bt_types.h"
45 #include "stack/include/bt_uuid16.h"
46 #include "stack/include/btm_client_interface.h"
47 #include "stack/include/gatt_api.h"
48 #include "stack/include/sdp_api.h"
49 #include "types/bluetooth/uuid.h"
50 #include "types/raw_address.h"
51 
52 // TODO(b/369381361) Enfore -Wmissing-prototypes
53 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
54 
55 using namespace bluetooth::legacy::stack::sdp;
56 using namespace bluetooth;
57 
58 using base::StringPrintf;
59 using bluetooth::Uuid;
60 using gatt::Characteristic;
61 using gatt::Database;
62 using gatt::DatabaseBuilder;
63 using gatt::Descriptor;
64 using gatt::IncludedService;
65 using gatt::Service;
66 
67 static tGATT_STATUS bta_gattc_sdp_service_disc(tCONN_ID conn_id, tBTA_GATTC_SERV* p_server_cb);
68 const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle);
69 const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle);
70 static void bta_gattc_explore_srvc_finished(tCONN_ID conn_id, tBTA_GATTC_SERV* p_srvc_cb);
71 
72 static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data,
73                                         bool is_svc_chg);
74 
75 static void bta_gattc_read_ext_prop_desc_cmpl(tBTA_GATTC_CLCB* p_clcb,
76                                               const tBTA_GATTC_OP_CMPL* p_data);
77 
78 // define the max retry count for DATABASE_OUT_OF_SYNC
79 #define BTA_GATTC_DISCOVER_RETRY_COUNT 2
80 
81 #define BTA_GATT_SDP_DB_SIZE 4096
82 
83 /*****************************************************************************
84  *  Constants and data types
85  ****************************************************************************/
86 
87 typedef struct {
88   tSDP_DISCOVERY_DB* p_sdp_db;
89   tCONN_ID sdp_conn_id;
90 } tBTA_GATTC_CB_DATA;
91 
92 #if (BTA_GATT_DEBUG == TRUE)
93 /* utility functions */
94 
95 /* debug function to display the server cache */
bta_gattc_display_cache_server(const Database & database)96 static void bta_gattc_display_cache_server(const Database& database) {
97   log::info("<=--------------=Start Server Cache =-----------=>");
98   std::istringstream iss(database.ToString());
99   for (std::string line; std::getline(iss, line);) {
100     log::info("{}", line);
101   }
102   log::info("<=--------------=End Server Cache =-----------=>");
103 }
104 
105 /** debug function to display the exploration list */
bta_gattc_display_explore_record(const DatabaseBuilder & database)106 static void bta_gattc_display_explore_record(const DatabaseBuilder& database) {
107   log::info("<=--------------=Start Explore Queue =-----------=>");
108   std::istringstream iss(database.ToString());
109   for (std::string line; std::getline(iss, line);) {
110     log::info("{}", line);
111   }
112   log::info("<=--------------= End Explore Queue =-----------=>");
113 }
114 #endif /* BTA_GATT_DEBUG == TRUE */
115 
116 /** Initialize the database cache and discovery related resources */
bta_gattc_init_cache(tBTA_GATTC_SERV * p_srvc_cb)117 void bta_gattc_init_cache(tBTA_GATTC_SERV* p_srvc_cb) {
118   p_srvc_cb->gatt_database = gatt::Database();
119   p_srvc_cb->pending_discovery.Clear();
120 }
121 
bta_gattc_find_matching_service(const std::list<Service> & services,uint16_t handle)122 const Service* bta_gattc_find_matching_service(const std::list<Service>& services,
123                                                uint16_t handle) {
124   for (const Service& service : services) {
125     if (handle >= service.handle && handle <= service.end_handle) {
126       return &service;
127     }
128   }
129 
130   return nullptr;
131 }
132 
133 /// Whether the peer device uses robust caching
GetRobustCachingSupport(const tBTA_GATTC_CLCB * p_clcb,const gatt::Database & db)134 RobustCachingSupport GetRobustCachingSupport(const tBTA_GATTC_CLCB* p_clcb,
135                                              const gatt::Database& db) {
136   log::debug("GetRobustCachingSupport {}", p_clcb->bda.ToRedactedStringForLogging());
137 
138   // An empty database means that discovery hasn't taken place yet, so
139   // we can't infer anything from that
140   if (!db.IsEmpty()) {
141     // Here, we can simply check whether the database hash is present
142     for (const auto& service : db.Services()) {
143       if (service.uuid.As16Bit() != UUID_SERVCLASS_GATT_SERVER) {
144         continue;
145       }
146       for (const auto& characteristic : service.characteristics) {
147         if (characteristic.uuid.As16Bit() == GATT_UUID_DATABASE_HASH) {
148           // the hash was found, so we should read it
149           log::debug("database hash characteristic found, so SUPPORTED");
150           return RobustCachingSupport::SUPPORTED;
151         }
152       }
153     }
154 
155     // The database hash characteristic was not found, so there's no point
156     // searching for it. Even if the hash was previously not present but is now,
157     // we will still get the service changed indication, so there's no need to
158     // speculatively check for the hash every time.
159     log::debug("database hash characteristic not found, so UNSUPPORTED");
160     return RobustCachingSupport::UNSUPPORTED;
161   }
162 
163   if (p_clcb->transport == BT_TRANSPORT_LE &&
164       !get_btm_client_interface().ble.BTM_IsRemoteVersionReceived(p_clcb->bda)) {
165     log::info("version info is not ready yet");
166     return RobustCachingSupport::W4_REMOTE_VERSION;
167   }
168 
169   // This is workaround for the embedded devices being already on the market
170   // and having a serious problem with handle Read By Type with
171   // GATT_UUID_DATABASE_HASH. With this workaround, Android will assume that
172   // embedded device having LMP version lower than 5.1 (0x0a), it does not
173   // support GATT Caching.
174   uint8_t lmp_version = 0;
175   if (!get_btm_client_interface().peer.BTM_ReadRemoteVersion(p_clcb->bda, &lmp_version, nullptr,
176                                                              nullptr)) {
177     log::warn("Could not read remote version for {}", p_clcb->bda);
178   }
179 
180   if (lmp_version < 0x0a) {
181     log::warn(
182             "Device LMP version 0x{:02x} < Bluetooth 5.1. Ignore database cache "
183             "read.",
184             lmp_version);
185     return RobustCachingSupport::UNSUPPORTED;
186   }
187 
188   // Some LMP 5.2 devices also don't support robust caching. This workaround
189   // conditionally disables the feature based on a combination of LMP
190   // version and OUI prefix.
191   if (lmp_version < 0x0c && interop_match_addr(INTEROP_DISABLE_ROBUST_CACHING, &p_clcb->bda)) {
192     log::warn(
193             "Device LMP version 0x{:02x} <= Bluetooth 5.2 and MAC addr on interop "
194             "list, skipping robust caching",
195             lmp_version);
196     return RobustCachingSupport::UNSUPPORTED;
197   }
198 
199   // If we have no cached database and no interop considerations,
200   // it is unknown whether or not robust caching is supported
201   log::debug("database hash support is UNKNOWN");
202   return RobustCachingSupport::UNKNOWN;
203 }
204 
205 /** Start primary service discovery */
bta_gattc_discover_pri_service(tCONN_ID conn_id,tBTA_GATTC_SERV * p_server_cb,tGATT_DISC_TYPE disc_type)206 [[nodiscard]] tGATT_STATUS bta_gattc_discover_pri_service(tCONN_ID conn_id,
207                                                           tBTA_GATTC_SERV* p_server_cb,
208                                                           tGATT_DISC_TYPE disc_type) {
209   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
210   if (!p_clcb) {
211     return GATT_ERROR;
212   }
213 
214   if (p_clcb->transport == BT_TRANSPORT_LE) {
215     return GATTC_Discover(conn_id, disc_type, 0x0001, 0xFFFF);
216   }
217 
218   // only for Classic transport
219   return bta_gattc_sdp_service_disc(conn_id, p_server_cb);
220 }
221 
222 /** start exploring next service, or finish discovery if no more services left
223  */
bta_gattc_explore_next_service(tCONN_ID conn_id,tBTA_GATTC_SERV * p_srvc_cb)224 static void bta_gattc_explore_next_service(tCONN_ID conn_id, tBTA_GATTC_SERV* p_srvc_cb) {
225   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
226   if (!p_clcb) {
227     log::error("unknown conn_id=0x{:x}", conn_id);
228     return;
229   }
230 
231   if (p_srvc_cb->pending_discovery.StartNextServiceExploration()) {
232     const auto& service = p_srvc_cb->pending_discovery.CurrentlyExploredService();
233     log::verbose("Start service discovery");
234 
235     /* start discovering included services */
236     if (GATTC_Discover(conn_id, GATT_DISC_INC_SRVC, service.first, service.second) !=
237         GATT_SUCCESS) {
238       log::warn("Unable to discover GATT client conn_id:{}", conn_id);
239     }
240     return;
241   }
242   // No more services to discover
243 
244   // As part of service discovery, read the values of "Characteristic Extended
245   // Properties" descriptor
246   const auto& descriptors = p_srvc_cb->pending_discovery.DescriptorHandlesToRead();
247   if (!descriptors.empty()) {
248     // set request field to READ_EXT_PROP_DESC
249     p_clcb->request_during_discovery = BTA_GATTC_DISCOVER_REQ_READ_EXT_PROP_DESC;
250 
251     if (p_srvc_cb->read_multiple_not_supported || descriptors.size() == 1) {
252       tGATT_READ_PARAM read_param{
253               .by_handle = {.auth_req = GATT_AUTH_REQ_NONE, .handle = descriptors.front()}};
254       if (GATTC_Read(conn_id, GATT_READ_BY_HANDLE, &read_param) != GATT_SUCCESS) {
255         log::warn("Unable to read GATT client conn_id:{}", conn_id);
256       }
257       // asynchronous continuation in bta_gattc_op_cmpl_during_discovery
258       return;
259     }
260 
261     // TODO(jpawlowski): as a limit we should use MTU/2 rather than
262     // GATT_MAX_READ_MULTI_HANDLES
263     /* each descriptor contains just 2 bytes, so response size is same as
264      * request size */
265     size_t num_handles = std::min(descriptors.size(), (size_t)GATT_MAX_READ_MULTI_HANDLES);
266 
267     tGATT_READ_PARAM read_param;
268     memset(&read_param, 0, sizeof(tGATT_READ_PARAM));
269 
270     read_param.read_multiple.num_handles = num_handles;
271     read_param.read_multiple.auth_req = GATT_AUTH_REQ_NONE;
272     memcpy(&read_param.read_multiple.handles, descriptors.data(), sizeof(uint16_t) * num_handles);
273     if (GATTC_Read(conn_id, GATT_READ_MULTIPLE, &read_param) != GATT_SUCCESS) {
274       log::warn("Unable to read GATT client conn_id:{}", conn_id);
275     }
276 
277     // asynchronous continuation in bta_gattc_op_cmpl_during_discovery
278     return;
279   }
280 
281   bta_gattc_explore_srvc_finished(conn_id, p_srvc_cb);
282 }
283 
bta_gattc_explore_srvc_finished(tCONN_ID conn_id,tBTA_GATTC_SERV * p_srvc_cb)284 static void bta_gattc_explore_srvc_finished(tCONN_ID conn_id, tBTA_GATTC_SERV* p_srvc_cb) {
285   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
286   if (!p_clcb) {
287     log::error("unknown conn_id=0x{:x}", conn_id);
288     return;
289   }
290 
291   /* no service found at all, the end of server discovery*/
292   log::info("service discovery finished");
293 
294   p_srvc_cb->gatt_database = p_srvc_cb->pending_discovery.Build();
295 
296 #if (BTA_GATT_DEBUG == TRUE)
297   bta_gattc_display_cache_server(p_srvc_cb->gatt_database);
298 #endif
299   /* save cache to NV */
300   p_clcb->p_srcb->state = BTA_GATTC_SERV_SAVE;
301 
302   // If robust caching is enabled, do something optimized
303   Octet16 hash = p_clcb->p_srcb->gatt_database.Hash();
304   bool success = bta_gattc_hash_write(hash, p_clcb->p_srcb->gatt_database);
305 
306   // If the device is trusted, link the addr file to hash file
307   if (success && btm_sec_is_a_bonded_dev(p_srvc_cb->server_bda)) {
308     log::debug("Linking db hash to address {}",
309                p_clcb->p_srcb->server_bda.ToRedactedStringForLogging());
310     bta_gattc_cache_link(p_clcb->p_srcb->server_bda, hash);
311   }
312 
313   // After success, reset the count.
314   log::debug("service discovery succeed, reset count to zero, conn_id=0x{:04x}", conn_id);
315   p_srvc_cb->srvc_disc_count = 0;
316 
317   bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS);
318 }
319 
320 /** Start discovery for characteristic descriptor */
bta_gattc_start_disc_char_dscp(tCONN_ID conn_id,tBTA_GATTC_SERV * p_srvc_cb)321 void bta_gattc_start_disc_char_dscp(tCONN_ID conn_id, tBTA_GATTC_SERV* p_srvc_cb) {
322   log::verbose("starting discover characteristics descriptor");
323 
324   std::pair<uint16_t, uint16_t> range = p_srvc_cb->pending_discovery.NextDescriptorRangeToExplore();
325   if (range == DatabaseBuilder::EXPLORE_END) {
326     goto descriptor_discovery_done;
327   }
328 
329   if (GATTC_Discover(conn_id, GATT_DISC_CHAR_DSCPT, range.first, range.second) != GATT_SUCCESS) {
330     goto descriptor_discovery_done;
331   }
332   return;
333 
334 descriptor_discovery_done:
335   /* all characteristic has been explored, start with next service if any */
336   bta_gattc_explore_next_service(conn_id, p_srvc_cb);
337   return;
338 }
339 
340 /* Process the discovery result from sdp */
bta_gattc_sdp_callback(tBTA_GATTC_CB_DATA * cb_data,const RawAddress &,tSDP_STATUS sdp_status)341 void bta_gattc_sdp_callback(tBTA_GATTC_CB_DATA* cb_data, const RawAddress& /* bd_addr */,
342                             tSDP_STATUS sdp_status) {
343   tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(cb_data->sdp_conn_id);
344 
345   if (p_srvc_cb == nullptr) {
346     log::error("GATT service discovery is done on unknown connection");
347     /* allocated in bta_gattc_sdp_service_disc */
348     osi_free(cb_data);
349     return;
350   }
351 
352   if ((sdp_status != tSDP_STATUS::SDP_SUCCESS) && (sdp_status != tSDP_STATUS::SDP_DB_FULL)) {
353     bta_gattc_explore_srvc_finished(cb_data->sdp_conn_id, p_srvc_cb);
354 
355     /* allocated in bta_gattc_sdp_service_disc */
356     osi_free(cb_data);
357     return;
358   }
359 
360   bool no_pending_disc = !p_srvc_cb->pending_discovery.InProgress();
361 
362   tSDP_DISC_REC* p_sdp_rec =
363           get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(cb_data->p_sdp_db, 0, nullptr);
364   while (p_sdp_rec != nullptr) {
365     /* find a service record, report it */
366     Uuid service_uuid;
367     if (!get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec(p_sdp_rec, &service_uuid)) {
368       continue;
369     }
370 
371     tSDP_PROTOCOL_ELEM pe;
372     if (!get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(p_sdp_rec,
373                                                                           UUID_PROTOCOL_ATT, &pe)) {
374       continue;
375     }
376 
377     uint16_t start_handle = (uint16_t)pe.params[0];
378     uint16_t end_handle = (uint16_t)pe.params[1];
379 
380 #if (BTA_GATT_DEBUG == TRUE)
381     log::verbose("Found ATT service uuid={}, s_handle=0x{:x}, e_handle=0x{:x}", service_uuid,
382                  start_handle, end_handle);
383 #endif
384 
385     if (!GATT_HANDLE_IS_VALID(start_handle) || !GATT_HANDLE_IS_VALID(end_handle)) {
386       log::error("invalid start_handle=0x{:x}, end_handle=0x{:x}", start_handle, end_handle);
387       p_sdp_rec =
388               get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(cb_data->p_sdp_db, 0, p_sdp_rec);
389       continue;
390     }
391 
392     /* discover services result, add services into a service list */
393     p_srvc_cb->pending_discovery.AddService(start_handle, end_handle, service_uuid, true);
394 
395     p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(cb_data->p_sdp_db, 0, p_sdp_rec);
396   }
397 
398   // If discovery is already pending, no need to call
399   // bta_gattc_explore_next_service. Next service will be picked up to discovery
400   // once current one is discovered. If discovery is not pending, start one
401   if (no_pending_disc) {
402     bta_gattc_explore_next_service(cb_data->sdp_conn_id, p_srvc_cb);
403   }
404 
405   /* allocated in bta_gattc_sdp_service_disc */
406   osi_free(cb_data);
407 }
408 
409 /* Start DSP Service Discovery */
bta_gattc_sdp_service_disc(tCONN_ID conn_id,tBTA_GATTC_SERV * p_server_cb)410 static tGATT_STATUS bta_gattc_sdp_service_disc(tCONN_ID conn_id, tBTA_GATTC_SERV* p_server_cb) {
411   uint16_t num_attrs = 2;
412   uint16_t attr_list[2];
413 
414   /*
415    * On success, cb_data will be freed inside bta_gattc_sdp_callback,
416    * otherwise it will be freed within this function.
417    */
418   tBTA_GATTC_CB_DATA* cb_data =
419           (tBTA_GATTC_CB_DATA*)osi_malloc(sizeof(tBTA_GATTC_CB_DATA) + BTA_GATT_SDP_DB_SIZE);
420 
421   cb_data->p_sdp_db = (tSDP_DISCOVERY_DB*)(cb_data + 1);
422   attr_list[0] = ATTR_ID_SERVICE_CLASS_ID_LIST;
423   attr_list[1] = ATTR_ID_PROTOCOL_DESC_LIST;
424 
425   Uuid uuid = Uuid::From16Bit(UUID_PROTOCOL_ATT);
426   if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(
427               cb_data->p_sdp_db, BTA_GATT_SDP_DB_SIZE, 1, &uuid, num_attrs, attr_list)) {
428     log::warn("Unable to initialize SDP service discovery db peer:{}", p_server_cb->server_bda);
429   };
430 
431   if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2(
432               p_server_cb->server_bda, cb_data->p_sdp_db,
433               base::BindRepeating(bta_gattc_sdp_callback, cb_data))) {
434     log::warn("Unable to start SDP service search attribute request peer:{}",
435               p_server_cb->server_bda);
436     osi_free(cb_data);
437     return GATT_ERROR;
438   }
439 
440   cb_data->sdp_conn_id = conn_id;
441   return GATT_SUCCESS;
442 }
443 
444 /** operation completed */
bta_gattc_op_cmpl_during_discovery(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)445 void bta_gattc_op_cmpl_during_discovery(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
446   // Currently, there are two cases needed to be handled.
447   // 1. Read ext prop descriptor value after service discovery
448   // 2. Read db hash before starting service discovery
449   switch (p_clcb->request_during_discovery) {
450     case BTA_GATTC_DISCOVER_REQ_READ_EXT_PROP_DESC:
451       bta_gattc_read_ext_prop_desc_cmpl(p_clcb, &p_data->op_cmpl);
452       break;
453     case BTA_GATTC_DISCOVER_REQ_READ_DB_HASH:
454     case BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG: {
455       bool is_svc_chg =
456               (p_clcb->request_during_discovery == BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG);
457       bta_gattc_read_db_hash_cmpl(p_clcb, &p_data->op_cmpl, is_svc_chg);
458       break;
459     }
460     case BTA_GATTC_DISCOVER_REQ_NONE:
461     default:
462       break;
463   }
464 }
465 
466 /** callback function to GATT client stack */
bta_gattc_disc_res_cback(tCONN_ID conn_id,tGATT_DISC_TYPE disc_type,tGATT_DISC_RES * p_data)467 void bta_gattc_disc_res_cback(tCONN_ID conn_id, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data) {
468   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
469   tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(conn_id);
470 
471   if (!p_srvc_cb || !p_clcb || p_clcb->state != BTA_GATTC_DISCOVER_ST) {
472     return;
473   }
474 
475   switch (disc_type) {
476     case GATT_DISC_SRVC_ALL:
477     case GATT_DISC_SRVC_BY_UUID:
478       p_srvc_cb->pending_discovery.AddService(p_data->handle, p_data->value.group_value.e_handle,
479                                               p_data->value.group_value.service_type, true);
480       break;
481 
482     case GATT_DISC_INC_SRVC:
483       p_srvc_cb->pending_discovery.AddIncludedService(
484               p_data->handle, p_data->value.incl_service.service_type,
485               p_data->value.incl_service.s_handle, p_data->value.incl_service.e_handle);
486       break;
487 
488     case GATT_DISC_CHAR:
489       p_srvc_cb->pending_discovery.AddCharacteristic(
490               p_data->handle, p_data->value.dclr_value.val_handle,
491               p_data->value.dclr_value.char_uuid, p_data->value.dclr_value.char_prop);
492       break;
493 
494     case GATT_DISC_CHAR_DSCPT:
495       p_srvc_cb->pending_discovery.AddDescriptor(p_data->handle, p_data->type);
496       break;
497 
498     case GATT_DISC_MAX:
499     default:
500       log::error("Received illegal discovery item");
501       break;
502   }
503 }
504 
bta_gattc_disc_cmpl_cback(tCONN_ID conn_id,tGATT_DISC_TYPE disc_type,tGATT_STATUS status)505 void bta_gattc_disc_cmpl_cback(tCONN_ID conn_id, tGATT_DISC_TYPE disc_type, tGATT_STATUS status) {
506   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
507   tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(conn_id);
508 
509   if (p_clcb && (status != GATT_SUCCESS || p_clcb->status != GATT_SUCCESS)) {
510     if (status == GATT_SUCCESS) {
511       p_clcb->status = status;
512     }
513 
514     // if db out of sync is received, try to start service discovery if possible
515     if (status == GATT_DATABASE_OUT_OF_SYNC) {
516       if (p_srvc_cb && p_srvc_cb->srvc_disc_count < BTA_GATTC_DISCOVER_RETRY_COUNT) {
517         p_srvc_cb->srvc_disc_count++;
518         p_clcb->auto_update = BTA_GATTC_DISC_WAITING;
519       } else {
520         log::error("retry limit exceeds for db out of sync, conn_id={}", conn_id);
521       }
522     }
523 
524     bta_gattc_sm_execute(p_clcb, BTA_GATTC_DISCOVER_CMPL_EVT, NULL);
525     return;
526   }
527 
528   if (!p_srvc_cb) {
529     return;
530   }
531 
532   switch (disc_type) {
533     case GATT_DISC_SRVC_ALL:
534     case GATT_DISC_SRVC_BY_UUID:
535 // definition of all services are discovered, now it's time to discover
536 // their content
537 #if (BTA_GATT_DEBUG == TRUE)
538       bta_gattc_display_explore_record(p_srvc_cb->pending_discovery);
539 #endif
540       bta_gattc_explore_next_service(conn_id, p_srvc_cb);
541       break;
542 
543     case GATT_DISC_INC_SRVC: {
544       auto& service = p_srvc_cb->pending_discovery.CurrentlyExploredService();
545       /* start discovering characteristic */
546       if (GATTC_Discover(conn_id, GATT_DISC_CHAR, service.first, service.second) != GATT_SUCCESS) {
547         log::warn("Unable to discover GATT client conn_id:{}", conn_id);
548       }
549       break;
550     }
551 
552     case GATT_DISC_CHAR: {
553 #if (BTA_GATT_DEBUG == TRUE)
554       bta_gattc_display_explore_record(p_srvc_cb->pending_discovery);
555 #endif
556       bta_gattc_start_disc_char_dscp(conn_id, p_srvc_cb);
557       break;
558     }
559 
560     case GATT_DISC_CHAR_DSCPT:
561       /* start discovering next characteristic for char descriptor */
562       bta_gattc_start_disc_char_dscp(conn_id, p_srvc_cb);
563       break;
564 
565     case GATT_DISC_MAX:
566     default:
567       log::error("Received illegal discovery item");
568       break;
569   }
570 }
571 
572 /** search local cache for matching service record */
bta_gattc_search_service(tBTA_GATTC_CLCB * p_clcb,Uuid * p_uuid)573 void bta_gattc_search_service(tBTA_GATTC_CLCB* p_clcb, Uuid* p_uuid) {
574   for (const Service& service : p_clcb->p_srcb->gatt_database.Services()) {
575     if (p_uuid && *p_uuid != service.uuid) {
576       continue;
577     }
578 
579 #if (BTA_GATT_DEBUG == TRUE)
580     log::verbose("found service {} handle:{}", service.uuid, service.handle);
581 #endif
582     if (!p_clcb->p_rcb->p_cback) {
583       continue;
584     }
585 
586     tBTA_GATTC cb_data;
587     memset(&cb_data, 0, sizeof(tBTA_GATTC));
588     cb_data.srvc_res.conn_id = p_clcb->bta_conn_id;
589     cb_data.srvc_res.service_uuid.inst_id = service.handle;
590     cb_data.srvc_res.service_uuid.uuid = service.uuid;
591 
592     (*p_clcb->p_rcb->p_cback)(BTA_GATTC_SEARCH_RES_EVT, &cb_data);
593   }
594 }
595 
bta_gattc_get_services_srcb(tBTA_GATTC_SERV * p_srcb)596 const std::list<Service>* bta_gattc_get_services_srcb(tBTA_GATTC_SERV* p_srcb) {
597   if (!p_srcb || p_srcb->gatt_database.IsEmpty()) {
598     return NULL;
599   }
600 
601   return &p_srcb->gatt_database.Services();
602 }
603 
bta_gattc_get_services(tCONN_ID conn_id)604 const std::list<Service>* bta_gattc_get_services(tCONN_ID conn_id) {
605   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
606 
607   if (p_clcb == NULL) {
608     return NULL;
609   }
610 
611   tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
612 
613   return bta_gattc_get_services_srcb(p_srcb);
614 }
615 
bta_gattc_get_service_for_handle_srcb(tBTA_GATTC_SERV * p_srcb,uint16_t handle)616 const Service* bta_gattc_get_service_for_handle_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle) {
617   const std::list<Service>* services = bta_gattc_get_services_srcb(p_srcb);
618   if (services == NULL) {
619     return NULL;
620   }
621   return bta_gattc_find_matching_service(*services, handle);
622 }
623 
bta_gattc_get_service_for_handle(tCONN_ID conn_id,uint16_t handle)624 const Service* bta_gattc_get_service_for_handle(tCONN_ID conn_id, uint16_t handle) {
625   const std::list<Service>* services = bta_gattc_get_services(conn_id);
626   if (services == NULL) {
627     return NULL;
628   }
629 
630   return bta_gattc_find_matching_service(*services, handle);
631 }
632 
bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV * p_srcb,uint16_t handle)633 const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle) {
634   const Service* service = bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
635 
636   if (!service) {
637     return NULL;
638   }
639 
640   for (const Characteristic& charac : service->characteristics) {
641     if (handle == charac.value_handle) {
642       return &charac;
643     }
644   }
645 
646   return NULL;
647 }
648 
bta_gattc_get_characteristic(tCONN_ID conn_id,uint16_t handle)649 const Characteristic* bta_gattc_get_characteristic(tCONN_ID conn_id, uint16_t handle) {
650   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
651 
652   if (p_clcb == NULL) {
653     return NULL;
654   }
655 
656   tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
657   return bta_gattc_get_characteristic_srcb(p_srcb, handle);
658 }
659 
bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV * p_srcb,uint16_t handle)660 const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle) {
661   const Service* service = bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
662 
663   if (!service) {
664     return NULL;
665   }
666 
667   for (const Characteristic& charac : service->characteristics) {
668     for (const Descriptor& desc : charac.descriptors) {
669       if (handle == desc.handle) {
670         return &desc;
671       }
672     }
673   }
674 
675   return NULL;
676 }
677 
bta_gattc_get_descriptor(tCONN_ID conn_id,uint16_t handle)678 const Descriptor* bta_gattc_get_descriptor(tCONN_ID conn_id, uint16_t handle) {
679   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
680 
681   if (p_clcb == NULL) {
682     return NULL;
683   }
684 
685   tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
686   return bta_gattc_get_descriptor_srcb(p_srcb, handle);
687 }
688 
bta_gattc_get_owning_characteristic_srcb(tBTA_GATTC_SERV * p_srcb,uint16_t handle)689 const Characteristic* bta_gattc_get_owning_characteristic_srcb(tBTA_GATTC_SERV* p_srcb,
690                                                                uint16_t handle) {
691   const Service* service = bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
692 
693   if (!service) {
694     return NULL;
695   }
696 
697   for (const Characteristic& charac : service->characteristics) {
698     for (const Descriptor& desc : charac.descriptors) {
699       if (handle == desc.handle) {
700         return &charac;
701       }
702     }
703   }
704 
705   return NULL;
706 }
707 
bta_gattc_get_owning_characteristic(tCONN_ID conn_id,uint16_t handle)708 const Characteristic* bta_gattc_get_owning_characteristic(tCONN_ID conn_id, uint16_t handle) {
709   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
710   if (!p_clcb) {
711     return NULL;
712   }
713 
714   return bta_gattc_get_owning_characteristic_srcb(p_clcb->p_srcb, handle);
715 }
716 
717 /* request reading database hash */
bta_gattc_read_db_hash(tBTA_GATTC_CLCB * p_clcb,bool is_svc_chg)718 bool bta_gattc_read_db_hash(tBTA_GATTC_CLCB* p_clcb, bool is_svc_chg) {
719   tGATT_READ_PARAM read_param;
720   memset(&read_param, 0, sizeof(tGATT_READ_BY_TYPE));
721 
722   read_param.char_type.s_handle = 0x0001;
723   read_param.char_type.e_handle = 0xFFFF;
724   read_param.char_type.uuid = Uuid::From16Bit(GATT_UUID_DATABASE_HASH);
725   read_param.char_type.auth_req = GATT_AUTH_REQ_NONE;
726   tGATT_STATUS status = GATTC_Read(p_clcb->bta_conn_id, GATT_READ_BY_TYPE, &read_param);
727 
728   if (status != GATT_SUCCESS) {
729     return false;
730   }
731 
732   if (is_svc_chg) {
733     p_clcb->request_during_discovery = BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG;
734   } else {
735     p_clcb->request_during_discovery = BTA_GATTC_DISCOVER_REQ_READ_DB_HASH;
736   }
737 
738   return true;
739 }
740 
741 /* handle response of reading database hash */
bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_OP_CMPL * p_data,bool is_svc_chg)742 static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data,
743                                         bool is_svc_chg) {
744   uint8_t op = (uint8_t)p_data->op_code;
745   if (op != GATTC_OPTYPE_READ) {
746     log::verbose("op = {}", p_data->hdr.layer_specific);
747     return;
748   }
749   p_clcb->request_during_discovery = BTA_GATTC_DISCOVER_REQ_NONE;
750 
751   // run match flow only if the status is success
752   bool matched = false;
753   bool found = false;
754   if (p_data->status == GATT_SUCCESS) {
755     // start to compare local hash and remote hash
756     uint16_t len = p_data->p_cmpl->att_value.len;
757     uint8_t* data = p_data->p_cmpl->att_value.value;
758 
759     Octet16 remote_hash;
760     if (len == remote_hash.max_size()) {
761       std::copy(data, data + len, remote_hash.begin());
762 
763       Octet16 local_hash = p_clcb->p_srcb->gatt_database.Hash();
764       matched = (local_hash == remote_hash);
765 
766       log::debug("lhash={}", base::HexEncode(local_hash.data(), local_hash.size()));
767       log::debug("rhash={}", base::HexEncode(remote_hash.data(), remote_hash.size()));
768 
769       if (!matched) {
770         gatt::Database db = bta_gattc_hash_load(remote_hash);
771         if (!db.IsEmpty()) {
772           p_clcb->p_srcb->gatt_database = db;
773           found = true;
774         }
775         // If the device is trusted, link addr file to correct hash file
776         if (found && (btm_sec_is_a_bonded_dev(p_clcb->p_srcb->server_bda))) {
777           bta_gattc_cache_link(p_clcb->p_srcb->server_bda, remote_hash);
778         }
779       }
780     }
781   } else {
782     // Only load cache for trusted device if no database hash on server side.
783     // If is_svc_chg is true, do not read the existing cache.
784     bool is_a_bonded_dev = btm_sec_is_a_bonded_dev(p_clcb->p_srcb->server_bda);
785     if (!is_svc_chg && is_a_bonded_dev) {
786       gatt::Database db = bta_gattc_cache_load(p_clcb->p_srcb->server_bda);
787       if (!db.IsEmpty()) {
788         p_clcb->p_srcb->gatt_database = db;
789         found = true;
790       }
791       log::debug("load cache directly, result={}", found);
792     } else {
793       log::debug("skip read cache, is_svc_chg={}, is_a_bonded_dev={}", is_svc_chg, is_a_bonded_dev);
794     }
795   }
796 
797   if (matched) {
798     log::debug("hash is the same, skip service discovery");
799     p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE;
800     bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS);
801   } else {
802     if (found) {
803       log::debug("hash found in cache, skip service discovery");
804 
805 #if (BTA_GATT_DEBUG == TRUE)
806       bta_gattc_display_cache_server(p_clcb->p_srcb->gatt_database);
807 #endif
808 
809       p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE;
810       bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS);
811     } else {
812       log::debug("hash is not the same, start service discovery");
813       bta_gattc_start_discover_internal(p_clcb);
814     }
815   }
816 }
817 
818 /* handle response of reading extended properties descriptor */
bta_gattc_read_ext_prop_desc_cmpl(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_OP_CMPL * p_data)819 static void bta_gattc_read_ext_prop_desc_cmpl(tBTA_GATTC_CLCB* p_clcb,
820                                               const tBTA_GATTC_OP_CMPL* p_data) {
821   uint8_t op = (uint8_t)p_data->op_code;
822   if (op != GATTC_OPTYPE_READ) {
823     log::verbose("op = {}", p_data->hdr.layer_specific);
824     return;
825   }
826 
827   if (!p_clcb->disc_active) {
828     log::verbose("not active in discover state");
829     return;
830   }
831   p_clcb->request_during_discovery = BTA_GATTC_DISCOVER_REQ_NONE;
832 
833   tBTA_GATTC_SERV* p_srvc_cb = p_clcb->p_srcb;
834   const uint8_t status = p_data->status;
835 
836   if (status == GATT_REQ_NOT_SUPPORTED && !p_srvc_cb->read_multiple_not_supported) {
837     // can't do "read multiple request", fall back to "read request"
838     p_srvc_cb->read_multiple_not_supported = true;
839     bta_gattc_explore_next_service(p_clcb->bta_conn_id, p_srvc_cb);
840     return;
841   }
842 
843   if (status != GATT_SUCCESS) {
844     log::warn("Discovery on server failed: 0x{:x}", status);
845     bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_ERROR);
846     return;
847   }
848 
849   const tGATT_VALUE& att_value = p_data->p_cmpl->att_value;
850   if (p_srvc_cb->read_multiple_not_supported && att_value.len != 2) {
851     // Just one Characteristic Extended Properties value at a time in Read
852     // Response
853     log::warn("Read Response should be just 2 bytes!");
854     bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_INVALID_PDU);
855     return;
856   }
857 
858   // Parsing is same for "Read Multiple Response", and for "Read Response"
859   const uint8_t* p = att_value.value;
860   std::vector<uint16_t> value_of_descriptors;
861   while (p < att_value.value + att_value.len) {
862     uint16_t extended_properties;
863     STREAM_TO_UINT16(extended_properties, p);
864     value_of_descriptors.push_back(extended_properties);
865   }
866 
867   bool ret = p_srvc_cb->pending_discovery.SetValueOfDescriptors(value_of_descriptors);
868   if (!ret) {
869     log::warn("Problem setting Extended Properties descriptors values");
870     bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_ERROR);
871     return;
872   }
873 
874   // Continue service discovery
875   bta_gattc_explore_next_service(p_clcb->bta_conn_id, p_srvc_cb);
876 }
877 
878 /*******************************************************************************
879  *
880  * Function         bta_gattc_fill_gatt_db_el
881  *
882  * Description      fill a btgatt_db_element_t value
883  *
884  * Returns          None.
885  *
886  ******************************************************************************/
bta_gattc_fill_gatt_db_el(btgatt_db_element_t * p_attr,bt_gatt_db_attribute_type_t type,uint16_t att_handle,uint16_t s_handle,uint16_t e_handle,uint16_t id,const Uuid & uuid,uint8_t prop)887 void bta_gattc_fill_gatt_db_el(btgatt_db_element_t* p_attr, bt_gatt_db_attribute_type_t type,
888                                uint16_t att_handle, uint16_t s_handle, uint16_t e_handle,
889                                uint16_t id, const Uuid& uuid, uint8_t prop) {
890   p_attr->type = type;
891   p_attr->attribute_handle = att_handle;
892   p_attr->start_handle = s_handle;
893   p_attr->end_handle = e_handle;
894   p_attr->id = id;
895   p_attr->properties = prop;
896 
897   // Permissions are not discoverable using the attribute protocol.
898   // Core 5.0, Part F, 3.2.5 Attribute Permissions
899   p_attr->permissions = 0;
900   p_attr->uuid = uuid;
901 }
902 
903 /*******************************************************************************
904  * Returns          number of elements inside db from start_handle to end_handle
905  ******************************************************************************/
bta_gattc_get_db_size(const std::list<Service> & services,uint16_t start_handle,uint16_t end_handle)906 static size_t bta_gattc_get_db_size(const std::list<Service>& services, uint16_t start_handle,
907                                     uint16_t end_handle) {
908   if (services.empty()) {
909     return 0;
910   }
911 
912   size_t db_size = 0;
913 
914   for (const Service& service : services) {
915     if (service.handle < start_handle) {
916       continue;
917     }
918 
919     if (service.end_handle > end_handle) {
920       break;
921     }
922 
923     db_size++;
924 
925     for (const Characteristic& charac : service.characteristics) {
926       db_size++;
927 
928       db_size += charac.descriptors.size();
929     }
930 
931     db_size += service.included_services.size();
932   }
933 
934   return db_size;
935 }
936 
937 /*******************************************************************************
938  *
939  * Function         bta_gattc_get_gatt_db_impl
940  *
941  * Description      copy the server GATT database into db parameter.
942  *
943  * Parameters       p_srvc_cb: server.
944  *                  db: output parameter which will contain GATT database copy.
945  *                      Caller is responsible for freeing it.
946  *                  count: output parameter which will contain number of
947  *                  elements in database.
948  *
949  * Returns          None.
950  *
951  ******************************************************************************/
bta_gattc_get_gatt_db_impl(tBTA_GATTC_SERV * p_srvc_cb,uint16_t start_handle,uint16_t end_handle,btgatt_db_element_t ** db,int * count)952 static void bta_gattc_get_gatt_db_impl(tBTA_GATTC_SERV* p_srvc_cb, uint16_t start_handle,
953                                        uint16_t end_handle, btgatt_db_element_t** db, int* count) {
954   log::verbose("start_handle 0x{:04x}, end_handle 0x{:04x}", start_handle, end_handle);
955 
956   if (p_srvc_cb->gatt_database.IsEmpty()) {
957     *count = 0;
958     *db = NULL;
959     return;
960   }
961 
962   size_t db_size =
963           bta_gattc_get_db_size(p_srvc_cb->gatt_database.Services(), start_handle, end_handle);
964 
965   void* buffer = osi_malloc(db_size * sizeof(btgatt_db_element_t));
966   btgatt_db_element_t* curr_db_attr = (btgatt_db_element_t*)buffer;
967 
968   for (const Service& service : p_srvc_cb->gatt_database.Services()) {
969     if (service.handle < start_handle) {
970       continue;
971     }
972 
973     if (service.end_handle > end_handle) {
974       break;
975     }
976 
977     bta_gattc_fill_gatt_db_el(
978             curr_db_attr,
979             service.is_primary ? BTGATT_DB_PRIMARY_SERVICE : BTGATT_DB_SECONDARY_SERVICE,
980             0 /* att_handle */, service.handle, service.end_handle, service.handle, service.uuid,
981             0 /* prop */);
982     curr_db_attr++;
983 
984     for (const Characteristic& charac : service.characteristics) {
985       bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_CHARACTERISTIC, charac.value_handle,
986                                 0 /* s_handle */, 0 /* e_handle */, charac.value_handle,
987                                 charac.uuid, charac.properties);
988       btgatt_db_element_t* characteristic = curr_db_attr;
989       curr_db_attr++;
990 
991       for (const Descriptor& desc : charac.descriptors) {
992         bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_DESCRIPTOR, desc.handle, 0 /* s_handle */,
993                                   0 /* e_handle */, desc.handle, desc.uuid, 0 /* property */);
994 
995         if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP)) {
996           characteristic->extended_properties = desc.characteristic_extended_properties;
997         }
998         curr_db_attr++;
999       }
1000     }
1001 
1002     for (const IncludedService& p_isvc : service.included_services) {
1003       bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_INCLUDED_SERVICE, p_isvc.handle,
1004                                 p_isvc.start_handle, 0 /* e_handle */, p_isvc.handle, p_isvc.uuid,
1005                                 0 /* property */);
1006       curr_db_attr++;
1007     }
1008   }
1009 
1010   *db = (btgatt_db_element_t*)buffer;
1011   *count = db_size;
1012 }
1013 
1014 /*******************************************************************************
1015  *
1016  * Function         bta_gattc_get_gatt_db
1017  *
1018  * Description      copy the server GATT database into db parameter.
1019  *
1020  * Parameters       conn_id: connection ID which identify the server.
1021  *                  db: output parameter which will contain GATT database copy.
1022  *                      Caller is responsible for freeing it.
1023  *                  count: number of elements in database.
1024  *
1025  * Returns          None.
1026  *
1027  ******************************************************************************/
bta_gattc_get_gatt_db(tCONN_ID conn_id,uint16_t start_handle,uint16_t end_handle,btgatt_db_element_t ** db,int * count)1028 void bta_gattc_get_gatt_db(tCONN_ID conn_id, uint16_t start_handle, uint16_t end_handle,
1029                            btgatt_db_element_t** db, int* count) {
1030   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
1031 
1032   log::info("");
1033   if (p_clcb == NULL) {
1034     log::error("Unknown conn_id=0x{:x}", conn_id);
1035     return;
1036   }
1037 
1038   if (p_clcb->state != BTA_GATTC_CONN_ST) {
1039     log::error("server cache not available, CLCB state={}", p_clcb->state);
1040     return;
1041   }
1042 
1043   if (!p_clcb->p_srcb || p_clcb->p_srcb->pending_discovery.InProgress() ||
1044       p_clcb->p_srcb->gatt_database.IsEmpty()) {
1045     log::error("No server cache available");
1046     return;
1047   }
1048 
1049   bta_gattc_get_gatt_db_impl(p_clcb->p_srcb, start_handle, end_handle, db, count);
1050 }
1051