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