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 ATT functions
22  *
23  ******************************************************************************/
24 
25 #include <bluetooth/log.h>
26 #include <com_android_bluetooth_flags.h>
27 
28 #include "btif/include/btif_dm.h"
29 #include "btif/include/btif_storage.h"
30 #include "btif/include/stack_manager_t.h"
31 #include "device/include/interop.h"
32 #include "internal_include/bt_target.h"
33 #include "internal_include/stack_config.h"
34 #include "main/shim/acl_api.h"
35 #include "osi/include/allocator.h"
36 #include "osi/include/properties.h"
37 #include "stack/arbiter/acl_arbiter.h"
38 #include "stack/btm/btm_dev.h"
39 #include "stack/btm/btm_sec.h"
40 #include "stack/connection_manager/connection_manager.h"
41 #include "stack/eatt/eatt.h"
42 #include "stack/gatt/gatt_int.h"
43 #include "stack/include/acl_api.h"
44 #include "stack/include/bt_hdr.h"
45 #include "stack/include/bt_psm_types.h"
46 #include "stack/include/bt_types.h"
47 #include "stack/include/btm_client_interface.h"
48 #include "stack/include/gatt_api.h"
49 #include "stack/include/l2cap_acl_interface.h"
50 #include "stack/include/l2cap_interface.h"
51 #include "stack/include/l2cdefs.h"
52 #include "stack/include/srvc_api.h"  // tDIS_VALUE
53 #include "types/raw_address.h"
54 
55 using bluetooth::eatt::EattExtension;
56 using namespace bluetooth;
57 
58 bluetooth::common::TimestampedCircularBuffer<tTCB_STATE_HISTORY> tcb_state_history_(
59         100 /*history size*/);
60 
61 /******************************************************************************/
62 /*            L O C A L    F U N C T I O N     P R O T O T Y P E S            */
63 /******************************************************************************/
64 static void gatt_le_connect_cback(uint16_t chan, const RawAddress& bd_addr, bool connected,
65                                   uint16_t reason, tBT_TRANSPORT transport);
66 static void gatt_le_data_ind(uint16_t chan, const RawAddress& bd_addr, BT_HDR* p_buf);
67 static void gatt_le_cong_cback(const RawAddress& remote_bda, bool congest);
68 
69 static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr, uint16_t l2cap_cid,
70                                          uint16_t psm, uint8_t l2cap_id);
71 static void gatt_l2cif_connect_cfm_cback(uint16_t l2cap_cid, tL2CAP_CONN result);
72 static void gatt_l2cif_config_ind_cback(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg);
73 static void gatt_l2cif_config_cfm_cback(uint16_t lcid, uint16_t result, tL2CAP_CFG_INFO* p_cfg);
74 static void gatt_l2cif_disconnect_ind_cback(uint16_t l2cap_cid, bool ack_needed);
75 static void gatt_l2cif_disconnect(uint16_t l2cap_cid);
76 static void gatt_l2cif_data_ind_cback(uint16_t l2cap_cid, BT_HDR* p_msg);
77 static void gatt_send_conn_cback(tGATT_TCB* p_tcb);
78 static void gatt_l2cif_congest_cback(uint16_t cid, bool congested);
79 static void gatt_on_l2cap_error(uint16_t lcid, uint16_t result);
80 bool check_cached_model_name(const RawAddress& bd_addr);
81 static void read_dis_cback(const RawAddress& bd_addr, tDIS_VALUE* p_dis_value);
82 
83 static const tL2CAP_APPL_INFO dyn_info = {gatt_l2cif_connect_ind_cback,
84                                           gatt_l2cif_connect_cfm_cback,
85                                           gatt_l2cif_config_ind_cback,
86                                           gatt_l2cif_config_cfm_cback,
87                                           gatt_l2cif_disconnect_ind_cback,
88                                           NULL,
89                                           gatt_l2cif_data_ind_cback,
90                                           gatt_l2cif_congest_cback,
91                                           NULL,
92                                           gatt_on_l2cap_error,
93                                           NULL,
94                                           NULL,
95                                           NULL,
96                                           NULL};
97 
98 tGATT_CB gatt_cb;
99 
100 /*******************************************************************************
101  *
102  * Function         gatt_init
103  *
104  * Description      This function is enable the GATT profile on the device.
105  *                  It clears out the control blocks, and registers with L2CAP.
106  *
107  * Returns          void
108  *
109  ******************************************************************************/
gatt_init(void)110 void gatt_init(void) {
111   tL2CAP_FIXED_CHNL_REG fixed_reg;
112 
113   log::verbose("");
114 
115   gatt_cb = tGATT_CB();
116   connection_manager::reset(true);
117   memset(&fixed_reg, 0, sizeof(tL2CAP_FIXED_CHNL_REG));
118 
119   // To catch a potential OOB, 40>31 is used, any valid value (1 to GATT_IF_MAX) is okay.
120   gatt_cb.last_gatt_if = static_cast<tGATT_IF>(40);
121 
122   gatt_cb.sign_op_queue = fixed_queue_new(SIZE_MAX);
123   gatt_cb.srv_chg_clt_q = fixed_queue_new(SIZE_MAX);
124   /* First, register fixed L2CAP channel for ATT over BLE */
125   fixed_reg.pL2CA_FixedConn_Cb = gatt_le_connect_cback;
126   fixed_reg.pL2CA_FixedData_Cb = gatt_le_data_ind;
127   fixed_reg.pL2CA_FixedCong_Cb = gatt_le_cong_cback; /* congestion callback */
128 
129   // the GATT timeout is updated after a connection
130   // is established, when we know whether any
131   // clients exist
132   fixed_reg.default_idle_tout = L2CAP_NO_IDLE_TIMEOUT;
133 
134   if (!stack::l2cap::get_interface().L2CA_RegisterFixedChannel(L2CAP_ATT_CID, &fixed_reg)) {
135     log::error("Unable to register L2CAP ATT fixed channel");
136   }
137 
138   gatt_cb.over_br_enabled = osi_property_get_bool("bluetooth.gatt.over_bredr.enabled", true);
139   /* Now, register with L2CAP for ATT PSM over BR/EDR */
140   if (gatt_cb.over_br_enabled && !stack::l2cap::get_interface().L2CA_RegisterWithSecurity(
141                                          BT_PSM_ATT, dyn_info, false /* enable_snoop */, nullptr,
142                                          GATT_MAX_MTU_SIZE, 0, BTM_SEC_NONE)) {
143     log::error("ATT Dynamic Registration failed");
144   }
145 
146   gatt_cb.hdl_cfg.gatt_start_hdl = GATT_GATT_START_HANDLE;
147   gatt_cb.hdl_cfg.gap_start_hdl = GATT_GAP_START_HANDLE;
148   gatt_cb.hdl_cfg.gmcs_start_hdl = GATT_GMCS_START_HANDLE;
149   gatt_cb.hdl_cfg.gtbs_start_hdl = GATT_GTBS_START_HANDLE;
150   gatt_cb.hdl_cfg.tmas_start_hdl = GATT_TMAS_START_HANDLE;
151   gatt_cb.hdl_cfg.app_start_hdl = GATT_APP_START_HANDLE;
152 
153   gatt_cb.hdl_list_info = new std::list<tGATT_HDL_LIST_ELEM>();
154   gatt_cb.srv_list_info = new std::list<tGATT_SRV_LIST_ELEM>();
155   gatt_profile_db_init();
156 
157   EattExtension::GetInstance()->Start();
158 }
159 
160 /*******************************************************************************
161  *
162  * Function         gatt_free
163  *
164  * Description      This function frees resources used by the GATT profile.
165  *
166  * Returns          void
167  *
168  ******************************************************************************/
gatt_free(void)169 void gatt_free(void) {
170   int i;
171   log::verbose("");
172 
173   fixed_queue_free(gatt_cb.sign_op_queue, NULL);
174   gatt_cb.sign_op_queue = NULL;
175   fixed_queue_free(gatt_cb.srv_chg_clt_q, NULL);
176   gatt_cb.srv_chg_clt_q = NULL;
177   for (i = 0; i < GATT_MAX_PHY_CHANNEL; i++) {
178     gatt_cb.tcb[i].pending_enc_clcb = std::deque<tGATT_CLCB*>();
179 
180     fixed_queue_free(gatt_cb.tcb[i].pending_ind_q, NULL);
181     gatt_cb.tcb[i].pending_ind_q = NULL;
182 
183     alarm_free(gatt_cb.tcb[i].conf_timer);
184     gatt_cb.tcb[i].conf_timer = NULL;
185 
186     alarm_free(gatt_cb.tcb[i].ind_ack_timer);
187     gatt_cb.tcb[i].ind_ack_timer = NULL;
188 
189     fixed_queue_free(gatt_cb.tcb[i].sr_cmd.multi_rsp_q, NULL);
190     gatt_cb.tcb[i].sr_cmd.multi_rsp_q = NULL;
191 
192     if (gatt_cb.tcb[i].eatt) {
193       EattExtension::GetInstance()->FreeGattResources(gatt_cb.tcb[i].peer_bda);
194     }
195   }
196 
197   gatt_cb.hdl_list_info->clear();
198   delete gatt_cb.hdl_list_info;
199   gatt_cb.hdl_list_info = nullptr;
200   gatt_cb.srv_list_info->clear();
201   delete gatt_cb.srv_list_info;
202   gatt_cb.srv_list_info = nullptr;
203 
204   EattExtension::GetInstance()->Stop();
205 }
206 
207 /*******************************************************************************
208  *
209  * Function         gatt_connect
210  *
211  * Description      This function is called to initiate a connection to a peer
212  *                  device.
213  *
214  * Parameter        rem_bda: remote device address to connect to.
215  *
216  * Returns          true if connection is started, otherwise return false.
217  *
218  ******************************************************************************/
gatt_connect(const RawAddress & rem_bda,tBLE_ADDR_TYPE addr_type,tGATT_TCB * p_tcb,tBT_TRANSPORT transport,uint8_t,tGATT_IF gatt_if)219 static bool gatt_connect(const RawAddress& rem_bda, tBLE_ADDR_TYPE addr_type, tGATT_TCB* p_tcb,
220                          tBT_TRANSPORT transport, uint8_t /* initiating_phys */, tGATT_IF gatt_if) {
221   if (gatt_get_ch_state(p_tcb) != GATT_CH_OPEN) {
222     gatt_set_ch_state(p_tcb, GATT_CH_CONN);
223   }
224 
225   if (transport != BT_TRANSPORT_LE) {
226     p_tcb->att_lcid = stack::l2cap::get_interface().L2CA_ConnectReqWithSecurity(BT_PSM_ATT, rem_bda,
227                                                                                 BTM_SEC_NONE);
228     return p_tcb->att_lcid != 0;
229   }
230 
231   // Already connected, mark the link as used
232   if (gatt_get_ch_state(p_tcb) == GATT_CH_OPEN) {
233     gatt_update_app_use_link_flag(gatt_if, p_tcb, true, true);
234     return true;
235   }
236 
237   p_tcb->att_lcid = L2CAP_ATT_CID;
238   return connection_manager::create_le_connection(gatt_if, rem_bda, addr_type);
239 }
240 
241 /*******************************************************************************
242  *
243  * Function         gatt_cancel_connect
244  *
245  * Description      This will remove device from allow list and cancel connection
246  *
247  * Parameter        bd_addr: peer device address.
248  *                  transport: transport
249  *
250  *
251  ******************************************************************************/
gatt_cancel_connect(const RawAddress & bd_addr,tBT_TRANSPORT transport)252 void gatt_cancel_connect(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
253   /* This shall be call only when device is not connected */
254   log::debug("{}, transport {}", bd_addr, transport);
255 
256   if (!connection_manager::direct_connect_remove(CONN_MGR_ID_L2CAP, bd_addr)) {
257     bluetooth::shim::ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(bd_addr));
258     log::info(
259             "GATT connection manager has no record but removed filter "
260             "acceptlist gatt_if:{} peer:{}",
261             static_cast<uint8_t>(CONN_MGR_ID_L2CAP), bd_addr);
262   }
263 
264   gatt_cleanup_upon_disc(bd_addr, GATT_CONN_TERMINATE_LOCAL_HOST, transport);
265 }
266 
267 /*******************************************************************************
268  *
269  * Function         gatt_disconnect
270  *
271  * Description      This function is called to disconnect to an ATT device.
272  *
273  * Parameter        p_tcb: pointer to the TCB to disconnect.
274  *
275  * Returns          true: if connection found and to be disconnected; otherwise
276  *                  return false.
277  *
278  ******************************************************************************/
gatt_disconnect(tGATT_TCB * p_tcb)279 bool gatt_disconnect(tGATT_TCB* p_tcb) {
280   log::verbose("");
281 
282   if (!p_tcb) {
283     log::warn("Unable to disconnect an unknown device");
284     return false;
285   }
286 
287   tGATT_CH_STATE ch_state = gatt_get_ch_state(p_tcb);
288   if (ch_state == GATT_CH_CLOSING) {
289     log::debug("Device already in closing state peer:{}", p_tcb->peer_bda);
290     return true;
291   }
292 
293   if (p_tcb->att_lcid == L2CAP_ATT_CID) {
294     if (ch_state == GATT_CH_OPEN) {
295       if (com::android::bluetooth::flags::gatt_disconnect_fix() && p_tcb->eatt) {
296         /* ATT is fixed channel and it is expected to drop ACL.
297          * Make sure all EATT channels are disconnected before doing that.
298          */
299         EattExtension::GetInstance()->Disconnect(p_tcb->peer_bda);
300       }
301       if (!stack::l2cap::get_interface().L2CA_RemoveFixedChnl(L2CAP_ATT_CID, p_tcb->peer_bda)) {
302         log::warn("Unable to remove L2CAP ATT fixed channel peer:{}", p_tcb->peer_bda);
303       }
304       gatt_set_ch_state(p_tcb, GATT_CH_CLOSING);
305     } else {
306       gatt_cancel_connect(p_tcb->peer_bda, p_tcb->transport);
307     }
308   } else {
309     if ((ch_state == GATT_CH_OPEN) || (ch_state == GATT_CH_CFG)) {
310       gatt_l2cif_disconnect(p_tcb->att_lcid);
311     } else {
312       log::verbose("gatt_disconnect channel not opened");
313     }
314   }
315 
316   return true;
317 }
318 
319 /*******************************************************************************
320  *
321  * Function         gatt_update_app_hold_link_status
322  *
323  * Description      Update the application use link status
324  *
325  * Returns          true if any modifications are made or
326  *                  when it already exists, false otherwise.
327  *
328  ******************************************************************************/
gatt_update_app_hold_link_status(tGATT_IF gatt_if,tGATT_TCB * p_tcb,bool is_add)329 static bool gatt_update_app_hold_link_status(tGATT_IF gatt_if, tGATT_TCB* p_tcb, bool is_add) {
330   log::debug("gatt_if={}, is_add={}, peer_bda={}", gatt_if, is_add, p_tcb->peer_bda);
331   auto& holders = p_tcb->app_hold_link;
332 
333   if (is_add) {
334     auto ret = holders.insert(gatt_if);
335     if (ret.second) {
336       log::info("added gatt_if={}", gatt_if);
337     } else {
338       log::warn("attempt to add already existing gatt_if={}", gatt_if);
339     }
340 
341     auto holders_string = gatt_tcb_get_holders_info_string(p_tcb);
342     tcb_state_history_.Push({.address = p_tcb->peer_bda,
343                              .transport = p_tcb->transport,
344                              .state = p_tcb->ch_state,
345                              .holders_info = holders_string});
346     return true;
347   }
348 
349   //! is_add
350   if (!holders.erase(gatt_if)) {
351     log::warn("attempt to remove non-existing gatt_if={}", gatt_if);
352     return false;
353   }
354 
355   log::info("removed gatt_if={}", gatt_if);
356 
357   auto holders_string = gatt_tcb_get_holders_info_string(p_tcb);
358   tcb_state_history_.Push({.address = p_tcb->peer_bda,
359                            .transport = p_tcb->transport,
360                            .state = p_tcb->ch_state,
361                            .holders_info = holders_string});
362   return true;
363 }
364 
365 /*******************************************************************************
366  *
367  * Function         gatt_update_app_use_link_flag
368  *
369  * Description      Update the application use link flag and optional to check
370  *                  the acl link if the link is up then set the idle time out
371  *                  accordingly
372  *
373  * Returns          void.
374  *
375  ******************************************************************************/
gatt_update_app_use_link_flag(tGATT_IF gatt_if,tGATT_TCB * p_tcb,bool is_add,bool check_acl_link)376 void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, bool is_add,
377                                    bool check_acl_link) {
378   log::debug("gatt_if={}, is_add={} chk_link={}", gatt_if, is_add, check_acl_link);
379 
380   if (!p_tcb) {
381     log::warn("p_tcb is null");
382     return;
383   }
384 
385   // If we make no modification, i.e. kill app that was never connected to a
386   // device, skip updating the device state.
387   if (!gatt_update_app_hold_link_status(gatt_if, p_tcb, is_add)) {
388     log::info("App status is not updated for gatt_if={}", gatt_if);
389     return;
390   }
391 
392   if (!check_acl_link) {
393     log::info("check_acl_link is false, no need to check");
394     return;
395   }
396 
397   bool is_valid_handle = (get_btm_client_interface().peer.BTM_GetHCIConnHandle(
398                                   p_tcb->peer_bda, p_tcb->transport) != GATT_INVALID_ACL_HANDLE);
399 
400   if (is_add) {
401     if (p_tcb->att_lcid == L2CAP_ATT_CID && is_valid_handle) {
402       log::info("disable link idle timer for {}", p_tcb->peer_bda);
403       /* acl link is connected disable the idle timeout */
404       GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT, p_tcb->transport,
405                           true /* is_active */);
406     } else {
407       log::info("invalid handle {} or dynamic CID {}", is_valid_handle, p_tcb->att_lcid);
408     }
409   } else {
410     if (p_tcb->app_hold_link.empty()) {
411       // acl link is connected but no application needs to use the link
412       if (p_tcb->att_lcid == L2CAP_ATT_CID && is_valid_handle) {
413         /* Drop EATT before closing ATT */
414         EattExtension::GetInstance()->Disconnect(p_tcb->peer_bda);
415 
416         /* for fixed channel, set the timeout value to
417            GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP seconds */
418         log::info(
419                 "GATT fixed channel is no longer useful, start link idle timer for "
420                 "{} seconds",
421                 GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP);
422         GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP, p_tcb->transport,
423                             false /* is_active */);
424       } else {
425         // disconnect the dynamic channel
426         log::info("disconnect GATT dynamic channel");
427         gatt_disconnect(p_tcb);
428       }
429     } else {
430       auto holders = gatt_tcb_get_holders_info_string(p_tcb);
431       log::info("is_add=false, but some app is still using the ACL link. {}", holders);
432 
433       tcb_state_history_.Push({.address = p_tcb->peer_bda,
434                                .transport = p_tcb->transport,
435                                .state = p_tcb->ch_state,
436                                .holders_info = holders});
437     }
438   }
439 }
440 
441 /** GATT connection initiation */
gatt_act_connect(tGATT_REG * p_reg,const RawAddress & bd_addr,tBLE_ADDR_TYPE addr_type,tBT_TRANSPORT transport,int8_t initiating_phys)442 bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type,
443                       tBT_TRANSPORT transport, int8_t initiating_phys) {
444   log::verbose("address:{}, transport:{}", bd_addr, bt_transport_text(transport));
445   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport);
446   if (p_tcb != NULL) {
447     /* before link down, another app try to open a GATT connection */
448     uint8_t st = gatt_get_ch_state(p_tcb);
449     if (st == GATT_CH_OPEN && p_tcb->app_hold_link.empty() && transport == BT_TRANSPORT_LE) {
450       if (!gatt_connect(bd_addr, addr_type, p_tcb, transport, initiating_phys, p_reg->gatt_if)) {
451         return false;
452       }
453     } else if (st == GATT_CH_CLOSING) {
454       log::info("Must finish disconnection before new connection");
455       /* need to complete the closing first */
456       return false;
457     }
458 
459     return true;
460   }
461 
462   p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, transport);
463   if (!p_tcb) {
464     log::error("Max TCB for gatt_if [ {}] reached.", p_reg->gatt_if);
465     return false;
466   }
467 
468   if (!gatt_connect(bd_addr, addr_type, p_tcb, transport, initiating_phys, p_reg->gatt_if)) {
469     log::error("gatt_connect failed");
470     fixed_queue_free(p_tcb->pending_ind_q, NULL);
471     *p_tcb = tGATT_TCB();
472     return false;
473   }
474 
475   return true;
476 }
477 
gatt_act_connect(tGATT_REG * p_reg,const RawAddress & bd_addr,tBT_TRANSPORT transport,int8_t initiating_phys)478 bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, tBT_TRANSPORT transport,
479                       int8_t initiating_phys) {
480   return gatt_act_connect(p_reg, bd_addr, BLE_ADDR_PUBLIC, transport, initiating_phys);
481 }
482 
483 namespace connection_manager {
on_connection_timed_out(uint8_t,const RawAddress & address)484 void on_connection_timed_out(uint8_t /* app_id */, const RawAddress& address) {
485   gatt_le_connect_cback(L2CAP_ATT_CID, address, false, 0x08, BT_TRANSPORT_LE);
486 }
487 }  // namespace connection_manager
488 
489 /** This callback function is called by L2CAP to indicate that the ATT fixed
490  * channel for LE is connected (conn = true)/disconnected (conn = false).
491  */
gatt_le_connect_cback(uint16_t,const RawAddress & bd_addr,bool connected,uint16_t reason,tBT_TRANSPORT transport)492 static void gatt_le_connect_cback(uint16_t /* chan */, const RawAddress& bd_addr, bool connected,
493                                   uint16_t reason, tBT_TRANSPORT transport) {
494   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport);
495   bool check_srv_chg = false;
496   tGATTS_SRV_CHG* p_srv_chg_clt = NULL;
497 
498   if (transport == BT_TRANSPORT_BR_EDR) {
499     log::warn("Ignoring fixed channel connect/disconnect on br_edr for GATT");
500     return;
501   }
502 
503   log::verbose("GATT   ATT protocol channel with BDA: {} is {}", bd_addr,
504                (connected) ? "connected" : "disconnected");
505 
506   p_srv_chg_clt = gatt_is_bda_in_the_srv_chg_clt_list(bd_addr);
507   if (p_srv_chg_clt != NULL) {
508     check_srv_chg = true;
509   } else {
510     if (btm_sec_is_a_bonded_dev(bd_addr)) {
511       gatt_add_a_bonded_dev_for_srv_chg(bd_addr);
512     }
513   }
514 
515   if (!connected) {
516     if (p_tcb != nullptr) {
517       bluetooth::shim::arbiter::GetArbiter().OnLeDisconnect(p_tcb->tcb_idx);
518     }
519     gatt_cleanup_upon_disc(bd_addr, static_cast<tGATT_DISCONN_REASON>(reason), transport);
520     return;
521   }
522 
523   /* do we have a channel initiating a connection? */
524   if (p_tcb) {
525     /* we are initiating connection */
526     if (gatt_get_ch_state(p_tcb) == GATT_CH_CONN) {
527       /* send callback */
528       gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
529       p_tcb->payload_size = GATT_DEF_BLE_MTU_SIZE;
530 
531       gatt_send_conn_cback(p_tcb);
532     }
533     if (check_srv_chg) {
534       gatt_chk_srv_chg(p_srv_chg_clt);
535     }
536   } else {
537     /* this is incoming connection or background connection callback */
538     p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, BT_TRANSPORT_LE);
539     if (!p_tcb) {
540       log::error("Disconnecting address:{} due to out of resources.", bd_addr);
541       // When single FIXED channel cannot be created, there is no reason to
542       // keep the link
543       btm_remove_acl(bd_addr, transport);
544       return;
545     }
546 
547     p_tcb->att_lcid = L2CAP_ATT_CID;
548 
549     gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
550 
551     p_tcb->payload_size = GATT_DEF_BLE_MTU_SIZE;
552 
553     gatt_send_conn_cback(p_tcb);
554     if (check_srv_chg) {
555       gatt_chk_srv_chg(p_srv_chg_clt);
556     }
557   }
558 
559   auto advertising_set = bluetooth::shim::ACL_GetAdvertisingSetConnectedTo(bd_addr);
560 
561   if (advertising_set.has_value()) {
562     bluetooth::shim::arbiter::GetArbiter().OnLeConnect(p_tcb->tcb_idx, advertising_set.value());
563   }
564 
565   bool device_le_audio_capable = is_le_audio_capable_during_service_discovery(bd_addr);
566   if (device_le_audio_capable) {
567     log::info("Read model name for le audio capable device");
568     if (!check_cached_model_name(bd_addr)) {
569       if (!DIS_ReadDISInfo(bd_addr, read_dis_cback, DIS_ATTR_MODEL_NUM_BIT)) {
570         log::warn("Read DIS failed");
571       }
572     }
573   } else if (check_cached_model_name(bd_addr)) {
574     log::info("Get cache model name for device");
575   }
576 
577   if (stack_config_get_interface()->get_pts_connect_eatt_before_encryption()) {
578     log::info("Start EATT before encryption");
579     EattExtension::GetInstance()->Connect(bd_addr);
580   }
581 
582   /* TODO: This preference should be used to exchange MTU with the peer device before the apps are
583    * notified of the connection. */
584   uint16_t app_mtu_pref = gatt_get_apps_preferred_mtu(bd_addr);
585   gatt_remove_apps_mtu_prefs(bd_addr);
586   p_tcb->app_mtu_pref = app_mtu_pref;
587   if (app_mtu_pref > GATT_DEF_BLE_MTU_SIZE) {
588     log::verbose("Combined app MTU prefs for {}: {}", bd_addr, app_mtu_pref);
589   }
590 }
591 
check_cached_model_name(const RawAddress & bd_addr)592 bool check_cached_model_name(const RawAddress& bd_addr) {
593   bt_property_t prop;
594   bt_bdname_t model_name;
595   BTIF_STORAGE_FILL_PROPERTY(&prop, BT_PROPERTY_REMOTE_MODEL_NUM, sizeof(model_name), &model_name);
596 
597   if (btif_storage_get_remote_device_property(&bd_addr, &prop) != BT_STATUS_SUCCESS ||
598       prop.len == 0) {
599     log::info("Device {} no cached model name", bd_addr);
600     return false;
601   }
602 
603   GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, bd_addr,
604                                                                        1, &prop);
605   return true;
606 }
607 
read_dis_cback(const RawAddress & bd_addr,tDIS_VALUE * p_dis_value)608 static void read_dis_cback(const RawAddress& bd_addr, tDIS_VALUE* p_dis_value) {
609   if (p_dis_value == NULL) {
610     log::error("received unexpected/error DIS callback");
611     return;
612   }
613 
614   if (p_dis_value->attr_mask & DIS_ATTR_MODEL_NUM_BIT) {
615     for (int i = 0; i < DIS_MAX_STRING_DATA; i++) {
616       if (p_dis_value->data_string[i] != NULL) {
617         bt_property_t prop;
618         prop.type = BT_PROPERTY_REMOTE_MODEL_NUM;
619         prop.val = p_dis_value->data_string[i];
620         prop.len = strlen((char*)prop.val);
621 
622         log::info("Device {}, model name: {}", bd_addr, (char*)prop.val);
623 
624         btif_storage_set_remote_device_property(&bd_addr, &prop);
625         GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS,
626                                                                              bd_addr, 1, &prop);
627       }
628     }
629   } else {
630     log::error("unknown bit, mask: {}", (int)p_dis_value->attr_mask);
631   }
632 }
633 
634 /** This function is called to process the congestion callback from lcb */
gatt_channel_congestion(tGATT_TCB * p_tcb,bool congested)635 static void gatt_channel_congestion(tGATT_TCB* p_tcb, bool congested) {
636   uint8_t i = 0;
637   tGATT_REG* p_reg = NULL;
638   tCONN_ID conn_id;
639 
640   /* if uncongested, check to see if there is any more pending data */
641   if (p_tcb != NULL && !congested) {
642     gatt_cl_send_next_cmd_inq(*p_tcb);
643   }
644   /* notifying all applications for the connection up event */
645   if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
646     for (auto& [i, p_reg] : gatt_cb.cl_rcb_map) {
647       if (p_reg->in_use && p_reg->app_cb.p_congestion_cb) {
648         conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
649         (*p_reg->app_cb.p_congestion_cb)(conn_id, congested);
650       }
651     }
652   } else {
653     for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
654       if (p_reg->in_use) {
655         if (p_reg->app_cb.p_congestion_cb) {
656           conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
657           (*p_reg->app_cb.p_congestion_cb)(conn_id, congested);
658         }
659       }
660     }
661   }
662 }
663 
gatt_notify_phy_updated(tHCI_STATUS status,uint16_t handle,uint8_t tx_phy,uint8_t rx_phy)664 void gatt_notify_phy_updated(tHCI_STATUS status, uint16_t handle, uint8_t tx_phy, uint8_t rx_phy) {
665   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
666   if (!p_dev_rec) {
667     log::warn("No Device Found!");
668     return;
669   }
670 
671   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE);
672   if (!p_tcb) {
673     return;
674   }
675 
676   // TODO: Clean up this status conversion.
677   tGATT_STATUS gatt_status = static_cast<tGATT_STATUS>(status);
678 
679   if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
680     for (auto& [i, p_reg] : gatt_cb.cl_rcb_map) {
681       if (p_reg->in_use && p_reg->app_cb.p_phy_update_cb) {
682         tCONN_ID conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
683         (*p_reg->app_cb.p_phy_update_cb)(p_reg->gatt_if, conn_id, tx_phy, rx_phy, gatt_status);
684       }
685     }
686   } else {
687     for (int i = 0; i < GATT_MAX_APPS; i++) {
688       tGATT_REG* p_reg = &gatt_cb.cl_rcb[i];
689       if (p_reg->in_use && p_reg->app_cb.p_phy_update_cb) {
690         tCONN_ID conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
691         (*p_reg->app_cb.p_phy_update_cb)(p_reg->gatt_if, conn_id, tx_phy, rx_phy, gatt_status);
692       }
693     }
694   }
695 }
696 
gatt_notify_conn_update(const RawAddress & remote,uint16_t interval,uint16_t latency,uint16_t timeout,tHCI_STATUS status)697 void gatt_notify_conn_update(const RawAddress& remote, uint16_t interval, uint16_t latency,
698                              uint16_t timeout, tHCI_STATUS status) {
699   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote, BT_TRANSPORT_LE);
700 
701   if (!p_tcb) {
702     return;
703   }
704 
705   if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
706     for (auto& [i, p_reg] : gatt_cb.cl_rcb_map) {
707       if (p_reg->in_use && p_reg->app_cb.p_conn_update_cb) {
708         tCONN_ID conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
709         (*p_reg->app_cb.p_conn_update_cb)(p_reg->gatt_if, conn_id, interval, latency, timeout,
710                                           static_cast<tGATT_STATUS>(status));
711       }
712     }
713   } else {
714     for (int i = 0; i < GATT_MAX_APPS; i++) {
715       tGATT_REG* p_reg = &gatt_cb.cl_rcb[i];
716       if (p_reg->in_use && p_reg->app_cb.p_conn_update_cb) {
717         tCONN_ID conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
718         (*p_reg->app_cb.p_conn_update_cb)(p_reg->gatt_if, conn_id, interval, latency, timeout,
719                                           static_cast<tGATT_STATUS>(status));
720       }
721     }
722   }
723 }
724 
gatt_notify_subrate_change(uint16_t handle,uint16_t subrate_factor,uint16_t latency,uint16_t cont_num,uint16_t timeout,uint8_t status)725 void gatt_notify_subrate_change(uint16_t handle, uint16_t subrate_factor, uint16_t latency,
726                                 uint16_t cont_num, uint16_t timeout, uint8_t status) {
727   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
728   if (!p_dev_rec) {
729     log::warn("No Device Found!");
730     return;
731   }
732 
733   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE);
734   if (!p_tcb) {
735     return;
736   }
737 
738   if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
739     for (auto& [i, p_reg] : gatt_cb.cl_rcb_map) {
740       if (p_reg->in_use && p_reg->app_cb.p_subrate_chg_cb) {
741         tCONN_ID conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
742         (*p_reg->app_cb.p_subrate_chg_cb)(p_reg->gatt_if, conn_id, subrate_factor, latency,
743                                           cont_num, timeout, static_cast<tGATT_STATUS>(status));
744       }
745     }
746   } else {
747     for (int i = 0; i < GATT_MAX_APPS; i++) {
748       tGATT_REG* p_reg = &gatt_cb.cl_rcb[i];
749       if (p_reg->in_use && p_reg->app_cb.p_subrate_chg_cb) {
750         tCONN_ID conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
751         (*p_reg->app_cb.p_subrate_chg_cb)(p_reg->gatt_if, conn_id, subrate_factor, latency,
752                                           cont_num, timeout, static_cast<tGATT_STATUS>(status));
753       }
754     }
755   }
756 }
757 
758 /** This function is called when GATT fixed channel is congested or uncongested
759  */
gatt_le_cong_cback(const RawAddress & remote_bda,bool congested)760 static void gatt_le_cong_cback(const RawAddress& remote_bda, bool congested) {
761   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote_bda, BT_TRANSPORT_LE);
762   if (!p_tcb) {
763     return;
764   }
765 
766   /* if uncongested, check to see if there is any more pending data */
767   gatt_channel_congestion(p_tcb, congested);
768 }
769 
770 /*******************************************************************************
771  *
772  * Function         gatt_le_data_ind
773  *
774  * Description      This function is called when data is received from L2CAP.
775  *                  if we are the originator of the connection, we are the ATT
776  *                  client, and the received message is queued up for the
777  *                  client.
778  *
779  *                  If we are the destination of the connection, we are the ATT
780  *                  server, so the message is passed to the server processing
781  *                  function.
782  *
783  * Returns          void
784  *
785  ******************************************************************************/
gatt_le_data_ind(uint16_t,const RawAddress & bd_addr,BT_HDR * p_buf)786 static void gatt_le_data_ind(uint16_t /* chan */, const RawAddress& bd_addr, BT_HDR* p_buf) {
787   /* Find CCB based on bd addr */
788   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_LE);
789   if (p_tcb) {
790     auto decision =
791             bluetooth::shim::arbiter::GetArbiter().InterceptAttPacket(p_tcb->tcb_idx, p_buf);
792 
793     if (decision == bluetooth::shim::arbiter::InterceptAction::DROP) {
794       // do nothing, just free it at the end
795     } else if (gatt_get_ch_state(p_tcb) < GATT_CH_OPEN) {
796       log::warn("ATT - Ignored L2CAP data while in state: {}", gatt_get_ch_state(p_tcb));
797     } else {
798       gatt_data_process(*p_tcb, L2CAP_ATT_CID, p_buf);
799     }
800   }
801 
802   osi_free(p_buf);
803 }
804 
805 /*******************************************************************************
806  *
807  * Function         gatt_l2cif_connect_ind
808  *
809  * Description      This function handles an inbound connection indication
810  *                  from L2CAP. This is the case where we are acting as a
811  *                  server.
812  *
813  * Returns          void
814  *
815  ******************************************************************************/
gatt_l2cif_connect_ind_cback(const RawAddress & bd_addr,uint16_t lcid,uint16_t,uint8_t)816 static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid,
817                                          uint16_t /* psm */, uint8_t /* id */) {
818   tL2CAP_CONN result = tL2CAP_CONN::L2CAP_CONN_OK;
819   log::info("Connection indication cid = {}", lcid);
820 
821   /* new connection ? */
822   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_BR_EDR);
823   if (p_tcb == NULL) {
824     /* allocate tcb */
825     p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, BT_TRANSPORT_BR_EDR);
826     if (p_tcb == NULL) {
827       /* no tcb available, reject L2CAP connection */
828       result = tL2CAP_CONN::L2CAP_CONN_NO_RESOURCES;
829     } else {
830       p_tcb->att_lcid = lcid;
831     }
832 
833   } else /* existing connection , reject it */
834   {
835     result = tL2CAP_CONN::L2CAP_CONN_NO_RESOURCES;
836   }
837 
838   /* If we reject the connection, send DisconnectReq */
839   if (result != tL2CAP_CONN::L2CAP_CONN_OK) {
840     if (!stack::l2cap::get_interface().L2CA_DisconnectReq(lcid)) {
841       log::warn("Unable to disconnect L2CAP peer:{} cid:{}", bd_addr, lcid);
842     }
843     return;
844   }
845 
846   /* transition to configuration state */
847   gatt_set_ch_state(p_tcb, GATT_CH_CFG);
848 }
849 
gatt_on_l2cap_error(uint16_t lcid,uint16_t)850 static void gatt_on_l2cap_error(uint16_t lcid, uint16_t /* result */) {
851   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
852   if (p_tcb == nullptr) {
853     return;
854   }
855   if (gatt_get_ch_state(p_tcb) == GATT_CH_CONN) {
856     gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_L2C_FAILURE, BT_TRANSPORT_BR_EDR);
857   } else {
858     gatt_l2cif_disconnect(lcid);
859   }
860 }
861 
862 /** This is the L2CAP connect confirm callback function */
gatt_l2cif_connect_cfm_cback(uint16_t lcid,tL2CAP_CONN result)863 static void gatt_l2cif_connect_cfm_cback(uint16_t lcid, tL2CAP_CONN result) {
864   tGATT_TCB* p_tcb;
865 
866   /* look up clcb for this channel */
867   p_tcb = gatt_find_tcb_by_cid(lcid);
868   if (!p_tcb) {
869     return;
870   }
871 
872   log::verbose("result: {} ch_state: {}, lcid:0x{:x}", result, gatt_get_ch_state(p_tcb),
873                p_tcb->att_lcid);
874 
875   if (gatt_get_ch_state(p_tcb) == GATT_CH_CONN && result == tL2CAP_CONN::L2CAP_CONN_OK) {
876     gatt_set_ch_state(p_tcb, GATT_CH_CFG);
877   } else {
878     gatt_on_l2cap_error(lcid, static_cast<uint16_t>(result));
879   }
880 }
881 
882 /** This is the L2CAP config confirm callback function */
gatt_l2cif_config_cfm_cback(uint16_t lcid,uint16_t,tL2CAP_CFG_INFO * p_cfg)883 void gatt_l2cif_config_cfm_cback(uint16_t lcid, uint16_t /* initiator */, tL2CAP_CFG_INFO* p_cfg) {
884   gatt_l2cif_config_ind_cback(lcid, p_cfg);
885 
886   /* look up clcb for this channel */
887   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
888   if (!p_tcb) {
889     return;
890   }
891 
892   /* if in incorrect state */
893   if (gatt_get_ch_state(p_tcb) != GATT_CH_CFG) {
894     return;
895   }
896 
897   gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
898 
899   tGATTS_SRV_CHG* p_srv_chg_clt = gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda);
900   if (p_srv_chg_clt != NULL) {
901     gatt_chk_srv_chg(p_srv_chg_clt);
902   } else {
903     if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) {
904       gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda);
905     }
906   }
907 
908   /* send callback */
909   gatt_send_conn_cback(p_tcb);
910 }
911 
912 /** This is the L2CAP config indication callback function */
gatt_l2cif_config_ind_cback(uint16_t lcid,tL2CAP_CFG_INFO * p_cfg)913 void gatt_l2cif_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) {
914   /* look up clcb for this channel */
915   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
916   if (!p_tcb) {
917     return;
918   }
919 
920   /* GATT uses the smaller of our MTU and peer's MTU  */
921   if (p_cfg->mtu_present && p_cfg->mtu < L2CAP_DEFAULT_MTU) {
922     p_tcb->payload_size = p_cfg->mtu;
923   } else {
924     p_tcb->payload_size = L2CAP_DEFAULT_MTU;
925   }
926 }
927 
928 /** This is the L2CAP disconnect indication callback function */
gatt_l2cif_disconnect_ind_cback(uint16_t lcid,bool)929 void gatt_l2cif_disconnect_ind_cback(uint16_t lcid, bool /* ack_needed */) {
930   /* look up clcb for this channel */
931   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
932   if (!p_tcb) {
933     return;
934   }
935 
936   if (gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda) == NULL) {
937     if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) {
938       gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda);
939     }
940   }
941   /* send disconnect callback */
942   gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_TERMINATE_PEER_USER, BT_TRANSPORT_BR_EDR);
943 }
944 
gatt_l2cif_disconnect(uint16_t lcid)945 static void gatt_l2cif_disconnect(uint16_t lcid) {
946   if (!stack::l2cap::get_interface().L2CA_DisconnectReq(lcid)) {
947     log::warn("Unable to disconnect L2CAP cid:{}", lcid);
948   }
949 
950   /* look up clcb for this channel */
951   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
952   if (!p_tcb) {
953     return;
954   }
955 
956   /* If the device is not in the service changed client list, add it... */
957   if (gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda) == NULL) {
958     if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) {
959       gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda);
960     }
961   }
962 
963   gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_TERMINATE_LOCAL_HOST, BT_TRANSPORT_BR_EDR);
964 }
965 
966 /** This is the L2CAP data indication callback function */
gatt_l2cif_data_ind_cback(uint16_t lcid,BT_HDR * p_buf)967 static void gatt_l2cif_data_ind_cback(uint16_t lcid, BT_HDR* p_buf) {
968   /* look up clcb for this channel */
969   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
970   if (p_tcb && gatt_get_ch_state(p_tcb) == GATT_CH_OPEN) {
971     /* process the data */
972     gatt_data_process(*p_tcb, lcid, p_buf);
973   }
974 
975   osi_free(p_buf);
976 }
977 
978 /** L2CAP congestion callback */
gatt_l2cif_congest_cback(uint16_t lcid,bool congested)979 static void gatt_l2cif_congest_cback(uint16_t lcid, bool congested) {
980   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
981 
982   if (p_tcb != NULL) {
983     gatt_channel_congestion(p_tcb, congested);
984   }
985 }
986 
987 /** Callback used to notify layer above about a connection */
gatt_send_conn_cback(tGATT_TCB * p_tcb)988 static void gatt_send_conn_cback(tGATT_TCB* p_tcb) {
989   uint8_t i;
990   tGATT_REG* p_reg;
991   tCONN_ID conn_id;
992 
993   std::set<tGATT_IF> apps = connection_manager::get_apps_connecting_to(p_tcb->peer_bda);
994 
995   /* notifying all applications for the connection up event */
996 
997   if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
998     for (auto& [i, p_reg] : gatt_cb.cl_rcb_map) {
999       if (!p_reg->in_use) {
1000         continue;
1001       }
1002 
1003       if (apps.find(p_reg->gatt_if) != apps.end()) {
1004         gatt_update_app_use_link_flag(p_reg->gatt_if, p_tcb, true, true);
1005       }
1006 
1007       if (p_reg->direct_connect_request.count(p_tcb->peer_bda) > 0) {
1008         gatt_update_app_use_link_flag(p_reg->gatt_if, p_tcb, true, true);
1009         log::info("Removing device {} from the direct connect list of gatt_if {}", p_tcb->peer_bda,
1010                   p_reg->gatt_if);
1011         p_reg->direct_connect_request.erase(p_tcb->peer_bda);
1012       }
1013 
1014       if (p_reg->app_cb.p_conn_cb) {
1015         conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
1016         (*p_reg->app_cb.p_conn_cb)(p_reg->gatt_if, p_tcb->peer_bda, conn_id, kGattConnected,
1017                                    GATT_CONN_OK, p_tcb->transport);
1018       }
1019     }
1020   } else {
1021     for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
1022       if (!p_reg->in_use) {
1023         continue;
1024       }
1025 
1026       if (apps.find(p_reg->gatt_if) != apps.end()) {
1027         gatt_update_app_use_link_flag(p_reg->gatt_if, p_tcb, true, true);
1028       }
1029 
1030       if (p_reg->direct_connect_request.count(p_tcb->peer_bda) > 0) {
1031         gatt_update_app_use_link_flag(p_reg->gatt_if, p_tcb, true, true);
1032         log::info("Removing device {} from the direct connect list of gatt_if {}", p_tcb->peer_bda,
1033                   p_reg->gatt_if);
1034         p_reg->direct_connect_request.erase(p_tcb->peer_bda);
1035       }
1036 
1037       if (p_reg->app_cb.p_conn_cb) {
1038         conn_id = gatt_create_conn_id(p_tcb->tcb_idx, p_reg->gatt_if);
1039         (*p_reg->app_cb.p_conn_cb)(p_reg->gatt_if, p_tcb->peer_bda, conn_id, kGattConnected,
1040                                    GATT_CONN_OK, p_tcb->transport);
1041       }
1042     }
1043   }
1044 
1045   /* Remove the direct connection */
1046   connection_manager::on_connection_complete(p_tcb->peer_bda);
1047 
1048   if (p_tcb->att_lcid == L2CAP_ATT_CID) {
1049     if (!p_tcb->app_hold_link.empty()) {
1050       /* disable idle timeout if one or more clients are holding the link
1051        * disable the idle timer */
1052       GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT, p_tcb->transport,
1053                           true /* is_active */);
1054     } else {
1055       GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP, p_tcb->transport,
1056                           false /* is_active */);
1057     }
1058   }
1059 }
1060 
gatt_consolidate(const RawAddress & identity_addr,const RawAddress & rpa)1061 void gatt_consolidate(const RawAddress& identity_addr, const RawAddress& rpa) {
1062   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(rpa, BT_TRANSPORT_LE);
1063   if (p_tcb == NULL) {
1064     return;
1065   }
1066 
1067   log::info("consolidate {} -> {}", rpa, identity_addr);
1068   p_tcb->peer_bda = identity_addr;
1069 
1070   // Address changed, notify GATT clients/servers device is available under new
1071   // address
1072   gatt_send_conn_cback(p_tcb);
1073 }
1074 /*******************************************************************************
1075  *
1076  * Function         gatt_data_process
1077  *
1078  * Description      This function is called when data is received from L2CAP.
1079  *                  if we are the originator of the connection, we are the ATT
1080  *                  client, and the received message is queued up for the
1081  *                  client.
1082  *
1083  *                  If we are the destination of the connection, we are the ATT
1084  *                  server, so the message is passed to the server processing
1085  *                  function.
1086  *
1087  * Returns          void
1088  *
1089  ******************************************************************************/
gatt_data_process(tGATT_TCB & tcb,uint16_t cid,BT_HDR * p_buf)1090 void gatt_data_process(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_buf) {
1091   uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset;
1092   uint8_t op_code, pseudo_op_code;
1093 
1094   if (p_buf->len <= 0) {
1095     log::error("invalid data length, ignore");
1096     return;
1097   }
1098 
1099   uint16_t msg_len = p_buf->len - 1;
1100   STREAM_TO_UINT8(op_code, p);
1101 
1102   /* remove the two MSBs associated with sign write and write cmd */
1103   pseudo_op_code = op_code & (~GATT_WRITE_CMD_MASK);
1104 
1105   if (pseudo_op_code >= GATT_OP_CODE_MAX) {
1106     /* Note: PTS: GATT/SR/UNS/BI-01-C mandates error on unsupported ATT request.
1107      */
1108     log::error("ATT - Rcvd L2CAP data, unknown cmd: 0x{:x}", op_code);
1109     gatt_send_error_rsp(tcb, cid, GATT_REQ_NOT_SUPPORTED, op_code, 0, false);
1110     return;
1111   }
1112 
1113   if (op_code == GATT_SIGN_CMD_WRITE) {
1114     gatt_verify_signature(tcb, cid, p_buf);
1115   } else {
1116     /* message from client */
1117     if ((op_code % 2) == 0) {
1118       gatt_server_handle_client_req(tcb, cid, op_code, msg_len, p);
1119     } else {
1120       gatt_client_handle_server_rsp(tcb, cid, op_code, msg_len, p);
1121     }
1122   }
1123 }
1124 
1125 /** Add a bonded dev to the service changed client list */
gatt_add_a_bonded_dev_for_srv_chg(const RawAddress & bda)1126 void gatt_add_a_bonded_dev_for_srv_chg(const RawAddress& bda) {
1127   tGATTS_SRV_CHG_REQ req;
1128   tGATTS_SRV_CHG srv_chg_clt;
1129 
1130   srv_chg_clt.bda = bda;
1131   srv_chg_clt.srv_changed = false;
1132   if (!gatt_add_srv_chg_clt(&srv_chg_clt)) {
1133     return;
1134   }
1135 
1136   req.srv_chg.bda = bda;
1137   req.srv_chg.srv_changed = false;
1138   if (gatt_cb.cb_info.p_srv_chg_callback) {
1139     (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_ADD_CLIENT, &req, NULL);
1140   }
1141 }
1142 
1143 /** This function is called to send a service changed indication to the
1144  * specified bd address */
gatt_send_srv_chg_ind(const RawAddress & peer_bda)1145 void gatt_send_srv_chg_ind(const RawAddress& peer_bda) {
1146   static const uint16_t sGATT_DEFAULT_START_HANDLE = (uint16_t)osi_property_get_int32(
1147           "bluetooth.gatt.default_start_handle_for_srvc_change.value", GATT_GATT_START_HANDLE);
1148   static const uint16_t sGATT_LAST_HANDLE = (uint16_t)osi_property_get_int32(
1149           "bluetooth.gatt.last_handle_for_srvc_change.value", 0xFFFF);
1150 
1151   log::verbose("");
1152 
1153   if (!gatt_cb.handle_of_h_r) {
1154     return;
1155   }
1156 
1157   tCONN_ID conn_id = gatt_profile_find_conn_id_by_bd_addr(peer_bda);
1158   if (conn_id == GATT_INVALID_CONN_ID) {
1159     log::error("Unable to find conn_id for {}", peer_bda);
1160     return;
1161   }
1162 
1163   uint8_t handle_range[GATT_SIZE_OF_SRV_CHG_HNDL_RANGE];
1164   uint8_t* p = handle_range;
1165   UINT16_TO_STREAM(p, sGATT_DEFAULT_START_HANDLE);
1166   UINT16_TO_STREAM(p, sGATT_LAST_HANDLE);
1167   if (GATTS_HandleValueIndication(conn_id, gatt_cb.handle_of_h_r, GATT_SIZE_OF_SRV_CHG_HNDL_RANGE,
1168                                   handle_range) != GATT_SUCCESS) {
1169     log::warn("Unable to handle GATT service value indication conn_id:{}", conn_id);
1170   }
1171 }
1172 
1173 /** Check sending service changed Indication is required or not if required then
1174  * send the Indication */
gatt_chk_srv_chg(tGATTS_SRV_CHG * p_srv_chg_clt)1175 void gatt_chk_srv_chg(tGATTS_SRV_CHG* p_srv_chg_clt) {
1176   log::verbose("srv_changed={}", p_srv_chg_clt->srv_changed);
1177 
1178   if (p_srv_chg_clt->srv_changed) {
1179     gatt_send_srv_chg_ind(p_srv_chg_clt->bda);
1180   }
1181 }
1182 
1183 /** This function is used to initialize the service changed attribute value */
gatt_init_srv_chg(void)1184 void gatt_init_srv_chg(void) {
1185   tGATTS_SRV_CHG_REQ req;
1186   tGATTS_SRV_CHG_RSP rsp;
1187   tGATTS_SRV_CHG srv_chg_clt;
1188 
1189   log::verbose("");
1190   if (!gatt_cb.cb_info.p_srv_chg_callback) {
1191     log::verbose("callback not registered yet");
1192     return;
1193   }
1194 
1195   bool status =
1196           (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_READ_NUM_CLENTS, NULL, &rsp);
1197 
1198   if (!(status && rsp.num_clients)) {
1199     return;
1200   }
1201 
1202   log::verbose("num_srv_chg_clt_clients={}", rsp.num_clients);
1203   uint8_t num_clients = rsp.num_clients;
1204   uint8_t i = 1; /* use one based index */
1205   while ((i <= num_clients) && status) {
1206     req.client_read_index = i;
1207     status = (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_READ_CLENT, &req, &rsp);
1208     if (status) {
1209       memcpy(&srv_chg_clt, &rsp.srv_chg, sizeof(tGATTS_SRV_CHG));
1210       if (gatt_add_srv_chg_clt(&srv_chg_clt) == NULL) {
1211         log::error("Unable to add a service change client");
1212         status = false;
1213       }
1214     }
1215     i++;
1216   }
1217 }
1218 
1219 /**This function is process the service changed request */
gatt_proc_srv_chg(void)1220 void gatt_proc_srv_chg(void) {
1221   RawAddress bda;
1222   tBT_TRANSPORT transport;
1223   uint8_t found_idx;
1224 
1225   log::verbose("");
1226 
1227   if (!gatt_cb.cb_info.p_srv_chg_callback || !gatt_cb.handle_of_h_r) {
1228     return;
1229   }
1230 
1231   gatt_set_srv_chg();
1232   uint8_t start_idx = 0;
1233   while (gatt_find_the_connected_bda(start_idx, bda, &found_idx, &transport)) {
1234     tGATT_TCB* p_tcb = &gatt_cb.tcb[found_idx];
1235 
1236     bool send_indication = true;
1237 
1238     if (gatt_is_srv_chg_ind_pending(p_tcb)) {
1239       send_indication = false;
1240       log::verbose("discard srv chg - already has one in the queue");
1241     }
1242 
1243     // Some LE GATT clients don't respond to service changed indications.
1244     char remote_name[BD_NAME_LEN] = "";
1245     if (send_indication && btif_storage_get_stored_remote_name(bda, remote_name)) {
1246       if (interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, remote_name)) {
1247         log::verbose("discard srv chg - interop matched {}", remote_name);
1248         send_indication = false;
1249       }
1250     }
1251 
1252     if (send_indication) {
1253       gatt_send_srv_chg_ind(bda);
1254     }
1255 
1256     start_idx = ++found_idx;
1257   }
1258 }
1259 
1260 /** This function set the ch_state in tcb */
gatt_set_ch_state(tGATT_TCB * p_tcb,tGATT_CH_STATE ch_state)1261 void gatt_set_ch_state(tGATT_TCB* p_tcb, tGATT_CH_STATE ch_state) {
1262   if (!p_tcb) {
1263     return;
1264   }
1265 
1266   std::string holders_string = gatt_tcb_get_holders_info_string(p_tcb);
1267   log::verbose("{}, transport: {}, state: {} -> {}, {}", p_tcb->peer_bda,
1268                bt_transport_text(p_tcb->transport), gatt_channel_state_text(p_tcb->ch_state),
1269                gatt_channel_state_text(ch_state), holders_string);
1270 
1271   tcb_state_history_.Push({.address = p_tcb->peer_bda,
1272                            .transport = p_tcb->transport,
1273                            .state = ch_state,
1274                            .holders_info = holders_string});
1275 
1276   p_tcb->ch_state = ch_state;
1277 }
1278 
1279 /** This function get the ch_state in tcb */
gatt_get_ch_state(tGATT_TCB * p_tcb)1280 tGATT_CH_STATE gatt_get_ch_state(tGATT_TCB* p_tcb) {
1281   if (!p_tcb) {
1282     return GATT_CH_CLOSE;
1283   }
1284 
1285   log::verbose("{}, transport {},  ch_state={}", p_tcb->peer_bda,
1286                bt_transport_text(p_tcb->transport), gatt_channel_state_text(p_tcb->ch_state));
1287   return p_tcb->ch_state;
1288 }
1289