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 "bt_target.h"
29 
30 #include <errno.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <sstream>
35 
36 #include "bt_common.h"
37 #include "bta_gattc_int.h"
38 #include "bta_sys.h"
39 #include "btm_api.h"
40 #include "btm_ble_api.h"
41 #include "btm_int.h"
42 #include "database.h"
43 #include "database_builder.h"
44 #include "osi/include/log.h"
45 #include "osi/include/osi.h"
46 #include "sdp_api.h"
47 #include "sdpdefs.h"
48 #include "utl.h"
49 
50 using base::StringPrintf;
51 using bluetooth::Uuid;
52 using gatt::Characteristic;
53 using gatt::Database;
54 using gatt::DatabaseBuilder;
55 using gatt::Descriptor;
56 using gatt::IncludedService;
57 using gatt::Service;
58 using gatt::StoredAttribute;
59 
60 static void bta_gattc_cache_write(const RawAddress& server_bda,
61                                   const std::vector<StoredAttribute>& attr);
62 static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id,
63                                                tBTA_GATTC_SERV* p_server_cb);
64 const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb,
65                                                 uint16_t handle);
66 const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb,
67                                                         uint16_t handle);
68 static void bta_gattc_explore_srvc_finished(uint16_t conn_id,
69                                             tBTA_GATTC_SERV* p_srvc_cb);
70 
71 #define BTA_GATT_SDP_DB_SIZE 4096
72 
73 #define GATT_CACHE_PREFIX "/data/misc/bluetooth/gatt_cache_"
74 #define GATT_CACHE_VERSION 5
75 
bta_gattc_generate_cache_file_name(char * buffer,size_t buffer_len,const RawAddress & bda)76 static void bta_gattc_generate_cache_file_name(char* buffer, size_t buffer_len,
77                                                const RawAddress& bda) {
78   snprintf(buffer, buffer_len, "%s%02x%02x%02x%02x%02x%02x", GATT_CACHE_PREFIX,
79            bda.address[0], bda.address[1], bda.address[2], bda.address[3],
80            bda.address[4], bda.address[5]);
81 }
82 
83 /*****************************************************************************
84  *  Constants and data types
85  ****************************************************************************/
86 
87 typedef struct {
88   tSDP_DISCOVERY_DB* p_sdp_db;
89   uint16_t sdp_conn_id;
90 } tBTA_GATTC_CB_DATA;
91 
92 #if (BTA_GATT_DEBUG == TRUE)
93 /* utility functions */
94 
95 /* debug function to display the server cache */
bta_gattc_display_cache_server(const Database & database)96 static void bta_gattc_display_cache_server(const Database& database) {
97   LOG(INFO) << "<================Start Server Cache =============>";
98   std::istringstream iss(database.ToString());
99   for (std::string line; std::getline(iss, line);) {
100     LOG(INFO) << line;
101   }
102   LOG(INFO) << "<================End Server Cache =============>";
103 }
104 
105 /** debug function to display the exploration list */
bta_gattc_display_explore_record(const DatabaseBuilder & database)106 static void bta_gattc_display_explore_record(const DatabaseBuilder& database) {
107   LOG(INFO) << "<================Start Explore Queue =============>";
108   std::istringstream iss(database.ToString());
109   for (std::string line; std::getline(iss, line);) {
110     LOG(INFO) << line;
111   }
112   LOG(INFO) << "<================ End Explore Queue =============>";
113 }
114 #endif /* BTA_GATT_DEBUG == TRUE */
115 
116 /** Initialize the database cache and discovery related resources */
bta_gattc_init_cache(tBTA_GATTC_SERV * p_srvc_cb)117 void bta_gattc_init_cache(tBTA_GATTC_SERV* p_srvc_cb) {
118   p_srvc_cb->gatt_database = gatt::Database();
119   p_srvc_cb->pending_discovery.Clear();
120 }
121 
bta_gattc_find_matching_service(const std::list<Service> & services,uint16_t handle)122 const Service* bta_gattc_find_matching_service(
123     const std::list<Service>& services, uint16_t handle) {
124   for (const Service& service : services) {
125     if (handle >= service.handle && handle <= service.end_handle)
126       return &service;
127   }
128 
129   return nullptr;
130 }
131 
132 /** Start primary service discovery */
bta_gattc_discover_pri_service(uint16_t conn_id,tBTA_GATTC_SERV * p_server_cb,uint8_t disc_type)133 tGATT_STATUS bta_gattc_discover_pri_service(uint16_t conn_id,
134                                             tBTA_GATTC_SERV* p_server_cb,
135                                             uint8_t disc_type) {
136   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
137   if (!p_clcb) return GATT_ERROR;
138 
139   if (p_clcb->transport == BTA_TRANSPORT_LE) {
140     return GATTC_Discover(conn_id, disc_type, 0x0001, 0xFFFF);
141   }
142 
143   // only for Classic transport
144   return bta_gattc_sdp_service_disc(conn_id, p_server_cb);
145 }
146 
147 /** start exploring next service, or finish discovery if no more services left
148  */
bta_gattc_explore_next_service(uint16_t conn_id,tBTA_GATTC_SERV * p_srvc_cb)149 static void bta_gattc_explore_next_service(uint16_t conn_id,
150                                            tBTA_GATTC_SERV* p_srvc_cb) {
151   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
152   if (!p_clcb) {
153     LOG(ERROR) << "unknown conn_id=" << loghex(conn_id);
154     return;
155   }
156 
157   if (!p_srvc_cb->pending_discovery.StartNextServiceExploration()) {
158     bta_gattc_explore_srvc_finished(conn_id, p_srvc_cb);
159     return;
160   }
161 
162   const auto& service = p_srvc_cb->pending_discovery.CurrentlyExploredService();
163   VLOG(1) << "Start service discovery";
164 
165   /* start discovering included services */
166   GATTC_Discover(conn_id, GATT_DISC_INC_SRVC, service.first, service.second);
167 }
168 
bta_gattc_explore_srvc_finished(uint16_t conn_id,tBTA_GATTC_SERV * p_srvc_cb)169 static void bta_gattc_explore_srvc_finished(uint16_t conn_id,
170                                             tBTA_GATTC_SERV* p_srvc_cb) {
171   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
172   if (!p_clcb) {
173     LOG(ERROR) << "unknown conn_id=" << loghex(conn_id);
174     return;
175   }
176 
177   /* no service found at all, the end of server discovery*/
178   LOG(INFO) << __func__ << ": service discovery finished";
179 
180   p_srvc_cb->gatt_database = p_srvc_cb->pending_discovery.Build();
181 
182 #if (BTA_GATT_DEBUG == TRUE)
183   bta_gattc_display_cache_server(p_srvc_cb->gatt_database);
184 #endif
185   /* save cache to NV */
186   p_clcb->p_srcb->state = BTA_GATTC_SERV_SAVE;
187 
188   if (btm_sec_is_a_bonded_dev(p_srvc_cb->server_bda)) {
189     bta_gattc_cache_write(p_clcb->p_srcb->server_bda,
190                           p_clcb->p_srcb->gatt_database.Serialize());
191   }
192 
193   bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS);
194 }
195 
196 /** Start discovery for characteristic descriptor */
bta_gattc_start_disc_char_dscp(uint16_t conn_id,tBTA_GATTC_SERV * p_srvc_cb)197 void bta_gattc_start_disc_char_dscp(uint16_t conn_id,
198                                     tBTA_GATTC_SERV* p_srvc_cb) {
199   VLOG(1) << "starting discover characteristics descriptor";
200 
201   std::pair<uint16_t, uint16_t> range =
202       p_srvc_cb->pending_discovery.NextDescriptorRangeToExplore();
203   if (range == DatabaseBuilder::EXPLORE_END) {
204     goto descriptor_discovery_done;
205   }
206 
207   if (GATTC_Discover(conn_id, GATT_DISC_CHAR_DSCPT, range.first,
208                      range.second) != 0) {
209     goto descriptor_discovery_done;
210   }
211   return;
212 
213 descriptor_discovery_done:
214   /* all characteristic has been explored, start with next service if any */
215   DVLOG(3) << "all characteristics explored";
216 
217   bta_gattc_explore_next_service(conn_id, p_srvc_cb);
218   return;
219 }
220 
221 /* Process the discovery result from sdp */
bta_gattc_sdp_callback(uint16_t sdp_status,void * user_data)222 void bta_gattc_sdp_callback(uint16_t sdp_status, void* user_data) {
223   tBTA_GATTC_CB_DATA* cb_data = (tBTA_GATTC_CB_DATA*)user_data;
224   tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(cb_data->sdp_conn_id);
225 
226   if (p_srvc_cb == nullptr) {
227     LOG(ERROR) << "GATT service discovery is done on unknown connection";
228     /* allocated in bta_gattc_sdp_service_disc */
229     osi_free(cb_data);
230     return;
231   }
232 
233   if ((sdp_status != SDP_SUCCESS) && (sdp_status != SDP_DB_FULL)) {
234     bta_gattc_explore_srvc_finished(cb_data->sdp_conn_id, p_srvc_cb);
235 
236     /* allocated in bta_gattc_sdp_service_disc */
237     osi_free(cb_data);
238     return;
239   }
240 
241   bool no_pending_disc = !p_srvc_cb->pending_discovery.InProgress();
242 
243   tSDP_DISC_REC* p_sdp_rec = SDP_FindServiceInDb(cb_data->p_sdp_db, 0, nullptr);
244   while (p_sdp_rec != nullptr) {
245     /* find a service record, report it */
246     Uuid service_uuid;
247     if (!SDP_FindServiceUUIDInRec(p_sdp_rec, &service_uuid)) continue;
248 
249     tSDP_PROTOCOL_ELEM pe;
250     if (!SDP_FindProtocolListElemInRec(p_sdp_rec, UUID_PROTOCOL_ATT, &pe))
251       continue;
252 
253     uint16_t start_handle = (uint16_t)pe.params[0];
254     uint16_t end_handle = (uint16_t)pe.params[1];
255 
256 #if (BTA_GATT_DEBUG == TRUE)
257     VLOG(1) << "Found ATT service uuid=" << service_uuid
258             << ", s_handle=" << loghex(start_handle)
259             << ", e_handle=" << loghex(end_handle);
260 #endif
261 
262     if (!GATT_HANDLE_IS_VALID(start_handle) ||
263         !GATT_HANDLE_IS_VALID(end_handle)) {
264       LOG(ERROR) << "invalid start_handle=" << loghex(start_handle)
265                  << ", end_handle=" << loghex(end_handle);
266       continue;
267     }
268 
269     /* discover services result, add services into a service list */
270     p_srvc_cb->pending_discovery.AddService(start_handle, end_handle,
271                                             service_uuid, true);
272 
273     p_sdp_rec = SDP_FindServiceInDb(cb_data->p_sdp_db, 0, p_sdp_rec);
274   }
275 
276   // If discovery is already pending, no need to call
277   // bta_gattc_explore_next_service. Next service will be picked up to discovery
278   // once current one is discovered. If discovery is not pending, start one
279   if (no_pending_disc) {
280     bta_gattc_explore_next_service(cb_data->sdp_conn_id, p_srvc_cb);
281   }
282 
283   /* allocated in bta_gattc_sdp_service_disc */
284   osi_free(cb_data);
285 }
286 
287 /* Start DSP Service Discovery */
bta_gattc_sdp_service_disc(uint16_t conn_id,tBTA_GATTC_SERV * p_server_cb)288 static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id,
289                                                tBTA_GATTC_SERV* p_server_cb) {
290   uint16_t num_attrs = 2;
291   uint16_t attr_list[2];
292 
293   /*
294    * On success, cb_data will be freed inside bta_gattc_sdp_callback,
295    * otherwise it will be freed within this function.
296    */
297   tBTA_GATTC_CB_DATA* cb_data = (tBTA_GATTC_CB_DATA*)osi_malloc(
298       sizeof(tBTA_GATTC_CB_DATA) + BTA_GATT_SDP_DB_SIZE);
299 
300   cb_data->p_sdp_db = (tSDP_DISCOVERY_DB*)(cb_data + 1);
301   attr_list[0] = ATTR_ID_SERVICE_CLASS_ID_LIST;
302   attr_list[1] = ATTR_ID_PROTOCOL_DESC_LIST;
303 
304   Uuid uuid = Uuid::From16Bit(UUID_PROTOCOL_ATT);
305   SDP_InitDiscoveryDb(cb_data->p_sdp_db, BTA_GATT_SDP_DB_SIZE, 1, &uuid,
306                       num_attrs, attr_list);
307 
308   if (!SDP_ServiceSearchAttributeRequest2(p_server_cb->server_bda,
309                                           cb_data->p_sdp_db,
310                                           &bta_gattc_sdp_callback, cb_data)) {
311     osi_free(cb_data);
312     return GATT_ERROR;
313   }
314 
315   cb_data->sdp_conn_id = conn_id;
316   return GATT_SUCCESS;
317 }
318 
319 /** 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)320 void bta_gattc_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type,
321                               tGATT_DISC_RES* p_data) {
322   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
323   tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(conn_id);
324 
325   if (!p_srvc_cb || !p_clcb || p_clcb->state != BTA_GATTC_DISCOVER_ST) return;
326 
327   switch (disc_type) {
328     case GATT_DISC_SRVC_ALL:
329     case GATT_DISC_SRVC_BY_UUID:
330       p_srvc_cb->pending_discovery.AddService(
331           p_data->handle, p_data->value.group_value.e_handle,
332           p_data->value.group_value.service_type, true);
333       break;
334 
335     case GATT_DISC_INC_SRVC:
336       p_srvc_cb->pending_discovery.AddIncludedService(
337           p_data->handle, p_data->value.incl_service.service_type,
338           p_data->value.incl_service.s_handle,
339           p_data->value.incl_service.e_handle);
340       break;
341 
342     case GATT_DISC_CHAR:
343       p_srvc_cb->pending_discovery.AddCharacteristic(
344           p_data->handle, p_data->value.dclr_value.val_handle,
345           p_data->value.dclr_value.char_uuid,
346           p_data->value.dclr_value.char_prop);
347       break;
348 
349     case GATT_DISC_CHAR_DSCPT:
350       p_srvc_cb->pending_discovery.AddDescriptor(p_data->handle, p_data->type);
351       break;
352   }
353 }
354 
bta_gattc_disc_cmpl_cback(uint16_t conn_id,tGATT_DISC_TYPE disc_type,tGATT_STATUS status)355 void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type,
356                                tGATT_STATUS status) {
357   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
358 
359   if (p_clcb && (status != GATT_SUCCESS || p_clcb->status != GATT_SUCCESS)) {
360     if (status == GATT_SUCCESS) p_clcb->status = status;
361     bta_gattc_sm_execute(p_clcb, BTA_GATTC_DISCOVER_CMPL_EVT, NULL);
362     return;
363   }
364 
365   tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(conn_id);
366   if (!p_srvc_cb) return;
367 
368   switch (disc_type) {
369     case GATT_DISC_SRVC_ALL:
370     case GATT_DISC_SRVC_BY_UUID:
371 // definition of all services are discovered, now it's time to discover
372 // their content
373 #if (BTA_GATT_DEBUG == TRUE)
374       bta_gattc_display_explore_record(p_srvc_cb->pending_discovery);
375 #endif
376       bta_gattc_explore_next_service(conn_id, p_srvc_cb);
377       break;
378 
379     case GATT_DISC_INC_SRVC: {
380       auto& service = p_srvc_cb->pending_discovery.CurrentlyExploredService();
381       /* start discovering characteristic */
382       GATTC_Discover(conn_id, GATT_DISC_CHAR, service.first, service.second);
383       break;
384     }
385 
386     case GATT_DISC_CHAR: {
387 #if (BTA_GATT_DEBUG == TRUE)
388       bta_gattc_display_explore_record(p_srvc_cb->pending_discovery);
389 #endif
390       bta_gattc_start_disc_char_dscp(conn_id, p_srvc_cb);
391       break;
392     }
393 
394     case GATT_DISC_CHAR_DSCPT:
395       /* start discovering next characteristic for char descriptor */
396       bta_gattc_start_disc_char_dscp(conn_id, p_srvc_cb);
397       break;
398   }
399 }
400 
401 /** search local cache for matching service record */
bta_gattc_search_service(tBTA_GATTC_CLCB * p_clcb,Uuid * p_uuid)402 void bta_gattc_search_service(tBTA_GATTC_CLCB* p_clcb, Uuid* p_uuid) {
403   for (const Service& service : p_clcb->p_srcb->gatt_database.Services()) {
404     if (p_uuid && *p_uuid != service.uuid) continue;
405 
406 #if (BTA_GATT_DEBUG == TRUE)
407     VLOG(1) << __func__ << "found service " << service.uuid
408             << " handle:" << +service.handle;
409 #endif
410     if (!p_clcb->p_rcb->p_cback) continue;
411 
412     tBTA_GATTC cb_data;
413     memset(&cb_data, 0, sizeof(tBTA_GATTC));
414     cb_data.srvc_res.conn_id = p_clcb->bta_conn_id;
415     cb_data.srvc_res.service_uuid.inst_id = service.handle;
416     cb_data.srvc_res.service_uuid.uuid = service.uuid;
417 
418     (*p_clcb->p_rcb->p_cback)(BTA_GATTC_SEARCH_RES_EVT, &cb_data);
419   }
420 }
421 
bta_gattc_get_services_srcb(tBTA_GATTC_SERV * p_srcb)422 const std::list<Service>* bta_gattc_get_services_srcb(tBTA_GATTC_SERV* p_srcb) {
423   if (!p_srcb || p_srcb->gatt_database.IsEmpty()) return NULL;
424 
425   return &p_srcb->gatt_database.Services();
426 }
427 
bta_gattc_get_services(uint16_t conn_id)428 const std::list<Service>* bta_gattc_get_services(uint16_t conn_id) {
429   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
430 
431   if (p_clcb == NULL) return NULL;
432 
433   tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
434 
435   return bta_gattc_get_services_srcb(p_srcb);
436 }
437 
bta_gattc_get_service_for_handle_srcb(tBTA_GATTC_SERV * p_srcb,uint16_t handle)438 const Service* bta_gattc_get_service_for_handle_srcb(tBTA_GATTC_SERV* p_srcb,
439                                                      uint16_t handle) {
440   const std::list<Service>* services = bta_gattc_get_services_srcb(p_srcb);
441   if (services == NULL) return NULL;
442   return bta_gattc_find_matching_service(*services, handle);
443 }
444 
bta_gattc_get_service_for_handle(uint16_t conn_id,uint16_t handle)445 const Service* bta_gattc_get_service_for_handle(uint16_t conn_id,
446                                                 uint16_t handle) {
447   const std::list<Service>* services = bta_gattc_get_services(conn_id);
448   if (services == NULL) return NULL;
449 
450   return bta_gattc_find_matching_service(*services, handle);
451 }
452 
bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV * p_srcb,uint16_t handle)453 const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb,
454                                                         uint16_t handle) {
455   const Service* service =
456       bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
457 
458   if (!service) return NULL;
459 
460   for (const Characteristic& charac : service->characteristics) {
461     if (handle == charac.value_handle) return &charac;
462   }
463 
464   return NULL;
465 }
466 
bta_gattc_get_characteristic(uint16_t conn_id,uint16_t handle)467 const Characteristic* bta_gattc_get_characteristic(uint16_t conn_id,
468                                                    uint16_t handle) {
469   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
470 
471   if (p_clcb == NULL) return NULL;
472 
473   tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
474   return bta_gattc_get_characteristic_srcb(p_srcb, handle);
475 }
476 
bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV * p_srcb,uint16_t handle)477 const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb,
478                                                 uint16_t handle) {
479   const Service* service =
480       bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
481 
482   if (!service) {
483     return NULL;
484   }
485 
486   for (const Characteristic& charac : service->characteristics) {
487     for (const Descriptor& desc : charac.descriptors) {
488       if (handle == desc.handle) return &desc;
489     }
490   }
491 
492   return NULL;
493 }
494 
bta_gattc_get_descriptor(uint16_t conn_id,uint16_t handle)495 const Descriptor* bta_gattc_get_descriptor(uint16_t conn_id, uint16_t handle) {
496   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
497 
498   if (p_clcb == NULL) return NULL;
499 
500   tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
501   return bta_gattc_get_descriptor_srcb(p_srcb, handle);
502 }
503 
bta_gattc_get_owning_characteristic_srcb(tBTA_GATTC_SERV * p_srcb,uint16_t handle)504 const Characteristic* bta_gattc_get_owning_characteristic_srcb(
505     tBTA_GATTC_SERV* p_srcb, uint16_t handle) {
506   const Service* service =
507       bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
508 
509   if (!service) return NULL;
510 
511   for (const Characteristic& charac : service->characteristics) {
512     for (const Descriptor& desc : charac.descriptors) {
513       if (handle == desc.handle) return &charac;
514     }
515   }
516 
517   return NULL;
518 }
519 
bta_gattc_get_owning_characteristic(uint16_t conn_id,uint16_t handle)520 const Characteristic* bta_gattc_get_owning_characteristic(uint16_t conn_id,
521                                                           uint16_t handle) {
522   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
523   if (!p_clcb) return NULL;
524 
525   return bta_gattc_get_owning_characteristic_srcb(p_clcb->p_srcb, handle);
526 }
527 
528 /*******************************************************************************
529  *
530  * Function         bta_gattc_fill_gatt_db_el
531  *
532  * Description      fill a btgatt_db_element_t value
533  *
534  * Returns          None.
535  *
536  ******************************************************************************/
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)537 void bta_gattc_fill_gatt_db_el(btgatt_db_element_t* p_attr,
538                                bt_gatt_db_attribute_type_t type,
539                                uint16_t att_handle, uint16_t s_handle,
540                                uint16_t e_handle, uint16_t id, const Uuid& uuid,
541                                uint8_t prop) {
542   p_attr->type = type;
543   p_attr->attribute_handle = att_handle;
544   p_attr->start_handle = s_handle;
545   p_attr->end_handle = e_handle;
546   p_attr->id = id;
547   p_attr->properties = prop;
548 
549   // Permissions are not discoverable using the attribute protocol.
550   // Core 5.0, Part F, 3.2.5 Attribute Permissions
551   p_attr->permissions = 0;
552   p_attr->uuid = uuid;
553 }
554 
555 /*******************************************************************************
556  * Returns          number of elements inside db from start_handle to end_handle
557  ******************************************************************************/
bta_gattc_get_db_size(const std::list<Service> & services,uint16_t start_handle,uint16_t end_handle)558 static size_t bta_gattc_get_db_size(const std::list<Service>& services,
559                                     uint16_t start_handle,
560                                     uint16_t end_handle) {
561   if (services.empty()) return 0;
562 
563   size_t db_size = 0;
564 
565   for (const Service& service : services) {
566     if (service.handle < start_handle) continue;
567 
568     if (service.end_handle > end_handle) break;
569 
570     db_size++;
571 
572     for (const Characteristic& charac : service.characteristics) {
573       db_size++;
574 
575       db_size += charac.descriptors.size();
576     }
577 
578     db_size += service.included_services.size();
579   }
580 
581   return db_size;
582 }
583 
584 /*******************************************************************************
585  *
586  * Function         bta_gattc_get_gatt_db_impl
587  *
588  * Description      copy the server GATT database into db parameter.
589  *
590  * Parameters       p_srvc_cb: server.
591  *                  db: output parameter which will contain GATT database copy.
592  *                      Caller is responsible for freeing it.
593  *                  count: output parameter which will contain number of
594  *                  elements in database.
595  *
596  * Returns          None.
597  *
598  ******************************************************************************/
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)599 static void bta_gattc_get_gatt_db_impl(tBTA_GATTC_SERV* p_srvc_cb,
600                                        uint16_t start_handle,
601                                        uint16_t end_handle,
602                                        btgatt_db_element_t** db, int* count) {
603   VLOG(1) << __func__
604           << StringPrintf(": start_handle 0x%04x, end_handle 0x%04x",
605                           start_handle, end_handle);
606 
607   if (p_srvc_cb->gatt_database.IsEmpty()) {
608     *count = 0;
609     *db = NULL;
610     return;
611   }
612 
613   size_t db_size = bta_gattc_get_db_size(p_srvc_cb->gatt_database.Services(),
614                                          start_handle, end_handle);
615 
616   void* buffer = osi_malloc(db_size * sizeof(btgatt_db_element_t));
617   btgatt_db_element_t* curr_db_attr = (btgatt_db_element_t*)buffer;
618 
619   for (const Service& service : p_srvc_cb->gatt_database.Services()) {
620     if (service.handle < start_handle) continue;
621 
622     if (service.end_handle > end_handle) break;
623 
624     bta_gattc_fill_gatt_db_el(curr_db_attr,
625                               service.is_primary ? BTGATT_DB_PRIMARY_SERVICE
626                                                  : BTGATT_DB_SECONDARY_SERVICE,
627                               0 /* att_handle */, service.handle,
628                               service.end_handle, service.handle, service.uuid,
629                               0 /* prop */);
630     curr_db_attr++;
631 
632     for (const Characteristic& charac : service.characteristics) {
633       bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_CHARACTERISTIC,
634                                 charac.value_handle, 0 /* s_handle */,
635                                 0 /* e_handle */, charac.value_handle,
636                                 charac.uuid, charac.properties);
637       curr_db_attr++;
638 
639       for (const Descriptor& desc : charac.descriptors) {
640         bta_gattc_fill_gatt_db_el(
641             curr_db_attr, BTGATT_DB_DESCRIPTOR, desc.handle, 0 /* s_handle */,
642             0 /* e_handle */, desc.handle, desc.uuid, 0 /* property */);
643         curr_db_attr++;
644       }
645     }
646 
647     for (const IncludedService& p_isvc : service.included_services) {
648       bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_INCLUDED_SERVICE,
649                                 p_isvc.handle, p_isvc.start_handle,
650                                 0 /* e_handle */, p_isvc.handle, p_isvc.uuid,
651                                 0 /* property */);
652       curr_db_attr++;
653     }
654   }
655 
656   *db = (btgatt_db_element_t*)buffer;
657   *count = db_size;
658 }
659 
660 /*******************************************************************************
661  *
662  * Function         bta_gattc_get_gatt_db
663  *
664  * Description      copy the server GATT database into db parameter.
665  *
666  * Parameters       conn_id: connection ID which identify the server.
667  *                  db: output parameter which will contain GATT database copy.
668  *                      Caller is responsible for freeing it.
669  *                  count: number of elements in database.
670  *
671  * Returns          None.
672  *
673  ******************************************************************************/
bta_gattc_get_gatt_db(uint16_t conn_id,uint16_t start_handle,uint16_t end_handle,btgatt_db_element_t ** db,int * count)674 void bta_gattc_get_gatt_db(uint16_t conn_id, uint16_t start_handle,
675                            uint16_t end_handle, btgatt_db_element_t** db,
676                            int* count) {
677   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
678 
679   LOG_DEBUG("%s", __func__);
680   if (p_clcb == NULL) {
681     LOG(ERROR) << "Unknown conn_id=" << loghex(conn_id);
682     return;
683   }
684 
685   if (p_clcb->state != BTA_GATTC_CONN_ST) {
686     LOG(ERROR) << "server cache not available, CLCB state=" << +p_clcb->state;
687     return;
688   }
689 
690   if (!p_clcb->p_srcb || p_clcb->p_srcb->pending_discovery.InProgress() ||
691       p_clcb->p_srcb->gatt_database.IsEmpty()) {
692     LOG(ERROR) << "No server cache available";
693     return;
694   }
695 
696   bta_gattc_get_gatt_db_impl(p_clcb->p_srcb, start_handle, end_handle, db,
697                              count);
698 }
699 
700 /*******************************************************************************
701  *
702  * Function         bta_gattc_cache_load
703  *
704  * Description      Load GATT cache from storage for server.
705  *
706  * Parameter        p_srcb: pointer to server cache, that will
707  *                          be filled from storage
708  * Returns          true on success, false otherwise
709  *
710  ******************************************************************************/
bta_gattc_cache_load(tBTA_GATTC_SERV * p_srcb)711 bool bta_gattc_cache_load(tBTA_GATTC_SERV* p_srcb) {
712   char fname[255] = {0};
713   bta_gattc_generate_cache_file_name(fname, sizeof(fname), p_srcb->server_bda);
714 
715   FILE* fd = fopen(fname, "rb");
716   if (!fd) {
717     LOG(ERROR) << __func__ << ": can't open GATT cache file " << fname
718                << " for reading, error: " << strerror(errno);
719     return false;
720   }
721 
722   uint16_t cache_ver = 0;
723   bool success = false;
724   uint16_t num_attr = 0;
725 
726   if (fread(&cache_ver, sizeof(uint16_t), 1, fd) != 1) {
727     LOG(ERROR) << __func__ << ": can't read GATT cache version from: " << fname;
728     goto done;
729   }
730 
731   if (cache_ver != GATT_CACHE_VERSION) {
732     LOG(ERROR) << __func__ << ": wrong GATT cache version: " << fname;
733     goto done;
734   }
735 
736   if (fread(&num_attr, sizeof(uint16_t), 1, fd) != 1) {
737     LOG(ERROR) << __func__
738                << ": can't read number of GATT attributes: " << fname;
739     goto done;
740   }
741 
742   {
743     std::vector<StoredAttribute> attr(num_attr);
744 
745     if (fread(attr.data(), sizeof(StoredAttribute), num_attr, fd) != num_attr) {
746       LOG(ERROR) << __func__ << "s: can't read GATT attributes: " << fname;
747       goto done;
748     }
749 
750     p_srcb->gatt_database = gatt::Database::Deserialize(attr, &success);
751   }
752 
753 done:
754   fclose(fd);
755   return success;
756 }
757 
758 /*******************************************************************************
759  *
760  * Function         bta_gattc_cache_write
761  *
762  * Description      This callout function is executed by GATT when a server
763  *                  cache is available to save.
764  *
765  * Parameter        server_bda: server bd address of this cache belongs to
766  *                  attr: attributes to save.
767  * Returns
768  *
769  ******************************************************************************/
bta_gattc_cache_write(const RawAddress & server_bda,const std::vector<StoredAttribute> & attr)770 static void bta_gattc_cache_write(const RawAddress& server_bda,
771                                   const std::vector<StoredAttribute>& attr) {
772   char fname[255] = {0};
773   bta_gattc_generate_cache_file_name(fname, sizeof(fname), server_bda);
774 
775   FILE* fd = fopen(fname, "wb");
776   if (!fd) {
777     LOG(ERROR) << __func__
778                << ": can't open GATT cache file for writing: " << fname;
779     return;
780   }
781 
782   uint16_t cache_ver = GATT_CACHE_VERSION;
783   if (fwrite(&cache_ver, sizeof(uint16_t), 1, fd) != 1) {
784     LOG(ERROR) << __func__ << ": can't write GATT cache version: " << fname;
785     fclose(fd);
786     return;
787   }
788 
789   uint16_t num_attr = attr.size();
790   if (fwrite(&num_attr, sizeof(uint16_t), 1, fd) != 1) {
791     LOG(ERROR) << __func__
792                << ": can't write GATT cache attribute count: " << fname;
793     fclose(fd);
794     return;
795   }
796 
797   if (fwrite(attr.data(), sizeof(StoredAttribute), num_attr, fd) != num_attr) {
798     LOG(ERROR) << __func__ << ": can't write GATT cache attributes: " << fname;
799     fclose(fd);
800     return;
801   }
802 
803   fclose(fd);
804 }
805 
806 /*******************************************************************************
807  *
808  * Function         bta_gattc_cache_reset
809  *
810  * Description      This callout function is executed by GATTC to reset cache in
811  *                  application
812  *
813  * Parameter        server_bda: server bd address of this cache belongs to
814  *
815  * Returns          void.
816  *
817  ******************************************************************************/
bta_gattc_cache_reset(const RawAddress & server_bda)818 void bta_gattc_cache_reset(const RawAddress& server_bda) {
819   VLOG(1) << __func__;
820   char fname[255] = {0};
821   bta_gattc_generate_cache_file_name(fname, sizeof(fname), server_bda);
822   unlink(fname);
823 }
824