bta_gattc_cache.cc revision 6918d40fd9ca8c58c115cf694f165413165e5758
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
35#include "bt_common.h"
36#include "bta_gattc_int.h"
37#include "bta_sys.h"
38#include "btm_api.h"
39#include "btm_ble_api.h"
40#include "btm_int.h"
41#include "osi/include/log.h"
42#include "osi/include/osi.h"
43#include "sdp_api.h"
44#include "sdpdefs.h"
45#include "utl.h"
46
47using bluetooth::Uuid;
48using base::StringPrintf;
49
50static void bta_gattc_cache_write(const RawAddress& server_bda,
51                                  uint16_t num_attr, tBTA_GATTC_NV_ATTR* attr);
52static void bta_gattc_char_dscpt_disc_cmpl(uint16_t conn_id,
53                                           tBTA_GATTC_SERV* p_srvc_cb);
54static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id,
55                                               tBTA_GATTC_SERV* p_server_cb);
56const tBTA_GATTC_DESCRIPTOR* bta_gattc_get_descriptor_srcb(
57    tBTA_GATTC_SERV* p_srcb, uint16_t handle);
58tBTA_GATTC_CHARACTERISTIC* bta_gattc_get_characteristic_srcb(
59    tBTA_GATTC_SERV* p_srcb, uint16_t handle);
60
61#define BTA_GATT_SDP_DB_SIZE 4096
62
63#define GATT_CACHE_PREFIX "/data/misc/bluetooth/gatt_cache_"
64#define GATT_CACHE_VERSION 2
65
66static void bta_gattc_generate_cache_file_name(char* buffer, size_t buffer_len,
67                                               const RawAddress& bda) {
68  snprintf(buffer, buffer_len, "%s%02x%02x%02x%02x%02x%02x", GATT_CACHE_PREFIX,
69           bda.address[0], bda.address[1], bda.address[2], bda.address[3],
70           bda.address[4], bda.address[5]);
71}
72
73/*****************************************************************************
74 *  Constants and data types
75 ****************************************************************************/
76
77typedef struct {
78  tSDP_DISCOVERY_DB* p_sdp_db;
79  uint16_t sdp_conn_id;
80} tBTA_GATTC_CB_DATA;
81
82#if (BTA_GATT_DEBUG == TRUE)
83/* utility functions */
84
85/* debug function to display the server cache */
86static void display_db(const std::vector<tBTA_GATTC_SERVICE>& cache) {
87  for (const tBTA_GATTC_SERVICE& service : cache) {
88    LOG(ERROR) << "Service: s_handle=" << loghex(service.s_handle)
89               << ", e_handle=" << loghex(service.e_handle)
90               << ", inst=" << loghex(service.handle)
91               << ", uuid=" << service.uuid;
92
93    if (service.characteristics.empty()) {
94      LOG(ERROR) << "\t No characteristics";
95      continue;
96    }
97
98    for (const tBTA_GATTC_CHARACTERISTIC& c : service.characteristics) {
99      LOG(ERROR) << "\t Characteristic value_handle=" << loghex(c.value_handle)
100                 << ", uuid=" << c.uuid << ", prop=" << loghex(c.properties);
101
102      if (c.descriptors.empty()) {
103        LOG(ERROR) << "\t\t No descriptors";
104        continue;
105      }
106
107      for (const tBTA_GATTC_DESCRIPTOR& d : c.descriptors) {
108        LOG(ERROR) << "\t\t Descriptor handle=" << loghex(d.handle)
109                   << ", uuid=" << d.uuid;
110      }
111    }
112  }
113}
114
115/* debug function to display the server cache */
116static void bta_gattc_display_cache_server(
117    const std::vector<tBTA_GATTC_SERVICE>& cache) {
118  LOG(ERROR) << "<================Start Server Cache =============>";
119  display_db(cache);
120  LOG(ERROR) << "<================End Server Cache =============>";
121  LOG(ERROR) << " ";
122}
123
124/** debug function to display the exploration list */
125static void bta_gattc_display_explore_record(
126    const std::vector<tBTA_GATTC_SERVICE>& cache) {
127  LOG(ERROR) << "<================Start Explore Queue =============>";
128  display_db(cache);
129  LOG(ERROR) << "<================ End Explore Queue =============>";
130  LOG(ERROR) << " ";
131}
132#endif /* BTA_GATT_DEBUG == TRUE */
133
134/*******************************************************************************
135 *
136 * Function         bta_gattc_init_cache
137 *
138 * Description      Initialize the database cache and discovery related
139 *                  resources.
140 *
141 * Returns          status
142 *
143 ******************************************************************************/
144tGATT_STATUS bta_gattc_init_cache(tBTA_GATTC_SERV* p_srvc_cb) {
145  // clear reallocating
146  std::vector<tBTA_GATTC_SERVICE>().swap(p_srvc_cb->srvc_cache);
147  std::vector<tBTA_GATTC_SERVICE>().swap(p_srvc_cb->pending_discovery);
148  return GATT_SUCCESS;
149}
150
151tBTA_GATTC_SERVICE* bta_gattc_find_matching_service(
152    std::vector<tBTA_GATTC_SERVICE>& services, uint16_t handle) {
153  for (tBTA_GATTC_SERVICE& service : services) {
154    if (handle >= service.s_handle && handle <= service.e_handle)
155      return &service;
156  }
157
158  return nullptr;
159}
160
161/** Add a service into GATT database */
162static void add_service_to_gatt_db(std::vector<tBTA_GATTC_SERVICE>& gatt_db,
163                                   uint16_t s_handle, uint16_t e_handle,
164                                   const Uuid& uuid, bool is_primary) {
165#if (BTA_GATT_DEBUG == TRUE)
166  VLOG(1) << "Add a service into Service";
167#endif
168
169  gatt_db.emplace_back(tBTA_GATTC_SERVICE{
170      .s_handle = s_handle,
171      .e_handle = e_handle,
172      .is_primary = is_primary,
173      .uuid = uuid,
174      .handle = s_handle,
175  });
176}
177
178/** Add a characteristic into GATT database */
179static void add_characteristic_to_gatt_db(
180    std::vector<tBTA_GATTC_SERVICE>& gatt_db, uint16_t attr_handle,
181    uint16_t value_handle, const Uuid& uuid, uint8_t property) {
182#if (BTA_GATT_DEBUG == TRUE)
183  VLOG(1) << __func__
184          << ": Add a characteristic into service. handle:" << +value_handle
185          << " uuid:" << uuid << " property=0x" << std::hex << +property;
186#endif
187
188  tBTA_GATTC_SERVICE* service =
189      bta_gattc_find_matching_service(gatt_db, attr_handle);
190  if (!service) {
191    LOG(ERROR) << "Illegal action to add char/descr/incl srvc for non-existing "
192                  "service!";
193    return;
194  }
195
196  /* TODO(jpawlowski): We should use attribute handle, not value handle to refer
197     to characteristic.
198     This is just a temporary workaround.
199  */
200  if (service->e_handle < value_handle) service->e_handle = value_handle;
201
202  service->characteristics.emplace_back(
203      tBTA_GATTC_CHARACTERISTIC{.declaration_handle = attr_handle,
204                                .value_handle = value_handle,
205                                .properties = property,
206                                .uuid = uuid});
207  return;
208}
209
210/* Add an descriptor into database cache buffer */
211static void add_descriptor_to_gatt_db(std::vector<tBTA_GATTC_SERVICE>& gatt_db,
212                                      uint16_t handle, const Uuid& uuid) {
213#if (BTA_GATT_DEBUG == TRUE)
214  VLOG(1) << __func__ << ": add descriptor, handle=" << loghex(handle)
215          << ", uuid=" << uuid;
216#endif
217
218  tBTA_GATTC_SERVICE* service =
219      bta_gattc_find_matching_service(gatt_db, handle);
220  if (!service) {
221    LOG(ERROR) << "Illegal action to add descriptor for non-existing service!";
222    return;
223  }
224
225  if (service->characteristics.empty()) {
226    LOG(ERROR) << __func__
227               << ": Illegal action to add descriptor before adding a "
228                  "characteristic!";
229    return;
230  }
231
232  tBTA_GATTC_CHARACTERISTIC* char_node = &service->characteristics.front();
233  for (auto it = service->characteristics.begin();
234       it != service->characteristics.end(); it++) {
235    if (it->value_handle > handle) break;
236    char_node = &(*it);
237  }
238
239  char_node->descriptors.emplace_back(
240      tBTA_GATTC_DESCRIPTOR{.handle = handle, .uuid = uuid});
241}
242
243/* Add an attribute into database cache buffer */
244static void add_incl_srvc_to_gatt_db(std::vector<tBTA_GATTC_SERVICE>& gatt_db,
245                                     uint16_t handle, const Uuid& uuid,
246                                     uint16_t incl_srvc_s_handle) {
247#if (BTA_GATT_DEBUG == TRUE)
248  VLOG(1) << __func__ << ": add included service, handle=" << loghex(handle)
249          << ", uuid=" << uuid;
250#endif
251
252  tBTA_GATTC_SERVICE* service =
253      bta_gattc_find_matching_service(gatt_db, handle);
254  if (!service) {
255    LOG(ERROR) << "Illegal action to add incl srvc for non-existing service!";
256    return;
257  }
258
259  tBTA_GATTC_SERVICE* included_service =
260      bta_gattc_find_matching_service(gatt_db, incl_srvc_s_handle);
261  if (!included_service) {
262    LOG(ERROR) << __func__
263               << ": Illegal action to add non-existing included service!";
264    return;
265  }
266
267  service->included_svc.emplace_back(tBTA_GATTC_INCLUDED_SVC{
268      .handle = handle,
269      .uuid = uuid,
270      .owning_service = service,
271      .included_service = included_service,
272  });
273}
274
275/** Start primary service discovery */
276tGATT_STATUS bta_gattc_discover_pri_service(uint16_t conn_id,
277                                            tBTA_GATTC_SERV* p_server_cb,
278                                            uint8_t disc_type) {
279  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
280  if (!p_clcb) return GATT_ERROR;
281
282  if (p_clcb->transport == BTA_TRANSPORT_LE) {
283    tGATT_DISC_PARAM param{.s_handle = 0x0001, .e_handle = 0xFFFF};
284    return GATTC_Discover(conn_id, disc_type, &param);
285  }
286
287  return bta_gattc_sdp_service_disc(conn_id, p_server_cb);
288}
289
290/** Start discovery for characteristic descriptor */
291void bta_gattc_start_disc_char_dscp(uint16_t conn_id,
292                                    tBTA_GATTC_SERV* p_srvc_cb) {
293  VLOG(1) << "starting discover characteristics descriptor";
294  auto& characteristic = p_srvc_cb->pending_char;
295
296  uint16_t end_handle = 0xFFFF;
297  // if there are more characteristics in the service
298  if (std::next(p_srvc_cb->pending_char) !=
299      p_srvc_cb->pending_service->characteristics.end()) {
300    // end at beginning of next characteristic
301    end_handle = std::next(p_srvc_cb->pending_char)->declaration_handle - 1;
302  } else {
303    // end at the end of current service
304    end_handle = p_srvc_cb->pending_service->e_handle;
305  }
306
307  tGATT_DISC_PARAM param{
308      .s_handle = (uint16_t)(characteristic->value_handle + 1),
309      .e_handle = end_handle};
310  if (GATTC_Discover(conn_id, GATT_DISC_CHAR_DSCPT, &param) != 0) {
311    bta_gattc_char_dscpt_disc_cmpl(conn_id, p_srvc_cb);
312  }
313}
314
315/** process the service discovery complete event */
316static void bta_gattc_explore_srvc(uint16_t conn_id,
317                                   tBTA_GATTC_SERV* p_srvc_cb) {
318  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
319  if (!p_clcb) {
320    LOG(ERROR) << "unknown conn_id=" << +conn_id;
321    return;
322  }
323
324  /* start expore a service if there is service not been explored */
325  if (p_srvc_cb->pending_service != p_srvc_cb->pending_discovery.end()) {
326    auto& service = *p_srvc_cb->pending_service;
327    VLOG(1) << "Start service discovery";
328
329    /* start discovering included services */
330    tGATT_DISC_PARAM param = {.s_handle = service.s_handle,
331                              .e_handle = service.e_handle};
332    GATTC_Discover(conn_id, GATT_DISC_INC_SRVC, &param);
333    return;
334  }
335
336  /* no service found at all, the end of server discovery*/
337  LOG(INFO) << __func__ << ": no more services found";
338
339  p_srvc_cb->srvc_cache.swap(p_srvc_cb->pending_discovery);
340  std::vector<tBTA_GATTC_SERVICE>().swap(p_srvc_cb->pending_discovery);
341
342#if (BTA_GATT_DEBUG == TRUE)
343  bta_gattc_display_cache_server(p_srvc_cb->srvc_cache);
344#endif
345  /* save cache to NV */
346  p_clcb->p_srcb->state = BTA_GATTC_SERV_SAVE;
347
348  if (btm_sec_is_a_bonded_dev(p_srvc_cb->server_bda)) {
349    bta_gattc_cache_save(p_clcb->p_srcb, p_clcb->bta_conn_id);
350  }
351
352  bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS);
353}
354
355/** process the char descriptor discovery complete event */
356static void bta_gattc_char_dscpt_disc_cmpl(uint16_t conn_id,
357                                           tBTA_GATTC_SERV* p_srvc_cb) {
358  ++p_srvc_cb->pending_char;
359  if (p_srvc_cb->pending_char !=
360      p_srvc_cb->pending_service->characteristics.end()) {
361    /* start discoverying next characteristic for char descriptor */
362    bta_gattc_start_disc_char_dscp(conn_id, p_srvc_cb);
363    return;
364  }
365
366  /* all characteristic has been explored, start with next service if any */
367#if (BTA_GATT_DEBUG == TRUE)
368  LOG(ERROR) << "all char has been explored";
369#endif
370  p_srvc_cb->pending_service++;
371  bta_gattc_explore_srvc(conn_id, p_srvc_cb);
372}
373
374static bool bta_gattc_srvc_in_list(std::vector<tBTA_GATTC_SERVICE>& services,
375                                   uint16_t s_handle, uint16_t e_handle, Uuid) {
376  if (!GATT_HANDLE_IS_VALID(s_handle) || !GATT_HANDLE_IS_VALID(e_handle)) {
377    LOG(ERROR) << "invalid included service s_handle=" << loghex(s_handle)
378               << ", e_handle=" << loghex(e_handle);
379    return true;
380  }
381
382  for (tBTA_GATTC_SERVICE& service : services) {
383    if (service.s_handle == s_handle || service.e_handle == e_handle)
384      return true;
385  }
386
387  return false;
388}
389
390/*******************************************************************************
391 *
392 * Function         bta_gattc_sdp_callback
393 *
394 * Description      Process the discovery result from sdp
395 *
396 * Returns          void
397 *
398 ******************************************************************************/
399void bta_gattc_sdp_callback(uint16_t sdp_status, void* user_data) {
400  tSDP_PROTOCOL_ELEM pe;
401  tBTA_GATTC_CB_DATA* cb_data = (tBTA_GATTC_CB_DATA*)user_data;
402  tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(cb_data->sdp_conn_id);
403
404  if (((sdp_status == SDP_SUCCESS) || (sdp_status == SDP_DB_FULL)) &&
405      p_srvc_cb != NULL) {
406    tSDP_DISC_REC* p_sdp_rec = NULL;
407    do {
408      /* find a service record, report it */
409      p_sdp_rec = SDP_FindServiceInDb(cb_data->p_sdp_db, 0, p_sdp_rec);
410      if (p_sdp_rec) {
411        Uuid service_uuid;
412        if (SDP_FindServiceUUIDInRec(p_sdp_rec, &service_uuid)) {
413          if (SDP_FindProtocolListElemInRec(p_sdp_rec, UUID_PROTOCOL_ATT,
414                                            &pe)) {
415            uint16_t start_handle = (uint16_t)pe.params[0];
416            uint16_t end_handle = (uint16_t)pe.params[1];
417
418#if (BTA_GATT_DEBUG == TRUE)
419            VLOG(1) << "Found ATT service uuid=" << service_uuid
420                    << ", s_handle=" << loghex(start_handle)
421                    << ", e_handle=" << loghex(end_handle);
422#endif
423
424            if (GATT_HANDLE_IS_VALID(start_handle) &&
425                GATT_HANDLE_IS_VALID(end_handle) && p_srvc_cb != NULL) {
426              /* discover services result, add services into a service list */
427              add_service_to_gatt_db(p_srvc_cb->pending_discovery, start_handle,
428                                     end_handle, service_uuid, true);
429            } else {
430              LOG(ERROR) << "invalid start_handle=" << loghex(start_handle)
431                         << ", end_handle=" << loghex(end_handle);
432            }
433          }
434        }
435      }
436    } while (p_sdp_rec);
437  }
438
439  if (p_srvc_cb != NULL) {
440    /* start discover primary service */
441    bta_gattc_explore_srvc(cb_data->sdp_conn_id, p_srvc_cb);
442  } else {
443    LOG(ERROR) << "GATT service discovery is done on unknown connection";
444  }
445
446  /* both were allocated in bta_gattc_sdp_service_disc */
447  osi_free(cb_data->p_sdp_db);
448  osi_free(cb_data);
449}
450/*******************************************************************************
451 *
452 * Function         bta_gattc_sdp_service_disc
453 *
454 * Description      Start DSP Service Discovert
455 *
456 * Returns          void
457 *
458 ******************************************************************************/
459static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id,
460                                               tBTA_GATTC_SERV* p_server_cb) {
461  uint16_t num_attrs = 2;
462  uint16_t attr_list[2];
463
464  /*
465   * On success, cb_data will be freed inside bta_gattc_sdp_callback,
466   * otherwise it will be freed within this function.
467   */
468  tBTA_GATTC_CB_DATA* cb_data =
469      (tBTA_GATTC_CB_DATA*)osi_malloc(sizeof(tBTA_GATTC_CB_DATA));
470
471  cb_data->p_sdp_db = (tSDP_DISCOVERY_DB*)osi_malloc(BTA_GATT_SDP_DB_SIZE);
472  attr_list[0] = ATTR_ID_SERVICE_CLASS_ID_LIST;
473  attr_list[1] = ATTR_ID_PROTOCOL_DESC_LIST;
474
475  Uuid uuid = Uuid::From16Bit(UUID_PROTOCOL_ATT);
476  SDP_InitDiscoveryDb(cb_data->p_sdp_db, BTA_GATT_SDP_DB_SIZE, 1, &uuid,
477                      num_attrs, attr_list);
478
479  if (!SDP_ServiceSearchAttributeRequest2(p_server_cb->server_bda,
480                                          cb_data->p_sdp_db,
481                                          &bta_gattc_sdp_callback, cb_data)) {
482    osi_free(cb_data->p_sdp_db);
483    osi_free(cb_data);
484    return GATT_ERROR;
485  }
486
487  cb_data->sdp_conn_id = conn_id;
488  return GATT_SUCCESS;
489}
490
491/** callback function to GATT client stack */
492void bta_gattc_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type,
493                              tGATT_DISC_RES* p_data) {
494  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
495  tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(conn_id);
496
497  if (!p_srvc_cb || !p_clcb || p_clcb->state != BTA_GATTC_DISCOVER_ST) return;
498
499  switch (disc_type) {
500    case GATT_DISC_SRVC_ALL:
501    case GATT_DISC_SRVC_BY_UUID:
502      /* discover services result, add services into a service list */
503      add_service_to_gatt_db(p_srvc_cb->pending_discovery, p_data->handle,
504                             p_data->value.group_value.e_handle,
505                             p_data->value.group_value.service_type, true);
506      break;
507
508    case GATT_DISC_INC_SRVC:
509      /* add included service into service list if it's secondary or it never
510         showed up in the primary service search */
511      if (!bta_gattc_srvc_in_list(p_srvc_cb->pending_discovery,
512                                  p_data->value.incl_service.s_handle,
513                                  p_data->value.incl_service.e_handle,
514                                  p_data->value.incl_service.service_type)) {
515        add_service_to_gatt_db(p_srvc_cb->pending_discovery,
516                               p_data->value.incl_service.s_handle,
517                               p_data->value.incl_service.e_handle,
518                               p_data->value.incl_service.service_type, false);
519      }
520
521      /* add into database */
522      add_incl_srvc_to_gatt_db(p_srvc_cb->pending_discovery, p_data->handle,
523                               p_data->value.incl_service.service_type,
524                               p_data->value.incl_service.s_handle);
525      break;
526
527    case GATT_DISC_CHAR:
528      /* add char value into database */
529      add_characteristic_to_gatt_db(p_srvc_cb->pending_discovery,
530                                    p_data->handle,
531                                    p_data->value.dclr_value.val_handle,
532                                    p_data->value.dclr_value.char_uuid,
533                                    p_data->value.dclr_value.char_prop);
534      break;
535
536    case GATT_DISC_CHAR_DSCPT:
537      add_descriptor_to_gatt_db(p_srvc_cb->pending_discovery, p_data->handle,
538                                p_data->type);
539      break;
540  }
541}
542
543void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type,
544                               tGATT_STATUS status) {
545  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
546
547  if (p_clcb && (status != GATT_SUCCESS || p_clcb->status != GATT_SUCCESS)) {
548    if (status == GATT_SUCCESS) p_clcb->status = status;
549    bta_gattc_sm_execute(p_clcb, BTA_GATTC_DISCOVER_CMPL_EVT, NULL);
550    return;
551  }
552
553  tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(conn_id);
554  if (!p_srvc_cb) return;
555
556  switch (disc_type) {
557    case GATT_DISC_SRVC_ALL:
558    case GATT_DISC_SRVC_BY_UUID:
559// definition of all services are discovered, now it's time to discover
560// their content
561#if (BTA_GATT_DEBUG == TRUE)
562      bta_gattc_display_explore_record(p_srvc_cb->pending_discovery);
563#endif
564      p_srvc_cb->pending_service = p_srvc_cb->pending_discovery.begin();
565      bta_gattc_explore_srvc(conn_id, p_srvc_cb);
566      break;
567
568    case GATT_DISC_INC_SRVC: {
569      auto& service = *p_srvc_cb->pending_service;
570
571      /* start discoverying characteristic */
572
573      tGATT_DISC_PARAM param = {.s_handle = service.s_handle,
574                                .e_handle = service.e_handle};
575      GATTC_Discover(conn_id, GATT_DISC_CHAR, &param);
576      break;
577    }
578
579    case GATT_DISC_CHAR: {
580#if (BTA_GATT_DEBUG == TRUE)
581      bta_gattc_display_explore_record(p_srvc_cb->pending_discovery);
582#endif
583      auto& service = *p_srvc_cb->pending_service;
584      if (!service.characteristics.empty()) {
585        /* discover descriptors */
586        p_srvc_cb->pending_char = service.characteristics.begin();
587        bta_gattc_start_disc_char_dscp(conn_id, p_srvc_cb);
588        return;
589      }
590      /* start next service */
591      ++p_srvc_cb->pending_service;
592      bta_gattc_explore_srvc(conn_id, p_srvc_cb);
593      break;
594    }
595
596    case GATT_DISC_CHAR_DSCPT:
597      bta_gattc_char_dscpt_disc_cmpl(conn_id, p_srvc_cb);
598      break;
599  }
600}
601
602/** search local cache for matching service record */
603void bta_gattc_search_service(tBTA_GATTC_CLCB* p_clcb, Uuid* p_uuid) {
604  for (const tBTA_GATTC_SERVICE& service : p_clcb->p_srcb->srvc_cache) {
605    if (p_uuid && *p_uuid != service.uuid) continue;
606
607#if (BTA_GATT_DEBUG == TRUE)
608    VLOG(1) << __func__ << "found service " << service.uuid
609            << ", inst:" << +service.handle << " handle:" << +service.s_handle;
610#endif
611    if (!p_clcb->p_rcb->p_cback) continue;
612
613    tBTA_GATTC cb_data;
614    memset(&cb_data, 0, sizeof(tBTA_GATTC));
615    cb_data.srvc_res.conn_id = p_clcb->bta_conn_id;
616    cb_data.srvc_res.service_uuid.inst_id = service.handle;
617    cb_data.srvc_res.service_uuid.uuid = service.uuid;
618
619    (*p_clcb->p_rcb->p_cback)(BTA_GATTC_SEARCH_RES_EVT, &cb_data);
620  }
621}
622
623std::vector<tBTA_GATTC_SERVICE>* bta_gattc_get_services_srcb(
624    tBTA_GATTC_SERV* p_srcb) {
625  if (!p_srcb || p_srcb->srvc_cache.empty()) return NULL;
626
627  return &p_srcb->srvc_cache;
628}
629
630std::vector<tBTA_GATTC_SERVICE>* bta_gattc_get_services(uint16_t conn_id) {
631  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
632
633  if (p_clcb == NULL) return NULL;
634
635  tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
636
637  return bta_gattc_get_services_srcb(p_srcb);
638}
639
640tBTA_GATTC_SERVICE* bta_gattc_get_service_for_handle_srcb(
641    tBTA_GATTC_SERV* p_srcb, uint16_t handle) {
642  std::vector<tBTA_GATTC_SERVICE>* services =
643      bta_gattc_get_services_srcb(p_srcb);
644  if (services == NULL) return NULL;
645  return bta_gattc_find_matching_service(*services, handle);
646}
647
648const tBTA_GATTC_SERVICE* bta_gattc_get_service_for_handle(uint16_t conn_id,
649                                                           uint16_t handle) {
650  std::vector<tBTA_GATTC_SERVICE>* services = bta_gattc_get_services(conn_id);
651  if (services == NULL) return NULL;
652
653  return bta_gattc_find_matching_service(*services, handle);
654}
655
656tBTA_GATTC_CHARACTERISTIC* bta_gattc_get_characteristic_srcb(
657    tBTA_GATTC_SERV* p_srcb, uint16_t handle) {
658  tBTA_GATTC_SERVICE* service =
659      bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
660
661  if (!service) return NULL;
662
663  for (tBTA_GATTC_CHARACTERISTIC& charac : service->characteristics) {
664    if (handle == charac.value_handle) return &charac;
665  }
666
667  return NULL;
668}
669
670tBTA_GATTC_CHARACTERISTIC* bta_gattc_get_characteristic(uint16_t conn_id,
671                                                        uint16_t handle) {
672  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
673
674  if (p_clcb == NULL) return NULL;
675
676  tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
677  return bta_gattc_get_characteristic_srcb(p_srcb, handle);
678}
679
680const tBTA_GATTC_DESCRIPTOR* bta_gattc_get_descriptor_srcb(
681    tBTA_GATTC_SERV* p_srcb, uint16_t handle) {
682  const tBTA_GATTC_SERVICE* service =
683      bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
684
685  if (!service) {
686    return NULL;
687  }
688
689  for (const tBTA_GATTC_CHARACTERISTIC& charac : service->characteristics) {
690    for (const tBTA_GATTC_DESCRIPTOR& desc : charac.descriptors) {
691      if (handle == desc.handle) return &desc;
692    }
693  }
694
695  return NULL;
696}
697
698const tBTA_GATTC_DESCRIPTOR* bta_gattc_get_descriptor(uint16_t conn_id,
699                                                      uint16_t handle) {
700  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
701
702  if (p_clcb == NULL) return NULL;
703
704  tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb;
705  return bta_gattc_get_descriptor_srcb(p_srcb, handle);
706}
707
708tBTA_GATTC_CHARACTERISTIC* bta_gattc_get_owning_characteristic_srcb(
709    tBTA_GATTC_SERV* p_srcb, uint16_t handle) {
710  tBTA_GATTC_SERVICE* service =
711      bta_gattc_get_service_for_handle_srcb(p_srcb, handle);
712
713  if (!service) return NULL;
714
715  for (tBTA_GATTC_CHARACTERISTIC& charac : service->characteristics) {
716    for (const tBTA_GATTC_DESCRIPTOR& desc : charac.descriptors) {
717      if (handle == desc.handle) return &charac;
718    }
719  }
720
721  return NULL;
722}
723
724const tBTA_GATTC_CHARACTERISTIC* bta_gattc_get_owning_characteristic(
725    uint16_t conn_id, uint16_t handle) {
726  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
727  if (!p_clcb) return NULL;
728
729  return bta_gattc_get_owning_characteristic_srcb(p_clcb->p_srcb, handle);
730}
731
732/*******************************************************************************
733 *
734 * Function         bta_gattc_fill_gatt_db_el
735 *
736 * Description      fill a btgatt_db_element_t value
737 *
738 * Returns          None.
739 *
740 ******************************************************************************/
741void bta_gattc_fill_gatt_db_el(btgatt_db_element_t* p_attr,
742                               bt_gatt_db_attribute_type_t type,
743                               uint16_t att_handle, uint16_t s_handle,
744                               uint16_t e_handle, uint16_t id, const Uuid& uuid,
745                               uint8_t prop) {
746  p_attr->type = type;
747  p_attr->attribute_handle = att_handle;
748  p_attr->start_handle = s_handle;
749  p_attr->end_handle = e_handle;
750  p_attr->id = id;
751  p_attr->properties = prop;
752
753  // Permissions are not discoverable using the attribute protocol.
754  // Core 5.0, Part F, 3.2.5 Attribute Permissions
755  p_attr->permissions = 0;
756  p_attr->uuid = uuid;
757}
758
759/*******************************************************************************
760 * Returns          number of elements inside db from start_handle to end_handle
761 ******************************************************************************/
762static size_t bta_gattc_get_db_size(
763    const std::vector<tBTA_GATTC_SERVICE>& services, uint16_t start_handle,
764    uint16_t end_handle) {
765  if (services.empty()) return 0;
766
767  size_t db_size = 0;
768
769  for (const tBTA_GATTC_SERVICE& service : services) {
770    if (service.s_handle < start_handle) continue;
771
772    if (service.e_handle > end_handle) break;
773
774    db_size++;
775
776    for (const tBTA_GATTC_CHARACTERISTIC& charac : service.characteristics) {
777      db_size++;
778
779      db_size += charac.descriptors.size();
780    }
781
782    db_size += service.included_svc.size();
783  }
784
785  return db_size;
786}
787
788/*******************************************************************************
789 *
790 * Function         bta_gattc_get_gatt_db_impl
791 *
792 * Description      copy the server GATT database into db parameter.
793 *
794 * Parameters       p_srvc_cb: server.
795 *                  db: output parameter which will contain GATT database copy.
796 *                      Caller is responsible for freeing it.
797 *                  count: output parameter which will contain number of
798 *                  elements in database.
799 *
800 * Returns          None.
801 *
802 ******************************************************************************/
803static void bta_gattc_get_gatt_db_impl(tBTA_GATTC_SERV* p_srvc_cb,
804                                       uint16_t start_handle,
805                                       uint16_t end_handle,
806                                       btgatt_db_element_t** db, int* count) {
807  VLOG(1) << __func__
808          << StringPrintf(": start_handle 0x%04x, end_handle 0x%04x",
809                          start_handle, end_handle);
810
811  if (p_srvc_cb->srvc_cache.empty()) {
812    *count = 0;
813    *db = NULL;
814    return;
815  }
816
817  size_t db_size =
818      bta_gattc_get_db_size(p_srvc_cb->srvc_cache, start_handle, end_handle);
819
820  void* buffer = osi_malloc(db_size * sizeof(btgatt_db_element_t));
821  btgatt_db_element_t* curr_db_attr = (btgatt_db_element_t*)buffer;
822
823  for (const tBTA_GATTC_SERVICE& service : p_srvc_cb->srvc_cache) {
824    if (service.s_handle < start_handle) continue;
825
826    if (service.e_handle > end_handle) break;
827
828    bta_gattc_fill_gatt_db_el(curr_db_attr,
829                              service.is_primary ? BTGATT_DB_PRIMARY_SERVICE
830                                                 : BTGATT_DB_SECONDARY_SERVICE,
831                              0 /* att_handle */, service.s_handle,
832                              service.e_handle, service.s_handle, service.uuid,
833                              0 /* prop */);
834    curr_db_attr++;
835
836    for (const tBTA_GATTC_CHARACTERISTIC& charac : service.characteristics) {
837      bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_CHARACTERISTIC,
838                                charac.value_handle, 0 /* s_handle */,
839                                0 /* e_handle */, charac.value_handle,
840                                charac.uuid, charac.properties);
841      curr_db_attr++;
842
843      for (const tBTA_GATTC_DESCRIPTOR& desc : charac.descriptors) {
844        bta_gattc_fill_gatt_db_el(
845            curr_db_attr, BTGATT_DB_DESCRIPTOR, desc.handle, 0 /* s_handle */,
846            0 /* e_handle */, desc.handle, desc.uuid, 0 /* property */);
847        curr_db_attr++;
848      }
849    }
850
851    for (const tBTA_GATTC_INCLUDED_SVC& p_isvc : service.included_svc) {
852      bta_gattc_fill_gatt_db_el(
853          curr_db_attr, BTGATT_DB_INCLUDED_SERVICE, p_isvc.handle,
854          p_isvc.included_service ? p_isvc.included_service->s_handle : 0,
855          0 /* e_handle */, p_isvc.handle, p_isvc.uuid, 0 /* property */);
856      curr_db_attr++;
857    }
858  }
859
860  *db = (btgatt_db_element_t*)buffer;
861  *count = db_size;
862}
863
864/*******************************************************************************
865 *
866 * Function         bta_gattc_get_gatt_db
867 *
868 * Description      copy the server GATT database into db parameter.
869 *
870 * Parameters       conn_id: connection ID which identify the server.
871 *                  db: output parameter which will contain GATT database copy.
872 *                      Caller is responsible for freeing it.
873 *                  count: number of elements in database.
874 *
875 * Returns          None.
876 *
877 ******************************************************************************/
878void bta_gattc_get_gatt_db(uint16_t conn_id, uint16_t start_handle,
879                           uint16_t end_handle, btgatt_db_element_t** db,
880                           int* count) {
881  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
882
883  LOG_DEBUG(LOG_TAG, "%s", __func__);
884  if (p_clcb == NULL) {
885    LOG(ERROR) << "Unknown conn_id=" << loghex(conn_id);
886    return;
887  }
888
889  if (p_clcb->state != BTA_GATTC_CONN_ST) {
890    LOG(ERROR) << "server cache not available, CLCB state=" << +p_clcb->state;
891    return;
892  }
893
894  if (!p_clcb->p_srcb ||
895      !p_clcb->p_srcb->pending_discovery.empty() || /* no active discovery */
896      p_clcb->p_srcb->srvc_cache.empty()) {
897    LOG(ERROR) << "No server cache available";
898    return;
899  }
900
901  bta_gattc_get_gatt_db_impl(p_clcb->p_srcb, start_handle, end_handle, db,
902                             count);
903}
904
905/*******************************************************************************
906 *
907 * Function         bta_gattc_rebuild_cache
908 *
909 * Description      rebuild server cache from NV cache.
910 *
911 * Parameters
912 *
913 * Returns          None.
914 *
915 ******************************************************************************/
916void bta_gattc_rebuild_cache(tBTA_GATTC_SERV* p_srvc_cb, uint16_t num_attr,
917                             tBTA_GATTC_NV_ATTR* p_attr) {
918  /* first attribute loading, initialize buffer */
919  LOG(ERROR) << __func__;
920
921  // clear reallocating
922  std::vector<tBTA_GATTC_SERVICE>().swap(p_srvc_cb->srvc_cache);
923
924  while (num_attr > 0 && p_attr != NULL) {
925    switch (p_attr->attr_type) {
926      case BTA_GATTC_ATTR_TYPE_SRVC:
927        add_service_to_gatt_db(p_srvc_cb->srvc_cache, p_attr->s_handle,
928                               p_attr->e_handle, p_attr->uuid,
929                               p_attr->is_primary);
930        break;
931
932      case BTA_GATTC_ATTR_TYPE_CHAR:
933        add_characteristic_to_gatt_db(p_srvc_cb->srvc_cache, p_attr->s_handle,
934                                      p_attr->s_handle, p_attr->uuid,
935                                      p_attr->prop);
936        break;
937
938      case BTA_GATTC_ATTR_TYPE_CHAR_DESCR:
939        add_descriptor_to_gatt_db(p_srvc_cb->srvc_cache, p_attr->s_handle,
940                                  p_attr->uuid);
941        break;
942      case BTA_GATTC_ATTR_TYPE_INCL_SRVC:
943        add_incl_srvc_to_gatt_db(p_srvc_cb->srvc_cache, p_attr->s_handle,
944                                 p_attr->uuid, p_attr->incl_srvc_handle);
945        break;
946    }
947    p_attr++;
948    num_attr--;
949  }
950}
951
952/*******************************************************************************
953 *
954 * Function         bta_gattc_fill_nv_attr
955 *
956 * Description      fill a NV attribute entry value
957 *
958 * Returns          None.
959 *
960 ******************************************************************************/
961void bta_gattc_fill_nv_attr(tBTA_GATTC_NV_ATTR* p_attr, uint8_t type,
962                            uint16_t s_handle, uint16_t e_handle, Uuid uuid,
963                            uint8_t prop, uint16_t incl_srvc_handle,
964                            bool is_primary) {
965  p_attr->s_handle = s_handle;
966  p_attr->e_handle = e_handle;
967  p_attr->attr_type = type;
968  p_attr->is_primary = is_primary;
969  p_attr->id = 0;
970  p_attr->prop = prop;
971  p_attr->incl_srvc_handle = incl_srvc_handle;
972  p_attr->uuid = uuid;
973}
974
975/*******************************************************************************
976 *
977 * Function         bta_gattc_cache_save
978 *
979 * Description      save the server cache into NV
980 *
981 * Returns          None.
982 *
983 ******************************************************************************/
984void bta_gattc_cache_save(tBTA_GATTC_SERV* p_srvc_cb, uint16_t conn_id) {
985  if (p_srvc_cb->srvc_cache.empty()) return;
986
987  int i = 0;
988  size_t db_size = bta_gattc_get_db_size(p_srvc_cb->srvc_cache, 0x0000, 0xFFFF);
989  tBTA_GATTC_NV_ATTR* nv_attr =
990      (tBTA_GATTC_NV_ATTR*)osi_malloc(db_size * sizeof(tBTA_GATTC_NV_ATTR));
991
992  for (const tBTA_GATTC_SERVICE& service : p_srvc_cb->srvc_cache) {
993    bta_gattc_fill_nv_attr(&nv_attr[i++], BTA_GATTC_ATTR_TYPE_SRVC,
994                           service.s_handle, service.e_handle, service.uuid,
995                           0 /* properties */, 0 /* incl_srvc_handle */,
996                           service.is_primary);
997  }
998
999  for (const tBTA_GATTC_SERVICE& service : p_srvc_cb->srvc_cache) {
1000    for (const tBTA_GATTC_CHARACTERISTIC& charac : service.characteristics) {
1001      bta_gattc_fill_nv_attr(
1002          &nv_attr[i++], BTA_GATTC_ATTR_TYPE_CHAR, charac.value_handle, 0,
1003          charac.uuid, charac.properties, 0 /* incl_srvc_handle */, false);
1004
1005      for (const tBTA_GATTC_DESCRIPTOR& desc : charac.descriptors) {
1006        bta_gattc_fill_nv_attr(&nv_attr[i++], BTA_GATTC_ATTR_TYPE_CHAR_DESCR,
1007                               desc.handle, 0, desc.uuid, 0 /* properties */,
1008                               0 /* incl_srvc_handle */, false);
1009      }
1010    }
1011
1012    for (const tBTA_GATTC_INCLUDED_SVC& p_isvc : service.included_svc) {
1013      bta_gattc_fill_nv_attr(&nv_attr[i++], BTA_GATTC_ATTR_TYPE_INCL_SRVC,
1014                             p_isvc.handle, 0, p_isvc.uuid, 0 /* properties */,
1015                             p_isvc.included_service->s_handle, false);
1016    }
1017  }
1018
1019  bta_gattc_cache_write(p_srvc_cb->server_bda, db_size, nv_attr);
1020  osi_free(nv_attr);
1021}
1022
1023/*******************************************************************************
1024 *
1025 * Function         bta_gattc_cache_load
1026 *
1027 * Description      Load GATT cache from storage for server.
1028 *
1029 * Parameter        p_clcb: pointer to server clcb, that will
1030 *                          be filled from storage
1031 * Returns          true on success, false otherwise
1032 *
1033 ******************************************************************************/
1034bool bta_gattc_cache_load(tBTA_GATTC_CLCB* p_clcb) {
1035  char fname[255] = {0};
1036  bta_gattc_generate_cache_file_name(fname, sizeof(fname),
1037                                     p_clcb->p_srcb->server_bda);
1038
1039  FILE* fd = fopen(fname, "rb");
1040  if (!fd) {
1041    LOG(ERROR) << __func__ << ": can't open GATT cache file " << fname
1042               << " for reading, error: " << strerror(errno);
1043    return false;
1044  }
1045
1046  uint16_t cache_ver = 0;
1047  tBTA_GATTC_NV_ATTR* attr = NULL;
1048  bool success = false;
1049  uint16_t num_attr = 0;
1050
1051  if (fread(&cache_ver, sizeof(uint16_t), 1, fd) != 1) {
1052    LOG(ERROR) << __func__ << ": can't read GATT cache version from: " << fname;
1053    goto done;
1054  }
1055
1056  if (cache_ver != GATT_CACHE_VERSION) {
1057    LOG(ERROR) << __func__ << ": wrong GATT cache version: " << fname;
1058    goto done;
1059  }
1060
1061  if (fread(&num_attr, sizeof(uint16_t), 1, fd) != 1) {
1062    LOG(ERROR) << __func__
1063               << ": can't read number of GATT attributes: " << fname;
1064    goto done;
1065  }
1066
1067  if (num_attr > 0xFFFF) {
1068    LOG(ERROR) << __func__ << ": more than 0xFFFF GATT attributes: " << fname;
1069    goto done;
1070  }
1071
1072  attr = (tBTA_GATTC_NV_ATTR*)osi_malloc(sizeof(tBTA_GATTC_NV_ATTR) * num_attr);
1073
1074  if (fread(attr, sizeof(tBTA_GATTC_NV_ATTR), num_attr, fd) != num_attr) {
1075    LOG(ERROR) << __func__ << "s: can't read GATT attributes: " << fname;
1076    goto done;
1077  }
1078
1079  bta_gattc_rebuild_cache(p_clcb->p_srcb, num_attr, attr);
1080
1081  success = true;
1082
1083done:
1084  osi_free(attr);
1085  fclose(fd);
1086  return success;
1087}
1088
1089/*******************************************************************************
1090 *
1091 * Function         bta_gattc_cache_write
1092 *
1093 * Description      This callout function is executed by GATT when a server
1094 *                  cache is available to save.
1095 *
1096 * Parameter        server_bda: server bd address of this cache belongs to
1097 *                  num_attr: number of attribute to be save.
1098 *                  attr: pointer to the list of attributes to save.
1099 * Returns
1100 *
1101 ******************************************************************************/
1102static void bta_gattc_cache_write(const RawAddress& server_bda,
1103                                  uint16_t num_attr, tBTA_GATTC_NV_ATTR* attr) {
1104  char fname[255] = {0};
1105  bta_gattc_generate_cache_file_name(fname, sizeof(fname), server_bda);
1106
1107  FILE* fd = fopen(fname, "wb");
1108  if (!fd) {
1109    LOG(ERROR) << __func__
1110               << ": can't open GATT cache file for writing: " << fname;
1111    return;
1112  }
1113
1114  uint16_t cache_ver = GATT_CACHE_VERSION;
1115  if (fwrite(&cache_ver, sizeof(uint16_t), 1, fd) != 1) {
1116    LOG(ERROR) << __func__ << ": can't write GATT cache version: " << fname;
1117    fclose(fd);
1118    return;
1119  }
1120
1121  if (fwrite(&num_attr, sizeof(uint16_t), 1, fd) != 1) {
1122    LOG(ERROR) << __func__
1123               << ": can't write GATT cache attribute count: " << fname;
1124    fclose(fd);
1125    return;
1126  }
1127
1128  if (fwrite(attr, sizeof(tBTA_GATTC_NV_ATTR), num_attr, fd) != num_attr) {
1129    LOG(ERROR) << __func__ << ": can't write GATT cache attributes: " << fname;
1130    fclose(fd);
1131    return;
1132  }
1133
1134  fclose(fd);
1135}
1136
1137/*******************************************************************************
1138 *
1139 * Function         bta_gattc_cache_reset
1140 *
1141 * Description      This callout function is executed by GATTC to reset cache in
1142 *                  application
1143 *
1144 * Parameter        server_bda: server bd address of this cache belongs to
1145 *
1146 * Returns          void.
1147 *
1148 ******************************************************************************/
1149void bta_gattc_cache_reset(const RawAddress& server_bda) {
1150  VLOG(1) << __func__;
1151  char fname[255] = {0};
1152  bta_gattc_generate_cache_file_name(fname, sizeof(fname), server_bda);
1153  unlink(fname);
1154}
1155