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