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