1 /******************************************************************************
2  *
3  *  Copyright 1999-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 functions that handle BTM interface functions for the
22  *  Bluetooth device including Rest, HCI buffer size and others
23  *
24  ******************************************************************************/
25 
26 #define LOG_TAG "devctl"
27 
28 #include <bluetooth/log.h>
29 #include <stddef.h>
30 #include <stdlib.h>
31 #include <string.h>
32 
33 #include "acl_api_types.h"
34 #include "btm_sec_cb.h"
35 #include "btm_sec_int_types.h"
36 #include "hci/controller_interface.h"
37 #include "main/shim/btm_api.h"
38 #include "main/shim/entry.h"
39 #include "stack/btm/btm_int_types.h"
40 #include "stack/btm/btm_sec.h"
41 #include "stack/connection_manager/connection_manager.h"
42 #include "stack/include/acl_api.h"
43 #include "stack/include/acl_api_types.h"
44 #include "stack/include/acl_hci_link_interface.h"
45 #include "stack/include/bt_types.h"
46 #include "stack/include/btm_ble_privacy.h"
47 #include "stack/include/btm_inq.h"
48 #include "stack/include/btm_status.h"
49 #include "stack/include/hcidefs.h"
50 #include "stack/include/l2cap_controller_interface.h"
51 #include "types/raw_address.h"
52 
53 // TODO(b/369381361) Enfore -Wmissing-prototypes
54 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
55 
56 using namespace ::bluetooth;
57 
58 extern tBTM_CB btm_cb;
59 
60 void btm_inq_db_reset(void);
61 /******************************************************************************/
62 /*               L O C A L    D A T A    D E F I N I T I O N S                */
63 /******************************************************************************/
64 
65 #ifndef BTM_DEV_RESET_TIMEOUT
66 #define BTM_DEV_RESET_TIMEOUT 4
67 #endif
68 
69 // TODO: Reevaluate this value in the context of timers with ms granularity
70 #define BTM_DEV_NAME_REPLY_TIMEOUT_MS    \
71   (2 * 1000) /* 2 seconds for name reply \
72               */
73 
74 #define BTM_INFO_TIMEOUT 5 /* 5 seconds for info response */
75 
76 /******************************************************************************/
77 /*            L O C A L    F U N C T I O N     P R O T O T Y P E S            */
78 /******************************************************************************/
79 
80 static void decode_controller_support();
81 
82 /*******************************************************************************
83  *
84  * Function         btm_dev_init
85  *
86  * Description      This function is on the BTM startup
87  *
88  * Returns          void
89  *
90  ******************************************************************************/
btm_dev_init()91 void btm_dev_init() {
92   /* Initialize nonzero defaults */
93   memset(btm_sec_cb.cfg.bd_name, 0, sizeof(BD_NAME));
94 
95   btm_cb.devcb.read_rssi_timer = alarm_new("btm.read_rssi_timer");
96   btm_cb.devcb.read_failed_contact_counter_timer =
97           alarm_new("btm.read_failed_contact_counter_timer");
98   btm_cb.devcb.read_automatic_flush_timeout_timer =
99           alarm_new("btm.read_automatic_flush_timeout_timer");
100   btm_cb.devcb.read_tx_power_timer = alarm_new("btm.read_tx_power_timer");
101 }
102 
btm_dev_free()103 void btm_dev_free() {
104   alarm_free(btm_cb.devcb.read_rssi_timer);
105   alarm_free(btm_cb.devcb.read_failed_contact_counter_timer);
106   alarm_free(btm_cb.devcb.read_automatic_flush_timeout_timer);
107   alarm_free(btm_cb.devcb.read_tx_power_timer);
108 }
109 
110 /*******************************************************************************
111  *
112  * Function         btm_db_reset
113  *
114  * Returns          void
115  *
116  ******************************************************************************/
BTM_db_reset(void)117 void BTM_db_reset(void) {
118   tBTM_CMPL_CB* p_cb;
119 
120   btm_inq_db_reset();
121 
122   if (btm_cb.devcb.p_rln_cmpl_cb) {
123     p_cb = btm_cb.devcb.p_rln_cmpl_cb;
124     btm_cb.devcb.p_rln_cmpl_cb = NULL;
125 
126     if (p_cb) {
127       (*p_cb)(nullptr);
128     }
129   }
130 
131   if (btm_cb.devcb.p_rssi_cmpl_cb) {
132     p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
133     btm_cb.devcb.p_rssi_cmpl_cb = NULL;
134 
135     if (p_cb) {
136       tBTM_RSSI_RESULT btm_rssi_result;
137       btm_rssi_result.status = tBTM_STATUS::BTM_DEV_RESET;
138       (*p_cb)(&btm_rssi_result);
139     }
140   }
141 
142   if (btm_cb.devcb.p_failed_contact_counter_cmpl_cb) {
143     p_cb = btm_cb.devcb.p_failed_contact_counter_cmpl_cb;
144     btm_cb.devcb.p_failed_contact_counter_cmpl_cb = NULL;
145 
146     if (p_cb) {
147       tBTM_FAILED_CONTACT_COUNTER_RESULT btm_failed_contact_counter_result;
148       btm_failed_contact_counter_result.status = tBTM_STATUS::BTM_DEV_RESET;
149       (*p_cb)(&btm_failed_contact_counter_result);
150     }
151   }
152 
153   if (btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb) {
154     p_cb = btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb;
155     btm_cb.devcb.p_automatic_flush_timeout_cmpl_cb = NULL;
156 
157     if (p_cb) {
158       tBTM_AUTOMATIC_FLUSH_TIMEOUT_RESULT btm_automatic_flush_timeout_result;
159       btm_automatic_flush_timeout_result.status = tBTM_STATUS::BTM_DEV_RESET;
160       (*p_cb)(&btm_automatic_flush_timeout_result);
161     }
162   }
163 }
164 
set_sec_state_idle(void * data,void *)165 static bool set_sec_state_idle(void* data, void* /* context */) {
166   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
167   p_dev_rec->sec_rec.le_link = tSECURITY_STATE::IDLE;
168   p_dev_rec->sec_rec.classic_link = tSECURITY_STATE::IDLE;
169   return true;
170 }
171 
BTM_reset_complete()172 void BTM_reset_complete() {
173   /* Tell L2CAP that all connections are gone */
174   l2cu_device_reset();
175 
176   /* Clear current security state */
177   list_foreach(btm_sec_cb.sec_dev_rec, set_sec_state_idle, NULL);
178 
179   /* After the reset controller should restore all parameters to defaults. */
180   btm_cb.btm_inq_vars.inq_counter = 1;
181   btm_cb.btm_inq_vars.inq_scan_window = HCI_DEF_INQUIRYSCAN_WINDOW;
182   btm_cb.btm_inq_vars.inq_scan_period = HCI_DEF_INQUIRYSCAN_INTERVAL;
183   btm_cb.btm_inq_vars.inq_scan_type = HCI_DEF_SCAN_TYPE;
184 
185   btm_cb.btm_inq_vars.page_scan_window = HCI_DEF_PAGESCAN_WINDOW;
186   btm_cb.btm_inq_vars.page_scan_period = HCI_DEF_PAGESCAN_INTERVAL;
187   btm_cb.btm_inq_vars.page_scan_type = HCI_DEF_SCAN_TYPE;
188 
189   btm_cb.ble_ctr_cb.set_connection_state_idle();
190   connection_manager::reset(true);
191 
192   btm_pm_reset();
193 
194   l2c_link_init(bluetooth::shim::GetController()->GetNumAclPacketBuffers());
195 
196   // setup the random number generator
197   std::srand(std::time(nullptr));
198 
199   /* Set up the BLE privacy settings */
200   if (bluetooth::shim::GetController()->SupportsBle() &&
201       bluetooth::shim::GetController()->SupportsBlePrivacy() &&
202       bluetooth::shim::GetController()->GetLeResolvingListSize() > 0) {
203     btm_ble_resolving_list_init(bluetooth::shim::GetController()->GetLeResolvingListSize());
204     /* set the default random private address timeout */
205     btsnd_hcic_ble_set_rand_priv_addr_timeout(btm_get_next_private_address_interval_ms() / 1000);
206   } else {
207     log::info("Le Address Resolving list disabled due to lack of controller support");
208   }
209 
210   if (bluetooth::shim::GetController()->SupportsBle()) {
211     l2c_link_process_ble_num_bufs(
212             bluetooth::shim::GetController()->GetLeBufferSize().total_num_le_packets_);
213   }
214 
215   BTM_SetPinType(btm_sec_cb.cfg.pin_type, btm_sec_cb.cfg.pin_code, btm_sec_cb.cfg.pin_code_len);
216 
217   decode_controller_support();
218 }
219 
220 /*******************************************************************************
221  *
222  * Function         BTM_IsDeviceUp
223  *
224  * Description      This function is called to check if the device is up.
225  *
226  * Returns          true if device is up, else false
227  *
228  ******************************************************************************/
BTM_IsDeviceUp(void)229 bool BTM_IsDeviceUp(void) { return bluetooth::shim::GetController() != nullptr; }
230 
decode_controller_support()231 static void decode_controller_support() {
232   /* Create (e)SCO supported packet types mask */
233   btm_cb.btm_sco_pkt_types_supported = 0;
234   btm_cb.sco_cb.esco_supported = false;
235   if (bluetooth::shim::GetController()->SupportsSco()) {
236     btm_cb.btm_sco_pkt_types_supported = ESCO_PKT_TYPES_MASK_HV1;
237 
238     if (bluetooth::shim::GetController()->SupportsHv2Packets()) {
239       btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_HV2;
240     }
241 
242     if (bluetooth::shim::GetController()->SupportsHv3Packets()) {
243       btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_HV3;
244     }
245   }
246 
247   if (bluetooth::shim::GetController()->SupportsEv3Packets()) {
248     btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV3;
249   }
250 
251   if (bluetooth::shim::GetController()->SupportsEv4Packets()) {
252     btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV4;
253   }
254 
255   if (bluetooth::shim::GetController()->SupportsEv5Packets()) {
256     btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV5;
257   }
258 
259   if (btm_cb.btm_sco_pkt_types_supported & BTM_ESCO_LINK_ONLY_MASK) {
260     btm_cb.sco_cb.esco_supported = true;
261 
262     /* Add in EDR related eSCO types */
263     if (bluetooth::shim::GetController()->SupportsEsco2mPhy()) {
264       if (!bluetooth::shim::GetController()->Supports3SlotEdrPackets()) {
265         btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_NO_2_EV5;
266       }
267     } else {
268       btm_cb.btm_sco_pkt_types_supported |=
269               (ESCO_PKT_TYPES_MASK_NO_2_EV3 + ESCO_PKT_TYPES_MASK_NO_2_EV5);
270     }
271 
272     if (bluetooth::shim::GetController()->SupportsEsco3mPhy()) {
273       if (!bluetooth::shim::GetController()->Supports3SlotEdrPackets()) {
274         btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_NO_3_EV5;
275       }
276     } else {
277       btm_cb.btm_sco_pkt_types_supported |=
278               (ESCO_PKT_TYPES_MASK_NO_3_EV3 + ESCO_PKT_TYPES_MASK_NO_3_EV5);
279     }
280   }
281 
282   log::verbose("Local supported SCO packet types: 0x{:04x}", btm_cb.btm_sco_pkt_types_supported);
283 
284   BTM_acl_after_controller_started();
285   btm_sec_dev_reset();
286 
287   if (bluetooth::shim::GetController()->SupportsRssiWithInquiryResults()) {
288     if (bluetooth::shim::GetController()->SupportsExtendedInquiryResponse()) {
289       if (BTM_SetInquiryMode(BTM_INQ_RESULT_EXTENDED) != tBTM_STATUS::BTM_SUCCESS) {
290         log::warn("Unable to set inquiry mode BTM_INQ_RESULT_EXTENDED");
291       }
292     } else {
293       if (BTM_SetInquiryMode(BTM_INQ_RESULT_WITH_RSSI) != tBTM_STATUS::BTM_SUCCESS) {
294         log::warn("Unable to set inquiry mode BTM_INQ_RESULT_WITH_RSSI");
295       }
296     }
297   }
298 
299   l2cu_set_non_flushable_pbf(bluetooth::shim::GetController()->SupportsNonFlushablePb());
300   BTM_EnableInterlacedPageScan();
301   BTM_EnableInterlacedInquiryScan();
302 }
303 
304 /*******************************************************************************
305  *
306  * Function         BTM_SetLocalDeviceName
307  *
308  * Description      This function is called to set the local device name.
309  *
310  * Returns          status of the operation
311  *
312  ******************************************************************************/
BTM_SetLocalDeviceName(const char * p_name)313 tBTM_STATUS BTM_SetLocalDeviceName(const char* p_name) {
314   if (!p_name || !p_name[0] || (strlen(p_name) > BD_NAME_LEN)) {
315     return tBTM_STATUS::BTM_ILLEGAL_VALUE;
316   }
317 
318   if (bluetooth::shim::GetController() == nullptr) {
319     return tBTM_STATUS::BTM_DEV_RESET;
320   }
321   /* Save the device name if local storage is enabled */
322 
323   bd_name_from_char_pointer(btm_sec_cb.cfg.bd_name, p_name);
324 
325   bluetooth::shim::GetController()->WriteLocalName(p_name);
326   return tBTM_STATUS::BTM_CMD_STARTED;
327 }
328 
329 /*******************************************************************************
330  *
331  * Function         BTM_ReadLocalDeviceName
332  *
333  * Description      This function is called to read the local device name.
334  *
335  * Returns          status of the operation
336  *                  If success, tBTM_STATUS::BTM_SUCCESS is returned and p_name points stored
337  *                              local device name
338  *                  If BTM doesn't store local device name, tBTM_STATUS::BTM_NO_RESOURCES is
339  *                              is returned and p_name is set to NULL
340  *
341  ******************************************************************************/
BTM_ReadLocalDeviceName(const char ** p_name)342 tBTM_STATUS BTM_ReadLocalDeviceName(const char** p_name) {
343   *p_name = (const char*)btm_sec_cb.cfg.bd_name;
344   return tBTM_STATUS::BTM_SUCCESS;
345 }
346 
347 /*******************************************************************************
348  *
349  * Function         BTM_SetDeviceClass
350  *
351  * Description      This function is called to set the local device class
352  *
353  * Returns          status of the operation
354  *
355  ******************************************************************************/
BTM_SetDeviceClass(DEV_CLASS dev_class)356 tBTM_STATUS BTM_SetDeviceClass(DEV_CLASS dev_class) {
357   if (btm_cb.devcb.dev_class == dev_class) {
358     return tBTM_STATUS::BTM_SUCCESS;
359   }
360 
361   btm_cb.devcb.dev_class = dev_class;
362 
363   if (bluetooth::shim::GetController() == nullptr) {
364     return tBTM_STATUS::BTM_DEV_RESET;
365   }
366 
367   btsnd_hcic_write_dev_class(dev_class);
368 
369   return tBTM_STATUS::BTM_SUCCESS;
370 }
371 
372 /*******************************************************************************
373  *
374  * Function         BTM_ReadDeviceClass
375  *
376  * Description      This function is called to read the local device class
377  *
378  * Returns          the device class
379  *
380  ******************************************************************************/
BTM_ReadDeviceClass(void)381 DEV_CLASS BTM_ReadDeviceClass(void) { return btm_cb.devcb.dev_class; }
382 
383 /*******************************************************************************
384  *
385  * Function         BTM_VendorSpecificCommand
386  *
387  * Description      Send a vendor specific HCI command to the controller.
388  *
389  * Notes
390  *      Opcode will be OR'd with HCI_GRP_VENDOR_SPECIFIC.
391  *
392  ******************************************************************************/
BTM_VendorSpecificCommand(uint16_t opcode,uint8_t param_len,uint8_t * p_param_buf,tBTM_VSC_CMPL_CB * p_cb)393 void BTM_VendorSpecificCommand(uint16_t opcode, uint8_t param_len, uint8_t* p_param_buf,
394                                tBTM_VSC_CMPL_CB* p_cb) {
395   log::verbose("BTM: Opcode: 0x{:04X}, ParamLen: {}.", opcode, param_len);
396 
397   /* Send the HCI command (opcode will be OR'd with HCI_GRP_VENDOR_SPECIFIC) */
398   btsnd_hcic_vendor_spec_cmd(opcode, param_len, p_param_buf, p_cb);
399 }
400 
401 /*******************************************************************************
402  *
403  * Function         BTM_WritePageTimeout
404  *
405  * Description      Send HCI Write Page Timeout.
406  *
407  ******************************************************************************/
BTM_WritePageTimeout(uint16_t timeout)408 void BTM_WritePageTimeout(uint16_t timeout) {
409   log::verbose("BTM: BTM_WritePageTimeout: Timeout: {}.", timeout);
410 
411   /* Send the HCI command */
412   btsnd_hcic_write_page_tout(timeout);
413 }
414 
415 /*******************************************************************************
416  *
417  * Function         BTM_WriteVoiceSettings
418  *
419  * Description      Send HCI Write Voice Settings command.
420  *                  See hcidefs.h for settings bitmask values.
421  *
422  ******************************************************************************/
BTM_WriteVoiceSettings(uint16_t settings)423 void BTM_WriteVoiceSettings(uint16_t settings) {
424   log::verbose("BTM: BTM_WriteVoiceSettings: Settings: 0x{:04x}.", settings);
425 
426   /* Send the HCI command */
427   btsnd_hcic_write_voice_settings((uint16_t)(settings & 0x03ff));
428 }
429 
430 /*******************************************************************************
431  *
432  * Function         BTM_EnableTestMode
433  *
434  * Description      Send HCI the enable device under test command.
435  *
436  *                  Note: Controller can only be taken out of this mode by
437  *                      resetting the controller.
438  *
439  * Returns
440  *      tBTM_STATUS::BTM_SUCCESS         Command sent.
441  *      tBTM_STATUS::BTM_NO_RESOURCES    If out of resources to send the command.
442  *
443  *
444  ******************************************************************************/
BTM_EnableTestMode(void)445 tBTM_STATUS BTM_EnableTestMode(void) {
446   uint8_t cond;
447 
448   log::verbose("BTM: BTM_EnableTestMode");
449 
450   /* set auto accept connection as this is needed during test mode */
451   /* Allocate a buffer to hold HCI command */
452   cond = HCI_DO_AUTO_ACCEPT_CONNECT;
453   btsnd_hcic_set_event_filter(HCI_FILTER_CONNECTION_SETUP, HCI_FILTER_COND_NEW_DEVICE, &cond,
454                               sizeof(cond));
455 
456   /* put device to connectable mode */
457   if (BTM_SetConnectability(BTM_CONNECTABLE) != tBTM_STATUS::BTM_SUCCESS) {
458     return tBTM_STATUS::BTM_NO_RESOURCES;
459   }
460 
461   /* put device to discoverable mode */
462   if (BTM_SetDiscoverability(BTM_GENERAL_DISCOVERABLE) != tBTM_STATUS::BTM_SUCCESS) {
463     return tBTM_STATUS::BTM_NO_RESOURCES;
464   }
465 
466   /* mask off all of event from controller */
467   bluetooth::shim::BTM_ClearEventMask();
468 
469   /* Send the HCI command */
470   btsnd_hcic_enable_test_mode();
471   return tBTM_STATUS::BTM_SUCCESS;
472 }
473 
474 /*******************************************************************************
475  *
476  * Function         BTM_DeleteStoredLinkKey
477  *
478  * Description      This function is called to delete link key for the specified
479  *                  device addresses from the NVRAM storage attached to the
480  *                  Bluetooth controller.
481  *
482  * Parameters:      bd_addr      - Addresses of the devices
483  *                  p_cb         - Call back function to be called to return
484  *                                 the results
485  *
486  ******************************************************************************/
BTM_DeleteStoredLinkKey(const RawAddress * bd_addr,tBTM_CMPL_CB * p_cb)487 tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* bd_addr, tBTM_CMPL_CB* p_cb) {
488   /* Read and Write STORED link key stems from a legacy use-case and is no
489    * longer expected to be used. Disable explicitly for Floss and queue overall
490    * deletion from Fluoride.
491    */
492 #if !defined(TARGET_FLOSS)
493   /* Check if the previous command is completed */
494   if (btm_sec_cb.devcb.p_stored_link_key_cmpl_cb) {
495     return tBTM_STATUS::BTM_BUSY;
496   }
497 
498   bool delete_all_flag = !bd_addr;
499 
500   log::verbose("BTM: BTM_DeleteStoredLinkKey: delete_all_flag: {}", delete_all_flag);
501 
502   btm_sec_cb.devcb.p_stored_link_key_cmpl_cb = p_cb;
503   if (!bd_addr) {
504     /* This is to delete all link keys */
505     /* We don't care the BD address. Just pass a non zero pointer */
506     RawAddress local_bd_addr = RawAddress::kEmpty;
507     btsnd_hcic_delete_stored_key(local_bd_addr, delete_all_flag);
508   } else {
509     btsnd_hcic_delete_stored_key(*bd_addr, delete_all_flag);
510   }
511 #endif
512 
513   return tBTM_STATUS::BTM_SUCCESS;
514 }
515 
516 /*******************************************************************************
517  *
518  * Function         btm_delete_stored_link_key_complete
519  *
520  * Description      This function is called when the command complete message
521  *                  is received from the HCI for the delete stored link key
522  *                  command.
523  *
524  * Returns          void
525  *
526  ******************************************************************************/
btm_delete_stored_link_key_complete(uint8_t * p,uint16_t evt_len)527 void btm_delete_stored_link_key_complete(uint8_t* p, uint16_t evt_len) {
528   tBTM_CMPL_CB* p_cb = btm_sec_cb.devcb.p_stored_link_key_cmpl_cb;
529   tBTM_DELETE_STORED_LINK_KEY_COMPLETE result;
530 
531   /* If there was a callback registered for read stored link key, call it */
532   btm_sec_cb.devcb.p_stored_link_key_cmpl_cb = NULL;
533 
534   if (p_cb) {
535     /* Set the call back event to indicate command complete */
536     result.event = BTM_CB_EVT_DELETE_STORED_LINK_KEYS;
537 
538     if (evt_len < 3) {
539       log::error("Malformatted event packet, too short");
540       return;
541     }
542 
543     /* Extract the result fields from the HCI event */
544     STREAM_TO_UINT8(result.status, p);
545     STREAM_TO_UINT16(result.num_keys, p);
546 
547     /* Call the call back and pass the result */
548     (*p_cb)(&result);
549   }
550 }
551