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 action functions for the state
22  *  machine.
23  *
24  ******************************************************************************/
25 
26 #define LOG_TAG "bt_bta_gattc"
27 
28 #include <base/functional/bind.h>
29 #include <base/strings/stringprintf.h>
30 #include <bluetooth/log.h>
31 #include <com_android_bluetooth_flags.h>
32 
33 #include "bta/gatt/bta_gattc_int.h"
34 #include "bta/include/bta_api.h"
35 #include "btif/include/btif_debug_conn.h"
36 #include "hardware/bt_gatt_types.h"
37 #include "hci/controller_interface.h"
38 #include "internal_include/bt_trace.h"
39 #include "main/shim/entry.h"
40 #include "os/log.h"
41 #include "osi/include/allocator.h"
42 #include "stack/include/bt_hdr.h"
43 #include "stack/include/bt_uuid16.h"
44 #include "stack/include/btm_ble_api_types.h"
45 #include "stack/include/btm_sec_api.h"
46 #include "stack/include/l2c_api.h"
47 #include "stack/include/main_thread.h"
48 #include "types/bluetooth/uuid.h"
49 #include "types/raw_address.h"
50 
51 using base::StringPrintf;
52 using bluetooth::Uuid;
53 using namespace bluetooth;
54 
55 /*****************************************************************************
56  *  Constants
57  ****************************************************************************/
58 static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bda,
59                                  uint16_t conn_id, bool connected,
60                                  tGATT_DISCONN_REASON reason,
61                                  tBT_TRANSPORT transport);
62 
63 static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op,
64                                  tGATT_STATUS status,
65                                  tGATT_CL_COMPLETE* p_data);
66 static void bta_gattc_deregister_cmpl(tBTA_GATTC_RCB* p_clreg);
67 static void bta_gattc_enc_cmpl_cback(tGATT_IF gattc_if, const RawAddress& bda);
68 static void bta_gattc_cong_cback(uint16_t conn_id, bool congested);
69 static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id,
70                                        uint8_t tx_phy, uint8_t rx_phy,
71                                        tGATT_STATUS status);
72 static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id,
73                                         uint16_t interval, uint16_t latency,
74                                         uint16_t timeout, tGATT_STATUS status);
75 static void bta_gattc_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id,
76                                         uint16_t subrate_factor,
77                                         uint16_t latency, uint16_t cont_num,
78                                         uint16_t timeout, tGATT_STATUS status);
79 static void bta_gattc_init_bk_conn(const tBTA_GATTC_API_OPEN* p_data,
80                                    tBTA_GATTC_RCB* p_clreg);
81 
82 static tGATT_CBACK bta_gattc_cl_cback = {
83     .p_conn_cb = bta_gattc_conn_cback,
84     .p_cmpl_cb = bta_gattc_cmpl_cback,
85     .p_disc_res_cb = bta_gattc_disc_res_cback,
86     .p_disc_cmpl_cb = bta_gattc_disc_cmpl_cback,
87     .p_req_cb = nullptr,
88     .p_enc_cmpl_cb = bta_gattc_enc_cmpl_cback,
89     .p_congestion_cb = bta_gattc_cong_cback,
90     .p_phy_update_cb = bta_gattc_phy_update_cback,
91     .p_conn_update_cb = bta_gattc_conn_update_cback,
92     .p_subrate_chg_cb = bta_gattc_subrate_chg_cback,
93 };
94 
95 /* opcode(tGATTC_OPTYPE) order has to be comply with internal event order */
96 static uint16_t bta_gattc_opcode_to_int_evt[] = {
97     /* Skip: GATTC_OPTYPE_NONE */
98     /* Skip: GATTC_OPTYPE_DISCOVERY */
99     BTA_GATTC_API_READ_EVT,   /* GATTC_OPTYPE_READ */
100     BTA_GATTC_API_WRITE_EVT,  /* GATTC_OPTYPE_WRITE */
101     BTA_GATTC_API_EXEC_EVT,   /* GATTC_OPTYPE_EXE_WRITE */
102     BTA_GATTC_API_CFG_MTU_EVT /* GATTC_OPTYPE_CONFIG */
103 };
104 
105 static const char* bta_gattc_op_code_name[] = {
106     "Unknown",      /* GATTC_OPTYPE_NONE */
107     "Discovery",    /* GATTC_OPTYPE_DISCOVERY */
108     "Read",         /* GATTC_OPTYPE_READ */
109     "Write",        /* GATTC_OPTYPE_WRITE */
110     "Exec",         /* GATTC_OPTYPE_EXE_WRITE */
111     "Config",       /* GATTC_OPTYPE_CONFIG */
112     "Notification", /* GATTC_OPTYPE_NOTIFICATION */
113     "Indication"    /* GATTC_OPTYPE_INDICATION */
114 };
115 
116 /*****************************************************************************
117  *  Action Functions
118  ****************************************************************************/
119 
120 void bta_gattc_reset_discover_st(tBTA_GATTC_SERV* p_srcb, tGATT_STATUS status);
121 
122 /** Enables GATTC module */
bta_gattc_enable()123 static void bta_gattc_enable() {
124   log::verbose("");
125 
126   if (bta_gattc_cb.state == BTA_GATTC_STATE_DISABLED) {
127     /* initialize control block */
128     bta_gattc_cb = tBTA_GATTC_CB();
129     bta_gattc_cb.state = BTA_GATTC_STATE_ENABLED;
130   } else {
131     log::verbose("GATTC is already enabled");
132   }
133 }
134 
135 /** Disable GATTC module by cleaning up all active connections and deregister
136  * all application */
bta_gattc_disable()137 void bta_gattc_disable() {
138   uint8_t i;
139 
140   log::verbose("");
141 
142   if (bta_gattc_cb.state != BTA_GATTC_STATE_ENABLED) {
143     log::error("not enabled, or disabled in progress");
144     return;
145   }
146 
147   for (i = 0; i < BTA_GATTC_CL_MAX; i++) {
148     if (!bta_gattc_cb.cl_rcb[i].in_use) continue;
149 
150     bta_gattc_cb.state = BTA_GATTC_STATE_DISABLING;
151     bta_gattc_deregister(&bta_gattc_cb.cl_rcb[i]);
152   }
153 
154   /* no registered apps, indicate disable completed */
155   if (bta_gattc_cb.state != BTA_GATTC_STATE_DISABLING) {
156     bta_gattc_cb = tBTA_GATTC_CB();
157     bta_gattc_cb.state = BTA_GATTC_STATE_DISABLED;
158   }
159 }
160 
161 /** start an application interface */
bta_gattc_start_if(uint8_t client_if)162 static void bta_gattc_start_if(uint8_t client_if) {
163   log::debug("client_if={}", client_if);
164   if (!bta_gattc_cl_get_regcb(client_if)) {
165     log::error("Unable to start app.: Unknown client_if={}", client_if);
166     return;
167   }
168 
169   GATT_StartIf(client_if);
170 }
171 
172 /** Register a GATT client application with BTA */
bta_gattc_register(const Uuid & app_uuid,tBTA_GATTC_CBACK * p_cback,BtaAppRegisterCallback cb,bool eatt_support)173 void bta_gattc_register(const Uuid& app_uuid, tBTA_GATTC_CBACK* p_cback,
174                         BtaAppRegisterCallback cb, bool eatt_support) {
175   tGATT_STATUS status = GATT_NO_RESOURCES;
176   uint8_t client_if = 0;
177   log::debug("state: {}, uuid={}", bta_gattc_cb.state, app_uuid.ToString());
178 
179   /* check if  GATTC module is already enabled . Else enable */
180   if (bta_gattc_cb.state == BTA_GATTC_STATE_DISABLED) {
181     log::debug("GATTC module not enabled, enabling it");
182     bta_gattc_enable();
183   }
184   /* todo need to check duplicate uuid */
185   for (uint8_t i = 0; i < BTA_GATTC_CL_MAX; i++) {
186     if (!bta_gattc_cb.cl_rcb[i].in_use) {
187       bta_gattc_cb.cl_rcb[i].client_if = GATT_Register(
188           app_uuid, "GattClient", &bta_gattc_cl_cback, eatt_support);
189       if (bta_gattc_cb.cl_rcb[i].client_if == 0) {
190         log::error(
191             "Register with GATT stack failed with index {}, trying next index",
192             i);
193         status = GATT_ERROR;
194       } else {
195         bta_gattc_cb.cl_rcb[i].in_use = true;
196         bta_gattc_cb.cl_rcb[i].p_cback = p_cback;
197         bta_gattc_cb.cl_rcb[i].app_uuid = app_uuid;
198 
199         /* BTA use the same client interface as BTE GATT statck */
200         client_if = bta_gattc_cb.cl_rcb[i].client_if;
201 
202         log::debug(
203             "Registered GATT client interface {} with uuid={}, starting it on "
204             "main thread",
205             client_if, app_uuid.ToString());
206 
207         do_in_main_thread(FROM_HERE,
208                           base::BindOnce(&bta_gattc_start_if, client_if));
209 
210         status = GATT_SUCCESS;
211         break;
212       }
213     }
214   }
215 
216   if (!cb.is_null()) {
217     cb.Run(client_if, status);
218   } else {
219     log::warn("No GATT callback available, client_if={}, status={}", client_if,
220               status);
221   }
222 }
223 
224 /** De-Register a GATT client application with BTA */
bta_gattc_deregister(tBTA_GATTC_RCB * p_clreg)225 void bta_gattc_deregister(tBTA_GATTC_RCB* p_clreg) {
226   uint8_t accept_list_size = 0;
227   if (bluetooth::shim::GetController()->SupportsBle()) {
228     accept_list_size =
229         bluetooth::shim::GetController()->GetLeFilterAcceptListSize();
230   }
231 
232   /* remove bg connection associated with this rcb */
233   for (uint8_t i = 0; i < accept_list_size; i++) {
234     if (!bta_gattc_cb.bg_track[i].in_use) continue;
235 
236     if (bta_gattc_cb.bg_track[i].cif_mask & ((tBTA_GATTC_CIF_MASK)1 << (p_clreg->client_if - 1))) {
237       bta_gattc_mark_bg_conn(p_clreg->client_if,
238                              bta_gattc_cb.bg_track[i].remote_bda, false);
239       if (!GATT_CancelConnect(p_clreg->client_if,
240                               bta_gattc_cb.bg_track[i].remote_bda, false)) {
241         log::warn(
242             "Unable to cancel GATT connection client_if:{} peer:{} "
243             "is_direct:{}",
244             p_clreg->client_if, bta_gattc_cb.bg_track[i].remote_bda, false);
245       }
246     }
247   }
248 
249   if (p_clreg->num_clcb == 0) {
250     bta_gattc_deregister_cmpl(p_clreg);
251     return;
252   }
253 
254   /* close all CLCB related to this app */
255   for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) {
256     if (!bta_gattc_cb.clcb[i].in_use || (bta_gattc_cb.clcb[i].p_rcb != p_clreg))
257       continue;
258 
259     p_clreg->dereg_pending = true;
260 
261     BT_HDR_RIGID buf;
262     buf.event = BTA_GATTC_API_CLOSE_EVT;
263     buf.layer_specific = bta_gattc_cb.clcb[i].bta_conn_id;
264     bta_gattc_close(&bta_gattc_cb.clcb[i], (tBTA_GATTC_DATA*)&buf);
265   }
266 }
267 
268 /** process connect API request */
bta_gattc_process_api_open(const tBTA_GATTC_DATA * p_msg)269 void bta_gattc_process_api_open(const tBTA_GATTC_DATA* p_msg) {
270   uint16_t event = ((BT_HDR_RIGID*)p_msg)->event;
271 
272   tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(p_msg->api_conn.client_if);
273   if (!p_clreg) {
274     log::error("Failed, unknown client_if={}", p_msg->api_conn.client_if);
275     return;
276   }
277 
278   if (p_msg->api_conn.connection_type != BTM_BLE_DIRECT_CONNECTION) {
279     bta_gattc_init_bk_conn(&p_msg->api_conn, p_clreg);
280     return;
281   }
282 
283   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_alloc_clcb(
284       p_msg->api_conn.client_if, p_msg->api_conn.remote_bda,
285       p_msg->api_conn.transport);
286   if (p_clcb != nullptr) {
287     bta_gattc_sm_execute(p_clcb, event, p_msg);
288   } else {
289     log::error("No resources to open a new connection.");
290 
291     bta_gattc_send_open_cback(p_clreg, GATT_NO_RESOURCES,
292                               p_msg->api_conn.remote_bda, GATT_INVALID_CONN_ID,
293                               p_msg->api_conn.transport, 0);
294   }
295 }
296 
297 /** process connect API request */
bta_gattc_process_api_open_cancel(const tBTA_GATTC_DATA * p_msg)298 void bta_gattc_process_api_open_cancel(const tBTA_GATTC_DATA* p_msg) {
299   log::assert_that(p_msg != nullptr, "assert failed: p_msg != nullptr");
300 
301   uint16_t event = ((BT_HDR_RIGID*)p_msg)->event;
302 
303   if (!p_msg->api_cancel_conn.is_direct) {
304     log::debug("Cancel GATT client background connection");
305     bta_gattc_cancel_bk_conn(&p_msg->api_cancel_conn);
306     return;
307   }
308   log::debug("Cancel GATT client direct connection");
309 
310   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_cif(
311       p_msg->api_cancel_conn.client_if, p_msg->api_cancel_conn.remote_bda,
312       BT_TRANSPORT_LE);
313   if (p_clcb != NULL) {
314     bta_gattc_sm_execute(p_clcb, event, p_msg);
315     return;
316   }
317 
318   log::error("No such connection need to be cancelled");
319 
320   tBTA_GATTC_RCB* p_clreg =
321       bta_gattc_cl_get_regcb(p_msg->api_cancel_conn.client_if);
322 
323   if (p_clreg && p_clreg->p_cback) {
324     tBTA_GATTC cb_data;
325     cb_data.status = GATT_ERROR;
326     (*p_clreg->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
327   }
328 }
329 
330 /** process encryption complete message */
bta_gattc_process_enc_cmpl(tGATT_IF client_if,const RawAddress & bda)331 static void bta_gattc_process_enc_cmpl(tGATT_IF client_if,
332                                        const RawAddress& bda) {
333   tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(client_if);
334 
335   if (!p_clreg || !p_clreg->p_cback) return;
336 
337   tBTA_GATTC cb_data;
338   memset(&cb_data, 0, sizeof(tBTA_GATTC));
339 
340   cb_data.enc_cmpl.client_if = client_if;
341   cb_data.enc_cmpl.remote_bda = bda;
342 
343   (*p_clreg->p_cback)(BTA_GATTC_ENC_CMPL_CB_EVT, &cb_data);
344 }
345 
bta_gattc_cancel_open_error(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA *)346 void bta_gattc_cancel_open_error(tBTA_GATTC_CLCB* p_clcb,
347                                  const tBTA_GATTC_DATA* /* p_data */) {
348   tBTA_GATTC cb_data;
349 
350   cb_data.status = GATT_ERROR;
351 
352   if (p_clcb && p_clcb->p_rcb && p_clcb->p_rcb->p_cback)
353     (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
354 }
355 
bta_gattc_open_error(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA *)356 void bta_gattc_open_error(tBTA_GATTC_CLCB* p_clcb,
357                           const tBTA_GATTC_DATA* /* p_data */) {
358   log::error("Connection already opened. wrong state");
359 
360   bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_SUCCESS, p_clcb->bda,
361                             p_clcb->bta_conn_id, p_clcb->transport, 0);
362 }
363 
bta_gattc_open_fail(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)364 void bta_gattc_open_fail(tBTA_GATTC_CLCB* p_clcb,
365                          const tBTA_GATTC_DATA* p_data) {
366   if (com::android::bluetooth::flags::enumerate_gatt_errors() &&
367       p_data->int_conn.reason == GATT_CONN_TIMEOUT) {
368     log::warn(
369         "Connection timed out after 30 seconds. conn_id=0x{:x}. Return "
370         "GATT_CONNECTION_TIMEOUT({})",
371         p_clcb->bta_conn_id, GATT_CONNECTION_TIMEOUT);
372     bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_CONNECTION_TIMEOUT,
373                               p_clcb->bda, p_clcb->bta_conn_id,
374                               p_clcb->transport, 0);
375   } else {
376     log::warn(
377         "Cannot establish Connection. conn_id=0x{:x}. Return GATT_ERROR({})",
378         p_clcb->bta_conn_id, GATT_ERROR);
379     bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_ERROR, p_clcb->bda,
380                               p_clcb->bta_conn_id, p_clcb->transport, 0);
381   }
382 
383   /* open failure, remove clcb */
384   bta_gattc_clcb_dealloc(p_clcb);
385 }
386 
387 /** Process API connection function */
bta_gattc_open(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)388 void bta_gattc_open(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
389   tBTA_GATTC_DATA gattc_data;
390 
391   /* open/hold a connection */
392   if (!GATT_Connect(p_clcb->p_rcb->client_if, p_data->api_conn.remote_bda,
393                     p_data->api_conn.remote_addr_type,
394                     BTM_BLE_DIRECT_CONNECTION, p_data->api_conn.transport,
395                     p_data->api_conn.opportunistic,
396                     p_data->api_conn.initiating_phys)) {
397     log::error("Connection open failure");
398     bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_OPEN_FAIL_EVT, p_data);
399     return;
400   }
401 
402   tBTA_GATTC_RCB* p_clreg = p_clcb->p_rcb;
403   /* Re-enable notification registration for closed connection */
404   for (int i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) {
405     if (p_clreg->notif_reg[i].in_use &&
406         p_clreg->notif_reg[i].remote_bda == p_clcb->bda &&
407         p_clreg->notif_reg[i].app_disconnected) {
408       p_clreg->notif_reg[i].app_disconnected = false;
409     }
410   }
411 
412   /* a connected remote device */
413   if (GATT_GetConnIdIfConnected(
414           p_clcb->p_rcb->client_if, p_data->api_conn.remote_bda,
415           &p_clcb->bta_conn_id, p_data->api_conn.transport)) {
416     gattc_data.int_conn.hdr.layer_specific = p_clcb->bta_conn_id;
417 
418     bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CONN_EVT, &gattc_data);
419   }
420   /* else wait for the callback event */
421 }
422 
423 /** Process API Open for a background connection */
bta_gattc_init_bk_conn(const tBTA_GATTC_API_OPEN * p_data,tBTA_GATTC_RCB * p_clreg)424 static void bta_gattc_init_bk_conn(const tBTA_GATTC_API_OPEN* p_data,
425                                    tBTA_GATTC_RCB* p_clreg) {
426   if (!bta_gattc_mark_bg_conn(p_data->client_if, p_data->remote_bda, true)) {
427     log::warn("Unable to find space for accept list connection mask");
428     bta_gattc_send_open_cback(p_clreg, GATT_NO_RESOURCES, p_data->remote_bda,
429                               GATT_INVALID_CONN_ID, BT_TRANSPORT_LE, 0);
430     return;
431   }
432 
433   /* always call open to hold a connection */
434   if (!GATT_Connect(p_data->client_if, p_data->remote_bda,
435                     p_data->connection_type, p_data->transport, false)) {
436     log::error("Unable to connect to remote bd_addr={}", p_data->remote_bda);
437     bta_gattc_send_open_cback(p_clreg, GATT_ILLEGAL_PARAMETER,
438                               p_data->remote_bda, GATT_INVALID_CONN_ID,
439                               BT_TRANSPORT_LE, 0);
440     return;
441   }
442 
443   uint16_t conn_id;
444   if (!GATT_GetConnIdIfConnected(p_data->client_if, p_data->remote_bda,
445                                  &conn_id, p_data->transport)) {
446     log::info("Not a connected remote device yet");
447     return;
448   }
449 
450   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_alloc_clcb(
451       p_data->client_if, p_data->remote_bda, BT_TRANSPORT_LE);
452   if (!p_clcb) {
453     log::warn("Unable to find connection link for device:{}",
454               p_data->remote_bda);
455     return;
456   }
457 
458   p_clcb->bta_conn_id = conn_id;
459   tBTA_GATTC_DATA gattc_data = {
460       .hdr =
461           {
462               .layer_specific = conn_id,
463           },
464   };
465 
466   /* open connection */
467   bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CONN_EVT,
468                        static_cast<const tBTA_GATTC_DATA*>(&gattc_data));
469 }
470 
471 /** Process API Cancel Open for a background connection */
bta_gattc_cancel_bk_conn(const tBTA_GATTC_API_CANCEL_OPEN * p_data)472 void bta_gattc_cancel_bk_conn(const tBTA_GATTC_API_CANCEL_OPEN* p_data) {
473   tBTA_GATTC_RCB* p_clreg;
474   tBTA_GATTC cb_data;
475   cb_data.status = GATT_ERROR;
476 
477   /* remove the device from the bg connection mask */
478   if (bta_gattc_mark_bg_conn(p_data->client_if, p_data->remote_bda, false)) {
479     if (GATT_CancelConnect(p_data->client_if, p_data->remote_bda, false)) {
480       cb_data.status = GATT_SUCCESS;
481     } else {
482       log::error("failed for client_if={}, remote_bda={}, is_direct=false",
483                  static_cast<int>(p_data->client_if), p_data->remote_bda);
484     }
485   }
486   p_clreg = bta_gattc_cl_get_regcb(p_data->client_if);
487 
488   if (p_clreg && p_clreg->p_cback) {
489     (*p_clreg->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
490   }
491 }
492 
bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA *)493 void bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB* p_clcb,
494                               const tBTA_GATTC_DATA* /* p_data */) {
495   tBTA_GATTC cb_data;
496 
497   if (p_clcb->p_rcb->p_cback) {
498     cb_data.status = GATT_SUCCESS;
499     (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
500   }
501 
502   bta_gattc_clcb_dealloc(p_clcb);
503 }
504 
bta_gattc_cancel_open(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)505 void bta_gattc_cancel_open(tBTA_GATTC_CLCB* p_clcb,
506                            const tBTA_GATTC_DATA* p_data) {
507   tBTA_GATTC cb_data;
508 
509   if (GATT_CancelConnect(p_clcb->p_rcb->client_if,
510                          p_data->api_cancel_conn.remote_bda, true)) {
511     bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CANCEL_OPEN_OK_EVT, p_data);
512   } else {
513     if (p_clcb->p_rcb->p_cback) {
514       cb_data.status = GATT_ERROR;
515       (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
516     }
517   }
518 }
519 
520 /** receive connection callback from stack */
bta_gattc_conn(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)521 void bta_gattc_conn(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
522   tGATT_IF gatt_if;
523   log::verbose("server cache state={}", p_clcb->p_srcb->state);
524 
525   if (p_data != NULL) {
526     log::verbose("conn_id=0x{:x}", p_data->hdr.layer_specific);
527     p_clcb->bta_conn_id = p_data->int_conn.hdr.layer_specific;
528 
529     if (!GATT_GetConnectionInfor(p_data->hdr.layer_specific, &gatt_if,
530                                  p_clcb->bda, &p_clcb->transport)) {
531       log::warn("Unable to get GATT connection information peer:{}",
532                 p_clcb->bda);
533     }
534   }
535 
536   p_clcb->p_srcb->connected = true;
537 
538   if (p_clcb->p_srcb->mtu == 0) p_clcb->p_srcb->mtu = GATT_DEF_BLE_MTU_SIZE;
539 
540   tBTA_GATTC_RCB* p_clreg = p_clcb->p_rcb;
541   /* Re-enable notification registration for closed connection */
542   for (int i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) {
543     if (p_clreg->notif_reg[i].in_use &&
544         p_clreg->notif_reg[i].remote_bda == p_clcb->bda &&
545         p_clreg->notif_reg[i].app_disconnected) {
546       p_clreg->notif_reg[i].app_disconnected = false;
547     }
548   }
549 
550   /* start database cache if needed */
551   if (p_clcb->p_srcb->gatt_database.IsEmpty() ||
552       p_clcb->p_srcb->state != BTA_GATTC_SERV_IDLE) {
553     if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) {
554       p_clcb->p_srcb->state = BTA_GATTC_SERV_LOAD;
555       // Consider the case that if GATT Server is changed, but no service
556       // changed indication is received, the database might be out of date. So
557       // if robust caching is known to be supported, always check the db hash
558       // first, before loading the stored database.
559 
560       // Only load the database if we are bonded, since the device cache is
561       // meaningless otherwise (as we need to do rediscovery regardless)
562       gatt::Database db = btm_sec_is_a_bonded_dev(p_clcb->bda)
563                               ? bta_gattc_cache_load(p_clcb->p_srcb->server_bda)
564                               : gatt::Database();
565       auto robust_caching_support = GetRobustCachingSupport(p_clcb, db);
566       log::info("Connected to {}, robust caching support is {}",
567                 p_clcb->bda.ToRedactedStringForLogging(),
568                 robust_caching_support);
569 
570       if (!db.IsEmpty()) p_clcb->p_srcb->gatt_database = db;
571 
572       if (db.IsEmpty() ||
573           robust_caching_support != RobustCachingSupport::UNSUPPORTED) {
574         // If the peer device is expected to support robust caching, or if we
575         // don't know its services yet, then we should do discovery (which may
576         // short-circuit through a hash match, but might also do the full
577         // discovery).
578         p_clcb->p_srcb->state = BTA_GATTC_SERV_DISC;
579 
580         /* set true to read database hash before service discovery */
581         p_clcb->p_srcb->srvc_hdl_db_hash = true;
582 
583         /* cache load failure, start discovery */
584         bta_gattc_start_discover(p_clcb, NULL);
585       } else {
586         p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE;
587         bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS);
588       }
589     } else /* cache is building */
590       p_clcb->state = BTA_GATTC_DISCOVER_ST;
591   }
592 
593   else {
594     /* a pending service handle change indication */
595     if (p_clcb->p_srcb->srvc_hdl_chg) {
596       p_clcb->p_srcb->srvc_hdl_chg = false;
597 
598       /* set true to read database hash before service discovery */
599       p_clcb->p_srcb->srvc_hdl_db_hash = true;
600 
601       /* start discovery */
602       bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
603     }
604   }
605 
606   if (p_clcb->p_rcb) {
607     /* there is no RM for GATT */
608     if (p_clcb->transport == BT_TRANSPORT_BR_EDR)
609       bta_sys_conn_open(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
610 
611     bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_SUCCESS, p_clcb->bda,
612                               p_clcb->bta_conn_id, p_clcb->transport,
613                               p_clcb->p_srcb->mtu);
614   }
615 }
616 
617 /** close a  connection */
bta_gattc_close_fail(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)618 void bta_gattc_close_fail(tBTA_GATTC_CLCB* p_clcb,
619                           const tBTA_GATTC_DATA* p_data) {
620   tBTA_GATTC cb_data;
621 
622   if (p_clcb->p_rcb->p_cback) {
623     memset(&cb_data, 0, sizeof(tBTA_GATTC));
624     cb_data.close.client_if = p_clcb->p_rcb->client_if;
625     cb_data.close.conn_id = p_data->hdr.layer_specific;
626     cb_data.close.remote_bda = p_clcb->bda;
627     cb_data.close.reason = BTA_GATT_CONN_NONE;
628     cb_data.close.status = GATT_ERROR;
629 
630     log::warn("conn_id=0x{:x}. Returns GATT_ERROR({}).", cb_data.close.conn_id,
631               GATT_ERROR);
632 
633     (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CLOSE_EVT, &cb_data);
634   }
635 }
636 
637 /** close a GATTC connection */
bta_gattc_close(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)638 void bta_gattc_close(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
639   tBTA_GATTC_CBACK* p_cback = p_clcb->p_rcb->p_cback;
640   tBTA_GATTC_RCB* p_clreg = p_clcb->p_rcb;
641   tBTA_GATTC cb_data = {
642       .close =
643           {
644               .conn_id = p_clcb->bta_conn_id,
645               .status = GATT_SUCCESS,
646               .client_if = p_clcb->p_rcb->client_if,
647               .remote_bda = p_clcb->bda,
648               .reason = GATT_CONN_OK,
649           },
650   };
651 
652   if (p_clcb->transport == BT_TRANSPORT_BR_EDR) {
653     bta_sys_conn_close(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
654   }
655 
656   /* Disable notification registration for closed connection */
657   for (int i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) {
658     if (p_clreg->notif_reg[i].in_use &&
659         p_clreg->notif_reg[i].remote_bda == p_clcb->bda) {
660       p_clreg->notif_reg[i].app_disconnected = true;
661     }
662   }
663 
664   if (p_data->hdr.event == BTA_GATTC_INT_DISCONN_EVT) {
665     /* Since link has been disconnected by and it is possible that here are
666      * already some new p_clcb created for the background connect, the number of
667      * p_srcb->num_clcb is NOT 0. This will prevent p_srcb to be cleared inside
668      * the bta_gattc_clcb_dealloc.
669      *
670      * In this point of time, we know that link does not exist, so let's make
671      * sure the connection state, mtu and database is cleared.
672      */
673     bta_gattc_server_disconnected(p_clcb->p_srcb);
674   }
675 
676   bta_gattc_clcb_dealloc(p_clcb);
677 
678   if (p_data->hdr.event == BTA_GATTC_API_CLOSE_EVT) {
679     cb_data.close.status = GATT_Disconnect(p_data->hdr.layer_specific);
680     cb_data.close.reason = GATT_CONN_TERMINATE_LOCAL_HOST;
681     log::debug("Local close event client_if:{} conn_id:{} reason:{}",
682                cb_data.close.client_if, cb_data.close.conn_id,
683                gatt_disconnection_reason_text(
684                    static_cast<tGATT_DISCONN_REASON>(cb_data.close.reason)));
685   } else if (p_data->hdr.event == BTA_GATTC_INT_DISCONN_EVT) {
686     cb_data.close.status = static_cast<tGATT_STATUS>(p_data->int_conn.reason);
687     cb_data.close.reason = p_data->int_conn.reason;
688     log::debug("Peer close disconnect event client_if:{} conn_id:{} reason:{}",
689                cb_data.close.client_if, cb_data.close.conn_id,
690                gatt_disconnection_reason_text(
691                    static_cast<tGATT_DISCONN_REASON>(cb_data.close.reason)));
692   }
693 
694   if (p_cback) (*p_cback)(BTA_GATTC_CLOSE_EVT, &cb_data);
695 
696   if (p_clreg->num_clcb == 0 && p_clreg->dereg_pending) {
697     bta_gattc_deregister_cmpl(p_clreg);
698   }
699 }
700 
701 /** when a SRCB finished discovery, tell all related clcb */
bta_gattc_reset_discover_st(tBTA_GATTC_SERV * p_srcb,tGATT_STATUS status)702 void bta_gattc_reset_discover_st(tBTA_GATTC_SERV* p_srcb, tGATT_STATUS status) {
703   for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) {
704     if (bta_gattc_cb.clcb[i].p_srcb == p_srcb) {
705       bta_gattc_cb.clcb[i].status = status;
706       bta_gattc_sm_execute(&bta_gattc_cb.clcb[i], BTA_GATTC_DISCOVER_CMPL_EVT,
707                            NULL);
708     }
709   }
710 }
711 
712 /** close a GATTC connection while in discovery state */
bta_gattc_disc_close(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)713 void bta_gattc_disc_close(tBTA_GATTC_CLCB* p_clcb,
714                           const tBTA_GATTC_DATA* p_data) {
715   log::verbose("Discovery cancel conn_id=0x{:x}", p_clcb->bta_conn_id);
716 
717   if (p_clcb->disc_active ||
718       (com::android::bluetooth::flags::gatt_rediscover_on_canceled() &&
719        (p_clcb->request_during_discovery ==
720             BTA_GATTC_DISCOVER_REQ_READ_DB_HASH ||
721         p_clcb->request_during_discovery ==
722             BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG))) {
723     bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_ERROR);
724   } else {
725     p_clcb->state = BTA_GATTC_CONN_ST;
726   }
727 
728   // This function only gets called as the result of a BTA_GATTC_API_CLOSE_EVT
729   // while in the BTA_GATTC_DISCOVER_ST state. Once the state changes, the
730   // connection itself still needs to be closed to resolve the original event.
731   if (p_clcb->state == BTA_GATTC_CONN_ST) {
732     log::verbose(
733         "State is back to BTA_GATTC_CONN_ST. Trigger connection close");
734     bta_gattc_close(p_clcb, p_data);
735   }
736 }
737 
738 /** when a SRCB start discovery, tell all related clcb and set the state */
bta_gattc_set_discover_st(tBTA_GATTC_SERV * p_srcb)739 static void bta_gattc_set_discover_st(tBTA_GATTC_SERV* p_srcb) {
740   for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) {
741     if (bta_gattc_cb.clcb[i].p_srcb == p_srcb) {
742       bta_gattc_cb.clcb[i].status = GATT_SUCCESS;
743       bta_gattc_cb.clcb[i].state = BTA_GATTC_DISCOVER_ST;
744       bta_gattc_cb.clcb[i].request_during_discovery =
745           BTA_GATTC_DISCOVER_REQ_NONE;
746     }
747   }
748 }
749 
750 /** process service change in discovery state, mark up the auto update flag and
751  * set status to be discovery cancel for current discovery.
752  */
bta_gattc_restart_discover(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA *)753 void bta_gattc_restart_discover(tBTA_GATTC_CLCB* p_clcb,
754                                 const tBTA_GATTC_DATA* /* p_data */) {
755   p_clcb->status = GATT_CANCEL;
756   p_clcb->auto_update = BTA_GATTC_DISC_WAITING;
757 }
758 
759 /** Configure MTU size on the GATT connection */
bta_gattc_cfg_mtu(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)760 void bta_gattc_cfg_mtu(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
761   uint16_t current_mtu = 0;
762   auto result = GATTC_TryMtuRequest(p_clcb->bda, p_clcb->transport,
763                                     p_clcb->bta_conn_id, &current_mtu);
764   switch (result) {
765     case MTU_EXCHANGE_DEVICE_DISCONNECTED:
766       log::info("Device {} disconnected", p_clcb->bda);
767       bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG,
768                              GATT_NO_RESOURCES, NULL);
769       bta_gattc_continue(p_clcb);
770       return;
771     case MTU_EXCHANGE_NOT_ALLOWED:
772       log::info("Not allowed for BR/EDR devices {}", p_clcb->bda);
773       bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG,
774                              GATT_ERR_UNLIKELY, NULL);
775       bta_gattc_continue(p_clcb);
776       return;
777     case MTU_EXCHANGE_ALREADY_DONE:
778       /* Check if MTU is not already set, if so, just report it back to the user
779        * and continue with other requests.
780        */
781       GATTC_UpdateUserAttMtuIfNeeded(p_clcb->bda, p_clcb->transport,
782                                      p_data->api_mtu.mtu);
783       bta_gattc_send_mtu_response(p_clcb, p_data, current_mtu);
784       return;
785     case MTU_EXCHANGE_IN_PROGRESS:
786       log::info("Enqueue MTU Request  - waiting for response on p_clcb {}",
787                 fmt::ptr(p_clcb));
788       /* MTU request is in progress and this one will not be sent to remote
789        * device. Just push back on the queue and response will be sent up to
790        * the upper layer when MTU Exchange will be completed.
791        */
792       p_clcb->p_q_cmd_queue.push_back(p_data);
793       return;
794 
795     case MTU_EXCHANGE_NOT_DONE_YET:
796       /* OK to proceed */
797       break;
798   }
799 
800   if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return;
801 
802   tGATT_STATUS status =
803       GATTC_ConfigureMTU(p_clcb->bta_conn_id, p_data->api_mtu.mtu);
804 
805   /* if failed, return callback here */
806   if (status != GATT_SUCCESS && status != GATT_CMD_STARTED) {
807     /* Dequeue the data, if it was enqueued */
808     if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
809 
810     bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, status,
811                            NULL);
812     bta_gattc_continue(p_clcb);
813   }
814 }
815 
bta_gattc_start_discover_internal(tBTA_GATTC_CLCB * p_clcb)816 void bta_gattc_start_discover_internal(tBTA_GATTC_CLCB* p_clcb) {
817   if (p_clcb->transport == BT_TRANSPORT_LE)
818     L2CA_LockBleConnParamsForServiceDiscovery(p_clcb->p_srcb->server_bda, true);
819 
820   bta_gattc_init_cache(p_clcb->p_srcb);
821   p_clcb->status = bta_gattc_discover_pri_service(
822       p_clcb->bta_conn_id, p_clcb->p_srcb, GATT_DISC_SRVC_ALL);
823   if (p_clcb->status != GATT_SUCCESS) {
824     log::error("discovery on server failed");
825     bta_gattc_reset_discover_st(p_clcb->p_srcb, p_clcb->status);
826   } else
827     p_clcb->disc_active = true;
828 }
829 
830 static void bta_gattc_continue_with_version_and_cache_known(
831     tBTA_GATTC_CLCB* p_clcb, RobustCachingSupport cache_support,
832     bool is_svc_chg);
833 
834 /** Start a discovery on server */
bta_gattc_start_discover(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA *)835 void bta_gattc_start_discover(tBTA_GATTC_CLCB* p_clcb,
836                               const tBTA_GATTC_DATA* /* p_data */) {
837   log::verbose("conn_id:0x{:x} p_clcb->p_srcb->state:{}", p_clcb->bta_conn_id,
838                p_clcb->p_srcb->state);
839 
840   if (((p_clcb->p_q_cmd == NULL ||
841         p_clcb->auto_update == BTA_GATTC_REQ_WAITING) &&
842        p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) ||
843       p_clcb->p_srcb->state == BTA_GATTC_SERV_DISC)
844   /* no pending operation, start discovery right away */
845   {
846     p_clcb->auto_update = BTA_GATTC_NO_SCHEDULE;
847 
848     if (p_clcb->p_srcb == NULL) {
849       log::error("unknown device, can not start discovery");
850       return;
851     }
852 
853     /* set all srcb related clcb into discovery ST */
854     bta_gattc_set_discover_st(p_clcb->p_srcb);
855 
856     // Before clear mask, set is_svc_chg to
857     // 1. true, invoked by service changed indication
858     // 2. false, invoked by connect API
859     bool is_svc_chg = p_clcb->p_srcb->srvc_hdl_chg;
860 
861     /* clear the service change mask */
862     p_clcb->p_srcb->srvc_hdl_chg = false;
863     p_clcb->p_srcb->update_count = 0;
864     p_clcb->p_srcb->state = BTA_GATTC_SERV_DISC_ACT;
865     p_clcb->p_srcb->disc_blocked_waiting_on_version = false;
866 
867     auto cache_support =
868         GetRobustCachingSupport(p_clcb, p_clcb->p_srcb->gatt_database);
869     if (cache_support == RobustCachingSupport::W4_REMOTE_VERSION) {
870       log::info(
871           "Pausing service discovery till remote version is read conn_id:{}",
872           p_clcb->bta_conn_id);
873       p_clcb->p_srcb->disc_blocked_waiting_on_version = true;
874       p_clcb->p_srcb->blocked_conn_id = p_clcb->bta_conn_id;
875       return;
876     }
877 
878     bta_gattc_continue_with_version_and_cache_known(p_clcb, cache_support,
879                                                     is_svc_chg);
880   }
881   /* pending operation, wait until it finishes */
882   else {
883     p_clcb->auto_update = BTA_GATTC_DISC_WAITING;
884 
885     if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE)
886       p_clcb->state = BTA_GATTC_CONN_ST; /* set clcb state */
887   }
888 }
889 
bta_gattc_continue_discovery_if_needed(const RawAddress & bd_addr,uint16_t)890 void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr,
891                                             uint16_t /* acl_handle */) {
892   tBTA_GATTC_SERV* p_srcb = bta_gattc_find_srvr_cache(bd_addr);
893   if (!p_srcb || !p_srcb->disc_blocked_waiting_on_version) {
894     return;
895   }
896 
897   uint16_t conn_id = p_srcb->blocked_conn_id;
898 
899   p_srcb->disc_blocked_waiting_on_version = false;
900   p_srcb->blocked_conn_id = 0;
901 
902   log::info("Received remote version, continue service discovery for {}",
903             bd_addr);
904 
905   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
906 
907   if (!p_clcb) {
908     log::error("Can't find CLCB to continue service discovery, id:{}", conn_id);
909     return;
910   }
911 
912   bool is_svc_chg = p_clcb->p_srcb->srvc_hdl_chg;
913 
914   auto cache_support =
915       GetRobustCachingSupport(p_clcb, p_clcb->p_srcb->gatt_database);
916   bta_gattc_continue_with_version_and_cache_known(p_clcb, cache_support,
917                                                   is_svc_chg);
918 }
919 
bta_gattc_continue_with_version_and_cache_known(tBTA_GATTC_CLCB * p_clcb,RobustCachingSupport cache_support,bool is_svc_chg)920 void bta_gattc_continue_with_version_and_cache_known(
921     tBTA_GATTC_CLCB* p_clcb, RobustCachingSupport cache_support,
922     bool is_svc_chg) {
923   if (cache_support == RobustCachingSupport::UNSUPPORTED ||
924       (com::android::bluetooth::flags::skip_unknown_robust_caching() &&
925        cache_support == RobustCachingSupport::UNKNOWN)) {
926     // Skip initial DB hash read if no DB hash is known, or if
927     // we have strong reason (due to interop,
928     // or a prior discovery) to believe that it is unsupported.
929     p_clcb->p_srcb->srvc_hdl_db_hash = false;
930   }
931 
932   /* read db hash if db hash characteristic exists */
933   if (p_clcb->p_srcb->srvc_hdl_db_hash &&
934       bta_gattc_read_db_hash(p_clcb, is_svc_chg)) {
935     log::info("pending service discovery, read db hash first conn_id:0x{:x}",
936               p_clcb->bta_conn_id);
937     p_clcb->p_srcb->srvc_hdl_db_hash = false;
938     return;
939   }
940   bta_gattc_start_discover_internal(p_clcb);
941 }
942 
943 /** discovery on server is finished */
bta_gattc_disc_cmpl(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA *)944 void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB* p_clcb,
945                          const tBTA_GATTC_DATA* /* p_data */) {
946   const tBTA_GATTC_DATA* p_q_cmd = p_clcb->p_q_cmd;
947 
948   log::verbose("conn_id=0x{:x}", p_clcb->bta_conn_id);
949 
950   if (p_clcb->transport == BT_TRANSPORT_LE) {
951     L2CA_LockBleConnParamsForServiceDiscovery(p_clcb->p_srcb->server_bda,
952                                               false);
953   }
954   p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE;
955   p_clcb->disc_active = false;
956 
957   if (p_clcb->status != GATT_SUCCESS) {
958     /* clean up cache */
959     if (p_clcb->p_srcb) {
960       p_clcb->p_srcb->gatt_database.Clear();
961     }
962 
963     /* used to reset cache in application */
964     bta_gattc_cache_reset(p_clcb->p_srcb->server_bda);
965   }
966 
967   if (p_clcb->p_srcb) {
968     p_clcb->p_srcb->pending_discovery.Clear();
969   }
970 
971   if (p_clcb->auto_update == BTA_GATTC_DISC_WAITING) {
972     /* start discovery again */
973     p_clcb->auto_update = BTA_GATTC_REQ_WAITING;
974     bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
975   }
976   /* get any queued command to proceed */
977   else if (p_q_cmd != NULL) {
978     p_clcb->p_q_cmd = NULL;
979     /* execute pending operation of link block still present */
980     if (L2CA_IsLinkEstablished(p_clcb->p_srcb->server_bda, p_clcb->transport)) {
981       bta_gattc_sm_execute(p_clcb, p_q_cmd->hdr.event, p_q_cmd);
982     }
983     /* if the command executed requeued the cmd, we don't
984      * want to free the underlying buffer that's being
985      * referenced by p_clcb->p_q_cmd
986      */
987     if (!bta_gattc_is_data_queued(p_clcb, p_q_cmd)) {
988       osi_free_and_reset((void**)&p_q_cmd);
989     }
990   } else {
991     bta_gattc_continue(p_clcb);
992   }
993 
994   if (p_clcb->p_rcb->p_cback) {
995     tBTA_GATTC bta_gattc;
996     bta_gattc.remote_bda = p_clcb->p_srcb->server_bda;
997     (*p_clcb->p_rcb->p_cback)(BTA_GATTC_SRVC_DISC_DONE_EVT, &bta_gattc);
998   }
999 }
1000 
1001 /** Read an attribute */
bta_gattc_read(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)1002 void bta_gattc_read(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
1003   if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return;
1004 
1005   tGATT_STATUS status;
1006   if (p_data->api_read.handle != 0) {
1007     tGATT_READ_PARAM read_param;
1008     memset(&read_param, 0, sizeof(tGATT_READ_PARAM));
1009     read_param.by_handle.handle = p_data->api_read.handle;
1010     read_param.by_handle.auth_req = p_data->api_read.auth_req;
1011     status = GATTC_Read(p_clcb->bta_conn_id, GATT_READ_BY_HANDLE, &read_param);
1012   } else {
1013     tGATT_READ_PARAM read_param;
1014     memset(&read_param, 0, sizeof(tGATT_READ_BY_TYPE));
1015 
1016     read_param.char_type.s_handle = p_data->api_read.s_handle;
1017     read_param.char_type.e_handle = p_data->api_read.e_handle;
1018     read_param.char_type.uuid = p_data->api_read.uuid;
1019     read_param.char_type.auth_req = p_data->api_read.auth_req;
1020     status = GATTC_Read(p_clcb->bta_conn_id, GATT_READ_BY_TYPE, &read_param);
1021   }
1022 
1023   /* read fail */
1024   if (status != GATT_SUCCESS) {
1025     /* Dequeue the data, if it was enqueued */
1026     if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
1027 
1028     bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_READ, status,
1029                            NULL);
1030     bta_gattc_continue(p_clcb);
1031   }
1032 }
1033 
1034 /** read multiple */
bta_gattc_read_multi(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)1035 void bta_gattc_read_multi(tBTA_GATTC_CLCB* p_clcb,
1036                           const tBTA_GATTC_DATA* p_data) {
1037   if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return;
1038 
1039   if (p_data->api_read_multi.handles.num_attr > GATT_MAX_READ_MULTI_HANDLES) {
1040     log::error("api_read_multi.num_attr > GATT_MAX_READ_MULTI_HANDLES");
1041     return;
1042   }
1043 
1044   tGATT_READ_PARAM read_param;
1045   memset(&read_param, 0, sizeof(tGATT_READ_PARAM));
1046 
1047   read_param.read_multiple.num_handles =
1048       p_data->api_read_multi.handles.num_attr;
1049   read_param.read_multiple.auth_req = p_data->api_read_multi.auth_req;
1050   read_param.read_multiple.variable_len = p_data->api_read_multi.variable_len;
1051   memcpy(&read_param.read_multiple.handles,
1052          p_data->api_read_multi.handles.handles,
1053          sizeof(uint16_t) * p_data->api_read_multi.handles.num_attr);
1054 
1055   tGATT_READ_TYPE read_type = (read_param.read_multiple.variable_len)
1056                                   ? GATT_READ_MULTIPLE_VAR_LEN
1057                                   : GATT_READ_MULTIPLE;
1058   tGATT_STATUS status = GATTC_Read(p_clcb->bta_conn_id, read_type, &read_param);
1059   /* read fail */
1060   if (status != GATT_SUCCESS) {
1061     /* Dequeue the data, if it was enqueued */
1062     if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
1063 
1064     bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_READ, status,
1065                            NULL);
1066     bta_gattc_continue(p_clcb);
1067   }
1068 }
1069 
1070 /** Write an attribute */
bta_gattc_write(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)1071 void bta_gattc_write(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
1072   if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return;
1073 
1074   tGATT_STATUS status = GATT_SUCCESS;
1075   tGATT_VALUE attr;
1076 
1077   attr.conn_id = p_clcb->bta_conn_id;
1078   attr.handle = p_data->api_write.handle;
1079   attr.offset = p_data->api_write.offset;
1080   attr.len = p_data->api_write.len;
1081   attr.auth_req = p_data->api_write.auth_req;
1082 
1083   /* Before coping to the fixed array, make sure it fits. */
1084   if (attr.len > GATT_MAX_ATTR_LEN) {
1085     status = GATT_INVALID_ATTR_LEN;
1086   } else {
1087     if (p_data->api_write.p_value)
1088       memcpy(attr.value, p_data->api_write.p_value, p_data->api_write.len);
1089 
1090     status =
1091         GATTC_Write(p_clcb->bta_conn_id, p_data->api_write.write_type, &attr);
1092   }
1093 
1094   /* write fail */
1095   if (status != GATT_SUCCESS) {
1096     /* Dequeue the data, if it was enqueued */
1097     if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
1098 
1099     bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_WRITE, status,
1100                            NULL);
1101     bta_gattc_continue(p_clcb);
1102   }
1103 }
1104 
1105 /** send execute write */
bta_gattc_execute(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)1106 void bta_gattc_execute(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
1107   if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return;
1108 
1109   tGATT_STATUS status =
1110       GATTC_ExecuteWrite(p_clcb->bta_conn_id, p_data->api_exec.is_execute);
1111   if (status != GATT_SUCCESS) {
1112     /* Dequeue the data, if it was enqueued */
1113     if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
1114 
1115     bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_EXE_WRITE, status,
1116                            NULL);
1117     bta_gattc_continue(p_clcb);
1118   }
1119 }
1120 
1121 /** send handle value confirmation */
bta_gattc_confirm(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)1122 void bta_gattc_confirm(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
1123   uint16_t cid = p_data->api_confirm.cid;
1124 
1125   if (GATTC_SendHandleValueConfirm(p_data->api_confirm.hdr.layer_specific,
1126                                    cid) != GATT_SUCCESS) {
1127     log::error("to cid=0x{:x} failed", cid);
1128   } else {
1129     /* if over BR_EDR, inform PM for mode change */
1130     if (p_clcb->transport == BT_TRANSPORT_BR_EDR) {
1131       bta_sys_busy(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
1132       bta_sys_idle(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
1133     }
1134   }
1135 }
1136 
1137 /** read complete */
bta_gattc_read_cmpl(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_OP_CMPL * p_data)1138 static void bta_gattc_read_cmpl(tBTA_GATTC_CLCB* p_clcb,
1139                                 const tBTA_GATTC_OP_CMPL* p_data) {
1140   void* my_cb_data;
1141 
1142   if (!p_clcb->p_q_cmd->api_read.is_multi_read) {
1143     GATT_READ_OP_CB cb = p_clcb->p_q_cmd->api_read.read_cb;
1144     my_cb_data = p_clcb->p_q_cmd->api_read.read_cb_data;
1145 
1146     /* if it was read by handle, return the handle requested, if read by UUID,
1147      * use handle returned from remote
1148      */
1149     uint16_t handle = p_clcb->p_q_cmd->api_read.handle;
1150     if (handle == 0) handle = p_data->p_cmpl->att_value.handle;
1151 
1152     osi_free_and_reset((void**)&p_clcb->p_q_cmd);
1153 
1154     if (cb) {
1155       cb(p_clcb->bta_conn_id, p_data->status, handle,
1156          p_data->p_cmpl->att_value.len, p_data->p_cmpl->att_value.value,
1157          my_cb_data);
1158     }
1159   } else {
1160     GATT_READ_MULTI_OP_CB cb = p_clcb->p_q_cmd->api_read_multi.read_cb;
1161     my_cb_data = p_clcb->p_q_cmd->api_read_multi.read_cb_data;
1162     tBTA_GATTC_MULTI handles = p_clcb->p_q_cmd->api_read_multi.handles;
1163 
1164     osi_free_and_reset((void**)&p_clcb->p_q_cmd);
1165 
1166     if (cb) {
1167       cb(p_clcb->bta_conn_id, p_data->status, handles,
1168          p_data->p_cmpl->att_value.len, p_data->p_cmpl->att_value.value,
1169          my_cb_data);
1170     }
1171   }
1172 }
1173 
1174 /** write complete */
bta_gattc_write_cmpl(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_OP_CMPL * p_data)1175 static void bta_gattc_write_cmpl(tBTA_GATTC_CLCB* p_clcb,
1176                                  const tBTA_GATTC_OP_CMPL* p_data) {
1177   GATT_WRITE_OP_CB cb = p_clcb->p_q_cmd->api_write.write_cb;
1178   void* my_cb_data = p_clcb->p_q_cmd->api_write.write_cb_data;
1179 
1180   if (cb) {
1181     if (p_data->status == 0 &&
1182         p_clcb->p_q_cmd->api_write.write_type == BTA_GATTC_WRITE_PREPARE) {
1183       log::debug("Handling prepare write success response: handle 0x{:04x}",
1184                  p_data->p_cmpl->att_value.handle);
1185       /* If this is successful Prepare write, lets provide to the callback the
1186        * data provided by server */
1187       cb(p_clcb->bta_conn_id, p_data->status, p_data->p_cmpl->att_value.handle,
1188          p_data->p_cmpl->att_value.len, p_data->p_cmpl->att_value.value,
1189          my_cb_data);
1190     } else {
1191       log::debug("Handling write response type: {}: handle 0x{:04x}",
1192                  p_clcb->p_q_cmd->api_write.write_type,
1193                  p_data->p_cmpl->att_value.handle);
1194       /* Otherwise, provide data which were intended to write. */
1195       cb(p_clcb->bta_conn_id, p_data->status, p_data->p_cmpl->att_value.handle,
1196          p_clcb->p_q_cmd->api_write.len, p_clcb->p_q_cmd->api_write.p_value,
1197          my_cb_data);
1198     }
1199   }
1200 
1201   osi_free_and_reset((void**)&p_clcb->p_q_cmd);
1202 }
1203 
1204 /** execute write complete */
bta_gattc_exec_cmpl(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_OP_CMPL * p_data)1205 static void bta_gattc_exec_cmpl(tBTA_GATTC_CLCB* p_clcb,
1206                                 const tBTA_GATTC_OP_CMPL* p_data) {
1207   tBTA_GATTC cb_data;
1208 
1209   osi_free_and_reset((void**)&p_clcb->p_q_cmd);
1210   p_clcb->status = GATT_SUCCESS;
1211 
1212   /* execute complete, callback */
1213   cb_data.exec_cmpl.conn_id = p_clcb->bta_conn_id;
1214   cb_data.exec_cmpl.status = p_data->status;
1215 
1216   (*p_clcb->p_rcb->p_cback)(BTA_GATTC_EXEC_EVT, &cb_data);
1217 }
1218 
1219 /** configure MTU operation complete */
bta_gattc_cfg_mtu_cmpl(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_OP_CMPL * p_data)1220 static void bta_gattc_cfg_mtu_cmpl(tBTA_GATTC_CLCB* p_clcb,
1221                                    const tBTA_GATTC_OP_CMPL* p_data) {
1222   GATT_CONFIGURE_MTU_OP_CB cb = p_clcb->p_q_cmd->api_mtu.mtu_cb;
1223   void* my_cb_data = p_clcb->p_q_cmd->api_mtu.mtu_cb_data;
1224   tBTA_GATTC cb_data;
1225 
1226   osi_free_and_reset((void**)&p_clcb->p_q_cmd);
1227 
1228   if (p_data->p_cmpl && p_data->status == GATT_SUCCESS)
1229     p_clcb->p_srcb->mtu = p_data->p_cmpl->mtu;
1230 
1231   /* configure MTU complete, callback */
1232   p_clcb->status = p_data->status;
1233   cb_data.cfg_mtu.conn_id = p_clcb->bta_conn_id;
1234   cb_data.cfg_mtu.status = p_data->status;
1235   cb_data.cfg_mtu.mtu = p_clcb->p_srcb->mtu;
1236 
1237   if (cb) {
1238     cb(p_clcb->bta_conn_id, p_data->status, my_cb_data);
1239   }
1240 
1241   (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CFG_MTU_EVT, &cb_data);
1242 }
1243 
1244 /** operation completed */
bta_gattc_op_cmpl(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)1245 void bta_gattc_op_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
1246   if (p_clcb->p_q_cmd == NULL) {
1247     log::error("No pending command gatt client command");
1248     return;
1249   }
1250 
1251   const tGATTC_OPTYPE op = p_data->op_cmpl.op_code;
1252   switch (op) {
1253     case GATTC_OPTYPE_READ:
1254     case GATTC_OPTYPE_WRITE:
1255     case GATTC_OPTYPE_EXE_WRITE:
1256     case GATTC_OPTYPE_CONFIG:
1257       break;
1258 
1259     case GATTC_OPTYPE_NONE:
1260     case GATTC_OPTYPE_DISCOVERY:
1261     case GATTC_OPTYPE_NOTIFICATION:
1262     case GATTC_OPTYPE_INDICATION:
1263     default:
1264       log::error("unexpected operation, ignored");
1265       return;
1266   }
1267 
1268   if (p_clcb->p_q_cmd->hdr.event !=
1269           bta_gattc_opcode_to_int_evt[op - GATTC_OPTYPE_READ] &&
1270       (p_clcb->p_q_cmd->hdr.event != BTA_GATTC_API_READ_MULTI_EVT ||
1271        op != GATTC_OPTYPE_READ)) {
1272     uint8_t mapped_op =
1273         p_clcb->p_q_cmd->hdr.event - BTA_GATTC_API_READ_EVT + GATTC_OPTYPE_READ;
1274 
1275     if (mapped_op > GATTC_OPTYPE_INDICATION) mapped_op = 0;
1276 
1277     log::error("expect op:({} :0x{:04x}), receive unexpected operation ({}).",
1278                bta_gattc_op_code_name[mapped_op], p_clcb->p_q_cmd->hdr.event,
1279                bta_gattc_op_code_name[op]);
1280     return;
1281   }
1282 
1283   /* Except for MTU configuration, discard responses if service change
1284    * indication is received before operation completed
1285    */
1286   if (p_clcb->auto_update == BTA_GATTC_DISC_WAITING &&
1287       p_clcb->p_srcb->srvc_hdl_chg && op != GATTC_OPTYPE_CONFIG) {
1288     log::verbose(
1289         "Discard all responses when service change indication is received.");
1290     // TODO Fix constness
1291     const_cast<tBTA_GATTC_DATA*>(p_data)->op_cmpl.status = GATT_ERROR;
1292   }
1293 
1294   /* service handle change void the response, discard it */
1295   if (op == GATTC_OPTYPE_READ) {
1296     bta_gattc_read_cmpl(p_clcb, &p_data->op_cmpl);
1297   } else if (op == GATTC_OPTYPE_WRITE) {
1298     bta_gattc_write_cmpl(p_clcb, &p_data->op_cmpl);
1299   } else if (op == GATTC_OPTYPE_EXE_WRITE) {
1300     bta_gattc_exec_cmpl(p_clcb, &p_data->op_cmpl);
1301   } else if (op == GATTC_OPTYPE_CONFIG) {
1302     bta_gattc_cfg_mtu_cmpl(p_clcb, &p_data->op_cmpl);
1303 
1304     /* If there are more clients waiting for the MTU results on the same device,
1305      * lets trigger them now.
1306      */
1307 
1308     auto outstanding_conn_ids =
1309         GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest(p_clcb->bda);
1310     for (auto conn_id : outstanding_conn_ids) {
1311       tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
1312       log::debug("Continue MTU request clcb {}", fmt::ptr(p_clcb));
1313       if (p_clcb) {
1314         log::debug("Continue MTU request for client conn_id=0x{:04x}", conn_id);
1315         bta_gattc_continue(p_clcb);
1316       }
1317     }
1318   }
1319 
1320   // If receive DATABASE_OUT_OF_SYNC error code, bta_gattc should start service
1321   // discovery immediately
1322   if (p_data->op_cmpl.status == GATT_DATABASE_OUT_OF_SYNC) {
1323     log::info("DATABASE_OUT_OF_SYNC, re-discover service");
1324     p_clcb->auto_update = BTA_GATTC_REQ_WAITING;
1325     /* request read db hash first */
1326     p_clcb->p_srcb->srvc_hdl_db_hash = true;
1327     bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
1328     return;
1329   }
1330 
1331   if (p_clcb->auto_update == BTA_GATTC_DISC_WAITING) {
1332     p_clcb->auto_update = BTA_GATTC_REQ_WAITING;
1333 
1334     /* request read db hash first */
1335     p_clcb->p_srcb->srvc_hdl_db_hash = true;
1336 
1337     bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
1338     return;
1339   }
1340 
1341   bta_gattc_continue(p_clcb);
1342 }
1343 
1344 /** start a search in the local server cache */
bta_gattc_search(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)1345 void bta_gattc_search(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
1346   tGATT_STATUS status = GATT_INTERNAL_ERROR;
1347   tBTA_GATTC cb_data;
1348   log::verbose("conn_id=0x{:x}", p_clcb->bta_conn_id);
1349   if (p_clcb->p_srcb && !p_clcb->p_srcb->gatt_database.IsEmpty()) {
1350     status = GATT_SUCCESS;
1351     /* search the local cache of a server device */
1352     bta_gattc_search_service(p_clcb, p_data->api_search.p_srvc_uuid);
1353   }
1354   cb_data.search_cmpl.status = status;
1355   cb_data.search_cmpl.conn_id = p_clcb->bta_conn_id;
1356 
1357   /* end of search or no server cache available */
1358   (*p_clcb->p_rcb->p_cback)(BTA_GATTC_SEARCH_CMPL_EVT, &cb_data);
1359 }
1360 
1361 /** enqueue a command into control block, usually because discovery operation is
1362  * busy */
bta_gattc_q_cmd(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA * p_data)1363 void bta_gattc_q_cmd(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) {
1364   bta_gattc_enqueue(p_clcb, p_data);
1365 }
1366 
1367 /** report API call failure back to apps */
bta_gattc_fail(tBTA_GATTC_CLCB * p_clcb,const tBTA_GATTC_DATA *)1368 void bta_gattc_fail(tBTA_GATTC_CLCB* p_clcb,
1369                     const tBTA_GATTC_DATA* /* p_data */) {
1370   if (p_clcb->status == GATT_SUCCESS) {
1371     log::error("operation not supported at current state {}", p_clcb->state);
1372   }
1373 }
1374 
1375 /* De-Register a GATT client application with BTA completed */
bta_gattc_deregister_cmpl(tBTA_GATTC_RCB * p_clreg)1376 static void bta_gattc_deregister_cmpl(tBTA_GATTC_RCB* p_clreg) {
1377   tGATT_IF client_if = p_clreg->client_if;
1378   tBTA_GATTC cb_data;
1379   tBTA_GATTC_CBACK* p_cback = p_clreg->p_cback;
1380 
1381   memset(&cb_data, 0, sizeof(tBTA_GATTC));
1382 
1383   GATT_Deregister(p_clreg->client_if);
1384   memset(p_clreg, 0, sizeof(tBTA_GATTC_RCB));
1385 
1386   cb_data.reg_oper.client_if = client_if;
1387   cb_data.reg_oper.status = GATT_SUCCESS;
1388 
1389   if (p_cback) /* callback with de-register event */
1390     (*p_cback)(BTA_GATTC_DEREG_EVT, &cb_data);
1391 
1392   if (bta_gattc_num_reg_app() == 0 &&
1393       bta_gattc_cb.state == BTA_GATTC_STATE_DISABLING) {
1394     bta_gattc_cb.state = BTA_GATTC_STATE_DISABLED;
1395   }
1396 }
1397 
1398 /** callback functions to GATT client stack */
bta_gattc_conn_cback(tGATT_IF gattc_if,const RawAddress & bdaddr,uint16_t conn_id,bool connected,tGATT_DISCONN_REASON reason,tBT_TRANSPORT transport)1399 static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bdaddr,
1400                                  uint16_t conn_id, bool connected,
1401                                  tGATT_DISCONN_REASON reason,
1402                                  tBT_TRANSPORT transport) {
1403   if (connected) {
1404     log::info("Connected client_if:{} addr:{}, transport:{} reason:{}",
1405               gattc_if, bdaddr, bt_transport_text(transport),
1406               gatt_disconnection_reason_text(reason));
1407     btif_debug_conn_state(bdaddr, BTIF_DEBUG_CONNECTED, GATT_CONN_OK);
1408   } else {
1409     log::info("Disconnected att_id:{} addr:{}, transport:{} reason:{}",
1410               gattc_if, bdaddr, bt_transport_text(transport),
1411               gatt_disconnection_reason_text(reason));
1412     btif_debug_conn_state(bdaddr, BTIF_DEBUG_DISCONNECTED, GATT_CONN_OK);
1413   }
1414 
1415   tBTA_GATTC_DATA* p_buf =
1416       (tBTA_GATTC_DATA*)osi_calloc(sizeof(tBTA_GATTC_DATA));
1417   p_buf->int_conn.hdr.event =
1418       connected ? BTA_GATTC_INT_CONN_EVT : BTA_GATTC_INT_DISCONN_EVT;
1419   p_buf->int_conn.hdr.layer_specific = conn_id;
1420   p_buf->int_conn.client_if = gattc_if;
1421   p_buf->int_conn.role = L2CA_GetBleConnRole(bdaddr);
1422   p_buf->int_conn.reason = reason;
1423   p_buf->int_conn.transport = transport;
1424   p_buf->int_conn.remote_bda = bdaddr;
1425 
1426   bta_sys_sendmsg(p_buf);
1427 }
1428 
1429 /** encryption complete callback function to GATT client stack */
bta_gattc_enc_cmpl_cback(tGATT_IF gattc_if,const RawAddress & bda)1430 static void bta_gattc_enc_cmpl_cback(tGATT_IF gattc_if, const RawAddress& bda) {
1431   tBTA_GATTC_CLCB* p_clcb =
1432       bta_gattc_find_clcb_by_cif(gattc_if, bda, BT_TRANSPORT_LE);
1433 
1434   if (p_clcb == NULL) return;
1435 
1436   log::verbose("cif:{}", gattc_if);
1437 
1438   do_in_main_thread(FROM_HERE,
1439                     base::BindOnce(&bta_gattc_process_enc_cmpl, gattc_if, bda));
1440 }
1441 
1442 /** process refresh API to delete cache and start a new discovery if currently
1443  * connected */
bta_gattc_process_api_refresh(const RawAddress & remote_bda)1444 void bta_gattc_process_api_refresh(const RawAddress& remote_bda) {
1445   tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_srvr_cache(remote_bda);
1446   if (p_srvc_cb) {
1447     /* try to find a CLCB */
1448     if (p_srvc_cb->connected && p_srvc_cb->num_clcb != 0) {
1449       bool found = false;
1450       tBTA_GATTC_CLCB* p_clcb = &bta_gattc_cb.clcb[0];
1451       for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++, p_clcb++) {
1452         if (p_clcb->in_use && p_clcb->p_srcb == p_srvc_cb) {
1453           found = true;
1454           break;
1455         }
1456       }
1457       if (found) {
1458         bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
1459         return;
1460       }
1461     }
1462     /* in all other cases, mark it and delete the cache */
1463 
1464     p_srvc_cb->gatt_database.Clear();
1465   }
1466 
1467   /* used to reset cache in application */
1468   bta_gattc_cache_reset(remote_bda);
1469 }
1470 
1471 /** process service change indication */
bta_gattc_process_srvc_chg_ind(uint16_t conn_id,tBTA_GATTC_RCB * p_clrcb,tBTA_GATTC_SERV * p_srcb,tBTA_GATTC_CLCB * p_clcb,tBTA_GATTC_NOTIFY * p_notify,tGATT_VALUE * att_value)1472 static bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id,
1473                                            tBTA_GATTC_RCB* p_clrcb,
1474                                            tBTA_GATTC_SERV* p_srcb,
1475                                            tBTA_GATTC_CLCB* p_clcb,
1476                                            tBTA_GATTC_NOTIFY* p_notify,
1477                                            tGATT_VALUE* att_value) {
1478   Uuid gattp_uuid = Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER);
1479   Uuid srvc_chg_uuid = Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD);
1480 
1481   if (p_srcb->gatt_database.IsEmpty() && p_srcb->state == BTA_GATTC_SERV_IDLE) {
1482     gatt::Database db = bta_gattc_cache_load(p_srcb->server_bda);
1483     if (!db.IsEmpty()) {
1484       p_srcb->gatt_database = db;
1485     }
1486   }
1487 
1488   const gatt::Characteristic* p_char =
1489       bta_gattc_get_characteristic_srcb(p_srcb, p_notify->handle);
1490   if (!p_char) return false;
1491   const gatt::Service* p_svc =
1492       bta_gattc_get_service_for_handle_srcb(p_srcb, p_char->value_handle);
1493   if (!p_svc || p_svc->uuid != gattp_uuid || p_char->uuid != srvc_chg_uuid) {
1494     return false;
1495   }
1496 
1497   if (att_value->len != BTA_GATTC_SERVICE_CHANGED_LEN) {
1498     log::error("received malformed service changed indication, skipping");
1499     return false;
1500   }
1501 
1502   uint8_t* p = att_value->value;
1503   uint16_t s_handle = ((uint16_t)(*(p)) + (((uint16_t)(*(p + 1))) << 8));
1504   uint16_t e_handle = ((uint16_t)(*(p + 2)) + (((uint16_t)(*(p + 3))) << 8));
1505 
1506   log::error("service changed s_handle=0x{:x}, e_handle=0x{:x}", s_handle,
1507              e_handle);
1508 
1509   /* mark service handle change pending */
1510   p_srcb->srvc_hdl_chg = true;
1511   /* clear up all notification/indication registration */
1512   bta_gattc_clear_notif_registration(p_srcb, conn_id, s_handle, e_handle);
1513   /* service change indication all received, do discovery update */
1514   if (++p_srcb->update_count == bta_gattc_num_reg_app()) {
1515     /* not an opened connection; or connection busy */
1516     /* search for first available clcb and start discovery */
1517     if (p_clcb == NULL || (p_clcb && p_clcb->p_q_cmd != NULL)) {
1518       for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) {
1519         if (bta_gattc_cb.clcb[i].in_use &&
1520             bta_gattc_cb.clcb[i].p_srcb == p_srcb &&
1521             bta_gattc_cb.clcb[i].p_q_cmd == NULL) {
1522           p_clcb = &bta_gattc_cb.clcb[i];
1523           break;
1524         }
1525       }
1526     }
1527     /* send confirmation here if this is an indication, it should always be */
1528     if (GATTC_SendHandleValueConfirm(conn_id, p_notify->cid) != GATT_SUCCESS) {
1529       log::warn(
1530           "Unable to send GATT client handle value confirmation conn_id:{} "
1531           "cid:{}",
1532           conn_id, p_notify->cid);
1533     }
1534 
1535     /* if connection available, refresh cache by doing discovery now */
1536     if (p_clcb) {
1537       /* request read db hash first */
1538       p_srcb->srvc_hdl_db_hash = true;
1539       bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
1540     }
1541   }
1542 
1543   /* notify applicationf or service change */
1544   if (p_clrcb->p_cback) {
1545     tBTA_GATTC bta_gattc;
1546     bta_gattc.service_changed.remote_bda = p_srcb->server_bda;
1547     bta_gattc.service_changed.conn_id = conn_id;
1548     (*p_clrcb->p_cback)(BTA_GATTC_SRVC_CHG_EVT, &bta_gattc);
1549   }
1550 
1551   return true;
1552 }
1553 
1554 /** process all non-service change indication/notification */
bta_gattc_proc_other_indication(tBTA_GATTC_CLCB * p_clcb,uint8_t op,tGATT_CL_COMPLETE * p_data,tBTA_GATTC_NOTIFY * p_notify)1555 static void bta_gattc_proc_other_indication(tBTA_GATTC_CLCB* p_clcb, uint8_t op,
1556                                             tGATT_CL_COMPLETE* p_data,
1557                                             tBTA_GATTC_NOTIFY* p_notify) {
1558   log::verbose("check p_data->att_value.handle={} p_data->handle={}",
1559                p_data->att_value.handle, p_data->handle);
1560   log::verbose("is_notify {}", p_notify->is_notify);
1561 
1562   p_notify->is_notify = (op == GATTC_OPTYPE_INDICATION) ? false : true;
1563   p_notify->len = p_data->att_value.len;
1564   p_notify->bda = p_clcb->bda;
1565   memcpy(p_notify->value, p_data->att_value.value, p_data->att_value.len);
1566   p_notify->conn_id = p_clcb->bta_conn_id;
1567 
1568   if (p_clcb->p_rcb->p_cback) {
1569     tBTA_GATTC bta_gattc;
1570     bta_gattc.notify = *p_notify;
1571     (*p_clcb->p_rcb->p_cback)(BTA_GATTC_NOTIF_EVT, &bta_gattc);
1572   }
1573 }
1574 
1575 /** process indication/notification */
bta_gattc_process_indicate(uint16_t conn_id,tGATTC_OPTYPE op,tGATT_CL_COMPLETE * p_data)1576 static void bta_gattc_process_indicate(uint16_t conn_id, tGATTC_OPTYPE op,
1577                                        tGATT_CL_COMPLETE* p_data) {
1578   uint16_t handle = p_data->att_value.handle;
1579   tBTA_GATTC_NOTIFY notify;
1580   RawAddress remote_bda;
1581   tGATT_IF gatt_if;
1582   tBT_TRANSPORT transport;
1583 
1584   if (!GATT_GetConnectionInfor(conn_id, &gatt_if, remote_bda, &transport)) {
1585     log::error("indication/notif for unknown app");
1586     if (op == GATTC_OPTYPE_INDICATION) {
1587       if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) {
1588         log::warn(
1589             "Unable to send GATT client handle value confirmation conn_id:{} "
1590             "cid:{}",
1591             conn_id, p_data->cid);
1592       }
1593     }
1594     return;
1595   }
1596 
1597   tBTA_GATTC_RCB* p_clrcb = bta_gattc_cl_get_regcb(gatt_if);
1598   if (p_clrcb == NULL) {
1599     log::error("indication/notif for unregistered app");
1600     if (op == GATTC_OPTYPE_INDICATION) {
1601       if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) {
1602         log::warn(
1603             "Unable to send GATT client handle value confirmation conn_id:{} "
1604             "cid:{}",
1605             conn_id, p_data->cid);
1606       }
1607     }
1608     return;
1609   }
1610 
1611   tBTA_GATTC_SERV* p_srcb = bta_gattc_find_srcb(remote_bda);
1612   if (p_srcb == NULL) {
1613     log::error("indication/notif for unknown device, ignore");
1614     if (op == GATTC_OPTYPE_INDICATION) {
1615       if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) {
1616         log::warn(
1617             "Unable to send GATT client handle value confirmation conn_id:{} "
1618             "cid:{}",
1619             conn_id, p_data->cid);
1620       }
1621     }
1622     return;
1623   }
1624 
1625   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
1626 
1627   notify.handle = handle;
1628   notify.cid = p_data->cid;
1629 
1630   /* if service change indication/notification, don't forward to application */
1631   if (bta_gattc_process_srvc_chg_ind(conn_id, p_clrcb, p_srcb, p_clcb, &notify,
1632                                      &p_data->att_value))
1633     return;
1634 
1635   /* if app registered for the notification */
1636   if (bta_gattc_check_notif_registry(p_clrcb, p_srcb, &notify)) {
1637     /* connection not open yet */
1638     if (p_clcb == NULL) {
1639       p_clcb = bta_gattc_clcb_alloc(gatt_if, remote_bda, transport);
1640 
1641       if (p_clcb == NULL) {
1642         log::error("No resources");
1643         return;
1644       }
1645 
1646       p_clcb->bta_conn_id = conn_id;
1647       p_clcb->transport = transport;
1648 
1649       bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CONN_EVT, NULL);
1650     }
1651 
1652     if (p_clcb != NULL)
1653       bta_gattc_proc_other_indication(p_clcb, op, p_data, &notify);
1654   }
1655   /* no one intersted and need ack? */
1656   else if (op == GATTC_OPTYPE_INDICATION) {
1657     log::verbose("no one interested, ack now");
1658     if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) {
1659       log::warn(
1660           "Unable to send GATT client handle value confirmation conn_id:{} "
1661           "cid:{}",
1662           conn_id, p_data->cid);
1663     }
1664   }
1665 }
1666 
1667 /** client operation complete callback register with BTE GATT */
bta_gattc_cmpl_cback(uint16_t conn_id,tGATTC_OPTYPE op,tGATT_STATUS status,tGATT_CL_COMPLETE * p_data)1668 static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op,
1669                                  tGATT_STATUS status,
1670                                  tGATT_CL_COMPLETE* p_data) {
1671   log::verbose("conn_id:{} op:{} status:{}", conn_id, op, status);
1672 
1673   /* notification and indication processed right away */
1674   if (op == GATTC_OPTYPE_NOTIFICATION || op == GATTC_OPTYPE_INDICATION) {
1675     bta_gattc_process_indicate(conn_id, op, p_data);
1676     return;
1677   }
1678   /* for all other operation, not expected if w/o connection */
1679   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
1680   if (!p_clcb) {
1681     log::error("unknown conn_id=0x{:x} ignore data", conn_id);
1682     return;
1683   }
1684 
1685   /* if over BR_EDR, inform PM for mode change */
1686   if (p_clcb->transport == BT_TRANSPORT_BR_EDR) {
1687     bta_sys_busy(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
1688     bta_sys_idle(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
1689   }
1690 
1691   bta_gattc_cmpl_sendmsg(conn_id, op, status, p_data);
1692 }
1693 
1694 /** client operation complete send message */
bta_gattc_cmpl_sendmsg(uint16_t conn_id,tGATTC_OPTYPE op,tGATT_STATUS status,tGATT_CL_COMPLETE * p_data)1695 void bta_gattc_cmpl_sendmsg(uint16_t conn_id, tGATTC_OPTYPE op,
1696                             tGATT_STATUS status, tGATT_CL_COMPLETE* p_data) {
1697   const size_t len = sizeof(tBTA_GATTC_OP_CMPL) + sizeof(tGATT_CL_COMPLETE);
1698   tBTA_GATTC_OP_CMPL* p_buf = (tBTA_GATTC_OP_CMPL*)osi_calloc(len);
1699 
1700   p_buf->hdr.event = BTA_GATTC_OP_CMPL_EVT;
1701   p_buf->hdr.layer_specific = conn_id;
1702   p_buf->status = status;
1703   p_buf->op_code = op;
1704 
1705   if (p_data) {
1706     p_buf->p_cmpl = (tGATT_CL_COMPLETE*)(p_buf + 1);
1707     memcpy(p_buf->p_cmpl, p_data, sizeof(tGATT_CL_COMPLETE));
1708   }
1709 
1710   bta_sys_sendmsg(p_buf);
1711 }
1712 
1713 /** congestion callback for BTA GATT client */
bta_gattc_cong_cback(uint16_t conn_id,bool congested)1714 static void bta_gattc_cong_cback(uint16_t conn_id, bool congested) {
1715   tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
1716   if (!p_clcb || !p_clcb->p_rcb->p_cback) return;
1717 
1718   tBTA_GATTC cb_data;
1719   cb_data.congest.conn_id = conn_id;
1720   cb_data.congest.congested = congested;
1721 
1722   (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CONGEST_EVT, &cb_data);
1723 }
1724 
bta_gattc_phy_update_cback(tGATT_IF gatt_if,uint16_t conn_id,uint8_t tx_phy,uint8_t rx_phy,tGATT_STATUS status)1725 static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id,
1726                                        uint8_t tx_phy, uint8_t rx_phy,
1727                                        tGATT_STATUS status) {
1728   tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(gatt_if);
1729 
1730   if (!p_clreg || !p_clreg->p_cback) {
1731     log::error("client_if={} not found", gatt_if);
1732     return;
1733   }
1734 
1735   tBTA_GATTC cb_data;
1736   cb_data.phy_update.conn_id = conn_id;
1737   cb_data.phy_update.server_if = gatt_if;
1738   cb_data.phy_update.tx_phy = tx_phy;
1739   cb_data.phy_update.rx_phy = rx_phy;
1740   cb_data.phy_update.status = status;
1741   (*p_clreg->p_cback)(BTA_GATTC_PHY_UPDATE_EVT, &cb_data);
1742 }
1743 
bta_gattc_conn_update_cback(tGATT_IF gatt_if,uint16_t conn_id,uint16_t interval,uint16_t latency,uint16_t timeout,tGATT_STATUS status)1744 static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id,
1745                                         uint16_t interval, uint16_t latency,
1746                                         uint16_t timeout, tGATT_STATUS status) {
1747   tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(gatt_if);
1748 
1749   if (!p_clreg || !p_clreg->p_cback) {
1750     log::error("client_if={} not found", gatt_if);
1751     return;
1752   }
1753 
1754   tBTA_GATTC cb_data;
1755   cb_data.conn_update.conn_id = conn_id;
1756   cb_data.conn_update.interval = interval;
1757   cb_data.conn_update.latency = latency;
1758   cb_data.conn_update.timeout = timeout;
1759   cb_data.conn_update.status = status;
1760   (*p_clreg->p_cback)(BTA_GATTC_CONN_UPDATE_EVT, &cb_data);
1761 }
1762 
bta_gattc_subrate_chg_cback(tGATT_IF gatt_if,uint16_t conn_id,uint16_t subrate_factor,uint16_t latency,uint16_t cont_num,uint16_t timeout,tGATT_STATUS status)1763 static void bta_gattc_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id,
1764                                         uint16_t subrate_factor,
1765                                         uint16_t latency, uint16_t cont_num,
1766                                         uint16_t timeout, tGATT_STATUS status) {
1767   tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(gatt_if);
1768 
1769   if (!p_clreg || !p_clreg->p_cback) {
1770     log::error("client_if={} not found", gatt_if);
1771     return;
1772   }
1773 
1774   tBTA_GATTC cb_data;
1775   cb_data.subrate_chg.conn_id = conn_id;
1776   cb_data.subrate_chg.subrate_factor = subrate_factor;
1777   cb_data.subrate_chg.latency = latency;
1778   cb_data.subrate_chg.cont_num = cont_num;
1779   cb_data.subrate_chg.timeout = timeout;
1780   cb_data.subrate_chg.status = status;
1781   (*p_clreg->p_cback)(BTA_GATTC_SUBRATE_CHG_EVT, &cb_data);
1782 }
1783