1 /******************************************************************************
2  *
3  *  Copyright 2009-2013 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  *  Filename:      btif_gatt_server.c
22  *
23  *  Description:   GATT server implementation
24  *
25  ******************************************************************************/
26 
27 #define LOG_TAG "bt_btif_gatt"
28 
29 #include <base/functional/bind.h>
30 #include <bluetooth/log.h>
31 #include <com_android_bluetooth_flags.h>
32 #include <hardware/bluetooth.h>
33 #include <hardware/bt_gatt.h>
34 #include <hardware/bt_gatt_types.h>
35 #include <stdlib.h>
36 #include <string.h>
37 
38 #include "bta/include/bta_sec_api.h"
39 #include "bta_gatt_api.h"
40 #include "btif_common.h"
41 #include "btif_gatt.h"
42 #include "btif_gatt_util.h"
43 #include "osi/include/allocator.h"
44 #include "stack/include/bt_uuid16.h"
45 #include "stack/include/main_thread.h"
46 #include "types/ble_address_with_type.h"
47 #include "types/bluetooth/uuid.h"
48 #include "types/bt_transport.h"
49 #include "types/raw_address.h"
50 
51 bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type);
52 bool btif_get_device_type(const RawAddress& bda, int* p_device_type);
53 
54 using base::Bind;
55 using bluetooth::Uuid;
56 using std::vector;
57 using namespace bluetooth;
58 
59 /*******************************************************************************
60  *  Constants & Macros
61  ******************************************************************************/
62 
63 #define CHECK_BTGATT_INIT()                \
64   do {                                     \
65     if (bt_gatt_callbacks == NULL) {       \
66       log::warn("BTGATT not initialized"); \
67       return BT_STATUS_NOT_READY;          \
68     } else {                               \
69       log::verbose("");                    \
70     }                                      \
71   } while (0)
72 
73 /*******************************************************************************
74  *  Static variables
75  ******************************************************************************/
76 
77 extern const btgatt_callbacks_t* bt_gatt_callbacks;
78 
79 /*******************************************************************************
80  *  Static functions
81  ******************************************************************************/
82 
btapp_gatts_copy_req_data(uint16_t event,char * p_dest,const char * p_src)83 static void btapp_gatts_copy_req_data(uint16_t event, char* p_dest,
84                                       const char* p_src) {
85   tBTA_GATTS* p_dest_data = (tBTA_GATTS*)p_dest;
86   const tBTA_GATTS* p_src_data = (const tBTA_GATTS*)p_src;
87 
88   if (!p_src_data || !p_dest_data) return;
89 
90   // Copy basic structure first
91   maybe_non_aligned_memcpy(p_dest_data, p_src_data, sizeof(*p_src_data));
92 
93   // Allocate buffer for request data if necessary
94   switch (event) {
95     case BTA_GATTS_READ_CHARACTERISTIC_EVT:
96     case BTA_GATTS_READ_DESCRIPTOR_EVT:
97     case BTA_GATTS_WRITE_CHARACTERISTIC_EVT:
98     case BTA_GATTS_WRITE_DESCRIPTOR_EVT:
99     case BTA_GATTS_EXEC_WRITE_EVT:
100     case BTA_GATTS_MTU_EVT:
101       p_dest_data->req_data.p_data =
102           (tGATTS_DATA*)osi_malloc(sizeof(tGATTS_DATA));
103       memcpy(p_dest_data->req_data.p_data, p_src_data->req_data.p_data,
104              sizeof(tGATTS_DATA));
105       break;
106 
107     default:
108       break;
109   }
110 }
111 
btapp_gatts_free_req_data(uint16_t event,tBTA_GATTS * p_data)112 static void btapp_gatts_free_req_data(uint16_t event, tBTA_GATTS* p_data) {
113   switch (event) {
114     case BTA_GATTS_READ_CHARACTERISTIC_EVT:
115     case BTA_GATTS_READ_DESCRIPTOR_EVT:
116     case BTA_GATTS_WRITE_CHARACTERISTIC_EVT:
117     case BTA_GATTS_WRITE_DESCRIPTOR_EVT:
118     case BTA_GATTS_EXEC_WRITE_EVT:
119     case BTA_GATTS_MTU_EVT:
120       if (p_data != NULL) osi_free_and_reset((void**)&p_data->req_data.p_data);
121       break;
122 
123     default:
124       break;
125   }
126 }
127 
btapp_gatts_handle_cback(uint16_t event,char * p_param)128 static void btapp_gatts_handle_cback(uint16_t event, char* p_param) {
129   log::verbose("Event {}", event);
130 
131   tBTA_GATTS* p_data = (tBTA_GATTS*)p_param;
132   switch (event) {
133     case BTA_GATTS_REG_EVT: {
134       HAL_CBACK(bt_gatt_callbacks, server->register_server_cb,
135                 p_data->reg_oper.status, p_data->reg_oper.server_if,
136                 p_data->reg_oper.uuid);
137       break;
138     }
139 
140     case BTA_GATTS_DEREG_EVT:
141       break;
142 
143     case BTA_GATTS_CONNECT_EVT: {
144       btif_gatt_check_encrypted_link(p_data->conn.remote_bda,
145                                      p_data->conn.transport);
146 
147       HAL_CBACK(bt_gatt_callbacks, server->connection_cb, p_data->conn.conn_id,
148                 p_data->conn.server_if, true, p_data->conn.remote_bda);
149       break;
150     }
151 
152     case BTA_GATTS_DISCONNECT_EVT: {
153       HAL_CBACK(bt_gatt_callbacks, server->connection_cb, p_data->conn.conn_id,
154                 p_data->conn.server_if, false, p_data->conn.remote_bda);
155       break;
156     }
157 
158     case BTA_GATTS_STOP_EVT:
159       HAL_CBACK(bt_gatt_callbacks, server->service_stopped_cb,
160                 p_data->srvc_oper.status, p_data->srvc_oper.server_if,
161                 p_data->srvc_oper.service_id);
162       break;
163 
164     case BTA_GATTS_DELELTE_EVT:
165       HAL_CBACK(bt_gatt_callbacks, server->service_deleted_cb,
166                 p_data->srvc_oper.status, p_data->srvc_oper.server_if,
167                 p_data->srvc_oper.service_id);
168       break;
169 
170     case BTA_GATTS_READ_CHARACTERISTIC_EVT: {
171       HAL_CBACK(bt_gatt_callbacks, server->request_read_characteristic_cb,
172                 p_data->req_data.conn_id, p_data->req_data.trans_id,
173                 p_data->req_data.remote_bda,
174                 p_data->req_data.p_data->read_req.handle,
175                 p_data->req_data.p_data->read_req.offset,
176                 p_data->req_data.p_data->read_req.is_long);
177       break;
178     }
179 
180     case BTA_GATTS_READ_DESCRIPTOR_EVT: {
181       HAL_CBACK(bt_gatt_callbacks, server->request_read_descriptor_cb,
182                 p_data->req_data.conn_id, p_data->req_data.trans_id,
183                 p_data->req_data.remote_bda,
184                 p_data->req_data.p_data->read_req.handle,
185                 p_data->req_data.p_data->read_req.offset,
186                 p_data->req_data.p_data->read_req.is_long);
187       break;
188     }
189 
190     case BTA_GATTS_WRITE_CHARACTERISTIC_EVT: {
191       const auto& req = p_data->req_data.p_data->write_req;
192       HAL_CBACK(bt_gatt_callbacks, server->request_write_characteristic_cb,
193                 p_data->req_data.conn_id, p_data->req_data.trans_id,
194                 p_data->req_data.remote_bda, req.handle, req.offset,
195                 req.need_rsp, req.is_prep, req.value, req.len);
196       break;
197     }
198 
199     case BTA_GATTS_WRITE_DESCRIPTOR_EVT: {
200       const auto& req = p_data->req_data.p_data->write_req;
201       HAL_CBACK(bt_gatt_callbacks, server->request_write_descriptor_cb,
202                 p_data->req_data.conn_id, p_data->req_data.trans_id,
203                 p_data->req_data.remote_bda, req.handle, req.offset,
204                 req.need_rsp, req.is_prep, req.value, req.len);
205       break;
206     }
207 
208     case BTA_GATTS_EXEC_WRITE_EVT: {
209       HAL_CBACK(bt_gatt_callbacks, server->request_exec_write_cb,
210                 p_data->req_data.conn_id, p_data->req_data.trans_id,
211                 p_data->req_data.remote_bda,
212                 p_data->req_data.p_data->exec_write);
213       break;
214     }
215 
216     case BTA_GATTS_CONF_EVT:
217       HAL_CBACK(bt_gatt_callbacks, server->indication_sent_cb,
218                 p_data->req_data.conn_id, p_data->req_data.status);
219       break;
220 
221     case BTA_GATTS_CONGEST_EVT:
222       HAL_CBACK(bt_gatt_callbacks, server->congestion_cb,
223                 p_data->congest.conn_id, p_data->congest.congested);
224       break;
225 
226     case BTA_GATTS_MTU_EVT:
227       HAL_CBACK(bt_gatt_callbacks, server->mtu_changed_cb,
228                 p_data->req_data.conn_id, p_data->req_data.p_data->mtu);
229       break;
230 
231     case BTA_GATTS_OPEN_EVT:
232     case BTA_GATTS_CANCEL_OPEN_EVT:
233     case BTA_GATTS_CLOSE_EVT:
234       log::info("Empty event ({})!", event);
235       break;
236 
237     case BTA_GATTS_PHY_UPDATE_EVT:
238       HAL_CBACK(bt_gatt_callbacks, server->phy_updated_cb,
239                 p_data->phy_update.conn_id, p_data->phy_update.tx_phy,
240                 p_data->phy_update.rx_phy, p_data->phy_update.status);
241       break;
242 
243     case BTA_GATTS_CONN_UPDATE_EVT:
244       HAL_CBACK(bt_gatt_callbacks, server->conn_updated_cb,
245                 p_data->conn_update.conn_id, p_data->conn_update.interval,
246                 p_data->conn_update.latency, p_data->conn_update.timeout,
247                 p_data->conn_update.status);
248       break;
249 
250     case BTA_GATTS_SUBRATE_CHG_EVT:
251       HAL_CBACK(bt_gatt_callbacks, server->subrate_chg_cb,
252                 p_data->subrate_chg.conn_id, p_data->subrate_chg.subrate_factor,
253                 p_data->subrate_chg.latency, p_data->subrate_chg.cont_num,
254                 p_data->subrate_chg.timeout, p_data->subrate_chg.status);
255       break;
256 
257     default:
258       log::error("Unhandled event ({})!", event);
259       break;
260   }
261 
262   btapp_gatts_free_req_data(event, p_data);
263 }
264 
btapp_gatts_cback(tBTA_GATTS_EVT event,tBTA_GATTS * p_data)265 static void btapp_gatts_cback(tBTA_GATTS_EVT event, tBTA_GATTS* p_data) {
266   bt_status_t status;
267   status = btif_transfer_context(btapp_gatts_handle_cback, (uint16_t)event,
268                                  (char*)p_data, sizeof(tBTA_GATTS),
269                                  btapp_gatts_copy_req_data);
270   ASSERTC(status == BT_STATUS_SUCCESS, "Context transfer failed!", status);
271 }
272 
273 /*******************************************************************************
274  *  Server API Functions
275  ******************************************************************************/
btif_gatts_register_app(const Uuid & bt_uuid,bool eatt_support)276 static bt_status_t btif_gatts_register_app(const Uuid& bt_uuid,
277                                            bool eatt_support) {
278   CHECK_BTGATT_INIT();
279 
280   return do_in_jni_thread(
281       Bind(&BTA_GATTS_AppRegister, bt_uuid, &btapp_gatts_cback, eatt_support));
282 }
283 
btif_gatts_unregister_app(int server_if)284 static bt_status_t btif_gatts_unregister_app(int server_if) {
285   CHECK_BTGATT_INIT();
286   return do_in_jni_thread(Bind(&BTA_GATTS_AppDeregister, server_if));
287 }
288 
btif_gatts_open_impl(int server_if,const RawAddress & address,bool is_direct,int transport_param)289 static void btif_gatts_open_impl(int server_if, const RawAddress& address,
290                                  bool is_direct, int transport_param) {
291   // Ensure device is in inquiry database
292   tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC;
293   int device_type = 0;
294   tBT_TRANSPORT transport = BT_TRANSPORT_LE;
295 
296   if (btif_get_address_type(address, &addr_type) &&
297       btif_get_device_type(address, &device_type) &&
298       device_type != BT_DEVICE_TYPE_BREDR) {
299     BTA_DmAddBleDevice(address, addr_type, device_type);
300   }
301 
302   // Determine transport
303   if (transport_param != BT_TRANSPORT_AUTO) {
304     transport = transport_param;
305   } else {
306     switch (device_type) {
307       case BT_DEVICE_TYPE_BREDR:
308         transport = BT_TRANSPORT_BR_EDR;
309         break;
310 
311       case BT_DEVICE_TYPE_BLE:
312         transport = BT_TRANSPORT_LE;
313         break;
314 
315       case BT_DEVICE_TYPE_DUMO:
316         transport = BT_TRANSPORT_BR_EDR;
317         break;
318     }
319   }
320 
321   // Connect!
322   BTA_GATTS_Open(server_if, address, BLE_ADDR_PUBLIC, is_direct, transport);
323 }
324 
325 // Used instead of btif_gatts_open_impl if the flag
326 // ble_gatt_server_use_address_type_in_connection is enabled.
btif_gatts_open_impl_use_address_type(int server_if,const RawAddress & address,tBLE_ADDR_TYPE addr_type,bool is_direct,int transport_param)327 static void btif_gatts_open_impl_use_address_type(int server_if,
328                                                   const RawAddress& address,
329                                                   tBLE_ADDR_TYPE addr_type,
330                                                   bool is_direct,
331                                                   int transport_param) {
332   int device_type = BT_DEVICE_TYPE_UNKNOWN;
333   if (btif_get_address_type(address, &addr_type) &&
334       btif_get_device_type(address, &device_type) &&
335       device_type != BT_DEVICE_TYPE_BREDR) {
336     BTA_DmAddBleDevice(address, addr_type, device_type);
337   }
338 
339   if (transport_param != BT_TRANSPORT_AUTO) {
340     log::info("addr_type:{}, transport_param:{}", addr_type, transport_param);
341     BTA_GATTS_Open(server_if, address, addr_type, is_direct, transport_param);
342     return;
343   }
344 
345   tBT_TRANSPORT transport = (device_type == BT_DEVICE_TYPE_BREDR)
346                                 ? BT_TRANSPORT_BR_EDR
347                                 : BT_TRANSPORT_LE;
348   log::info("addr_type:{}, transport:{}", addr_type, transport);
349   BTA_GATTS_Open(server_if, address, addr_type, is_direct, transport);
350 }
351 
btif_gatts_open(int server_if,const RawAddress & bd_addr,uint8_t addr_type,bool is_direct,int transport)352 static bt_status_t btif_gatts_open(int server_if, const RawAddress& bd_addr,
353                                    uint8_t addr_type, bool is_direct,
354                                    int transport) {
355   CHECK_BTGATT_INIT();
356 
357   if (com::android::bluetooth::flags::
358           ble_gatt_server_use_address_type_in_connection()) {
359     return do_in_jni_thread(Bind(&btif_gatts_open_impl_use_address_type,
360                                  server_if, bd_addr, addr_type, is_direct,
361                                  transport));
362   } else {
363     return do_in_jni_thread(
364         Bind(&btif_gatts_open_impl, server_if, bd_addr, is_direct, transport));
365   }
366 }
367 
btif_gatts_close_impl(int server_if,const RawAddress & address,int conn_id)368 static void btif_gatts_close_impl(int server_if, const RawAddress& address,
369                                   int conn_id) {
370   // Close active connection
371   if (conn_id != 0)
372     BTA_GATTS_Close(conn_id);
373   else
374     BTA_GATTS_CancelOpen(server_if, address, true);
375 
376   // Cancel pending background connections
377   BTA_GATTS_CancelOpen(server_if, address, false);
378 }
379 
btif_gatts_close(int server_if,const RawAddress & bd_addr,int conn_id)380 static bt_status_t btif_gatts_close(int server_if, const RawAddress& bd_addr,
381                                     int conn_id) {
382   CHECK_BTGATT_INIT();
383   return do_in_jni_thread(
384       Bind(&btif_gatts_close_impl, server_if, bd_addr, conn_id));
385 }
386 
on_service_added_cb(tGATT_STATUS status,int server_if,vector<btgatt_db_element_t> service)387 static void on_service_added_cb(tGATT_STATUS status, int server_if,
388                                 vector<btgatt_db_element_t> service) {
389   HAL_CBACK(bt_gatt_callbacks, server->service_added_cb, status, server_if,
390             service.data(), service.size());
391 }
392 
add_service_impl(int server_if,vector<btgatt_db_element_t> service)393 static void add_service_impl(int server_if,
394                              vector<btgatt_db_element_t> service) {
395   // TODO(jpawlowski): btif should be a pass through layer, and no checks should
396   // be made here. This exception is added only until GATT server code is
397   // refactored, and one can distinguish stack-internal aps from external apps
398   if (service[0].uuid == Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER) ||
399       service[0].uuid == Uuid::From16Bit(UUID_SERVCLASS_GAP_SERVER)) {
400     log::error("Attept to register restricted service");
401     HAL_CBACK(bt_gatt_callbacks, server->service_added_cb,
402               BT_STATUS_AUTH_REJECTED, server_if, service.data(),
403               service.size());
404     return;
405   }
406 
407   BTA_GATTS_AddService(server_if, service,
408                        jni_thread_wrapper(base::Bind(&on_service_added_cb)));
409 }
410 
btif_gatts_add_service(int server_if,const btgatt_db_element_t * service,size_t service_count)411 static bt_status_t btif_gatts_add_service(int server_if,
412                                           const btgatt_db_element_t* service,
413                                           size_t service_count) {
414   CHECK_BTGATT_INIT();
415   return do_in_jni_thread(Bind(&add_service_impl, server_if,
416                                std::vector(service, service + service_count)));
417 }
418 
btif_gatts_stop_service(int server_if,int service_handle)419 static bt_status_t btif_gatts_stop_service(int server_if, int service_handle) {
420   CHECK_BTGATT_INIT();
421   return do_in_jni_thread(Bind(&BTA_GATTS_StopService, service_handle));
422 }
423 
btif_gatts_delete_service(int server_if,int service_handle)424 static bt_status_t btif_gatts_delete_service(int server_if,
425                                              int service_handle) {
426   CHECK_BTGATT_INIT();
427   return do_in_jni_thread(Bind(&BTA_GATTS_DeleteService, service_handle));
428 }
429 
btif_gatts_send_indication(int server_if,int attribute_handle,int conn_id,int confirm,const uint8_t * value,size_t length)430 static bt_status_t btif_gatts_send_indication(int server_if,
431                                               int attribute_handle, int conn_id,
432                                               int confirm, const uint8_t* value,
433                                               size_t length) {
434   CHECK_BTGATT_INIT();
435 
436   if (length > GATT_MAX_ATTR_LEN) length = GATT_MAX_ATTR_LEN;
437 
438   return do_in_jni_thread(Bind(&BTA_GATTS_HandleValueIndication, conn_id,
439                                attribute_handle,
440                                std::vector(value, value + length), confirm));
441   // TODO: Might need to send an ACK if handle value indication is
442   //       invoked without need for confirmation.
443 }
444 
btif_gatts_send_response_impl(int conn_id,int trans_id,int status,btgatt_response_t response)445 static void btif_gatts_send_response_impl(int conn_id, int trans_id, int status,
446                                           btgatt_response_t response) {
447   tGATTS_RSP rsp_struct;
448   btif_to_bta_response(&rsp_struct, &response);
449 
450   BTA_GATTS_SendRsp(conn_id, trans_id, static_cast<tGATT_STATUS>(status),
451                     &rsp_struct);
452 
453   HAL_CBACK(bt_gatt_callbacks, server->response_confirmation_cb, 0,
454             rsp_struct.attr_value.handle);
455 }
456 
btif_gatts_send_response(int conn_id,int trans_id,int status,const btgatt_response_t & response)457 static bt_status_t btif_gatts_send_response(int conn_id, int trans_id,
458                                             int status,
459                                             const btgatt_response_t& response) {
460   CHECK_BTGATT_INIT();
461   return do_in_jni_thread(Bind(&btif_gatts_send_response_impl, conn_id,
462                                trans_id, status, response));
463 }
464 
btif_gatts_set_preferred_phy(const RawAddress & bd_addr,uint8_t tx_phy,uint8_t rx_phy,uint16_t phy_options)465 static bt_status_t btif_gatts_set_preferred_phy(const RawAddress& bd_addr,
466                                                 uint8_t tx_phy, uint8_t rx_phy,
467                                                 uint16_t phy_options) {
468   CHECK_BTGATT_INIT();
469   do_in_main_thread(FROM_HERE,
470                     Bind(&BTM_BleSetPhy, bd_addr, tx_phy, rx_phy, phy_options));
471   return BT_STATUS_SUCCESS;
472 }
473 
btif_gatts_read_phy(const RawAddress & bd_addr,base::Callback<void (uint8_t tx_phy,uint8_t rx_phy,uint8_t status)> cb)474 static bt_status_t btif_gatts_read_phy(
475     const RawAddress& bd_addr,
476     base::Callback<void(uint8_t tx_phy, uint8_t rx_phy, uint8_t status)> cb) {
477   CHECK_BTGATT_INIT();
478   do_in_main_thread(FROM_HERE,
479                     Bind(&BTM_BleReadPhy, bd_addr, jni_thread_wrapper(cb)));
480   return BT_STATUS_SUCCESS;
481 }
482 
483 const btgatt_server_interface_t btgattServerInterface = {
484     btif_gatts_register_app,   btif_gatts_unregister_app,
485     btif_gatts_open,           btif_gatts_close,
486     btif_gatts_add_service,    btif_gatts_stop_service,
487     btif_gatts_delete_service, btif_gatts_send_indication,
488     btif_gatts_send_response,  btif_gatts_set_preferred_phy,
489     btif_gatts_read_phy};
490