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 "bt_target.h"
26 
27 #include "bt_common.h"
28 #include "bt_utils.h"
29 #include "btif_storage.h"
30 #include "btm_ble_int.h"
31 #include "btm_int.h"
32 #include "connection_manager.h"
33 #include "device/include/interop.h"
34 #include "gatt_int.h"
35 #include "l2c_api.h"
36 #include "osi/include/osi.h"
37 
38 using base::StringPrintf;
39 
40 /* Configuration flags. */
41 #define GATT_L2C_CFG_IND_DONE (1 << 0)
42 #define GATT_L2C_CFG_CFM_DONE (1 << 1)
43 
44 /* minimum GATT MTU size over BR/EDR link
45  */
46 #define GATT_MIN_BR_MTU_SIZE 48
47 
48 /******************************************************************************/
49 /*            L O C A L    F U N C T I O N     P R O T O T Y P E S            */
50 /******************************************************************************/
51 static void gatt_le_connect_cback(uint16_t chan, const RawAddress& bd_addr,
52                                   bool connected, uint16_t reason,
53                                   tBT_TRANSPORT transport);
54 static void gatt_le_data_ind(uint16_t chan, const RawAddress& bd_addr,
55                              BT_HDR* p_buf);
56 static void gatt_le_cong_cback(const RawAddress& remote_bda, bool congest);
57 
58 static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr,
59                                          uint16_t l2cap_cid, uint16_t psm,
60                                          uint8_t l2cap_id);
61 static void gatt_l2cif_connect_cfm_cback(uint16_t l2cap_cid, uint16_t result);
62 static void gatt_l2cif_config_ind_cback(uint16_t l2cap_cid,
63                                         tL2CAP_CFG_INFO* p_cfg);
64 static void gatt_l2cif_config_cfm_cback(uint16_t l2cap_cid,
65                                         tL2CAP_CFG_INFO* p_cfg);
66 static void gatt_l2cif_disconnect_ind_cback(uint16_t l2cap_cid,
67                                             bool ack_needed);
68 static void gatt_l2cif_disconnect_cfm_cback(uint16_t l2cap_cid,
69                                             uint16_t result);
70 static void gatt_l2cif_data_ind_cback(uint16_t l2cap_cid, BT_HDR* p_msg);
71 static void gatt_send_conn_cback(tGATT_TCB* p_tcb);
72 static void gatt_l2cif_congest_cback(uint16_t cid, bool congested);
73 
74 static const tL2CAP_APPL_INFO dyn_info = {gatt_l2cif_connect_ind_cback,
75                                           gatt_l2cif_connect_cfm_cback,
76                                           NULL,
77                                           gatt_l2cif_config_ind_cback,
78                                           gatt_l2cif_config_cfm_cback,
79                                           gatt_l2cif_disconnect_ind_cback,
80                                           gatt_l2cif_disconnect_cfm_cback,
81                                           NULL,
82                                           gatt_l2cif_data_ind_cback,
83                                           gatt_l2cif_congest_cback,
84                                           NULL,
85                                           NULL /* tL2CA_CREDITS_RECEIVED_CB */};
86 
87 tGATT_CB gatt_cb;
88 
89 /*******************************************************************************
90  *
91  * Function         gatt_init
92  *
93  * Description      This function is enable the GATT profile on the device.
94  *                  It clears out the control blocks, and registers with L2CAP.
95  *
96  * Returns          void
97  *
98  ******************************************************************************/
gatt_init(void)99 void gatt_init(void) {
100   tL2CAP_FIXED_CHNL_REG fixed_reg;
101 
102   VLOG(1) << __func__;
103 
104   gatt_cb = tGATT_CB();
105   connection_manager::reset(true);
106   memset(&fixed_reg, 0, sizeof(tL2CAP_FIXED_CHNL_REG));
107 
108   gatt_cb.def_mtu_size = GATT_DEF_BLE_MTU_SIZE;
109   gatt_cb.sign_op_queue = fixed_queue_new(SIZE_MAX);
110   gatt_cb.srv_chg_clt_q = fixed_queue_new(SIZE_MAX);
111   /* First, register fixed L2CAP channel for ATT over BLE */
112   fixed_reg.pL2CA_FixedConn_Cb = gatt_le_connect_cback;
113   fixed_reg.pL2CA_FixedData_Cb = gatt_le_data_ind;
114   fixed_reg.pL2CA_FixedCong_Cb = gatt_le_cong_cback; /* congestion callback */
115   fixed_reg.default_idle_tout = 0xffff; /* 0xffff default idle timeout */
116 
117   L2CA_RegisterFixedChannel(L2CAP_ATT_CID, &fixed_reg);
118 
119   /* Now, register with L2CAP for ATT PSM over BR/EDR */
120   if (!L2CA_Register(BT_PSM_ATT, (tL2CAP_APPL_INFO*)&dyn_info,
121                      false /* enable_snoop */, nullptr, gatt_cb.def_mtu_size)) {
122     LOG(ERROR) << "ATT Dynamic Registration failed";
123   }
124 
125   BTM_SetSecurityLevel(true, "", BTM_SEC_SERVICE_ATT, BTM_SEC_NONE, BT_PSM_ATT,
126                        0, 0);
127   BTM_SetSecurityLevel(false, "", BTM_SEC_SERVICE_ATT, BTM_SEC_NONE, BT_PSM_ATT,
128                        0, 0);
129 
130   gatt_cb.hdl_cfg.gatt_start_hdl = GATT_GATT_START_HANDLE;
131   gatt_cb.hdl_cfg.gap_start_hdl = GATT_GAP_START_HANDLE;
132   gatt_cb.hdl_cfg.app_start_hdl = GATT_APP_START_HANDLE;
133 
134   gatt_cb.hdl_list_info = new std::list<tGATT_HDL_LIST_ELEM>();
135   gatt_cb.srv_list_info = new std::list<tGATT_SRV_LIST_ELEM>();
136   gatt_profile_db_init();
137 }
138 
139 /*******************************************************************************
140  *
141  * Function         gatt_free
142  *
143  * Description      This function frees resources used by the GATT profile.
144  *
145  * Returns          void
146  *
147  ******************************************************************************/
gatt_free(void)148 void gatt_free(void) {
149   int i;
150   VLOG(1) << __func__;
151 
152   fixed_queue_free(gatt_cb.sign_op_queue, NULL);
153   gatt_cb.sign_op_queue = NULL;
154   fixed_queue_free(gatt_cb.srv_chg_clt_q, NULL);
155   gatt_cb.srv_chg_clt_q = NULL;
156   for (i = 0; i < GATT_MAX_PHY_CHANNEL; i++) {
157     gatt_cb.tcb[i].pending_enc_clcb = std::queue<tGATT_CLCB*>();
158 
159     fixed_queue_free(gatt_cb.tcb[i].pending_ind_q, NULL);
160     gatt_cb.tcb[i].pending_ind_q = NULL;
161 
162     alarm_free(gatt_cb.tcb[i].conf_timer);
163     gatt_cb.tcb[i].conf_timer = NULL;
164 
165     alarm_free(gatt_cb.tcb[i].ind_ack_timer);
166     gatt_cb.tcb[i].ind_ack_timer = NULL;
167 
168     fixed_queue_free(gatt_cb.tcb[i].sr_cmd.multi_rsp_q, NULL);
169     gatt_cb.tcb[i].sr_cmd.multi_rsp_q = NULL;
170   }
171 
172   gatt_cb.hdl_list_info->clear();
173   gatt_cb.hdl_list_info = nullptr;
174   gatt_cb.srv_list_info->clear();
175   gatt_cb.srv_list_info = nullptr;
176 }
177 
178 /*******************************************************************************
179  *
180  * Function         gatt_connect
181  *
182  * Description      This function is called to initiate a connection to a peer
183  *                  device.
184  *
185  * Parameter        rem_bda: remote device address to connect to.
186  *
187  * Returns          true if connection is started, otherwise return false.
188  *
189  ******************************************************************************/
gatt_connect(const RawAddress & rem_bda,tGATT_TCB * p_tcb,tBT_TRANSPORT transport,uint8_t initiating_phys,tGATT_IF gatt_if)190 bool gatt_connect(const RawAddress& rem_bda, tGATT_TCB* p_tcb,
191                   tBT_TRANSPORT transport, uint8_t initiating_phys,
192                   tGATT_IF gatt_if) {
193   if (gatt_get_ch_state(p_tcb) != GATT_CH_OPEN)
194     gatt_set_ch_state(p_tcb, GATT_CH_CONN);
195 
196   if (transport != BT_TRANSPORT_LE) {
197     p_tcb->att_lcid = L2CA_ConnectReq(BT_PSM_ATT, rem_bda);
198     return p_tcb->att_lcid != 0;
199   }
200 
201   // Already connected, mark the link as used
202   if (gatt_get_ch_state(p_tcb) == GATT_CH_OPEN) {
203     gatt_update_app_use_link_flag(gatt_if, p_tcb, true, true);
204     return true;
205   }
206 
207   p_tcb->att_lcid = L2CAP_ATT_CID;
208   return connection_manager::direct_connect_add(gatt_if, rem_bda);
209 }
210 
211 /*******************************************************************************
212  *
213  * Function         gatt_disconnect
214  *
215  * Description      This function is called to disconnect to an ATT device.
216  *
217  * Parameter        p_tcb: pointer to the TCB to disconnect.
218  *
219  * Returns          true: if connection found and to be disconnected; otherwise
220  *                  return false.
221  *
222  ******************************************************************************/
gatt_disconnect(tGATT_TCB * p_tcb)223 bool gatt_disconnect(tGATT_TCB* p_tcb) {
224   VLOG(1) << __func__;
225 
226   if (!p_tcb) return false;
227 
228   tGATT_CH_STATE ch_state = gatt_get_ch_state(p_tcb);
229   if (ch_state == GATT_CH_CLOSING) {
230     VLOG(1) << __func__ << " already in closing state";
231     return true;
232   }
233 
234   bool ret = true;
235   if (p_tcb->att_lcid == L2CAP_ATT_CID) {
236     if (ch_state == GATT_CH_OPEN) {
237       /* only LCB exist between remote device and local */
238       ret = L2CA_RemoveFixedChnl(L2CAP_ATT_CID, p_tcb->peer_bda);
239     } else {
240       L2CA_CancelBleConnectReq(p_tcb->peer_bda);
241       gatt_cleanup_upon_disc(p_tcb->peer_bda, HCI_ERR_CONN_CAUSE_LOCAL_HOST, p_tcb->transport);
242       return true;
243     }
244     gatt_set_ch_state(p_tcb, GATT_CH_CLOSING);
245   } else {
246     if ((ch_state == GATT_CH_OPEN) || (ch_state == GATT_CH_CFG))
247       ret = L2CA_DisconnectReq(p_tcb->att_lcid);
248     else
249       VLOG(1) << __func__ << " gatt_disconnect channel not opened";
250   }
251 
252   return ret;
253 }
254 
255 /*******************************************************************************
256  *
257  * Function         gatt_update_app_hold_link_status
258  *
259  * Description      Update the application use link status
260  *
261  * Returns          true if any modifications are made or
262  *                  when it already exists, false otherwise.
263  *
264  ******************************************************************************/
gatt_update_app_hold_link_status(tGATT_IF gatt_if,tGATT_TCB * p_tcb,bool is_add)265 bool gatt_update_app_hold_link_status(tGATT_IF gatt_if, tGATT_TCB* p_tcb,
266                                       bool is_add) {
267   auto& holders = p_tcb->app_hold_link;
268 
269   VLOG(1) << __func__;
270   if (is_add) {
271     auto ret = holders.insert(gatt_if);
272     if (ret.second) {
273       VLOG(1) << "added gatt_if=" << +gatt_if;
274     } else {
275       VLOG(1) << "attempt to add already existing gatt_if=" << +gatt_if;
276     }
277     return true;
278   }
279 
280   //! is_add
281   if (!holders.erase(gatt_if)) {
282     VLOG(1) << "attempt to remove nonexisting gatt_if=" << +gatt_if;
283     return false;
284   }
285 
286   VLOG(1) << "removed gatt_if=" << +gatt_if;
287   return true;
288 }
289 
290 /*******************************************************************************
291  *
292  * Function         gatt_update_app_use_link_flag
293  *
294  * Description      Update the application use link flag and optional to check
295  *                  the acl link if the link is up then set the idle time out
296  *                  accordingly
297  *
298  * Returns          void.
299  *
300  ******************************************************************************/
gatt_update_app_use_link_flag(tGATT_IF gatt_if,tGATT_TCB * p_tcb,bool is_add,bool check_acl_link)301 void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb,
302                                    bool is_add, bool check_acl_link) {
303   VLOG(1) << StringPrintf("%s: is_add=%d chk_link=%d", __func__, is_add,
304                           check_acl_link);
305 
306   if (!p_tcb) return;
307 
308   // If we make no modification, i.e. kill app that was never connected to a
309   // device, skip updating the device state.
310   if (!gatt_update_app_hold_link_status(gatt_if, p_tcb, is_add)) return;
311 
312   if (!check_acl_link) {
313     return;
314   }
315 
316   bool is_valid_handle =
317       (BTM_GetHCIConnHandle(p_tcb->peer_bda, p_tcb->transport) !=
318        GATT_INVALID_ACL_HANDLE);
319 
320   if (is_add) {
321     if (p_tcb->att_lcid == L2CAP_ATT_CID && is_valid_handle) {
322       VLOG(1) << "disable link idle timer";
323       /* acl link is connected disable the idle timeout */
324       GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT,
325                           p_tcb->transport);
326     }
327   } else {
328     if (p_tcb->app_hold_link.empty()) {
329       // acl link is connected but no application needs to use the link
330       if (p_tcb->att_lcid == L2CAP_ATT_CID && is_valid_handle) {
331         /* for fixed channel, set the timeout value to
332            GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP seconds */
333         VLOG(1) << " start link idle timer = "
334                 << GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP << " sec";
335         GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP,
336                             p_tcb->transport);
337       } else
338         // disconnect the dynamic channel
339         gatt_disconnect(p_tcb);
340     }
341   }
342 }
343 
344 /** GATT connection initiation */
gatt_act_connect(tGATT_REG * p_reg,const RawAddress & bd_addr,tBT_TRANSPORT transport,int8_t initiating_phys)345 bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr,
346                       tBT_TRANSPORT transport, int8_t initiating_phys) {
347   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport);
348   if (p_tcb != NULL) {
349     /* before link down, another app try to open a GATT connection */
350     uint8_t st = gatt_get_ch_state(p_tcb);
351     if (st == GATT_CH_OPEN && p_tcb->app_hold_link.empty() &&
352         transport == BT_TRANSPORT_LE) {
353       if (!gatt_connect(bd_addr, p_tcb, transport, initiating_phys,
354                         p_reg->gatt_if))
355         return false;
356     } else if (st == GATT_CH_CLOSING) {
357       LOG(INFO) << "Must finish disconnection before new connection";
358       /* need to complete the closing first */
359       return false;
360     }
361 
362     return true;
363   }
364 
365   p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, transport);
366   if (!p_tcb) {
367     LOG(ERROR) << "Max TCB for gatt_if [ " << +p_reg->gatt_if << "] reached.";
368     return false;
369   }
370 
371   if (!gatt_connect(bd_addr, p_tcb, transport, initiating_phys,
372                     p_reg->gatt_if)) {
373     LOG(ERROR) << "gatt_connect failed";
374     fixed_queue_free(p_tcb->pending_ind_q, NULL);
375     *p_tcb = tGATT_TCB();
376     return false;
377   }
378 
379   return true;
380 }
381 
382 namespace connection_manager {
on_connection_timed_out(uint8_t app_id,const RawAddress & address)383 void on_connection_timed_out(uint8_t app_id, const RawAddress& address) {
384   gatt_le_connect_cback(L2CAP_ATT_CID, address, false, 0xff, BT_TRANSPORT_LE);
385 }
386 }  // namespace connection_manager
387 
388 /** This callback function is called by L2CAP to indicate that the ATT fixed
389  * channel for LE is connected (conn = true)/disconnected (conn = false).
390  */
gatt_le_connect_cback(uint16_t chan,const RawAddress & bd_addr,bool connected,uint16_t reason,tBT_TRANSPORT transport)391 static void gatt_le_connect_cback(uint16_t chan, const RawAddress& bd_addr,
392                                   bool connected, uint16_t reason,
393                                   tBT_TRANSPORT transport) {
394   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport);
395   bool check_srv_chg = false;
396   tGATTS_SRV_CHG* p_srv_chg_clt = NULL;
397 
398   /* ignore all fixed channel connect/disconnect on BR/EDR link for GATT */
399   if (transport == BT_TRANSPORT_BR_EDR) return;
400 
401   VLOG(1) << "GATT   ATT protocol channel with BDA: " << bd_addr << " is "
402           << ((connected) ? "connected" : "disconnected");
403 
404   p_srv_chg_clt = gatt_is_bda_in_the_srv_chg_clt_list(bd_addr);
405   if (p_srv_chg_clt != NULL) {
406     check_srv_chg = true;
407   } else {
408     if (btm_sec_is_a_bonded_dev(bd_addr))
409       gatt_add_a_bonded_dev_for_srv_chg(bd_addr);
410   }
411 
412   if (!connected) {
413     gatt_cleanup_upon_disc(bd_addr, reason, transport);
414     VLOG(1) << "ATT disconnected";
415     return;
416   }
417 
418   /* do we have a channel initiating a connection? */
419   if (p_tcb) {
420     /* we are initiating connection */
421     if (gatt_get_ch_state(p_tcb) == GATT_CH_CONN) {
422       /* send callback */
423       gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
424       p_tcb->payload_size = GATT_DEF_BLE_MTU_SIZE;
425 
426       gatt_send_conn_cback(p_tcb);
427     }
428     if (check_srv_chg) gatt_chk_srv_chg(p_srv_chg_clt);
429   }
430   /* this is incoming connection or background connection callback */
431 
432   else {
433     p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, BT_TRANSPORT_LE);
434     if (!p_tcb) {
435       LOG(ERROR) << "CCB max out, no rsources";
436       return;
437     }
438 
439     p_tcb->att_lcid = L2CAP_ATT_CID;
440 
441     gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
442 
443     p_tcb->payload_size = GATT_DEF_BLE_MTU_SIZE;
444 
445     gatt_send_conn_cback(p_tcb);
446     if (check_srv_chg) {
447       gatt_chk_srv_chg(p_srv_chg_clt);
448     }
449   }
450 }
451 
452 /** This function is called to process the congestion callback from lcb */
gatt_channel_congestion(tGATT_TCB * p_tcb,bool congested)453 static void gatt_channel_congestion(tGATT_TCB* p_tcb, bool congested) {
454   uint8_t i = 0;
455   tGATT_REG* p_reg = NULL;
456   uint16_t conn_id;
457 
458   /* if uncongested, check to see if there is any more pending data */
459   if (p_tcb != NULL && !congested) {
460     gatt_cl_send_next_cmd_inq(*p_tcb);
461   }
462   /* notifying all applications for the connection up event */
463   for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
464     if (p_reg->in_use) {
465       if (p_reg->app_cb.p_congestion_cb) {
466         conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if);
467         (*p_reg->app_cb.p_congestion_cb)(conn_id, congested);
468       }
469     }
470   }
471 }
472 
gatt_notify_phy_updated(uint8_t status,uint16_t handle,uint8_t tx_phy,uint8_t rx_phy)473 void gatt_notify_phy_updated(uint8_t status, uint16_t handle, uint8_t tx_phy,
474                              uint8_t rx_phy) {
475   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
476   if (!p_dev_rec) {
477     BTM_TRACE_WARNING("%s: No Device Found!", __func__);
478     return;
479   }
480 
481   tGATT_TCB* p_tcb =
482       gatt_find_tcb_by_addr(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE);
483   if (!p_tcb) return;
484 
485   for (int i = 0; i < GATT_MAX_APPS; i++) {
486     tGATT_REG* p_reg = &gatt_cb.cl_rcb[i];
487     if (p_reg->in_use && p_reg->app_cb.p_phy_update_cb) {
488       uint16_t conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if);
489       (*p_reg->app_cb.p_phy_update_cb)(p_reg->gatt_if, conn_id, tx_phy, rx_phy,
490                                        status);
491     }
492   }
493 }
494 
gatt_notify_conn_update(uint16_t handle,uint16_t interval,uint16_t latency,uint16_t timeout,uint8_t status)495 void gatt_notify_conn_update(uint16_t handle, uint16_t interval,
496                              uint16_t latency, uint16_t timeout,
497                              uint8_t status) {
498   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
499   if (!p_dev_rec) return;
500 
501   tGATT_TCB* p_tcb =
502       gatt_find_tcb_by_addr(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE);
503   if (!p_tcb) return;
504 
505   for (int i = 0; i < GATT_MAX_APPS; i++) {
506     tGATT_REG* p_reg = &gatt_cb.cl_rcb[i];
507     if (p_reg->in_use && p_reg->app_cb.p_conn_update_cb) {
508       uint16_t conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if);
509       (*p_reg->app_cb.p_conn_update_cb)(p_reg->gatt_if, conn_id, interval,
510                                         latency, timeout, status);
511     }
512   }
513 }
514 
515 /** This function is called when GATT fixed channel is congested or uncongested
516  */
gatt_le_cong_cback(const RawAddress & remote_bda,bool congested)517 static void gatt_le_cong_cback(const RawAddress& remote_bda, bool congested) {
518   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote_bda, BT_TRANSPORT_LE);
519   if (!p_tcb) return;
520 
521   /* if uncongested, check to see if there is any more pending data */
522     gatt_channel_congestion(p_tcb, congested);
523 }
524 
525 /*******************************************************************************
526  *
527  * Function         gatt_le_data_ind
528  *
529  * Description      This function is called when data is received from L2CAP.
530  *                  if we are the originator of the connection, we are the ATT
531  *                  client, and the received message is queued up for the
532  *                  client.
533  *
534  *                  If we are the destination of the connection, we are the ATT
535  *                  server, so the message is passed to the server processing
536  *                  function.
537  *
538  * Returns          void
539  *
540  ******************************************************************************/
gatt_le_data_ind(uint16_t chan,const RawAddress & bd_addr,BT_HDR * p_buf)541 static void gatt_le_data_ind(uint16_t chan, const RawAddress& bd_addr,
542                              BT_HDR* p_buf) {
543 
544   /* Find CCB based on bd addr */
545   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_LE);
546   if (p_tcb) {
547     if (gatt_get_ch_state(p_tcb) < GATT_CH_OPEN) {
548       LOG(WARNING) << "ATT - Ignored L2CAP data while in state: "
549                    << +gatt_get_ch_state(p_tcb);
550     } else
551       gatt_data_process(*p_tcb, p_buf);
552   }
553 
554   osi_free(p_buf);
555 }
556 
557 /*******************************************************************************
558  *
559  * Function         gatt_l2cif_connect_ind
560  *
561  * Description      This function handles an inbound connection indication
562  *                  from L2CAP. This is the case where we are acting as a
563  *                  server.
564  *
565  * Returns          void
566  *
567  ******************************************************************************/
gatt_l2cif_connect_ind_cback(const RawAddress & bd_addr,uint16_t lcid,UNUSED_ATTR uint16_t psm,uint8_t id)568 static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr,
569                                          uint16_t lcid,
570                                          UNUSED_ATTR uint16_t psm, uint8_t id) {
571   uint8_t result = L2CAP_CONN_OK;
572   LOG(INFO) << "Connection indication cid = " << +lcid;
573 
574   /* new connection ? */
575   tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_BR_EDR);
576   if (p_tcb == NULL) {
577     /* allocate tcb */
578     p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, BT_TRANSPORT_BR_EDR);
579     if (p_tcb == NULL) {
580       /* no tcb available, reject L2CAP connection */
581       result = L2CAP_CONN_NO_RESOURCES;
582     } else
583       p_tcb->att_lcid = lcid;
584 
585   } else /* existing connection , reject it */
586   {
587     result = L2CAP_CONN_NO_RESOURCES;
588   }
589 
590   /* Send L2CAP connect rsp */
591   L2CA_ConnectRsp(bd_addr, id, lcid, result, 0);
592 
593   /* if result ok, proceed with connection */
594   if (result != L2CAP_CONN_OK) return;
595 
596   /* transition to configuration state */
597   gatt_set_ch_state(p_tcb, GATT_CH_CFG);
598 
599   /* Send L2CAP config req */
600   tL2CAP_CFG_INFO cfg;
601   memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
602   cfg.mtu_present = true;
603   cfg.mtu = GATT_MAX_MTU_SIZE;
604 
605   L2CA_ConfigReq(lcid, &cfg);
606 }
607 
608 /** This is the L2CAP connect confirm callback function */
gatt_l2cif_connect_cfm_cback(uint16_t lcid,uint16_t result)609 static void gatt_l2cif_connect_cfm_cback(uint16_t lcid, uint16_t result) {
610   tGATT_TCB* p_tcb;
611   tL2CAP_CFG_INFO cfg;
612 
613   /* look up clcb for this channel */
614   p_tcb = gatt_find_tcb_by_cid(lcid);
615   if (!p_tcb) return;
616 
617   VLOG(1) << __func__
618           << StringPrintf(" result: %d ch_state: %d, lcid:0x%x", result,
619                           gatt_get_ch_state(p_tcb), p_tcb->att_lcid);
620 
621   /* if in correct state */
622   if (gatt_get_ch_state(p_tcb) == GATT_CH_CONN) {
623     /* if result successful */
624     if (result == L2CAP_CONN_OK) {
625       /* set channel state */
626       gatt_set_ch_state(p_tcb, GATT_CH_CFG);
627 
628       /* Send L2CAP config req */
629       memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
630       cfg.mtu_present = true;
631       cfg.mtu = GATT_MAX_MTU_SIZE;
632       L2CA_ConfigReq(lcid, &cfg);
633     }
634     /* else initiating connection failure */
635     else {
636       gatt_cleanup_upon_disc(p_tcb->peer_bda, result, GATT_TRANSPORT_BR_EDR);
637     }
638   } else /* wrong state, disconnect it */
639   {
640     if (result == L2CAP_CONN_OK) {
641       /* just in case the peer also accepts our connection - Send L2CAP
642        * disconnect req */
643       L2CA_DisconnectReq(lcid);
644     }
645   }
646 }
647 
648 /** This is the L2CAP config confirm callback function */
gatt_l2cif_config_cfm_cback(uint16_t lcid,tL2CAP_CFG_INFO * p_cfg)649 void gatt_l2cif_config_cfm_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) {
650 
651   /* look up clcb for this channel */
652   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
653   if (!p_tcb) return;
654 
655   /* if in incorrect state */
656   if (gatt_get_ch_state(p_tcb) != GATT_CH_CFG) return;
657 
658   /* if result not successful */
659   if (p_cfg->result != L2CAP_CFG_OK) {
660     /* Send L2CAP disconnect req */
661     L2CA_DisconnectReq(lcid);
662     return;
663   }
664 
665   /* update flags */
666   p_tcb->ch_flags |= GATT_L2C_CFG_CFM_DONE;
667 
668   /* if configuration not complete */
669   if (!(p_tcb->ch_flags & GATT_L2C_CFG_IND_DONE)) return;
670 
671   gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
672 
673   tGATTS_SRV_CHG* p_srv_chg_clt =
674       gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda);
675   if (p_srv_chg_clt != NULL) {
676     gatt_chk_srv_chg(p_srv_chg_clt);
677   } else {
678     if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda))
679       gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda);
680   }
681 
682   /* send callback */
683   gatt_send_conn_cback(p_tcb);
684 }
685 
686 /** This is the L2CAP config indication callback function */
gatt_l2cif_config_ind_cback(uint16_t lcid,tL2CAP_CFG_INFO * p_cfg)687 void gatt_l2cif_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) {
688   tGATTS_SRV_CHG* p_srv_chg_clt = NULL;
689   /* look up clcb for this channel */
690   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
691   if (!p_tcb) return;
692 
693   /* GATT uses the smaller of our MTU and peer's MTU  */
694   if (p_cfg->mtu_present &&
695       (p_cfg->mtu >= GATT_MIN_BR_MTU_SIZE && p_cfg->mtu < L2CAP_DEFAULT_MTU))
696     p_tcb->payload_size = p_cfg->mtu;
697   else
698     p_tcb->payload_size = L2CAP_DEFAULT_MTU;
699 
700   /* send L2CAP configure response */
701   memset(p_cfg, 0, sizeof(tL2CAP_CFG_INFO));
702   p_cfg->result = L2CAP_CFG_OK;
703   L2CA_ConfigRsp(lcid, p_cfg);
704 
705   /* if not first config ind */
706   if ((p_tcb->ch_flags & GATT_L2C_CFG_IND_DONE)) return;
707 
708   /* update flags */
709   p_tcb->ch_flags |= GATT_L2C_CFG_IND_DONE;
710 
711   /* if configuration not complete */
712   if ((p_tcb->ch_flags & GATT_L2C_CFG_CFM_DONE) == 0) return;
713 
714   gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
715   p_srv_chg_clt = gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda);
716   if (p_srv_chg_clt != NULL) {
717     gatt_chk_srv_chg(p_srv_chg_clt);
718   } else {
719     if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda))
720       gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda);
721   }
722 
723   /* send callback */
724   gatt_send_conn_cback(p_tcb);
725 }
726 
727 /** This is the L2CAP disconnect indication callback function */
gatt_l2cif_disconnect_ind_cback(uint16_t lcid,bool ack_needed)728 void gatt_l2cif_disconnect_ind_cback(uint16_t lcid, bool ack_needed) {
729 
730   /* look up clcb for this channel */
731   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
732   if (!p_tcb) return;
733 
734   if (ack_needed) {
735     /* send L2CAP disconnect response */
736     L2CA_DisconnectRsp(lcid);
737   }
738 
739   if (gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda) == NULL) {
740     if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda))
741       gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda);
742   }
743   /* if ACL link is still up, no reason is logged, l2cap is disconnect from
744    * peer */
745   uint16_t reason = L2CA_GetDisconnectReason(p_tcb->peer_bda, p_tcb->transport);
746   if (reason == 0) reason = GATT_CONN_TERMINATE_PEER_USER;
747 
748   /* send disconnect callback */
749   gatt_cleanup_upon_disc(p_tcb->peer_bda, reason, GATT_TRANSPORT_BR_EDR);
750 }
751 
752 /** This is the L2CAP disconnect confirm callback function */
gatt_l2cif_disconnect_cfm_cback(uint16_t lcid,UNUSED_ATTR uint16_t result)753 static void gatt_l2cif_disconnect_cfm_cback(uint16_t lcid,
754                                             UNUSED_ATTR uint16_t result) {
755 
756   /* look up clcb for this channel */
757   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
758   if (!p_tcb) return;
759 
760   /* If the device is not in the service changed client list, add it... */
761   if (gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda) == NULL) {
762     if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda))
763       gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda);
764   }
765 
766   /* send disconnect callback */
767   /* if ACL link is still up, no reason is logged, l2cap is disconnect from
768    * peer */
769   uint16_t reason = L2CA_GetDisconnectReason(p_tcb->peer_bda, p_tcb->transport);
770   if (reason == 0) reason = GATT_CONN_TERMINATE_LOCAL_HOST;
771 
772   gatt_cleanup_upon_disc(p_tcb->peer_bda, reason, GATT_TRANSPORT_BR_EDR);
773 }
774 
775 /** This is the L2CAP data indication callback function */
gatt_l2cif_data_ind_cback(uint16_t lcid,BT_HDR * p_buf)776 static void gatt_l2cif_data_ind_cback(uint16_t lcid, BT_HDR* p_buf) {
777   /* look up clcb for this channel */
778   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
779   if (p_tcb && gatt_get_ch_state(p_tcb) == GATT_CH_OPEN) {
780     /* process the data */
781     gatt_data_process(*p_tcb, p_buf);
782   }
783 
784   osi_free(p_buf);
785 }
786 
787 /** L2CAP congestion callback */
gatt_l2cif_congest_cback(uint16_t lcid,bool congested)788 static void gatt_l2cif_congest_cback(uint16_t lcid, bool congested) {
789   tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid);
790 
791   if (p_tcb != NULL) {
792     gatt_channel_congestion(p_tcb, congested);
793   }
794 }
795 
796 /** Callback used to notify layer above about a connection */
gatt_send_conn_cback(tGATT_TCB * p_tcb)797 static void gatt_send_conn_cback(tGATT_TCB* p_tcb) {
798   uint8_t i;
799   tGATT_REG* p_reg;
800   uint16_t conn_id;
801 
802   std::set<tGATT_IF> apps =
803       connection_manager::get_apps_connecting_to(p_tcb->peer_bda);
804 
805   /* notifying all applications for the connection up event */
806   for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) {
807     if (!p_reg->in_use) continue;
808 
809     if (apps.find(p_reg->gatt_if) != apps.end())
810       gatt_update_app_use_link_flag(p_reg->gatt_if, p_tcb, true, true);
811 
812     if (p_reg->app_cb.p_conn_cb) {
813       conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if);
814       (*p_reg->app_cb.p_conn_cb)(p_reg->gatt_if, p_tcb->peer_bda, conn_id, true,
815                                  0, p_tcb->transport);
816     }
817   }
818 
819   /* Remove the direct connection */
820   connection_manager::on_connection_complete(p_tcb->peer_bda);
821 
822   if (!p_tcb->app_hold_link.empty() && p_tcb->att_lcid == L2CAP_ATT_CID) {
823     /* disable idle timeout if one or more clients are holding the link disable
824      * the idle timer */
825     GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT,
826                         p_tcb->transport);
827   }
828 }
829 
830 /*******************************************************************************
831  *
832  * Function         gatt_le_data_ind
833  *
834  * Description      This function is called when data is received from L2CAP.
835  *                  if we are the originator of the connection, we are the ATT
836  *                  client, and the received message is queued up for the
837  *                  client.
838  *
839  *                  If we are the destination of the connection, we are the ATT
840  *                  server, so the message is passed to the server processing
841  *                  function.
842  *
843  * Returns          void
844  *
845  ******************************************************************************/
gatt_data_process(tGATT_TCB & tcb,BT_HDR * p_buf)846 void gatt_data_process(tGATT_TCB& tcb, BT_HDR* p_buf) {
847   uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset;
848   uint8_t op_code, pseudo_op_code;
849 
850   if (p_buf->len <= 0) {
851     LOG(ERROR) << "invalid data length, ignore";
852     return;
853   }
854 
855   uint16_t msg_len = p_buf->len - 1;
856   STREAM_TO_UINT8(op_code, p);
857 
858   /* remove the two MSBs associated with sign write and write cmd */
859   pseudo_op_code = op_code & (~GATT_WRITE_CMD_MASK);
860 
861   if (pseudo_op_code >= GATT_OP_CODE_MAX) {
862     /* Note: PTS: GATT/SR/UNS/BI-01-C mandates error on unsupported ATT request.
863      */
864     LOG(ERROR) << __func__
865                << ": ATT - Rcvd L2CAP data, unknown cmd: " << loghex(op_code);
866     gatt_send_error_rsp(tcb, GATT_REQ_NOT_SUPPORTED, op_code, 0, false);
867     return;
868   }
869 
870   if (op_code == GATT_SIGN_CMD_WRITE) {
871     gatt_verify_signature(tcb, p_buf);
872   } else {
873     /* message from client */
874     if ((op_code % 2) == 0)
875       gatt_server_handle_client_req(tcb, op_code, msg_len, p);
876     else
877       gatt_client_handle_server_rsp(tcb, op_code, msg_len, p);
878   }
879 }
880 
881 /** Add a bonded dev to the service changed client list */
gatt_add_a_bonded_dev_for_srv_chg(const RawAddress & bda)882 void gatt_add_a_bonded_dev_for_srv_chg(const RawAddress& bda) {
883   tGATTS_SRV_CHG_REQ req;
884   tGATTS_SRV_CHG srv_chg_clt;
885 
886   srv_chg_clt.bda = bda;
887   srv_chg_clt.srv_changed = false;
888   if (!gatt_add_srv_chg_clt(&srv_chg_clt)) return;
889 
890   req.srv_chg.bda = bda;
891   req.srv_chg.srv_changed = false;
892   if (gatt_cb.cb_info.p_srv_chg_callback)
893     (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_ADD_CLIENT, &req,
894                                           NULL);
895 }
896 
897 /** This function is called to send a service chnaged indication to the
898  * specified bd address */
gatt_send_srv_chg_ind(const RawAddress & peer_bda)899 void gatt_send_srv_chg_ind(const RawAddress& peer_bda) {
900   VLOG(1) << __func__;
901 
902   if (!gatt_cb.handle_of_h_r) return;
903 
904   uint16_t conn_id = gatt_profile_find_conn_id_by_bd_addr(peer_bda);
905   if (conn_id == GATT_INVALID_CONN_ID) {
906     LOG(ERROR) << "Unable to find conn_id for " << peer_bda;
907     return;
908   }
909 
910   uint8_t handle_range[GATT_SIZE_OF_SRV_CHG_HNDL_RANGE];
911   uint8_t* p = handle_range;
912   UINT16_TO_STREAM(p, 1);
913   UINT16_TO_STREAM(p, 0xFFFF);
914   GATTS_HandleValueIndication(conn_id, gatt_cb.handle_of_h_r,
915                               GATT_SIZE_OF_SRV_CHG_HNDL_RANGE, handle_range);
916 }
917 
918 /** Check sending service chnaged Indication is required or not if required then
919  * send the Indication */
gatt_chk_srv_chg(tGATTS_SRV_CHG * p_srv_chg_clt)920 void gatt_chk_srv_chg(tGATTS_SRV_CHG* p_srv_chg_clt) {
921   VLOG(1) << __func__ << " srv_changed=" << +p_srv_chg_clt->srv_changed;
922 
923   if (p_srv_chg_clt->srv_changed) {
924     gatt_send_srv_chg_ind(p_srv_chg_clt->bda);
925   }
926 }
927 
928 /** This function is used to initialize the service changed attribute value */
gatt_init_srv_chg(void)929 void gatt_init_srv_chg(void) {
930   tGATTS_SRV_CHG_REQ req;
931   tGATTS_SRV_CHG_RSP rsp;
932   tGATTS_SRV_CHG srv_chg_clt;
933 
934   VLOG(1) << __func__;
935   if (!gatt_cb.cb_info.p_srv_chg_callback) {
936     VLOG(1) << __func__ << " callback not registered yet";
937     return;
938   }
939 
940   bool status = (*gatt_cb.cb_info.p_srv_chg_callback)(
941       GATTS_SRV_CHG_CMD_READ_NUM_CLENTS, NULL, &rsp);
942 
943   if (!(status && rsp.num_clients)) return;
944 
945   VLOG(1) << "num_srv_chg_clt_clients=" << +rsp.num_clients;
946   uint8_t num_clients = rsp.num_clients;
947   uint8_t i = 1; /* use one based index */
948   while ((i <= num_clients) && status) {
949     req.client_read_index = i;
950     status = (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_READ_CLENT,
951                                                    &req, &rsp);
952     if (status) {
953       memcpy(&srv_chg_clt, &rsp.srv_chg, sizeof(tGATTS_SRV_CHG));
954       if (gatt_add_srv_chg_clt(&srv_chg_clt) == NULL) {
955         LOG(ERROR) << "Unable to add a service change client";
956         status = false;
957       }
958     }
959     i++;
960   }
961 }
962 
963 /**This function is process the service changed request */
gatt_proc_srv_chg(void)964 void gatt_proc_srv_chg(void) {
965   RawAddress bda;
966   tBT_TRANSPORT transport;
967   uint8_t found_idx;
968 
969   VLOG(1) << __func__;
970 
971   if (!gatt_cb.cb_info.p_srv_chg_callback || !gatt_cb.handle_of_h_r) return;
972 
973   gatt_set_srv_chg();
974   uint8_t start_idx = 0;
975   while (gatt_find_the_connected_bda(start_idx, bda, &found_idx, &transport)) {
976     tGATT_TCB* p_tcb = &gatt_cb.tcb[found_idx];
977 
978     bool send_indication = true;
979 
980     if (gatt_is_srv_chg_ind_pending(p_tcb)) {
981       send_indication = false;
982       VLOG(1) << "discard srv chg - already has one in the queue";
983     }
984 
985     // Some LE GATT clients don't respond to service changed indications.
986     char remote_name[BTM_MAX_REM_BD_NAME_LEN] = "";
987     if (send_indication &&
988         btif_storage_get_stored_remote_name(bda, remote_name)) {
989       if (interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND,
990                              remote_name)) {
991         VLOG(1) << "discard srv chg - interop matched " << remote_name;
992         send_indication = false;
993       }
994     }
995 
996     if (send_indication) gatt_send_srv_chg_ind(bda);
997 
998     start_idx = ++found_idx;
999   }
1000 }
1001 
1002 /** This function set the ch_state in tcb */
gatt_set_ch_state(tGATT_TCB * p_tcb,tGATT_CH_STATE ch_state)1003 void gatt_set_ch_state(tGATT_TCB* p_tcb, tGATT_CH_STATE ch_state) {
1004   if (!p_tcb) return;
1005 
1006   VLOG(1) << __func__ << ": old=" << +p_tcb->ch_state
1007           << " new=" << loghex(ch_state);
1008   p_tcb->ch_state = ch_state;
1009 }
1010 
1011 /** This function get the ch_state in tcb */
gatt_get_ch_state(tGATT_TCB * p_tcb)1012 tGATT_CH_STATE gatt_get_ch_state(tGATT_TCB* p_tcb) {
1013   if (!p_tcb) return GATT_CH_CLOSE;
1014 
1015   VLOG(1) << "gatt_get_ch_state: ch_state=" << +p_tcb->ch_state;
1016   return p_tcb->ch_state;
1017 }
1018