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