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