• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2008-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 main GATT server attributes access request
22  *  handling functions.
23  *
24  ******************************************************************************/
25 
26 #include <map>
27 
28 #include "base/callback.h"
29 #include "bt_target.h"
30 #include "bt_utils.h"
31 #include "btif/include/btif_storage.h"
32 #include "eatt/eatt.h"
33 #include "gatt_api.h"
34 #include "gatt_int.h"
35 #include "gd/common/init_flags.h"
36 #include "osi/include/log.h"
37 #include "osi/include/osi.h"
38 
39 using base::StringPrintf;
40 using bluetooth::Uuid;
41 
42 #define BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK 0x01
43 
44 #define BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK 0x01
45 #define BLE_GATT_CL_SUP_FEAT_EATT_BITMASK 0x02
46 #define BLE_GATT_CL_SUP_FEAT_MULTI_NOTIF_BITMASK 0x04
47 
48 #define BLE_GATT_CL_ANDROID_SUP_FEAT \
49   (BLE_GATT_CL_SUP_FEAT_EATT_BITMASK | BLE_GATT_CL_SUP_FEAT_MULTI_NOTIF_BITMASK)
50 
51 using gatt_sr_supported_feat_cb =
52     base::OnceCallback<void(const RawAddress&, uint8_t)>;
53 
54 typedef struct {
55   uint16_t op_uuid;
56   gatt_sr_supported_feat_cb cb;
57 } gatt_op_cb_data;
58 
59 static std::map<uint16_t, gatt_op_cb_data> OngoingOps;
60 
61 static void gatt_request_cback(uint16_t conn_id, uint32_t trans_id,
62                                uint8_t op_code, tGATTS_DATA* p_data);
63 static void gatt_connect_cback(UNUSED_ATTR tGATT_IF gatt_if,
64                                const RawAddress& bda, uint16_t conn_id,
65                                bool connected, tGATT_DISCONN_REASON reason,
66                                tBT_TRANSPORT transport);
67 static void gatt_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type,
68                                 tGATT_DISC_RES* p_data);
69 static void gatt_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type,
70                                  tGATT_STATUS status);
71 static void gatt_cl_op_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op,
72                                   tGATT_STATUS status,
73                                   tGATT_CL_COMPLETE* p_data);
74 
75 static void gatt_cl_start_config_ccc(tGATT_PROFILE_CLCB* p_clcb);
76 
77 static bool gatt_sr_is_robust_caching_enabled();
78 
79 static tGATT_STATUS gatt_sr_read_db_hash(uint16_t conn_id,
80                                          tGATT_VALUE* p_value);
81 static tGATT_STATUS gatt_sr_read_cl_supp_feat(uint16_t conn_id,
82                                               tGATT_VALUE* p_value);
83 static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id,
84                                                tGATT_WRITE_REQ* p_data);
85 
86 static tGATT_CBACK gatt_profile_cback = {.p_conn_cb = gatt_connect_cback,
87                                          .p_cmpl_cb = gatt_cl_op_cmpl_cback,
88                                          .p_disc_res_cb = gatt_disc_res_cback,
89                                          .p_disc_cmpl_cb = gatt_disc_cmpl_cback,
90                                          .p_req_cb = gatt_request_cback,
91                                          .p_enc_cmpl_cb = nullptr,
92                                          .p_congestion_cb = nullptr,
93                                          .p_phy_update_cb = nullptr,
94                                          .p_conn_update_cb = nullptr};
95 
96 /*******************************************************************************
97  *
98  * Function         gatt_profile_find_conn_id_by_bd_addr
99  *
100  * Description      Find the connection ID by remote address
101  *
102  * Returns          Connection ID
103  *
104  ******************************************************************************/
gatt_profile_find_conn_id_by_bd_addr(const RawAddress & remote_bda)105 uint16_t gatt_profile_find_conn_id_by_bd_addr(const RawAddress& remote_bda) {
106   uint16_t conn_id = GATT_INVALID_CONN_ID;
107   GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id,
108                             BT_TRANSPORT_LE);
109   if (conn_id == GATT_INVALID_CONN_ID)
110     GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id,
111                               BT_TRANSPORT_BR_EDR);
112   return conn_id;
113 }
114 
115 /*******************************************************************************
116  *
117  * Function         gatt_profile_find_clcb_by_conn_id
118  *
119  * Description      find clcb by Connection ID
120  *
121  * Returns          Pointer to the found link conenction control block.
122  *
123  ******************************************************************************/
gatt_profile_find_clcb_by_conn_id(uint16_t conn_id)124 static tGATT_PROFILE_CLCB* gatt_profile_find_clcb_by_conn_id(uint16_t conn_id) {
125   uint8_t i_clcb;
126   tGATT_PROFILE_CLCB* p_clcb = NULL;
127 
128   for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS;
129        i_clcb++, p_clcb++) {
130     if (p_clcb->in_use && p_clcb->conn_id == conn_id) return p_clcb;
131   }
132 
133   return NULL;
134 }
135 
136 /*******************************************************************************
137  *
138  * Function         gatt_profile_find_clcb_by_bd_addr
139  *
140  * Description      The function searches all LCBs with macthing bd address.
141  *
142  * Returns          Pointer to the found link conenction control block.
143  *
144  ******************************************************************************/
gatt_profile_find_clcb_by_bd_addr(const RawAddress & bda,tBT_TRANSPORT transport)145 static tGATT_PROFILE_CLCB* gatt_profile_find_clcb_by_bd_addr(
146     const RawAddress& bda, tBT_TRANSPORT transport) {
147   uint8_t i_clcb;
148   tGATT_PROFILE_CLCB* p_clcb = NULL;
149 
150   for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS;
151        i_clcb++, p_clcb++) {
152     if (p_clcb->in_use && p_clcb->transport == transport && p_clcb->connected &&
153         p_clcb->bda == bda)
154       return p_clcb;
155   }
156 
157   return NULL;
158 }
159 
160 /*******************************************************************************
161  *
162  * Function         gatt_profile_clcb_alloc
163  *
164  * Description      The function allocates a GATT profile connection link
165  *                  control block
166  *
167  * Returns          NULL if not found. Otherwise pointer to the connection link
168  *                  block.
169  *
170  ******************************************************************************/
gatt_profile_clcb_alloc(uint16_t conn_id,const RawAddress & bda,tBT_TRANSPORT tranport)171 tGATT_PROFILE_CLCB* gatt_profile_clcb_alloc(uint16_t conn_id,
172                                             const RawAddress& bda,
173                                             tBT_TRANSPORT tranport) {
174   uint8_t i_clcb = 0;
175   tGATT_PROFILE_CLCB* p_clcb = NULL;
176 
177   for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS;
178        i_clcb++, p_clcb++) {
179     if (!p_clcb->in_use) {
180       p_clcb->in_use = true;
181       p_clcb->conn_id = conn_id;
182       p_clcb->connected = true;
183       p_clcb->transport = tranport;
184       p_clcb->bda = bda;
185       break;
186     }
187   }
188   if (i_clcb < GATT_MAX_APPS) return p_clcb;
189 
190   return NULL;
191 }
192 
193 /*******************************************************************************
194  *
195  * Function         gatt_profile_clcb_dealloc
196  *
197  * Description      The function deallocates a GATT profile connection link
198  *                  control block
199  *
200  * Returns          void
201  *
202  ******************************************************************************/
gatt_profile_clcb_dealloc(tGATT_PROFILE_CLCB * p_clcb)203 void gatt_profile_clcb_dealloc(tGATT_PROFILE_CLCB* p_clcb) {
204   memset(p_clcb, 0, sizeof(tGATT_PROFILE_CLCB));
205 }
206 
207 /** GAP Attributes Database Request callback */
read_attr_value(uint16_t conn_id,uint16_t handle,tGATT_VALUE * p_value,bool is_long)208 tGATT_STATUS read_attr_value(uint16_t conn_id, uint16_t handle,
209                              tGATT_VALUE* p_value, bool is_long) {
210   uint8_t* p = p_value->value;
211 
212   if (handle == gatt_cb.handle_sr_supported_feat) {
213     /* GATT_UUID_SERVER_SUP_FEAT*/
214     if (is_long) return GATT_NOT_LONG;
215 
216     UINT8_TO_STREAM(p, gatt_cb.gatt_svr_supported_feat_mask);
217     p_value->len = sizeof(gatt_cb.gatt_svr_supported_feat_mask);
218     return GATT_SUCCESS;
219   }
220 
221   if (handle == gatt_cb.handle_cl_supported_feat) {
222     /*GATT_UUID_CLIENT_SUP_FEAT */
223     if (is_long) return GATT_NOT_LONG;
224 
225     return gatt_sr_read_cl_supp_feat(conn_id, p_value);
226   }
227 
228   if (handle == gatt_cb.handle_of_database_hash) {
229     /* GATT_UUID_DATABASE_HASH */
230     if (is_long) return GATT_NOT_LONG;
231 
232     return gatt_sr_read_db_hash(conn_id, p_value);
233   }
234 
235   if (handle == gatt_cb.handle_of_h_r) {
236     /* GATT_UUID_GATT_SRV_CHGD */
237     return GATT_READ_NOT_PERMIT;
238   }
239 
240   return GATT_NOT_FOUND;
241 }
242 
243 /** GAP Attributes Database Read/Read Blob Request process */
proc_read_req(uint16_t conn_id,tGATTS_REQ_TYPE,tGATT_READ_REQ * p_data,tGATTS_RSP * p_rsp)244 tGATT_STATUS proc_read_req(uint16_t conn_id, tGATTS_REQ_TYPE,
245                            tGATT_READ_REQ* p_data, tGATTS_RSP* p_rsp) {
246   if (p_data->is_long) p_rsp->attr_value.offset = p_data->offset;
247 
248   p_rsp->attr_value.handle = p_data->handle;
249 
250   return read_attr_value(conn_id, p_data->handle, &p_rsp->attr_value,
251                          p_data->is_long);
252 }
253 
254 /** GAP ATT server process a write request */
proc_write_req(uint16_t conn_id,tGATTS_REQ_TYPE,tGATT_WRITE_REQ * p_data)255 tGATT_STATUS proc_write_req(uint16_t conn_id, tGATTS_REQ_TYPE,
256                             tGATT_WRITE_REQ* p_data) {
257   uint16_t handle = p_data->handle;
258 
259   /* GATT_UUID_SERVER_SUP_FEAT*/
260   if (handle == gatt_cb.handle_sr_supported_feat) return GATT_WRITE_NOT_PERMIT;
261 
262   /* GATT_UUID_CLIENT_SUP_FEAT*/
263   if (handle == gatt_cb.handle_cl_supported_feat)
264     return gatt_sr_write_cl_supp_feat(conn_id, p_data);
265 
266   /* GATT_UUID_DATABASE_HASH */
267   if (handle == gatt_cb.handle_of_database_hash) return GATT_WRITE_NOT_PERMIT;
268 
269   /* GATT_UUID_GATT_SRV_CHGD */
270   if (handle == gatt_cb.handle_of_h_r) return GATT_WRITE_NOT_PERMIT;
271 
272   return GATT_NOT_FOUND;
273 }
274 
275 /*******************************************************************************
276  *
277  * Function         gatt_request_cback
278  *
279  * Description      GATT profile attribute access request callback.
280  *
281  * Returns          void.
282  *
283  ******************************************************************************/
gatt_request_cback(uint16_t conn_id,uint32_t trans_id,tGATTS_REQ_TYPE type,tGATTS_DATA * p_data)284 static void gatt_request_cback(uint16_t conn_id, uint32_t trans_id,
285                                tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) {
286   tGATT_STATUS status = GATT_INVALID_PDU;
287   tGATTS_RSP rsp_msg;
288   bool rsp_needed = true;
289 
290   memset(&rsp_msg, 0, sizeof(tGATTS_RSP));
291 
292   switch (type) {
293     case GATTS_REQ_TYPE_READ_CHARACTERISTIC:
294     case GATTS_REQ_TYPE_READ_DESCRIPTOR:
295       status = proc_read_req(conn_id, type, &p_data->read_req, &rsp_msg);
296       break;
297 
298     case GATTS_REQ_TYPE_WRITE_CHARACTERISTIC:
299     case GATTS_REQ_TYPE_WRITE_DESCRIPTOR:
300     case GATTS_REQ_TYPE_WRITE_EXEC:
301     case GATT_CMD_WRITE:
302       if (!p_data->write_req.need_rsp) rsp_needed = false;
303 
304       status = proc_write_req(conn_id, type, &p_data->write_req);
305       break;
306 
307     case GATTS_REQ_TYPE_MTU:
308       VLOG(1) << "Get MTU exchange new mtu size: " << +p_data->mtu;
309       rsp_needed = false;
310       break;
311 
312     default:
313       VLOG(1) << "Unknown/unexpected LE GAP ATT request: " << loghex(type);
314       break;
315   }
316 
317   if (rsp_needed) GATTS_SendRsp(conn_id, trans_id, status, &rsp_msg);
318 }
319 
320 /*******************************************************************************
321  *
322  * Function         gatt_connect_cback
323  *
324  * Description      Gatt profile connection callback.
325  *
326  * Returns          void
327  *
328  ******************************************************************************/
gatt_connect_cback(UNUSED_ATTR tGATT_IF gatt_if,const RawAddress & bda,uint16_t conn_id,bool connected,tGATT_DISCONN_REASON reason,tBT_TRANSPORT transport)329 static void gatt_connect_cback(UNUSED_ATTR tGATT_IF gatt_if,
330                                const RawAddress& bda, uint16_t conn_id,
331                                bool connected, tGATT_DISCONN_REASON reason,
332                                tBT_TRANSPORT transport) {
333   VLOG(1) << __func__ << ": from " << bda << " connected: " << connected
334           << ", conn_id: " << loghex(conn_id);
335 
336   // if the device is not trusted, remove data when the link is disconnected
337   if (!connected && !btm_sec_is_a_bonded_dev(bda)) {
338     LOG(INFO) << __func__ << ": remove untrusted client status, bda=" << bda;
339     btif_storage_remove_gatt_cl_supp_feat(bda);
340     btif_storage_remove_gatt_cl_db_hash(bda);
341   }
342 
343   tGATT_PROFILE_CLCB* p_clcb =
344       gatt_profile_find_clcb_by_bd_addr(bda, transport);
345   if (p_clcb == NULL) return;
346 
347   if (connected) {
348     p_clcb->conn_id = conn_id;
349     p_clcb->connected = true;
350 
351     if (p_clcb->ccc_stage == GATT_SVC_CHANGED_CONNECTING) {
352       p_clcb->ccc_stage++;
353       gatt_cl_start_config_ccc(p_clcb);
354     }
355   } else {
356     gatt_profile_clcb_dealloc(p_clcb);
357   }
358 }
359 
360 /*******************************************************************************
361  *
362  * Function         gatt_profile_db_init
363  *
364  * Description      Initializa the GATT profile attribute database.
365  *
366  ******************************************************************************/
gatt_profile_db_init(void)367 void gatt_profile_db_init(void) {
368   uint16_t service_handle = 0;
369 
370   /* Fill our internal UUID with a fixed pattern 0x81 */
371   std::array<uint8_t, Uuid::kNumBytes128> tmp;
372   tmp.fill(0x81);
373 
374   /* Create a GATT profile service */
375   gatt_cb.gatt_if = GATT_Register(Uuid::From128BitBE(tmp), "GattProfileDb",
376                                   &gatt_profile_cback, false);
377   GATT_StartIf(gatt_cb.gatt_if);
378 
379   Uuid service_uuid = Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER);
380 
381   Uuid srv_changed_char_uuid = Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD);
382   Uuid svr_sup_feat_uuid = Uuid::From16Bit(GATT_UUID_SERVER_SUP_FEAT);
383   Uuid cl_sup_feat_uuid = Uuid::From16Bit(GATT_UUID_CLIENT_SUP_FEAT);
384   Uuid database_hash_uuid = Uuid::From16Bit(GATT_UUID_DATABASE_HASH);
385 
386   btgatt_db_element_t service[] = {
387       {
388           .uuid = service_uuid,
389           .type = BTGATT_DB_PRIMARY_SERVICE,
390       },
391       {
392           .uuid = srv_changed_char_uuid,
393           .type = BTGATT_DB_CHARACTERISTIC,
394           .properties = GATT_CHAR_PROP_BIT_INDICATE,
395           .permissions = 0,
396       },
397       {
398           .type = BTGATT_DB_CHARACTERISTIC,
399           .uuid = svr_sup_feat_uuid,
400           .properties = GATT_CHAR_PROP_BIT_READ,
401           .permissions = GATT_PERM_READ,
402       },
403       {
404           .type = BTGATT_DB_CHARACTERISTIC,
405           .uuid = cl_sup_feat_uuid,
406           .properties = GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE,
407           .permissions = GATT_PERM_READ | GATT_PERM_WRITE,
408       },
409       {
410           .uuid = database_hash_uuid,
411           .type = BTGATT_DB_CHARACTERISTIC,
412           .properties = GATT_CHAR_PROP_BIT_READ,
413           .permissions = GATT_PERM_READ,
414       }};
415 
416   GATTS_AddService(gatt_cb.gatt_if, service,
417                    sizeof(service) / sizeof(btgatt_db_element_t));
418 
419   service_handle = service[0].attribute_handle;
420   gatt_cb.handle_of_h_r = service[1].attribute_handle;
421   gatt_cb.handle_sr_supported_feat = service[2].attribute_handle;
422   gatt_cb.handle_cl_supported_feat = service[3].attribute_handle;
423   gatt_cb.handle_of_database_hash = service[4].attribute_handle;
424 
425   gatt_cb.gatt_svr_supported_feat_mask |= BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK;
426   gatt_cb.gatt_cl_supported_feat_mask |= BLE_GATT_CL_ANDROID_SUP_FEAT;
427 
428   if (gatt_sr_is_robust_caching_enabled())
429     gatt_cb.gatt_cl_supported_feat_mask |= BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK;
430 
431   VLOG(1) << __func__ << ": gatt_if=" << gatt_cb.gatt_if << " EATT supported";
432 }
433 
434 /*******************************************************************************
435  *
436  * Function         gatt_disc_res_cback
437  *
438  * Description      Gatt profile discovery result callback
439  *
440  * Returns          void
441  *
442  ******************************************************************************/
gatt_disc_res_cback(uint16_t conn_id,tGATT_DISC_TYPE disc_type,tGATT_DISC_RES * p_data)443 static void gatt_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type,
444                                 tGATT_DISC_RES* p_data) {
445   tGATT_PROFILE_CLCB* p_clcb = gatt_profile_find_clcb_by_conn_id(conn_id);
446 
447   if (p_clcb == NULL) return;
448 
449   switch (disc_type) {
450     case GATT_DISC_SRVC_BY_UUID: /* stage 1 */
451       p_clcb->e_handle = p_data->value.group_value.e_handle;
452       p_clcb->ccc_result++;
453       break;
454 
455     case GATT_DISC_CHAR: /* stage 2 */
456       p_clcb->s_handle = p_data->value.dclr_value.val_handle;
457       p_clcb->ccc_result++;
458       break;
459 
460     case GATT_DISC_CHAR_DSCPT: /* stage 3 */
461       if (p_data->type == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) {
462         p_clcb->s_handle = p_data->handle;
463         p_clcb->ccc_result++;
464       }
465       break;
466 
467     case GATT_DISC_SRVC_ALL:
468     case GATT_DISC_INC_SRVC:
469     case GATT_DISC_MAX:
470       LOG_ERROR("Illegal discovery item handled");
471       break;
472   }
473 }
474 
475 /*******************************************************************************
476  *
477  * Function         gatt_disc_cmpl_cback
478  *
479  * Description      Gatt profile discovery complete callback
480  *
481  * Returns          void
482  *
483  ******************************************************************************/
gatt_disc_cmpl_cback(uint16_t conn_id,tGATT_DISC_TYPE disc_type,tGATT_STATUS status)484 static void gatt_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type,
485                                  tGATT_STATUS status) {
486   tGATT_PROFILE_CLCB* p_clcb = gatt_profile_find_clcb_by_conn_id(conn_id);
487   if (p_clcb == NULL) {
488     LOG_WARN("Unable to find gatt profile after discovery complete");
489     return;
490   }
491 
492   if (status != GATT_SUCCESS) {
493     LOG_WARN("Gatt discovery completed with errors status:%u", status);
494     return;
495   }
496   if (p_clcb->ccc_result == 0) {
497     LOG_WARN("Gatt discovery completed but connection was idle id:%hu",
498              conn_id);
499     return;
500   }
501 
502   p_clcb->ccc_result = 0;
503   p_clcb->ccc_stage++;
504   gatt_cl_start_config_ccc(p_clcb);
505 }
506 
gatt_svc_read_cl_supp_feat_req(uint16_t conn_id,gatt_op_cb_data * cb)507 static bool gatt_svc_read_cl_supp_feat_req(uint16_t conn_id,
508                                            gatt_op_cb_data* cb) {
509   tGATT_READ_PARAM param;
510 
511   memset(&param, 0, sizeof(tGATT_READ_PARAM));
512 
513   param.service.s_handle = 1;
514   param.service.e_handle = 0xFFFF;
515   param.service.auth_req = 0;
516 
517   param.service.uuid = bluetooth::Uuid::From16Bit(GATT_UUID_CLIENT_SUP_FEAT);
518 
519   tGATT_STATUS status = GATTC_Read(conn_id, GATT_READ_BY_TYPE, &param);
520   if (status != GATT_SUCCESS) {
521     LOG(ERROR) << __func__ << " Read failed. Status: "
522                << loghex(static_cast<uint8_t>(status));
523     return false;
524   }
525 
526   cb->op_uuid = GATT_UUID_CLIENT_SUP_FEAT;
527   return true;
528 }
529 
gatt_att_write_cl_supp_feat(uint16_t conn_id,uint16_t handle)530 static bool gatt_att_write_cl_supp_feat(uint16_t conn_id, uint16_t handle) {
531   tGATT_VALUE attr;
532 
533   memset(&attr, 0, sizeof(tGATT_VALUE));
534 
535   attr.conn_id = conn_id;
536   attr.handle = handle;
537   attr.len = 1;
538   attr.value[0] = gatt_cb.gatt_cl_supported_feat_mask;
539 
540   tGATT_STATUS status = GATTC_Write(conn_id, GATT_WRITE, &attr);
541   if (status != GATT_SUCCESS) {
542     LOG(ERROR) << __func__ << " Write failed. Status: "
543                << loghex(static_cast<uint8_t>(status));
544     return false;
545   }
546 
547   return true;
548 }
549 
550 /*******************************************************************************
551  *
552  * Function         gatt_cl_op_cmpl_cback
553  *
554  * Description      Gatt profile client operation complete callback
555  *
556  * Returns          void
557  *
558  ******************************************************************************/
gatt_cl_op_cmpl_cback(uint16_t conn_id,tGATTC_OPTYPE op,tGATT_STATUS status,tGATT_CL_COMPLETE * p_data)559 static void gatt_cl_op_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op,
560                                   tGATT_STATUS status,
561                                   tGATT_CL_COMPLETE* p_data) {
562   auto iter = OngoingOps.find(conn_id);
563 
564   VLOG(1) << __func__ << " opcode: " << loghex(static_cast<uint8_t>(op))
565           << " status: " << status
566           << " conn id: " << loghex(static_cast<uint8_t>(conn_id));
567 
568   if (op != GATTC_OPTYPE_READ) return;
569 
570   if (iter == OngoingOps.end()) {
571     LOG(ERROR) << __func__ << " Unexpected read complete";
572     return;
573   }
574 
575   gatt_op_cb_data* operation_callback_data = &iter->second;
576   uint16_t cl_op_uuid = operation_callback_data->op_uuid;
577   operation_callback_data->op_uuid = 0;
578 
579   uint8_t* pp = p_data->att_value.value;
580 
581   VLOG(1) << __func__ << " cl_op_uuid " << loghex(cl_op_uuid);
582 
583   switch (cl_op_uuid) {
584     case GATT_UUID_SERVER_SUP_FEAT: {
585       uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id);
586       tGATT_TCB& tcb = gatt_cb.tcb[tcb_idx];
587 
588       /* Check if EATT is supported */
589       if (status == GATT_SUCCESS) {
590         STREAM_TO_UINT8(tcb.sr_supp_feat, pp);
591         btif_storage_set_gatt_sr_supp_feat(tcb.peer_bda, tcb.sr_supp_feat);
592       }
593 
594       /* Notify user about the supported features */
595       std::move(operation_callback_data->cb)
596           .Run(tcb.peer_bda, tcb.sr_supp_feat);
597 
598       /* If server supports EATT lets try to find handle for the
599        * client supported features characteristic, where we could write
600        * our supported features as a client.
601        */
602       if (tcb.sr_supp_feat & BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK) {
603         /* If read succeed, return here */
604         if (gatt_svc_read_cl_supp_feat_req(conn_id, operation_callback_data))
605           return;
606       }
607 
608       /* Could not read client supported charcteristic or eatt is not
609        * supported. Erase callback data now.
610        */
611       OngoingOps.erase(iter);
612       break;
613     }
614     case GATT_UUID_CLIENT_SUP_FEAT:
615       /*We don't need callback data anymore */
616       OngoingOps.erase(iter);
617 
618       if (status != GATT_SUCCESS) {
619         LOG(INFO) << __func__
620                   << " Client supported features charcteristic not found";
621         return;
622       }
623 
624       /* Write our client supported features to the remote device */
625       gatt_att_write_cl_supp_feat(conn_id, p_data->att_value.handle);
626       break;
627   }
628 }
629 
630 /*******************************************************************************
631  *
632  * Function         gatt_cl_start_config_ccc
633  *
634  * Description      Gatt profile start configure service change CCC
635  *
636  * Returns          void
637  *
638  ******************************************************************************/
gatt_cl_start_config_ccc(tGATT_PROFILE_CLCB * p_clcb)639 static void gatt_cl_start_config_ccc(tGATT_PROFILE_CLCB* p_clcb) {
640 
641   VLOG(1) << __func__ << ": stage: " << +p_clcb->ccc_stage;
642 
643   switch (p_clcb->ccc_stage) {
644     case GATT_SVC_CHANGED_SERVICE: /* discover GATT service */
645       GATTC_Discover(p_clcb->conn_id, GATT_DISC_SRVC_BY_UUID, 0x0001, 0xffff,
646                      Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER));
647       break;
648 
649     case GATT_SVC_CHANGED_CHARACTERISTIC: /* discover service change char */
650       GATTC_Discover(p_clcb->conn_id, GATT_DISC_CHAR, 0x0001, p_clcb->e_handle,
651                      Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD));
652       break;
653 
654     case GATT_SVC_CHANGED_DESCRIPTOR: /* discover service change ccc */
655       GATTC_Discover(p_clcb->conn_id, GATT_DISC_CHAR_DSCPT, p_clcb->s_handle,
656                      p_clcb->e_handle);
657       break;
658 
659     case GATT_SVC_CHANGED_CONFIGURE_CCCD: /* write ccc */
660     {
661       tGATT_VALUE ccc_value;
662       memset(&ccc_value, 0, sizeof(tGATT_VALUE));
663       ccc_value.handle = p_clcb->s_handle;
664       ccc_value.len = 2;
665       ccc_value.value[0] = GATT_CLT_CONFIG_INDICATION;
666       GATTC_Write(p_clcb->conn_id, GATT_WRITE, &ccc_value);
667       break;
668     }
669   }
670 }
671 
672 /*******************************************************************************
673  *
674  * Function         GATT_ConfigServiceChangeCCC
675  *
676  * Description      Configure service change indication on remote device
677  *
678  * Returns          none
679  *
680  ******************************************************************************/
GATT_ConfigServiceChangeCCC(const RawAddress & remote_bda,bool enable,tBT_TRANSPORT transport)681 void GATT_ConfigServiceChangeCCC(const RawAddress& remote_bda, bool enable,
682                                  tBT_TRANSPORT transport) {
683   tGATT_PROFILE_CLCB* p_clcb =
684       gatt_profile_find_clcb_by_bd_addr(remote_bda, transport);
685 
686   if (p_clcb == NULL)
687     p_clcb = gatt_profile_clcb_alloc(0, remote_bda, transport);
688 
689   if (p_clcb == NULL) return;
690 
691   if (GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &p_clcb->conn_id,
692                                 transport)) {
693     p_clcb->connected = true;
694   }
695   /* hold the link here */
696   GATT_Connect(gatt_cb.gatt_if, remote_bda, true, transport, true);
697   p_clcb->ccc_stage = GATT_SVC_CHANGED_CONNECTING;
698 
699   if (!p_clcb->connected) {
700     /* wait for connection */
701     return;
702   }
703 
704   p_clcb->ccc_stage++;
705   gatt_cl_start_config_ccc(p_clcb);
706 }
707 
708 /*******************************************************************************
709  *
710  * Function         gatt_cl_init_sr_status
711  *
712  * Description      Restore status for trusted GATT Server device
713  *
714  * Returns          none
715  *
716  ******************************************************************************/
gatt_cl_init_sr_status(tGATT_TCB & tcb)717 void gatt_cl_init_sr_status(tGATT_TCB& tcb) {
718   tcb.sr_supp_feat = btif_storage_get_sr_supp_feat(tcb.peer_bda);
719 
720   if (tcb.sr_supp_feat & BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK)
721     bluetooth::eatt::EattExtension::AddFromStorage(tcb.peer_bda);
722 }
723 
724 /*******************************************************************************
725  *
726  * Function         gatt_cl_read_sr_supp_feat_req
727  *
728  * Description      Read remote device supported GATT feature mask.
729  *
730  * Returns          bool
731  *
732  ******************************************************************************/
gatt_cl_read_sr_supp_feat_req(const RawAddress & peer_bda,base::OnceCallback<void (const RawAddress &,uint8_t)> cb)733 bool gatt_cl_read_sr_supp_feat_req(
734     const RawAddress& peer_bda,
735     base::OnceCallback<void(const RawAddress&, uint8_t)> cb) {
736   tGATT_PROFILE_CLCB* p_clcb;
737   tGATT_READ_PARAM param;
738   uint16_t conn_id;
739 
740   if (!cb) return false;
741 
742   VLOG(1) << __func__ << " BDA: " << peer_bda
743           << " read gatt supported features";
744 
745   GATT_GetConnIdIfConnected(gatt_cb.gatt_if, peer_bda, &conn_id,
746                             BT_TRANSPORT_LE);
747   if (conn_id == GATT_INVALID_CONN_ID) return false;
748 
749   p_clcb = gatt_profile_find_clcb_by_conn_id(conn_id);
750   if (!p_clcb) {
751     p_clcb = gatt_profile_clcb_alloc(conn_id, peer_bda, BT_TRANSPORT_LE);
752   }
753 
754   if (!p_clcb) {
755     VLOG(1) << __func__ << " p_clcb is NULL " << loghex(conn_id);
756     return false;
757   }
758 
759   auto it = OngoingOps.find(conn_id);
760   if (it != OngoingOps.end()) {
761     LOG(ERROR) << __func__ << " There is ongoing operation for conn_id: "
762                << loghex(conn_id);
763     return false;
764   }
765 
766   memset(&param, 0, sizeof(tGATT_READ_PARAM));
767 
768   param.service.s_handle = 1;
769   param.service.e_handle = 0xFFFF;
770   param.service.auth_req = 0;
771 
772   param.service.uuid = bluetooth::Uuid::From16Bit(GATT_UUID_SERVER_SUP_FEAT);
773 
774   if (GATTC_Read(conn_id, GATT_READ_BY_TYPE, &param) != GATT_SUCCESS) {
775     LOG(ERROR) << __func__ << " Read GATT Support features GATT_Read Failed";
776     return false;
777   }
778 
779   gatt_op_cb_data cb_data;
780   cb_data.cb = std::move(cb);
781   cb_data.op_uuid = GATT_UUID_SERVER_SUP_FEAT;
782   OngoingOps[conn_id] = std::move(cb_data);
783 
784   return true;
785 }
786 
787 /*******************************************************************************
788  *
789  * Function         gatt_profile_get_eatt_support
790  *
791  * Description      Check if EATT is supported with remote device.
792  *
793  * Returns          if EATT is supported.
794  *
795  ******************************************************************************/
gatt_profile_get_eatt_support(const RawAddress & remote_bda)796 bool gatt_profile_get_eatt_support(const RawAddress& remote_bda) {
797   uint16_t conn_id;
798 
799   VLOG(1) << __func__ << " BDA: " << remote_bda << " read GATT support";
800 
801   GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id,
802                             BT_TRANSPORT_LE);
803 
804   /* This read is important only when connected */
805   if (conn_id == GATT_INVALID_CONN_ID) return false;
806 
807   /* Get tcb info */
808   uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id);
809   tGATT_TCB& tcb = gatt_cb.tcb[tcb_idx];
810   return tcb.sr_supp_feat & BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK;
811 }
812 
813 /*******************************************************************************
814  *
815  * Function         gatt_sr_is_robust_caching_enabled
816  *
817  * Description      Check if Robust Caching is enabled on server side.
818  *
819  * Returns          true if enabled in gd flag, otherwise false
820  *
821  ******************************************************************************/
gatt_sr_is_robust_caching_enabled()822 static bool gatt_sr_is_robust_caching_enabled() {
823   return bluetooth::common::init_flags::gatt_robust_caching_is_enabled();
824 }
825 
826 /*******************************************************************************
827  *
828  * Function         gatt_sr_is_cl_robust_caching_supported
829  *
830  * Description      Check if Robust Caching is supported for the connection
831  *
832  * Returns          true if enabled by client side, otherwise false
833  *
834  ******************************************************************************/
gatt_sr_is_cl_robust_caching_supported(tGATT_TCB & tcb)835 static bool gatt_sr_is_cl_robust_caching_supported(tGATT_TCB& tcb) {
836   // if robust caching is not enabled, should always return false
837   if (!gatt_sr_is_robust_caching_enabled()) return false;
838   return (tcb.cl_supp_feat & BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK);
839 }
840 
841 /*******************************************************************************
842  *
843  * Function         gatt_sr_is_cl_change_aware
844  *
845  * Description      Check if the connection is change-aware
846  *
847  * Returns          true if change aware, otherwise false
848  *
849  ******************************************************************************/
gatt_sr_is_cl_change_aware(tGATT_TCB & tcb)850 bool gatt_sr_is_cl_change_aware(tGATT_TCB& tcb) {
851   // if robust caching is not supported, should always return true by default
852   if (!gatt_sr_is_cl_robust_caching_supported(tcb)) return true;
853   return tcb.is_robust_cache_change_aware;
854 }
855 
856 /*******************************************************************************
857  *
858  * Function         gatt_sr_init_cl_status
859  *
860  * Description      Restore status for trusted device
861  *
862  * Returns          none
863  *
864  ******************************************************************************/
gatt_sr_init_cl_status(tGATT_TCB & tcb)865 void gatt_sr_init_cl_status(tGATT_TCB& tcb) {
866   tcb.cl_supp_feat = btif_storage_get_gatt_cl_supp_feat(tcb.peer_bda);
867   // This is used to reset bit when robust caching is disabled
868   if (!gatt_sr_is_robust_caching_enabled()) {
869     tcb.cl_supp_feat &= ~BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK;
870   }
871 
872   if (gatt_sr_is_cl_robust_caching_supported(tcb)) {
873     Octet16 stored_hash = btif_storage_get_gatt_cl_db_hash(tcb.peer_bda);
874     tcb.is_robust_cache_change_aware = (stored_hash == gatt_cb.database_hash);
875   } else {
876     // set default value for untrusted device
877     tcb.is_robust_cache_change_aware = true;
878   }
879 
880   LOG(INFO) << __func__ << ": bda=" << tcb.peer_bda
881             << ", cl_supp_feat=" << loghex(tcb.cl_supp_feat)
882             << ", aware=" << tcb.is_robust_cache_change_aware;
883 }
884 
885 /*******************************************************************************
886  *
887  * Function         gatt_sr_update_cl_status
888  *
889  * Description      Update change-aware status for the remote device
890  *
891  * Returns          none
892  *
893  ******************************************************************************/
gatt_sr_update_cl_status(tGATT_TCB & tcb,bool chg_aware)894 void gatt_sr_update_cl_status(tGATT_TCB& tcb, bool chg_aware) {
895   // if robust caching is not supported, do nothing
896   if (!gatt_sr_is_cl_robust_caching_supported(tcb)) return;
897 
898   // only when client status is changed from change-unaware to change-aware, we
899   // can then store database hash into btif_storage
900   if (!tcb.is_robust_cache_change_aware && chg_aware) {
901     btif_storage_set_gatt_cl_db_hash(tcb.peer_bda, gatt_cb.database_hash);
902   }
903 
904   // only when the status is changed, print the log
905   if (tcb.is_robust_cache_change_aware != chg_aware) {
906     LOG(INFO) << __func__ << ": bda=" << tcb.peer_bda
907               << ", chg_aware=" << chg_aware;
908   }
909 
910   tcb.is_robust_cache_change_aware = chg_aware;
911 }
912 
913 /* handle request for reading database hash */
gatt_sr_read_db_hash(uint16_t conn_id,tGATT_VALUE * p_value)914 static tGATT_STATUS gatt_sr_read_db_hash(uint16_t conn_id,
915                                          tGATT_VALUE* p_value) {
916   LOG(INFO) << __func__ << ": conn_id=" << loghex(conn_id);
917 
918   uint8_t* p = p_value->value;
919   Octet16& db_hash = gatt_cb.database_hash;
920   ARRAY_TO_STREAM(p, db_hash.data(), (uint16_t)db_hash.size());
921   p_value->len = (uint16_t)db_hash.size();
922 
923   // Every time when database hash is requested, reset flag.
924   uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id);
925   gatt_sr_update_cl_status(gatt_cb.tcb[tcb_idx], /* chg_aware= */ true);
926   return GATT_SUCCESS;
927 }
928 
929 /* handle request for reading client supported features */
gatt_sr_read_cl_supp_feat(uint16_t conn_id,tGATT_VALUE * p_value)930 static tGATT_STATUS gatt_sr_read_cl_supp_feat(uint16_t conn_id,
931                                               tGATT_VALUE* p_value) {
932   // Get tcb info
933   uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id);
934   tGATT_TCB& tcb = gatt_cb.tcb[tcb_idx];
935 
936   uint8_t* p = p_value->value;
937   UINT8_TO_STREAM(p, tcb.cl_supp_feat);
938   p_value->len = 1;
939 
940   return GATT_SUCCESS;
941 }
942 
943 /* handle request for writing client supported features */
gatt_sr_write_cl_supp_feat(uint16_t conn_id,tGATT_WRITE_REQ * p_data)944 static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id,
945                                                tGATT_WRITE_REQ* p_data) {
946   std::list<uint8_t> tmp;
947   uint16_t len = p_data->len;
948   uint8_t value, *p = p_data->value;
949   // Read all octets into list
950   while (len > 0) {
951     STREAM_TO_UINT8(value, p);
952     tmp.push_back(value);
953     len--;
954   }
955   // Remove trailing zero octets
956   while (!tmp.empty()) {
957     if (tmp.back() != 0x00) break;
958     tmp.pop_back();
959   }
960 
961   // Get tcb info
962   uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id);
963   tGATT_TCB& tcb = gatt_cb.tcb[tcb_idx];
964 
965   std::list<uint8_t> feature_list;
966   feature_list.push_back(tcb.cl_supp_feat);
967 
968   // If input length is zero, return value_not_allowed
969   if (tmp.empty()) {
970     LOG(INFO) << __func__ << ": zero length, conn_id=" << loghex(conn_id)
971               << ", bda=" << tcb.peer_bda;
972     return GATT_VALUE_NOT_ALLOWED;
973   }
974   // if original length is longer than new one, it must be the bit reset case.
975   if (feature_list.size() > tmp.size()) {
976     LOG(INFO) << __func__ << ": shorter length, conn_id=" << loghex(conn_id)
977               << ", bda=" << tcb.peer_bda;
978     return GATT_VALUE_NOT_ALLOWED;
979   }
980   // new length is longer or equals to the original, need to check bits
981   // one by one. Here we use bit-wise operation.
982   // 1. Use XOR to locate the change bit, val_xor is the change bit mask
983   // 2. Use AND for val_xor and *it_new to get val_and
984   // 3. If val_and != val_xor, it means the change is from 1 to 0
985   auto it_old = feature_list.cbegin();
986   auto it_new = tmp.cbegin();
987   for (; it_old != feature_list.cend(); it_old++, it_new++) {
988     uint8_t val_xor = *it_old ^ *it_new;
989     uint8_t val_and = val_xor & *it_new;
990     if (val_and != val_xor) {
991       LOG(INFO) << __func__
992                 << ": bit cannot be reset, conn_id=" << loghex(conn_id)
993                 << ", bda=" << tcb.peer_bda;
994       return GATT_VALUE_NOT_ALLOWED;
995     }
996   }
997 
998   // get current robust caching status before setting new one
999   bool curr_caching_state = gatt_sr_is_cl_robust_caching_supported(tcb);
1000 
1001   tcb.cl_supp_feat = tmp.front();
1002   if (!gatt_sr_is_robust_caching_enabled()) {
1003     // remove robust caching bit
1004     tcb.cl_supp_feat &= ~BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK;
1005     LOG(INFO) << __func__
1006               << ": reset robust caching bit, conn_id=" << loghex(conn_id)
1007               << ", bda=" << tcb.peer_bda;
1008   }
1009   // TODO(hylo): save data as byte array
1010   btif_storage_set_gatt_cl_supp_feat(tcb.peer_bda, tcb.cl_supp_feat);
1011 
1012   // get new robust caching status after setting new one
1013   bool new_caching_state = gatt_sr_is_cl_robust_caching_supported(tcb);
1014   // only when the first time robust caching request, print the log
1015   if (!curr_caching_state && new_caching_state) {
1016     LOG(INFO) << __func__ << ": robust caching enabled by client"
1017               << ", conn_id=" << loghex(conn_id);
1018   }
1019 
1020   return GATT_SUCCESS;
1021 }
1022