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