1/******************************************************************************
2 *
3 *  Copyright 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;
29using bluetooth::Uuid;
30
31namespace {
32
33typedef struct {
34  uint16_t uuid;
35  tGAP_BLE_CMPL_CBACK* p_cback;
36} tGAP_REQUEST;
37
38typedef struct {
39  RawAddress bda;
40  tGAP_BLE_CMPL_CBACK* p_cback;
41  uint16_t conn_id;
42  uint16_t cl_op_uuid;
43  bool connected;
44  std::queue<tGAP_REQUEST> requests;
45} tGAP_CLCB;
46
47typedef struct {
48  uint16_t handle;
49  uint16_t uuid;
50  tGAP_BLE_ATTR_VALUE attr_value;
51} tGAP_ATTR;
52
53void server_attr_request_cback(uint16_t, uint32_t, tGATTS_REQ_TYPE,
54                               tGATTS_DATA*);
55void client_connect_cback(tGATT_IF, const RawAddress&, uint16_t, bool,
56                          tGATT_DISCONN_REASON, tGATT_TRANSPORT);
57void client_cmpl_cback(uint16_t, tGATTC_OPTYPE, tGATT_STATUS,
58                       tGATT_CL_COMPLETE*);
59
60tGATT_CBACK gap_cback = {client_connect_cback,
61                         client_cmpl_cback,
62                         NULL,
63                         NULL,
64                         server_attr_request_cback,
65                         NULL,
66                         NULL,
67                         NULL,
68                         NULL};
69
70constexpr int GAP_CHAR_DEV_NAME_SIZE = BD_NAME_LEN;
71constexpr int GAP_MAX_CHAR_NUM = 4;
72
73std::vector<tGAP_CLCB> gap_clcbs;
74/* LE GAP attribute database */
75std::array<tGAP_ATTR, GAP_MAX_CHAR_NUM> gatt_attr;
76tGATT_IF gatt_if;
77
78/** returns LCB with macthing bd address, or nullptr */
79tGAP_CLCB* find_clcb_by_bd_addr(const RawAddress& bda) {
80  for (auto& cb : gap_clcbs)
81    if (cb.bda == bda) return &cb;
82
83  return nullptr;
84}
85
86/** returns LCB with macthing connection ID, or nullptr if not found  */
87tGAP_CLCB* ble_find_clcb_by_conn_id(uint16_t conn_id) {
88  for (auto& cb : gap_clcbs)
89    if (cb.connected && cb.conn_id == conn_id) return &cb;
90
91  return nullptr;
92}
93
94/** allocates a GAP connection link control block */
95tGAP_CLCB* clcb_alloc(const RawAddress& bda) {
96  gap_clcbs.emplace_back();
97  tGAP_CLCB& cb = gap_clcbs.back();
98  cb.bda = bda;
99  return &cb;
100}
101
102/** The function clean up the pending request queue in GAP */
103void clcb_dealloc(tGAP_CLCB& clcb) {
104  // put last element into place of current element, and remove last one - just
105  // fast remove.
106  for (auto it = gap_clcbs.begin(); it != gap_clcbs.end(); it++) {
107    if (it->conn_id == clcb.conn_id) {
108      auto last_one = std::prev(gap_clcbs.end());
109      *it = *last_one;
110      gap_clcbs.erase(last_one);
111      return;
112    }
113  }
114}
115
116/** GAP Attributes Database Request callback */
117tGATT_STATUS read_attr_value(uint16_t handle, tGATT_VALUE* p_value,
118                             bool is_long) {
119  uint8_t* p = p_value->value;
120  uint16_t offset = p_value->offset;
121  uint8_t* p_dev_name = NULL;
122
123  for (const tGAP_ATTR& db_attr : gatt_attr) {
124    const tGAP_BLE_ATTR_VALUE& attr_value = db_attr.attr_value;
125    if (handle == db_attr.handle) {
126      if (db_attr.uuid != GATT_UUID_GAP_DEVICE_NAME && is_long)
127        return GATT_NOT_LONG;
128
129      switch (db_attr.uuid) {
130        case GATT_UUID_GAP_DEVICE_NAME:
131          BTM_ReadLocalDeviceName((char**)&p_dev_name);
132          if (strlen((char*)p_dev_name) > GATT_MAX_ATTR_LEN)
133            p_value->len = GATT_MAX_ATTR_LEN;
134          else
135            p_value->len = (uint16_t)strlen((char*)p_dev_name);
136
137          if (offset > p_value->len)
138            return GATT_INVALID_OFFSET;
139          else {
140            p_value->len -= offset;
141            p_dev_name += offset;
142            ARRAY_TO_STREAM(p, p_dev_name, p_value->len);
143            DVLOG(1) << "GATT_UUID_GAP_DEVICE_NAME len=" << +p_value->len;
144          }
145          break;
146
147        case GATT_UUID_GAP_ICON:
148          UINT16_TO_STREAM(p, attr_value.icon);
149          p_value->len = 2;
150          break;
151
152        case GATT_UUID_GAP_PREF_CONN_PARAM:
153          UINT16_TO_STREAM(p, attr_value.conn_param.int_min); /* int_min */
154          UINT16_TO_STREAM(p, attr_value.conn_param.int_max); /* int_max */
155          UINT16_TO_STREAM(p, attr_value.conn_param.latency); /* latency */
156          UINT16_TO_STREAM(p, attr_value.conn_param.sp_tout); /* sp_tout */
157          p_value->len = 8;
158          break;
159
160        /* address resolution */
161        case GATT_UUID_GAP_CENTRAL_ADDR_RESOL:
162          UINT8_TO_STREAM(p, attr_value.addr_resolution);
163          p_value->len = 1;
164          break;
165      }
166      return GATT_SUCCESS;
167    }
168  }
169  return GATT_NOT_FOUND;
170}
171
172/** GAP Attributes Database Read/Read Blob Request process */
173tGATT_STATUS proc_read(tGATTS_REQ_TYPE, tGATT_READ_REQ* p_data,
174                       tGATTS_RSP* p_rsp) {
175  if (p_data->is_long) p_rsp->attr_value.offset = p_data->offset;
176
177  p_rsp->attr_value.handle = p_data->handle;
178
179  return read_attr_value(p_data->handle, &p_rsp->attr_value, p_data->is_long);
180}
181
182/** GAP ATT server process a write request */
183uint8_t proc_write_req(tGATTS_REQ_TYPE, tGATT_WRITE_REQ* p_data) {
184  for (const auto& db_addr : gatt_attr)
185    if (p_data->handle == db_addr.handle) return GATT_WRITE_NOT_PERMIT;
186
187  return GATT_NOT_FOUND;
188}
189
190/** GAP ATT server attribute access request callback */
191void server_attr_request_cback(uint16_t conn_id, uint32_t trans_id,
192                               tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) {
193  uint8_t status = GATT_INVALID_PDU;
194  bool ignore = false;
195
196  DVLOG(1) << StringPrintf("%s: recv type (0x%02x)", __func__, type);
197
198  tGATTS_RSP rsp_msg;
199  memset(&rsp_msg, 0, sizeof(tGATTS_RSP));
200
201  switch (type) {
202    case GATTS_REQ_TYPE_READ_CHARACTERISTIC:
203    case GATTS_REQ_TYPE_READ_DESCRIPTOR:
204      status = proc_read(type, &p_data->read_req, &rsp_msg);
205      break;
206
207    case GATTS_REQ_TYPE_WRITE_CHARACTERISTIC:
208    case GATTS_REQ_TYPE_WRITE_DESCRIPTOR:
209      if (!p_data->write_req.need_rsp) ignore = true;
210
211      status = proc_write_req(type, &p_data->write_req);
212      break;
213
214    case GATTS_REQ_TYPE_WRITE_EXEC:
215      ignore = true;
216      DVLOG(1) << "Ignore GATTS_REQ_TYPE_WRITE_EXEC";
217      break;
218
219    case GATTS_REQ_TYPE_MTU:
220      DVLOG(1) << "Get MTU exchange new mtu size: " << +p_data->mtu;
221      ignore = true;
222      break;
223
224    default:
225      DVLOG(1) << StringPrintf("Unknown/unexpected LE GAP ATT request: 0x%02x",
226                               type);
227      break;
228  }
229
230  if (!ignore) GATTS_SendRsp(conn_id, trans_id, status, &rsp_msg);
231}
232
233/**
234 * utility function to send a read request for a GAP charactersitic.
235 * Returns true if read started, else false if GAP is busy.
236 */
237bool send_cl_read_request(tGAP_CLCB& clcb) {
238  if (!clcb.requests.size()) {
239    return false;
240  }
241
242  tGAP_REQUEST& req = clcb.requests.front();
243  clcb.p_cback = req.p_cback;
244  uint16_t uuid = req.uuid;
245  clcb.requests.pop();
246
247  tGATT_READ_PARAM param;
248  memset(&param, 0, sizeof(tGATT_READ_PARAM));
249
250  param.service.uuid = Uuid::From16Bit(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  uint16_t service_handle;
397
398  /* Fill our internal UUID with a fixed pattern 0x82 */
399  std::array<uint8_t, Uuid::kNumBytes128> tmp;
400  tmp.fill(0x82);
401  Uuid app_uuid = Uuid::From128BitBE(tmp);
402  gatt_attr.fill({});
403
404  gatt_if = GATT_Register(app_uuid, &gap_cback);
405
406  GATT_StartIf(gatt_if);
407
408  Uuid svc_uuid = Uuid::From16Bit(UUID_SERVCLASS_GAP_SERVER);
409  Uuid name_uuid = Uuid::From16Bit(GATT_UUID_GAP_DEVICE_NAME);
410  Uuid icon_uuid = Uuid::From16Bit(GATT_UUID_GAP_ICON);
411  Uuid addr_res_uuid = Uuid::From16Bit(GATT_UUID_GAP_CENTRAL_ADDR_RESOL);
412
413  btgatt_db_element_t service[] = {
414    {.type = BTGATT_DB_PRIMARY_SERVICE, .uuid = svc_uuid},
415    {.type = BTGATT_DB_CHARACTERISTIC,
416     .uuid = name_uuid,
417     .properties = GATT_CHAR_PROP_BIT_READ,
418     .permissions = GATT_PERM_READ},
419    {.type = BTGATT_DB_CHARACTERISTIC,
420     .uuid = icon_uuid,
421     .properties = GATT_CHAR_PROP_BIT_READ,
422     .permissions = GATT_PERM_READ},
423    {.type = BTGATT_DB_CHARACTERISTIC,
424     .uuid = addr_res_uuid,
425     .properties = GATT_CHAR_PROP_BIT_READ,
426     .permissions = GATT_PERM_READ}
427#if (BTM_PERIPHERAL_ENABLED == TRUE) /* Only needed for peripheral testing */
428    ,
429    {.type = BTGATT_DB_CHARACTERISTIC,
430     .uuid = Uuid::From16Bit(GATT_UUID_GAP_PREF_CONN_PARAM),
431     .properties = GATT_CHAR_PROP_BIT_READ,
432     .permissions = GATT_PERM_READ}
433#endif
434  };
435
436  /* Add a GAP service */
437  GATTS_AddService(gatt_if, service,
438                   sizeof(service) / sizeof(btgatt_db_element_t));
439  service_handle = service[0].attribute_handle;
440
441  DVLOG(1) << __func__ << ": service_handle = " << +service_handle;
442
443  gatt_attr[0].uuid = GATT_UUID_GAP_DEVICE_NAME;
444  gatt_attr[0].handle = service[1].attribute_handle;
445
446  gatt_attr[1].uuid = GATT_UUID_GAP_ICON;
447  gatt_attr[1].handle = service[2].attribute_handle;
448
449  gatt_attr[2].uuid = GATT_UUID_GAP_CENTRAL_ADDR_RESOL;
450  gatt_attr[2].handle = service[3].attribute_handle;
451  gatt_attr[2].attr_value.addr_resolution = 0;
452
453#if (BTM_PERIPHERAL_ENABLED == TRUE) /*  Only needed for peripheral testing */
454
455  gatt_attr[3].uuid = GATT_UUID_GAP_PREF_CONN_PARAM;
456  gatt_attr[3].attr_value.conn_param.int_max = GAP_PREFER_CONN_INT_MAX; /* 6 */
457  gatt_attr[3].attr_value.conn_param.int_min = GAP_PREFER_CONN_INT_MIN; /* 0 */
458  gatt_attr[3].attr_value.conn_param.latency = GAP_PREFER_CONN_LATENCY; /* 0 */
459  gatt_attr[3].attr_value.conn_param.sp_tout =
460      GAP_PREFER_CONN_SP_TOUT; /* 2000 */
461  gatt_attr[3].handle = service[4].attribute_handle;
462#endif
463}
464
465/*******************************************************************************
466 *
467 * Function         GAP_BleAttrDBUpdate
468 *
469 * Description      GAP ATT database update.
470 *
471 ******************************************************************************/
472void GAP_BleAttrDBUpdate(uint16_t attr_uuid, tGAP_BLE_ATTR_VALUE* p_value) {
473  DVLOG(1) << StringPrintf("%s: attr_uuid=0x%04x", __func__, attr_uuid);
474
475  for (tGAP_ATTR& db_attr : gatt_attr) {
476    if (db_attr.uuid == attr_uuid) {
477      DVLOG(1) << StringPrintf("Found attr_uuid=0x%04x", attr_uuid);
478
479      switch (attr_uuid) {
480        case GATT_UUID_GAP_ICON:
481          db_attr.attr_value.icon = p_value->icon;
482          break;
483
484        case GATT_UUID_GAP_PREF_CONN_PARAM:
485          memcpy((void*)&db_attr.attr_value.conn_param,
486                 (const void*)&p_value->conn_param,
487                 sizeof(tGAP_BLE_PREF_PARAM));
488          break;
489
490        case GATT_UUID_GAP_DEVICE_NAME:
491          BTM_SetLocalDeviceName((char*)p_value->p_dev_name);
492          break;
493
494        case GATT_UUID_GAP_CENTRAL_ADDR_RESOL:
495          db_attr.attr_value.addr_resolution = p_value->addr_resolution;
496          break;
497      }
498      break;
499    }
500  }
501
502  return;
503}
504
505/*******************************************************************************
506 *
507 * Function         GAP_BleReadPeerPrefConnParams
508 *
509 * Description      Start a process to read a connected peripheral's preferred
510 *                  connection parameters
511 *
512 * Returns          true if read started, else false if GAP is busy
513 *
514 ******************************************************************************/
515bool GAP_BleReadPeerPrefConnParams(const RawAddress& peer_bda) {
516  return accept_client_operation(peer_bda, GATT_UUID_GAP_PREF_CONN_PARAM, NULL);
517}
518
519/*******************************************************************************
520 *
521 * Function         GAP_BleReadPeerDevName
522 *
523 * Description      Start a process to read a connected peripheral's device
524 *                  name.
525 *
526 * Returns          true if request accepted
527 *
528 ******************************************************************************/
529bool GAP_BleReadPeerDevName(const RawAddress& peer_bda,
530                            tGAP_BLE_CMPL_CBACK* p_cback) {
531  return accept_client_operation(peer_bda, GATT_UUID_GAP_DEVICE_NAME, p_cback);
532}
533
534/*******************************************************************************
535 *
536 * Function         GAP_BleReadPeerAddressResolutionCap
537 *
538 * Description      Start a process to read peer address resolution capability
539 *
540 * Returns          true if request accepted
541 *
542 ******************************************************************************/
543bool GAP_BleReadPeerAddressResolutionCap(const RawAddress& peer_bda,
544                                         tGAP_BLE_CMPL_CBACK* p_cback) {
545  return accept_client_operation(peer_bda, GATT_UUID_GAP_CENTRAL_ADDR_RESOL,
546                                 p_cback);
547}
548
549/*******************************************************************************
550 *
551 * Function         GAP_BleCancelReadPeerDevName
552 *
553 * Description      Cancel reading a peripheral's device name.
554 *
555 * Returns          true if request accepted
556 *
557 ******************************************************************************/
558bool GAP_BleCancelReadPeerDevName(const RawAddress& peer_bda) {
559  tGAP_CLCB* p_clcb = find_clcb_by_bd_addr(peer_bda);
560
561  DVLOG(1) << __func__ << ": BDA: " << peer_bda
562           << StringPrintf(" cl_op_uuid: 0x%04x",
563                           (p_clcb == NULL) ? 0 : p_clcb->cl_op_uuid);
564
565  if (p_clcb == NULL) {
566    LOG(ERROR) << "Cannot cancel current op is not get dev name";
567    return false;
568  }
569
570  if (!p_clcb->connected) {
571    if (!GATT_CancelConnect(gatt_if, peer_bda, true)) {
572      LOG(ERROR) << "Cannot cancel where No connection id";
573      return false;
574    }
575  }
576
577  cl_op_cmpl(*p_clcb, false, 0, NULL);
578
579  return (true);
580}
581