1/******************************************************************************
2 *
3 *  Copyright (C) 2017 The Android Open Source Project
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#include <base/logging.h>
20#include <base/strings/stringprintf.h>
21#include <string.h>
22#include <array>
23#include <list>
24#include <queue>
25#include "gap_api.h"
26#include "gatt_api.h"
27
28using base::StringPrintf;
29
30namespace {
31
32typedef struct {
33  uint16_t uuid;
34  tGAP_BLE_CMPL_CBACK* p_cback;
35} tGAP_REQUEST;
36
37typedef struct {
38  RawAddress bda;
39  tGAP_BLE_CMPL_CBACK* p_cback;
40  uint16_t conn_id;
41  uint16_t cl_op_uuid;
42  bool connected;
43  std::queue<tGAP_REQUEST> requests;
44} tGAP_CLCB;
45
46typedef struct {
47  uint16_t handle;
48  uint16_t uuid;
49  tGAP_BLE_ATTR_VALUE attr_value;
50} tGAP_ATTR;
51
52void server_attr_request_cback(uint16_t, uint32_t, tGATTS_REQ_TYPE,
53                               tGATTS_DATA*);
54void client_connect_cback(tGATT_IF, const RawAddress&, uint16_t, bool,
55                          tGATT_DISCONN_REASON, tGATT_TRANSPORT);
56void client_cmpl_cback(uint16_t, tGATTC_OPTYPE, tGATT_STATUS,
57                       tGATT_CL_COMPLETE*);
58
59tGATT_CBACK gap_cback = {client_connect_cback,
60                         client_cmpl_cback,
61                         NULL,
62                         NULL,
63                         server_attr_request_cback,
64                         NULL,
65                         NULL,
66                         NULL,
67                         NULL};
68
69constexpr int GAP_CHAR_DEV_NAME_SIZE = BD_NAME_LEN;
70constexpr int GAP_MAX_CHAR_NUM = 4;
71
72std::vector<tGAP_CLCB> gap_clcbs;
73/* LE GAP attribute database */
74std::array<tGAP_ATTR, GAP_MAX_CHAR_NUM> gatt_attr;
75tGATT_IF gatt_if;
76
77/** returns LCB with macthing bd address, or nullptr */
78tGAP_CLCB* find_clcb_by_bd_addr(const RawAddress& bda) {
79  for (auto& cb : gap_clcbs)
80    if (cb.bda == bda) return &cb;
81
82  return nullptr;
83}
84
85/** returns LCB with macthing connection ID, or nullptr if not found  */
86tGAP_CLCB* ble_find_clcb_by_conn_id(uint16_t conn_id) {
87  for (auto& cb : gap_clcbs)
88    if (cb.connected && cb.conn_id == conn_id) return &cb;
89
90  return nullptr;
91}
92
93/** allocates a GAP connection link control block */
94tGAP_CLCB* clcb_alloc(const RawAddress& bda) {
95  gap_clcbs.emplace_back();
96  tGAP_CLCB& cb = gap_clcbs.back();
97  cb.bda = bda;
98  return &cb;
99}
100
101/** The function clean up the pending request queue in GAP */
102void clcb_dealloc(tGAP_CLCB& clcb) {
103  // put last element into place of current element, and remove last one - just
104  // fast remove.
105  for (auto it = gap_clcbs.begin(); it != gap_clcbs.end(); it++) {
106    if (it->conn_id == clcb.conn_id) {
107      auto last_one = std::prev(gap_clcbs.end());
108      *it = *last_one;
109      gap_clcbs.erase(last_one);
110      return;
111    }
112  }
113}
114
115/** GAP Attributes Database Request callback */
116tGATT_STATUS read_attr_value(uint16_t handle, tGATT_VALUE* p_value,
117                             bool is_long) {
118  uint8_t* p = p_value->value;
119  uint16_t offset = p_value->offset;
120  uint8_t* p_dev_name = NULL;
121
122  for (const tGAP_ATTR& db_attr : gatt_attr) {
123    const tGAP_BLE_ATTR_VALUE& attr_value = db_attr.attr_value;
124    if (handle == db_attr.handle) {
125      if (db_attr.uuid != GATT_UUID_GAP_DEVICE_NAME && is_long == true)
126        return GATT_NOT_LONG;
127
128      switch (db_attr.uuid) {
129        case GATT_UUID_GAP_DEVICE_NAME:
130          BTM_ReadLocalDeviceName((char**)&p_dev_name);
131          if (strlen((char*)p_dev_name) > GATT_MAX_ATTR_LEN)
132            p_value->len = GATT_MAX_ATTR_LEN;
133          else
134            p_value->len = (uint16_t)strlen((char*)p_dev_name);
135
136          if (offset > p_value->len)
137            return GATT_INVALID_OFFSET;
138          else {
139            p_value->len -= offset;
140            p_dev_name += offset;
141            ARRAY_TO_STREAM(p, p_dev_name, p_value->len);
142            DVLOG(1) << "GATT_UUID_GAP_DEVICE_NAME len=" << +p_value->len;
143          }
144          break;
145
146        case GATT_UUID_GAP_ICON:
147          UINT16_TO_STREAM(p, attr_value.icon);
148          p_value->len = 2;
149          break;
150
151        case GATT_UUID_GAP_PREF_CONN_PARAM:
152          UINT16_TO_STREAM(p, attr_value.conn_param.int_min); /* int_min */
153          UINT16_TO_STREAM(p, attr_value.conn_param.int_max); /* int_max */
154          UINT16_TO_STREAM(p, attr_value.conn_param.latency); /* latency */
155          UINT16_TO_STREAM(p, attr_value.conn_param.sp_tout); /* sp_tout */
156          p_value->len = 8;
157          break;
158
159        /* address resolution */
160        case GATT_UUID_GAP_CENTRAL_ADDR_RESOL:
161          UINT8_TO_STREAM(p, attr_value.addr_resolution);
162          p_value->len = 1;
163          break;
164      }
165      return GATT_SUCCESS;
166    }
167  }
168  return GATT_NOT_FOUND;
169}
170
171/** GAP Attributes Database Read/Read Blob Request process */
172tGATT_STATUS proc_read(tGATTS_REQ_TYPE, tGATT_READ_REQ* p_data,
173                       tGATTS_RSP* p_rsp) {
174  if (p_data->is_long) p_rsp->attr_value.offset = p_data->offset;
175
176  p_rsp->attr_value.handle = p_data->handle;
177
178  return read_attr_value(p_data->handle, &p_rsp->attr_value, p_data->is_long);
179}
180
181/** GAP ATT server process a write request */
182uint8_t proc_write_req(tGATTS_REQ_TYPE, tGATT_WRITE_REQ* p_data) {
183  for (const auto& db_addr : gatt_attr)
184    if (p_data->handle == db_addr.handle) return GATT_WRITE_NOT_PERMIT;
185
186  return GATT_NOT_FOUND;
187}
188
189/** GAP ATT server attribute access request callback */
190void server_attr_request_cback(uint16_t conn_id, uint32_t trans_id,
191                               tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) {
192  uint8_t status = GATT_INVALID_PDU;
193  bool ignore = false;
194
195  DVLOG(1) << StringPrintf("%s: recv type (0x%02x)", __func__, type);
196
197  tGATTS_RSP rsp_msg;
198  memset(&rsp_msg, 0, sizeof(tGATTS_RSP));
199
200  switch (type) {
201    case GATTS_REQ_TYPE_READ_CHARACTERISTIC:
202    case GATTS_REQ_TYPE_READ_DESCRIPTOR:
203      status = proc_read(type, &p_data->read_req, &rsp_msg);
204      break;
205
206    case GATTS_REQ_TYPE_WRITE_CHARACTERISTIC:
207    case GATTS_REQ_TYPE_WRITE_DESCRIPTOR:
208      if (!p_data->write_req.need_rsp) ignore = true;
209
210      status = proc_write_req(type, &p_data->write_req);
211      break;
212
213    case GATTS_REQ_TYPE_WRITE_EXEC:
214      ignore = true;
215      DVLOG(1) << "Ignore GATTS_REQ_TYPE_WRITE_EXEC";
216      break;
217
218    case GATTS_REQ_TYPE_MTU:
219      DVLOG(1) << "Get MTU exchange new mtu size: " << +p_data->mtu;
220      ignore = true;
221      break;
222
223    default:
224      DVLOG(1) << StringPrintf("Unknown/unexpected LE GAP ATT request: 0x%02x",
225                               type);
226      break;
227  }
228
229  if (!ignore) GATTS_SendRsp(conn_id, trans_id, status, &rsp_msg);
230}
231
232/**
233 * utility function to send a read request for a GAP charactersitic.
234 * Returns true if read started, else false if GAP is busy.
235 */
236bool send_cl_read_request(tGAP_CLCB& clcb) {
237  if (!clcb.requests.size()) {
238    return false;
239  }
240
241  tGAP_REQUEST& req = clcb.requests.front();
242  clcb.p_cback = req.p_cback;
243  uint16_t uuid = req.uuid;
244  clcb.requests.pop();
245
246  tGATT_READ_PARAM param;
247  memset(&param, 0, sizeof(tGATT_READ_PARAM));
248
249  param.service.uuid.len = LEN_UUID_16;
250  param.service.uuid.uu.uuid16 = uuid;
251  param.service.s_handle = 1;
252  param.service.e_handle = 0xFFFF;
253  param.service.auth_req = 0;
254
255  if (GATTC_Read(clcb.conn_id, GATT_READ_BY_TYPE, &param) == GATT_SUCCESS) {
256    clcb.cl_op_uuid = uuid;
257  }
258
259  return true;
260}
261
262/** GAP client operation complete callback */
263void cl_op_cmpl(tGAP_CLCB& clcb, bool status, uint16_t len, uint8_t* p_name) {
264  tGAP_BLE_CMPL_CBACK* p_cback = clcb.p_cback;
265  uint16_t op = clcb.cl_op_uuid;
266
267  DVLOG(1) << StringPrintf("%s: status: %d", __func__, status);
268
269  clcb.cl_op_uuid = 0;
270  clcb.p_cback = NULL;
271
272  if (p_cback && op) {
273    DVLOG(1) << __func__ << ": calling";
274    (*p_cback)(status, clcb.bda, len, (char*)p_name);
275  }
276
277  /* if no further activity is requested in callback, drop the link */
278  if (clcb.connected) {
279    if (!send_cl_read_request(clcb)) {
280      GATT_Disconnect(clcb.conn_id);
281      clcb_dealloc(clcb);
282    }
283  }
284}
285
286/** Client connection callback */
287void client_connect_cback(tGATT_IF, const RawAddress& bda, uint16_t conn_id,
288                          bool connected, tGATT_DISCONN_REASON reason,
289                          tGATT_TRANSPORT) {
290  tGAP_CLCB* p_clcb = find_clcb_by_bd_addr(bda);
291  if (p_clcb == NULL) return;
292
293  if (connected) {
294    p_clcb->conn_id = conn_id;
295    p_clcb->connected = true;
296    /* start operation is pending */
297    send_cl_read_request(*p_clcb);
298  } else {
299    p_clcb->connected = false;
300    cl_op_cmpl(*p_clcb, false, 0, NULL);
301    /* clean up clcb */
302    clcb_dealloc(*p_clcb);
303  }
304}
305
306/** Client operation complete callback */
307void client_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status,
308                       tGATT_CL_COMPLETE* p_data) {
309  tGAP_CLCB* p_clcb = ble_find_clcb_by_conn_id(conn_id);
310  uint16_t op_type;
311  uint16_t min, max, latency, tout;
312  uint16_t len;
313  uint8_t* pp;
314
315  if (p_clcb == NULL) return;
316
317  op_type = p_clcb->cl_op_uuid;
318
319  DVLOG(1) << StringPrintf(
320      "%s: - op_code: 0x%02x  status: 0x%02x  read_type: 0x%04x", __func__, op,
321      status, op_type);
322  /* Currently we only issue read commands */
323  if (op != GATTC_OPTYPE_READ) return;
324
325  if (status != GATT_SUCCESS) {
326    cl_op_cmpl(*p_clcb, false, 0, NULL);
327    return;
328  }
329
330  pp = p_data->att_value.value;
331  switch (op_type) {
332    case GATT_UUID_GAP_PREF_CONN_PARAM:
333      /* Extract the peripheral preferred connection parameters and save them */
334      STREAM_TO_UINT16(min, pp);
335      STREAM_TO_UINT16(max, pp);
336      STREAM_TO_UINT16(latency, pp);
337      STREAM_TO_UINT16(tout, pp);
338
339      BTM_BleSetPrefConnParams(p_clcb->bda, min, max, latency, tout);
340      /* release the connection here */
341      cl_op_cmpl(*p_clcb, true, 0, NULL);
342      break;
343
344    case GATT_UUID_GAP_DEVICE_NAME:
345      len = (uint16_t)strlen((char*)pp);
346      if (len > GAP_CHAR_DEV_NAME_SIZE) len = GAP_CHAR_DEV_NAME_SIZE;
347      cl_op_cmpl(*p_clcb, true, len, pp);
348      break;
349
350    case GATT_UUID_GAP_CENTRAL_ADDR_RESOL:
351      cl_op_cmpl(*p_clcb, true, 1, pp);
352      break;
353  }
354}
355
356bool accept_client_operation(const RawAddress& peer_bda, uint16_t uuid,
357                             tGAP_BLE_CMPL_CBACK* p_cback) {
358  if (p_cback == NULL && uuid != GATT_UUID_GAP_PREF_CONN_PARAM) return false;
359
360  tGAP_CLCB* p_clcb = find_clcb_by_bd_addr(peer_bda);
361  if (p_clcb == NULL) {
362    p_clcb = clcb_alloc(peer_bda);
363  }
364
365  DVLOG(1) << __func__ << ": BDA: " << peer_bda
366           << StringPrintf(" cl_op_uuid: 0x%04x", uuid);
367
368  if (GATT_GetConnIdIfConnected(gatt_if, peer_bda, &p_clcb->conn_id,
369                                BT_TRANSPORT_LE))
370    p_clcb->connected = true;
371
372  if (!GATT_Connect(gatt_if, p_clcb->bda, true, BT_TRANSPORT_LE, true))
373    return false;
374
375  /* enqueue the request */
376  p_clcb->requests.push({.uuid = uuid, .p_cback = p_cback});
377
378  if (p_clcb->connected && p_clcb->cl_op_uuid == 0)
379    return send_cl_read_request(*p_clcb);
380  else /* wait for connection up or pending operation to finish */
381    return true;
382}
383
384}  // namespace
385
386/*******************************************************************************
387 *
388 * Function         btm_ble_att_db_init
389 *
390 * Description      GAP ATT database initalization.
391 *
392 * Returns          void.
393 *
394 ******************************************************************************/
395void gap_attr_db_init(void) {
396  tBT_UUID app_uuid = {LEN_UUID_128, {0}};
397  uint16_t service_handle;
398
399  /* Fill our internal UUID with a fixed pattern 0x82 */
400  memset(&app_uuid.uu.uuid128, 0x82, LEN_UUID_128);
401  gatt_attr.fill({});
402
403  gatt_if = GATT_Register(&app_uuid, &gap_cback);
404
405  GATT_StartIf(gatt_if);
406
407  bt_uuid_t svc_uuid, name_uuid, icon_uuid, pref_uuid, addr_res_uuid;
408  uuid_128_from_16(&svc_uuid, UUID_SERVCLASS_GAP_SERVER);
409  uuid_128_from_16(&name_uuid, GATT_UUID_GAP_DEVICE_NAME);
410  uuid_128_from_16(&icon_uuid, GATT_UUID_GAP_ICON);
411  uuid_128_from_16(&pref_uuid, GATT_UUID_GAP_PREF_CONN_PARAM);
412  uuid_128_from_16(&addr_res_uuid, GATT_UUID_GAP_CENTRAL_ADDR_RESOL);
413
414  btgatt_db_element_t service[] = {
415    {.type = BTGATT_DB_PRIMARY_SERVICE, .uuid = svc_uuid},
416    {.type = BTGATT_DB_CHARACTERISTIC,
417     .uuid = name_uuid,
418     .properties = GATT_CHAR_PROP_BIT_READ,
419     .permissions = GATT_PERM_READ},
420    {.type = BTGATT_DB_CHARACTERISTIC,
421     .uuid = icon_uuid,
422     .properties = GATT_CHAR_PROP_BIT_READ,
423     .permissions = GATT_PERM_READ},
424    {.type = BTGATT_DB_CHARACTERISTIC,
425     .uuid = addr_res_uuid,
426     .properties = GATT_CHAR_PROP_BIT_READ,
427     .permissions = GATT_PERM_READ}
428#if (BTM_PERIPHERAL_ENABLED == TRUE) /* Only needed for peripheral testing */
429    ,
430    {.type = BTGATT_DB_CHARACTERISTIC,
431     .uuid = pref_uuid,
432     .properties = GATT_CHAR_PROP_BIT_READ,
433     .permissions = GATT_PERM_READ}
434#endif
435  };
436
437  /* Add a GAP service */
438  GATTS_AddService(gatt_if, service,
439                   sizeof(service) / sizeof(btgatt_db_element_t));
440  service_handle = service[0].attribute_handle;
441
442  DVLOG(1) << __func__ << ": service_handle = " << +service_handle;
443
444  gatt_attr[0].uuid = GATT_UUID_GAP_DEVICE_NAME;
445  gatt_attr[0].handle = service[1].attribute_handle;
446
447  gatt_attr[1].uuid = GATT_UUID_GAP_ICON;
448  gatt_attr[1].handle = service[2].attribute_handle;
449
450  gatt_attr[2].uuid = GATT_UUID_GAP_CENTRAL_ADDR_RESOL;
451  gatt_attr[2].handle = service[3].attribute_handle;
452  gatt_attr[2].attr_value.addr_resolution = 0;
453
454#if (BTM_PERIPHERAL_ENABLED == TRUE) /*  Only needed for peripheral testing */
455
456  gatt_attr[3].uuid = GATT_UUID_GAP_PREF_CONN_PARAM;
457  gatt_attr[3].attr_value.conn_param.int_max = GAP_PREFER_CONN_INT_MAX; /* 6 */
458  gatt_attr[3].attr_value.conn_param.int_min = GAP_PREFER_CONN_INT_MIN; /* 0 */
459  gatt_attr[3].attr_value.conn_param.latency = GAP_PREFER_CONN_LATENCY; /* 0 */
460  gatt_attr[3].attr_value.conn_param.sp_tout =
461      GAP_PREFER_CONN_SP_TOUT; /* 2000 */
462  gatt_attr[3].handle = service[4].attribute_handle;
463#endif
464}
465
466/*******************************************************************************
467 *
468 * Function         GAP_BleAttrDBUpdate
469 *
470 * Description      GAP ATT database update.
471 *
472 ******************************************************************************/
473void GAP_BleAttrDBUpdate(uint16_t attr_uuid, tGAP_BLE_ATTR_VALUE* p_value) {
474  DVLOG(1) << StringPrintf("%s: attr_uuid=0x%04x", __func__, attr_uuid);
475
476  for (tGAP_ATTR& db_attr : gatt_attr) {
477    if (db_attr.uuid == attr_uuid) {
478      DVLOG(1) << StringPrintf("Found attr_uuid=0x%04x", attr_uuid);
479
480      switch (attr_uuid) {
481        case GATT_UUID_GAP_ICON:
482          db_attr.attr_value.icon = p_value->icon;
483          break;
484
485        case GATT_UUID_GAP_PREF_CONN_PARAM:
486          memcpy((void*)&db_attr.attr_value.conn_param,
487                 (const void*)&p_value->conn_param,
488                 sizeof(tGAP_BLE_PREF_PARAM));
489          break;
490
491        case GATT_UUID_GAP_DEVICE_NAME:
492          BTM_SetLocalDeviceName((char*)p_value->p_dev_name);
493          break;
494
495        case GATT_UUID_GAP_CENTRAL_ADDR_RESOL:
496          db_attr.attr_value.addr_resolution = p_value->addr_resolution;
497          break;
498      }
499      break;
500    }
501  }
502
503  return;
504}
505
506/*******************************************************************************
507 *
508 * Function         GAP_BleReadPeerPrefConnParams
509 *
510 * Description      Start a process to read a connected peripheral's preferred
511 *                  connection parameters
512 *
513 * Returns          true if read started, else false if GAP is busy
514 *
515 ******************************************************************************/
516bool GAP_BleReadPeerPrefConnParams(const RawAddress& peer_bda) {
517  return accept_client_operation(peer_bda, GATT_UUID_GAP_PREF_CONN_PARAM, NULL);
518}
519
520/*******************************************************************************
521 *
522 * Function         GAP_BleReadPeerDevName
523 *
524 * Description      Start a process to read a connected peripheral's device
525 *                  name.
526 *
527 * Returns          true if request accepted
528 *
529 ******************************************************************************/
530bool GAP_BleReadPeerDevName(const RawAddress& peer_bda,
531                            tGAP_BLE_CMPL_CBACK* p_cback) {
532  return accept_client_operation(peer_bda, GATT_UUID_GAP_DEVICE_NAME, p_cback);
533}
534
535/*******************************************************************************
536 *
537 * Function         GAP_BleReadPeerAddressResolutionCap
538 *
539 * Description      Start a process to read peer address resolution capability
540 *
541 * Returns          true if request accepted
542 *
543 ******************************************************************************/
544bool GAP_BleReadPeerAddressResolutionCap(const RawAddress& peer_bda,
545                                         tGAP_BLE_CMPL_CBACK* p_cback) {
546  return accept_client_operation(peer_bda, GATT_UUID_GAP_CENTRAL_ADDR_RESOL,
547                                 p_cback);
548}
549
550/*******************************************************************************
551 *
552 * Function         GAP_BleCancelReadPeerDevName
553 *
554 * Description      Cancel reading a peripheral's device name.
555 *
556 * Returns          true if request accepted
557 *
558 ******************************************************************************/
559bool GAP_BleCancelReadPeerDevName(const RawAddress& peer_bda) {
560  tGAP_CLCB* p_clcb = find_clcb_by_bd_addr(peer_bda);
561
562  DVLOG(1) << __func__ << ": BDA: " << peer_bda
563           << StringPrintf(" cl_op_uuid: 0x%04x",
564                           (p_clcb == NULL) ? 0 : p_clcb->cl_op_uuid);
565
566  if (p_clcb == NULL) {
567    LOG(ERROR) << "Cannot cancel current op is not get dev name";
568    return false;
569  }
570
571  if (!p_clcb->connected) {
572    if (!GATT_CancelConnect(gatt_if, peer_bda, true)) {
573      LOG(ERROR) << "Cannot cancel where No connection id";
574      return false;
575    }
576  }
577
578  cl_op_cmpl(*p_clcb, false, 0, NULL);
579
580  return (true);
581}
582