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